CustomerController.php 31 KB

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