WaybillService.php 16 KB

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