@pisell/pisellos 2.2.36 → 2.2.38

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 (105) 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 +497 -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 +23 -0
  17. package/dist/model/strategy/adapter/walletPass/type.d.ts +165 -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 +965 -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 +15 -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/types.d.ts +3 -1
  33. package/dist/modules/Payment/types.js +1 -0
  34. package/dist/modules/Payment/utils.js +3 -0
  35. package/dist/modules/Payment/walletpass.d.ts +23 -0
  36. package/dist/modules/Payment/walletpass.js +191 -95
  37. package/dist/modules/Product/index.d.ts +1 -1
  38. package/dist/modules/Rules/index.d.ts +8 -3
  39. package/dist/modules/Rules/index.js +143 -23
  40. package/dist/modules/Rules/types.d.ts +1 -0
  41. package/dist/modules/Summary/types.d.ts +2 -0
  42. package/dist/modules/Summary/utils.d.ts +6 -0
  43. package/dist/modules/Summary/utils.js +21 -0
  44. package/dist/plugins/window.d.ts +2 -0
  45. package/dist/solution/BookingByStep/index.d.ts +2 -1
  46. package/dist/solution/BookingTicket/index.d.ts +1 -1
  47. package/dist/solution/Checkout/index.d.ts +3 -1
  48. package/dist/solution/Checkout/index.js +663 -257
  49. package/dist/solution/Checkout/types.d.ts +1 -1
  50. package/dist/solution/ShopDiscount/index.d.ts +1 -0
  51. package/dist/solution/ShopDiscount/index.js +13 -3
  52. package/dist/solution/ShopDiscount/types.d.ts +1 -0
  53. package/lib/index.d.ts +1 -0
  54. package/lib/index.js +3 -1
  55. package/lib/model/index.d.ts +1 -0
  56. package/lib/model/index.js +23 -0
  57. package/lib/model/strategy/adapter/index.d.ts +3 -0
  58. package/lib/model/strategy/adapter/index.js +45 -0
  59. package/lib/model/strategy/adapter/type.d.ts +28 -0
  60. package/lib/model/strategy/adapter/type.js +17 -0
  61. package/lib/model/strategy/adapter/walletPass/evaluator.d.ts +84 -0
  62. package/lib/model/strategy/adapter/walletPass/evaluator.js +421 -0
  63. package/lib/model/strategy/adapter/walletPass/example.d.ts +4 -0
  64. package/lib/model/strategy/adapter/walletPass/example.js +207 -0
  65. package/lib/model/strategy/adapter/walletPass/index.d.ts +32 -0
  66. package/lib/model/strategy/adapter/walletPass/index.js +142 -0
  67. package/lib/model/strategy/adapter/walletPass/locales.d.ts +1 -0
  68. package/lib/model/strategy/adapter/walletPass/locales.js +51 -0
  69. package/lib/model/strategy/adapter/walletPass/type.d.ts +165 -0
  70. package/lib/model/strategy/adapter/walletPass/type.js +17 -0
  71. package/lib/model/strategy/adapter/walletPass/utils.d.ts +50 -0
  72. package/lib/model/strategy/adapter/walletPass/utils.js +660 -0
  73. package/lib/model/strategy/index.d.ts +94 -0
  74. package/lib/model/strategy/index.js +413 -0
  75. package/lib/model/strategy/strategy-example.d.ts +5 -0
  76. package/lib/model/strategy/strategy-example.js +318 -0
  77. package/lib/model/strategy/type.d.ts +228 -0
  78. package/lib/model/strategy/type.js +44 -0
  79. package/lib/modules/Cart/types.d.ts +2 -0
  80. package/lib/modules/Cart/utils/cartProduct.js +9 -0
  81. package/lib/modules/Discount/types.d.ts +15 -0
  82. package/lib/modules/Payment/index.d.ts +2 -1
  83. package/lib/modules/Payment/index.js +1 -0
  84. package/lib/modules/Payment/types.d.ts +3 -1
  85. package/lib/modules/Payment/types.js +1 -0
  86. package/lib/modules/Payment/utils.js +3 -0
  87. package/lib/modules/Payment/walletpass.d.ts +23 -0
  88. package/lib/modules/Payment/walletpass.js +94 -17
  89. package/lib/modules/Product/index.d.ts +1 -1
  90. package/lib/modules/Rules/index.d.ts +8 -3
  91. package/lib/modules/Rules/index.js +352 -187
  92. package/lib/modules/Rules/types.d.ts +1 -0
  93. package/lib/modules/Summary/types.d.ts +2 -0
  94. package/lib/modules/Summary/utils.d.ts +6 -0
  95. package/lib/modules/Summary/utils.js +15 -0
  96. package/lib/plugins/window.d.ts +2 -0
  97. package/lib/solution/BookingByStep/index.d.ts +2 -1
  98. package/lib/solution/BookingTicket/index.d.ts +1 -1
  99. package/lib/solution/Checkout/index.d.ts +3 -1
  100. package/lib/solution/Checkout/index.js +282 -10
  101. package/lib/solution/Checkout/types.d.ts +1 -1
  102. package/lib/solution/ShopDiscount/index.d.ts +1 -0
  103. package/lib/solution/ShopDiscount/index.js +8 -2
  104. package/lib/solution/ShopDiscount/types.d.ts +1 -0
  105. package/package.json +1 -1
