WaybillController.php 73 KB

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