WaybillController.php 71 KB

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