@pisell/pisellos 0.0.567 → 0.0.568

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 (228) hide show
  1. package/dist/core/index.js +6 -9
  2. package/dist/model/strategy/adapter/walletPass/evaluator.js +0 -2
  3. package/dist/model/strategy/adapter/walletPass/example.js +3 -26
  4. package/dist/model/strategy/adapter/walletPass/utils.js +0 -3
  5. package/dist/model/strategy/strategy-example.js +5 -19
  6. package/dist/modules/Cart/index.js +0 -3
  7. package/dist/modules/Cart/utils/cartProduct.js +0 -1
  8. package/dist/modules/Date/index.js +1 -5
  9. package/dist/modules/Discount/index.js +1 -4
  10. package/dist/modules/OpenData/index.js +0 -2
  11. package/dist/modules/Order/index.d.ts +1 -1
  12. package/dist/modules/Order/index.js +14 -41
  13. package/dist/modules/Payment/index.js +142 -270
  14. package/dist/modules/Payment/walletpass.js +4 -5
  15. package/dist/modules/Rules/index.js +0 -7
  16. package/dist/modules/Schedule/utils.js +0 -1
  17. package/dist/modules/Step/index.js +0 -1
  18. package/dist/plugins/request.js +1 -4
  19. package/dist/plugins/window.js +2 -6
  20. package/dist/server/index.js +88 -121
  21. package/dist/server/modules/menu/index.js +32 -41
  22. package/dist/server/modules/products/index.js +29 -49
  23. package/dist/server/modules/quotation/index.js +29 -38
  24. package/dist/server/modules/resource/index.js +3 -4
  25. package/dist/server/modules/schedule/index.js +32 -40
  26. package/dist/server/utils/product.js +0 -1
  27. package/dist/solution/BookingByStep/index.d.ts +1 -1
  28. package/dist/solution/BookingByStep/index.js +7 -59
  29. package/dist/solution/BookingByStep/utils/capacity.js +1 -11
  30. package/dist/solution/BookingByStep/utils/resources.js +1 -3
  31. package/dist/solution/BookingByStep/utils/timeslots.js +2 -43
  32. package/dist/solution/BookingTicket/index.d.ts +1 -1
  33. package/dist/solution/BookingTicket/index.js +5 -7
  34. package/dist/solution/BookingTicket/utils/scan/handleScan.js +25 -31
  35. package/dist/solution/BookingTicket/utils/scan/index.js +6 -10
  36. package/dist/solution/BuyTickets/index.js +9 -12
  37. package/dist/solution/Checkout/index.js +177 -246
  38. package/dist/solution/Checkout/utils/index.js +4 -16
  39. package/dist/solution/RegisterAndLogin/index.js +30 -76
  40. package/dist/solution/ScanOrder/index.js +50 -60
  41. package/dist/solution/ShopDiscount/index.js +2 -7
  42. package/dist/solution/VenueBooking/index.d.ts +5 -0
  43. package/dist/solution/VenueBooking/index.js +364 -327
  44. package/dist/utils/task.js +15 -18
  45. package/dist/utils/watch.js +0 -1
  46. package/lib/apis/picoding.js +2 -0
  47. package/lib/core/index.js +130 -131
  48. package/lib/effects/index.js +46 -57
  49. package/lib/index.js +92 -53
  50. package/lib/model/index.js +14 -21
  51. package/lib/model/strategy/adapter/dataVariant/adapter.js +38 -50
  52. package/lib/model/strategy/adapter/dataVariant/evaluator.js +162 -236
  53. package/lib/model/strategy/adapter/dataVariant/examples.js +229 -237
  54. package/lib/model/strategy/adapter/dataVariant/index.js +39 -34
  55. package/lib/model/strategy/adapter/dataVariant/type.js +57 -28
  56. package/lib/model/strategy/adapter/index.js +100 -64
  57. package/lib/model/strategy/adapter/itemRule/adapter.js +156 -144
  58. package/lib/model/strategy/adapter/itemRule/evaluator.js +36 -48
  59. package/lib/model/strategy/adapter/itemRule/examples.js +295 -225
  60. package/lib/model/strategy/adapter/itemRule/index.js +83 -57
  61. package/lib/model/strategy/adapter/itemRule/type.js +97 -36
  62. package/lib/model/strategy/adapter/promotion/adapter.js +84 -63
  63. package/lib/model/strategy/adapter/promotion/evaluator.js +381 -231
  64. package/lib/model/strategy/adapter/promotion/examples.js +139 -159
  65. package/lib/model/strategy/adapter/promotion/index.js +1 -49
  66. package/lib/model/strategy/adapter/promotion/type.js +199 -35
  67. package/lib/model/strategy/adapter/type.js +4 -16
  68. package/lib/model/strategy/adapter/walletPass/evaluator.js +180 -152
  69. package/lib/model/strategy/adapter/walletPass/example.js +217 -190
  70. package/lib/model/strategy/adapter/walletPass/index.js +75 -51
  71. package/lib/model/strategy/adapter/walletPass/locales.js +36 -58
  72. package/lib/model/strategy/adapter/walletPass/type.js +4 -16
  73. package/lib/model/strategy/adapter/walletPass/utils.js +652 -402
  74. package/lib/model/strategy/engine.js +270 -168
  75. package/lib/model/strategy/index.js +49 -34
  76. package/lib/model/strategy/strategy-example.js +243 -239
  77. package/lib/model/strategy/type.js +100 -40
  78. package/lib/modules/Account/index.js +39 -53
  79. package/lib/modules/Account/types.js +20 -33
  80. package/lib/modules/AccountList/index.js +116 -154
  81. package/lib/modules/AccountList/types.js +30 -31
  82. package/lib/modules/AccountList/utils.js +18 -30
  83. package/lib/modules/BaseModule.js +22 -45
  84. package/lib/modules/Cart/index.js +170 -124
  85. package/lib/modules/Cart/types.js +46 -51
  86. package/lib/modules/Cart/utils/cartAccount.js +40 -39
  87. package/lib/modules/Cart/utils/cartDate.js +56 -61
  88. package/lib/modules/Cart/utils/cartDiscount.js +28 -33
  89. package/lib/modules/Cart/utils/cartNote.js +27 -32
  90. package/lib/modules/Cart/utils/cartProduct.js +306 -241
  91. package/lib/modules/Cart/utils/cartRelationForms.js +29 -35
  92. package/lib/modules/Cart/utils/cartResource.js +72 -78
  93. package/lib/modules/Cart/utils/changePrice.js +26 -62
  94. package/lib/modules/Cart/utils/index.js +106 -48
  95. package/lib/modules/Customer/constants.js +13 -34
  96. package/lib/modules/Customer/index.js +216 -153
  97. package/lib/modules/Customer/types.js +38 -35
  98. package/lib/modules/Date/index.js +116 -115
  99. package/lib/modules/Date/types.js +16 -28
  100. package/lib/modules/Date/utils.js +174 -123
  101. package/lib/modules/Discount/index.js +117 -113
  102. package/lib/modules/Discount/types.js +9 -31
  103. package/lib/modules/Guests/index.js +30 -56
  104. package/lib/modules/Guests/types.js +23 -33
  105. package/lib/modules/Holder/index.js +209 -189
  106. package/lib/modules/Holder/types.js +4 -16
  107. package/lib/modules/Holder/utils.js +20 -49
  108. package/lib/modules/OpenData/index.js +63 -74
  109. package/lib/modules/OpenData/types.js +4 -16
  110. package/lib/modules/OpenData/utils.js +44 -78
  111. package/lib/modules/Order/index.d.ts +1 -1
  112. package/lib/modules/Order/index.js +332 -320
  113. package/lib/modules/Order/types.js +24 -33
  114. package/lib/modules/Order/utils.js +350 -284
  115. package/lib/modules/Payment/cash.js +20 -33
  116. package/lib/modules/Payment/cashRecommendationAlgorithm.js +145 -76
  117. package/lib/modules/Payment/eftpos.js +16 -30
  118. package/lib/modules/Payment/index.js +566 -432
  119. package/lib/modules/Payment/mx51.js +1 -0
  120. package/lib/modules/Payment/types.js +216 -107
  121. package/lib/modules/Payment/utils.js +50 -47
  122. package/lib/modules/Payment/walletpass.js +221 -203
  123. package/lib/modules/Product/index.js +51 -46
  124. package/lib/modules/Product/types.js +4 -16
  125. package/lib/modules/Product/utils.js +32 -33
  126. package/lib/modules/ProductList/index.js +111 -110
  127. package/lib/modules/ProductList/types.js +9 -31
  128. package/lib/modules/Quotation/index.js +60 -82
  129. package/lib/modules/Quotation/types.js +4 -16
  130. package/lib/modules/Resource/index.js +27 -59
  131. package/lib/modules/Resource/types.js +22 -32
  132. package/lib/modules/Resource/utils.js +30 -38
  133. package/lib/modules/Rules/index.js +1172 -872
  134. package/lib/modules/Rules/types.js +17 -40
  135. package/lib/modules/SalesSummary/index.js +59 -68
  136. package/lib/modules/SalesSummary/types.js +4 -16
  137. package/lib/modules/SalesSummary/utils.js +176 -193
  138. package/lib/modules/ScanOrderLogger/index.js +59 -79
  139. package/lib/modules/ScanOrderLogger/providers/feishu.js +54 -78
  140. package/lib/modules/ScanOrderLogger/providers/grafana.js +13 -36
  141. package/lib/modules/ScanOrderLogger/types.js +4 -16
  142. package/lib/modules/Schedule/getDateIsInSchedule.js +334 -167
  143. package/lib/modules/Schedule/index.js +97 -107
  144. package/lib/modules/Schedule/type.js +4 -16
  145. package/lib/modules/Schedule/types.js +4 -16
  146. package/lib/modules/Schedule/utils.js +433 -291
  147. package/lib/modules/Step/index.js +40 -52
  148. package/lib/modules/Step/tyeps.js +4 -16
  149. package/lib/modules/Summary/index.js +66 -70
  150. package/lib/modules/Summary/types.js +4 -16
  151. package/lib/modules/Summary/utils.js +782 -429
  152. package/lib/modules/index.js +212 -57
  153. package/lib/plugins/app.js +4 -16
  154. package/lib/plugins/index.js +36 -25
  155. package/lib/plugins/request.js +137 -126
  156. package/lib/plugins/shopStore.js +4 -16
  157. package/lib/plugins/user.js +4 -16
  158. package/lib/plugins/window.js +171 -179
  159. package/lib/server/index.js +882 -623
  160. package/lib/server/modules/index.js +85 -59
  161. package/lib/server/modules/menu/index.js +146 -122
  162. package/lib/server/modules/menu/types.js +18 -31
  163. package/lib/server/modules/order/index.js +195 -231
  164. package/lib/server/modules/order/types.js +107 -32
  165. package/lib/server/modules/order/utils/filterBookings.js +174 -140
  166. package/lib/server/modules/order/utils/filterOrders.js +89 -60
  167. package/lib/server/modules/products/index.js +430 -335
  168. package/lib/server/modules/products/types.js +41 -34
  169. package/lib/server/modules/quotation/index.js +76 -77
  170. package/lib/server/modules/quotation/types.js +21 -31
  171. package/lib/server/modules/resource/index.js +216 -187
  172. package/lib/server/modules/resource/types.js +42 -33
  173. package/lib/server/modules/schedule/index.js +134 -119
  174. package/lib/server/modules/schedule/types.js +14 -21
  175. package/lib/server/modules/schedule/utils.js +334 -163
  176. package/lib/server/types.js +4 -16
  177. package/lib/server/utils/index.js +25 -23
  178. package/lib/server/utils/product.js +196 -139
  179. package/lib/server/utils/schedule.js +34 -41
  180. package/lib/server/utils/time.js +40 -49
  181. package/lib/solution/BookingByStep/index.d.ts +1 -1
  182. package/lib/solution/BookingByStep/index.js +1530 -1343
  183. package/lib/solution/BookingByStep/types.js +40 -99
  184. package/lib/solution/BookingByStep/utils/capacity.js +192 -160
  185. package/lib/solution/BookingByStep/utils/products.js +42 -52
  186. package/lib/solution/BookingByStep/utils/resources.js +527 -330
  187. package/lib/solution/BookingByStep/utils/stock.js +65 -44
  188. package/lib/solution/BookingByStep/utils/timeslots.js +129 -131
  189. package/lib/solution/BookingTicket/index.d.ts +1 -1
  190. package/lib/solution/BookingTicket/index.js +147 -122
  191. package/lib/solution/BookingTicket/types.js +38 -64
  192. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +64 -80
  193. package/lib/solution/BookingTicket/utils/scan/handleScan.js +82 -80
  194. package/lib/solution/BookingTicket/utils/scan/index.js +90 -94
  195. package/lib/solution/BookingTicket/utils/scan/scanCache.js +90 -43
  196. package/lib/solution/BuyTickets/index.js +67 -70
  197. package/lib/solution/BuyTickets/types.js +22 -38
  198. package/lib/solution/Checkout/index.js +1451 -1158
  199. package/lib/solution/Checkout/types.js +91 -61
  200. package/lib/solution/Checkout/utils/index.js +227 -158
  201. package/lib/solution/PlaceOrder/index.js +55 -0
  202. package/lib/solution/RegisterAndLogin/config.js +493 -460
  203. package/lib/solution/RegisterAndLogin/index.js +633 -630
  204. package/lib/solution/RegisterAndLogin/types.js +189 -76
  205. package/lib/solution/RegisterAndLogin/utils.js +183 -125
  206. package/lib/solution/Sales/index.js +218 -200
  207. package/lib/solution/Sales/types.js +27 -33
  208. package/lib/solution/ScanOrder/index.js +803 -840
  209. package/lib/solution/ScanOrder/types.js +34 -34
  210. package/lib/solution/ScanOrder/utils.js +372 -331
  211. package/lib/solution/ShopDiscount/index.js +230 -236
  212. package/lib/solution/ShopDiscount/types.js +15 -37
  213. package/lib/solution/ShopDiscount/utils.js +309 -172
  214. package/lib/solution/VenueBooking/index.d.ts +5 -0
  215. package/lib/solution/VenueBooking/index.js +886 -929
  216. package/lib/solution/VenueBooking/types.js +20 -40
  217. package/lib/solution/VenueBooking/utils/dateSummary.js +22 -54
  218. package/lib/solution/VenueBooking/utils/resource.js +31 -54
  219. package/lib/solution/VenueBooking/utils/slotMerge.js +88 -106
  220. package/lib/solution/VenueBooking/utils/smartPricing.js +112 -100
  221. package/lib/solution/VenueBooking/utils/timeSlot.js +133 -132
  222. package/lib/solution/VenueBooking/utils.js +130 -67
  223. package/lib/solution/index.js +102 -37
  224. package/lib/store/createStore.js +32 -29
  225. package/lib/types/index.js +4 -16
  226. package/lib/utils/task.js +36 -36
  227. package/lib/utils/watch.js +81 -47
  228. package/package.json +2 -1
@@ -1,348 +1,361 @@
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;
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ CheckoutImpl: true
18
8
  };
