@pisell/pisellos 2.3.127 → 2.3.128

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