@pisell/pisellos 2.2.318 → 2.2.320

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 (35) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.d.ts +2 -1
  2. package/dist/model/strategy/adapter/promotion/evaluator.js +19 -12
  3. package/dist/modules/Discount/types.d.ts +4 -0
  4. package/dist/modules/Order/index.js +740 -775
  5. package/dist/modules/Order/types.d.ts +2 -2
  6. package/dist/modules/Order/types.js +2 -2
  7. package/dist/modules/Order/utils.js +45 -45
  8. package/dist/modules/Payment/walletpass.js +32 -6
  9. package/dist/modules/Product/index.d.ts +1 -1
  10. package/dist/modules/Rules/index.d.ts +3 -10
  11. package/dist/modules/Rules/index.js +169 -87
  12. package/dist/modules/Rules/promotionSelection.d.ts +14 -0
  13. package/dist/modules/Rules/promotionSelection.js +390 -0
  14. package/dist/modules/Rules/types.d.ts +9 -0
  15. package/dist/solution/BaseSales/index.js +41 -21
  16. package/dist/solution/BaseSales/utils/cartPromotion.js +5 -2
  17. package/dist/solution/BookingByStep/index.d.ts +2 -2
  18. package/lib/model/strategy/adapter/promotion/evaluator.d.ts +2 -1
  19. package/lib/model/strategy/adapter/promotion/evaluator.js +18 -11
  20. package/lib/modules/Discount/types.d.ts +4 -0
  21. package/lib/modules/Order/index.js +13 -8
  22. package/lib/modules/Order/types.d.ts +2 -2
  23. package/lib/modules/Order/types.js +2 -2
  24. package/lib/modules/Order/utils.js +1 -1
  25. package/lib/modules/Payment/walletpass.js +23 -1
  26. package/lib/modules/Product/index.d.ts +1 -1
  27. package/lib/modules/Rules/index.d.ts +3 -10
  28. package/lib/modules/Rules/index.js +62 -22
  29. package/lib/modules/Rules/promotionSelection.d.ts +14 -0
  30. package/lib/modules/Rules/promotionSelection.js +230 -0
  31. package/lib/modules/Rules/types.d.ts +9 -0
  32. package/lib/solution/BaseSales/index.js +19 -5
  33. package/lib/solution/BaseSales/utils/cartPromotion.js +5 -2
  34. package/lib/solution/BookingByStep/index.d.ts +2 -2
  35. package/package.json +1 -1
@@ -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;
@@ -27,6 +27,7 @@ var _pickupTiming2 = require("./pickupTiming");
27
27
  var _fulfillmentItemRules = require("./fulfillmentItemRules");
28
28
  var _holderRelations = require("../../modules/Order/holderRelations");
29
29
  var _contactInfo = require("../../modules/OpenData/contactInfo");
30
+ var _promotionSelection = require("../../modules/Rules/promotionSelection");
30
31
  var _decimal = _interopRequireDefault(require("decimal.js"));
31
32
  var _lodashEs = require("lodash-es");
32
33
  var _types2 = require("../BookingByStep/types");
@@ -2141,17 +2142,25 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2141
2142
  return {
2142
2143
  ...discount,
2143
2144
  isSelected: false,
2144
- isManualSelect: true
2145
+ isManualSelect: true,
2146
+ promotionSelection: currentDiscount.promotionSelection,
2147
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2145
2148
  };
2146
2149
  }
2147
2150
  if (currentDiscount.isSelected) {
2148
2151
  return {
2149
2152
  ...discount,
2150
2153
  isSelected: true,
2151
- isManualSelect: false
2154
+ isManualSelect: false,
2155
+ promotionSelection: currentDiscount.promotionSelection,
2156
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2152
2157
  };
2153
2158
  }
2154
- return discount;
2159
+ return currentDiscount.promotionSelection ? {
2160
+ ...discount,
2161
+ promotionSelection: currentDiscount.promotionSelection,
2162
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
2163
+ } : discount;
2155
2164
  });
