WaybillController.php 69 KB

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