@pisell/pisellos 2.2.318 → 2.2.319

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 (33) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.js +5 -4
  2. package/dist/modules/Discount/types.d.ts +4 -0
  3. package/dist/modules/Order/index.d.ts +1 -1
  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/Rules/index.d.ts +3 -10
  10. package/dist/modules/Rules/index.js +169 -87
  11. package/dist/modules/Rules/promotionSelection.d.ts +14 -0
  12. package/dist/modules/Rules/promotionSelection.js +390 -0
  13. package/dist/modules/Rules/types.d.ts +9 -0
  14. package/dist/solution/BaseSales/index.js +41 -21
  15. package/dist/solution/BaseSales/utils/cartPromotion.js +5 -2
  16. package/dist/solution/BookingByStep/index.d.ts +1 -1
  17. package/lib/model/strategy/adapter/promotion/evaluator.js +5 -4
  18. package/lib/modules/Discount/types.d.ts +4 -0
  19. package/lib/modules/Order/index.d.ts +1 -1
  20. package/lib/modules/Order/index.js +13 -8
  21. package/lib/modules/Order/types.d.ts +2 -2
  22. package/lib/modules/Order/types.js +2 -2
  23. package/lib/modules/Order/utils.js +1 -1
  24. package/lib/modules/Payment/walletpass.js +23 -1
  25. package/lib/modules/Rules/index.d.ts +3 -10
  26. package/lib/modules/Rules/index.js +62 -22
  27. package/lib/modules/Rules/promotionSelection.d.ts +14 -0
  28. package/lib/modules/Rules/promotionSelection.js +230 -0
  29. package/lib/modules/Rules/types.d.ts +9 -0
  30. package/lib/solution/BaseSales/index.js +19 -5
  31. package/lib/solution/BaseSales/utils/cartPromotion.js +5 -2
  32. package/lib/solution/BookingByStep/index.d.ts +1 -1
  33. package/package.json +1 -1
