WaybillController.php 63 KB

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