CustomerController.php 29 KB

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