WaybillService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. $waybills = Waybill::query()->with(['owner','logistic','originationCity','destinationCity.parent',
  143. 'uploadFiles','amountUnit','warehouseWeightUnit','carrierWeightUnit','district','order',
  144. 'warehouseWeightUnitOther','carrierWeightUnitOther','carType','uploadFiles','waybillAuditLogs.user'])
  145. ->selectRaw('waybills.* ,waybill_on_tops.id top_id,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
  146. ->leftJoin('waybill_on_tops','waybill_on_tops.waybill_id','=','waybills.id')
  147. ->whereNull('waybill_on_tops.deleted_at')
  148. ->orderBy('waybill_on_tops.updated_at','desc')
  149. ->orderBy('waybills.id','desc')
  150. ->where('waybills.type','专线')
  151. ->where('waybills.amount','>',0);
  152. if ($param['screenDate'] ?? false)$waybills->where('waybills.deliver_at','like',$param['screenDate'].'%');
  153. $waybills = $waybills->get();
  154. if ($waybills->isEmpty()) return '无数据';
  155. foreach ($waybills as $waybill){
  156. if (!$waybill['carrier_weight_other'] && !$waybill['carrier_weight']) return null;
  157. if (!$waybill['carrier_weight_other'] || $waybill['carrier_weight_other']<=0) $waybill['carrier_weight_other']=($waybill['carrier_weight']/0.25*100);
  158. }
  159. $daily_total_weight=$waybills->sum('carrier_weight_other');
  160. $updateParams = [['id','pick_up_fee','updated_at']];
  161. foreach ($waybills as $waybill){
  162. $waybill['pick_up_fee']=round(($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']);
  163. $updateParams[] = [
  164. 'id' => $waybill->id,
  165. 'pick_up_fee' =>(($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']),
  166. 'updated_at' => Carbon::now()->toDateTimeString(),
  167. ];
  168. }
  169. if (count($updateParams)>0)app(BatchUpdateService::class)->batchUpdate('waybills', $updateParams);
  170. return $waybills;
  171. }
  172. public function store(Request $request){
  173. return DB::transaction(function ()use($request){
  174. $waybill=new Waybill();
  175. $inputs = $request->all();
  176. $inputs['status']='未审核';
  177. $inputs['waybill_number']=Uuid::uuid1();
  178. $waybill->fill($inputs);
  179. if ($request->collect_fee)$waybill->collect_fee=$request->collect_fee;
  180. $waybill->save();
  181. $number_id=$waybill->id;
  182. if ($request->type=='直发车') $waybill_number='BSZF';
  183. else $waybill_number='BSZX';
  184. $waybill_number .= date ("ymd").str_pad($number_id>99999?$number_id%99999:$number_id,4,"0",STR_PAD_LEFT);
  185. $waybill->update(['waybill_number' => $waybill_number ]);
  186. WaybillAuditLog::query()->create([
  187. 'waybill_id'=>$waybill->id,
  188. 'audit_stage'=>'创建',
  189. 'user_id'=>Auth::id() ?? 0,
  190. ]);
  191. return $waybill;
  192. });
  193. }
  194. public function find($id){
  195. return Waybill::query()->find($id);
  196. }
  197. /**
  198. * 修改物流单
  199. *
  200. * @param Waybill|\stdClass $waybill
  201. * @param array $param
  202. *
  203. * @return Model
  204. */
  205. public function update(Waybill $waybill,array $param)
  206. {
  207. //替换换行符
  208. if ($param["dispatch_remark"] ?? false)$param["dispatch_remark"] = str_replace(["\n","\r"], ' ', $param["dispatch_remark"]);
  209. if (!($param["destination"] ?? false)) $param["destination"] = $waybill->destination;
  210. $waybill->fill($param);
  211. $waybill->update();
  212. return $waybill;
  213. }
  214. public function getDeliveringSql(array $param){
  215. $waybills = $this->conditionQuery($param);
  216. if (!Auth::user()->isSuperAdmin()){
  217. $users=DB::table('logistic_user')->where('user_id',Auth::id())->get();
  218. $userIds=array_column($users->toArray(),'logistic_id');
  219. $waybills=$waybills->whereIn("waybills.logistic_id",$userIds);
  220. }
  221. return $waybills->leftJoin('owners','owners.id','=','waybills.owner_id')->selectRaw('owners.name owner_name')
  222. ->leftJoin('logistics','logistics.id','=','waybills.logistic_id')
  223. ->selectRaw('logistics.name carrier_name')
  224. ->sql();
  225. }
  226. public function createInstantBill(Waybill $waybill) :bool
  227. {
  228. /** @var \stdClass $waybill */
  229. if (!$waybill || $waybill->status != "已完结" || !$waybill->wms_bill_number || !$waybill->logistic_id)return false;
  230. $waybill->loadMissing(["destinationCity","order.owner"]);
  231. if (!$waybill->destinationCity && !$waybill->order)return false;
  232. $owner_id = $waybill->order->owner_id ?? $waybill->owner_id;
  233. $detail = OwnerFeeDetail::query()->where("type","发货")
  234. ->where("owner_id",$owner_id)->whereIn("operation_bill",[$waybill->wms_bill_number,$waybill->waybill_number])->first();
  235. if ($detail && $detail->logistic_fee !== null)return false;
  236. if ($waybill->type == "专线"){
  237. $provinceId = $waybill->order ? app("ProvinceService")->getProvince($waybill->order->province) : $waybill->destinationCity->province_id;
  238. $cityId = $waybill->destination_city_id;
  239. $consigneeName = $waybill->order ? $waybill->order->consignee_name : $waybill->recipient;
  240. $consigneePhone = $waybill->order ? $waybill->order->consignee_phone : $waybill->recipient_mobile;
  241. $GLOBALS["FEE_INFO"] = [
  242. "province_id" => $provinceId,
  243. "owner_id" => $waybill->owner_id,
  244. "city_id" => $cityId,
  245. "logistic_id" => $waybill->logistic_id,
  246. "order_number" => $waybill->wms_bill_number,
  247. "recipient_name"=>$consigneeName,
  248. "recipient_phone"=>$consigneePhone,
  249. "quantity"=>$waybill->carrier_weight_other,
  250. "unit_id"=>$waybill->carrier_weight_unit_id_other,
  251. "remark"=>$waybill->ordering_remark,
  252. "created_at"=>$waybill->updated_at,
  253. ];
  254. /** @var OwnerPriceLogisticService $service */
  255. $service = app("OwnerPriceLogisticService");
  256. list($fee,$taxFee) = $service->matching($waybill->carrier_weight_other,$owner_id,$waybill->logistic_id,
  257. $waybill->carrier_weight_unit_id_other,$provinceId, $cityId);
  258. $this->buildWaybillFeeInfo();
  259. }else{
  260. /** @var OwnerPriceDirectLogisticService $service */
  261. $service = app("OwnerPriceDirectLogisticService");
  262. list($fee,$taxFee) = $service->matching($waybill->mileage,$owner_id,$waybill->carType_id);
  263. }
  264. $obj = [
  265. "owner_id" => $owner_id,
  266. "worked_at"=> $waybill->updated_at,
  267. "type" => "发货",
  268. "operation_bill" => $waybill->waybill_number,
  269. "province" => $waybill->order_id ? ($waybill->order->province ?? '') : ($waybill->destinationCity->parent->name ?? ''),
  270. "consignee_name" => $waybill->recipient,
  271. "consignee_phone" => $waybill->recipient_mobile,
  272. "commodity_amount" => $waybill->amount,
  273. "logistic_bill" => $waybill->carrier_bill,
  274. "volume" =>$waybill->carrier_weight ?? $waybill->warehouse_weight,
  275. "weight" => $waybill->carrier_weight_other ?? $waybill->warehouse_weight_other,
  276. "logistic_id" => $waybill->logistic_id,
  277. "logistic_fee" => $fee,
  278. "outer_id" => $waybill->id,
  279. "outer_table_name" => "waybills",
  280. "logistic_tax_fee" => $taxFee,
  281. ];
  282. if ($detail)app("OwnerFeeDetailService")->updateFind($detail,$obj);
  283. else OwnerFeeDetail::query()->create($obj);
  284. return true;
  285. }
  286. /**
  287. * 构建运输费用信息
  288. */
  289. public function buildWaybillFeeInfo()
  290. {
  291. if (!isset($GLOBALS["FEE_INFO"]))return;
  292. OwnerFeeLogistic::query()->create($GLOBALS["FEE_INFO"]);
  293. }
  294. /**
  295. * 生成德邦单据
  296. *
  297. * @param Order|\stdClass $order
  298. *
  299. * @return void
  300. */
  301. public function createDbBill(Order $order)
  302. {
  303. $order->loadMissing("logistic");
  304. if (!$order->logistic || substr($order->logistic->code,0,2) != 'DB')return;
  305. if (Waybill::query()->selectRaw("1")->where("wms_bill_number",$order->code)->first())return;
  306. $waybill = Waybill::query()->create([
  307. 'type'=> "德邦物流",
  308. 'waybill_number'=> Uuid::uuid1(),
  309. 'owner_id'=> $order->owner_id,
  310. 'wms_bill_number'=> $order->code,
  311. 'destination'=> $order->address,
  312. 'recipient'=> $order->consignee_name,
  313. 'recipient_mobile'=>$order->consignee_phone,
  314. 'source_bill'=> $order->client_code,
  315. 'is_to_pay'=> strstr($order->logistic->code,'DF')===false ? 0 : 1,
  316. 'destination_city_id'=>$order->city ? app(RegionService::class)->getCity($order->city) : null,
  317. 'order_id'=> $order->id,
  318. ]);
  319. $waybill->update([
  320. "waybill_number" => 'BSDB'.date ("ymd").str_pad($waybill->id>99999?$waybill->id%99999:$waybill->id,4,"0",STR_PAD_LEFT),
  321. ]);
  322. WaybillAuditLog::query()->create([
  323. 'waybill_id'=>$waybill->id,
  324. 'audit_stage'=>'创建',
  325. 'user_id'=>Auth::id() ?? 0,
  326. ]);
  327. }
  328. /**
  329. * 通知FLUX新单号
  330. *
  331. * @param Model|\stdClass $waybill
  332. *
  333. * @return bool
  334. */
  335. public function notifyFlux($waybill):bool
  336. {
  337. /** @var Waybill|\stdClass $w */
  338. $w = new Waybill();
  339. $w->wms_bill_number = $waybill->wms_bill_number;
  340. $w->waybill_number = $waybill->carrier_bill;
  341. $controller = new WaybillController();
  342. return $controller->accomplishToWMS($w);
  343. }
  344. /**
  345. * 获取调度数据
  346. *
  347. */
  348. public function getDispatchQuery():Builder
  349. {
  350. return Waybill::query()->with(["order:id,address","logistic:id,name","amountUnit:id,name"])
  351. ->select("id","order_id","logistic_id","amount_unit_id",
  352. "waybill_number","destination","recipient","recipient_mobile",
  353. "carrier_bill","warehouse_weight","carrier_weight","inquire_tel",
  354. "warehouse_weight_other","carrier_weight_other","amount","origination")->where(function ($query){
  355. /** @var Builder $query */
  356. $query->whereIn("owner_id",app("OwnerService")->getQuery())
  357. ->orWhereIn("logistic_id",app("LogisticService")->getQuery());
  358. })->whereNotNull("deliver_at")->whereIn("status",["已审核","待终审"]);
  359. }
  360. }