CustomerController.php 30 KB

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