@pisell/pisellos 2.3.74 → 2.3.76

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