DeliveryAppointmentController.php 20 KB

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