2156
2165
  }
2157
2166
  resolveDiscountConfigCustomerId(tempOrder) {
@@ -2348,6 +2357,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2348
2357
  }
2349
2358
  async bestDiscount(cb) {
2350
2359
  if (!this.store.order) throw new Error('order 模块未初始化');
2360
+ this.hasManualDiscountSelection = false;
2351
2361
  const tempOrder = this.store.order.ensureTempOrder();
2352
2362
  if (this.isActiveVirtualSettlementOrder(tempOrder)) {
2353
2363
  const result = {
@@ -2512,8 +2522,10 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2512
2522
  nextDiscountList = result.discountList;
2513
2523
  if (!params.isSelected) {
2514
2524
  const beforeSelectedIds = new Set(updated.filter(d => d.isSelected).map(d => d.id));
2525
+ // Rules 已对促销组完成互斥报价,不能再移除其选中的卡而留下已取消的促销。
2526
+ 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))));
2515
2527
  for (const d of nextDiscountList) {
2516
- if (d.isSelected && !beforeSelectedIds.has(d.id)) {
2528
+ if (d.isSelected && !beforeSelectedIds.has(d.id) && !promotionCardIds.has(String(d.id))) {
2517
2529
  d.isSelected = false;
2518
2530
  d.isManualSelect = true;
2519
2531
  d.appliedProductDetails = [];
@@ -2524,6 +2536,8 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2524
2536
  }
2525
2537
  const selectedResourceIds = new Set(nextDiscountList.filter(d => d.isSelected).map(d => d.id));
2526
2538
  const filterSelectedDiscountDetails = discountList => (discountList || []).filter(pd => {
2539
+ // 互斥计算保留/恢复的系统促销没有钱包 resource_id,不能按已选卡列表移除。
2540
+ if (pd.type === 'promotion' || pd.type === 'product' && pd.metadata?.source === 'promotion') return true;
2527
2541
  const rid = pd.discount?.resource_id ?? pd.id;
2528
2542
  return rid != null && selectedResourceIds.has(rid);
2529
2543
  });
@@ -2550,7 +2564,7 @@ class BaseSalesImpl extends _BaseModule.BaseModule {
2550
2564
 
2551
2565
  // 券作用于 source(不含 option、不含 bundle);算出新 source 折后价后补回 options
2552
2566
  // 写入含 option 的 main_product_selling_price,再合成 composite 回写 selling_price。
2553
- const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + (pd.amount || 0), 0);
2567
+ const totalPerUnitDiscount = (product.discount_list || []).reduce((sum, pd) => sum + Number(pd.amount || 0), 0);
2554
2568
  // TODO 这块逻辑需要拿掉
2555
2569
  const optionSum = (0, _utils.sumOptionUnitPrice)((0, _utils.getProductSkuOptions)(product));
2556
2570
  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 ?? '');
@@ -328,7 +328,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
328
328
  date: string;
329
329
  status: string;
330
330
  week: string;
331
- weekNum: 0 | 2 | 1 | 6 | 4 | 5 | 3;
331
+ weekNum: 0 | 2 | 1 | 3 | 4 | 5 | 6;
332
332
  }[]>;
333
333
  submitTimeSlot(timeSlots: TimeSliceItem): void;
334
334
  private getScheduleDataByIds;
@@ -375,7 +375,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
375
375
  };
376
376
  setOtherData(key: string, value: any): void;
377
377
  getOtherData(key: string): any;
378
- getProductTypeById(id: number): Promise<"normal" | "duration" | "session">;
378
+ getProductTypeById(id: number): Promise<"duration" | "normal" | "session">;
379
379
  /**
380
380
  * 提供给 UI 的方法,减轻 UI 层的计算压力,UI 层只需要传递 cartItemId 和 resourceCode 即返回对应的 renderList
381
381
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "2.2.318",
4
+ "version": "2.2.320",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",