WaybillController.php 72 KB

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