CustomerController.php 30 KB

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