OwnerPriceOperationService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <?php
  2. namespace App\Services;
  3. use App\Feature;
  4. use App\OwnerFeeDetail;
  5. use App\OwnerPriceOperation;
  6. use App\OwnerPriceOperationItem;
  7. use App\Services\common\QueryService;
  8. use Illuminate\Database\Eloquent\Builder;
  9. use Illuminate\Database\Eloquent\Collection;
  10. use Illuminate\Database\Eloquent\Model;
  11. use Illuminate\Support\Facades\Cache;
  12. use Illuminate\Support\Facades\DB;
  13. use App\Traits\ServiceAppAop;
  14. class OwnerPriceOperationService
  15. {
  16. use ServiceAppAop;
  17. protected $modelClass=OwnerPriceOperation::class;
  18. /**
  19. * @param Builder $builder
  20. * @param array $params
  21. * @return Builder
  22. */
  23. private function query(Builder $builder, array $params)
  24. {
  25. if ($params["owner_id"] ?? false){
  26. $ids = $this->ownerGetIds($params["owner_id"]);
  27. if ($ids)$builder->whereIn("id",$ids);
  28. unset($params["owner_id"]);
  29. }
  30. $columnQueryRules = [
  31. "name" => ["like"=>""]
  32. ];
  33. return app(QueryService::class)->query($params, $builder, $columnQueryRules);
  34. }
  35. public function paginate(array $params, array $withs = [])
  36. {
  37. return $this->query(OwnerPriceOperation::query()->orderByDesc('id')->with($withs),$params)
  38. ->paginate($params["paginate"] ?? 50);
  39. }
  40. private function ownerGetIds(string $ownerId)
  41. {
  42. if (!$ownerId)return [];
  43. $arr = DB::select(DB::raw("SELECT owner_price_operation_id AS id FROM owner_price_operation_owner WHERE owner_id in (".$ownerId.")"));
  44. return array_column($arr,"id");
  45. }
  46. /**
  47. * 拷贝目标数据
  48. *
  49. * @param object|int $model
  50. * @param array $values
  51. * @param array $items
  52. * @param array|null $owners
  53. * @param bool $isLoadItem
  54. *
  55. * @return object|null
  56. */
  57. public function copy($model, $values = [], $owners = null, $items = [], $isLoadItem = true)
  58. {
  59. if (is_integer($model))$model = OwnerPriceOperation::query()->find($model);
  60. if (!$model)return null;
  61. $values["operation"] = "U";
  62. $values["target_id"] = $model->id;
  63. foreach ($model->getFillable() as $column){
  64. if (!array_key_exists($column,$values))$values[$column] = $model[$column];
  65. }
  66. if ($owners === null){
  67. $query = DB::raw("SELECT * FROM owner_price_operation_owner WHERE owner_price_operation_id = {$model->id}");
  68. $owners = array_column(DB::select($query),"owner_id");
  69. }
  70. /** @var OwnerPriceOperation $copyModel */
  71. $copyModel = OwnerPriceOperation::query()->create($values);
  72. $copyModel->owners()->sync($owners);
  73. $insert = [];
  74. if ($isLoadItem){
  75. $model->load("items");
  76. /** @var \stdClass $model */
  77. foreach ($model->items as $item){
  78. $columns = ["strategy","amount","unit_id","unit_price","feature","priority","discount_price"];
  79. if ($items[$item->id] ?? false){
  80. foreach ($columns as $column){
  81. if (!array_key_exists($column,$items[$item->id]))$items[$item->id][$column] = $item[$column];
  82. }
  83. $obj = $items[$item->id];
  84. unset($items[$item->id]);
  85. }else{
  86. /** @var OwnerPriceOperationItem $item */
  87. $obj = $item->toArray();
  88. unset($obj["id"]);
  89. }
  90. $obj["owner_price_operation_id"] = $copyModel->id;
  91. $insert[] = $obj;
  92. }
  93. }else{
  94. foreach ($items as $item){
  95. $arr = [];
  96. $arr["owner_price_operation_id"] = $copyModel->id;
  97. $arr["strategy"] = $item["strategy"];
  98. $arr["amount"] = $item["amount"] ?? null;
  99. $arr["unit_id"] = $item["unit_id"];
  100. $arr["unit_price"] = $item["unit_price"];
  101. $arr["feature"] = $item["feature"] ?? null;
  102. $arr["priority"] = $item["priority"] ?? 0;
  103. $arr["discount_price"] = isset($item["discount_price"]) ? (is_array($item["discount_price"]) ? implode(",",$item["discount_price"]) : $item["discount_price"]) : null;
  104. $insert[] = $arr;
  105. }
  106. }
  107. if ($insert)OwnerPriceOperationItem::query()->insert($insert);
  108. return $copyModel;
  109. }
  110. /**
  111. * 审核或恢复目标集
  112. *
  113. * @param bool $isAudit
  114. * @param integer|null|array $ownerId
  115. * @param integer|null|array $ids
  116. */
  117. public function auditOrRecover($isAudit = true, $ownerId = null, $ids = null)
  118. {
  119. if (!$ownerId && !$ids)return;
  120. $result = app(QueryService::class)->priceModelAuditOrRecoverQuery($isAudit,OwnerPriceOperation::query(),$ownerId,$ids);
  121. if ($result["delete"])$this->destroy($result["delete"]);
  122. if ($result["update"])OwnerPriceOperation::query()->whereIn("id",$result["update"])->update(["operation"=>null,"target_id"=>null]);
  123. if (!is_array($ownerId))$ownerId = [$ownerId];
  124. foreach ($ownerId as $ow)Cache::tags("operationFeeOwner:".$ow)->flush();
  125. }
  126. public function destroy($id)
  127. {
  128. if (!is_array($id))$id = [$id];
  129. OwnerPriceOperationItem::query()->whereIn("owner_price_operation_id",$id)->delete();
  130. $query = "IN (";
  131. for ($i=0;$i<count($id)-1;$i++)$query .= "{$id[$i]},";
  132. $query .= "{$id[count($id)-1]})";
  133. $sql = "SELECT * FROM owner_price_operation_owner WHERE owner_price_operation_id {$query}";
  134. $owners = array_column(DB::select(DB::raw($sql)),"owner_id");
  135. DB::table("owner_price_operation_owner")->whereIn("owner_price_operation_id",$id)->delete();
  136. app("OwnerService")->refreshRelevance($owners,1,true);
  137. return OwnerPriceOperation::destroy($id);
  138. }
  139. /**
  140. * @param array $params
  141. * @return Model
  142. */
  143. public function create(array $params)
  144. {
  145. $params["operation"] = "C";
  146. return OwnerPriceOperation::query()->create($params);
  147. }
  148. public function insertItem(array $params)
  149. {
  150. OwnerPriceOperationItem::query()->insert($params);
  151. }
  152. public function find($id, $withs = [])
  153. {
  154. $query = OwnerPriceOperation::query()->with($withs)->find($id);
  155. return $query;
  156. }
  157. public function update(array $params, array $values)
  158. {
  159. $query = OwnerPriceOperation::query();
  160. foreach ($params as $column => $value){
  161. $query->where($column,$value);
  162. }
  163. return $query->update($values);
  164. }
  165. public function destroyItem($id)
  166. {
  167. return OwnerPriceOperationItem::query()->where("owner_price_operation_id",$id)->delete();
  168. }
  169. public function findUpdate(OwnerPriceOperation $model, array $params)
  170. {
  171. return $model->update($params);
  172. }
  173. /**
  174. * 获取计费模型缓存
  175. *
  176. * @param integer $owner
  177. * @param string $type
  178. * @param int|null $typeMark
  179. *
  180. * @return array|Collection
  181. *
  182. */
  183. public function getOwnerPriceOperation($owner, $type, $typeMark)
  184. {
  185. return Cache::tags("operationFeeOwner:".$owner)->remember("operationFee:".$owner.$type.$typeMark,config("cache.expirations.rarelyChange"),
  186. function ()use($owner,$type,$typeMark){
  187. $query = OwnerPriceOperation::query()->with(["items"=>function($query){
  188. /** @var Builder $query */
  189. $query->orderByRaw("CASE strategy WHEN '起步' THEN 1 WHEN '默认' THEN 2 WHEN '特征' THEN 3 END DESC,priority");
  190. }])->where("operation_type",$type)->whereHas("owners",function ($query)use($owner){
  191. /** @var Builder $query */
  192. $query->where("id",$owner);
  193. })->where(function(Builder $query){
  194. $query->whereNull("operation")->orWhere("operation","");
  195. })->orderByRaw("strategy desc,priority desc");
  196. if ($typeMark!==null)$query->where("type_mark",$typeMark);
  197. else $query->whereNull("type_mark");
  198. return $query->get();
  199. });
  200. }
  201. /**
  202. * 获取满减信息
  203. *
  204. * @param null|string $discount
  205. * @param integer $total
  206. *
  207. * @return bool|array
  208. */
  209. public function getDiscount($discount, $total)
  210. {
  211. if ($discount){
  212. foreach (array_reverse(explode(",",$discount),true) as $index=>$discount){
  213. if ($total >= $discount)return [$index=>$discount];
  214. }
  215. }
  216. return false;
  217. }
  218. /**
  219. * 处理折扣单
  220. *
  221. * @param object $rule
  222. * @param integer $owner
  223. * @param bool|array $result
  224. */
  225. public function handleDiscount($rule, $owner, $result)
  226. {
  227. $sign = false;
  228. //入口仅在此处存在 缓存1000s
  229. $key = "pivot_".$rule->id."_".$owner;
  230. $discountIndex = key($result);
  231. $targetValue = $result[$discountIndex];
  232. $pivot = app(CacheService::class)->getOrExecute($key,function ()use($key,$targetValue,&$sign,$rule,$owner){
  233. try{
  234. DB::beginTransaction();
  235. //此处暂时未使用cache的互斥锁 使用sql行锁代替下 防止缓存击穿
  236. $pivot = DB::selectOne(DB::raw("SELECT * FROM owner_price_operation_owner WHERE owner_price_operation_id = ? AND owner_id = ? for update"),[$rule->id,$owner]);
  237. if ($pivot && (!$pivot->discount_date || substr($pivot->discount_date,0,7)!=date("Y-m") || $pivot->target_value < $targetValue)){
  238. //未被标记过处理时间或处理时间不为本月,或上次处理值过期,处理历史即时账单
  239. $sign = true;
  240. }
  241. if ($sign){
  242. //先标记成功 这将在后续推进历史单处理流程,防止程序在此堵塞
  243. DB::update(DB::raw("UPDATE owner_price_operation_owner SET discount_date = ?,target_value = ? WHERE owner_price_operation_id = ? AND owner_id = ?"),
  244. [date("Y-m-d"),$targetValue,$rule->id,$owner]);
  245. $pivot->discount_date = date("Y-m-d");
  246. $pivot->target_value = $targetValue;
  247. Cache::put($key,$pivot,1000);
  248. }
  249. DB::commit();
  250. }catch (\Exception $exception){
  251. DB::rollBack();
  252. LogService::log(__CLASS__,"即时账单满减处理失败",$exception->getMessage());
  253. }
  254. return $pivot ?? null;
  255. },1000);
  256. //进入历史单处理
  257. if ($pivot && $sign)$this->handlePastBill($rule,$owner,$discountIndex,$pivot);
  258. }
  259. /** 参数顺序: 数量 匹配对象 列映射 货主ID 单位ID 类型 SKU .
  260. * 匹配顺序: 类型 货主 策略 单位 特征 ..多对多匹配规则废弃,1对1,设单位必定为件,对应规则必然只有一项存在
  261. * 单位匹配: 件,箱 由小到大,依次换算匹配 .
  262. *
  263. * 2:没有总数量存在,都为子项内数量
  264. *
  265. * @param array|object $matchObject key-val
  266. * @param array $columnMapping key-val
  267. * @param string $ownerId
  268. * @param string $type
  269. * @param int|null $typeMark
  270. *
  271. * @return double|array
  272. * 错误代码: -1:无匹配对象 -2:无计费模型 -3:未知单位 -4:sku为空 -5:货主未找到 -6:无箱规 -7:未匹配到计费模型
  273. *
  274. * 一. 2020-10-10 zzd
  275. * 二. 2021-01-08 zzd
  276. * 三. 2021-01-28 zzd
  277. * 增加满减策略:子策略匹配时不再考虑单,仅件箱换算,满减满足后标记模型修改历史对账单
  278. * 增加按订单计价策略:主匹配模型增加字段量价,该字段存在时视为按单计价,价格为该值
  279. * 四. 2021-02-18 zzd
  280. * 满减多阶段匹配 满减字段由单值改为字符串多值 匹配时转数组寻找最相近
  281. * 五. 2021-03-18 zzd
  282. * 区分单据类型,增加字段
  283. * 六. 2021-03-23 zzd
  284. * 不严格区分入库出库差异 统一模型
  285. */
  286. public function matching($matchObject, $columnMapping, $ownerId, $type = '出库', $typeMark = null)
  287. {
  288. $units = app("UnitService")->getUnitMapping(["件","箱"]); //获取单位映射集
  289. $rules = $this->getOwnerPriceOperation($ownerId,$type,$typeMark);//货主下的全部规则
  290. if (!$rules)return -2; //规则不存在跳出
  291. $total = app("OrderService")->getOrderQuantity($ownerId);//获取该货主本月C端单量
  292. foreach ($rules as $rule){
  293. if (!$rule->items)continue; //不存在子规则跳出
  294. $result = $this->getDiscount($rule->discount_count,$total); //满减信息
  295. if ($result)$this->handleDiscount($rule,$ownerId,$result);//满减存在
  296. if ($rule->strategy == '特征'){
  297. if (app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject)){
  298. if ($rule->total_price)return ["id"=>$rule->id,"money"=>$result ? explode(",",$rule->total_discount_price)[key($result)] : $rule->total_price];//按单计价存在,直接返回单总价或减免总价
  299. $money = $this->matchItem($rule->items,$columnMapping,$matchObject,$units,$ownerId,$result);
  300. if ($money>0)return ["id"=>$rule->id,"money"=>$money];
  301. };
  302. }else{
  303. if ($rule->total_price)return ["id"=>$rule->id,"money"=>$result ? explode(",",$rule->total_discount_price)[key($result)] : $rule->total_price]; //按单计价存在,直接返回单总价或减免总价
  304. $money = $this->matchItem($rule->items,$columnMapping,$matchObject,$units,$ownerId,$result);
  305. if ($money>0)return ["id"=>$rule->id,"money"=>$money];
  306. };
  307. }
  308. return $money ?? -7;
  309. }
  310. /**
  311. * 根据货主 sku寻找箱规并将指定数量切换为箱
  312. * 不满一箱视为一箱
  313. *
  314. * @param integer $amount
  315. * @param integer $ownerId
  316. * @param null|object $commodity
  317. *
  318. * @return int
  319. */
  320. private function changeUnit($amount,$ownerId,$commodity)
  321. {
  322. if (!$commodity)return -4;
  323. if ($commodity->pack_spec)return ceil($amount/$commodity->pack_spec);
  324. $pack = app("CommodityService")->getPack($ownerId,$commodity->sku);
  325. if (!$pack)return -6;
  326. return ceil($amount/$pack);
  327. }
  328. /**
  329. * 重置子节点的映射对象 将无限极数组扁平化为二维 以Feature中定义的8:商品数量 key为基准
  330. *
  331. * @param object|array $matchObject
  332. * @param array $columnMapping
  333. *
  334. * @return array
  335. */
  336. private function resetChildNodeMapping($matchObject,&$columnMapping)
  337. {
  338. $need = "";
  339. foreach (Feature::TYPE_NODE as $index){
  340. if (!$need)$need=strstr($columnMapping[$index],".",true);
  341. $columnMapping[$index] = ltrim(strstr($columnMapping[$index],"."),".");
  342. }
  343. $nextObj = strstr($columnMapping[8],".",true);
  344. $first = $matchObject[$need] ?? false;
  345. if ($first && is_array($first))$first = reset($first);
  346. else return $matchObject;
  347. if (!$first)return $matchObject;
  348. if (is_array($first[$nextObj])){
  349. $result = [];
  350. foreach ($matchObject[$need] as $arr)$result = array_merge($result,$arr[$nextObj]);
  351. return $this->resetChildNodeMapping($result,$columnMapping);
  352. }
  353. return $matchObject[$need];
  354. }
  355. /**
  356. * 匹配子策略
  357. *
  358. * @param array $rules 策略对象组
  359. * @param array $columnMapping 映射对象
  360. * @param array $matchObject 被匹配对象
  361. * @param array $units 单位集
  362. * @param integer $ownerId 货主ID
  363. * @param bool|array $result 满减信息
  364. *
  365. * @return double
  366. */
  367. private function matchItem($rules, $columnMapping, $matchObject, $units, $ownerId, $result)
  368. {
  369. /** @var Collection $matchObject */
  370. $matchObject = $this->resetChildNodeMapping($matchObject->toArray(),$columnMapping);
  371. if (!$matchObject)return -1;
  372. $unitName = "";
  373. foreach ($rules as $rule){
  374. if ($result)$rule->unit_price = explode(",",$rule->discount_price)[key($result)]; //满足满减条件,单价调整为满减单价
  375. if ($rule->strategy=='起步'){
  376. if ($unitName && $unitName != $units[$rule->unit_id])return -3; //校验单位是否一致
  377. $money = $rule->unit_price;
  378. $startNumber = $rule->amount;
  379. if ($startNumber)$matchObject=$this->settingCount($matchObject,$columnMapping[8],$startNumber);
  380. if ($matchObject)foreach ($matchObject as $package)$money += $package[$columnMapping[8]] * $package["price"];
  381. if (!$startNumber && $money<$rule->unit_price)$money = $rule->unit_price;
  382. return $money;
  383. }
  384. foreach ($matchObject as &$package){
  385. if ($package["price"] ?? false)continue;
  386. if (!isset($units[$rule->unit_id]))return -3;
  387. if (!$unitName)$unitName = $units[$rule->unit_id];
  388. else if ($unitName != $units[$rule->unit_id]) return -3;
  389. if ($rule->strategy=='特征')if (!app("FeatureService")->matchFeature($rule->feature,$columnMapping,$package)) continue;
  390. $package["price"] = $rule->unit_price;
  391. }
  392. if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
  393. $amount = 0;
  394. foreach ($matchObject as $commodity)$amount += $this->changeUnit($commodity[$columnMapping[8]],$ownerId,$commodity[$columnMapping[9]]);
  395. if ($amount<0)return $amount;
  396. $package[$columnMapping[8]] = $amount;
  397. }
  398. }
  399. if ($matchObject){
  400. $money = 0;
  401. foreach ($matchObject as $package)if ($package["price"])$money += $package[$columnMapping[8]] * $package["price"];
  402. }
  403. return $money ?? -7;
  404. }
  405. //递归式重新设置数量
  406. private function settingCount($packages,$amountColumn,$startNumber)
  407. {
  408. if (!$packages) return null;
  409. $maxPrice = 0;
  410. $index = null;
  411. foreach ($packages as $i => $package){
  412. if ($package[$amountColumn] <= 0){
  413. unset($packages[$i]);continue;
  414. }
  415. if ($package["price"] > $maxPrice || ($package["price"]==0 && $maxPrice==0)){
  416. $maxPrice = $package["price"];
  417. $index = $i;
  418. }
  419. }
  420. if ($packages[$index][$amountColumn] >= $startNumber){
  421. $packages[$index][$amountColumn] -= $startNumber;
  422. return $packages;
  423. }else{
  424. $startNumber -= $packages[$index][$amountColumn];
  425. unset($packages[$index]);
  426. $this->settingCount($packages,$amountColumn,$startNumber);
  427. }
  428. }
  429. /**
  430. * 处理历史账单
  431. *
  432. * @param object $rule
  433. * @param int $owner
  434. * @param int $discountIndex
  435. * @param object $pivot
  436. */
  437. public function handlePastBill($rule, $owner, $discountIndex, $pivot)
  438. {
  439. try{
  440. DB::beginTransaction();
  441. $month = date("Y-m");
  442. $day = date("t",strtotime($month));
  443. $units = app("UnitService")->getUnitMapping(["件","箱"]); //获取单位映射集
  444. foreach (OwnerFeeDetail::query()->with(["order.logistic","order.shop","order.packages.commodities.commodity","order.batch"])
  445. ->where("owner_id",$owner)
  446. ->whereBetween("worked_at",[$month."-01",$month."-".$day])->get() as $detail){
  447. $order = $detail->order;
  448. $logistic_fee = 0;
  449. if ($logistic_fee!==null && $logistic_fee<0)$logistic_fee = null;
  450. $money = $this->matchItem($rule->items,Feature::MAPPING["order"],$order,$units,$owner,[$discountIndex=>true]);
  451. if ($money>0)$detail->update(["work_fee"=>$money]);
  452. else LogService::log(__CLASS__,"处理历史即时账单时发生匹配错误","账单主键:".$detail->id."; 错误代码".$money);
  453. };
  454. DB::commit();
  455. }catch (\Exception $e){
  456. DB::rollBack();
  457. //处理失败回退标记
  458. DB::update(DB::raw("UPDATE owner_price_operation_owner SET discount_date = ?,target_value = ? WHERE owner_price_operation_id = ? AND owner_id = ?"),
  459. [$pivot->discount_date,$pivot->target_value,$rule->id,$owner]);
  460. LogService::log(__CLASS__,"处理历史即时账单时发生系统错误","计费模型主键:".$rule->id."; 错误信息".$e->getMessage());
  461. }
  462. }
  463. }