DeliveryAppointmentController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\CarType;
  4. use App\Components\AsyncResponse;
  5. use App\DeliveryAppointment;
  6. use App\DeliveryAppointmentCar;
  7. use App\Events\DeliveryAppointmentEvent;
  8. use App\Imports\AppointmentDetail;
  9. use App\Jobs\DeliveryAppointmentCheck;
  10. use App\Services\common\ExportService;
  11. use App\Warehouse;
  12. use Carbon\Carbon;
  13. use Carbon\CarbonPeriod;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Support\Facades\Auth;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Gate;
  18. use Illuminate\Support\Facades\Validator;
  19. class DeliveryAppointmentController extends Controller
  20. {
  21. use AsyncResponse;
  22. public function list()
  23. {
  24. if(!Gate::allows('入库管理-入库预约-预约管理')){ return view("exception.authority"); }
  25. $list = app("DeliveryAppointmentService")->query(request()->input())
  26. ->paginate(request("paginate") ?? 50);
  27. $warehouses = Warehouse::query()->select("id","name")->get();
  28. $owners = app("OwnerService")->getIntersectPermitting();
  29. return view("store.deliveryAppointment.list",compact("list","warehouses","owners"));
  30. }
  31. public function appointment()
  32. {
  33. if(!Gate::allows('入库管理-入库预约-预约')){ return view("exception.authority"); }
  34. $owners = app("OwnerService")->getIntersectPermitting();
  35. $cars = CarType::query()->get();
  36. $warehouses = Warehouse::query()->select("id","name")->get();
  37. return view("store.deliveryAppointment.appointment",compact("owners","cars","warehouses"));
  38. }
  39. public function import()
  40. {
  41. $this->importExcel(new AppointmentDetail());
  42. }
  43. /**
  44. * 获取产能
  45. *
  46. */
  47. public function getCapacity()
  48. {
  49. $this->gate("入库管理-入库预约-预约");
  50. $model = request("model");
  51. $errors = $this->appointmentValidator($model)->errors();
  52. if (count($errors)>0)$this->success(["errors"=>$errors]);
  53. /** @var \stdClass $warehouse */
  54. $warehouse = Warehouse::query()->find($model["warehouse_id"]);
  55. $tonne = $model["tonne"] ?? 0;
  56. $cubicMeter = $model["cubic_meter"] ?? 0;
  57. $amount = request("detail_amount");
  58. $need = app("DeliveryAppointmentService")->calculateCapacity($tonne,$cubicMeter,$amount,$warehouse->reduced_production_capacity_coefficient);//所需产能
  59. $start = Carbon::today();
  60. $end = Carbon::today()->addDays(6);
  61. $map = [];
  62. DeliveryAppointment::query()->selectRaw("appointment_date,date_period,SUM(capacity) AS capacity")
  63. ->whereBetween("appointment_date",[$start->toDateString(),$end->toDateString()])
  64. ->whereIn("status",[0,2])
  65. ->where("warehouse_id",$warehouse->id)
  66. ->groupBy(["appointment_date","date_period"])->get()
  67. ->each(function ($appointment)use(&$map){
  68. $map[$appointment->appointment_date."-".$appointment->date_period] = $appointment->capacity;
  69. });
  70. $list = [];
  71. $capacity = $warehouse->production_capacity;
  72. foreach (CarbonPeriod::create($start,$end) as $date){
  73. /** @var $date Carbon */
  74. $date = $date->format("Y-m-d");
  75. $periods = [];
  76. if ($date==date("Y-m-d")){
  77. $hour = date("H");
  78. foreach (DeliveryAppointment::PERIOD as $key=>$period){
  79. $period = explode("-",$period);
  80. $periodArr = ["time"=>$period[0].":00 - ".$period[1].":00","index"=>$key,"isAvailable"=>false];
  81. if ($hour<$period[1]-1){
  82. $total = $capacity*DeliveryAppointment::HOUR[$key];//仓库该时段产能总量
  83. $used = $map[$date."-".$key] ?? 0; //已使用产能
  84. $available = $total-$used; //可用产能
  85. if ($available > $need)$periodArr["isAvailable"] = true;
  86. }
  87. $periods[] = $periodArr;
  88. }
  89. }else{
  90. foreach (DeliveryAppointment::PERIOD as $key=>$period){
  91. $period = explode("-",$period);
  92. $period = $period[0].":00 - ".$period[1].":00";
  93. $periodArr = ["time"=>$period,"index"=>$key,"isAvailable"=>false];
  94. $total = $capacity*DeliveryAppointment::HOUR[$key];//仓库该时段产能总量
  95. $used = $map[$date."-".$key] ?? 0; //已使用产能
  96. $available = $total-$used; //可用产能
  97. if ($available > $need)$periodArr["isAvailable"] = true;
  98. $periods[] = $periodArr;
  99. }
  100. }
  101. $list[] = ["date"=>$date,"period"=>$periods];
  102. }
  103. $this->success($list);
  104. }
  105. /**
  106. * 确定预约
  107. */
  108. public function submitAppointment()
  109. {
  110. $this->gate("入库管理-入库预约-预约");
  111. $model = request("model");
  112. $selectDate = request("date");
  113. $details = request("details");
  114. $errors = $this->appointmentValidator($model)->errors();
  115. if (count($errors)>0)$this->success(["errors"=>$errors]);
  116. $errors = Validator::make($selectDate,[
  117. "date" => ["required","date","after:today"],
  118. "time" => ["required","integer"],
  119. ])->errors();
  120. if (count($errors)>0)$this->error("未选定预约日期");
  121. DB::transaction(function ()use($model,$selectDate,$details,&$appointment){
  122. $result = DeliveryAppointment::query()->selectRaw("appointment_date,date_period,SUM(capacity) AS capacity")
  123. ->where("appointment_date",$selectDate["date"])
  124. ->where("date_period",$selectDate["time"])
  125. ->where("warehouse_id",$model["warehouse_id"])
  126. ->where("status",0)
  127. ->groupBy(["appointment_date","date_period"])
  128. ->lockForUpdate()->first();
  129. /** @var \stdClass $warehouse */
  130. $warehouse = Warehouse::query()->find($model["warehouse_id"]);
  131. $need = app("DeliveryAppointmentService")->
  132. calculateCapacity($model["tonne"] ?? 0,$model["cubic_meter"] ?? 0,count($details),
  133. $warehouse->reduced_production_capacity_coefficient);
  134. if ($result){
  135. $total = $warehouse->production_capacity*DeliveryAppointment::HOUR[$selectDate["time"]];
  136. $available = $total-$result->capacity;
  137. if ($available < $need)$this->success(["isFail"=>true]);
  138. }
  139. /** @var \stdClass $appointment */
  140. $appointment = DeliveryAppointment::query()->create([
  141. "user_id" => Auth::id(),
  142. "owner_id" => $model["owner_id"],
  143. "procurement_number" => $model["procurement_number"] ?? null,
  144. "asn_number" => $model["asn_number"] ?? null,
  145. "warehouse_id" => $model["warehouse_id"],
  146. "tonne" => $model["tonne"] ?? 0,
  147. "cubic_meter" => $model["cubic_meter"] ?? 0,
  148. "box_amount" => $model["box_amount"] ?? 0,
  149. "capacity" => $need,
  150. "appointment_date" => $selectDate["date"],
  151. "date_period" => $selectDate["time"],
  152. ]);
  153. if ($details)app("DeliveryAppointmentService")->insertDetails($appointment,$details);
  154. $insert = [];
  155. foreach ($model["cars"] as $index=>$car){
  156. $rand = mt_rand(0,9);
  157. $len = strlen($appointment->id);
  158. $ten = $len < 2 ? "0" : substr($appointment->id,$len-2,1);
  159. $one = substr($appointment->id,$len-1,1);
  160. //唯一码 随机数+十位+当前下标+个位+日期
  161. $number = $rand.$ten.$index.$one.date("d");
  162. $insert[] = [
  163. "delivery_appointment_id" => $appointment->id,
  164. "license_plate_number" => $car["license_plate_number"],
  165. "car_id" => $car["car_id"] ?? null,
  166. "driver_name" => $car["driver_name"] ?? null,
  167. "driver_phone" => $car["driver_phone"] ?? null,
  168. "appointment_number" => $number,
  169. ];
  170. }
  171. DeliveryAppointmentCar::query()->insert($insert);
  172. });
  173. dispatch(new DeliveryAppointmentCheck($appointment->id))->delay(Carbon::parse($appointment->appointment_date." ".(explode("-",DeliveryAppointment::PERIOD[$appointment->date_period])[1]).":00:01"));
  174. //md5加密在密文第五位后插入
  175. $md5 = substr_replace(md5(date("m-d")),$appointment->id,5,0);
  176. $this->success(["key"=>$md5]);
  177. }
  178. private function appointmentValidator(array $model)
  179. {
  180. return Validator::make($model,[
  181. "owner_id" => ["required","integer"],
  182. "warehouse_id" => ["required","integer"],
  183. "tonne" => ["required_without:cubic_meter","numeric"],
  184. "cubic_meter" => ["required_without:tonne","numeric"],
  185. "box_amount" => ["nullable","integer"],
  186. "cars.*.license_plate_number" => ["required","size:7"],
  187. "cars.*.car_id" => ["nullable","integer"],
  188. "cars.*.driver_phone" => ["nullable"],
  189. "cars.*.driver_name" => ["nullable"],
  190. ],[
  191. 'required'=>':attribute 不应为空',
  192. 'integer'=>':attribute 应为数值',
  193. 'required_without'=>':attribute 不应为空',
  194. 'numeric'=>':attribute 必须为数字',
  195. 'size'=>':attribute 非法',
  196. ],[
  197. 'owner_id'=>'货主',
  198. 'warehouse_id'=>'仓库',
  199. 'tonne'=>'吨',
  200. 'cubic_meter'=>'立方',
  201. 'cars.*.license_plate_number'=>'车牌号',
  202. 'cars.*.car_id'=>'车型',
  203. 'cars.*.driver_phone'=>'司机电话',
  204. 'cars.*.driver_name'=>'司机姓名',
  205. ]);
  206. }
  207. /**
  208. * 根据key取id 鉴权数据
  209. */
  210. public function showAppointmentInfo()
  211. {
  212. if(!Gate::allows('入库管理-入库预约-预约')){ return view("exception.authority"); }
  213. $key = request("k");
  214. $len = strlen($key);
  215. $id = substr($key,5,$len-32);
  216. $md5 = substr($key,0,5).substr($key,5+$len-32);
  217. if ($md5!==md5(date("m-d")))return view("exception.404");
  218. /** @var \stdClass $appointment */
  219. $appointment = DeliveryAppointment::query()->with("cars")->find($id);
  220. if (!$appointment || $appointment->user_id != Auth::id())return view("exception.404");
  221. return view("store.deliveryAppointment.success",compact("appointment"));
  222. }
  223. /**
  224. * 取消预约
  225. */
  226. public function cancel()
  227. {
  228. $this->gate("入库管理-入库预约-预约");
  229. $id = request("id");
  230. if (!$id)$this->error("非法参数");
  231. DeliveryAppointment::query()->where("status",0)->where("id",$id)->update(["status"=>1]);
  232. $this->success(1);
  233. }
  234. /**
  235. * 导出
  236. */
  237. public function export()
  238. {
  239. if(!Gate::allows('入库管理-入库预约-预约管理')){ return view("exception.authority"); }
  240. if (request("checkAllSign")){
  241. $params = request()->input();
  242. unset($params["checkAllSign"]);
  243. $query = app("DeliveryAppointmentService")->query($params);
  244. }else $query = app("DeliveryAppointmentService")->query(["id"=>request("id")]);
  245. /** @var Builder $query */
  246. $list = $query->with(["owner","warehouse"])->get();
  247. $row = ["状态","货主","预约时间","仓库","预约号","车牌号","车型",
  248. "司机姓名","司机电话","吨","立方","箱数","采购单号","ASN单号","商品名称","条码","数量","创建时间"];
  249. foreach ($list as &$data){
  250. $appointment = "";
  251. $number = "";
  252. $carType = "";
  253. $driverName = "";
  254. $driverPhone = "";
  255. $commodityName = "";
  256. $commodityCode = "";
  257. $amount = "";
  258. foreach ($data->cars as $car){
  259. $appointment .= $car->appointment_number."\r\n";
  260. $number .= $car->license_plate_number."\r\n";
  261. $carType .= ($car->car->name ?? '')."\r\n";
  262. $driverName .= ($car->driver_name ?? '')."\r\n";
  263. $driverPhone .= ($car->driver_phone ?? '')."\r\n";
  264. }
  265. foreach ($data->details as $detail){
  266. $commodityName .= ($detail->commodity->name ?? $detail->name)."\r\n";
  267. $commodityCode .= ($detail->commodity->barcodes->code ?? $detail->bar_code)."\r\n";
  268. $amount .= $detail->amount."\r\n";
  269. }
  270. $data = [
  271. DeliveryAppointment::STATUS[$data->status],
  272. $data->owner->name ?? '',
  273. $data->appointment_date,
  274. $data->warehouse->name ?? '',
  275. $appointment,
  276. $number,
  277. $carType,
  278. $driverName,
  279. $driverPhone,
  280. $data->tonne,
  281. $data->cubic_meter,
  282. $data->box_amount,
  283. $data->procurement_number,
  284. $data->asn_number,
  285. $commodityName,
  286. $commodityCode,
  287. $amount,
  288. $data->created_at
  289. ];
  290. }
  291. return app(ExportService::class)->json($row,$list,"预约记录");
  292. }
  293. private function carList($period,$date,$warehouse)
  294. {
  295. $list = [];
  296. DeliveryAppointmentCar::query()->with(["deliveryAppointment"=>function($query){
  297. /** @var Builder $query */
  298. $query->withCount("cars");
  299. }])->whereHas("deliveryAppointment",function ($query)use($period,$warehouse,$date){
  300. /** @var Builder $query */
  301. $query->where("appointment_date",$date)
  302. ->where("warehouse_id",$warehouse)->whereIn("status",[0,2]);
  303. })->where(function ($query)use($period){
  304. /** @var Builder $query */
  305. $query->where("status",1)->orWhereHas("deliveryAppointment",function (Builder $query)use($period){
  306. $query->where("date_period",">=",$period);
  307. });
  308. })->orderByRaw("(CASE WHEN status=0 THEN 2 WHEN status=2 THEN 3 END),IF(ISNULL(delivery_time),1,0),delivery_time")
  309. ->limit(10)->get()->each(function ($car)use(&$list){
  310. //$diff = $car->delivery_time ? (strtotime($car->delivery_time)+1799)-time() : 0;
  311. $count = $car->deliveryAppointment->cars_count ?? 0;
  312. $list[] = [
  313. "id" => $car->id,
  314. "license_plate_number" => $car->license_plate_number,
  315. "driver_name" => $car->driver_name,
  316. "driver_phone" => $car->driver_phone,
  317. "status" => $car->status,
  318. "cubic_meter" => isset($car->deliveryAppointment->cubic_meter) && $car->deliveryAppointment->cubic_meter>0 ? ($count>1 ? $car->deliveryAppointment->cubic_meter."/".$count : $car->deliveryAppointment->cubic_meter) : "",
  319. "tonne" => isset($car->deliveryAppointment->tonne) && $car->deliveryAppointment->tonne>0 ? ($count>1 ? $car->deliveryAppointment->tonne."/".$count : $car->deliveryAppointment->tonne) : "",
  320. //"diff" => $diff>0 ? $diff*1000 : 0,
  321. ];
  322. });
  323. return $list;
  324. }
  325. /**
  326. * 获取展览数据
  327. */
  328. public function getExhibitionList()
  329. {
  330. $this->gate("入库管理-入库预约-入库区终端");
  331. $hour = date("H");
  332. $warehouse = request("warehouse");
  333. $index = null;
  334. foreach (DeliveryAppointment::PERIOD as $key=>$period){
  335. $arr = explode("-",$period);
  336. if (count($arr)!=2)continue;
  337. if ($hour<$arr[1]){
  338. $index = $key;
  339. break;
  340. }
  341. }
  342. if ($index===null)$this->success();
  343. $list = $this->carList($index,date("Y-m-d"),$warehouse);
  344. $counts = DeliveryAppointmentCar::query()->whereHas("deliveryAppointment",function (Builder $query)use($index,$warehouse){
  345. $query->where("appointment_date",date("Y-m-d"))
  346. ->where("warehouse_id",$warehouse)->whereIn("status",[0,2]);
  347. })->selectRaw("status, COUNT(1) AS c")->groupByRaw("status")->get();
  348. $success = 0;
  349. $work = 0;
  350. $notReached = 0;
  351. if ($counts)foreach ($counts as $c){
  352. switch ($c->status){
  353. case 0:
  354. $notReached = $c->c;
  355. break;
  356. case 1:
  357. $work = $c->c;
  358. break;
  359. case 2:
  360. $success = $c->c;
  361. break;
  362. }
  363. }
  364. $result = ["list"=>$list,"success"=>$success,"work"=>$work,"notReached"=>$notReached,"nextDay"=>$this->carList(0,date("Y-m-d",strtotime("+1 day")),$warehouse)];
  365. $nextTime = DeliveryAppointment::PERIOD[$index+1] ?? null;
  366. if ($nextTime){
  367. $nextTime = explode("-",$nextTime)[0];
  368. $timestamp = strtotime(date("Y-m-d")." ".$nextTime.":00:00");
  369. $result["refresh"] = (($timestamp-time())*1000) ?? 1000;
  370. }
  371. $this->success($result);
  372. }
  373. public function getKey()
  374. {
  375. $this->success(app("DeliveryAppointmentService")->getKey());
  376. }
  377. /**
  378. * 错误信息
  379. *
  380. * @return string
  381. */
  382. public function errMsg()
  383. {
  384. return <<<html
  385. <div style='font-weight: bold;color: red;margin: 500px auto;text-align: center;'>
  386. <span style='font-size: 200px;'>&times;</span><br>
  387. <span style='font-size: 50px'>二维码已过期,请重新扫描!</span><br><h1 style="color: #1b1e21;">如果多次扫描失败,请联系管理人员检查!</h1>
  388. </div>"
  389. html;
  390. }
  391. /**
  392. * 检查key有效性
  393. * 21-4-2 切换永久二维码 取消时段校验
  394. *
  395. * @param string $key
  396. * @param int $offset
  397. *
  398. * @return bool
  399. */
  400. private function check($key,$offset):bool
  401. {
  402. if (!$key)return false;
  403. $key = base64_decode($key);
  404. $ch = app("DeliveryAppointmentService")->getKey();
  405. $len = strlen($ch);
  406. if (substr($key,0,$len)!=$ch)return false;
  407. /*$timeLen = strlen($key)-$len;
  408. $time = substr($key,$len)+$offset;
  409. $thisTime = (integer)substr(time(),$timeLen*-1);
  410. if ($thisTime>$time)return false;*/
  411. return true;
  412. }
  413. /**
  414. * 进入预约界面填写预约码
  415. */
  416. public function delivery()
  417. {
  418. if (!$this->check(request("k"),65))return $this->errMsg();
  419. return view("store.deliveryAppointment.delivery",["k"=>request("k")]);
  420. }
  421. /**
  422. * 验证预约码
  423. *
  424. */
  425. public function checkAppointment()
  426. {
  427. if (!$this->check(request("k"),180))return ["status"=>406];
  428. $number = request("number");
  429. if (!$number)return ["status"=>417];
  430. $period = app("DeliveryAppointmentService")->getPeriod();
  431. if ($period===false)return ["status"=>416]; //非法时段扫码
  432. $car = DeliveryAppointmentCar::query()->whereNull("delivery_time")->where("status",0)
  433. ->where("appointment_number",$number)->whereHas("deliveryAppointment",function (Builder $query)use($period){
  434. $query->where("appointment_date",date("Y-m-d"))
  435. ->where("date_period",$period)->where("status",0);
  436. })->first();
  437. if (!$car)return ["status"=>417];
  438. $car->update(["delivery_time"=>date("Y-m-d H:i:s"),"status"=>1]);
  439. /** @var DeliveryAppointmentCar $car */
  440. event(new DeliveryAppointmentEvent($car));
  441. return ["status"=>200,"k"=>$car->delivery_appointment_id];
  442. }
  443. public function successMsg()
  444. {
  445. if (!request("k"))return view("exception.404");
  446. /** @var \stdClass $appointment */
  447. $appointment = DeliveryAppointment::query()->with(["cars"=>function($query){
  448. /** @var Builder $query */
  449. $query->whereNull("delivery_time");
  450. }])->find(request("k"));
  451. return view("store.deliveryAppointment.deliverySuccess",["cars"=>$appointment->cars]);
  452. }
  453. /**
  454. * 卸货完成
  455. */
  456. public function unloading()
  457. {
  458. if (!request("id"))$this->error("非法参数");
  459. /** @var DeliveryAppointmentCar|\stdClass $car */
  460. $car = DeliveryAppointmentCar::query()->find(request("id"));
  461. if (!$car || !$car->deliveryAppointment)$this->error("单据不存在");
  462. $car->update(["status"=>2]);
  463. app("DeliveryAppointmentService")->checkFull($car->delivery_appointment_id);
  464. event(new DeliveryAppointmentEvent($car));
  465. $this->success();
  466. }
  467. /**
  468. * 产能维护
  469. * */
  470. public function capacityMaintenance()
  471. {
  472. if(!Gate::allows('入库管理-入库预约-产能维护')){ return view("exception.authority"); }
  473. $warehouses = Warehouse::query()->select("name","id","production_capacity","reduced_production_capacity_coefficient")->get();
  474. return view("store.deliveryAppointment.capacityMaintenance",compact("warehouses"));
  475. }
  476. /**
  477. * 修改产能
  478. */
  479. public function updateCapacity()
  480. {
  481. $this->gate("入库管理-入库预约-产能维护");
  482. $id = request("id");
  483. $capacity = request("production_capacity");
  484. Warehouse::query()->where("id",$id)->update(["production_capacity"=>$capacity]);
  485. $this->success();
  486. }
  487. /**
  488. * 入库区终端界面
  489. */
  490. public function exhibition()
  491. {
  492. if(!Gate::allows('入库管理-入库预约-入库区终端')){ return view("exception.authority"); }
  493. if (!request("warehouse"))$warehouses = Warehouse::query()->select("name","id")->get();
  494. return view("store.deliveryAppointment.exhibition",["warehouses"=>$warehouses??[],"id"=>request("warehouse")]);
  495. }
  496. }