@pisell/pisellos 2.2.318 → 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 (33) 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 +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/Rules/index.d.ts +3 -10
  10. package/dist/modules/Rules/index.js +169 -87
  11. package/dist/modules/Rules/promotionSelection.d.ts +14 -0
  12. package/dist/modules/Rules/promotionSelection.js +390 -0
  13. package/dist/modules/Rules/types.d.ts +9 -0
  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/modules/Discount/types.d.ts +4 -0
  19. package/lib/modules/Order/index.d.ts +1 -1
  20. package/lib/modules/Order/index.js +13 -8
  21. package/lib/modules/Order/types.d.ts +2 -2
  22. package/lib/modules/Order/types.js +2 -2
  23. package/lib/modules/Order/utils.js +1 -1
  24. package/lib/modules/Payment/walletpass.js +23 -1
  25. package/lib/modules/Rules/index.d.ts +3 -10
  26. package/lib/modules/Rules/index.js +62 -22
  27. package/lib/modules/Rules/promotionSelection.d.ts +14 -0
  28. package/lib/modules/Rules/promotionSelection.js +230 -0
  29. package/lib/modules/Rules/types.d.ts +9 -0
  30. package/lib/solution/BaseSales/index.js +19 -5
  31. package/lib/solution/BaseSales/utils/cartPromotion.js +5 -2
  32. package/lib/solution/BookingByStep/index.d.ts +1 -1
  33. package/package.json +1 -1
