DeliveryAppointmentController.php 30 KB

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