@@ -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,390 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
3
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
5
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
6
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
7
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
8
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
9
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
10
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
11
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
13
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
14
+ import Decimal from 'decimal.js';
15
+ import { cloneDeep } from 'lodash-es';
16
+ export function isPromotionDiscountCard(discount) {
17
+ return ['discount_card', 'product_discount_card'].includes((discount === null || discount === void 0 ? void 0 : discount.tag) || (discount === null || discount === void 0 ? void 0 : discount.type));
18
+ }
19
+
20
+ /** 只处理当前购物车的 X 件 Y 元,历史成交和其他促销继续使用原有规则。 */
21
+ export function getExclusivePromotion(product) {
22
+ var _product$metadata, _product$metadata2;
23
+ var promotion = product === null || product === void 0 || (_product$metadata = product.metadata) === null || _product$metadata === void 0 ? void 0 : _product$metadata._promotion;
24
+ if (product !== null && product !== void 0 && product.order_detail_id || product !== null && product !== void 0 && product.orderDetailId || product !== null && product !== void 0 && product.booking_id || product !== null && product !== void 0 && (_product$metadata2 = product.metadata) !== null && _product$metadata2 !== void 0 && _product$metadata2.booking_id || (promotion === null || promotion === void 0 ? void 0 : promotion.actionType) !== 'X_ITEMS_FOR_Y_PRICE' || !promotion.strategyId || !(promotion.inPromotion === true || promotion.excludedByDiscountCard === true)) return undefined;
25
+ return promotion;
26
+ }
27
+ /**
28
+ * 以完整策略参与组为单位比较两套实际报价。每次试算都从同一快照开始,
29
+ * 由原引擎重新做卡券校验和整单卡分摊,不能从叠加结果里事后减掉某条优惠。
30
+ */
31
+ export function calculatePromotionSelection(params, options, hooks, calculate) {
32
+ var discountList = params.discountList.map(function (discount) {
33
+ if (discount.isEditMode || !isPromotionDiscountCard(discount)) return discount;
34
+ if ((options === null || options === void 0 ? void 0 : options.preserveEntitlementSelection) === false) {
35
+ return _objectSpread(_objectSpread({}, discount), {}, {
36
+ promotionSelection: undefined,
37
+ promotionSelectionStrategyIds: undefined,
38
+ isManualSelect: false
39
+ });
40
+ }
41
+ if ((options === null || options === void 0 ? void 0 : options.discountId) !== undefined && String(discount.id) === String(options.discountId) && typeof options.isSelected === 'boolean') {
42
+ return _objectSpread(_objectSpread({}, discount), {}, {
43
+ promotionSelection: options.isSelected ? 'card' : 'promotion',
44
+ isSelected: options.isSelected,
45
+ isManualSelect: !options.isSelected
46
+ });
47
+ }
48
+ return _objectSpread({}, discount);
49
+ });
50
+ // 未凑足促销时也要清理重叠商品上的旧手选,避免再次凑组后切回之前的卡。
51
+ var changedCard = (options === null || options === void 0 ? void 0 : options.discountId) !== undefined && typeof options.isSelected === 'boolean' ? discountList.find(function (discount) {
52
+ return !discount.isEditMode && isPromotionDiscountCard(discount) && String(discount.id) === String(options.discountId);
53
+ }) : undefined;
54
+ if (changedCard) {
55
+ var changedProductIds = new Set(changedCard.applicableProductIds || []);
56
+ var _iterator = _createForOfIteratorHelper(params.productList),
57
+ _step;
58
+ try {
59
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
60
+ var _detail$discount_list;
61
+ var _product = _step.value;
62
+ var detail = hooks.getProduct(_product);
63
+ if ((_detail$discount_list = detail.discount_list) !== null && _detail$discount_list !== void 0 && _detail$discount_list.some(function (discount) {
64
+ var _discount$discount$re, _discount$discount;
65
+ return isPromotionDiscountCard(discount) && String((_discount$discount$re = (_discount$discount = discount.discount) === null || _discount$discount === void 0 ? void 0 : _discount$discount.resource_id) !== null && _discount$discount$re !== void 0 ? _discount$discount$re : discount.id) === String(changedCard.id);
66
+ })) changedProductIds.add(detail.id);
67
+ }
68
+ } catch (err) {
69
+ _iterator.e(err);
70
+ } finally {
71
+ _iterator.f();
72
+ }
73
+ var _iterator2 = _createForOfIteratorHelper(discountList),
74
+ _step2;
75
+ try {
76
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
77
+ var _discount$applicableP;
78
+ var _discount = _step2.value;
79
+ if (_discount.isEditMode || !isPromotionDiscountCard(_discount) || String(_discount.id) === String(changedCard.id) || !_discount.promotionSelection) continue;
80
+ if ((_discount$applicableP = _discount.applicableProductIds) !== null && _discount$applicableP !== void 0 && _discount$applicableP.some(function (id) {
81
+ return changedProductIds.has(id);
82
+ })) {
83
+ _discount.promotionSelection = undefined;
84
+ _discount.promotionSelectionStrategyIds = undefined;
85
+ }
86
+ }
87
+ } catch (err) {
88
+ _iterator2.e(err);
89
+ } finally {
90
+ _iterator2.f();
91
+ }
92
+ }
93
+ var strategyIds = new Set();
94
+ var _iterator3 = _createForOfIteratorHelper(params.productList),
95
+ _step3;
96
+ try {
97
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
98
+ var _product2 = _step3.value;
99
+ var promotion = getExclusivePromotion(_product2);
100
+ if (promotion && hooks.getProduct(_product2).isManualDiscount !== true) {
101
+ strategyIds.add(String(promotion.strategyId));
102
+ }
103
+ }
104
+ } catch (err) {
105
+ _iterator3.e(err);
106
+ } finally {
107
+ _iterator3.f();
108
+ }
109
+ if (!strategyIds.size) return calculate(_objectSpread(_objectSpread({}, params), {}, {
110
+ discountList: discountList
111
+ }), options);
112
+ var applicableGroups = new Map();
113
+ var quote = function quote(blockedStrategyIds) {
114
+ var collectApplicable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
115
+ var productList = cloneDeep(params.productList).map(function (product) {
116
+ var _promotion$originalPr;
117
+ var promotion = getExclusivePromotion(product);
118
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) return product;
119
+ var detail = hooks.getProduct(product);
120
+ if (detail.isManualDiscount === true) return product;
121
+ var keepPromotion = blockedStrategyIds.has(String(promotion.strategyId));
122
+ var originalPrice = Number((_promotion$originalPr = promotion.originalPrice) !== null && _promotion$originalPr !== void 0 ? _promotion$originalPr : detail.price);
123
+ var finalPrice = Number(promotion.finalPrice);
124
+ var promotionDiscount = (detail.discount_list || []).find(function (discount) {
125
+ return discount.type === 'promotion';
126
+ });
127
+ var retainedDiscounts = (detail.discount_list || []).filter(function (discount) {
128
+ return discount.type !== 'promotion' && (!isPromotionDiscountCard(discount) || !keepPromotion && discountList.some(function (card) {
129
+ var _discount$discount$re2, _discount$discount2;
130
+ return !card.isManualSelect && String(card.id) === String((_discount$discount$re2 = (_discount$discount2 = discount.discount) === null || _discount$discount2 === void 0 ? void 0 : _discount$discount2.resource_id) !== null && _discount$discount$re2 !== void 0 ? _discount$discount$re2 : discount.id);
131
+ }));
132
+ });
133
+ if (keepPromotion && originalPrice !== finalPrice) {
134
+ var _promotion$strategyMe;
135
+ retainedDiscounts.push(promotionDiscount || {
136
+ type: 'promotion',
137
+ amount: new Decimal(originalPrice).minus(finalPrice).toFixed(2),
138
+ discount: {
139
+ original_amount: String(originalPrice),
140
+ fixed_amount: new Decimal(originalPrice).minus(finalPrice).toFixed(2),
141
+ title: ((_promotion$strategyMe = promotion.strategyMetadata) === null || _promotion$strategyMe === void 0 ? void 0 : _promotion$strategyMe.name) || '',
142
+ resource_id: ''
143
+ }
144
+ });
145
+ }
146
+ product.metadata._promotion = _objectSpread(_objectSpread({}, promotion), {}, {
147
+ inPromotion: keepPromotion,
148
+ excludedByDiscountCard: !keepPromotion
149
+ });
150
+ return hooks.setProduct(product, {
151
+ discount_list: retainedDiscounts,
152
+ main_product_selling_price: keepPromotion ? finalPrice : originalPrice
153
+ });
154
+ });
155
+ return calculate(_objectSpread(_objectSpread({}, params), {}, {
156
+ productList: productList,
157
+ discountList: cloneDeep(discountList).map(function (discount) {
158
+ return !discount.isEditMode && isPromotionDiscountCard(discount) && !discount.isManualSelect
159
+ // 自动落选不等于手动禁用;整单卡仍须进入下一轮候选分摊。
160
+ ? _objectSpread(_objectSpread({}, discount), {}, {
161
+ isSelected: discount.isSelected === false ? undefined : discount.isSelected
162
+ }) : discount;
163
+ })
164
+ }), options, {
165
+ blockedStrategyIds: blockedStrategyIds,
166
+ onApplicableCard: collectApplicable ? function (product, discount) {
167
+ var promotion = getExclusivePromotion(product);
168
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) return;
169
+ var id = String(discount.id);
170
+ var groups = applicableGroups.get(id) || new Set();
171
+ groups.add(String(promotion.strategyId));
172
+ applicableGroups.set(id, groups);
173
+ } : undefined
174
+ });
175
+ };
176
+
177
+ // 起点保留所有促销;未发生冲突的商品和卡券仍由原引擎正常计算。
178
+ var blockedStrategyIds = new Set(strategyIds);
179
+ var result = quote(blockedStrategyIds, true);
180
+ // 取消已应用的卡时,即使它刚好失效,也应恢复它原来替代的促销组。
181
+ var _iterator4 = _createForOfIteratorHelper(params.productList),
182
+ _step4;
183
+ try {
184
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
185
+ var _product3 = _step4.value;
186
+ var _promotion = getExclusivePromotion(_product3);
187
+ if (!_promotion || !strategyIds.has(String(_promotion.strategyId))) continue;
188
+ var _iterator9 = _createForOfIteratorHelper(hooks.getProduct(_product3).discount_list || []),
189
+ _step9;
190
+ try {
191
+ var _loop = function _loop() {
192
+ var _detail$discount$reso, _detail$discount;
193
+ var detail = _step9.value;
194
+ if (!isPromotionDiscountCard(detail)) return 0; // continue
195
+ var id = String((_detail$discount$reso = (_detail$discount = detail.discount) === null || _detail$discount === void 0 ? void 0 : _detail$discount.resource_id) !== null && _detail$discount$reso !== void 0 ? _detail$discount$reso : detail.id);
196
+ if (!discountList.some(function (discount) {
197
+ return String(discount.id) === id && (discount.isManualSelect || discount.promotionSelection === 'promotion');
198
+ })) return 0; // continue
199
+ var groups = applicableGroups.get(id) || new Set();
200
+ groups.add(String(_promotion.strategyId));
201
+ applicableGroups.set(id, groups);
202
+ },
203
+ _ret;
204
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
205
+ _ret = _loop();
206
+ if (_ret === 0) continue;
207
+ }
208
+ } catch (err) {
209
+ _iterator9.e(err);
210
+ } finally {
211
+ _iterator9.f();
212
+ }
213
+ }
214
+ // 同一参与组以最近一次手动操作为准,不能让先前选过的另一张卡重新压过取消操作。
215
+ } catch (err) {
216
+ _iterator4.e(err);
217
+ } finally {
218
+ _iterator4.f();
219
+ }
220
+ var changedGroups = (options === null || options === void 0 ? void 0 : options.discountId) !== undefined && typeof options.isSelected === 'boolean' ? applicableGroups.get(String(options.discountId)) : undefined;
221
+ if (changedGroups !== null && changedGroups !== void 0 && changedGroups.size) {
222
+ var _iterator5 = _createForOfIteratorHelper(discountList),
223
+ _step5;
224
+ try {
225
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
226
+ var _discount2 = _step5.value;
227
+ if (!_discount2.isEditMode && String(_discount2.id) === String(options === null || options === void 0 ? void 0 : options.discountId)) {
228
+ _discount2.promotionSelectionStrategyIds = _toConsumableArray(changedGroups);
229
+ continue;
230
+ }
231
+ if (_discount2.isEditMode || !isPromotionDiscountCard(_discount2) || String(_discount2.id) === String(options === null || options === void 0 ? void 0 : options.discountId) || !_discount2.promotionSelection) continue;
232
+ var groups = new Set([].concat(_toConsumableArray(applicableGroups.get(String(_discount2.id)) || []), _toConsumableArray(_discount2.promotionSelectionStrategyIds || [])));
233
+ if (_toConsumableArray(groups).some(function (group) {
234
+ return changedGroups.has(group);
235
+ })) {
236
+ _discount2.promotionSelection = undefined;
237
+ _discount2.promotionSelectionStrategyIds = undefined;
238
+ }
239
+ }
240
+ } catch (err) {
241
+ _iterator5.e(err);
242
+ } finally {
243
+ _iterator5.f();
244
+ }
245
+ }
246
+ var manualPromotionGroups = new Set();
247
+ var manualCardGroups = new Set();
248
+ var _iterator6 = _createForOfIteratorHelper(discountList),
249
+ _step6;
250
+ try {
251
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
252
+ var _discount3 = _step6.value;
253
+ if (!isPromotionDiscountCard(_discount3) || _discount3.isEditMode) continue;
254
+ var _groups = applicableGroups.get(String(_discount3.id)) || [];
255
+ if (_discount3.isManualSelect || _discount3.promotionSelection === 'promotion') {
256
+ var _iterator10 = _createForOfIteratorHelper(_groups),
257
+ _step10;
258
+ try {
259
+ for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
260
+ var group = _step10.value;
261
+ manualPromotionGroups.add(group);
262
+ }
263
+ } catch (err) {
264
+ _iterator10.e(err);
265
+ } finally {
266
+ _iterator10.f();
267
+ }
268
+ var _iterator11 = _createForOfIteratorHelper(_discount3.promotionSelectionStrategyIds || []),
269
+ _step11;
270
+ try {
271
+ for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
272
+ var _group = _step11.value;
273
+ if (strategyIds.has(_group)) manualPromotionGroups.add(_group);
274
+ }
275
+ } catch (err) {
276
+ _iterator11.e(err);
277
+ } finally {
278
+ _iterator11.f();
279
+ }
280
+ } else if (_discount3.promotionSelection === 'card') {
281
+ var _iterator12 = _createForOfIteratorHelper(_groups),
282
+ _step12;
283
+ try {
284
+ for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
285
+ var _group2 = _step12.value;
286
+ manualCardGroups.add(_group2);
287
+ }
288
+ } catch (err) {
289
+ _iterator12.e(err);
290
+ } finally {
291
+ _iterator12.f();
292
+ }
293
+ }
294
+ }
295
+ } catch (err) {
296
+ _iterator6.e(err);
297
+ } finally {
298
+ _iterator6.f();
299
+ }
300
+ var total = function total(candidate) {
301
+ return candidate.productList.reduce(function (sum, product) {
302
+ var detail = hooks.getProduct(product);
303
+ var discounts = [].concat(_toConsumableArray(detail.discount_list), _toConsumableArray((detail.bundle || []).flatMap(function (bundle) {
304
+ return (bundle.discount_list || []).filter(function (discount) {
305
+ return !discount.id;
306
+ });
307
+ })));
308
+ // 与订单小计一致:整单卡未计入单价的尾差按行扣一次,不能漏算或再乘数量。
309
+ var difference = discounts.reduce(function (amount, discount) {
310
+ var _discount$metadata;
311
+ return amount.plus(((_discount$metadata = discount.metadata) === null || _discount$metadata === void 0 ? void 0 : _discount$metadata.product_discount_difference) || 0);
312
+ }, new Decimal(0));
313
+ return sum.plus(detail.total).minus(difference);
314
+ }, new Decimal(0));
315
+ };
316
+ var hasAppliedCard = function hasAppliedCard(candidate, strategyId) {
317
+ return candidate.productList.some(function (product) {
318
+ var _getExclusivePromotio;
319
+ return String((_getExclusivePromotio = getExclusivePromotion(product)) === null || _getExclusivePromotio === void 0 ? void 0 : _getExclusivePromotio.strategyId) === strategyId && hooks.getProduct(product).discount_list.some(isPromotionDiscountCard);
320
+ });
321
+ };
322
+ // 手动选择先落定,随后只对未手选的参与组比较优惠。
323
+ var _iterator7 = _createForOfIteratorHelper(manualCardGroups),
324
+ _step7;
325
+ try {
326
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
327
+ var _strategyId = _step7.value;
328
+ var _candidateBlocked = new Set(blockedStrategyIds);
329
+ _candidateBlocked.delete(_strategyId);
330
+ var _candidate = quote(_candidateBlocked);
331
+ if (hasAppliedCard(_candidate, _strategyId)) {
332
+ blockedStrategyIds = _candidateBlocked;
333
+ result = _candidate;
334
+ }
335
+ }
336
+ } catch (err) {
337
+ _iterator7.e(err);
338
+ } finally {
339
+ _iterator7.f();
340
+ }
341
+ var automaticGroups = new Set(_toConsumableArray(strategyIds).filter(function (id) {
342
+ return !manualCardGroups.has(id) && !manualPromotionGroups.has(id) && discountList.some(function (discount) {
343
+ var _applicableGroups$get;
344
+ return !discount.isEditMode && !discount.isManualSelect && ((_applicableGroups$get = applicableGroups.get(String(discount.id))) === null || _applicableGroups$get === void 0 ? void 0 : _applicableGroups$get.has(id));
345
+ });
346
+ }));
347
+ // 多组共用整单卡时先选节省最多的一组,再重新试算其余组,避免依赖购物车行顺序。
348
+ while (automaticGroups.size) {
349
+ var bestGroup = void 0;
350
+ var bestResult = result;
351
+ var bestTotal = total(result);
352
+ var _iterator8 = _createForOfIteratorHelper(automaticGroups),
353
+ _step8;
354
+ try {
355
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
356
+ var strategyId = _step8.value;
357
+ var candidateBlocked = new Set(blockedStrategyIds);
358
+ candidateBlocked.delete(strategyId);
359
+ var candidate = quote(candidateBlocked);
360
+ var candidateTotal = total(candidate);
361
+ // 没有实际可用卡时保持促销;同价继续保留促销。
362
+ if (hasAppliedCard(candidate, strategyId) && candidateTotal.lessThan(bestTotal)) {
363
+ bestGroup = strategyId;
364
+ bestResult = candidate;
365
+ bestTotal = candidateTotal;
366
+ }
367
+ }
368
+ } catch (err) {
369
+ _iterator8.e(err);
370
+ } finally {
371
+ _iterator8.f();
372
+ }
373
+ if (bestGroup === undefined) break;
374
+ blockedStrategyIds.delete(bestGroup);
375
+ automaticGroups.delete(bestGroup);
376
+ result = bestResult;
377
+ }
378
+ // 即使最终保留首次报价,也要回写上面清除的旧手动意图。
379
+ result.discountList = result.discountList.map(function (discount) {
380
+ if (discount.isEditMode || !isPromotionDiscountCard(discount)) return discount;
381
+ var selection = discountList.find(function (card) {
382
+ return !card.isEditMode && String(card.id) === String(discount.id);
383
+ });
384
+ return _objectSpread(_objectSpread({}, discount), {}, {
385
+ promotionSelection: selection === null || selection === void 0 ? void 0 : selection.promotionSelection,
386
+ promotionSelectionStrategyIds: selection === null || selection === void 0 ? void 0 : selection.promotionSelectionStrategyIds
387
+ });
388
+ });
389
+ return result;
390
+ }
@@ -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;
@@ -42,6 +42,7 @@ import { PickupTimingController } from "./pickupTiming";
42
42
  import { FulfillmentItemRulesController } from "./fulfillmentItemRules";
