@pisell/pisellos 2.1.28 → 2.1.30

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.
@@ -49,6 +49,9 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
49
49
  this.defaultVersion = "1.0.0";
50
50
  this.isSolution = true;
51
51
  this.otherParams = {};
52
+ // LoggerManager 实例
53
+ // 计算缓存(用于性能优化)
54
+ this.calculationCache = {};
52
55
  }
53
56
  async initialize(core, options) {
54
57
  this.core = core;
@@ -344,7 +347,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
344
347
  totalInfoKeys: params.totalInfo ? Object.keys(params.totalInfo) : []
345
348
  });
346
349
  try {
347
- await this.resetStoreStateAsync();
350
+ this.resetStoreState();
348
351
  const validation = (0, import_utils.validateLocalOrderData)(params.orderData);
349
352
  if (!validation.valid) {
350
353
  throw (0, import_utils.createCheckoutError)(
@@ -394,13 +397,20 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
394
397
  }
395
398
  });
396
399
  this.store.currentOrder = paymentOrder;
397
- if (params.autoPayment) {
398
- }
399
400
  this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreated, {
400
401
  order: paymentOrder,
401
402
  timestamp: Date.now()
402
403
  });
404
+ const updateAmountStartTime = Date.now();
403
405
  await this.updateStateAmountToRemaining(false);
406
+ const updateAmountDuration = Date.now() - updateAmountStartTime;
407
+ this.logInfo("updateStateAmountToRemaining operation completed", {
408
+ operation: "updateStateAmountToRemaining",
409
+ orderUuid: paymentOrder.uuid,
410
+ orderId: paymentOrder.order_id,
411
+ duration: `${updateAmountDuration}ms`,
412
+ performance: updateAmountDuration > 200 ? "slow" : updateAmountDuration > 100 ? "medium" : "fast"
413
+ });
404
414
  this.logInfo("本地订单创建成功:", {
405
415
  localOrderId,
406
416
  uuid: paymentOrder.uuid,
@@ -475,7 +485,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
475
485
  );
476
486
  const paidAmount = activePayments.reduce((sum, p) => {
477
487
  const amt = new import_decimal.default(p.amount || "0");
478
- const rounding = new import_decimal.default(p.rounding_amount || "0").abs();
488
+ const rounding = new import_decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || "0").abs();
479
489
  return sum.plus(amt).plus(rounding);
480
490
  }, new import_decimal.default(0));
481
491
  const remaining = import_decimal.default.max(0, totalAmount.minus(paidAmount)).toFixed(
@@ -524,7 +534,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
524
534
  });
525
535
  const syncedAmount = activePayments.reduce((sum, p) => {
526
536
  const amt = new import_decimal.default(p.amount || "0");
527
- const rounding = new import_decimal.default(p.rounding_amount || "0").abs();
537
+ const rounding = new import_decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || "0").abs();
528
538
  return sum.plus(amt).plus(rounding);
529
539
  }, new import_decimal.default(0));
530
540
  const remainingExpectAmount = import_decimal.default.max(0, totalAmount.minus(syncedAmount)).toFixed(
@@ -589,7 +599,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
589
599
  timestamp: Date.now()
590
600
  });
591
601
  console.log("[Checkout] 结账流程完成:", order.id);
592
- await this.resetStoreStateAsync();
602
+ this.resetStoreState();
593
603
  return {
594
604
  success: true,
595
605
  orderId: String(order.id)
@@ -854,6 +864,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
854
864
  paymentItemWithType
855
865
  );
856
866
  this.logInfo("支付项添加成功");
867
+ this.clearCalculationCache();
857
868
  await this.updateStateAmountToRemaining();
858
869
  const remainingAmount = await this.calculateRemainingAmountAsync();
859
870
  if (Number(remainingAmount) > 0) {
@@ -944,6 +955,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
944
955
  paymentUuid
945
956
  );
946
957
  this.logInfo("Payment支付项删除完成", paymentItem);
958
+ this.clearCalculationCache();
947
959
  const currentOrderId = this.store.currentOrder.order_id;
