CustomerController.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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","storageAudit","operationAudit","expressAudit","logisticAudit","directLogisticAudit","systemAudit"]);
  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. "subjection" => request("subjection"),
  178. ]);
  179. $this->success($owner);
  180. }
  181. //获取货主下所有相关计费模型
  182. public function getOwnerPriceModel(Request $request)
  183. {
  184. $owner = new Owner();
  185. $owner->id = $request->id;
  186. $owner->load(["ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics"]);
  187. return ["success"=>true,"data"=>["ownerPriceOperations"=>$owner->ownerPriceOperations,
  188. "ownerPriceExpresses"=>$owner->ownerPriceExpresses,
  189. "ownerPriceLogistics"=>$owner->ownerPriceLogistics,
  190. "ownerPriceDirectLogistics"=>$owner->ownerPriceDirectLogistics]];
  191. }
  192. public function projectEdit($id)
  193. {
  194. if(!Gate::allows('项目管理-项目-编辑')){ return redirect('denied'); }
  195. /** @var Owner $owner */
  196. $owner = app('OwnerService')->find($id);
  197. $owner->loadCount(["ownerStoragePriceModels","ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics","ownerPriceSystem"]);
  198. $isExist = false;
  199. /** @var \stdClass $owner */
  200. if($owner->owner_storage_price_models_count ||
  201. $owner->owner_price_operations_count ||
  202. $owner->owner_price_expresses_count ||
  203. $owner->owner_price_logistics_count ||
  204. $owner->owner_price_system_count ||
  205. $owner->owner_price_direct_logistics_count) $isExist = true;
  206. $customers = app('CustomerService')->getSelection();
  207. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  208. $userGroups = app('UserWorkgroupService')->getSelection(["id","name","warehouse_id"]);
  209. $warehouses = app('WarehouseService')->getSelection();
  210. $type = request("type");
  211. return response()->view('customer.project.create',compact("customers","ownerGroups","warehouses",'owner',"isExist", "type","userGroups"));
  212. }
  213. public function projectArea(Request $request)
  214. {
  215. if(!Gate::allows('项目管理-项目-面积')){ return redirect('denied'); }
  216. $areas = app('OwnerAreaReportService')->paginate($request->input(),["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels.unit"]);},"userOwnerGroup"]);
  217. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  218. $customers = app('CustomerService')->getSelection();
  219. $owners = app('OwnerService')->getIntersectPermitting();
  220. $params = $request->input();
  221. return response()->view('customer.project.area',compact("areas","ownerGroups","customers","owners","params"));
  222. }
  223. public function updateArea()
  224. {
  225. $this->gate("项目管理-项目-面积-编辑");
  226. if (!request("id")) $this->error("非法参数");
  227. $total = ((int)request("areaOnTray")*2.5) +
  228. ((int)request("areaOnHalfTray")*1.8) + ((int)request("areaOnFlat")*1.3);
  229. $obj = [
  230. "user_owner_group_id" => request("ownerGroupId"),
  231. "area_on_tray" => request("areaOnTray"),
  232. "area_on_half_tray" => request("areaOnHalfTray"),
  233. "area_on_flat" => request("areaOnFlat"),
  234. "accounting_area" => intval($total*1000)/1000,
  235. ];
  236. $re = app('OwnerAreaReportService')->update(["id"=>request("id")],$obj);
  237. if ($re===true)$this->success($obj);
  238. else $this->error($re);
  239. }
  240. //面积报表审核
  241. public function areaReportAudit()
  242. {
  243. $this->gate("项目管理-项目-用仓盘点-审核");
  244. $id = request("id");
  245. if(!$id)$this->error("非法参数");
  246. $area = OwnerAreaReport::query()->find($id);
  247. /** @var \stdClass $area */
  248. if (!$area || $area->status!='编辑中')$this->error("记录已被操作");
  249. $area->update(["status"=>"已审核"]);
  250. $this->success();
  251. }
  252. public function projectAreaExport(Request $request)
  253. {
  254. if(!Gate::allows('项目管理-项目-面积')){ return redirect('denied'); }
  255. $params = $request->input();
  256. if ($request->checkAllSign)unset($params['checkAllSign']);
  257. else $params = ["id"=>$request->data];
  258. /** @var OwnerAreaReportService $serves */
  259. $serves = app('OwnerAreaReportService');
  260. $areas = $serves->get($params,["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels","userOwnerGroup"]);}]);
  261. $column = ["状态","项目组","客户","子项目","结算月","录入时间","用仓类型","货物整托","货物半托","平面区面积","结算面积"];
  262. $list = [];
  263. foreach ($areas as $area){
  264. $list[] = [
  265. $area->status,
  266. $area->owner ? ($area->owner->userOwnerGroup ? $area->owner->userOwnerGroup->name : '') : '',
  267. $area->owner ? ($area->owner->customer ? $area->owner->customer->name : '') : '',
  268. $area->owner ? $area->owner->name : '',
  269. $area->counting_month,
  270. $area->updated_at,
  271. $area->owner ? implode(",",array_unique(array_column(($area->owner->ownerStoragePriceModels)->toArray(),"using_type"))) : '',
  272. $area->area_on_tray,
  273. $area->area_on_half_tray,
  274. $area->area_on_flat,
  275. $area->accounting_area,
  276. ];
  277. }
  278. $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
  279. if ($post->status() == 500){
  280. throw new Exception($post->header("Msg"));
  281. }
  282. return response($post,200, [
  283. "Content-type"=>"application/octet-stream",
  284. "Content-Disposition"=>"attachment; filename=项目面积报表-".date('ymdHis').'.xlsx',
  285. ]);
  286. }
  287. public function financeInstantBill(Request $request)
  288. {
  289. if(!Gate::allows('结算管理-即时账单')){ return redirect('denied'); }
  290. $params = $request->input();
  291. $shops = app('ShopService')->getSelection();
  292. $customers = app('CustomerService')->getSelection();
  293. $owners = app('OwnerService')->getIntersectPermitting();
  294. $details = app('OwnerFeeDetailService')->paginate($params,["owner.customer","shop","processMethod","logistic","items"]);
  295. return response()->view('finance.instantBill',compact("details","params","shops","customers","owners"));
  296. }
  297. public function financeInstantBillExport(Request $request)
  298. {
  299. if(!Gate::allows('结算管理-即时账单')){ return redirect('denied'); }
  300. $params = $request->input();
  301. if ($request->checkAllSign)unset($params['checkAllSign']);
  302. else $params = ["id"=>$request->data];
  303. $sql = app('OwnerFeeDetailService')->getSql($params);
  304. $row = ["客户", "项目", "作业时间", "类型","店铺", "单号(发/收/退/提)", "收件人", "收件人电话", "商品数量",
  305. "物流/快递单号", "体积", "重量", "承运商", "操作费", "物流费", "合计"];
  306. $column = ["customer_name", "owner_name", "worked_at", "type","shop_name", "operation_bill", "consignee_name", "consignee_phone", "commodity_amount",
  307. "logistic_bill", "volume", "weight", "logistic_name", "work_fee", "logistic_fee", "total"];
  308. $rule = ["work_fee"=>"mysqlDate"];
  309. $post = Http::post(config('go.export.url'),['type'=>'unify','sql'=>$sql, 'connection'=>'mysql',
  310. 'row'=>json_encode($row,JSON_UNESCAPED_UNICODE), 'column'=>json_encode($column), 'rule'=>json_encode($rule)]);
  311. if ($post->status() == 500){
  312. throw new Exception($post->header("Msg"));
  313. }
  314. return response($post,200, [
  315. "Content-type"=>"application/octet-stream",
  316. "Content-Disposition"=>"attachment; filename=即时账单记录-".date('ymdHis').'.xlsx',
  317. ]);
  318. }
  319. public function financeBillConfirmation(Request $request)
  320. {
  321. if(!Gate::allows('结算管理-账单确认')){ return redirect('denied'); }
  322. $params = $request->input();
  323. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  324. $customers = app('CustomerService')->getSelection();
  325. $owners = app('OwnerService')->getIntersectPermitting();
  326. $bills = app('OwnerBillReportService')->paginate($params,["owner"=>function($query){
  327. /** @var Builder $query */
  328. $query->with(["customer","userOwnerGroup"]);
  329. }]);
  330. return response()->view('finance.billConfirmation',compact("params","owners","ownerGroups","customers","bills"));
  331. }
  332. public function financeBillConfirmationExport(Request $request)
  333. {
  334. if(!Gate::allows('结算管理-账单确认')){ return redirect('denied'); }
  335. $params = $request->input();
  336. if ($request->checkAllSign)unset($params['checkAllSign']);
  337. else $params = ["id"=>$request->data];
  338. /** @var OwnerBillReportService $serves */
  339. $serves = app('OwnerBillReportService');
  340. $bills = $serves->get($params,["owner"=>function($query){
  341. /** @var Builder $query */
  342. $query->with(["customer","userOwnerGroup"]);
  343. }]);
  344. $column = ["项目小组","客户","子项目","结算月","录入日期","原始账单金额","确认账单金额","差额","状态"];
  345. $list = [];
  346. foreach ($bills as $bill){
  347. $list[] = [
  348. $bill->owner ? ($bill->owner->userOwnerGroup ? $bill->owner->userOwnerGroup->name : '') : '',
  349. $bill->owner ? ($bill->owner->customer ? $bill->owner->customer->name : '') : '',
  350. $bill->owner ? $bill->owner->name : '',
  351. $bill->counting_month,
  352. $bill->updated_at,
  353. $bill->initial_fee,
  354. $bill->confirm_fee,
  355. $bill->difference,
  356. $bill->confirmed == '是' ? '已确认' : '未确认',
  357. ];
  358. }
  359. $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
  360. if ($post->status() == 500){
  361. throw new Exception($post->header("Msg"));
  362. }
  363. return response($post,200, [
  364. "Content-type"=>"application/octet-stream",
  365. "Content-Disposition"=>"attachment; filename=客户账单报表-".date('ymdHis').'.xlsx',
  366. ]);
  367. }
  368. public function updateBillReport(Request $request)
  369. {
  370. if(!Gate::allows('结算管理-账单确认-编辑')){ return ["success"=>false,'data'=>"无权操作!"]; }
  371. if (!$request->confirm_fee || !is_numeric($request->confirm_fee) || $request->confirm_fee<0)return ["success"=>false,"data"=>"非法金额参数"];
  372. $date = date('Y-m-d H:i:s');
  373. 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]);
  374. LogService::log(__METHOD__,"项目管理-修改账单报表",json_encode($request->input()));
  375. return ["success"=>true,"data"=>$date];
  376. }
  377. public function billConfirm()
  378. {
  379. $this->gate("结算管理-账单确认-完结");
  380. if (!request("id"))$this->error("非法参数");
  381. /** @var OwnerBillReport $bill */
  382. $bill = app('OwnerBillReportService')->first(["id"=>request("id"),"confirmed"=>"否"]);
  383. if (!$bill)$this->error("账单状态变更,禁止操作");
  384. /** @var \stdClass $bill */
  385. $area = OwnerAreaReport::query()->where("owner_id",$bill->owner_id)
  386. ->where("counting_month","like",$bill->counting_month."%")->first();
  387. if (!$area || $area->status!='编辑中')$this->error("对应面积报表状态异常");
  388. $bill->update(["confirmed"=>"是"]);
  389. LogService::log(__METHOD__,"项目管理-确认账单",json_encode(request()->input()));
  390. app('OwnerAreaReportService')->lockArea(null, $bill->owner_id, $bill->counting_month);
  391. LogService::log(__METHOD__,"项目管理-锁定账单的所有面积",json_encode($bill,JSON_UNESCAPED_UNICODE));
  392. $this->success();
  393. }
  394. private function validator(array $params){
  395. $validator=Validator::make($params,[
  396. 'id' => ['required'],
  397. 'customer_id'=>['required'],
  398. 'owner_group_id'=>['required'],
  399. 'warehouse_id'=>['required'],
  400. 'tax_rate_id' => ["required",'integer'],
  401. 'waring_line_on' => ["nullable",'integer'],
  402. ],[
  403. 'required'=>':attribute 为必填项',
  404. 'integer'=>':attribute 必须为整数',
  405. 'numeric'=>':attribute 必须为数字',
  406. ],[
  407. 'code'=>'项目代码',
  408. 'name'=>'项目名称',
  409. 'warehouse_id'=>'仓库',
  410. 'customer_id'=>'客户',
  411. 'owner_group_id'=>'工作组',
  412. 'tax_rate_id' => '税率',
  413. 'waring_line_on' => '月单量预警'
  414. ]);
  415. return $validator;
  416. }
  417. public function verifyProject(Request $request)
  418. {
  419. $this->success($this->validator($request->input())->errors());
  420. }
  421. public function createReport()
  422. {
  423. $ids = \request("val");
  424. if (!$ids)$this->error("未选择任何项目");
  425. $reports = OwnerReport::query()->with("owner")
  426. ->where("counting_month",">=",date("Y-m")."-01")
  427. ->whereIn("owner_id",$ids)->get(["id","owner_id"]);
  428. $errors = [];
  429. $exist = [];
  430. foreach ($reports as $report){
  431. $errors[] = "“".($report->owner ? $report->owner->name : $report->owner_id)."”已存在本月报表";
  432. $exist[] = $report->owner_id;
  433. }
  434. $ids = array_diff($ids,$exist);
  435. $insert = [];
  436. $date = date("Y-m-d H:i:s");
  437. foreach ($ids as $id){
  438. $insert[] = [
  439. "owner_id" => $id,
  440. "counting_month" => date("Y-m-d"),
  441. "created_at" => $date
  442. ];
  443. }
  444. if ($insert){
  445. OwnerReport::query()->insert($insert);
  446. LogService::log(__METHOD__,"手动生成报表",json_encode($insert));
  447. }
  448. $reports = OwnerReport::query()->with(["owner.userOwnerGroup","owner.customer"])
  449. ->where("counting_month",">=",date("Y-m")."-01")
  450. ->whereIn("owner_id",$ids)->get();
  451. $result = [];
  452. foreach ($reports as $report){
  453. $result[] = [
  454. "id" => $report->id,
  455. "ownerGroupName" => $report->owner ? ($report->owner->userOwnerGroup ? $report->owner->userOwnerGroup->name : '') : '',
  456. "customerName" => $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
  457. "ownerName" => $report->owner ? $report->owner->name : '',
  458. "ownerStatus" => $report->owner ? ($report->owner->deleted_at ? "冻结" : "激活") : '',
  459. "ownerStorageDuration" => $report->owner ? ($report->owner->created_at ? ((new \DateTime())->diff(new \DateTime($report->owner->created_at))->days) : '') : '',
  460. "ownerCreatedAt" => $report->owner ? $report->owner->created_at : '',
  461. "countingMonth" => $report->counting_month,
  462. ];
  463. }
  464. $this->success(["errors"=>$errors,"data"=>$result]);
  465. }
  466. public function createAreaReport()
  467. {
  468. $ids = \request("val");
  469. if (!$ids)$this->error("未选择任何项目");
  470. /** @var OwnerService $service */
  471. $service = app("OwnerService");
  472. $owners = $service->get(["id"=>$ids],["ownerStoragePriceModels"],false,true);
  473. app("OwnerAreaReportService")->notExistToInsert($owners);
  474. $reports = OwnerAreaReport::query()->with(["owner","ownerStoragePriceModel.unit"])
  475. ->where("counting_month",">=",date("Y-m")."-01")
  476. ->whereIn("owner_id",array_column($owners->toArray(),"id"))->get();
  477. $result = [];
  478. foreach ($reports as $report){
  479. $result[] = [
  480. "id" => $report->id,
  481. "ownerGroupId" => $report->user_owner_group_id,
  482. "ownerName" => $report->owner ? $report->owner->name : '',
  483. "customerName" => $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
  484. "countingMonth" => $report->counting_month,
  485. "areaOnTray" => $report->area_on_tray,
  486. "areaOnHalfTray" => $report->area_on_half_tray,
  487. "areaOnFlat" => $report->area_on_flat,
  488. "accountingArea" => $report->accounting_area,
  489. "status" => $report->status,
  490. "updatedAt" => $report->updated_at,
  491. "unitName" => $report->ownerStoragePriceModel ? ($report->ownerStoragePriceModel->unit ? $report->ownerStoragePriceModel->unit->name : '') : '',
  492. "ownerStoragePriceModel"=> $report->ownerStoragePriceModel ? $report->ownerStoragePriceModel->using_type : '' ,
  493. ];
  494. }
  495. $this->success($result);
  496. }
  497. public function resetInstantBill()
  498. {
  499. $startData = request("startDate");
  500. $endDate = request("endDate");
  501. $owner = request("owner");
  502. if (!$startData)$this->error("非法参数");
  503. $details = OwnerFeeDetail::query()->where("worked_at",">=",$startData." 00:00:00");
  504. if ($endDate)$details->where("worked_at","<=",$endDate." 23:59:59");
  505. if (count($owner)>0)$details->whereIn("owner_id",$owner);
  506. $details->get()->each(function ($detail){
  507. $this->dispatch(new ResetInstantBill($detail));
  508. });
  509. $this->success();
  510. }
  511. public function resetBillConfirmation()
  512. {
  513. $month = request("month");
  514. $owner = request("owner");
  515. $sql = <<<sql
  516. SELECT owner_id,SUM(IFNULL(work_fee,0)) AS work_fee,SUM(IFNULL(logistic_fee,0)) AS logistic_fee
  517. FROM owner_fee_details WHERE worked_at LIKE ?
  518. sql;
  519. if ($owner && count($owner)>0){
  520. $sql.=" AND owner_id IN (''";
  521. foreach ($owner as $o)$sql .=",'{$o}'";
  522. $sql.=")";
  523. }
  524. $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";
  525. $billDetails = DB::select(DB::raw($sql),[$month."%"]);
  526. $areas = OwnerAreaReport::query()->with("ownerStoragePriceModel")->where("counting_month","like",$month."%")->get();
  527. $map = [];
  528. foreach($areas as $area){
  529. if (isset($map[$area->owner_id."_".$area->counting_month])){
  530. if (!$area->ownerStoragePriceModel)continue;
  531. $map[$area->owner_id."_".$area->counting_month] += app('OwnerStoragePriceModelService')
  532. ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
  533. }else{
  534. if (!$area->ownerStoragePriceModel)continue;
  535. $map[$area->owner_id."_".$area->counting_month] = app('OwnerStoragePriceModelService')
  536. ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
  537. }
  538. }
  539. $chunks = array_chunk($billDetails,50);
  540. foreach ($chunks as $bills){
  541. foreach ($bills as $bill){
  542. $key = $bill->owner_id."_".$month;
  543. OwnerBillReport::query()->where("owner_id",$bill->owner_id)
  544. ->where("counting_month",$month."-01")
  545. ->update(["work_fee"=>$bill->work_fee,"logistic_fee"=>$bill->logistic_fee,"storage_fee"=>$map[$key] ?? 0]);
  546. }
  547. }
  548. $this->success();
  549. }
  550. }