43
43
  import { getProductHolderRelations, hasProductBooking } from "../../modules/Order/holderRelations";
44
44
  import { resolveContactInfoConfig, getMissingContactInfoFields, ContactInfoRequiredError } from "../../modules/OpenData/contactInfo";
45
+ import { getExclusivePromotion, isPromotionDiscountCard } from "../../modules/Rules/promotionSelection";
45
46
  import Decimal from 'decimal.js';
46
47
  import { cloneDeep, isEqual, mergeWith } from 'lodash-es';
47
48
  import { createModule } from "../BookingByStep/types";
@@ -3364,16 +3365,23 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3364
3365
  if (currentDiscount.isManualSelect) {
3365
3366
  return _objectSpread(_objectSpread({}, discount), {}, {
3366
3367
  isSelected: false,
3367
- isManualSelect: true
3368
+ isManualSelect: true,
3369
+ promotionSelection: currentDiscount.promotionSelection,
3370
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3368
3371
  });
3369
3372
  }
3370
3373
  if (currentDiscount.isSelected) {
3371
3374
  return _objectSpread(_objectSpread({}, discount), {}, {
3372
3375
  isSelected: true,
3373
- isManualSelect: false
3376
+ isManualSelect: false,
3377
+ promotionSelection: currentDiscount.promotionSelection,
3378
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3374
3379
  });
3375
3380
  }
