WaybillController.php 60 KB

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