WaybillController.php 55 KB

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