WaybillService.php 18 KB

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