@pisell/pisellos 0.0.252 → 0.0.253

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.
@@ -1,4 +1,5 @@
1
- import { CheckoutInitParams, CheckoutError, CheckoutErrorType, CheckoutStatus, CheckoutStep } from '../types';
1
+ import { CheckoutInitParams, CheckoutError, CheckoutErrorType, CheckoutStatus, CheckoutStep, LocalOrderData, CartSummaryItem, ExtractedAmountInfo } from '../types';
2
+ import { CartItem } from '../../../modules/Cart/types';
2
3
  /**
3
4
  * 验证结账数据
4
5
  */
@@ -71,3 +72,46 @@ export declare const logger: {
71
72
  error: (message: string, ...args: any[]) => void;
72
73
  debug: (message: string, ...args: any[]) => void;
73
74
  };
75
+ /**
76
+ * 验证本地订单数据
77
+ */
78
+ export declare function validateLocalOrderData(orderData: LocalOrderData): {
79
+ valid: boolean;
80
+ errors: string[];
81
+ };
82
+ /**
83
+ * 生成本地订单ID
84
+ */
85
+ export declare function generateLocalOrderId(): string;
86
+ /**
87
+ * 格式化日期时间为 YYYY-MM-DD hh:mm:ss 格式
88
+ *
89
+ * @param date 要格式化的日期对象
90
+ * @returns 格式化后的日期时间字符串
91
+ */
92
+ export declare function formatDateTime(date: Date): string;
93
+ /**
94
+ * 从购物车小计数据中提取金额信息
95
+ */
96
+ export declare function extractAmountFromCartSummary(cartSummary: CartSummaryItem[]): ExtractedAmountInfo;
97
+ /**
98
+ * 计算购物车总金额
99
+ */
100
+ export declare function calculateTotalAmount(cartItems: CartItem[]): string;
101
+ /**
102
+ * 判断订单ID是否为本地生成的虚拟ID
103
+ *
104
+ * @param orderId 订单ID
105
+ * @returns true 表示是虚拟ID,false 表示是真实的后端ID
106
+ */
107
+ export declare function isVirtualOrderId(orderId: string): boolean;
108
+ /**
109
+ * 判断支付方式是否需要同步订单到后端
110
+ *
111
+ * 现金支付(CASHMANUAL)和自定义支付不需要同步,其他支付方式需要同步
112
+ *
113
+ * @param paymentCode 支付方式代码
114
+ * @param paymentType 支付方式类型
115
+ * @returns 是否需要同步订单
116
+ */
117
+ export declare function shouldSyncOrderForPayment(paymentCode: string, paymentType: string): boolean;
@@ -3,6 +3,7 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try
3
3
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
4
4
  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); }
5
5
  import { CheckoutStatus, CheckoutStep } from "../types";
6
+ import { PaymentMethodType } from "../../../modules/Payment/types";
6
7
 
