@pisell/pisellos 0.0.230 → 0.0.232

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 (54) hide show
  1. package/dist/modules/Order/index.d.ts +13 -2
  2. package/dist/modules/Order/index.js +93 -1
  3. package/dist/modules/Order/types.d.ts +45 -0
  4. package/dist/modules/Order/types.js +8 -0
  5. package/dist/modules/Payment/cash.d.ts +8 -0
  6. package/dist/modules/Payment/cash.js +20 -1
  7. package/dist/modules/Payment/cashRecommendationAlgorithm.d.ts +22 -0
  8. package/dist/modules/Payment/cashRecommendationAlgorithm.js +423 -0
  9. package/dist/modules/Payment/eftpos.js +1 -1
  10. package/dist/modules/Payment/index.d.ts +34 -124
  11. package/dist/modules/Payment/index.js +662 -1280
  12. package/dist/modules/Payment/mx51.d.ts +0 -0
  13. package/dist/modules/Payment/mx51.js +0 -0
  14. package/dist/modules/Payment/types.d.ts +323 -45
  15. package/dist/modules/Payment/types.js +101 -2
  16. package/dist/modules/Payment/utils.d.ts +17 -0
  17. package/dist/modules/Payment/utils.js +62 -0
  18. package/dist/modules/Payment/walletpass.d.ts +96 -0
  19. package/dist/modules/Payment/walletpass.js +492 -0
  20. package/dist/modules/Schedule/index.d.ts +9 -0
  21. package/dist/modules/Schedule/index.js +60 -0
  22. package/dist/solution/Checkout/index.d.ts +254 -2
  23. package/dist/solution/Checkout/index.js +2472 -320
  24. package/dist/solution/Checkout/types.d.ts +207 -6
  25. package/dist/solution/Checkout/types.js +5 -0
  26. package/lib/modules/Order/index.d.ts +13 -2
  27. package/lib/modules/Order/index.js +65 -1
  28. package/lib/modules/Order/types.d.ts +45 -0
  29. package/lib/modules/Payment/cash.d.ts +8 -0
  30. package/lib/modules/Payment/cash.js +14 -1
  31. package/lib/modules/Payment/cashRecommendationAlgorithm.d.ts +22 -0
  32. package/lib/modules/Payment/cashRecommendationAlgorithm.js +342 -0
  33. package/lib/modules/Payment/eftpos.js +1 -1
  34. package/lib/modules/Payment/index.d.ts +34 -124
  35. package/lib/modules/Payment/index.js +232 -533
  36. package/lib/modules/Payment/mx51.d.ts +0 -0
  37. package/lib/modules/Payment/mx51.js +0 -0
  38. package/lib/modules/Payment/types.d.ts +323 -45
  39. package/lib/modules/Payment/types.js +37 -2
  40. package/lib/modules/Payment/utils.d.ts +17 -0
  41. package/lib/modules/Payment/utils.js +67 -0
  42. package/lib/modules/Payment/walletpass.d.ts +96 -0
  43. package/lib/modules/Payment/walletpass.js +304 -0
  44. package/lib/modules/Schedule/index.d.ts +9 -0
  45. package/lib/modules/Schedule/index.js +36 -0
  46. package/lib/solution/Checkout/index.d.ts +254 -2
  47. package/lib/solution/Checkout/index.js +1361 -39
  48. package/lib/solution/Checkout/types.d.ts +207 -6
  49. package/lib/solution/Checkout/types.js +5 -0
  50. package/package.json +1 -1
  51. package/dist/modules/Payment/wallet.d.ts +0 -11
  52. package/dist/modules/Payment/wallet.js +0 -78
  53. package/lib/modules/Payment/wallet.d.ts +0 -11
  54. package/lib/modules/Payment/wallet.js +0 -51
@@ -29,7 +29,7 @@ var import_types = require("./types");
29
29
  var import_utils = require("../Cart/utils");
30
30
  var import_cash = require("./cash");
31
31
  var import_eftpos = require("./eftpos");
32
- var import_wallet = require("./wallet");
32
+ var import_walletpass = require("./walletpass");
33
33
  var import_decimal = require("decimal.js");
34
34
  __reExport(Payment_exports, require("./types"), module.exports);
35
35
  function formatAmount(amount) {
@@ -60,7 +60,7 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
60
60
  this.defaultVersion = "1.0.0";
61
61
  this.cash = new import_cash.CashPaymentImpl(this);
62
62
  this.eftpos = new import_eftpos.EftposPaymentImpl(this);
63
- this.wallet = new import_wallet.WalletPaymentImpl(this);
63
+ this.wallet = new import_walletpass.WalletPassPaymentImpl(this);
64
64
  }
65
65
  async initialize(core, options) {
66
66
  this.core = core;
@@ -77,7 +77,6 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
77
77
  this.dbManager = this.app.dbManager;
78
78
  this.logger = this.app.logger;
79
79
  await this.ensurePaymentTables();
80
- this.registerTaskHandlers();
81
80
  this.registerNetworkHandlers();
82
81
  console.log("[PaymentModule] 初始化完成");
83
82
  this.logInfo("PaymentModule initialized successfully");
@@ -152,11 +151,7 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
152
151
  previousStatus: status.previousStatus
153
152
  });
154
153
  if (status.connected) {
155
- this.logInfo("Network reconnected - triggering payment sync queue");
156
- const requeuedCount = await this.recheckAndRequeueUnsyncedOrders();
157
- if (requeuedCount > 0) {
158
- await this.runPaymentSyncQueue();
159
- }
154
+ this.logInfo("Network reconnected");
160
155
  }
161
156
  });
162
157
  }
@@ -177,7 +172,7 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
177
172
  this.refreshPaymentMethodsInBackground(cachedMethods);
178
173
  return cachedMethods;
