@pisell/pisellos 2.2.318 → 2.2.320

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 (35) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.d.ts +2 -1
  2. package/dist/model/strategy/adapter/promotion/evaluator.js +19 -12
  3. package/dist/modules/Discount/types.d.ts +4 -0
  4. package/dist/modules/Order/index.js +740 -775
  5. package/dist/modules/Order/types.d.ts +2 -2
  6. package/dist/modules/Order/types.js +2 -2
  7. package/dist/modules/Order/utils.js +45 -45
  8. package/dist/modules/Payment/walletpass.js +32 -6
  9. package/dist/modules/Product/index.d.ts +1 -1
  10. package/dist/modules/Rules/index.d.ts +3 -10
  11. package/dist/modules/Rules/index.js +169 -87
  12. package/dist/modules/Rules/promotionSelection.d.ts +14 -0
  13. package/dist/modules/Rules/promotionSelection.js +390 -0
  14. package/dist/modules/Rules/types.d.ts +9 -0
  15. package/dist/solution/BaseSales/index.js +41 -21
  16. package/dist/solution/BaseSales/utils/cartPromotion.js +5 -2
  17. package/dist/solution/BookingByStep/index.d.ts +2 -2
  18. package/lib/model/strategy/adapter/promotion/evaluator.d.ts +2 -1
  19. package/lib/model/strategy/adapter/promotion/evaluator.js +18 -11
  20. package/lib/modules/Discount/types.d.ts +4 -0
  21. package/lib/modules/Order/index.js +13 -8
  22. package/lib/modules/Order/types.d.ts +2 -2
  23. package/lib/modules/Order/types.js +2 -2
  24. package/lib/modules/Order/utils.js +1 -1
  25. package/lib/modules/Payment/walletpass.js +23 -1
  26. package/lib/modules/Product/index.d.ts +1 -1
  27. package/lib/modules/Rules/index.d.ts +3 -10
  28. package/lib/modules/Rules/index.js +62 -22
  29. package/lib/modules/Rules/promotionSelection.d.ts +14 -0
  30. package/lib/modules/Rules/promotionSelection.js +230 -0
  31. package/lib/modules/Rules/types.d.ts +9 -0
  32. package/lib/solution/BaseSales/index.js +19 -5
  33. package/lib/solution/BaseSales/utils/cartPromotion.js +5 -2
  34. package/lib/solution/BookingByStep/index.d.ts +2 -2
  35. package/package.json +1 -1
