@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.
@@ -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;
@@ -41,6 +41,7 @@ import { isFulfillmentTimingBooking } from "../../modules/Order/pickupTiming";
41
41
  import { PickupTimingController } from "./pickupTiming";
42
42
  import { getProductHolderRelations, hasProductBooking } from "../../modules/Order/holderRelations";
43
43
  import { resolveContactInfoConfig, getMissingContactInfoFields, ContactInfoRequiredError } from "../../modules/OpenData/contactInfo";
44
+ import { getExclusivePromotion, isPromotionDiscountCard } from "../../modules/Rules/promotionSelection";
44
45
  import Decimal from 'decimal.js';
45
46
  import { cloneDeep, isEqual, mergeWith } from 'lodash-es';
46
47
  import { createModule } from "../BookingByStep/types";
@@ -3431,16 +3432,23 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3431
3432
  if (currentDiscount.isManualSelect) {
3432
3433
  return _objectSpread(_objectSpread({}, discount), {}, {
3433
3434
  isSelected: false,
3434
- isManualSelect: true
3435
+ isManualSelect: true,
3436
+ promotionSelection: currentDiscount.promotionSelection,
3437
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3435
3438
  });
3436
3439
  }
3437
3440
  if (currentDiscount.isSelected) {
3438
3441
  return _objectSpread(_objectSpread({}, discount), {}, {
3439
3442
  isSelected: true,
3440
- isManualSelect: false
3443
+ isManualSelect: false,
3444
+ promotionSelection: currentDiscount.promotionSelection,
3445
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3441
3446
  });
3442
3447
  }
3443
- return discount;
3448
+ return currentDiscount.promotionSelection ? _objectSpread(_objectSpread({}, discount), {}, {
3449
+ promotionSelection: currentDiscount.promotionSelection,
3450
+ promotionSelectionStrategyIds: currentDiscount.promotionSelectionStrategyIds
3451
+ }) : discount;
3444
3452
  });
3445
3453
  }
3446
3454
  }, {
@@ -3862,9 +3870,10 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3862
3870
  }
3863
3871
  throw new Error('order 模块未初始化');
3864
3872
  case 2:
3873
+ this.hasManualDiscountSelection = false;
3865
3874
  tempOrder = this.store.order.ensureTempOrder();
3866
3875
  if (!this.isActiveVirtualSettlementOrder(tempOrder)) {
3867
- _context34.next = 7;
3876
+ _context34.next = 8;
3868
3877
  break;
3869
3878
  }
3870
3879
  _result2 = {
@@ -3873,7 +3882,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3873
3882
  };
3874
3883
  cb === null || cb === void 0 || cb(_result2);
3875
3884
  return _context34.abrupt("return", _result2);
3876
- case 7:
3885
+ case 8:
3877
3886
  orderStore = this.store.order.store || {};
3878
3887
  discountModule = orderStore.discount;
3879
3888
  rulesModule = orderStore.rules;
@@ -3884,11 +3893,11 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3884
3893
  productList: tempOrder.products || [],
3885
3894
  discountList: nextDiscountList
3886
3895
  };
3887
- _context34.next = 16;
3896
+ _context34.next = 17;
3888
3897
  return discountModule === null || discountModule === void 0 ? void 0 : discountModule.setDiscountList(nextDiscountList);
3889
- case 16:
3898
+ case 17:
3890
3899
  if (!rulesModule) {
3891
- _context34.next = 27;
3900
+ _context34.next = 28;
3892
3901
  break;
3893
3902
  }
3894
3903
  orderTotalAmount = Number(((_orderStore$summary2 = orderStore.summary) === null || _orderStore$summary2 === void 0 ? void 0 : _orderStore$summary2.total_amount) || 0);
@@ -3907,14 +3916,14 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3907
3916
  tempOrder.products = preserveManualProductDiscountProducts(tempOrder.products, result.productList);
3908
3917
  }
3909
3918
  if (!result.discountList) {
3910
- _context34.next = 27;
3919
+ _context34.next = 28;
3911
3920
  break;
3912
3921
  }
3913
3922
  nextDiscountList = this.mergeHistoricalDiscountList(result.discountList, tempOrder.products || []);
3914
3923
  OrderModule.populateSavedAmounts(tempOrder.products, nextDiscountList);
3915
- _context34.next = 25;
3924
+ _context34.next = 26;
3916
3925
  return discountModule === null || discountModule === void 0 ? void 0 : discountModule.setDiscountList(nextDiscountList);
3917
- case 25:
3926
+ case 26:
3918
3927
  tempOrder.discount_list = nextDiscountList.filter(function (discount) {
3919
3928
  return discount.isSelected;
3920
3929
  });
@@ -3922,24 +3931,24 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
3922
3931
  productList: tempOrder.products,
3923
3932
  discountList: nextDiscountList
3924
3933
  };
3925
- case 27:
3926
- _context34.next = 29;
3934
+ case 28:
3935
+ _context34.next = 30;
3927
3936
  return this.store.order.recalculateSummary({
3928
3937
  createIfMissing: true
3929
3938
  });
3930
- case 29:
3939
+ case 30:
3931
3940
  this.store.order.persistTempOrder();
3932
- _context34.next = 32;
3941
+ _context34.next = 33;
3933
3942
  return this.effectsEmit('onDiscountApplied', {
3934
3943
  productList: tempOrder.products || [],
3935
3944
  discountList: nextDiscountList,
3936
3945
  selectedDiscountList: tempOrder.discount_list || [],
3937
3946
  tempOrder: tempOrder
3938
3947
  });
3939
- case 32:
3948
+ case 33:
3940
3949
  cb === null || cb === void 0 || cb(result);