3376
- return discount;
3381
+ return currentDiscount.promotionSelection ? _objectSpread(_objectSpread({}, discount), {}, {
3382
+ promotionSelection: currentDiscount.promotionSelection,
3383
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3384
+ }) : discount;
3377
3385
  });
3378
3386
  }
3379
3387
  }, {
@@ -3795,9 +3803,10 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3795
3803
  }
3796
3804
  throw new Error('order 模块未初始化');
3797
3805
  case 2:
3806
+ this.hasManualDiscountSelection = false;
3798
3807
  tempOrder = this.store.order.ensureTempOrder();
3799
3808
  if (!this.isActiveVirtualSettlementOrder(tempOrder)) {
3800
- _context33.next = 7;
3809
+ _context33.next = 8;
3801
3810
  break;
3802
3811
  }
3803
3812
  _result2 = {
@@ -3806,7 +3815,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3806
3815
  };
3807
3816
  cb === null || cb === void 0 || cb(_result2);
3808
3817
  return _context33.abrupt("return", _result2);
3809
- case 7:
3818
+ case 8:
3810
3819
  orderStore = this.store.order.store || {};
3811
3820
  discountModule = orderStore.discount;
3812
3821
  rulesModule = orderStore.rules;
@@ -3817,11 +3826,11 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3817
3826
  productList: tempOrder.products || [],
