CustomerController.php 29 KB

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