WaybillController.php 71 KB

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