@@ -313,6 +313,8 @@ class PromotionEvaluator {
313
313
  // 3. 追踪已处理的商品(避免重复处理)
314
314
  // key: `${product_id}_${product_variant_id}`
315
315
  const processedQuantityMap = new Map();
316
+ // X件Y元处理过的数量仍可作为商品奖励的触发条件。
317
+ const xItemsProcessedQuantityMap = new Map();
316
318
 
317
319
  // 4. 处理每个促销组,收集结果
318
320
  const pricedProducts = [];
@@ -328,7 +330,7 @@ class PromotionEvaluator {
328
330
  const matchedBundleIndexMap = group.productMatchedBundleIndexMap || new Map();
329
331
  if (actionType === _type.PROMOTION_ACTION_TYPES.X_ITEMS_FOR_Y_PRICE) {
330
332
  // X件Y元处理
331
- const result = this.processXItemsForYPrice(group, processedQuantityMap, matchedBundleIndexMap);
333
+ const result = this.processXItemsForYPrice(group, processedQuantityMap, xItemsProcessedQuantityMap, matchedBundleIndexMap);
332
334
  pricedProducts.push(...result.products);
333
335
  totalOriginalAmount = totalOriginalAmount.plus(result.originalAmount);
334
336
  totalFinalAmount = totalFinalAmount.plus(result.finalAmount);
@@ -345,7 +347,7 @@ class PromotionEvaluator {
345
347
  }
346
348
  } else if (actionType === _type.PROMOTION_ACTION_TYPES.ITEM_REWARD) {
347
349
  // 商品奖励处理:条件商品触发,目标商品行享优惠,不自动新增商品
348
- const result = this.processItemReward(group, processedQuantityMap, products, matchedBundleIndexMap);
350
+ const result = this.processItemReward(group, processedQuantityMap, products, xItemsProcessedQuantityMap, matchedBundleIndexMap);
349
351
  pricedProducts.push(...result.products);
350
352
  totalOriginalAmount = totalOriginalAmount.plus(result.originalAmount);
351
353
  totalFinalAmount = totalFinalAmount.plus(result.finalAmount);
@@ -566,7 +568,7 @@ class PromotionEvaluator {
566
568
  *
567
569
  * 注意:每个商品按 id 独立处理,不会合并不同 id 的商品
568
570
  */
569
- processXItemsForYPrice(group, processedQuantityMap, matchedBundleIndexMap) {
571
+ processXItemsForYPrice(group, processedQuantityMap, xItemsProcessedQuantityMap, matchedBundleIndexMap) {
570
572
  const {
571
573
  strategyId,
572
574
  strategyMetadata,
@@ -646,6 +648,7 @@ class PromotionEvaluator {
646
648
  // 按组内原价比例均摊
647
649
  // 记录每个原商品的均摊价格累加(用于后续聚合)
648
650
  const allocatedPricesByProductId = new Map();
651
+ let expectedPromoTotal = new _decimal.default(0);
649
652
  for (let g = 0; g < groupCount; g++) {
650
653
  const startIdx = g * x;
651
654
  const endIdx = startIdx + x;
@@ -654,8 +657,9 @@ class PromotionEvaluator {
654
657
  // 计算组内原价总和
655
658
  const groupOriginalTotal = groupUnits.reduce((sum, u) => sum.plus(u.price), new _decimal.default(0));
656
659
 
657
- // 按原价比例均摊
658
- const groupPriceDecimal = new _decimal.default(groupPrice);
660
+ // 组价高于本组原价时保留原价,尾差目标也必须使用封顶后的实际组价。
661
+ const groupPriceDecimal = _decimal.default.min(new _decimal.default(groupPrice), groupOriginalTotal);
662
+ expectedPromoTotal = expectedPromoTotal.plus(groupPriceDecimal);
659
663
  let allocatedSum = new _decimal.default(0);
660
664
  for (let i = 0; i < groupUnits.length; i++) {
661
665
  const unit = groupUnits[i];
@@ -757,11 +761,11 @@ class PromotionEvaluator {
757
761
 
758
762
  // 更新已处理数量
759
763
  processedQuantityMap.set(key, processedQty + availableQty);
764
+ xItemsProcessedQuantityMap.set(key, (xItemsProcessedQuantityMap.get(key) || 0) + availableQty);
760
765
  }
761
766
 
762
- // 8. 尾差调整:确保促销商品的 finalPrice × quantity 之和精确等于 groupPrice × groupCount
767
+ // 8. 尾差调整:只补实际组价的舍入差额,不将高于原价的组价补到某一件。
763
768
  if (groupCount > 0) {
764
- const expectedPromoTotal = new _decimal.default(groupPrice).mul(groupCount);
765
769
  const promoItems = result.filter(p => p.inPromotion);
766
770
  let actualPromoTotal = new _decimal.default(0);
767
771
  for (const p of promoItems) {
@@ -921,7 +925,7 @@ class PromotionEvaluator {
921
925
  * 4. 按消费者最优(可节省金额从高到低)选择目标单位
922
926
  * 5. 对目标商品拆分并写入 finalPrice,触发商品本身不改价
923
927
  */
924
- processItemReward(group, processedQuantityMap, allProducts, matchedBundleIndexMap) {
928
+ processItemReward(group, processedQuantityMap, allProducts, xItemsProcessedQuantityMap, matchedBundleIndexMap) {
925
929
  const {
926
930
  strategyId,
927
931
  strategyMetadata,
@@ -931,7 +935,7 @@ class PromotionEvaluator {
931
935
  const detail = actionDetail;
932
936
  const triggerQuantity = this.normalizePositiveInteger(detail.triggerQuantity, 1);
933
937
  const rewardQuantity = this.normalizePositiveInteger(detail.rewardQuantity, 1);
934
- const conditionQuantity = this.getAvailablePromotionQuantity(triggerProducts, processedQuantityMap, matchedBundleIndexMap);
938
+ const conditionQuantity = this.getItemRewardTriggerQuantity(triggerProducts, processedQuantityMap, xItemsProcessedQuantityMap, matchedBundleIndexMap);
935
939
  if (conditionQuantity < triggerQuantity) {
936
940
  return {
937
941
  products: [],
@@ -1027,12 +1031,15 @@ class PromotionEvaluator {
1027
1031
  const n = Math.floor(Number(value));
1028
1032
  return Number.isFinite(n) && n > 0 ? n : fallback;
1029
1033
  }
1030
- getAvailablePromotionQuantity(products, processedQuantityMap, matchedBundleIndexMap) {
1034
+
1035
+ /** 仅放开 X件Y元处理过的触发数量,奖励目标仍按全部已处理数量互斥。 */
1036
+ getItemRewardTriggerQuantity(products, processedQuantityMap, xItemsProcessedQuantityMap, matchedBundleIndexMap) {
1031
1037
  let total = 0;
1032
1038
  for (const product of products) {
1033
1039
  const key = this.getProductKey(product);
1034
1040
  const processedQty = processedQuantityMap.get(key) || 0;
1035
- const availableQty = product.quantity - processedQty;
1041
+ const xItemsProcessedQty = xItemsProcessedQuantityMap.get(key) || 0;
1042
+ const availableQty = product.quantity - processedQty + xItemsProcessedQty;
1036
1043
  if (availableQty <= 0) continue;
1037
1044
  const matchedBundleIndex = matchedBundleIndexMap?.get(product.id);
1038
1045
  if (matchedBundleIndex !== undefined && product.bundle) {
@@ -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;
@@ -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 => {
@@ -969,14 +980,8 @@ class OrderModule extends _BaseModule.BaseModule {
969
980
  }
970
981
  } else {
971
982
  for (const addAction of result.giftActions.toAdd) {
972
- // 单选普通赠品可累加;预约赠品必须新增独立 booking,不能只改 num。
973
- if (addAction.giftOptions.length === 1) {
974
- const sameStrategy = result.products.find(p => p.metadata?._giftInfo?.strategyId === addAction.strategyId);
975
- if (sameStrategy && !sameStrategy.booking_uid && !sameStrategy.metadata?.booking_uid) {
976
- sameStrategy.num = (Number(sameStrategy.num) || 0) + (addAction.giftCount || 1);
977
- continue;
978
- }
979
- }
983
+ // 唯一候选也可能有规格/套餐。每次补赠都交给 SDK 判断,不能复用旧赠品的选择。
984
+
980
985
  const giftMutationBaseline = options?.isCurrentOrder ? (0, _lodashEs.cloneDeep)({
981
986
  products: tempOrder.products,
982
987
  bookings: tempOrder.bookings
@@ -71,8 +71,8 @@ export interface OrderGiftSelectResult {
71
71
  /**
72
72
  * 赠品解析回调签名(SDK → OS 的返回值)。
73
73
  *
74
- * - 单选项:SDK 内部自动构造商品,不弹窗
75
- * - 多选项:SDK 弹窗等用户确认后构造
74
+ * - 唯一且无规格/套餐的候选:SDK 自动构造商品
75
+ * - 有规格/套餐或多个候选:SDK 弹窗等用户确认后构造
76
76
  * - 用户取消:抛错或返回空数组(OS 视为放弃本次添加)
77
77
  *
78
78
  * 返回数组时沿用旧协议,只写 tempOrder.products;返回对象时可同时写入预约 bookings。
@@ -32,8 +32,8 @@ let OrderHooks = exports.OrderHooks = /*#__PURE__*/function (OrderHooks) {
32
32
  /**
33
33
  * 赠品解析回调签名(SDK → OS 的返回值)。
34
34
  *
35
- * - 单选项:SDK 内部自动构造商品,不弹窗
36
- * - 多选项:SDK 弹窗等用户确认后构造
35
+ * - 唯一且无规格/套餐的候选:SDK 自动构造商品
36
+ * - 有规格/套餐或多个候选:SDK 弹窗等用户确认后构造
37
37
  * - 用户取消:抛错或返回空数组(OS 视为放弃本次添加)
38
38
  *
39
39
  * 返回数组时沿用旧协议,只写 tempOrder.products;返回对象时可同时写入预约 bookings。
@@ -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);
@@ -49,5 +49,5 @@ export declare class Product extends BaseModule implements Module {
49
49
  getCategories(): ProductCategory[];
50
50
  setOtherParams(key: string, value: any): void;
51
51
  getOtherParams(): any;
52
- getProductType(): "normal" | "duration" | "session";
52
+ getProductType(): "duration" | "normal" | "session";
53
53
  }
@@ -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;