WaybillController.php 72 KB

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