DeliveryAppointmentController.php 31 KB

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