179
174
  }
180
- const response = await this.request.get("/pay/custom-payment/available");
175
+ const response = await this.request.get("/pay/custom-payment/available", { channel: "pos" });
181
176
  const payMethods = response.data || [];
182
177
  try {
183
178
  for (const method of payMethods) {
@@ -210,7 +205,7 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
210
205
  });
211
206
  try {
212
207
  console.log("[PaymentModule] 后台刷新支付方式列表...");
213
- const response = await this.request.get("/pay/custom-payment/available");
208
+ const response = await this.request.get("/pay/custom-payment/available", { channel: "pos" });
214
209
  const newPayMethods = response.data || [];
215
210
  const hasChanges = this.hasPaymentMethodsChanged(
216
211
  cachedMethods,
@@ -350,14 +345,6 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
350
345
  throw error;
351
346
  }
352
347
  }
353
- /**
354
- * 往交易组中添加订单(兼容性方法)
355
- * @deprecated 使用 createPaymentOrderAsync 替代
356
- */
357
- async pushOrderAsync(params) {
358
- console.warn("[PaymentModule] pushOrderAsync 已废弃,请使用 createPaymentOrderAsync 替代");
359
- return this.createPaymentOrderAsync(params);
360
- }
361
348
  /**
362
349
  * 删除支付订单(新方法)
363
350
  */
@@ -374,14 +361,6 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
374
361
  throw error;
375
362
  }
376
363
  }
377
- /**
378
- * 删除订单(兼容性方法)
379
- * @deprecated 使用 deletePaymentOrderAsync 替代
380
- */
381
- async deleteOrderAsync(orderUuid) {
382
- console.warn("[PaymentModule] deleteOrderAsync 已废弃,请使用 deletePaymentOrderAsync 替代");
383
- return this.deletePaymentOrderAsync(orderUuid);
384
- }
385
364
  /**
386
365
  * 更新订单
387
366
  */
