CustomerController.php 30 KB

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