WaybillController.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\CarType;
  4. use App\Components\AsyncResponse;
  5. use App\Owner;
  6. use App\Region;
  7. use App\Services\CarTypeService;
  8. use App\Services\LogisticService;
  9. use App\Services\LogService;
  10. use App\Services\OwnerService;
  11. use App\Services\UnitService;
  12. use App\Services\WaybillPayoffService;
  13. use App\Services\WaybillPriceModelService;
  14. use App\Services\WaybillService;
  15. use App\UploadFile;
  16. use App\WaybillAuditLog;
  17. use App\WaybillOnTop;
  18. use App\WaybillPriceModel;
  19. use App\Unit;
  20. use App\Waybill;
  21. use App\WaybillPayoff;
  22. use App\WaybillFinancialExcepted;
  23. use App\WaybillFinancialSnapshot;
  24. use Carbon\Carbon;
  25. use Illuminate\Database\Eloquent\Builder;
  26. use Illuminate\Database\Eloquent\Collection;
  27. use Illuminate\Database\Eloquent\Model;
  28. use Illuminate\Http\Request;
  29. use Illuminate\Support\Facades\Auth;
  30. use Illuminate\Support\Facades\DB;
  31. use Illuminate\Support\Facades\Gate;
  32. use Illuminate\Support\Facades\Storage;
  33. use Illuminate\Support\Facades\Validator;
  34. use Intervention\Image\Facades\Image;
  35. use Oursdreams\Export\Export;
  36. use Ramsey\Uuid\Uuid;
  37. class WaybillController extends Controller
  38. {
  39. use AsyncResponse;
  40. public function __construct()
  41. {
  42. app()->singleton('waybillService',WaybillService::class);
  43. }
  44. /**
  45. * @param Request $request
  46. * @param OwnerService $ownerService
  47. * @param LogisticService $logisticService
  48. * @return \Illuminate\View\View
  49. */
  50. public function index(Request $request,OwnerService $ownerService,LogisticService $logisticService)
  51. {
  52. if(!Gate::allows('运输管理-运单-查询')){ return view("exception.authority"); }
  53. $paginateParams = $request->input();
  54. $waybills=app('waybillService')->paginate($request->input());
  55. return view('transport.waybill.index', [
  56. 'waybills' => $waybills,
  57. 'logistics' => $logisticService->getSelection(["id","name"],"物流"),
  58. 'owners' => $ownerService->getIntersectPermitting(),
  59. "carTypes" => CarType::query()->get(),
  60. 'paginateParams'=>$paginateParams,
  61. 'uriType'=>$request->uriType??'']);
  62. }
  63. public function create(Request $request,OwnerService $ownerService)
  64. {
  65. if(!Gate::allows('运输管理-运单-录入')){ return redirect(url('denied')); }
  66. $type=$request->type ?? "";
  67. if ($type==='ZF')$type='直发车';
  68. if ($type==='ZX')$type='专线';
  69. if ($type==='DBWL')$type='德邦物流';
  70. return view('transport.waybill.create',['owners'=>$ownerService->getIntersectPermitting(),'type'=>$type]);
  71. }
  72. public function store(Request $request)
  73. {
  74. if(!Gate::allows('运输管理-运单-录入')){ return redirect(url('denied')); }
  75. $this->validatorWaybill($request,false)->validate();
  76. /** @var WaybillService */
  77. $waybill=app('waybillService')->store($request);
  78. return redirect('transport/waybill/index')->with('successTip','新运单“'.$waybill->waybill_number.'”录入成功');
  79. }
  80. public function edit($id,LogisticService $logisticService,CarTypeService $carTypeService,UnitService $unitService)
  81. {
  82. $waybill = app('waybillService')->find($id);
  83. if ($waybill->order_id){
  84. /** @var Waybill $waybill */
  85. $waybill->load("order.owner");
  86. $waybill->destination_city_id = app("RegionService")->getCity($waybill->order->city ?? '',$waybill->order->province ?? '');
  87. }else{
  88. /** @var Waybill $waybill */
  89. $waybill->load("owner");
  90. }
  91. if ($waybill->merge_owner)$waybill->merge_owner = implode(",",array_column(Owner::query()->select("name")->whereIn("id",explode(",",$waybill->merge_owner))->get()->toArray(),"name"));
  92. /** @var \stdClass $waybill */
  93. if (!$waybill)return view("exception.default",["code"=>"500","message"=>"数据已被删除或丢失"]);
  94. if ($waybill->deliver_at){
  95. $waybill->deliver_at_date=Carbon::parse($waybill->deliver_at)->format('Y-m-d');
  96. $waybill->deliver_at_time=Carbon::parse($waybill->deliver_at)->format('H:i:s');
  97. }
  98. $cities=app("RegionService")->getSelection(2);
  99. $units=$unitService->getSelection();
  100. $carTypes=$carTypeService->getSelection();
  101. $deliveryType = app('DeliveryTypeService')->getSelection();
  102. return view('transport.waybill.edit',['waybill'=>$waybill,'logistics'=>$logisticService->getSelection(["id","name","tag"],"物流"),'cities'=>$cities,'units'=>$units,'carTypes'=>$carTypes,
  103. 'deliveryTypes'=>$deliveryType,'orderTypes' =>collect(config('api_logistic.DB.prod.orderType')),'transportTypes' => collect(config('api_logistic.DB.prod.transportType'))
  104. ,'payTypes' => collect(config('api_logistic.DB.prod.payType')),'backSignBills' => collect(config('api_logistic.DB.prod.backSignBill')),'packageServices' => collect(config('api_logistic.DB.prod.packageService'))
  105. ]);
  106. }
  107. public function update(Request $request, $id,WaybillPriceModelService $waybillPriceModelService,
  108. LogisticService $logisticService,WaybillPayoffService $waybillPayoffService)
  109. {
  110. if(!Gate::allows('运输管理-运单-调度') && $request->type != '德邦物流'){ return view("exception.authority"); }
  111. if (!$request->warehouse_weight && $request->warehouse_weight_unit_id)$request->offsetUnset('warehouse_weight_unit_id');
  112. if (!$request->warehouse_weight_other && $request->warehouse_weight_unit_id_other)$request->offsetUnset('warehouse_weight_unit_id_other');
  113. if (!$request->carrier_weight && $request->carrier_weight_unit_id)$request->offsetUnset('carrier_weight_unit_id');
  114. if (!$request->carrier_weight_other && $request->carrier_weight_unit_id_other)$request->offsetUnset('carrier_weight_unit_id_other');
  115. if ($request->type == '德邦物流' && empty($request->carrier_bill)) $request->offsetSet('carrier_bill', 'dbwl');
  116. $this->validatorWaybillDispatch($request,$id)->validate();
  117. if ($request->carrier_bill == 'dbwl')$request->offsetSet('carrier_bill', '');
  118. $waybillPayoffParam = [];
  119. $waybillPayoffParam['total_receivable']=0;
  120. /** @var WaybillService */
  121. $waybill = app('waybillService')->find($id);
  122. $oldBill = $waybill->carrier_bill;
  123. DB::beginTransaction();
  124. try {
  125. $waybill = app('waybillService')->update($waybill, $request->input());
  126. if ($waybill->type=="直发车"){
  127. if ($waybill->charge)$waybillPayoffParam['total_receivable'] = ($waybill->charge);
  128. elseif ($waybill->collect_fee)$waybillPayoffParam['total_receivable'] = ($waybill->collect_fee);
  129. $waybillPayoffParam['total_expense'] = ($waybill->fee)+($waybill->other_fee)-($waybill->collect_fee);
  130. }else {
  131. $waybillPriceModel_id=$request->input('waybillPriceModel');
  132. if ($waybillPriceModel_id){
  133. $carrier_weight=$request->input('carrier_weight');
  134. $waybillPriceModel=$waybillPriceModelService->find($waybillPriceModel_id);
  135. $logistic=$logisticService->find($waybill->logistic_id);
  136. if ($carrier_weight<$waybillPriceModel->initial_weight){
  137. $fee=(($waybillPriceModel->unit_price)*($waybillPriceModel->initial_weight))+$logistic->delivery_fee;
  138. }else{
  139. $fee=(($waybillPriceModel->unit_price)*$carrier_weight)+$logistic->delivery_fee;
  140. }
  141. if ($waybillPriceModel->base_fee&&$fee<$waybillPriceModel->base_fee){
  142. $fee=$waybillPriceModel->base_fee;
  143. }
  144. $waybill->fee=$fee;
  145. $waybill->waybill_price_model_id=$waybillPriceModel_id;
  146. }
  147. $waybill->save();
  148. if ($waybill->charge)$waybillPayoffParam['total_receivable'] = ($waybill->charge);
  149. elseif($waybill->collect_fee) {
  150. $waybillPayoffParam['total_receivable'] = $waybill->collect_fee;
  151. }
  152. $waybillPayoffParam['total_expense'] = ($waybill->pick_up_fee)+($waybill->other_fee)+($waybill->fee);
  153. }
  154. if ($waybillPayoffParam['total_receivable'] > 0){
  155. $waybillPayoffParam['waybill_id'] = $id;
  156. $waybillPayoffParam['gross_margin'] = $waybillPayoffParam['total_receivable'] - $waybillPayoffParam['total_expense'];
  157. $waybillPayoffParam['gross_profit_rate'] = $waybillPayoffParam['gross_margin']/$waybillPayoffParam['total_receivable'];
  158. $waybillPayoffService->updateOrCreate($waybillPayoffParam);
  159. }
  160. $stage = "发起调度";
  161. if ($waybill->type=='德邦物流' && !$oldBill){
  162. $bill = app('DbOpenService')->getDbOrderNo($waybill);
  163. if (!$bill){DB::rollBack();return "获取德邦单号失败,德邦服务异常";}
  164. $waybill->update(["carrier_bill"=>$bill['mailNo'],'waybill_number'=>$bill['mailNo'],'station_no' => $bill['stationNo'], 'arrived_org_simple_name' =>$bill['arrivedOrgSimpleName'], 'much_higher_delivery'=>$bill['muchHigherDelivery']]);
  165. $msg = "【申请德邦物流单号:".$bill['mailNo']."】";
  166. if (!app("WaybillService")->notifyFlux($waybill))$msg .= ",通知FLUX失败";
  167. $stage = '发起德邦调度';
  168. }
  169. WaybillAuditLog::query()->create([
  170. 'waybill_id' => $id,
  171. 'audit_stage' => $stage,
  172. 'user_id' => Auth::id(),
  173. ]);
  174. DB::commit();
  175. }catch (\Exception $e){
  176. DB::rollBack();
  177. return "调度失败".$e->getMessage();
  178. }
  179. return redirect('transport/waybill/index')->with('successTip','运单“'.$waybill->waybill_number.'”创建成功 '. ($msg??''));
  180. }
  181. public function checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id){
  182. //确保承运商计数与计数单位为一个数组且长度2
  183. if(!$logistic_id)return false;
  184. if(!$destination_city_id)return false;
  185. if(!$carrier_weight)return false;
  186. if(!$carrier_weight_unit_id)return false;
  187. //多个计数标准,计算价格,取最贵
  188. if ($carrier_weight[0]&&$carrier_weight[1]&&$carrier_weight_unit_id[0]&&$carrier_weight_unit_id[1]){
  189. //城市价格区间不为空
  190. $waybillPriceModelOne=WaybillPriceModel::query()->where('logistic_id',$logistic_id)->where('city_id',$destination_city_id)
  191. ->where('range_min','<',$carrier_weight[0])->where('range_max','>=',$carrier_weight[0])
  192. ->where('unit_id',$carrier_weight_unit_id[0])->first();
  193. $waybillPriceModelTwo=WaybillPriceModel::query()->where('logistic_id',$logistic_id)->where('city_id',$destination_city_id)
  194. ->where('range_min','<',$carrier_weight[1])->where('range_max','>=',$carrier_weight[1])
  195. ->where('unit_id',$carrier_weight_unit_id[1])->first();
  196. if ($waybillPriceModelOne&&$waybillPriceModelTwo){
  197. if ($waybillPriceModelOne->unit_price*$carrier_weight[0]>=$waybillPriceModelTwo->unit_price*$carrier_weight[1]){
  198. return $waybillPriceModelOne->id;
  199. }else{
  200. return $waybillPriceModelTwo->id;
  201. }
  202. }
  203. if ($waybillPriceModelOne)return $waybillPriceModelOne->id;
  204. if ($waybillPriceModelTwo)return $waybillPriceModelTwo->id;
  205. //价格区间为空
  206. $waybillPriceModelRangeOne=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND city_id = ? AND unit_id = ? AND range_max IS NULL',[$logistic_id,$destination_city_id,$carrier_weight_unit_id[0]])->first();
  207. $waybillPriceModelRangeTwo=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND city_id = ? AND unit_id = ? AND range_max IS NULL',[$logistic_id,$destination_city_id,$carrier_weight_unit_id[1]])->first();
  208. if ($waybillPriceModelRangeOne&&$waybillPriceModelRangeTwo){
  209. if ($waybillPriceModelRangeOne->unit_price*$carrier_weight[0]>=$waybillPriceModelRangeTwo->unit_price*$carrier_weight[1]){
  210. return $waybillPriceModelRangeOne->id;
  211. }else{
  212. return $waybillPriceModelRangeTwo->id;
  213. }
  214. }
  215. if ($waybillPriceModelRangeOne)return $waybillPriceModelRangeOne->id;
  216. if ($waybillPriceModelRangeTwo)return $waybillPriceModelRangeTwo->id;
  217. //城市为空
  218. $city=Region::query()->where('id',$destination_city_id)->select('parent_id')->first();
  219. $waybillPriceModelProvinceOne=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max >= ? AND range_min < ? AND city_id IS NULL',
  220. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[0],$carrier_weight[0],$carrier_weight[0]])->first();
  221. $waybillPriceModelProvinceTwo=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max >= ? AND range_min < ? AND city_id IS NULL',
  222. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[1],$carrier_weight[1],$carrier_weight[1]])->first();
  223. if ($waybillPriceModelProvinceOne&&$waybillPriceModelProvinceTwo){
  224. if ($waybillPriceModelProvinceOne->unit_price*$carrier_weight[0]>=$waybillPriceModelProvinceTwo->unit_price*$carrier_weight[1]){
  225. return $waybillPriceModelProvinceOne->id;
  226. }else{
  227. return $waybillPriceModelProvinceTwo->id;
  228. }
  229. }
  230. if ($waybillPriceModelProvinceOne)return $waybillPriceModelProvinceOne->id;
  231. if ($waybillPriceModelProvinceTwo)return $waybillPriceModelProvinceTwo->id;
  232. //城市价格区间都为空
  233. $waybillPriceModelProvinceRangeOne=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max IS NULL AND city_id IS NULL',
  234. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[0]])->first();
  235. $waybillPriceModelProvinceRangeTwo=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max IS NULL AND city_id IS NULL',
  236. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[1]])->first();
  237. if ($waybillPriceModelProvinceRangeOne&&$waybillPriceModelProvinceRangeTwo){
  238. if ($waybillPriceModelProvinceRangeOne->unit_price*$carrier_weight[0]>=$waybillPriceModelProvinceRangeTwo->unit_price*$carrier_weight[1]){
  239. return $waybillPriceModelProvinceRangeOne->id;
  240. }else{
  241. return $waybillPriceModelProvinceRangeOne->id;
  242. }
  243. }
  244. if ($waybillPriceModelProvinceRangeOne)return $waybillPriceModelProvinceRangeOne->id;
  245. if ($waybillPriceModelProvinceRangeTwo)return $waybillPriceModelProvinceRangeTwo->id;
  246. };
  247. for ($i=0;$i<count($carrier_weight);$i++){
  248. if ($carrier_weight[$i]&&$carrier_weight_unit_id[$i]){
  249. //城市价格区间不为空
  250. $waybillPriceModel=WaybillPriceModel::query()->where('logistic_id',$logistic_id)->where('city_id',$destination_city_id)
  251. ->where('range_min','<',$carrier_weight[$i])->where('range_max','>=',$carrier_weight[$i])
  252. ->where('unit_id',$carrier_weight_unit_id[$i])->first();
  253. if($waybillPriceModel)return $waybillPriceModel->id;
  254. //价格区间为空
  255. $waybillPriceModelRange=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND city_id = ? AND unit_id = ? AND range_max IS NULL',[$logistic_id,$destination_city_id,$carrier_weight_unit_id[$i]])->first();
  256. if ($waybillPriceModelRange){ return $waybillPriceModelRange->id;}
  257. //城市为空
  258. $city=Region::query()->where('id',$destination_city_id)->select('parent_id')->first();
  259. $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max >= ? AND range_min < ? AND city_id IS NULL',
  260. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[$i],$carrier_weight[$i],$carrier_weight[$i]])->first();
  261. if ($waybillPriceModelProvince){return $waybillPriceModelProvince->id;}
  262. //城市价格区间都为空
  263. $waybillPriceModelProvinceRange=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max IS NULL AND city_id IS NULL',
  264. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[$i]])->first();
  265. if ($waybillPriceModelProvinceRange){return $waybillPriceModelProvinceRange->id;}
  266. }
  267. }
  268. return false;
  269. }
  270. /*三层条件:无优先级,找到第一个直接返回
  271. * 无论是否为KG||T,计数单位一为KG,计数单位一为T,计数单位二为KG,计数单位二为T
  272. * 计数一与计数二同时存在取最贵价格:
  273. * 计数一存在,二不存在:
  274. * 计数二存在,一不存在:
  275. * 城市价格区间不为空,城市价格区间都为空,城市为空,价格区间为空
  276. * */
  277. public function isWaybillPriceModel(Request $request){
  278. $logistic_id=$request->input('logistic_id');
  279. $destination_city_id=$request->input('destination_city_id');
  280. $carrier_weight=$request->input('carrier_weight');
  281. $carrier_weight_unit_id=$request->input('carrier_weight_unit_id');
  282. $validatorData=["logistic_id"=>$logistic_id,"destination_city_id"=>$destination_city_id,
  283. 'carrier_weight'=>$carrier_weight[0],"carrier_weight_unit_id"=>$carrier_weight_unit_id[0],
  284. "carrier_weight_other"=>$carrier_weight[1],"carrier_weight_unit_id_other"=>$carrier_weight_unit_id[1]];
  285. if ($logistic_id == 15){
  286. $flag = 1;
  287. $validatorData['cargo_name'] = $request->input('cargo_name');
  288. $validatorData['total_number'] = $request->input('total_number');
  289. $validatorData['total_weight'] = $request->input('total_weight');
  290. $validatorData['deliveryType_id'] = $request->input('deliveryType_id');
  291. $validatorData['order_type'] = $request->input('order_type');
  292. $validatorData['transport_type'] = $request->input('transport_type');
  293. $validatorData['pay_type'] = $request->input('pay_type');
  294. $validatorData['back_sign_bill'] = $request->input('back_sign_bill');
  295. $validatorData['package_service'] = $request->input('package_service');
  296. }else $flag = 0;
  297. $errors=Validator::make($validatorData,[
  298. 'logistic_id'=>'required|integer',
  299. 'destination_city_id'=>'required|integer',
  300. 'carrier_weight'=>'nullable|min:0|numeric|max:999999',
  301. 'carrier_weight_unit_id'=>'required_with:carrier_weight',
  302. 'carrier_weight_other'=>'nullable|min:0|numeric|max:999999',
  303. 'carrier_weight_unit_id_other'=>'required_with:carrier_weight_other',
  304. 'cargo_name' => $flag ? 'required' : '',
  305. 'total_number' => $flag ? 'required|min:0|numeric|max:999999' : '',
  306. 'total_weight' => $flag ? 'required|min:0|numeric|max:999999' : '',
  307. 'deliveryType_id' => $flag ? 'required' : '',
  308. 'order_type' => $flag ? 'required' : '',
  309. 'transport_type' => $flag ? 'required' : '',
  310. 'pay_type' => $flag ? 'required' : '',
  311. 'back_sign_bill' => $flag ? 'required' : '',
  312. 'package_service' => $flag ? 'required' : '',
  313. ],[
  314. 'required'=>':attribute 为必填项',
  315. 'max'=>':attribute 字符过多或输入值过大',
  316. 'min'=>':attribute 不得为负',
  317. 'numeric'=>':attribute 应为数字',
  318. 'unique'=>':attribute 已存在',
  319. 'required_with'=>':attribute 未填',
  320. 'integer'=>':attribute 必须为数字',
  321. ],[
  322. 'carrier_weight'=>'承运商计数(抛)',
  323. 'logistic_id'=>'承运商',
  324. 'destination_city_id'=>'目的市',
  325. 'carrier_weight_unit_id'=>'承运商计数单位',
  326. 'carrier_weight_other'=>'承运商计数二',
  327. 'carrier_weight_unit_id_other'=>'承运商计数单位二',
  328. 'cargo_name' => '货物名称',
  329. 'total_number' => '总包裹数',
  330. 'total_weight' => '总重量',
  331. 'deliveryType_id' => '送货方式',
  332. 'order_type' => '下单模式',
  333. 'transport_type' => '运输方式/产品类型',
  334. 'pay_type' => '支付方式',
  335. 'back_sign_bill' => '签收回单',
  336. ])->errors();
  337. if (count($errors)>0)return ['error'=>$errors];
  338. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  339. if (!$result){
  340. //单位为kg,T时
  341. $unitKG=Unit::query()->where('name','kg')->first();
  342. $unitT=Unit::query()->where('name','T')->first();
  343. if ($carrier_weight_unit_id[0]==$unitKG->id){
  344. $carrier_weight_unit_id[0]=$unitT->id;
  345. $carrier_weight[0]=$carrier_weight[0]/1000;
  346. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  347. if ($result)return ['success'=>$result];
  348. }
  349. if ($carrier_weight_unit_id[1]==$unitKG->id){
  350. $carrier_weight_unit_id[1]=$unitT->id;
  351. $carrier_weight[1]=$carrier_weight[1]/1000;
  352. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  353. if ($result)return ['success'=>$result];
  354. }
  355. if ($carrier_weight_unit_id[0]==$unitT->id){
  356. $carrier_weight_unit_id[0]=$unitKG->id;
  357. $carrier_weight[0]=$carrier_weight[0]*1000;
  358. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  359. if ($result)return ['success'=>$result];
  360. }
  361. if ($carrier_weight_unit_id[1]==$unitT->id){
  362. $carrier_weight_unit_id[1]=$unitKG->id;
  363. $carrier_weight[1]=$carrier_weight[1]*1000;
  364. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  365. if ($result)return ['success'=>$result];
  366. }
  367. }
  368. return ['success'=>$result];
  369. }
  370. public function waybillUpdate(Request $request, $id){
  371. if(!Gate::allows('运输管理-编辑')){ return redirect(url('/')); }
  372. $this->validatorWaybill($request,$id)->validate();
  373. $data=$request->input();
  374. $waybill=app('waybillService')->find($id);
  375. $waybill->fill($data);
  376. if ($waybill->save()){
  377. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($waybill),Auth::user()['id']);
  378. return redirect('transport/waybill/index')->with('successTip','运单“'.$waybill->waybill_number.'”修改成功');
  379. }
  380. }
  381. public function waybillAudit(Request $request){
  382. if(!Gate::allows('运输管理-运单-运单审核')){ return redirect(url('/')); }
  383. $id=$request->input('id');
  384. $waybill=app('waybillService')->find($id);
  385. $isAudit=WaybillAuditLog::whereRaw('waybill_id = ? and audit_stage = ?',[$id,"运单阶段"])->first();
  386. if (empty($isAudit)){
  387. $waybillAuditLog=new WaybillAuditLog([
  388. 'waybill_id'=>$id,
  389. 'audit_stage'=>'运单阶段',
  390. 'user_id'=>Auth::id(),
  391. ]);
  392. $waybillAuditLog->save();
  393. $waybillAuditLog['user']=Auth::user();
  394. $waybill->status='已审核';
  395. $result=$waybill->save();
  396. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($waybill),Auth::user()['id']);
  397. return ['success'=>$result,'status'=>$waybill->status,'waybillAuditLog'=>$waybillAuditLog];
  398. }
  399. return ['exception'=>'请勿重复审核!'];
  400. }
  401. public function waybillEdit($id){
  402. if(!Gate::allows('运输管理-编辑')){ return redirect(url('/')); }
  403. $waybill=app('waybillService')->find($id);
  404. $owners=app("OwnerService")->getIntersectPermitting();
  405. return view('transport.waybill.waybillEdit',['waybill'=>$waybill,'owners'=>$owners]);
  406. }
  407. public function waybillRetreatAudit(Request $request){
  408. if(!Gate::allows('运输管理-运单-调度')){ return redirect(url('/')); }
  409. $id=$request->input('id');
  410. /** @var Model|\stdClass $waybill */
  411. $waybill=app('waybillService')->find($id);
  412. $waybillLog = WaybillAuditLog::query()->whereRaw('waybill_id = ? and audit_stage = ?',[$id,"运单阶段"])->delete();
  413. $waybill->status='待重审';
  414. return ['success'=>$waybill->save(),'status'=>$waybill->status,"log"=>$waybillLog];
  415. }
  416. public function waybillEndAudit(Request $request){
  417. if(!Gate::allows('运输管理-运单-调度审核')){ return redirect(url('/')); }
  418. $id=$request->input('id');
  419. $waybill=Waybill::query()->with(["owner","logistic","originationCity","destinationCity","carType",'priceModel',"amountUnit",
  420. "warehouseWeightUnit","carrierWeightUnit","warehouseWeightUnitOther","carrierWeightUnitOther"])->find($id);
  421. if (!$waybill->charge&&!$waybill->collect_fee)return ['exception'=>'收费或到付费用未填!'];
  422. if ($waybill->charge==0&&$waybill->collect_fee==0)return ['exception'=>'收费与到付费用都为0!'];
  423. if ($waybill->type=='专线'){
  424. if (!$waybill->carrier_weight_other||$waybill->carrier_weight_other==0)return ['exception'=>'承运商计重未填或为0!'];
  425. if (!$waybill->carrier_weight_unit_id_other)return ['exception'=>'承运商计重单位未选!'];
  426. }
  427. $isAudit=WaybillAuditLog::query()->whereRaw('waybill_id = ? and audit_stage = ?',[$id,"调度阶段"])->first();
  428. if (empty($isAudit)){
  429. $waybillAuditLog=new WaybillAuditLog([
  430. 'waybill_id'=>$id,
  431. 'audit_stage'=>'调度阶段',
  432. 'user_id'=>Auth::id(),
  433. ]);
  434. $waybillAuditLog->save();
  435. $waybillAuditLog['user']=Auth::user();
  436. if ($waybill->waybill_price_model_id||$waybill->type=='直发车'){
  437. $waybill->status='已完结';
  438. $result=$waybill->save();
  439. $waybillPayoff=WaybillPayoff::query()->where('waybill_id','=',$id)->first();
  440. $waybillPayoffJson=json_encode($this->createReportData($waybill,$waybillPayoff),JSON_UNESCAPED_UNICODE);
  441. WaybillFinancialSnapshot::query()->create([
  442. 'waybill_id'=>$id,
  443. 'json_content'=>$waybillPayoffJson,
  444. ]);
  445. }else{
  446. $waybill->status='无模型';
  447. $result=$waybill->save();
  448. $waybillPayoff=WaybillPayoff::query()->where('waybill_id','=',$id)->first();
  449. if ($waybillPayoff){
  450. $waybillPayoffJson=json_encode($this->createReportData($waybill,$waybillPayoff),JSON_UNESCAPED_UNICODE);
  451. WaybillFinancialExcepted::query()->create([
  452. 'waybill_id'=>$id,
  453. 'json_content'=>$waybillPayoffJson,
  454. ]);
  455. }
  456. }
  457. app("waybillService")->createInstantBill($waybill);
  458. app('LogService')->log(__METHOD__,__FUNCTION__,$waybillPayoffJson,Auth::id());
  459. return ['success'=>$result,'status'=>$waybill->status,'waybillAuditLog'=>$waybillAuditLog];
  460. }
  461. return ['exception'=>'请勿重复审核!'];
  462. }
  463. //生成报表数据
  464. private function createReportData($waybill,$waybillPayoff){
  465. /** @var Waybill $waybill */
  466. $waybill->loadMissing(["order.owner"]);
  467. return [
  468. "type"=>$waybill->type,
  469. "waybill_number"=>$waybill->waybill_number,
  470. "owner_name"=>$waybill->order->owner->name ?? ($waybill->owner->name ?? null),
  471. "wms_bill_number"=>$waybill->wms_bill_number,
  472. "source_bill"=>$waybill->source_bill,
  473. "origination"=>$waybill->origination,
  474. "destination"=>$waybill->order->address ?? $waybill->destination,
  475. "recipient"=>$waybill->order->consignee_name ?? $waybill->recipient,
  476. "recipient_mobile"=>$waybill->order->consignee_phone ?? $waybill->recipient_mobile,
  477. "charge"=>$waybill->charge,
  478. "collect_fee"=>$waybill->collect_fee,
  479. "ordering_remark"=>$waybill->ordering_remark,
  480. "carrier_name"=>$waybill->logistic->name ?? null,
  481. "carrier_bill"=>$waybill->carrier_bill,
  482. "origination_city_name"=>$waybill->originationCity ? $waybill->originationCity->name : null,
  483. "destination_city_name"=>$waybill->order->city ?? ($waybill->destinationCity->name ?? null),
  484. "warehouse_weight"=>$waybill->warehouse_weight.($waybill->warehouseWeightUnit ? $waybill->warehouseWeightUnit->name : ''),
  485. "carrier_weight"=>$waybill->carrier_weight.($waybill->carrierWeightUnit ? $waybill->carrierWeightUnit->name : ''),
  486. "warehouse_weight_other"=>$waybill->warehouse_weight_other.($waybill->warehouseWeightUnitOther ? $waybill->warehouseWeightUnitOther->name : ''),
  487. "carrier_weight_other"=>$waybill->carrier_weight_other.($waybill->carrierWeightUnitOther ? $waybill->carrierWeightUnitOther->name : ''),
  488. "car_type_name"=>$waybill->carType ? $waybill->carType->name : null,
  489. "fee"=>$waybill->fee,
  490. "pick_up_fee"=>$waybill->pick_up_fee,
  491. "other_fee"=>$waybill->other_fee,
  492. "dispatch_remark"=>$waybill->dispatch_remark,
  493. "price_model_range_min"=>$waybill->priceModel ? $waybill->priceModel->range_min : null,
  494. "price_model_range_max"=>$waybill->priceModel ? $waybill->priceModel->range_max : null,
  495. "price_model_unit_price"=>$waybill->priceModel ? $waybill->priceModel->unit_price : null,
  496. "price_model_base_fee"=>$waybill->priceModel ? $waybill->priceModel->base_fee : null,
  497. "price_model_initial_weight"=>$waybill->priceModel ? $waybill->priceModel->initial_weight : null,
  498. "car_owner_info"=>$waybill->car_owner_info,
  499. "status"=>$waybill->status,
  500. "mileage"=>$waybill->mileage,
  501. 'amount'=>$waybill->amount.($waybill->amountUnit ? $waybill->amountUnit->name : ''),
  502. "inquire_tel"=>$waybill->inquire_tel,
  503. "other_charge"=>$waybill->other_charge,
  504. "other_charge_remark"=>$waybill->other_charge_remark,
  505. "deliver_at"=>$waybill->deliver_at,
  506. "created_at"=>$waybill->created_at,
  507. "auditLog_user_name"=>Auth::user()['name'],
  508. "total_expense"=>$waybillPayoff->total_expense,
  509. "total_receivable"=>$waybillPayoff->total_receivable,
  510. "gross_margin"=>$waybillPayoff->gross_margin,
  511. "gross_profit_rate"=>$waybillPayoff->gross_profit_rate,
  512. ];
  513. }
  514. public function upload(Request $request){
  515. $this->gate("运输管理-运单-图片上传");
  516. $files=$request->file("files");
  517. if (!$files)$this->error("未传递照片");
  518. $id=$request->input('id');
  519. $waybill=Waybill::query()->find($id);
  520. if (!$waybill)$this->error("未找到该运单!");
  521. $res = [];
  522. foreach ($files as $file){
  523. if (!$file->isValid()){
  524. return ['success'=>false,'error'=>"找不到照片!"];
  525. }
  526. $tmpFile = $file->getRealPath();
  527. if (! is_uploaded_file($tmpFile)) {
  528. return ['success'=>false,'error'=>"文件错误!"];
  529. }
  530. $fileExtension=$file->getClientOriginalExtension();
  531. // 5.存储, 生成一个随机文件名
  532. $fileName = date('ymd').'-'.Uuid::uuid1();//thumbnail common bulky
  533. $thumbnailName=storage_path('app/public/files/'.$fileName.'-thumbnail.'.$fileExtension);
  534. $commonName=storage_path('app/public/files/'.$fileName.'-common.'.$fileExtension);
  535. $bulkyName=storage_path('app/public/files/'.$fileName.'-bulky.'.$fileExtension);
  536. $result=move_uploaded_file ($tmpFile ,$bulkyName);
  537. if ($result){
  538. $img=Image::make($bulkyName);
  539. if ($img->height() > $img->width())
  540. $img->heighten(250)->save($commonName);
  541. else $img->widen(250)->save($commonName);
  542. $img->heighten(28)->save($thumbnailName);
  543. /** @var UploadFile|\stdClass $uploadFile */
  544. $uploadFile=new UploadFile([
  545. "table_name"=>"waybills",
  546. "table_id"=>$waybill->id,
  547. "url"=>'/files/'.$fileName,
  548. "type"=>$fileExtension,
  549. ]);
  550. if ($uploadFile->save())
  551. app('LogService')->log(__CLASS__,'运输图片上传',json_encode($request),Auth::user()['id']);
  552. $res[] = $uploadFile;
  553. }else $this->error("图片存储失败,检查服务器状态");
  554. }
  555. $this->success($res);
  556. }
  557. //批量上传图片
  558. public function batchUploadImages()
  559. {
  560. $this->gate("运输管理-运单-图片上传");
  561. ini_set('max_execution_time',1000);
  562. ini_set('memory_limit','100M');
  563. $images = request("images");
  564. $errors = [];
  565. $number = [];
  566. $mapping = [];
  567. $type = ["jpg","png","gif","jfif","pjpeg","jpeg","webp"];
  568. foreach ($images as $index => $image){
  569. $arr = explode(".",$image["name"]);
  570. $suffix = $arr[count($arr)-1];
  571. unset($arr[count($arr)-1]);
  572. $name = implode(".",$arr);
  573. if (array_search(strtolower($suffix),$type) === false){
  574. $errors[] = "“".$name."”格式错误";
  575. unset($images[$index]);
  576. continue;
  577. }
  578. $images[$index]["suffix"] = $suffix;
  579. $num = trim(rtrim($name,".".$suffix));
  580. $number[] = $num;
  581. $mapping[$num] = $index;
  582. }
  583. $waybills = Waybill::query()->select("id","source_bill")->whereIn('source_bill',$number)->get();
  584. foreach (array_diff($number,array_column($waybills->toArray(),"source_bill")) as $diff){
  585. $errors[] = "“".$diff."”不存在运单";
  586. unset($images[$mapping[$diff]]);
  587. }
  588. $insert = [];
  589. foreach ($waybills as $waybill){
  590. $image = $images[$mapping[$waybill->source_bill]];
  591. $fileName = date('ymd').'-'.Uuid::uuid1();
  592. $suffix = $image["suffix"];
  593. $thumbnailName=storage_path('app/public/files/'.$fileName.'-thumbnail.'.$suffix);
  594. $commonName=storage_path('app/public/files/'.$fileName.'-common.'.$suffix);
  595. $bulkyName=storage_path('app/public/files/'.$fileName.'-bulky.'.$suffix);
  596. preg_match('/^(data:\s*image\/(\w+);base64,)/',$image["src"],$res);
  597. $base64_img=base64_decode(str_replace($res[1],'', $image["src"]));
  598. Storage::put('public/files/'.$fileName.'-bulky.'.$suffix,$base64_img);
  599. $img=Image::make($bulkyName);
  600. if ($img->height() > $img->width())
  601. $img->heighten(250)->save($commonName);
  602. else $img->widen(250)->save($commonName);
  603. $img->heighten(28)->save($thumbnailName);
  604. $insert[] = [
  605. "table_name"=>"waybills",
  606. "table_id"=>$waybill->id,
  607. "url"=>'/files/'.$fileName,
  608. "type"=>strtolower($suffix),
  609. ];
  610. }
  611. if ($insert)UploadFile::query()->insert($insert);
  612. $waybills->load("uploadFiles");
  613. $this->success(["errors"=>$errors,"data"=>$waybills]);
  614. }
  615. //删除照片
  616. public function deleteImg(Request $request){
  617. $this->gate("运输管理-运单-图片删除");
  618. $query=UploadFile::query()->where('table_name','waybills');
  619. if ($request->input("url"))$query = $query->where('table_id',$request->input("id"))->where("url",$request->input("url"));
  620. else $query = $query->whereIn('table_id',$request->input("id"));
  621. foreach ($query->get() as $uploadFile){
  622. $bulky=storage_path('app/public/'.$uploadFile->url.'-bulky.'.$uploadFile->type);
  623. $common=storage_path('app/public/'.$uploadFile->url.'-common.'.$uploadFile->type);
  624. $thumbnail=storage_path('app/public/'.$uploadFile->url.'-thumbnail.'.$uploadFile->type);
  625. if (file_exists($bulky) && file_exists($common) && file_exists($thumbnail)){
  626. unlink($bulky);unlink($common);unlink($thumbnail);
  627. }
  628. }
  629. $query->delete();
  630. app('LogService')->log(__METHOD__,'图片删除',json_encode($request),Auth::user()['id']);
  631. $this->success();
  632. }
  633. public function export(){
  634. ini_set('max_execution_time',2500);
  635. ini_set('memory_limit','1526M');
  636. $append = \request("append")=='true';
  637. request()->offsetUnset("append");
  638. $this->gate('运输管理-运单-查询');
  639. /** @var Collection $waybills */
  640. if (request("checkAllSign")){
  641. request()->offsetUnset("checkAllSign");
  642. $waybills = app('waybillService')->get(request()->input());
  643. }else $waybills = app('waybillService')->get(["id"=>request("data")]);
  644. if ($waybills->count()==0)return "无数据";
  645. $row = [
  646. "运单类型", "货主", "上游单号", "wms订单号", "运单号", "运输收费",
  647. "其他收费", "其他收费备注", "始发地", "目的地","下单备注", "承运商", "承运商单号",
  648. "仓库计抛", "承运商计抛", "仓库计重", "承运商计重", "车型", "车辆信息",
  649. "计件", "里程数", "运费(元)", "提货费(元)", "其他费用(元)", "发货时间",
  650. "调度备注", "创建时间", "省", "市", "区", "FLUX地址", "FLUX重量", "FLUX数量"
  651. ];
  652. $list = [];
  653. $codes = [];
  654. $code = '';
  655. $map = [];
  656. $waybills->each(function ($waybill,$index)use(&$list,&$codes,&$code,&$map){
  657. foreach (explode(",",$waybill->wms_bill_number) as $bill){
  658. $code .= "'".$bill."',";
  659. $map[$bill] = $index;
  660. }
  661. if ($index%800==0){
  662. $codes[] = rtrim($code,",");
  663. $code = '';
  664. }
  665. $list[] = [
  666. $waybill->type,
  667. $waybill->owner->name ?? ($waybill->order->owner->name ?? ""),
  668. $waybill->source_bill,
  669. $waybill->wms_bill_number,
  670. $waybill->waybill_number,
  671. $waybill->charge,
  672. $waybill->other_charge,
  673. $waybill->other_charge_remark,
  674. $waybill->origination,
  675. $waybill->destination ?: ($waybill->order->address ?? ''),
  676. $waybill->ordering_remark,
  677. $waybill->logistic->name ?? "",
  678. $waybill->carrier_bill,
  679. $waybill->warehouse_weight,
  680. $waybill->carrier_weight,
  681. $waybill->warehouse_weight_other,
  682. $waybill->carrier_weight_other,
  683. $waybill->car_type_name,
  684. $waybill->car_owner_info,
  685. $waybill->amount,
  686. $waybill->mileage,
  687. $waybill->fee,
  688. $waybill->pick_up_fee,
  689. $waybill->other_fee,
  690. $waybill->deliver_at,
  691. $waybill->dispatch_remark,
  692. $waybill->created_at->toDateTimeString(),
  693. "", "", "","",0,0
  694. ];
  695. });
  696. if ($code)$codes[] = rtrim($code,",");
  697. if ($codes && $append){
  698. foreach ($codes as $code){
  699. $sql = <<<SQL
  700. SELECT H.ORDERNO,SUM(S.GROSSWEIGHT) WEIGHT,SUM(S.QTY) AMOUNT,H.C_ADDRESS1,H.C_DISTRICT,H.C_PROVINCE,H.C_CITY FROM DOC_ORDER_PACKING_SUMMARY S
  701. LEFT JOIN DOC_ORDER_HEADER H ON S.ORDERNO = H.ORDERNO
  702. WHERE H.ORDERNO IN ({$code}) GROUP BY H.ORDERNO,H.C_ADDRESS1,H.C_DISTRICT,H.C_PROVINCE,H.C_CITY
  703. SQL;
  704. foreach (DB::connection("oracle")->select(DB::raw($sql)) as $summary){
  705. $list[$map[$summary->orderno]][27] = $summary->c_province;
  706. $list[$map[$summary->orderno]][28] = $summary->c_city;
  707. $list[$map[$summary->orderno]][29] = $summary->c_district;
  708. $list[$map[$summary->orderno]][30] = $summary->c_address1;
  709. $list[$map[$summary->orderno]][31] += $summary->weight;
  710. $list[$map[$summary->orderno]][32] += $summary->amount;
  711. }
  712. }
  713. }
  714. return Export::make($row,$list,"运输记录单-".date("YmdH"));
  715. }
  716. public function deliveringExport(Request $request){
  717. if ($request->checkAllSign){
  718. $param = $request->input();
  719. unset($param['checkAllSign']);
  720. $sql = app('waybillService')->getDeliveringSql($param);
  721. }else{
  722. $sql = app('waybillService')->getDeliveringSql(['id'=>$request->data]);
  723. }
  724. $e = new Export();
  725. $e->setMysqlConnection(config('database.connections.mysql.host'),
  726. config('database.connections.mysql.port'),config('database.connections.mysql.database')
  727. ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
  728. $e->setFileName("发运报表");
  729. return $e->sql($sql,[
  730. "created_at"=>"日期","carrier_name"=>"承运商",
  731. "waybill_number"=>"宝时运单号","origination"=>"提货仓",
  732. "owner_name"=>"货主","warehouse_weight_other"=>"预估重量",
  733. "warehouse_weight"=>"预估体积","status"=>"状态",
  734. "carrier_bill"=>"专线运单号","inquire_tel"=>"查件电话",
  735. "amount"=>"件数","carrier_weight_other"=>"重量",
  736. "carrier_weight"=>"体积"
  737. ])->direct();
  738. }
  739. //发运
  740. public function delivering(Request $request){
  741. if (!Auth::user())return view('exception.login');
  742. $waybills= Waybill::query()->where("type","专线")
  743. ->whereNotNull("logistic_id")->whereNotIn("status",["未审核","待重审"])
  744. ->orderByDesc("id");
  745. if (!Auth::user()->isSuperAdmin()){
  746. $carriersUsers=DB::table('logistic_user')->where('user_id',Auth::id())->get();
  747. $carrierIds=array_column($carriersUsers->toArray(),'logistic_id');
  748. if ($carrierIds)$waybills->whereIn("logistic_id",$carrierIds);
  749. }
  750. $searchText = $request->get("searchText","");
  751. if ($searchText)$waybills->where(function ($query)use($searchText){
  752. $query->where("waybill_number",'like','%'.$searchText.'%')->orWhere("carrier_bill",'like','%'.$searchText.'%');
  753. });
  754. $waybills = $waybills->get();
  755. return view('transport.waybill.delivering',compact('waybills',"searchText"));
  756. }
  757. //承运商提交
  758. public function storeCarrierBill(Request $request){
  759. //if(!Gate::allows("运输管理-承运商调度"))return ["error"=>"无权操作!"];
  760. $errors=Validator::make($request->input(),[
  761. 'id'=>'required|integer',
  762. 'carrier_bill'=>'required',
  763. 'inquire_tel'=>'nullable',
  764. 'amount'=>'nullable|integer',
  765. 'carrier_weight'=>'required_without:carrier_weight_other|nullable|numeric',
  766. 'carrier_weight_other'=>'required_without:carrier_weight|nullable|numeric',
  767. ],[
  768. 'required'=>':attribute 为必填项',
  769. 'integer'=>':attribute 应为整数',
  770. 'numeric'=>':attribute 应为数字',
  771. 'required_with'=>':attribute 重量与体积至少存在一项',
  772. ],[
  773. 'carrier_bill'=>'运单号',
  774. 'inquire_tel'=>'查件电话',
  775. 'amount'=>'件数',
  776. 'carrier_weight'=>'体积',
  777. 'carrier_weight_other'=>'重量',
  778. ])->errors();
  779. $unit = app("UnitService")->getUnit("kg");
  780. $unit1 = app("UnitService")->getUnit("件");
  781. $unit2 = app("UnitService")->getUnit("m³");
  782. if (count($errors)>0)return ["errors"=>$errors];
  783. $waybill=Waybill::query()->find($request->input('id'));
  784. if (!$waybill)return ["error"=>"未找到该运单!"];
  785. $request->offsetSet("carrier_weight_unit_id",$unit2);
  786. $request->offsetSet("carrier_weight_unit_id_other",$unit);
  787. $request->offsetSet("amount_unit_id",$unit1);
  788. $waybill->fill($request->input());
  789. $waybill->update();
  790. return $waybill;
  791. }
  792. protected function validatorWaybill(Request $request,$id){
  793. if ($id){$wms_bill_number=$id;};
  794. return Validator::make($request->input(),[
  795. 'owner_id'=>'required_without:order_id',
  796. 'wms_bill_number'=>['nullable','max:50',isset($wms_bill_number)?"unique:waybills,wms_bill_number,$wms_bill_number":'unique:waybills,wms_bill_number'],
  797. 'origination'=>'required|max:255',
  798. 'destination'=>'required_without:order_id|max:255',
  799. 'recipient'=>'required_without:order_id|max:50',
  800. 'recipient_mobile'=>['required_without:order_id','regex:/^(\d{7,11})|(1[3|4|5|7|8][0-9]\d{4,8})$/'],
  801. 'charge'=>'nullable|min:0|max:999999|numeric',
  802. 'collect_fee'=>'nullable|min:0|numeric',
  803. ],[
  804. 'required'=>':attribute 为必填项',
  805. 'required_without'=>':attribute 为必填项',
  806. 'alpha_num'=>':attribute 应为字母或数字',
  807. 'max'=>':attribute 字符过多或输入值过大',
  808. 'regex'=>':attribute 输入有误',
  809. 'integer'=>':attribute 应为整数',
  810. 'min'=>':attribute 不得为负',
  811. 'numeric'=>':attribute 应为数字',
  812. 'unique'=>':attribute 已存在',
  813. ],[
  814. 'owner_id'=>'货主',
  815. 'wms_bill_number'=>'WMS单号',
  816. 'origination'=>'始发地',
  817. 'destination'=>'目的地',
  818. 'recipient'=>'收件人',
  819. 'recipient_mobile'=>'收件人电话',
  820. 'charge'=>'收费',
  821. 'collect_fee'=>'到付金额',
  822. ]);
  823. }
  824. protected function validatorWaybillDispatch(Request $request,$id){
  825. $rule=[
  826. 'logistic_id'=>'required_without:order_id|integer',
  827. 'carrier_bill'=>"sometimes|required|max:50|unique:waybills,carrier_bill,$id",
  828. 'fee'=>'sometimes|nullable|min:0|numeric|max:999999',
  829. 'inquire_tel'=>'required',
  830. 'carType_id'=>'sometimes|required|integer',
  831. 'other_fee'=>'sometimes|nullable|min:0|numeric|max:999999',
  832. 'charge'=>'sometimes|nullable|min:0|numeric|max:999999',
  833. 'mileage'=>'nullable|numeric|min:0',
  834. 'amount'=>'numeric|min:0',
  835. 'amount_unit_id'=>'required',
  836. 'origination_city_id'=>'sometimes|required|integer',
  837. 'destination_city_id'=>'sometimes|required_without:order_id|integer',
  838. 'warehouse_weight_other'=>'sometimes|nullable|min:0|numeric|max:999999',
  839. 'warehouse_weight_unit_id_other'=>'sometimes|required_with:warehouse_weight_other|nullable|integer',
  840. 'pick_up_fee'=>'sometimes|nullable|min:0|numeric|max:999999',
  841. 'warehouse_weight'=>'sometimes|nullable|min:0|numeric|max:999999',
  842. 'warehouse_weight_unit_id'=>'sometimes|required_with:warehouse_weight|nullable|integer',
  843. 'carrier_weight'=>'sometimes|nullable|min:0|numeric|max:999999',
  844. 'carrier_weight_unit_id'=>'sometimes|required_with:carrier_weight',
  845. 'carrier_weight_other'=>'sometimes|nullable|min:0|numeric|max:999999',
  846. 'carrier_weight_unit_id_other'=>'sometimes|required_with:carrier_weight_other',
  847. 'deliver_at_date'=>'required',
  848. ];
  849. if ($request->type == '专线'){
  850. $rule['origination_city_id']='required|integer';
  851. $rule['destination_city_id']='required_without:order_id|integer';
  852. }
  853. return Validator::make($request->input(),$rule,[
  854. 'required'=>':attribute 为必填项',
  855. 'required_without'=>':attribute 为必填项',
  856. 'alpha_num'=>':attribute 应为字母或数字',
  857. 'max'=>':attribute 字符过多或输入值过大',
  858. 'min'=>':attribute 不得为负',
  859. 'numeric'=>':attribute 应为数字',
  860. 'unique'=>':attribute 已存在',
  861. 'required_with'=>':attribute 未填',
  862. 'integer'=>':attribute 必须为数字',
  863. ],[
  864. 'logistic_id'=>'承运商',
  865. 'inquire_tel'=>'查件电话',
  866. 'carrier_bill'=>'承运商单号',
  867. 'fee'=>'运费',
  868. 'other_fee'=>'其他费用',
  869. 'charge'=>'收费',
  870. 'mileage'=>'里程数',
  871. 'amount'=>'计数',
  872. 'amount_unit_id'=>'计数单位',
  873. 'warehouse_weight'=>'仓库计数(抛)',
  874. 'carrier_weight'=>'承运商计数(抛)',
  875. 'pick_up_fee'=>'提货费',
  876. 'destination_city_id'=>'目的市',
  877. 'carrier_weight_unit_id'=>'承运商计数单位',
  878. 'warehouse_weight_unit_id'=>'仓库计数单位',
  879. 'warehouse_weight_other'=>'仓库计数二',
  880. 'carrier_weight_other'=>'承运商计数二',
  881. 'warehouse_weight_unit_id_other'=>'仓库技数单位二',
  882. 'carrier_weight_unit_id_other'=>'承运商计数单位二',
  883. 'deliver_at_date'=>'发货日期',
  884. ]);
  885. }
  886. public function addCounty(){
  887. $name = app("RegionService")->formatName(request("name"),2);
  888. if (!$name)$this->error("非法参数");
  889. $region = Region::query()->firstOrCreate(["name"=>$name,"type"=>2,"parent_id"=>request("province")]);
  890. $this->success($region);
  891. }
  892. // 运单删除 软删除
  893. public function destroy(int $id){
  894. if(!GAte::allows('运输管理-运单-删除')){return['success'=>0,'status'=>'没有权限'];}
  895. if(is_null($id)){return ['success'=>'0','status'=>'传入id为空'];}
  896. $result = Waybill::where('id',$id)->delete();
  897. WaybillAuditLog::query()->create([
  898. 'waybill_id'=>$id,
  899. 'audit_stage'=>'删除运单',
  900. 'user_id'=>Auth::id(),
  901. ]);
  902. return ['success'=>$result,'status'=>$result];
  903. }
  904. // 回收站
  905. public function recycle(Request $request){
  906. if(!Gate::allows('运输管理-运单-删除')){return redirect('/');}
  907. $paginate = $request->input('paginate')??50;
  908. /** @var Collection $waybills */
  909. $waybills = Waybill::query()->with(['owner','order.owner','logistic','amountUnit','warehouseWeightUnit','carrierWeightUnit',
  910. 'warehouseWeightUnitOther','carrierWeightUnitOther','carType','waybillAuditLogs' => function ($query) {
  911. /** @var Builder $query */
  912. $query->with('user');
  913. }])->orderBy('deleted_at', 'DESC')->withTrashed()->whereNotNull('deleted_at')->paginate(50);
  914. $total = $waybills->count();
  915. $paginateParams = [];
  916. $paginateParams['paginate'] = $paginate;
  917. return view('transport.waybill.recycle',compact('waybills','total','paginateParams'));
  918. }
  919. // 软删除恢复
  920. public function apiRestoreSelected(Request $request){
  921. if(!Gate::allows('运输管理-运单-删除')){return ['success'=>'false','fail_info'=>'没有权限'];}
  922. $ids = $request->input('ids')??'';
  923. if($ids == ''){return ['success'=>'false','fail_info'=>'没有可恢复对象'];}
  924. $waybills = Waybill::withTrashed()->whereIn('id',$ids)->get();
  925. $waybills->each(function (Waybill $waybill){
  926. $waybill->restore();
  927. });
  928. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  929. foreach ($ids as $id) WaybillAuditLog::query()->create([
  930. 'waybill_id'=>$id,
  931. 'audit_stage'=>'恢复运单',
  932. 'user_id'=>Auth::id(),
  933. ]);
  934. return ['success'=>'true','waybills'=>$waybills];
  935. }
  936. // 修改运费
  937. public function changeFee(Request $request){
  938. if(!Gate::allows('运输管理-运单-运费')){return ['success'=>'false','fail_info'=>'没有权限'];}
  939. $wayBillId = $request->input('id');
  940. $waybillFee = $request->input('fee');
  941. if(is_null($wayBillId) or is_null($waybillFee)){
  942. return ['success'=>'false','fail_info'=>'参数异常'];
  943. }
  944. $result = Waybill::where('id',$wayBillId)->update(['fee'=>$waybillFee]);
  945. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  946. return ['success'=>$result,'status'=>$result];
  947. }
  948. // 修改运输收费
  949. public function changeCharge(Request $request){
  950. if(!Gate::allows('运输管理-运单-运单编辑')){return ['success'=>'false','fail_info'=>'没有权限'];}
  951. $wayBillId = $request->id;
  952. $waybillCharge = $request->input('charge');
  953. if(is_null($wayBillId) or is_null($waybillCharge)){
  954. return ['success'=>'false','fail_info'=>'参数异常'];
  955. }
  956. $result = Waybill::where('id',$wayBillId)->update(['charge'=>$waybillCharge]);
  957. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  958. return ['success'=>$result,'status'=>$result];
  959. }
  960. // 置顶
  961. public function waybillOnTop(Request $request){
  962. $id = $request->input('id');
  963. $detail = $request->input('detail');
  964. if(!Gate::allows('运输管理-运单-置顶')){return ['success'=>'false','fail_info'=>'没有权限'];}
  965. if(is_null($id)){
  966. return ['success'=>'false','fail_info'=>'传参错误'];
  967. }
  968. $wayontop = WaybillOnTop::withTrashed()->where('waybill_id',$id);
  969. if(count($wayontop->get()) == 0){
  970. $wayontop = WaybillOnTop::create(['waybill_id'=>$id,'remark'=>$detail]);
  971. $result = $wayontop->save();
  972. }else{
  973. $result = WaybillOnTop::withTrashed()->where('waybill_id',$id)->restore();
  974. }
  975. return ['success'=>$result,'status'=>$result];
  976. }
  977. // 取消置顶
  978. public function cancelOnTop(Request $request){
  979. $id = $request->input('id');
  980. if(!Gate::allows('运输管理-运单-置顶')){return ['success'=>'false','fail_info'=>'没有权限'];}
  981. if(is_null($id)){
  982. return ['success'=>'false','fail_info'=>'传参错误'];
  983. }
  984. $result = WaybillOnTop::where('waybill_id',$id)->forceDelete();
  985. return ['success'=>$result,'status'=>$result];
  986. }
  987. //同步刷新仓库计重
  988. public function refreshWaveHouseWeight(Request $request){
  989. $wms_bill_number=$request->input('wms_bill_number');
  990. if(is_null($wms_bill_number)) return ['success'=>false,'fail_info'=>'传参错误'];
  991. $waybills=DB::connection('oracle')->table('DOC_ORDER_DETAILS')->where('orderno',$wms_bill_number)->get();
  992. if($waybills->isEmpty()) return ['success'=>false,'fail_info'=>'传参错误'];
  993. $warehouseWeight=0;
  994. foreach ($waybills as $waybill){
  995. if ($waybill->grossweight) $warehouseWeight += $waybill->grossweight;
  996. if (!$waybill->grossweight&& $waybill->netweight) $warehouseWeight +=$waybill->netweight;
  997. }
  998. $warehouseWeight=round($warehouseWeight,2);
  999. $waybill=Waybill::where('wms_bill_number',$wms_bill_number)->first();
  1000. if ($warehouseWeight!=0){
  1001. if ($waybill['warehouse_weight_other']!=$warehouseWeight){
  1002. $waybill['warehouse_weight_other']=$warehouseWeight;
  1003. $waybill->update();
  1004. app('LogService')->log(__METHOD__,'刷新仓库计重'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  1005. }
  1006. }else{
  1007. $warehouseWeight=$waybill['warehouse_weight_other'];
  1008. }
  1009. return ['success'=>true,'warehouseWeight'=>$warehouseWeight];
  1010. }
  1011. //寻找订单
  1012. public function seekOrder()
  1013. {
  1014. $this->gate("运输管理");
  1015. $code = request("code");
  1016. if (!$code)$this->error("暂无绑定订单");
  1017. $order = app("OrderService")->first(["code"=>$code]);
  1018. if (!$order)$this->error("暂无绑定订单");
  1019. $this->success($order);
  1020. }
  1021. //按日输入专线费
  1022. public function dailyBilling(Request $request): array
  1023. {
  1024. if(!Gate::allows('运输管理-运单-按日计算专线费')){return ['success'=>false,'message'=>'没有权限'];}
  1025. $dailyBilling=$request->input('param');
  1026. $waybills=app('waybillService')->dailyBilling($dailyBilling);
  1027. if ($waybills=='无数据')return ['success'=>false,'message'=>'当前选定发货日期没有任何记录'];
  1028. if (!isset($waybills))return ['success'=>false,'message'=>'该日有记录未填写重量'];
  1029. return ['success'=>true,'data'=>$waybills];
  1030. }
  1031. public function countPickUpFee(Request $request): array
  1032. {
  1033. if(!Gate::allows('运输管理-运单-查询')){ return ['success'=>false,'message'=>'没有权限']; }
  1034. $param=$request->input('param');
  1035. $waybills=app('waybillService')->get($param);
  1036. $total_pick_up_fee=$waybills->sum('pick_up_fee');
  1037. if ($total_pick_up_fee)$total_pick_up_fee=round($total_pick_up_fee);
  1038. return ['success'=>true,'data'=>$total_pick_up_fee];
  1039. }
  1040. /**
  1041. * 运单合并
  1042. */
  1043. public function waybillMerge(Request $request)
  1044. {
  1045. $this->gate("运输管理-编辑");
  1046. $ids = $request->input("ids");
  1047. if (!$ids || count($ids)<2)$this->error("至少选择两条记录");
  1048. /** @var Collection $waybills */
  1049. $waybills = Waybill::query()->with("order")->whereIn("id",$ids)->orderBy("order_id")->get();
  1050. if ($waybills->count()<2)$this->error("运单不存在");
  1051. $waybill = $waybills->first();
  1052. $destroys = [];
  1053. $owner = [$waybill->owner_id];
  1054. if (array_search($waybill->status,["未审核","已审核","待终审"])===false)$this->error("运单禁止合并");
  1055. for ($i=1;$i<$waybills->count();$i++){
  1056. //信息一致性校验
  1057. $identical = ($waybill->order && ($waybills[$i]->order->consignee_name!=$waybill->order->consignee_name
  1058. || $waybills[$i]->order->consignee_phone!=$waybill->order->consignee_phone
  1059. || $waybills[$i]->order->address!=$waybill->order->address)) ||
  1060. (!$waybill->order && ($waybills[$i]->recipient!=$waybill->recipient
  1061. || $waybills[$i]->recipient_mobile!=$waybill->recipient_mobile
  1062. || $waybills[$i]->destination!=$waybill->destination));
  1063. if (array_search($waybills[$i]->status,["未审核","已审核"])===false
  1064. || $identical)$this->error("信息不一致,无法进行合并");
  1065. $destroys[] = $waybills[$i]->id;
  1066. $waybill->source_bill .= $waybills[$i]->source_bill ? ",".$waybills[$i]->source_bill : '';
  1067. $waybill->wms_bill_number .= $waybills[$i]->wms_bill_number ? ",".$waybills[$i]->wms_bill_number : '';
  1068. $waybill->charge += (double)$waybills[$i]->charge;
  1069. $waybill->collect_fee += (double)$waybills[$i]->collect_fee;
  1070. $waybill->other_fee += (double)$waybills[$i]->other_fee;
  1071. $waybill->warehouse_weight_other += (double)$waybills[$i]->warehouse_weight_other;
  1072. $waybill->warehouse_weight += (double)$waybills[$i]->warehouse_weight;
  1073. $waybill->ordering_remark = $waybill->ordering_remark ? $waybill->ordering_remark.",".$waybills[$i]->ordering_remark : $waybills[$i]->ordering_remark;
  1074. $owner[] = $waybills[$i]->owner_id;
  1075. }
  1076. if (strlen($waybill->source_bill)>191 || strlen($waybill->wms_bill_number)>191)$this->error("单号超长,无法合并");
  1077. $owner = array_unique($owner);
  1078. if (count($owner)>1)$waybill->merge_owner = implode(',',$owner);
  1079. $waybill->update();
  1080. Waybill::destroy($destroys);
  1081. WaybillAuditLog::query()->create([
  1082. 'waybill_id'=>$waybill->id,
  1083. 'audit_stage'=>'合并运单',
  1084. 'user_id'=>Auth::id(),
  1085. ]);
  1086. $this->success($waybill->waybill_number);
  1087. }
  1088. /**
  1089. * 运单拆分
  1090. */
  1091. public function waybillSplit(Request $request)
  1092. {
  1093. $this->gate("运输管理-编辑");
  1094. $ids = $request->input("ids");
  1095. DB::beginTransaction();
  1096. try {
  1097. /** @var Collection $waybills */
  1098. $waybills = Waybill::query()->whereHas("waybillAuditLogs",function ($query){
  1099. $query->where("audit_stage","合并运单");
  1100. })->whereIn("id",$ids)->get();
  1101. if ($waybills->count()==0)$this->error("运单不存在或非合并运单");
  1102. foreach ($waybills as $waybill){
  1103. $codes = explode(",",$waybill->wms_bill_number);
  1104. $bills = explode(",",$waybill->source_bill);
  1105. $remark = explode(",",$waybill->ordering_remark);
  1106. if (!$codes)continue;
  1107. /** @var Collection $destroys */
  1108. foreach (Waybill::onlyTrashed()->whereIn("wms_bill_number",$codes)->get() as $obj){
  1109. unset($codes[array_search($obj->wms_bill_number,$codes)]);
  1110. unset($bills[array_search($obj->source_bill,$bills)]);
  1111. if (array_search($obj->ordering_remark,$remark)===false)unset($bills[array_search($obj->ordering_remark,$remark)]);
  1112. $waybill->charge -= (double)$obj->charge;
  1113. $waybill->collect_fee -= (double)$obj->collect_fee;
  1114. $waybill->other_fee -= (double)$obj->other_fee;
  1115. $waybill->warehouse_weight_other -= (double)$obj->warehouse_weight_other;
  1116. $waybill->warehouse_weight -= (double)$obj->warehouse_weight;
  1117. }
  1118. Waybill::onlyTrashed()->whereIn("wms_bill_number",explode(",",$waybill->wms_bill_number))->restore();
  1119. $waybill->merge_owner = null;
  1120. $waybill->source_bill = implode(",",$bills);
  1121. $waybill->wms_bill_number = implode(",",$codes);
  1122. $waybill->ordering_remark = implode(",",$remark);
  1123. $waybill->update();
  1124. WaybillAuditLog::query()->create([
  1125. 'waybill_id'=>$waybill->id,
  1126. 'audit_stage'=>'拆单返回',
  1127. 'user_id'=>Auth::id(),
  1128. ]);
  1129. }
  1130. DB::commit();
  1131. }catch (\Exception $e){
  1132. DB::rollBack();
  1133. $this->error($e->getMessage());
  1134. }
  1135. $this->success(count($ids)==$waybills->count() ? '运单拆单完毕' : '部分运单不符合拆单条件');
  1136. }
  1137. /**
  1138. * 快递面单打印 :暂时支持 德邦
  1139. */
  1140. public function expressFaceList(Request $request)
  1141. {
  1142. $this->gate("运输管理-编辑");
  1143. $ids = $request->input("ids");
  1144. try {
  1145. /** @var Collection $waybills */
  1146. $waybills = Waybill::query()->where('type','德邦物流')
  1147. ->whereIn("id",$ids)
  1148. ->whereHas("waybillAuditLogs",function ($query){
  1149. $query->where("audit_stage","发起德邦调度");
  1150. })
  1151. ->get();
  1152. if ($waybills->count()==0)$this->error("运单不存在或运单类型不正确");
  1153. foreach ($waybills as $waybill){
  1154. $waybill->loadMissing([
  1155. "order.shop","destinationCity","owner","order.warehouse.province","order.warehouse.city","order.warehouse.county","deliveryType"
  1156. ]);
  1157. }
  1158. }catch (\Exception $e){
  1159. $this->error($e->getMessage());
  1160. }
  1161. if (count($ids)==$waybills->count())$this->success($waybills );
  1162. $this->error('非德邦快递不可打印');
  1163. }
  1164. public function changeExpressTag(Request $request)
  1165. {
  1166. $this->gate("运输管理-编辑");
  1167. $id = $request->input("id");
  1168. try {
  1169. $row = Waybill::where('waybill_number',$id)->update(['express_face_list'=>1, 'updated_at'=>date('Y-m-d H:i:s')]);
  1170. if ($row) $this->success('打印成功');
  1171. }catch (\Exception $e){
  1172. $this->error($e->getMessage());
  1173. }
  1174. $this->error('打印失败');
  1175. }
  1176. /**
  1177. * 运输发货在PC-APP上临时入口
  1178. */
  1179. public function shipment()
  1180. {
  1181. $logistics = app("LogisticService")->getSelection(['id','name','tag'],"物流");
  1182. return view("transport.waybill.android.shipment",compact("logistics"));
  1183. }
  1184. /**
  1185. * 发货与合并
  1186. */
  1187. public function shipmentAndMerge()
  1188. {
  1189. $this->gate("运输管理-编辑");
  1190. if (!\request("logistic"))$this->error("未选择承运商");
  1191. $waybill = Waybill::query()->where("waybill_number",\request("waybill"))->whereNull("deliver_at")
  1192. ->whereNotIn("status",["已完结","无模型"])->first();
  1193. if (!$waybill)$this->error("运单禁止操作");
  1194. if ($waybill->deliver_at)$this->error("运单已发货,请勿重复调配");
  1195. $codes = explode("\n",\request("order"));
  1196. $waybills = Waybill::query()->whereIn("wms_bill_number",$codes)
  1197. ->where("id","!=",$waybill->id)
  1198. ->whereNull("deliver_at")
  1199. ->whereNotIn("status",["已完结","无模型"])->get();
  1200. if ($waybills->count()){
  1201. if ($waybills->count()<count($codes)-1)$this->error("存在非法订单");
  1202. $destroys = [];
  1203. $owner = [$waybill->owner_id];
  1204. foreach ($waybills as $item){
  1205. //信息一致性校验
  1206. $identical = ($waybill->order && ($item->order->consignee_name!=$waybill->order->consignee_name
  1207. || $item->order->consignee_phone!=$waybill->order->consignee_phone
  1208. || $item->order->address!=$waybill->order->address)) ||
  1209. (!$waybill->order && ($item->recipient!=$waybill->recipient
  1210. || $item->recipient_mobile!=$waybill->recipient_mobile
  1211. || $item->destination!=$waybill->destination));
  1212. if ($identical)$this->error("订单信息不一致,无法统一发货");
  1213. $destroys[] = $item->id;
  1214. $waybill->source_bill .= $item->source_bill ? ",".$item->source_bill : '';
  1215. $waybill->wms_bill_number .= $item->wms_bill_number ? ",".$item->wms_bill_number : '';
  1216. $waybill->charge += (double)$item->charge;
  1217. $waybill->collect_fee += (double)$item->collect_fee;
  1218. $waybill->other_fee += (double)$item->other_fee;
  1219. $waybill->warehouse_weight_other += (double)$item->warehouse_weight_other;
  1220. $waybill->warehouse_weight += (double)$item->warehouse_weight;
  1221. $waybill->ordering_remark = $waybill->ordering_remark ? $waybill->ordering_remark.",".$item->ordering_remark : $item->ordering_remark;
  1222. $owner[] = $item->owner_id;
  1223. }
  1224. if (strlen($waybill->source_bill)>191 || strlen($waybill->wms_bill_number)>191)$this->error("单号超长,无法合并");
  1225. $owner = array_unique($owner);
  1226. if (count($owner)>1)$waybill->merge_owner = implode(',',$owner);
  1227. $waybill->deliver_at = date("Y-m-d H:i:s");
  1228. if ($waybill->status=='未审核')$waybill->status = '已审核';
  1229. $waybill->update();
  1230. Waybill::destroy($destroys);
  1231. WaybillAuditLog::query()->create([
  1232. 'waybill_id'=>$waybill->id,
  1233. 'audit_stage'=>'合并运单',
  1234. 'user_id'=>Auth::id(),
  1235. ]);
  1236. WaybillAuditLog::query()->create([
  1237. 'waybill_id'=>$waybill->id,
  1238. 'audit_stage'=>'合单发货',
  1239. 'user_id'=>Auth::id(),
  1240. ]);
  1241. }else{
  1242. WaybillAuditLog::query()->create([
  1243. 'waybill_id'=>$waybill->id,
  1244. 'audit_stage'=>'单独发货',
  1245. 'user_id'=>Auth::id(),
  1246. ]);
  1247. $update = ["deliver_at"=>date("Y-m-d H:i:s"),"logistic_id"=>\request("logistic")];
  1248. if ($waybill->status=='未审核')$update["status"] = '已审核';
  1249. $waybill->update($update);
  1250. }
  1251. $this->success();
  1252. }
  1253. /**
  1254. * 运输发货在PC-APP上临时入口
  1255. */
  1256. public function waybillDispatch()
  1257. {
  1258. return view("transport.waybill.android.dispatch");
  1259. }
  1260. /**
  1261. * 搜索运单获取信息
  1262. */
  1263. public function searchWaybill()
  1264. {
  1265. $this->success($this->dispatchCheck(\request("bill")));
  1266. }
  1267. private function dispatchCheck($bill)
  1268. {
  1269. if (!$bill)$this->error("参数异常");
  1270. $waybill = Waybill::query()->select(["id","carrier_bill","inquire_tel","carrier_weight_other","carrier_weight","amount","deliver_at"])
  1271. ->where("waybill_number",$bill)->whereNotIn("status",["已完结","无模型"])->first();
  1272. if(!$waybill)$this->error("非法运单号");
  1273. if ($waybill->carrier_bill)$this->error("运单已发货,请勿重复调配");
  1274. if (!$waybill->deliver_at)$this->error("运单未发货,无法调配");
  1275. return $waybill;
  1276. }
  1277. /**
  1278. * 调配
  1279. *
  1280. */
  1281. public function dispatchSubmit()
  1282. {
  1283. $this->gate("运输管理-编辑");
  1284. if (!\request("waybill") || !\request("phone")
  1285. || !\request("volume") || !\request("weight") || !\request("amount"))$this->error("非法参数");
  1286. $waybill = $this->dispatchCheck(\request("waybill"));
  1287. $unit = app("UnitService")->getUnit("kg");
  1288. $unit1 = app("UnitService")->getUnit("件");
  1289. $waybill->update([
  1290. "carrier_bill" => \request("waybill"),
  1291. "inquire_tel" => \request("phone"),
  1292. "carrier_weight_other" => \request("volume"),
  1293. "carrier_weight" => \request("weight"),
  1294. "amount" => \request("amount"),
  1295. "amount_unit_id" => $unit->id,
  1296. "carrier_weight_unit_id" => $unit->id,
  1297. "carrier_weight_unit_id_other" => $unit1->id,
  1298. ]);
  1299. WaybillAuditLog::query()->create([
  1300. 'waybill_id'=>$waybill->id,
  1301. 'audit_stage'=>'调度阶段',
  1302. 'user_id'=>Auth::id(),
  1303. ]);
  1304. $this->success();
  1305. }
  1306. public function appendSubjoinFee()
  1307. {
  1308. $this->gate("运输管理-编辑");
  1309. $id = \request("id");
  1310. $subjoinFee = \request("subjoinFee");
  1311. if (!$id || !$subjoinFee)$this->error("非法参数");
  1312. if (Waybill::query()->where("id",$id)->update(["subjoin_fee"=>$subjoinFee]) == 0)$this->error("修改失败,运单信息发送变更");
  1313. LogService::log("运输附加费","调度商添加","录入人:".Auth::id()." | 修改费用{$id}为:".$subjoinFee);
  1314. $this->success();
  1315. }
  1316. }