@pisell/pisellos 0.10.77 → 0.10.79

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 (51) 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.js +27 -13
  4. package/dist/modules/Product/index.d.ts +1 -1
  5. package/dist/modules/ProductList/index.d.ts +2 -0
  6. package/dist/modules/ProductList/index.js +125 -39
  7. package/dist/modules/ResourcePlanner/planner.js +5 -0
  8. package/dist/modules/Rules/index.d.ts +3 -10
  9. package/dist/modules/Rules/index.js +164 -82
  10. package/dist/modules/Rules/promotionSelection.d.ts +14 -0
  11. package/dist/modules/Rules/promotionSelection.js +390 -0
  12. package/dist/modules/Rules/types.d.ts +9 -0
  13. package/dist/solution/BaseSales/index.d.ts +12 -1
  14. package/dist/solution/BaseSales/index.js +316 -206
  15. package/dist/solution/BaseSales/utils/cartPromotion.js +5 -2
  16. package/dist/solution/BookingByStep/index.d.ts +2 -2
  17. package/dist/solution/BookingTicket/index.d.ts +1 -13
  18. package/dist/solution/UnifiedBookingSales/index.d.ts +23 -1
  19. package/dist/solution/UnifiedBookingSales/index.js +1307 -635
  20. package/dist/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
  21. package/dist/solution/UnifiedBookingSales/sessionResourceCache.js +271 -0
  22. package/dist/solution/UnifiedBookingSales/types.d.ts +25 -2
  23. package/dist/solution/UnifiedBookingSales/types.js +2 -0
  24. package/dist/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
  25. package/dist/solution/UnifiedBookingSales/venueCatalogSession.js +277 -0
  26. package/lib/model/strategy/adapter/promotion/evaluator.js +5 -4
  27. package/lib/modules/Discount/types.d.ts +4 -0
  28. package/lib/modules/Order/index.js +11 -0
  29. package/lib/modules/Product/index.d.ts +1 -1
  30. package/lib/modules/ProductList/index.d.ts +2 -0
  31. package/lib/modules/ProductList/index.js +56 -0
  32. package/lib/modules/ResourcePlanner/planner.js +4 -0
  33. package/lib/modules/Rules/index.d.ts +3 -10
  34. package/lib/modules/Rules/index.js +62 -22
  35. package/lib/modules/Rules/promotionSelection.d.ts +14 -0
  36. package/lib/modules/Rules/promotionSelection.js +230 -0
  37. package/lib/modules/Rules/types.d.ts +9 -0
  38. package/lib/solution/BaseSales/index.d.ts +12 -1
  39. package/lib/solution/BaseSales/index.js +84 -5
  40. package/lib/solution/BaseSales/utils/cartPromotion.js +5 -2
  41. package/lib/solution/BookingByStep/index.d.ts +2 -2
  42. package/lib/solution/BookingTicket/index.d.ts +1 -13
  43. package/lib/solution/UnifiedBookingSales/index.d.ts +23 -1
  44. package/lib/solution/UnifiedBookingSales/index.js +359 -5
  45. package/lib/solution/UnifiedBookingSales/sessionResourceCache.d.ts +27 -0
  46. package/lib/solution/UnifiedBookingSales/sessionResourceCache.js +199 -0
  47. package/lib/solution/UnifiedBookingSales/types.d.ts +25 -2
  48. package/lib/solution/UnifiedBookingSales/types.js +1 -0
  49. package/lib/solution/UnifiedBookingSales/venueCatalogSession.d.ts +32 -0
  50. package/lib/solution/UnifiedBookingSales/venueCatalogSession.js +151 -0
  51. package/package.json +1 -1
@@ -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';
@@ -150,6 +151,12 @@ class RulesModule extends _BaseModule.BaseModule {
150
151
  }
151
152
  });
152
153
 