3818
3827
  discountList: nextDiscountList
3819
3828
  };
3820
- _context33.next = 16;
3829
+ _context33.next = 17;
3821
3830
  return discountModule === null || discountModule === void 0 ? void 0 : discountModule.setDiscountList(nextDiscountList);
3822
- case 16:
3831
+ case 17:
3823
3832
  if (!rulesModule) {
3824
- _context33.next = 27;
3833
+ _context33.next = 28;
3825
3834
  break;
3826
3835
  }
3827
3836
  orderTotalAmount = Number(((_orderStore$summary2 = orderStore.summary) === null || _orderStore$summary2 === void 0 ? void 0 : _orderStore$summary2.total_amount) || 0);
@@ -3840,14 +3849,14 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3840
3849
  tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
3841
3850
  }
3842
3851
  if (!result.discountList) {
3843
- _context33.next = 27;
3852
+ _context33.next = 28;
3844
3853
  break;
3845
3854
  }
3846
3855
  nextDiscountList = this.mergeHistoricalDiscountList(result.discountList, tempOrder.products || []);
3847
3856
  OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
3848
- _context33.next = 25;
3857
+ _context33.next = 26;
3849
3858
  return discountModule === null || discountModule === void 0 ? void 0 : discountModule.setDiscountList(nextDiscountList);
