WaybillController.php 73 KB

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