7
8
  /**
8
9
  * 验证结账数据
@@ -368,4 +369,181 @@ export var logger = {
368
369
  (_console4 = console).debug.apply(_console4, ["[Checkout] ".concat(message)].concat(args));
369
370
  }
370
371
  }
371
- };
372
+ };
373
+
374
+ // ========== 从 CheckoutImpl 类中移出的纯静态方法 ==========
375
+
376
+ /**
377
+ * 验证本地订单数据
378
+ */
379
+ export function validateLocalOrderData(orderData) {
380
+ var _orderData$relation_p;
381
+ var errors = [];
382
+
383
+ // 验证基本字段
384
+ if (!orderData.type) {
385
+ errors.push('订单类型不能为空');
386
+ }
387
+ if (!orderData.platform) {
388
+ errors.push('平台信息不能为空');
389
+ }
390
+ if ((!orderData.bookings || orderData.bookings.length === 0) && !(orderData !== null && orderData !== void 0 && (_orderData$relation_p = orderData.relation_products) !== null && _orderData$relation_p !== void 0 && _orderData$relation_p.length)) {
391
+ errors.push('预订信息不能为空');
392
+ }
393
+
394
+ // 验证预订信息
395
+ if (orderData.bookings) {
396
+ orderData.bookings.forEach(function (booking, index) {
397
+ if (!booking.product || !booking.product.product_id) {
398
+ errors.push("\u9884\u8BA2\u9879 ".concat(index + 1, " \u7F3A\u5C11\u5546\u54C1\u4FE1\u606F"));
399
+ }
400
+ if (!booking.start_date) {
401
+ errors.push("\u9884\u8BA2\u9879 ".concat(index + 1, " \u7F3A\u5C11\u5F00\u59CB\u65E5\u671F"));
402
+ }
403
+ if (!booking.start_time) {
404
+ errors.push("\u9884\u8BA2\u9879 ".concat(index + 1, " \u7F3A\u5C11\u5F00\u59CB\u65F6\u95F4"));
405
+ }
406
+ });
407
+ }
408
+ return {
409
+ valid: errors.length === 0,
410
+ errors: errors
411
+ };
412
+ }
413
+
414
+ /**
415
+ * 生成本地订单ID
416
+ */
417
+ export function generateLocalOrderId() {
418
+ var timestamp = Date.now();
419
+ var random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
420
+ return "local_order_".concat(timestamp, "_").concat(random);
421
+ }
422
+
423
+ /**
424
+ * 格式化日期时间为 YYYY-MM-DD hh:mm:ss 格式
425
+ *
426
+ * @param date 要格式化的日期对象
427
+ * @returns 格式化后的日期时间字符串
428
+ */
429
+ export function formatDateTime(date) {
430
+ var year = date.getFullYear();
431
+ var month = String(date.getMonth() + 1).padStart(2, '0');
432
+ var day = String(date.getDate()).padStart(2, '0');
433
+ var hours = String(date.getHours()).padStart(2, '0');
434
+ var minutes = String(date.getMinutes()).padStart(2, '0');
435
+ var seconds = String(date.getSeconds()).padStart(2, '0');
436
+ return "".concat(year, "-").concat(month, "-").concat(day, " ").concat(hours, ":").concat(minutes, ":").concat(seconds);
437
+ }
438
+
439
+ /**
440
+ * 从购物车小计数据中提取金额信息
441
+ */
442
+ export function extractAmountFromCartSummary(cartSummary) {
443
+ var result = {
444
+ totalAmount: '0.00',
445
+ subTotal: '0.00',
446
+ taxAmount: '0.00',
447
+ discountAmount: '0.00',
448
+ shopDiscountAmount: '0.00',
449
+ roundingAmount: '0.00'
450
+ };
451
+ cartSummary.forEach(function (item) {
452
+ var value = Number(item.value).toFixed(2);
453
+ switch (item.key) {
454
+ case 'expect_amount':
455
+ result.totalAmount = value;
456
+ break;
457
+ case 'sub_total':
458
+ result.subTotal = value;
459
+ break;
460
+ case 'tax':
461
+ result.taxAmount = value;
462
+ if (item.tax) {
463
+ result.taxDetails = item.tax;
464
+ }
465
+ break;
466
+ case 'discount':
467
+ result.discountAmount = value;
468
+ break;
469
+ case 'shop_discount':
470
+ result.shopDiscountAmount = value;
471
+ break;
472
+ case 'custom_roundingAmount':
473
+ result.roundingAmount = value;
474
+ break;
475
+ default:
476
+ // 处理其他可能的键,如定金等
477
+ if (item.key.includes('deposit')) {
478
+ result.depositAmount = value;
479
+ }
480
+ break;
481
+ }
482
+ });
483
+ console.log('[Checkout] 从购物车小计提取金额信息:', {
484
+ totalAmount: result.totalAmount,
485
+ subTotal: result.subTotal,
486
+ taxAmount: result.taxAmount,
487
+ discountAmount: result.discountAmount,
488
+ shopDiscountAmount: result.shopDiscountAmount,
489
+ roundingAmount: result.roundingAmount
490
+ });
491
+ return result;
492
+ }
493
+
494
+ /**
495
+ * 计算购物车总金额
496
+ */
497
+ export function calculateTotalAmount(cartItems) {
498
+ var total = cartItems.reduce(function (sum, item) {
499
+ var price = parseFloat(String(item.price) || '0');
500
+ var quantity = item.quantity || 1;
501
+ return sum + price * quantity;
502
+ }, 0);
503
+ return total.toFixed(2);
504
+ }
505
+
506
+ /**
507
+ * 判断订单ID是否为本地生成的虚拟ID
508
+ *
509
+ * @param orderId 订单ID
510
+ * @returns true 表示是虚拟ID,false 表示是真实的后端ID
511
+ */
512
+ export function isVirtualOrderId(orderId) {
513
+ return orderId.startsWith('local_order_');
514
+ }
515
+
516
+ /**
517
+ * 判断支付方式是否需要同步订单到后端
518
+ *
519
+ * 现金支付(CASHMANUAL)和自定义支付不需要同步,其他支付方式需要同步
520
+ *
521
+ * @param paymentCode 支付方式代码
522
+ * @param paymentType 支付方式类型
523
+ * @returns 是否需要同步订单
524
+ */
525
+ export function shouldSyncOrderForPayment(paymentCode, paymentType) {
526
+ var codeUpper = (paymentCode === null || paymentCode === void 0 ? void 0 : paymentCode.toUpperCase()) || '';
527
+ var typeUpper = (paymentType === null || paymentType === void 0 ? void 0 : paymentType.toUpperCase()) || '';
528
+
529
+ // 现金支付不需要同步 - 支持多种现金支付识别方式
530
+ var cashIdentifiers = ['CASHMANUAL', 'CASH', 'MANUAL'];
531
+ if (cashIdentifiers.some(function (id) {
532
+ return codeUpper.includes(id) || typeUpper.includes(id);
533
+ })) {
534
+ return false;
535
+ }
536
+
537
+ // 标准现金支付代码检查
538
+ if (paymentCode === PaymentMethodType.Cash || paymentType === PaymentMethodType.Cash) {
539
+ return false;
540
+ }
541
+
542
+ // 自定义支付不需要同步
543
+ if (codeUpper.includes('CUSTOM') || typeUpper.includes('CUSTOM')) {
544
+ return false;
545
+ }
546
+
547
+ // 其他支付方式都需要同步
548
+ return true;
549
+ }
@@ -7,8 +7,21 @@ export declare class OrderModule extends BaseModule implements Module, OrderModu
7
7
  protected defaultVersion: string;
