DeliveryAppointmentController.php 28 KB

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