@pisell/pisellos 2.3.125 → 2.3.127

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 (91) hide show
  1. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  2. package/dist/model/strategy/adapter/walletPass/evaluator.d.ts +2 -0
  3. package/dist/model/strategy/adapter/walletPass/evaluator.js +4 -2
  4. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +58 -19
  5. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +24 -12
  6. package/dist/modules/Customer/index.js +6 -3
  7. package/dist/modules/Customer/types.d.ts +2 -0
  8. package/dist/modules/Discount/availability.d.ts +7 -0
  9. package/dist/modules/Discount/availability.js +49 -0
  10. package/dist/modules/Discount/entitlementPass.d.ts +34 -0
  11. package/dist/modules/Discount/entitlementPass.js +147 -0
  12. package/dist/modules/Discount/index.d.ts +2 -2
  13. package/dist/modules/Discount/index.js +37 -151
  14. package/dist/modules/Discount/types.d.ts +36 -5
  15. package/dist/modules/Order/index.d.ts +6 -0
  16. package/dist/modules/Order/index.js +440 -232
  17. package/dist/modules/Order/utils/orderCollectionIdentity.js +16 -12
  18. package/dist/modules/Order/utils.d.ts +1 -1
  19. package/dist/modules/Order/utils.js +101 -60
  20. package/dist/modules/Payment/types.d.ts +21 -1
  21. package/dist/modules/Payment/types.js +2 -0
  22. package/dist/modules/Payment/walletpass.d.ts +1 -1
  23. package/dist/modules/Payment/walletpass.js +80 -47
  24. package/dist/modules/Rules/index.d.ts +2 -2
  25. package/dist/modules/Rules/index.js +480 -186
  26. package/dist/modules/Rules/types.d.ts +4 -0
  27. package/dist/server/modules/order/types.d.ts +2 -0
  28. package/dist/solution/BaseSales/index.d.ts +1 -0
  29. package/dist/solution/BaseSales/index.js +5 -2
  30. package/dist/solution/BaseSales/types.d.ts +2 -2
  31. package/dist/solution/BaseSales/utils/cartPromotion.js +141 -126
  32. package/dist/solution/BookingByStep/index.d.ts +1 -1
  33. package/dist/solution/BookingTicket/index.d.ts +2 -3
  34. package/dist/solution/BookingTicket/index.js +60 -63
  35. package/dist/solution/BookingTicket/types.d.ts +5 -1
  36. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +2 -0
  37. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +338 -147
  38. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +8 -4
  39. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +6 -0
  40. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.js +19 -6
  41. package/dist/solution/ShopDiscount/index.d.ts +2 -0
  42. package/dist/solution/ShopDiscount/index.js +99 -42
  43. package/dist/solution/ShopDiscount/utils.d.ts +4 -2
  44. package/dist/solution/ShopDiscount/utils.js +43 -23
  45. package/dist/solution/UnifiedBookingSales/index.js +2 -2
  46. package/lib/model/strategy/adapter/promotion/index.js +46 -1
  47. package/lib/model/strategy/adapter/walletPass/evaluator.d.ts +2 -0
  48. package/lib/model/strategy/adapter/walletPass/evaluator.js +2 -0
  49. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +35 -6
  50. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +13 -6
  51. package/lib/modules/Customer/index.js +5 -1
  52. package/lib/modules/Customer/types.d.ts +2 -0
  53. package/lib/modules/Discount/availability.d.ts +7 -0
  54. package/lib/modules/Discount/availability.js +43 -0
  55. package/lib/modules/Discount/entitlementPass.d.ts +34 -0
  56. package/lib/modules/Discount/entitlementPass.js +141 -0
  57. package/lib/modules/Discount/index.d.ts +2 -2
  58. package/lib/modules/Discount/index.js +23 -129
  59. package/lib/modules/Discount/types.d.ts +36 -5
  60. package/lib/modules/Order/index.d.ts +6 -0
  61. package/lib/modules/Order/index.js +213 -40
  62. package/lib/modules/Order/utils/orderCollectionIdentity.js +14 -11
  63. package/lib/modules/Order/utils.d.ts +1 -1
  64. package/lib/modules/Order/utils.js +39 -3
  65. package/lib/modules/Payment/types.d.ts +21 -1
  66. package/lib/modules/Payment/types.js +1 -0
  67. package/lib/modules/Payment/walletpass.d.ts +1 -1
  68. package/lib/modules/Payment/walletpass.js +29 -9
  69. package/lib/modules/Rules/index.d.ts +2 -2
  70. package/lib/modules/Rules/index.js +357 -110
  71. package/lib/modules/Rules/types.d.ts +4 -0
  72. package/lib/server/modules/order/types.d.ts +2 -0
  73. package/lib/solution/BaseSales/index.d.ts +1 -0
  74. package/lib/solution/BaseSales/index.js +5 -2
  75. package/lib/solution/BaseSales/types.d.ts +2 -2
  76. package/lib/solution/BaseSales/utils/cartPromotion.js +12 -4
  77. package/lib/solution/BookingByStep/index.d.ts +1 -1
  78. package/lib/solution/BookingTicket/index.d.ts +2 -3
  79. package/lib/solution/BookingTicket/index.js +36 -33
  80. package/lib/solution/BookingTicket/types.d.ts +5 -1
  81. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +2 -0
  82. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +174 -42
  83. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +8 -4
  84. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +6 -0
  85. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.js +11 -3
  86. package/lib/solution/ShopDiscount/index.d.ts +2 -0
  87. package/lib/solution/ShopDiscount/index.js +55 -9
  88. package/lib/solution/ShopDiscount/utils.d.ts +4 -2
  89. package/lib/solution/ShopDiscount/utils.js +42 -25
  90. package/lib/solution/UnifiedBookingSales/index.js +2 -2
  91. package/package.json +1 -1
@@ -11,6 +11,8 @@ var _utils2 = require("../Cart/utils");
11
11
  var _decimal = _interopRequireDefault(require("decimal.js"));
12
12
  var _lodashEs = require("lodash-es");
13
13
  var _dayjs = _interopRequireDefault(require("dayjs"));
