DeliveryAppointmentController.php 32 KB

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