CustomerController.php 32 KB

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