WaybillController.php 69 KB

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