@pisell/pisellos 0.10.78 → 0.10.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,46 +1 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- Object.defineProperty(exports, "BUY_X_GET_Y_FREE_STRATEGY", {
7
- enumerable: true,
8
- get: function () {
9
- return _examples.BUY_X_GET_Y_FREE_STRATEGY;
10
- }
11
- });
12
- Object.defineProperty(exports, "ITEM_REWARD_STRATEGY", {
13
- enumerable: true,
14
- get: function () {
15
- return _examples.ITEM_REWARD_STRATEGY;
16
- }
17
- });
18
- Object.defineProperty(exports, "PromotionAdapter", {
19
- enumerable: true,
20
- get: function () {
21
- return _adapter.PromotionAdapter;
22
- }
23
- });
24
- Object.defineProperty(exports, "PromotionEvaluator", {
25
- enumerable: true,
26
- get: function () {
27
- return _evaluator.PromotionEvaluator;
28
- }
29
- });
30
- Object.defineProperty(exports, "X_ITEMS_FOR_Y_PRICE_STRATEGY", {
31
- enumerable: true,
32
- get: function () {
33
- return _examples.X_ITEMS_FOR_Y_PRICE_STRATEGY;
34
- }
35
- });
36
- Object.defineProperty(exports, "default", {
37
- enumerable: true,
38
- get: function () {
39
- return _adapter.default;
40
- }
41
- });
42
- var _evaluator = require("./evaluator");
43
- var _adapter = _interopRequireWildcard(require("./adapter"));
44
- var _examples = require("./examples");
45
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
46
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
1
+ "use strict";
@@ -158,6 +158,10 @@ export interface Discount {
158
158
  discount_calculation_mode: 'item_level' | 'order_level';
159
159
  };
160
160
  isManualSelect?: boolean;
161
+ /** X 件 Y 元互斥选择的手动意图;isSelected 只表示本次实际应用结果。 */
162
+ promotionSelection?: 'card' | 'promotion';
163
+ /** 记录手动操作影响的促销组,避免卡失效后普通重算丢失取消意图。 */
164
+ promotionSelectionStrategyIds?: string[];
161
165
  isDisabled?: boolean;
162
166
  isSelected?: boolean;
163
167
  isAvailable?: boolean;
@@ -683,6 +683,7 @@ class OrderModule extends _BaseModule.BaseModule {
683
683
  }