19
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/solution/Checkout/index.ts
31
- var Checkout_exports = {};
32
- __export(Checkout_exports, {
33
- CheckoutImpl: () => CheckoutImpl
9
+ exports.CheckoutImpl = void 0;
10
+ var _BaseModule = require("../../modules/BaseModule");
11
+ var _decimal = _interopRequireDefault(require("decimal.js"));
12
+ var _Order = require("../../modules/Order");
13
+ var _Payment = require("../../modules/Payment");
14
+ var _types = require("./types");
15
+ Object.keys(_types).forEach(function (key) {
16
+ if (key === "default" || key === "__esModule") return;
17
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
18
+ if (key in exports && exports[key] === _types[key]) return;
19
+ Object.defineProperty(exports, key, {
20
+ enumerable: true,
21
+ get: function () {
22
+ return _types[key];
23
+ }
24
+ });
34
25
  });
35
- module.exports = __toCommonJS(Checkout_exports);
36
- var import_BaseModule = require("../../modules/BaseModule");
37
- var import_decimal = __toESM(require("decimal.js"));
38
- var import_Order = require("../../modules/Order");
39
- var import_Payment = require("../../modules/Payment");
40
- var import_types = require("./types");
41
- var import_types2 = require("../../modules/Payment/types");
42
- var import_utils = require("./utils");
43
- var import_utils2 = require("../../modules/Cart/utils");
44
- __reExport(Checkout_exports, require("./types"), module.exports);
45
- var CheckoutImpl = class extends import_BaseModule.BaseModule {
26
+ var _types2 = require("../../modules/Payment/types");
27
+ var _utils = require("./utils");
28
+ var _utils2 = require("../../modules/Cart/utils");
29
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30
+ /**
31
+ * 结账解决方案实现
32
+ *
33
+ * 整合订单处理和支付功能,提供完整的结账流程管理。
34
+ * 支持多种支付方式,提供实时状态跟踪和错误处理。
35
+ */
36
+ class CheckoutImpl extends _BaseModule.BaseModule {
37
+ defaultName = 'checkout';
38
+ defaultVersion = '1.0.0';
39
+ isSolution = true;
40
+ request;
41
+ store;
42
+ otherParams = {};
43
+ logger; // LoggerManager 实例
44
+
45
+ // 计算缓存(用于性能优化)
46
+ calculationCache = {};
47
+
48
+ // 同步订单到后端锁(按订单维度),防止短时间内重复触发导致同一订单多次同步
49
+ syncOrderToBackendInFlightByOrderKey = new Map();
50
+
51
+ // 直接挂载的模块
52
+ order;
53
+ payment;
46
54
  constructor(name, version) {
47
- super(name || "checkout", version || "1.0.0");
48
- this.defaultName = "checkout";
49
- this.defaultVersion = "1.0.0";
50
- this.isSolution = true;
51
- this.otherParams = {};
52
- // LoggerManager 实例
53
- // 计算缓存(用于性能优化)
54
- this.calculationCache = {};
55
- // 同步订单到后端锁(按订单维度),防止短时间内重复触发导致同一订单多次同步
56
- this.syncOrderToBackendInFlightByOrderKey = /* @__PURE__ */ new Map();
55
+ super(name || 'checkout', version || '1.0.0');
57
56
  }
58
57
  async initialize(core, options) {
59
58
  this.core = core;
60
59
  this.otherParams = options.otherParams || {};
61
- this.request = core.getPlugin("request");
60
+
61
+ // 获取依赖的插件
62
+ this.request = core.getPlugin('request');
62
63
  if (!this.request) {
63
- throw new Error("Checkout 解决方案需要 request 插件支持");
64
+ throw new Error('Checkout 解决方案需要 request 插件支持');
64
65
  }
65
- const appPlugin = core.getPlugin("app");
66
+
67
+ // 获取 logger 实例
68
+ const appPlugin = core.getPlugin('app');
66
69
  if (!appPlugin) {
67
- throw new Error("Checkout 解决方案需要 app 插件支持");
70
+ throw new Error('Checkout 解决方案需要 app 插件支持');
68
71
  }
69
72
  const app = appPlugin.getApp();
70
73
  this.logger = app.logger;
71
- this.order = new import_Order.OrderModule();
72
- this.payment = new import_Payment.PaymentModule();
74
+
75
+ // 初始化模块
76
+ this.order = new _Order.OrderModule();
77
+ this.payment = new _Payment.PaymentModule();
78
+
79
+ // 初始化状态
73
80
  this.store = {
74
81
  cartItems: [],
75
82
  paymentMethods: [],
76
- stateAmount: "0.00",
77
- balanceDueAmount: "0.00",
78
- cartSummary: void 0,
83
+ stateAmount: '0.00',
84
+ balanceDueAmount: '0.00',
85
+ cartSummary: undefined,
79
86
  isOrderSynced: false,
80
- currentCustomer: void 0
87
+ currentCustomer: undefined
81
88
  };
89
+
90
+ // 注册并初始化子模块
82
91
  await this.initializeSubModules(core, options);
92
+
93
+ // 预加载支付方式(利用缓存机制)
83
94
  await this.preloadPaymentMethods();
95
+
96
+ // 清理过期的已同步订单数据
84
97
  await this.cleanupExpiredOrdersAsync();
85
- console.log("[Checkout] 初始化完成");
86
98
  await this.core.effects.emit(`${this.name}:onCheckoutInitialized`, {
87
99
  timestamp: Date.now()
88
100
  });
89
- this.logInfo("CheckoutModule initialized successfully");
101
+ this.logInfo('CheckoutModule initialized successfully');
90
102
  }
103
+
91
104
  /**
92
105
  * 记录信息日志
93
106
  */
94
107
  logInfo(title, metadata) {
95
108
  if (this.logger) {
96
109
  this.logger.addLog({
97
- type: "info",
110
+ type: 'info',
98
111
  title: `[CheckoutModule] ${this.getCurrentOrderId()} ${title}`,
99
112
  metadata: metadata || {}
100
113
  });
101
114
  }
102
115
  }
116
+
103
117
  /**
104
118
  * 记录警告日志
105
119
  */
106
120
  logWarning(title, metadata) {
107
121
  if (this.logger) {
108
122
  this.logger.addLog({
109
- type: "warning",
123
+ type: 'warning',
110
124
  title: `[CheckoutModule] ${title}`,
111
125
  metadata: metadata || {}
112
126
  });
113
127
  }
114
128
  }
129
+
115
130
  /**
116
131
  * 记录错误日志
117
132
  */
118
133
  logError(title, metadata) {
119
134
  if (this.logger) {
120
135
  this.logger.addLog({
121
- type: "error",
136
+ type: 'error',
122
137
  title: `[CheckoutModule] ${title}`,
123
138
  metadata: metadata || {}
124
139
  });
125
140
  }
126
141
  }
142
+
127
143
  /**
128
144
  * 初始化子模块
129
145
  */
130
146
  async initializeSubModules(core, options) {
131
- var _a, _b;
147
+ // 初始化订单模块
132
148
  core.registerModule(this.order, {
133
- store: ((_a = options.store) == null ? void 0 : _a.order) || {},
134
- otherParams: { ...this.otherParams, fatherModule: this.name }
149
+ store: options.store?.order || {},
150
+ otherParams: {
151
+ ...this.otherParams,
152
+ fatherModule: this.name
153
+ }
135
154
  });
155
+
156
+ // 初始化支付模块
136
157
  core.registerModule(this.payment, {
137
- store: ((_b = options.store) == null ? void 0 : _b.payment) || {},
138
- otherParams: { ...this.otherParams, fatherModule: this.name }
158
+ store: options.store?.payment || {},
159
+ otherParams: {
160
+ ...this.otherParams,
161
+ fatherModule: this.name
162
+ }
139
163
  });
164
+
165
+ // 监听支付模块事件
140
166
  this.setupPaymentEventListeners();
141
167
  }
168
+
142
169
  /**
143
170
  * 设置支付模块事件监听
144
171
  */
145
172
  setupPaymentEventListeners() {
146
- this.core.effects.on("payment:onPaymentSyncSuccess", async (data) => {
147
- var _a;
148
- if (((_a = this.store.currentOrder) == null ? void 0 : _a.uuid) === data.orderUuid) {
173
+ // 监听支付成功事件
174
+ this.core.effects.on('payment:onPaymentSyncSuccess', async data => {
175
+ if (this.store.currentOrder?.uuid === data.orderUuid) {
149
176
  await this.handlePaymentSuccess(data);
150
177
  }
151
178
  });
152
- this.core.effects.on("payment:onPaymentSyncError", async (data) => {
153
- var _a;
154
- if (((_a = this.store.currentOrder) == null ? void 0 : _a.uuid) === data.orderUuid) {
179
+
180
+ // 监听支付失败事件
181
+ this.core.effects.on('payment:onPaymentSyncError', async data => {
182
+ if (this.store.currentOrder?.uuid === data.orderUuid) {
155
183
  await this.handlePaymentError(data);
156
184
  }
157
185
  });
158
- this.core.effects.on(
159
- import_types2.PaymentHooks.OnPaymentMethodsLoaded,
160
- async (methods) => {
161
- console.log("[Checkout] 收到支付方式加载完成事件:", methods.length);
162
- this.store.paymentMethods = methods;
163
- }
164
- );
165
- this.core.effects.on(
166
- import_types2.PaymentHooks.OnPaymentMethodsChanged,
167
- async (data) => {
168
- console.log("[Checkout] 收到支付方式变更事件:", {
169
- oldCount: data.oldMethods.length,
170
- newCount: data.newMethods.length
171
- });
172
- this.store.paymentMethods = data.newMethods;
173
- }
174
- );
186
+
187
+ // 监听支付方式加载完成事件
188
+ this.core.effects.on(_types2.PaymentHooks.OnPaymentMethodsLoaded, async methods => {
189
+ this.store.paymentMethods = methods;
190
+ });
191
+
192
+ // 监听支付方式变更事件
193
+ this.core.effects.on(_types2.PaymentHooks.OnPaymentMethodsChanged, async data => {
194
+ this.store.paymentMethods = data.newMethods;
195
+ });
175
196
  }
197
+
176
198
  /**
177
199
  * 初始化结账流程
178
200
  */
179
201
  async initializeCheckoutAsync(params) {
180
- var _a;
181
- this.logInfo("initializeCheckoutAsync called", {
182
- cartItemsCount: ((_a = params.cartItems) == null ? void 0 : _a.length) || 0,
202
+ this.logInfo('initializeCheckoutAsync called', {
203
+ cartItemsCount: params.cartItems?.length || 0,
183
204
  orderType: params.orderType,
184
205
  platform: params.platform
185
206
  });
186
207
  try {
208
+ // 验证参数
187
209
  const validation = this.validateCheckoutParams(params);
188
210
  if (!validation.valid) {
189
- throw (0, import_utils.createCheckoutError)(
190
- import_types.CheckoutErrorType.ValidationFailed,
191
- `参数验证失败: ${validation.errors.join(", ")}`
192
- );
211
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, `参数验证失败: ${validation.errors.join(', ')}`);
193
212
  }
213
+
214
+ // 保存购物车数据
194
215
  this.store.cartItems = params.cartItems;
195
- console.log("[Checkout] 结账流程初始化完成");
196
216
  } catch (error) {
197
- await this.handleError(error, import_types.CheckoutErrorType.UnknownError);
217
+ await this.handleError(error, _types.CheckoutErrorType.UnknownError);
198
218
  throw error;
199
219
  }
200
220
  }
201
221
  getHolderIdFromBooking(obj) {
202
- var _a;
203
- if (!obj)
204
- return void 0;
205
- let ret = obj.holder_id || ((_a = obj.holder) == null ? void 0 : _a.form_record);
222
+ if (!obj) return undefined;
223
+ let ret = obj.holder_id || obj.holder?.form_record;
206
224
  if (Array.isArray(ret)) {
207
- return ret.length > 0 ? Number(ret[0]) : void 0;
225
+ return ret.length > 0 ? Number(ret[0]) : undefined;
208
226
  }
209
- return Number(ret) || void 0;
227
+ return Number(ret) || undefined;
210
228
  }
211
229
  getProductListByOrder() {
212
- var _a, _b, _c, _d, _e;
213
230
  if (!this.store.currentOrder) {
214
231
  return [];
215
232
  }
216
- const getDiscountListAmount = (list) => {
233
+ const getDiscountListAmount = list => {
217
234
  return list.reduce((pre, item) => {
218
235
  return pre + (item.amount || 0);
219
236
  }, 0);
220
237
  };
221
- const formatProduct = (items) => {
222
- return items.map(
223
- (item) => ({
224
- product_id: item.product_id,
225
- product_variant_id: item.product_variant_id,
226
- quantity: item.num,
227
- is_price_include_tax: item.is_price_include_tax,
228
- // 商品是否含税:1;0
229
- is_charge_tax: item.is_charge_tax ?? 0,
230
- // 若商品不含税,计算得到的税费,单位(元)
231
- tax_fee: item.tax_fee,
232
- // 整个商品折扣后的总金额
233
- selling_price: item.calculated_selling_price,
234
- // 使用者id
235
- holder_id: item.holder_id,
236
- // 整个商品折扣前的总金额
237
- original_price: item.calculated_original_price,
238
- // 主商品折扣前金额,不包含套餐子商品
239
- main_product_original_price: item.price,
240
- // 主商品折扣后金额,不包含套餐子商品
241
- main_product_selling_price: item.main_product_selling_price,
242
- metadata: {
243
- // 主商品+非原价(加减价)子商品税费
244
- "main_product_attached_bundle_tax_fee": item.metadata.main_product_attached_bundle_tax_fee,
245
- // 主商品+非原价(加减价)子商品附加费
246
- "main_product_attached_bundle_surcharge_fee": item.metadata.main_product_attached_bundle_surcharge_fee,
247
- // 可选,附加费均摊舍入金额
248
- "surcharge_rounding_remainder": item.metadata.surcharge_rounding_remainder
249
- },
250
- product_bundle: (item.product_bundle || []).map((bundle) => {
251
- return {
252
- is_price_include_tax: item.is_price_include_tax,
253
- bundle_id: bundle.bundle_id,
254
- bundle_product_id: bundle.bundle_product_id,
255
- bundle_variant_id: bundle.bundle_variant_id,
256
- price_type: bundle.price_type,
257
- price_type_ext: bundle.price_type_ext,
258
- // 套餐子商品总价,不包含折扣金额
259
- bundle_sum_price: bundle.bundle_sum_price,
260
- // 套餐子商品折扣后金额
261
- bundle_selling_price: bundle.bundle_selling_price,
262
- num: bundle.num,
263
- is_charge_tax: bundle.is_charge_tax,
264
- tax_fee: bundle.tax_fee,
265
- metadata: {
266
- // 子商品单数量附加费
267
- "surcharge_fee": bundle.metadata.surcharge_fee,
268
- // 可选,附加费均摊舍入金额
269
- "surcharge_rounding_remainder": bundle.metadata.surcharge_rounding_remainder
270
- }
271
- };
272
- })
273
- })
274
- ) || [];
275
- };
276
- const productList = formatProduct(
277
- ((_c = (_b = (_a = this.store.currentOrder.order_info) == null ? void 0 : _a.original_order_data) == null ? void 0 : _b.bookings) == null ? void 0 : _c.map(
278
- (item) => {
238
+ const formatProduct = items => {
239
+ return items.map(item => ({
240
+ product_id: item.product_id,
241
+ product_variant_id: item.product_variant_id,
242
+ quantity: item.num,
243
+ is_price_include_tax: item.is_price_include_tax,
244
+ // 商品是否含税:1;0
245
+ is_charge_tax: item.is_charge_tax ?? 0,
246
+ // 若商品不含税,计算得到的税费,单位(元)
247
+ tax_fee: item.tax_fee,
248
+ // 整个商品折扣后的总金额
249
+ selling_price: item.calculated_selling_price,
250
+ // 使用者id
251
+ holder_id: item.holder_id,
252
+ // 整个商品折扣前的总金额
253
+ original_price: item.calculated_original_price,
254
+ // 主商品折扣前金额,不包含套餐子商品
255
+ main_product_original_price: item.price,
256
+ // 主商品折扣后金额,不包含套餐子商品
257
+ main_product_selling_price: item.main_product_selling_price,
258
+ metadata: {
259
+ // 主商品+非原价(加减价)子商品税费
260
+ "main_product_attached_bundle_tax_fee": item.metadata.main_product_attached_bundle_tax_fee,
261
+ // 主商品+非原价(加减价)子商品附加费
262
+ "main_product_attached_bundle_surcharge_fee": item.metadata.main_product_attached_bundle_surcharge_fee,
263
+ // 可选,附加费均摊舍入金额
264
+ "surcharge_rounding_remainder": item.metadata.surcharge_rounding_remainder
265
+ },
266
+ product_bundle: (item.product_bundle || []).map(bundle => {
279
267
  return {
280
- ...item.product,
281
- holder_id: this.getHolderIdFromBooking(item)
268
+ is_price_include_tax: item.is_price_include_tax,
269
+ bundle_id: bundle.bundle_id,
270
+ bundle_product_id: bundle.bundle_product_id,
271
+ bundle_variant_id: bundle.bundle_variant_id,
272
+ price_type: bundle.price_type,
273
+ price_type_ext: bundle.price_type_ext,
274
+ // 套餐子商品总价,不包含折扣金额
275
+ bundle_sum_price: bundle.bundle_sum_price,
276
+ // 套餐子商品折扣后金额
277
+ bundle_selling_price: bundle.bundle_selling_price,
278
+ num: bundle.num,
279
+ is_charge_tax: bundle.is_charge_tax,
280
+ tax_fee: bundle.tax_fee,
281
+ metadata: {
282
+ // 子商品单数量附加费
283
+ "surcharge_fee": bundle.metadata.surcharge_fee,
284
+ // 可选,附加费均摊舍入金额
285
+ "surcharge_rounding_remainder": bundle.metadata.surcharge_rounding_remainder
286
+ }
282
287
  };
283
- }
284
- )) || []
285
- );
286
- const relationProducts = formatProduct(((_e = (_d = this.store.currentOrder.order_info) == null ? void 0 : _d.original_order_data) == null ? void 0 : _e.relation_products) || []);
288
+ })
289
+ })) || [];
290
+ };
291
+ const productList = formatProduct(this.store.currentOrder.order_info?.original_order_data?.bookings?.map(item => {
292
+ return {
293
+ ...item.product,
294
+ holder_id: this.getHolderIdFromBooking(item)
295
+ };
296
+ }) || []);
297
+ const relationProducts = formatProduct(this.store.currentOrder.order_info?.original_order_data?.relation_products || []);
287
298
  return [...productList, ...relationProducts];
288
299
  }
289
300
  async initWalletData(params) {
290
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
291
- this.logInfo("initWalletData called", {
301
+ this.logInfo('initWalletData called', {
292
302
  params
293
303
  });
294
304
  try {
295
- const amountInfo = (_b = (_a = this.store.currentOrder) == null ? void 0 : _a.order_info) == null ? void 0 : _b.amount_breakdown;
305
+ const amountInfo = this.store.currentOrder?.order_info?.amount_breakdown;
296
306
  if (!amountInfo) {
297
- this.logInfo("initWalletData amountInfo not found", {
307
+ this.logInfo('initWalletData amountInfo not found', {
298
308
  params
299
309
  });
300
310
  return;
301
311
  }
312
+ // 准备钱包初始化的业务数据
302
313
  const walletBusinessData = {
303
- customer_id: ((_c = this.store.currentCustomer) == null ? void 0 : _c.customer_id) ? Number(this.store.currentCustomer.customer_id) : void 0,
304
- holder: (_f = (_e = (_d = this.store.currentOrder) == null ? void 0 : _d.order_info) == null ? void 0 : _e.original_order_data) == null ? void 0 : _f.holder,
314
+ customer_id: this.store.currentCustomer?.customer_id ? Number(this.store.currentCustomer.customer_id) : undefined,
315
+ holder: this.store.currentOrder?.order_info?.original_order_data?.holder,
305
316
  amountInfo: {
306
317
  totalAmount: amountInfo.totalAmount,
307
318
  subTotal: amountInfo.subTotal,
308
- depositAmount: (_g = this.store.currentOrder) == null ? void 0 : _g.deposit_amount,
309
- isDeposit: (_h = this.store.currentOrder) == null ? void 0 : _h.is_deposit
319
+ depositAmount: this.store.currentOrder?.deposit_amount,
320
+ isDeposit: this.store.currentOrder?.is_deposit
310
321
  },
311
322
  products: this.getProductListByOrder(),
312
323
  is_price_include_tax: this.otherParams.is_price_include_tax,
313
324
  // core 有
314
325
  ...params
315
326
  };
327
+ // 判断订单是否已经同步,如果是则追加payment_order_id参数
316
328
  if (this.store.isOrderSynced) {
317
- walletBusinessData.payment_order_id = (_i = this.store.currentOrder) == null ? void 0 : _i.order_id;
329
+ walletBusinessData.payment_order_id = this.store.currentOrder?.order_id;
318
330
  }
319
- this.logInfo("开始拉取:initializeWalletDataFromBusinessAsync", {
331
+ this.logInfo('开始拉取:initializeWalletDataFromBusinessAsync', {
320
332
  walletBusinessData
321
333
  });
322
- await this.payment.wallet.initializeWalletDataFromBusinessAsync(
323
- walletBusinessData
324
- );
325
- this.logInfo("调用结束:initializeWalletDataFromBusinessAsync", {
334
+ await this.payment.wallet.initializeWalletDataFromBusinessAsync(walletBusinessData);
335
+ this.logInfo('调用结束:initializeWalletDataFromBusinessAsync', {
326
336
  walletBusinessData
327
337
  });
338
+
339
+ // 因为上面是接口 这里最好检查一下还有没有 currentOrder 了,如果没有,则不触发事件
328
340
  if (!this.store.currentOrder) {
329
341
  return;
330
342
  }
331
- this.logInfo("initWalletData currentOrder found", {
343
+ this.logInfo('initWalletData currentOrder found', {
332
344
  currentOrder: this.store.currentOrder
333
345
  });
346
+ // 触发钱包数据初始化完成事件
334
347
  await this.core.effects.emit(`${this.name}:onWalletDataInitialized`, {
335
- orderUuid: (_j = this.store.currentOrder) == null ? void 0 : _j.uuid,
348
+ orderUuid: this.store.currentOrder?.uuid,
336
349
  customerId: walletBusinessData.customer_id,
337
350
  walletBusinessData: {
338
351
  customer_id: walletBusinessData.customer_id,
339
352
  amountInfo: walletBusinessData.amountInfo,
340
- order_wait_pay_amount: params == null ? void 0 : params.order_wait_pay_amount
353
+ order_wait_pay_amount: params?.order_wait_pay_amount
341
354
  },
342
355
  timestamp: Date.now()
343
356
  });
344
357
  } catch (error) {
345
- this.logError("initWalletData error", {
358
+ this.logError('initWalletData error', {
346
359
  error: error instanceof Error ? error.message : String(error)
347
360
  });
348
361
  throw error;
@@ -354,11 +367,11 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
354
367
  protocols: [],
355
368
  hasDeposit: false
356
369
  };
357
- bookings == null ? void 0 : bookings.forEach((item) => {
370
+ bookings?.forEach(item => {
358
371
  const total = item.product.calculated_selling_price;
359
- const deposit = (0, import_utils2.getProductDeposit)({
372
+ const deposit = (0, _utils2.getProductDeposit)({
360
373
  cartItem: {
361
- total
374
+ total: total
362
375
  },
363
376
  product: item.product,
364
377
  bundle: item.bundle,
@@ -366,16 +379,14 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
366
379
  num: item.num
367
380
  });
368
381
  item.deposit = deposit;
369
- if ((deposit == null ? void 0 : deposit.total) && Number(deposit.total) > 0) {
370
- summaryDeposit.protocols = summaryDeposit.protocols.concat(
371
- deposit.protocols
372
- );
373
- summaryDeposit.total = new import_decimal.default(summaryDeposit.total).plus(deposit.total).toNumber();
382
+ if (deposit?.total && Number(deposit.total) > 0) {
383
+ summaryDeposit.protocols = summaryDeposit.protocols.concat(deposit.protocols);
384
+ summaryDeposit.total = new _decimal.default(summaryDeposit.total).plus(deposit.total).toNumber();
374
385
  summaryDeposit.hasDeposit = true;
375
386
  }
376
387
  });
377
- relationProducts == null ? void 0 : relationProducts.forEach((item) => {
378
- const deposit = (0, import_utils2.getProductDeposit)({
388
+ relationProducts?.forEach(item => {
389
+ const deposit = (0, _utils2.getProductDeposit)({
379
390
  cartItem: {
380
391
  total: item.price * item.num
381
392
  },
@@ -385,20 +396,22 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
385
396
  num: item.num
386
397
  });
387
398
  item.deposit = deposit;
388
- if ((deposit == null ? void 0 : deposit.total) && Number(deposit.total) > 0) {
389
- summaryDeposit.total = new import_decimal.default(summaryDeposit.total).plus(deposit.total).toNumber();
390
- item.discount_list.forEach((discount) => {
391
- summaryDeposit.total = new import_decimal.default(summaryDeposit.total).minus(discount.amount || 0).toNumber();
399
+ if (deposit?.total && Number(deposit.total) > 0) {
400
+ // 需要减去商品券折扣卡抵扣的金额
401
+ summaryDeposit.total = new _decimal.default(summaryDeposit.total).plus(deposit.total).toNumber();
402
+ item.discount_list.forEach(discount => {
403
+ summaryDeposit.total = new _decimal.default(summaryDeposit.total).minus(discount.amount || 0).toNumber();
392
404
  });
393
- summaryDeposit.protocols = summaryDeposit.protocols.concat(
394
- deposit.protocols
395
- );
405
+ summaryDeposit.protocols = summaryDeposit.protocols.concat(deposit.protocols);
396
406
  summaryDeposit.hasDeposit = true;
397
407
  }
398
408
  });
399
- summaryDeposit.total = new import_decimal.default(summaryDeposit.total).toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber();
409
+
410
+ // 将总金额四舍五入到两位小数
411
+ summaryDeposit.total = new _decimal.default(summaryDeposit.total).toDecimalPlaces(2, _decimal.default.ROUND_HALF_UP).toNumber();
400
412
  return summaryDeposit;
401
413
  }
414
+
402
415
  /**
403
416
  * 创建本地订单 (前端模拟下单流程)
404
417
  *
@@ -407,60 +420,72 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
407
420
  * 方法会记录参数并创建本地虚拟订单,然后用 Payment 模块管理支付流程。
408
421
  */
409
422
  async createLocalOrderAsync(params) {
410
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
411
- this.logInfo("createLocalOrderAsync called", {
412
- orderDataType: (_a = params.orderData) == null ? void 0 : _a.type,
413
- platform: (_b = params.orderData) == null ? void 0 : _b.platform,
414
- bookingsCount: ((_d = (_c = params.orderData) == null ? void 0 : _c.bookings) == null ? void 0 : _d.length) || 0,
415
- relationProductsCount: ((_f = (_e = params.orderData) == null ? void 0 : _e.relation_products) == null ? void 0 : _f.length) || 0,
416
- customerId: (_g = params.orderData) == null ? void 0 : _g.customer_id,
423
+ this.logInfo('createLocalOrderAsync called', {
424
+ orderDataType: params.orderData?.type,
425
+ platform: params.orderData?.platform,
426
+ bookingsCount: params.orderData?.bookings?.length || 0,
427
+ relationProductsCount: params.orderData?.relation_products?.length || 0,
428
+ customerId: params.orderData?.customer_id,
417
429
  autoPayment: params.autoPayment,
418
- cartSummaryCount: ((_h = params.cartSummary) == null ? void 0 : _h.length) || 0,
430
+ cartSummaryCount: params.cartSummary?.length || 0,
419
431
  totalInfoKeys: params.totalInfo ? Object.keys(params.totalInfo) : []
420
432
  });
421
433
  try {
434
+ // 🔧 修改:在创建新订单前,直接重置 store 状态(同步执行)
422
435
  this.resetStoreState();
423
- const validation = (0, import_utils.validateLocalOrderData)(params.orderData);
436
+ // 验证订单数据
437
+ const validation = (0, _utils.validateLocalOrderData)(params.orderData);
424
438
  if (!validation.valid) {
425
- throw (0, import_utils.createCheckoutError)(
426
- import_types.CheckoutErrorType.ValidationFailed,
427
- `订单数据验证失败: ${validation.errors.join(", ")}`
428
- );
439
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, `订单数据验证失败: ${validation.errors.join(', ')}`);
429
440
  }
430
- const localOrderId = (0, import_utils.generateLocalOrderId)();
431
- const amountInfo = (0, import_utils.extractAmountFromCartSummary)(params.cartSummary);
432
- params.orderData.platform = "pos";
433
- params.orderData.created_at = (0, import_utils.formatDateTime)(/* @__PURE__ */ new Date());
434
- params.orderData.surcharge_fee = (_j = (_i = params.totalInfo) == null ? void 0 : _i.total) == null ? void 0 : _j.otherAmount;
435
- params.orderData.surcharges = (_l = (_k = params.totalInfo) == null ? void 0 : _k.total) == null ? void 0 : _l.surcharge;
436
- params.orderData.shop_discount = (_n = (_m = params.totalInfo) == null ? void 0 : _m.total) == null ? void 0 : _n.shopDiscount;
437
- params.orderData.tax_fee = (_p = (_o = params.totalInfo) == null ? void 0 : _o.total) == null ? void 0 : _p.tax;
441
+
442
+ // 生成本地虚拟订单ID (后续可以被真实订单ID替换)
443
+ const localOrderId = (0, _utils.generateLocalOrderId)();
444
+
445
+ // 从购物车小计数据中提取金额信息
446
+ const amountInfo = (0, _utils.extractAmountFromCartSummary)(params.cartSummary);
447
+ // TODO: 外面传的是 pos ,但是现在 后端只有 shop 和 kiosk
448
+ params.orderData.platform = 'pos';
449
+ // 补充 created_at 时间 (YYYY-MM-DD hh:mm:ss 格式)
450
+ params.orderData.created_at = (0, _utils.formatDateTime)(new Date());
451
+ // 补充附加费信息
452
+ params.orderData.surcharge_fee = params.totalInfo?.total?.otherAmount;
453
+ params.orderData.surcharges = params.totalInfo?.total?.surcharge;
454
+ // 补充订单折扣信息
455
+ params.orderData.shop_discount = params.totalInfo?.total?.shopDiscount;
456
+ // 补充税费信息
457
+ params.orderData.tax_fee = params.totalInfo?.total?.tax;
458
+
459
+ // 保存原始订单数据和小计数据到状态中
438
460
  this.store.localOrderData = params.orderData;
439
461
  this.store.cartSummary = params.cartSummary;
462
+
463
+ // 提取并保存客户信息(如果有)
440
464
  const customerInfo = {
441
465
  customer_id: params.orderData.customer_id,
442
466
  customer_name: params.orderData.customer_name
443
467
  };
468
+
469
+ // 只有在有客户信息时才存储
444
470
  if (customerInfo.customer_id || customerInfo.customer_name) {
445
471
  this.store.currentCustomer = customerInfo;
446
- console.log("[Checkout] 保存客户信息:", customerInfo);
447
472
  } else {
448
- this.store.currentCustomer = void 0;
449
- console.log("[Checkout] 未提供客户信息");
473
+ this.store.currentCustomer = undefined;
450
474
  }
451
- const isNeedDeposit = this.checkIsNeedDepositAsync(
452
- params.orderData.bookings,
453
- params.orderData.relation_products
454
- );
475
+
476
+ // 计算是否需要支付定金,如果需要默认切换到定金模式,以及记录定金总金额,并把当前默认待付金额调整为定金总金额
477
+ const isNeedDeposit = this.checkIsNeedDepositAsync(params.orderData.bookings, params.orderData.relation_products);
478
+
479
+ // 创建支付订单对象
455
480
  const paymentOrder = await this.payment.createPaymentOrderAsync({
456
481
  order_id: localOrderId,
457
482
  total_amount: amountInfo.totalAmount,
458
483
  is_deposit: isNeedDeposit.hasDeposit ? 1 : 0,
459
- deposit_amount: isNeedDeposit.total ? isNeedDeposit.total.toString() : "0.00",
484
+ deposit_amount: isNeedDeposit.total ? isNeedDeposit.total.toString() : '0.00',
460
485
  order_info: {
461
486
  original_order_data: params.orderData,
462
487
  cart_summary: params.cartSummary,
463
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
488
+ created_at: new Date().toISOString(),
464
489
  platform: params.orderData.platform,
465
490
  type: params.orderData.type,
466
491
  schedule_date: params.orderData.schedule_date,
@@ -469,21 +494,30 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
469
494
  }
470
495
  });
471
496
  this.store.currentOrder = paymentOrder;
497
+
498
+ // // 如果设置了自动支付,直接跳转到支付步骤
499
+ // if (params.autoPayment) {
500
+ // // 自动支付模式标记
501
+ // }
502
+
472
503
  this.core.effects.emit(`${this.name}:onOrderCreated`, {
473
504
  order: paymentOrder,
474
505
  timestamp: Date.now()
475
506
  });
507
+
508
+ // 自动设置 stateAmount 为剩余未支付金额
509
+ // 🚀 性能监控:记录 updateStateAmountToRemaining 操作耗时
476
510
  const updateAmountStartTime = Date.now();
477
511
  await this.updateStateAmountToRemaining(false);
478
512
  const updateAmountDuration = Date.now() - updateAmountStartTime;
479
- this.logInfo("updateStateAmountToRemaining operation completed", {
480
- operation: "updateStateAmountToRemaining",
513
+ this.logInfo('updateStateAmountToRemaining operation completed', {
514
+ operation: 'updateStateAmountToRemaining',
481
515
  orderUuid: paymentOrder.uuid,
482
516
  orderId: paymentOrder.order_id,
483
517
  duration: `${updateAmountDuration}ms`,
484
- performance: updateAmountDuration > 200 ? "slow" : updateAmountDuration > 100 ? "medium" : "fast"
518
+ performance: updateAmountDuration > 200 ? 'slow' : updateAmountDuration > 100 ? 'medium' : 'fast'
485
519
  });
486
- this.logInfo("本地订单创建成功:", {
520
+ this.logInfo('本地订单创建成功:', {
487
521
  localOrderId,
488
522
  uuid: paymentOrder.uuid,
489
523
  totalAmount: amountInfo.totalAmount,
@@ -494,11 +528,8 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
494
528
  this.initWalletData();
495
529
  return paymentOrder;
496
530
  } catch (error) {
497
- await this.handleError(
498
- error,
499
- import_types.CheckoutErrorType.OrderCreationFailed
500
- );
501
- this.logError("本地订单创建失败:", error);
531
+ await this.handleError(error, _types.CheckoutErrorType.OrderCreationFailed);
532
+ this.logError('本地订单创建失败:', error);
502
533
  this.core.effects.emit(`${this.name}:onOrderCreationFailed`, {
503
534
  error: this.store.lastError,
504
535
  timestamp: Date.now()
@@ -506,6 +537,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
506
537
  throw error;
507
538
  }
508
539
  }
540
+
509
541
  /**
510
542
  * 更新本地订单(已同步后端的订单)并设置为当前订单
511
543
  *
@@ -513,31 +545,37 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
513
545
  * 会覆盖 order_info 与金额等字段,并重新计算待付金额,最后设置为 currentOrder。
514
546
  */
515
547
  async updateLocalOrderAsync(params) {
516
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
517
548
  this.payment.wallet.clearAllCache();
518
- this.logInfo("updateLocalOrderAsync called", {
549
+ this.logInfo('updateLocalOrderAsync called', {
519
550
  orderId: params.orderId,
520
- orderDataType: (_a = params.orderData) == null ? void 0 : _a.type,
521
- bookingsCount: ((_c = (_b = params.orderData) == null ? void 0 : _b.bookings) == null ? void 0 : _c.length) || 0,
522
- cartSummaryCount: ((_d = params.cartSummary) == null ? void 0 : _d.length) || 0,
551
+ orderDataType: params.orderData?.type,
552
+ bookingsCount: params.orderData?.bookings?.length || 0,
553
+ cartSummaryCount: params.cartSummary?.length || 0,
523
554
  totalInfoKeys: params.totalInfo ? Object.keys(params.totalInfo) : []
524
555
  });
525
- const validation = (0, import_utils.validateLocalOrderData)(params.orderData);
556
+
557
+ // 基础校验
558
+ const validation = (0, _utils.validateLocalOrderData)(params.orderData);
526
559
  if (!validation.valid) {
527
- throw (0, import_utils.createCheckoutError)(
528
- import_types.CheckoutErrorType.ValidationFailed,
529
- `订单数据验证失败: ${validation.errors.join(", ")}`
530
- );
560
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, `订单数据验证失败: ${validation.errors.join(', ')}`);
531
561
  }
532
- const amountInfo = (0, import_utils.extractAmountFromCartSummary)(params.cartSummary);
533
- params.orderData.created_at = (0, import_utils.formatDateTime)(/* @__PURE__ */ new Date());
534
- params.orderData.platform = "pos";
535
- params.orderData.surcharge_fee = (_f = (_e = params.totalInfo) == null ? void 0 : _e.total) == null ? void 0 : _f.otherAmount;
536
- params.orderData.surcharges = (_h = (_g = params.totalInfo) == null ? void 0 : _g.total) == null ? void 0 : _h.surcharge;
537
- params.orderData.shop_discount = (_j = (_i = params.totalInfo) == null ? void 0 : _i.total) == null ? void 0 : _j.shopDiscount;
538
- params.orderData.tax_fee = (_l = (_k = params.totalInfo) == null ? void 0 : _k.total) == null ? void 0 : _l.tax;
562
+
563
+ // 计算金额
564
+ const amountInfo = (0, _utils.extractAmountFromCartSummary)(params.cartSummary);
565
+
566
+ // 规范化补充字段
567
+ params.orderData.created_at = (0, _utils.formatDateTime)(new Date());
568
+ params.orderData.platform = 'pos';
569
+ params.orderData.surcharge_fee = params.totalInfo?.total?.otherAmount;
570
+ params.orderData.surcharges = params.totalInfo?.total?.surcharge;
571
+ params.orderData.shop_discount = params.totalInfo?.total?.shopDiscount;
572
+ params.orderData.tax_fee = params.totalInfo?.total?.tax;
573
+
574
+ // 持久化原始数据
539
575
  this.store.localOrderData = params.orderData;
540
576
  this.store.cartSummary = params.cartSummary;
577
+
578
+ // 同步客户信息
541
579
  const customerInfo = {
542
580
  customer_id: params.orderData.customer_id,
543
581
  customer_name: params.orderData.customer_name
@@ -545,43 +583,49 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
545
583
  if (customerInfo.customer_id || customerInfo.customer_name) {
546
584
  this.store.currentCustomer = customerInfo;
547
585
  } else {
548
- this.store.currentCustomer = void 0;
586
+ this.store.currentCustomer = undefined;
549
587
  }
588
+
589
+ // 保留原有支付项:通过 orderId 找到现有订单(按 id 或 order_id 匹配)
550
590
  const allOrders = await this.payment.getOrderListAsync();
551
- const existingOrder = allOrders.find(
552
- (o) => String(o.id) === String(params.orderId) || String(o.order_id) === String(params.orderId)
553
- );
591
+ const existingOrder = allOrders.find(o => String(o.id) === String(params.orderId) || String(o.order_id) === String(params.orderId));
554
592
  if (existingOrder) {
593
+ // 🔧 新增: 如果传入了 existPayment,需要更新支付项列表
555
594
  if (params.existPayment && params.existPayment.length > 0) {
556
- this.logInfo("检测到云端支付项,将替换本地订单的支付项列表", {
595
+ this.logInfo('检测到云端支付项,将替换本地订单的支付项列表', {
557
596
  orderId: params.orderId,
558
- existingPaymentCount: ((_m = existingOrder.payment) == null ? void 0 : _m.length) || 0,
597
+ existingPaymentCount: existingOrder.payment?.length || 0,
559
598
  newPaymentCount: params.existPayment.length
560
599
  });
600
+
601
+ // 标记订单已同步(因为支付项来自云端)
561
602
  this.store.isOrderSynced = true;
562
- const currentTime = (0, import_utils.formatDateTime)(/* @__PURE__ */ new Date());
563
- const formattedExistPayments = params.existPayment.map((payment) => ({
603
+
604
+ // 格式化云端支付项(添加时间戳、标记已同步)
605
+ const currentTime = (0, _utils.formatDateTime)(new Date());
606
+ const formattedExistPayments = params.existPayment.map(payment => ({
564
607
  ...payment,
565
608
  isSynced: true,
566
609
  // 标记为已同步
567
- status: payment.status || "active",
610
+ status: payment.status || 'active',
568
611
  created_at: payment.created_at || currentTime,
569
612
  updated_at: payment.updated_at || currentTime
570
613
  }));
571
- const isNeedDeposit3 = this.checkIsNeedDepositAsync(
572
- params.orderData.bookings,
573
- params.orderData.relation_products
574
- );
614
+
615
+ // 计算是否需要支付定金
616
+ const isNeedDeposit = this.checkIsNeedDepositAsync(params.orderData.bookings, params.orderData.relation_products);
617
+
618
+ // 更新订单,替换支付项列表
575
619
  await this.payment.updateOrderAsync(existingOrder.uuid, {
576
620
  total_amount: amountInfo.totalAmount,
577
- is_deposit: isNeedDeposit3.hasDeposit ? 1 : 0,
578
- deposit_amount: isNeedDeposit3.total ? isNeedDeposit3.total.toString() : "0.00",
621
+ is_deposit: isNeedDeposit.hasDeposit ? 1 : 0,
622
+ deposit_amount: isNeedDeposit.total ? isNeedDeposit.total.toString() : '0.00',
579
623
  payment: formattedExistPayments,
580
624
  // 🔧 替换支付项列表
581
625
  order_info: {
582
626
  original_order_data: params.orderData,
583
627
  cart_summary: params.cartSummary,
584
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
628
+ created_at: new Date().toISOString(),
585
629
  platform: params.orderData.platform,
586
630
  type: params.orderData.type,
587
631
  schedule_date: params.orderData.schedule_date,
@@ -589,70 +633,68 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
589
633
  amount_breakdown: amountInfo
590
634
  }
591
635
  });
592
- const updated2 = await this.payment.getPaymentOrderByUuidAsync(
593
- existingOrder.uuid
594
- );
595
- if (!updated2)
596
- throw (0, import_utils.createCheckoutError)(
597
- import_types.CheckoutErrorType.UnknownError,
598
- "订单更新失败"
599
- );
600
- this.store.currentOrder = updated2;
636
+ const updated = await this.payment.getPaymentOrderByUuidAsync(existingOrder.uuid);
637
+ if (!updated) throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.UnknownError, '订单更新失败');
638
+ this.store.currentOrder = updated;
601
639
  await this.updateStateAmountToRemaining(false);
602
- this.logInfo("本地订单更新成功(已替换云端支付项):", {
640
+ this.logInfo('本地订单更新成功(已替换云端支付项):', {
603
641
  orderId: params.orderId,
604
- uuid: updated2.uuid,
605
- payments: ((_n = updated2.payment) == null ? void 0 : _n.length) || 0,
606
- totalAmount: updated2.total_amount,
607
- expectAmount: updated2.expect_amount,
642
+ uuid: updated.uuid,
643
+ payments: updated.payment?.length || 0,
644
+ totalAmount: updated.total_amount,
645
+ expectAmount: updated.expect_amount,
608
646
  isOrderSynced: true
609
647
  });
648
+
649
+ // 事件通知
610
650
  await this.core.effects.emit(`${this.name}:onOrderCreated`, {
611
- order: updated2,
651
+ order: updated,
612
652
  timestamp: Date.now()
613
653
  });
614
- const syncedPayments = updated2.payment.filter((p) => p.isSynced && p.status !== "voided");
615
- const syncedAmount2 = syncedPayments.reduce((sum, p) => {
616
- let amt = new import_decimal.default(p.amount || "0");
617
- const rounding = new import_decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || "0").abs();
654
+
655
+ // 计算已同步的支付金额
656
+ const syncedPayments = updated.payment.filter(p => p.isSynced && p.status !== 'voided');
657
+ const syncedAmount = syncedPayments.reduce((sum, p) => {
658
+ let amt = new _decimal.default(p.amount || '0');
659
+ const rounding = new _decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || '0').abs();
618
660
  return sum.plus(amt).plus(rounding);
619
- }, new import_decimal.default(0));
620
- const totalAmount2 = new import_decimal.default(amountInfo.totalAmount || "0");
621
- const remainingExpectAmount2 = import_decimal.default.max(0, totalAmount2.minus(syncedAmount2)).toFixed(2);
622
- let depositDiffAmount2 = new import_decimal.default(0).toFixed(2);
623
- if (updated2.is_deposit === 1) {
624
- depositDiffAmount2 = new import_decimal.default(updated2.deposit_amount).minus(syncedAmount2).toFixed(2);
661
+ }, new _decimal.default(0));
662
+ const totalAmount = new _decimal.default(amountInfo.totalAmount || '0');
663
+ const remainingExpectAmount = _decimal.default.max(0, totalAmount.minus(syncedAmount)).toFixed(2);
664
+
665
+ // 计算定金差值
666
+ let depositDiffAmount = new _decimal.default(0).toFixed(2);
667
+ if (updated.is_deposit === 1) {
668
+ depositDiffAmount = new _decimal.default(updated.deposit_amount).minus(syncedAmount).toFixed(2);
625
669
  }
626
670
  this.initWalletData({
627
- order_wait_pay_amount: Number(depositDiffAmount2) > 0 ? Number(depositDiffAmount2) : Number(remainingExpectAmount2)
671
+ order_wait_pay_amount: Number(depositDiffAmount) > 0 ? Number(depositDiffAmount) : Number(remainingExpectAmount)
628
672
  });
629
- return updated2;
673
+ return updated;
630
674
  }
631
- const totalAmount = new import_decimal.default(amountInfo.totalAmount || "0");
632
- const activePayments = (existingOrder.payment || []).filter(
633
- (p) => p.status !== "voided" && (!p.voucher_id || p.voucher_id && p.isSynced)
634
- );
675
+
676
+ // 原有逻辑:保留现有支付项
677
+ const totalAmount = new _decimal.default(amountInfo.totalAmount || '0');
678
+ const activePayments = (existingOrder.payment || []).filter(p => p.status !== 'voided' && (!p.voucher_id || p.voucher_id && p.isSynced));
635
679
  const paidAmount = activePayments.reduce((sum, p) => {
636
- const amt = new import_decimal.default(p.amount || "0");
637
- const rounding = new import_decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || "0").abs();
680
+ const amt = new _decimal.default(p.amount || '0');
681
+ const rounding = new _decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || '0').abs();
638
682
  return sum.plus(amt).plus(rounding);
639
- }, new import_decimal.default(0));
640
- const remaining = import_decimal.default.max(0, totalAmount.minus(paidAmount)).toFixed(
641
- 2
642
- );
643
- const isNeedDeposit2 = this.checkIsNeedDepositAsync(
644
- params.orderData.bookings,
645
- params.orderData.relation_products
646
- );
683
+ }, new _decimal.default(0));
684
+ const remaining = _decimal.default.max(0, totalAmount.minus(paidAmount)).toFixed(2);
685
+ // 计算是否需要支付定金,如果需要默认切换到定金模式,以及记录定金总金额,并把当前默认待付金额调整为定金总金额
686
+ const isNeedDeposit = this.checkIsNeedDepositAsync(params.orderData.bookings, params.orderData.relation_products);
687
+
688
+ // 更新到支付模块(使用 uuid,不修改 payment 列表)
647
689
  await this.payment.updateOrderAsync(existingOrder.uuid, {
648
690
  total_amount: amountInfo.totalAmount,
649
- is_deposit: isNeedDeposit2.hasDeposit ? 1 : 0,
650
- deposit_amount: isNeedDeposit2.total ? isNeedDeposit2.total.toString() : "0.00",
691
+ is_deposit: isNeedDeposit.hasDeposit ? 1 : 0,
692
+ deposit_amount: isNeedDeposit.total ? isNeedDeposit.total.toString() : '0.00',
651
693
  expect_amount: remaining,
652
694
  order_info: {
653
695
  original_order_data: params.orderData,
654
696
  cart_summary: params.cartSummary,
655
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
697
+ created_at: new Date().toISOString(),
656
698
  platform: params.orderData.platform,
657
699
  type: params.orderData.type,
658
700
  schedule_date: params.orderData.schedule_date,
@@ -660,59 +702,56 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
660
702
  amount_breakdown: amountInfo
661
703
  }
662
704
  });
663
- const updated = await this.payment.getPaymentOrderByUuidAsync(
664
- existingOrder.uuid
665
- );
666
- if (!updated)
667
- throw (0, import_utils.createCheckoutError)(
668
- import_types.CheckoutErrorType.UnknownError,
669
- "订单更新失败"
670
- );
705
+ const updated = await this.payment.getPaymentOrderByUuidAsync(existingOrder.uuid);
706
+ if (!updated) throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.UnknownError, '订单更新失败');
671
707
  this.store.currentOrder = updated;
672
708
  await this.updateStateAmountToRemaining(false);
673
- this.logInfo("本地订单更新成功(保留支付项):", {
709
+ this.logInfo('本地订单更新成功(保留支付项):', {
674
710
  orderId: params.orderId,
675
711
  uuid: updated.uuid,
676
- payments: ((_o = updated.payment) == null ? void 0 : _o.length) || 0,
712
+ payments: updated.payment?.length || 0,
677
713
  totalAmount: updated.total_amount,
678
714
  expectAmount: updated.expect_amount
679
715
  });
716
+
717
+ // 事件通知(复用创建事件,便于上层监听刷新)
680
718
  await this.core.effects.emit(`${this.name}:onOrderCreated`, {
681
719
  order: updated,
682
720
  timestamp: Date.now()
683
721
  });
722
+
723
+ // 需要减去已经同步给后端的支付过的钱
684
724
  const syncedAmount = activePayments.reduce((sum, p) => {
685
- const amt = new import_decimal.default(p.amount || "0");
686
- const rounding = new import_decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || "0").abs();
725
+ const amt = new _decimal.default(p.amount || '0');
726
+ const rounding = new _decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || '0').abs();
687
727
  return sum.plus(amt).plus(rounding);
688
- }, new import_decimal.default(0));
689
- const remainingExpectAmount = import_decimal.default.max(0, totalAmount.minus(syncedAmount)).toFixed(
690
- 2
691
- );
692
- let depositDiffAmount = new import_decimal.default(0).toFixed(2);
728
+ }, new _decimal.default(0));
729
+ const remainingExpectAmount = _decimal.default.max(0, totalAmount.minus(syncedAmount)).toFixed(2);
730
+ // 要计算一个总价的差值和一个定金的差值,如果定金的差值>0,则需要使用定金的差值,否则使用总价的差值
731
+ let depositDiffAmount = new _decimal.default(0).toFixed(2);
693
732
  if (updated.is_deposit === 1) {
694
- depositDiffAmount = new import_decimal.default(updated.deposit_amount).minus(syncedAmount).toFixed(2);
733
+ depositDiffAmount = new _decimal.default(updated.deposit_amount).minus(syncedAmount).toFixed(2);
695
734
  }
696
735
  this.initWalletData({
697
736
  order_wait_pay_amount: Number(depositDiffAmount) > 0 ? Number(depositDiffAmount) : Number(remainingExpectAmount)
698
737
  });
699
738
  return updated;
700
739
  }
701
- const isNeedDeposit = this.checkIsNeedDepositAsync(
702
- params.orderData.bookings,
703
- params.orderData.relation_products
704
- );
740
+ // 计算是否需要支付定金,如果需要默认切换到定金模式,以及记录定金总金额,并把当前默认待付金额调整为定金总金额
741
+ const isNeedDeposit = this.checkIsNeedDepositAsync(params.orderData.bookings, params.orderData.relation_products);
742
+
743
+ // 没找到现有订单时,回退为创建逻辑(用于异常兜底)
705
744
  const created = await this.payment.createPaymentOrderAsync({
706
745
  order_id: String(params.orderId),
707
746
  total_amount: amountInfo.totalAmount,
708
747
  is_deposit: isNeedDeposit.hasDeposit ? 1 : 0,
709
- deposit_amount: isNeedDeposit.total ? isNeedDeposit.total.toString() : "0.00",
748
+ deposit_amount: isNeedDeposit.total ? isNeedDeposit.total.toString() : '0.00',
710
749
  existPayment: params.existPayment,
711
750
  // 🔧 新增: 传递云端支付项
712
751
  order_info: {
713
752
  original_order_data: params.orderData,
714
753
  cart_summary: params.cartSummary,
715
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
754
+ created_at: new Date().toISOString(),
716
755
  platform: params.orderData.platform,
717
756
  type: params.orderData.type,
718
757
  schedule_date: params.orderData.schedule_date,
@@ -721,15 +760,20 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
721
760
  }
722
761
  });
723
762
  this.store.currentOrder = created;
724
- if (params.existPayment && params.existPayment.length > 0 || ((_p = this.store.currentOrder) == null ? void 0 : _p.order_id) && !(0, import_utils.isVirtualOrderId)((_q = this.store.currentOrder) == null ? void 0 : _q.order_id)) {
763
+
764
+ // 🔧 新增: 如果有云端支付项,需要计算正确的待付金额
765
+ if (params.existPayment && params.existPayment.length > 0 || this.store.currentOrder?.order_id && !(0, _utils.isVirtualOrderId)(this.store.currentOrder?.order_id)) {
766
+ // 标记订单已同步(因为订单和支付项都来自云端)
725
767
  this.store.isOrderSynced = true;
726
- const syncedPayments = created.payment.filter((p) => p.isSynced && p.status !== "voided");
768
+
769
+ // 计算已同步的支付金额
770
+ const syncedPayments = created.payment.filter(p => p.isSynced && p.status !== 'voided');
727
771
  const syncedAmount = syncedPayments.reduce((sum, p) => {
728
- const amt = new import_decimal.default(p.amount || "0");
729
- const rounding = new import_decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || "0").abs();
772
+ const amt = new _decimal.default(p.amount || '0');
773
+ const rounding = new _decimal.default(Number(p.rounding_amount) > 0 ? 0 : p.rounding_amount || '0').abs();
730
774
  return sum.plus(amt).plus(rounding);
731
- }, new import_decimal.default(0));
732
- this.logInfo("云端订单初始化钱包数据", {
775
+ }, new _decimal.default(0));
776
+ this.logInfo('云端订单初始化钱包数据', {
733
777
  orderId: params.orderId,
734
778
  totalAmount: created.total_amount,
735
779
  expectAmount: created.expect_amount,
@@ -737,57 +781,60 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
737
781
  syncedPaymentCount: syncedPayments.length,
738
782
  isOrderSynced: true
739
783
  });
784
+
785
+ // 初始化钱包数据,使用系统计算的待付金额
740
786
  this.initWalletData({
741
787
  order_wait_pay_amount: Number(created.expect_amount)
742
788
  });
743
789
  } else {
790
+ // 没有云端支付项,正常初始化
744
791
  this.initWalletData();
745
792
  }
746
793
  return created;
747
794
  }
795
+
748
796
  /**
749
797
  * 完成结账
750
798
  */
751
799
  async completeCheckoutAsync() {
752
800
  try {
753
801
  if (!this.store.currentOrder) {
754
- throw (0, import_utils.createCheckoutError)(
755
- import_types.CheckoutErrorType.ValidationFailed,
756
- "未找到当前订单"
757
- );
802
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, '未找到当前订单');
758
803
  }
759
- const order = await this.payment.getPaymentOrderByUuidAsync(
760
- this.store.currentOrder.uuid
761
- );
762
- if (!order || order.payment_status !== import_types2.PaymentStatus.Finished) {
763
- throw (0, import_utils.createCheckoutError)(
764
- import_types.CheckoutErrorType.ValidationFailed,
765
- "订单支付未完成,无法完成结账"
766
- );
804
+
805
+ // 检查支付状态
806
+ const order = await this.payment.getPaymentOrderByUuidAsync(this.store.currentOrder.uuid);
807
+ if (!order || order.payment_status !== _types2.PaymentStatus.Finished) {
808
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, '订单支付未完成,无法完成结账');
767
809
  }
810
+
811
+ // 清理钱包模块的所有缓存数据
768
812
  this.payment.wallet.clearAllCache();
769
813
  await this.core.effects.emit(`${this.name}:onCheckoutCompleted`, {
770
814
  orderId: order.id,
771
815
  timestamp: Date.now()
772
816
  });
773
- console.log("[Checkout] 结账流程完成:", order.id);
817
+ // 🔧 新增:自动重置 store 状态(同步执行)
774
818
  this.resetStoreState();
775
819
  return {
776
820
  success: true,
777
821
  orderId: String(order.id)
778
822
  };
779
823
  } catch (error) {
780
- await this.handleError(error, import_types.CheckoutErrorType.UnknownError);
781
- return { success: false };
824
+ await this.handleError(error, _types.CheckoutErrorType.UnknownError);
825
+ return {
826
+ success: false
827
+ };
782
828
  }
783
829
  }
830
+
784
831
  /**
785
832
  * 获取订单原始数据
786
833
  */
787
834
  getOrderOriginalData() {
788
- var _a;
789
- return (_a = this.store.currentOrder) == null ? void 0 : _a.order_info;
835
+ return this.store.currentOrder?.order_info;
790
836
  }
837
+
791
838
  /**
792
839
  * 获取当前订单基础信息
793
840
  *
@@ -795,15 +842,20 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
795
842
  */
796
843
  getCurrentOrderInfo() {
797
844
  try {
798
- const { currentOrder, cartItems, localOrderData } = this.store;
845
+ const {
846
+ currentOrder,
847
+ cartItems,
848
+ localOrderData
849
+ } = this.store;
799
850
  if (!currentOrder) {
800
- console.log("[Checkout] 当前没有活跃订单");
801
851
  return null;
802
852
  }
853
+
854
+ // 从本地订单数据或订单信息中提取基础信息
803
855
  const orderInfo = currentOrder.order_info || {};
804
- const createdAt = orderInfo.created_at || (/* @__PURE__ */ new Date()).toISOString();
805
- const orderType = (localOrderData == null ? void 0 : localOrderData.type) || orderInfo.type || "virtual";
806
- const platform = (localOrderData == null ? void 0 : localOrderData.platform) || orderInfo.platform || "pc";
856
+ const createdAt = orderInfo.created_at || new Date().toISOString();
857
+ const orderType = localOrderData?.type || orderInfo.type || 'virtual';
858
+ const platform = localOrderData?.platform || orderInfo.platform || 'pc';
807
859
  const result = {
808
860
  uuid: currentOrder.uuid,
809
861
  orderId: currentOrder.order_id,
@@ -812,18 +864,19 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
812
864
  paymentStatus: currentOrder.payment_status,
813
865
  isDeposit: Boolean(currentOrder.is_deposit),
814
866
  depositAmount: currentOrder.deposit_amount,
815
- orderType,
816
- platform,
867
+ orderType: orderType,
868
+ platform: platform,
817
869
  createdAt,
818
870
  itemCount: cartItems.length,
819
871
  hasLocalOrderData: Boolean(localOrderData)
820
872
  };
821
873
  return result;
822
874
  } catch (error) {
823
- console.error("[Checkout] 获取当前订单基础信息失败:", error);
875
+ console.error('[Checkout] 获取当前订单基础信息失败:', error);
824
876
  return null;
825
877
  }
826
878
  }
879
+
827
880
  /**
828
881
  * 获取当前订单的支付项
829
882
  *
@@ -831,32 +884,36 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
831
884
  */
832
885
  async getCurrentOrderPaymentItemsAsync() {
833
886
  try {
834
- const { currentOrder } = this.store;
887
+ const {
888
+ currentOrder
889
+ } = this.store;
835
890
  if (!currentOrder) {
836
- console.log("[Checkout] 当前没有活跃订单,无法获取支付项");
837
891
  return [];
838
892
  }
839
- const paymentItems = await this.payment.getPaymentItemsAsync(
840
- currentOrder.uuid
841
- );
893
+
894
+ // 调用Payment模块获取支付项
895
+ const paymentItems = await this.payment.getPaymentItemsAsync(currentOrder.uuid);
842
896
  return paymentItems;
843
897
  } catch (error) {
844
- console.error("[Checkout] 获取当前订单支付项失败:", error);
898
+ console.error('[Checkout] 获取当前订单支付项失败:', error);
845
899
  return [];
846
900
  }
847
901
  }
902
+
848
903
  /**
849
904
  * 获取订单模块
850
905
  */
851
906
  getOrderModule() {
852
907
  return this.order;
853
908
  }
909
+
854
910
  /**
855
911
  * 获取支付模块
856
912
  */
857
913
  getPaymentModule() {
858
914
  return this.payment;
859
915
  }
916
+
860
917
  /**
861
918
  * 替换本地订单ID为真实订单ID
862
919
  *
@@ -868,43 +925,45 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
868
925
  async replaceLocalOrderIdAsync(newOrderId) {
869
926
  try {
870
927
  if (!this.store.currentOrder) {
871
- console.warn("[Checkout] 没有当前订单,无法替换订单ID");
928
+ console.warn('[Checkout] 没有当前订单,无法替换订单ID');
872
929
  return null;
873
930
  }
874
931
  const previousOrder = this.store.currentOrder;
875
932
  const latestPaymentStatus = previousOrder.payment_status;
876
- const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(
877
- previousOrder.uuid,
878
- newOrderId
879
- );
933
+ const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(previousOrder.uuid, newOrderId);
880
934
  if (updatedOrder) {
935
+ // 🔧 重要:Payment.replaceOrderIdByUuidAsync 返回的是 DB 快照(只保证 order_id 变化)
936
+ // 这里需要合并到内存态,避免覆盖掉刚刚从后端拿到的 payment_status 等字段
881
937
  this.store.currentOrder = {
882
938
  ...previousOrder,
883
939
  ...updatedOrder,
884
940
  payment_status: latestPaymentStatus
885
941
  };
886
- if (latestPaymentStatus)
887
- await this.payment.updateOrderAsync(previousOrder.uuid, {
888
- payment_status: latestPaymentStatus
889
- });
942
+
943
+ // 同步更新 Payment 模块 DB,避免后续再次从 DB 读回旧的 payment_status
944
+ if (latestPaymentStatus) await this.payment.updateOrderAsync(previousOrder.uuid, {
945
+ payment_status: latestPaymentStatus
946
+ });
947
+
948
+ // 触发订单更新事件
890
949
  await this.core.effects.emit(`${this.name}:onOrderCreated`, {
891
950
  order: updatedOrder,
892
951
  timestamp: Date.now()
893
952
  });
894
- console.log("[Checkout] 本地订单ID替换成功:", {
895
- uuid: updatedOrder.uuid,
896
- newOrderId: updatedOrder.id
897
- });
953
+ // 标记订单已同步(替换ID意味着订单已在后端创建)
898
954
  this.store.isOrderSynced = true;
955
+
956
+ // 订单ID替换后更新 stateAmount
899
957
  await this.updateStateAmountToRemaining(false);
900
958
  }
901
959
  return updatedOrder;
902
960
  } catch (error) {
903
- console.error("[Checkout] 替换订单ID失败:", error);
904
- await this.handleError(error, import_types.CheckoutErrorType.UnknownError);
961
+ console.error('[Checkout] 替换订单ID失败:', error);
962
+ await this.handleError(error, _types.CheckoutErrorType.UnknownError);
905
963
  return null;
906
964
  }
907
965
  }
966
+
908
967
  /**
909
968
  * 设置自定义支付金额
910
969
  *
@@ -914,35 +973,40 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
914
973
  */
915
974
  async setStateAmountAsync(amount) {
916
975
  try {
976
+ // 验证金额格式
917
977
  const numAmount = parseFloat(amount);
918
978
  if (isNaN(numAmount) || numAmount < 0) {
919
979
  throw new Error(`无效的支付金额: ${amount}`);
920
980
  }
921
981
  const oldAmount = this.store.stateAmount;
922
982
  const formattedAmount = numAmount.toFixed(2);
983
+
984
+ // 如果金额没有变化,直接返回
923
985
  if (oldAmount === formattedAmount) {
924
986
  return;
925
987
  }
926
- this.logInfo("[Checkout] 设置自定义支付金额:", {
988
+ this.logInfo('[Checkout] 设置自定义支付金额:', {
927
989
  oldAmount,
928
990
  newAmount: formattedAmount
929
991
  });
992
+
993
+ // 更新状态
930
994
  this.store.stateAmount = formattedAmount;
995
+
996
+ // 触发金额变更事件
931
997
  await this.core.effects.emit(`${this.name}:onStateAmountChanged`, {
932
998
  oldAmount,
933
999
  newAmount: formattedAmount,
934
1000
  timestamp: Date.now()
935
1001
  });
936
1002
  } catch (error) {
937
- const errorMessage = error instanceof Error ? error.message : "设置支付金额失败";
938
- console.error("[Checkout] 设置自定义支付金额失败:", errorMessage);
939
- await this.handleError(
940
- new Error(errorMessage),
941
- import_types.CheckoutErrorType.ValidationFailed
942
- );
1003
+ const errorMessage = error instanceof Error ? error.message : '设置支付金额失败';
1004
+ console.error('[Checkout] 设置自定义支付金额失败:', errorMessage);
1005
+ await this.handleError(new Error(errorMessage), _types.CheckoutErrorType.ValidationFailed);
943
1006
  throw error;
944
1007
  }
945
1008
  }
1009
+
946
1010
  /**
947
1011
  * 获取当前自定义支付金额
948
1012
  *
@@ -951,6 +1015,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
951
1015
  getStateAmount() {
952
1016
  return this.store.stateAmount;
953
1017
  }
1018
+
954
1019
  /**
955
1020
  * 获取系统计算的待付金额(只读)
956
1021
  *
@@ -961,6 +1026,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
961
1026
  getBalanceDueAmount() {
962
1027
  return this.store.balanceDueAmount;
963
1028
  }
1029
+
964
1030
  /**
965
1031
  * 获取购物车小计数据
966
1032
  *
@@ -970,19 +1036,20 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
970
1036
  */
971
1037
  getCartSummary() {
972
1038
  if (!this.store.cartSummary || this.store.cartSummary.length === 0) {
973
- console.warn("[Checkout] 没有可用的购物车小计数据");
1039
+ console.warn('[Checkout] 没有可用的购物车小计数据');
974
1040
  return null;
975
1041
  }
976
- this.logInfo("获取购物车小计数据:", {
1042
+ this.logInfo('获取购物车小计数据:', {
977
1043
  itemCount: this.store.cartSummary.length,
978
- items: this.store.cartSummary.map((item) => ({
1044
+ items: this.store.cartSummary.map(item => ({
979
1045
  key: item.key,
980
1046
  value: item.value,
981
1047
  label: item.label
982
1048
  }))
983
1049
  });
984
- return [...this.store.cartSummary];
1050
+ return [...this.store.cartSummary]; // 返回副本,避免外部修改
985
1051
  }
1052
+
986
1053
  /**
987
1054
  * 获取支付方式列表
988
1055
  *
@@ -992,25 +1059,26 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
992
1059
  * @returns 支付方式列表
993
1060
  */
994
1061
  async getPaymentMethodsAsync() {
1062
+ // 优先使用 store 中的缓存数据
995
1063
  if (this.store.paymentMethods && this.store.paymentMethods.length > 0) {
996
- this.logInfo(
997
- `使用缓存的支付方式数据,共 ${this.store.paymentMethods.length} 种`
998
- );
1064
+ this.logInfo(`使用缓存的支付方式数据,共 ${this.store.paymentMethods.length} 种`);
999
1065
  return this.store.paymentMethods;
1000
1066
  }
1001
- this.logInfo("store 中无缓存,从 Payment 模块获取支付方式...");
1067
+
1068
+ // 如果缓存为空,调用 Payment 模块获取
1069
+ this.logInfo('store 中无缓存,从 Payment 模块获取支付方式...');
1002
1070
  try {
1003
1071
  const methods = await this.payment.getPayMethodListAsync();
1072
+ // 更新缓存
1004
1073
  this.store.paymentMethods = methods;
1005
- this.logInfo(
1006
- `从 Payment 模块获取到 ${methods.length} 种支付方式,已更新缓存`
1007
- );
1074
+ this.logInfo(`从 Payment 模块获取到 ${methods.length} 种支付方式,已更新缓存`);
1008
1075
  return methods;
1009
1076
  } catch (error) {
1010
- this.logError("获取支付方式失败:", error);
1077
+ this.logError('获取支付方式失败:', error);
1011
1078
  return [];
1012
1079
  }
1013
1080
  }
1081
+
1014
1082
  /**
1015
1083
  * 为当前订单添加支付项
1016
1084
  *
@@ -1020,14 +1088,16 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1020
1088
  * @throws 当前没有活跃订单时抛出错误
1021
1089
  */
1022
1090
  async addPaymentItemAsync(paymentItem, orderUuid) {
1023
- var _a, _b, _c, _d, _e;
1024
- this.logInfo("addPaymentItemAsync called", { paymentItem, orderUuid });
1025
- const isEftposPayment = ((_a = paymentItem.type) == null ? void 0 : _a.toLowerCase()) === "eftpos" || ((_b = paymentItem.code) == null ? void 0 : _b.toUpperCase().includes("EFTPOS"));
1091
+ this.logInfo('addPaymentItemAsync called', {
1092
+ paymentItem,
1093
+ orderUuid
1094
+ });
1095
+ const isEftposPayment = paymentItem.type?.toLowerCase() === 'eftpos' || paymentItem.code?.toUpperCase().includes('EFTPOS');
1026
1096
  const shouldRepairFromIndexDb = !!orderUuid && isEftposPayment && (!this.store.currentOrder || this.store.currentOrder.uuid !== orderUuid);
1027
1097
  if (shouldRepairFromIndexDb) {
1028
- this.logError("EFTPOS push payment repair triggered", {
1098
+ this.logError('EFTPOS push payment repair triggered', {
1029
1099
  orderUuid,
1030
- currentOrderUuid: (_c = this.store.currentOrder) == null ? void 0 : _c.uuid,
1100
+ currentOrderUuid: this.store.currentOrder?.uuid,
1031
1101
  paymentCode: paymentItem.code,
1032
1102
  paymentType: paymentItem.type
1033
1103
  });
@@ -1037,7 +1107,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1037
1107
  paymentItem
1038
1108
  });
1039
1109
  } catch (error) {
1040
- this.logError("EFTPOS push payment repair failed", {
1110
+ this.logError('EFTPOS push payment repair failed', {
1041
1111
  orderUuid,
1042
1112
  error: error instanceof Error ? error.message : String(error)
1043
1113
  });
@@ -1045,63 +1115,73 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1045
1115
  return;
1046
1116
  }
1047
1117
  try {
1118
+ // 检查是否有当前订单
1048
1119
  if (!this.store.currentOrder) {
1049
- throw (0, import_utils.createCheckoutError)(
1050
- import_types.CheckoutErrorType.ValidationFailed,
1051
- "未找到当前订单,无法添加支付项"
1052
- );
1120
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, '未找到当前订单,无法添加支付项');
1053
1121
  }
1054
- const orderPaymentType = this.store.currentOrder.is_deposit === 1 ? "deposit" : "normal";
1122
+
1123
+ // 根据当前订单的定金状态设置订单支付类型
1124
+ const orderPaymentType = this.store.currentOrder.is_deposit === 1 ? 'deposit' : 'normal';
1125
+
1126
+ // 处理现金支付的找零逻辑
1055
1127
  const processedPaymentItem = await this.processCashPaymentItem(paymentItem);
1128
+
1129
+ // 从 otherParams 获取 metadata 字段
1056
1130
  const metadata = {
1057
1131
  ...processedPaymentItem.metadata,
1058
1132
  rounding_rule: this.otherParams.order_rounding_setting,
1059
1133
  shop_wallet_pass_id: this.otherParams.shop_wallet_pass_id
1060
1134
  };
1135
+
1136
+ // 设置支付项的订单支付类型和 metadata
1061
1137
  const paymentItemWithType = {
1062
1138
  ...processedPaymentItem,
1063
1139
  order_payment_type: orderPaymentType,
1064
1140
  metadata
1065
1141
  };
1066
- await this.payment.addPaymentItemAsync(
1067
- this.store.currentOrder.uuid,
1068
- paymentItemWithType
1069
- );
1070
- this.logInfo("支付项添加成功");
1142
+
1143
+ // 添加支付项到订单
1144
+ await this.payment.addPaymentItemAsync(this.store.currentOrder.uuid, paymentItemWithType);
1145
+ this.logInfo('支付项添加成功');
1146
+
1147
+ // 🚀 清除计算缓存,确保获取最新数据
1071
1148
  this.clearCalculationCache();
1149
+
1150
+ // 支付项添加后,更新 stateAmount 为剩余未支付金额
1072
1151
  await this.updateStateAmountToRemaining();
1152
+
1153
+ // 检查订单金额是否还有待付的,如果有才同步 EFTPOS 支付
1073
1154
  const remainingAmount = await this.calculateRemainingAmountAsync();
1074
1155
  if (Number(remainingAmount) > 0) {
1075
- this.logInfo("订单金额还有待付的,同步 EFTPOS 支付");
1076
- const isEftposPayment2 = ((_d = paymentItem.type) == null ? void 0 : _d.toLowerCase()) === "eftpos" || ((_e = paymentItem.code) == null ? void 0 : _e.toUpperCase().includes("EFTPOS"));
1077
- const isCash = (0, import_utils.isCashPayment)(paymentItem);
1078
- const isCustomePayment = paymentItem.type === "custom";
1079
- this.logInfo("EFTPOS 支付检查:", {
1156
+ this.logInfo('订单金额还有待付的,同步 EFTPOS 支付');
1157
+ // 检查是否是 EFTPOS 支付,如果是则立即同步订单
1158
+ const isEftposPayment = paymentItem.type?.toLowerCase() === 'eftpos' || paymentItem.code?.toUpperCase().includes('EFTPOS');
1159
+ const isCash = (0, _utils.isCashPayment)(paymentItem);
1160
+ const isCustomePayment = paymentItem.type === 'custom';
1161
+ this.logInfo('EFTPOS 支付检查:', {
1080
1162
  paymentCode: paymentItem.code,
1081
1163
  paymentType: paymentItem.type,
1082
- isEftposPayment: isEftposPayment2,
1164
+ isEftposPayment,
1083
1165
  currentOrderSynced: this.store.isOrderSynced
1084
1166
  });
1085
- if (isEftposPayment2 || isCash || isCustomePayment) {
1086
- this.logInfo("检测到 EFTPOS 支付,立即同步订单到后端...");
1167
+ if (isEftposPayment || isCash || isCustomePayment) {
1168
+ this.logInfo('检测到 EFTPOS 支付,立即同步订单到后端...');
1087
1169
  try {
1170
+ // EFTPOS 支付后的同步标记为手动同步,确保 OnOrderSynced 事件中 isManual = true
1088
1171
  const syncResult = await this.syncOrderToBackendWithReturn(true);
1089
- this.logInfo("EFTPOS 支付后订单同步完成 (已标记为手动同步):", {
1172
+ this.logInfo('EFTPOS 支付后订单同步完成 (已标记为手动同步):', {
1090
1173
  orderId: syncResult.orderId,
1091
1174
  isOrderSynced: this.store.isOrderSynced,
1092
1175
  backendResponse: syncResult.response
1093
1176
  });
1094
1177
  } catch (error) {
1095
- this.logError("EFTPOS 支付后订单同步失败:", error);
1096
- await this.handleError(
1097
- new Error(
1098
- `EFTPOS 支付后订单同步失败: ${error instanceof Error ? error.message : String(error)}`
1099
- ),
1100
- import_types.CheckoutErrorType.OrderCreationFailed
1101
- );
1178
+ this.logError('EFTPOS 支付后订单同步失败:', error);
1179
+ // 不抛出错误,避免影响支付流程,但记录错误
1180
+ await this.handleError(new Error(`EFTPOS 支付后订单同步失败: ${error instanceof Error ? error.message : String(error)}`), _types.CheckoutErrorType.OrderCreationFailed);
1102
1181
  }
1103
1182
  }
1104
1183
  }
1184
+ // 触发支付项添加事件(可以复用支付开始事件)
1105
1185
  this.core.effects.emit(`${this.name}:onPaymentItemAdded`, {
1106
1186
  orderUuid: this.store.currentOrder.uuid,
1107
1187
  paymentMethodCode: paymentItem.code,
@@ -1110,11 +1190,12 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1110
1190
  timestamp: Date.now()
1111
1191
  });
1112
1192
  } catch (error) {
1113
- this.logError("添加支付项失败:", error);
1114
- await this.handleError(error, import_types.CheckoutErrorType.PaymentFailed);
1193
+ this.logError('添加支付项失败:', error);
1194
+ await this.handleError(error, _types.CheckoutErrorType.PaymentFailed);
1115
1195
  throw error;
1116
1196
  }
1117
1197
  }
1198
+
1118
1199
  /**
1119
1200
  * 删除当前订单的支付项
1120
1201
  *
@@ -1126,59 +1207,56 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1126
1207
  */
1127
1208
  async deletePaymentItemAsync(paymentUuid) {
1128
1209
  try {
1210
+ // 检查是否有当前订单
1129
1211
  if (!this.store.currentOrder) {
1130
- throw (0, import_utils.createCheckoutError)(
1131
- import_types.CheckoutErrorType.ValidationFailed,
1132
- "当前没有活跃订单,无法删除支付项"
1133
- );
1212
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, '当前没有活跃订单,无法删除支付项');
1134
1213
  }
1135
- this.logWarning("开始删除支付项:", {
1214
+ this.logWarning('开始删除支付项:', {
1136
1215
  orderUuid: this.store.currentOrder.uuid,
1137
- paymentUuid
1216
+ paymentUuid: paymentUuid
1138
1217
  });
1139
- const currentPayments = await this.payment.getPaymentItemsAsync(
1140
- this.store.currentOrder.uuid,
1141
- true
1142
- // 包括已撤销的支付项,因为我们需要验证是否存在
1218
+
1219
+ // 从 Payment 模块验证支付项是否存在
1220
+ const currentPayments = await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid, true // 包括已撤销的支付项,因为我们需要验证是否存在
1143
1221
  );
1144
- const paymentItem = currentPayments.find((p) => p.uuid === paymentUuid);
1222
+ const paymentItem = currentPayments.find(p => p.uuid === paymentUuid);
1145
1223
  if (!paymentItem) {
1146
- throw (0, import_utils.createCheckoutError)(
1147
- import_types.CheckoutErrorType.ValidationFailed,
1148
- `支付项不存在: ${paymentUuid}`
1149
- );
1224
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, `支付项不存在: ${paymentUuid}`);
1150
1225
  }
1151
- this.logInfo("找到要删除的支付项:", {
1226
+ this.logInfo('找到要删除的支付项:', {
1152
1227
  uuid: paymentItem.uuid,
1153
1228
  code: paymentItem.code,
1154
1229
  amount: paymentItem.amount,
1155
1230
  status: paymentItem.status
1156
1231
  });
1157
- await this.payment.deletePaymentAsync(
1158
- this.store.currentOrder.uuid,
1159
- paymentUuid
1160
- );
1161
- this.logInfo("Payment支付项删除完成", paymentItem);
1232
+
1233
+ // 调用 Payment 模块删除支付项
1234
+ await this.payment.deletePaymentAsync(this.store.currentOrder.uuid, paymentUuid);
1235
+ this.logInfo('Payment支付项删除完成', paymentItem);
1236
+
1237
+ // 🚀 清除计算缓存,确保获取最新数据
1162
1238
  this.clearCalculationCache();
1163
- const currentOrderId = this.store.currentOrder.order_id;
1164
- const isCurrentOrderReal = currentOrderId && !(0, import_utils.isVirtualOrderId)(currentOrderId);
1165
- const updatedOrder = await this.payment.getPaymentOrderByUuidAsync(
1166
- this.store.currentOrder.uuid
1167
- );
1239
+
1240
+ // 重新从Payment模块获取最新的订单数据,确保支付项同步
1241
+ const currentOrderId = this.store.currentOrder.order_id; // 保存当前的订单ID
1242
+ const isCurrentOrderReal = currentOrderId && !(0, _utils.isVirtualOrderId)(currentOrderId);
1243
+ const updatedOrder = await this.payment.getPaymentOrderByUuidAsync(this.store.currentOrder.uuid);
1168
1244
  if (updatedOrder) {
1169
- if (isCurrentOrderReal && (0, import_utils.isVirtualOrderId)(updatedOrder.order_id)) {
1170
- this.logWarning(
1171
- "[Checkout] deletePaymentItemAsync: 检测到订单ID回退,保护真实订单ID:",
1172
- {
1173
- currentRealId: currentOrderId,
1174
- retrievedVirtualId: updatedOrder.order_id
1175
- }
1176
- );
1177
- updatedOrder.order_id = currentOrderId;
1245
+ // 如果当前订单ID是真实ID,但获取到的订单ID是虚拟ID,需要保护真实ID
1246
+ if (isCurrentOrderReal && (0, _utils.isVirtualOrderId)(updatedOrder.order_id)) {
1247
+ this.logWarning('[Checkout] deletePaymentItemAsync: 检测到订单ID回退,保护真实订单ID:', {
1248
+ currentRealId: currentOrderId,
1249
+ retrievedVirtualId: updatedOrder.order_id
1250
+ });
1251
+ updatedOrder.order_id = currentOrderId; // 恢复真实的订单ID
1178
1252
  }
1179
1253
  this.store.currentOrder = updatedOrder;
1180
1254
  }
1255
+
1256
+ // 更新 stateAmount 为剩余未支付金额
1181
1257
  await this.updateStateAmountToRemaining(false);
1258
+
1259
+ // 触发支付项删除事件
1182
1260
  await this.core.effects.emit(`${this.name}:onPaymentStarted`, {
1183
1261
  orderUuid: this.store.currentOrder.uuid,
1184
1262
  paymentMethodCode: paymentItem.code,
@@ -1187,11 +1265,12 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1187
1265
  timestamp: Date.now()
1188
1266
  });
1189
1267
  } catch (error) {
1190
- this.logError("删除支付项失败:", error);
1191
- await this.handleError(error, import_types.CheckoutErrorType.PaymentFailed);
1268
+ this.logError('删除支付项失败:', error);
1269
+ await this.handleError(error, _types.CheckoutErrorType.PaymentFailed);
1192
1270
  throw error;
1193
1271
  }
1194
1272
  }
1273
+
1195
1274
  /**
1196
1275
  * 批量更新当前订单的代金券支付项(覆盖更新)
1197
1276
  *
@@ -1204,55 +1283,56 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1204
1283
  */
1205
1284
  async updateVoucherPaymentItemsAsync(voucherPaymentItems) {
1206
1285
  try {
1207
- this.logInfo("updateVoucherPaymentItemsAsync called:", {
1286
+ this.logInfo('updateVoucherPaymentItemsAsync called:', {
1208
1287
  voucherPaymentItems
1209
1288
  });
1289
+ // 检查是否有当前订单
1210
1290
  if (!this.store.currentOrder) {
1211
- throw (0, import_utils.createCheckoutError)(
1212
- import_types.CheckoutErrorType.ValidationFailed,
1213
- "当前没有活跃订单,无法更新代金券支付项"
1214
- );
1291
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, '当前没有活跃订单,无法更新代金券支付项');
1215
1292
  }
1216
- const paymentItems = await this.payment.getPaymentItemsAsync(
1217
- this.store.currentOrder.uuid
1218
- );
1219
- if (!voucherPaymentItems || (voucherPaymentItems == null ? void 0 : voucherPaymentItems.length) === 0) {
1220
- const savedVoucherPaymentItems = (paymentItems == null ? void 0 : paymentItems.filter((item) => item.voucher_id && !item.isSynced)) || [];
1221
- this.logInfo("未传入 voucher 且本地订单无 voucher 记录,阻断updateVoucherPaymentItemsAsync", {
1293
+
1294
+ // 🔒 防重复操作检查:只有订单已同步且支付完成且所有支付项都已经同步
1295
+ const paymentItems = await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid);
1296
+ if (!voucherPaymentItems || voucherPaymentItems?.length === 0) {
1297
+ const savedVoucherPaymentItems = paymentItems?.filter(item => item.voucher_id && !item.isSynced) || [];
1298
+ this.logInfo('未传入 voucher 且本地订单无 voucher 记录,阻断updateVoucherPaymentItemsAsync', {
1222
1299
  voucherPaymentItems,
1223
1300
  savedVoucherPaymentItems
1224
1301
  });
1225
- if ((savedVoucherPaymentItems == null ? void 0 : savedVoucherPaymentItems.length) === 0) {
1302
+ if (savedVoucherPaymentItems?.length === 0) {
1226
1303
  this.updateStateAmountToRemaining(false);
1227
1304
  return;
1228
1305
  }
1229
1306
  }
1230
- const allPaymentItemsSynced = paymentItems.every((item) => item.isSynced);
1307
+ const allPaymentItemsSynced = paymentItems.every(item => item.isSynced);
1231
1308
  const remainingAmount = await this.calculateRemainingAmountAsync();
1232
- const remainingValue = new import_decimal.default(remainingAmount);
1309
+ const remainingValue = new _decimal.default(remainingAmount);
1233
1310
  const isOrderSynced = this.store.isOrderSynced;
1234
1311
  if (remainingValue.lte(0) && isOrderSynced && voucherPaymentItems.length === 0 && allPaymentItemsSynced) {
1235
- this.logInfo("订单已同步且支付完成,跳过清空代金券操作避免重复同步:", {
1312
+ this.logInfo('订单已同步且支付完成,跳过清空代金券操作避免重复同步:', {
1236
1313
  orderUuid: this.store.currentOrder.uuid,
1237
1314
  orderId: this.store.currentOrder.order_id,
1238
1315
  remainingAmount,
1239
1316
  isOrderSynced,
1240
1317
  voucherPaymentItemsCount: voucherPaymentItems.length,
1241
- reason: "Order synced and payment completed, skip clear vouchers to avoid duplicate sync"
1318
+ reason: 'Order synced and payment completed, skip clear vouchers to avoid duplicate sync'
1242
1319
  });
1243
- return;
1320
+ return; // 直接返回,不执行任何操作
1244
1321
  }
1245
- this.logInfo("开始批量更新代金券支付项:", {
1322
+ this.logInfo('开始批量更新代金券支付项:', {
1246
1323
  voucherPaymentItems
1247
1324
  });
1248
- const orderPaymentType = this.store.currentOrder.is_deposit === 1 ? "deposit" : "normal";
1249
- const voucherPaymentItemsWithType = voucherPaymentItems.map((item) => {
1325
+
1326
+ // 根据当前订单的定金状态设置订单支付类型
1327
+ const orderPaymentType = this.store.currentOrder.is_deposit === 1 ? 'deposit' : 'normal';
1328
+
1329
+ // 验证所有支付项都包含 voucher_id,并设置 order_payment_type 和 metadata
1330
+ const voucherPaymentItemsWithType = voucherPaymentItems.map(item => {
1250
1331
  if (!item.voucher_id) {
1251
- throw (0, import_utils.createCheckoutError)(
1252
- import_types.CheckoutErrorType.ValidationFailed,
1253
- `代金券支付项缺少 voucher_id: ${JSON.stringify(item)}`
1254
- );
1332
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, `代金券支付项缺少 voucher_id: ${JSON.stringify(item)}`);
1255
1333
  }
1334
+
1335
+ // 从 otherParams 获取 metadata 字段
1256
1336
  const metadata = {
1257
1337
  ...item.metadata,
1258
1338
  rounding_rule: this.otherParams.order_rounding_setting,
@@ -1264,43 +1344,49 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1264
1344
  metadata
1265
1345
  };
1266
1346
  });
1267
- await this.payment.updateVoucherPaymentItemsAsync(
1268
- this.store.currentOrder.uuid,
1269
- voucherPaymentItemsWithType
1270
- );
1347
+
1348
+ // 调用 Payment 模块的批量更新方法
1349
+ await this.payment.updateVoucherPaymentItemsAsync(this.store.currentOrder.uuid, voucherPaymentItemsWithType);
1350
+
1351
+ // 🚀 清除计算缓存,确保获取最新数据
1271
1352
  this.clearCalculationCache();
1272
- const currentOrderId = this.store.currentOrder.order_id;
1273
- const isCurrentOrderReal = currentOrderId && !(0, import_utils.isVirtualOrderId)(currentOrderId);
1274
- const updatedOrder = await this.payment.getPaymentOrderByUuidAsync(
1275
- this.store.currentOrder.uuid
1276
- );
1353
+
1354
+ // 重新从Payment模块获取最新的订单数据,确保支付项同步
1355
+ const currentOrderId = this.store.currentOrder.order_id; // 保存当前的订单ID
1356
+ const isCurrentOrderReal = currentOrderId && !(0, _utils.isVirtualOrderId)(currentOrderId);
1357
+ const updatedOrder = await this.payment.getPaymentOrderByUuidAsync(this.store.currentOrder.uuid);
1277
1358
  if (updatedOrder) {
1278
- if (isCurrentOrderReal && (0, import_utils.isVirtualOrderId)(updatedOrder.order_id)) {
1279
- this.logWarning(
1280
- "updateVoucherPaymentItemsAsync: 检测到订单ID回退,保护真实订单ID:",
1281
- {
1282
- currentRealId: currentOrderId,
1283
- retrievedVirtualId: updatedOrder.order_id
1284
- }
1285
- );
1286
- updatedOrder.order_id = currentOrderId;
1359
+ // 如果当前订单ID是真实ID,但获取到的订单ID是虚拟ID,需要保护真实ID
1360
+ if (isCurrentOrderReal && (0, _utils.isVirtualOrderId)(updatedOrder.order_id)) {
1361
+ this.logWarning('updateVoucherPaymentItemsAsync: 检测到订单ID回退,保护真实订单ID:', {
1362
+ currentRealId: currentOrderId,
1363
+ retrievedVirtualId: updatedOrder.order_id
1364
+ });
1365
+ updatedOrder.order_id = currentOrderId; // 恢复真实的订单ID
1287
1366
  }
1288
1367
  this.store.currentOrder = updatedOrder;
1289
1368
  }
1369
+
1370
+ // 更新 stateAmount 为剩余未支付金额
1290
1371
  await this.updateStateAmountToRemaining(false);
1372
+
1373
+ // 触发支付项更新事件
1291
1374
  await this.core.effects.emit(`${this.name}:onPaymentStarted`, {
1292
1375
  orderUuid: this.store.currentOrder.uuid,
1293
- paymentMethodCode: "VOUCHER_BATCH",
1376
+ paymentMethodCode: 'VOUCHER_BATCH',
1294
1377
  amount: voucherPaymentItems.reduce((sum, item) => sum + parseFloat(String(item.amount)), 0).toFixed(2),
1295
1378
  timestamp: Date.now()
1296
1379
  });
1297
- this.logInfo("代金券支付项批量更新成功");
1380
+ this.logInfo('代金券支付项批量更新成功');
1298
1381
  } catch (error) {
1299
- this.logInfo("[Checkout] 批量更新代金券支付项失败:", { error });
1300
- await this.handleError(error, import_types.CheckoutErrorType.PaymentFailed);
1382
+ this.logInfo('[Checkout] 批量更新代金券支付项失败:', {
1383
+ error
1384
+ });
1385
+ await this.handleError(error, _types.CheckoutErrorType.PaymentFailed);
1301
1386
  throw error;
1302
1387
  }
1303
1388
  }
1389
+
1304
1390
  /**
1305
1391
  * 修改当前订单的定金状态
1306
1392
  *
@@ -1311,62 +1397,77 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1311
1397
  */
1312
1398
  async updateOrderDepositStatusAsync(isDeposit) {
1313
1399
  try {
1400
+ // 验证参数
1314
1401
  if (isDeposit !== 0 && isDeposit !== 1) {
1315
- throw (0, import_utils.createCheckoutError)(
1316
- import_types.CheckoutErrorType.ValidationFailed,
1317
- "isDeposit 参数只能是 0(全款订单)或 1(定金订单)"
1318
- );
1402
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, 'isDeposit 参数只能是 0(全款订单)或 1(定金订单)');
1319
1403
  }
1404
+
1405
+ // 检查是否有当前订单
1320
1406
  if (!this.store.currentOrder) {
1321
- throw (0, import_utils.createCheckoutError)(
1322
- import_types.CheckoutErrorType.ValidationFailed,
1323
- "未找到当前订单,无法修改定金状态"
1324
- );
1407
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, '未找到当前订单,无法修改定金状态');
1325
1408
  }
1326
1409
  const newDepositValue = isDeposit;
1327
1410
  const oldDepositValue = this.store.currentOrder.is_deposit;
1411
+
1412
+ // 如果状态没有变化,直接返回
1328
1413
  if (oldDepositValue === newDepositValue) {
1329
- console.log("[Checkout] 定金状态无变化,跳过更新");
1330
1414
  return;
1331
1415
  }
1332
- let deposit_amount = this.store.currentOrder.deposit_amount || "0.00";
1416
+ let deposit_amount = this.store.currentOrder.deposit_amount || '0.00';
1417
+ // 如果原来没有 deposit_amount,则默认把待付金额置为 deposit_amount
1333
1418
  if (!deposit_amount || Number(deposit_amount) === 0) {
1334
1419
  deposit_amount = this.store.currentOrder.expect_amount;
1335
1420
  }
1421
+
1422
+ // 准备更新参数
1336
1423
  const updateParams = {
1337
1424
  is_deposit: newDepositValue,
1338
- deposit_amount
1425
+ deposit_amount: deposit_amount
1339
1426
  };
1340
- await this.payment.updateOrderAsync(
1341
- this.store.currentOrder.uuid,
1342
- updateParams
1343
- );
1427
+
1428
+ // 如果从定金改为全款,可以清空定金金额
1429
+ // if (
1430
+ // isDeposit === 0 &&
1431
+ // this.store.currentOrder.deposit_amount !== '0.00'
1432
+ // ) {
1433
+ // updateParams.deposit_amount = '0.00';
1434
+ // this.logInfo('订单从定金改为全款,清空定金金额');
1435
+ // }
1436
+
1437
+ // 调用 Payment 模块更新订单
1438
+ await this.payment.updateOrderAsync(this.store.currentOrder.uuid, updateParams);
1439
+
1440
+ // 更新本地缓存的订单对象
1344
1441
  this.store.currentOrder = {
1345
1442
  ...this.store.currentOrder,
1346
1443
  ...updateParams
1347
1444
  };
1445
+
1446
+ // 同时更新本地订单数据(如果存在)
1348
1447
  if (this.store.localOrderData) {
1349
1448
  this.store.localOrderData.is_deposit = newDepositValue;
1350
1449
  }
1450
+
1451
+ // 🚀 清除计算缓存,确保获取最新数据
1351
1452
  this.clearCalculationCache();
1352
1453
  this.updateStateAmountToRemaining(false);
1454
+
1455
+ // 触发订单更新事件
1353
1456
  await this.core.effects.emit(`${this.name}:onOrderCreated`, {
1354
1457
  order: this.store.currentOrder,
1355
1458
  timestamp: Date.now()
1356
1459
  });
1357
- this.logInfo("订单定金状态更新成功:", {
1460
+ this.logInfo('订单定金状态更新成功:', {
1358
1461
  isDeposit: newDepositValue,
1359
1462
  depositAmount: this.store.currentOrder.deposit_amount
1360
1463
  });
1361
1464
  } catch (error) {
1362
- this.logError("更新订单定金状态失败:", error);
1363
- await this.handleError(
1364
- error,
1365
- import_types.CheckoutErrorType.ValidationFailed
1366
- );
1465
+ this.logError('更新订单定金状态失败:', error);
1466
+ await this.handleError(error, _types.CheckoutErrorType.ValidationFailed);
1367
1467
  throw error;
1368
1468
  }
1369
1469
  }
1470
+
1370
1471
  /**
1371
1472
  * 手动设置当前订单的定金金额
1372
1473
  *
@@ -1377,76 +1478,89 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1377
1478
  * @throws 定金金额格式无效或超过订单总额时抛出错误
1378
1479
  */
1379
1480
  async setDepositAmountAsync(depositAmount) {
1380
- var _a, _b;
1381
- this.logInfo("setDepositAmountAsync called", {
1481
+ this.logInfo('setDepositAmountAsync called', {
1382
1482
  depositAmount,
1383
1483
  hasCurrentOrder: !!this.store.currentOrder,
1384
- currentOrderId: (_a = this.store.currentOrder) == null ? void 0 : _a.order_id,
1385
- currentTotalAmount: (_b = this.store.currentOrder) == null ? void 0 : _b.total_amount
1484
+ currentOrderId: this.store.currentOrder?.order_id,
1485
+ currentTotalAmount: this.store.currentOrder?.total_amount
1386
1486
  });
1387
1487
  try {
1388
- const depositValue = new import_decimal.default(depositAmount);
1488
+ // 验证定金金额格式
1489
+ const depositValue = new _decimal.default(depositAmount);
1389
1490
  if (depositValue.isNaN() || depositValue.lt(0)) {
1390
- throw (0, import_utils.createCheckoutError)(
1391
- import_types.CheckoutErrorType.ValidationFailed,
1392
- `无效的定金金额格式: ${depositAmount}`
1393
- );
1491
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, `无效的定金金额格式: ${depositAmount}`);
1394
1492
  }
1493
+
1494
+ // 检查是否有当前订单
1395
1495
  if (!this.store.currentOrder) {
1396
- throw (0, import_utils.createCheckoutError)(
1397
- import_types.CheckoutErrorType.ValidationFailed,
1398
- "未找到当前订单,无法设置定金金额"
1399
- );
1496
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, '未找到当前订单,无法设置定金金额');
1400
1497
  }
1401
1498
  const formattedDepositAmount = depositValue.toFixed(2);
1402
- const oldDepositAmount = this.store.currentOrder.deposit_amount || "0.00";
1499
+ const oldDepositAmount = this.store.currentOrder.deposit_amount || '0.00';
1500
+
1501
+ // 如果定金金额没有变化,直接返回
1403
1502
  if (formattedDepositAmount === oldDepositAmount) {
1404
- this.logInfo("定金金额无变化,跳过更新:", {
1503
+ this.logInfo('定金金额无变化,跳过更新:', {
1405
1504
  currentAmount: oldDepositAmount,
1406
1505
  newAmount: formattedDepositAmount
1407
1506
  });
1408
1507
  return;
1409
1508
  }
1410
- this.logInfo("开始设置订单定金金额:", {
1509
+ this.logInfo('开始设置订单定金金额:', {
1411
1510
  orderUuid: this.store.currentOrder.uuid,
1412
1511
  orderId: this.store.currentOrder.order_id,
1413
1512
  oldDepositAmount,
1414
1513
  newDepositAmount: formattedDepositAmount,
1415
1514
  totalAmount: this.store.currentOrder.total_amount
1416
1515
  });
1516
+
1517
+ // 准备更新参数
1417
1518
  const updateParams = {
1418
1519
  deposit_amount: formattedDepositAmount
1419
1520
  };
1521
+
1522
+ // 如果设置的定金金额大于0,自动将订单标记为定金订单
1420
1523
  if (depositValue.gt(0) && this.store.currentOrder.is_deposit !== 1) {
1421
1524
  updateParams.is_deposit = 1;
1422
- this.logInfo("定金金额大于0,自动设置为定金订单");
1423
- } else if (depositValue.eq(0) && this.store.currentOrder.is_deposit === 1) {
1525
+ this.logInfo('定金金额大于0,自动设置为定金订单');
1526
+ }
1527
+ // 如果设置的定金金额为0,可以考虑将订单标记为全款订单
1528
+ else if (depositValue.eq(0) && this.store.currentOrder.is_deposit === 1) {
1424
1529
  updateParams.is_deposit = 0;
1425
- this.logInfo("定金金额为0,自动设置为全款订单");
1530
+ this.logInfo('定金金额为0,自动设置为全款订单');
1426
1531
  }
1427
- await this.payment.updateOrderAsync(
1428
- this.store.currentOrder.uuid,
1429
- updateParams
1430
- );
1532
+
1533
+ // 调用 Payment 模块更新订单
1534
+ await this.payment.updateOrderAsync(this.store.currentOrder.uuid, updateParams);
1535
+
1536
+ // 更新本地缓存的订单对象
1431
1537
  this.store.currentOrder = {
1432
1538
  ...this.store.currentOrder,
1433
1539
  ...updateParams
1434
1540
  };
1541
+
1542
+ // 同时更新本地订单数据(如果存在)
1435
1543
  if (this.store.localOrderData) {
1436
- if ("deposit_amount" in this.store.localOrderData) {
1544
+ // 注意:本地订单数据中没有deposit_amount字段,但如果需要可以在这里添加
1545
+ if ('deposit_amount' in this.store.localOrderData) {
1437
1546
  this.store.localOrderData.deposit_amount = formattedDepositAmount;
1438
1547
  }
1439
- if (updateParams.is_deposit !== void 0) {
1548
+ // 同步更新 is_deposit 状态(如果有变化)
1549
+ if (updateParams.is_deposit !== undefined) {
1440
1550
  this.store.localOrderData.is_deposit = updateParams.is_deposit;
1441
1551
  }
1442
1552
  }
1553
+
1554
+ // 🚀 清除计算缓存,确保获取最新数据
1443
1555
  this.clearCalculationCache();
1444
1556
  this.updateStateAmountToRemaining(false);
1557
+
1558
+ // 触发订单更新事件
1445
1559
  await this.core.effects.emit(`${this.name}:onOrderCreated`, {
1446
1560
  order: this.store.currentOrder,
1447
1561
  timestamp: Date.now()
1448
1562
  });
1449
- this.logInfo("订单定金金额设置成功:", {
1563
+ this.logInfo('订单定金金额设置成功:', {
1450
1564
  orderUuid: this.store.currentOrder.uuid,
1451
1565
  orderId: this.store.currentOrder.order_id,
1452
1566
  oldDepositAmount,
@@ -1455,84 +1569,83 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1455
1569
  totalAmount: this.store.currentOrder.total_amount
1456
1570
  });
1457
1571
  } catch (error) {
1458
- this.logError("设置订单定金金额失败:", error);
1459
- await this.handleError(
1460
- error,
1461
- import_types.CheckoutErrorType.ValidationFailed
1462
- );
1572
+ this.logError('设置订单定金金额失败:', error);
1573
+ await this.handleError(error, _types.CheckoutErrorType.ValidationFailed);
1463
1574
  throw error;
1464
1575
  }
1465
1576
  }
1577
+
1466
1578
  /**
1467
1579
  * 手动同步订单到后端
1468
1580
  *
1469
1581
  * 用于强制同步订单到后端,特别适用于纯代金券支付完成的订单
1470
1582
  */
1471
1583
  async manualSyncOrderAsync() {
1472
- var _a, _b, _c, _d, _e;
1473
- console.log("manualSyncOrderAsync called");
1474
- this.logInfo("manualSyncOrderAsync called", {
1584
+ this.logInfo('manualSyncOrderAsync called', {
1475
1585
  hasCurrentOrder: !!this.store.currentOrder,
1476
- currentOrderId: (_a = this.store.currentOrder) == null ? void 0 : _a.order_id,
1477
- orderUuid: (_b = this.store.currentOrder) == null ? void 0 : _b.uuid,
1478
- totalAmount: (_c = this.store.currentOrder) == null ? void 0 : _c.total_amount,
1586
+ currentOrderId: this.store.currentOrder?.order_id,
1587
+ orderUuid: this.store.currentOrder?.uuid,
1588
+ totalAmount: this.store.currentOrder?.total_amount,
1479
1589
  isOrderSynced: this.store.isOrderSynced,
1480
- isVirtualOrderId: this.store.currentOrder ? (0, import_utils.isVirtualOrderId)(this.store.currentOrder.order_id) : false
1590
+ isVirtualOrderId: this.store.currentOrder ? (0, _utils.isVirtualOrderId)(this.store.currentOrder.order_id) : false
1481
1591
  });
1482
1592
  try {
1593
+ // 检查是否有当前订单
1483
1594
  if (!this.store.currentOrder) {
1484
1595
  return {
1485
1596
  success: false,
1486
- message: "当前没有活跃订单,无法同步"
1597
+ message: '当前没有活跃订单,无法同步'
1487
1598
  };
1488
1599
  }
1489
1600
  const orderUuid = this.store.currentOrder.uuid;
1490
1601
  const oldOrderId = this.store.currentOrder.order_id;
1602
+
1603
+ // 检查订单是否已经同步
1491
1604
  if (this.store.isOrderSynced) {
1492
- this.logInfo("订单已同步过,将执行更新操作");
1605
+ this.logInfo('订单已同步过,将执行更新操作');
1493
1606
  }
1494
- this.logInfo("开始手动同步订单到后端:", {
1495
- orderUuid,
1607
+ this.logInfo('开始手动同步订单到后端:', {
1608
+ orderUuid: orderUuid,
1496
1609
  orderId: oldOrderId,
1497
1610
  totalAmount: this.store.currentOrder.total_amount,
1498
1611
  remainingAmount: await this.calculateRemainingAmountAsync()
1499
1612
  });
1500
- console.time("manualSyncOrderAsync");
1613
+ // 强制同步订单到后端,并获取完整响应数据
1501
1614
  const syncResult = await this.syncOrderToBackendWithReturn(true);
1502
- console.timeEnd("manualSyncOrderAsync");
1503
- this.logInfo("手动同步订单完成:", {
1504
- orderUuid,
1505
- syncResult,
1506
- oldOrderId,
1615
+ this.logInfo('手动同步订单完成:', {
1616
+ orderUuid: orderUuid,
1617
+ syncResult: syncResult,
1618
+ oldOrderId: oldOrderId,
1507
1619
  realOrderId: syncResult.orderId,
1508
1620
  isOrderSynced: this.store.isOrderSynced
1509
1621
  });
1622
+
1623
+ // 🔍 关键验证:检查最终状态是否正确
1510
1624
  const finalOrderId = this.store.currentOrder.order_id;
1511
- const finalIsVirtual = (0, import_utils.isVirtualOrderId)(finalOrderId);
1625
+ const finalIsVirtual = (0, _utils.isVirtualOrderId)(finalOrderId);
1512
1626
  if (finalIsVirtual) {
1513
- this.logError("严重警告:手动同步完成后订单ID仍为虚拟ID!");
1627
+ this.logError('严重警告:手动同步完成后订单ID仍为虚拟ID!');
1514
1628
  }
1515
1629
  if (syncResult.orderId !== finalOrderId) {
1516
- this.logError(
1517
- "[Checkout] 严重警告:返回的订单ID与存储的订单ID不一致!"
1518
- );
1630
+ this.logError('[Checkout] 严重警告:返回的订单ID与存储的订单ID不一致!');
1519
1631
  }
1520
1632
  let newRes = {
1521
1633
  ...syncResult,
1522
- is_deposit: ((_d = this.store.currentOrder) == null ? void 0 : _d.is_deposit) || 0
1634
+ is_deposit: this.store.currentOrder?.is_deposit || 0
1523
1635
  };
1524
1636
  await this.updateStateAmountToRemaining(false);
1525
1637
  return newRes;
1526
1638
  } catch (error) {
1527
- this.logError("手动同步订单失败:", error);
1528
- const errorMessage = error instanceof Error ? error.message : "同步失败";
1639
+ this.logError('手动同步订单失败:', error);
1640
+ const errorMessage = error instanceof Error ? error.message : '同步失败';
1529
1641
  return {
1530
1642
  success: false,
1531
1643
  message: `订单同步失败: ${errorMessage}`,
1532
- orderUuid: (_e = this.store.currentOrder) == null ? void 0 : _e.uuid
1644
+ orderUuid: this.store.currentOrder?.uuid
1533
1645
  };
1534
1646
  }
1535
1647
  }
1648
+
1536
1649
  /**
1537
1650
  * 获取当前订单备注
1538
1651
  *
@@ -1540,11 +1653,11 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1540
1653
  */
1541
1654
  getOrderNote() {
1542
1655
  if (!this.store.localOrderData) {
1543
- console.log("[Checkout] 没有本地订单数据,无法获取备注");
1544
- return "";
1656
+ return '';
1545
1657
  }
1546
- return this.store.localOrderData.shop_note || "";
1658
+ return this.store.localOrderData.shop_note || '';
1547
1659
  }
1660
+
1548
1661
  /**
1549
1662
  * 获取当前订单ID
1550
1663
  *
@@ -1556,24 +1669,21 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1556
1669
  }
1557
1670
  return this.store.currentOrder.order_id;
1558
1671
  }
1672
+
1559
1673
  /**
1560
1674
  * 获取当前订单是否已同步到后端
1561
1675
  *
1562
1676
  * @returns 当前订单是否已同步状态,如果没有订单则返回false
1563
1677
  */
1564
1678
  isCurrentOrderSynced() {
1679
+ // 如果没有当前订单,返回false
1565
1680
  if (!this.store.currentOrder) {
1566
- console.log("[Checkout] 没有当前订单,同步状态为false");
1567
1681
  return false;
1568
1682
  }
1569
1683
  const syncStatus = this.store.isOrderSynced;
1570
- console.log("[Checkout] 当前订单同步状态:", {
1571
- orderUuid: this.store.currentOrder.uuid,
1572
- orderId: this.store.currentOrder.order_id,
1573
- isOrderSynced: syncStatus
1574
- });
1575
1684
  return syncStatus;
1576
1685
  }
1686
+
1577
1687
  /**
1578
1688
  * 取消当前本地订单
1579
1689
  *
@@ -1583,81 +1693,92 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1583
1693
  * @returns 取消结果
1584
1694
  */
1585
1695
  async cancelCurrentOrderAsync(cancelReason) {
1586
- var _a, _b;
1587
1696
  try {
1588
- this.logInfo("开始取消当前本地订单:", {
1697
+ this.logInfo('开始取消当前本地订单:', {
1589
1698
  hasCurrentOrder: !!this.store.currentOrder,
1590
- orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid,
1591
- orderId: (_b = this.store.currentOrder) == null ? void 0 : _b.order_id,
1699
+ orderUuid: this.store.currentOrder?.uuid,
1700
+ orderId: this.store.currentOrder?.order_id,
1592
1701
  isOrderSynced: this.store.isOrderSynced,
1593
- cancelReason
1702
+ cancelReason: cancelReason
1594
1703
  });
1704
+
1705
+ // 检查是否有当前订单
1595
1706
  if (!this.store.currentOrder) {
1596
- this.logInfo("没有当前订单,无需取消");
1707
+ this.logInfo('没有当前订单,无需取消');
1597
1708
  return {
1598
1709
  success: false,
1599
- message: "没有当前订单可取消"
1710
+ message: '没有当前订单可取消'
1600
1711
  };
1601
1712
  }
1602
1713
  const currentOrderUuid = this.store.currentOrder.uuid;
1603
1714
  const currentOrderId = this.store.currentOrder.order_id;
1604
1715
  const isOrderSynced = this.store.isOrderSynced;
1716
+
1717
+ // 检查订单是否已同步,已同步的订单不能取消
1605
1718
  if (isOrderSynced) {
1606
- this.logInfo("订单已同步到后端,不能取消:", {
1719
+ this.logInfo('订单已同步到后端,不能取消:', {
1607
1720
  orderId: currentOrderId,
1608
1721
  orderUuid: currentOrderUuid
1609
1722
  });
1610
1723
  return {
1611
1724
  success: false,
1612
- message: "订单已同步到后端,无法取消",
1725
+ message: '订单已同步到后端,无法取消',
1613
1726
  orderId: currentOrderId
1614
1727
  };
1615
1728
  }
1729
+ // 标记本地订单为已删除(不从 IndexDB 物理删除)
1616
1730
  try {
1617
- this.logInfo("标记本地订单为已删除");
1731
+ this.logInfo('标记本地订单为已删除');
1618
1732
  await this.payment.updateOrderAsync(currentOrderUuid, {
1619
- payment_status: import_types2.PaymentStatus.Voided
1733
+ payment_status: _types2.PaymentStatus.Voided
1620
1734
  });
1621
- this.logInfo("本地订单删除标记成功");
1735
+ this.logInfo('本地订单删除标记成功');
1622
1736
  } catch (error) {
1623
- this.logWarning("标记本地订单删除失败,但继续执行:", error);
1737
+ this.logWarning('标记本地订单删除失败,但继续执行:', error);
1624
1738
  }
1625
- this.logInfo("清理订单相关状态");
1626
- this.store.currentOrder = void 0;
1627
- this.store.localOrderData = void 0;
1628
- this.store.stateAmount = "0.00";
1629
- this.store.balanceDueAmount = "0.00";
1739
+
1740
+ // 清理订单相关状态,确保正确释放 currentOrder
1741
+ this.logInfo('清理订单相关状态');
1742
+ this.store.currentOrder = undefined; // 释放 currentOrder
1743
+ this.store.localOrderData = undefined;
1744
+ this.store.stateAmount = '0.00';
1745
+ this.store.balanceDueAmount = '0.00';
1630
1746
  this.store.isOrderSynced = false;
1631
- this.store.currentCustomer = void 0;
1747
+ this.store.currentCustomer = undefined;
1748
+
1749
+ // 清理钱包缓存
1632
1750
  this.payment.wallet.clearAllCache();
1633
- this.logInfo("订单状态清理完成,currentOrder已释放");
1751
+ this.logInfo('订单状态清理完成,currentOrder已释放');
1752
+
1753
+ // 触发订单取消事件
1634
1754
  await this.core.effects.emit(`${this.name}:onOrderCancelled`, {
1635
1755
  orderUuid: currentOrderUuid,
1636
1756
  orderId: currentOrderId,
1637
- cancelReason,
1757
+ cancelReason: cancelReason,
1638
1758
  wasSynced: false,
1639
1759
  // 只有未同步订单可以被取消
1640
1760
  timestamp: Date.now()
1641
1761
  });
1642
- this.logInfo("本地订单取消完成:", {
1762
+ this.logInfo('本地订单取消完成:', {
1643
1763
  orderUuid: currentOrderUuid,
1644
1764
  orderId: currentOrderId,
1645
- cancelReason
1765
+ cancelReason: cancelReason
1646
1766
  });
1647
1767
  return {
1648
1768
  success: true,
1649
- message: "本地订单已成功取消",
1769
+ message: '本地订单已成功取消',
1650
1770
  orderId: currentOrderId
1651
1771
  };
1652
1772
  } catch (error) {
1653
- this.logError("取消本地订单失败:", error);
1654
- const errorMessage = error instanceof Error ? error.message : "未知错误";
1773
+ this.logError('取消本地订单失败:', error);
1774
+ const errorMessage = error instanceof Error ? error.message : '未知错误';
1655
1775
  return {
1656
1776
  success: false,
1657
1777
  message: `取消订单失败: ${errorMessage}`
1658
1778
  };
1659
1779
  }
1660
1780
  }
1781
+
1661
1782
  /**
1662
1783
  * 保存订单并稍后支付
1663
1784
  *
@@ -1665,163 +1786,149 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1665
1786
  * 适用于用户想要保存订单但稍后完成支付的场景
1666
1787
  */
1667
1788
  async saveForLaterPaymentAsync() {
1668
- var _a;
1669
1789
  try {
1790
+ // 检查是否有当前订单
1670
1791
  if (!this.store.currentOrder) {
1671
1792
  return {
1672
1793
  success: false,
1673
- message: "当前没有活跃订单,无法保存"
1794
+ message: '当前没有活跃订单,无法保存'
1674
1795
  };
1675
1796
  }
1676
1797
  const orderUuid = this.store.currentOrder.uuid;
1677
1798
  const currentOrderId = this.store.currentOrder.order_id;
1678
- this.logInfo("开始保存订单并稍后支付:", {
1679
- orderUuid,
1799
+ this.logInfo('开始保存订单并稍后支付:', {
1800
+ orderUuid: orderUuid,
1680
1801
  orderId: currentOrderId,
1681
1802
  totalAmount: this.store.currentOrder.total_amount
1682
1803
  });
1683
- const allPaymentItems = await this.payment.getPaymentItemsAsync(
1684
- this.store.currentOrder.uuid
1685
- );
1686
- const orderPaymentStatus = allPaymentItems.filter((item) => item.status !== "voided").length > 0 ? "partially_paid" : "payment_processing";
1687
- const syncResult = await this.syncOrderToBackendWithReturn(
1688
- true,
1689
- allPaymentItems,
1690
- orderPaymentStatus
1691
- );
1692
- this.logInfo("保存订单完成:", {
1693
- orderUuid,
1804
+
1805
+ // 获取当前订单的所有支付项
1806
+ const allPaymentItems = await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid);
1807
+
1808
+ // 保存并稍后支付的订单状态需要特殊处理
1809
+ // 如果当前订单已经有支付项了,则标记为partially_paid 否则标记为 payment_processing
1810
+ const orderPaymentStatus = allPaymentItems.filter(item => item.status !== 'voided').length > 0 ? 'partially_paid' : 'payment_processing';
1811
+
1812
+ // 调用同步方法,传入过滤后的支付项
1813
+ const syncResult = await this.syncOrderToBackendWithReturn(true, allPaymentItems, orderPaymentStatus);
1814
+ this.logInfo('保存订单完成:', {
1815
+ orderUuid: orderUuid,
1694
1816
  oldOrderId: currentOrderId,
1695
- syncResult,
1817
+ syncResult: syncResult,
1696
1818
  realOrderId: syncResult.orderId,
1697
1819
  isOrderSynced: this.store.isOrderSynced,
1698
1820
  filteredPaymentsCount: allPaymentItems.length
1699
1821
  });
1700
1822
  return {
1701
1823
  success: true,
1702
- message: "订单保存成功,可稍后继续支付",
1824
+ message: '订单保存成功,可稍后继续支付',
1703
1825
  orderId: syncResult.orderId,
1704
- orderUuid,
1826
+ orderUuid: orderUuid,
1705
1827
  response: syncResult.response
1706
1828
  };
1707
1829
  } catch (error) {
1708
- this.logError("保存订单失败:", error);
1709
- const errorMessage = error instanceof Error ? error.message : "保存失败";
1830
+ this.logError('保存订单失败:', error);
1831
+ const errorMessage = error instanceof Error ? error.message : '保存失败';
1710
1832
  return {
1711
1833
  success: false,
1712
1834
  message: `订单保存失败: ${errorMessage}`,
1713
- orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid
1835
+ orderUuid: this.store.currentOrder?.uuid
1714
1836
  };
1715
1837
  }
1716
1838
  }
1839
+
1717
1840
  /**
1718
1841
  * 更新订单备注
1719
1842
  *
1720
1843
  * @param note 订单备注内容
1721
1844
  */
1722
1845
  async updateOrderNoteAsync(note) {
1723
- var _a, _b;
1724
1846
  try {
1847
+ // 检查是否有本地订单数据
1725
1848
  if (!this.store.localOrderData) {
1726
- throw (0, import_utils.createCheckoutError)(
1727
- import_types.CheckoutErrorType.ValidationFailed,
1728
- "没有本地订单数据,无法更新备注"
1729
- );
1849
+ throw (0, _utils.createCheckoutError)(_types.CheckoutErrorType.ValidationFailed, '没有本地订单数据,无法更新备注');
1730
1850
  }
1731
- console.log("[Checkout] 更新订单备注:", {
1732
- orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid,
1733
- oldNote: this.store.localOrderData.shop_note,
1734
- newNote: note
1735
- });
1851
+ // 更新备注
1736
1852
  const oldNote = this.store.localOrderData.shop_note;
1737
1853
  this.store.localOrderData.shop_note = note;
1854
+
1855
+ // 如果有当前订单,也同步到Payment模块中的订单数据
1738
1856
  if (this.store.currentOrder) {
1857
+ // 更新Payment模块中的订单数据(如果订单对象中有note字段)
1739
1858
  try {
1740
- const orderInPayment = await this.payment.getPaymentOrderByUuidAsync(
1741
- this.store.currentOrder.uuid
1742
- );
1743
- if (orderInPayment && orderInPayment.note !== void 0) {
1744
- console.log("[Checkout] 同步备注到Payment模块的订单数据中");
1745
- }
1859
+ const orderInPayment = await this.payment.getPaymentOrderByUuidAsync(this.store.currentOrder.uuid);
1860
+ if (orderInPayment && orderInPayment.note !== undefined) {}
1746
1861
  } catch (syncError) {
1747
- console.warn(
1748
- "[Checkout] 同步备注到Payment模块失败,但本地更新成功:",
1749
- syncError
1750
- );
1862
+ console.warn('[Checkout] 同步备注到Payment模块失败,但本地更新成功:', syncError);
1751
1863
  }
1752
1864
  }
1865
+
1866
+ // 触发订单数据变更事件
1753
1867
  await this.core.effects.emit(`${this.name}:onOrderNoteChanged`, {
1754
- orderUuid: (_b = this.store.currentOrder) == null ? void 0 : _b.uuid,
1868
+ orderUuid: this.store.currentOrder?.uuid,
1755
1869
  oldNote,
1756
1870
  newNote: note,
1757
1871
  timestamp: Date.now()
1758
1872
  });
1759
- console.log("[Checkout] 订单备注更新成功:", {
1760
- oldNote,
1761
- newNote: note
1762
- });
1763
1873
  } catch (error) {
1764
- console.error("[Checkout] 更新订单备注失败:", error);
1765
- await this.handleError(
1766
- error,
1767
- import_types.CheckoutErrorType.ValidationFailed
1768
- );
1874
+ console.error('[Checkout] 更新订单备注失败:', error);
1875
+ await this.handleError(error, _types.CheckoutErrorType.ValidationFailed);
1769
1876
  throw error;
1770
1877
  }
1771
1878
  }
1879
+
1772
1880
  /**
1773
1881
  * 处理错误
1774
1882
  */
1775
1883
  async handleError(error, type) {
1776
- const checkoutError = error instanceof Error && "type" in error ? error : (0, import_utils.createCheckoutError)(type, error.message, error);
1884
+ const checkoutError = error instanceof Error && 'type' in error ? error : (0, _utils.createCheckoutError)(type, error.message, error);
1777
1885
  this.store.lastError = checkoutError;
1778
1886
  await this.core.effects.emit(`${this.name}:onError`, {
1779
1887
  error: checkoutError,
1780
1888
  context: {},
1781
1889
  timestamp: Date.now()
1782
1890
  });
1783
- console.error("[Checkout] 错误:", checkoutError);
1891
+ console.error('[Checkout] 错误:', checkoutError);
1784
1892
  }
1893
+
1785
1894
  /**
1786
1895
  * 处理支付成功
1787
1896
  */
1788
1897
  async handlePaymentSuccess(data) {
1789
- var _a;
1898
+ // 支付状态变更后更新 stateAmount
1790
1899
  await this.updateStateAmountToRemaining();
1791
1900
  await this.core.effects.emit(`${this.name}:onPaymentSuccess`, {
1792
1901
  orderUuid: data.orderUuid,
1793
- paymentMethodCode: "",
1794
- amount: ((_a = this.store.currentOrder) == null ? void 0 : _a.total_amount) || "0",
1902
+ paymentMethodCode: '',
1903
+ amount: this.store.currentOrder?.total_amount || '0',
1795
1904
  timestamp: data.timestamp
1796
1905
  });
1906
+
1907
+ // 自动完成结账
1797
1908
  await this.completeCheckoutAsync();
1798
1909
  }
1910
+
1799
1911
  /**
1800
1912
  * 处理支付错误
1801
1913
  */
1802
1914
  async handlePaymentError(data) {
1803
- var _a;
1804
- const error = (0, import_utils.createCheckoutError)(
1805
- import_types.CheckoutErrorType.PaymentFailed,
1806
- data.error || "支付同步失败"
1807
- );
1808
- await this.handleError(
1809
- error instanceof Error ? error : new Error(String(error)),
1810
- import_types.CheckoutErrorType.PaymentFailed
1811
- );
1915
+ const error = (0, _utils.createCheckoutError)(_types.CheckoutErrorType.PaymentFailed, data.error || '支付同步失败');
1916
+ await this.handleError(error instanceof Error ? error : new Error(String(error)), _types.CheckoutErrorType.PaymentFailed);
1812
1917
  await this.core.effects.emit(`${this.name}:onPaymentFailed`, {
1813
1918
  orderUuid: data.orderUuid,
1814
- paymentMethodCode: "",
1815
- amount: ((_a = this.store.currentOrder) == null ? void 0 : _a.total_amount) || "0",
1919
+ paymentMethodCode: '',
1920
+ amount: this.store.currentOrder?.total_amount || '0',
1816
1921
  timestamp: data.timestamp
1817
1922
  });
1818
1923
  }
1924
+
1819
1925
  /**
1820
1926
  * 验证结账参数
1821
1927
  */
1822
1928
  validateCheckoutParams(params) {
1823
- return (0, import_utils.validateCheckoutData)(params);
1929
+ return (0, _utils.validateCheckoutData)(params);
1824
1930
  }
1931
+
1825
1932
  /**
1826
1933
  * 处理现金支付项的找零逻辑
1827
1934
  *
@@ -1829,27 +1936,37 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1829
1936
  * @returns 处理后的支付项(包含找零信息)
1830
1937
  */
1831
1938
  async processCashPaymentItem(paymentItem) {
1832
- const cashPayment = (0, import_utils.isCashPayment)(paymentItem);
1939
+ // 检查是否是现金支付
1940
+ const cashPayment = (0, _utils.isCashPayment)(paymentItem);
1833
1941
  if (!cashPayment) {
1942
+ // 非现金支付,直接返回原始支付项
1834
1943
  return paymentItem;
1835
1944
  }
1836
1945
  try {
1946
+ // 获取剩余待付金额
1837
1947
  const remainingAmountStr = await this.calculateRemainingAmountAsync();
1838
- let remainingAmount = new import_decimal.default(remainingAmountStr);
1839
- const cashAmount = new import_decimal.default(String(paymentItem.amount));
1948
+ let remainingAmount = new _decimal.default(remainingAmountStr);
1949
+ const cashAmount = new _decimal.default(String(paymentItem.amount));
1950
+
1951
+ // 如果现金金额小于等于剩余待付金额,无需找零
1840
1952
  if (cashAmount.lte(remainingAmount)) {
1841
1953
  return paymentItem;
1842
1954
  }
1955
+
1956
+ // 使用 Decimal.js 安全计算找零金额
1843
1957
  const changeAmount = cashAmount.sub(remainingAmount);
1958
+
1959
+ // 如果还有 rounding_amount 的配置,要判断是否和 changeAmount 相等
1844
1960
  if (Number(paymentItem.rounding_amount) > 0) {
1845
1961
  if (Number(paymentItem.rounding_amount) === changeAmount.toNumber()) {
1846
1962
  return paymentItem;
1847
1963
  } else {
1848
- remainingAmount = remainingAmount.add(
1849
- new import_decimal.default(paymentItem.rounding_amount || "0")
1850
- );
1964
+ // 如果不等于,则remainingAmount需要加上 rounding_amount,避免这里被改为未舍入金额
1965
+ remainingAmount = remainingAmount.add(new _decimal.default(paymentItem.rounding_amount || '0'));
1851
1966
  }
1852
1967
  }
1968
+
1969
+ // 创建包含找零信息的支付项
1853
1970
  const processedPaymentItem = {
1854
1971
  ...paymentItem,
1855
1972
  amount: remainingAmount.toFixed(2),
@@ -1858,11 +1975,10 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1858
1975
  ...paymentItem.metadata,
1859
1976
  actual_paid_amount: cashAmount.toNumber(),
1860
1977
  // 实付金额
1861
- change_given_amount: changeAmount.toNumber()
1862
- // 找零金额
1978
+ change_given_amount: changeAmount.toNumber() // 找零金额
1863
1979
  }
1864
1980
  };
1865
- this.logInfo("Cash payment with change processed", {
1981
+ this.logInfo('Cash payment with change processed', {
1866
1982
  originalAmount: cashAmount.toFixed(2),
1867
1983
  chargedAmount: remainingAmount.toFixed(2),
1868
1984
  changeAmount: changeAmount.toFixed(2),
@@ -1877,77 +1993,82 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1877
1993
  });
1878
1994
  return processedPaymentItem;
1879
1995
  } catch (error) {
1880
- this.logError("处理现金支付项时出错:", error);
1996
+ this.logError('处理现金支付项时出错:', error);
1997
+ // 出错时返回原始支付项,避免中断支付流程
1881
1998
  return paymentItem;
1882
1999
  }
1883
2000
  }
2001
+
1884
2002
  /**
1885
2003
  * 预加载支付方式(在初始化时调用)
1886
2004
  */
1887
2005
  async preloadPaymentMethods() {
1888
2006
  try {
1889
- console.log("[Checkout] 预加载支付方式...");
1890
2007
  const methods = await this.payment.getPayMethodListAsync();
1891
2008
  this.store.paymentMethods = methods;
1892
- console.log(`[Checkout] 预加载完成,共 ${methods.length} 种支付方式`);
1893
2009
  } catch (error) {
1894
- console.error("[Checkout] 预加载支付方式失败:", error);
2010
+ console.error('[Checkout] 预加载支付方式失败:', error);
1895
2011
  this.store.paymentMethods = [];
1896
2012
  }
1897
2013
  }
2014
+
1898
2015
  /**
1899
2016
  * 清理过期的已同步订单数据
1900
2017
  *
1901
2018
  * 删除本地 IndexDB 中超过指定天数且已同步到后端的订单数据
1902
2019
  */
1903
2020
  async cleanupExpiredOrdersAsync() {
1904
- var _a, _b, _c;
1905
2021
  try {
2022
+ // 检查是否启用了清理功能
1906
2023
  const cleanupConfig = this.otherParams.orderDataCleanup || {};
1907
- const isCleanupEnabled = cleanupConfig.enabled !== false;
1908
- const retentionDays = cleanupConfig.retentionDays || 7;
1909
- const maxOrdersToDelete = cleanupConfig.maxOrdersToDelete || 100;
2024
+ const isCleanupEnabled = cleanupConfig.enabled !== false; // 默认启用
2025
+ const retentionDays = cleanupConfig.retentionDays || 7; // 默认保留7天
2026
+ const maxOrdersToDelete = cleanupConfig.maxOrdersToDelete || 100; // 默认最多删除100个订单
2027
+
1910
2028
  if (!isCleanupEnabled) {
1911
- console.log("[Checkout] 订单数据清理功能已禁用");
1912
2029
  return;
1913
2030
  }
1914
- console.log(
1915
- `[Checkout] 开始清理过期订单数据(保留 ${retentionDays} 天内的数据)...`
1916
- );
2031
+ // 获取所有订单
1917
2032
  const allOrders = await this.payment.getOrderListAsync();
1918
2033
  if (!allOrders || allOrders.length === 0) {
1919
- console.log("[Checkout] 没有找到需要清理的订单数据");
1920
2034
  return;
1921
2035
  }
1922
- const thresholdDate = /* @__PURE__ */ new Date();
2036
+ const thresholdDate = new Date();
1923
2037
  thresholdDate.setDate(thresholdDate.getDate() - retentionDays);
1924
2038
  let deletedCount = 0;
1925
2039
  const ordersToDelete = [];
1926
2040
  for (const order of allOrders) {
1927
2041
  try {
1928
- const isSynced = order.order_id && !(0, import_utils.isVirtualOrderId)(order.order_id);
2042
+ // 检查订单是否已同步(订单ID不是虚拟ID)
2043
+ const isSynced = order.order_id && !(0, _utils.isVirtualOrderId)(order.order_id);
1929
2044
  if (!isSynced) {
1930
- continue;
2045
+ continue; // 跳过未同步的订单
1931
2046
  }
2047
+
2048
+ // 检查创建时间
1932
2049
  let orderCreatedAt = null;
1933
- if ((_a = order.order_info) == null ? void 0 : _a.created_at) {
2050
+
2051
+ // 尝试从 order_info.created_at 获取创建时间
2052
+ if (order.order_info?.created_at) {
1934
2053
  orderCreatedAt = new Date(order.order_info.created_at);
1935
- } else if ((_c = (_b = order.order_info) == null ? void 0 : _b.original_order_data) == null ? void 0 : _c.created_at) {
1936
- orderCreatedAt = new Date(
1937
- order.order_info.original_order_data.created_at
1938
- );
1939
2054
  }
2055
+ // 如果没有,尝试从 order_info.original_order_data.created_at 获取
2056
+ else if (order.order_info?.original_order_data?.created_at) {
2057
+ orderCreatedAt = new Date(order.order_info.original_order_data.created_at);
2058
+ }
2059
+
2060
+ // 如果无法获取创建时间,跳过此订单
1940
2061
  if (!orderCreatedAt || isNaN(orderCreatedAt.getTime())) {
1941
2062
  continue;
1942
2063
  }
2064
+
2065
+ // 检查是否超过指定天数
1943
2066
  if (orderCreatedAt < thresholdDate) {
1944
2067
  ordersToDelete.push({
1945
2068
  uuid: order.uuid,
1946
2069
  orderId: order.order_id,
1947
2070
  createdAt: orderCreatedAt.toISOString(),
1948
- daysSinceCreated: Math.floor(
1949
- (Date.now() - orderCreatedAt.getTime()) / (1e3 * 60 * 60 * 24)
1950
- )
2071
+ daysSinceCreated: Math.floor((Date.now() - orderCreatedAt.getTime()) / (1000 * 60 * 60 * 24))
1951
2072
  });
1952
2073
  }
1953
2074
  } catch (error) {
@@ -1955,17 +2076,16 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1955
2076
  continue;
1956
2077
  }
1957
2078
  }
1958
- ordersToDelete.sort(
1959
- (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
1960
- );
2079
+
2080
+ // 按创建时间排序(最老的先删除)并限制删除数量
2081
+ ordersToDelete.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1961
2082
  const actualOrdersToDelete = ordersToDelete.slice(0, maxOrdersToDelete);
2083
+
2084
+ // 删除符合条件的订单
1962
2085
  for (const orderInfo of actualOrdersToDelete) {
1963
2086
  try {
1964
2087
  await this.payment.deletePaymentOrderAsync(orderInfo.uuid);
1965
2088
  deletedCount++;
1966
- console.log(
1967
- `[Checkout] 已删除过期订单: ${orderInfo.orderId} (${orderInfo.daysSinceCreated} 天前创建)`
1968
- );
1969
2089
  } catch (error) {
1970
2090
  console.error(`[Checkout] 删除订单 ${orderInfo.uuid} 失败:`, error);
1971
2091
  }
@@ -1973,76 +2093,93 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
1973
2093
  const summary = {
1974
2094
  totalOrders: allOrders.length,
1975
2095
  expiredSyncedOrders: ordersToDelete.length,
1976
- maxOrdersToDelete,
2096
+ maxOrdersToDelete: maxOrdersToDelete,
1977
2097
  actualDeletedOrders: deletedCount,
1978
- retentionDays,
1979
- cleanupDate: (/* @__PURE__ */ new Date()).toISOString(),
2098
+ retentionDays: retentionDays,
2099
+ cleanupDate: new Date().toISOString(),
1980
2100
  thresholdDate: thresholdDate.toISOString(),
1981
2101
  skippedOrders: Math.max(0, ordersToDelete.length - maxOrdersToDelete)
1982
2102
  };
1983
- this.logInfo("Expired orders cleanup completed", summary);
1984
- if (ordersToDelete.length > maxOrdersToDelete) {
1985
- console.log(
1986
- `[Checkout] 过期订单清理完成: 总计 ${allOrders.length} 个订单,发现 ${ordersToDelete.length} 个过期已同步订单,删除了 ${deletedCount} 个(限制为 ${maxOrdersToDelete} 个)`
1987
- );
1988
- } else {
1989
- console.log(
1990
- `[Checkout] 过期订单清理完成: 总计 ${allOrders.length} 个订单,删除了 ${deletedCount} 个过期已同步订单`
1991
- );
1992
- }
2103
+
2104
+ // 记录清理结果
2105
+ this.logInfo('Expired orders cleanup completed', summary);
2106
+ if (ordersToDelete.length > maxOrdersToDelete) {} else {}
1993
2107
  } catch (error) {
1994
2108
  const errorMessage = error instanceof Error ? error.message : String(error);
1995
- console.error("[Checkout] 清理过期订单数据失败:", error);
1996
- this.logError("Expired orders cleanup failed", { error: errorMessage });
2109
+ console.error('[Checkout] 清理过期订单数据失败:', error);
2110
+ this.logError('Expired orders cleanup failed', {
2111
+ error: errorMessage
2112
+ });
1997
2113
  }
1998
2114
  }
2115
+
1999
2116
  /**
2000
2117
  * 清除计算缓存
2001
2118
  */
2002
2119
  clearCalculationCache() {
2003
2120
  this.calculationCache = {};
2004
2121
  }
2122
+
2005
2123
  /**
2006
2124
  * 批量获取订单数据(用于性能优化)
2007
2125
  * 一次性获取所有需要的数据,避免重复查询
2008
2126
  */
2009
2127
  async fetchOrderDataBatch() {
2010
2128
  if (!this.store.currentOrder) {
2011
- return { paymentItems: [], currentOrder: null };
2129
+ return {
2130
+ paymentItems: [],
2131
+ currentOrder: null
2132
+ };
2012
2133
  }
2013
2134
  const orderUuid = this.store.currentOrder.uuid;
2135
+
2136
+ // 检查缓存是否有效(5秒内的缓存认为有效)
2014
2137
  const now = Date.now();
2015
- const cacheValid = this.calculationCache.orderUuid === orderUuid && this.calculationCache.timestamp && now - this.calculationCache.timestamp < 5e3;
2138
+ const cacheValid = this.calculationCache.orderUuid === orderUuid && this.calculationCache.timestamp && now - this.calculationCache.timestamp < 5000;
2016
2139
  if (cacheValid && this.calculationCache.paymentItems && this.calculationCache.currentOrder) {
2140
+ // 使用缓存
2017
2141
  return {
2018
2142
  paymentItems: this.calculationCache.paymentItems,
2019
2143
  currentOrder: this.calculationCache.currentOrder
2020
2144
  };
2021
2145
  }
2022
- const [paymentItems, currentOrder] = await Promise.all([
2023
- this.payment.getPaymentItemsAsync(orderUuid, false),
2024
- this.payment.getPaymentOrderByUuidAsync(orderUuid)
2025
- ]);
2146
+
2147
+ // 并行获取数据,减少等待时间
2148
+ const [paymentItems, currentOrder] = await Promise.all([this.payment.getPaymentItemsAsync(orderUuid, false), this.payment.getPaymentOrderByUuidAsync(orderUuid)]);
2149
+
2150
+ // 更新缓存
2026
2151
  this.calculationCache = {
2027
2152
  paymentItems,
2028
2153
  currentOrder,
2029
2154
  orderUuid,
2030
2155
  timestamp: now
2031
2156
  };
2032
- return { paymentItems, currentOrder };
2157
+ return {
2158
+ paymentItems,
2159
+ currentOrder
2160
+ };
2033
2161
  }
2162
+
2034
2163
  /**
2035
2164
  * 从支付项数组计算已支付金额(纯计算,不查询数据库)
2036
2165
  */
2037
2166
  calculatePaidAmountFromItems(payments) {
2038
- const paidAmount = payments.filter((payment) => payment.status !== "voided").reduce((sum, payment) => {
2039
- const paymentAmount = new import_decimal.default(payment.amount || 0);
2040
- const roundingAmount = new import_decimal.default(payment.rounding_amount || 0);
2167
+ // 使用 Decimal.js 进行安全的金额计算
2168
+ const paidAmount = payments.filter(payment => payment.status !== 'voided') // 只计算未撤销的支付项
2169
+ .reduce((sum, payment) => {
2170
+ // const amount = new Decimal(payment.amount || '0');
2171
+ // 计算有效支付金额:支付金额 + 抹零金额的绝对值
2172
+ // 当 rounding_amount 为负数时,表示抹掉的金额,按绝对值计算有效支付
2173
+ // 例如:amount=15, rounding_amount=-0.2,有效支付=15.2(抹掉0.2元零头)
2174
+ // 例2:amount=15,rounding_amount=0.2,有效支付 14.8
2175
+ const paymentAmount = new _decimal.default(payment.amount || 0);
2176
+ const roundingAmount = new _decimal.default(payment.rounding_amount || 0);
2041
2177
  const effectiveAmount = paymentAmount.minus(roundingAmount);
2042
2178
  return sum.add(effectiveAmount);
2043
- }, new import_decimal.default(0));
2179
+ }, new _decimal.default(0));
2044
2180
  return paidAmount.toFixed(2);
2045
2181
  }
2182
+
2046
2183
  /**
2047
2184
  * 计算已支付金额(从 Payment 模块获取最新数据)
2048
2185
  *
@@ -2051,50 +2188,63 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2051
2188
  */
2052
2189
  async calculatePaidAmountAsync() {
2053
2190
  if (!this.store.currentOrder) {
2054
- this.logWarning("[Checkout] calculatePaidAmountAsync: 没有当前订单");
2055
- return "0.00";
2191
+ this.logWarning('[Checkout] calculatePaidAmountAsync: 没有当前订单');
2192
+ return '0.00';
2056
2193
  }
2057
2194
  try {
2195
+ // 检查是否有缓存的已支付金额
2058
2196
  const now = Date.now();
2059
- const cacheValid = this.calculationCache.orderUuid === this.store.currentOrder.uuid && this.calculationCache.timestamp && now - this.calculationCache.timestamp < 5e3 && this.calculationCache.paidAmount;
2197
+ const cacheValid = this.calculationCache.orderUuid === this.store.currentOrder.uuid && this.calculationCache.timestamp && now - this.calculationCache.timestamp < 5000 && this.calculationCache.paidAmount;
2060
2198
  if (cacheValid && this.calculationCache.paidAmount) {
2061
2199
  return this.calculationCache.paidAmount;
2062
2200
  }
2063
- const payments = await this.payment.getPaymentItemsAsync(
2064
- this.store.currentOrder.uuid,
2065
- false
2066
- // 不包括已撤销的支付项
2201
+
2202
+ // 从 Payment 模块获取最新的支付项数据
2203
+ const payments = await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid, false // 不包括已撤销的支付项
2067
2204
  );
2068
2205
  const result = this.calculatePaidAmountFromItems(payments);
2206
+
2207
+ // 更新缓存
2069
2208
  this.calculationCache.paidAmount = result;
2070
- this.logInfo("calculatePaidAmountAsync: 计算结果 =", result);
2209
+ this.logInfo('calculatePaidAmountAsync: 计算结果 =', result);
2071
2210
  return result;
2072
2211
  } catch (error) {
2073
- this.logError("calculatePaidAmountAsync 失败:", error);
2074
- return "0.00";
2212
+ this.logError('calculatePaidAmountAsync 失败:', error);
2213
+ return '0.00';
2075
2214
  }
2076
2215
  }
2216
+
2077
2217
  /**
2078
2218
  * 从订单和支付项计算剩余金额(纯计算,不查询数据库)
2079
2219
  */
2080
2220
  calculateRemainingAmountFromData(currentOrder, paidAmount) {
2081
- let totalAmount = new import_decimal.default(currentOrder.total_amount || "0");
2221
+ // 使用 Decimal.js 进行安全的金额计算
2222
+ let totalAmount = new _decimal.default(currentOrder.total_amount || '0');
2223
+
2224
+ // 如果是定金订单,使用定金金额
2082
2225
  if (currentOrder.is_deposit && currentOrder.deposit_amount && Number(currentOrder.deposit_amount) > 0) {
2083
- totalAmount = new import_decimal.default(currentOrder.deposit_amount);
2226
+ totalAmount = new _decimal.default(currentOrder.deposit_amount);
2084
2227
  }
2085
- const paid = new import_decimal.default(paidAmount);
2228
+ const paid = new _decimal.default(paidAmount);
2086
2229
  const remainingAmount = totalAmount.sub(paid);
2087
- return import_decimal.default.max(0, remainingAmount).toFixed(2);
2230
+
2231
+ // 确保剩余金额不为负数
2232
+ return _decimal.default.max(0, remainingAmount).toFixed(2);
2088
2233
  }
2234
+
2089
2235
  /**
2090
2236
  * 从订单和支付项计算剩余总金额(纯计算,排除定金)
2091
2237
  */
2092
2238
  calculateRemainingTotalAmountFromData(currentOrder, paidAmount) {
2093
- const totalAmount = new import_decimal.default(currentOrder.total_amount || "0");
2094
- const paid = new import_decimal.default(paidAmount);
2239
+ // 始终使用订单总金额,不进行定金相关的计算
2240
+ const totalAmount = new _decimal.default(currentOrder.total_amount || '0');
2241
+ const paid = new _decimal.default(paidAmount);
2095
2242
  const remainingAmount = totalAmount.sub(paid);
2096
- return import_decimal.default.max(0, remainingAmount).toFixed(2);
2243
+
2244
+ // 确保剩余金额不为负数
2245
+ return _decimal.default.max(0, remainingAmount).toFixed(2);
2097
2246
  }
2247
+
2098
2248
  /**
2099
2249
  * 计算剩余未支付金额(从 Payment 模块获取最新数据)
2100
2250
  *
@@ -2103,18 +2253,23 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2103
2253
  */
2104
2254
  async calculateRemainingAmountAsync() {
2105
2255
  if (!this.store.currentOrder) {
2106
- this.logWarning("calculateRemainingAmountAsync: 没有当前订单");
2107
- return "0.00";
2256
+ this.logWarning('calculateRemainingAmountAsync: 没有当前订单');
2257
+ return '0.00';
2108
2258
  }
2109
- const { currentOrder } = await this.fetchOrderDataBatch();
2259
+
2260
+ // 尝试使用批量获取的数据
2261
+ const {
2262
+ currentOrder
2263
+ } = await this.fetchOrderDataBatch();
2110
2264
  if (!currentOrder) {
2111
- return "0.00";
2265
+ return '0.00';
2112
2266
  }
2113
2267
  const paidAmountStr = await this.calculatePaidAmountAsync();
2114
2268
  const result = this.calculateRemainingAmountFromData(currentOrder, paidAmountStr);
2115
- this.logInfo("calculateRemainingAmountAsync: 计算=", result);
2269
+ this.logInfo('calculateRemainingAmountAsync: 计算=', result);
2116
2270
  return result;
2117
2271
  }
2272
+
2118
2273
  /**
2119
2274
  * 计算剩余未支付金额(排除定金计算,始终使用订单总金额)
2120
2275
  *
@@ -2123,18 +2278,23 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2123
2278
  */
2124
2279
  async calculateRemainingTotalAmountAsync() {
2125
2280
  if (!this.store.currentOrder) {
2126
- this.logWarning("calculateRemainingTotalAmountAsync: 没有当前订单");
2127
- return "0.00";
2281
+ this.logWarning('calculateRemainingTotalAmountAsync: 没有当前订单');
2282
+ return '0.00';
2128
2283
  }
2129
- const { currentOrder } = await this.fetchOrderDataBatch();
2284
+
2285
+ // 尝试使用批量获取的数据
2286
+ const {
2287
+ currentOrder
2288
+ } = await this.fetchOrderDataBatch();
2130
2289
  if (!currentOrder) {
2131
- return "0.00";
2290
+ return '0.00';
2132
2291
  }
2133
2292
  const paidAmountStr = await this.calculatePaidAmountAsync();
2134
2293
  const result = this.calculateRemainingTotalAmountFromData(currentOrder, paidAmountStr);
2135
- this.logInfo("calculateRemainingTotalAmountAsync: 计算=", result);
2294
+ this.logInfo('calculateRemainingTotalAmountAsync: 计算=', result);
2136
2295
  return result;
2137
2296
  }
2297
+
2138
2298
  /**
2139
2299
  * 更新 balanceDueAmount 为当前剩余未支付金额(系统内部计算)
2140
2300
  */
@@ -2143,28 +2303,33 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2143
2303
  const remainingAmount = await this.calculateRemainingAmountAsync();
2144
2304
  const remainingTotalAmount = await this.calculateRemainingTotalAmountAsync();
2145
2305
  const currentBalanceDueAmount = this.store.balanceDueAmount;
2306
+
2307
+ // 只有当剩余金额与当前 balanceDueAmount 不同时才更新
2146
2308
  if (remainingAmount !== currentBalanceDueAmount) {
2147
2309
  this.store.balanceDueAmount = remainingAmount;
2310
+
2311
+ // 发出 balanceDueAmount 变更事件
2148
2312
  await this.core.effects.emit(`${this.name}:onBalanceDueAmountChanged`, {
2149
2313
  oldAmount: currentBalanceDueAmount,
2150
2314
  newAmount: remainingAmount,
2151
2315
  timestamp: Date.now(),
2152
2316
  totalAmount: remainingTotalAmount
2153
2317
  });
2154
- this.logInfo("balanceDueAmount 已自动更新:", {
2318
+ this.logInfo('balanceDueAmount 已自动更新:', {
2155
2319
  oldAmount: currentBalanceDueAmount,
2156
2320
  newAmount: remainingAmount
2157
2321
  });
2158
2322
  } else {
2159
- this.logInfo("balanceDueAmount 无需更新,当前值已是最新:", {
2323
+ this.logInfo('balanceDueAmount 无需更新,当前值已是最新:', {
2160
2324
  balanceDueAmount: currentBalanceDueAmount,
2161
- remainingAmount
2325
+ remainingAmount: remainingAmount
2162
2326
  });
2163
2327
  }
2164
2328
  } catch (error) {
2165
- this.logError("更新 balanceDueAmount 失败:", error);
2329
+ this.logError('更新 balanceDueAmount 失败:', error);
2166
2330
  }
2167
2331
  }
2332
+
2168
2333
  /**
2169
2334
  * 更新 stateAmount 为当前剩余未支付金额
2170
2335
  *
@@ -2175,37 +2340,51 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2175
2340
  if (!this.store.currentOrder) {
2176
2341
  return;
2177
2342
  }
2178
- console.time("updateStateAmountToRemaining");
2179
- const { paymentItems, currentOrder } = await this.fetchOrderDataBatch();
2180
- console.timeEnd("updateStateAmountToRemaining");
2343
+ // 🚀 性能优化:一次性批量获取所有需要的数据
2344
+ const {
2345
+ paymentItems,
2346
+ currentOrder
2347
+ } = await this.fetchOrderDataBatch();
2181
2348
  if (!currentOrder) {
2182
- this.logWarning("updateStateAmountToRemaining: 未找到当前订单");
2349
+ this.logWarning('updateStateAmountToRemaining: 未找到当前订单');
2183
2350
  return;
2184
2351
  }
2352
+ // 🚀 性能优化:一次性计算所有金额(纯计算,不查询数据库)
2185
2353
  const paidAmount = this.calculatePaidAmountFromItems(paymentItems);
2354
+
2355
+ // 缓存已支付金额,供其他方法使用
2186
2356
  this.calculationCache.paidAmount = paidAmount;
2357
+
2358
+ // 检查定金支付状态,可能需要切换支付模式
2187
2359
  let needUpdateDepositStatus = false;
2188
2360
  if (currentOrder.is_deposit === 1) {
2189
- const depositPaidAmount = paymentItems.filter(
2190
- (item) => item.order_payment_type === "deposit" && item.status !== "voided"
2191
- ).reduce((sum, item) => {
2192
- if (item.voucher_id && !item.isSynced && paymentItems.filter((item2) => !item2.voucher_id).length === 0) {
2361
+ const depositPaidAmount = paymentItems.filter(item => item.order_payment_type === 'deposit' && item.status !== 'voided').reduce((sum, item) => {
2362
+ // 如果是 wallet,并且还没同步到后端,且此时还没有其他类型的支付项(现金,eftpos,标记支付),不计入已付金额
2363
+ // 如果有其他支付项了,代表此时处于马上要同步的状态,所以计入
2364
+ if (item.voucher_id && !item.isSynced && paymentItems.filter(item => !item.voucher_id).length === 0) {
2193
2365
  return sum;
2194
2366
  }
2195
- const amount = new import_decimal.default(item.amount || "0");
2196
- const roundingAmount = new import_decimal.default(item.rounding_amount || "0");
2367
+ const amount = new _decimal.default(item.amount || '0');
2368
+ const roundingAmount = new _decimal.default(item.rounding_amount || '0');
2197
2369
  return sum.add(amount.add(roundingAmount.isNegative() ? roundingAmount.abs() : 0));
2198
- }, new import_decimal.default(0));
2199
- if (depositPaidAmount.gte(currentOrder.deposit_amount || "0")) {
2370
+ }, new _decimal.default(0));
2371
+ if (depositPaidAmount.gte(currentOrder.deposit_amount || '0')) {
2200
2372
  needUpdateDepositStatus = true;
2373
+ // 更新缓存中的订单状态
2201
2374
  currentOrder.is_deposit = 0;
2202
2375
  }
2203
2376
  }
2377
+
2378
+ // 计算剩余金额(使用缓存的数据)
2204
2379
  const remainingAmount = this.calculateRemainingAmountFromData(currentOrder, paidAmount);
2205
2380
  const remainingTotalAmount = this.calculateRemainingTotalAmountFromData(currentOrder, paidAmount);
2206
2381
  const currentStateAmount = this.store.stateAmount;
2207
2382
  const currentBalanceDueAmount = this.store.balanceDueAmount;
2383
+
2384
+ // 批量更新状态,减少操作次数
2208
2385
  let hasStateChanged = false;
2386
+
2387
+ // 如果需要更新定金状态
2209
2388
  if (needUpdateDepositStatus) {
2210
2389
  this.store.currentOrder = {
2211
2390
  ...this.store.currentOrder,
@@ -2216,11 +2395,12 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2216
2395
  });
2217
2396
  hasStateChanged = true;
2218
2397
  }
2219
- console.time("updateStateAmountToRemaining: remainingAmount");
2398
+ // 更新 stateAmount
2220
2399
  if (remainingAmount !== currentStateAmount) {
2221
2400
  this.store.stateAmount = remainingAmount;
2222
2401
  hasStateChanged = true;
2223
2402
  setTimeout(() => {
2403
+ // 发出 stateAmount 变更事件
2224
2404
  this.core.effects.emit(`${this.name}:onStateAmountChanged`, {
2225
2405
  oldAmount: currentStateAmount,
2226
2406
  newAmount: remainingAmount,
@@ -2228,16 +2408,17 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2228
2408
  totalAmount: remainingTotalAmount
2229
2409
  });
2230
2410
  }, 0);
2231
- this.logInfo("stateAmount 已自动更新为剩余金额:", {
2411
+ this.logInfo('stateAmount 已自动更新为剩余金额:', {
2232
2412
  oldAmount: currentStateAmount,
2233
2413
  newAmount: remainingAmount
2234
2414
  });
2235
2415
  }
2236
- console.timeEnd("updateStateAmountToRemaining: remainingAmount");
2237
- console.time("updateStateAmountToRemaining: updateStateAmountToRemaining");
2416
+ // 更新 balanceDueAmount
2238
2417
  if (remainingAmount !== currentBalanceDueAmount) {
2239
2418
  this.store.balanceDueAmount = remainingAmount;
2240
2419
  hasStateChanged = true;
2420
+
2421
+ // 发出 balanceDueAmount 变更事件
2241
2422
  setTimeout(() => {
2242
2423
  this.core.effects.emit(`${this.name}:onBalanceDueAmountChanged`, {
2243
2424
  oldAmount: currentBalanceDueAmount,
@@ -2246,27 +2427,29 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2246
2427
  totalAmount: remainingTotalAmount
2247
2428
  });
2248
2429
  }, 0);
2249
- this.logInfo("balanceDueAmount 已自动更新:", {
2430
+ this.logInfo('balanceDueAmount 已自动更新:', {
2250
2431
  oldAmount: currentBalanceDueAmount,
2251
2432
  newAmount: remainingAmount
2252
2433
  });
2253
2434
  }
2254
- console.timeEnd("updateStateAmountToRemaining: updateStateAmountToRemaining");
2255
2435
  if (!hasStateChanged) {
2256
- this.logInfo("状态无需更新,当前值已是最新:", {
2436
+ this.logInfo('状态无需更新,当前值已是最新:', {
2257
2437
  stateAmount: currentStateAmount,
2258
- remainingAmount
2438
+ remainingAmount: remainingAmount
2259
2439
  });
2260
2440
  }
2441
+
2442
+ // 检查订单支付完成(复用已获取的数据)
2261
2443
  if (checkOrder) {
2262
2444
  await this.checkOrderPaymentCompletionOptimized(paymentItems, remainingAmount);
2263
2445
  } else {
2264
- this.logInfo("外部传入无需 checkOrder,不执行订单支付完成检测和同步");
2446
+ this.logInfo('外部传入无需 checkOrder,不执行订单支付完成检测和同步');
2265
2447
  }
2266
2448
  } catch (error) {
2267
- this.logError("更新 stateAmount 为剩余金额失败:", error);
2449
+ this.logError('更新 stateAmount 为剩余金额失败:', error);
2268
2450
  }
2269
2451
  }
2452
+
2270
2453
  /**
2271
2454
  * 检查订单支付是否完成(优化版,复用已获取的数据)
2272
2455
  *
@@ -2278,11 +2461,13 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2278
2461
  if (!this.store.currentOrder) {
2279
2462
  return;
2280
2463
  }
2281
- const remainingValue = new import_decimal.default(remainingAmount);
2464
+ const remainingValue = new _decimal.default(remainingAmount);
2465
+
2466
+ // 当剩余金额小于等于0时,认为订单已完成支付
2282
2467
  if (remainingValue.lte(0)) {
2283
2468
  const totalAmount = this.store.currentOrder.total_amount;
2284
- const paidAmount = this.calculationCache.paidAmount || "0.00";
2285
- this.logInfo("检测到订单支付完成:", {
2469
+ const paidAmount = this.calculationCache.paidAmount || '0.00';
2470
+ this.logInfo('检测到订单支付完成:', {
2286
2471
  orderUuid: this.store.currentOrder.uuid,
2287
2472
  orderId: this.store.currentOrder.order_id,
2288
2473
  totalAmount,
@@ -2290,38 +2475,40 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2290
2475
  remainingAmount,
2291
2476
  isOrderSynced: this.store.isOrderSynced
2292
2477
  });
2478
+
2479
+ // 检查自动同步条件(复用已获取的支付项数据)
2293
2480
  const hasPaymentItems = paymentItems.length > 0;
2294
- const allPaymentsHaveVoucherId = hasPaymentItems && paymentItems.every(
2295
- (item) => item.status !== "voided" && item.voucher_id
2296
- );
2481
+ const allPaymentsHaveVoucherId = hasPaymentItems && paymentItems.every(item => item.status !== 'voided' && item.voucher_id);
2297
2482
  const shouldAutoSync = hasPaymentItems && !allPaymentsHaveVoucherId;
2298
- this.logInfo("自动同步订单条件检查:", {
2483
+ this.logInfo('自动同步订单条件检查:', {
2299
2484
  paymentCount: paymentItems.length,
2300
2485
  hasPaymentItems,
2301
2486
  allHaveVoucherId: allPaymentsHaveVoucherId,
2302
2487
  isOrderSynced: this.store.isOrderSynced,
2303
2488
  shouldAutoSync,
2304
- reason: shouldAutoSync ? "支付完成,需要同步最终支付状态" : "跳过同步",
2305
- paymentItems: paymentItems.map((p) => ({
2489
+ reason: shouldAutoSync ? '支付完成,需要同步最终支付状态' : '跳过同步',
2490
+ paymentItems: paymentItems.map(p => ({
2306
2491
  uuid: p.uuid,
2307
2492
  code: p.code,
2308
2493
  amount: p.amount,
2309
2494
  rounding_amount: p.rounding_amount,
2310
- effective_amount: (parseFloat(p.amount || "0") + Math.abs(parseFloat(Number(p.rounding_amount) > 0 ? "0" : p.rounding_amount || "0"))).toFixed(2),
2495
+ effective_amount: (parseFloat(p.amount || '0') + Math.abs(parseFloat(Number(p.rounding_amount) > 0 ? '0' : p.rounding_amount || '0'))).toFixed(2),
2311
2496
  voucher_id: p.voucher_id,
2312
2497
  status: p.status
2313
2498
  }))
2314
2499
  });
2315
2500
  if (shouldAutoSync) {
2316
- this.logInfo("满足自动同步条件,开始同步订单到后端...");
2501
+ this.logInfo('满足自动同步条件,开始同步订单到后端...');
2317
2502
  await this.syncOrderToBackendWithReturn(false);
2318
2503
  } else {
2319
2504
  if (!hasPaymentItems) {
2320
- this.logInfo("没有支付项,跳过订单同步");
2505
+ this.logInfo('没有支付项,跳过订单同步');
2321
2506
  } else if (allPaymentsHaveVoucherId) {
2322
- this.logInfo("所有支付项均为代金券类型,跳过订单同步");
2507
+ this.logInfo('所有支付项均为代金券类型,跳过订单同步');
2323
2508
  }
2324
2509
  }
2510
+
2511
+ // 触发订单支付完成事件
2325
2512
  await this.core.effects.emit(`${this.name}:onOrderPaymentCompleted`, {
2326
2513
  orderUuid: this.store.currentOrder.uuid,
2327
2514
  orderId: this.store.currentOrder.order_id,
@@ -2332,9 +2519,10 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2332
2519
  });
2333
2520
  }
2334
2521
  } catch (error) {
2335
- this.logError("检查订单支付完成状态失败:", error);
2522
+ this.logError('检查订单支付完成状态失败:', error);
2336
2523
  }
2337
2524
  }
2525
+
2338
2526
  /**
2339
2527
  * 检查订单支付是否完成
2340
2528
  *
@@ -2349,11 +2537,13 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2349
2537
  return;
2350
2538
  }
2351
2539
  const remainingAmount = await this.calculateRemainingAmountAsync();
2352
- const remainingValue = new import_decimal.default(remainingAmount);
2540
+ const remainingValue = new _decimal.default(remainingAmount);
2541
+
2542
+ // 当剩余金额小于等于0时,认为订单已完成支付
2353
2543
  if (remainingValue.lte(0)) {
2354
2544
  const totalAmount = this.store.currentOrder.total_amount;
2355
2545
  const paidAmount = await this.calculatePaidAmountAsync();
2356
- this.logInfo("检测到订单支付完成:", {
2546
+ this.logInfo('检测到订单支付完成:', {
2357
2547
  orderUuid: this.store.currentOrder.uuid,
2358
2548
  orderId: this.store.currentOrder.order_id,
2359
2549
  totalAmount,
@@ -2361,43 +2551,53 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2361
2551
  remainingAmount,
2362
2552
  isOrderSynced: this.store.isOrderSynced
2363
2553
  });
2364
- const currentPayments = await this.payment.getPaymentItemsAsync(
2365
- this.store.currentOrder.uuid,
2366
- false
2367
- // 不包括已撤销的支付项
2554
+
2555
+ // 从 Payment 模块获取最新支付项,检查自动同步条件
2556
+ const currentPayments = await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid, false // 不包括已撤销的支付项
2368
2557
  );
2558
+
2559
+ // 检查自动同步条件:
2560
+ // 1. 待付金额为 0 ✓ (已在上面检查)
2561
+ // 2. 需要有支付项
2562
+ // 3. 支付项不能全是带 voucher_id 的数据
2369
2563
  const hasPaymentItems = currentPayments.length > 0;
2370
- const allPaymentsHaveVoucherId = hasPaymentItems && currentPayments.every(
2371
- (item) => item.status !== "voided" && item.voucher_id
2372
- );
2564
+ const allPaymentsHaveVoucherId = hasPaymentItems && currentPayments.every(item => item.status !== 'voided' && item.voucher_id);
2565
+
2566
+ // 判断是否需要自动同步订单
2567
+ // 条件:
2568
+ // 1. 有支付项
2569
+ // 2. 不全是代金券支付
2570
+ // 3. 订单未同步 OR (订单已同步但支付刚完成,需要同步最终支付状态)
2373
2571
  const shouldAutoSync = hasPaymentItems && !allPaymentsHaveVoucherId;
2374
- this.logInfo("自动同步订单条件检查:", {
2572
+ this.logInfo('自动同步订单条件检查:', {
2375
2573
  paymentCount: currentPayments.length,
2376
2574
  hasPaymentItems,
2377
2575
  allHaveVoucherId: allPaymentsHaveVoucherId,
2378
2576
  isOrderSynced: this.store.isOrderSynced,
2379
2577
  shouldAutoSync,
2380
- reason: shouldAutoSync ? "支付完成,需要同步最终支付状态" : "跳过同步",
2381
- paymentItems: currentPayments.map((p) => ({
2578
+ reason: shouldAutoSync ? '支付完成,需要同步最终支付状态' : '跳过同步',
2579
+ paymentItems: currentPayments.map(p => ({
2382
2580
  uuid: p.uuid,
2383
2581
  code: p.code,
2384
2582
  amount: p.amount,
2385
2583
  rounding_amount: p.rounding_amount,
2386
- effective_amount: (parseFloat(p.amount || "0") + Math.abs(parseFloat(Number(p.rounding_amount) > 0 ? "0" : p.rounding_amount || "0"))).toFixed(2),
2584
+ effective_amount: (parseFloat(p.amount || '0') + Math.abs(parseFloat(Number(p.rounding_amount) > 0 ? '0' : p.rounding_amount || '0'))).toFixed(2),
2387
2585
  voucher_id: p.voucher_id,
2388
2586
  status: p.status
2389
2587
  }))
2390
2588
  });
2391
2589
  if (shouldAutoSync) {
2392
- this.logInfo("满足自动同步条件,开始同步订单到后端...");
2590
+ this.logInfo('满足自动同步条件,开始同步订单到后端...');
2393
2591
  await this.syncOrderToBackendWithReturn(false);
2394
2592
  } else {
2395
2593
  if (!hasPaymentItems) {
2396
- this.logInfo("没有支付项,跳过订单同步");
2594
+ this.logInfo('没有支付项,跳过订单同步');
2397
2595
  } else if (allPaymentsHaveVoucherId) {
2398
- this.logInfo("所有支付项均为代金券类型,跳过订单同步");
2596
+ this.logInfo('所有支付项均为代金券类型,跳过订单同步');
2399
2597
  }
2400
2598
  }
2599
+
2600
+ // 触发订单支付完成事件
2401
2601
  await this.core.effects.emit(`${this.name}:onOrderPaymentCompleted`, {
2402
2602
  orderUuid: this.store.currentOrder.uuid,
2403
2603
  orderId: this.store.currentOrder.order_id,
@@ -2408,20 +2608,23 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2408
2608
  });
2409
2609
  }
2410
2610
  } catch (error) {
2411
- this.logError("检查订单支付完成状态失败:", error);
2611
+ this.logError('检查订单支付完成状态失败:', error);
2412
2612
  }
2413
2613
  }
2414
2614
  async repairEftposPaymentFromIndexDbAsync(params) {
2415
- const { orderUuid, paymentItem } = params;
2615
+ const {
2616
+ orderUuid,
2617
+ paymentItem
2618
+ } = params;
2416
2619
  const order = await this.payment.getPaymentOrderByUuidAsync(orderUuid);
2417
2620
  if (!order) {
2418
- this.logError("EFTPOS repair failed: order not found in IndexDB", {
2621
+ this.logError('EFTPOS repair failed: order not found in IndexDB', {
2419
2622
  orderUuid,
2420
2623
  paymentItem
2421
2624
  });
2422
2625
  return;
2423
2626
  }
2424
- const orderPaymentType = order.is_deposit === 1 ? "deposit" : "normal";
2627
+ const orderPaymentType = order.is_deposit === 1 ? 'deposit' : 'normal';
2425
2628
  const processedPaymentItem = await this.processCashPaymentItem(paymentItem);
2426
2629
  const metadata = {
2427
2630
  ...processedPaymentItem.metadata,
@@ -2434,81 +2637,79 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2434
2637
  metadata
2435
2638
  };
2436
2639
  await this.payment.addPaymentItemAsync(orderUuid, paymentItemWithType);
2437
- await this.syncOrderToBackendFromIndexDbAsync({ orderUuid });
2640
+ await this.syncOrderToBackendFromIndexDbAsync({
2641
+ orderUuid
2642
+ });
2438
2643
  }
2439
2644
  async syncOrderToBackendFromIndexDbAsync(params) {
2440
- var _a, _b, _c, _d, _e, _f, _g, _h;
2441
- const { orderUuid } = params;
2645
+ const {
2646
+ orderUuid
2647
+ } = params;
2442
2648
  const paymentOrder = await this.payment.getPaymentOrderByUuidAsync(orderUuid);
2443
2649
  if (!paymentOrder) {
2444
- this.logError("EFTPOS repair sync failed: missing payment order", {
2650
+ this.logError('EFTPOS repair sync failed: missing payment order', {
2445
2651
  orderUuid
2446
2652
  });
2447
- return { success: false };
2653
+ return {
2654
+ success: false
2655
+ };
2448
2656
  }
2449
- const localOrderData = ((_a = paymentOrder.order_info) == null ? void 0 : _a.original_order_data) || ((_b = paymentOrder.order_info) == null ? void 0 : _b.order_data);
2657
+ const localOrderData = paymentOrder.order_info?.original_order_data || paymentOrder.order_info?.order_data;
2450
2658
  if (!localOrderData) {
2451
- this.logError("EFTPOS repair sync failed: missing local order data", {
2659
+ this.logError('EFTPOS repair sync failed: missing local order data', {
2452
2660
  orderUuid,
2453
2661
  orderInfoKeys: Object.keys(paymentOrder.order_info || {})
2454
2662
  });
2455
- return { success: false };
2456
- }
2457
- const paymentItems = await this.payment.getPaymentItemsAsync(orderUuid);
2458
- const processedPaymentItems = paymentItems.map((item) => {
2459
- var _a2, _b2;
2460
2663
  return {
2461
- ...item,
2462
- metadata: {
2463
- ...item.metadata,
2464
- rounding_rule: ((_a2 = item.metadata) == null ? void 0 : _a2.rounding_rule) || this.otherParams.order_rounding_setting,
2465
- shop_wallet_pass_id: ((_b2 = item.metadata) == null ? void 0 : _b2.shop_wallet_pass_id) || this.otherParams.shop_wallet_pass_id
2466
- }
2664
+ success: false
2467
2665
  };
2468
- });
2666
+ }
2667
+ const paymentItems = await this.payment.getPaymentItemsAsync(orderUuid);
2668
+ const processedPaymentItems = paymentItems.map(item => ({
2669
+ ...item,
2670
+ metadata: {
2671
+ ...item.metadata,
2672
+ rounding_rule: item.metadata?.rounding_rule || this.otherParams.order_rounding_setting,
2673
+ shop_wallet_pass_id: item.metadata?.shop_wallet_pass_id || this.otherParams.shop_wallet_pass_id
2674
+ }
2675
+ }));
2469
2676
  let finalDepositAmount;
2470
- const manualDepositAmount = paymentOrder.deposit_amount || "0.00";
2471
- const manualDepositValue = new import_decimal.default(manualDepositAmount);
2677
+ const manualDepositAmount = paymentOrder.deposit_amount || '0.00';
2678
+ const manualDepositValue = new _decimal.default(manualDepositAmount);
2472
2679
  if (manualDepositValue.gt(0)) {
2473
2680
  finalDepositAmount = manualDepositAmount;
2474
2681
  } else {
2475
- finalDepositAmount = "0.00";
2682
+ finalDepositAmount = '0.00';
2476
2683
  }
2477
- if (paymentOrder.is_deposit === 0 && processedPaymentItems.every((item) => item.order_payment_type !== "deposit")) {
2478
- finalDepositAmount = "0.00";
2684
+ if (paymentOrder.is_deposit === 0 && processedPaymentItems.every(item => item.order_payment_type !== 'deposit')) {
2685
+ finalDepositAmount = '0.00';
2479
2686
  }
2480
- if (paymentOrder.is_deposit === 0 && processedPaymentItems.some((item) => item.order_payment_type === "deposit")) {
2481
- finalDepositAmount = processedPaymentItems.filter(
2482
- (item) => item.status !== "voided" && item.order_payment_type === "deposit"
2483
- ).reduce((sum, item) => {
2484
- const amountValue = new import_decimal.default(item.amount || "0");
2485
- const roundingValue = new import_decimal.default(item.rounding_amount || "0");
2687
+ if (paymentOrder.is_deposit === 0 && processedPaymentItems.some(item => item.order_payment_type === 'deposit')) {
2688
+ finalDepositAmount = processedPaymentItems.filter(item => item.status !== 'voided' && item.order_payment_type === 'deposit').reduce((sum, item) => {
2689
+ const amountValue = new _decimal.default(item.amount || '0');
2690
+ const roundingValue = new _decimal.default(item.rounding_amount || '0');
2486
2691
  return sum.plus(amountValue).sub(roundingValue);
2487
- }, new import_decimal.default(0)).toFixed(2);
2488
- }
2489
- if (paymentOrder.is_deposit === 1 && new import_decimal.default(finalDepositAmount).gte(
2490
- new import_decimal.default(paymentOrder.total_amount)
2491
- )) {
2492
- finalDepositAmount = processedPaymentItems.filter(
2493
- (item) => item.status !== "voided" && item.order_payment_type === "deposit"
2494
- ).reduce((sum, item) => {
2495
- const amountValue = new import_decimal.default(item.amount || "0");
2496
- const roundingValue = new import_decimal.default(item.rounding_amount || "0");
2692
+ }, new _decimal.default(0)).toFixed(2);
2693
+ }
2694
+ if (paymentOrder.is_deposit === 1 && new _decimal.default(finalDepositAmount).gte(new _decimal.default(paymentOrder.total_amount))) {
2695
+ finalDepositAmount = processedPaymentItems.filter(item => item.status !== 'voided' && item.order_payment_type === 'deposit').reduce((sum, item) => {
2696
+ const amountValue = new _decimal.default(item.amount || '0');
2697
+ const roundingValue = new _decimal.default(item.rounding_amount || '0');
2497
2698
  return sum.plus(amountValue).sub(roundingValue);
2498
- }, new import_decimal.default(0)).toFixed(2);
2699
+ }, new _decimal.default(0)).toFixed(2);
2499
2700
  }
2500
2701
  let orderPaymentStatus;
2501
- const totalPaidAmount = processedPaymentItems.filter((item) => item.status !== "voided").reduce((sum, item) => {
2502
- const amountValue = new import_decimal.default(item.amount || "0");
2503
- const roundingValue = new import_decimal.default(item.rounding_amount || "0");
2702
+ const totalPaidAmount = processedPaymentItems.filter(item => item.status !== 'voided').reduce((sum, item) => {
2703
+ const amountValue = new _decimal.default(item.amount || '0');
2704
+ const roundingValue = new _decimal.default(item.rounding_amount || '0');
2504
2705
  return sum.plus(amountValue).sub(roundingValue);
2505
- }, new import_decimal.default(0));
2506
- if (totalPaidAmount.gte(new import_decimal.default(paymentOrder.total_amount))) {
2507
- orderPaymentStatus = "paid";
2706
+ }, new _decimal.default(0));
2707
+ if (totalPaidAmount.gte(new _decimal.default(paymentOrder.total_amount))) {
2708
+ orderPaymentStatus = 'paid';
2508
2709
  } else if (totalPaidAmount.gt(0)) {
2509
- orderPaymentStatus = "partially_paid";
2710
+ orderPaymentStatus = 'partially_paid';
2510
2711
  } else {
2511
- orderPaymentStatus = "unpaid";
2712
+ orderPaymentStatus = 'unpaid';
2512
2713
  }
2513
2714
  const orderParams = {
2514
2715
  ...localOrderData,
@@ -2524,44 +2725,46 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2524
2725
  currency_code: this.otherParams.currency_code,
2525
2726
  currency_symbol: this.otherParams.currency_symbol,
2526
2727
  currency_format: this.otherParams.currency_format,
2527
- business_code: ((_c = this.otherParams) == null ? void 0 : _c.business_code) || void 0,
2728
+ business_code: this.otherParams?.business_code || undefined,
2528
2729
  is_deposit: (paymentOrder.is_deposit || Number(finalDepositAmount) > 0 ? 1 : 0) || 0,
2529
2730
  deposit_amount: finalDepositAmount,
2530
2731
  product_tax_fee: localOrderData.tax_fee,
2531
2732
  note: localOrderData.shop_note,
2532
- bookings: (_d = localOrderData.bookings) == null ? void 0 : _d.map((item) => {
2733
+ bookings: localOrderData.bookings?.map(item => {
2533
2734
  return {
2534
2735
  ...item,
2535
2736
  product: {
2536
2737
  ...item.product,
2537
- custom_deposit_data: void 0
2738
+ custom_deposit_data: undefined
2538
2739
  },
2539
- deposit: void 0
2740
+ deposit: undefined
2540
2741
  };
2541
2742
  }),
2542
- relation_products: (_e = localOrderData.relation_products) == null ? void 0 : _e.map((item) => {
2743
+ relation_products: localOrderData.relation_products?.map(item => {
2543
2744
  return {
2544
2745
  ...item,
2545
- custom_deposit_data: void 0,
2546
- deposit: void 0
2746
+ custom_deposit_data: undefined,
2747
+ deposit: undefined
2547
2748
  };
2548
2749
  })
2549
2750
  };
2550
2751
  const currentOrderId = paymentOrder.order_id;
2551
- const isUpdateOperation = currentOrderId && !(0, import_utils.isVirtualOrderId)(currentOrderId);
2752
+ const isUpdateOperation = currentOrderId && !(0, _utils.isVirtualOrderId)(currentOrderId);
2552
2753
  if (isUpdateOperation) {
2553
2754
  orderParams.order_id = currentOrderId;
2554
2755
  }
2555
- this.logError("EFTPOS repair sync start", {
2756
+ this.logError('EFTPOS repair sync start', {
2556
2757
  orderUuid,
2557
2758
  orderId: currentOrderId,
2558
2759
  isUpdateOperation,
2559
2760
  paymentItemCount: processedPaymentItems.length
2560
2761
  });
2762
+
2763
+ // 发送下单接口请求开始事件
2561
2764
  const startTime = Date.now();
2562
2765
  await this.core.effects.emit(`${this.name}:onOrderSubmitStart`, {
2563
- orderUuid,
2564
- operation: isUpdateOperation ? "update" : "create",
2766
+ orderUuid: orderUuid,
2767
+ operation: isUpdateOperation ? 'update' : 'create',
2565
2768
  isManual: false,
2566
2769
  paymentItemCount: processedPaymentItems.length,
2567
2770
  timestamp: startTime
@@ -2570,80 +2773,85 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2570
2773
  let submitSuccess = false;
2571
2774
  let submitError;
2572
2775
  try {
2573
- this.logError("EFTPOS repair calling backend checkout API", {
2574
- url: "/order/checkout",
2776
+ this.logError('EFTPOS repair calling backend checkout API', {
2777
+ url: '/order/checkout',
2575
2778
  isManual: true,
2576
2779
  ...orderParams
2577
2780
  });
2578
2781
  checkoutResponse = await this.order.createOrderByCheckout(orderParams);
2579
2782
  submitSuccess = true;
2580
2783
  } catch (error) {
2581
- this.logError("EFTPOS repair checkout API failed", {
2784
+ this.logError('EFTPOS repair checkout API failed', {
2582
2785
  orderUuid,
2583
2786
  error: error instanceof Error ? error.message : String(error)
2584
2787
  });
2585
2788
  submitError = error instanceof Error ? error.message : String(error);
2586
2789
  throw error;
2587
2790
  } finally {
2588
- this.logError("EFTPOS repair sync end", {
2791
+ this.logError('EFTPOS repair sync end', {
2589
2792
  orderUuid,
2590
2793
  orderId: currentOrderId,
2591
- responseStatus: checkoutResponse == null ? void 0 : checkoutResponse.status
2794
+ responseStatus: checkoutResponse?.status
2592
2795
  });
2593
2796
  this.core.effects.emit(`${this.name}:onOrderSubmitEnd`, {
2594
2797
  success: submitSuccess,
2595
- orderUuid,
2596
- operation: isUpdateOperation ? "update" : "create",
2798
+ orderUuid: orderUuid,
2799
+ operation: isUpdateOperation ? 'update' : 'create',
2597
2800
  isManual: false,
2598
- orderId: submitSuccess ? ((_f = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _f.order_id) || (checkoutResponse == null ? void 0 : checkoutResponse.order_id) : void 0,
2801
+ orderId: submitSuccess ? checkoutResponse?.data?.order_id || checkoutResponse?.order_id : undefined,
2599
2802
  error: submitError,
2600
2803
  duration: Date.now() - startTime,
2601
2804
  timestamp: Date.now()
2602
2805
  });
2603
2806
  }
2604
- const responseStatus = checkoutResponse == null ? void 0 : checkoutResponse.status;
2605
- const isSuccessResponse = responseStatus === true || responseStatus === 200 || responseStatus === "success" || responseStatus === 1 && (checkoutResponse == null ? void 0 : checkoutResponse.code) === 200;
2807
+ const responseStatus = checkoutResponse?.status;
2808
+ const isSuccessResponse = responseStatus === true || responseStatus === 200 || responseStatus === 'success' || responseStatus === 1 && checkoutResponse?.code === 200;
2606
2809
  if (!isSuccessResponse) {
2607
- const errorMessage = (checkoutResponse == null ? void 0 : checkoutResponse.message) || "订单同步失败,后端返回非成功状态";
2608
- this.logError("EFTPOS repair sync failed: api error", {
2810
+ const errorMessage = checkoutResponse?.message || '订单同步失败,后端返回非成功状态';
2811
+ this.logError('EFTPOS repair sync failed: api error', {
2609
2812
  orderUuid,
2610
2813
  errorMessage,
2611
2814
  response: checkoutResponse
2612
2815
  });
2613
- return { success: false, response: checkoutResponse };
2816
+ return {
2817
+ success: false,
2818
+ response: checkoutResponse
2819
+ };
2614
2820
  }
2615
2821
  let realOrderId = currentOrderId;
2616
2822
  if (!isUpdateOperation) {
2617
- let extractedOrderId = (_g = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _g.order_id;
2823
+ let extractedOrderId = checkoutResponse?.data?.order_id;
2618
2824
  if (!extractedOrderId) {
2619
- extractedOrderId = checkoutResponse == null ? void 0 : checkoutResponse.order_id;
2825
+ extractedOrderId = checkoutResponse?.order_id;
2620
2826
  }
2621
- if (extractedOrderId !== void 0 && extractedOrderId !== null) {
2827
+ if (extractedOrderId !== undefined && extractedOrderId !== null) {
2622
2828
  extractedOrderId = String(extractedOrderId);
2623
2829
  }
2624
2830
  realOrderId = extractedOrderId;
2625
2831
  if (realOrderId) {
2626
2832
  await this.payment.replaceOrderIdByUuidAsync(orderUuid, realOrderId);
2627
2833
  } else {
2628
- this.logError("EFTPOS repair missing order_id in response", {
2834
+ this.logError('EFTPOS repair missing order_id in response', {
2629
2835
  orderUuid,
2630
2836
  response: checkoutResponse
2631
2837
  });
2632
2838
  }
2633
2839
  }
2634
- const syncedPaymentUuids = processedPaymentItems.filter((item) => item.status !== "voided").map((item) => item.uuid).filter(Boolean);
2840
+ const syncedPaymentUuids = processedPaymentItems.filter(item => item.status !== 'voided').map(item => item.uuid).filter(Boolean);
2635
2841
  for (const paymentUuid of syncedPaymentUuids) {
2636
2842
  await this.payment.updatePaymentAsync(orderUuid, paymentUuid, {
2637
2843
  isSynced: true,
2638
- syncError: void 0
2844
+ syncError: undefined
2639
2845
  });
2640
2846
  }
2641
- const latestPaymentStatus = ((_h = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _h.payment_status) || orderPaymentStatus;
2847
+ const latestPaymentStatus = checkoutResponse?.data?.payment_status || orderPaymentStatus;
2642
2848
  await this.payment.updateOrderAsync(orderUuid, {
2643
2849
  payment_status: latestPaymentStatus
2644
2850
  });
2851
+
2852
+ // 触发订单同步完成事件
2645
2853
  await this.core.effects.emit(`${this.name}:onOrderSynced`, {
2646
- orderUuid,
2854
+ orderUuid: orderUuid,
2647
2855
  realOrderId,
2648
2856
  virtualOrderId: orderUuid,
2649
2857
  timestamp: Date.now(),
@@ -2657,6 +2865,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2657
2865
  response: checkoutResponse
2658
2866
  };
2659
2867
  }
2868
+
2660
2869
  /**
2661
2870
  * 同步订单到后端并返回真实订单ID
2662
2871
  *
@@ -2665,26 +2874,22 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2665
2874
  * @returns 包含订单ID、UUID和完整后端响应的对象
2666
2875
  */
2667
2876
  async syncOrderToBackendWithReturn(isManual = false, customPaymentItems, paymentStatus) {
2668
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2669
2877
  if (!this.store.localOrderData || !this.store.currentOrder) {
2670
- throw new Error("缺少必要的订单数据,无法同步到后端");
2878
+ throw new Error('缺少必要的订单数据,无法同步到后端');
2671
2879
  }
2672
2880
  const orderLockKey = this.store.currentOrder.uuid || this.store.currentOrder.order_id;
2673
2881
  if (!orderLockKey) {
2674
- throw new Error("缺少订单标识,无法同步到后端");
2882
+ throw new Error('缺少订单标识,无法同步到后端');
2675
2883
  }
2676
2884
  const existingInFlight = this.syncOrderToBackendInFlightByOrderKey.get(orderLockKey);
2677
2885
  if (existingInFlight) {
2678
- this.logInfo(
2679
- "syncOrderToBackendWithReturn 触发锁:当前订单正在同步中,将等待当前同步结束",
2680
- {
2681
- orderLockKey,
2682
- orderUuid: this.store.currentOrder.uuid,
2683
- orderId: this.store.currentOrder.order_id,
2684
- isManual,
2685
- hasCustomPaymentItems: !!customPaymentItems
2686
- }
2687
- );
2886
+ this.logInfo('syncOrderToBackendWithReturn 触发锁:当前订单正在同步中,将等待当前同步结束', {
2887
+ orderLockKey,
2888
+ orderUuid: this.store.currentOrder.uuid,
2889
+ orderId: this.store.currentOrder.order_id,
2890
+ isManual,
2891
+ hasCustomPaymentItems: !!customPaymentItems
2892
+ });
2688
2893
  return await existingInFlight;
2689
2894
  }
2690
2895
  let resolveInFlight;
@@ -2695,65 +2900,77 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2695
2900
  });
2696
2901
  this.syncOrderToBackendInFlightByOrderKey.set(orderLockKey, inFlightPromise);
2697
2902
  try {
2698
- this.logInfo("syncOrderToBackendWithReturn called", { isManual });
2903
+ this.logInfo('syncOrderToBackendWithReturn called', {
2904
+ isManual
2905
+ });
2699
2906
  const currentOrderId = this.store.currentOrder.order_id;
2700
- const isUpdateOperation = this.store.isOrderSynced || !(0, import_utils.isVirtualOrderId)(currentOrderId);
2907
+ const isUpdateOperation = this.store.isOrderSynced || !(0, _utils.isVirtualOrderId)(currentOrderId);
2701
2908
  this.logInfo(`开始同步订单到后端...`, {
2702
2909
  currentOrderId,
2703
- isVirtualId: (0, import_utils.isVirtualOrderId)(currentOrderId || ""),
2910
+ isVirtualId: (0, _utils.isVirtualOrderId)(currentOrderId || ''),
2704
2911
  orderUuid: this.store.currentOrder.uuid,
2705
2912
  isOrderSynced: this.store.isOrderSynced,
2706
2913
  isManual
2707
2914
  });
2708
- const paymentItems = customPaymentItems || await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid);
2709
- const processedPaymentItems = paymentItems.map((item) => {
2710
- var _a2, _b2;
2711
- return {
2712
- ...item,
2713
- metadata: {
2714
- ...item.metadata,
2715
- rounding_rule: ((_a2 = item.metadata) == null ? void 0 : _a2.rounding_rule) || this.otherParams.order_rounding_setting,
2716
- shop_wallet_pass_id: ((_b2 = item.metadata) == null ? void 0 : _b2.shop_wallet_pass_id) || this.otherParams.shop_wallet_pass_id
2717
- }
2718
- };
2719
- });
2915
+
2916
+ // 获取当前订单的支付项
2917
+ const paymentItems = customPaymentItems || (await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid));
2918
+
2919
+ // 处理支付项数据,确保包含完整的 metadata
2920
+ const processedPaymentItems = paymentItems.map(item => ({
2921
+ ...item,
2922
+ metadata: {
2923
+ ...item.metadata,
2924
+ rounding_rule: item.metadata?.rounding_rule || this.otherParams.order_rounding_setting,
2925
+ shop_wallet_pass_id: item.metadata?.shop_wallet_pass_id || this.otherParams.shop_wallet_pass_id
2926
+ }
2927
+ }));
2928
+
2929
+ // 确定最终的定金金额:优先使用手动设置的值,否则从支付项中计算
2720
2930
  let finalDepositAmount;
2721
- const manualDepositAmount = ((_a = this.store.currentOrder) == null ? void 0 : _a.deposit_amount) || "0.00";
2722
- const manualDepositValue = new import_decimal.default(manualDepositAmount);
2931
+ const manualDepositAmount = this.store.currentOrder?.deposit_amount || '0.00';
2932
+
2933
+ // 优先级逻辑:手动设置的定金金额 > 从支付项计算的金额
2934
+ const manualDepositValue = new _decimal.default(manualDepositAmount);
2723
2935
  if (manualDepositValue.gt(0)) {
2936
+ // 如果手动设置了定金金额且大于0,使用手动设置的值
2724
2937
  finalDepositAmount = manualDepositAmount;
2725
- this.logInfo("使用手动设置的定金金额", {
2938
+ this.logInfo('使用手动设置的定金金额', {
2726
2939
  manualDepositAmount,
2727
- reason: "用户通过setDepositAmountAsync手动设置了定金金额"
2940
+ reason: '用户通过setDepositAmountAsync手动设置了定金金额'
2728
2941
  });
2729
2942
  } else {
2730
- finalDepositAmount = "0.00";
2731
- this.logInfo("定金金额为0", {
2943
+ // 都为0,使用0
2944
+ finalDepositAmount = '0.00';
2945
+ this.logInfo('定金金额为0', {
2732
2946
  manualDepositAmount,
2733
- reason: "手动设置和计算值均为0"
2947
+ reason: '手动设置和计算值均为0'
2734
2948
  });
2735
2949
  }
2736
- if (this.store.currentOrder.is_deposit === 0 && processedPaymentItems.every((item) => item.order_payment_type !== "deposit")) {
2737
- finalDepositAmount = "0.00";
2950
+ // 如果此时是普通支付状态,并且要同步的支付项里一个定金支付的都没有,则 is_deposit 和 deposit_amount 都置为 0
2951
+ if (this.store.currentOrder.is_deposit === 0 && processedPaymentItems.every(item => item.order_payment_type !== 'deposit')) {
2952
+ finalDepositAmount = '0.00';
2738
2953
  this.store.currentOrder.is_deposit = 0;
2739
2954
  }
2740
- if (this.store.currentOrder.is_deposit === 0 && processedPaymentItems.some((item) => item.order_payment_type === "deposit")) {
2741
- finalDepositAmount = processedPaymentItems.filter((item) => item.status !== "voided" && item.order_payment_type === "deposit").reduce((sum, item) => {
2742
- const amt = new import_decimal.default(item.amount || "0");
2743
- const rounding = new import_decimal.default(item.rounding_amount || "0");
2955
+ // 如果此时是普通支付,并且有普通支付项进来了,则提交给后端的 deposit_amount 只能是支付项里已经支付的order_payment_type = deposit 的金额
2956
+ if (this.store.currentOrder.is_deposit === 0 && processedPaymentItems.some(item => item.order_payment_type === 'deposit')) {
2957
+ finalDepositAmount = processedPaymentItems.filter(item => item.status !== 'voided' && item.order_payment_type === 'deposit').reduce((sum, item) => {
2958
+ const amt = new _decimal.default(item.amount || '0');
2959
+ const rounding = new _decimal.default(item.rounding_amount || '0');
2744
2960
  return sum.plus(amt).sub(rounding);
2745
- }, new import_decimal.default(0)).toFixed(2);
2961
+ }, new _decimal.default(0)).toFixed(2);
2746
2962
  }
2747
- if (this.store.currentOrder.is_deposit === 1 && new import_decimal.default(finalDepositAmount).gte(new import_decimal.default(this.store.currentOrder.total_amount))) {
2748
- finalDepositAmount = processedPaymentItems.filter((item) => item.status !== "voided" && item.order_payment_type === "deposit").reduce((sum, item) => {
2749
- const amt = new import_decimal.default(item.amount || "0");
2750
- const rounding = new import_decimal.default(item.rounding_amount || "0");
2963
+ // 如果当前是定金支付,并且定金额度已经大于等于了订单总计,则 finalDepositAmount 为实际付出去的定金金额
2964
+ if (this.store.currentOrder.is_deposit === 1 && new _decimal.default(finalDepositAmount).gte(new _decimal.default(this.store.currentOrder.total_amount))) {
2965
+ finalDepositAmount = processedPaymentItems.filter(item => item.status !== 'voided' && item.order_payment_type === 'deposit').reduce((sum, item) => {
2966
+ const amt = new _decimal.default(item.amount || '0');
2967
+ const rounding = new _decimal.default(item.rounding_amount || '0');
2751
2968
  return sum.plus(amt).sub(rounding);
2752
- }, new import_decimal.default(0)).toFixed(2);
2969
+ }, new _decimal.default(0)).toFixed(2);
2753
2970
  }
2754
- this.logInfo("定金金额确定结果", {
2971
+ this.logInfo('定金金额确定结果', {
2755
2972
  depositPaymentItemsCount: processedPaymentItems.length,
2756
- depositPaymentItems: processedPaymentItems.map((item) => ({
2973
+ depositPaymentItems: processedPaymentItems.map(item => ({
2757
2974
  uuid: item.uuid,
2758
2975
  code: item.code,
2759
2976
  amount: item.amount,
@@ -2763,23 +2980,32 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2763
2980
  })),
2764
2981
  manualDepositAmount,
2765
2982
  finalDepositAmount,
2766
- isDeposit: ((_b = this.store.currentOrder) == null ? void 0 : _b.is_deposit) || 0
2983
+ isDeposit: this.store.currentOrder?.is_deposit || 0
2767
2984
  });
2985
+
2986
+ // 计算订单状态,优先读取外面传递的,如果没有则根据订单支付数据来
2987
+ // paid 已全额付款
2988
+ // partially_paid 部分付款
2989
+ // unpaid 未支付(弃单状态)
2990
+ // payment_processing 待支付
2768
2991
  let orderPaymentStatus = paymentStatus;
2769
2992
  if (!orderPaymentStatus) {
2770
- const totalPaidAmount = processedPaymentItems.filter((item) => item.status !== "voided").reduce((sum, item) => {
2771
- const amt = new import_decimal.default(item.amount || "0");
2772
- const rounding = new import_decimal.default(item.rounding_amount || "0");
2993
+ // 判断当前支付项里的数据是否已经满足订单的金额
2994
+ const totalPaidAmount = processedPaymentItems.filter(item => item.status !== 'voided').reduce((sum, item) => {
2995
+ const amt = new _decimal.default(item.amount || '0');
2996
+ const rounding = new _decimal.default(item.rounding_amount || '0');
2773
2997
  return sum.plus(amt).sub(rounding);
2774
- }, new import_decimal.default(0));
2775
- if (totalPaidAmount.gte(new import_decimal.default(this.store.currentOrder.total_amount))) {
2776
- orderPaymentStatus = "paid";
2998
+ }, new _decimal.default(0));
2999
+ if (totalPaidAmount.gte(new _decimal.default(this.store.currentOrder.total_amount))) {
3000
+ orderPaymentStatus = 'paid';
2777
3001
  } else if (totalPaidAmount.gt(0)) {
2778
- orderPaymentStatus = "partially_paid";
3002
+ orderPaymentStatus = 'partially_paid';
2779
3003
  } else {
2780
- orderPaymentStatus = "unpaid";
3004
+ orderPaymentStatus = 'unpaid';
2781
3005
  }
2782
3006
  }
3007
+
3008
+ // 构造订单参数,直接使用 localOrderData 中已处理好的数据
2783
3009
  const orderParams = {
2784
3010
  ...this.store.localOrderData,
2785
3011
  payment_status: orderPaymentStatus,
@@ -2787,7 +3013,7 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2787
3013
  platform: this.store.localOrderData.platform,
2788
3014
  payments: processedPaymentItems,
2789
3015
  // 使用处理过的支付项数据
2790
- customer_id: (_c = this.store.currentCustomer) == null ? void 0 : _c.customer_id,
3016
+ customer_id: this.store.currentCustomer?.customer_id,
2791
3017
  // 添加客户ID
2792
3018
  is_price_include_tax: this.otherParams.is_price_include_tax,
2793
3019
  // core 有
@@ -2800,45 +3026,46 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2800
3026
  currency_code: this.otherParams.currency_code,
2801
3027
  currency_symbol: this.otherParams.currency_symbol,
2802
3028
  currency_format: this.otherParams.currency_format,
2803
- business_code: ((_d = this.otherParams) == null ? void 0 : _d.business_code) || void 0,
2804
- is_deposit: (((_e = this.store.currentOrder) == null ? void 0 : _e.is_deposit) || Number(finalDepositAmount) > 0 ? 1 : 0) || 0,
3029
+ business_code: this.otherParams?.business_code || undefined,
3030
+ is_deposit: (this.store.currentOrder?.is_deposit || Number(finalDepositAmount) > 0 ? 1 : 0) || 0,
2805
3031
  deposit_amount: finalDepositAmount,
2806
3032
  // 使用最终确定的定金金额(手动设置优先)
2807
3033
  product_tax_fee: this.store.localOrderData.tax_fee,
2808
3034
  note: this.store.localOrderData.shop_note,
2809
- bookings: (_f = this.store.localOrderData.bookings) == null ? void 0 : _f.map((item) => {
3035
+ bookings: this.store.localOrderData.bookings?.map(item => {
2810
3036
  return {
2811
3037
  ...item,
2812
3038
  product: {
2813
3039
  ...item.product,
2814
- custom_deposit_data: void 0
3040
+ custom_deposit_data: undefined
2815
3041
  },
2816
- deposit: void 0
3042
+ deposit: undefined
2817
3043
  };
2818
3044
  }),
2819
- relation_products: (_g = this.store.localOrderData.relation_products) == null ? void 0 : _g.map(
2820
- (item) => {
2821
- return {
2822
- ...item,
2823
- custom_deposit_data: void 0,
2824
- deposit: void 0
2825
- };
2826
- }
2827
- )
3045
+ relation_products: this.store.localOrderData.relation_products?.map(item => {
3046
+ return {
3047
+ ...item,
3048
+ custom_deposit_data: undefined,
3049
+ deposit: undefined
3050
+ };
3051
+ })
2828
3052
  };
3053
+
3054
+ // 如果是更新操作,需要在参数中包含真实的订单ID
2829
3055
  if (isUpdateOperation) {
2830
- if ((0, import_utils.isVirtualOrderId)(currentOrderId)) {
2831
- this.logWarning(
2832
- "尝试数据修复:暂时不包含order_id,注意:这次调用将作为创建操作处理,但后续会修复数据一致性"
2833
- );
3056
+ // 如果当前订单ID是虚拟ID,但订单已同步过,可能存在数据不一致的问题
3057
+ if ((0, _utils.isVirtualOrderId)(currentOrderId)) {
3058
+ this.logWarning('尝试数据修复:暂时不包含order_id,注意:这次调用将作为创建操作处理,但后续会修复数据一致性');
2834
3059
  } else {
2835
3060
  orderParams.order_id = currentOrderId;
2836
3061
  }
2837
3062
  }
3063
+
3064
+ // 发送下单接口请求开始事件
2838
3065
  const startTime = Date.now();
2839
3066
  await this.core.effects.emit(`${this.name}:onOrderSubmitStart`, {
2840
3067
  orderUuid: this.store.currentOrder.uuid,
2841
- operation: isUpdateOperation ? "update" : "create",
3068
+ operation: isUpdateOperation ? 'update' : 'create',
2842
3069
  isManual,
2843
3070
  paymentItemCount: paymentItems.length,
2844
3071
  timestamp: startTime
@@ -2847,73 +3074,93 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2847
3074
  let submitSuccess = false;
2848
3075
  let submitError;
2849
3076
  try {
2850
- this.logInfo("Calling backend checkout API", {
2851
- url: "/order/checkout",
3077
+ // 记录接口调用参数
3078
+ this.logInfo('Calling backend checkout API', {
3079
+ url: '/order/checkout',
2852
3080
  isManual,
2853
3081
  ...orderParams
2854
3082
  });
3083
+
3084
+ // 调用 Order 模块的专用 createOrderByCheckout 方法
2855
3085
  checkoutResponse = await this.order.createOrderByCheckout(orderParams);
2856
3086
  submitSuccess = true;
2857
3087
  this.store.currentOrder.payment_status = checkoutResponse.data.payment_status;
2858
- this.logInfo("下单接口调用成功", checkoutResponse);
3088
+ this.logInfo('下单接口调用成功', checkoutResponse);
2859
3089
  } catch (error) {
2860
3090
  submitSuccess = false;
2861
3091
  submitError = error instanceof Error ? error.message : String(error);
2862
- this.logError("下单接口调用失败:", submitError);
3092
+ this.logError('下单接口调用失败:', submitError);
3093
+
3094
+ // 发送订单同步失败事件(网络错误或请求失败)
2863
3095
  await this.core.effects.emit(`${this.name}:onOrderSyncFailed`, {
2864
3096
  orderUuid: this.store.currentOrder.uuid,
2865
- operation: isUpdateOperation ? "update" : "create",
3097
+ operation: isUpdateOperation ? 'update' : 'create',
2866
3098
  isManual,
2867
3099
  error: submitError,
2868
- errorType: "network_error",
3100
+ errorType: 'network_error',
2869
3101
  duration: Date.now() - startTime,
2870
3102
  timestamp: Date.now()
2871
3103
  });
2872
- throw error;
3104
+ throw error; // 重新抛出错误以保持原有逻辑
2873
3105
  } finally {
3106
+ // 发送下单接口请求完成事件
2874
3107
  await this.core.effects.emit(`${this.name}:onOrderSubmitEnd`, {
2875
3108
  success: submitSuccess,
2876
3109
  orderUuid: this.store.currentOrder.uuid,
2877
- operation: isUpdateOperation ? "update" : "create",
3110
+ operation: isUpdateOperation ? 'update' : 'create',
2878
3111
  isManual,
2879
- orderId: submitSuccess ? ((_h = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _h.order_id) || (checkoutResponse == null ? void 0 : checkoutResponse.order_id) : void 0,
3112
+ orderId: submitSuccess ? checkoutResponse?.data?.order_id || checkoutResponse?.order_id : undefined,
2880
3113
  error: submitError,
2881
3114
  duration: Date.now() - startTime,
2882
3115
  timestamp: Date.now()
2883
3116
  });
2884
3117
  }
2885
- const responseStatus = checkoutResponse == null ? void 0 : checkoutResponse.status;
2886
- const isSuccessResponse = responseStatus === true || responseStatus === 200 || responseStatus === "success" || responseStatus === 1 && (checkoutResponse == null ? void 0 : checkoutResponse.code) === 200;
3118
+
3119
+ // 检查响应状态是否为成功状态
3120
+ const responseStatus = checkoutResponse?.status;
3121
+ const isSuccessResponse = responseStatus === true || responseStatus === 200 || responseStatus === 'success' || responseStatus === 1 && checkoutResponse?.code === 200;
2887
3122
  if (!isSuccessResponse) {
2888
- const errorMessage = (checkoutResponse == null ? void 0 : checkoutResponse.message) || "订单同步失败,后端返回非成功状态";
3123
+ const errorMessage = checkoutResponse?.message || '订单同步失败,后端返回非成功状态';
3124
+
3125
+ // 发送订单同步失败事件
2889
3126
  await this.core.effects.emit(`${this.name}:onOrderSyncFailed`, {
2890
3127
  orderUuid: this.store.currentOrder.uuid,
2891
- operation: isUpdateOperation ? "update" : "create",
3128
+ operation: isUpdateOperation ? 'update' : 'create',
2892
3129
  isManual,
2893
3130
  error: errorMessage,
2894
- errorType: "api_error",
3131
+ errorType: 'api_error',
2895
3132
  response: checkoutResponse,
2896
3133
  duration: Date.now() - startTime,
2897
3134
  timestamp: Date.now()
2898
3135
  });
3136
+
3137
+ // 抛出错误,终止后续处理
2899
3138
  throw new Error(errorMessage);
2900
3139
  }
2901
3140
  let realOrderId;
2902
3141
  if (isUpdateOperation) {
3142
+ // 更新操作:使用现有的订单ID
2903
3143
  realOrderId = currentOrderId;
2904
3144
  } else {
2905
- let extractedOrderId = (_i = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _i.order_id;
3145
+ // 创建操作:从响应中提取新的订单ID
3146
+ let extractedOrderId = checkoutResponse?.data?.order_id;
3147
+
3148
+ // 如果data.order_id不存在,尝试直接从根级获取
2906
3149
  if (!extractedOrderId) {
2907
- extractedOrderId = checkoutResponse == null ? void 0 : checkoutResponse.order_id;
3150
+ extractedOrderId = checkoutResponse?.order_id;
2908
3151
  }
2909
- if (extractedOrderId !== void 0 && extractedOrderId !== null) {
3152
+
3153
+ // 确保转换为字符串类型
3154
+ if (extractedOrderId !== undefined && extractedOrderId !== null) {
2910
3155
  extractedOrderId = String(extractedOrderId);
2911
3156
  }
2912
3157
  if (!extractedOrderId) {
2913
- this.logError("后端返回的订单信息中未包含订单ID");
3158
+ this.logError('后端返回的订单信息中未包含订单ID');
2914
3159
  }
2915
3160
  realOrderId = extractedOrderId;
2916
- this.logInfo("准备替换订单ID:", {
3161
+
3162
+ // 替换虚拟订单ID为真实订单ID
3163
+ this.logInfo('准备替换订单ID:', {
2917
3164
  orderUuid: this.store.currentOrder.uuid,
2918
3165
  oldOrderId: this.store.currentOrder.order_id,
2919
3166
  newOrderId: realOrderId
@@ -2921,74 +3168,84 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
2921
3168
  try {
2922
3169
  const latestPaymentStatus = this.store.currentOrder.payment_status;
2923
3170
  const previousOrder = this.store.currentOrder;
2924
- const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(
2925
- previousOrder.uuid,
2926
- realOrderId
2927
- );
2928
- this.logInfo("Payment模块替换订单ID结果:", {
3171
+ const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(previousOrder.uuid, realOrderId);
3172
+ this.logInfo('Payment模块替换订单ID结果:', {
2929
3173
  wasSuccessful: !!updatedOrder,
2930
- returnedOrderId: updatedOrder == null ? void 0 : updatedOrder.order_id,
3174
+ returnedOrderId: updatedOrder?.order_id,
2931
3175
  expectedOrderId: realOrderId
2932
3176
  });
2933
3177
  if (updatedOrder) {
2934
- this.logInfo("Payment模块返回的更新后订单:", {
3178
+ this.logInfo('Payment模块返回的更新后订单:', {
2935
3179
  uuid: updatedOrder.uuid,
2936
3180
  orderId: updatedOrder.order_id,
2937
3181
  totalAmount: updatedOrder.total_amount
2938
3182
  });
3183
+
3184
+ // 🔧 合并 DB 快照到内存态,避免覆盖 payment_status(以及其它刚更新过的内存字段)
2939
3185
  this.store.currentOrder = {
2940
3186
  ...previousOrder,
2941
3187
  ...updatedOrder,
2942
3188
  payment_status: latestPaymentStatus
2943
3189
  };
2944
- if (latestPaymentStatus)
2945
- await this.payment.updateOrderAsync(previousOrder.uuid, {
2946
- payment_status: latestPaymentStatus
2947
- });
2948
- this.logInfo(
2949
- "[Checkout] 订单ID替换成功,当前订单ID:",
2950
- this.store.currentOrder.order_id
2951
- );
3190
+
3191
+ // 同步更新 Payment 模块 DB,避免后续读取 DB 时又拿回旧状态
3192
+ if (latestPaymentStatus) await this.payment.updateOrderAsync(previousOrder.uuid, {
3193
+ payment_status: latestPaymentStatus
3194
+ });
3195
+ this.logInfo('[Checkout] 订单ID替换成功,当前订单ID:', this.store.currentOrder.order_id);
2952
3196
  } else {
2953
- this.logError(
2954
- "[Checkout] Payment模块返回空订单,订单ID替换失败,开始手动替换"
2955
- );
3197
+ this.logError('[Checkout] Payment模块返回空订单,订单ID替换失败,开始手动替换');
3198
+
3199
+ // 如果替换失败,手动更新订单ID
2956
3200
  const beforeManualUpdate = this.store.currentOrder.order_id;
2957
3201
  this.store.currentOrder.order_id = realOrderId;
2958
- this.logInfo("手动设置订单ID:", {
3202
+ this.logInfo('手动设置订单ID:', {
2959
3203
  beforeReplacement: beforeManualUpdate,
2960
3204
  afterReplacement: this.store.currentOrder.order_id,
2961
3205
  目标ID: realOrderId
2962
3206
  });
2963
3207
  }
2964
3208
  } catch (error) {
2965
- this.logError("调用Payment模块替换订单ID时发生错误:", error);
3209
+ this.logError('调用Payment模块替换订单ID时发生错误:', error);
3210
+
3211
+ // 发生错误时也进行手动替换
2966
3212
  this.store.currentOrder.order_id = realOrderId;
2967
- this.logInfo("错误恢复:手动设置订单ID:", realOrderId);
3213
+ this.logInfo('错误恢复:手动设置订单ID:', realOrderId);
2968
3214
  }
2969
3215
  }
3216
+
3217
+ // 成功后:标记本次传递给后端的支付项为已同步
2970
3218
  try {
2971
- const syncedPaymentUuids = processedPaymentItems.filter((item) => item.status !== "voided").map((item) => item.uuid).filter(Boolean);
3219
+ const syncedPaymentUuids = processedPaymentItems.filter(item => item.status !== 'voided').map(item => item.uuid).filter(Boolean);
2972
3220
  for (const paymentUuid of syncedPaymentUuids) {
2973
- await this.payment.updatePaymentAsync(
2974
- this.store.currentOrder.uuid,
2975
- paymentUuid,
2976
- { isSynced: true, syncError: void 0 }
2977
- );
3221
+ await this.payment.updatePaymentAsync(this.store.currentOrder.uuid, paymentUuid, {
3222
+ isSynced: true,
3223
+ syncError: undefined
3224
+ });
2978
3225
  }
2979
3226
  } catch (e) {
2980
- this.logWarning("标记支付项已同步失败(不阻塞主流程)", { error: e });
3227
+ this.logWarning('标记支付项已同步失败(不阻塞主流程)', {
3228
+ error: e
3229
+ });
2981
3230
  }
3231
+
3232
+ // 标记订单已同步
2982
3233
  this.store.isOrderSynced = true;
3234
+
3235
+ // 🚀 清除计算缓存,订单已同步,数据可能已变更
2983
3236
  this.clearCalculationCache();
3237
+
3238
+ // 触发订单同步完成事件
2984
3239
  await this.core.effects.emit(`${this.name}:onOrderSynced`, {
2985
3240
  orderUuid: this.store.currentOrder.uuid,
2986
3241
  realOrderId,
2987
3242
  virtualOrderId: this.store.currentOrder.order_id,
2988
3243
  timestamp: Date.now(),
2989
- isManual,
3244
+ isManual: isManual,
2990
3245
  response: checkoutResponse
2991
3246
  });
3247
+
3248
+ // 返回同步结果
2992
3249
  const result = {
2993
3250
  success: true,
2994
3251
  orderId: realOrderId,
@@ -3007,8 +3264,10 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
3007
3264
  }
3008
3265
  }
3009
3266
  }
3010
- async setOtherParams(params, { cover = false } = {}) {
3011
- this.logInfo("setOtherParams called", {
3267
+ async setOtherParams(params, {
3268
+ cover = false
3269
+ } = {}) {
3270
+ this.logInfo('setOtherParams called', {
3012
3271
  metadata: {
3013
3272
  params,
3014
3273
  cover
@@ -3017,9 +3276,13 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
3017
3276
  if (cover) {
3018
3277
  this.otherParams = params;
3019
3278
  } else {
3020
- this.otherParams = { ...this.otherParams, ...params };
3279
+ this.otherParams = {
3280
+ ...this.otherParams,
3281
+ ...params
3282
+ };
3021
3283
  }
3022
3284
  }
3285
+
3023
3286
  /**
3024
3287
  * 通过订单ID编辑订单备注
3025
3288
  *
@@ -3030,41 +3293,54 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
3030
3293
  * @returns 修改结果
3031
3294
  */
3032
3295
  async editOrderNoteByOrderIdAsync(orderId, note) {
3033
- this.logInfo("editOrderNoteByOrderIdAsync called", {
3034
- orderId,
3035
- note,
3296
+ this.logInfo('editOrderNoteByOrderIdAsync called', {
3297
+ orderId: orderId,
3298
+ note: note,
3036
3299
  noteLength: note.length
3037
3300
  });
3038
3301
  try {
3302
+ // 参数验证
3039
3303
  if (!orderId) {
3040
3304
  return {
3041
3305
  success: false,
3042
- message: "订单ID不能为空",
3043
- orderId
3306
+ message: '订单ID不能为空',
3307
+ orderId: orderId
3044
3308
  };
3045
3309
  }
3046
- this.logInfo("Calling order note edit API", {
3310
+
3311
+ // 记录接口调用
3312
+ this.logInfo('Calling order note edit API', {
3047
3313
  url: `/order/order/${orderId}/note`,
3048
- method: "PUT",
3049
- orderId,
3050
- note,
3314
+ method: 'PUT',
3315
+ orderId: orderId,
3316
+ note: note,
3051
3317
  noteLength: note.length
3052
3318
  });
3319
+
3320
+ // 调用后端API修改订单备注
3053
3321
  const response = await this.request.put(`/order/order/${orderId}/note`, {
3054
- note
3322
+ note: note
3055
3323
  });
3056
- this.logInfo("订单备注编辑响应:", {
3057
- orderId,
3324
+ this.logInfo('订单备注编辑响应:', {
3325
+ orderId: orderId,
3058
3326
  status: response.status,
3059
3327
  message: response.message,
3060
- response
3328
+ response: response
3061
3329
  });
3330
+
3331
+ // 检查响应状态
3062
3332
  if (response.status === true || response.status === 200) {
3333
+ // 如果当前订单就是被修改的订单,同时更新本地状态
3063
3334
  if (this.store.currentOrder && (String(this.store.currentOrder.order_id) === String(orderId) || String(this.store.currentOrder.id) === String(orderId))) {
3335
+ // 获取修改前的备注用于事件
3064
3336
  const previousNote = this.getOrderNote();
3337
+
3338
+ // 更新本地订单数据中的备注
3065
3339
  if (this.store.localOrderData) {
3066
3340
  this.store.localOrderData.shop_note = note;
3067
3341
  }
3342
+
3343
+ // 触发订单备注变更事件
3068
3344
  await this.core.effects.emit(`${this.name}:onOrderNoteChanged`, {
3069
3345
  orderUuid: this.store.currentOrder.uuid,
3070
3346
  oldNote: previousNote,
@@ -3074,28 +3350,30 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
3074
3350
  }
3075
3351
  return {
3076
3352
  success: true,
3077
- message: response.message || "订单备注修改成功",
3078
- orderId
3353
+ message: response.message || '订单备注修改成功',
3354
+ orderId: orderId
3079
3355
  };
3080
3356
  } else {
3081
- const errorMessage = response.message || "订单备注修改失败";
3357
+ // API返回失败状态
3358
+ const errorMessage = response.message || '订单备注修改失败';
3082
3359
  this.logError(`订单 ${orderId} 备注修改失败:`, errorMessage);
3083
3360
  return {
3084
3361
  success: false,
3085
3362
  message: errorMessage,
3086
- orderId
3363
+ orderId: orderId
3087
3364
  };
3088
3365
  }
3089
3366
  } catch (error) {
3090
- this.logError("编辑订单备注失败:", error);
3091
- const errorMessage = error instanceof Error ? error.message : "网络错误或服务器异常";
3367
+ this.logError('编辑订单备注失败:', error);
3368
+ const errorMessage = error instanceof Error ? error.message : '网络错误或服务器异常';
3092
3369
  return {
3093
3370
  success: false,
3094
3371
  message: `编辑订单备注失败: ${errorMessage}`,
3095
- orderId
3372
+ orderId: orderId
3096
3373
  };
3097
3374
  }
3098
3375
  }
3376
+
3099
3377
  /**
3100
3378
  * 发送客户支付链接邮件
3101
3379
  *
@@ -3105,78 +3383,85 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
3105
3383
  * @returns 发送结果
3106
3384
  */
3107
3385
  async sendCustomerPayLinkAsync(params) {
3108
- var _a, _b;
3109
- this.logInfo("sendCustomerPayLinkAsync called", {
3386
+ this.logInfo('sendCustomerPayLinkAsync called', {
3110
3387
  orderIds: params.order_ids,
3111
- orderIdsCount: ((_a = params.order_ids) == null ? void 0 : _a.length) || 0,
3388
+ orderIdsCount: params.order_ids?.length || 0,
3112
3389
  emails: params.emails,
3113
- emailsCount: ((_b = params.emails) == null ? void 0 : _b.length) || 0,
3114
- notifyAction: params.notify_action || "order_payment_reminder"
3390
+ emailsCount: params.emails?.length || 0,
3391
+ notifyAction: params.notify_action || 'order_payment_reminder'
3115
3392
  });
3116
3393
  try {
3394
+ // 参数验证
3117
3395
  if (!params.order_ids || params.order_ids.length === 0) {
3118
3396
  return {
3119
3397
  success: false,
3120
- message: "订单ID列表不能为空"
3398
+ message: '订单ID列表不能为空'
3121
3399
  };
3122
3400
  }
3123
3401
  if (!params.emails || params.emails.length === 0) {
3124
3402
  return {
3125
3403
  success: false,
3126
- message: "邮箱地址列表不能为空"
3404
+ message: '邮箱地址列表不能为空'
3127
3405
  };
3128
3406
  }
3407
+
3408
+ // 验证邮箱格式
3129
3409
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
3130
- const invalidEmails = params.emails.filter(
3131
- (email) => !emailRegex.test(email)
3132
- );
3410
+ const invalidEmails = params.emails.filter(email => !emailRegex.test(email));
3133
3411
  if (invalidEmails.length > 0) {
3134
3412
  return {
3135
3413
  success: false,
3136
- message: `邮箱格式无效: ${invalidEmails.join(", ")}`
3414
+ message: `邮箱格式无效: ${invalidEmails.join(', ')}`
3137
3415
  };
3138
3416
  }
3417
+
3418
+ // 构建请求参数
3139
3419
  const requestBody = {
3140
3420
  order_ids: params.order_ids,
3141
- notify_action: params.notify_action || "order_payment_reminder",
3421
+ notify_action: params.notify_action || 'order_payment_reminder',
3142
3422
  emails: params.emails
3143
3423
  };
3144
- this.logInfo("Calling batch email API", {
3145
- url: "/order/batch-email",
3424
+
3425
+ // 记录接口调用
3426
+ this.logInfo('Calling batch email API', {
3427
+ url: '/order/batch-email',
3146
3428
  ...requestBody
3147
3429
  });
3148
- const response = await this.request.post(
3149
- "/order/batch-email",
3150
- requestBody
3151
- );
3152
- this.logInfo("支付链接邮件发送响应:", {
3430
+
3431
+ // 调用后端API发送邮件
3432
+ const response = await this.request.post('/order/batch-email', requestBody);
3433
+ this.logInfo('支付链接邮件发送响应:', {
3153
3434
  status: response.status,
3154
3435
  message: response.message,
3155
3436
  data: response.data,
3156
- response
3437
+ response: response
3157
3438
  });
3439
+
3440
+ // 检查响应状态
3158
3441
  if (response.status === true || response.status === 200) {
3159
3442
  return {
3160
3443
  success: true,
3161
- message: response.message || "支付链接邮件发送成功"
3444
+ message: response.message || '支付链接邮件发送成功'
3162
3445
  };
3163
3446
  } else {
3164
- const errorMessage = response.message || "支付链接邮件发送失败";
3165
- console.error("[Checkout] 支付链接邮件发送失败:", errorMessage);
3447
+ // API返回失败状态
3448
+ const errorMessage = response.message || '支付链接邮件发送失败';
3449
+ console.error('[Checkout] 支付链接邮件发送失败:', errorMessage);
3166
3450
  return {
3167
3451
  success: false,
3168
3452
  message: errorMessage
3169
3453
  };
3170
3454
  }
3171
3455
  } catch (error) {
3172
- this.logError("发送客户支付链接邮件失败:", error);
3173
- const errorMessage = error instanceof Error ? error.message : "网络错误或服务器异常";
3456
+ this.logError('发送客户支付链接邮件失败:', error);
3457
+ const errorMessage = error instanceof Error ? error.message : '网络错误或服务器异常';
3174
3458
  return {
3175
3459
  success: false,
3176
3460
  message: `发送支付链接邮件失败: ${errorMessage}`
3177
3461
  };
3178
3462
  }
3179
3463
  }
3464
+
3180
3465
  /**
3181
3466
  * 金额舍入
3182
3467
  *
@@ -3184,31 +3469,33 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
3184
3469
  * @returns 舍入结果详情,包含原始金额、舍入后金额和舍入差额
3185
3470
  */
3186
3471
  async roundAmountAsync(amount) {
3187
- var _a, _b, _c;
3188
- const cashManualPayment = this.store.paymentMethods.find((p) => p.code === "CASHMANUAL");
3189
- if (!((_a = cashManualPayment == null ? void 0 : cashManualPayment.metadata) == null ? void 0 : _a.order_rounding_switch)) {
3472
+ // 检查 CASHMANUAL 的支付项是否开启了舍入,如果没开直接返回 amount
3473
+ const cashManualPayment = this.store.paymentMethods.find(p => p.code === 'CASHMANUAL');
3474
+ if (!cashManualPayment?.metadata?.order_rounding_switch) {
3190
3475
  return {
3191
3476
  originalAmount: amount.toString(),
3192
3477
  roundedAmount: amount.toString(),
3193
- roundingDifference: "0.00"
3478
+ roundingDifference: '0.00'
3194
3479
  };
3195
3480
  }
3196
- const result = await this.payment.roundAmountAsync(
3197
- amount,
3198
- (_b = this.otherParams.order_rounding_setting) == null ? void 0 : _b.interval,
3199
- (_c = this.otherParams.order_rounding_setting) == null ? void 0 : _c.type
3200
- );
3481
+ const result = await this.payment.roundAmountAsync(amount, this.otherParams.order_rounding_setting?.interval, this.otherParams.order_rounding_setting?.type);
3201
3482
  return result;
3202
3483
  }
3203
3484
  async destroy() {
3204
- var _a, _b, _c, _d;
3485
+ // 清理钱包模块的所有缓存数据
3205
3486
  this.payment.wallet.clearAllCache();
3487
+
3488
+ // 清理事件监听
3206
3489
  this.core.effects.offByModuleDestroy(this.name);
3207
- await ((_b = (_a = this.order) == null ? void 0 : _a.destroy) == null ? void 0 : _b.call(_a));
3208
- await ((_d = (_c = this.payment) == null ? void 0 : _c.destroy) == null ? void 0 : _d.call(_c));
3490
+
3491
+ // 销毁子模块
3492
+ await this.order?.destroy?.();
3493
+ await this.payment?.destroy?.();
3494
+
3495
+ // 取消注册模块
3209
3496
  this.core.unregisterModule(this);
3210
- console.log("[Checkout] 已销毁");
3211
3497
  }
3498
+
3212
3499
  /**
3213
3500
  * 重置 store 状态
3214
3501
  *
@@ -3222,19 +3509,29 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
3222
3509
  uuid: this.store.currentOrder.uuid,
3223
3510
  orderId: this.store.currentOrder.order_id
3224
3511
  } : null;
3225
- console.log("[Checkout] 重置 store 状态,准备创建新订单", prevOrderInfo);
3226
- this.store.currentOrder = void 0;
3227
- this.store.localOrderData = void 0;
3228
- this.store.cartSummary = void 0;
3229
- this.store.stateAmount = "0.00";
3230
- this.store.balanceDueAmount = "0.00";
3512
+ // 重置订单相关的 store 状态(保留 paymentMethods,因为支付方式数据变更不频繁)
3513
+ this.store.currentOrder = undefined;
3514
+ this.store.localOrderData = undefined;
3515
+ this.store.cartSummary = undefined;
3516
+ this.store.stateAmount = '0.00';
3517
+ this.store.balanceDueAmount = '0.00';
3231
3518
  this.store.isOrderSynced = false;
3232
- this.store.currentCustomer = void 0;
3233
- this.store.lastError = void 0;
3519
+ this.store.currentCustomer = undefined;
3520
+ this.store.lastError = undefined;
3521
+
3522
+ // 清空购物车项目
3234
3523
  this.store.cartItems = [];
3524
+
3525
+ // 清理钱包缓存(同步操作)
3235
3526
  this.payment.wallet.clearAllCache();
3527
+
3528
+ // 🚀 清除计算缓存
3236
3529
  this.clearCalculationCache();
3237
- console.log("[Checkout] Store 状态重置完成");
3530
+
3531
+ // 注意:故意保留 this.store.paymentMethods,因为支付方式数据不易变更,保留在内存中提高性能
3532
+
3533
+ // 🚀 性能优化:异步触发订单清理事件(不阻塞主流程)
3534
+ // 使用 setTimeout 确保事件处理不会阻塞状态重置
3238
3535
  if (prevOrderInfo) {
3239
3536
  setTimeout(() => {
3240
3537
  this.core.effects.emit(`${this.name}:onOrderCleared`, {
@@ -3244,12 +3541,8 @@ var CheckoutImpl = class extends import_BaseModule.BaseModule {
3244
3541
  }, 0);
3245
3542
  }
3246
3543
  } catch (error) {
3247
- console.error("[Checkout] 重置 store 状态失败:", error);
3544
+ console.error('[Checkout] 重置 store 状态失败:', error);
3248
3545
  }
3249
3546
  }
3250
- };
3251
- // Annotate the CommonJS export names for ESM import in node:
3252
- 0 && (module.exports = {
3253
- CheckoutImpl,
3254
- ...require("./types")
3255
- });
3547
+ }
3548
+ exports.CheckoutImpl = CheckoutImpl;