OwnerPriceOperationService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. <?php
  2. namespace App\Services;
  3. use App\Components\ErrorPush;
  4. use App\Feature;
  5. use App\Jobs\HandlePastBill;
  6. use App\Owner;
  7. use App\OwnerFeeDetail;
  8. use App\OwnerPriceOperation;
  9. use App\OwnerPriceOperationItem;
  10. use App\Services\common\QueryService;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Database\Eloquent\Collection;
  13. use Illuminate\Database\Eloquent\Model;
  14. use Illuminate\Support\Facades\Cache;
  15. use Illuminate\Support\Facades\DB;
  16. use App\Traits\ServiceAppAop;
  17. class OwnerPriceOperationService
  18. {
  19. use ServiceAppAop;
  20. use ErrorPush;
  21. protected $modelClass=OwnerPriceOperation::class;
  22. /**
  23. * @param Builder $builder
  24. * @param array $params
  25. * @return Builder
  26. */
  27. private function query(Builder $builder, array $params)
  28. {
  29. if ($params["owner_id"] ?? false){
  30. $ids = $this->ownerGetIds($params["owner_id"]);
  31. if ($ids)$builder->whereIn("id",$ids);
  32. unset($params["owner_id"]);
  33. }
  34. $columnQueryRules = [
  35. "name" => ["like"=>""]
  36. ];
  37. return app(QueryService::class)->query($params, $builder, $columnQueryRules);
  38. }
  39. public function paginate(array $params, array $withs = [])
  40. {
  41. return $this->query(OwnerPriceOperation::query()->orderByDesc('id')->with($withs),$params)
  42. ->paginate($params["paginate"] ?? 50);
  43. }
  44. private function ownerGetIds(string $ownerId)
  45. {
  46. if (!$ownerId)return [];
  47. $arr = DB::select(DB::raw("SELECT owner_price_operation_id AS id FROM owner_price_operation_owner WHERE owner_id in (".$ownerId.")"));
  48. return array_column($arr,"id");
  49. }
  50. /**
  51. * 拷贝目标数据
  52. *
  53. * @param object|int $model
  54. * @param array $values
  55. * @param array $items
  56. * @param array|null $owners
  57. * @param bool $isLoadItem
  58. *
  59. * @return object|null
  60. */
  61. public function copy($model, $values = [], $owners = null, $items = [], $isLoadItem = true)
  62. {
  63. if (is_integer($model))$model = OwnerPriceOperation::query()->find($model);
  64. if (!$model)return null;
  65. $values["operation"] = "U";
  66. $values["target_id"] = $model->id;
  67. foreach ($model->getFillable() as $column){
  68. if (!array_key_exists($column,$values))$values[$column] = $model[$column];
  69. }
  70. if ($owners === null){
  71. $query = DB::raw("SELECT * FROM owner_price_operation_owner WHERE owner_price_operation_id = {$model->id}");
  72. $owners = array_column(DB::select($query),"owner_id");
  73. }
  74. /** @var OwnerPriceOperation $copyModel */
  75. $copyModel = OwnerPriceOperation::query()->create($values);
  76. $copyModel->owners()->sync($owners);
  77. $insert = [];
  78. if ($isLoadItem){
  79. $model->load("items");
  80. /** @var \stdClass $model */
  81. foreach ($model->items as $item){
  82. $columns = ["strategy","amount","unit_id","unit_price","feature","priority","discount_price","odd_price"];
  83. if ($items[$item->id] ?? false){
  84. foreach ($columns as $column){
  85. if (!array_key_exists($column,$items[$item->id]))$items[$item->id][$column] = $item[$column];
  86. }
  87. $obj = $items[$item->id];
  88. unset($items[$item->id]);
  89. }else{
  90. /** @var OwnerPriceOperationItem $item */
  91. $obj = $item->toArray();
  92. unset($obj["id"]);
  93. }
  94. $obj["owner_price_operation_id"] = $copyModel->id;
  95. $insert[] = $obj;
  96. }
  97. }else{
  98. foreach ($items as $item){
  99. $arr = [];
  100. $arr["owner_price_operation_id"] = $copyModel->id;
  101. $arr["strategy"] = $item["strategy"];
  102. $arr["amount"] = $item["amount"] ?? null;
  103. $arr["unit_id"] = $item["unit_id"];
  104. $arr["unit_price"] = $item["unit_price"];
  105. $arr["feature"] = $item["feature"] ?? null;
  106. $arr["odd_price"] = $item["odd_price"] ?? null;
  107. $arr["priority"] = $item["priority"] ?? 0;
  108. $arr["discount_price"] = isset($item["discount_price"]) ? (is_array($item["discount_price"]) ? implode(",",$item["discount_price"]) : $item["discount_price"]) : null;
  109. $insert[] = $arr;
  110. }
  111. }
  112. if ($insert)OwnerPriceOperationItem::query()->insert($insert);
  113. return $copyModel;
  114. }
  115. /**
  116. * 审核或恢复目标集
  117. *
  118. * @param bool $isAudit
  119. * @param integer|null|array $ownerId
  120. * @param integer|null|array $ids
  121. */
  122. public function auditOrRecover($isAudit = true, $ownerId = null, $ids = null)
  123. {
  124. if (!$ownerId && !$ids)return;
  125. $result = app(QueryService::class)->priceModelAuditOrRecoverQuery($isAudit,OwnerPriceOperation::query(),$ownerId,$ids);
  126. if ($result["delete"])$this->destroy($result["delete"]);
  127. if ($result["update"])OwnerPriceOperation::query()->whereIn("id",$result["update"])->update(["operation"=>null,"target_id"=>null]);
  128. if (!is_array($ownerId))$ownerId = [$ownerId];
  129. foreach ($ownerId as $ow)Cache::tags("operationFeeOwner:".$ow)->flush();
  130. }
  131. public function destroy($id)
  132. {
  133. if (!is_array($id))$id = [$id];
  134. OwnerPriceOperationItem::query()->whereIn("owner_price_operation_id",$id)->delete();
  135. DB::table("owner_price_operation_owner")->whereIn("owner_price_operation_id",$id)->delete();
  136. return OwnerPriceOperation::destroy($id);
  137. }
  138. /**
  139. * @param array $params
  140. * @return Model
  141. */
  142. public function create(array $params)
  143. {
  144. $params["operation"] = "C";
  145. return OwnerPriceOperation::query()->create($params);
  146. }
  147. public function insertItem(array $params)
  148. {
  149. OwnerPriceOperationItem::query()->insert($params);
  150. }
  151. public function find($id, $withs = [])
  152. {
  153. $query = OwnerPriceOperation::query()->with($withs)->find($id);
  154. return $query;
  155. }
  156. public function update(array $params, array $values)
  157. {
  158. $query = OwnerPriceOperation::query();
  159. foreach ($params as $column => $value){
  160. $query->where($column,$value);
  161. }
  162. return $query->update($values);
  163. }
  164. public function destroyItem($id)
  165. {
  166. return OwnerPriceOperationItem::query()->where("owner_price_operation_id",$id)->delete();
  167. }
  168. public function findUpdate(OwnerPriceOperation $model, array $params)
  169. {
  170. return $model->update($params);
  171. }
  172. /**
  173. * 获取计费模型缓存
  174. *
  175. * @param integer $owner
  176. * @param string $type
  177. * @param int|null $typeMark
  178. *
  179. * @return array|Collection
  180. *
  181. */
  182. public function getOwnerPriceOperation(int $owner, string $type, ?int $typeMark)
  183. {
  184. return Cache::tags("operationFeeOwner:".$owner)->remember("operationFee:".$owner.$type.$typeMark,config("cache.expirations.rarelyChange"),
  185. function ()use($owner,$type,$typeMark){
  186. $query = OwnerPriceOperation::query()->with(["items"=>function($query){
  187. /** @var Builder $query */
  188. $query->orderByRaw("CASE strategy WHEN '起步' THEN 1 WHEN '默认' THEN 2 WHEN '特征' THEN 3 END DESC,priority");
  189. }])->where("operation_type",$type)->whereHas("owners",function ($query)use($owner){
  190. /** @var Builder $query */
  191. $query->where("id",$owner);
  192. })->where(function(Builder $query){
  193. $query->whereNull("operation")->orWhere("operation","");
  194. })->orderByRaw("strategy desc,priority desc");
  195. if ($typeMark!==null)$query->where("type_mark",$typeMark);
  196. else $query->whereNull("type_mark");
  197. return $query->get();
  198. });
  199. }
  200. /**
  201. * 获取满减信息
  202. *
  203. * @param null|string $discount
  204. * @param integer $total
  205. *
  206. * @return bool|array
  207. */
  208. public function getDiscount(?string $discount, int $total)
  209. {
  210. if (!$discount)return false;
  211. foreach (array_reverse(explode(",",$discount),true) as $index=>$discount){
  212. if ($total >= $discount)return [$index=>$discount];
  213. }
  214. return false;
  215. }
  216. /**
  217. * 处理折扣单
  218. *
  219. * @param Model|\stdClass $rule
  220. * @param integer $owner
  221. * @param bool|array $result
  222. */
  223. public function handleDiscount(Model $rule, int $owner, $result)
  224. {
  225. if (!$result)return;
  226. $sign = false;
  227. //入口仅在此处存在 缓存1000s
  228. $key = "owner_price_operation_owner_".$rule->id."_".$owner;
  229. $discountIndex = key($result);
  230. $targetValue = $result[$discountIndex];
  231. $pivot = null;
  232. try{
  233. DB::beginTransaction();
  234. //此处暂时未使用cache的互斥锁 使用sql行锁代替下 防止缓存击穿
  235. $pivot = app(CacheService::class)->getOrExecute($key,function ()use($key,$targetValue,&$sign,$rule,$owner){
  236. return DB::selectOne(DB::raw("SELECT * FROM owner_price_operation_owner WHERE owner_price_operation_id = ? AND owner_id = ? for update"),[$rule->id,$owner]);
  237. },1000);
  238. if ($pivot && (!$pivot->discount_date || substr($pivot->discount_date,0,7)!=date("Y-m") || $pivot->target_value < $targetValue)){
  239. //未被标记过处理时间或处理时间不为本月,或上次处理值过期,处理历史即时账单
  240. $sign = true;
  241. }
  242. if ($sign){
  243. //先标记成功 这将在后续推进历史单处理流程,防止程序在此堵塞
  244. DB::update(DB::raw("UPDATE owner_price_operation_owner SET discount_date = ?,target_value = ? WHERE owner_price_operation_id = ? AND owner_id = ?"),
  245. [date("Y-m-d"),$targetValue,$rule->id,$owner]);
  246. $pivot->discount_date = date("Y-m-d");
  247. $pivot->target_value = $targetValue;
  248. Cache::put($key,$pivot,1000);
  249. }
  250. DB::commit();
  251. }catch (\Exception $exception){
  252. DB::rollBack();
  253. $this->push(__METHOD__."->".__LINE__,"即时账单满减处理失败",$exception->getMessage()." 参数".json_encode(array($rule, $owner, $result)));
  254. }
  255. //进入历史单处理
  256. if ($pivot && $sign)dispatch(new HandlePastBill(array($rule,$owner,$discountIndex,$pivot)));
  257. }
  258. /** 参数顺序: 数量 匹配对象 列映射 货主ID 单位ID 类型 SKU .
  259. * 匹配顺序: 类型 货主 策略 单位 特征 ..多对多匹配规则废弃,1对1,设单位必定为件,对应规则必然只有一项存在
  260. * 单位匹配: 件,箱 由小到大,依次换算匹配 .
  261. *
  262. * 2:没有总数量存在,都为子项内数量
  263. *
  264. * @param string $month
  265. * @param array|object|Model $matchObject key-val
  266. * @param array $columnMapping key-val
  267. * @param integer $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. * 七. 2021-03-30 zzd
  286. * 增加一级二级特征,零头价,满减按总件,附加费用等
  287. * 八. 2021-04-19 zzd
  288. * 增加税率计算,改变返回值数据结构,增加封顶费
  289. * 九. 2021-04-21 zzd
  290. * 排除掉order不存在包裹情况,预设输出值为null防止返回0,历史账单处理推进队列防止超时
  291. * 十. 2021-08-13
  292. * 优化匹配模型,设置超全局费用信息提取
  293. */
  294. public function matching(string $month, $matchObject, array $columnMapping, int $ownerId, string $type = '出库', ?int $typeMark = null):array
  295. {
  296. $units = app("UnitService")->getUnitMapping(["件","单","箱","m³","T","kg"],true); //获取单位映射集
  297. $rules = $this->getOwnerPriceOperation($ownerId,$type,$typeMark);//货主下的全部规则
  298. if (!$rules)return array(null,null,null); //规则不存在跳出
  299. if ($type == '出库'){
  300. $total = app("OrderService")->getOrderQuantity($ownerId,false,$month)+1;//获取该货主本月C端单量
  301. $matchObject->packages->each(function ($package)use(&$orderTotal){
  302. if($package->commodities->count()==0)return;
  303. $package->commodities[0]->bulk = $package->bulk/1000000;
  304. $package->commodities[0]->weight = $package->weight;
  305. $package->commodities->each(function ($commodity)use(&$orderTotal){
  306. $orderTotal += (int)$commodity->amount;
  307. });
  308. });
  309. $matchObject[$columnMapping[12]] = $orderTotal;
  310. }else {
  311. $total = 0;
  312. if ($matchObject->storeItems)foreach ($matchObject->storeItems as $item)$total += $item->amount;
  313. $matchObject[$columnMapping[12]] = $total;
  314. $total += app("StoreService")->getStoreAmount($ownerId,$month);//获取该货主本月入库件数
  315. }
  316. foreach ($rules as $rule){
  317. if (!$rule->items)continue; //不存在子规则跳出
  318. //第一级匹配 特征类别不符合要求跳出
  319. if ($rule->strategy == '特征' && !app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject))continue;
  320. //获取满减信息并处理满减
  321. $result = $this->getDiscount($rule->discount_count,$total); //满减信息
  322. $this->handleDiscount($rule,$ownerId,$result);
  323. $taxRate = app("OwnerService")->getTaxRateFee($rule, $ownerId);//获取税率
  324. if (!$rule->total_price){
  325. $money = $this->matchItem($rule,$columnMapping,$matchObject,$units,$ownerId,$result);//匹配子项获取详细报价
  326. $money = $this->settingMaxFee($rule,$money,$taxRate,$units);
  327. } else{
  328. $money = $result ? explode(",",$rule->total_discount_price)[key($result)] : $rule->total_price;//按单计价存在,直接返回单总价或减免总价
  329. $arr = $this->resetChildNodeMapping($matchObject->toArray(),$columnMapping);
  330. if ($arr)$this->extractInfo($arr,$money,$result,array_flip($units),$taxRate);
  331. }
  332. if ($money<=0)$money=null;//计算失误
  333. $taxFee = $money*($taxRate/100);
  334. return array($rule->id,$money,$taxFee);
  335. }
  336. return array(null,null,null);
  337. }
  338. /**
  339. * 提取信息插入超全局变量中
  340. */
  341. private function extractInfo(array $arr, $money, $result, $flip, $taxRate)
  342. {
  343. foreach ($arr as $index => $item){
  344. $details = [[
  345. "name" => "单价",
  346. "amount" => $item["amount"] ?? 0,
  347. "price" => 0,
  348. "unit_id" => $flip["件"],
  349. ]];
  350. if ($index==0){
  351. $feeDescription = "按单计价".($result ? '('.value($result).')' : '').':'.$money.'元';
  352. $details[] = [
  353. "name" => "按单计费",
  354. "amount" => 1,
  355. "price" => $money,
  356. "unit_id" => $flip["单"],
  357. ];
  358. }else $feeDescription = '该单已被按单计费,续费0元';
  359. $GLOBALS["FEE_INFO"][] = [
  360. "commodity_id" => $item["commodity_id"] ?? 0,
  361. "total_fee" => $money,
  362. "tax_rate" => $taxRate,
  363. "fee_description" => $feeDescription,
  364. "details" => $details
  365. ];
  366. }
  367. }
  368. /**
  369. * 根据货主 sku寻找箱规并将指定数量切换为箱 返回箱规
  370. *
  371. * @param integer $ownerId
  372. * @param null|object|array $commodity
  373. *
  374. * @return int
  375. */
  376. private function changeUnit(int $ownerId,$commodity):int
  377. {
  378. if (!$commodity)return -4;
  379. if ($commodity["pack_spec"])return $commodity["pack_spec"];
  380. $pack = app("CommodityService")->getPack($ownerId,$commodity["sku"]);
  381. if (!$pack)return -6;
  382. return $pack;
  383. }
  384. /**
  385. * 重置子节点的映射对象 将无限极数组扁平化为二维 以Feature中定义的8:商品数量 key为基准
  386. *
  387. * @param object|array $matchObject
  388. * @param array $columnMapping
  389. *
  390. * @return array|null
  391. */
  392. private function resetChildNodeMapping($matchObject, array &$columnMapping):?array
  393. {
  394. $need = "";
  395. foreach (Feature::TYPE_NODE as $index){
  396. if (!isset($columnMapping[$index]))continue;
  397. if (!$need)$need=strstr($columnMapping[$index],".",true);
  398. $columnMapping[$index] = ltrim(strstr($columnMapping[$index],"."),".");
  399. }
  400. $nextObj = strstr($columnMapping[8],".",true);
  401. $first = $matchObject[$need] ?? false;
  402. if ($first===false)return $matchObject;
  403. if (!$first)return $first;
  404. if (is_array($first))$first = reset($first);
  405. if ($nextObj && is_array($first[$nextObj])){
  406. $result = [];
  407. foreach ($matchObject[$need] as $arr)$result = array_merge($result,$arr[$nextObj]);
  408. return $this->resetChildNodeMapping($result,$columnMapping);
  409. }
  410. return $matchObject[$need];
  411. }
  412. /**
  413. * 匹配子策略
  414. *
  415. * @param Model|\stdClass $obj 策略对象
  416. * @param array $columnMapping 映射对象
  417. * @param Model|\stdClass $matchObject 被匹配对象
  418. * @param array $units 单位集
  419. * @param integer $ownerId 货主ID
  420. * @param bool|array $result 满减信息
  421. *
  422. * @return double
  423. */
  424. public function matchItem($obj, array $columnMapping, $matchObject, array $units, int $ownerId, $result)
  425. {
  426. $matchObject = $this->resetChildNodeMapping($matchObject->toArray(),$columnMapping);
  427. if (!$matchObject)return -1;
  428. $total = $surcharge = $oddMoney = $surchargeAmount = 0; //商品总数 附加费 零头附加费
  429. foreach ($matchObject as $commodity)$total += $commodity[$columnMapping[8]]; //取对象内商品数量总数将其当作子属性插入原对象
  430. if ($obj->surcharge_unit_id && $obj->surcharge){
  431. $surchargeAmount = $units[$obj->surcharge_unit_id] == '件' ? $total : 1;
  432. $surcharge += $obj->surcharge*$surchargeAmount;
  433. }//耗材附加费
  434. $flip = array_flip($units);
  435. $exe = function ($package,$index,$partMoney,$startNumber,$rule)use($columnMapping,$flip,$surcharge,$surchargeAmount,$obj,$units){
  436. $details = $package["fee_info"] ?? []; //获取在匹配过程中记录的费用,例:零头费
  437. $fee_description = $details ? "箱装包含零头附加费" : '';
  438. $details[] = [
  439. "name" => "单价",
  440. "amount" => $package[$columnMapping[8]],
  441. "price" => $package["price"],
  442. "unit_id" => $package["unitId"] ?? $flip["件"],
  443. ];
  444. if ($index==0){
  445. if ($surcharge){
  446. $details[] = [
  447. "name" => "耗材附加费",
  448. "amount" => $surchargeAmount,
  449. "price" => $obj->surcharge,
  450. "unit_id" => $obj->surcharge_unit_id,
  451. ];
  452. $fee_description .= ",包含耗材附加费".$surcharge."元";
  453. $partMoney += $surcharge;
  454. }
  455. if ($startNumber){
  456. $details[] = [
  457. "name" => "起步费",
  458. "amount" => $startNumber,
  459. "price" => $rule->unit_price,
  460. "unit_id" => $rule->unit_id,
  461. ];
  462. $fee_description .= ",包含起步费({$startNumber}/{$units[$rule->unit_id]})".$rule->unit_price."元";
  463. $partMoney += $rule->unit_price;
  464. }
  465. }else if ($startNumber) $fee_description .= "数量被起步数平摊";
  466. $GLOBALS["FEE_INFO"][] = [
  467. "commodity_id" => $package["commodity_id"] ?? 0,
  468. "total_fee" => $partMoney,
  469. "tax_rate" => 0,
  470. "fee_description" => ltrim($fee_description,","),
  471. "details" => $details
  472. ];
  473. };
  474. foreach ($obj->items as $rule){
  475. if ($result)$rule->unit_price = explode(",",$rule->discount_price)[key($result)]; //满足满减条件,单价调整为满减单价
  476. if ($rule->strategy=='起步'){
  477. $startNumber = $rule->amount;
  478. $money = 0;
  479. if ($startNumber){ //起步数存在 重设数量
  480. $money = $rule->unit_price;
  481. $matchObject=$this->settingCount($matchObject,$columnMapping[8],$startNumber,$rule->unit_id);
  482. }
  483. //费用计算
  484. if ($matchObject)foreach ($matchObject as $index=>$package){
  485. if (!isset($package["price"]))$package["price"] = 0;
  486. $partMoney = $package[$columnMapping[8]] * $package["price"];
  487. $money += $partMoney;
  488. $exe($package,$index,$partMoney,$startNumber,$rule); //向信息提取器输入信息
  489. }
  490. //起步费存在 验证重设
  491. if (!$startNumber && $money<$rule->unit_price){
  492. $diffMoney = $rule->unit_price-$money;
  493. if ($GLOBALS["FEE_INFO"]){
  494. $msg = "低于起步费".$rule->unit_price."元,加收差费".$diffMoney;
  495. $GLOBALS["FEE_INFO"][0]["fee_description"] .= $GLOBALS["FEE_INFO"][0]["fee_description"] ?
  496. $GLOBALS["FEE_INFO"][0]["fee_description"].",".$msg : $msg;
  497. $GLOBALS["FEE_INFO"][0]["details"][] = [
  498. "name" => "起步费补差",
  499. "amount" => 1,
  500. "price" => $diffMoney,
  501. "unit_id" => $flip["单"],
  502. ];
  503. }
  504. $money += $diffMoney;
  505. }
  506. return $money+$surcharge+$oddMoney;
  507. }
  508. foreach ($matchObject as &$package){
  509. if (isset($package["price"]))continue; //单价存在 跳过
  510. if (!isset($units[$rule->unit_id]))return -3;//单位未知 跳出
  511. if ($rule->strategy=='特征'){
  512. $package[$columnMapping[10]] = $total; //设置一个不存在的总数进入原对象
  513. if (!app("FeatureService")->matchFeature($rule->feature,$columnMapping,$package)) continue;
  514. }
  515. $package["price"] = $rule->unit_price;
  516. $package["unitId"] = $rule->unit_id;
  517. $package["fee_info"] = [];
  518. //单位转换 数量匹配
  519. switch ($units[$rule->unit_id]){
  520. case "箱"://为箱时同步商品寻找箱规并改变商品数量
  521. $pack = $this->changeUnit($ownerId,$package[$columnMapping[9]]);
  522. if ($pack<=0)return $pack;
  523. if ($rule->odd_price){
  524. $amount = $package[$columnMapping[8]];
  525. $odd = $amount%$pack;
  526. $amount = floor($amount/$pack);
  527. $oddMoney += $rule->odd_price * $odd; //零头附加费
  528. $package["fee_info"][] = [
  529. "name" => "零头附加费",
  530. "amount" => $odd,
  531. "price" => $rule->odd_price,
  532. "unit_id" => $flip["件"],
  533. ];
  534. }else $amount = ceil($package[$columnMapping[8]]/$pack);
  535. if ($amount<0)return $amount;
  536. $package[$columnMapping[8]] = $amount;
  537. break;
  538. case "m³":
  539. $package[$columnMapping[8]] = $package["bulk"] ?? 0;
  540. break;
  541. case "kg":
  542. $package[$columnMapping[8]] = $package["weight"] ?? 0;
  543. break;
  544. case "T":
  545. $package[$columnMapping[8]] = ($package["weight"]/1000) ?? 0;
  546. break;
  547. }
  548. }
  549. }
  550. $money = $surcharge+$oddMoney;
  551. foreach ($matchObject as $index=>$mo){
  552. if (!isset($mo["price"]))$mo["price"] = 0;
  553. $partMoney = $mo[$columnMapping[8]] * $mo["price"];
  554. $money += $partMoney;
  555. $exe($mo,$index,$partMoney,0,null);
  556. }
  557. return $money ?: -7;
  558. }
  559. /**
  560. * 设置封顶费
  561. *
  562. * @param $rule
  563. * @param $money
  564. * @param $taxRate
  565. * @param $units
  566. * @return double
  567. */
  568. private function settingMaxFee($rule,$money,$taxRate,$units):float
  569. {
  570. if ($rule->max_fee&&$money>$rule->max_fee){
  571. $money = $rule->max_fee;//封顶费
  572. foreach ($GLOBALS["FEE_INFO"] as $index=>$info){
  573. foreach ($GLOBALS["FEE_INFO"][$index]["details"] as &$item)$item["price"] = 0;
  574. $GLOBALS["FEE_INFO"][$index]["tax_rate"] = $taxRate;
  575. if ($index==0){
  576. $GLOBALS["FEE_INFO"][$index]["total_fee"] = $rule->max_fee;
  577. $GLOBALS["FEE_INFO"][$index]["fee_description"] = "订单费用超出封顶费,封顶费:".$rule->max_fee
  578. ."(详:".$GLOBALS["FEE_INFO"][$index]["fee_description"].")";
  579. $GLOBALS["FEE_INFO"][$index]["details"][] = [
  580. "name" => "封顶费",
  581. "amount" => 1,
  582. "price" => $rule->max_fee,
  583. "unit_id" => array_flip($units)["单"],
  584. ];
  585. }else{
  586. $GLOBALS["FEE_INFO"][$index]["total_fee"] = 0;
  587. $GLOBALS["FEE_INFO"][$index]["fee_description"] = "封顶费平摊"
  588. ."(详:".$GLOBALS["FEE_INFO"][$index]["fee_description"].")";
  589. }
  590. }
  591. }
  592. return $money;
  593. }
  594. //递归式重新设置数量 只设置单位匹配对象
  595. private function settingCount($packages,$amountColumn,$startNumber,$unitId)
  596. {
  597. if (!$packages) return null;
  598. $maxPrice = 0;
  599. foreach ($packages as $i => $package){
  600. if ($package[$amountColumn] <= 0){$package["price"] = 0;$packages[$i]["price"] = 0;continue;}
  601. if (!isset($package["price"])){$package["price"] = 0;$packages[$i]["price"] = 0;}
  602. if (isset($package["unitId"]) && $package["unitId"]!=$unitId)continue;//单位不一致 跳过
  603. if ($package["price"] > $maxPrice || ($package["price"]==0 && $maxPrice==0)){$maxPrice = $package["price"];$index = $i;}
  604. }
  605. if (!isset($index))return $packages;
  606. if ($packages[$index][$amountColumn] >= $startNumber){
  607. $packages[$index][$amountColumn] -= $startNumber;
  608. return $packages;
  609. }else{
  610. $startNumber -= $packages[$index][$amountColumn];
  611. $packages[$index]["price"] = 0;
  612. $this->settingCount($packages,$amountColumn,$startNumber,$unitId);
  613. }
  614. return $packages;
  615. }
  616. /**
  617. * 处理历史账单
  618. *
  619. * @param Model|\stdClass $rule
  620. * @param int $owner
  621. * @param int $discountIndex
  622. * @param \stdClass|object $pivot
  623. */
  624. public function handlePastBill($rule, int $owner, int $discountIndex, $pivot)
  625. {
  626. DB::beginTransaction();
  627. try{
  628. $month = date("Y-m");
  629. $day = date("t",strtotime($month));
  630. $query = OwnerFeeDetail::query()->where("owner_id",$owner)->whereBetween("worked_at",[$month."-01",$month."-".$day]);
  631. $units = app("UnitService")->getUnitMapping(["件","单","箱","m³","T","kg"],true); //获取单位映射集
  632. $taxRate = app("OwnerService")->getTaxRateFee($rule, $owner);//获取税率
  633. $exe = function ($mapping,$object,$detail)use($rule,$units,$owner,$discountIndex,$taxRate,$pivot){
  634. $GLOBALS["FEE_INFO"] = [];
  635. if (!$rule->total_price){
  636. $money = $this->matchItem($rule,$mapping,$object,$units,$owner,[$discountIndex=>$pivot->target_value ?? true]);
  637. $money = $this->settingMaxFee($rule,$money,$taxRate,$units);
  638. } else{
  639. $money = explode(",",$rule->total_discount_price)[$discountIndex];//按单计价存在,直接返回单总价或减免总价
  640. $arr = $this->resetChildNodeMapping($mapping->toArray(),$object);
  641. if ($arr)$this->extractInfo($arr,$money,[$discountIndex=>$pivot->target_value ?? true],array_flip($units),$taxRate);
  642. }
  643. if ($money>0){ //重置
  644. $detail->update(["work_fee"=>$money,"work_tax_fee"=>$taxRate ? ($money*($taxRate/100)) : null]);
  645. app("StoreService")->clearFeeInfo($detail->operation_bill);
  646. app("StoreService")->constructFeeInfo([
  647. "worked_at" => $detail->worked_at,
  648. "owner_id" => $detail->owner_id,
  649. "model_id" => $rule->id,
  650. "source_number"=> null,
  651. "doc_number" => $detail->operation_bill,
  652. "commodity_id" => 0,
  653. "total_fee" =>0,
  654. "tax_rate" =>0,
  655. "fee_description"=>'',
  656. ]);
  657. }
  658. else $this->push(__METHOD__."->".__LINE__,"处理历史即时账单时发生匹配错误","账单主键:".$detail->id."; 错误代码".$money.";参数列表:".json_encode(array($rule, $owner, $discountIndex)));
  659. };
  660. if ($rule->operation_type=='入库'){
  661. foreach ($query->with(["store.storeItems.commodity","store.warehouse"])
  662. ->where("outer_table_name",'stores')->get() as $detail)
  663. $exe(Feature::MAPPING["store"],$detail->store,$detail);
  664. }else{
  665. foreach ($query->with(["order.logistic","order.shop","order.packages.commodities.commodity","order.batch"])
  666. ->where("outer_table_name",'orders')->get() as $detail)
  667. $exe(Feature::MAPPING["order"],$detail->order,$detail);
  668. }
  669. DB::commit();
  670. }catch (\Exception $e){
  671. DB::rollBack();
  672. //处理失败回退标记
  673. DB::update(DB::raw("UPDATE owner_price_operation_owner SET discount_date = ?,target_value = ? WHERE owner_price_operation_id = ? AND owner_id = ?"),
  674. [$pivot->discount_date,$pivot->target_value,$rule->id,$owner]);
  675. $this->push(__METHOD__."->".__LINE__,"处理历史即时账单时发生系统错误","计费模型主键:".$rule->id."; 错误信息".$e->getMessage().";参数列表:".json_encode(array($rule, $owner, $discountIndex,$pivot)));
  676. }
  677. }
  678. }