3941
3950
  return _context34.abrupt("return", result);
3942
- case 34:
3951
+ case 35:
3943
3952
  case "end":
3944
3953
  return _context34.stop();
3945
3954
  }
@@ -4079,7 +4088,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4079
4088
  key: "setDiscountSelected",
4080
4089
  value: function () {
4081
4090
  var _setDiscountSelected = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee37(params) {
4082
- 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;
4091
+ 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;
4083
4092
  return _regeneratorRuntime().wrap(function _callee37$(_context37) {
4084
4093
  while (1) switch (_context37.prev = _context37.next) {
4085
4094
  case 0:
@@ -4151,12 +4160,21 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4151
4160
  return d.isSelected;
4152
4161
  }).map(function (d) {
4153
4162
  return d.id;
4163
+ })); // Rules 已对促销组完成互斥报价,不能再移除其选中的卡而留下已取消的促销。
4164
+ promotionCardIds = new Set((result.productList || []).filter(function (product) {
4165
+ var _getExclusivePromotio;
4166
+ return (_getExclusivePromotio = getExclusivePromotion(product)) === null || _getExclusivePromotio === void 0 ? void 0 : _getExclusivePromotio.excludedByDiscountCard;
4167
+ }).flatMap(function (product) {
4168
+ return (product.discount_list || []).filter(isPromotionDiscountCard).map(function (discount) {
4169
+ var _discount$discount$re, _discount$discount5;
4170
+ 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);
4171
+ });
4154
4172
  }));
4155
4173
  _iterator6 = _createForOfIteratorHelper(nextDiscountList);
4156
4174
  try {
4157
4175
  for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
4158
4176
  d = _step6.value;
4159
- if (d.isSelected && !beforeSelectedIds.has(d.id)) {
4177
+ if (d.isSelected && !beforeSelectedIds.has(d.id) && !promotionCardIds.has(String(d.id))) {
4160
4178
  d.isSelected = false;
4161
4179
  d.isManualSelect = true;
4162
4180
  d.appliedProductDetails = [];
@@ -4177,7 +4195,9 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4177
4195
  }));
4178
4196
  filterSelectedDiscountDetails = function filterSelectedDiscountDetails(discountList) {
4179
4197
  return (discountList || []).filter(function (pd) {
4180
- var _pd$discount$resource, _pd$discount;
4198
+ var _pd$metadata, _pd$discount$resource, _pd$discount;
4199
+ // 互斥计算保留/恢复的系统促销没有钱包 resource_id,不能按已选卡列表移除。
4200
+ if (pd.type === 'promotion' || pd.type === 'product' && ((_pd$metadata = pd.metadata) === null || _pd$metadata === void 0 ? void 0 : _pd$metadata.source) === 'promotion') return true;
4181
4201
  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;
4182
4202
  return rid != null && selectedResourceIds.has(rid);
4183
4203
  });
@@ -4218,7 +4238,7 @@ export var BaseSalesImpl = /*#__PURE__*/function (_BaseModule) {
4218
4238
  // 券作用于 source(不含 option、不含 bundle);算出新 source 折后价后补回 options
4219
4239
  // 写入含 option 的 main_product_selling_price,再合成 composite 回写 selling_price。
4220
4240
  totalPerUnitDiscount = (product.discount_list || []).reduce(function (sum, pd) {
4221
- return sum + (pd.amount || 0);
4241
+ return sum + Number(pd.amount || 0);
4222
4242
  }, 0); // TODO 这块逻辑需要拿掉
4223
4243
  optionSum = sumOptionUnitPrice(getProductSkuOptions(product));
4224
4244
  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 : '');
@@ -651,6 +651,7 @@ class PromotionEvaluator {
651
651
  // 按组内原价比例均摊
652
652
  // 记录每个原商品的均摊价格累加(用于后续聚合)
653
653
  const allocatedPricesByProductId = new Map();
654
+ let expectedPromoTotal = new _decimal.default(0);
654
655
  for (let g = 0; g < groupCount; g++) {
655
656
  const startIdx = g * x;
656
657
  const endIdx = startIdx + x;
@@ -659,8 +660,9 @@ class PromotionEvaluator {
659
660
  // 计算组内原价总和
660
661
  const groupOriginalTotal = groupUnits.reduce((sum, u) => sum.plus(u.price), new _decimal.default(0));
661
662
 
662
- // 按原价比例均摊
663
- const groupPriceDecimal = new _decimal.default(groupPrice);
663
+ // 组价高于本组原价时保留原价,尾差目标也必须使用封顶后的实际组价。
664
+ const groupPriceDecimal = _decimal.default.min(new _decimal.default(groupPrice), groupOriginalTotal);
665
+ expectedPromoTotal = expectedPromoTotal.plus(groupPriceDecimal);
664
666
  let allocatedSum = new _decimal.default(0);
665
667
  for (let i = 0; i < groupUnits.length; i++) {
666
668
  const unit = groupUnits[i];
@@ -764,9 +766,8 @@ class PromotionEvaluator {
764
766
  processedQuantityMap.set(key, processedQty + availableQty);
765
767
  }
766
768
 
767
- // 8. 尾差调整:确保促销商品的 finalPrice × quantity 之和精确等于 groupPrice × groupCount
769
+ // 8. 尾差调整:只补实际组价的舍入差额,不将高于原价的组价补到某一件。
768
770
  if (groupCount > 0) {
769
- const expectedPromoTotal = new _decimal.default(groupPrice).mul(groupCount);
770
771
  const promoItems = result.filter(p => p.inPromotion);
771
772
  let actualPromoTotal = new _decimal.default(0);
772
773
  for (const p of promoItems) {