948
960
  const isCurrentOrderReal = currentOrderId && !(0, import_utils.isVirtualOrderId)(currentOrderId);
949
961
  const updatedOrder = await this.payment.getPaymentOrderByUuidAsync(
@@ -1038,6 +1050,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1038
1050
  this.store.currentOrder.uuid,
1039
1051
  voucherPaymentItemsWithType
1040
1052
  );
1053
+ this.clearCalculationCache();
1041
1054
  const currentOrderId = this.store.currentOrder.order_id;
1042
1055
  const isCurrentOrderReal = currentOrderId && !(0, import_utils.isVirtualOrderId)(currentOrderId);
1043
1056
  const updatedOrder = await this.payment.getPaymentOrderByUuidAsync(
@@ -1117,6 +1130,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1117
1130
  if (this.store.localOrderData) {
1118
1131
  this.store.localOrderData.is_deposit = newDepositValue;
1119
1132
  }
1133
+ this.clearCalculationCache();
1120
1134
  this.updateStateAmountToRemaining(false);
1121
1135
  await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreated, {
1122
1136
  order: this.store.currentOrder,
@@ -1208,6 +1222,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1208
1222
  this.store.localOrderData.is_deposit = updateParams.is_deposit;
1209
1223
  }
1210
1224
  }
1225
+ this.clearCalculationCache();
1211
1226
  this.updateStateAmountToRemaining(false);
