WaybillService.php 15 KB

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