@@ -439,6 +418,8 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
439
418
  const updatedOrder = {
440
419
  ...existingOrder,
441
420
  id: newOrderId,
421
+ order_id: newOrderId,
422
+ // 🔧 修复:同时更新根级的 order_id 字段
442
423
  order_info: {
443
424
  ...existingOrder.order_info,
444
425
  order_id: newOrderId,
@@ -476,26 +457,36 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
476
457
  }
477
458
  /**
478
459
  * 获取支付项(新方法)
460
+ *
461
+ * @param orderUuid 订单UUID
462
+ * @param includeVoided 是否包含已撤销的支付项,默认为false
463
+ * @returns 支付项数组
479
464
  */
480
- async getPaymentItemsAsync(orderUuid) {
465
+ async getPaymentItemsAsync(orderUuid, includeVoided = false) {
481
466
  if (!orderUuid) {
482
467
  throw new Error("orderUuid is required");
483
468
  }
484
469
  const order = await this.getPaymentOrderByUuidAsync(orderUuid);
485
- return (order == null ? void 0 : order.payment) || [];
470
+ const allPayments = (order == null ? void 0 : order.payment) || [];
471
+ if (includeVoided) {
472
+ return allPayments;
473
+ }
474
+ return allPayments.filter((payment) => payment.status !== "voided");
486
475
  }
487
476
  /**
488
- * 获取支付项(兼容性方法)
489
- * @deprecated 使用 getPaymentItemsAsync 替代
477
+ * 获取所有支付项(包括已撤销的)
478
+ *
479
+ * @param orderUuid 订单UUID
480
+ * @returns 所有支付项数组(包括撤销的)
490
481
  */
491
- async getPaymentAsync(orderUuid) {
492
- console.warn("[PaymentModule] getPaymentAsync 已废弃,请使用 getPaymentItemsAsync 替代");
493
- return this.getPaymentItemsAsync(orderUuid);
482
+ async getAllPaymentItemsAsync(orderUuid) {
483
+ return this.getPaymentItemsAsync(orderUuid, true);
494
484
  }
495
485
  /**
496
486
  * 为某个订单添加支付项(新方法)
497
487
  */
498
488
  async addPaymentItemAsync(orderUuid, paymentItem) {
489
+ var _a;
499
490
  this.logInfo("Starting addPaymentItemAsync", {
500
491
  orderUuid,
501
492
  paymentAmount: paymentItem.amount,
@@ -506,8 +497,9 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
506
497
  if (!order) {
507
498
  throw new Error(`Order not found: ${orderUuid}`);
508
499
  }
500
+ const paymentUuid = (0, import_utils.getUniqueId)("payment_");
509
501
  const newPaymentItem = {
510
- uuid: (0, import_utils.getUniqueId)("payment_"),
502
+ uuid: paymentUuid,
511
503
  id: paymentItem.id || 0,
512
504
  name: paymentItem.name,
513
505
  code: paymentItem.code,
@@ -515,8 +507,13 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
515
507
  amount: formatAmount(paymentItem.amount),
516
508
  voucher_id: paymentItem.voucher_id || "",
517
509
  rounding_amount: "0.00",
518
- service_charge: { percentage: "0.00", amount: "0.00" },
519
- isSynced: false
510
+ service_charge: paymentItem.service_charge,
511
+ status: "active",
512
+ // 新支付项默认为活跃状态
513
+ metadata: {
514
+ unique_payment_number: paymentUuid
515
+ // 设置唯一支付号为支付项的 uuid
516
+ }
520
517
  };
521
518
  order.payment.push(newPaymentItem);
522
519
  this.recalculateOrderAmount(order);
@@ -528,6 +525,7 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
528
525
  this.logInfo("addPaymentItemAsync completed successfully", {
529
526
  orderUuid,
530
527
  paymentUuid: newPaymentItem.uuid,
528
+ uniquePaymentNumber: (_a = newPaymentItem.metadata) == null ? void 0 : _a.unique_payment_number,
531
529
  newExpectAmount: order.expect_amount
532
530
  });
533
531
  } catch (error) {
@@ -540,42 +538,131 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
540
538
  }
541
539
  }
542
540
  /**
543
- * 为某个订单设置一个支付项(兼容性方法)
544
- * @deprecated 使用 addPaymentItemAsync 替代
545
- */
546
- async pushPaymentAsync(orderUuid, paymentItem) {
547
- console.warn("[PaymentModule] pushPaymentAsync 已废弃,请使用 addPaymentItemAsync 替代");
548
- return this.addPaymentItemAsync(orderUuid, paymentItem);
549
- }
550
- /**
551
- * 删除一个支付项
541
+ * 删除一个支付项 - 标记删除而非物理删除
552
542
  */
553
543
  async deletePaymentAsync(orderUuid, paymentUuid) {
554
- this.logInfo("Starting deletePaymentAsync", { orderUuid, paymentUuid });
544
+ this.logInfo("Starting deletePaymentAsync (mark as voided)", { orderUuid, paymentUuid });
555
545
  try {
556
546
  const order = await this.dbManager.get("order", orderUuid);
557
547
  if (!order) {
558
548
  throw new Error("订单不存在");
559
549
  }
560
- const index = order.payment.findIndex(
550
+ const paymentItem = order.payment.find(
561
551
  (payment) => payment.uuid === paymentUuid
562
552
  );
563
- if (index > -1) {
564
- const deletedPayment = order.payment.splice(index, 1)[0];
565
- this.recalculateOrderAmount(order);
566
- await this.dbManager.update("order", order);
567
- await this.core.effects.emit(import_types.PaymentHooks.OnPaymentDeleted, {
568
- order,
569
- paymentItem: deletedPayment
570
- });
571
- await this.core.effects.emit(import_types.PaymentHooks.OnOrderChanged, {
572
- action: "payment_delete",
573
- order,
574
- paymentItem: deletedPayment
575
- });
553
+ if (!paymentItem) {
554
+ throw new Error(`支付项不存在: ${paymentUuid}`);
555
+ }
556
+ if (paymentItem.status === "voided") {
557
+ console.warn(`[PaymentModule] 支付项 ${paymentUuid} 已经被删除,跳过操作`);
558
+ return;
576
559
  }
560
+ paymentItem.status = "voided";
561
+ paymentItem.origin_amount = paymentItem.amount;
562
+ paymentItem.amount = "0.00";
563
+ console.log(`[PaymentModule] 支付项标记为删除:`, {
564
+ uuid: paymentItem.uuid,
565
+ originalAmount: paymentItem.origin_amount,
566
+ status: paymentItem.status
567
+ });
568
+ this.recalculateOrderAmount(order);
569
+ await this.dbManager.update("order", order);
570
+ await this.core.effects.emit(import_types.PaymentHooks.OnPaymentDeleted, {
571
+ order,
572
+ paymentItem
573
+ });
574
+ await this.core.effects.emit(import_types.PaymentHooks.OnOrderChanged, {
575
+ action: "payment_delete",
576
+ order,
577
+ paymentItem
578
+ });
579
+ this.logInfo("deletePaymentAsync completed successfully (marked as voided)", {
580
+ orderUuid,
581
+ paymentUuid,
582
+ originalAmount: paymentItem.origin_amount,
583
+ newExpectAmount: order.expect_amount
584
+ });
577
585
  } catch (error) {
578
586
  console.error("[PaymentModule] 删除支付项失败", error);
587
+ this.logError("deletePaymentAsync failed", error, {
588
+ orderUuid,
589
+ paymentUuid
590
+ });
591
+ throw error;
592
+ }
593
+ }
594
+ /**
595
+ * 批量更新代金券类支付项(覆盖更新)
596
+ *
597
+ * 删除所有现有的带 voucher_id 的支付项,然后添加新的代金券支付项
598
+ * 这是一个覆盖式更新,确保代金券支付项的一致性
599
+ */
600
+ async updateVoucherPaymentItemsAsync(orderUuid, voucherPaymentItems) {
601
+ this.logInfo("Starting updateVoucherPaymentItemsAsync", {
602
+ orderUuid,
603
+ newVoucherCount: voucherPaymentItems.length,
604
+ voucherItems: voucherPaymentItems.map((item) => ({
605
+ code: item.code,
606
+ amount: item.amount,
607
+ voucher_id: item.voucher_id
608
+ }))
609
+ });
610
+ try {
611
+ const order = await this.getPaymentOrderByUuidAsync(orderUuid);
612
+ if (!order) {
613
+ throw new Error(`订单不存在: ${orderUuid}`);
614
+ }
615
+ const existingVoucherItems = order.payment.filter(
616
+ (payment) => payment.voucher_id && payment.status !== "voided"
617
+ );
618
+ console.log("[PaymentModule] 发现现有代金券支付项:", {
619
+ orderUuid,
620
+ existingVoucherCount: existingVoucherItems.length,
621
+ existingItems: existingVoucherItems.map((item) => ({
622
+ uuid: item.uuid,
623
+ code: item.code,
624
+ amount: item.amount,
625
+ voucher_id: item.voucher_id
626
+ }))
627
+ });
628
+ for (const voucherItem of existingVoucherItems) {
629
+ console.log(`[PaymentModule] 删除现有代金券支付项: ${voucherItem.uuid}`);
630
+ await this.deletePaymentAsync(orderUuid, voucherItem.uuid);
631
+ }
632
+ console.log("[PaymentModule] 添加新的代金券支付项:", {
633
+ orderUuid,
634
+ newItemCount: voucherPaymentItems.length
635
+ });
636
+ for (const voucherItem of voucherPaymentItems) {
637
+ if (!voucherItem.voucher_id) {
638
+ throw new Error(`代金券支付项缺少 voucher_id: ${JSON.stringify(voucherItem)}`);
639
+ }
640
+ console.log(`[PaymentModule] 添加代金券支付项:`, {
641
+ code: voucherItem.code,
642
+ amount: voucherItem.amount,
643
+ voucher_id: voucherItem.voucher_id
644
+ });
645
+ await this.addPaymentItemAsync(orderUuid, voucherItem);
646
+ }
647
+ const updatedOrder = await this.getPaymentOrderByUuidAsync(orderUuid);
648
+ await this.core.effects.emit(import_types.PaymentHooks.OnPaymentAdded, {
649
+ orderUuid,
650
+ order: updatedOrder,
651
+ payment: null
652
+ // 批量操作不提供单个支付项
653
+ });
654
+ this.logInfo("updateVoucherPaymentItemsAsync completed successfully", {
655
+ orderUuid,
656
+ removedVoucherCount: existingVoucherItems.length,
657
+ addedVoucherCount: voucherPaymentItems.length,
658
+ finalExpectAmount: updatedOrder == null ? void 0 : updatedOrder.expect_amount
659
+ });
660
+ } catch (error) {
661
+ console.error("[PaymentModule] 批量更新代金券支付项失败:", error);
662
+ this.logError("updateVoucherPaymentItemsAsync failed", error, {
663
+ orderUuid,
664
+ voucherPaymentItems
665
+ });
579
666
  throw error;
580
667
  }
581
668
  }
@@ -625,32 +712,20 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
625
712
  const order = await this.dbManager.get("order", orderUuid);
626
713
  orderToSubmit = order ? [order] : [];
627
714
  } else {
628
- const allOrders2 = await this.dbManager.getAll("order");
629
- orderToSubmit = allOrders2.filter(
715
+ const allOrders = await this.dbManager.getAll("order");
716
+ orderToSubmit = allOrders.filter(
630
717
  (order) => order.payment_status === import_types.PaymentStatus.Processing || order.payment_status === import_types.PaymentStatus.PartiallyPaid
631
718
  );
632
719
  }
633
720
  for (const order of orderToSubmit) {
634
721
  await this.submitSingleOrderPayment(order);
635
722
  }
636
- await this.runPaymentSyncQueue();
637
- const allOrders = await this.dbManager.getAll("order");
638
- const allOrdersProcessed = allOrders.every(
639
- (order) => order.payment.every((payment) => payment.isSynced === true)
640
- );
641
- if (allOrdersProcessed) {
642
- const result = { status: "success" };
643
- this.logInfo("submitPayAsync completed", {
644
- result: result.status,
645
- processedOrdersCount: allOrders.length
646
- });
647
- return result;
648
- } else {
649
- this.logWarning("submitPayAsync completed with unprocessed orders", {
650
- totalOrders: allOrders.length
651
- });
652
- return { status: "failed" };
653
- }
723
+ const result = { status: "success" };
724
+ this.logInfo("submitPayAsync completed", {
725
+ result: result.status,
726
+ processedOrdersCount: orderToSubmit.length
727
+ });
728
+ return result;
654
729
  } catch (error) {
655
730
  console.error("[PaymentModule] 提交支付失败", error);
656
731
  this.logError("submitPayAsync failed", error, { orderUuid });
@@ -696,14 +771,13 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
696
771
  paymentData.payment_status = order.payment_status === import_types.PaymentStatus.Finished ? "paid" : "partially_paid";
697
772
  await this.dbManager.update("order", order);
698
773
  if (paymentData.payments.length === 0) {
699
- console.log(`[PaymentModule] 订单 ${order.uuid} 支付列表为空,跳过队列推送`);
700
- this.logWarning("Empty payment queue submission", {
774
+ console.log(`[PaymentModule] 订单 ${order.uuid} 支付列表为空,跳过支付处理`);
775
+ this.logWarning("Empty payment list", {
701
776
  orderUuid: order.uuid,
702
777
  orderId: order.order_id
703
778
  });
704
779
  return;
705
780
  }
706
- await this.addToSyncQueue(order, paymentData);
707
781
  await this.core.effects.emit(import_types.PaymentHooks.OnPaymentSubmitted, order);
708
782
  await this.core.effects.emit(import_types.PaymentHooks.OnOrderChanged, {
709
783
  action: "submit",
@@ -714,39 +788,6 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
714
788
  throw error;
715
789
  }
716
790
  }
717
- /**
718
- * 添加到同步任务队列
719
- */
720
- async addToSyncQueue(order, paymentData) {
721
- try {
722
- console.log(`[PaymentModule] 订单 ${order.uuid} 已添加到同步队列`);
723
- if (this.app.tasksManager) {
724
- this.app.tasksManager.addTask({
725
- module: "payment",
726
- queueId: "payment_sync",
727
- tasks: [
728
- {
729
- id: `payment_${order.uuid}`,
730
- action: "syncPayment",
731
- payload: {
732
- orderUuid: order.uuid,
733
- orderId: order.order_id,
734
- paymentData,
735
- core: this.core
736
- },
737
- maxRetries: 3,
738
- type: "cloud"
739
- }
740
- ]
741
- });
742
- console.log(`[PaymentModule] 订单 ${order.uuid} 同步任务已添加到队列`);
743
- } else {
744
- console.warn("[PaymentModule] TasksManager 未初始化,无法添加同步任务");
745
- }
746
- } catch (error) {
747
- console.error("[PaymentModule] 添加同步任务失败", error);
748
- }
749
- }
750
791
  /**
751
792
  * 获取订单剩余待付金额
752
793
  */
@@ -799,6 +840,9 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
799
840
  const paidAmount = order.payment.reduce(
800
841
  (sum, payment) => {
801
842
  try {
843
+ if (payment.status === "voided") {
844
+ return sum;
845
+ }
802
846
  return sum.plus(payment.amount);
803
847
  } catch (error) {
804
848
  console.warn(`[PaymentModule] 无效的支付金额: ${payment.amount},跳过计算`);
@@ -809,6 +853,14 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
809
853
  );
810
854
  const remainingAmount = totalAmount.minus(paidAmount);
811
855
  order.expect_amount = import_decimal.Decimal.max(0, remainingAmount).toFixed(2);
856
+ console.log(`[PaymentModule] 重新计算订单金额:`, {
857
+ orderUuid: order.uuid,
858
+ totalAmount: order.total_amount,
859
+ paidAmount: paidAmount.toFixed(2),
860
+ remainingAmount: order.expect_amount,
861
+ activePayments: order.payment.filter((p) => p.status !== "voided").length,
862
+ voidedPayments: order.payment.filter((p) => p.status === "voided").length
863
+ });
812
864
  }
813
865
  /**
814
866
  * 获取现金支付方式
@@ -852,189 +904,6 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
852
904
  return null;
853
905
  }
854
906
  }
855
- /**
856
- * 注册任务处理函数
857
- */
858
- registerTaskHandlers() {
859
- if (this.app.tasksManager) {
860
- this.app.tasksManager.addTaskFunction(
861
- "syncPayment",
862
- PaymentModule.syncPaymentTask
863
- );
864
- console.log("[PaymentModule] 任务处理函数已注册");
865
- } else {
866
- console.warn(
867
- "[PaymentModule] TasksManager 未初始化,无法注册任务处理函数"
868
- );
869
- }
870
- }
871
- /**
872
- * 静态方法:处理支付同步任务(后台网络同步)
873
- * 这个方法里不允许用 this,因为需要作为静态方法注入到任务队列里
874
- */
875
- static async syncPaymentTask(payload) {
876
- var _a, _b, _c, _d, _e, _f;
877
- const { orderUuid, orderId, paymentData, core } = payload.task.payload;
878
- console.log(`[PaymentModule] 开始后台同步支付,订单ID: ${orderId}`);
879
- paymentData.request_unique = generateRequestUniqueId();
880
- const app = window.app;
881
- const logger = app == null ? void 0 : app.logger;
882
- if (logger) {
883
- logger.addLog({
884
- type: "info",
885
- title: "[PaymentModule] Starting syncPaymentTask",
886
- metadata: {
887
- orderUuid,
888
- orderId,
889
- paymentDataKeys: Object.keys(paymentData)
890
- }
891
- });
892
- }
893
- if (!app) {
894
- throw new Error("App 实例未找到");
895
- }
896
- const request = app.request;
897
- if (!request) {
898
- throw new Error("Request 插件未找到");
899
- }
900
- const dbManager = app.dbManager;
901
- if (!dbManager) {
902
- throw new Error("DBManager 未找到");
903
- }
904
- try {
905
- const requestRes = await request.post(
906
- `/shop/order/${orderId}/order-payment`,
907
- paymentData,
908
- { noToast: true }
909
- );
910
- if (requestRes.status === true) {
911
- const order = await dbManager.get("order", orderUuid);
912
- if (order) {
913
- order.payment.forEach((payment) => {
914
- payment.isSynced = true;
915
- delete payment.syncError;
916
- });
917
- await dbManager.update("order", order);
918
- console.log(`[PaymentModule] 订单 ${orderUuid} 同步状态已更新`);
919
- }
920
- console.log(`[PaymentModule] 订单 ${orderUuid} 后台同步成功`);
921
- await core.effects.emit("payment:onPaymentSyncSuccess", {
922
- orderUuid,
923
- orderId,
924
- timestamp: Date.now()
925
- });
926
- console.log(
927
- `[PaymentModule] 已通过 effects 通知前端订单 ${orderUuid} 同步成功`
928
- );
929
- if (logger) {
930
- logger.addLog({
931
- type: "info",
932
- title: "[PaymentModule] syncPaymentTask completed successfully",
933
- metadata: { orderUuid, orderId }
934
- });
935
- }
936
- return { status: "success", orderUuid, orderId };
937
- } else {
938
- console.log(`[PaymentModule] 接口返回失败,订单 ${orderUuid} 同步失败`);
939
- const businessError = new Error(requestRes.message || "接口返回失败");
940
- businessError.response = { status: 200 };
941
- businessError.isBusinessError = true;
942
- businessError.responseData = requestRes;
943
- throw businessError;
944
- }
945
- } catch (error) {
946
- console.error("[PaymentModule] 后台同步失败:", error);
947
- const isNetworkError = !error.response && !error.status && (error.code === "NETWORK_ERROR" || error.code === "ERR_NETWORK" || error.code === "ECONNREFUSED" || error.code === "ENOTFOUND" || error.code === "ETIMEDOUT" || ((_a = error.message) == null ? void 0 : _a.includes("网络")) || ((_b = error.message) == null ? void 0 : _b.includes("network")) || ((_c = error.message) == null ? void 0 : _c.includes("fetch")));
948
- if (isNetworkError) {
949
- console.log(`[PaymentModule] 网络错误,订单 ${orderUuid} 将重试同步`);
950
- if (logger) {
951
- logger.addLog({
952
- type: "warning",
953
- title: "[PaymentModule] syncPaymentTask network error - will retry",
954
- metadata: {
955
- orderUuid,
956
- orderId,
957
- errorCode: error.code,
958
- errorMessage: error.message
959
- }
960
- });
961
- }
962
- throw error;
963
- } else {
964
- console.log(
965
- `[PaymentModule] 业务错误,订单 ${orderUuid} 同步失败,通知前端`
966
- );
967
- try {
968
- if (core && core.effects) {
969
- const errorData = {
970
- orderUuid,
971
- orderId,
972
- error: error.message || "业务错误",
973
- errorCode: error.code,
974
- statusCode: ((_d = error.response) == null ? void 0 : _d.status) || error.status,
975
- timestamp: Date.now()
976
- };
977
- if (error.isBusinessError && error.responseData) {
978
- errorData.error = error.responseData.message || error.message || "接口返回失败";
979
- errorData.responseData = error.responseData;
980
- }
981
- await core.effects.emit("payment:onPaymentSyncError", errorData);
982
- console.log(
983
- `[PaymentModule] 已通过 effects 通知前端订单 ${orderUuid} 同步错误`
984
- );
985
- } else {
986
- console.warn(
987
- `[PaymentModule] 无法获取 core 实例,无法通知前端错误`
988
- );
989
- }
990
- if (logger) {
991
- logger.addLog({
992
- type: "error",
993
- title: "[PaymentModule] syncPaymentTask business error",
994
- metadata: {
995
- orderUuid,
996
- orderId,
997
- errorCode: error.code,
998
- errorMessage: error.message,
999
- statusCode: ((_e = error.response) == null ? void 0 : _e.status) || error.status,
1000
- isBusinessError: error.isBusinessError
1001
- }
1002
- });
1003
- }
1004
- } catch (notifyError) {
1005
- console.error(`[PaymentModule] 通知前端同步错误失败:`, notifyError);
1006
- if (logger) {
1007
- logger.addLog({
1008
- type: "error",
1009
- title: "[PaymentModule] Failed to notify frontend of sync error",
1010
- metadata: {
1011
- orderUuid,
1012
- orderId,
1013
- notifyError: notifyError instanceof Error ? notifyError.message : String(notifyError)
1014
- }
1015
- });
1016
- }
1017
- }
1018
- const order = await dbManager.get("order", orderUuid);
1019
- if (order) {
1020
- order.payment.forEach((payment) => {
1021
- payment.isSynced = true;
1022
- });
1023
- await dbManager.update("order", order);
1024
- console.log(
1025
- `[PaymentModule] 订单 ${orderUuid} 业务错误,已标记为已同步`
1026
- );
1027
- }
1028
- return {
1029
- status: "completed_with_error",
1030
- orderUuid,
1031
- orderId,
1032
- error: error.message || "业务错误",
1033
- statusCode: ((_f = error.response) == null ? void 0 : _f.status) || error.status
1034
- };
1035
- }
1036
- }
1037
- }
1038
907
  /**
1039
908
  * 确保支付模块所需的数据库表已创建
1040
909
  */
@@ -1070,249 +939,79 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
1070
939
  return [];
1071
940
  }
1072
941
  }
942
+ // === 新的 API 方法实现 ===
1073
943
  /**
1074
- * 获取未同步到服务器的订单
1075
- */
1076
- async getUnsyncedOrdersAsync() {
1077
- try {
1078
- const allOrders = await this.dbManager.getAll("order");
1079
- return allOrders.filter((order) => {
1080
- return (order.payment_status === import_types.PaymentStatus.Finished || order.payment_status === import_types.PaymentStatus.PartiallyPaid) && order.payment.some((payment) => !payment.isSynced);
1081
- });
1082
- } catch (error) {
1083
- console.error("[PaymentModule] 获取未同步订单失败", error);
1084
- return [];
1085
- }
1086
- }
1087
- /**
1088
- * 清理已完成且已同步的订单
1089
- * 注意:只清理完全支付的订单,部分支付的订单保留以便继续支付
1090
- */
1091
- async cleanupFinishedOrders() {
1092
- try {
1093
- const allOrders = await this.dbManager.getAll("order");
1094
- const finishedAndSyncedOrders = allOrders.filter(
1095
- (order) => order.payment_status === import_types.PaymentStatus.Finished && order.payment.every((payment) => payment.isSynced)
1096
- );
1097
- for (const order of finishedAndSyncedOrders) {
1098
- await this.deleteOrderAsync(order.uuid);
1099
- }
1100
- console.log(
1101
- `[PaymentModule] 清理了 ${finishedAndSyncedOrders.length} 个已完成且已同步的订单`
1102
- );
1103
- } catch (error) {
1104
- console.error("[PaymentModule] 清理已完成订单失败", error);
1105
- }
1106
- }
1107
- /**
1108
- * 检测未同步的订单并重新加入任务队列
1109
- *
1110
- * 此方法专门用于处理因网络问题导致任务队列执行失败但队列被清空的情况。
1111
- * 它会检查本地 IndexDB 中所有未同步的订单(isSynced: false),
1112
- * 并将这些订单重新添加到任务队列中。
1113
- *
1114
- * 使用场景:
1115
- * - 网络恢复后重新检查未同步的订单
1116
- * - 应用启动时检查并重新排队未完成的支付
1117
- * - 用户手动重试前的预检查
1118
- *
1119
- * @returns Promise<number> 返回重新加入队列的订单数量
1120
- */
1121
- async recheckAndRequeueUnsyncedOrders() {
1122
- this.logInfo("Starting recheckAndRequeueUnsyncedOrders");
1123
- try {
1124
- if (!this.app.tasksManager) {
1125
- console.warn(
1126
- "[PaymentModule] TasksManager 未初始化,无法重新排队未同步订单"
1127
- );
1128
- this.logWarning(
1129
- "TasksManager not initialized, cannot requeue unsynced orders"
1130
- );
1131
- return 0;
1132
- }
1133
- const unsyncedOrders = await this.getUnsyncedOrdersAsync();
1134
- if (unsyncedOrders.length === 0) {
1135
- console.log("[PaymentModule] 没有发现未同步的订单");
1136
- this.logInfo("No unsynced orders found");
1137
- return 0;
1138
- }
1139
- console.log(
1140
- `[PaymentModule] 发现 ${unsyncedOrders.length} 个未同步的订单,开始重新加入任务队列`
1141
- );
1142
- this.logInfo("Found unsynced orders, adding to sync queue", {
1143
- unsyncedCount: unsyncedOrders.length,
1144
- orderUuids: unsyncedOrders.map((o) => o.uuid)
1145
- });
1146
- let requeuedCount = 0;
1147
- for (const order of unsyncedOrders) {
1148
- const success = await this.reAddOrderToSyncQueue(order);
1149
- if (success) {
1150
- requeuedCount++;
1151
- }
1152
- }
1153
- console.log(
1154
- `[PaymentModule] 成功重新加入 ${requeuedCount} 个订单到任务队列`
1155
- );
1156
- this.logInfo("Successfully requeued unsynced orders", {
1157
- requeuedCount,
1158
- totalFound: unsyncedOrders.length
1159
- });
1160
- return requeuedCount;
1161
- } catch (error) {
1162
- console.error("[PaymentModule] 重新排队未同步订单失败", error);
1163
- this.logError("recheckAndRequeueUnsyncedOrders failed", error);
1164
- return 0;
1165
- }
1166
- }
1167
- /**
1168
- * 手动执行支付同步队列
1169
- * 外部可以调用此方法来触发支付同步任务的执行
1170
- *
1171
- * 注意:此方法只执行现有队列中的任务,不会检查未同步的订单。
1172
- * 如果需要检查未同步订单,请先调用 recheckAndRequeueUnsyncedOrders()
1173
- *
1174
- * 使用示例:
1175
- * ```typescript
1176
- * // 1. 先检查并重新排队未同步订单,然后执行队列
1177
- * const requeuedCount = await paymentModule.recheckAndRequeueUnsyncedOrders();
1178
- * if (requeuedCount > 0) {
1179
- * await paymentModule.runPaymentSyncQueue();
1180
- * }
1181
- *
1182
- * // 2. 或者直接执行现有队列(不检查未同步订单)
1183
- * await paymentModule.runPaymentSyncQueue();
1184
- * ```
944
+ * 智能金额舍入
945
+ *
946
+ * 根据指定的舍入间隔和规则对金额进行舍入处理
947
+ *
948
+ * @param originalAmount 原始金额
949
+ * @param interval 舍入间隔 (0.05, 0.1, 0.5, 1)
950
+ * @param rule 舍入规则 (standard, standard_down, always_up, always_down)
951
+ * @returns 舍入后的金额(保留两位小数的字符串)
1185
952
  */
1186
- async runPaymentSyncQueue() {
1187
- this.logInfo("Starting runPaymentSyncQueue");
953
+ async roundAmountAsync(originalAmount, interval, rule) {
1188
954
  try {
1189
- if (!this.app.tasksManager) {
1190
- console.warn("[PaymentModule] TasksManager 未初始化,无法执行同步队列");
1191
- this.logWarning("TasksManager not initialized, cannot run sync queue");
1192
- return;
1193
- }
1194
- const queue = this.app.tasksManager.getTaskQueue({
1195
- module: "payment",
1196
- queueId: "payment_sync"
1197
- });
1198
- if (!(queue == null ? void 0 : queue.length)) {
1199
- console.log("[PaymentModule] 支付同步队列无内容,不执行");
1200
- return;
1201
- }
1202
- console.log("[PaymentModule] 开始执行支付同步队列");
1203
- await this.app.tasksManager.run({
1204
- module: "payment",
1205
- queueId: "payment_sync",
1206
- callback: () => {
1207
- console.log("[PaymentModule] 支付同步队列执行完成");
1208
- if (this.logger) {
1209
- this.logger.addLog({
1210
- type: "info",
1211
- title: "[PaymentModule] Payment sync queue completed",
1212
- metadata: {}
1213
- });
1214
- }
1215
- }
1216
- });
1217
- this.logInfo("runPaymentSyncQueue completed successfully");
955
+ const amount = new import_decimal.Decimal(originalAmount);
956
+ const roundingInterval = new import_decimal.Decimal(interval);
957
+ if (roundingInterval.lte(0)) {
958
+ throw new Error("舍入间隔必须大于 0");
959
+ }
960
+ const supportedIntervals = [0.05, 0.1, 0.5, 1];
961
+ const intervalValue = roundingInterval.toNumber();
962
+ if (!supportedIntervals.includes(intervalValue)) {
963
+ console.warn(`[PaymentModule] 不支持的舍入间隔: ${intervalValue}, 支持的间隔: ${supportedIntervals.join(", ")}`);
964
+ }
965
+ const baseValue = amount.div(roundingInterval);
966
+ console.log(`[PaymentModule] 舍入计算 - 原始金额: ${amount.toString()}, 间隔: ${intervalValue}, 基础值: ${baseValue.toString()}, 规则: ${rule}`);
967
+ let roundedValue;
968
+ switch (rule) {
969
+ case import_types.RoundingRule.Standard:
970
+ case "standard":
971
+ roundedValue = this.standardRound(baseValue, true);
972
+ break;
973
+ case import_types.RoundingRule.StandardDown:
974
+ case "standard_down":
975
+ roundedValue = this.standardRound(baseValue, false);
976
+ break;
977
+ case import_types.RoundingRule.AlwaysUp:
978
+ case "always_up":
979
+ roundedValue = baseValue.ceil();
980
+ break;
981
+ case import_types.RoundingRule.AlwaysDown:
982
+ case "always_down":
983
+ roundedValue = baseValue.floor();
984
+ break;
985
+ default:
986
+ throw new Error(`不支持的舍入规则: ${rule}`);
987
+ }
988
+ const finalAmount = roundedValue.mul(roundingInterval);
989
+ const result = finalAmount.toFixed(2);
990
+ console.log(`[PaymentModule] 舍入结果 - 舍入值: ${roundedValue.toString()}, 最终金额: ${result}`);
991
+ return result;
1218
992
  } catch (error) {
1219
- console.error("[PaymentModule] 执行支付同步队列失败", error);
1220
- this.logError("runPaymentSyncQueue failed", error);
993
+ console.error("[PaymentModule] 金额舍入失败:", error);
994
+ throw new Error(`金额舍入失败: ${error instanceof Error ? error.message : String(error)}`);
1221
995
  }
1222
996
  }
1223
997
  /**
1224
- * 重新将订单添加到同步队列
1225
- * 用于处理因网络问题导致任务队列清空但订单未同步的情况
1226
- *
1227
- * @param order 要重新添加的订单
1228
- * @returns Promise<boolean> 是否成功添加到队列
1229
- */
1230
- async reAddOrderToSyncQueue(order) {
1231
- try {
1232
- const paymentData = {
1233
- payments: order.payment.map((payment) => ({
1234
- uuid: payment.uuid,
1235
- amount: payment.amount,
1236
- code: payment.code,
1237
- id: payment.id,
1238
- name: payment.name,
1239
- type: payment.type,
1240
- voucher_id: payment.voucher_id,
1241
- metadata: payment.metadata,
1242
- rounding_amount: payment.rounding_amount,
1243
- service_charge: payment.service_charge
1244
- })),
1245
- payment_status: order.payment_status === import_types.PaymentStatus.Finished ? "paid" : "partially_paid"
1246
- };
1247
- const existingQueue = this.app.tasksManager.getTaskQueue({
1248
- module: "payment",
1249
- queueId: "payment_sync"
1250
- });
1251
- const taskId = `payment_${order.uuid}`;
1252
- const taskExists = existingQueue == null ? void 0 : existingQueue.some((task) => task.id === taskId);
1253
- if (taskExists) {
1254
- console.log(
1255
- `[PaymentModule] 任务 ${taskId} 已存在于队列中,跳过重复添加`
1256
- );
1257
- return false;
1258
- }
1259
- await this.addToSyncQueue(order, paymentData);
1260
- console.log(`[PaymentModule] 订单 ${order.uuid} 已重新添加到同步队列`);
1261
- this.logInfo("Order re-added to sync queue", {
1262
- orderUuid: order.uuid,
1263
- orderId: order.order_id,
1264
- paymentStatus: order.payment_status,
1265
- unsyncedPayments: order.payment.filter((p) => !p.isSynced).length
1266
- });
1267
- return true;
1268
- } catch (error) {
1269
- console.error(
1270
- `[PaymentModule] 重新添加订单 ${order.uuid} 到同步队列失败`,
1271
- error
1272
- );
1273
- this.logError("Failed to re-add order to sync queue", error, {
1274
- orderUuid: order.uuid,
1275
- orderId: order.order_id
1276
- });
1277
- return false;
998
+ * 标准舍入处理(处理中点情况)
999
+ *
1000
+ * @param value 要舍入的值
1001
+ * @param midpointUp 中点是否向上舍入
1002
+ * @returns 舍入后的值
1003
+ */
1004
+ standardRound(value, midpointUp) {
1005
+ const floorValue = value.floor();
1006
+ const fractionalPart = value.minus(floorValue);
1007
+ if (fractionalPart.eq(0.5)) {
1008
+ return midpointUp ? floorValue.plus(1) : floorValue;
1009
+ } else if (fractionalPart.gt(0.5)) {
1010
+ return floorValue.plus(1);
1011
+ } else {
1012
+ return floorValue;
1278
1013
  }
1279
1014
  }
1280
- // === 新的 API 方法实现 ===
1281
- /**
1282
- * 删除支付项(新方法)
1283
- */
1284
- async deletePaymentItemAsync(orderUuid, paymentUuid) {
1285
- console.warn("[PaymentModule] deletePaymentItemAsync 暂时使用 deletePaymentAsync 实现");
1286
- return this.deletePaymentAsync(orderUuid, paymentUuid);
1287
- }
1288
- /**
1289
- * 更新支付项(新方法)
1290
- */
1291
- async updatePaymentItemAsync(orderUuid, paymentUuid, params) {
1292
- console.warn("[PaymentModule] updatePaymentItemAsync 暂时使用 updatePaymentAsync 实现");
1293
- return this.updatePaymentAsync(orderUuid, paymentUuid, params);
1294
- }
1295
- /**
1296
- * 获取订单剩余待付金额(新方法)
1297
- */
1298
- async getRemainingAmountAsync(orderUuid) {
1299
- console.warn("[PaymentModule] getRemainingAmountAsync 暂时使用 getRemainingOrderAmountAsync 实现");
1300
- return this.getRemainingOrderAmountAsync(orderUuid);
1301
- }
1302
- /**
1303
- * 获取订单剩余待付金额(基于用户输入的金额)(新方法)
1304
- */
1305
- async getRemainingAmountWithInputAsync(inputAmount, orderUuid) {
1306
- console.warn("[PaymentModule] getRemainingAmountWithInputAsync 暂时使用 getRemainingOrderAmountWithInputAsync 实现");
1307
- return this.getRemainingOrderAmountWithInputAsync(inputAmount, orderUuid);
1308
- }
1309
- /**
1310
- * 提交支付(新方法)
1311
- */
1312
- async submitPaymentAsync(orderUuid) {
1313
- console.warn("[PaymentModule] submitPaymentAsync 暂时使用 submitPayAsync 实现");
1314
- return this.submitPayAsync(orderUuid);
1315
- }
1316
1015
  };
1317
1016
  // Annotate the CommonJS export names for ESM import in node:
1318
1017
  0 && (module.exports = {