CustomerController.php 28 KB

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