154
+ // 卡可用但互斥比较选择了促销时,扫码仍应加入可选卡列表,不能被标为商品不适用。
155
+ if (!hasApplicableDiscount) {
156
+ const promotionProductIds = new Set(result.productList.filter(product => (0, _promotionSelection.getExclusivePromotion)(product)?.inPromotion === true).map(product => this.hooks.getProduct(product).id));
157
+ hasApplicableDiscount = result.discountList.some(discount => newDiscountIds.includes(discount.id) && (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.isAvailable && discount.applicableProductIds?.some(id => promotionProductIds.has(id)));
158
+ }
159
+
153
160
  // 如果券不可用,判断不可用原因
154
161
  let unavailableReason;
155
162
  if (!hasApplicableDiscount) {
@@ -217,13 +224,28 @@ class RulesModule extends _BaseModule.BaseModule {
217
224
  }
218
225
  return _types.UnavailableReason.Unknown;
219
226
  }
220
- calcDiscount({
227
+ calcDiscount(params, options) {
228
+ return (0, _promotionSelection.calculatePromotionSelection)(params, options, this.hooks, (input, calculationOptions, policy) => this.calcDiscountCore(input, calculationOptions, policy));
229
+ }
230
+ calcDiscountCore({
221
231
  discountList,
222
232
  productList,
223
233
  holders,
224
234
  isFormSubject,
225
235
  orderTotalAmount
226
- }, options) {
236
+ }, options, promotionPolicy) {
237
+ const cancelledPromotionCards = discountList.filter(discount => !discount.isEditMode && (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.promotionSelection === 'promotion');
238
+ const cancelledPromotionProductIds = new Set(cancelledPromotionCards.flatMap(discount => discount.applicableProductIds || []));
239
+ const cancelledPromotionStrategyIds = new Set(cancelledPromotionCards.flatMap(discount => discount.promotionSelectionStrategyIds || []));
240
+ const isCardBlockedByPromotion = (flatItem, discount) => {
241
+ if (flatItem.type !== 'main' || !(0, _promotionSelection.isPromotionDiscountCard)(discount)) return false;
242
+ const originProduct = flatItem.originProduct;
243
+ if (originProduct?.order_detail_id || originProduct?.orderDetailId || originProduct?.booking_id || originProduct?.metadata?.booking_id) return false;
244
+ // 取消卡后即使数量暂未凑足促销,也不能自动改用另一张卡;重新手选/最佳组合会清除该意图。
245
+ if (cancelledPromotionProductIds.has(flatItem.product.id) || cancelledPromotionStrategyIds.has(String(originProduct?.metadata?._promotion?.strategyId))) return true;
246
+ const promotion = (0, _promotionSelection.getExclusivePromotion)(originProduct);
247
+ return Boolean(promotion && promotionPolicy?.blockedStrategyIds.has(String(promotion.strategyId)));
248
+ };
227
249
  const preferredEntitlementPassIds = new Set((options?.preferredEntitlementPassIds || []).map(String));
228
250
  const resolveIsFormSubject = product => typeof isFormSubject === 'function' ? Boolean(isFormSubject(product)) : Boolean(isFormSubject);
229
251
 
@@ -729,6 +751,7 @@ class RulesModule extends _BaseModule.BaseModule {
729
751
  const checkItemApplicableForDiscount = (flatItem, discount) => {
730
752
  if (this.discountScope && !this.discountScope(flatItem.originProduct, discount)) return false;
731
753
  if (discount.config?.isAvailable === false) return false;
754
+ if (isCardBlockedByPromotion(flatItem, discount)) return false;
732
755
  let product;
733
756
  if (flatItem.type === 'main') {
734
757
  product = flatItem.product;
@@ -789,6 +812,11 @@ class RulesModule extends _BaseModule.BaseModule {
789
812
  return isLimitedProduct && isBundleAvailable;
790
813
  };
791
814
 
815
+ // 分摊占位与实际应用共用选择优先级,数量跌出促销门槛时也保留手选意图。
816
+ 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);
817
+ 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));
818
+ 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)));
819
+
792
820
  // 收集所有被勾选的 order_level 折扣卡及其适用商品
793
821
  const selectedOrderLevelDiscounts = sortedDiscountList.filter(discount => {
794
822
  return (0, _utils.isOrderLevelFixedAmountDiscount)(discount) && discount.isSelected !== false;
@@ -816,6 +844,18 @@ class RulesModule extends _BaseModule.BaseModule {
816
844
  // Map<flatItemId, discountId> - 记录被占用的商品及其对应的折扣卡
817
845
  const occupiedItems = new Map();
818
846
 
847
+ // 手选/已应用的卡先占位(包括全品类卡),其他候选卡不能抢走其分摊商品。
848
+ sortedFlattenedList.forEach(flatItem => {
849
+ const product = flatItem.type === 'main' ? flatItem.product : flatItem.bundleItem;
850
+ const holderProduct = flatItem.type === 'main' ? flatItem.product : flatItem.parentProduct;
851
+ const applicableCards = sortedDiscountList.filter(discount => (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.config?.isAvailable && checkItemApplicableForDiscount(flatItem, discount) && this.checkHolderMatch(discount, {
852
+ isNeedHolder: resolveIsFormSubject(holderProduct) && !holderProduct?.isNormalProduct,
853
+ holder_id: holderProduct?.holder_id || product.holder_id
854
+ }, flatItem.originProduct, holders));
855
+ const preferredCard = findExplicitlySelectedDiscount(applicableCards) || findAppliedDiscountCard(applicableCards, getAppliedWalletDiscountIds(product)) || applicableCards.find(discount => discount.isScan && discount.isSelected);
856
+ if (preferredCard) occupiedItems.set(flatItem._id, preferredCard.id);
857
+ });
858
+
819
859
  // 按排序顺序遍历折扣卡,判断哪些是专属折扣卡
820
860
  selectedOrderLevelDiscounts.forEach(discount => {
821
861
  const limitedData = discount.limited_relation_product_data;
@@ -956,6 +996,9 @@ class RulesModule extends _BaseModule.BaseModule {
956
996
  if (isAvailableProduct && !isItemRewardProductDiscount && isLimitedProduct && timeLimit && isBundleAvailable && discount.config?.isAvailable && (!(0, _entitlementPass.isEntitlementPass)(discount) || (0, _entitlementPass.getRemainingEntitlementUses)(discount, 0, 1) > 0)) {
957
997
  // 记录此优惠券适用的商品
958
998
  discountApplicability.get(discount.id)?.push(product.id);
999
+ if (flatItem.type === 'main' && (0, _promotionSelection.isPromotionDiscountCard)(discount)) {
1000
+ promotionPolicy?.onApplicableCard?.(originProduct, discount);
1001
+ }
959
1002
 
960
1003
  // 记录可抵扣的商品详情
961
1004
  const applicableProducts = discountApplicableProducts.get(discount.id) || [];
@@ -1101,6 +1144,7 @@ class RulesModule extends _BaseModule.BaseModule {
1101
1144
  const applicableDiscounts = sortedDiscountList.filter(discount => {
1102
1145
  if (this.discountScope && !this.discountScope(originProduct, discount)) return false;
1103
1146
  if (this.isItemRewardProductDiscount(product)) return false;
1147
+ if (isCardBlockedByPromotion(flatItem, discount)) return false;
1104
1148
  // 🔥 检查策略可用性(针对全额抵扣卡和折扣卡)
1105
1149
  const discountType = discount.tag || discount.type;
1106
1150
  const currentOriginUid = getOriginProductUid(originProduct);
@@ -1180,20 +1224,14 @@ class RulesModule extends _BaseModule.BaseModule {
1180
1224
 
1181
1225
  // 识别用户本次显式选择的卡券,供次卡和折扣卡各自的优先级使用。
1182
1226
  // 目标仍必须在当前商品的 applicableDiscounts 中,因此不会绕过 Holder、时间或商品范围校验。
1183
- const explicitlySelectedDiscount = options?.isSelected === true && options.discountId !== undefined ? applicableDiscounts.find(discount => {
1184
- const discountType = discount.tag || discount.type;
1185
- return String(discount.id) === String(options.discountId) && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType ?? '');
1186
- }) : undefined;
1227
+ const explicitlySelectedDiscount = findExplicitlySelectedDiscount(applicableDiscounts);
1187
1228
  // 折扣卡会复用于整条商品行;商品券必须继续按单张拆分,不能复用该分支。
1188
1229
  const explicitlySelectedDiscountCard = explicitlySelectedDiscount && !(0, _entitlementPass.isFullCoveragePass)(explicitlySelectedDiscount) ? explicitlySelectedDiscount : undefined;
1189
1230
 
1190
1231
  // 商品数量等变化会触发无 discountId 的重算。只要当前行已应用的卡仍在
1191
1232
  // applicableDiscounts 中,就应保留该行选择,避免被自动排序中力度更大的卡替换。
1192
- 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));
1193
- const appliedDiscountCard = options?.scan ? undefined : applicableDiscounts.find(discount => {
1194
- const discountType = discount.tag || discount.type;
1195
- return discount.isSelected === true && ['discount_card', 'product_discount_card'].includes(discountType ?? '') && appliedWalletDiscountIds.has(String(discount.id));
1196
- });
1233
+ const appliedWalletDiscountIds = getAppliedWalletDiscountIds(product);
1234
+ const appliedDiscountCard = findAppliedDiscountCard(applicableDiscounts, appliedWalletDiscountIds);
1197
1235
  const appliedEntitlementPass = options?.scan || options?.preserveEntitlementSelection === false ? undefined : applicableDiscounts.find(discount => (0, _entitlementPass.isEntitlementPass)(discount) && discount.isSelected === true && appliedWalletDiscountIds.has(String(discount.id)));
1198
1236
 
1199
1237
  // 次卡内部按本次手选/扫码、当前行已应用、默认排序选择。
@@ -1428,14 +1466,15 @@ class RulesModule extends _BaseModule.BaseModule {
1428
1466
  let discountedOptions = product.options;
1429
1467
  let optionDiscountAmount = 0;
1430
1468
  let reapplyDiscountPercent;
1431
- if (isOrderLevel && productAllocation) {
1432
- // order_level:使用预计算的分摊金额
1433
- amount = productAllocation.discountAmount;
1434
- productDiscountDifference = productAllocation.difference;
1469
+ const bookingDiscountPercent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1470
+ if (isOrderLevel && (productAllocation || bookingDiscountPercent === undefined)) {
1471
+ // 整单卡只能使用分摊结果,缺少分摊时不能回退为每件扣减整单额度。
1472
+ amount = productAllocation?.discountAmount ?? 0;
1473
+ productDiscountDifference = productAllocation?.difference;
1435
1474
  mainProductSellingPrice = Math.max(new _decimal.default(product.price).minus(amount).toNumber(), 0);
1436
- } else if (resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount) !== undefined) {
1475
+ } else if (bookingDiscountPercent !== undefined) {
1437
1476
  // Change time 重套编辑态折扣卡时,历史 par_value 不是运行时折扣口径,优先使用后端快照里的 percent。
1438
- const percent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1477
+ const percent = bookingDiscountPercent;
1439
1478
  reapplyDiscountPercent = new _decimal.default(percent).toFixed(2);
1440
1479
  mainProductSellingPrice = new _decimal.default(product.price || 0).mul(new _decimal.default(100).minus(percent)).div(100).toDecimalPlaces(2).toNumber();
1441
1480
  amount = new _decimal.default(product.price).minus(mainProductSellingPrice).toNumber();
@@ -1629,15 +1668,16 @@ class RulesModule extends _BaseModule.BaseModule {
1629
1668
  let fixedAmountPerItem;
1630
1669
  let productDiscountDifference;
1631
1670
  let reapplyDiscountPercent;
1632
- if (isOrderLevel && productAllocation) {
1671
+ const bookingDiscountPercent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1672
+ if (isOrderLevel && (productAllocation || bookingDiscountPercent === undefined)) {
1633
1673
  // order_level:使用预计算的单价折扣金额(已经是单价,无需再除以数量)
1634
- fixedAmountPerItem = productAllocation.discountAmount;
1635
- productDiscountDifference = productAllocation.difference;
1674
+ fixedAmountPerItem = productAllocation?.discountAmount ?? 0;
1675
+ productDiscountDifference = productAllocation?.difference;
1636
1676
  targetProductTotal = Math.max(new _decimal.default(productOriginTotal).minus(fixedAmountPerItem).toNumber(), 0);
1637
- } else if (resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount) !== undefined) {
1677
+ } else if (bookingDiscountPercent !== undefined) {
1638
1678
  // hydrate 后 par_value 可能是余额/原值(例如 3500),百分比口径以
1639
1679
  // 后端折扣快照 discount.percent 为准,与主商品重套逻辑保持一致。
1640
- const percent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1680
+ const percent = bookingDiscountPercent;
1641
1681
  reapplyDiscountPercent = new _decimal.default(percent).toFixed(2);
1642
1682
  targetProductTotal = new _decimal.default(productOriginTotal).mul(new _decimal.default(100).minus(percent)).div(100).toDecimalPlaces(2).toNumber();
1643
1683
  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;
@@ -129,7 +129,7 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
129
129
  * /product/query 的智能定价评估只读取 strategy_context;
130
130
  * application_code 仅作为接口兼容字段,不能替代 channel / business_code。
131
131
  */
132
- private getPriceQueryStrategyContext;
132
+ protected getPriceQueryStrategyContext(channel?: string): Record<string, any>;
133
133
  /**
134
134
  * 子类可在商品重报价前准备客户维度的策略上下文,例如等待 Wallet/优惠资产加载。
135
135
  */
@@ -156,6 +156,12 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
156
156
  private prepareRawProductForPriceQuery;
157
157
  private resolveLocalProductForPriceQuery;
158
158
  private loadProductsForPriceQuery;
159
+ /** Opt-in subclasses may supply page-owned raw pools; ordinary sales keep remote fallback. */
160
+ protected isVenueCatalogLocalPricingActive(): boolean;
161
+ protected getVenueCatalogLocalPriceSource(_productId: number, _selectedProduct?: Record<string, any>): {
162
+ product: Record<string, any>;
163
+ menuList: Record<string, any>[];
164
+ } | undefined;
159
165
  private resolveProductsForPriceQuery;
160
166
  private getAuthoritativeBundleItems;
161
167
  private findAuthoritativeBundleItem;
@@ -523,6 +529,11 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
523
529
  submitBeforeSend?: boolean;
524
530
  }): Promise<T>;
525
531
  transformBaseProductToOrderProduct(params: TransformBaseProductToOrderProductParams): import("./utils/transformBaseProductToOrderProduct").BaseProductOrderProductInput | null;
532
+ /** Explicit pool source avoids races between two simultaneous Venue pricing contexts. */
533
+ protected calculateVenueCatalogProductBookingPrice(params: BaseSalesCalculateProductBookingPriceParams, source: {
534
+ product: Record<string, any>;
535
+ menuList: Record<string, any>[];
536
+ }): Promise<BaseSalesProductBookingPriceResult>;
526
537
  calculateProductBookingPrice(params: BaseSalesCalculateProductBookingPriceParams): Promise<BaseSalesProductBookingPriceResult>;
527
538
  getQuotationCustomerScopeInfo(): BaseSalesQuotationCustomerScopeInfo;
528
539
  private hasSmartPricingStrategies;
@@ -26,6 +26,7 @@ var _pickupTiming = require("../../modules/Order/pickupTiming");
26
26
  var _pickupTiming2 = require("./pickupTiming");
27
27
  var _holderRelations = require("../../modules/Order/holderRelations");
28
28
  var _contactInfo = require("../../modules/OpenData/contactInfo");
29
+ var _promotionSelection = require("../../modules/Rules/promotionSelection");
29
30
  var _decimal = _interopRequireDefault(require("decimal.js"));
30
31
  var _lodashEs = require("lodash-es");
31
32
  var _types2 = require("../BookingByStep/types");
@@ -1042,6 +1043,9 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1042
1043
  products: [preparedProduct],
1043
1044
  queryPayload: params.queryPayload,
1044
1045
  handledByOsServer: false,
1046
+ ...(params.menuList ? {
1047
+ menuList: params.menuList
1048
+ } : {}),
1045
1049
  ...(scheduleList ? {
1046
1050
  scheduleList
1047
1051
  } : {})
@@ -1097,6 +1101,14 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1097
1101
  return productsById;
1098
1102
  }
1099
1103
  }
1104
+
1105
+ /** Opt-in subclasses may supply page-owned raw pools; ordinary sales keep remote fallback. */
1106
+ isVenueCatalogLocalPricingActive() {
1107
+ return false;
1108
+ }
1109
+ getVenueCatalogLocalPriceSource(_productId, _selectedProduct) {
1110
+ return undefined;
1111
+ }
1100
1112
  async resolveProductsForPriceQuery(params) {
1101
1113
  const selectedProducts = params.priceQueries.map(item => item.product || {});
1102
1114
  const productIds = selectedProducts.map(product => this.getPriceQueryProductId(product));
@@ -1104,6 +1116,30 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
1104
1116
  if (!ids.length) {
1105
1117
  return selectedProducts.map(() => null);
1106
1118
  }
1119
+
1120
+ // An explicitly active Venue pool owns all its product reads. Missing raw data
1121
+ // or rules must fail visibly; never silently spend a second list/detail request.
1122
+ if (this.isVenueCatalogLocalPricingActive()) {
1123
+ const queryPayload = this.buildPriceQueryPayload({
1124
+ ids,
1125
+ schedule: params.schedule,
1126
+ customerId: params.customerId,
1127
+ channel: params.channel
1128
+ });
1129
+ return selectedProducts.map((selectedProduct, index) => {
1130
+ const source = productIds[index] == null ? undefined : this.getVenueCatalogLocalPriceSource(productIds[index], selectedProduct);
1131
+ const resolved = source && this.resolveLocalProductForPriceQuery({
1132
+ selectedProduct,
1133
+ rawProduct: source.product,
1134
+ menuList: source.menuList,
1135
+ queryPayload
1136
+ });
1137
+ if (!resolved) throw Object.assign(new Error('The complete venue product or pricing rules are not ready. Reload the catalog before continuing.'), {
1138
+ code: 'VENUE_LOCAL_PRICE_UNAVAILABLE'
1139
+ });
1140
+ return resolved;
1141
+ });
1142
+ }
1107
1143
  const handledByOsServer = this.request ? (0, _clientDataVariants.isProductQueryHandledByOsServer)(this.core, this.request) : false;
1108
1144
  const canUseLocalFastPath = this.isCustomerUserPriceQuery() && !handledByOsServer;
1109
1145
  if (!canUseLocalFastPath) {
@@ -2146,17 +2182,25 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2146
2182
  return {
2147
2183
  ...discount,
2148
2184
  isSelected: false,
2149
- isManualSelect: true
2185
+ isManualSelect: true,
2186
+ promotionSelection: currentDiscount.promotionSelection,
2187
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2150
2188
  };
2151
2189
  }
2152
2190
  if (currentDiscount.isSelected) {
2153
2191
  return {
2154
2192
  ...discount,
2155
2193
  isSelected: true,
2156
- isManualSelect: false
2194
+ isManualSelect: false,
2195
+ promotionSelection: currentDiscount.promotionSelection,
2196
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2157
2197
  };
2158
2198
  }
2159
- return discount;
2199
+ return currentDiscount.promotionSelection ? {
2200
+ ...discount,
2201
+ promotionSelection: currentDiscount.promotionSelection,
2202
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2203
+ } : discount;
2160
2204
  });
2161
2205
  }
2162
2206
  resolveDiscountConfigCustomerId(tempOrder) {
@@ -2353,6 +2397,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2353
2397
  }
2354
2398
  async bestDiscount(cb) {
2355
2399
  if (!this.store.order) throw new Error('order 模块未初始化');
2400
+ this.hasManualDiscountSelection = false;
2356
2401
  const tempOrder = this.store.order.ensureTempOrder();
2357
2402
  if (this.isActiveVirtualSettlementOrder(tempOrder)) {
2358
2403
  const result = {
@@ -2517,8 +2562,10 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2517
2562
  nextDiscountList = result.discountList;
2518
2563
  if (!params.isSelected) {
2519
2564
  const beforeSelectedIds = new Set(updated.filter(d => d.isSelected).map(d => d.id));
2565
+ // Rules 已对促销组完成互斥报价,不能再移除其选中的卡而留下已取消的促销。
2566
+ const promotionCardIds = new Set((result.productList || []).filter(product => (0, _promotionSelection.getExclusivePromotion)(product)?.excludedByDiscountCard).flatMap(product => (product.discount_list || []).filter(_promotionSelection.isPromotionDiscountCard).map(discount => String(discount.discount?.resource_id ?? discount.id))));
2520
2567
  for (const d of nextDiscountList) {
2521
- if (d.isSelected && !beforeSelectedIds.has(d.id)) {
2568
+ if (d.isSelected && !beforeSelectedIds.has(d.id) && !promotionCardIds.has(String(d.id))) {
2522
2569
  d.isSelected = false;
2523
2570
  d.isManualSelect = true;
2524
2571
  d.appliedProductDetails = [];
@@ -2529,6 +2576,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2529
2576
  }
2530
2577
  const selectedResourceIds = new Set(nextDiscountList.filter(d => d.isSelected).map(d => d.id));
2531
2578
  const filterSelectedDiscountDetails = discountList => (discountList || []).filter(pd => {
2579
+ // 互斥计算保留/恢复的系统促销没有钱包 resource_id,不能按已选卡列表移除。
2580
+ if (pd.type === 'promotion' || pd.type === 'product' && pd.metadata?.source === 'promotion') return true;
2532
2581
  const rid = pd.discount?.resource_id ?? pd.id;
2533
2582
  return rid != null && selectedResourceIds.has(rid);
2534
2583
  });
@@ -2555,7 +2604,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2555
2604
 
2556
2605
  // 券作用于 source(不含 option、不含 bundle);算出新 source 折后价后补回 options
2557
2606
  // 写入含 option 的 main_product_selling_price,再合成 composite 回写 selling_price。
2558
- const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + (pd.amount || 0), 0);
2607
+ const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + Number(pd.amount || 0), 0);
2559
2608
  // TODO 这块逻辑需要拿掉
2560
2609
  const optionSum = (0, _utils.sumOptionUnitPrice)((0, _utils.getProductSkuOptions)(product));
2561
2610
  const sourcePrice = product.metadata?.source_product_price ?? (product.metadata?.main_product_original_price != null ? new _decimal.default(Number(product.metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : product.original_price ?? '0');
@@ -3987,6 +4036,36 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
3987
4036
  transformBaseProductToOrderProduct(params) {
3988
4037
  return (0, _transformBaseProductToOrderProduct.transformBaseProductToOrderProduct)(params);
3989
4038
  }
4039
+
4040
+ /** Explicit pool source avoids races between two simultaneous Venue pricing contexts. */
4041
+ async calculateVenueCatalogProductBookingPrice(params, source) {
4042
+ const customerId = params.customer_id ?? this.getCurrentOrderCustomerId();
4043
+ await this.prepareProductPriceQueryContext(customerId);
4044
+ const channel = this.getPriceQueryChannel(params.channel);
4045
+ const queryPayload = this.buildPriceQueryPayload({
4046
+ ids: [Number(source.product.id)],
4047
+ schedule: this.getPriceQuerySchedule(params),
4048
+ customerId,
4049
+ channel
4050
+ });
4051
+ const authoritativeProduct = this.resolveLocalProductForPriceQuery({
4052
+ selectedProduct: params.product,
4053
+ rawProduct: source.product,
4054
+ menuList: source.menuList,
4055
+ queryPayload
4056
+ });
4057
+ if (!authoritativeProduct) throw Object.assign(new Error('Complete product pricing rules are not ready. Please retry.'), {
4058
+ code: 'VENUE_LOCAL_PRICE_UNAVAILABLE'
4059
+ });
4060
+ return (0, _quotationPrice.calculateBaseSalesProductBookingPrice)({
4061
+ ...params,
4062
+ channel,
4063
+ customer_id: customerId,
4064
+ product: this.mergeProductForPriceQuery(params.product, authoritativeProduct),
4065
+ fallback_price: undefined,
4066
+ quotation: undefined
4067
+ });
4068
+ }
3990
4069
  async calculateProductBookingPrice(params) {
3991
4070
  const useCustomerUserPricing = this.isCustomerUserPriceQuery();
3992
4071
  const quotation = useCustomerUserPricing ? undefined : this.store.quotation;