WaybillController.php 71 KB

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