CustomerController.php 28 KB

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