CustomerController.php 30 KB

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