DeliveryAppointmentController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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\Services\common\ExportService;
  10. use App\Warehouse;
  11. use Carbon\Carbon;
  12. use Carbon\CarbonPeriod;
  13. use Illuminate\Database\Eloquent\Builder;
  14. use Illuminate\Support\Facades\Auth;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Gate;
  17. use Illuminate\Support\Facades\Validator;
  18. class DeliveryAppointmentController extends Controller
  19. {
  20. use AsyncResponse;
  21. public function list()
  22. {
  23. if(!Gate::allows('入库管理-客户预约-预约管理')){ return view("exception.authority"); }
  24. $list = app("DeliveryAppointmentService")->query(request()->input())
  25. ->paginate(request("paginate") ?? 50);
  26. $warehouses = Warehouse::query()->select("id","name")->get();
  27. $owners = app("OwnerService")->getIntersectPermitting();
  28. return view("store.deliveryAppointment.list",compact("list","warehouses","owners"));
  29. }
  30. public function appointment()
  31. {
  32. if(!Gate::allows('入库管理-客户预约-预约')){ return view("exception.authority"); }
  33. $owners = app("OwnerService")->getIntersectPermitting();
  34. $cars = CarType::query()->get();
  35. $warehouses = Warehouse::query()->select("id","name")->get();
  36. return view("store.deliveryAppointment.appointment",compact("owners","cars","warehouses"));
  37. }
  38. public function import()
  39. {
  40. $this->importExcel(new AppointmentDetail());
  41. }
  42. /**
  43. * 获取产能
  44. *
  45. */
  46. public function getCapacity()
  47. {
  48. $this->gate("入库管理-客户预约-预约");
  49. $model = request("model");
  50. $errors = $this->appointmentValidator($model)->errors();
  51. if (count($errors)>0)$this->success(["errors"=>$errors]);
  52. /** @var \stdClass $warehouse */
  53. $warehouse = Warehouse::query()->find($model["warehouse_id"]);
  54. $tonne = $model["tonne"] ?? 0;
  55. $cubicMeter = $model["cubic_meter"] ?? 0;
  56. $amount = request("detail_amount");
  57. $need = app("DeliveryAppointmentService")->calculateCapacity($tonne,$cubicMeter,$amount,$warehouse->reduced_production_capacity_coefficient);//所需产能
  58. $start = Carbon::tomorrow();
  59. $end = Carbon::today()->addDays(7);
  60. $map = [];
  61. DeliveryAppointment::query()->selectRaw("appointment_date,date_period,SUM(capacity) AS capacity")
  62. ->whereBetween("appointment_date",[$start->toDateString(),$end->toDateString()])
  63. ->where("status",0)
  64. ->where("warehouse_id",$warehouse->id)
  65. ->groupBy(["appointment_date","date_period"])->get()
  66. ->each(function ($appointment)use(&$map){
  67. $map[$appointment->appointment_date."-".$appointment->date_period] = $appointment->capacity;
  68. });
  69. $list = [];
  70. $capacity = $warehouse->production_capacity;
  71. foreach (CarbonPeriod::create($start,$end) as $date){
  72. /** @var $date Carbon */
  73. $date = $date->format("Y-m-d");
  74. $periods = [];
  75. foreach (DeliveryAppointment::PERIOD as $key=>$period){
  76. $total = $capacity*DeliveryAppointment::HOUR[$key];//仓库该时段产能总量
  77. $used = $map[$date."-".$key] ?? 0; //已使用产能
  78. $available = $total-$used; //可用产能
  79. $period = explode("-",$period);
  80. $period = $period[0].":00 - ".$period[1].":00";
  81. if ($available < $need)$periods[] = ["time"=>$period,"index"=>$key,"isAvailable"=>false];
  82. else $periods[] = ["time"=>$period,"index"=>$key,"isAvailable"=>true];
  83. }
  84. $list[] = ["date"=>$date,"period"=>$periods];
  85. }
  86. $this->success($list);
  87. }
  88. /**
  89. * 确定预约
  90. */
  91. public function submitAppointment()
  92. {
  93. $this->gate("入库管理-客户预约-预约");
  94. $model = request("model");
  95. $selectDate = request("date");
  96. $details = request("details");
  97. $errors = $this->appointmentValidator($model)->errors();
  98. if (count($errors)>0)$this->success(["errors"=>$errors]);
  99. $errors = Validator::make($selectDate,[
  100. "date" => ["required","date","after:today"],
  101. "time" => ["required","integer"],
  102. ])->errors();
  103. if (count($errors)>0)$this->error("未选定预约日期");
  104. DB::transaction(function ()use($model,$selectDate,$details,&$appointment){
  105. $result = DeliveryAppointment::query()->selectRaw("appointment_date,date_period,SUM(capacity) AS capacity")
  106. ->where("appointment_date",$selectDate["date"])
  107. ->where("date_period",$selectDate["time"])
  108. ->where("warehouse_id",$model["warehouse_id"])
  109. ->where("status",0)
  110. ->groupBy(["appointment_date","date_period"])
  111. ->lockForUpdate()->first();
  112. /** @var \stdClass $warehouse */
  113. $warehouse = Warehouse::query()->find($model["warehouse_id"]);
  114. $need = app("DeliveryAppointmentService")->
  115. calculateCapacity($model["tonne"] ?? 0,$model["cubic_meter"] ?? 0,count($details),
  116. $warehouse->reduced_production_capacity_coefficient);
  117. if ($result){
  118. $total = $warehouse->production_capacity*DeliveryAppointment::HOUR[$selectDate["time"]];
  119. $available = $total-$result->capacity;
  120. if ($available < $need)$this->success(["isFail"=>true]);
  121. }
  122. /** @var \stdClass $appointment */
  123. $appointment = DeliveryAppointment::query()->create([
  124. "user_id" => Auth::id(),
  125. "owner_id" => $model["owner_id"],
  126. "procurement_number" => $model["procurement_number"] ?? null,
  127. "asn_number" => $model["asn_number"] ?? null,
  128. "warehouse_id" => $model["warehouse_id"],
  129. "tonne" => $model["tonne"] ?? 0,
  130. "cubic_meter" => $model["cubic_meter"] ?? 0,
  131. "box_amount" => $model["box_amount"] ?? 0,
  132. "capacity" => $need,
  133. "appointment_date" => $selectDate["date"],
  134. "date_period" => $selectDate["time"],
  135. ]);
  136. if ($details)app("DeliveryAppointmentService")->insertDetails($appointment,$details);
  137. $insert = [];
  138. foreach ($model["cars"] as $index=>$car){
  139. $rand = mt_rand(0,9);
  140. $len = strlen($appointment->id);
  141. $ten = $len < 2 ? "0" : substr($appointment->id,$len-2,1);
  142. $one = substr($appointment->id,$len-1,1);
  143. //唯一码 随机数+十位+当前下标+个位+日期
  144. $number = $rand.$ten.$index.$one.date("d");
  145. $insert[] = [
  146. "delivery_appointment_id" => $appointment->id,
  147. "license_plate_number" => $car["license_plate_number"],
  148. "car_id" => $car["car_id"],
  149. "driver_name" => $car["driver_name"],
  150. "driver_phone" => $car["driver_phone"],
  151. "appointment_number" => $number,
  152. ];
  153. }
  154. DeliveryAppointmentCar::query()->insert($insert);
  155. });
  156. //md5加密在密文第五位后插入
  157. $md5 = substr_replace(md5(date("m-d")),$appointment->id,5,0);
  158. $this->success(["key"=>$md5]);
  159. }
  160. private function appointmentValidator(array $model)
  161. {
  162. return Validator::make($model,[
  163. "owner_id" => ["required","integer"],
  164. "warehouse_id" => ["required","integer"],
  165. "tonne" => ["required_without:cubic_meter","numeric"],
  166. "cubic_meter" => ["required_without:tonne","numeric"],
  167. "box_amount" => ["nullable","integer"],
  168. "cars.*.license_plate_number" => ["required","size:7"],
  169. "cars.*.car_id" => ["nullable","integer"],
  170. "cars.*.driver_phone" => ["nullable"],
  171. "cars.*.driver_name" => ["nullable"],
  172. ],[
  173. 'required'=>':attribute 不应为空',
  174. 'integer'=>':attribute 应为数值',
  175. 'required_without'=>':attribute 不应为空',
  176. 'numeric'=>':attribute 必须为数字',
  177. 'size'=>':attribute 非法',
  178. ],[
  179. 'owner_id'=>'货主',
  180. 'warehouse_id'=>'仓库',
  181. 'tonne'=>'吨',
  182. 'cubic_meter'=>'立方',
  183. 'cars.*.license_plate_number'=>'车牌号',
  184. 'cars.*.car_id'=>'车型',
  185. 'cars.*.driver_phone'=>'司机电话',
  186. 'cars.*.driver_name'=>'司机姓名',
  187. ]);
  188. }
  189. /**
  190. * 根据key取id 鉴权数据
  191. */
  192. public function showAppointmentInfo()
  193. {
  194. if(!Gate::allows('入库管理-客户预约-预约')){ return view("exception.authority"); }
  195. $key = request("k");
  196. $len = strlen($key);
  197. $id = substr($key,5,$len-32);
  198. $md5 = substr($key,0,5).substr($key,5+$len-32);
  199. if ($md5!==md5(date("m-d")))return view("exception.404");
  200. /** @var \stdClass $appointment */
  201. $appointment = DeliveryAppointment::query()->with("cars")->find($id);
  202. if (!$appointment || $appointment->user_id != Auth::id())return view("exception.404");
  203. return view("store.deliveryAppointment.success",compact("appointment"));
  204. }
  205. /**
  206. * 取消预约
  207. */
  208. public function cancel()
  209. {
  210. $this->gate("入库管理-客户预约-预约");
  211. $id = request("id");
  212. if (!$id)$this->error("非法参数");
  213. DeliveryAppointment::query()->where("status",0)->where("id",$id)->update(["status"=>1]);
  214. $this->success(1);
  215. }
  216. /**
  217. * 导出
  218. */
  219. public function export()
  220. {
  221. if(!Gate::allows('入库管理-客户预约-预约管理')){ return view("exception.authority"); }
  222. if (request("checkAllSign")){
  223. $params = request()->input();
  224. unset($params["checkAllSign"]);
  225. $query = app("DeliveryAppointmentService")->query($params);
  226. }else $query = app("DeliveryAppointmentService")->query(["id"=>request("id")]);
  227. /** @var Builder $query */
  228. $list = $query->with(["owner","warehouse"])->get();
  229. $row = ["状态","货主","预约时间","仓库","预约号","车牌号","车型",
  230. "司机姓名","司机电话","吨","立方","箱数","采购单号","ASN单号","商品名称","条码","数量","创建时间"];
  231. foreach ($list as &$data){
  232. $appointment = "";
  233. $number = "";
  234. $carType = "";
  235. $driverName = "";
  236. $driverPhone = "";
  237. $commodityName = "";
  238. $commodityCode = "";
  239. $amount = "";
  240. foreach ($data->cars as $car){
  241. $appointment .= $car->appointment_number."\r\n";
  242. $number .= $car->license_plate_number."\r\n";
  243. $carType .= ($car->car->name ?? '')."\r\n";
  244. $driverName .= ($car->driver_name ?? '')."\r\n";
  245. $driverPhone .= ($car->driver_phone ?? '')."\r\n";
  246. }
  247. foreach ($data->details as $detail){
  248. $commodityName .= ($detail->commodity->name ?? $detail->name)."\r\n";
  249. $commodityCode .= ($detail->commodity->barcodes->code ?? $detail->bar_code)."\r\n";
  250. $amount .= $detail->amount."\r\n";
  251. }
  252. $data = [
  253. DeliveryAppointment::STATUS[$data->status],
  254. $data->owner->name ?? '',
  255. $data->appointment_date,
  256. $data->warehouse->name ?? '',
  257. $appointment,
  258. $number,
  259. $carType,
  260. $driverName,
  261. $driverPhone,
  262. $data->tonne,
  263. $data->cubic_meter,
  264. $data->box_amount,
  265. $data->procurement_number,
  266. $data->asn_number,
  267. $commodityName,
  268. $commodityCode,
  269. $amount,
  270. $data->created_at
  271. ];
  272. }
  273. return app(ExportService::class)->json($row,$list,"预约记录");
  274. }
  275. /**
  276. * 获取展览数据
  277. */
  278. public function getExhibitionList()
  279. {
  280. $this->gate("入库管理-客户预约-预约管理");
  281. $list = [];
  282. $hour = date("H");
  283. $index = null;
  284. foreach (DeliveryAppointment::PERIOD as $key=>$period){
  285. $arr = explode("-",$period);
  286. if (count($arr)!=2)continue;
  287. if ($hour<$arr[1])$index = $key;
  288. }
  289. if ($index===null)$this->success([]);
  290. DeliveryAppointmentCar::query()->whereHas("deliveryAppointment",function (Builder $query)use($index){
  291. $query->where("appointment_date",date("Y-m-d"))->whereIn("status",[0,2])
  292. ->where("date_period",">=",$index);
  293. })->orderByDesc("id")->limit(10)->get()->each(function ($car)use(&$list){
  294. $diff = $car->delivery_time ? (strtotime($car->delivery_time)+1799)-time() : 0;
  295. $list[] = [
  296. "license_plate_number" => $car->license_plate_number,
  297. "driver_name" => $car->driver_name,
  298. "driver_phone" => $car->driver_phone,
  299. "diff" => $diff>0 ? $diff*1000 : 0,
  300. ];
  301. });
  302. $result = ["list"=>$list];
  303. $nextTime = DeliveryAppointment::PERIOD[$index+1] ?? null;
  304. if ($nextTime){
  305. $nextTime = explode("-",$nextTime)[0];
  306. $timestamp = strtotime(date("Y-m-d")." ".$nextTime.":00:00");
  307. $result["refresh"] = (($timestamp-time())*1000) ?? 1000;
  308. }
  309. $this->success($result);
  310. }
  311. public function getKey()
  312. {
  313. $this->success(app("DeliveryAppointmentService")->getKey());
  314. }
  315. /**
  316. * 错误信息
  317. *
  318. * @return string
  319. */
  320. public function errMsg()
  321. {
  322. return <<<html
  323. <div style='font-weight: bold;color: red;margin: 500px auto;text-align: center;'>
  324. <span style='font-size: 200px;'>&times;</span><br>
  325. <span style='font-size: 50px'>二维码已过期,请重新扫描!</span><br><h1 style="color: #1b1e21;">如果多次扫描失败,请联系管理人员检查!</h1>
  326. </div>"
  327. html;
  328. }
  329. /**
  330. * 检查key有效性
  331. *
  332. * @param string $key
  333. * @param int $offset
  334. *
  335. * @return bool
  336. */
  337. private function check($key,$offset):bool
  338. {
  339. if (!$key)return false;
  340. $key = base64_decode($key);
  341. $ch = app("DeliveryAppointmentService")->getKey();
  342. $len = strlen($ch);
  343. $timeLen = strlen($key)-$len;
  344. if (substr($key,0,$len)!=$ch)return false;
  345. $time = substr($key,$len)+$offset;
  346. $thisTime = (integer)substr(time(),$timeLen*-1);
  347. if ($thisTime>$time)return false;
  348. return true;
  349. }
  350. /**
  351. * 进入预约界面填写预约码
  352. */
  353. public function delivery()
  354. {
  355. if (!$this->check(request("k"),65))return $this->errMsg();
  356. return view("store.deliveryAppointment.delivery",["k"=>request("k")]);
  357. }
  358. /**
  359. * 验证预约码
  360. *
  361. */
  362. public function checkAppointment()
  363. {
  364. if (!$this->check(request("k"),180))return ["status"=>406];
  365. $number = request("number");
  366. if (!$number)return ["status"=>417];
  367. $period = app("DeliveryAppointmentService")->getPeriod();
  368. if ($period===false)return ["status"=>416]; //非法时段扫码
  369. $car = DeliveryAppointmentCar::query()->whereNull("delivery_time")
  370. ->where("appointment_number",$number)->whereHas("deliveryAppointment",function (Builder $query)use($period){
  371. $query->where("appointment_date",date("Y-m-d"))
  372. ->where("date_period",$period)->where("status",0);
  373. })->first();
  374. if (!$car)return ["status"=>417];
  375. $car->update(["delivery_time"=>date("Y-m-d H:i:s")]);
  376. /** @var DeliveryAppointmentCar $car */
  377. event(new DeliveryAppointmentEvent($car));
  378. app("DeliveryAppointmentService")->checkFull($car->delivery_appointment_id);
  379. return ["status"=>200,"k"=>$car->delivery_appointment_id];
  380. }
  381. public function successMsg()
  382. {
  383. if (!request("k"))return view("exception.404");
  384. /** @var \stdClass $appointment */
  385. $appointment = DeliveryAppointment::query()->with(["cars"=>function($query){
  386. /** @var Builder $query */
  387. $query->whereNull("delivery_time");
  388. }])->find(request("k"));
  389. return view("store.deliveryAppointment.deliverySuccess",["cars"=>$appointment->cars]);
  390. }
  391. }