3850
- case 25:
3859
+ case 26:
3851
3860
  tempOrder.discount_list = nextDiscountList.filter(function (discount) {
3852
3861
  return discount.isSelected;
3853
3862
  });
@@ -3855,24 +3864,24 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3855
3864
  productList: tempOrder.products,
3856
3865
  discountList: nextDiscountList
3857
3866
  };
3858
- case 27:
3859
- _context33.next = 29;
3867
+ case 28:
3868
+ _context33.next = 30;
3860
3869
  return this.store.order.recalculateSummary({
3861
3870
  createIfMissing: true
3862
3871
  });
3863
- case 29:
3872
+ case 30:
3864
3873
  this.store.order.persistTempOrder();
3865
- _context33.next = 32;
3874
+ _context33.next = 33;
3866
3875
  return this.effectsEmit('onDiscountApplied', {
3867
3876
  productList: tempOrder.products || [],
3868
3877
  discountList: nextDiscountList,
3869
3878
  selectedDiscountList: tempOrder.discount_list || [],
3870
3879
  tempOrder: tempOrder
3871
3880
  });
3872
- case 32:
3881
+ case 33:
3873
3882
  cb === null || cb === void 0 || cb(result);
3874
3883
  return _context33.abrupt("return", result);
3875
- case 34:
3884
+ case 35:
3876
3885
  case "end":
