@pisell/pisellos 2.2.317 → 2.2.319

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.js +5 -4
  2. package/dist/modules/Discount/types.d.ts +4 -0
  3. package/dist/modules/Order/index.d.ts +1 -1
  4. package/dist/modules/Order/index.js +27 -13
  5. package/dist/modules/Order/utils.js +45 -45
  6. package/dist/modules/Payment/walletpass.js +32 -6
  7. package/dist/modules/Rules/index.d.ts +3 -10
  8. package/dist/modules/Rules/index.js +169 -87
  9. package/dist/modules/Rules/promotionSelection.d.ts +14 -0
  10. package/dist/modules/Rules/promotionSelection.js +390 -0
  11. package/dist/modules/Rules/types.d.ts +9 -0
  12. package/dist/server/modules/order/index.d.ts +6 -0
  13. package/dist/server/modules/order/index.js +782 -447
  14. package/dist/solution/BaseSales/index.js +41 -21
  15. package/dist/solution/BaseSales/utils/cartPromotion.js +5 -2
  16. package/dist/solution/BookingByStep/index.d.ts +1 -1
  17. package/lib/model/strategy/adapter/promotion/evaluator.js +5 -4
  18. package/lib/model/strategy/adapter/promotion/index.js +1 -46
  19. package/lib/modules/Discount/types.d.ts +4 -0
  20. package/lib/modules/Order/index.d.ts +1 -1
  21. package/lib/modules/Order/index.js +11 -0
  22. package/lib/modules/Order/utils.js +1 -1
  23. package/lib/modules/Payment/walletpass.js +23 -1
  24. package/lib/modules/Rules/index.d.ts +3 -10
  25. package/lib/modules/Rules/index.js +62 -22
  26. package/lib/modules/Rules/promotionSelection.d.ts +14 -0
  27. package/lib/modules/Rules/promotionSelection.js +230 -0
  28. package/lib/modules/Rules/types.d.ts +9 -0
  29. package/lib/server/modules/order/index.d.ts +6 -0
  30. package/lib/server/modules/order/index.js +226 -29
  31. package/lib/solution/BaseSales/index.js +19 -5
  32. package/lib/solution/BaseSales/utils/cartPromotion.js +5 -2
  33. package/lib/solution/BookingByStep/index.d.ts +1 -1
  34. package/package.json +1 -1
@@ -42,6 +42,7 @@ import { PickupTimingController } from "./pickupTiming";
42
42
  import { FulfillmentItemRulesController } from "./fulfillmentItemRules";
43
43
  import { getProductHolderRelations, hasProductBooking } from "../../modules/Order/holderRelations";
44
44
  import { resolveContactInfoConfig, getMissingContactInfoFields, ContactInfoRequiredError } from "../../modules/OpenData/contactInfo";
45
+ import { getExclusivePromotion, isPromotionDiscountCard } from "../../modules/Rules/promotionSelection";
45
46
  import Decimal from 'decimal.js';
46
47
  import { cloneDeep, isEqual, mergeWith } from 'lodash-es';
47
48
  import { createModule } from "../BookingByStep/types";
@@ -3364,16 +3365,23 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3364
3365
  if (currentDiscount.isManualSelect) {
3365
3366
  return _objectSpread(_objectSpread({}, discount), {}, {
3366
3367
  isSelected: false,
3367
- isManualSelect: true
3368
+ isManualSelect: true,
3369
+ promotionSelection: currentDiscount.promotionSelection,
3370
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3368
3371
  });
3369
3372
  }
3370
3373
  if (currentDiscount.isSelected) {
3371
3374
  return _objectSpread(_objectSpread({}, discount), {}, {
3372
3375
  isSelected: true,
3373
- isManualSelect: false
3376
+ isManualSelect: false,
3377
+ promotionSelection: currentDiscount.promotionSelection,
3378
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3374
3379
  });
3375
3380
  }
3376
- return discount;
3381
+ return currentDiscount.promotionSelection ? _objectSpread(_objectSpread({}, discount), {}, {
3382
+ promotionSelection: currentDiscount.promotionSelection,
3383
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3384
+ }) : discount;
3377
3385
  });
3378
3386
  }
3379
3387
  }, {
@@ -3795,9 +3803,10 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3795
3803
  }
3796
3804
  throw new Error('order 模块未初始化');
3797
3805
  case 2:
3806
+ this.hasManualDiscountSelection = false;
3798
3807
  tempOrder = this.store.order.ensureTempOrder();
3799
3808
  if (!this.isActiveVirtualSettlementOrder(tempOrder)) {
3800
- _context33.next = 7;
3809
+ _context33.next = 8;
3801
3810
  break;
3802
3811
  }
3803
3812
  _result2 = {
@@ -3806,7 +3815,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3806
3815
  };
3807
3816
  cb === null || cb === void 0 || cb(_result2);
3808
3817
  return _context33.abrupt("return", _result2);
3809
- case 7:
3818
+ case 8:
3810
3819
  orderStore = this.store.order.store || {};
3811
3820
  discountModule = orderStore.discount;
3812
3821
  rulesModule = orderStore.rules;
@@ -3817,11 +3826,11 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3817
3826
  productList: tempOrder.products || [],
3818
3827
  discountList: nextDiscountList
3819
3828
  };
3820
- _context33.next = 16;
3829
+ _context33.next = 17;
3821
3830
  return discountModule === null || discountModule === void 0 ? void 0 : discountModule.setDiscountList(nextDiscountList);
