DeliveryAppointmentController.php 16 KB

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