684
684
  if (discountList) {
685
685
  const currentDiscountList = this.store.discount?.getDiscountList() || [];
686
+ const currentPromotionSelections = new Map(currentDiscountList.filter(discount => !discount.isEditMode && discount.promotionSelection).map(discount => [String(discount.id), discount]));
686
687
  const currentCommittedDiscounts = currentDiscountList.filter(discount => discount?.isEditMode || discount?.committedAppliedProductDetails?.length);
687
688
  const currentScanDiscounts = currentDiscountList.filter(discount => discount?.isScan);
688
689
  const currentScanDiscountById = new Map(currentScanDiscounts.flatMap(discount => {
@@ -720,6 +721,16 @@ class OrderModule extends _BaseModule.BaseModule {
720
721
  isManualSelect: currentScanDiscount.isManualSelect ?? nextDiscount.isManualSelect
721
722
  };
722
723
  }
724
+ const currentSelection = currentPromotionSelections.get(String(discount.id));
725
+ if (currentSelection) {
726
+ nextDiscount = {
727
+ ...nextDiscount,
728
+ promotionSelection: currentSelection.promotionSelection,
729
+ promotionSelectionStrategyIds: currentSelection.promotionSelectionStrategyIds,
730
+ isManualSelect: currentSelection.isManualSelect,
731
+ isSelected: currentSelection.isSelected
732
+ };
733
+ }
723
734
  return [nextDiscount];
724
735
  });
725
736
  const retainedCommittedDiscounts = currentCommittedDiscounts.filter(discount => {
@@ -1,6 +1,6 @@
1
1
  import { Module, PisellCore, ModuleOptions } from '../../types';
2
2
  import { BaseModule } from '../BaseModule';
3
- import { Rules, RulesModuleAPI, DiscountResult, RulesFormSubject, RulesCalcDiscountOptions, UnavailableReason } from './types';
3
+ import { Rules, RulesModuleAPI, DiscountResult, RulesFormSubject, RulesCalcDiscountOptions, RulesCalcDiscountParams, UnavailableReason } from './types';
4
4
  import { Discount } from '../Discount/types';
5
5
  import { WindowPlugin } from '../../plugins';
6
6
  export declare class RulesModule extends BaseModule implements Module, RulesModuleAPI {
@@ -46,15 +46,8 @@ export declare class RulesModule extends BaseModule implements Module, RulesModu
46
46
  resolveDiscountListForManualOverride(discountList: Discount[]): Discount[];
47
47
  private isItemRewardProductDiscount;
48
48
  private getUnavailableReason;
49
- calcDiscount({ discountList, productList, holders, isFormSubject, orderTotalAmount }: {
50
- discountList: Discount[];
51
- productList: any[];
52
- holders: {
53
- form_record_id: number;
54
- }[];
55
- isFormSubject: RulesFormSubject;
56
- orderTotalAmount: number;
57
- }, options?: RulesCalcDiscountOptions): DiscountResult;
49
+ calcDiscount(params: RulesCalcDiscountParams, options?: RulesCalcDiscountOptions): DiscountResult;
50
+ private calcDiscountCore;
58
51
  /**
59
52
  * 检查优惠是否符合 PackageSubItemUsageRules 配置
60
53
  * @param discount 优惠券
@@ -14,6 +14,7 @@ var _lodashEs = require("lodash-es");
14
14
  var _dayjs = _interopRequireDefault(require("dayjs"));
15
15
  var _entitlementPass = require("../Discount/entitlementPass");
16
16
  var _availability = require("../Discount/availability");
17
+ var _promotionSelection = require("./promotionSelection");
17
18
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18
19
  class RulesModule extends _BaseModule.BaseModule {
19
20
  defaultName = 'rules';
@@ -150,6 +151,12 @@ class RulesModule extends _BaseModule.BaseModule {
150
151
  }
151
152
  });
152
153
 
154
+ // 卡可用但互斥比较选择了促销时,扫码仍应加入可选卡列表,不能被标为商品不适用。
155
+ if (!hasApplicableDiscount) {
156
+ const promotionProductIds = new Set(result.productList.filter(product => (0, _promotionSelection.getExclusivePromotion)(product)?.inPromotion === true).map(product => this.hooks.getProduct(product).id));
157
+ hasApplicableDiscount = result.discountList.some(discount => newDiscountIds.includes(discount.id) && (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.isAvailable && discount.applicableProductIds?.some(id => promotionProductIds.has(id)));
158
+ }
159
+
153
160
  // 如果券不可用,判断不可用原因
154
161
  let unavailableReason;
155
162
  if (!hasApplicableDiscount) {
@@ -217,13 +224,28 @@ class RulesModule extends _BaseModule.BaseModule {
217
224
  }
218
225
  return _types.UnavailableReason.Unknown;
219
226
  }
220
- calcDiscount({
227
+ calcDiscount(params, options) {
228
+ return (0, _promotionSelection.calculatePromotionSelection)(params, options, this.hooks, (input, calculationOptions, policy) => this.calcDiscountCore(input, calculationOptions, policy));
229
+ }
230
+ calcDiscountCore({
221
231
  discountList,
222
232
  productList,
223
233
  holders,
224
234
  isFormSubject,
225
235
  orderTotalAmount
226
- }, options) {
236
+ }, options, promotionPolicy) {
237
+ const cancelledPromotionCards = discountList.filter(discount => !discount.isEditMode && (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.promotionSelection === 'promotion');
238
+ const cancelledPromotionProductIds = new Set(cancelledPromotionCards.flatMap(discount => discount.applicableProductIds || []));
239
+ const cancelledPromotionStrategyIds = new Set(cancelledPromotionCards.flatMap(discount => discount.promotionSelectionStrategyIds || []));
240
+ const isCardBlockedByPromotion = (flatItem, discount) => {
241
+ if (flatItem.type !== 'main' || !(0, _promotionSelection.isPromotionDiscountCard)(discount)) return false;
242
+ const originProduct = flatItem.originProduct;
243
+ if (originProduct?.order_detail_id || originProduct?.orderDetailId || originProduct?.booking_id || originProduct?.metadata?.booking_id) return false;
244
+ // 取消卡后即使数量暂未凑足促销,也不能自动改用另一张卡;重新手选/最佳组合会清除该意图。
245
+ if (cancelledPromotionProductIds.has(flatItem.product.id) || cancelledPromotionStrategyIds.has(String(originProduct?.metadata?._promotion?.strategyId))) return true;
246
+ const promotion = (0, _promotionSelection.getExclusivePromotion)(originProduct);
247
+ return Boolean(promotion && promotionPolicy?.blockedStrategyIds.has(String(promotion.strategyId)));
248
+ };
227
249
  const preferredEntitlementPassIds = new Set((options?.preferredEntitlementPassIds || []).map(String));
228
250
  const resolveIsFormSubject = product => typeof isFormSubject === 'function' ? Boolean(isFormSubject(product)) : Boolean(isFormSubject);
229
251
 
@@ -729,6 +751,7 @@ class RulesModule extends _BaseModule.BaseModule {
729
751
  const checkItemApplicableForDiscount = (flatItem, discount) => {
730
752
  if (this.discountScope && !this.discountScope(flatItem.originProduct, discount)) return false;
731
753
  if (discount.config?.isAvailable === false) return false;
754
+ if (isCardBlockedByPromotion(flatItem, discount)) return false;
732
755
  let product;
733
756
  if (flatItem.type === 'main') {
734
757
  product = flatItem.product;
@@ -789,6 +812,11 @@ class RulesModule extends _BaseModule.BaseModule {
789
812
  return isLimitedProduct && isBundleAvailable;
790
813
  };
791
814
 
815
+ // 分摊占位与实际应用共用选择优先级,数量跌出促销门槛时也保留手选意图。
816
+ const findExplicitlySelectedDiscount = applicableDiscounts => (options?.isSelected === true && options.discountId !== undefined ? applicableDiscounts.find(discount => String(discount.id) === String(options.discountId) && ((0, _entitlementPass.isFullCoveragePass)(discount) || (0, _promotionSelection.isPromotionDiscountCard)(discount))) : undefined) || (options?.preserveEntitlementSelection !== false ? applicableDiscounts.find(discount => discount.promotionSelection === 'card') : undefined);
817
+ const getAppliedWalletDiscountIds = product => new Set((product.discount_list || []).filter(item => ['entitlement_pass', 'discount_card', 'product_discount_card'].includes(item?.tag || item?.type)).map(item => item?.discount?.resource_id ?? item?.resource_id ?? item?.id).filter(id => id !== undefined && id !== null).map(String));
818
+ const findAppliedDiscountCard = (applicableDiscounts, appliedIds) => options?.scan || options?.preserveEntitlementSelection === false ? undefined : applicableDiscounts.find(discount => discount.isSelected === true && (0, _promotionSelection.isPromotionDiscountCard)(discount) && appliedIds.has(String(discount.id)));
819
+
792
820
  // 收集所有被勾选的 order_level 折扣卡及其适用商品
793
821
  const selectedOrderLevelDiscounts = sortedDiscountList.filter(discount => {
794
822
  return (0, _utils.isOrderLevelFixedAmountDiscount)(discount) && discount.isSelected !== false;
@@ -816,6 +844,18 @@ class RulesModule extends _BaseModule.BaseModule {
816
844
  // Map<flatItemId, discountId> - 记录被占用的商品及其对应的折扣卡
817
845
  const occupiedItems = new Map();
818
846
 
847
+ // 手选/已应用的卡先占位(包括全品类卡),其他候选卡不能抢走其分摊商品。
848
+ sortedFlattenedList.forEach(flatItem => {
849
+ const product = flatItem.type === 'main' ? flatItem.product : flatItem.bundleItem;
850
+ const holderProduct = flatItem.type === 'main' ? flatItem.product : flatItem.parentProduct;
851
+ const applicableCards = sortedDiscountList.filter(discount => (0, _promotionSelection.isPromotionDiscountCard)(discount) && discount.config?.isAvailable && checkItemApplicableForDiscount(flatItem, discount) && this.checkHolderMatch(discount, {
852
+ isNeedHolder: resolveIsFormSubject(holderProduct) && !holderProduct?.isNormalProduct,
853
+ holder_id: holderProduct?.holder_id || product.holder_id
854
+ }, flatItem.originProduct, holders));
855
+ const preferredCard = findExplicitlySelectedDiscount(applicableCards) || findAppliedDiscountCard(applicableCards, getAppliedWalletDiscountIds(product)) || applicableCards.find(discount => discount.isScan && discount.isSelected);
856
+ if (preferredCard) occupiedItems.set(flatItem._id, preferredCard.id);
857
+ });
858
+
819
859
  // 按排序顺序遍历折扣卡,判断哪些是专属折扣卡
820
860
  selectedOrderLevelDiscounts.forEach(discount => {
821
861
  const limitedData = discount.limited_relation_product_data;
@@ -956,6 +996,9 @@ class RulesModule extends _BaseModule.BaseModule {
956
996
  if (isAvailableProduct && !isItemRewardProductDiscount && isLimitedProduct && timeLimit && isBundleAvailable && discount.config?.isAvailable && (!(0, _entitlementPass.isEntitlementPass)(discount) || (0, _entitlementPass.getRemainingEntitlementUses)(discount, 0, 1) > 0)) {
957
997
  // 记录此优惠券适用的商品
958
998
  discountApplicability.get(discount.id)?.push(product.id);
999
+ if (flatItem.type === 'main' && (0, _promotionSelection.isPromotionDiscountCard)(discount)) {
1000
+ promotionPolicy?.onApplicableCard?.(originProduct, discount);
1001
+ }
959
1002
 
960
1003
  // 记录可抵扣的商品详情
961
1004
  const applicableProducts = discountApplicableProducts.get(discount.id) || [];
@@ -1101,6 +1144,7 @@ class RulesModule extends _BaseModule.BaseModule {
1101
1144
  const applicableDiscounts = sortedDiscountList.filter(discount => {
1102
1145
  if (this.discountScope && !this.discountScope(originProduct, discount)) return false;
1103
1146
  if (this.isItemRewardProductDiscount(product)) return false;
1147
+ if (isCardBlockedByPromotion(flatItem, discount)) return false;
1104
1148
  // 🔥 检查策略可用性(针对全额抵扣卡和折扣卡)
1105
1149
  const discountType = discount.tag || discount.type;
1106
1150
  const currentOriginUid = getOriginProductUid(originProduct);
@@ -1180,20 +1224,14 @@ class RulesModule extends _BaseModule.BaseModule {
1180
1224
 
1181
1225
  // 识别用户本次显式选择的卡券,供次卡和折扣卡各自的优先级使用。
1182
1226
  // 目标仍必须在当前商品的 applicableDiscounts 中,因此不会绕过 Holder、时间或商品范围校验。
1183
- const explicitlySelectedDiscount = options?.isSelected === true && options.discountId !== undefined ? applicableDiscounts.find(discount => {
1184
- const discountType = discount.tag || discount.type;
1185
- return String(discount.id) === String(options.discountId) && ['entitlement_pass', 'good_pass', 'discount_card', 'product_discount_card'].includes(discountType ?? '');
1186
- }) : undefined;
1227
+ const explicitlySelectedDiscount = findExplicitlySelectedDiscount(applicableDiscounts);
1187
1228
  // 折扣卡会复用于整条商品行;商品券必须继续按单张拆分,不能复用该分支。
1188
1229
  const explicitlySelectedDiscountCard = explicitlySelectedDiscount && !(0, _entitlementPass.isFullCoveragePass)(explicitlySelectedDiscount) ? explicitlySelectedDiscount : undefined;
1189
1230
 
1190
1231
  // 商品数量等变化会触发无 discountId 的重算。只要当前行已应用的卡仍在
1191
1232
  // applicableDiscounts 中,就应保留该行选择,避免被自动排序中力度更大的卡替换。
1192
- const appliedWalletDiscountIds = new Set((product.discount_list || []).filter(item => ['entitlement_pass', 'discount_card', 'product_discount_card'].includes(item?.tag || item?.type)).map(item => item?.discount?.resource_id ?? item?.resource_id ?? item?.id).filter(id => id !== undefined && id !== null).map(String));
1193
- const appliedDiscountCard = options?.scan ? undefined : applicableDiscounts.find(discount => {
1194
- const discountType = discount.tag || discount.type;
1195
- return discount.isSelected === true && ['discount_card', 'product_discount_card'].includes(discountType ?? '') && appliedWalletDiscountIds.has(String(discount.id));
1196
- });
1233
+ const appliedWalletDiscountIds = getAppliedWalletDiscountIds(product);
1234
+ const appliedDiscountCard = findAppliedDiscountCard(applicableDiscounts, appliedWalletDiscountIds);
1197
1235
  const appliedEntitlementPass = options?.scan || options?.preserveEntitlementSelection === false ? undefined : applicableDiscounts.find(discount => (0, _entitlementPass.isEntitlementPass)(discount) && discount.isSelected === true && appliedWalletDiscountIds.has(String(discount.id)));
1198
1236
 
1199
1237
  // 次卡内部按本次手选/扫码、当前行已应用、默认排序选择。
@@ -1428,14 +1466,15 @@ class RulesModule extends _BaseModule.BaseModule {
1428
1466
  let discountedOptions = product.options;
1429
1467
  let optionDiscountAmount = 0;
1430
1468
  let reapplyDiscountPercent;
1431
- if (isOrderLevel && productAllocation) {
1432
- // order_level:使用预计算的分摊金额
1433
- amount = productAllocation.discountAmount;
1434
- productDiscountDifference = productAllocation.difference;
1469
+ const bookingDiscountPercent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1470
+ if (isOrderLevel && (productAllocation || bookingDiscountPercent === undefined)) {
1471
+ // 整单卡只能使用分摊结果,缺少分摊时不能回退为每件扣减整单额度。
1472
+ amount = productAllocation?.discountAmount ?? 0;
1473
+ productDiscountDifference = productAllocation?.difference;
1435
1474
  mainProductSellingPrice = Math.max(new _decimal.default(product.price).minus(amount).toNumber(), 0);
1436
- } else if (resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount) !== undefined) {
1475
+ } else if (bookingDiscountPercent !== undefined) {
1437
1476
  // Change time 重套编辑态折扣卡时,历史 par_value 不是运行时折扣口径,优先使用后端快照里的 percent。
1438
- const percent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1477
+ const percent = bookingDiscountPercent;
1439
1478
  reapplyDiscountPercent = new _decimal.default(percent).toFixed(2);
1440
1479
  mainProductSellingPrice = new _decimal.default(product.price || 0).mul(new _decimal.default(100).minus(percent)).div(100).toDecimalPlaces(2).toNumber();
1441
1480
  amount = new _decimal.default(product.price).minus(mainProductSellingPrice).toNumber();
@@ -1629,15 +1668,16 @@ class RulesModule extends _BaseModule.BaseModule {
1629
1668
  let fixedAmountPerItem;
1630
1669
  let productDiscountDifference;
1631
1670
  let reapplyDiscountPercent;
1632
- if (isOrderLevel && productAllocation) {
1671
+ const bookingDiscountPercent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1672
+ if (isOrderLevel && (productAllocation || bookingDiscountPercent === undefined)) {
1633
1673
  // order_level:使用预计算的单价折扣金额(已经是单价,无需再除以数量)
1634
- fixedAmountPerItem = productAllocation.discountAmount;
1635
- productDiscountDifference = productAllocation.difference;
1674
+ fixedAmountPerItem = productAllocation?.discountAmount ?? 0;
1675
+ productDiscountDifference = productAllocation?.difference;
1636
1676
  targetProductTotal = Math.max(new _decimal.default(productOriginTotal).minus(fixedAmountPerItem).toNumber(), 0);
1637
- } else if (resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount) !== undefined) {
1677
+ } else if (bookingDiscountPercent !== undefined) {
1638
1678
  // hydrate 后 par_value 可能是余额/原值(例如 3500),百分比口径以
1639
1679
  // 后端折扣快照 discount.percent 为准,与主商品重套逻辑保持一致。
1640
- const percent = resolveReapplyBookingDiscountPercent(originProduct, selectedDiscount);
1680
+ const percent = bookingDiscountPercent;
1641
1681
  reapplyDiscountPercent = new _decimal.default(percent).toFixed(2);
1642
1682
  targetProductTotal = new _decimal.default(productOriginTotal).mul(new _decimal.default(100).minus(percent)).div(100).toDecimalPlaces(2).toNumber();
1643
1683
  fixedAmountPerItem = new _decimal.default(productOriginTotal).minus(targetProductTotal).toNumber();
@@ -0,0 +1,14 @@
1
+ import type { Discount } from '../Discount/types';
2
+ import type { DiscountResult, RulesCalcDiscountOptions, RulesCalcDiscountParams, RulesParamsHooks } from './types';
3
+ export declare function isPromotionDiscountCard(discount: any): boolean;
4
+ /** 只处理当前购物车的 X 件 Y 元,历史成交和其他促销继续使用原有规则。 */
5
+ export declare function getExclusivePromotion(product: any): any | undefined;
6
+ export interface PromotionSelectionPolicy {
7
+ blockedStrategyIds: ReadonlySet<string>;
8
+ onApplicableCard?: (product: any, discount: Discount) => void;
9
+ }
10
+ /**
11
+ * 以完整策略参与组为单位比较两套实际报价。每次试算都从同一快照开始,
12
+ * 由原引擎重新做卡券校验和整单卡分摊,不能从叠加结果里事后减掉某条优惠。
13
+ */
14
+ export declare function calculatePromotionSelection(params: RulesCalcDiscountParams, options: RulesCalcDiscountOptions | undefined, hooks: RulesParamsHooks, calculate: (params: RulesCalcDiscountParams, options?: RulesCalcDiscountOptions, policy?: PromotionSelectionPolicy) => DiscountResult): DiscountResult;
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.calculatePromotionSelection = calculatePromotionSelection;
7
+ exports.getExclusivePromotion = getExclusivePromotion;
8
+ exports.isPromotionDiscountCard = isPromotionDiscountCard;
9
+ var _decimal = _interopRequireDefault(require("decimal.js"));
10
+ var _lodashEs = require("lodash-es");
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+ function isPromotionDiscountCard(discount) {
13
+ return ['discount_card', 'product_discount_card'].includes(discount?.tag || discount?.type);
14
+ }
15
+
16
+ /** 只处理当前购物车的 X 件 Y 元,历史成交和其他促销继续使用原有规则。 */
17
+ function getExclusivePromotion(product) {
18
+ const promotion = product?.metadata?._promotion;
19
+ if (product?.order_detail_id || product?.orderDetailId || product?.booking_id || product?.metadata?.booking_id || promotion?.actionType !== 'X_ITEMS_FOR_Y_PRICE' || !promotion.strategyId || !(promotion.inPromotion === true || promotion.excludedByDiscountCard === true)) return undefined;
20
+ return promotion;
21
+ }
22
+ /**
23
+ * 以完整策略参与组为单位比较两套实际报价。每次试算都从同一快照开始,
24
+ * 由原引擎重新做卡券校验和整单卡分摊,不能从叠加结果里事后减掉某条优惠。
25
+ */
26
+ function calculatePromotionSelection(params, options, hooks, calculate) {
27
+ const discountList = params.discountList.map(discount => {
28
+ if (discount.isEditMode || !isPromotionDiscountCard(discount)) return discount;
29
+ if (options?.preserveEntitlementSelection === false) {
30
+ return {
31
+ ...discount,
32
+ promotionSelection: undefined,
33
+ promotionSelectionStrategyIds: undefined,
34
+ isManualSelect: false
35
+ };
36
+ }
37
+ if (options?.discountId !== undefined && String(discount.id) === String(options.discountId) && typeof options.isSelected === 'boolean') {
38
+ return {
39
+ ...discount,
40
+ promotionSelection: options.isSelected ? 'card' : 'promotion',
41
+ isSelected: options.isSelected,
42
+ isManualSelect: !options.isSelected
43
+ };
44
+ }
45
+ return {
46
+ ...discount
47
+ };
48
+ });
49
+ // 未凑足促销时也要清理重叠商品上的旧手选,避免再次凑组后切回之前的卡。
50
+ const changedCard = options?.discountId !== undefined && typeof options.isSelected === 'boolean' ? discountList.find(discount => !discount.isEditMode && isPromotionDiscountCard(discount) && String(discount.id) === String(options.discountId)) : undefined;
51
+ if (changedCard) {
52
+ const changedProductIds = new Set(changedCard.applicableProductIds || []);
53
+ for (const product of params.productList) {
54
+ const detail = hooks.getProduct(product);
55
+ if (detail.discount_list?.some(discount => isPromotionDiscountCard(discount) && String(discount.discount?.resource_id ?? discount.id) === String(changedCard.id))) changedProductIds.add(detail.id);
56
+ }
57
+ for (const discount of discountList) {
58
+ if (discount.isEditMode || !isPromotionDiscountCard(discount) || String(discount.id) === String(changedCard.id) || !discount.promotionSelection) continue;
59
+ if (discount.applicableProductIds?.some(id => changedProductIds.has(id))) {
60
+ discount.promotionSelection = undefined;
61
+ discount.promotionSelectionStrategyIds = undefined;
62
+ }
63
+ }
64
+ }
65
+ const strategyIds = new Set();
66
+ for (const product of params.productList) {
67
+ const promotion = getExclusivePromotion(product);
68
+ if (promotion && hooks.getProduct(product).isManualDiscount !== true) {
69
+ strategyIds.add(String(promotion.strategyId));
70
+ }
71
+ }
72
+ if (!strategyIds.size) return calculate({
73
+ ...params,
74
+ discountList
75
+ }, options);
76
+ const applicableGroups = new Map();
77
+ const quote = (blockedStrategyIds, collectApplicable = false) => {
78
+ const productList = (0, _lodashEs.cloneDeep)(params.productList).map(product => {
79
+ const promotion = getExclusivePromotion(product);
80
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) return product;
81
+ const detail = hooks.getProduct(product);
82
+ if (detail.isManualDiscount === true) return product;
83
+ const keepPromotion = blockedStrategyIds.has(String(promotion.strategyId));
84
+ const originalPrice = Number(promotion.originalPrice ?? detail.price);
85
+ const finalPrice = Number(promotion.finalPrice);
86
+ const promotionDiscount = (detail.discount_list || []).find(discount => discount.type === 'promotion');
87
+ const retainedDiscounts = (detail.discount_list || []).filter(discount => discount.type !== 'promotion' && (!isPromotionDiscountCard(discount) || !keepPromotion && discountList.some(card => !card.isManualSelect && String(card.id) === String(discount.discount?.resource_id ?? discount.id))));
88
+ if (keepPromotion && originalPrice !== finalPrice) {
89
+ retainedDiscounts.push(promotionDiscount || {
90
+ type: 'promotion',
91
+ amount: new _decimal.default(originalPrice).minus(finalPrice).toFixed(2),
92
+ discount: {
93
+ original_amount: String(originalPrice),
94
+ fixed_amount: new _decimal.default(originalPrice).minus(finalPrice).toFixed(2),
95
+ title: promotion.strategyMetadata?.name || '',
96
+ resource_id: ''
97
+ }
98
+ });
99
+ }
100
+ product.metadata._promotion = {
101
+ ...promotion,
102
+ inPromotion: keepPromotion,
103
+ excludedByDiscountCard: !keepPromotion
104
+ };
105
+ return hooks.setProduct(product, {
106
+ discount_list: retainedDiscounts,
107
+ main_product_selling_price: keepPromotion ? finalPrice : originalPrice
108
+ });
109
+ });
110
+ return calculate({
111
+ ...params,
112
+ productList,
113
+ discountList: (0, _lodashEs.cloneDeep)(discountList).map(discount => !discount.isEditMode && isPromotionDiscountCard(discount) && !discount.isManualSelect
114
+ // 自动落选不等于手动禁用;整单卡仍须进入下一轮候选分摊。
115
+ ? {
116
+ ...discount,
117
+ isSelected: discount.isSelected === false ? undefined : discount.isSelected
118
+ } : discount)
119
+ }, options, {
120
+ blockedStrategyIds,
121
+ onApplicableCard: collectApplicable ? (product, discount) => {
122
+ const promotion = getExclusivePromotion(product);
123
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) return;
124
+ const id = String(discount.id);
125
+ const groups = applicableGroups.get(id) || new Set();
126
+ groups.add(String(promotion.strategyId));
127
+ applicableGroups.set(id, groups);
128
+ } : undefined
129
+ });
130
+ };
131
+
132
+ // 起点保留所有促销;未发生冲突的商品和卡券仍由原引擎正常计算。
133
+ let blockedStrategyIds = new Set(strategyIds);
134
+ let result = quote(blockedStrategyIds, true);
135
+ // 取消已应用的卡时,即使它刚好失效,也应恢复它原来替代的促销组。
136
+ for (const product of params.productList) {
137
+ const promotion = getExclusivePromotion(product);
138
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) continue;
139
+ for (const detail of hooks.getProduct(product).discount_list || []) {
140
+ if (!isPromotionDiscountCard(detail)) continue;
141
+ const id = String(detail.discount?.resource_id ?? detail.id);
142
+ if (!discountList.some(discount => String(discount.id) === id && (discount.isManualSelect || discount.promotionSelection === 'promotion'))) continue;
143
+ const groups = applicableGroups.get(id) || new Set();
144
+ groups.add(String(promotion.strategyId));
145
+ applicableGroups.set(id, groups);
146
+ }
147
+ }
148
+ // 同一参与组以最近一次手动操作为准,不能让先前选过的另一张卡重新压过取消操作。
149
+ const changedGroups = options?.discountId !== undefined && typeof options.isSelected === 'boolean' ? applicableGroups.get(String(options.discountId)) : undefined;
150
+ if (changedGroups?.size) {
151
+ for (const discount of discountList) {
152
+ if (!discount.isEditMode && String(discount.id) === String(options?.discountId)) {
153
+ discount.promotionSelectionStrategyIds = [...changedGroups];
154
+ continue;
155
+ }
156
+ if (discount.isEditMode || !isPromotionDiscountCard(discount) || String(discount.id) === String(options?.discountId) || !discount.promotionSelection) continue;
157
+ const groups = new Set([...(applicableGroups.get(String(discount.id)) || []), ...(discount.promotionSelectionStrategyIds || [])]);
158
+ if ([...groups].some(group => changedGroups.has(group))) {
159
+ discount.promotionSelection = undefined;
160
+ discount.promotionSelectionStrategyIds = undefined;
161
+ }
162
+ }
163
+ }
164
+ const manualPromotionGroups = new Set();
165
+ const manualCardGroups = new Set();
166
+ for (const discount of discountList) {
167
+ if (!isPromotionDiscountCard(discount) || discount.isEditMode) continue;
168
+ const groups = applicableGroups.get(String(discount.id)) || [];
169
+ if (discount.isManualSelect || discount.promotionSelection === 'promotion') {
170
+ for (const group of groups) manualPromotionGroups.add(group);
171
+ for (const group of discount.promotionSelectionStrategyIds || []) {
172
+ if (strategyIds.has(group)) manualPromotionGroups.add(group);
173
+ }
174
+ } else if (discount.promotionSelection === 'card') {
175
+ for (const group of groups) manualCardGroups.add(group);
176
+ }
177
+ }
178
+ const total = candidate => candidate.productList.reduce((sum, product) => {
179
+ const detail = hooks.getProduct(product);
180
+ const discounts = [...detail.discount_list, ...(detail.bundle || []).flatMap(bundle => (bundle.discount_list || []).filter(discount => !discount.id))];
181
+ // 与订单小计一致:整单卡未计入单价的尾差按行扣一次,不能漏算或再乘数量。
182
+ const difference = discounts.reduce((amount, discount) => amount.plus(discount.metadata?.product_discount_difference || 0), new _decimal.default(0));
183
+ return sum.plus(detail.total).minus(difference);
184
+ }, new _decimal.default(0));
185
+ const hasAppliedCard = (candidate, strategyId) => candidate.productList.some(product => String(getExclusivePromotion(product)?.strategyId) === strategyId && hooks.getProduct(product).discount_list.some(isPromotionDiscountCard));
186
+ // 手动选择先落定,随后只对未手选的参与组比较优惠。
187
+ for (const strategyId of manualCardGroups) {
188
+ const candidateBlocked = new Set(blockedStrategyIds);
189
+ candidateBlocked.delete(strategyId);
190
+ const candidate = quote(candidateBlocked);
191
+ if (hasAppliedCard(candidate, strategyId)) {
192
+ blockedStrategyIds = candidateBlocked;
193
+ result = candidate;
194
+ }
195
+ }
196
+ const automaticGroups = new Set([...strategyIds].filter(id => !manualCardGroups.has(id) && !manualPromotionGroups.has(id) && discountList.some(discount => !discount.isEditMode && !discount.isManualSelect && applicableGroups.get(String(discount.id))?.has(id))));
197
+ // 多组共用整单卡时先选节省最多的一组,再重新试算其余组,避免依赖购物车行顺序。
198
+ while (automaticGroups.size) {
199
+ let bestGroup;
200
+ let bestResult = result;
201
+ let bestTotal = total(result);
202
+ for (const strategyId of automaticGroups) {
203
+ const candidateBlocked = new Set(blockedStrategyIds);
204
+ candidateBlocked.delete(strategyId);
205
+ const candidate = quote(candidateBlocked);
206
+ const candidateTotal = total(candidate);
207
+ // 没有实际可用卡时保持促销;同价继续保留促销。
208
+ if (hasAppliedCard(candidate, strategyId) && candidateTotal.lessThan(bestTotal)) {
209
+ bestGroup = strategyId;
210
+ bestResult = candidate;
211
+ bestTotal = candidateTotal;
212
+ }
213
+ }
214
+ if (bestGroup === undefined) break;
215
+ blockedStrategyIds.delete(bestGroup);
216
+ automaticGroups.delete(bestGroup);
217
+ result = bestResult;
218
+ }
219
+ // 即使最终保留首次报价,也要回写上面清除的旧手动意图。
220
+ result.discountList = result.discountList.map(discount => {
221
+ if (discount.isEditMode || !isPromotionDiscountCard(discount)) return discount;
222
+ const selection = discountList.find(card => !card.isEditMode && String(card.id) === String(discount.id));
223
+ return {
224
+ ...discount,
225
+ promotionSelection: selection?.promotionSelection,
226
+ promotionSelectionStrategyIds: selection?.promotionSelectionStrategyIds
227
+ };
228
+ });
229
+ return result;
230
+ }
@@ -24,6 +24,15 @@ export interface DiscountResult {
24
24
  discountList: any[];
25
25
  }
26
26
  export type RulesFormSubject = boolean | ((product: any) => boolean);
27
+ export interface RulesCalcDiscountParams {
28
+ discountList: Discount[];
29
+ productList: any[];
30
+ holders: {
31
+ form_record_id: number;
32
+ }[];
33
+ isFormSubject: RulesFormSubject;
34
+ orderTotalAmount: number;
35
+ }
27
36
  export interface RulesCalcDiscountOptions {
28
37
  isSelected?: boolean;
29
38
  discountId?: number;
@@ -26,6 +26,7 @@ var _pickupTiming = require("../../modules/Order/pickupTiming");
26
26
  var _pickupTiming2 = require("./pickupTiming");
27
27
  var _holderRelations = require("../../modules/Order/holderRelations");
28
28
  var _contactInfo = require("../../modules/OpenData/contactInfo");
29
+ var _promotionSelection = require("../../modules/Rules/promotionSelection");
29
30
  var _decimal = _interopRequireDefault(require("decimal.js"));
30
31
  var _lodashEs = require("lodash-es");
31
32
  var _types2 = require("../BookingByStep/types");
@@ -2181,17 +2182,25 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2181
2182
  return {
2182
2183
  ...discount,
2183
2184
  isSelected: false,
2184
- isManualSelect: true
2185
+ isManualSelect: true,
2186
+ promotionSelection: currentDiscount.promotionSelection,
2187
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2185
2188
  };
2186
2189
  }
2187
2190
  if (currentDiscount.isSelected) {
2188
2191
  return {
2189
2192
  ...discount,
2190
2193
  isSelected: true,
2191
- isManualSelect: false
2194
+ isManualSelect: false,
2195
+ promotionSelection: currentDiscount.promotionSelection,
2196
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2192
2197
  };
2193
2198
  }
2194
- return discount;
2199
+ return currentDiscount.promotionSelection ? {
2200
+ ...discount,
2201
+ promotionSelection: currentDiscount.promotionSelection,
2202
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2203
+ } : discount;
2195
2204
  });
