WaybillService.php 13 KB

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