8
8
  private store;
9
9
  private request;
10
+ private logger;
10
11
  constructor(name?: string, version?: string);
11
12
  initialize(core: PisellCore, options: ModuleOptions): Promise<void>;
13
+ /**
14
+ * 记录信息日志
15
+ */
16
+ private logInfo;
17
+ /**
18
+ * 记录警告日志
19
+ */
20
+ private logWarning;
21
+ /**
22
+ * 记录错误日志
23
+ */
24
+ private logError;
12
25
  createOrder(params: CommitOrderParams['query']): {
13
26
  type: "virtual" | "appointment_booking";
14
27
  platform: string;
@@ -37,6 +37,7 @@ var import_utils = require("./utils");
37
37
  var import_utils2 = require("../Product/utils");
38
38
  var import_dayjs = __toESM(require("dayjs"));
39
39
  var OrderModule = class extends import_BaseModule.BaseModule {
40
+ // LoggerManager 实例
40
41
  constructor(name, version) {
41
42
  super(name, version);
42
43
  this.defaultName = "order";
@@ -46,6 +47,44 @@ var OrderModule = class extends import_BaseModule.BaseModule {
46
47
  this.core = core;
47
48
  this.store = options.store;
48
49
  this.request = this.core.getPlugin("request");
50
+ this.logger = this.core.getPlugin("logger");
51
+ this.logInfo("OrderModule initialized successfully");
52
+ }
53
+ /**
54
+ * 记录信息日志
55
+ */
56
+ logInfo(title, metadata) {
57
+ if (this.logger) {
58
+ this.logger.addLog({
59
+ type: "info",
60
+ title: `[OrderModule] ${title}`,
61
+ metadata: metadata || {}
62
+ });
63
+ }
64
+ }
65
+ /**
66
+ * 记录警告日志
67
+ */
68
+ logWarning(title, metadata) {
69
+ if (this.logger) {
70
+ this.logger.addLog({
71
+ type: "warning",
72
+ title: `[OrderModule] ${title}`,
73
+ metadata: metadata || {}
74
+ });
75
+ }
76
+ }
77
+ /**
78
+ * 记录错误日志
79
+ */
80
+ logError(title, metadata) {
81
+ if (this.logger) {
82
+ this.logger.addLog({
83
+ type: "error",
84
+ title: `[OrderModule] ${title}`,
85
+ metadata: metadata || {}
86
+ });
87
+ }
49
88
  }
50
89
  createOrder(params) {
51
90
  var _a;
@@ -97,6 +136,11 @@ var OrderModule = class extends import_BaseModule.BaseModule {
97
136
  return order;
98
137
  }
99
138
  checkBeforeSubmitOrder(params) {
139
+ var _a;
140
+ this.logInfo("checkBeforeSubmitOrder called", {
141
+ cartItemsCount: ((_a = params.cartItems) == null ? void 0 : _a.length) || 0,
142
+ type: params.type
143
+ });
100
144
  const { cartItems, type } = params;
101
145
  if (type === "holder") {
102
146
  const hasNoHolderId = cartItems.some((item) => !item.holder_id);
@@ -107,9 +151,25 @@ var OrderModule = class extends import_BaseModule.BaseModule {
107
151
  return true;
108
152
  }
109
153
  async submitOrder(order) {
154
+ var _a, _b, _c;
155
+ this.logInfo("submitOrder called", {
156
+ url: order.url,
157
+ orderType: order.query.type,
158
+ platform: order.query.platform,
159
+ cartItemsCount: ((_a = order.query.cartItems) == null ? void 0 : _a.length) || 0
160
+ });
110
161
  const { url, query } = order;
111
162
  const fetchUrl = url || "/order/appointment";
112
163
  const params = this.createOrder(query);
164
+ this.logInfo("Calling backend order API", {
165
+ url: fetchUrl,
166
+ orderType: params.type,
167
+ platform: params.platform,
168
+ isDeposit: params.is_deposit,
169
+ bookingsCount: ((_b = params.bookings) == null ? void 0 : _b.length) || 0,
170
+ relationProductsCount: ((_c = params.relation_products) == null ? void 0 : _c.length) || 0,
171
+ scheduleDate: params.schedule_date
172
+ });
113
173
  return this.request.post(fetchUrl, params);
114
174
  }
115
175
  /**
@@ -123,15 +183,31 @@ var OrderModule = class extends import_BaseModule.BaseModule {
123
183
  * @returns 后端返回的订单数据(包含订单ID等)
124
184
  */
125
185
  async createOrderByCheckout(params) {
126
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
127
- console.log("[Order] createOrderByCheckout 开始创建订单:", {
186
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
187
+ this.logInfo("createOrderByCheckout called", {
128
188
  type: params.type,
129
189
  platform: params.platform,
130
190
  is_deposit: params.is_deposit,
131
191
  customer_id: params.customer_id,
132
192
  bookingsCount: ((_a = params.bookings) == null ? void 0 : _a.length) || 0,
133
193
  relationProductsCount: ((_b = params.relation_products) == null ? void 0 : _b.length) || 0,
134
- paymentsCount: ((_c = params.payments) == null ? void 0 : _c.length) || 0
194
+ paymentsCount: ((_c = params.payments) == null ? void 0 : _c.length) || 0,
195
+ depositAmount: params.deposit_amount,
196
+ productTaxFee: params.product_tax_fee,
197
+ note: params.note,
198
+ scheduleDate: params.schedule_date,
199
+ hasOrderId: !!params.order_id,
200
+ orderIdIncluded: params.order_id,
201
+ paymentMethods: ((_d = params.payments) == null ? void 0 : _d.map((p) => p.code)) || []
202
+ });
203
+ console.log("[Order] createOrderByCheckout 开始创建订单:", {
204
+ type: params.type,
205
+ platform: params.platform,
206
+ is_deposit: params.is_deposit,
207
+ customer_id: params.customer_id,
208
+ bookingsCount: ((_e = params.bookings) == null ? void 0 : _e.length) || 0,
209
+ relationProductsCount: ((_f = params.relation_products) == null ? void 0 : _f.length) || 0,
210
+ paymentsCount: ((_g = params.payments) == null ? void 0 : _g.length) || 0
135
211
  });
136
212
  try {
137
213
  const orderData = {
@@ -147,7 +223,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
147
223
  ...params
148
224
  // 使用传入的参数覆盖默认值
149
225
  };
150
- if ((_d = orderData.payments) == null ? void 0 : _d.length) {
226
+ if ((_h = orderData.payments) == null ? void 0 : _h.length) {
151
227
  orderData.small_ticket_data_flag = 1;
152
228
  }
153
229
  if (params.order_id) {
@@ -163,15 +239,38 @@ var OrderModule = class extends import_BaseModule.BaseModule {
163
239
  platform: orderData.platform,
164
240
  isDeposit: orderData.is_deposit,
165
241
  customerId: orderData.customer_id,
166
- bookingsCount: ((_e = orderData.bookings) == null ? void 0 : _e.length) || 0,
167
- relationProductsCount: ((_f = orderData.relation_products) == null ? void 0 : _f.length) || 0,
168
- paymentsCount: ((_g = orderData.payments) == null ? void 0 : _g.length) || 0,
169
- paymentsMethods: ((_h = orderData.payments) == null ? void 0 : _h.map((p) => p.code)) || []
242
+ bookingsCount: ((_i = orderData.bookings) == null ? void 0 : _i.length) || 0,
243
+ relationProductsCount: ((_j = orderData.relation_products) == null ? void 0 : _j.length) || 0,
244
+ paymentsCount: ((_k = orderData.payments) == null ? void 0 : _k.length) || 0,
245
+ paymentsMethods: ((_l = orderData.payments) == null ? void 0 : _l.map((p) => p.code)) || []
246
+ });
247
+ this.logInfo("Calling backend checkout API", {
248
+ url: "/order/checkout",
249
+ orderType: orderData.type,
250
+ platform: orderData.platform,
251
+ isDeposit: orderData.is_deposit,
252
+ customerId: orderData.customer_id,
253
+ depositAmount: orderData.deposit_amount,
254
+ bookingsCount: ((_m = orderData.bookings) == null ? void 0 : _m.length) || 0,
255
+ relationProductsCount: ((_n = orderData.relation_products) == null ? void 0 : _n.length) || 0,
256
+ paymentsCount: ((_o = orderData.payments) == null ? void 0 : _o.length) || 0,
257
+ paymentMethods: ((_p = orderData.payments) == null ? void 0 : _p.map((p) => ({
258
+ code: p.code,
259
+ amount: p.amount,
260
+ type: p.type,
261
+ hasVoucherId: !!p.voucher_id,
262
+ orderPaymentType: p.order_payment_type
263
+ }))) || [],
264
+ productTaxFee: orderData.product_tax_fee,
265
+ note: orderData.note,
266
+ scheduleDate: orderData.schedule_date,
267
+ hasOrderId: !!orderData.order_id,
268
+ smallTicketDataFlag: orderData.small_ticket_data_flag
170
269
  });
171
270
  const response = await this.request.post("/order/checkout", orderData);
172
271
  console.log("[Order] 订单创建成功,后端响应:", {
173
272
  success: !!response,
174
- hasOrderId: !!(((_i = response == null ? void 0 : response.data) == null ? void 0 : _i.order_id) || (response == null ? void 0 : response.order_id))
273
+ hasOrderId: !!(((_q = response == null ? void 0 : response.data) == null ? void 0 : _q.order_id) || (response == null ? void 0 : response.order_id))
175
274
  });
176
275
  return response;
177
276
  } catch (error) {
@@ -18,10 +18,23 @@ export declare class CheckoutImpl extends BaseModule implements Module, Checkout
18
18
  private request;
19
19
  private store;
20
20
  private otherParams;
21
+ private logger;
21
22
  order: OrderModule;
22
23
  payment: PaymentModule;
23
24
  constructor(name?: string, version?: string);
24
25
  initialize(core: PisellCore, options: ModuleOptions): Promise<void>;
26
+ /**
27
+ * 记录信息日志
28
+ */
29
+ private logInfo;
30
+ /**
31
+ * 记录警告日志
32
+ */
33
+ private logWarning;
34
+ /**
35
+ * 记录错误日志
36
+ */
37
+ private logError;
25
38
  /**
26
39
  * 初始化子模块
27
40
  */
@@ -366,33 +379,16 @@ export declare class CheckoutImpl extends BaseModule implements Module, Checkout
366
379
  * 验证结账参数
367
380
  */
368
381
  private validateCheckoutParams;
369
- /**
370
- * 验证本地订单数据
371
- */
372
- private validateLocalOrderData;
373
- /**
374
- * 生成本地订单ID
375
- */
376
- private generateLocalOrderId;
377
- /**
378
- * 格式化日期时间为 YYYY-MM-DD hh:mm:ss 格式
379
- *
380
- * @param date 要格式化的日期对象
381
- * @returns 格式化后的日期时间字符串
382
- */
383
- private formatDateTime;
384
- /**
385
- * 从购物车小计数据中提取金额信息
386
- */
387
- private extractAmountFromCartSummary;
388
382
  /**
389
383
  * 预加载支付方式(在初始化时调用)
390
384
  */
391
385
  private preloadPaymentMethods;
392
386
  /**
393
- * 计算总金额
387
+ * 清理过期的已同步订单数据
388
+ *
389
+ * 删除本地 IndexDB 中超过指定天数且已同步到后端的订单数据
394
390
  */
395
- private calculateTotalAmount;
391
+ private cleanupExpiredOrdersAsync;
396
392
  /**
397
393
  * 计算已支付金额(从 Payment 模块获取最新数据)
398
394
  */
@@ -415,28 +411,11 @@ export declare class CheckoutImpl extends BaseModule implements Module, Checkout
415
411
  * 当剩余待付款金额 <= 0 时,触发订单支付完成事件
416
412
  */
417
413
  private checkOrderPaymentCompletion;
418
- /**
419
- * 判断支付方式是否需要同步订单到后端
420
- *
421
- * 现金支付(CASHMANUAL)和自定义支付不需要同步,其他支付方式需要同步
422
- *
423
- * @param paymentCode 支付方式代码
424
- * @param paymentType 支付方式类型
425
- * @returns 是否需要同步订单
426
- */
427
- private shouldSyncOrderForPayment;
428
414
  /**
429
415
  * 同步订单到后端
430
416
  *
431
417
  * 调用后端 /order/checkout 接口创建真实订单
432
418
  */
433
- /**
434
- * 判断订单ID是否为本地生成的虚拟ID
435
- *
436
- * @param orderId 订单ID
437
- * @returns true 表示是虚拟ID,false 表示是真实的后端ID
438
- */
439
- private isVirtualOrderId;
440
419
  /**
441
420
  * 同步订单到后端并返回真实订单ID
442
421
  *