DeliveryAppointmentController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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\Services\common\ExportService;
  10. use App\Warehouse;
  11. use Carbon\Carbon;
  12. use Carbon\CarbonPeriod;
  13. use Illuminate\Database\Eloquent\Builder;
  14. use Illuminate\Database\Eloquent\Model;
  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"],
  150. "driver_name" => $car["driver_name"],
  151. "driver_phone" => $car["driver_phone"],
  152. "appointment_number" => $number,
  153. ];
  154. }
  155. DeliveryAppointmentCar::query()->insert($insert);
  156. });
  157. //md5加密在密文第五位后插入
  158. $md5 = substr_replace(md5(date("m-d")),$appointment->id,5,0);
  159. $this->success(["key"=>$md5]);
  160. }
  161. private function appointmentValidator(array $model)
  162. {
  163. return Validator::make($model,[
  164. "owner_id" => ["required","integer"],
  165. "warehouse_id" => ["required","integer"],
  166. "tonne" => ["required_without:cubic_meter","numeric"],
  167. "cubic_meter" => ["required_without:tonne","numeric"],
  168. "box_amount" => ["nullable","integer"],
  169. "cars.*.license_plate_number" => ["required","size:7"],
  170. "cars.*.car_id" => ["nullable","integer"],
  171. "cars.*.driver_phone" => ["nullable"],
  172. "cars.*.driver_name" => ["nullable"],
  173. ],[
  174. 'required'=>':attribute 不应为空',
  175. 'integer'=>':attribute 应为数值',
  176. 'required_without'=>':attribute 不应为空',
  177. 'numeric'=>':attribute 必须为数字',
  178. 'size'=>':attribute 非法',
  179. ],[
  180. 'owner_id'=>'货主',
  181. 'warehouse_id'=>'仓库',
  182. 'tonne'=>'吨',
  183. 'cubic_meter'=>'立方',
  184. 'cars.*.license_plate_number'=>'车牌号',
  185. 'cars.*.car_id'=>'车型',
  186. 'cars.*.driver_phone'=>'司机电话',
  187. 'cars.*.driver_name'=>'司机姓名',
  188. ]);
  189. }
  190. /**
  191. * 根据key取id 鉴权数据
  192. */
  193. public function showAppointmentInfo()
  194. {
  195. if(!Gate::allows('入库管理-客户预约-预约')){ return view("exception.authority"); }
  196. $key = request("k");
  197. $len = strlen($key);
  198. $id = substr($key,5,$len-32);
  199. $md5 = substr($key,0,5).substr($key,5+$len-32);
  200. if ($md5!==md5(date("m-d")))return view("exception.404");
  201. /** @var \stdClass $appointment */
  202. $appointment = DeliveryAppointment::query()->with("cars")->find($id);
  203. if (!$appointment || $appointment->user_id != Auth::id())return view("exception.404");
  204. return view("store.deliveryAppointment.success",compact("appointment"));
  205. }
  206. /**
  207. * 取消预约
  208. */
  209. public function cancel()
  210. {
  211. $this->gate("入库管理-客户预约-预约");
  212. $id = request("id");
  213. if (!$id)$this->error("非法参数");
  214. DeliveryAppointment::query()->where("status",0)->where("id",$id)->update(["status"=>1]);
  215. $this->success(1);
  216. }
  217. /**
  218. * 导出
  219. */
  220. public function export()
  221. {
  222. if(!Gate::allows('入库管理-客户预约-预约管理')){ return view("exception.authority"); }
  223. if (request("checkAllSign")){
  224. $params = request()->input();
  225. unset($params["checkAllSign"]);
  226. $query = app("DeliveryAppointmentService")->query($params);
  227. }else $query = app("DeliveryAppointmentService")->query(["id"=>request("id")]);
  228. /** @var Builder $query */
  229. $list = $query->with(["owner","warehouse"])->get();
  230. $row = ["状态","货主","预约时间","仓库","预约号","车牌号","车型",
  231. "司机姓名","司机电话","吨","立方","箱数","采购单号","ASN单号","商品名称","条码","数量","创建时间"];
  232. foreach ($list as &$data){
  233. $appointment = "";
  234. $number = "";
  235. $carType = "";
  236. $driverName = "";
  237. $driverPhone = "";
  238. $commodityName = "";
  239. $commodityCode = "";
  240. $amount = "";
  241. foreach ($data->cars as $car){
  242. $appointment .= $car->appointment_number."\r\n";
  243. $number .= $car->license_plate_number."\r\n";
  244. $carType .= ($car->car->name ?? '')."\r\n";
  245. $driverName .= ($car->driver_name ?? '')."\r\n";
  246. $driverPhone .= ($car->driver_phone ?? '')."\r\n";
  247. }
  248. foreach ($data->details as $detail){
  249. $commodityName .= ($detail->commodity->name ?? $detail->name)."\r\n";
  250. $commodityCode .= ($detail->commodity->barcodes->code ?? $detail->bar_code)."\r\n";
  251. $amount .= $detail->amount."\r\n";
  252. }
  253. $data = [
  254. DeliveryAppointment::STATUS[$data->status],
  255. $data->owner->name ?? '',
  256. $data->appointment_date,
  257. $data->warehouse->name ?? '',
  258. $appointment,
  259. $number,
  260. $carType,
  261. $driverName,
  262. $driverPhone,
  263. $data->tonne,
  264. $data->cubic_meter,
  265. $data->box_amount,
  266. $data->procurement_number,
  267. $data->asn_number,
  268. $commodityName,
  269. $commodityCode,
  270. $amount,
  271. $data->created_at
  272. ];
  273. }
  274. return app(ExportService::class)->json($row,$list,"预约记录");
  275. }
  276. /**
  277. * 获取展览数据
  278. */
  279. public function getExhibitionList()
  280. {
  281. $this->gate("入库管理-客户预约-预约管理");
  282. $list = [];
  283. $hour = date("H");
  284. $index = null;
  285. foreach (DeliveryAppointment::PERIOD as $key=>$period){
  286. $arr = explode("-",$period);
  287. if (count($arr)!=2)continue;
  288. if ($hour<$arr[1]){
  289. $index = $key;
  290. break;
  291. }
  292. }
  293. if ($index===null)$this->success([]);
  294. DeliveryAppointmentCar::query()->whereHas("deliveryAppointment",function (Builder $query)use($index){
  295. $query->where("appointment_date",date("Y-m-d"))->whereIn("status",[0,2]);
  296. })->where(function ($query)use($index){
  297. /** @var Builder $query */
  298. $query->where("status",1)->orWhereHas("deliveryAppointment",function (Builder $query)use($index){
  299. $query->where("date_period",">=",$index);
  300. });
  301. })->orderByRaw("(CASE WHEN status=0 THEN 2 WHEN status=2 THEN 3 END),IF(ISNULL(delivery_time),1,0),delivery_time")
  302. ->limit(10)->get()->each(function ($car)use(&$list){
  303. //$diff = $car->delivery_time ? (strtotime($car->delivery_time)+1799)-time() : 0;
  304. $list[] = [
  305. "id" => $car->id,
  306. "license_plate_number" => $car->license_plate_number,
  307. "driver_name" => $car->driver_name,
  308. "driver_phone" => $car->driver_phone,
  309. "status" => $car->status,
  310. //"diff" => $diff>0 ? $diff*1000 : 0,
  311. ];
  312. });
  313. $counts = DeliveryAppointmentCar::query()->whereHas("deliveryAppointment",function (Builder $query)use($index){
  314. $query->where("appointment_date",date("Y-m-d"))->whereIn("status",[0,2]);
  315. })->selectRaw("status, COUNT(1) AS c")->groupByRaw("status")->get();
  316. $success = 0;
  317. $work = 0;
  318. $notReached = 0;
  319. if ($counts)foreach ($counts as $c){
  320. switch ($c->status){
  321. case 0:
  322. $notReached = $c->c;
  323. break;
  324. case 1:
  325. $work = $c->c;
  326. break;
  327. case 2:
  328. $success = $c->c;
  329. break;
  330. }
  331. }
  332. $result = ["list"=>$list,"success"=>$success,"work"=>$work,"notReached"=>$notReached];
  333. $nextTime = DeliveryAppointment::PERIOD[$index+1] ?? null;
  334. if ($nextTime){
  335. $nextTime = explode("-",$nextTime)[0];
  336. $timestamp = strtotime(date("Y-m-d")." ".$nextTime.":00:00");
  337. $result["refresh"] = (($timestamp-time())*1000) ?? 1000;
  338. }
  339. $this->success($result);
  340. }
  341. public function getKey()
  342. {
  343. $this->success(app("DeliveryAppointmentService")->getKey());
  344. }
  345. /**
  346. * 错误信息
  347. *
  348. * @return string
  349. */
  350. public function errMsg()
  351. {
  352. return <<<html
  353. <div style='font-weight: bold;color: red;margin: 500px auto;text-align: center;'>
  354. <span style='font-size: 200px;'>&times;</span><br>
  355. <span style='font-size: 50px'>二维码已过期,请重新扫描!</span><br><h1 style="color: #1b1e21;">如果多次扫描失败,请联系管理人员检查!</h1>
  356. </div>"
  357. html;
  358. }
  359. /**
  360. * 检查key有效性
  361. * 21-4-2 切换永久二维码 取消时段校验
  362. *
  363. * @param string $key
  364. * @param int $offset
  365. *
  366. * @return bool
  367. */
  368. private function check($key,$offset):bool
  369. {
  370. if (!$key)return false;
  371. $key = base64_decode($key);
  372. $ch = app("DeliveryAppointmentService")->getKey();
  373. $len = strlen($ch);
  374. if (substr($key,0,$len)!=$ch)return false;
  375. /*$timeLen = strlen($key)-$len;
  376. $time = substr($key,$len)+$offset;
  377. $thisTime = (integer)substr(time(),$timeLen*-1);
  378. if ($thisTime>$time)return false;*/
  379. return true;
  380. }
  381. /**
  382. * 进入预约界面填写预约码
  383. */
  384. public function delivery()
  385. {
  386. if (!$this->check(request("k"),65))return $this->errMsg();
  387. return view("store.deliveryAppointment.delivery",["k"=>request("k")]);
  388. }
  389. /**
  390. * 验证预约码
  391. *
  392. */
  393. public function checkAppointment()
  394. {
  395. if (!$this->check(request("k"),180))return ["status"=>406];
  396. $number = request("number");
  397. if (!$number)return ["status"=>417];
  398. $period = app("DeliveryAppointmentService")->getPeriod();
  399. if ($period===false)return ["status"=>416]; //非法时段扫码
  400. $car = DeliveryAppointmentCar::query()->whereNull("delivery_time")->where("status",0)
  401. ->where("appointment_number",$number)->whereHas("deliveryAppointment",function (Builder $query)use($period){
  402. $query->where("appointment_date",date("Y-m-d"))
  403. ->where("date_period",$period)->where("status",0);
  404. })->first();
  405. if (!$car)return ["status"=>417];
  406. $car->update(["delivery_time"=>date("Y-m-d H:i:s"),"status"=>1]);
  407. /** @var DeliveryAppointmentCar $car */
  408. event(new DeliveryAppointmentEvent($car));
  409. return ["status"=>200,"k"=>$car->delivery_appointment_id];
  410. }
  411. public function successMsg()
  412. {
  413. if (!request("k"))return view("exception.404");
  414. /** @var \stdClass $appointment */
  415. $appointment = DeliveryAppointment::query()->with(["cars"=>function($query){
  416. /** @var Builder $query */
  417. $query->whereNull("delivery_time");
  418. }])->find(request("k"));
  419. return view("store.deliveryAppointment.deliverySuccess",["cars"=>$appointment->cars]);
  420. }
  421. /**
  422. * 卸货完成
  423. */
  424. public function unloading()
  425. {
  426. if (!request("id"))$this->error("非法参数");
  427. /** @var DeliveryAppointmentCar|\stdClass $car */
  428. $car = DeliveryAppointmentCar::query()->find(request("id"));
  429. if (!$car || !$car->deliveryAppointment)$this->error("单据不存在");
  430. $car->update(["status"=>2]);
  431. app("DeliveryAppointmentService")->checkFull($car->delivery_appointment_id);
  432. event(new DeliveryAppointmentEvent($car));
  433. $this->success();
  434. }
  435. }