@pisell/pisellos 2.1.103 → 2.1.104

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 (100) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.js +1 -0
  3. package/dist/model/index.d.ts +1 -0
  4. package/dist/model/index.js +1 -0
  5. package/dist/model/strategy/adapter/index.d.ts +3 -0
  6. package/dist/model/strategy/adapter/index.js +4 -0
  7. package/dist/model/strategy/adapter/type.d.ts +28 -0
  8. package/dist/model/strategy/adapter/type.js +1 -0
  9. package/dist/model/strategy/adapter/walletPass/evaluator.d.ts +84 -0
  10. package/dist/model/strategy/adapter/walletPass/evaluator.js +498 -0
  11. package/dist/model/strategy/adapter/walletPass/example.d.ts +4 -0
  12. package/dist/model/strategy/adapter/walletPass/example.js +258 -0
  13. package/dist/model/strategy/adapter/walletPass/index.d.ts +32 -0
  14. package/dist/model/strategy/adapter/walletPass/index.js +182 -0
  15. package/dist/model/strategy/adapter/walletPass/locales.d.ts +1 -0
  16. package/dist/model/strategy/adapter/walletPass/locales.js +26 -0
  17. package/dist/model/strategy/adapter/walletPass/type.d.ts +169 -0
  18. package/dist/model/strategy/adapter/walletPass/type.js +1 -0
  19. package/dist/model/strategy/adapter/walletPass/utils.d.ts +50 -0
  20. package/dist/model/strategy/adapter/walletPass/utils.js +1064 -0
  21. package/dist/model/strategy/index.d.ts +94 -0
  22. package/dist/model/strategy/index.js +551 -0
  23. package/dist/model/strategy/strategy-example.d.ts +5 -0
  24. package/dist/model/strategy/strategy-example.js +331 -0
  25. package/dist/model/strategy/type.d.ts +228 -0
  26. package/dist/model/strategy/type.js +94 -0
  27. package/dist/modules/Cart/types.d.ts +2 -0
  28. package/dist/modules/Cart/utils/cartProduct.js +11 -0
  29. package/dist/modules/Discount/types.d.ts +16 -0
  30. package/dist/modules/Payment/index.d.ts +2 -1
  31. package/dist/modules/Payment/index.js +10 -7
  32. package/dist/modules/Payment/utils.js +3 -0
  33. package/dist/modules/Payment/walletpass.d.ts +23 -0
  34. package/dist/modules/Payment/walletpass.js +191 -95
  35. package/dist/modules/Product/index.d.ts +1 -1
  36. package/dist/modules/Rules/index.d.ts +9 -5
  37. package/dist/modules/Rules/index.js +545 -129
  38. package/dist/modules/Rules/types.d.ts +1 -0
  39. package/dist/modules/Summary/types.d.ts +2 -0
  40. package/dist/modules/Summary/utils.d.ts +6 -0
  41. package/dist/modules/Summary/utils.js +21 -0
  42. package/dist/plugins/window.d.ts +2 -0
  43. package/dist/solution/BookingByStep/index.d.ts +3 -2
  44. package/dist/solution/BookingTicket/index.d.ts +1 -1
  45. package/dist/solution/Checkout/index.js +3 -1
  46. package/dist/solution/ShopDiscount/index.d.ts +1 -0
  47. package/dist/solution/ShopDiscount/index.js +23 -7
  48. package/dist/solution/ShopDiscount/types.d.ts +1 -0
  49. package/dist/solution/ShopDiscount/types.js +2 -1
  50. package/dist/solution/ShopDiscount/utils.js +26 -12
  51. package/lib/index.d.ts +1 -0
  52. package/lib/index.js +3 -1
  53. package/lib/model/index.d.ts +1 -0
  54. package/lib/model/index.js +23 -0
  55. package/lib/model/strategy/adapter/index.d.ts +3 -0
  56. package/lib/model/strategy/adapter/index.js +45 -0
  57. package/lib/model/strategy/adapter/type.d.ts +28 -0
  58. package/lib/model/strategy/adapter/type.js +17 -0
  59. package/lib/model/strategy/adapter/walletPass/evaluator.d.ts +84 -0
  60. package/lib/model/strategy/adapter/walletPass/evaluator.js +422 -0
  61. package/lib/model/strategy/adapter/walletPass/example.d.ts +4 -0
  62. package/lib/model/strategy/adapter/walletPass/example.js +207 -0
  63. package/lib/model/strategy/adapter/walletPass/index.d.ts +32 -0
  64. package/lib/model/strategy/adapter/walletPass/index.js +142 -0
  65. package/lib/model/strategy/adapter/walletPass/locales.d.ts +1 -0
  66. package/lib/model/strategy/adapter/walletPass/locales.js +54 -0
  67. package/lib/model/strategy/adapter/walletPass/type.d.ts +169 -0
  68. package/lib/model/strategy/adapter/walletPass/type.js +17 -0
  69. package/lib/model/strategy/adapter/walletPass/utils.d.ts +50 -0
  70. package/lib/model/strategy/adapter/walletPass/utils.js +720 -0
  71. package/lib/model/strategy/index.d.ts +94 -0
  72. package/lib/model/strategy/index.js +413 -0
  73. package/lib/model/strategy/strategy-example.d.ts +5 -0
  74. package/lib/model/strategy/strategy-example.js +318 -0
  75. package/lib/model/strategy/type.d.ts +228 -0
  76. package/lib/model/strategy/type.js +44 -0
  77. package/lib/modules/Cart/types.d.ts +2 -0
  78. package/lib/modules/Cart/utils/cartProduct.js +9 -0
  79. package/lib/modules/Discount/types.d.ts +16 -0
  80. package/lib/modules/Payment/index.d.ts +2 -1
  81. package/lib/modules/Payment/index.js +1 -0
  82. package/lib/modules/Payment/utils.js +3 -0
  83. package/lib/modules/Payment/walletpass.d.ts +23 -0
  84. package/lib/modules/Payment/walletpass.js +94 -17
  85. package/lib/modules/Product/index.d.ts +1 -1
  86. package/lib/modules/Rules/index.d.ts +9 -5
  87. package/lib/modules/Rules/index.js +671 -262
  88. package/lib/modules/Rules/types.d.ts +1 -0
  89. package/lib/modules/Summary/types.d.ts +2 -0
  90. package/lib/modules/Summary/utils.d.ts +6 -0
  91. package/lib/modules/Summary/utils.js +15 -0
  92. package/lib/plugins/window.d.ts +2 -0
  93. package/lib/solution/BookingByStep/index.d.ts +3 -2
  94. package/lib/solution/BookingTicket/index.d.ts +1 -1
  95. package/lib/solution/Checkout/index.js +3 -1
  96. package/lib/solution/ShopDiscount/index.d.ts +1 -0
  97. package/lib/solution/ShopDiscount/index.js +22 -8
  98. package/lib/solution/ShopDiscount/types.d.ts +1 -0
  99. package/lib/solution/ShopDiscount/utils.js +10 -6
  100. package/package.json +1 -1