14
+ var _entitlementPass = require("../Discount/entitlementPass");
15
+ var _availability = require("../Discount/availability");
14
16
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
17
  class RulesModule extends _BaseModule.BaseModule {
16
18
  defaultName = 'rules';
@@ -49,12 +51,20 @@ class RulesModule extends _BaseModule.BaseModule {
49
51
  }
50
52
 
51
53
  /**
52
- * 特定 form Holder 卡只授权给绑定同一 Holder Record 的商品行。
53
- * required/isNeedHolder 仅控制是否强制选择 Holder,不参与优惠资格。
54
+ * 商品未开启 Holder 选择时跳过匹配;已开启时,特定 form Holder 卡
55
+ * 只适用于同一 Holder Record,是否必填不影响匹配规则。
54
56
  */
55
- checkHolderMatch(discount, product, holders) {
57
+ checkHolderMatch(discount, product, holderSource, holders) {
56
58
  // 非表单类型 holder 视为匹配
57
59
  if (discount.holder?.holder_type !== 'form') return true;
60
+
61
+ // getProduct 会裁剪商品字段,从原始商品读取配置,套餐子项沿用父商品。
62
+ const holderConfig = holderSource?.holder_config ?? holderSource?.metadata?.holder_config ?? holderSource?.origin?.holder_config ?? holderSource?.metadata?.origin?.holder_config ?? holderSource?._origin?.holder_config ?? holderSource?._extend?.holder_config ?? holderSource?._extend?.product?.holder_config ?? holderSource?._extend?.product?.metadata?.holder_config;
63
+ const holderStatus = holderConfig?.status;
64
+ const holderEnabled = holderStatus === true || ['enable', '1'].includes(String(holderStatus).trim().toLowerCase());
65
+ if (!holderEnabled || holderConfig?.resource_id === undefined || holderConfig?.resource_id === null || holderConfig?.resource_id === '') {
66
+ return true;
67
+ }
58
68
  const discountHolderIds = this.normalizeHolderRecordIds(discount.holder.holder_id);
59
69
  if (!discountHolderIds.length) return false;
60
70
  const productHolderIds = this.normalizeHolderRecordIds(product.holder_id);
@@ -94,10 +104,12 @@ class RulesModule extends _BaseModule.BaseModule {
94
104
  unavailableReason: _types.UnavailableReason.AlreadyUsed
95
105
  };
96
106
  }
107
+ const scannedEntitlementPassIds = newDiscountList.filter(discount => (0, _entitlementPass.isEntitlementPass)(discount)).map(discount => discount.id);
108
+ const scannedEntitlementPassIdSet = new Set(scannedEntitlementPassIds.map(String));
97
109
 
98
- // 合并新旧折扣列表,并计算折扣结果,注意,如果旧折扣里有 isEditMode 为 true 的优惠券,则不合并
99
- // 保留之前扫码得到的商品券(isScan: true)
100
- const filteredOldDiscountList = oldDiscountList.filter(discount => !discount.isEditMode && (discount.tag !== 'good_pass' || discount.isScan));
110
+ // 客户次卡必须保留在完整列表中;同一实例以本次扫码数据更新。
111
+ // 历史折扣不参与试算,商品券继续沿用仅保留扫码来源的规则。
112
+ const filteredOldDiscountList = oldDiscountList.filter(discount => !discount.isEditMode && (!(0, _entitlementPass.isFullCoveragePass)(discount) || (0, _entitlementPass.isEntitlementPass)(discount) || discount.isScan) && !scannedEntitlementPassIdSet.has(String(discount.id)));
101
113
  const mergedDiscountList = (0, _utils.uniqueById)([...filteredOldDiscountList, ...newDiscountList]);
102
114
  const result = this.calcDiscount({
103
115
  discountList: mergedDiscountList,
@@ -106,7 +118,8 @@ class RulesModule extends _BaseModule.BaseModule {
106
118
  holders,
107
119
  isFormSubject
108
120
  }, {
109
- scan: true
121
+ scan: true,
122
+ preferredEntitlementPassIds: scannedEntitlementPassIds
110
123
  });
111
124
 
112
125
  // 检查是否有产品使用了新折扣
@@ -206,6 +219,7 @@ class RulesModule extends _BaseModule.BaseModule {
206
219
  isFormSubject,
207
220
  orderTotalAmount
208
221
  }, options) {
222
+ const preferredEntitlementPassIds = new Set((options?.preferredEntitlementPassIds || []).map(String));
209
223
  const resolveIsFormSubject = product => typeof isFormSubject === 'function' ? Boolean(isFormSubject(product)) : Boolean(isFormSubject);
210
224
 
211
225
  // 识别出来是不是在编辑的界面里又新增了商品
@@ -222,7 +236,7 @@ class RulesModule extends _BaseModule.BaseModule {
222
236
  const uid = getOriginProductUid(originProduct);
223
237
  if (!uid || !reapplyBookingDiscountProductUids.has(uid)) return false;
224
238
  const discountType = selectedDiscount.tag || selectedDiscount.type;
225
- return selectedDiscount.isEditMode === true && selectedDiscount.isSelected === true && ['good_pass', 'discount_card', 'product_discount_card'].includes(discountType);
239
+ return selectedDiscount.isEditMode === true && selectedDiscount.isSelected === true && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType ?? '');
226
240
  };
227
241
  const resolveReapplyBookingDiscountPercent = (originProduct, selectedDiscount) => {
228
242
  if (!shouldReapplyBookingDiscount(originProduct, selectedDiscount)) return undefined;
@@ -239,7 +253,13 @@ class RulesModule extends _BaseModule.BaseModule {
239
253
  if (discount.isEditMode) {
240
254
  editModeDiscount.push(discount);
241
255
  } else {
242
- addModeDiscount.push(discount);
256
+ // 试算不能把 config / 不可用原因写回原有选券;每次重新计算以清除旧原因。
257
+ addModeDiscount.push({
258
+ ...discount,
259
+ usageLimitFailKey: (0, _availability.getDiscountUsageLimitFailKey)(discount),
260
+ reason: undefined,
261
+ reasonCode: (0, _availability.getDiscountUsageBlockReason)(discount)
262
+ });
243
263
  }
244
264
  });
245
265
 
@@ -268,7 +288,7 @@ class RulesModule extends _BaseModule.BaseModule {
268
288
  }
269
289
  const canUseEditModeDiscountForReapply = discount => {
270
290
  const discountType = discount.tag || discount.type;
271
- return reapplyBookingDiscountProductUids.size > 0 && discount.isEditMode === true && discount.isSelected === true && ['good_pass', 'discount_card', 'product_discount_card'].includes(discountType);
291
+ return reapplyBookingDiscountProductUids.size > 0 && discount.isEditMode === true && discount.isSelected === true && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType ?? '');
272
292
  };
273
293
 
274
294
  // 过滤掉手动取消false的优惠券,但仅用于应用优惠逻辑。
@@ -342,6 +362,7 @@ class RulesModule extends _BaseModule.BaseModule {
342
362
 
343
363
  // 辅助函数:判断是否是商品券
344
364
  const isGoodPass = discount => discount.tag === 'good_pass';
365
+ const isEntitlement = discount => (0, _entitlementPass.isEntitlementPass)(discount);
345
366
 
346
367
  // 辅助函数:判断是否是订单级折扣卡
347
368
  const isOrderLevelDiscount = discount => discount.tag === 'product_discount_card' && discount.metadata?.discount_calculation_mode === 'order_level';
@@ -403,6 +424,14 @@ class RulesModule extends _BaseModule.BaseModule {
403
424
  }
404
425
  return 0;
405
426
  }
427
+ const entitlementA = isEntitlement(a);
428
+ const entitlementB = isEntitlement(b);
429
+ if (entitlementA || entitlementB) {
430
+ if (entitlementA && entitlementB) {
431
+ return (0, _entitlementPass.compareEntitlementPassPriority)(a, b);
432
+ }
433
+ return entitlementA ? -1 : 1;
434
+ }
406
435
 
407
436
  // 1. 先按优先级排序
408
437
  const priorityA = getPriority(a);
@@ -471,19 +500,34 @@ class RulesModule extends _BaseModule.BaseModule {
471
500
 
472
501
  // 🔥 为每个折扣卡/商品券执行策略检查并附加config
473
502
  const evaluator = this.getWalletPassEvaluator();
503
+ addModeDiscount.forEach(discount => {
504
+ if (discount.reasonCode) discount.config = {
505
+ isAvailable: false
506
+ };
507
+ });
474
508
  if (evaluator) {
475
509
  addModeDiscount.forEach(discount => {
510
+ // 即使没有匹配的动态策略,服务端状态和次数限制也不能被覆盖为可用。
511
+ if (discount.reasonCode) return;
476
512
  const discountType = discount.tag || discount.type;
477
- // 只对 good_pass 和 discount_card 类型执行策略检查
478
- if (['good_pass', 'discount_card', 'product_discount_card'].includes(discountType)) {
513
+ // 对两类全额抵扣卡和折扣卡执行附加策略检查。
514
+ if (['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType ?? '')) {
515
+ const entitlementQuota = (0, _entitlementPass.isEntitlementPass)(discount) ? (0, _entitlementPass.resolveEntitlementQuota)(discount) : null;
516
+ if ((0, _entitlementPass.isEntitlementPass)(discount) && !entitlementQuota) {
517
+ discount.config = {
518
+ isAvailable: false
519
+ };
520
+ return;
521
+ }
522
+
479
523
  // 转换 discount 为 Voucher 格式
480
524
  const voucher = {
481
525
  id: discount.id,
482
526
  amount: Number(discount.par_value || 0),
483
- balance: Number(discount.balance || 0),
527
+ balance: entitlementQuota?.type === 'unlimited' ? Number.MAX_SAFE_INTEGER : entitlementQuota?.type === 'limited' ? entitlementQuota.balance : Number(discount.balance || 0),
484
528
  type: discountType,
485
529
  product_id: discount.product_id,
486
- unified_available_status: 1,
530
+ unified_available_status: discount.unified_available_status ?? 1,
487
531
  available_product_type: discount.limited_relation_product_data?.type,
488
532
  available_product_ids: discount.limited_relation_product_data?.product_ids
489
533
  };
@@ -514,6 +558,8 @@ class RulesModule extends _BaseModule.BaseModule {
514
558
  discount.config = {
515
559
  isAvailable: false
516
560
  };
561
+ discount.reason = result.reason;
562
+ discount.reasonCode = result.reasonCode || 'not_meet_the_required_conditions';
517
563
  }
518
564
  }
519
565
  });
@@ -536,17 +582,126 @@ class RulesModule extends _BaseModule.BaseModule {
536
582
  });
537
583
  */
538
584
 
539
- // 标记已使用的优惠券
585
+ // good_pass / 折扣卡保持原有的一次性使用标记。
540
586
  const usedDiscounts = new Map();
541
587
 
588
+ // Entitlement Pass 单独记录本次重算新增分配的次数。
589
+ const entitlementUsageCounts = new Map();
590
+
542
591
  // 🔥 统计每个 product_id(商品券商品id)已使用的数量,用于 maxUsagePerOrder 限制
543
592
  const usedProductIdCounts = new Map();
593
+ const markDiscountUsed = (discount, count = 1) => {
594
+ if ((0, _entitlementPass.isEntitlementPass)(discount)) {
595
+ entitlementUsageCounts.set(discount.id, (entitlementUsageCounts.get(discount.id) || 0) + count);
596
+ return;
597
+ }
598
+ usedDiscounts.set(discount.id, true);
599
+ };
600
+ const isDiscountUsed = discount => {
601
+ if ((0, _entitlementPass.isEntitlementPass)(discount)) {
602
+ return (entitlementUsageCounts.get(discount.id) || 0) > 0;
603
+ }
604
+ return usedDiscounts.get(discount.id) === true;
605
+ };
606
+ const buildFullCoveragePassUsageGroups = (discounts, requestedCount) => {
607
+ const groups = [];
608
+ const pendingUsedDiscounts = new Set(Array.from(usedDiscounts.entries()).filter(([, used]) => used).map(([discountId]) => discountId));
609
+ const pendingEntitlementCounts = new Map(entitlementUsageCounts);
610
+ const pendingProductCounts = new Map(usedProductIdCounts);
611
+ const firstGoodPass = discounts.find(discount => (0, _entitlementPass.isFullCoveragePass)(discount) && !(0, _entitlementPass.isEntitlementPass)(discount));
612
+ const legacyGoodPassPerLineLimit = firstGoodPass ? Number(firstGoodPass.config?.maxUsagePerOrder || 0) : 0;
613
+ let allocatedGoodPassCount = 0;
614
+ let remaining = Math.max(Math.floor(requestedCount), 0);
615
+ for (const discount of discounts) {
616
+ if (remaining <= 0) break;
617
+ if (!(0, _entitlementPass.isFullCoveragePass)(discount)) continue;
618
+ const currentEntitlementCount = pendingEntitlementCounts.get(discount.id) || 0;
619
+ let availableCount = (0, _entitlementPass.isEntitlementPass)(discount) ? (0, _entitlementPass.getRemainingEntitlementUses)(discount, currentEntitlementCount, remaining) : pendingUsedDiscounts.has(discount.id) ? 0 : 1;
620
+ if (!(0, _entitlementPass.isEntitlementPass)(discount) && legacyGoodPassPerLineLimit > 0) {
621
+ availableCount = Math.min(availableCount, Math.max(Math.floor(legacyGoodPassPerLineLimit) - allocatedGoodPassCount, 0));
622
+ }
623
+ const maxUsagePerOrder = Number(discount.config?.maxUsagePerOrder || 0);
624
+ if ((0, _entitlementPass.isEntitlementPass)(discount) && maxUsagePerOrder > 0) {
625
+ const currentProductCount = pendingProductCounts.get(discount.product_id) || 0;
626
+ availableCount = Math.min(availableCount, Math.max(Math.floor(maxUsagePerOrder) - currentProductCount, 0));
627
+ }
628
+ const allocatedCount = Math.min(availableCount, remaining);
629
+ if (allocatedCount <= 0) continue;
630
+ const existingGroup = groups.find(group => String(group.discount.id) === String(discount.id));
631
+ if (existingGroup) {
632
+ existingGroup.count += allocatedCount;
633
+ } else {
634
+ groups.push({
635
+ discount,
636
+ count: allocatedCount
637
+ });
638
+ }
639
+ if ((0, _entitlementPass.isEntitlementPass)(discount)) {
640
+ pendingEntitlementCounts.set(discount.id, currentEntitlementCount + allocatedCount);
641
+ } else {
642
+ pendingUsedDiscounts.add(discount.id);
643
+ allocatedGoodPassCount += allocatedCount;
644
+ }
645
+ pendingProductCounts.set(discount.product_id, (pendingProductCounts.get(discount.product_id) || 0) + allocatedCount);
646
+ remaining -= allocatedCount;
647
+ }
648
+ return groups;
649
+ };
650
+ const mergeEntitlementAppliedProductDetails = details => {
651
+ const mergedDetails = [];
652
+ const mergedIndexByKey = new Map();
653
+ const toComparableNumber = value => {
654
+ const numberValue = Number(value);
655
+ return Number.isFinite(numberValue) ? String(numberValue) : String(value ?? '');
656
+ };
657
+ for (const detail of details || []) {
658
+ if (!(0, _entitlementPass.isEntitlementPass)(detail)) {
659
+ mergedDetails.push(detail);
660
+ continue;
661
+ }
662
+ const resourceId = detail?.discount?.resource_id ?? detail?.resource_id;
663
+ if (resourceId === undefined || resourceId === null) {
664
+ mergedDetails.push(detail);
665
+ continue;
666
+ }
667
+ const key = [resourceId, detail?.discount?.product_id ?? '', detail?.metadata?.custom_product_bundle_map_id ?? '', toComparableNumber(detail?.amount), toComparableNumber(detail?.discount?.fixed_amount)].join('|');
668
+ const rawUsageCount = Number(detail?.metadata?.num ?? detail?._num ?? 1);
669
+ const usageCount = Number.isFinite(rawUsageCount) && rawUsageCount > 0 ? rawUsageCount : 1;
670
+ const mergedIndex = mergedIndexByKey.get(key);
671
+ if (mergedIndex === undefined) {
672
+ mergedIndexByKey.set(key, mergedDetails.length);
673
+ mergedDetails.push({
674
+ ...detail,
675
+ metadata: {
676
+ ...(detail?.metadata || {}),
677
+ num: usageCount
678
+ },
679
+ _num: usageCount
680
+ });
681
+ continue;
682
+ }
683
+ const existed = mergedDetails[mergedIndex];
684
+ const existedUsageCount = Number(existed?.metadata?.num ?? existed?._num ?? 1);
685
+ const totalUsageCount = existedUsageCount + usageCount;
686
+ mergedDetails[mergedIndex] = {
687
+ ...existed,
688
+ metadata: {
689
+ ...(existed?.metadata || {}),
690
+ num: totalUsageCount
691
+ },
692
+ _num: totalUsageCount
693
+ };
694
+ }
695
+ return mergedDetails;
696
+ };
544
697
 
545
698
  // 记录每个优惠券适用的商品ID
546
699
  const discountApplicability = new Map();
547
700
 
548
701
  // 记录每个优惠券适用的商品详细信息
549
702
  const discountApplicableProducts = new Map();
703
+ const discountTimeReasons = new Map();
704
+ const discountHolderMismatch = new Set();
550
705
 
551
706
  // 初始化每个优惠券的适用性和可抵扣商品
552
707
  addModeDiscount.forEach(discount => {
@@ -566,6 +721,7 @@ class RulesModule extends _BaseModule.BaseModule {
566
721
 
567
722
  // 辅助函数:检查商品是否对某个折扣卡可用
568
723
  const checkItemApplicableForDiscount = (flatItem, discount) => {
724
+ if (discount.config?.isAvailable === false) return false;
569
725
  let product;
570
726
  if (flatItem.type === 'main') {
571
727
  product = flatItem.product;
@@ -586,7 +742,7 @@ class RulesModule extends _BaseModule.BaseModule {
586
742
  }
587
743
 
588
744
  // 编辑的商品使用了优惠券不可用
589
- const isAvailableProduct = flatItem.type === 'main' ? !(product?.booking_id && product?.discount_list?.length && product?.discount_list?.every(d => d.id && ['good_pass', 'discount_card', 'product_discount_card'].includes(d.tag || d.type))) : !(flatItem?.booking_id && !!flatItem?.bundleItem?.discount_list?.length && flatItem?.bundleItem?.discount_list?.every(d => d.id));
745
+ const isAvailableProduct = flatItem.type === 'main' ? !(product?.booking_id && product?.discount_list?.length && product?.discount_list?.every(d => d.id && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(d.tag || d.type))) : !(flatItem?.booking_id && !!flatItem?.bundleItem?.discount_list?.length && flatItem?.bundleItem?.discount_list?.every(d => d.id));
590
746
  if (!isAvailableProduct) {
591
747
  return false;
592
748
  }
@@ -770,30 +926,37 @@ class RulesModule extends _BaseModule.BaseModule {
770
926
  const isHolderMatch = this.checkHolderMatch(discount, {
771
927
  isNeedHolder: resolveIsFormSubject(_tempVar) && !_tempVar?.isNormalProduct,
772
928
  holder_id: _tempVar?.holder_id || product.holder_id
773
- }, holders);
774
- let timeLimit = true;
775
- timeLimit = !!(0, _utils.filterDiscountListByBookingTime)([discount], (product?.startDate || (0, _dayjs.default)()).format('YYYY-MM-DD HH:mm:ss')).length;
929
+ }, flatItem.originProduct, holders);
930
+ const timeReason = (0, _utils.getDiscountTimeUnavailableReason)(discount, (product?.startDate || (0, _dayjs.default)()).format('YYYY-MM-DD HH:mm:ss'));
931
+ const timeLimit = !timeReason;
776
932
  // 是符合折扣的商品
777
- const isLimitedProduct = (limitedData.type === 'product_all' && limitedData.filter !== 1 || limitedData.type === 'product_all' && limitedData.filter === 1 && !limitedData.exclude_product_ids.includes(product.id) || limitedData.product_ids && limitedData.product_ids.includes(product.id)) && isHolderMatch;
933
+ const isProductInScope = limitedData.type === 'product_all' && limitedData.filter !== 1 || limitedData.type === 'product_all' && limitedData.filter === 1 && !limitedData.exclude_product_ids.includes(product.id) || limitedData.product_ids && limitedData.product_ids.includes(product.id);
934
+ const isLimitedProduct = isProductInScope && isHolderMatch;
778
935
 
779
936
  // 编辑的商品 使用了优惠券不可用
780
- const isAvailableProduct = flatItem.type === 'main' ? !(product?.booking_id && product?.discount_list?.length && product?.discount_list?.every(discount => discount.id && ['good_pass', 'discount_card', 'product_discount_card'].includes(discount.tag || discount.type))) : !(flatItem?.booking_id && !!flatItem?.bundleItem?.discount_list?.length && flatItem?.bundleItem?.discount_list?.every(discount => discount.id));
937
+ const isAvailableProduct = flatItem.type === 'main' ? !(product?.booking_id && product?.discount_list?.length && product?.discount_list?.every(discount => discount.id && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discount.tag || discount.type))) : !(flatItem?.booking_id && !!flatItem?.bundleItem?.discount_list?.length && flatItem?.bundleItem?.discount_list?.every(discount => discount.id));
781
938
 
782
939
  // 套餐是否可用判断
783
940
  const isBundleAvailable = this.checkPackageSubItemUsageRules(discount, flatItem);
941
+ if (isProductInScope && isBundleAvailable && !isItemRewardProductDiscount) {
942
+ const timeReasons = discountTimeReasons.get(discount.id) || [];
943
+ timeReasons.push(timeReason);
944
+ discountTimeReasons.set(discount.id, timeReasons);
945
+ if (!isHolderMatch && timeLimit) discountHolderMismatch.add(discount.id);
946
+ }
784
947
 
785
948
  // 判断优惠券是否适用于该商品
786
- if (isAvailableProduct && !isItemRewardProductDiscount && isLimitedProduct && timeLimit && isBundleAvailable && discount.config?.isAvailable) {
949
+ if (isAvailableProduct && !isItemRewardProductDiscount && isLimitedProduct && timeLimit && isBundleAvailable && discount.config?.isAvailable && (!(0, _entitlementPass.isEntitlementPass)(discount) || (0, _entitlementPass.getRemainingEntitlementUses)(discount, 0, 1) > 0)) {
787
950
  // 记录此优惠券适用的商品
788
951
  discountApplicability.get(discount.id)?.push(product.id);
789
952
 
790
953
  // 记录可抵扣的商品详情
791
954
  const applicableProducts = discountApplicableProducts.get(discount.id) || [];
792
955
  const discountType = discount.tag || discount.type;
793
- const isGoodPass = discountType === 'good_pass';
956
+ const isFullCoverage = (0, _entitlementPass.isFullCoveragePass)(discount);
794
957
 
795
958
  // 使用数量
796
- const num = isGoodPass || flatItem?.type === 'main' ? 1 : product.num;
959
+ const num = isFullCoverage || flatItem?.type === 'main' ? 1 : product.num;
797
960
  const productData = {
798
961
  amount: product.price * num,
799
962
  type: discountType,
@@ -810,6 +973,7 @@ class RulesModule extends _BaseModule.BaseModule {
810
973
  discount_product_id: discount.product_id
811
974
  },
812
975
  metadata: {
976
+ encoded: discount.metadata?.encoded || discount.encoded,
813
977
  num: num,
814
978
  discount_rule_uncheck_flag: discount?.discount_rule_uncheck_flag
815
979
  }
@@ -911,7 +1075,7 @@ class RulesModule extends _BaseModule.BaseModule {
911
1075
  const hasExistingWalletDiscount = product.discount_list?.length && product?.discount_list?.every(discount => {
912
1076
  const discountIdentity = discount.id ?? discount.discount?.resource_id;
913
1077
  const discountType = discount.tag || discount.type;
914
- return Boolean(discountIdentity && ['good_pass', 'discount_card', 'product_discount_card'].includes(discountType));
1078
+ return Boolean(discountIdentity && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType));
915
1079
  });
916
1080
 
917
1081
  // 已持久化且已有钱包券/折扣卡的商品行跳过,保留后端历史折扣结果。
@@ -928,7 +1092,7 @@ class RulesModule extends _BaseModule.BaseModule {
928
1092
  // 找到适用于此商品的所有优惠券,仅考虑isSelected不为false的优惠券
929
1093
  const applicableDiscounts = sortedDiscountList.filter(discount => {
930
1094
  if (this.isItemRewardProductDiscount(product)) return false;
931
- // 🔥 检查策略可用性(针对 good_pass 和折扣卡)
1095
+ // 🔥 检查策略可用性(针对全额抵扣卡和折扣卡)
932
1096
  const discountType = discount.tag || discount.type;
933
1097
  const currentOriginUid = getOriginProductUid(originProduct);
934
1098
  const isReapplyEditModeDiscountForProduct = discount.isEditMode && reapplyBookingDiscountProductUids.size > 0 && currentOriginUid && reapplyBookingDiscountProductUids.has(String(currentOriginUid)) && discount.isSelected === true;
@@ -937,7 +1101,7 @@ class RulesModule extends _BaseModule.BaseModule {
937
1101
  if (!uid || !reapplyBookingDiscountProductUids.has(uid)) return false;
938
1102
  if (!discount.isSelected) return false;
939
1103
  }
940
- if (['good_pass', 'discount_card', 'product_discount_card'].includes(discountType) && !isReapplyEditModeDiscountForProduct) {
1104
+ if (['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType ?? '') && !isReapplyEditModeDiscountForProduct) {
941
1105
  // 如果策略检查后没有config,说明不可用
942
1106
  if (discount.config === undefined || !discount?.config?.isAvailable) {
943
1107
  return false;
@@ -945,17 +1109,22 @@ class RulesModule extends _BaseModule.BaseModule {
945
1109
  }
946
1110
 
947
1111
  // 如果商品价格为 0,其实不需要使用任何优惠券,直接 return true
948
- // 商品券时主商品价格为0不可用
949
- if ((Number(product.price) <= 0 || !product.price) && !product.discount_list?.length && (discount.tag || discount.type) === 'good_pass') return false;
1112
+ // 全额抵扣卡在主商品价格为 0 时不可用。
1113
+ if ((Number(product.price) <= 0 || !product.price) && !product.discount_list?.length && (0, _entitlementPass.isFullCoveragePass)(discount)) return false;
950
1114
 
951
1115
  // 折扣卡商品价格为0时不可用
952
- if ((Number(product.price) <= 0 || !product.price) && !product.discount_list?.find(n => n.discount?.resource_id === discount.id) && (discount.tag || discount.type) !== 'good_pass') return false;
953
- // 如果优惠券已被使用,则跳过
954
- const targetUsedDiscounts = usedDiscounts.get(discount.id);
955
- if (targetUsedDiscounts && (discount.tag || discount.type) === 'good_pass') return false;
1116
+ if ((Number(product.price) <= 0 || !product.price) && !product.discount_list?.find(n => n.discount?.resource_id === discount.id) && !(0, _entitlementPass.isFullCoveragePass)(discount)) return false;
1117
+ // good_pass 保持一张实例只使用一次。
1118
+ if ((discount.tag || discount.type) === 'good_pass' && usedDiscounts.get(discount.id)) {
1119
+ return false;
1120
+ }
1121
+ // 有限次数卡按后端实时 balance 约束本次新增分配;无限卡不看余额。
1122
+ if ((0, _entitlementPass.isEntitlementPass)(discount) && (0, _entitlementPass.getRemainingEntitlementUses)(discount, entitlementUsageCounts.get(discount.id) || 0, 1) <= 0) {
1123
+ return false;
1124
+ }
956
1125
 
957
1126
  // 🔥 检查 maxUsagePerOrder 限制:同一 product_id 的商品券使用数量不能超过配置值
958
- if ((discount.tag || discount.type) === 'good_pass') {
1127
+ if ((0, _entitlementPass.isFullCoveragePass)(discount)) {
959
1128
  const maxUsagePerOrder = discount.config?.maxUsagePerOrder;
960
1129
  if (maxUsagePerOrder && maxUsagePerOrder > 0) {
961
1130
  const currentUsedCount = usedProductIdCounts.get(discount.product_id) || 0;
@@ -971,7 +1140,7 @@ class RulesModule extends _BaseModule.BaseModule {
971
1140
  const isHolderMatch = this.checkHolderMatch(discount, {
972
1141
  isNeedHolder: resolveIsFormSubject(_tempVar) && !_tempVar?.isNormalProduct,
973
1142
  holder_id: _tempVar?.holder_id || product.holder_id
974
- }, holders);
1143
+ }, flatItem.originProduct, holders);
975
1144
  // 如果 holder 不匹配,则不适用
976
1145
  if (!isHolderMatch) return false;
977
1146
  let timeLimit = true;
@@ -1000,31 +1169,34 @@ class RulesModule extends _BaseModule.BaseModule {
1000
1169
  return false;
1001
1170
  });
1002
1171
 
1003
- // 用户显式点击某张卡券时,本次选择优先于自动排序和扫码默认选择。
1172
+ // 识别用户本次显式选择的卡券,供次卡和折扣卡各自的优先级使用。
1004
1173
  // 目标仍必须在当前商品的 applicableDiscounts 中,因此不会绕过 Holder、时间或商品范围校验。
1005
1174
  const explicitlySelectedDiscount = options?.isSelected === true && options.discountId !== undefined ? applicableDiscounts.find(discount => {
1006
1175
  const discountType = discount.tag || discount.type;
1007
- return String(discount.id) === String(options.discountId) && ['good_pass', 'discount_card', 'product_discount_card'].includes(discountType);
1176
+ return String(discount.id) === String(options.discountId) && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType ?? '');
1008
1177
  }) : undefined;
1009
1178
  // 折扣卡会复用于整条商品行;商品券必须继续按单张拆分,不能复用该分支。
1010
- const explicitlySelectedDiscountCard = explicitlySelectedDiscount && (explicitlySelectedDiscount.tag || explicitlySelectedDiscount.type) !== 'good_pass' ? explicitlySelectedDiscount : undefined;
1179
+ const explicitlySelectedDiscountCard = explicitlySelectedDiscount && !(0, _entitlementPass.isFullCoveragePass)(explicitlySelectedDiscount) ? explicitlySelectedDiscount : undefined;
1011
1180
 
1012
- // 商品数量等变化会触发无 discountId 的重算。只要当前行已应用的折扣卡仍在
1181
+ // 商品数量等变化会触发无 discountId 的重算。只要当前行已应用的卡仍在
1013
1182
  // applicableDiscounts 中,就应保留该行选择,避免被自动排序中力度更大的卡替换。
1014
- const appliedDiscountCardIds = new Set((product.discount_list || []).filter(item => ['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));
1183
+ 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));
1015
1184
  const appliedDiscountCard = options?.scan ? undefined : applicableDiscounts.find(discount => {
1016
1185
  const discountType = discount.tag || discount.type;
1017
- return discount.isSelected === true && ['discount_card', 'product_discount_card'].includes(discountType) && appliedDiscountCardIds.has(String(discount.id));
1186
+ return discount.isSelected === true && ['discount_card', 'product_discount_card'].includes(discountType ?? '') && appliedWalletDiscountIds.has(String(discount.id));
1018
1187
  });
1188
+ const appliedEntitlementPass = options?.scan || options?.preserveEntitlementSelection === false ? undefined : applicableDiscounts.find(discount => (0, _entitlementPass.isEntitlementPass)(discount) && discount.isSelected === true && appliedWalletDiscountIds.has(String(discount.id)));
1019
1189
 
1020
- // 优先级:本次显式选择 > 当前行既有选择 > 扫码选择 > 自动排序第一项。
1021
- const scannedSelectedDiscountCard = applicableDiscounts.find(n => n.isScan && n.isSelected && (n.tag || n.type) !== 'good_pass');
1190
+ // 次卡内部按本次手选/扫码、当前行已应用、默认排序选择。
1191
+ const scannedSelectedDiscountCard = applicableDiscounts.find(n => n.isScan && n.isSelected && !(0, _entitlementPass.isFullCoveragePass)(n));
1022
1192
  const selectedDiscountCard = explicitlySelectedDiscountCard || appliedDiscountCard || scannedSelectedDiscountCard;
1023
- const selectedDiscount = explicitlySelectedDiscount || selectedDiscountCard || applicableDiscounts[0];
1024
- const prioritizedApplicableDiscounts = explicitlySelectedDiscount && (explicitlySelectedDiscount.tag || explicitlySelectedDiscount.type) === 'good_pass' ? [explicitlySelectedDiscount, ...applicableDiscounts.filter(discount => {
1025
- const discountType = discount.tag || discount.type;
1026
- return discountType === 'good_pass' && String(discount.id) !== String(explicitlySelectedDiscount.id);
1027
- }), ...applicableDiscounts.filter(discount => (discount.tag || discount.type) !== 'good_pass')] : applicableDiscounts;
1193
+ const selectedEntitlementPass = (explicitlySelectedDiscount && (0, _entitlementPass.isEntitlementPass)(explicitlySelectedDiscount) ? explicitlySelectedDiscount : undefined) || applicableDiscounts.find(discount => (0, _entitlementPass.isEntitlementPass)(discount) && preferredEntitlementPassIds.has(String(discount.id))) || appliedEntitlementPass || applicableDiscounts.find(discount => (0, _entitlementPass.isEntitlementPass)(discount));
1194
+ // 手选优先;普通重算保留当前折扣卡,扫码和最优选择仍使用原有优先级。
1195
+ const selectedDiscount = explicitlySelectedDiscount || (options?.preserveEntitlementSelection !== false && preferredEntitlementPassIds.size === 0 ? appliedDiscountCard : undefined) || selectedEntitlementPass || selectedDiscountCard || applicableDiscounts[0];
1196
+ // 实际次数分配必须使用同一顺序,避免选中状态切换后仍将次数分配给默认卡。
1197
+ const prioritizedApplicableDiscounts = selectedDiscount && (0, _entitlementPass.isFullCoveragePass)(selectedDiscount) ? [selectedDiscount, ...applicableDiscounts.filter(discount => {
1198
+ return (0, _entitlementPass.isFullCoveragePass)(discount) && String(discount.id) !== String(selectedDiscount.id);
1199
+ }), ...applicableDiscounts.filter(discount => !(0, _entitlementPass.isFullCoveragePass)(discount))] : applicableDiscounts;
1028
1200
 
1029
1201
  // 如果是手动折扣,则不适用优惠券
1030
1202
  let isManualDiscount = false;
@@ -1140,19 +1312,13 @@ class RulesModule extends _BaseModule.BaseModule {
1140
1312
  return;
1141
1313
  }
1142
1314
 
1143
- // 是否需要拆分(商品券需要拆分)
1144
- const isNeedSplit = (selectedDiscount.tag || selectedDiscount.type) === 'good_pass';
1315
+ // good_pass 与 Entitlement Pass 都沿用全额抵扣卡的商品行拆分机制。
1316
+ const isNeedSplit = (0, _entitlementPass.isFullCoveragePass)(selectedDiscount);
1145
1317
 
1146
1318
  // 需要拆分出来的数量
1147
1319
  const totalQuantity = product.quantity || product.num || 1;
1148
- const availableGoodPassCount = applicableDiscounts.filter(item => (item.tag || item.type) === 'good_pass').length;
1149
-
1150
- // 🔥 如果selectedDiscount有config配置,则使用config.maxUsagePerOrder限制使用次数
1151
- let maxUsageLimit = availableGoodPassCount;
1152
- if (selectedDiscount.config && selectedDiscount.config.maxUsagePerOrder) {
1153
- maxUsageLimit = Math.min(availableGoodPassCount, selectedDiscount.config.maxUsagePerOrder);
1154
- }
1155
- const splitCount = isNeedSplit ? Math.min(product.quantity || product.num || 1, maxUsageLimit) : 1;
1320
+ const fullCoveragePassUsageGroups = isNeedSplit ? buildFullCoveragePassUsageGroups(prioritizedApplicableDiscounts, totalQuantity) : [];
1321
+ const splitCount = isNeedSplit ? fullCoveragePassUsageGroups.reduce((total, group) => total + group.count, 0) : 1;
1156
1322
  const arr = [];
1157
1323
 
1158
1324
  // 🔥 主商品和bundle子商品分别处理
@@ -1160,22 +1326,22 @@ class RulesModule extends _BaseModule.BaseModule {
1160
1326
  // 主商品:保持原有逻辑
1161
1327
  if (splitCount < totalQuantity && isNeedSplit) {
1162
1328
  const remainingQuantity = totalQuantity - splitCount;
1163
- const applicableNonGoodPassById = new Map(applicableDiscounts.filter(discount => (discount.tag || discount.type) !== 'good_pass').map(discount => [String(discount.id), discount]));
1329
+ const applicableNonFullCoveragePassById = new Map(applicableDiscounts.filter(discount => !(0, _entitlementPass.isFullCoveragePass)(discount)).map(discount => [String(discount.id), discount]));
1164
1330
  const remainderDiscountList = (product.discount_list || []).filter(discount => {
1165
1331
  const discountType = discount.tag || discount.type;
1166
1332
  if (discountType === 'promotion') return true;
1167
- if (discountType === 'good_pass') return false;
1333
+ if ((0, _entitlementPass.isFullCoveragePass)(discount)) return false;
1168
1334
  const resourceId = discount.discount?.resource_id ?? discount.id;
1169
- return resourceId !== undefined && resourceId !== null && applicableNonGoodPassById.has(String(resourceId));
1335
+ return resourceId !== undefined && resourceId !== null && applicableNonFullCoveragePassById.has(String(resourceId));
1170
1336
  }).map(discount => {
1171
1337
  if ((discount.tag || discount.type) === 'promotion') return discount;
1172
1338
  const resourceId = discount.discount?.resource_id ?? discount.id;
1173
- const matchedDiscount = applicableNonGoodPassById.get(String(resourceId));
1339
+ const matchedDiscount = applicableNonFullCoveragePassById.get(String(resourceId));
1174
1340
  if (matchedDiscount) {
1175
1341
  // 实际场景:3 件折扣卡商品中拆出 1 件改用商品券后,
1176
1342
  // 剩余 2 件仍在使用原折扣卡;必须同步登记折扣卡的使用状态,
1177
1343
  // 否则 updatedDiscountList 会把它改成未选中并清空 savedAmount。
1178
- usedDiscounts.set(matchedDiscount.id, true);
1344
+ markDiscountUsed(matchedDiscount);
1179
1345
  const appliedProducts = appliedDiscountProducts.get(matchedDiscount.id) || [];
1180
1346
  appliedProducts.push({
1181
1347
  ...discount,
@@ -1189,14 +1355,14 @@ class RulesModule extends _BaseModule.BaseModule {
1189
1355
  _num: remainingQuantity
1190
1356
  };
1191
1357
  });
1192
- const hasRetainedWalletDiscount = remainderDiscountList.some(discount => !['promotion', 'good_pass'].includes(discount.tag || discount.type));
1358
+ const hasRetainedWalletDiscount = remainderDiscountList.some(discount => (discount.tag || discount.type) !== 'promotion' && !(0, _entitlementPass.isFullCoveragePass)(discount));
1193
1359
  let total = product.origin_total ?? product.total;
1194
1360
  if ((product.discount_list || []).some(item => item.type === 'promotion')) {
1195
1361
  total = product.total ?? product.origin_total;
1196
1362
  }
1197
1363
  arr.push(this.hooks.setProduct(originProduct, {
1198
1364
  // 商品券只替换被拆出的 splitCount 件。余量行原本仍有效的折扣卡
1199
- // 不能随 good_pass 拆分一起清除;已取消或已失效的折扣不会进入此列表。
1365
+ // 不能随全额抵扣卡拆分一起清除;已取消或已失效的折扣不会进入此列表。
1200
1366
  discount_list: remainderDiscountList,
1201
1367
  quantity: remainingQuantity,
1202
1368
  _id: product._id.split('___')[0],
@@ -1208,14 +1374,21 @@ class RulesModule extends _BaseModule.BaseModule {
1208
1374
  } : {})
1209
1375
  }));
1210
1376
  }
1211
- for (let i = 0; i < splitCount; i++) {
1212
- const selectedDiscount = isNeedSplit ? prioritizedApplicableDiscounts[i] : selectedDiscountCard || applicableDiscounts[i];
1377
+ const discountUsageGroups = isNeedSplit ? fullCoveragePassUsageGroups : [{
1378
+ discount: selectedDiscount,
1379
+ count: 1
1380
+ }];
1381
+ for (let i = 0; i < discountUsageGroups.length; i++) {
1382
+ const {
1383
+ discount: selectedDiscount,
1384
+ count: appliedUseCount
1385
+ } = discountUsageGroups[i];
1213
1386
  // 标记优惠券为已使用
1214
- usedDiscounts.set(selectedDiscount.id, true);
1387
+ markDiscountUsed(selectedDiscount, appliedUseCount);
1215
1388
  // 🔥 更新 product_id 使用计数
1216
- if ((selectedDiscount.tag || selectedDiscount.type) === 'good_pass') {
1389
+ if ((0, _entitlementPass.isFullCoveragePass)(selectedDiscount)) {
1217
1390
  const currentCount = usedProductIdCounts.get(selectedDiscount.product_id) || 0;
1218
- usedProductIdCounts.set(selectedDiscount.product_id, currentCount + 1);
1391
+ usedProductIdCounts.set(selectedDiscount.product_id, currentCount + appliedUseCount);
1219
1392
  }
1220
1393
 
1221
1394
  // 记录实际应用了优惠券的商品信息
@@ -1277,7 +1450,7 @@ class RulesModule extends _BaseModule.BaseModule {
1277
1450
  const mainProductDiscountAmount = amount;
1278
1451
  const lineDiscountAmount = new _decimal.default(mainProductDiscountAmount).plus(optionDiscountAmount).toNumber();
1279
1452
  const discountType = selectedDiscount.tag || selectedDiscount.type;
1280
- const isGoodPass = discountType === 'good_pass';
1453
+ const isFullCoverage = (0, _entitlementPass.isFullCoveragePass)(selectedDiscount);
1281
1454
  const discountDetail = {
1282
1455
  amount: lineDiscountAmount,
1283
1456
  type: selectedDiscount.tag === 'product_discount_card' ? 'discount_card' : discountType,
@@ -1293,10 +1466,11 @@ class RulesModule extends _BaseModule.BaseModule {
1293
1466
  discount_product_id: selectedDiscount.product_id
1294
1467
  },
1295
1468
  // 前端使用的num数量,为了计算优惠金额
1296
- _num: isGoodPass ? 1 : product.num,
1469
+ _num: isFullCoverage ? appliedUseCount : product.num,
1297
1470
  config: selectedDiscount?.config,
1298
1471
  metadata: {
1299
- num: 1,
1472
+ encoded: selectedDiscount.metadata?.encoded || selectedDiscount.encoded,
1473
+ num: isFullCoverage ? appliedUseCount : 1,
1300
1474
  discount_rule_uncheck_flag: selectedDiscount?.discount_rule_uncheck_flag,
1301
1475
  // 🔥 order_level 分摊差值
1302
1476
  ...(productDiscountDifference !== undefined && {
@@ -1315,9 +1489,9 @@ class RulesModule extends _BaseModule.BaseModule {
1315
1489
  if (product.isClient) {
1316
1490
  arr.push(this.hooks.setProduct(originProduct, {
1317
1491
  discount_list: [discountDetail],
1318
- // good_pass:主商品价以折后价为准;勿用 product.price - amount(amount 含 option 优惠时会算错)
1319
- price: isGoodPass ? mainProductSellingPrice : product.price,
1320
- quantity: isNeedSplit ? 1 : product.quantity,
1492
+ // 全额抵扣卡:主商品价以折后价为准;勿用 product.price - amount(amount 含 option 优惠时会算错)
1493
+ price: isFullCoverage ? mainProductSellingPrice : product.price,
1494
+ quantity: isNeedSplit ? appliedUseCount : product.quantity,
1321
1495
  origin_total: (0, _utils2.getProductOriginTotalPrice)({
1322
1496
  product: {
1323
1497
  original_price: product.original_price
@@ -1334,8 +1508,8 @@ class RulesModule extends _BaseModule.BaseModule {
1334
1508
  arr.push(this.hooks.setProduct(originProduct, {
1335
1509
  discount_list: this.filterDiscountListByType(product.discount_list, 'promotion').concat([discountDetail]),
1336
1510
  _id: product._id.split('___')[0] + '___' + selectedDiscount.id + index,
1337
- price: selectedDiscount.tag === 'good_pass' ? 0 : product.price,
1338
- quantity: isNeedSplit ? 1 : product.quantity,
1511
+ price: isFullCoverage ? 0 : product.price,
1512
+ quantity: isNeedSplit ? appliedUseCount : product.quantity,
1339
1513
  total: total,
1340
1514
  origin_total: productOriginTotal,
1341
1515
  main_product_selling_price: mainProductSellingPrice,
@@ -1352,14 +1526,17 @@ class RulesModule extends _BaseModule.BaseModule {
1352
1526
  const discountNum = splitCount;
1353
1527
  const normalNum = totalQuantity - discountNum;
1354
1528
 
1355
- // 生成有折扣的商品(每张商品券对应 num: 1)
1356
- for (let i = 0; i < discountNum; i++) {
1357
- const selectedDiscount = prioritizedApplicableDiscounts[i];
1358
- usedDiscounts.set(selectedDiscount.id, true);
1529
+ // 同一卡实例的本次新增使用合并为一条,metadata.num 记录实际次数。
1530
+ for (let i = 0; i < fullCoveragePassUsageGroups.length; i++) {
1531
+ const {
1532
+ discount: selectedDiscount,
1533
+ count: appliedUseCount
1534
+ } = fullCoveragePassUsageGroups[i];
1535
+ markDiscountUsed(selectedDiscount, appliedUseCount);
1359
1536
  // 🔥 更新 product_id 使用计数
1360
- if ((selectedDiscount.tag || selectedDiscount.type) === 'good_pass') {
1537
+ if ((0, _entitlementPass.isFullCoveragePass)(selectedDiscount)) {
1361
1538
  const currentCount = usedProductIdCounts.get(selectedDiscount.product_id) || 0;
1362
- usedProductIdCounts.set(selectedDiscount.product_id, currentCount + 1);
1539
+ usedProductIdCounts.set(selectedDiscount.product_id, currentCount + appliedUseCount);
1363
1540
  }
1364
1541
 
1365
1542
  // 🔥 生成唯一的 _id
@@ -1367,11 +1544,12 @@ class RulesModule extends _BaseModule.BaseModule {
1367
1544
 
1368
1545
  // 计算折扣后的价格(使用 getDiscountAmount,内部已处理 maxDeductionAmount)
1369
1546
  const discountedPrice = (0, _utils.getDiscountAmount)(selectedDiscount, product.origin_total, product.origin_total);
1370
- const bundleDiscountAmount = new _decimal.default(product.origin_total || 0).minus(discountedPrice).toNumber();
1547
+ const bundleDiscountAmountPerItem = new _decimal.default(product.origin_total || 0).minus(discountedPrice).toNumber();
1548
+ const bundleDiscountAmount = new _decimal.default(bundleDiscountAmountPerItem).mul(appliedUseCount).toNumber();
1371
1549
  debugger;
1372
1550
  const discountDetail = {
1373
1551
  amount: bundleDiscountAmount,
1374
- type: 'good_pass',
1552
+ type: selectedDiscount.tag || selectedDiscount.type,
1375
1553
  discount: {
1376
1554
  fixed_amount: product.origin_total,
1377
1555
  discount_calculation_mode: selectedDiscount?.metadata?.discount_calculation_mode,
@@ -1382,12 +1560,13 @@ class RulesModule extends _BaseModule.BaseModule {
1382
1560
  discount_product_id: selectedDiscount.product_id
1383
1561
  },
1384
1562
  metadata: {
1563
+ encoded: selectedDiscount.metadata?.encoded || selectedDiscount.encoded,
1385
1564
  // 🔥 使用拆分后的唯一 _id
1386
1565
  custom_product_bundle_map_id: uniqueId,
1387
1566
  discount_rule_uncheck_flag: selectedDiscount?.discount_rule_uncheck_flag,
1388
- num: 1
1567
+ num: appliedUseCount
1389
1568
  },
1390
- _num: 1,
1569
+ _num: appliedUseCount,
1391
1570
  config: selectedDiscount?.config
1392
1571
  };
1393
1572
 
@@ -1399,11 +1578,11 @@ class RulesModule extends _BaseModule.BaseModule {
1399
1578
  ...flatItem,
1400
1579
  // 🔥 使用唯一的 _id
1401
1580
  _id: uniqueId,
1402
- num: 1,
1403
- quantity: 1,
1581
+ num: appliedUseCount,
1582
+ quantity: appliedUseCount,
1404
1583
  price: discountedPrice,
1405
1584
  // 折扣后的价格
1406
- total: discountedPrice,
1585
+ total: new _decimal.default(discountedPrice).mul(appliedUseCount).toNumber(),
1407
1586
  discount_list: [discountDetail],
1408
1587
  processed: true,
1409
1588
  _discountId: selectedDiscount.id
@@ -1425,9 +1604,9 @@ class RulesModule extends _BaseModule.BaseModule {
1425
1604
  } else {
1426
1605
  // 折扣卡:不拆分数量,直接应用
1427
1606
  const selectedDiscount = selectedDiscountCard || applicableDiscounts[0];
1428
- usedDiscounts.set(selectedDiscount.id, true);
1607
+ markDiscountUsed(selectedDiscount);
1429
1608
  // 🔥 更新 product_id 使用计数(虽然此处主要是折扣卡,但保持一致性)
1430
- if ((selectedDiscount.tag || selectedDiscount.type) === 'good_pass') {
1609
+ if ((0, _entitlementPass.isFullCoveragePass)(selectedDiscount)) {
1431
1610
  const currentCount = usedProductIdCounts.get(selectedDiscount.product_id) || 0;
1432
1611
  usedProductIdCounts.set(selectedDiscount.product_id, currentCount + 1);
1433
1612
  }
@@ -1477,6 +1656,7 @@ class RulesModule extends _BaseModule.BaseModule {
1477
1656
  discount_product_id: selectedDiscount.product_id
1478
1657
  },
1479
1658
  metadata: {
1659
+ encoded: selectedDiscount.metadata?.encoded || selectedDiscount.encoded,
1480
1660
  // 🔥 使用唯一的 _id
1481
1661
  custom_product_bundle_map_id: uniqueId,
1482
1662
  discount_rule_uncheck_flag: selectedDiscount?.discount_rule_uncheck_flag,
@@ -1560,11 +1740,10 @@ class RulesModule extends _BaseModule.BaseModule {
1560
1740
  // 没有bundle,直接使用主商品处理结果
1561
1741
  result.push(...mainProductArr);
1562
1742
  } else {
1563
- // 🔥 有bundle,需要检查子商品是否应用了商品券
1743
+ // 🔥 有 bundle,需要检查子商品是否应用了全额抵扣卡
1564
1744
  // 1. 先收集所有bundle子商品的处理结果
1565
1745
  const bundleProcessingInfo = new Map();
1566
- let hasGoodPassApplied = false; // 标记是否有子商品应用了商品券
1567
-
1746
+ let hasFullCoveragePassApplied = false;
1568
1747
  if (product.bundle && Array.isArray(product.bundle)) {
1569
1748
  product.bundle.forEach((bundleItem, bundleIndex) => {
1570
1749
  const bundleItemId = `${product._id}_bundle_${bundleIndex}`;
@@ -1575,10 +1754,9 @@ class RulesModule extends _BaseModule.BaseModule {
1575
1754
  } else {
1576
1755
  // 处理过的bundle item
1577
1756
  bundleProcessingInfo.set(bundleIndex, processedBundleItems);
1578
- // 🔥 检查是否应用了商品券(good_pass)
1579
- const hasGoodPass = processedBundleItems.some(item => item.discount_list?.some(discount => discount.type === 'good_pass' || discount.tag === 'good_pass'));
1580
- if (hasGoodPass) {
1581
- hasGoodPassApplied = true;
1757
+ const hasFullCoveragePass = processedBundleItems.some(item => item.discount_list?.some(discount => (0, _entitlementPass.isFullCoveragePass)(discount)));
1758
+ if (hasFullCoveragePass) {
1759
+ hasFullCoveragePassApplied = true;
1582
1760
  }
1583
1761
  }
1584
1762
  });
@@ -1586,7 +1764,7 @@ class RulesModule extends _BaseModule.BaseModule {
1586
1764
 
1587
1765
  // 🔥 2. 如果有子商品应用了商品券,且主商品数量大于1,需要拆分主商品
1588
1766
  const mainProductQuantity = mainProductArr[0] ? this.hooks.getProduct(mainProductArr[0]).quantity : 1;
1589
- if (hasGoodPassApplied && mainProductArr.length === 1 && mainProductQuantity > 1) {
1767
+ if (hasFullCoveragePassApplied && mainProductArr.length === 1 && mainProductQuantity > 1) {
1590
1768
  const mainProduct = mainProductArr[0];
1591
1769
  const mainProductData = this.hooks.getProduct(mainProduct);
1592
1770
 
@@ -1890,27 +2068,39 @@ class RulesModule extends _BaseModule.BaseModule {
1890
2068
 
1891
2069
  // 获取此优惠券实际应用的商品详情
1892
2070
  const appliedProductDetails = appliedDiscountProducts.get(discount.id) || [];
2071
+ const committedAppliedProductDetails = (0, _entitlementPass.isEntitlementPass)(discount) ? mergeEntitlementAppliedProductDetails(discount.committedAppliedProductDetails || []) : [];
2072
+ const allAppliedProductDetails = (0, _entitlementPass.isEntitlementPass)(discount) ? mergeEntitlementAppliedProductDetails([...committedAppliedProductDetails, ...appliedProductDetails]) : appliedProductDetails;
1893
2073
 
1894
2074
  // 根据是否有适用商品决定isAvailable
1895
2075
  const isAvailable = applicableProducts.length > 0;
2076
+ const timeReasons = discountTimeReasons.get(discount.id) || [];
2077
+ const timeReason = timeReasons.length ? timeReasons.every(Boolean) ? timeReasons[0] : undefined : (0, _utils.getDiscountTimeUnavailableReason)(discount, (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss'));
2078
+ const reasonCode = isAvailable ? undefined : (0, _availability.getDiscountUsageBlockReason)(discount) || timeReason || discount.reasonCode || (discountHolderMismatch.has(discount.id) ? 'holder_not_matched' : 'product_not_applicable');
2079
+ const availabilityReason = {
2080
+ reasonCode,
2081
+ reason: reasonCode && reasonCode === discount.reasonCode ? discount.reason : undefined
2082
+ };
1896
2083
 
1897
2084
  // 如果此优惠券被明确设置为不选中,保持其状态,但正确设置isAvailable
1898
2085
  if (typeof discount.isSelected === 'boolean' && discount.isSelected === false && discount.isManualSelect) {
1899
2086
  return {
1900
2087
  ...discount,
2088
+ ...availabilityReason,
1901
2089
  isSelected: false,
1902
2090
  isAvailable: isAvailable,
1903
2091
  // 正确设置可用性
1904
2092
  applicableProductIds: applicableProducts,
1905
2093
  // 添加可抵扣的商品详情
1906
2094
  applicableProductDetails: applicableProductDetails,
1907
- // 添加实际抵扣的商品详情(对于未选中的优惠券,为空数组)
1908
- appliedProductDetails: []
2095
+ // 已提交的历史使用不可撤销;只取消本次新增分配。
2096
+ appliedProductDetails: committedAppliedProductDetails
1909
2097
  };
1910
2098
  }
1911
- if (usedDiscounts.get(discount.id)) {
2099
+ if (isDiscountUsed(discount)) {
1912
2100
  return {
1913
2101
  ...discount,
2102
+ reason: undefined,
2103
+ reasonCode: undefined,
1914
2104
  isSelected: true,
1915
2105
  isManualSelect: options?.scan ? false : discount.isManualSelect,
1916
2106
  // 标记为可用,因为它已被应用
@@ -1920,7 +2110,7 @@ class RulesModule extends _BaseModule.BaseModule {
1920
2110
  // 添加可抵扣的商品详情
1921
2111
  applicableProductDetails: applicableProductDetails,
1922
2112
  // 添加实际抵扣的商品详情
1923
- appliedProductDetails: appliedProductDetails
2113
+ appliedProductDetails: allAppliedProductDetails
1924
2114
  };
1925
2115
  }
1926
2116
  let isSelected = typeof discount.isSelected === 'boolean' ? discount.isSelected : undefined;
@@ -1928,11 +2118,12 @@ class RulesModule extends _BaseModule.BaseModule {
1928
2118
  // 如果是可用的 并且没有手动标记 则设置为选中
1929
2119
  if (isAvailable && appliedProductDetails.length && !discount.isManualSelect) {
1930
2120
  isSelected = true;
1931
- } else if (!appliedProductDetails.length) {
2121
+ } else if (!appliedProductDetails.length && !committedAppliedProductDetails.length) {
1932
2122
  isSelected = false;
1933
2123
  }
1934
2124
  return {
1935
2125
  ...discount,
2126
+ ...availabilityReason,
1936
2127
  // 如果有适用的商品,标记为可用
1937
2128
  isAvailable: isAvailable,
1938
2129
  isSelected,
@@ -1942,13 +2133,69 @@ class RulesModule extends _BaseModule.BaseModule {
1942
2133
  applicableProductIds: applicableProducts,
1943
2134
  // 添加可抵扣的商品详情
1944
2135
  applicableProductDetails: applicableProductDetails,
1945
- // 添加实际抵扣的商品详情(对于未使用的优惠券,为空数组)
1946
- appliedProductDetails: []
2136
+ // 编辑订单的历史使用继续保留,本次没有新增使用。
2137
+ appliedProductDetails: committedAppliedProductDetails
2138
+ };
2139
+ });
2140
+
2141
+ // 整单分配完成后统一记录卡余额;历史使用已包含在服务端余额中,只扣本次新增次数。
2142
+ const entitlementBalances = new Map();
2143
+ addModeDiscount.forEach(discount => {
2144
+ const quota = (0, _entitlementPass.resolveEntitlementQuota)(discount);
2145
+ if (!quota) return;
2146
+ entitlementBalances.set(String(discount.id), quota.type === 'unlimited' ? null : Math.max(quota.balance - (entitlementUsageCounts.get(discount.id) || 0), 0));
2147
+ });
2148
+ const getEntitlementBalance = detail => {
2149
+ if (!(0, _entitlementPass.isEntitlementPass)(detail)) return undefined;
2150
+ const resourceId = detail?.discount?.resource_id ?? detail?.resource_id;
2151
+ return entitlementBalances.get(String(resourceId));
2152
+ };
2153
+ const needsEntitlementBalance = detail => {
2154
+ const balance = getEntitlementBalance(detail);
2155
+ return balance !== undefined && detail?.metadata?.balance !== balance;
2156
+ };
2157
+ const withEntitlementBalance = detail => {
2158
+ if (!needsEntitlementBalance(detail)) return detail;
2159
+ return {
2160
+ ...detail,
2161
+ metadata: {
2162
+ ...(detail.metadata || {}),
2163
+ balance: getEntitlementBalance(detail)
2164
+ }
2165
+ };
2166
+ };
2167
+ const getProductDiscountDetails = originProduct => {
2168
+ const product = this.hooks.getProduct(originProduct);
2169
+ return [...(product.discount_list || []), ...(product.bundle || []).flatMap(bundle => bundle.discount_list || [])];
2170
+ };
2171
+ const productsWithEntitlementBalances = entitlementBalances.size ? processedProductList.map(product => {
2172
+ if (!getProductDiscountDetails(product).some(needsEntitlementBalance)) {
2173
+ return product;
2174
+ }
2175
+ // 历史商品及套餐可能仍引用输入快照;仅复制有变化的行,并直接更新 metadata。
2176
+ // 不再次调用价格换算钩子,避免只补余额时改变商品价格。
2177
+ const nextProduct = (0, _lodashEs.cloneDeep)(product);
2178
+ getProductDiscountDetails(nextProduct).forEach(detail => {
2179
+ if (!needsEntitlementBalance(detail)) return;
2180
+ detail.metadata = withEntitlementBalance(detail).metadata;
2181
+ });
2182
+ return nextProduct;
2183
+ }) : processedProductList;
2184
+ const discountsWithEntitlementBalances = [...editModeDiscount, ...updatedDiscountList].map(discount => {
2185
+ if (!(0, _entitlementPass.isEntitlementPass)(discount) || !entitlementBalances.has(String(discount.id))) {
2186
+ return discount;
2187
+ }
2188
+ return {
2189
+ ...discount,
2190
+ appliedProductDetails: (discount.appliedProductDetails || []).map(withEntitlementBalance),
2191
+ ...(discount.committedAppliedProductDetails ? {
2192
+ committedAppliedProductDetails: discount.committedAppliedProductDetails.map(withEntitlementBalance)
2193
+ } : {})
1947
2194
  };
1948
2195
  });
1949
2196
  return {
1950
- productList: processedProductList,
1951
- discountList: [...editModeDiscount, ...updatedDiscountList]
2197
+ productList: productsWithEntitlementBalances,
2198
+ discountList: discountsWithEntitlementBalances
1952
2199
  };
1953
2200
  }
1954
2201