1212
1227
  await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreated, {
1213
1228
  order: this.store.currentOrder,
@@ -1237,6 +1252,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1237
1252
  */
1238
1253
  async manualSyncOrderAsync() {
1239
1254
  var _a, _b, _c, _d, _e;
1255
+ console.log("manualSyncOrderAsync called");
1240
1256
  this.logInfo("manualSyncOrderAsync called", {
1241
1257
  hasCurrentOrder: !!this.store.currentOrder,
1242
1258
  currentOrderId: (_a = this.store.currentOrder) == null ? void 0 : _a.order_id,
@@ -1263,7 +1279,9 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1263
1279
  totalAmount: this.store.currentOrder.total_amount,
1264
1280
  remainingAmount: await this.calculateRemainingAmountAsync()
1265
1281
  });
1282
+ console.time("manualSyncOrderAsync");
1266
1283
  const syncResult = await this.syncOrderToBackendWithReturn(true);
1284
+ console.timeEnd("manualSyncOrderAsync");
1267
1285
  this.logInfo("手动同步订单完成:", {
1268
1286
  orderUuid,
1269
1287
  syncResult,
@@ -1756,8 +1774,58 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1756
1774
  this.logError("Expired orders cleanup failed", { error: errorMessage });
1757
1775
  }
1758
1776
  }
1777
+ /**
1778
+ * 清除计算缓存
1779
+ */
1780
+ clearCalculationCache() {
1781
+ this.calculationCache = {};
1782
+ }
1783
+ /**
1784
+ * 批量获取订单数据(用于性能优化)
1785
+ * 一次性获取所有需要的数据,避免重复查询
1786
+ */
1787
+ async fetchOrderDataBatch() {
1788
+ if (!this.store.currentOrder) {
1789
+ return { paymentItems: [], currentOrder: null };
1790
+ }
1791
+ const orderUuid = this.store.currentOrder.uuid;
1792
+ const now = Date.now();
1793
+ const cacheValid = this.calculationCache.orderUuid === orderUuid && this.calculationCache.timestamp && now - this.calculationCache.timestamp < 5e3;
1794
+ if (cacheValid && this.calculationCache.paymentItems && this.calculationCache.currentOrder) {
1795
+ return {
1796
+ paymentItems: this.calculationCache.paymentItems,
1797
+ currentOrder: this.calculationCache.currentOrder
1798
+ };
1799
+ }
1800
+ const [paymentItems, currentOrder] = await Promise.all([
1801
+ this.payment.getPaymentItemsAsync(orderUuid, false),
1802
+ this.payment.getPaymentOrderByUuidAsync(orderUuid)
1803
+ ]);
1804
+ this.calculationCache = {
1805
+ paymentItems,
1806
+ currentOrder,
1807
+ orderUuid,
1808
+ timestamp: now
1809
+ };
1810
+ return { paymentItems, currentOrder };
1811
+ }
1812
+ /**
1813
+ * 从支付项数组计算已支付金额(纯计算,不查询数据库)
1814
+ */
1815
+ calculatePaidAmountFromItems(payments) {
1816
+ const paidAmount = payments.filter((payment) => payment.status !== "voided").reduce((sum, payment) => {
1817
+ const amount = new import_decimal.default(payment.amount || "0");
1818
+ const roundingAmount = new import_decimal.default(payment.rounding_amount || "0");
1819
+ const effectiveAmount = amount.add(roundingAmount.isNegative() ? roundingAmount.abs() : 0);
1820
+ return sum.add(effectiveAmount);
1821
+ }, new import_decimal.default(0));
1822
+ return paidAmount.toFixed(2);
1823
+ }
1759
1824
  /**
1760
1825
  * 计算已支付金额(从 Payment 模块获取最新数据)
1826
+ *
1827
+ * 注意:此方法保持独立性,可以单独调用。
1828
+ * 在 updateStateAmountToRemaining 等批量操作中会使用缓存优化。
1761
1829
  */
1762
1830
  async calculatePaidAmountAsync() {
1763
1831
  if (!this.store.currentOrder) {
@@ -1765,30 +1833,18 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1765
1833
  return "0.00";
1766
1834
  }
1767
1835
  try {
1836
+ const now = Date.now();
1837
+ const cacheValid = this.calculationCache.orderUuid === this.store.currentOrder.uuid && this.calculationCache.timestamp && now - this.calculationCache.timestamp < 5e3 && this.calculationCache.paidAmount;
1838
+ if (cacheValid && this.calculationCache.paidAmount) {
1839
+ return this.calculationCache.paidAmount;
1840
+ }
1768
1841
  const payments = await this.payment.getPaymentItemsAsync(
1769
1842
  this.store.currentOrder.uuid,
1770
1843
  false
1771
1844
  // 不包括已撤销的支付项
1772
1845
  );
1773
- const paidAmount = payments.filter((payment) => payment.status !== "voided").reduce((sum, payment) => {
1774
- const amount = new import_decimal.default(payment.amount || "0");
1775
- const roundingAmount = new import_decimal.default(payment.rounding_amount || "0");
1776
- const effectiveAmount = amount.add(roundingAmount.abs());
1777
- console.log(`[Checkout] 计算支付项: ${payment.code}`, {
1778
- originalAmount: amount.toFixed(2),
1779
- roundingAmount: roundingAmount.toFixed(2),
1780
- effectiveAmount: effectiveAmount.toFixed(2),
1781
- description: !roundingAmount.isZero() ? `抹零金额 ${roundingAmount.toFixed(2)} 元,有效支付增加 ${roundingAmount.abs().toFixed(2)} 元` : "无抹零",
1782
- // Decimal 精度验证
1783
- preciseCalculationValues: {
1784
- amount: amount.toString(),
1785
- roundingAmount: roundingAmount.toString(),
1786
- effectiveAmount: effectiveAmount.toString()
1787
- }
1788
- });
1789
- return sum.add(effectiveAmount);
1790
- }, new import_decimal.default(0));
1791
- const result = paidAmount.toFixed(2);
1846
+ const result = this.calculatePaidAmountFromItems(payments);
1847
+ this.calculationCache.paidAmount = result;
1792
1848
  this.logInfo("calculatePaidAmountAsync: 计算结果 =", result);
1793
1849
  return result;
1794
1850
  } catch (error) {
@@ -1796,41 +1852,82 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1796
1852
  return "0.00";
1797
1853
  }
1798
1854
  }
1855
+ /**
1856
+ * 从订单和支付项计算剩余金额(纯计算,不查询数据库)
1857
+ */
1858
+ calculateRemainingAmountFromData(currentOrder, paidAmount) {
1859
+ let totalAmount = new import_decimal.default(currentOrder.total_amount || "0");
1860
+ if (currentOrder.is_deposit && currentOrder.deposit_amount && Number(currentOrder.deposit_amount) > 0) {
1861
+ totalAmount = new import_decimal.default(currentOrder.deposit_amount);
1862
+ }
1863
+ const paid = new import_decimal.default(paidAmount);
1864
+ const remainingAmount = totalAmount.sub(paid);
1865
+ return import_decimal.default.max(0, remainingAmount).toFixed(2);
1866
+ }
1867
+ /**
1868
+ * 从订单和支付项计算剩余总金额(纯计算,排除定金)
1869
+ */
1870
+ calculateRemainingTotalAmountFromData(currentOrder, paidAmount) {
1871
+ const totalAmount = new import_decimal.default(currentOrder.total_amount || "0");
1872
+ const paid = new import_decimal.default(paidAmount);
1873
+ const remainingAmount = totalAmount.sub(paid);
1874
+ return import_decimal.default.max(0, remainingAmount).toFixed(2);
1875
+ }
1799
1876
  /**
1800
1877
  * 计算剩余未支付金额(从 Payment 模块获取最新数据)
1878
+ *
1879
+ * 注意:此方法保持独立性,可以单独调用。
1880
+ * 在 updateStateAmountToRemaining 等批量操作中会使用缓存优化。
1801
1881
  */
1802
1882
  async calculateRemainingAmountAsync() {
1803
1883
  if (!this.store.currentOrder) {
1804
1884
  this.logWarning("calculateRemainingAmountAsync: 没有当前订单");
1805
1885
  return "0.00";
1806
1886
  }
1807
- let totalAmount = new import_decimal.default(this.store.currentOrder.total_amount || "0");
1808
- const currentOrder = await this.payment.getPaymentOrderByUuidAsync(
1809
- this.store.currentOrder.uuid
1810
- );
1811
- if ((currentOrder == null ? void 0 : currentOrder.is_deposit) && (currentOrder == null ? void 0 : currentOrder.deposit_amount) && Number(currentOrder == null ? void 0 : currentOrder.deposit_amount) > 0) {
1812
- totalAmount = new import_decimal.default(currentOrder == null ? void 0 : currentOrder.deposit_amount);
1887
+ const { currentOrder } = await this.fetchOrderDataBatch();
1888
+ if (!currentOrder) {
1889
+ return "0.00";
1813
1890
  }
1814
1891
  const paidAmountStr = await this.calculatePaidAmountAsync();
1815
- const paidAmount = new import_decimal.default(paidAmountStr);
1816
- const remainingAmount = totalAmount.sub(paidAmount);
1817
- const result = import_decimal.default.max(0, remainingAmount).toFixed(2);
1892
+ const result = this.calculateRemainingAmountFromData(currentOrder, paidAmountStr);
1818
1893
  this.logInfo("calculateRemainingAmountAsync: 计算=", result);
1819
1894
  return result;
1820
1895
  }
1896
+ /**
1897
+ * 计算剩余未支付金额(排除定金计算,始终使用订单总金额)
1898
+ *
1899
+ * 注意:此方法保持独立性,可以单独调用。
1900
+ * 在 updateStateAmountToRemaining 等批量操作中会使用缓存优化。
1901
+ */
1902
+ async calculateRemainingTotalAmountAsync() {
1903
+ if (!this.store.currentOrder) {
1904
+ this.logWarning("calculateRemainingTotalAmountAsync: 没有当前订单");
1905
+ return "0.00";
1906
+ }
1907
+ const { currentOrder } = await this.fetchOrderDataBatch();
1908
+ if (!currentOrder) {
1909
+ return "0.00";
1910
+ }
1911
+ const paidAmountStr = await this.calculatePaidAmountAsync();
1912
+ const result = this.calculateRemainingTotalAmountFromData(currentOrder, paidAmountStr);
1913
+ this.logInfo("calculateRemainingTotalAmountAsync: 计算=", result);
1914
+ return result;
1915
+ }
1821
1916
  /**
1822
1917
  * 更新 balanceDueAmount 为当前剩余未支付金额(系统内部计算)
1823
1918
  */
1824
1919
  async updateBalanceDueAmount() {
1825
1920
  try {
1826
1921
  const remainingAmount = await this.calculateRemainingAmountAsync();
1922
+ const remainingTotalAmount = await this.calculateRemainingTotalAmountAsync();
1827
1923
  const currentBalanceDueAmount = this.store.balanceDueAmount;
1828
1924
  if (remainingAmount !== currentBalanceDueAmount) {
1829
1925
  this.store.balanceDueAmount = remainingAmount;
1830
1926
  await this.core.effects.emit(import_types.CheckoutHooks.OnBalanceDueAmountChanged, {
1831
1927
  oldAmount: currentBalanceDueAmount,
1832
1928
  newAmount: remainingAmount,
1833
- timestamp: Date.now()
1929
+ timestamp: Date.now(),
1930
+ totalAmount: remainingTotalAmount
1834
1931
  });
1835
1932
  this.logInfo("balanceDueAmount 已自动更新:", {
1836
1933
  oldAmount: currentBalanceDueAmount,
@@ -1848,14 +1945,25 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1848
1945
  }
1849
1946
  /**
1850
1947
  * 更新 stateAmount 为当前剩余未支付金额
1948
+ *
1949
+ * 优化版本:批量获取数据,避免重复查询数据库
1851
1950
  */
1852
1951
  async updateStateAmountToRemaining(checkOrder = true) {
1853
- var _a, _b, _c, _d;
1854
1952
  try {
1855
- if (((_a = this.store.currentOrder) == null ? void 0 : _a.is_deposit) === 1) {
1856
- const paymentItems = await this.payment.getPaymentItemsAsync(
1857
- (_b = this.store.currentOrder) == null ? void 0 : _b.uuid
1858
- );
1953
+ if (!this.store.currentOrder) {
1954
+ return;
1955
+ }
1956
+ console.time("updateStateAmountToRemaining");
1957
+ const { paymentItems, currentOrder } = await this.fetchOrderDataBatch();
1958
+ console.timeEnd("updateStateAmountToRemaining");
1959
+ if (!currentOrder) {
1960
+ this.logWarning("updateStateAmountToRemaining: 未找到当前订单");
1961
+ return;
1962
+ }
1963
+ const paidAmount = this.calculatePaidAmountFromItems(paymentItems);
1964
+ this.calculationCache.paidAmount = paidAmount;
1965
+ let needUpdateDepositStatus = false;
1966
+ if (currentOrder.is_deposit === 1) {
1859
1967
  const depositPaidAmount = paymentItems.filter(
1860
1968
  (item) => item.order_payment_type === "deposit" && item.status !== "voided"
1861
1969
  ).reduce((sum, item) => {
@@ -1864,40 +1972,72 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1864
1972
  }
1865
1973
  const amount = new import_decimal.default(item.amount || "0");
1866
1974
  const roundingAmount = new import_decimal.default(item.rounding_amount || "0");
1867
- return sum.add(amount.add(roundingAmount.abs()));
1975
+ return sum.add(amount.add(roundingAmount.isNegative() ? roundingAmount.abs() : 0));
1868
1976
  }, new import_decimal.default(0));
1869
- if (depositPaidAmount.gte((_c = this.store.currentOrder) == null ? void 0 : _c.deposit_amount)) {
1870
- this.store.currentOrder = {
1871
- ...this.store.currentOrder,
1872
- is_deposit: 0
1873
- };
1874
- await this.payment.updateOrderAsync((_d = this.store.currentOrder) == null ? void 0 : _d.uuid, {
1875
- is_deposit: 0
1876
- });
1977
+ if (depositPaidAmount.gte(currentOrder.deposit_amount || "0")) {
1978
+ needUpdateDepositStatus = true;
1979
+ currentOrder.is_deposit = 0;
1877
1980
  }
1878
1981
  }
1879
- const remainingAmount = await this.calculateRemainingAmountAsync();
1982
+ const remainingAmount = this.calculateRemainingAmountFromData(currentOrder, paidAmount);
1983
+ const remainingTotalAmount = this.calculateRemainingTotalAmountFromData(currentOrder, paidAmount);
1880
1984
  const currentStateAmount = this.store.stateAmount;
1985
+ const currentBalanceDueAmount = this.store.balanceDueAmount;
1986
+ let hasStateChanged = false;
1987
+ if (needUpdateDepositStatus) {
1988
+ this.store.currentOrder = {
1989
+ ...this.store.currentOrder,
1990
+ is_deposit: 0
1991
+ };
1992
+ await this.payment.updateOrderAsync(this.store.currentOrder.uuid, {
1993
+ is_deposit: 0
1994
+ });
1995
+ hasStateChanged = true;
1996
+ }
1997
+ console.time("updateStateAmountToRemaining: remainingAmount");
1881
1998
  if (remainingAmount !== currentStateAmount) {
1882
1999
  this.store.stateAmount = remainingAmount;
1883
- this.core.effects.emit(import_types.CheckoutHooks.OnStateAmountChanged, {
1884
- oldAmount: currentStateAmount,
1885
- newAmount: remainingAmount,
1886
- timestamp: Date.now()
1887
- });
2000
+ hasStateChanged = true;
2001
+ setTimeout(() => {
2002
+ this.core.effects.emit(`${this.name}:onStateAmountChanged`, {
2003
+ oldAmount: currentStateAmount,
2004
+ newAmount: remainingAmount,
2005
+ timestamp: Date.now(),
2006
+ totalAmount: remainingTotalAmount
2007
+ });
2008
+ }, 0);
1888
2009
  this.logInfo("stateAmount 已自动更新为剩余金额:", {
1889
2010
  oldAmount: currentStateAmount,
1890
2011
  newAmount: remainingAmount
1891
2012
  });
1892
- } else {
1893
- this.logInfo("stateAmount 无需更新,当前值已是最新:", {
2013
+ }
2014
+ console.timeEnd("updateStateAmountToRemaining: remainingAmount");
2015
+ console.time("updateStateAmountToRemaining: updateStateAmountToRemaining");
2016
+ if (remainingAmount !== currentBalanceDueAmount) {
2017
+ this.store.balanceDueAmount = remainingAmount;
2018
+ hasStateChanged = true;
2019
+ setTimeout(() => {
2020
+ this.core.effects.emit(`${this.name}:onBalanceDueAmountChanged`, {
2021
+ oldAmount: currentBalanceDueAmount,
2022
+ newAmount: remainingAmount,
2023
+ timestamp: Date.now(),
2024
+ totalAmount: remainingTotalAmount
2025
+ });
2026
+ }, 0);
2027
+ this.logInfo("balanceDueAmount 已自动更新:", {
2028
+ oldAmount: currentBalanceDueAmount,
2029
+ newAmount: remainingAmount
2030
+ });
2031
+ }
2032
+ console.timeEnd("updateStateAmountToRemaining: updateStateAmountToRemaining");
2033
+ if (!hasStateChanged) {
2034
+ this.logInfo("状态无需更新,当前值已是最新:", {
1894
2035
  stateAmount: currentStateAmount,
1895
2036
  remainingAmount
1896
2037
  });
1897
2038
  }
1898
- await this.updateBalanceDueAmount();
1899
2039
  if (checkOrder) {
1900
- await this.checkOrderPaymentCompletion();
2040
+ await this.checkOrderPaymentCompletionOptimized(paymentItems, remainingAmount);
1901
2041
  } else {
1902
2042
  this.logInfo("外部传入无需 checkOrder,不执行订单支付完成检测和同步");
1903
2043
  }
@@ -1905,10 +2045,81 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1905
2045
  this.logError("更新 stateAmount 为剩余金额失败:", error);
1906
2046
  }
1907
2047
  }
2048
+ /**
2049
+ * 检查订单支付是否完成(优化版,复用已获取的数据)
2050
+ *
2051
+ * @param paymentItems 已获取的支付项数据
2052
+ * @param remainingAmount 已计算的剩余金额
2053
+ */
2054
+ async checkOrderPaymentCompletionOptimized(paymentItems, remainingAmount) {
2055
+ try {
2056
+ if (!this.store.currentOrder) {
2057
+ return;
2058
+ }
2059
+ const remainingValue = new import_decimal.default(remainingAmount);
2060
+ if (remainingValue.lte(0)) {
2061
+ const totalAmount = this.store.currentOrder.total_amount;
2062
+ const paidAmount = this.calculationCache.paidAmount || "0.00";
2063
+ this.logInfo("检测到订单支付完成:", {
2064
+ orderUuid: this.store.currentOrder.uuid,
2065
+ orderId: this.store.currentOrder.order_id,
2066
+ totalAmount,
2067
+ paidAmount,
2068
+ remainingAmount,
2069
+ isOrderSynced: this.store.isOrderSynced
2070
+ });
2071
+ const hasPaymentItems = paymentItems.length > 0;
2072
+ const allPaymentsHaveVoucherId = hasPaymentItems && paymentItems.every(
2073
+ (item) => item.status !== "voided" && item.voucher_id
2074
+ );
2075
+ const shouldAutoSync = hasPaymentItems && !allPaymentsHaveVoucherId;
2076
+ this.logInfo("自动同步订单条件检查:", {
2077
+ paymentCount: paymentItems.length,
2078
+ hasPaymentItems,
2079
+ allHaveVoucherId: allPaymentsHaveVoucherId,
2080
+ isOrderSynced: this.store.isOrderSynced,
2081
+ shouldAutoSync,
2082
+ reason: shouldAutoSync ? "支付完成,需要同步最终支付状态" : "跳过同步",
2083
+ paymentItems: paymentItems.map((p) => ({
2084
+ uuid: p.uuid,
2085
+ code: p.code,
2086
+ amount: p.amount,
2087
+ rounding_amount: p.rounding_amount,
2088
+ effective_amount: (parseFloat(p.amount || "0") + Math.abs(parseFloat(Number(p.rounding_amount) > 0 ? "0" : p.rounding_amount || "0"))).toFixed(2),
2089
+ voucher_id: p.voucher_id,
2090
+ status: p.status
2091
+ }))
2092
+ });
2093
+ if (shouldAutoSync) {
2094
+ this.logInfo("满足自动同步条件,开始同步订单到后端...");
2095
+ await this.syncOrderToBackendWithReturn(false);
2096
+ } else {
2097
+ if (!hasPaymentItems) {
2098
+ this.logInfo("没有支付项,跳过订单同步");
2099
+ } else if (allPaymentsHaveVoucherId) {
2100
+ this.logInfo("所有支付项均为代金券类型,跳过订单同步");
2101
+ }
2102
+ }
2103
+ await this.core.effects.emit(`${this.name}:onOrderPaymentCompleted`, {
2104
+ orderUuid: this.store.currentOrder.uuid,
2105
+ orderId: this.store.currentOrder.order_id,
2106
+ totalAmount,
2107
+ paidAmount,
2108
+ remainingAmount,
2109
+ timestamp: Date.now()
2110
+ });
2111
+ }
2112
+ } catch (error) {
2113
+ this.logError("检查订单支付完成状态失败:", error);
2114
+ }
2115
+ }
1908
2116
  /**
1909
2117
  * 检查订单支付是否完成
1910
2118
  *
1911
2119
  * 当剩余待付款金额 <= 0 时,触发订单支付完成事件
2120
+ *
2121
+ * 注意:此方法保持独立性,可以单独调用。
2122
+ * 在 updateStateAmountToRemaining 中会使用优化版本。
1912
2123
  */
1913
2124
  async checkOrderPaymentCompletion() {
1914
2125
  try {
@@ -1950,7 +2161,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1950
2161
  code: p.code,
1951
2162
  amount: p.amount,
1952
2163
  rounding_amount: p.rounding_amount,
1953
- effective_amount: (parseFloat(p.amount || "0") + Math.abs(parseFloat(p.rounding_amount || "0"))).toFixed(2),
2164
+ effective_amount: (parseFloat(p.amount || "0") + Math.abs(parseFloat(Number(p.rounding_amount) > 0 ? "0" : p.rounding_amount || "0"))).toFixed(2),
1954
2165
  voucher_id: p.voucher_id,
1955
2166
  status: p.status
1956
2167
  }))
@@ -2247,6 +2458,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2247
2458
  this.logWarning("标记支付项已同步失败(不阻塞主流程)", { error: e });
2248
2459
  }
2249
2460
  this.store.isOrderSynced = true;
2461
+ this.clearCalculationCache();
2250
2462
  await this.core.effects.emit(import_types.CheckoutHooks.OnOrderSynced, {
2251
2463
  orderUuid: this.store.currentOrder.uuid,
2252
2464
  realOrderId,
@@ -2433,11 +2645,19 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2433
2645
  * @returns 舍入结果详情,包含原始金额、舍入后金额和舍入差额
2434
2646
  */
2435
2647
  async roundAmountAsync(amount) {
2436
- var _a, _b;
2648
+ var _a, _b, _c;
2649
+ const cashManualPayment = this.store.paymentMethods.find((p) => p.code === "CASHMANUAL");
2650
+ if (!((_a = cashManualPayment == null ? void 0 : cashManualPayment.metadata) == null ? void 0 : _a.order_rounding_switch)) {
2651
+ return {
2652
+ originalAmount: amount.toString(),
2653
+ roundedAmount: amount.toString(),
2654
+ roundingDifference: "0.00"
2655
+ };
2656
+ }
2437
2657
  const result = await this.payment.roundAmountAsync(
2438
2658
  amount,
2439
- (_a = this.otherParams.order_rounding_setting) == null ? void 0 : _a.interval,
2440
- (_b = this.otherParams.order_rounding_setting) == null ? void 0 : _b.type
2659
+ (_b = this.otherParams.order_rounding_setting) == null ? void 0 : _b.interval,
2660
+ (_c = this.otherParams.order_rounding_setting) == null ? void 0 : _c.type
2441
2661
  );
2442
2662
  return result;
2443
2663
  }
@@ -2454,8 +2674,10 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2454
2674
  * 重置 store 状态
2455
2675
  *
2456
2676
  * 在创建新订单前调用,确保状态完全干净
2677
+ *
2678
+ * 🚀 性能优化:改为同步方法,事件发射不阻塞主流程
2457
2679
  */
2458
- async resetStoreStateAsync() {
2680
+ resetStoreState() {
2459
2681
  try {
2460
2682
  const prevOrderInfo = this.store.currentOrder ? {
2461
2683
  uuid: this.store.currentOrder.uuid,
@@ -2472,12 +2694,15 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2472
2694
  this.store.lastError = void 0;
2473
2695
  this.store.cartItems = [];
2474
2696
  this.payment.wallet.clearAllCache();
2697
+ this.clearCalculationCache();
2475
2698
  console.log("[Checkout] Store 状态重置完成");
2476
2699
  if (prevOrderInfo) {
2477
- await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCleared, {
2478
- previousOrder: prevOrderInfo,
2479
- timestamp: Date.now()
2480
- });
2700
+ setTimeout(() => {
2701
+ this.core.effects.emit(import_types.CheckoutHooks.OnOrderCleared, {
2702
+ previousOrder: prevOrderInfo,
2703
+ timestamp: Date.now()
2704
+ });
2705
+ }, 0);
2481
2706
  }
2482
2707
  } catch (error) {
2483
2708
  console.error("[Checkout] 重置 store 状态失败:", error);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "2.1.28",
4
+ "version": "2.1.30",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",