@@ -0,0 +1,421 @@
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
+ };
46
+ var WalletPassEvaluator = class {
47
+ constructor() {
48
+ this.strategyConfigs = [];
49
+ this.locale = "en";
50
+ this.engine = new import__.StrategyEngine({
51
+ debug: false,
52
+ enableTrace: false
53
+ });
54
+ }
55
+ setStrategyConfigs(strategyConfigs) {
56
+ this.strategyConfigs = strategyConfigs;
57
+ }
58
+ getStrategyConfigs() {
59
+ return this.strategyConfigs;
60
+ }
61
+ setLocale(locale) {
62
+ this.locale = locale;
63
+ }
64
+ getText(key) {
65
+ var _a, _b;
66
+ return (_b = (_a = import_locales.locales) == null ? void 0 : _a[this.locale]) == null ? void 0 : _b[key];
67
+ }
68
+ /**
69
+ * 搜索券的格式
70
+ * @param input 输入
71
+ * @returns 返回搜索券的格式
72
+ */
73
+ searchVoucherFormat(input) {
74
+ const results = this.evaluate(input);
75
+ return results.map((item) => {
76
+ var _a, _b;
77
+ if (item.isApplicable) {
78
+ return {
79
+ ...item.voucher,
80
+ config: {
81
+ ...(_a = item == null ? void 0 : item.strategyResult) == null ? void 0 : _a.config.metadata.custom
82
+ }
83
+ };
84
+ } else {
85
+ return {
86
+ ...item.voucher,
87
+ config: {
88
+ ...(_b = item == null ? void 0 : item.strategyResult) == null ? void 0 : _b.config.metadata.custom
89
+ },
90
+ _unified_available_status: 0,
91
+ reason: item.reason,
92
+ reasonCode: item.reasonCode
93
+ };
94
+ }
95
+ });
96
+ }
97
+ /**
98
+ * 评估可用的 vouchers
99
+ */
100
+ evaluate(input) {
101
+ var _a, _b;
102
+ const { orderTotalAmount, products, vouchers, strategyConfigs } = input;
103
+ const productIds = products.map((p) => p.product_id);
104
+ const results = [];
105
+ for (const voucher of vouchers) {
106
+ const applicableStrategies = this.findApplicableStrategies(
107
+ voucher,
108
+ strategyConfigs || this.strategyConfigs
109
+ );
110
+ if (applicableStrategies.length === 0) {
111
+ results.push({
112
+ voucher,
113
+ isApplicable: true,
114
+ canUseCount: 0,
115
+ maxDeduction: 0,
116
+ deductTaxAndFee: true,
117
+ applicableProductIds: [],
118
+ reason: "",
119
+ reasonCode: "",
120
+ strategyResult: {
121
+ config: {
122
+ metadata: {
123
+ custom: {
124
+ ...defaultStrategyMetadataCustom
125
+ }
126
+ }
127
+ }
128
+ }
129
+ });
130
+ continue;
131
+ }
132
+ const strategy = applicableStrategies[0];
133
+ const applicableProductIds = (0, import_utils.getApplicableProductIds)(voucher);
134
+ const { applicableTotal, applicableCount } = this.calculateApplicableProducts(
135
+ products,
136
+ applicableProductIds,
137
+ ((_b = (_a = strategy == null ? void 0 : strategy.metadata) == null ? void 0 : _a.custom) == null ? void 0 : _b.deductTaxAndFee) ?? true
138
+ );
139
+ const context = {
140
+ entities: {
141
+ voucher,
142
+ products,
143
+ order: {
144
+ orderTotalAmount,
145
+ products
146
+ }
147
+ },
148
+ attributes: {
149
+ orderTotalAmount,
150
+ applicableProductTotalAmount: applicableTotal,
151
+ applicableProductCount: applicableCount,
152
+ voucherProductId: voucher.product_id,
153
+ productIds
154
+ },
155
+ metadata: {
156
+ timestamp: Date.now()
157
+ }
158
+ };
159
+ const evaluationResult = this.engine.evaluate(strategy, context);
160
+ const businessConfig = strategy.metadata.custom || {};
161
+ const maxDeduction = businessConfig.maxDeductionAmount || 0;
162
+ const canUseCount = businessConfig.maxUsagePerOrder || 0;
163
+ const deductTaxAndFee = businessConfig.deductTaxAndFee ?? true;
164
+ if (evaluationResult.applicable) {
165
+ results.push({
166
+ voucher,
167
+ isApplicable: true,
168
+ canUseCount,
169
+ maxDeduction,
170
+ deductTaxAndFee,
171
+ applicableProductIds: applicableProductIds || [],
172
+ strategyResult: evaluationResult
173
+ });
174
+ } else {
175
+ let reasonCode = "not_meet_the_required_conditions";
176
+ if (evaluationResult.code) {
177
+ const codeMapping = {
178
+ INSUFFICIENT_AMOUNT: "not_meet_the_required_conditions",
179
+ USAGE_LIMIT_EXCEEDED: "usage_limit_reached",
180
+ CHANNEL_NOT_ALLOWED: "not_available_for_this_channel",
181
+ ORDER_TYPE_NOT_ALLOWED: "not_valid_for_this_order_type",
182
+ DEDUCTION_LIMIT_EXCEEDED: "exceeds_the_maximum_deduction_limit"
183
+ };
184
+ reasonCode = codeMapping[evaluationResult.code] || "not_meet_the_required_conditions";
185
+ }
186
+ results.push({
187
+ voucher,
188
+ isApplicable: false,
189
+ canUseCount: 0,
190
+ maxDeduction: 0,
191
+ deductTaxAndFee: false,
192
+ applicableProductIds: [],
193
+ reason: this.getText(reasonCode),
194
+ reasonCode,
195
+ strategyResult: evaluationResult
196
+ });
197
+ }
198
+ }
199
+ return results;
200
+ }
201
+ /** 检查代金券/折扣卡是否可用 并返回config */
202
+ checkVoucherAvailability(input) {
203
+ var _a, _b, _c, _d, _e;
204
+ const { orderTotalAmount, products, vouchers } = input;
205
+ const results = this.evaluate(input);
206
+ const isAvailable = ((_a = results[0]) == null ? void 0 : _a.isApplicable) || false;
207
+ return {
208
+ isAvailable,
209
+ config: {
210
+ ...(_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
211
+ }
212
+ };
213
+ }
214
+ /**
215
+ * 获取推荐券
216
+ * @param input 输入
217
+ * @returns 返回推荐券列表
218
+ */
219
+ getRecommendedVouchers(input) {
220
+ const { orderTotalAmount, products, vouchers } = input;
221
+ const noApplicableVoucher = [];
222
+ const applicableVoucher = [];
223
+ vouchers.forEach((voucher) => {
224
+ if (voucher.unified_available_status === 1) {
225
+ applicableVoucher.push(voucher);
226
+ } else {
227
+ noApplicableVoucher.push(voucher);
228
+ }
229
+ });
230
+ const results = this.evaluate({
231
+ ...input,
232
+ vouchers: applicableVoucher
233
+ });
234
+ const newVouchers = [];
235
+ results.forEach((item) => {
236
+ var _a, _b, _c;
237
+ if (item.isApplicable) {
238
+ newVouchers.push({
239
+ ...item.voucher,
240
+ config: {
241
+ ...defaultStrategyMetadataCustom,
242
+ ...((_c = (_b = (_a = item == null ? void 0 : item.strategyResult) == null ? void 0 : _a.config) == null ? void 0 : _b.metadata) == null ? void 0 : _c.custom) || {}
243
+ }
244
+ });
245
+ } else {
246
+ noApplicableVoucher.push({
247
+ ...item.voucher,
248
+ _unified_available_status: 0,
249
+ reason: item.reason,
250
+ reasonCode: item.reasonCode
251
+ });
252
+ }
253
+ });
254
+ const { recommended, transformList } = this.processVouchers(
255
+ newVouchers,
256
+ orderTotalAmount,
257
+ products
258
+ );
259
+ const recommendedAmount = recommended.reduce((sum, item) => {
260
+ return new import_decimal.default(sum).add(item._available_max_amount || 0).toNumber();
261
+ }, 0);
262
+ return {
263
+ // 推荐券总金额
264
+ recommendedAmount,
265
+ // 推荐券列表
266
+ recommended,
267
+ // 格式化后的可用券列表
268
+ transformList,
269
+ // 后端不可用券列表 和前端基于策略返回的 不可用列表 合并
270
+ noApplicableVoucher
271
+ };
272
+ }
273
+ enhanceWithReason(voucher) {
274
+ if (voucher._unified_available_status === 0 && voucher.reasonCode) {
275
+ return {
276
+ ...voucher,
277
+ reason: this.getText(voucher.reasonCode)
278
+ };
279
+ }
280
+ return voucher;
281
+ }
282
+ /**
283
+ * 优惠券处理函数
284
+ * @param applicableVouchers 可用的券列表
285
+ * @param orderTotalAmount 订单总金额
286
+ * @param products 订单商品列表
287
+ * @returns 返回推荐券列表和全部列表,每个券包含 _available_max_amount 和 _unified_available_status
288
+ */
289
+ processVouchers(vouchers, orderTotalAmount, products) {
290
+ const result = (0, import_utils.processVouchers)(vouchers, orderTotalAmount, products);
291
+ return {
292
+ recommended: result.recommended.map(
293
+ (item) => this.enhanceWithReason(item)
294
+ ),
295
+ transformList: result.transformList.map(
296
+ (item) => this.enhanceWithReason(item)
297
+ )
298
+ };
299
+ }
300
+ /**
301
+ * 重新计算优惠券状态(基于已选券的增量计算)
302
+ * @param allVouchers 所有原始券列表
303
+ * @param selectedVouchers 已选中的券列表(按选中顺序)
304
+ * @param orderTotalAmount 订单总金额
305
+ * @param products 订单商品列表
306
+ * @returns 返回更新后的所有券列表和已选券的详细抵扣信息
307
+ */
308
+ recalculateVouchers(allVouchers, selectedVouchers, orderTotalAmount, products) {
309
+ const result = (0, import_utils.recalculateVouchers)(
310
+ allVouchers,
311
+ selectedVouchers,
312
+ orderTotalAmount,
313
+ products
314
+ );
315
+ return {
316
+ allWithUpdatedStatus: result.allWithUpdatedStatus.map(
317
+ (item) => this.enhanceWithReason(item)
318
+ ),
319
+ selectedWithDetails: result.selectedWithDetails.map(
320
+ (item) => this.enhanceWithReason(item)
321
+ )
322
+ };
323
+ }
324
+ /**
325
+ * 查找适用于指定 voucher 的策略配置
326
+ */
327
+ findApplicableStrategies(voucher, strategyConfigs) {
328
+ return strategyConfigs.filter((config) => {
329
+ return this.checkVoucherInStrategy(voucher.product_id, config);
330
+ });
331
+ }
332
+ /**
333
+ * 检查策略中是否包含指定的 voucher ID
334
+ */
335
+ checkVoucherInStrategy(voucherProductId, config) {
336
+ const rules = config.conditions.rules;
337
+ for (const rule of rules) {
338
+ if ("operator" in rule && "rules" in rule) {
339
+ if (this.checkVoucherInConditionGroup(voucherProductId, rule)) {
340
+ return true;
341
+ }
342
+ } else {
343
+ const conditionRule = rule;
344
+ if (conditionRule.field === "voucherProductId" && conditionRule.operator === "in" && Array.isArray(conditionRule.value)) {
345
+ if (conditionRule.value.includes(voucherProductId)) {
346
+ return true;
347
+ }
348
+ }
349
+ if (conditionRule.field === "voucherProductId" && (conditionRule.operator === "=" || conditionRule.operator === "==")) {
350
+ if (conditionRule.value === voucherProductId) {
351
+ return true;
352
+ }
353
+ }
354
+ }
355
+ }
356
+ return false;
357
+ }
358
+ /**
359
+ * 递归检查条件组中是否包含 voucher ID
360
+ */
361
+ checkVoucherInConditionGroup(voucherProductId, group) {
362
+ for (const rule of group.rules) {
363
+ if ("operator" in rule && "rules" in rule) {
364
+ if (this.checkVoucherInConditionGroup(voucherProductId, rule)) {
365
+ return true;
366
+ }
367
+ } else {
368
+ if (rule.field === "voucherProductId" && rule.operator === "in" && Array.isArray(rule.value)) {
369
+ if (rule.value.includes(voucherProductId)) {
370
+ return true;
371
+ }
372
+ }
373
+ if (rule.field === "voucherProductId" && (rule.operator === "=" || rule.operator === "==")) {
374
+ if (rule.value === voucherProductId) {
375
+ return true;
376
+ }
377
+ }
378
+ }
379
+ }
380
+ return false;
381
+ }
382
+ /**
383
+ * 计算适用商品的总金额和数量
384
+ */
385
+ calculateApplicableProducts(products, applicableProductIds, deductTaxAndFee) {
386
+ let total = 0;
387
+ let count = 0;
388
+ if (applicableProductIds !== null && applicableProductIds.length === 0) {
389
+ return { applicableTotal: 0, applicableCount: 0 };
390
+ }
391
+ products.forEach((product) => {
392
+ const productQuantity = (0, import_utils.getProductQuantity)(product);
393
+ const isMainProductApplicable = applicableProductIds === null || applicableProductIds.includes(product.product_id);
394
+ if (isMainProductApplicable) {
395
+ total += (0, import_utils.getMainProductPrice)(product, deductTaxAndFee) * productQuantity;
396
+ count += productQuantity;
397
+ }
398
+ if (product.product_bundle && product.product_bundle.length > 0) {
399
+ product.product_bundle.forEach((bundleItem) => {
400
+ if ((0, import_utils.getBundleItemIsOriginalPrice)(bundleItem)) {
401
+ const isBundleItemApplicable = applicableProductIds === null || applicableProductIds.includes(bundleItem.bundle_product_id);
402
+ if (isBundleItemApplicable) {
403
+ const bundleItemQuantity = bundleItem.num * productQuantity;
404
+ total += (0, import_utils.getBundleItemPrice)(
405
+ bundleItem,
406
+ productQuantity,
407
+ deductTaxAndFee
408
+ );
409
+ count += bundleItemQuantity;
410
+ }
411
+ }
412
+ });
413
+ }
414
+ });
415
+ return { applicableTotal: total, applicableCount: count };
416
+ }
417
+ };
418
+ // Annotate the CommonJS export names for ESM import in node:
419
+ 0 && (module.exports = {
420
+ WalletPassEvaluator
421
+ });
@@ -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
+ }