@@ -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) {
@@ -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 => {
@@ -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);
@@ -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;
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.calculatePromotionSelection = calculatePromotionSelection;
7
+ exports.getExclusivePromotion = getExclusivePromotion;
8
+ exports.isPromotionDiscountCard = isPromotionDiscountCard;
9
+ var _decimal = _interopRequireDefault(require("decimal.js"));
10
+ var _lodashEs = require("lodash-es");
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+ function isPromotionDiscountCard(discount) {
13
+ return ['discount_card', 'product_discount_card'].includes(discount?.tag || discount?.type);
14
+ }
15
+
16
+ /** 只处理当前购物车的 X 件 Y 元,历史成交和其他促销继续使用原有规则。 */
17
+ function getExclusivePromotion(product) {
18
+ const promotion = product?.metadata?._promotion;
19
+ if (product?.order_detail_id || product?.orderDetailId || product?.booking_id || product?.metadata?.booking_id || promotion?.actionType !== 'X_ITEMS_FOR_Y_PRICE' || !promotion.strategyId || !(promotion.inPromotion === true || promotion.excludedByDiscountCard === true)) return undefined;
20
+ return promotion;
21
+ }
22
+ /**
23
+ * 以完整策略参与组为单位比较两套实际报价。每次试算都从同一快照开始,
24
+ * 由原引擎重新做卡券校验和整单卡分摊,不能从叠加结果里事后减掉某条优惠。
25
+ */
26
+ function calculatePromotionSelection(params, options, hooks, calculate) {
27
+ const discountList = params.discountList.map(discount => {
28
+ if (discount.isEditMode || !isPromotionDiscountCard(discount)) return discount;
29
+ if (options?.preserveEntitlementSelection === false) {
30
+ return {
31
+ ...discount,
32
+ promotionSelection: undefined,
33
+ promotionSelectionStrategyIds: undefined,
34
+ isManualSelect: false
35
+ };
36
+ }
37
+ if (options?.discountId !== undefined && String(discount.id) === String(options.discountId) && typeof options.isSelected === 'boolean') {
38
+ return {
39
+ ...discount,
40
+ promotionSelection: options.isSelected ? 'card' : 'promotion',
41
+ isSelected: options.isSelected,
42
+ isManualSelect: !options.isSelected
43
+ };
44
+ }
45
+ return {
46
+ ...discount
47
+ };
48
+ });
49
+ // 未凑足促销时也要清理重叠商品上的旧手选,避免再次凑组后切回之前的卡。
50
+ const changedCard = options?.discountId !== undefined && typeof options.isSelected === 'boolean' ? discountList.find(discount => !discount.isEditMode && isPromotionDiscountCard(discount) && String(discount.id) === String(options.discountId)) : undefined;
51
+ if (changedCard) {
52
+ const changedProductIds = new Set(changedCard.applicableProductIds || []);
53
+ for (const product of params.productList) {
54
+ const detail = hooks.getProduct(product);
55
+ if (detail.discount_list?.some(discount => isPromotionDiscountCard(discount) && String(discount.discount?.resource_id ?? discount.id) === String(changedCard.id))) changedProductIds.add(detail.id);
56
+ }
57
+ for (const discount of discountList) {
58
+ if (discount.isEditMode || !isPromotionDiscountCard(discount) || String(discount.id) === String(changedCard.id) || !discount.promotionSelection) continue;
59
+ if (discount.applicableProductIds?.some(id => changedProductIds.has(id))) {
60
+ discount.promotionSelection = undefined;
61
+ discount.promotionSelectionStrategyIds = undefined;
62
+ }
63
+ }
64
+ }
65
+ const strategyIds = new Set();
66
+ for (const product of params.productList) {
67
+ const promotion = getExclusivePromotion(product);
68
+ if (promotion && hooks.getProduct(product).isManualDiscount !== true) {
69
+ strategyIds.add(String(promotion.strategyId));
70
+ }
71
+ }
72
+ if (!strategyIds.size) return calculate({
73
+ ...params,
74
+ discountList
75
+ }, options);
76
+ const applicableGroups = new Map();
77
+ const quote = (blockedStrategyIds, collectApplicable = false) => {
78
+ const productList = (0, _lodashEs.cloneDeep)(params.productList).map(product => {
79
+ const promotion = getExclusivePromotion(product);
80
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) return product;
81
+ const detail = hooks.getProduct(product);
82
+ if (detail.isManualDiscount === true) return product;
83
+ const keepPromotion = blockedStrategyIds.has(String(promotion.strategyId));
84
+ const originalPrice = Number(promotion.originalPrice ?? detail.price);
85
+ const finalPrice = Number(promotion.finalPrice);
86
+ const promotionDiscount = (detail.discount_list || []).find(discount => discount.type === 'promotion');
87
+ const retainedDiscounts = (detail.discount_list || []).filter(discount => discount.type !== 'promotion' && (!isPromotionDiscountCard(discount) || !keepPromotion && discountList.some(card => !card.isManualSelect && String(card.id) === String(discount.discount?.resource_id ?? discount.id))));
88
+ if (keepPromotion && originalPrice !== finalPrice) {
89
+ retainedDiscounts.push(promotionDiscount || {
90
+ type: 'promotion',
91
+ amount: new _decimal.default(originalPrice).minus(finalPrice).toFixed(2),
92
+ discount: {
93
+ original_amount: String(originalPrice),
94
+ fixed_amount: new _decimal.default(originalPrice).minus(finalPrice).toFixed(2),
95
+ title: promotion.strategyMetadata?.name || '',
96
+ resource_id: ''
97
+ }
98
+ });
99
+ }
100
+ product.metadata._promotion = {
101
+ ...promotion,
102
+ inPromotion: keepPromotion,
103
+ excludedByDiscountCard: !keepPromotion
104
+ };
105
+ return hooks.setProduct(product, {
106
+ discount_list: retainedDiscounts,
107
+ main_product_selling_price: keepPromotion ? finalPrice : originalPrice
108
+ });
109
+ });
110
+ return calculate({
111
+ ...params,
112
+ productList,
113
+ discountList: (0, _lodashEs.cloneDeep)(discountList).map(discount => !discount.isEditMode && isPromotionDiscountCard(discount) && !discount.isManualSelect
114
+ // 自动落选不等于手动禁用;整单卡仍须进入下一轮候选分摊。
115
+ ? {
116
+ ...discount,
117
+ isSelected: discount.isSelected === false ? undefined : discount.isSelected
118
+ } : discount)
119
+ }, options, {
120
+ blockedStrategyIds,
121
+ onApplicableCard: collectApplicable ? (product, discount) => {
122
+ const promotion = getExclusivePromotion(product);
123
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) return;
124
+ const id = String(discount.id);
125
+ const groups = applicableGroups.get(id) || new Set();
126
+ groups.add(String(promotion.strategyId));
127
+ applicableGroups.set(id, groups);
128
+ } : undefined
129
+ });
130
+ };
131
+
132
+ // 起点保留所有促销;未发生冲突的商品和卡券仍由原引擎正常计算。
133
+ let blockedStrategyIds = new Set(strategyIds);
134
+ let result = quote(blockedStrategyIds, true);
135
+ // 取消已应用的卡时,即使它刚好失效,也应恢复它原来替代的促销组。
136
+ for (const product of params.productList) {
137
+ const promotion = getExclusivePromotion(product);
138
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) continue;
139
+ for (const detail of hooks.getProduct(product).discount_list || []) {
140
+ if (!isPromotionDiscountCard(detail)) continue;
141
+ const id = String(detail.discount?.resource_id ?? detail.id);
142
+ if (!discountList.some(discount => String(discount.id) === id && (discount.isManualSelect || discount.promotionSelection === 'promotion'))) continue;
143
+ const groups = applicableGroups.get(id) || new Set();
144
+ groups.add(String(promotion.strategyId));
145
+ applicableGroups.set(id, groups);
146
+ }
147
+ }
148
+ // 同一参与组以最近一次手动操作为准,不能让先前选过的另一张卡重新压过取消操作。
149
+ const changedGroups = options?.discountId !== undefined && typeof options.isSelected === 'boolean' ? applicableGroups.get(String(options.discountId)) : undefined;
150
+ if (changedGroups?.size) {
151
+ for (const discount of discountList) {
152
+ if (!discount.isEditMode && String(discount.id) === String(options?.discountId)) {
153
+ discount.promotionSelectionStrategyIds = [...changedGroups];
154
+ continue;
155
+ }
156
+ if (discount.isEditMode || !isPromotionDiscountCard(discount) || String(discount.id) === String(options?.discountId) || !discount.promotionSelection) continue;
157
+ const groups = new Set([...(applicableGroups.get(String(discount.id)) || []), ...(discount.promotionSelectionStrategyIds || [])]);
158
+ if ([...groups].some(group => changedGroups.has(group))) {
159
+ discount.promotionSelection = undefined;
160
+ discount.promotionSelectionStrategyIds = undefined;
161
+ }
162
+ }
163
+ }
164
+ const manualPromotionGroups = new Set();
165
+ const manualCardGroups = new Set();
166
+ for (const discount of discountList) {
167
+ if (!isPromotionDiscountCard(discount) || discount.isEditMode) continue;
168
+ const groups = applicableGroups.get(String(discount.id)) || [];
169
+ if (discount.isManualSelect || discount.promotionSelection === 'promotion') {
170
+ for (const group of groups) manualPromotionGroups.add(group);
171
+ for (const group of discount.promotionSelectionStrategyIds || []) {
172
+ if (strategyIds.has(group)) manualPromotionGroups.add(group);
173
+ }
174
+ } else if (discount.promotionSelection === 'card') {
175
+ for (const group of groups) manualCardGroups.add(group);
176
+ }
177
+ }
178
+ const total = candidate => candidate.productList.reduce((sum, product) => {
179
+ const detail = hooks.getProduct(product);
180
+ const discounts = [...detail.discount_list, ...(detail.bundle || []).flatMap(bundle => (bundle.discount_list || []).filter(discount => !discount.id))];
181
+ // 与订单小计一致:整单卡未计入单价的尾差按行扣一次,不能漏算或再乘数量。
182
+ const difference = discounts.reduce((amount, discount) => amount.plus(discount.metadata?.product_discount_difference || 0), new _decimal.default(0));
183
+ return sum.plus(detail.total).minus(difference);
184
+ }, new _decimal.default(0));
185
+ const hasAppliedCard = (candidate, strategyId) => candidate.productList.some(product => String(getExclusivePromotion(product)?.strategyId) === strategyId && hooks.getProduct(product).discount_list.some(isPromotionDiscountCard));
186
+ // 手动选择先落定,随后只对未手选的参与组比较优惠。
187
+ for (const strategyId of manualCardGroups) {
188
+ const candidateBlocked = new Set(blockedStrategyIds);
189
+ candidateBlocked.delete(strategyId);
190
+ const candidate = quote(candidateBlocked);
191
+ if (hasAppliedCard(candidate, strategyId)) {
192
+ blockedStrategyIds = candidateBlocked;
193
+ result = candidate;
194
+ }
195
+ }
196
+ const automaticGroups = new Set([...strategyIds].filter(id => !manualCardGroups.has(id) && !manualPromotionGroups.has(id) && discountList.some(discount => !discount.isEditMode && !discount.isManualSelect && applicableGroups.get(String(discount.id))?.has(id))));
197
+ // 多组共用整单卡时先选节省最多的一组,再重新试算其余组,避免依赖购物车行顺序。
198
+ while (automaticGroups.size) {
199
+ let bestGroup;
200
+ let bestResult = result;
201
+ let bestTotal = total(result);
202
+ for (const strategyId of automaticGroups) {
203
+ const candidateBlocked = new Set(blockedStrategyIds);
204
+ candidateBlocked.delete(strategyId);
205
+ const candidate = quote(candidateBlocked);
206
+ const candidateTotal = total(candidate);
207
+ // 没有实际可用卡时保持促销;同价继续保留促销。
208
+ if (hasAppliedCard(candidate, strategyId) && candidateTotal.lessThan(bestTotal)) {
209
+ bestGroup = strategyId;
210
+ bestResult = candidate;
211
+ bestTotal = candidateTotal;
212
+ }
213
+ }
214
+ if (bestGroup === undefined) break;
215
+ blockedStrategyIds.delete(bestGroup);
216
+ automaticGroups.delete(bestGroup);
217
+ result = bestResult;
218
+ }
219
+ // 即使最终保留首次报价,也要回写上面清除的旧手动意图。
220
+ result.discountList = result.discountList.map(discount => {
221
+ if (discount.isEditMode || !isPromotionDiscountCard(discount)) return discount;
222
+ const selection = discountList.find(card => !card.isEditMode && String(card.id) === String(discount.id));
223
+ return {
224
+ ...discount,
225
+ promotionSelection: selection?.promotionSelection,
226
+ promotionSelectionStrategyIds: selection?.promotionSelectionStrategyIds
227
+ };
228
+ });
229
+ return result;
230
+ }
@@ -24,6 +24,15 @@ export interface DiscountResult {
24
24
  discountList: any[];
25
25
  }
26
26
  export type RulesFormSubject = boolean | ((product: any) => boolean);
27
+ export interface RulesCalcDiscountParams {
28
+ discountList: Discount[];
29
+ productList: any[];
30
+ holders: {
31
+ form_record_id: number;
32
+ }[];
33
+ isFormSubject: RulesFormSubject;
34
+ orderTotalAmount: number;
35
+ }
27
36
  export interface RulesCalcDiscountOptions {
28
37
  isSelected?: boolean;
29
38
  discountId?: number;