WaybillController.php 55 KB

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