WaybillService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <?php
  2. namespace App\Services;
  3. use App\Http\Controllers\api\thirdPart\flux\WaybillController;
  4. use App\Logistic;
  5. use App\Order;
  6. use App\OwnerFeeDetail;
  7. use App\OwnerFeeLogistic;
  8. use App\Services\common\BatchUpdateService;
  9. use App\Services\common\QueryService;
  10. use App\Traits\ModelSearchWay;
  11. use App\Waybill;
  12. use App\WaybillAuditLog;
  13. use Carbon\Carbon;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Database\Eloquent\Model;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Support\Facades\Auth;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Log;
  20. use Ramsey\Uuid\Uuid;
  21. use App\Traits\ServiceAppAop;
  22. class WaybillService
  23. {
  24. use ServiceAppAop;
  25. use ModelSearchWay;
  26. protected $modelClass=Waybill::class;
  27. /**
  28. * @param array $param
  29. * @return Builder
  30. */
  31. private function conditionQuery(array $param){
  32. $waybills = Waybill::filterAuthorities()->with(['owner','logistic','originationCity','destinationCity.parent',
  33. 'uploadFiles','amountUnit','warehouseWeightUnit','carrierWeightUnit','district','order',
  34. 'warehouseWeightUnitOther','carrierWeightUnitOther','carType','uploadFiles','waybillAuditLogs.user'])
  35. ->selectRaw('waybills.* ,waybill_on_tops.id top_id ,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
  36. ->leftJoin('waybill_on_tops','waybill_on_tops.waybill_id','=','waybills.id')
  37. ->whereNull('waybill_on_tops.deleted_at')
  38. ->orderBy('waybill_on_tops.updated_at','desc')
  39. ->orderBy('waybills.id','desc');
  40. if ($param["owner"] ?? false){
  41. $ownerIds = explode(",",$param["owner"]);
  42. $waybills->where(function ($query)use($ownerIds){
  43. /** @var Builder $query */
  44. $query->whereIn("waybills.owner_id",$ownerIds)->orWhereHas("order",function ($query)use($ownerIds){
  45. /** @var Builder $query */
  46. $query->whereIn("owner_id",$ownerIds);
  47. });
  48. });
  49. unset($param["owner"]);
  50. }
  51. if ($param["destination"] ?? false){
  52. $destination = $param["destination"];
  53. $waybills->where(function ($query)use($destination){
  54. /** @var Builder $query */
  55. $query->where("waybills.destination","like",$destination."%")->orWhereHas("order",function ($query)use($destination){
  56. /** @var Builder $query */
  57. $query->where("address",'like',$destination."%");
  58. });
  59. });
  60. unset($param["destination"]);
  61. }
  62. if ($param["recipient"] ?? false){
  63. $recipient = $param["recipient"];
  64. $waybills->where(function ($query)use($recipient){
  65. if (strpos($recipient, ',') || strpos($recipient, ',') || strpos($recipient, ' ')) {
  66. $arr = array_filter(preg_split('/[,, ]+/is', $recipient));
  67. /** @var Builder $query */
  68. $query->whereIn("waybills.recipient",$arr)->orWhereHas("order",function ($query)use($arr){
  69. /** @var Builder $query */
  70. $query->whereIn("consignee_name",$arr);
  71. });
  72. } else {
  73. /** @var Builder $query */
  74. $query->where("waybills.recipient","like",$recipient."%")->orWhereHas("order",function ($query)use($recipient){
  75. /** @var Builder $query */
  76. $query->where("consignee_name",'like',$recipient."%");
  77. });
  78. }
  79. });
  80. unset($param["recipient"]);
  81. }
  82. if ($param["recipient_mobile"] ?? false){
  83. $recipientMobile = $param["recipient_mobile"];
  84. $waybills->where(function ($query)use($recipientMobile){
  85. if (strpos($recipientMobile, ',') || strpos($recipientMobile, ',') || strpos($recipientMobile, ' ')) {
  86. $arr = array_filter(preg_split('/[,, ]+/is', $recipientMobile));
  87. /** @var Builder $query */
  88. $query->whereIn("waybills.recipient_mobile",$arr)->orWhereHas("order",function ($query)use($arr){
  89. /** @var Builder $query */
  90. $query->whereIn("consignee_phone",$arr);
  91. });
  92. } else {
  93. /** @var Builder $query */
  94. $query->where("waybills.recipient_mobile","like",$recipientMobile."%")->orWhereHas("order",function ($query)use($recipientMobile){
  95. /** @var Builder $query */
  96. $query->where("consignee_phone",'like',$recipientMobile."%");
  97. });
  98. }
  99. });
  100. unset($param["recipient_mobile"]);
  101. }
  102. if (($param["updated_at_start"] ?? false) || ($param["updated_at_end"] ?? false)){
  103. $waybills->whereIn("waybills.status",['已完结','无模型']);
  104. }
  105. if ($param["mileage"] ?? false){
  106. $param["mileage"] = explode("-",$param["mileage"]);
  107. $waybills->whereBetween("mileage",[(int)$param["mileage"][0] ?? 0,(int)$param["mileage"][1]] ?? 0);
  108. unset($param["mileage"]);
  109. }
  110. if ($param["warehouse_weight_other"] ?? false){
  111. $param["warehouse_weight_other"] = explode("-",$param["warehouse_weight_other"]);
  112. $waybills->whereBetween("warehouse_weight_other",[(int)$param["warehouse_weight_other"][0] ?? 0,(int)$param["warehouse_weight_other"][1]] ?? 0);
  113. unset($param["warehouse_weight_other"]);
  114. }
  115. $columnQueryRules=[
  116. 'waybill_number' => ['batch' => ''],
  117. 'carrier_bill' => ['batch' => ''],
  118. 'wms_bill_number' => ['batch' => ''],
  119. 'origination' => ['batch' => ''],
  120. 'source_bill' => ['batch' => ''],
  121. 'car_owner_info' => ['batch' => ''],
  122. 'created_at_start' => ['alias' => 'created_at' , 'startDate' => ':00'],
  123. 'created_at_end' => ['alias' => 'created_at' , 'endDate' => ':59'],
  124. 'updated_at_start' => ['alias' => 'updated_at' , 'startDate' => ':00'],
  125. 'updated_at_end' => ['alias' => 'updated_at' , 'endDate' => ':59'],
  126. 'deliver_at_start' => ['alias' => 'deliver_at' , 'startDate' => ':00'],
  127. 'deliver_at_end' => ['alias' => 'deliver_at' , 'endDate' => ':59'],
  128. 'uriType' => ['alias' => 'type'],
  129. 'id' => ['multi' => ','],
  130. 'logistic' => ['alias' => 'logistic_id', 'multi' => ','],
  131. 'ordering_remark' => ['like' => '%'],
  132. ];
  133. return app(QueryService::class)->query($param,$waybills,$columnQueryRules,"waybills");
  134. }
  135. public function paginate(array $param){
  136. $waybills = $this->conditionQuery($param);
  137. return $waybills->paginate($param['paginate'] ?? 50);
  138. }
  139. public function get(array $param){
  140. $waybills = $this->conditionQuery($param);
  141. return $waybills->get();
  142. }
  143. public function dailyBilling(array $param, bool $isOnlyLogistic = false){
  144. if (($param['screenDate']??false)==false || ($param['billing']??false)==false) return 0; //入参错误
  145. $waybills = Waybill::query()->with(['owner','logistic','originationCity','destinationCity.parent',
  146. 'uploadFiles','amountUnit','warehouseWeightUnit','carrierWeightUnit','district','order',
  147. 'warehouseWeightUnitOther','carrierWeightUnitOther','carType','waybillAuditLogs.user'])
  148. ->selectRaw('waybills.* ,waybill_on_tops.id top_id,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
  149. ->leftJoin('waybill_on_tops','waybill_on_tops.waybill_id','=','waybills.id')
  150. ->whereNull('waybill_on_tops.deleted_at')
  151. ->orderBy('waybill_on_tops.updated_at','desc')
  152. ->orderBy('waybills.id','desc')
  153. ->where('waybills.type','专线')
  154. ->where('waybills.amount','>',0)
  155. ->where('waybills.deliver_at','like',$param['screenDate'].'%');
  156. if ($isOnlyLogistic)$waybills->whereIn("logistic_id",app("LogisticService")->getQuery());
  157. $waybills = $waybills->get();
  158. if ($waybills->isEmpty()) return 1;//无数据
  159. foreach ($waybills as $waybill){
  160. if (!$waybill['carrier_weight_other'] && !$waybill['carrier_weight']) return null;
  161. if (!$waybill['carrier_weight_other'] || $waybill['carrier_weight_other']<=0) $waybill['carrier_weight_other']=($waybill['carrier_weight']/0.25*100);
  162. }
  163. $daily_total_weight=$waybills->sum('carrier_weight_other');
  164. $updateParams = [['id','pick_up_fee','updated_at']];
  165. foreach ($waybills as $waybill){
  166. $waybill['pick_up_fee']=round(($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']);
  167. $updateParams[] = [
  168. 'id' => $waybill->id,
  169. 'pick_up_fee' =>(($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']),
  170. 'updated_at' => Carbon::now()->toDateTimeString(),
  171. ];
  172. }
  173. if (count($updateParams)>0)app(BatchUpdateService::class)->batchUpdate('waybills', $updateParams);
  174. return $waybills;
  175. }
  176. public function store(Request $request){
  177. return DB::transaction(function ()use($request){
  178. $waybill=new Waybill();
  179. $inputs = $request->all();
  180. $inputs['status']='未审核';
  181. $inputs['waybill_number']=Uuid::uuid1();
  182. $waybill->fill($inputs);
  183. if ($request->collect_fee)$waybill->collect_fee=$request->collect_fee;
  184. $waybill->save();
  185. $number_id=$waybill->id;
  186. if ($request->type=='直发车') $waybill_number='BSZF';
  187. else $waybill_number='BSZX';
  188. $waybill_number .= date ("ymd").str_pad($number_id>99999?$number_id%99999:$number_id,4,"0",STR_PAD_LEFT);
  189. $waybill->update(['waybill_number' => $waybill_number ]);
  190. WaybillAuditLog::query()->create([
  191. 'waybill_id'=>$waybill->id,
  192. 'audit_stage'=>'创建',
  193. 'user_id'=>Auth::id() ?? 0,
  194. ]);
  195. return $waybill;
  196. });
  197. }
  198. public function find($id){
  199. return Waybill::query()->find($id);
  200. }
  201. /**
  202. * 修改物流单
  203. *
  204. * @param Waybill|\stdClass $waybill
  205. * @param array $param
  206. *
  207. * @return Model
  208. */
  209. public function update(Waybill $waybill,array $param)
  210. {
  211. //替换换行符
  212. if ($param["dispatch_remark"] ?? false)$param["dispatch_remark"] = str_replace(["\n","\r"], ' ', $param["dispatch_remark"]);
  213. if (!($param["destination"] ?? false)) $param["destination"] = $waybill->destination;
  214. $waybill->fill($param);
  215. $waybill->update();
  216. return $waybill;
  217. }
  218. public function getDeliveringSql(array $param){
  219. $waybills = $this->conditionQuery($param);
  220. if (!Auth::user()->isSuperAdmin()){
  221. $users=DB::table('logistic_user')->where('user_id',Auth::id())->get();
  222. $userIds=array_column($users->toArray(),'logistic_id');
  223. $waybills=$waybills->whereIn("waybills.logistic_id",$userIds);
  224. }
  225. return $waybills->leftJoin('owners','owners.id','=','waybills.owner_id')->selectRaw('owners.name owner_name')
  226. ->leftJoin('logistics','logistics.id','=','waybills.logistic_id')
  227. ->selectRaw('logistics.name carrier_name')
  228. ->sql();
  229. }
  230. public function createInstantBill(Waybill $waybill) :bool
  231. {
  232. /** @var \stdClass $waybill */
  233. if (!$waybill || $waybill->status != "已完结" || !$waybill->wms_bill_number || !$waybill->logistic_id)return false;
  234. $waybill->loadMissing(["destinationCity","order.owner"]);
  235. if (!$waybill->destinationCity && !$waybill->order)return false;
  236. $owner_id = $waybill->order->owner_id ?? $waybill->owner_id;
  237. $detail = OwnerFeeDetail::query()->where("type","发货")
  238. ->where("owner_id",$owner_id)->whereIn("operation_bill",[$waybill->wms_bill_number,$waybill->waybill_number])->first();
  239. if ($detail && $detail->logistic_fee !== null)return false;
  240. if ($waybill->type == "专线"){
  241. $provinceId = $waybill->order ? app("ProvinceService")->getProvince($waybill->order->province) : $waybill->destinationCity->province_id;
  242. $cityId = $waybill->destination_city_id;
  243. $consigneeName = $waybill->order ? $waybill->order->consignee_name : $waybill->recipient;
  244. $consigneePhone = $waybill->order ? $waybill->order->consignee_phone : $waybill->recipient_mobile;
  245. $GLOBALS["FEE_INFO"] = [
  246. "province_id" => $provinceId,
  247. "owner_id" => $waybill->owner_id,
  248. "city_id" => $cityId,
  249. "logistic_id" => $waybill->logistic_id,
  250. "order_number" => $waybill->wms_bill_number,
  251. "recipient_name"=>$consigneeName,
  252. "recipient_phone"=>$consigneePhone,
  253. "quantity"=>$waybill->carrier_weight_other,
  254. "unit_id"=>$waybill->carrier_weight_unit_id_other,
  255. "remark"=>$waybill->ordering_remark,
  256. "created_at"=>$waybill->updated_at,
  257. ];
  258. /** @var OwnerPriceLogisticService $service */
  259. $service = app("OwnerPriceLogisticService");
  260. list($fee,$taxFee) = $service->matching($waybill->carrier_weight_other,$owner_id,$waybill->logistic_id,
  261. $waybill->carrier_weight_unit_id_other,$provinceId, $cityId);
  262. $this->buildWaybillFeeInfo();
  263. }else{
  264. /** @var OwnerPriceDirectLogisticService $service */
  265. $service = app("OwnerPriceDirectLogisticService");
  266. list($fee,$taxFee) = $service->matching($waybill->mileage,$owner_id,$waybill->carType_id);
  267. }
  268. $obj = [
  269. "owner_id" => $owner_id,
  270. "worked_at"=> $waybill->updated_at,
  271. "type" => "发货",
  272. "operation_bill" => $waybill->waybill_number,
  273. "province" => $waybill->order_id ? ($waybill->order->province ?? '') : ($waybill->destinationCity->parent->name ?? ''),
  274. "consignee_name" => $waybill->recipient,
  275. "consignee_phone" => $waybill->recipient_mobile,
  276. "commodity_amount" => $waybill->amount,
  277. "logistic_bill" => $waybill->carrier_bill,
  278. "volume" =>$waybill->carrier_weight ?? $waybill->warehouse_weight,
  279. "weight" => $waybill->carrier_weight_other ?? $waybill->warehouse_weight_other,
  280. "logistic_id" => $waybill->logistic_id,
  281. "logistic_fee" => $fee,
  282. "outer_id" => $waybill->id,
  283. "outer_table_name" => "waybills",
  284. "logistic_tax_fee" => $taxFee,
  285. ];
  286. if ($detail)app("OwnerFeeDetailService")->updateFind($detail,$obj);
  287. else OwnerFeeDetail::query()->create($obj);
  288. return true;
  289. }
  290. /**
  291. * 构建运输费用信息
  292. */
  293. public function buildWaybillFeeInfo()
  294. {
  295. if (!isset($GLOBALS["FEE_INFO"]))return;
  296. OwnerFeeLogistic::query()->create($GLOBALS["FEE_INFO"]);
  297. }
  298. /**
  299. * 生成德邦单据
  300. *
  301. * @param Order|\stdClass $order
  302. *
  303. * @return void
  304. */
  305. public function createDbBill(Order $order)
  306. {
  307. $order->loadMissing("logistic");
  308. if (!$order->logistic || substr($order->logistic->code,0,2) != 'DB')return;
  309. if (Waybill::query()->selectRaw("1")->where("wms_bill_number",$order->code)->first())return;
  310. $waybill = Waybill::query()->create([
  311. 'type'=> "德邦物流",
  312. 'waybill_number'=> Uuid::uuid1(),
  313. 'owner_id'=> $order->owner_id,
  314. 'wms_bill_number'=> $order->code,
  315. 'destination'=> $order->address,
  316. 'recipient'=> $order->consignee_name,
  317. 'recipient_mobile'=>$order->consignee_phone,
  318. 'source_bill'=> $order->client_code,
  319. 'is_to_pay'=> strstr($order->logistic->code,'DF')===false ? 0 : 1,
  320. 'destination_city_id'=>$order->city ? app(RegionService::class)->getCity($order->city) : null,
  321. 'order_id'=> $order->id,
  322. ]);
  323. $waybill->update([
  324. "waybill_number" => 'BSDB'.date ("ymd").str_pad($waybill->id>99999?$waybill->id%99999:$waybill->id,4,"0",STR_PAD_LEFT),
  325. ]);
  326. WaybillAuditLog::query()->create([
  327. 'waybill_id'=>$waybill->id,
  328. 'audit_stage'=>'创建',
  329. 'user_id'=>Auth::id() ?? 0,
  330. ]);
  331. }
  332. /**
  333. * 通知FLUX新单号
  334. *
  335. * @param Model|\stdClass $waybill
  336. *
  337. * @return bool
  338. */
  339. public function notifyFlux($waybill):bool
  340. {
  341. /** @var Waybill|\stdClass $w */
  342. $w = new Waybill();
  343. $w->wms_bill_number = $waybill->wms_bill_number;
  344. $w->waybill_number = $waybill->carrier_bill;
  345. $controller = new WaybillController();
  346. if ($controller->accomplishToWMS($w)){
  347. $sql = <<<SQL
  348. UPDATE ACT_ALLOCATION_DETAILS SET PICKTOTRACEID = ?,DROPID = ? WHERE ORDERNO = ?
  349. SQL;
  350. $updateRow = DB::connection("oracle")->update($sql,[
  351. $waybill->carrier_bill,$waybill->carrier_bill,$waybill->wms_bill_number
  352. ]);
  353. if ($updateRow==0)Log::warning("德邦单号修改分配失败",["param"=>$w,"row"=>$updateRow]);
  354. return true;
  355. }
  356. return false;
  357. }
  358. /**
  359. * 获取调度数据
  360. *
  361. */
  362. public function getDispatchQuery():Builder
  363. {
  364. return Waybill::query()->with(["order:id,address","logistic:id,name","amountUnit:id,name"])
  365. ->select("id","order_id","logistic_id","amount_unit_id","deliver_at",
  366. "waybill_number","destination","recipient","recipient_mobile",
  367. "carrier_bill","warehouse_weight","carrier_weight","inquire_tel",
  368. "warehouse_weight_other","carrier_weight_other","amount","origination")->where(function ($query){
  369. /** @var Builder $query */
  370. $query->whereIn("owner_id",app("OwnerService")->getQuery())
  371. ->orWhereIn("logistic_id",app("LogisticService")->getQuery());
  372. })->whereNotNull("deliver_at")->whereIn("status",["已审核","待终审"]);
  373. }
  374. public function autoGetDBBill(Waybill $waybill){
  375. if ($waybill->type=='德邦物流'){
  376. if ($waybill->carrier_bill)return;
  377. $waybill->load("order");
  378. if (!$waybill->order){
  379. Log::error("德邦单号获取失败",["no"=>$waybill->waybill_number,"info"=>"运单无绑定订单"]);
  380. return;
  381. }
  382. list($update,$waybill) = $this->paramDefault($waybill);
  383. $bill = app('DbOpenService')->getDbOrderNo($waybill);
  384. if (!$bill || $bill["result"]=="false"){
  385. Log::error("德邦单号获取失败",["no"=>$waybill->toArray(),"info"=>$bill]);
  386. return;
  387. }
  388. $update["carrier_bill"] = $bill['mailNo'];
  389. $update["waybill_number"] = $bill['mailNo'];
  390. $update["station_no"] = $bill['stationNo'];
  391. $update["arrived_org_simple_name"] = $bill['arrivedOrgSimpleName'];
  392. $update["much_higher_delivery"] = $bill['muchHigherDelivery'];
  393. $logistic = Logistic::query()->where("code","DBWL")->first();
  394. $update["logistic_id"] = $logistic->id ?? null;
  395. $waybill->update($update);
  396. if (!app("WaybillService")->notifyFlux($waybill)){
  397. Log::error("德邦单号回传FLUX失败",["no"=>$waybill->waybill_number,"info"=>$bill]);
  398. return;
  399. }
  400. }
  401. }
  402. private function paramDefault($waybill):array
  403. {
  404. $update = [];
  405. if (!$waybill->order_type){
  406. $update["order_type"] = $waybill->order_type = Waybill::ORDER_TYPE_DEFAULT;
  407. }
  408. if (!$waybill->transport_type){
  409. $update["transport_type"] = $waybill->transport_type = "JZKH";
  410. }
  411. if (!$waybill->cargo_name){
  412. $update["cargo_name"] = $waybill->cargo_name = "补货";
  413. }
  414. if (!$waybill->total_number){
  415. $update["total_number"] = $waybill->total_number = 1;
  416. }
  417. if (!$waybill->total_weight){
  418. $update["total_weight"] = $waybill->total_weight = 1;
  419. }
  420. if (!$waybill->package_service){
  421. $update["package_service"] = $waybill->package_service = '托膜';
  422. }
  423. if (!$waybill->deliveryType_id){
  424. $update["deliveryType_id"] = $waybill->deliveryType_id = 3;
  425. }
  426. if (!$waybill->pay_type){
  427. $update["pay_type"] = $waybill->pay_type = Waybill::PAY_TYPE_DEFAULT;
  428. }
  429. if (!$waybill->back_sign_bill){
  430. $update["back_sign_bill"] = $waybill->back_sign_bill = Waybill::BACK_SIGN_BILL_DEFAULT;
  431. }
  432. return array($update,$waybill);
  433. }
  434. }