WaybillService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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"] ?? false){
  36. $ownerIds = explode(",",$param["owner"]);
  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",$ownerIds);
  42. });
  43. });
  44. unset($param["owner"]);
  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["mileage"] ?? false){
  101. $param["mileage"] = explode("-",$param["mileage"]);
  102. $waybills->whereBetween("mileage",[(int)$param["mileage"][0] ?? 0,(int)$param["mileage"][1]] ?? 0);
  103. unset($param["mileage"]);
  104. }
  105. if ($param["warehouse_weight_other"] ?? false){
  106. $param["warehouse_weight_other"] = explode("-",$param["warehouse_weight_other"]);
  107. $waybills->whereBetween("warehouse_weight_other",[(int)$param["warehouse_weight_other"][0] ?? 0,(int)$param["warehouse_weight_other"][1]] ?? 0);
  108. unset($param["warehouse_weight_other"]);
  109. }
  110. $columnQueryRules=[
  111. 'waybill_number' => ['batch' => ''],
  112. 'carrier_bill' => ['batch' => ''],
  113. 'wms_bill_number' => ['batch' => ''],
  114. 'origination' => ['batch' => ''],
  115. 'source_bill' => ['batch' => ''],
  116. 'car_owner_info' => ['batch' => ''],
  117. 'created_at_start' => ['alias' => 'created_at' , 'startDate' => ':00'],
  118. 'created_at_end' => ['alias' => 'created_at' , 'endDate' => ':59'],
  119. 'updated_at_start' => ['alias' => 'updated_at' , 'startDate' => ':00'],
  120. 'updated_at_end' => ['alias' => 'updated_at' , 'endDate' => ':59'],
  121. 'deliver_at_start' => ['alias' => 'deliver_at' , 'startDate' => ':00'],
  122. 'deliver_at_end' => ['alias' => 'deliver_at' , 'endDate' => ':59'],
  123. 'uriType' => ['alias' => 'type'],
  124. 'id' => ['multi' => ','],
  125. 'logistic' => ['alias' => 'logistic_id', 'multi' => ','],
  126. ];
  127. $waybills = app(QueryService::class)->query($param,$waybills,$columnQueryRules,"waybills");
  128. return $waybills;
  129. }
  130. public function paginate(array $param){
  131. $waybills = $this->conditionQuery($param);
  132. return $waybills->paginate($param['paginate'] ?? 50);
  133. }
  134. public function get(array $param){
  135. $waybills = $this->conditionQuery($param);
  136. return $waybills->get();
  137. }
  138. public function dailyBilling(array $param){
  139. $waybills = Waybill::query()->with(['owner','logistic','originationCity','destinationCity.parent',
  140. 'uploadFiles','amountUnit','warehouseWeightUnit','carrierWeightUnit','district','order',
  141. 'warehouseWeightUnitOther','carrierWeightUnitOther','carType','uploadFiles','waybillAuditLogs.user'])
  142. ->selectRaw('waybills.* ,waybill_on_tops.id top_id,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
  143. ->leftJoin('waybill_on_tops','waybill_on_tops.waybill_id','=','waybills.id')
  144. ->whereNull('waybill_on_tops.deleted_at')
  145. ->orderBy('waybill_on_tops.updated_at','desc')
  146. ->orderBy('waybills.id','desc')
  147. ->where('waybills.type','专线')
  148. ->where('waybills.amount','>',0)
  149. ->where('waybills.deliver_at','like',$param['screenDate'].'%')
  150. ->get();
  151. if ($waybills->isEmpty()) return '无数据';
  152. foreach ($waybills as $waybill){
  153. if (!$waybill['carrier_weight_other'] && !$waybill['carrier_weight']) return null;
  154. if (!$waybill['carrier_weight_other'] || $waybill['carrier_weight_other']<=0) $waybill['carrier_weight_other']=($waybill['carrier_weight']/0.25*100);
  155. }
  156. $daily_total_weight=$waybills->sum('carrier_weight_other');
  157. $updateParams = [['id','pick_up_fee','updated_at']];
  158. foreach ($waybills as $waybill){
  159. $waybill['pick_up_fee']=round(($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']);
  160. $updateParams[] = [
  161. 'id' => $waybill->id,
  162. 'pick_up_fee' =>(($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']),
  163. 'updated_at' => Carbon::now()->toDateTimeString(),
  164. ];
  165. }
  166. if (count($updateParams)>0)app(BatchUpdateService::class)->batchUpdate('waybills', $updateParams);
  167. return $waybills;
  168. }
  169. public function store(Request $request){
  170. return DB::transaction(function ()use($request){
  171. $waybill=new Waybill();
  172. $inputs = $request->all();
  173. $inputs['status']='未审核';
  174. $inputs['waybill_number']=Uuid::uuid1();
  175. $waybill->fill($inputs);
  176. if ($request->collect_fee)$waybill->collect_fee=$request->collect_fee;
  177. $waybill->save();
  178. $number_id=$waybill->id;
  179. if ($request->type=='直发车') $waybill_number='BSZF';
  180. else $waybill_number='BSZX';
  181. $waybill_number .= date ("ymd").str_pad($number_id>99999?$number_id%99999:$number_id,4,"0",STR_PAD_LEFT);
  182. $waybill->update(['waybill_number' => $waybill_number ]);
  183. WaybillAuditLog::query()->create([
  184. 'waybill_id'=>$waybill->id,
  185. 'audit_stage'=>'创建',
  186. 'user_id'=>Auth::id() ?? 0,
  187. ]);
  188. return $waybill;
  189. });
  190. }
  191. public function find($id){
  192. return Waybill::query()->find($id);
  193. }
  194. public function update(Request $request,$id)
  195. {
  196. $waybill = $this->find($id);
  197. //替换换行符
  198. if ($request->dispatch_remark) {
  199. $request->offsetSet('dispatch_remark', str_replace(["\n","\r"], ' ', $request->dispatch_remark));
  200. }
  201. if (!$request->destination) $request->offsetSet('destination', $waybill->destination);
  202. $waybill->fill($request->input());
  203. $waybill->update();
  204. return $waybill;
  205. }
  206. public function getDeliveringSql(array $param){
  207. $waybills = $this->conditionQuery($param);
  208. if (!Auth::user()->isSuperAdmin()){
  209. $users=DB::table('logistic_user')->where('user_id',Auth::id())->get();
  210. $userIds=array_column($users->toArray(),'logistic_id');
  211. $waybills=$waybills->whereIn("waybills.logistic_id",$userIds);
  212. }
  213. return $waybills->leftJoin('owners','owners.id','=','waybills.owner_id')->selectRaw('owners.name owner_name')
  214. ->leftJoin('logistics','logistics.id','=','waybills.logistic_id')
  215. ->selectRaw('logistics.name carrier_name')
  216. ->sql();
  217. }
  218. public function createInstantBill(Waybill $waybill) :bool
  219. {
  220. /** @var \stdClass $waybill */
  221. if (!$waybill || $waybill->status != "已完结" || !$waybill->wms_bill_number || !$waybill->logistic_id)return false;
  222. $waybill->loadMissing(["destinationCity","order.owner"]);
  223. if (!$waybill->destinationCity && !$waybill->order)return false;
  224. $owner_id = $waybill->order->owner_id ?? $waybill->owner_id;
  225. $detail = OwnerFeeDetail::query()->where("type","发货")
  226. ->where("owner_id",$owner_id)->whereIn("operation_bill",[$waybill->wms_bill_number,$waybill->waybill_number])->first();
  227. if ($detail && $detail->logistic_fee !== null)return false;
  228. if ($waybill->type == "专线"){
  229. /** @var OwnerPriceLogisticService $service */
  230. $service = app("OwnerPriceLogisticService");
  231. list($fee,$taxFee) = $service->matching($waybill->carrier_weight_other,$owner_id,$waybill->logistic_id,
  232. $waybill->carrier_weight_unit_id_other,$waybill->order ? app("RegionService")->getProvince($waybill->order->province) : $waybill->destinationCity->province_id,
  233. $waybill->destination_city_id);
  234. }else{
  235. /** @var OwnerPriceDirectLogisticService $service */
  236. $service = app("OwnerPriceDirectLogisticService");
  237. list($fee,$taxFee) = $service->matching($waybill->mileage,$owner_id,$waybill->carType_id);
  238. }
  239. $obj = [
  240. "owner_id" => $owner_id,
  241. "worked_at"=> $waybill->updated_at,
  242. "type" => "发货",
  243. "operation_bill" => $waybill->waybill_number,
  244. "province" => $waybill->order_id ? ($waybill->order->province ?? '') : ($waybill->destinationCity->parent->name ?? ''),
  245. "consignee_name" => $waybill->recipient,
  246. "consignee_phone" => $waybill->recipient_mobile,
  247. "commodity_amount" => $waybill->amount,
  248. "logistic_bill" => $waybill->carrier_bill,
  249. "volume" =>$waybill->carrier_weight ?? $waybill->warehouse_weight,
  250. "weight" => $waybill->carrier_weight_other ?? $waybill->warehouse_weight_other,
  251. "logistic_id" => $waybill->logistic_id,
  252. "logistic_fee" => $fee,
  253. "outer_id" => $waybill->id,
  254. "outer_table_name" => "waybills",
  255. "logistic_tax_fee" => $taxFee,
  256. ];
  257. if ($detail)app("OwnerFeeDetailService")->updateFind($detail,$obj);
  258. else OwnerFeeDetail::query()->create($obj);
  259. return true;
  260. }
  261. /**
  262. * 生成德邦单据
  263. *
  264. * @param Order|\stdClass $order
  265. *
  266. * @return void
  267. */
  268. public function createDbBill(Order $order)
  269. {
  270. $order->loadMissing("logistic");
  271. if (!$order->logistic || substr($order->logistic->code,0,2) != 'DB')return;
  272. if (Waybill::query()->selectRaw("1")->where("wms_bill_number",$order->code)->first())return;
  273. $waybill = Waybill::query()->create([
  274. 'type'=> "德邦物流",
  275. 'waybill_number'=> Uuid::uuid1(),
  276. 'owner_id'=> $order->owner_id,
  277. 'wms_bill_number'=> $order->code,
  278. 'destination'=> $order->address,
  279. 'recipient'=> $order->consignee_name,
  280. 'recipient_mobile'=>$order->consignee_phone,
  281. 'source_bill'=> $order->client_code,
  282. 'is_to_pay'=> strstr($order->logistic->code,'DF')===false ? 0 : 1,
  283. 'destination_city_id'=>$order->city ? app(RegionService::class)->getCity($order->city) : null,
  284. 'order_id'=> $order->id,
  285. ]);
  286. $waybill->update([
  287. "waybill_number" => 'BSDB'.date ("ymd").str_pad($waybill->id>99999?$waybill->id%99999:$waybill->id,4,"0",STR_PAD_LEFT),
  288. ]);
  289. WaybillAuditLog::query()->create([
  290. 'waybill_id'=>$waybill->id,
  291. 'audit_stage'=>'创建',
  292. 'user_id'=>Auth::id() ?? 0,
  293. ]);
  294. }
  295. }