CustomerController.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Components\AsyncResponse;
  4. use App\Jobs\OrderCreateInstantBill;
  5. use App\Jobs\ResetInstantBill;
  6. use App\Jobs\SettlementBillReportJob;
  7. use App\Jobs\StoreCreateInstantBill;
  8. use App\Order;
  9. use App\Owner;
  10. use App\OwnerAreaReport;
  11. use App\OwnerBillReport;
  12. use App\OwnerFeeDetail;
  13. use App\OwnerFeeExpress;
  14. use App\OwnerFeeLogistic;
  15. use App\OwnerFeeOperation;
  16. use App\OwnerFeeOperationDetail;
  17. use App\OwnerFeeStorage;
  18. use App\OwnerPriceSystem;
  19. use App\OwnerReport;
  20. use App\Services\LogService;
  21. use App\Services\ObligationService;
  22. use App\Services\OwnerAreaReportService;
  23. use App\Services\OwnerBillReportService;
  24. use App\Services\OwnerReportService;
  25. use App\Services\OwnerService;
  26. use App\Store;
  27. use App\UserWorkgroup;
  28. use Illuminate\Database\Eloquent\Builder;
  29. use Illuminate\Http\Request;
  30. use Illuminate\Http\Response;
  31. use Illuminate\Support\Facades\DB;
  32. use Illuminate\Support\Facades\Gate;
  33. use Illuminate\Support\Facades\Validator;
  34. use Oursdreams\Export\Export;
  35. class CustomerController extends Controller
  36. {
  37. use AsyncResponse;
  38. public function projectReport(Request $request)
  39. {
  40. if(!Gate::allows('项目管理-项目-报表')){ return view('customer.index'); }
  41. $withs = ["ownerBillReport","owner"=>function($query){
  42. /** @var Builder $query */
  43. $query->select("id","warehouse_id","name","deleted_at","created_at","customer_id","user_owner_group_id")
  44. ->with(["customer","userOwnerGroup","warehouse","ownerAreaReport"]);
  45. }];
  46. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  47. $customers = app('CustomerService')->getSelection();
  48. $owners = app('OwnerService')->getIntersectPermitting();
  49. $reports = app("OwnerReportService")->paginate($request->input(),$withs);
  50. $params = $request->input();
  51. return response()->view('personnel.report',compact("reports","ownerGroups","customers","owners","params"));
  52. }
  53. public function projectReportExport(Request $request)
  54. {
  55. if(!Gate::allows('项目管理-项目-报表')){ return redirect('denied'); }
  56. /** @var OwnerReportService $service */
  57. $service = app('OwnerReportService');
  58. $withs = ["ownerBillReport","owner"=>function($query){
  59. /** @var Builder $query */
  60. $query->select("id","name","deleted_at","created_at","customer_id","user_owner_group_id")
  61. ->with(["customer","userOwnerGroup"]);
  62. }];
  63. if ($request->checkAllSign ?? false){
  64. $params = $request->input();
  65. unset($params['checkAllSign']);
  66. $reports = $service->get($params,$withs);
  67. }else $reports = $service->get(["id"=>$request->data ?? ''],$withs);
  68. $column = ["项目小组","客户","子项目","状态","创建日期","在库时长","结算月","日均单量","结算月上月盘点面积","结算月盘点面积","初始账单金额","确认账单金额","确认日期"];
  69. $list = [];
  70. foreach ($reports as $report){
  71. $list[] = [
  72. $report->owner ? ($report->owner->userOwnerGroup ? $report->owner->userOwnerGroup->name : '') : '',
  73. $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
  74. $report->owner ? $report->owner->name : '',
  75. $report->owner ? ($report->owner->deleted_at ? "冻结" : "激活") : '',
  76. $report->owner ? (string)$report->owner->created_at : '',
  77. $report->owner ? ($report->owner->created_at ? ((new \DateTime())->diff(new \DateTime($report->owner->created_at))->days)." 天" : '') : '',
  78. $report->counting_month,
  79. $report->daily_average_order_amount,
  80. $report->last_month_counting_area,
  81. $report->current_month_counting_area,
  82. $report->ownerBillReport ? $report->ownerBillReport->initial_fee : '',
  83. $report->ownerBillReport ? $report->ownerBillReport->confirm_fee : '',
  84. $report->ownerBillReport ? (string)$report->ownerBillReport->updated_at : '',
  85. ];
  86. }
  87. return Export::make($column,$list,"客户项目报表");
  88. }
  89. public function projectIndex()
  90. {
  91. if(!Gate::allows('项目管理-项目-查询')){ return redirect('denied'); }
  92. /** @var OwnerService $service */
  93. $service = app('OwnerService');
  94. $owners = $service->paginate(request()->input(),['customer',"userOwnerGroup","userWorkGroup",'departmentObligationOwner.department',
  95. "ownerStoragePriceModels","storageAudit","operationAudit","expressAudit","logisticAudit","directLogisticAudit","systemAudit"]);
  96. $owners=app('OwnerService')->combineOwners($owners);
  97. $models = app('OwnerService')->getIntersectPermitting();
  98. $customers = app('CustomerService')->getSelection();
  99. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  100. $params = request()->input();
  101. $userWorkGroups = UserWorkgroup::all();
  102. return response()->view('customer.project.index',compact("owners","models","customers","ownerGroups","params",'userWorkGroups'));
  103. }
  104. public function projectIndexExport(Request $request)
  105. {
  106. if(!Gate::allows('项目管理-项目-查询')){ return redirect('denied'); }
  107. /** @var OwnerService $service */
  108. $service = app('OwnerService');
  109. $withs = ['customer',"userOwnerGroup","contracts","taxRate","ownerStoragePriceModels","ownerAreaReport"=>function($query){
  110. $month = date('Y-m');
  111. /** @var Builder $query */
  112. $query->where("counting_month","like",$month."%");
  113. }];
  114. $params = $request->input();
  115. $params['customer_id']=true;
  116. if ($request->checkAllSign ?? false) unset($params['checkAllSign']);
  117. else $params = ["id"=>$request->data ?? ''];
  118. $owners = $service->get($params,$withs);
  119. $column = ["客户","税率","项目","货主代码","创建日期","合同号","销售名称","公司全称","联系人","联系电话","项目小组","用仓类型","当月结算面积","月单量预警","是否激活","项目描述"];
  120. $list = [];
  121. foreach ($owners as $owner){
  122. $list[] = [
  123. $owner->customer ? $owner->customer->name : '',
  124. $owner->taxRate->name ?? '',
  125. $owner->name,
  126. $owner->code,
  127. $owner->created_at,
  128. implode("\r\n",array_column($owner->contracts,"contract_number")),
  129. implode("\r\n",array_column($owner->contracts,"salesman")),
  130. $owner->customer ? $owner->customer->company_name : '',
  131. $owner->linkman,
  132. $owner->phone_number,
  133. $owner->userOwnerGroup ? $owner->userOwnerGroup->name : '',
  134. implode(",",array_unique(array_column(($owner->ownerStoragePriceModels)->toArray(),"using_type"))),
  135. $owner->ownerAreaReport ? $owner->ownerAreaReport->accounting_area : '',
  136. $owner->waring_line_on,
  137. $owner->deleted_at ? '否' : '是',
  138. $owner->description
  139. ];
  140. }
  141. return Export::make($column,$list,"客户报表");
  142. }
  143. public function projectCreate()
  144. {
  145. if(!Gate::allows('项目管理-项目-录入')){ return redirect('denied'); }
  146. $customers = app('CustomerService')->getSelection();
  147. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  148. $userGroups = app('UserWorkgroupService')->getSelection(["id","name","warehouse_id"]);
  149. $warehouses = app('WarehouseService')->getSelection();
  150. $owner = null;
  151. return response()->view('customer.project.create',compact("customers","ownerGroups","owner","warehouses","userGroups"));
  152. }
  153. public function projectUpdate()
  154. {
  155. $this->gate("项目管理-项目-录入");
  156. if (!request("id"))$this->error("项目不存在,无法补充详细信息");
  157. $errors = $this->validator(request()->input())->errors();
  158. if (count($errors)>0)$this->success(["errors"=>$errors]);
  159. /** @var Owner $owner */
  160. $owner = app('OwnerService')->find(request("id"));
  161. if (!$owner)$this->error("项目已被删除,无法操作");
  162. //if ($owner->tax_rate_id && !request("tax_rate_id"))app('OwnerService')->attachTaxRate($owner);
  163. //if (!$owner->tax_rate_id && request("tax_rate_id"))app('OwnerService')->removeTaxRate($owner);
  164. $owner = app('OwnerService')->update($owner,[
  165. "customer_id" => request("customer_id"),
  166. "warehouse_id" => request("warehouse_id"),
  167. "tax_rate_id" => request("tax_rate_id"),
  168. "linkman" => request("linkman"),
  169. "phone_number" => request("phone_number"),
  170. "user_owner_group_id" => request("owner_group_id"),
  171. "user_workgroup_id" => request("user_workgroup_id"),
  172. "waring_line_on" => request("waring_line_on"),
  173. "description" => request("description"),
  174. "subjection" => request("subjection"),
  175. "is_tax_exist" => request("is_tax_exist") ? 'Y' : 'N',
  176. ]);
  177. /** @var ObligationService $service*/
  178. $service= app('ObligationService');
  179. $owner=$service->createOrUpdate(request()->input());
  180. $this->success($owner);
  181. }
  182. //获取货主下所有相关计费模型
  183. public function getOwnerPriceModel(Request $request)
  184. {
  185. $owner = new Owner();
  186. $owner->id = $request->id;
  187. $owner->load(["ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics"]);
  188. return ["success"=>true,"data"=>["ownerPriceOperations"=>$owner->ownerPriceOperations,
  189. "ownerPriceExpresses"=>$owner->ownerPriceExpresses,
  190. "ownerPriceLogistics"=>$owner->ownerPriceLogistics,
  191. "ownerPriceDirectLogistics"=>$owner->ownerPriceDirectLogistics]];
  192. }
  193. public function projectEdit($id)
  194. {
  195. if(!Gate::allows('项目管理-项目-编辑')){ return redirect('denied'); }
  196. /** @var Owner $owner */
  197. $owner = app('OwnerService')->find($id,['departmentObligationOwner']);
  198. $departmentObligationOwner=$owner->departmentObligationOwner??[];
  199. if (count($departmentObligationOwner)>0){
  200. foreach ($departmentObligationOwner as $item){
  201. if ($item->obligation_code=='kc')$owner->kc=$item->department_id;
  202. if ($item->obligation_code=='jg')$owner->jg=$item->department_id;
  203. if ($item->obligation_code=='th')$owner->th=$item->department_id;
  204. if ($item->obligation_code=='sh')$owner->sh=$item->department_id;
  205. if ($item->obligation_code=='fh')$owner->fh=$item->department_id;
  206. }
  207. }
  208. $owner->loadCount(["ownerStoragePriceModels","ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics","ownerPriceSystem"]);
  209. $isExist = false;
  210. /** @var \stdClass $owner */
  211. if($owner->owner_storage_price_models_count ||
  212. $owner->owner_price_operations_count ||
  213. $owner->owner_price_expresses_count ||
  214. $owner->owner_price_logistics_count ||
  215. $owner->owner_price_system_count ||
  216. $owner->owner_price_direct_logistics_count) $isExist = true;
  217. $customers = app('CustomerService')->getSelection();
  218. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  219. $userGroups = app('UserWorkgroupService')->getSelection(["id","name","warehouse_id"]);
  220. $warehouses = app('WarehouseService')->getSelection();
  221. $type = request("type");
  222. return response()->view('customer.project.create',compact("customers","ownerGroups","warehouses",'owner',"isExist", "type","userGroups"));
  223. }
  224. public function projectArea(Request $request)
  225. {
  226. if(!Gate::allows('项目管理-项目-面积')){ return redirect('denied'); }
  227. $areas = app('OwnerAreaReportService')->paginate($request->input(),["owner.customer","ownerStoragePriceModel.unit","userOwnerGroup"]);
  228. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  229. $customers = app('CustomerService')->getSelection();
  230. $owners = app('OwnerService')->getIntersectPermitting();
  231. $params = $request->input();
  232. return response()->view('customer.project.area',compact("areas","ownerGroups","customers","owners","params"));
  233. }
  234. public function updateArea()
  235. {
  236. $this->gate("项目管理-项目-面积-编辑");
  237. if (!request("id")) $this->error("非法参数");
  238. $total = ((int)request("areaOnTray")*2.5) +
  239. ((int)request("areaOnHalfTray")*1.8) + ((int)request("areaOnFlat")*1.3);
  240. $obj = [
  241. "user_owner_group_id" => request("ownerGroupId"),
  242. "area_on_tray" => request("areaOnTray"),
  243. "area_on_half_tray" => request("areaOnHalfTray"),
  244. "area_on_flat" => request("areaOnFlat"),
  245. "accounting_area" => intval($total*1000)/1000,
  246. ];
  247. $re = app('OwnerAreaReportService')->update(["id"=>request("id")],$obj);
  248. if ($re===true)$this->success($obj);
  249. else $this->error($re);
  250. }
  251. //面积报表审核
  252. public function areaReportAudit()
  253. {
  254. $this->gate("项目管理-项目-用仓盘点-审核");
  255. $id = request("id");
  256. if(!$id)$this->error("非法参数");
  257. $area = OwnerAreaReport::query()->find($id);
  258. /** @var \stdClass $area */
  259. if (!$area || $area->status!='编辑中')$this->error("记录已被操作");
  260. $area->update(["status"=>"已审核"]);
  261. $this->success();
  262. }
  263. public function projectAreaExport(Request $request)
  264. {
  265. if(!Gate::allows('项目管理-项目-面积')){ return redirect('denied'); }
  266. $params = $request->input();
  267. if ($request->checkAllSign)unset($params['checkAllSign']);
  268. else $params = ["id"=>$request->data];
  269. /** @var OwnerAreaReportService $serves */
  270. $serves = app('OwnerAreaReportService');
  271. $areas = $serves->get($params,["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels","userOwnerGroup"]);}]);
  272. $column = ["状态","项目组","客户","子项目","结算月","录入时间","用仓类型","货物整托","货物半托","平面区面积","结算面积"];
  273. $list = [];
  274. foreach ($areas as $area){
  275. $list[] = [
  276. $area->status,
  277. $area->owner ? ($area->owner->userOwnerGroup ? $area->owner->userOwnerGroup->name : '') : '',
  278. $area->owner ? ($area->owner->customer ? $area->owner->customer->name : '') : '',
  279. $area->owner ? $area->owner->name : '',
  280. $area->counting_month,
  281. $area->updated_at,
  282. $area->owner ? implode(",",array_unique(array_column(($area->owner->ownerStoragePriceModels)->toArray(),"using_type"))) : '',
  283. $area->area_on_tray,
  284. $area->area_on_half_tray,
  285. $area->area_on_flat,
  286. $area->accounting_area,
  287. ];
  288. }
  289. return Export::make($column,$list,"项目面积报表");
  290. }
  291. public function financeInstantBill(Request $request)
  292. {
  293. if(!Gate::allows('结算管理-即时账单')){ return redirect('denied'); }
  294. $params = $request->input();
  295. $shops = app('ShopService')->getSelection();
  296. $customers = app('CustomerService')->getSelection();
  297. $owners = app('OwnerService')->getIntersectPermitting();
  298. $details = app('OwnerFeeDetailService')->paginate($params,["owner.customer","shop","processMethod","logistic","items"]);
  299. return response()->view('finance.instantBill',compact("details","params","shops","customers","owners"));
  300. }
  301. public function financeInstantBillExport(Request $request)
  302. {
  303. if(!Gate::allows('结算管理-即时账单')){ return redirect('denied'); }
  304. $params = $request->input();
  305. if ($request->checkAllSign)unset($params['checkAllSign']);
  306. else $params = ["id"=>$request->data];
  307. $sql = app('OwnerFeeDetailService')->getSql($params);
  308. $rule = ["work_fee"=>"mysqlDate"];
  309. $e = new Export();
  310. $e->setMysqlConnection(config('database.connections.mysql.host'),
  311. config('database.connections.mysql.port'),config('database.connections.mysql.database')
  312. ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
  313. $e->setFileName("即时账单记录");
  314. return $e->sql($sql,[
  315. "customer_name"=>"客户","owner_name"=>"项目",
  316. "worked_at"=>"作业时间","type"=>"类型",
  317. "shop_name"=>"店铺","operation_bill"=>"单号(发/收/退/提)",
  318. "consignee_name"=>"收件人","consignee_phone"=>"收件人电话",
  319. "commodity_amount"=>"商品数量","logistic_bill"=>"物流/快递单号",
  320. "volume"=>"体积","weight"=>"重量","logistic_name"=>"承运商",
  321. "work_fee"=>"操作费","logistic_fee"=>"物流费","total"=>"合计"
  322. ],$rule)->direct();
  323. }
  324. public function financeBillConfirmation(Request $request)
  325. {
  326. if(!Gate::allows('结算管理-账单确认')){ return redirect('denied'); }
  327. $params = $request->input();
  328. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  329. $customers = app('CustomerService')->getSelection();
  330. $owners = app('OwnerService')->getIntersectPermitting();
  331. $bills = app('OwnerBillReportService')->paginate($params,["owner"=>function($query){
  332. /** @var Builder $query */
  333. $query->with(["customer","userOwnerGroup"]);
  334. }]);
  335. return response()->view('finance.billConfirmation',compact("params","owners","ownerGroups","customers","bills"));
  336. }
  337. public function financeBillConfirmationExport(Request $request)
  338. {
  339. if(!Gate::allows('结算管理-账单确认')){ return redirect('denied'); }
  340. $params = $request->input();
  341. if ($request->checkAllSign)unset($params['checkAllSign']);
  342. else $params = ["id"=>$request->data];
  343. /** @var OwnerBillReportService $serves */
  344. $serves = app('OwnerBillReportService');
  345. $bills = $serves->get($params,["owner"=>function($query){
  346. /** @var Builder $query */
  347. $query->with(["customer","userOwnerGroup"]);
  348. }]);
  349. $column = ["项目小组","客户","子项目","结算月","录入日期","原始账单金额","确认账单金额","差额","状态"];
  350. $list = [];
  351. foreach ($bills as $bill){
  352. $list[] = [
  353. $bill->owner ? ($bill->owner->userOwnerGroup ? $bill->owner->userOwnerGroup->name : '') : '',
  354. $bill->owner ? ($bill->owner->customer ? $bill->owner->customer->name : '') : '',
  355. $bill->owner ? $bill->owner->name : '',
  356. $bill->counting_month,
  357. $bill->updated_at,
  358. $bill->initial_fee,
  359. $bill->confirm_fee,
  360. $bill->difference,
  361. $bill->confirmed == '是' ? '已确认' : '未确认',
  362. ];
  363. }
  364. return Export::make($column,$list,"客户账单报表");
  365. }
  366. public function updateBillReport(Request $request)
  367. {
  368. if(!Gate::allows('结算管理-账单确认-编辑')){ return ["success"=>false,'data'=>"无权操作!"]; }
  369. if (!$request->confirm_fee || !is_numeric($request->confirm_fee) || $request->confirm_fee<0)return ["success"=>false,"data"=>"非法金额参数"];
  370. $date = date('Y-m-d H:i:s');
  371. app('OwnerBillReportService')->update(["id"=>$request->id],["confirm_fee"=>$request->confirm_fee,"difference"=>DB::raw($request->confirm_fee.'- (IFNULL(work_fee,0)+IFNULL(storage_fee,0)+IFNULL(logistic_fee,0))'),"updated_at"=>$date]);
  372. LogService::log(__METHOD__,"项目管理-修改账单报表",json_encode($request->input()));
  373. return ["success"=>true,"data"=>$date];
  374. }
  375. public function billConfirm()
  376. {
  377. $this->gate("结算管理-账单确认-完结");
  378. if (!request("id"))$this->error("非法参数");
  379. /** @var OwnerBillReport $bill */
  380. $bill = app('OwnerBillReportService')->first(["id"=>request("id"),"confirmed"=>"否"]);
  381. if (!$bill)$this->error("账单状态变更,禁止操作");
  382. /** @var \stdClass $bill */
  383. $area = OwnerAreaReport::query()->where("owner_id",$bill->owner_id)
  384. ->where("counting_month","like",$bill->counting_month."%")->first();
  385. if (!$area || $area->status!='编辑中')$this->error("对应面积报表状态异常");
  386. $bill->update(["confirmed"=>"是"]);
  387. LogService::log(__METHOD__,"项目管理-确认账单",json_encode(request()->input()));
  388. app('OwnerAreaReportService')->lockArea(null, $bill->owner_id, $bill->counting_month);
  389. LogService::log(__METHOD__,"项目管理-锁定账单的所有面积",json_encode($bill,JSON_UNESCAPED_UNICODE));
  390. $this->success();
  391. }
  392. private function validator(array $params){
  393. $validator=Validator::make($params,[
  394. 'id' => ['required'],
  395. 'customer_id'=>['required'],
  396. 'owner_group_id'=>['required'],
  397. 'warehouse_id'=>['required'],
  398. 'tax_rate_id' => ["nullable",'integer'],
  399. 'waring_line_on' => ["nullable",'integer'],
  400. ],[
  401. 'required'=>':attribute 为必填项',
  402. 'integer'=>':attribute 必须为整数',
  403. 'numeric'=>':attribute 必须为数字',
  404. ],[
  405. 'code'=>'项目代码',
  406. 'name'=>'项目名称',
  407. 'warehouse_id'=>'仓库',
  408. 'customer_id'=>'客户',
  409. 'owner_group_id'=>'工作组',
  410. 'tax_rate_id' => '税率',
  411. 'waring_line_on' => '月单量预警'
  412. ]);
  413. return $validator;
  414. }
  415. public function verifyProject(Request $request)
  416. {
  417. $this->success($this->validator($request->input())->errors());
  418. }
  419. public function createReport()
  420. {
  421. $ids = \request("val");
  422. if (!$ids)$this->error("未选择任何项目");
  423. $reports = OwnerReport::query()->with("owner")
  424. ->where("counting_month",">=",date("Y-m")."-01")
  425. ->whereIn("owner_id",$ids)->get(["id","owner_id"]);
  426. $errors = [];
  427. $exist = [];
  428. foreach ($reports as $report){
  429. $errors[] = "“".($report->owner ? $report->owner->name : $report->owner_id)."”已存在本月报表";
  430. $exist[] = $report->owner_id;
  431. }
  432. $ids = array_diff($ids,$exist);
  433. $insert = [];
  434. $date = date("Y-m-d H:i:s");
  435. foreach ($ids as $id){
  436. $insert[] = [
  437. "owner_id" => $id,
  438. "counting_month" => date("Y-m-d"),
  439. "created_at" => $date
  440. ];
  441. }
  442. if ($insert){
  443. OwnerReport::query()->insert($insert);
  444. LogService::log(__METHOD__,"手动生成报表",json_encode($insert));
  445. }
  446. $reports = OwnerReport::query()->with(["owner.userOwnerGroup","owner.customer"])
  447. ->where("counting_month",">=",date("Y-m")."-01")
  448. ->whereIn("owner_id",$ids)->get();
  449. $result = [];
  450. foreach ($reports as $report){
  451. $result[] = [
  452. "id" => $report->id,
  453. "ownerGroupName" => $report->owner ? ($report->owner->userOwnerGroup ? $report->owner->userOwnerGroup->name : '') : '',
  454. "customerName" => $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
  455. "ownerName" => $report->owner ? $report->owner->name : '',
  456. "ownerStatus" => $report->owner ? ($report->owner->deleted_at ? "冻结" : "激活") : '',
  457. "ownerStorageDuration" => $report->owner ? ($report->owner->created_at ? ((new \DateTime())->diff(new \DateTime($report->owner->created_at))->days) : '') : '',
  458. "ownerCreatedAt" => $report->owner ? $report->owner->created_at : '',
  459. "countingMonth" => $report->counting_month,
  460. ];
  461. }
  462. $this->success(["errors"=>$errors,"data"=>$result]);
  463. }
  464. public function createAreaReport()
  465. {
  466. $ids = \request("val");
  467. if (!$ids)$this->error("未选择任何项目");
  468. /** @var OwnerService $service */
  469. $service = app("OwnerService");
  470. $owners = $service->get(["id"=>$ids],["ownerStoragePriceModels"],false,true);
  471. app("OwnerAreaReportService")->notExistToInsert($owners);
  472. $reports = OwnerAreaReport::query()->with(["owner","ownerStoragePriceModel.unit"])
  473. ->where("counting_month",">=",date("Y-m")."-01")
  474. ->whereIn("owner_id",array_column($owners->toArray(),"id"))->get();
  475. $result = [];
  476. foreach ($reports as $report){
  477. $result[] = [
  478. "id" => $report->id,
  479. "ownerGroupId" => $report->user_owner_group_id,
  480. "ownerName" => $report->owner ? $report->owner->name : '',
  481. "customerName" => $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
  482. "countingMonth" => $report->counting_month,
  483. "areaOnTray" => $report->area_on_tray,
  484. "areaOnHalfTray" => $report->area_on_half_tray,
  485. "areaOnFlat" => $report->area_on_flat,
  486. "accountingArea" => $report->accounting_area,
  487. "status" => $report->status,
  488. "updatedAt" => $report->updated_at,
  489. "unitName" => $report->ownerStoragePriceModel ? ($report->ownerStoragePriceModel->unit ? $report->ownerStoragePriceModel->unit->name : '') : '',
  490. "ownerStoragePriceModel"=> $report->ownerStoragePriceModel ? $report->ownerStoragePriceModel->using_type : '' ,
  491. ];
  492. }
  493. $this->success($result);
  494. }
  495. public function resetInstantBill()
  496. {
  497. ini_set('max_execution_time', 2500);
  498. $startData = request("startDate");
  499. $endDate = request("endDate");
  500. $owner = request("owner");
  501. if (!$startData)$this->error("非法参数");
  502. DB::beginTransaction();
  503. try {
  504. $details = OwnerFeeDetail::query()->where("worked_at",">=",$startData." 00:00:00");
  505. if ($endDate)$details->where("worked_at","<=",$endDate." 23:59:59");
  506. if (count($owner)>0)$details->whereIn("owner_id",$owner);
  507. $fee = OwnerFeeExpress::query()->where("created_at",">=",$startData." 00:00:00");
  508. if ($endDate)$fee->where("created_at","<=",$endDate." 23:59:59");
  509. if (count($owner)>0)$fee->whereIn("owner_id",$owner);
  510. $fee->delete();
  511. $feeQuery = OwnerFeeOperation::query()->select("id")->where("worked_at",">=",$startData);
  512. if ($endDate)$feeQuery->where("worked_at","<=",$endDate);
  513. if (count($owner)>0)$feeQuery->whereIn("owner_id",$owner);
  514. OwnerFeeOperationDetail::query()->whereIn("owner_fee_operation_id",$feeQuery)->delete();
  515. $feeQuery->delete();
  516. $fee = OwnerFeeLogistic::query()->where("created_at",">=",$startData." 00:00:00");
  517. if ($endDate)$fee->where("created_at","<=",$endDate." 23:59:59");
  518. if (count($owner)>0)$fee->whereIn("owner_id",$owner);
  519. $fee->delete();
  520. $details->get()->each(function ($detail){
  521. dispatch(new ResetInstantBill($detail));
  522. });
  523. DB::commit();
  524. $this->success();
  525. }catch (\Exception $e){
  526. DB::rollBack();
  527. $this->error("失败");
  528. }
  529. //$this->restoreResetInstantBillOrder($startData,$endDate);
  530. //$this->restoreResetInstantBillStore($startData,$endDate);
  531. }
  532. private function restoreResetInstantBillOrder($startData,$endDate)
  533. {
  534. $orders = Order::query()->where("wms_status","订单完成")->whereBetween("updated_at",["{$startData} 00:00:00","{$endDate} 23:59:59"])
  535. ->whereNotIn("id",OwnerFeeDetail::query()->select("outer_id")->where("outer_table_name","orders")
  536. ->whereBetween("worked_at",["{$startData} 00:00:00","{$endDate} 23:59:59"]))->get();
  537. foreach ($orders->chunk(50) as $or){
  538. dispatch(new OrderCreateInstantBill($or));
  539. }
  540. }
  541. private function restoreResetInstantBillStore($startData,$endDate)
  542. {
  543. $stores = Store::query()->where("status","已入库")->whereBetween("updated_at",["{$startData} 00:00:00","{$endDate} 23:59:59"])
  544. ->whereNotIn("id",OwnerFeeDetail::query()->select("outer_id")->where("outer_table_name","stores")
  545. ->whereBetween("worked_at",["{$startData} 00:00:00","{$endDate} 23:59:59"]))->get();
  546. foreach ($stores->chunk(50) as $st){
  547. dispatch(new StoreCreateInstantBill($st));
  548. }
  549. }
  550. public function resetBillConfirmation()
  551. {
  552. $month = request("month");
  553. if (!$month)$this->error("无日期");
  554. $owner = request("owner");
  555. if ($owner && !is_array($owner))$this->error("非法数据");
  556. $sql = <<<sql
  557. SELECT owner_id,SUM(IFNULL(work_fee,0)) AS work_fee,SUM(IFNULL(logistic_fee,0)) AS logistic_fee FROM owner_fee_details WHERE worked_at LIKE ? AND
  558. ((type = '发货' AND logistic_fee IS NOT NULL AND work_fee IS NOT NULL) OR (type <> '发货' AND work_fee IS NOT NULL))
  559. sql;
  560. if ($owner && count($owner)>0){
  561. $sql.=" AND owner_id IN (''";
  562. foreach ($owner as $o)$sql .=",'{$o}'";
  563. $sql.=")";
  564. }
  565. $sql .= " GROUP BY owner_id";
  566. $billDetails = DB::select(DB::raw($sql),[$month."%"]);
  567. $areas = OwnerAreaReport::query()->with(["ownerStoragePriceModel.timeUnit","ownerStoragePriceModel.taxRate"])
  568. ->where("counting_month","like",$month."%");
  569. if ($owner && count($owner)>0){
  570. $areas->whereIn("owner_id",$owner);
  571. }
  572. $areas = $areas->get();
  573. $map = [];
  574. $mapTax = [];
  575. foreach($areas as $area){
  576. if (!$area->ownerStoragePriceModel)continue;
  577. //信息提取模板
  578. $GLOBALS["FEE_INFO"] = [
  579. "counting_type" =>$area->ownerStoragePriceModel->counting_type,
  580. "using_type" =>$area->ownerStoragePriceModel->using_type,
  581. "fee_description" =>"",
  582. "total_fee" =>0,
  583. "tax_rate" =>0,
  584. ];
  585. $key = $area->owner_id."_".$area->counting_month;
  586. if (!isset($map[$key]))$map[$key] = $mapTax[$key] = 0;
  587. list($money,$taxFee) = app('OwnerStoragePriceModelService')
  588. ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
  589. $map[$key] += $money;
  590. $mapTax[$key] += $taxFee;
  591. $GLOBALS["FEE_INFO"]["total_fee"] = $money;
  592. OwnerFeeStorage::query()->where("area_id",$area->id)
  593. ->update($GLOBALS["FEE_INFO"]);
  594. }
  595. foreach (OwnerPriceSystem::query()->with(["timeUnit","taxRate"])
  596. ->select("owner_id","usage_fee")->whereNull("operation")
  597. ->orWhere("operation","")->get() as $system){
  598. list($systemFee[$system->owner_id],$systemTaxFee[$system->owner_id]) =
  599. app("OwnerAreaReportService")->systemFee($system,$month);
  600. }
  601. $chunks = array_chunk($billDetails,50);
  602. foreach ($chunks as $bills){
  603. foreach ($bills as $bill){
  604. $key = $bill->owner_id."_".$month;
  605. OwnerBillReport::query()->where("owner_id",$bill->owner_id)
  606. ->where("counting_month",$month."-01")
  607. ->update(["work_fee"=>$bill->work_fee,
  608. "logistic_fee"=>$bill->logistic_fee,
  609. "storage_fee"=>$map[$key] ?? 0,
  610. "other_fee" => $systemFee[$bill->owner_id] ?? null,
  611. "other_tax_fee" => $systemTaxFee[$bill->owner_id] ?? null,
  612. "storage_tax_fee" => $mapTax[$key] ?? 0]);
  613. }
  614. }
  615. $this->dispatch(new SettlementBillReportJob($month."-01",$owner));
  616. $this->success();
  617. }
  618. }