WaybillService.php 14 KB

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