OwnerPriceOperationService.php 32 KB

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