3877
3886
  return _context33.stop();
3878
3887
  }
@@ -4012,7 +4021,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4012
4021
  key: "setDiscountSelected",
4013
4022
  value: function () {
4014
4023
  var _setDiscountSelected = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee36(params) {
4015
- var currentOrder, _store3, _store3$setDiscountLi, list, updated, tempOrder, orderStore, _discountModule, rulesModule, nextDiscountList, _orderStore$summary3, orderTotalAmount, result, beforeSelectedIds, _iterator6, _step6, d, selectedResourceIds, filterSelectedDiscountDetails, _iterator7, _step7, _product$metadata8, _tempOrder$_extend7, _product$metadata$sou2, _product$metadata9, _product$metadata10, _product$original_pri2, product, productUid, runtimeOrigin, totalPerUnitDiscount, optionSum, sourcePrice, newSourceSellingPrice, newMainSellingPrice;
4024
+ var currentOrder, _store3, _store3$setDiscountLi, list, updated, tempOrder, orderStore, _discountModule, rulesModule, nextDiscountList, _orderStore$summary3, orderTotalAmount, result, beforeSelectedIds, promotionCardIds, _iterator6, _step6, d, selectedResourceIds, filterSelectedDiscountDetails, _iterator7, _step7, _product$metadata8, _tempOrder$_extend7, _product$metadata$sou2, _product$metadata9, _product$metadata10, _product$original_pri2, product, productUid, runtimeOrigin, totalPerUnitDiscount, optionSum, sourcePrice, newSourceSellingPrice, newMainSellingPrice;
4016
4025
  return _regeneratorRuntime().wrap(function _callee36$(_context36) {
4017
4026
  while (1) switch (_context36.prev = _context36.next) {
4018
4027
  case 0:
@@ -4084,12 +4093,21 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4084
4093
  return d.isSelected;
4085
4094
  }).map(function (d) {
4086
4095
  return d.id;
4096
+ })); // Rules 已对促销组完成互斥报价,不能再移除其选中的卡而留下已取消的促销。
4097
+ promotionCardIds = new Set((result.productList || []).filter(function (product) {
4098
+ var _getExclusivePromotio;
4099
+ return (_getExclusivePromotio = getExclusivePromotion(product)) === null || _getExclusivePromotio === void 0 ? void 0 : _getExclusivePromotio.excludedByDiscountCard;
4100
+ }).flatMap(function (product) {
4101
+ return (product.discount_list || []).filter(isPromotionDiscountCard).map(function (discount) {
4102
+ var _discount$discount$re, _discount$discount5;
4103
+ return String((_discount$discount$re = (_discount$discount5 = discount.discount) === null || _discount$discount5 === void 0 ? void 0 : _discount$discount5.resource_id) !== null && _discount$discount$re !== void 0 ? _discount$discount$re : discount.id);
4104
+ });
4087
4105
  }));
4088
4106
  _iterator6 = _createForOfIteratorHelper(nextDiscountList);
4089
4107
  try {
4090
4108
  for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
4091
4109
  d = _step6.value;
4092
- if (d.isSelected && !beforeSelectedIds.has(d.id)) {
4110
+ if (d.isSelected && !beforeSelectedIds.has(d.id) && !promotionCardIds.has(String(d.id))) {
4093
4111
  d.isSelected = false;
4094
4112
  d.isManualSelect = true;
4095
4113
  d.appliedProductDetails = [];
@@ -4110,7 +4128,9 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4110
4128
  }));
4111
4129
  filterSelectedDiscountDetails = function filterSelectedDiscountDetails(discountList) {
4112
4130
  return (discountList || []).filter(function (pd) {
4113
- var _pd$discount$resource, _pd$discount;
4131
+ var _pd$metadata, _pd$discount$resource, _pd$discount;
4132
+ // 互斥计算保留/恢复的系统促销没有钱包 resource_id,不能按已选卡列表移除。
4133
+ if (pd.type === 'promotion' || pd.type === 'product' && ((_pd$metadata = pd.metadata) === null || _pd$metadata === void 0 ? void 0 : _pd$metadata.source) === 'promotion') return true;
4114
4134
  var rid = (_pd$discount$resource = (_pd$discount = pd.discount) === null || _pd$discount === void 0 ? void 0 : _pd$discount.resource_id) !== null && _pd$discount$resource !== void 0 ? _pd$discount$resource : pd.id;
4115
4135
  return rid != null && selectedResourceIds.has(rid);
4116
4136
  });
@@ -4151,7 +4171,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4151
4171
  // 券作用于 source(不含 option、不含 bundle);算出新 source 折后价后补回 options
4152
4172
  // 写入含 option 的 main_product_selling_price,再合成 composite 回写 selling_price。
4153
4173
  totalPerUnitDiscount = (product.discount_list || []).reduce(function (sum, pd) {
4154
- return sum + (pd.amount || 0);
4174
+ return sum + Number(pd.amount || 0);
4155
4175
  }, 0); // TODO 这块逻辑需要拿掉
4156
4176
  optionSum = sumOptionUnitPrice(getProductSkuOptions(product));
4157
4177
  sourcePrice = (_product$metadata$sou2 = (_product$metadata9 = product.metadata) === null || _product$metadata9 === void 0 ? void 0 : _product$metadata9.source_product_price) !== null && _product$metadata$sou2 !== void 0 ? _product$metadata$sou2 : ((_product$metadata10 = product.metadata) === null || _product$metadata10 === void 0 ? void 0 : _product$metadata10.main_product_original_price) != null ? new Decimal(Number(product.metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : (_product$original_pri2 = product.original_price) !== null && _product$original_pri2 !== void 0 ? _product$original_pri2 : '0';
@@ -259,7 +259,10 @@ function resolveXItemsExpectedUnitPrice(promotion, sourceCartNum) {
259
259
  var y = Number(detail === null || detail === void 0 ? void 0 : detail.price);
260
260
  if (!Number.isFinite(x) || x <= 0 || !Number.isFinite(y)) return undefined;
261
261
  if (sourceCartNum < x) return undefined;
262
- return Number(new Decimal(y).div(x).toDecimalPlaces(2).toFixed(2));
262
+ var originalPrice = Number(promotion === null || promotion === void 0 ? void 0 : promotion.originalPrice);
263
+ var expectedUnit = new Decimal(y).div(x);
264
+ // 归并拆分行时沿用评估器的原价上限,避免重新按 Y / X 把原价抬高。
265
+ return (Number.isFinite(originalPrice) && originalPrice >= 0 ? Decimal.min(expectedUnit, originalPrice) : expectedUnit).toDecimalPlaces(2).toNumber();
263
266
  }
264
267
 
265
268
  /**
@@ -948,7 +951,7 @@ export function calculateUnfulfilledPromotions(processedProducts, applicableStra
948
951
  var _product$metadata5, _ref13, _product$_originalPro, _product$metadata6, _product$num2;
949
952
  var product = processedProducts[i];
950
953
  var promotion = product === null || product === void 0 || (_product$metadata5 = product.metadata) === null || _product$metadata5 === void 0 ? void 0 : _product$metadata5._promotion;
951
- if (!promotion || promotion.inPromotion !== false) return 0; // continue
954
+ if (!promotion || promotion.inPromotion !== false || promotion.excludedByDiscountCard) return 0; // continue
952
955
  var strategyId = promotion.strategyId;
953
956
  if (!strategyId) return 0; // continue
954
957
  var lookupUid = String((_ref13 = (_product$_originalPro = product === null || product === void 0 ? void 0 : product._originalProductUid) !== null && _product$_originalPro !== void 0 ? _product$_originalPro : product === null || product === void 0 || (_product$metadata6 = product.metadata) === null || _product$metadata6 === void 0 ? void 0 : _product$metadata6.unique_identification_number) !== null && _ref13 !== void 0 ? _ref13 : '');
@@ -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 | 1 | 2 | 3 | 4 | 5 | 6;
332
332
  }[]>;
333
333
  submitTimeSlot(timeSlots: TimeSliceItem): void;
334
334
  private getScheduleDataByIds;