WaybillController.php 72 KB

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