3822
- case 16:
3831
+ case 17:
3823
3832
  if (!rulesModule) {
3824
- _context33.next = 27;
3833
+ _context33.next = 28;
3825
3834
  break;
3826
3835
  }
3827
3836
  orderTotalAmount = Number(((_orderStore$summary2 = orderStore.summary) === null || _orderStore$summary2 === void 0 ? void 0 : _orderStore$summary2.total_amount) || 0);
@@ -3840,14 +3849,14 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3840
3849
  tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
3841
3850
  }
3842
3851
  if (!result.discountList) {
3843
- _context33.next = 27;
3852
+ _context33.next = 28;
3844
3853
  break;
3845
3854
  }
3846
3855
  nextDiscountList = this.mergeHistoricalDiscountList(result.discountList, tempOrder.products || []);
3847
3856
  OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
3848
- _context33.next = 25;
3857
+ _context33.next = 26;
3849
3858
  return discountModule === null || discountModule === void 0 ? void 0 : discountModule.setDiscountList(nextDiscountList);
3850
- case 25:
3859
+ case 26:
3851
3860
  tempOrder.discount_list = nextDiscountList.filter(function (discount) {
3852
3861
  return discount.isSelected;
3853
3862
  });
@@ -3855,24 +3864,24 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3855
3864
  productList: tempOrder.products,
3856
3865
  discountList: nextDiscountList
3857
3866
  };
3858
- case 27:
3859
- _context33.next = 29;
3867
+ case 28:
3868
+ _context33.next = 30;
3860
3869
  return this.store.order.recalculateSummary({
3861
3870
  createIfMissing: true
3862
3871
  });
3863
- case 29:
3872
+ case 30:
3864
3873
  this.store.order.persistTempOrder();
3865
- _context33.next = 32;
3874
+ _context33.next = 33;
3866
3875
  return this.effectsEmit('onDiscountApplied', {
3867
3876
  productList: tempOrder.products || [],
3868
3877
  discountList: nextDiscountList,
3869
3878
  selectedDiscountList: tempOrder.discount_list || [],
3870
3879
  tempOrder: tempOrder
3871
3880
  });
3872
- case 32:
3881
+ case 33:
3873
3882
  cb === null || cb === void 0 || cb(result);
3874
3883
  return _context33.abrupt("return", result);
3875
- case 34:
3884
+ case 35:
3876
3885
  case "end":
3877
3886
  return _context33.stop();
3878
3887
  }
@@ -4012,7 +4021,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4012
4021
  key: "setDiscountSelected",
