WaybillController.php 55 KB

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