WaybillService.php 17 KB

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