WaybillController.php 59 KB

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