WaybillController.php 63 KB

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