DeliveryAppointmentController.php 17 KB

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