2196
2205
  }
2197
2206
  resolveDiscountConfigCustomerId(tempOrder) {
@@ -2388,6 +2397,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2388
2397
  }
2389
2398
  async bestDiscount(cb) {
2390
2399
  if (!this.store.order) throw new Error('order 模块未初始化');
2400
+ this.hasManualDiscountSelection = false;
2391
2401
  const tempOrder = this.store.order.ensureTempOrder();
2392
2402
  if (this.isActiveVirtualSettlementOrder(tempOrder)) {
2393
2403
  const result = {
@@ -2552,8 +2562,10 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2552
2562
  nextDiscountList = result.discountList;
2553
2563
  if (!params.isSelected) {
2554
2564
  const beforeSelectedIds = new Set(updated.filter(d => d.isSelected).map(d => d.id));
2565
+ // Rules 已对促销组完成互斥报价,不能再移除其选中的卡而留下已取消的促销。
2566
+ const promotionCardIds = new Set((result.productList || []).filter(product => (0, _promotionSelection.getExclusivePromotion)(product)?.excludedByDiscountCard).flatMap(product => (product.discount_list || []).filter(_promotionSelection.isPromotionDiscountCard).map(discount => String(discount.discount?.resource_id ?? discount.id))));
2555
2567
  for (const d of nextDiscountList) {
2556
- if (d.isSelected && !beforeSelectedIds.has(d.id)) {
2568
+ if (d.isSelected && !beforeSelectedIds.has(d.id) && !promotionCardIds.has(String(d.id))) {
2557
2569
  d.isSelected = false;
2558
2570
  d.isManualSelect = true;
2559
2571
  d.appliedProductDetails = [];
@@ -2564,6 +2576,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2564
2576
  }
2565
2577
  const selectedResourceIds = new Set(nextDiscountList.filter(d => d.isSelected).map(d => d.id));
2566
2578
  const filterSelectedDiscountDetails = discountList => (discountList || []).filter(pd => {
2579
+ // 互斥计算保留/恢复的系统促销没有钱包 resource_id,不能按已选卡列表移除。
2580
+ if (pd.type === 'promotion' || pd.type === 'product' && pd.metadata?.source === 'promotion') return true;
2567
2581
  const rid = pd.discount?.resource_id ?? pd.id;
2568
2582
  return rid != null && selectedResourceIds.has(rid);
2569
2583
  });
@@ -2590,7 +2604,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2590
2604
 
2591
2605
  // 券作用于 source(不含 option、不含 bundle);算出新 source 折后价后补回 options
2592
2606
  // 写入含 option 的 main_product_selling_price,再合成 composite 回写 selling_price。
2593
- const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + (pd.amount || 0), 0);
2607
+ const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + Number(pd.amount || 0), 0);
2594
2608
  // TODO 这块逻辑需要拿掉
2595
2609
  const optionSum = (0, _utils.sumOptionUnitPrice)((0, _utils.getProductSkuOptions)(product));
2596
2610
  const sourcePrice = product.metadata?.source_product_price ?? (product.metadata?.main_product_original_price != null ? new _decimal.default(Number(product.metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : product.original_price ?? '0');
@@ -245,7 +245,10 @@ function resolveXItemsExpectedUnitPrice(promotion, sourceCartNum) {
245
245
  const y = Number(detail?.price);
246
246
  if (!Number.isFinite(x) || x <= 0 || !Number.isFinite(y)) return undefined;
247
247
  if (sourceCartNum < x) return undefined;
248
- return Number(new _decimal.default(y).div(x).toDecimalPlaces(2).toFixed(2));
248
+ const originalPrice = Number(promotion?.originalPrice);
249
+ const expectedUnit = new _decimal.default(y).div(x);
250
+ // 归并拆分行时沿用评估器的原价上限,避免重新按 Y / X 把原价抬高。
251
+ return (Number.isFinite(originalPrice) && originalPrice >= 0 ? _decimal.default.min(expectedUnit, originalPrice) : expectedUnit).toDecimalPlaces(2).toNumber();
249
252
  }
250
253
 
251
254
  /**
@@ -756,7 +759,7 @@ function calculateUnfulfilledPromotions(processedProducts, applicableStrategiesR
756
759
  for (let i = 0; i < processedProducts.length; i++) {
757
760
  const product = processedProducts[i];
758
761
  const promotion = product?.metadata?._promotion;
759
- if (!promotion || promotion.inPromotion !== false) continue;
762
+ if (!promotion || promotion.inPromotion !== false || promotion.excludedByDiscountCard) continue;
760
763
  const strategyId = promotion.strategyId;
761
764
  if (!strategyId) continue;
762
765
  const lookupUid = String(product?._originalProductUid ?? product?.metadata?.unique_identification_number ?? '');