WaybillController.php 72 KB

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