DeliveryAppointmentController.php 28 KB

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