WaybillController.php 71 KB

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