@pisell/pisellos 2.3.124 → 2.3.125

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