@@ -0,0 +1,422 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/model/strategy/adapter/walletPass/evaluator.ts
30
+ var evaluator_exports = {};
31
+ __export(evaluator_exports, {
32
+ WalletPassEvaluator: () => WalletPassEvaluator
33
+ });
34
+ module.exports = __toCommonJS(evaluator_exports);
35
+ var import__ = require("../../index");
36
+ var import_utils = require("./utils");
37
+ var import_locales = require("./locales");
38
+ var import_decimal = __toESM(require("decimal.js"));
39
+ var defaultStrategyMetadataCustom = {
40
+ maxDeductionAmount: 99999,
41
+ maxUsagePerOrder: 0,
42
+ allowCrossProduct: true,
43
+ applicableProductLimit: 0,
44
+ deductTaxAndFee: true,
45
+ maxPassesPerItem: 0
46
+ };
47
+ var WalletPassEvaluator = class {
48
+ constructor() {
49
+ this.strategyConfigs = [];
50
+ this.locale = "en";
51
+ this.engine = new import__.StrategyEngine({
52
+ debug: false,
53
+ enableTrace: false
54
+ });
55
+ }
56
+ setStrategyConfigs(strategyConfigs) {
57
+ this.strategyConfigs = strategyConfigs;
58
+ }
59
+ getStrategyConfigs() {
60
+ return this.strategyConfigs;
61
+ }
62
+ setLocale(locale) {
63
+ this.locale = locale;
64
+ }
65
+ getText(key) {
66
+ var _a, _b;
67
+ return (_b = (_a = import_locales.locales) == null ? void 0 : _a[this.locale]) == null ? void 0 : _b[key];
68
+ }
69
+ /**
70
+ * 搜索券的格式
71
+ * @param input 输入
72
+ * @returns 返回搜索券的格式
73
+ */
74
+ searchVoucherFormat(input) {
75
+ const results = this.evaluate(input);
76
+ return results.map((item) => {
77
+ var _a, _b;
78
+ if (item.isApplicable) {
79
+ return {
80
+ ...item.voucher,
81
+ config: {
82
+ ...(_a = item == null ? void 0 : item.strategyResult) == null ? void 0 : _a.config.metadata.custom
83
+ }
84
+ };
85
+ } else {
86
+ return {
87
+ ...item.voucher,
88
+ config: {
89
+ ...(_b = item == null ? void 0 : item.strategyResult) == null ? void 0 : _b.config.metadata.custom
90
+ },
91
+ _unified_available_status: 0,
92
+ reason: item.reason,
93
+ reasonCode: item.reasonCode
94
+ };
95
+ }
96
+ });
97
+ }
98
+ /**
99
+ * 评估可用的 vouchers
100
+ */
101
+ evaluate(input) {
102
+ var _a, _b;
103
+ const { orderTotalAmount, products, vouchers, strategyConfigs } = input;
104
+ const productIds = products.map((p) => p.product_id);
105
+ const results = [];
106
+ for (const voucher of vouchers) {
107
+ const applicableStrategies = this.findApplicableStrategies(
108
+ voucher,
109
+ strategyConfigs || this.strategyConfigs
110
+ );
111
+ if (applicableStrategies.length === 0) {
112
+ results.push({
113
+ voucher,
114
+ isApplicable: true,
115
+ canUseCount: 0,
116
+ maxDeduction: 0,
117
+ deductTaxAndFee: true,
118
+ applicableProductIds: [],
119
+ reason: "",
120
+ reasonCode: "",
121
+ strategyResult: {
122
+ config: {
123
+ metadata: {
124
+ custom: {
125
+ ...defaultStrategyMetadataCustom
126
+ }
127
+ }
128
+ }
129
+ }
130
+ });
131
+ continue;
132
+ }
133
+ const strategy = applicableStrategies[0];
134
+ const applicableProductIds = (0, import_utils.getApplicableProductIds)(voucher);
135
+ const { applicableTotal, applicableCount } = this.calculateApplicableProducts(
136
+ products,
137
+ applicableProductIds,
138
+ ((_b = (_a = strategy == null ? void 0 : strategy.metadata) == null ? void 0 : _a.custom) == null ? void 0 : _b.deductTaxAndFee) ?? true
139
+ );
140
+ const context = {
141
+ entities: {
142
+ voucher,
143
+ products,
144
+ order: {
145
+ orderTotalAmount,
146
+ products
147
+ }
148
+ },
149
+ attributes: {
150
+ orderTotalAmount,
151
+ applicableProductTotalAmount: applicableTotal,
152
+ applicableProductCount: applicableCount,
153
+ voucherProductId: voucher.product_id,
154
+ productIds
155
+ },
156
+ metadata: {
157
+ timestamp: Date.now()
158
+ }
159
+ };
160
+ const evaluationResult = this.engine.evaluate(strategy, context);
161
+ const businessConfig = strategy.metadata.custom || {};
162
+ const maxDeduction = businessConfig.maxDeductionAmount || 0;
163
+ const canUseCount = businessConfig.maxUsagePerOrder || 0;
164
+ const deductTaxAndFee = businessConfig.deductTaxAndFee ?? true;
165
+ if (evaluationResult.applicable) {
166
+ results.push({
167
+ voucher,
168
+ isApplicable: true,
169
+ canUseCount,
170
+ maxDeduction,
171
+ deductTaxAndFee,
172
+ applicableProductIds: applicableProductIds || [],
173
+ strategyResult: evaluationResult
174
+ });
175
+ } else {
176
+ let reasonCode = "not_meet_the_required_conditions";
177
+ if (evaluationResult.code) {
178
+ const codeMapping = {
179
+ INSUFFICIENT_AMOUNT: "not_meet_the_required_conditions",
180
+ USAGE_LIMIT_EXCEEDED: "usage_limit_reached",
181
+ CHANNEL_NOT_ALLOWED: "not_available_for_this_channel",
182
+ ORDER_TYPE_NOT_ALLOWED: "not_valid_for_this_order_type",
183
+ DEDUCTION_LIMIT_EXCEEDED: "exceeds_the_maximum_deduction_limit"
184
+ };
185
+ reasonCode = codeMapping[evaluationResult.code] || "not_meet_the_required_conditions";
186
+ }
187
+ results.push({
188
+ voucher,
189
+ isApplicable: false,
190
+ canUseCount: 0,
191
+ maxDeduction: 0,
192
+ deductTaxAndFee: false,
193
+ applicableProductIds: [],
194
+ reason: this.getText(reasonCode),
195
+ reasonCode,
196
+ strategyResult: evaluationResult
197
+ });
198
+ }
199
+ }
200
+ return results;
201
+ }
202
+ /** 检查代金券/折扣卡是否可用 并返回config */
203
+ checkVoucherAvailability(input) {
204
+ var _a, _b, _c, _d, _e;
205
+ const { orderTotalAmount, products, vouchers } = input;
206
+ const results = this.evaluate(input);
207
+ const isAvailable = ((_a = results[0]) == null ? void 0 : _a.isApplicable) || false;
208
+ return {
209
+ isAvailable,
210
+ config: {
211
+ ...(_e = (_d = (_c = (_b = results[0]) == null ? void 0 : _b.strategyResult) == null ? void 0 : _c.config) == null ? void 0 : _d.metadata) == null ? void 0 : _e.custom
212
+ }
213
+ };
214
+ }
215
+ /**
216
+ * 获取推荐券
217
+ * @param input 输入
218
+ * @returns 返回推荐券列表
219
+ */
220
+ getRecommendedVouchers(input) {
221
+ const { orderTotalAmount, products, vouchers } = input;
222
+ const noApplicableVoucher = [];
223
+ const applicableVoucher = [];
224
+ vouchers.forEach((voucher) => {
225
+ if (voucher.unified_available_status === 1) {
226
+ applicableVoucher.push(voucher);
227
+ } else {
228
+ noApplicableVoucher.push(voucher);
229
+ }
230
+ });
231
+ const results = this.evaluate({
232
+ ...input,
233
+ vouchers: applicableVoucher
234
+ });
235
+ const newVouchers = [];
236
+ results.forEach((item) => {
237
+ var _a, _b, _c;
238
+ if (item.isApplicable) {
239
+ newVouchers.push({
240
+ ...item.voucher,
241
+ config: {
242
+ ...defaultStrategyMetadataCustom,
243
+ ...((_c = (_b = (_a = item == null ? void 0 : item.strategyResult) == null ? void 0 : _a.config) == null ? void 0 : _b.metadata) == null ? void 0 : _c.custom) || {}
244
+ }
245
+ });
246
+ } else {
247
+ noApplicableVoucher.push({
248
+ ...item.voucher,
249
+ _unified_available_status: 0,
250
+ reason: item.reason,
251
+ reasonCode: item.reasonCode
252
+ });
253
+ }
254
+ });
255
+ const { recommended, transformList } = this.processVouchers(
256
+ newVouchers,
257
+ orderTotalAmount,
258
+ products
259
+ );
260
+ const recommendedAmount = recommended.reduce((sum, item) => {
261
+ return new import_decimal.default(sum).add(item._available_max_amount || 0).toNumber();
262
+ }, 0);
263
+ return {
264
+ // 推荐券总金额
265
+ recommendedAmount,
266
+ // 推荐券列表
267
+ recommended,
268
+ // 格式化后的可用券列表
269
+ transformList,
270
+ // 后端不可用券列表 和前端基于策略返回的 不可用列表 合并
271
+ noApplicableVoucher
272
+ };
273
+ }
274
+ enhanceWithReason(voucher) {
275
+ if (voucher._unified_available_status === 0 && voucher.reasonCode) {
276
+ return {
277
+ ...voucher,
278
+ reason: this.getText(voucher.reasonCode)
279
+ };
280
+ }
281
+ return voucher;
282
+ }
283
+ /**
284
+ * 优惠券处理函数
285
+ * @param applicableVouchers 可用的券列表
286
+ * @param orderTotalAmount 订单总金额
287
+ * @param products 订单商品列表
288
+ * @returns 返回推荐券列表和全部列表,每个券包含 _available_max_amount 和 _unified_available_status
289
+ */
290
+ processVouchers(vouchers, orderTotalAmount, products) {
291
+ const result = (0, import_utils.processVouchers)(vouchers, orderTotalAmount, products);
292
+ return {
293
+ recommended: result.recommended.map(
294
+ (item) => this.enhanceWithReason(item)
295
+ ),
296
+ transformList: result.transformList.map(
297
+ (item) => this.enhanceWithReason(item)
298
+ )
299
+ };
300
+ }
301
+ /**
302
+ * 重新计算优惠券状态(基于已选券的增量计算)
303
+ * @param allVouchers 所有原始券列表
304
+ * @param selectedVouchers 已选中的券列表(按选中顺序)
305
+ * @param orderTotalAmount 订单总金额
306
+ * @param products 订单商品列表
307
+ * @returns 返回更新后的所有券列表和已选券的详细抵扣信息
308
+ */
309
+ recalculateVouchers(allVouchers, selectedVouchers, orderTotalAmount, products) {
310
+ const result = (0, import_utils.recalculateVouchers)(
311
+ allVouchers,
312
+ selectedVouchers,
313
+ orderTotalAmount,
314
+ products
315
+ );
316
+ return {
317
+ allWithUpdatedStatus: result.allWithUpdatedStatus.map(
318
+ (item) => this.enhanceWithReason(item)
319
+ ),
320
+ selectedWithDetails: result.selectedWithDetails.map(
321
+ (item) => this.enhanceWithReason(item)
322
+ )
323
+ };
324
+ }
325
+ /**
326
+ * 查找适用于指定 voucher 的策略配置
327
+ */
328
+ findApplicableStrategies(voucher, strategyConfigs) {
329
+ return strategyConfigs.filter((config) => {
330
+ return this.checkVoucherInStrategy(voucher.product_id, config);
331
+ });
332
+ }
333
+ /**
334
+ * 检查策略中是否包含指定的 voucher ID
335
+ */
336
+ checkVoucherInStrategy(voucherProductId, config) {
337
+ const rules = config.conditions.rules;
338
+ for (const rule of rules) {
339
+ if ("operator" in rule && "rules" in rule) {
340
+ if (this.checkVoucherInConditionGroup(voucherProductId, rule)) {
341
+ return true;
342
+ }
343
+ } else {
344
+ const conditionRule = rule;
345
+ if (conditionRule.field === "voucherProductId" && conditionRule.operator === "in" && Array.isArray(conditionRule.value)) {
346
+ if (conditionRule.value.includes(voucherProductId)) {
347
+ return true;
348
+ }
349
+ }
350
+ if (conditionRule.field === "voucherProductId" && (conditionRule.operator === "=" || conditionRule.operator === "==")) {
351
+ if (conditionRule.value === voucherProductId) {
352
+ return true;
353
+ }
354
+ }
355
+ }
356
+ }
357
+ return false;
358
+ }
359
+ /**
360
+ * 递归检查条件组中是否包含 voucher ID
361
+ */
362
+ checkVoucherInConditionGroup(voucherProductId, group) {
363
+ for (const rule of group.rules) {
364
+ if ("operator" in rule && "rules" in rule) {
365
+ if (this.checkVoucherInConditionGroup(voucherProductId, rule)) {
366
+ return true;
367
+ }
368
+ } else {
369
+ if (rule.field === "voucherProductId" && rule.operator === "in" && Array.isArray(rule.value)) {
370
+ if (rule.value.includes(voucherProductId)) {
371
+ return true;
372
+ }
373
+ }
374
+ if (rule.field === "voucherProductId" && (rule.operator === "=" || rule.operator === "==")) {
375
+ if (rule.value === voucherProductId) {
376
+ return true;
377
+ }
378
+ }
379
+ }
380
+ }
381
+ return false;
382
+ }
383
+ /**
384
+ * 计算适用商品的总金额和数量
385
+ */
386
+ calculateApplicableProducts(products, applicableProductIds, deductTaxAndFee) {
387
+ let total = 0;
388
+ let count = 0;
389
+ if (applicableProductIds !== null && applicableProductIds.length === 0) {
390
+ return { applicableTotal: 0, applicableCount: 0 };
391
+ }
392
+ products.forEach((product) => {
393
+ const productQuantity = (0, import_utils.getProductQuantity)(product);
394
+ const isMainProductApplicable = applicableProductIds === null || applicableProductIds.includes(product.product_id);
395
+ if (isMainProductApplicable) {
396
+ total += (0, import_utils.getMainProductPrice)(product, deductTaxAndFee) * productQuantity;
397
+ count += productQuantity;
398
+ }
399
+ if (product.product_bundle && product.product_bundle.length > 0) {
400
+ product.product_bundle.forEach((bundleItem) => {
401
+ if ((0, import_utils.getBundleItemIsOriginalPrice)(bundleItem)) {
402
+ const isBundleItemApplicable = applicableProductIds === null || applicableProductIds.includes(bundleItem.bundle_product_id);
403
+ if (isBundleItemApplicable) {
404
+ const bundleItemQuantity = bundleItem.num * productQuantity;
405
+ total += (0, import_utils.getBundleItemPrice)(
406
+ bundleItem,
407
+ productQuantity,
408
+ deductTaxAndFee
409
+ );
410
+ count += bundleItemQuantity;
411
+ }
412
+ }
413
+ });
414
+ }
415
+ });
416
+ return { applicableTotal: total, applicableCount: count };
417
+ }
418
+ };
419
+ // Annotate the CommonJS export names for ESM import in node:
420
+ 0 && (module.exports = {
421
+ WalletPassEvaluator
422
+ });
@@ -0,0 +1,4 @@
1
+ /**
2
+ * WalletPass 评估器使用示例
3
+ */
4
+ export {};
@@ -0,0 +1,207 @@
1
+ // src/model/strategy/adapter/walletPass/example.ts
2
+ var import_evaluator = require("./evaluator");
3
+ var products = [
4
+ {
5
+ product_id: 60734,
6
+ price: 80,
7
+ quantity: 1,
8
+ name: "商品A"
9
+ },
10
+ {
11
+ product_id: 60735,
12
+ price: 50,
13
+ quantity: 2,
14
+ name: "商品B"
15
+ }
16
+ ];
17
+ var vouchers = [
18
+ {
19
+ id: "VOUCHER_001",
20
+ amount: 10,
21
+ balance: 10,
22
+ type: "cash_voucher"
23
+ },
24
+ {
25
+ id: "VOUCHER_002",
26
+ amount: 20,
27
+ balance: 20,
28
+ type: "cash_voucher"
29
+ },
30
+ {
31
+ id: "VOUCHER_003",
32
+ amount: 50,
33
+ balance: 50,
34
+ type: "cash_voucher"
35
+ }
36
+ ];
37
+ var strategyConfigs = [
38
+ // 策略1: 满100减10,适用于 VOUCHER_001
39
+ {
40
+ metadata: {
41
+ id: "STRATEGY_001",
42
+ name: "满100减10",
43
+ type: "wallet_pass",
44
+ custom: {
45
+ maxDeductionAmount: 10,
46
+ // 最大抵扣10元
47
+ maxUsagePerOrder: 1,
48
+ // 每单最多用1张
49
+ deductTaxAndFee: true,
50
+ // 抵扣税费
51
+ applicableProductIds: [60734, 60735]
52
+ // 适用于这两个商品
53
+ }
54
+ },
55
+ conditions: {
56
+ operator: "and",
57
+ rules: [
58
+ // 匹配 voucher ID
59
+ {
60
+ type: "operator",
61
+ field: "voucherId",
62
+ operator: "in",
63
+ value: ["VOUCHER_001"]
64
+ },
65
+ // 适用商品总额需 >= 100
66
+ {
67
+ type: "operator",
68
+ field: "applicableProductTotal",
69
+ operator: ">=",
70
+ value: 100
71
+ }
72
+ ],
73
+ actionIds: ["deduct_10"]
74
+ },
75
+ actions: [
76
+ {
77
+ id: "deduct_10",
78
+ type: "DEDUCT_AMOUNT",
79
+ value: 10,
80
+ target: "applicable_products",
81
+ priority: 1
82
+ }
83
+ ]
84
+ },
85
+ // 策略2: 满150减20,适用于 VOUCHER_002
86
+ {
87
+ metadata: {
88
+ id: "STRATEGY_002",
89
+ name: "满150减20",
90
+ type: "wallet_pass",
91
+ custom: {
92
+ maxDeductionAmount: 20,
93
+ maxUsagePerOrder: 1,
94
+ deductTaxAndFee: true,
95
+ applicableProductIds: [60734, 60735]
96
+ }
97
+ },
98
+ conditions: {
99
+ operator: "and",
100
+ rules: [
101
+ {
102
+ type: "operator",
103
+ field: "voucherId",
104
+ operator: "in",
105
+ value: ["VOUCHER_002"]
106
+ },
107
+ {
108
+ type: "operator",
109
+ field: "applicableProductTotal",
110
+ operator: ">=",
111
+ value: 150
112
+ }
113
+ ],
114
+ actionIds: ["deduct_20"]
115
+ },
116
+ actions: [
117
+ {
118
+ id: "deduct_20",
119
+ type: "DEDUCT_AMOUNT",
120
+ value: 20,
121
+ target: "applicable_products",
122
+ priority: 1
123
+ }
124
+ ]
125
+ },
126
+ // 策略3: 满200减50,适用于 VOUCHER_003
127
+ {
128
+ metadata: {
129
+ id: "STRATEGY_003",
130
+ name: "满200减50",
131
+ type: "wallet_pass",
132
+ custom: {
133
+ maxDeductionAmount: 50,
134
+ maxUsagePerOrder: 2,
135
+ deductTaxAndFee: false,
136
+ applicableProductIds: [60734, 60735]
137
+ }
138
+ },
139
+ conditions: {
140
+ operator: "and",
141
+ rules: [
142
+ {
143
+ type: "operator",
144
+ field: "voucherId",
145
+ operator: "in",
146
+ value: ["VOUCHER_003"]
147
+ },
148
+ {
149
+ type: "operator",
150
+ field: "applicableProductTotal",
151
+ operator: ">=",
152
+ value: 200
153
+ }
154
+ ],
155
+ actionIds: ["deduct_50"]
156
+ },
157
+ actions: [
158
+ {
159
+ id: "deduct_50",
160
+ type: "DEDUCT_AMOUNT",
161
+ value: 50,
162
+ target: "applicable_products",
163
+ priority: 1
164
+ }
165
+ ]
166
+ }
167
+ ];
168
+ function runExample() {
169
+ console.log("========== WalletPass 评估器示例 ==========\n");
170
+ const evaluator = new import_evaluator.WalletPassEvaluator();
171
+ const results = evaluator.evaluate({
172
+ orderTotalAmount: 180,
173
+ products,
174
+ vouchers,
175
+ strategyConfigs
176
+ });
177
+ console.log("订单信息:");
178
+ console.log(`- 总金额: ${180} 元`);
179
+ console.log(`- 商品: ${products.map((p) => `${p.name}(${p.quantity}件)`).join(", ")}
180
+ `);
181
+ console.log("评估结果:\n");
182
+ results.forEach((result, index) => {
183
+ console.log(`Voucher ${index + 1}: ${result.voucher.id}`);
184
+ console.log(` 面额: ${result.voucher.amount} 元`);
185
+ console.log(` 可用: ${result.isApplicable ? "✅ 是" : "❌ 否"}`);
186
+ if (result.isApplicable) {
187
+ console.log(` 最大抵扣: ${result.maxDeduction} 元`);
188
+ console.log(` 每单可用: ${result.canUseCount} 张`);
189
+ console.log(` 抵扣税费: ${result.deductTaxAndFee ? "是" : "否"}`);
190
+ console.log(` 适用商品: ${result.applicableProductIds.join(", ")}`);
191
+ } else {
192
+ console.log(` 原因: ${result.reason}`);
193
+ console.log(` 原因码: ${result.reasonCode}`);
194
+ }
195
+ console.log("");
196
+ });
197
+ const availableVouchers = results.filter((r) => r.isApplicable);
198
+ console.log(`
199
+ 共 ${availableVouchers.length} 张可用`);
200
+ if (availableVouchers.length > 0) {
201
+ console.log("可用 voucher ID:");
202
+ availableVouchers.forEach((v) => {
203
+ console.log(` - ${v.voucher.id}: 最多抵扣 ${v.maxDeduction} 元`);
204
+ });
205
+ }
206
+ }
207
+ runExample();
@@ -0,0 +1,32 @@
1
+ import { EvaluationResult, RuntimeContext } from '../../type';
2
+ import { BusinessAdapter } from '../type';
3
+ import { WalletPassBusinessData, WalletPassTransformResult } from './type';
4
+ /**
5
+ * Wallet Pass 适配器
6
+ * 用于将 wallet pass 业务数据转换为策略引擎可识别的格式
7
+ */
8
+ export default class WalletPassAdapter implements BusinessAdapter {
9
+ name: string;
10
+ version: string;
11
+ /**
12
+ * 准备运行时上下文
13
+ * 将业务数据转换为策略引擎可识别的 RuntimeContext
14
+ */
15
+ prepareContext(businessData: WalletPassBusinessData): RuntimeContext;
16
+ /**
17
+ * 转换执行结果
18
+ * 将策略引擎的通用结果转换为业务层需要的格式
19
+ */
20
+ transformResult(result: EvaluationResult, businessData?: WalletPassBusinessData): WalletPassTransformResult;
21
+ /**
22
+ * 格式化配置
23
+ */
24
+ formatConfig(result: EvaluationResult, businessData?: WalletPassBusinessData): {
25
+ result: EvaluationResult;
26
+ businessData?: WalletPassBusinessData;
27
+ };
28
+ /**
29
+ * 计算适用商品的总金额和数量
30
+ */
31
+ private calculateApplicableProducts;
32
+ }