4013
4022
  value: function () {
4014
4023
  var _setDiscountSelected = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee36(params) {
4015
- var currentOrder, _store3, _store3$setDiscountLi, list, updated, tempOrder, orderStore, _discountModule, rulesModule, nextDiscountList, _orderStore$summary3, orderTotalAmount, result, beforeSelectedIds, _iterator6, _step6, d, selectedResourceIds, filterSelectedDiscountDetails, _iterator7, _step7, _product$metadata8, _tempOrder$_extend7, _product$metadata$sou2, _product$metadata9, _product$metadata10, _product$original_pri2, product, productUid, runtimeOrigin, totalPerUnitDiscount, optionSum, sourcePrice, newSourceSellingPrice, newMainSellingPrice;
4024
+ var currentOrder, _store3, _store3$setDiscountLi, list, updated, tempOrder, orderStore, _discountModule, rulesModule, nextDiscountList, _orderStore$summary3, orderTotalAmount, result, beforeSelectedIds, promotionCardIds, _iterator6, _step6, d, selectedResourceIds, filterSelectedDiscountDetails, _iterator7, _step7, _product$metadata8, _tempOrder$_extend7, _product$metadata$sou2, _product$metadata9, _product$metadata10, _product$original_pri2, product, productUid, runtimeOrigin, totalPerUnitDiscount, optionSum, sourcePrice, newSourceSellingPrice, newMainSellingPrice;
4016
4025
  return _regeneratorRuntime().wrap(function _callee36$(_context36) {
4017
4026
  while (1) switch (_context36.prev = _context36.next) {
4018
4027
  case 0:
@@ -4084,12 +4093,21 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4084
4093
  return d.isSelected;
4085
4094
  }).map(function (d) {
4086
4095
  return d.id;
4096
+ })); // Rules 已对促销组完成互斥报价,不能再移除其选中的卡而留下已取消的促销。
4097
+ promotionCardIds = new Set((result.productList || []).filter(function (product) {
4098
+ var _getExclusivePromotio;
4099
+ return (_getExclusivePromotio = getExclusivePromotion(product)) === null || _getExclusivePromotio === void 0 ? void 0 : _getExclusivePromotio.excludedByDiscountCard;
4100
+ }).flatMap(function (product) {
4101
+ return (product.discount_list || []).filter(isPromotionDiscountCard).map(function (discount) {
4102
+ var _discount$discount$re, _discount$discount5;
4103
+ return String((_discount$discount$re = (_discount$discount5 = discount.discount) === null || _discount$discount5 === void 0 ? void 0 : _discount$discount5.resource_id) !== null && _discount$discount$re !== void 0 ? _discount$discount$re : discount.id);
4104
+ });
4087
4105
  }));
4088
4106
  _iterator6 = _createForOfIteratorHelper(nextDiscountList);
4089
4107
  try {
4090
4108
  for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
4091
4109
  d = _step6.value;
4092
- if (d.isSelected && !beforeSelectedIds.has(d.id)) {
4110
+ if (d.isSelected && !beforeSelectedIds.has(d.id) && !promotionCardIds.has(String(d.id))) {
4093
4111
  d.isSelected = false;
4094
4112
  d.isManualSelect = true;
4095
4113
  d.appliedProductDetails = [];
@@ -4110,7 +4128,9 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4110
4128
  }));
4111
4129
  filterSelectedDiscountDetails = function filterSelectedDiscountDetails(discountList) {
4112
4130
  return (discountList || []).filter(function (pd) {
4113
- var _pd$discount$resource, _pd$discount;
4131
+ var _pd$metadata, _pd$discount$resource, _pd$discount;
4132
+ // 互斥计算保留/恢复的系统促销没有钱包 resource_id,不能按已选卡列表移除。
4133
+ if (pd.type === 'promotion' || pd.type === 'product' && ((_pd$metadata = pd.metadata) === null || _pd$metadata === void 0 ? void 0 : _pd$metadata.source) === 'promotion') return true;
4114
4134
  var rid = (_pd$discount$resource = (_pd$discount = pd.discount) === null || _pd$discount === void 0 ? void 0 : _pd$discount.resource_id) !== null && _pd$discount$resource !== void 0 ? _pd$discount$resource : pd.id;
4115
4135
  return rid != null && selectedResourceIds.has(rid);
4116
4136
  });
@@ -4151,7 +4171,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4151
4171
  // 券作用于 source(不含 option、不含 bundle);算出新 source 折后价后补回 options
4152
4172
  // 写入含 option 的 main_product_selling_price,再合成 composite 回写 selling_price。
4153
4173
  totalPerUnitDiscount = (product.discount_list || []).reduce(function (sum, pd) {
4154
- return sum + (pd.amount || 0);
4174
+ return sum + Number(pd.amount || 0);
4155
4175
  }, 0); // TODO 这块逻辑需要拿掉
4156
4176
  optionSum = sumOptionUnitPrice(getProductSkuOptions(product));
4157
4177
  sourcePrice = (_product$metadata$sou2 = (_product$metadata9 = product.metadata) === null || _product$metadata9 === void 0 ? void 0 : _product$metadata9.source_product_price) !== null && _product$metadata$sou2 !== void 0 ? _product$metadata$sou2 : ((_product$metadata10 = product.metadata) === null || _product$metadata10 === void 0 ? void 0 : _product$metadata10.main_product_original_price) != null ? new Decimal(Number(product.metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : (_product$original_pri2 = product.original_price) !== null && _product$original_pri2 !== void 0 ? _product$original_pri2 : '0';
@@ -259,7 +259,10 @@ function resolveXItemsExpectedUnitPrice(promotion, sourceCartNum) {
259
259
  var y = Number(detail === null || detail === void 0 ? void 0 : detail.price);
260
260
  if (!Number.isFinite(x) || x <= 0 || !Number.isFinite(y)) return undefined;
261
261
  if (sourceCartNum < x) return undefined;
262
- return Number(new Decimal(y).div(x).toDecimalPlaces(2).toFixed(2));
262
+ var originalPrice = Number(promotion === null || promotion === void 0 ? void 0 : promotion.originalPrice);
263
+ var expectedUnit = new Decimal(y).div(x);
264
+ // 归并拆分行时沿用评估器的原价上限,避免重新按 Y / X 把原价抬高。
265
+ return (Number.isFinite(originalPrice) && originalPrice >= 0 ? Decimal.min(expectedUnit, originalPrice) : expectedUnit).toDecimalPlaces(2).toNumber();
263
266
  }
264
267
 
265
268
  /**
@@ -948,7 +951,7 @@ export function calculateUnfulfilledPromotions(processedProducts, applicableStra
948
951
  var _product$metadata5, _ref13, _product$_originalPro, _product$metadata6, _product$num2;
949
952
  var product = processedProducts[i];
950
953
  var promotion = product === null || product === void 0 || (_product$metadata5 = product.metadata) === null || _product$metadata5 === void 0 ? void 0 : _product$metadata5._promotion;
951
- if (!promotion || promotion.inPromotion !== false) return 0; // continue
954
+ if (!promotion || promotion.inPromotion !== false || promotion.excludedByDiscountCard) return 0; // continue
952
955
  var strategyId = promotion.strategyId;
953
956
  if (!strategyId) return 0; // continue
954
957
  var lookupUid = String((_ref13 = (_product$_originalPro = product === null || product === void 0 ? void 0 : product._originalProductUid) !== null && _product$_originalPro !== void 0 ? _product$_originalPro : product === null || product === void 0 || (_product$metadata6 = product.metadata) === null || _product$metadata6 === void 0 ? void 0 : _product$metadata6.unique_identification_number) !== null && _ref13 !== void 0 ? _ref13 : '');
@@ -328,7 +328,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
328
328
  date: string;
329
329
  status: string;
330
330
  week: string;
331
- weekNum: 0 | 2 | 1 | 6 | 4 | 5 | 3;
331
+ weekNum: 0 | 1 | 2 | 3 | 4 | 5 | 6;
332
332
  }[]>;
333
333
  submitTimeSlot(timeSlots: TimeSliceItem): void;
334
334
  private getScheduleDataByIds;
@@ -646,6 +646,7 @@ class PromotionEvaluator {
646
646
  // 按组内原价比例均摊
647
647
  // 记录每个原商品的均摊价格累加(用于后续聚合)
648
648
  const allocatedPricesByProductId = new Map();
649
+ let expectedPromoTotal = new _decimal.default(0);
649
650
  for (let g = 0; g < groupCount; g++) {
650
651
  const startIdx = g * x;
651
652
  const endIdx = startIdx + x;
@@ -654,8 +655,9 @@ class PromotionEvaluator {
654
655
  // 计算组内原价总和
655
656
  const groupOriginalTotal = groupUnits.reduce((sum, u) => sum.plus(u.price), new _decimal.default(0));
656
657
 
657
- // 按原价比例均摊
658
- const groupPriceDecimal = new _decimal.default(groupPrice);
658
+ // 组价高于本组原价时保留原价,尾差目标也必须使用封顶后的实际组价。
659
+ const groupPriceDecimal = _decimal.default.min(new _decimal.default(groupPrice), groupOriginalTotal);
660
+ expectedPromoTotal = expectedPromoTotal.plus(groupPriceDecimal);
659
661
  let allocatedSum = new _decimal.default(0);
660
662
  for (let i = 0; i < groupUnits.length; i++) {
661
663
  const unit = groupUnits[i];
@@ -759,9 +761,8 @@ class PromotionEvaluator {
759
761
  processedQuantityMap.set(key, processedQty + availableQty);
760
762
  }
761
763
 
762
- // 8. 尾差调整:确保促销商品的 finalPrice × quantity 之和精确等于 groupPrice × groupCount
764
+ // 8. 尾差调整:只补实际组价的舍入差额,不将高于原价的组价补到某一件。
763
765
  if (groupCount > 0) {
764
- const expectedPromoTotal = new _decimal.default(groupPrice).mul(groupCount);
765
766
  const promoItems = result.filter(p => p.inPromotion);
766
767
  let actualPromoTotal = new _decimal.default(0);
767
768
  for (const p of promoItems) {
@@ -1,46 +1 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- Object.defineProperty(exports, "BUY_X_GET_Y_FREE_STRATEGY", {
7
- enumerable: true,
8
- get: function () {
9
- return _examples.BUY_X_GET_Y_FREE_STRATEGY;
10
- }
11
- });
12
- Object.defineProperty(exports, "ITEM_REWARD_STRATEGY", {
13
- enumerable: true,
14
- get: function () {
15
- return _examples.ITEM_REWARD_STRATEGY;
16
- }
17
- });
18
- Object.defineProperty(exports, "PromotionAdapter", {
19
- enumerable: true,
20
- get: function () {
21
- return _adapter.PromotionAdapter;
22
- }
23
- });
24
- Object.defineProperty(exports, "PromotionEvaluator", {
25
- enumerable: true,
26
- get: function () {
27
- return _evaluator.PromotionEvaluator;
28
- }
29
- });
30
- Object.defineProperty(exports, "X_ITEMS_FOR_Y_PRICE_STRATEGY", {
31
- enumerable: true,
32
- get: function () {
33
- return _examples.X_ITEMS_FOR_Y_PRICE_STRATEGY;
34
- }
35
- });
36
- Object.defineProperty(exports, "default", {
37
- enumerable: true,
38
- get: function () {
39
- return _adapter.default;
40
- }
41
- });
42
- var _evaluator = require("./evaluator");
43
- var _adapter = _interopRequireWildcard(require("./adapter"));
44
- var _examples = require("./examples");
45
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
46
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
1
+ "use strict";
@@ -158,6 +158,10 @@ export interface Discount {
158
158
  discount_calculation_mode: 'item_level' | 'order_level';
159
159
  };
160
160
  isManualSelect?: boolean;
161
+ /** X 件 Y 元互斥选择的手动意图;isSelected 只表示本次实际应用结果。 */
162
+ promotionSelection?: 'card' | 'promotion';
163
+ /** 记录手动操作影响的促销组,避免卡失效后普通重算丢失取消意图。 */
164
+ promotionSelectionStrategyIds?: string[];
161
165
  isDisabled?: boolean;
162
166
  isSelected?: boolean;
163
167
  isAvailable?: boolean;
@@ -595,7 +595,7 @@ export declare class OrderModule extends BaseModule implements Module, OrderModu
595
595
  generateIdempotencyToken(): string;
596
596
  syncPaymentsToOrder<T = any>(params: SyncPaymentsToOrderParams): Promise<SyncPaymentsToOrderResult<T>>;
597
597
  createOrder(params: CommitOrderParams['query']): {
598
- type: "appointment_booking" | "virtual";
598
+ type: "virtual" | "appointment_booking";
599
599
  platform: string;
600
600
  sales_channel: string;
601
601
  order_sales_channel: string;
@@ -593,6 +593,7 @@ class OrderModule extends _BaseModule.BaseModule {
593
593
  }
594
594
  if (discountList) {
595
595
  const currentDiscountList = this.store.discount?.getDiscountList() || [];
596
+ const currentPromotionSelections = new Map(currentDiscountList.filter(discount => !discount.isEditMode && discount.promotionSelection).map(discount => [String(discount.id), discount]));
596
597
  const currentCommittedDiscounts = currentDiscountList.filter(discount => discount?.isEditMode || discount?.committedAppliedProductDetails?.length);
597
598
  const currentScanDiscounts = currentDiscountList.filter(discount => discount?.isScan);
598
599
  const currentScanDiscountById = new Map(currentScanDiscounts.flatMap(discount => {
@@ -630,6 +631,16 @@ class OrderModule extends _BaseModule.BaseModule {
630
631
  isManualSelect: currentScanDiscount.isManualSelect ?? nextDiscount.isManualSelect
631
632
  };
632
633
  }
634
+ const currentSelection = currentPromotionSelections.get(String(discount.id));
635
+ if (currentSelection) {
636
+ nextDiscount = {
637
+ ...nextDiscount,
638
+ promotionSelection: currentSelection.promotionSelection,
639
+ promotionSelectionStrategyIds: currentSelection.promotionSelectionStrategyIds,
640
+ isManualSelect: currentSelection.isManualSelect,
641
+ isSelected: currentSelection.isSelected
642
+ };
643
+ }
633
644
  return [nextDiscount];
634
645
  });
635
646
  const retainedCommittedDiscounts = currentCommittedDiscounts.filter(discount => {
@@ -1139,7 +1139,7 @@ function formatSubmitOptionItems(options, formatOptions = {}) {
1139
1139
  const option = {
1140
1140
  ...(d && typeof d === 'object' ? d : {}),
1141
1141
  num: d?.num,
1142
- option_group_item_id: d?.option_group_item_id,
1142
+ option_group_item_id: d?.option_group_item_id ?? d?.product_option_item_id ?? d?.id,
1143
1143
  option_group_id: d?.option_group_id
1144
1144
  };
1145
1145
  const productionCode = normalizeSubmitProductionCode(d?.production_code);
@@ -1146,7 +1146,10 @@ class WalletPassPaymentImpl {
1146
1146
  if (paymentAssets.length > 0) {
1147
1147
  this.searchResults = mergeWalletAssets(this.searchResults, paymentAssets);
1148
1148
  }
1149
- const asset = paymentAssets.find(item => String(item?.code || '') === normalizedCode) || paymentAssets[0];
1149
+ const matchedAsset = paymentAssets.find(item => String(item?.code || '') === normalizedCode);
1150
+ // 精确命中券码时仅处理该券;未命中时处理接口返回的全部结果。
1151
+ const assetsToApply = matchedAsset ? [matchedAsset] : paymentAssets;
1152
+ const asset = assetsToApply[0];
1150
1153
  if (!asset) {
1151
1154
  return {
1152
1155
  type: 'normalCode',
@@ -1155,6 +1158,25 @@ class WalletPassPaymentImpl {
1155
1158
  state: this.getWalletAssetsState()
1156
1159
  };
1157
1160
  }
1161
+
1162
+ // 根据 code 找不到结果时,则使用接口返回的所有券数据(扫手环)
1163
+ if (!matchedAsset && assetsToApply.length > 1) {
1164
+ const items = mergeWalletAssets(this.walletAssetsState.items, assetsToApply);
1165
+ const assetIds = assetsToApply.map(item => getWalletAssetId(item)).filter(id => id !== undefined && id !== null);
1166
+ const selectionSources = {
1167
+ ...this.walletAssetsState.selectionSources
1168
+ };
1169
+ assetIds.forEach(id => {
1170
+ selectionSources[String(id)] = 'scan';
1171
+ });
1172
+ const selected = this.walletAssetsBehavior.autoSelectAfterSearch ? this.recalculateWalletAssets(items, Array.from(new Set([...this.walletAssetsState.selectedIds, ...assetIds])), selectionSources) : this.recalculateWalletAssets(items, this.walletAssetsState.selectedIds, this.walletAssetsState.selectionSources);
1173
+ return {
1174
+ type: result.type,
1175
+ asset,
1176
+ selected: assetIds.some(id => selected.selectedIds.includes(id)),
1177
+ state: selected
1178
+ };
1179
+ }
1158
1180
  const items = mergeWalletAssets(this.walletAssetsState.items, [asset]);
1159
1181
  const recalculatedState = this.recalculateWalletAssets(items, this.walletAssetsState.selectedIds, this.walletAssetsState.selectionSources);
1160
1182
  const assetId = getWalletAssetId(asset);
@@ -1,6 +1,6 @@
1
1
  import { Module, PisellCore, ModuleOptions } from '../../types';
2
2
  import { BaseModule } from '../BaseModule';
3
- import { Rules, RulesModuleAPI, DiscountResult, RulesFormSubject, RulesCalcDiscountOptions, UnavailableReason } from './types';
3
+ import { Rules, RulesModuleAPI, DiscountResult, RulesFormSubject, RulesCalcDiscountOptions, RulesCalcDiscountParams, UnavailableReason } from './types';
4
4
  import { Discount } from '../Discount/types';
5
5
  import { WindowPlugin } from '../../plugins';
6
6
  export declare class RulesModule extends BaseModule implements Module, RulesModuleAPI {
@@ -44,15 +44,8 @@ export declare class RulesModule extends BaseModule implements Module, RulesModu
44
44
  resolveDiscountListForManualOverride(discountList: Discount[]): Discount[];
45
45
  private isItemRewardProductDiscount;
46
46
  private getUnavailableReason;
47
- calcDiscount({ discountList, productList, holders, isFormSubject, orderTotalAmount }: {
48
- discountList: Discount[];
49
- productList: any[];
50
- holders: {
51
- form_record_id: number;
52
- }[];
53
- isFormSubject: RulesFormSubject;
54
- orderTotalAmount: number;
55
- }, options?: RulesCalcDiscountOptions): DiscountResult;
47
+ calcDiscount(params: RulesCalcDiscountParams, options?: RulesCalcDiscountOptions): DiscountResult;
48
+ private calcDiscountCore;
56
49
  /**
57
50
  * 检查优惠是否符合 PackageSubItemUsageRules 配置
58
51
  * @param discount 优惠券
@@ -14,6 +14,7 @@ var _lodashEs = require("lodash-es");
14
14
  var _dayjs = _interopRequireDefault(require("dayjs"));
15
15
  var _entitlementPass = require("../Discount/entitlementPass");
16
16
  var _availability = require("../Discount/availability");
17
+ var _promotionSelection = require("./promotionSelection");
17
18
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18
19
  class RulesModule extends _BaseModule.BaseModule {
19
20
  defaultName = 'rules';
@@ -146,6 +147,12 @@ class RulesModule extends _BaseModule.BaseModule {
146
147
  }
147
148
  });
148
149
 
150
+ // 卡可用但互斥比较选择了促销时,扫码仍应加入可选卡列表,不能被标为商品不适用。
151
+ if (!hasApplicableDiscount) {
152
+ const promotionProductIds = new Set(result.productList.filter(product => (0, _promotionSelection.getExclusivePromotion)(product)?.inPromotion === true).map(product => this.hooks.getProduct(product).id));
153
+ hasApplicableDiscount = result.discountList.some(discount => newDiscountIds.includes(discount.id) && (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.isAvailable && discount.applicableProductIds?.some(id => promotionProductIds.has(id)));
154
+ }
155
+
149
156
  // 如果券不可用,判断不可用原因
150
157
  let unavailableReason;
151
158
  if (!hasApplicableDiscount) {
@@ -213,13 +220,28 @@ class RulesModule extends _BaseModule.BaseModule {
213
220
  }
214
221
  return _types.UnavailableReason.Unknown;
215
222
  }
216
- calcDiscount({
223
+ calcDiscount(params, options) {
224
+ return (0, _promotionSelection.calculatePromotionSelection)(params, options, this.hooks, (input, calculationOptions, policy) => this.calcDiscountCore(input, calculationOptions, policy));
225
+ }
226
+ calcDiscountCore({
217
227
  discountList,
218
228
  productList,
219
229
  holders,
220
230
  isFormSubject,
221
231
  orderTotalAmount
222
- }, options) {
232
+ }, options, promotionPolicy) {
233
+ const cancelledPromotionCards = discountList.filter(discount => !discount.isEditMode && (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.promotionSelection === 'promotion');
234
+ const cancelledPromotionProductIds = new Set(cancelledPromotionCards.flatMap(discount => discount.applicableProductIds || []));
235
+ const cancelledPromotionStrategyIds = new Set(cancelledPromotionCards.flatMap(discount => discount.promotionSelectionStrategyIds || []));
236
+ const isCardBlockedByPromotion = (flatItem, discount) => {
237
+ if (flatItem.type !== 'main' || !(0, _promotionSelection.isPromotionDiscountCard)(discount)) return false;
238
+ const originProduct = flatItem.originProduct;
239
+ if (originProduct?.order_detail_id || originProduct?.orderDetailId || originProduct?.booking_id || originProduct?.metadata?.booking_id) return false;
240
+ // 取消卡后即使数量暂未凑足促销,也不能自动改用另一张卡;重新手选/最佳组合会清除该意图。
241
+ if (cancelledPromotionProductIds.has(flatItem.product.id) || cancelledPromotionStrategyIds.has(String(originProduct?.metadata?._promotion?.strategyId))) return true;
242
+ const promotion = (0, _promotionSelection.getExclusivePromotion)(originProduct);
243
+ return Boolean(promotion && promotionPolicy?.blockedStrategyIds.has(String(promotion.strategyId)));
244
+ };
223
245
  const preferredEntitlementPassIds = new Set((options?.preferredEntitlementPassIds || []).map(String));
224
246
  const resolveIsFormSubject = product => typeof isFormSubject === 'function' ? Boolean(isFormSubject(product)) : Boolean(isFormSubject);
225
247
 
@@ -724,6 +746,7 @@ class RulesModule extends _BaseModule.BaseModule {
724
746
  // 辅助函数:检查商品是否对某个折扣卡可用
725
747
  const checkItemApplicableForDiscount = (flatItem, discount) => {
726
748
  if (discount.config?.isAvailable === false) return false;
749
+ if (isCardBlockedByPromotion(flatItem, discount)) return false;
727
750
  let product;
728
751
  if (flatItem.type === 'main') {
729
752
  product = flatItem.product;
@@ -784,6 +807,11 @@ class RulesModule extends _BaseModule.BaseModule {
784
807
  return isLimitedProduct && isBundleAvailable;
785
808
  };
786
809
 
810
+ // 分摊占位与实际应用共用选择优先级,数量跌出促销门槛时也保留手选意图。
811
+ const findExplicitlySelectedDiscount = applicableDiscounts => (options?.isSelected === true && options.discountId !== undefined ? applicableDiscounts.find(discount => String(discount.id) === String(options.discountId) && ((0, _entitlementPass.isFullCoveragePass)(discount) || (0, _promotionSelection.isPromotionDiscountCard)(discount))) : undefined) || (options?.preserveEntitlementSelection !== false ? applicableDiscounts.find(discount => discount.promotionSelection === 'card') : undefined);
812
+ const getAppliedWalletDiscountIds = product => new Set((product.discount_list || []).filter(item => ['entitlement_pass', 'discount_card', 'product_discount_card'].includes(item?.tag || item?.type)).map(item => item?.discount?.resource_id ?? item?.resource_id ?? item?.id).filter(id => id !== undefined && id !== null).map(String));
813
+ const findAppliedDiscountCard = (applicableDiscounts, appliedIds) => options?.scan || options?.preserveEntitlementSelection === false ? undefined : applicableDiscounts.find(discount => discount.isSelected === true && (0, _promotionSelection.isPromotionDiscountCard)(discount) && appliedIds.has(String(discount.id)));
814
+
787
815
  // 收集所有被勾选的 order_level 折扣卡及其适用商品
788
816
  const selectedOrderLevelDiscounts = sortedDiscountList.filter(discount => {
789
817
  return (0, _utils.isOrderLevelFixedAmountDiscount)(discount) && discount.isSelected !== false;
@@ -811,6 +839,18 @@ class RulesModule extends _BaseModule.BaseModule {
811
839
  // Map<flatItemId, discountId> - 记录被占用的商品及其对应的折扣卡
812
840
  const occupiedItems = new Map();
813
841
 
842
+ // 手选/已应用的卡先占位(包括全品类卡),其他候选卡不能抢走其分摊商品。
843
+ sortedFlattenedList.forEach(flatItem => {
844
+ const product = flatItem.type === 'main' ? flatItem.product : flatItem.bundleItem;
845
+ const holderProduct = flatItem.type === 'main' ? flatItem.product : flatItem.parentProduct;
846
+ const applicableCards = sortedDiscountList.filter(discount => (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.config?.isAvailable && checkItemApplicableForDiscount(flatItem, discount) && this.checkHolderMatch(discount, {
847
+ isNeedHolder: resolveIsFormSubject(holderProduct) && !holderProduct?.isNormalProduct,
848
+ holder_id: holderProduct?.holder_id || product.holder_id
849
+ }, flatItem.originProduct, holders));
850
+ const preferredCard = findExplicitlySelectedDiscount(applicableCards) || findAppliedDiscountCard(applicableCards, getAppliedWalletDiscountIds(product)) || applicableCards.find(discount => discount.isScan && discount.isSelected);
851
+ if (preferredCard) occupiedItems.set(flatItem._id, preferredCard.id);
852
+ });
853
+
814
854
  // 按排序顺序遍历折扣卡,判断哪些是专属折扣卡
815
855
  selectedOrderLevelDiscounts.forEach(discount => {
816
856
  const limitedData = discount.limited_relation_product_data;
@@ -970,6 +1010,9 @@ class RulesModule extends _BaseModule.BaseModule {
970
1010
  if (isAvailableProduct && !isItemRewardProductDiscount && isLimitedProduct && timeLimit && isBundleAvailable && discount.config?.isAvailable && ((0, _entitlementPass.isFullCoveragePass)(discount) || isDiscountCardPriceAvailable(flatItem, discount)) && (!(0, _entitlementPass.isEntitlementPass)(discount) || (0, _entitlementPass.getRemainingEntitlementUses)(discount, 0, 1) > 0)) {
971
1011
  // 记录此优惠券适用的商品
972
1012
  discountApplicability.get(discount.id)?.push(product.id);
1013
+ if (flatItem.type === 'main' && (0, _promotionSelection.isPromotionDiscountCard)(discount)) {
1014
+ promotionPolicy?.onApplicableCard?.(originProduct, discount);
1015
+ }
973
1016
 
974
1017
  // 记录可抵扣的商品详情
975
1018
  const applicableProducts = discountApplicableProducts.get(discount.id) || [];
@@ -1114,6 +1157,7 @@ class RulesModule extends _BaseModule.BaseModule {
1114
1157
  // 找到适用于此商品的所有优惠券,仅考虑isSelected不为false的优惠券
1115
1158
  const applicableDiscounts = sortedDiscountList.filter(discount => {
1116
1159
  if (this.isItemRewardProductDiscount(product)) return false;
1160
+ if (isCardBlockedByPromotion(flatItem, discount)) return false;
1117
1161
  // 🔥 检查策略可用性(针对全额抵扣卡和折扣卡)
1118
1162
  const discountType = discount.tag || discount.type;
1119
1163
  const currentOriginUid = getOriginProductUid(originProduct);
@@ -1193,20 +1237,14 @@ class RulesModule extends _BaseModule.BaseModule {
1193
1237
 
1194
1238
  // 识别用户本次显式选择的卡券,供次卡和折扣卡各自的优先级使用。
1195
1239
  // 目标仍必须在当前商品的 applicableDiscounts 中,因此不会绕过 Holder、时间或商品范围校验。
1196
- const explicitlySelectedDiscount = options?.isSelected === true && options.discountId !== undefined ? applicableDiscounts.find(discount => {
1197
- const discountType = discount.tag || discount.type;
1198
- return String(discount.id) === String(options.discountId) && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType ?? '');
1199
- }) : undefined;
1240
+ const explicitlySelectedDiscount = findExplicitlySelectedDiscount(applicableDiscounts);
1200
1241
  // 折扣卡会复用于整条商品行;商品券必须继续按单张拆分,不能复用该分支。
1201
1242
  const explicitlySelectedDiscountCard = explicitlySelectedDiscount && !(0, _entitlementPass.isFullCoveragePass)(explicitlySelectedDiscount) ? explicitlySelectedDiscount : undefined;
1202
1243
 
1203
1244
  // 商品数量等变化会触发无 discountId 的重算。只要当前行已应用的卡仍在
1204
1245
  // applicableDiscounts 中,就应保留该行选择,避免被自动排序中力度更大的卡替换。
1205
- const appliedWalletDiscountIds = new Set((product.discount_list || []).filter(item => ['entitlement_pass', 'discount_card', 'product_discount_card'].includes(item?.tag || item?.type)).map(item => item?.discount?.resource_id ?? item?.resource_id ?? item?.id).filter(id => id !== undefined && id !== null).map(String));
1206
- const appliedDiscountCard = options?.scan ? undefined : applicableDiscounts.find(discount => {
1207
- const discountType = discount.tag || discount.type;
1208
- return discount.isSelected === true && ['discount_card', 'product_discount_card'].includes(discountType ?? '') && appliedWalletDiscountIds.has(String(discount.id));
1209
- });
1246
+ const appliedWalletDiscountIds = getAppliedWalletDiscountIds(product);
1247
+ const appliedDiscountCard = findAppliedDiscountCard(applicableDiscounts, appliedWalletDiscountIds);
1210
1248
  const appliedEntitlementPass = options?.scan || options?.preserveEntitlementSelection === false ? undefined : applicableDiscounts.find(discount => (0, _entitlementPass.isEntitlementPass)(discount) && discount.isSelected === true && appliedWalletDiscountIds.has(String(discount.id)));
1211
1249
 
1212
1250
  // 次卡内部按本次手选/扫码、当前行已应用、默认排序选择。
@@ -1441,14 +1479,15 @@ class RulesModule extends _BaseModule.BaseModule {
1441
1479
  let discountedOptions = product.options;
1442
1480
  let optionDiscountAmount = 0;
1443
1481
  let reapplyDiscountPercent;
1444
- if (isOrderLevel && productAllocation) {
1445
- // order_level:使用预计算的分摊金额
1446
- amount = productAllocation.discountAmount;
1447
- productDiscountDifference = productAllocation.difference;
1482
+ const bookingDiscountPercent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1483
+ if (isOrderLevel && (productAllocation || bookingDiscountPercent === undefined)) {
1484
+ // 整单卡只能使用分摊结果,缺少分摊时不能回退为每件扣减整单额度。
1485
+ amount = productAllocation?.discountAmount ?? 0;
1486
+ productDiscountDifference = productAllocation?.difference;
1448
1487
  mainProductSellingPrice = Math.max(new _decimal.default(product.price).minus(amount).toNumber(), 0);
1449
- } else if (resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount) !== undefined) {
1488
+ } else if (bookingDiscountPercent !== undefined) {
1450
1489
  // Change time 重套编辑态折扣卡时,历史 par_value 不是运行时折扣口径,优先使用后端快照里的 percent。
1451
- const percent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1490
+ const percent = bookingDiscountPercent;
1452
1491
  reapplyDiscountPercent = new _decimal.default(percent).toFixed(2);
1453
1492
  mainProductSellingPrice = new _decimal.default(product.price || 0).mul(new _decimal.default(100).minus(percent)).div(100).toDecimalPlaces(2).toNumber();
1454
1493
  amount = new _decimal.default(product.price).minus(mainProductSellingPrice).toNumber();
@@ -1642,15 +1681,16 @@ class RulesModule extends _BaseModule.BaseModule {
1642
1681
  let fixedAmountPerItem;
1643
1682
  let productDiscountDifference;
1644
1683
  let reapplyDiscountPercent;
1645
- if (isOrderLevel && productAllocation) {
1684
+ const bookingDiscountPercent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1685
+ if (isOrderLevel && (productAllocation || bookingDiscountPercent === undefined)) {
1646
1686
  // order_level:使用预计算的单价折扣金额(已经是单价,无需再除以数量)
1647
- fixedAmountPerItem = productAllocation.discountAmount;
1648
- productDiscountDifference = productAllocation.difference;
1687
+ fixedAmountPerItem = productAllocation?.discountAmount ?? 0;
1688
+ productDiscountDifference = productAllocation?.difference;
1649
1689
  targetProductTotal = Math.max(new _decimal.default(productOriginTotal).minus(fixedAmountPerItem).toNumber(), 0);
1650
- } else if (resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount) !== undefined) {
1690
+ } else if (bookingDiscountPercent !== undefined) {
1651
1691
  // hydrate 后 par_value 可能是余额/原值(例如 3500),百分比口径以
1652
1692
  // 后端折扣快照 discount.percent 为准,与主商品重套逻辑保持一致。
1653
- const percent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1693
+ const percent = bookingDiscountPercent;
1654
1694
  reapplyDiscountPercent = new _decimal.default(percent).toFixed(2);
1655
1695
  targetProductTotal = new _decimal.default(productOriginTotal).mul(new _decimal.default(100).minus(percent)).div(100).toDecimalPlaces(2).toNumber();
1656
1696
  fixedAmountPerItem = new _decimal.default(productOriginTotal).minus(targetProductTotal).toNumber();
@@ -0,0 +1,14 @@
1
+ import type { Discount } from '../Discount/types';
2
+ import type { DiscountResult, RulesCalcDiscountOptions, RulesCalcDiscountParams, RulesParamsHooks } from './types';
3
+ export declare function isPromotionDiscountCard(discount: any): boolean;
4
+ /** 只处理当前购物车的 X 件 Y 元,历史成交和其他促销继续使用原有规则。 */
5
+ export declare function getExclusivePromotion(product: any): any | undefined;
6
+ export interface PromotionSelectionPolicy {
7
+ blockedStrategyIds: ReadonlySet<string>;
8
+ onApplicableCard?: (product: any, discount: Discount) => void;
9
+ }
10
+ /**
11
+ * 以完整策略参与组为单位比较两套实际报价。每次试算都从同一快照开始,
12
+ * 由原引擎重新做卡券校验和整单卡分摊,不能从叠加结果里事后减掉某条优惠。
13
+ */
14
+ export declare function calculatePromotionSelection(params: RulesCalcDiscountParams, options: RulesCalcDiscountOptions | undefined, hooks: RulesParamsHooks, calculate: (params: RulesCalcDiscountParams, options?: RulesCalcDiscountOptions, policy?: PromotionSelectionPolicy) => DiscountResult): DiscountResult;