CustomerController.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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\ObligationService;
  22. use App\Services\OwnerAreaReportService;
  23. use App\Services\OwnerBillReportService;
  24. use App\Services\OwnerReportService;
  25. use App\Services\OwnerService;
  26. use App\Store;
  27. use App\UserWorkgroup;
  28. use Illuminate\Database\Eloquent\Builder;
  29. use Illuminate\Http\Request;
  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. 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",'departmentObligationOwner.department',
  94. "ownerStoragePriceModels","storageAudit","operationAudit","expressAudit","logisticAudit","directLogisticAudit","systemAudit"]);
  95. $owners=app('OwnerService')->combineOwners($owners);
  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. /** @var ObligationService $service*/
  177. $service= app('ObligationService');
  178. $owner=$service->createOrUpdate(request()->input());
  179. $this->success($owner);
  180. }
  181. //获取货主下所有相关计费模型
  182. public function getOwnerPriceModel(Request $request)
  183. {
  184. $owner = new Owner();
  185. $owner->id = $request->id;
  186. $owner->load(["ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics"]);
  187. return ["success"=>true,"data"=>["ownerPriceOperations"=>$owner->ownerPriceOperations,
  188. "ownerPriceExpresses"=>$owner->ownerPriceExpresses,
  189. "ownerPriceLogistics"=>$owner->ownerPriceLogistics,
  190. "ownerPriceDirectLogistics"=>$owner->ownerPriceDirectLogistics]];
  191. }
  192. public function projectEdit($id)
  193. {
  194. if(!Gate::allows('项目管理-项目-编辑')){ return redirect('denied'); }
  195. /** @var Owner $owner */
  196. $owner = app('OwnerService')->find($id,['departmentObligationOwner']);
  197. $departmentObligationOwner=$owner->departmentObligationOwner??[];
  198. if (count($departmentObligationOwner)>0){
  199. foreach ($departmentObligationOwner as $item){
  200. if ($item->obligation_code=='kc')$owner->kc=$item->department_id;
  201. if ($item->obligation_code=='jg')$owner->jg=$item->department_id;
  202. if ($item->obligation_code=='th')$owner->th=$item->department_id;
  203. if ($item->obligation_code=='sh')$owner->sh=$item->department_id;
  204. if ($item->obligation_code=='fh')$owner->fh=$item->department_id;
  205. }
  206. }
  207. $owner->loadCount(["ownerStoragePriceModels","ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics","ownerPriceSystem"]);
  208. $isExist = false;
  209. /** @var \stdClass $owner */
  210. if($owner->owner_storage_price_models_count ||
  211. $owner->owner_price_operations_count ||
  212. $owner->owner_price_expresses_count ||
  213. $owner->owner_price_logistics_count ||
  214. $owner->owner_price_system_count ||
  215. $owner->owner_price_direct_logistics_count) $isExist = true;
  216. $customers = app('CustomerService')->getSelection();
  217. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  218. $userGroups = app('UserWorkgroupService')->getSelection(["id","name","warehouse_id"]);
  219. $warehouses = app('WarehouseService')->getSelection();
  220. $type = request("type");
  221. return response()->view('customer.project.create',compact("customers","ownerGroups","warehouses",'owner',"isExist", "type","userGroups"));
  222. }
  223. public function projectArea(Request $request)
  224. {
  225. if(!Gate::allows('项目管理-项目-面积')){ return redirect('denied'); }
  226. $areas = app('OwnerAreaReportService')->paginate($request->input(),["owner.customer","ownerStoragePriceModel.unit","userOwnerGroup"]);
  227. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  228. $customers = app('CustomerService')->getSelection();
  229. $owners = app('OwnerService')->getIntersectPermitting();
  230. $params = $request->input();
  231. return response()->view('customer.project.area',compact("areas","ownerGroups","customers","owners","params"));
  232. }
  233. public function updateArea()
  234. {
  235. $this->gate("项目管理-项目-面积-编辑");
  236. if (!request("id")) $this->error("非法参数");
  237. $total = ((int)request("areaOnTray")*2.5) +
  238. ((int)request("areaOnHalfTray")*1.8) + ((int)request("areaOnFlat")*1.3);
  239. $obj = [
  240. "user_owner_group_id" => request("ownerGroupId"),
  241. "area_on_tray" => request("areaOnTray"),
  242. "area_on_half_tray" => request("areaOnHalfTray"),
  243. "area_on_flat" => request("areaOnFlat"),
  244. "accounting_area" => intval($total*1000)/1000,
  245. ];
  246. $re = app('OwnerAreaReportService')->update(["id"=>request("id")],$obj);
  247. if ($re===true)$this->success($obj);
  248. else $this->error($re);
  249. }
  250. //面积报表审核
  251. public function areaReportAudit()
  252. {
  253. $this->gate("项目管理-项目-用仓盘点-审核");
  254. $id = request("id");
  255. if(!$id)$this->error("非法参数");
  256. $area = OwnerAreaReport::query()->find($id);
  257. /** @var \stdClass $area */
  258. if (!$area || $area->status!='编辑中')$this->error("记录已被操作");
  259. $area->update(["status"=>"已审核"]);
  260. $this->success();
  261. }
  262. public function projectAreaExport(Request $request)
  263. {
  264. if(!Gate::allows('项目管理-项目-面积')){ return redirect('denied'); }
  265. $params = $request->input();
  266. if ($request->checkAllSign)unset($params['checkAllSign']);
  267. else $params = ["id"=>$request->data];
  268. /** @var OwnerAreaReportService $serves */
  269. $serves = app('OwnerAreaReportService');
  270. $areas = $serves->get($params,["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels","userOwnerGroup"]);}]);
  271. $column = ["状态","项目组","客户","子项目","结算月","录入时间","用仓类型","货物整托","货物半托","平面区面积","结算面积"];
  272. $list = [];
  273. foreach ($areas as $area){
  274. $list[] = [
  275. $area->status,
  276. $area->owner ? ($area->owner->userOwnerGroup ? $area->owner->userOwnerGroup->name : '') : '',
  277. $area->owner ? ($area->owner->customer ? $area->owner->customer->name : '') : '',
  278. $area->owner ? $area->owner->name : '',
  279. $area->counting_month,
  280. $area->updated_at,
  281. $area->owner ? implode(",",array_unique(array_column(($area->owner->ownerStoragePriceModels)->toArray(),"using_type"))) : '',
  282. $area->area_on_tray,
  283. $area->area_on_half_tray,
  284. $area->area_on_flat,
  285. $area->accounting_area,
  286. ];
  287. }
  288. return Export::make($column,$list,"项目面积报表");
  289. }
  290. public function financeInstantBill(Request $request)
  291. {
  292. if(!Gate::allows('结算管理-即时账单')){ return redirect('denied'); }
  293. $params = $request->input();
  294. $shops = app('ShopService')->getSelection();
  295. $customers = app('CustomerService')->getSelection();
  296. $owners = app('OwnerService')->getIntersectPermitting();
  297. $details = app('OwnerFeeDetailService')->paginate($params,["owner.customer","shop","processMethod","logistic","items"]);
  298. return response()->view('finance.instantBill',compact("details","params","shops","customers","owners"));
  299. }
  300. public function financeInstantBillExport(Request $request)
  301. {
  302. if(!Gate::allows('结算管理-即时账单')){ return redirect('denied'); }
  303. $params = $request->input();
  304. if ($request->checkAllSign)unset($params['checkAllSign']);
  305. else $params = ["id"=>$request->data];
  306. $sql = app('OwnerFeeDetailService')->getSql($params);
  307. $rule = ["work_fee"=>"mysqlDate"];
  308. $e = new Export();
  309. $e->setMysqlConnection(config('database.connections.mysql.host'),
  310. config('database.connections.mysql.port'),config('database.connections.mysql.database')
  311. ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
  312. $e->setFileName("即时账单记录");
  313. return $e->sql($sql,[
  314. "customer_name"=>"客户","owner_name"=>"项目",
  315. "worked_at"=>"作业时间","type"=>"类型",
  316. "shop_name"=>"店铺","operation_bill"=>"单号(发/收/退/提)",
  317. "consignee_name"=>"收件人","consignee_phone"=>"收件人电话",
  318. "commodity_amount"=>"商品数量","logistic_bill"=>"物流/快递单号",
  319. "volume"=>"体积","weight"=>"重量","logistic_name"=>"承运商",
  320. "work_fee"=>"操作费","logistic_fee"=>"物流费","total"=>"合计"
  321. ],$rule)->direct();
  322. }
  323. public function financeBillConfirmation(Request $request)
  324. {
  325. if(!Gate::allows('结算管理-账单确认')){ return redirect('denied'); }
  326. $params = $request->input();
  327. $ownerGroups = app('UserOwnerGroupService')->getSelection();
  328. $customers = app('CustomerService')->getSelection();
  329. $owners = app('OwnerService')->getIntersectPermitting();
  330. $bills = app('OwnerBillReportService')->paginate($params,["owner"=>function($query){
  331. /** @var Builder $query */
  332. $query->with(["customer","userOwnerGroup"]);
  333. }]);
  334. return response()->view('finance.billConfirmation',compact("params","owners","ownerGroups","customers","bills"));
  335. }
  336. public function financeBillConfirmationExport(Request $request)
  337. {
  338. if(!Gate::allows('结算管理-账单确认')){ return redirect('denied'); }
  339. $params = $request->input();
  340. if ($request->checkAllSign)unset($params['checkAllSign']);
  341. else $params = ["id"=>$request->data];
  342. /** @var OwnerBillReportService $serves */
  343. $serves = app('OwnerBillReportService');
  344. $bills = $serves->get($params,["owner"=>function($query){
  345. /** @var Builder $query */
  346. $query->with(["customer","userOwnerGroup"]);
  347. }]);
  348. $column = ["项目小组","客户","子项目","结算月","录入日期","原始账单金额","确认账单金额","差额","状态"];
  349. $list = [];
  350. foreach ($bills as $bill){
  351. $list[] = [
  352. $bill->owner ? ($bill->owner->userOwnerGroup ? $bill->owner->userOwnerGroup->name : '') : '',
  353. $bill->owner ? ($bill->owner->customer ? $bill->owner->customer->name : '') : '',
  354. $bill->owner ? $bill->owner->name : '',
  355. $bill->counting_month,
  356. $bill->updated_at,
  357. $bill->initial_fee,
  358. $bill->confirm_fee,
  359. $bill->difference,
  360. $bill->confirmed == '是' ? '已确认' : '未确认',
  361. ];
  362. }
  363. return Export::make($column,$list,"客户账单报表");
  364. }
  365. public function updateBillReport(Request $request)
  366. {
  367. if(!Gate::allows('结算管理-账单确认-编辑')){ return ["success"=>false,'data'=>"无权操作!"]; }
  368. if (!$request->confirm_fee || !is_numeric($request->confirm_fee) || $request->confirm_fee<0)return ["success"=>false,"data"=>"非法金额参数"];
  369. $date = date('Y-m-d H:i:s');
  370. 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]);
  371. LogService::log(__METHOD__,"项目管理-修改账单报表",json_encode($request->input()));
  372. return ["success"=>true,"data"=>$date];
  373. }
  374. public function billConfirm()
  375. {
  376. $this->gate("结算管理-账单确认-完结");
  377. if (!request("id"))$this->error("非法参数");
  378. /** @var OwnerBillReport $bill */
  379. $bill = app('OwnerBillReportService')->first(["id"=>request("id"),"confirmed"=>"否"]);
  380. if (!$bill)$this->error("账单状态变更,禁止操作");
  381. /** @var \stdClass $bill */
  382. $area = OwnerAreaReport::query()->where("owner_id",$bill->owner_id)
  383. ->where("counting_month","like",$bill->counting_month."%")->first();
  384. if (!$area || $area->status!='编辑中')$this->error("对应面积报表状态异常");
  385. $bill->update(["confirmed"=>"是"]);
  386. LogService::log(__METHOD__,"项目管理-确认账单",json_encode(request()->input()));
  387. app('OwnerAreaReportService')->lockArea(null, $bill->owner_id, $bill->counting_month);
  388. LogService::log(__METHOD__,"项目管理-锁定账单的所有面积",json_encode($bill,JSON_UNESCAPED_UNICODE));
  389. $this->success();
  390. }
  391. private function validator(array $params){
  392. $validator=Validator::make($params,[
  393. 'id' => ['required'],
  394. 'customer_id'=>['required'],
  395. 'owner_group_id'=>['required'],
  396. 'warehouse_id'=>['required'],
  397. 'tax_rate_id' => ["nullable",'integer'],
  398. 'waring_line_on' => ["nullable",'integer'],
  399. ],[
  400. 'required'=>':attribute 为必填项',
  401. 'integer'=>':attribute 必须为整数',
  402. 'numeric'=>':attribute 必须为数字',
  403. ],[
  404. 'code'=>'项目代码',
  405. 'name'=>'项目名称',
  406. 'warehouse_id'=>'仓库',
  407. 'customer_id'=>'客户',
  408. 'owner_group_id'=>'工作组',
  409. 'tax_rate_id' => '税率',
  410. 'waring_line_on' => '月单量预警'
  411. ]);
  412. return $validator;
  413. }
  414. public function verifyProject(Request $request)
  415. {
  416. $this->success($this->validator($request->input())->errors());
  417. }
  418. public function createReport()
  419. {
  420. $ids = \request("val");
  421. if (!$ids)$this->error("未选择任何项目");
  422. $reports = OwnerReport::query()->with("owner")
  423. ->where("counting_month",">=",date("Y-m")."-01")
  424. ->whereIn("owner_id",$ids)->get(["id","owner_id"]);
  425. $errors = [];
  426. $exist = [];
  427. foreach ($reports as $report){
  428. $errors[] = "“".($report->owner ? $report->owner->name : $report->owner_id)."”已存在本月报表";
  429. $exist[] = $report->owner_id;
  430. }
  431. $ids = array_diff($ids,$exist);
  432. $insert = [];
  433. $date = date("Y-m-d H:i:s");
  434. foreach ($ids as $id){
  435. $insert[] = [
  436. "owner_id" => $id,
  437. "counting_month" => date("Y-m-d"),
  438. "created_at" => $date
  439. ];
  440. }
  441. if ($insert){
  442. OwnerReport::query()->insert($insert);
  443. LogService::log(__METHOD__,"手动生成报表",json_encode($insert));
  444. }
  445. $reports = OwnerReport::query()->with(["owner.userOwnerGroup","owner.customer"])
  446. ->where("counting_month",">=",date("Y-m")."-01")
  447. ->whereIn("owner_id",$ids)->get();
  448. $result = [];
  449. foreach ($reports as $report){
  450. $result[] = [
  451. "id" => $report->id,
  452. "ownerGroupName" => $report->owner ? ($report->owner->userOwnerGroup ? $report->owner->userOwnerGroup->name : '') : '',
  453. "customerName" => $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
  454. "ownerName" => $report->owner ? $report->owner->name : '',
  455. "ownerStatus" => $report->owner ? ($report->owner->deleted_at ? "冻结" : "激活") : '',
  456. "ownerStorageDuration" => $report->owner ? ($report->owner->created_at ? ((new \DateTime())->diff(new \DateTime($report->owner->created_at))->days) : '') : '',
  457. "ownerCreatedAt" => $report->owner ? $report->owner->created_at : '',
  458. "countingMonth" => $report->counting_month,
  459. ];
  460. }
  461. $this->success(["errors"=>$errors,"data"=>$result]);
  462. }
  463. public function createAreaReport()
  464. {
  465. $ids = \request("val");
  466. if (!$ids)$this->error("未选择任何项目");
  467. /** @var OwnerService $service */
  468. $service = app("OwnerService");
  469. $owners = $service->get(["id"=>$ids],["ownerStoragePriceModels"],false,true);
  470. app("OwnerAreaReportService")->notExistToInsert($owners);
  471. $reports = OwnerAreaReport::query()->with(["owner","ownerStoragePriceModel.unit"])
  472. ->where("counting_month",">=",date("Y-m")."-01")
  473. ->whereIn("owner_id",array_column($owners->toArray(),"id"))->get();
  474. $result = [];
  475. foreach ($reports as $report){
  476. $result[] = [
  477. "id" => $report->id,
  478. "ownerGroupId" => $report->user_owner_group_id,
  479. "ownerName" => $report->owner ? $report->owner->name : '',
  480. "customerName" => $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
  481. "countingMonth" => $report->counting_month,
  482. "areaOnTray" => $report->area_on_tray,
  483. "areaOnHalfTray" => $report->area_on_half_tray,
  484. "areaOnFlat" => $report->area_on_flat,
  485. "accountingArea" => $report->accounting_area,
  486. "status" => $report->status,
  487. "updatedAt" => $report->updated_at,
  488. "unitName" => $report->ownerStoragePriceModel ? ($report->ownerStoragePriceModel->unit ? $report->ownerStoragePriceModel->unit->name : '') : '',
  489. "ownerStoragePriceModel"=> $report->ownerStoragePriceModel ? $report->ownerStoragePriceModel->using_type : '' ,
  490. ];
  491. }
  492. $this->success($result);
  493. }
  494. public function resetInstantBill()
  495. {
  496. ini_set('max_execution_time', 2500);
  497. $startData = request("startDate");
  498. $endDate = request("endDate");
  499. $owner = request("owner");
  500. if (!$startData)$this->error("非法参数");
  501. DB::beginTransaction();
  502. try {
  503. $details = OwnerFeeDetail::query()->where("worked_at",">=",$startData." 00:00:00");
  504. if ($endDate)$details->where("worked_at","<=",$endDate." 23:59:59");
  505. if (count($owner)>0)$details->whereIn("owner_id",$owner);
  506. $fee = OwnerFeeExpress::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. $feeQuery = OwnerFeeOperation::query()->select("id")->where("worked_at",">=",$startData);
  511. if ($endDate)$feeQuery->where("worked_at","<=",$endDate);
  512. if (count($owner)>0)$feeQuery->whereIn("owner_id",$owner);
  513. OwnerFeeOperationDetail::query()->whereIn("owner_fee_operation_id",$feeQuery)->delete();
  514. $feeQuery->delete();
  515. $fee = OwnerFeeLogistic::query()->where("created_at",">=",$startData." 00:00:00");
  516. if ($endDate)$fee->where("created_at","<=",$endDate." 23:59:59");
  517. if (count($owner)>0)$fee->whereIn("owner_id",$owner);
  518. $fee->delete();
  519. $details->get()->each(function ($detail){
  520. dispatch(new ResetInstantBill($detail));
  521. });
  522. DB::commit();
  523. $this->success();
  524. }catch (\Exception $e){
  525. DB::rollBack();
  526. $this->error("失败");
  527. }
  528. //$this->restoreResetInstantBillOrder($startData,$endDate);
  529. //$this->restoreResetInstantBillStore($startData,$endDate);
  530. }
  531. private function restoreResetInstantBillOrder($startData,$endDate)
  532. {
  533. $orders = Order::query()->where("wms_status","订单完成")->whereBetween("updated_at",["{$startData} 00:00:00","{$endDate} 23:59:59"])
  534. ->whereNotIn("id",OwnerFeeDetail::query()->select("outer_id")->where("outer_table_name","orders")
  535. ->whereBetween("worked_at",["{$startData} 00:00:00","{$endDate} 23:59:59"]))->get();
  536. foreach ($orders->chunk(50) as $or){
  537. dispatch(new OrderCreateInstantBill($or));
  538. }
  539. }
  540. private function restoreResetInstantBillStore($startData,$endDate)
  541. {
  542. $stores = Store::query()->where("status","已入库")->whereBetween("updated_at",["{$startData} 00:00:00","{$endDate} 23:59:59"])
  543. ->whereNotIn("id",OwnerFeeDetail::query()->select("outer_id")->where("outer_table_name","stores")
  544. ->whereBetween("worked_at",["{$startData} 00:00:00","{$endDate} 23:59:59"]))->get();
  545. foreach ($stores->chunk(50) as $st){
  546. dispatch(new StoreCreateInstantBill($st));
  547. }
  548. }
  549. public function resetBillConfirmation()
  550. {
  551. $month = request("month");
  552. if (!$month)$this->error("无日期");
  553. $owner = request("owner");
  554. if ($owner && !is_array($owner))$this->error("非法数据");
  555. $sql = <<<sql
  556. 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
  557. ((type = '发货' AND logistic_fee IS NOT NULL AND work_fee IS NOT NULL) OR (type <> '发货' AND work_fee IS NOT NULL))
  558. sql;
  559. if ($owner && count($owner)>0){
  560. $sql.=" AND owner_id IN (''";
  561. foreach ($owner as $o)$sql .=",'{$o}'";
  562. $sql.=")";
  563. }
  564. $sql .= " GROUP BY owner_id";
  565. $billDetails = DB::select(DB::raw($sql),[$month."%"]);
  566. $areas = OwnerAreaReport::query()->with(["ownerStoragePriceModel.timeUnit","ownerStoragePriceModel.taxRate"])
  567. ->where("counting_month","like",$month."%");
  568. if ($owner && count($owner)>0){
  569. $areas->whereIn("owner_id",$owner);
  570. }
  571. $areas = $areas->get();
  572. $map = [];
  573. $mapTax = [];
  574. foreach($areas as $area){
  575. if (!$area->ownerStoragePriceModel)continue;
  576. //信息提取模板
  577. $GLOBALS["FEE_INFO"] = [
  578. "counting_type" =>$area->ownerStoragePriceModel->counting_type,
  579. "using_type" =>$area->ownerStoragePriceModel->using_type,
  580. "fee_description" =>"",
  581. "total_fee" =>0,
  582. "tax_rate" =>0,
  583. ];
  584. $key = $area->owner_id."_".$area->counting_month;
  585. if (!isset($map[$key]))$map[$key] = $mapTax[$key] = 0;
  586. list($money,$taxFee) = app('OwnerStoragePriceModelService')
  587. ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
  588. $map[$key] += $money;
  589. $mapTax[$key] += $taxFee;
  590. $GLOBALS["FEE_INFO"]["total_fee"] = $money;
  591. OwnerFeeStorage::query()->where("area_id",$area->id)
  592. ->update($GLOBALS["FEE_INFO"]);
  593. }
  594. foreach (OwnerPriceSystem::query()->with(["timeUnit","taxRate"])
  595. ->select("owner_id","usage_fee")->whereNull("operation")
  596. ->orWhere("operation","")->get() as $system){
  597. list($systemFee[$system->owner_id],$systemTaxFee[$system->owner_id]) =
  598. app("OwnerAreaReportService")->systemFee($system,$month);
  599. }
  600. $chunks = array_chunk($billDetails,50);
  601. foreach ($chunks as $bills){
  602. foreach ($bills as $bill){
  603. $key = $bill->owner_id."_".$month;
  604. OwnerBillReport::query()->where("owner_id",$bill->owner_id)
  605. ->where("counting_month",$month."-01")
  606. ->update(["work_fee"=>$bill->work_fee,
  607. "logistic_fee"=>$bill->logistic_fee,
  608. "storage_fee"=>$map[$key] ?? 0,
  609. "other_fee" => $systemFee[$bill->owner_id] ?? null,
  610. "other_tax_fee" => $systemTaxFee[$bill->owner_id] ?? null,
  611. "storage_tax_fee" => $mapTax[$key] ?? 0]);
  612. }
  613. }
  614. $this->dispatch(new SettlementBillReportJob($month."-01",$owner));
  615. $this->success();
  616. }
  617. }