WaybillController.php 70 KB

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