@pisell/pisellos 2.1.4 → 2.1.6

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 (287) hide show
  1. package/dist/core/index.js +2 -1
  2. package/dist/effects/index.d.ts +4 -3
  3. package/dist/effects/index.js +15 -6
  4. package/dist/modules/AccountList/index.d.ts +7 -1
  5. package/dist/modules/AccountList/index.js +81 -14
  6. package/dist/modules/AccountList/types.d.ts +28 -0
  7. package/dist/modules/AccountList/types.js +8 -0
  8. package/dist/modules/Cart/index.js +1 -1
  9. package/dist/modules/Customer/constants.d.ts +7 -0
  10. package/dist/modules/Customer/constants.js +12 -0
  11. package/dist/modules/Customer/index.d.ts +122 -0
  12. package/dist/modules/Customer/index.js +697 -0
  13. package/dist/modules/Customer/types.d.ts +146 -0
  14. package/dist/modules/Customer/types.js +41 -0
  15. package/dist/modules/Discount/index.d.ts +1 -0
  16. package/dist/modules/Order/index.d.ts +25 -1
  17. package/dist/modules/Order/index.js +224 -2
  18. package/dist/modules/Order/types.d.ts +45 -0
  19. package/dist/modules/Order/types.js +8 -0
  20. package/dist/modules/Payment/cash.d.ts +19 -0
  21. package/dist/modules/Payment/cash.js +97 -0
  22. package/dist/modules/Payment/cashRecommendationAlgorithm.d.ts +22 -0
  23. package/dist/modules/Payment/cashRecommendationAlgorithm.js +423 -0
  24. package/dist/modules/Payment/eftpos.d.ts +11 -0
  25. package/dist/modules/Payment/eftpos.js +80 -0
  26. package/dist/modules/Payment/index.d.ts +184 -9
  27. package/dist/modules/Payment/index.js +2012 -108
  28. package/dist/modules/Payment/mx51.d.ts +0 -0
  29. package/dist/modules/Payment/mx51.js +0 -0
  30. package/dist/modules/Payment/types.d.ts +750 -30
  31. package/dist/modules/Payment/types.js +236 -12
  32. package/dist/modules/Payment/utils.d.ts +17 -0
  33. package/dist/modules/Payment/utils.js +62 -0
  34. package/dist/modules/Payment/walletpass.d.ts +99 -0
  35. package/dist/modules/Payment/walletpass.js +701 -0
  36. package/dist/modules/Product/index.d.ts +1 -1
  37. package/dist/modules/ProductList/index.d.ts +12 -1
  38. package/dist/modules/ProductList/index.js +27 -3
  39. package/dist/modules/Rules/index.d.ts +2 -0
  40. package/dist/modules/Rules/index.js +39 -17
  41. package/dist/modules/Rules/types.d.ts +1 -0
  42. package/dist/modules/Schedule/index.d.ts +9 -0
  43. package/dist/modules/Schedule/index.js +77 -0
  44. package/dist/modules/index.d.ts +1 -0
  45. package/dist/modules/index.js +1 -0
  46. package/dist/plugins/app-types/app/app.d.ts +83 -0
  47. package/dist/plugins/app-types/app/const.d.ts +4 -0
  48. package/dist/plugins/app-types/app/index.d.ts +14 -0
  49. package/dist/plugins/app-types/applicationManager/application.d.ts +50 -0
  50. package/dist/plugins/app-types/applicationManager/index.d.ts +13 -0
  51. package/dist/plugins/app-types/config.d.ts +3 -0
  52. package/dist/plugins/app-types/cookie/index.d.ts +13 -0
  53. package/dist/plugins/app-types/data/index.d.ts +8 -0
  54. package/dist/plugins/app-types/history/config.d.ts +24 -0
  55. package/dist/plugins/app-types/history/index.d.ts +20 -0
  56. package/dist/plugins/app-types/history/type.d.ts +2 -0
  57. package/dist/plugins/app-types/hooks/index.d.ts +12 -0
  58. package/dist/plugins/app-types/hooks/useDelayedValue/index.d.ts +2 -0
  59. package/dist/plugins/app-types/hooks/useDispatch/index.d.ts +2 -0
  60. package/dist/plugins/app-types/hooks/useLowCode/index.d.ts +13 -0
  61. package/dist/plugins/app-types/hooks/useStore/index.d.ts +6 -0
  62. package/dist/plugins/app-types/index.d.ts +6 -0
  63. package/dist/plugins/app-types/indexDB/index.d.ts +178 -0
  64. package/dist/plugins/app-types/locales/en.d.ts +3 -0
  65. package/dist/plugins/app-types/locales/index.d.ts +37 -0
  66. package/dist/plugins/app-types/locales/original.d.ts +3 -0
  67. package/dist/plugins/app-types/locales/type.d.ts +19 -0
  68. package/dist/plugins/app-types/locales/zh-CN.d.ts +3 -0
  69. package/dist/plugins/app-types/locales/zh-HK.d.ts +3 -0
  70. package/dist/plugins/app-types/logger/feishu.d.ts +11 -0
  71. package/dist/plugins/app-types/logger/index.d.ts +122 -0
  72. package/dist/plugins/app-types/menuManager/hooks.d.ts +17 -0
  73. package/dist/plugins/app-types/menuManager/index.d.ts +28 -0
  74. package/dist/plugins/app-types/models/global.d.ts +32 -0
  75. package/dist/plugins/app-types/models/index.d.ts +45 -0
  76. package/dist/plugins/app-types/models/type.d.ts +2 -0
  77. package/dist/plugins/app-types/package.json +15 -0
  78. package/dist/plugins/app-types/plugin/index.d.ts +0 -0
  79. package/dist/plugins/app-types/pubsub/example.d.ts +5 -0
  80. package/dist/plugins/app-types/pubsub/index.d.ts +63 -0
  81. package/dist/plugins/app-types/request/cache.d.ts +46 -0
  82. package/dist/plugins/app-types/request/cancelToken.d.ts +38 -0
  83. package/dist/plugins/app-types/request/config.d.ts +3 -0
  84. package/dist/plugins/app-types/request/constants.d.ts +2 -0
  85. package/dist/plugins/app-types/request/index.d.ts +24 -0
  86. package/dist/plugins/app-types/request/pisell2Request.d.ts +6 -0
  87. package/dist/plugins/app-types/request/type.d.ts +41 -0
  88. package/dist/plugins/app-types/request/utils.d.ts +46 -0
  89. package/dist/plugins/app-types/routes/config.d.ts +7 -0
  90. package/dist/plugins/app-types/routes/index.d.ts +28 -0
  91. package/dist/plugins/app-types/socket/components/SocketMonitorPage.d.ts +6 -0
  92. package/dist/plugins/app-types/socket/components/index.d.ts +2 -0
  93. package/dist/plugins/app-types/socket/constants.d.ts +33 -0
  94. package/dist/plugins/app-types/socket/events.d.ts +31 -0
  95. package/dist/plugins/app-types/socket/heartbeat.d.ts +66 -0
  96. package/dist/plugins/app-types/socket/index.d.ts +61 -0
  97. package/dist/plugins/app-types/socket/monitor.d.ts +169 -0
  98. package/dist/plugins/app-types/socket/reconnect.d.ts +61 -0
  99. package/dist/plugins/app-types/socket/socket.d.ts +129 -0
  100. package/dist/plugins/app-types/socket/types.d.ts +85 -0
  101. package/dist/plugins/app-types/storage/index.d.ts +17 -0
  102. package/dist/plugins/app-types/tasks/index.d.ts +77 -0
  103. package/dist/plugins/app-types/tasks/type.d.ts +62 -0
  104. package/dist/plugins/app-types/tasks/useTasks.d.ts +5 -0
  105. package/dist/plugins/app-types/type.d.ts +2 -0
  106. package/dist/plugins/app-types/variables/VariablesProvider.d.ts +7 -0
  107. package/dist/plugins/app-types/variables/config.d.ts +3 -0
  108. package/dist/plugins/app-types/variables/index.d.ts +6 -0
  109. package/dist/plugins/app-types/variables/type.d.ts +2 -0
  110. package/dist/plugins/app-types/website/index.d.ts +6 -0
  111. package/dist/plugins/app.d.ts +8 -0
  112. package/dist/plugins/app.js +1 -0
  113. package/dist/plugins/window.d.ts +1 -0
  114. package/dist/solution/BookingByStep/index.d.ts +1 -1
  115. package/dist/solution/BookingByStep/index.js +1 -1
  116. package/dist/solution/BookingTicket/index.d.ts +180 -0
  117. package/dist/solution/BookingTicket/index.js +689 -0
  118. package/dist/solution/BookingTicket/types.d.ts +68 -0
  119. package/dist/solution/BookingTicket/types.js +43 -0
  120. package/dist/solution/BookingTicket/utils/scan/cloudSearch.d.ts +22 -0
  121. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +159 -0
  122. package/dist/solution/BookingTicket/utils/scan/handleScan.d.ts +22 -0
  123. package/dist/solution/BookingTicket/utils/scan/handleScan.js +189 -0
  124. package/dist/solution/BookingTicket/utils/scan/index.d.ts +81 -0
  125. package/dist/solution/BookingTicket/utils/scan/index.js +285 -0
  126. package/dist/solution/BookingTicket/utils/scan/scanCache.d.ts +78 -0
  127. package/dist/solution/BookingTicket/utils/scan/scanCache.js +305 -0
  128. package/dist/solution/Checkout/appointmentDemo.json +1 -0
  129. package/dist/solution/Checkout/index.d.ts +509 -0
  130. package/dist/solution/Checkout/index.js +4874 -0
  131. package/dist/solution/Checkout/types.d.ts +923 -0
  132. package/dist/solution/Checkout/types.js +148 -0
  133. package/dist/solution/Checkout/utils/index.d.ts +117 -0
  134. package/dist/solution/Checkout/utils/index.js +549 -0
  135. package/dist/solution/ShopDiscount/index.d.ts +4 -9
  136. package/dist/solution/ShopDiscount/index.js +106 -54
  137. package/dist/solution/ShopDiscount/types.d.ts +10 -1
  138. package/dist/solution/index.d.ts +2 -0
  139. package/dist/solution/index.js +3 -1
  140. package/dist/types/index.d.ts +3 -1
  141. package/dist/utils/task.d.ts +40 -0
  142. package/dist/utils/task.js +171 -0
  143. package/dist/utils/watch.d.ts +102 -0
  144. package/dist/utils/watch.js +294 -0
  145. package/lib/core/index.js +1 -1
  146. package/lib/effects/index.d.ts +4 -3
  147. package/lib/effects/index.js +4 -1
  148. package/lib/modules/AccountList/index.d.ts +7 -1
  149. package/lib/modules/AccountList/index.js +27 -0
  150. package/lib/modules/AccountList/types.d.ts +28 -0
  151. package/lib/modules/Cart/index.js +1 -1
  152. package/lib/modules/Customer/constants.d.ts +7 -0
  153. package/lib/modules/Customer/constants.js +39 -0
  154. package/lib/modules/Customer/index.d.ts +122 -0
  155. package/lib/modules/Customer/index.js +440 -0
  156. package/lib/modules/Customer/types.d.ts +146 -0
  157. package/lib/modules/Customer/types.js +37 -0
  158. package/lib/modules/Discount/index.d.ts +1 -0
  159. package/lib/modules/Order/index.d.ts +25 -1
  160. package/lib/modules/Order/index.js +182 -0
  161. package/lib/modules/Order/types.d.ts +45 -0
  162. package/lib/modules/Payment/cash.d.ts +19 -0
  163. package/lib/modules/Payment/cash.js +64 -0
  164. package/lib/modules/Payment/cashRecommendationAlgorithm.d.ts +22 -0
  165. package/lib/modules/Payment/cashRecommendationAlgorithm.js +342 -0
  166. package/lib/modules/Payment/eftpos.d.ts +11 -0
  167. package/lib/modules/Payment/eftpos.js +51 -0
  168. package/lib/modules/Payment/index.d.ts +184 -9
  169. package/lib/modules/Payment/index.js +1044 -50
  170. package/lib/modules/Payment/mx51.d.ts +0 -0
  171. package/lib/modules/Payment/mx51.js +0 -0
  172. package/lib/modules/Payment/types.d.ts +750 -30
  173. package/lib/modules/Payment/types.js +79 -6
  174. package/lib/modules/Payment/utils.d.ts +17 -0
  175. package/lib/modules/Payment/utils.js +67 -0
  176. package/lib/modules/Payment/walletpass.d.ts +99 -0
  177. package/lib/modules/Payment/walletpass.js +468 -0
  178. package/lib/modules/Product/index.d.ts +1 -1
  179. package/lib/modules/ProductList/index.d.ts +12 -1
  180. package/lib/modules/ProductList/index.js +29 -2
  181. package/lib/modules/Rules/index.d.ts +2 -0
  182. package/lib/modules/Rules/index.js +32 -15
  183. package/lib/modules/Rules/types.d.ts +1 -0
  184. package/lib/modules/Schedule/index.d.ts +9 -0
  185. package/lib/modules/Schedule/index.js +60 -0
  186. package/lib/modules/index.d.ts +1 -0
  187. package/lib/modules/index.js +2 -0
  188. package/lib/plugins/app-types/app/app.d.ts +83 -0
  189. package/lib/plugins/app-types/app/const.d.ts +4 -0
  190. package/lib/plugins/app-types/app/index.d.ts +14 -0
  191. package/lib/plugins/app-types/applicationManager/application.d.ts +50 -0
  192. package/lib/plugins/app-types/applicationManager/index.d.ts +13 -0
  193. package/lib/plugins/app-types/config.d.ts +3 -0
  194. package/lib/plugins/app-types/cookie/index.d.ts +13 -0
  195. package/lib/plugins/app-types/data/index.d.ts +8 -0
  196. package/lib/plugins/app-types/history/config.d.ts +24 -0
  197. package/lib/plugins/app-types/history/index.d.ts +20 -0
  198. package/lib/plugins/app-types/history/type.d.ts +2 -0
  199. package/lib/plugins/app-types/hooks/index.d.ts +12 -0
  200. package/lib/plugins/app-types/hooks/useDelayedValue/index.d.ts +2 -0
  201. package/lib/plugins/app-types/hooks/useDispatch/index.d.ts +2 -0
  202. package/lib/plugins/app-types/hooks/useLowCode/index.d.ts +13 -0
  203. package/lib/plugins/app-types/hooks/useStore/index.d.ts +6 -0
  204. package/lib/plugins/app-types/index.d.ts +6 -0
  205. package/lib/plugins/app-types/indexDB/index.d.ts +178 -0
  206. package/lib/plugins/app-types/locales/en.d.ts +3 -0
  207. package/lib/plugins/app-types/locales/index.d.ts +37 -0
  208. package/lib/plugins/app-types/locales/original.d.ts +3 -0
  209. package/lib/plugins/app-types/locales/type.d.ts +19 -0
  210. package/lib/plugins/app-types/locales/zh-CN.d.ts +3 -0
  211. package/lib/plugins/app-types/locales/zh-HK.d.ts +3 -0
  212. package/lib/plugins/app-types/logger/feishu.d.ts +11 -0
  213. package/lib/plugins/app-types/logger/index.d.ts +122 -0
  214. package/lib/plugins/app-types/menuManager/hooks.d.ts +17 -0
  215. package/lib/plugins/app-types/menuManager/index.d.ts +28 -0
  216. package/lib/plugins/app-types/models/global.d.ts +32 -0
  217. package/lib/plugins/app-types/models/index.d.ts +45 -0
  218. package/lib/plugins/app-types/models/type.d.ts +2 -0
  219. package/lib/plugins/app-types/package.json +15 -0
  220. package/lib/plugins/app-types/plugin/index.d.ts +0 -0
  221. package/lib/plugins/app-types/pubsub/example.d.ts +5 -0
  222. package/lib/plugins/app-types/pubsub/index.d.ts +63 -0
  223. package/lib/plugins/app-types/request/cache.d.ts +46 -0
  224. package/lib/plugins/app-types/request/cancelToken.d.ts +38 -0
  225. package/lib/plugins/app-types/request/config.d.ts +3 -0
  226. package/lib/plugins/app-types/request/constants.d.ts +2 -0
  227. package/lib/plugins/app-types/request/index.d.ts +24 -0
  228. package/lib/plugins/app-types/request/pisell2Request.d.ts +6 -0
  229. package/lib/plugins/app-types/request/type.d.ts +41 -0
  230. package/lib/plugins/app-types/request/utils.d.ts +46 -0
  231. package/lib/plugins/app-types/routes/config.d.ts +7 -0
  232. package/lib/plugins/app-types/routes/index.d.ts +28 -0
  233. package/lib/plugins/app-types/socket/components/SocketMonitorPage.d.ts +6 -0
  234. package/lib/plugins/app-types/socket/components/index.d.ts +2 -0
  235. package/lib/plugins/app-types/socket/constants.d.ts +33 -0
  236. package/lib/plugins/app-types/socket/events.d.ts +31 -0
  237. package/lib/plugins/app-types/socket/heartbeat.d.ts +66 -0
  238. package/lib/plugins/app-types/socket/index.d.ts +61 -0
  239. package/lib/plugins/app-types/socket/monitor.d.ts +169 -0
  240. package/lib/plugins/app-types/socket/reconnect.d.ts +61 -0
  241. package/lib/plugins/app-types/socket/socket.d.ts +129 -0
  242. package/lib/plugins/app-types/socket/types.d.ts +85 -0
  243. package/lib/plugins/app-types/storage/index.d.ts +17 -0
  244. package/lib/plugins/app-types/tasks/index.d.ts +77 -0
  245. package/lib/plugins/app-types/tasks/type.d.ts +62 -0
  246. package/lib/plugins/app-types/tasks/useTasks.d.ts +5 -0
  247. package/lib/plugins/app-types/type.d.ts +2 -0
  248. package/lib/plugins/app-types/variables/VariablesProvider.d.ts +7 -0
  249. package/lib/plugins/app-types/variables/config.d.ts +3 -0
  250. package/lib/plugins/app-types/variables/index.d.ts +6 -0
  251. package/lib/plugins/app-types/variables/type.d.ts +2 -0
  252. package/lib/plugins/app-types/website/index.d.ts +6 -0
  253. package/lib/plugins/app.d.ts +8 -0
  254. package/lib/plugins/app.js +17 -0
  255. package/lib/plugins/window.d.ts +1 -0
  256. package/lib/solution/BookingByStep/index.d.ts +1 -1
  257. package/lib/solution/BookingByStep/index.js +1 -2
  258. package/lib/solution/BookingTicket/index.d.ts +180 -0
  259. package/lib/solution/BookingTicket/index.js +420 -0
  260. package/lib/solution/BookingTicket/types.d.ts +68 -0
  261. package/lib/solution/BookingTicket/types.js +72 -0
  262. package/lib/solution/BookingTicket/utils/scan/cloudSearch.d.ts +22 -0
  263. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +117 -0
  264. package/lib/solution/BookingTicket/utils/scan/handleScan.d.ts +22 -0
  265. package/lib/solution/BookingTicket/utils/scan/handleScan.js +132 -0
  266. package/lib/solution/BookingTicket/utils/scan/index.d.ts +81 -0
  267. package/lib/solution/BookingTicket/utils/scan/index.js +210 -0
  268. package/lib/solution/BookingTicket/utils/scan/scanCache.d.ts +78 -0
  269. package/lib/solution/BookingTicket/utils/scan/scanCache.js +231 -0
  270. package/lib/solution/Checkout/appointmentDemo.json +1 -0
  271. package/lib/solution/Checkout/index.d.ts +509 -0
  272. package/lib/solution/Checkout/index.js +3002 -0
  273. package/lib/solution/Checkout/types.d.ts +923 -0
  274. package/lib/solution/Checkout/types.js +87 -0
  275. package/lib/solution/Checkout/utils/index.d.ts +117 -0
  276. package/lib/solution/Checkout/utils/index.js +403 -0
  277. package/lib/solution/ShopDiscount/index.d.ts +4 -9
  278. package/lib/solution/ShopDiscount/index.js +41 -13
  279. package/lib/solution/ShopDiscount/types.d.ts +10 -1
  280. package/lib/solution/index.d.ts +2 -0
  281. package/lib/solution/index.js +5 -1
  282. package/lib/types/index.d.ts +3 -1
  283. package/lib/utils/task.d.ts +40 -0
  284. package/lib/utils/task.js +109 -0
  285. package/lib/utils/watch.d.ts +102 -0
  286. package/lib/utils/watch.js +217 -0
  287. package/package.json +4 -2
@@ -0,0 +1,3002 @@
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;
18
+ };
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
34
+ });
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
+ __reExport(Checkout_exports, require("./types"), module.exports);
44
+ var CheckoutImpl = class extends import_BaseModule.BaseModule {
45
+ constructor(name, version) {
46
+ super(name || "checkout", version || "1.0.0");
47
+ this.defaultName = "checkout";
48
+ this.defaultVersion = "1.0.0";
49
+ this.isSolution = true;
50
+ this.otherParams = {};
51
+ }
52
+ async initialize(core, options) {
53
+ this.core = core;
54
+ this.otherParams = options.otherParams || {};
55
+ this.request = core.getPlugin("request");
56
+ if (!this.request) {
57
+ throw new Error("Checkout 解决方案需要 request 插件支持");
58
+ }
59
+ const appPlugin = core.getPlugin("app");
60
+ if (!appPlugin) {
61
+ throw new Error("Checkout 解决方案需要 app 插件支持");
62
+ }
63
+ const app = appPlugin.getApp();
64
+ this.logger = app.logger;
65
+ this.order = new import_Order.OrderModule();
66
+ this.payment = new import_Payment.PaymentModule();
67
+ this.store = {
68
+ status: import_types.CheckoutStatus.Initializing,
69
+ step: import_types.CheckoutStep.OrderConfirmation,
70
+ cartItems: [],
71
+ paymentMethods: [],
72
+ stateAmount: "0.00",
73
+ balanceDueAmount: "0.00",
74
+ cartSummary: void 0,
75
+ isOrderSynced: false,
76
+ currentCustomer: void 0
77
+ };
78
+ await this.initializeSubModules(core, options);
79
+ await this.preloadPaymentMethods();
80
+ await this.cleanupExpiredOrdersAsync();
81
+ this.setStatus(import_types.CheckoutStatus.Ready);
82
+ console.log("[Checkout] 初始化完成");
83
+ await this.core.effects.emit(import_types.CheckoutHooks.OnCheckoutInitialized, {
84
+ timestamp: Date.now()
85
+ });
86
+ this.logInfo("CheckoutModule initialized successfully");
87
+ }
88
+ /**
89
+ * 记录信息日志
90
+ */
91
+ logInfo(title, metadata) {
92
+ if (this.logger) {
93
+ this.logger.addLog({
94
+ type: "info",
95
+ title: `[CheckoutModule] ${this.getCurrentOrderId()} ${title}`,
96
+ metadata: metadata || {}
97
+ });
98
+ }
99
+ }
100
+ /**
101
+ * 记录警告日志
102
+ */
103
+ logWarning(title, metadata) {
104
+ if (this.logger) {
105
+ this.logger.addLog({
106
+ type: "warning",
107
+ title: `[CheckoutModule] ${title}`,
108
+ metadata: metadata || {}
109
+ });
110
+ }
111
+ }
112
+ /**
113
+ * 记录错误日志
114
+ */
115
+ logError(title, metadata) {
116
+ if (this.logger) {
117
+ this.logger.addLog({
118
+ type: "error",
119
+ title: `[CheckoutModule] ${title}`,
120
+ metadata: metadata || {}
121
+ });
122
+ }
123
+ }
124
+ /**
125
+ * 初始化子模块
126
+ */
127
+ async initializeSubModules(core, options) {
128
+ var _a, _b;
129
+ core.registerModule(this.order, {
130
+ store: ((_a = options.store) == null ? void 0 : _a.order) || {},
131
+ otherParams: { ...this.otherParams, fatherModule: this.name }
132
+ });
133
+ core.registerModule(this.payment, {
134
+ store: ((_b = options.store) == null ? void 0 : _b.payment) || {},
135
+ otherParams: { ...this.otherParams, fatherModule: this.name }
136
+ });
137
+ this.setupPaymentEventListeners();
138
+ }
139
+ /**
140
+ * 设置支付模块事件监听
141
+ */
142
+ setupPaymentEventListeners() {
143
+ this.core.effects.on("payment:onPaymentSyncSuccess", async (data) => {
144
+ var _a;
145
+ if (((_a = this.store.currentOrder) == null ? void 0 : _a.uuid) === data.orderUuid) {
146
+ await this.handlePaymentSuccess(data);
147
+ }
148
+ });
149
+ this.core.effects.on("payment:onPaymentSyncError", async (data) => {
150
+ var _a;
151
+ if (((_a = this.store.currentOrder) == null ? void 0 : _a.uuid) === data.orderUuid) {
152
+ await this.handlePaymentError(data);
153
+ }
154
+ });
155
+ this.core.effects.on(
156
+ import_types2.PaymentHooks.OnPaymentMethodsLoaded,
157
+ async (methods) => {
158
+ console.log("[Checkout] 收到支付方式加载完成事件:", methods.length);
159
+ this.store.paymentMethods = methods;
160
+ }
161
+ );
162
+ this.core.effects.on(
163
+ import_types2.PaymentHooks.OnPaymentMethodsChanged,
164
+ async (data) => {
165
+ console.log("[Checkout] 收到支付方式变更事件:", {
166
+ oldCount: data.oldMethods.length,
167
+ newCount: data.newMethods.length
168
+ });
169
+ this.store.paymentMethods = data.newMethods;
170
+ }
171
+ );
172
+ }
173
+ /**
174
+ * 初始化结账流程
175
+ */
176
+ async initializeCheckoutAsync(params) {
177
+ var _a;
178
+ this.logInfo("initializeCheckoutAsync called", {
179
+ cartItemsCount: ((_a = params.cartItems) == null ? void 0 : _a.length) || 0,
180
+ orderType: params.orderType,
181
+ platform: params.platform
182
+ });
183
+ try {
184
+ this.setStatus(import_types.CheckoutStatus.Initializing);
185
+ const validation = this.validateCheckoutParams(params);
186
+ if (!validation.valid) {
187
+ throw (0, import_utils.createCheckoutError)(
188
+ import_types.CheckoutErrorType.ValidationFailed,
189
+ `参数验证失败: ${validation.errors.join(", ")}`
190
+ );
191
+ }
192
+ this.store.cartItems = params.cartItems;
193
+ this.setStatus(import_types.CheckoutStatus.Ready);
194
+ this.setStep(import_types.CheckoutStep.OrderConfirmation);
195
+ console.log("[Checkout] 结账流程初始化完成");
196
+ } catch (error) {
197
+ await this.handleError(error, import_types.CheckoutErrorType.UnknownError);
198
+ throw error;
199
+ }
200
+ }
201
+ getProductListByOrder() {
202
+ var _a, _b, _c, _d, _e;
203
+ if (!this.store.currentOrder) {
204
+ return [];
205
+ }
206
+ const getDiscountListAmount = (list) => {
207
+ return list.reduce((pre, item) => {
208
+ return pre + (item.amount || 0);
209
+ }, 0);
210
+ };
211
+ const productList = ((_b = (_a = this.store.currentOrder.order_info) == null ? void 0 : _a.original_order_data.bookings) == null ? void 0 : _b.map(
212
+ (item) => ({
213
+ product_id: item.product.product_id,
214
+ product_variant_id: item.product.product_variant_id,
215
+ quantity: item.product.num,
216
+ selling_price: item.product.price - (item.product.discount_amount || 0) - getDiscountListAmount(item.product.discount_list)
217
+ })
218
+ )) || [];
219
+ const relationProducts = ((_e = (_d = (_c = this.store.currentOrder.order_info) == null ? void 0 : _c.original_order_data) == null ? void 0 : _d.relation_products) == null ? void 0 : _e.map((item) => ({
220
+ product_id: item.product_id,
221
+ product_variant_id: item.product_variant_id,
222
+ quantity: item.num,
223
+ selling_price: item.source_product_price
224
+ }))) || [];
225
+ return [...productList, ...relationProducts];
226
+ }
227
+ async initWalletData(params) {
228
+ var _a, _b, _c, _d;
229
+ const amountInfo = (_b = (_a = this.store.currentOrder) == null ? void 0 : _a.order_info) == null ? void 0 : _b.amount_breakdown;
230
+ if (!amountInfo) {
231
+ return;
232
+ }
233
+ const walletBusinessData = {
234
+ customer_id: ((_c = this.store.currentCustomer) == null ? void 0 : _c.customer_id) ? Number(this.store.currentCustomer.customer_id) : void 0,
235
+ amountInfo: {
236
+ totalAmount: amountInfo.totalAmount,
237
+ subTotal: amountInfo.subTotal
238
+ },
239
+ products: this.getProductListByOrder(),
240
+ ...params
241
+ };
242
+ await this.payment.wallet.initializeWalletDataFromBusinessAsync(
243
+ walletBusinessData
244
+ );
245
+ await this.core.effects.emit(import_types.CheckoutHooks.OnWalletDataInitialized, {
246
+ orderUuid: (_d = this.store.currentOrder) == null ? void 0 : _d.uuid,
247
+ customerId: walletBusinessData.customer_id,
248
+ walletBusinessData: {
249
+ customer_id: walletBusinessData.customer_id,
250
+ amountInfo: walletBusinessData.amountInfo,
251
+ order_wait_pay_amount: params == null ? void 0 : params.order_wait_pay_amount
252
+ },
253
+ timestamp: Date.now()
254
+ });
255
+ }
256
+ /**
257
+ * 创建本地订单 (前端模拟下单流程)
258
+ *
259
+ * 此方法用于在前端模拟整个下单流程,创建一个本地的虚拟订单。
260
+ * 用户在购物车点击下单时,会把购物车参数传递给此方法,
261
+ * 方法会记录参数并创建本地虚拟订单,然后用 Payment 模块管理支付流程。
262
+ */
263
+ async createLocalOrderAsync(params) {
264
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
265
+ this.logInfo("createLocalOrderAsync called", {
266
+ orderDataType: (_a = params.orderData) == null ? void 0 : _a.type,
267
+ platform: (_b = params.orderData) == null ? void 0 : _b.platform,
268
+ bookingsCount: ((_d = (_c = params.orderData) == null ? void 0 : _c.bookings) == null ? void 0 : _d.length) || 0,
269
+ relationProductsCount: ((_f = (_e = params.orderData) == null ? void 0 : _e.relation_products) == null ? void 0 : _f.length) || 0,
270
+ customerId: (_g = params.orderData) == null ? void 0 : _g.customer_id,
271
+ autoPayment: params.autoPayment,
272
+ cartSummaryCount: ((_h = params.cartSummary) == null ? void 0 : _h.length) || 0,
273
+ totalInfoKeys: params.totalInfo ? Object.keys(params.totalInfo) : []
274
+ });
275
+ try {
276
+ console.time("createLocalOrderAsync");
277
+ await this.resetStoreStateAsync();
278
+ this.setStatus(import_types.CheckoutStatus.CreatingOrder);
279
+ const validation = (0, import_utils.validateLocalOrderData)(params.orderData);
280
+ if (!validation.valid) {
281
+ throw (0, import_utils.createCheckoutError)(
282
+ import_types.CheckoutErrorType.ValidationFailed,
283
+ `订单数据验证失败: ${validation.errors.join(", ")}`
284
+ );
285
+ }
286
+ const localOrderId = (0, import_utils.generateLocalOrderId)();
287
+ const amountInfo = (0, import_utils.extractAmountFromCartSummary)(params.cartSummary);
288
+ params.orderData.platform = "pos";
289
+ params.orderData.created_at = (0, import_utils.formatDateTime)(/* @__PURE__ */ new Date());
290
+ params.orderData.surcharge_fee = (_j = (_i = params.totalInfo) == null ? void 0 : _i.total) == null ? void 0 : _j.otherAmount;
291
+ params.orderData.surcharges = (_l = (_k = params.totalInfo) == null ? void 0 : _k.total) == null ? void 0 : _l.surcharge;
292
+ params.orderData.shop_discount = (_n = (_m = params.totalInfo) == null ? void 0 : _m.total) == null ? void 0 : _n.shopDiscount;
293
+ params.orderData.tax_fee = (_p = (_o = params.totalInfo) == null ? void 0 : _o.total) == null ? void 0 : _p.tax;
294
+ this.store.localOrderData = params.orderData;
295
+ this.store.cartSummary = params.cartSummary;
296
+ const customerInfo = {
297
+ customer_id: params.orderData.customer_id,
298
+ customer_name: params.orderData.customer_name
299
+ };
300
+ if (customerInfo.customer_id || customerInfo.customer_name) {
301
+ this.store.currentCustomer = customerInfo;
302
+ console.log("[Checkout] 保存客户信息:", customerInfo);
303
+ } else {
304
+ this.store.currentCustomer = void 0;
305
+ console.log("[Checkout] 未提供客户信息");
306
+ }
307
+ const paymentOrder = await this.payment.createPaymentOrderAsync({
308
+ order_id: localOrderId,
309
+ total_amount: amountInfo.totalAmount,
310
+ is_deposit: params.orderData.is_deposit || 0,
311
+ deposit_amount: amountInfo.depositAmount || "0.00",
312
+ order_info: {
313
+ original_order_data: params.orderData,
314
+ cart_summary: params.cartSummary,
315
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
316
+ platform: params.orderData.platform,
317
+ type: params.orderData.type,
318
+ schedule_date: params.orderData.schedule_date,
319
+ shop_note: params.orderData.shop_note,
320
+ amount_breakdown: amountInfo
321
+ }
322
+ });
323
+ console.timeEnd("createLocalOrderAsync");
324
+ this.store.currentOrder = paymentOrder;
325
+ this.initWalletData();
326
+ this.setStatus(import_types.CheckoutStatus.OrderCreated);
327
+ this.setStep(import_types.CheckoutStep.PaymentMethod);
328
+ if (params.autoPayment) {
329
+ this.setStep(import_types.CheckoutStep.PaymentProcessing);
330
+ }
331
+ this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreated, {
332
+ order: paymentOrder,
333
+ timestamp: Date.now()
334
+ });
335
+ await this.updateStateAmountToRemaining();
336
+ console.log("[Checkout] 本地订单创建成功:", {
337
+ localOrderId,
338
+ uuid: paymentOrder.uuid,
339
+ totalAmount: amountInfo.totalAmount,
340
+ subTotal: amountInfo.subTotal,
341
+ taxAmount: amountInfo.taxAmount,
342
+ stateAmount: this.store.stateAmount
343
+ });
344
+ return paymentOrder;
345
+ } catch (error) {
346
+ await this.handleError(
347
+ error,
348
+ import_types.CheckoutErrorType.OrderCreationFailed
349
+ );
350
+ this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreationFailed, {
351
+ error: this.store.lastError,
352
+ timestamp: Date.now()
353
+ });
354
+ throw error;
355
+ }
356
+ }
357
+ /**
358
+ * 手动下单 (根据虚拟订单生成实际订单)
359
+ *
360
+ * 使用当前存储的本地订单数据调用 Order 模块创建真实订单
361
+ */
362
+ async placeOrderAsync(params = {}) {
363
+ var _a, _b;
364
+ this.logInfo("placeOrderAsync called", {
365
+ url: params.url,
366
+ autoReplaceOrderId: params.autoReplaceOrderId,
367
+ hasLocalOrderData: !!this.store.localOrderData,
368
+ hasCurrentOrder: !!this.store.currentOrder,
369
+ currentOrderId: (_a = this.store.currentOrder) == null ? void 0 : _a.order_id,
370
+ isOrderSynced: this.store.isOrderSynced
371
+ });
372
+ try {
373
+ if (!this.store.localOrderData) {
374
+ throw (0, import_utils.createCheckoutError)(
375
+ import_types.CheckoutErrorType.ValidationFailed,
376
+ "没有找到本地订单数据,请先调用 createLocalOrderAsync 创建虚拟订单"
377
+ );
378
+ }
379
+ if (!this.store.currentOrder) {
380
+ throw (0, import_utils.createCheckoutError)(
381
+ import_types.CheckoutErrorType.ValidationFailed,
382
+ "没有找到当前订单,请先创建虚拟订单"
383
+ );
384
+ }
385
+ console.log("[Checkout] 开始手动下单流程...");
386
+ this.setStatus(import_types.CheckoutStatus.CreatingOrder);
387
+ const orderData = {
388
+ cartItems: this.store.cartItems,
389
+ type: this.store.localOrderData.type,
390
+ platform: this.store.localOrderData.platform
391
+ };
392
+ const orderResponse = await this.order.submitOrder({
393
+ url: params.url,
394
+ // 可选的自定义 URL
395
+ query: orderData
396
+ });
397
+ const realOrderId = ((_b = orderResponse == null ? void 0 : orderResponse.data) == null ? void 0 : _b.order_id) || (orderResponse == null ? void 0 : orderResponse.order_id);
398
+ if (!realOrderId) {
399
+ throw (0, import_utils.createCheckoutError)(
400
+ import_types.CheckoutErrorType.OrderCreationFailed,
401
+ "订单创建成功但未返回订单ID"
402
+ );
403
+ }
404
+ console.log("[Checkout] 真实订单创建成功:", realOrderId);
405
+ if (params.autoReplaceOrderId !== false) {
406
+ console.log("[Checkout] 自动替换虚拟订单ID为真实订单ID...");
407
+ const updatedOrder = await this.replaceLocalOrderIdAsync(realOrderId);
408
+ if (updatedOrder) {
409
+ console.log("[Checkout] 订单ID替换成功:", {
410
+ oldId: this.store.currentOrder.order_id,
411
+ newId: realOrderId
412
+ });
413
+ }
414
+ }
415
+ this.setStatus(import_types.CheckoutStatus.OrderCreated);
416
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreated, {
417
+ order: this.store.currentOrder,
418
+ timestamp: Date.now()
419
+ });
420
+ this.store.isOrderSynced = true;
421
+ console.log("[Checkout] 手动下单流程完成");
422
+ return {
423
+ success: true,
424
+ orderId: realOrderId
425
+ };
426
+ } catch (error) {
427
+ let errorMessage = "下单失败";
428
+ if (error && typeof error === "object" && "message" in error) {
429
+ errorMessage = error.message;
430
+ } else if (error instanceof Error) {
431
+ errorMessage = error.message;
432
+ }
433
+ console.error("[Checkout] 手动下单失败:", errorMessage);
434
+ await this.handleError(
435
+ error,
436
+ import_types.CheckoutErrorType.OrderCreationFailed
437
+ );
438
+ return {
439
+ success: false,
440
+ error: errorMessage
441
+ };
442
+ }
443
+ }
444
+ /**
445
+ * 创建订单
446
+ */
447
+ async createOrderAsync(params) {
448
+ var _a;
449
+ try {
450
+ this.setStatus(import_types.CheckoutStatus.CreatingOrder);
451
+ const checkResult = this.order.checkBeforeSubmitOrder({
452
+ cartItems: params.cartItems,
453
+ type: "account"
454
+ // 默认使用 account 类型
455
+ });
456
+ if (!checkResult) {
457
+ throw (0, import_utils.createCheckoutError)(
458
+ import_types.CheckoutErrorType.ValidationFailed,
459
+ "购物车数据验证失败,请检查商品信息"
460
+ );
461
+ }
462
+ const orderResponse = await this.order.submitOrder({
463
+ query: {
464
+ cartItems: params.cartItems,
465
+ type: params.type || "appointment_booking",
466
+ platform: params.platform || "pc"
467
+ }
468
+ });
469
+ const paymentOrder = await this.payment.createPaymentOrderAsync({
470
+ order_id: ((_a = orderResponse == null ? void 0 : orderResponse.data) == null ? void 0 : _a.order_id) || `order_${Date.now()}`,
471
+ total_amount: (0, import_utils.calculateTotalAmount)(params.cartItems),
472
+ order_info: orderResponse == null ? void 0 : orderResponse.data
473
+ });
474
+ this.store.currentOrder = paymentOrder;
475
+ this.setStatus(import_types.CheckoutStatus.OrderCreated);
476
+ this.setStep(import_types.CheckoutStep.PaymentMethod);
477
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreated, {
478
+ order: paymentOrder,
479
+ timestamp: Date.now()
480
+ });
481
+ this.store.isOrderSynced = true;
482
+ await this.updateStateAmountToRemaining();
483
+ console.log("[Checkout] 订单创建成功:", paymentOrder.id);
484
+ return paymentOrder;
485
+ } catch (error) {
486
+ await this.handleError(
487
+ error,
488
+ import_types.CheckoutErrorType.OrderCreationFailed
489
+ );
490
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreationFailed, {
491
+ error: this.store.lastError,
492
+ timestamp: Date.now()
493
+ });
494
+ throw error;
495
+ }
496
+ }
497
+ /**
498
+ * 处理支付
499
+ */
500
+ async processPaymentAsync(params) {
501
+ try {
502
+ if (!this.store.currentOrder) {
503
+ throw (0, import_utils.createCheckoutError)(
504
+ import_types.CheckoutErrorType.ValidationFailed,
505
+ "未找到当前订单,请先创建订单"
506
+ );
507
+ }
508
+ this.setStatus(import_types.CheckoutStatus.ProcessingPayment);
509
+ this.setStep(import_types.CheckoutStep.PaymentProcessing);
510
+ const paymentMethod = this.store.paymentMethods.find(
511
+ (method) => method.code === params.paymentMethodCode
512
+ );
513
+ if (!paymentMethod) {
514
+ throw (0, import_utils.createCheckoutError)(
515
+ import_types.CheckoutErrorType.ValidationFailed,
516
+ `未找到支付方式: ${params.paymentMethodCode}`
517
+ );
518
+ }
519
+ const paymentItem = {
520
+ code: paymentMethod.code,
521
+ name: paymentMethod.name,
522
+ type: paymentMethod.type,
523
+ amount: String(params.amount),
524
+ id: paymentMethod.id
525
+ };
526
+ await this.payment.addPaymentItemAsync(
527
+ this.store.currentOrder.uuid,
528
+ paymentItem
529
+ );
530
+ const result = await this.payment.submitPayAsync(
531
+ this.store.currentOrder.uuid
532
+ );
533
+ await this.core.effects.emit(import_types.CheckoutHooks.OnPaymentStarted, {
534
+ orderUuid: this.store.currentOrder.uuid,
535
+ paymentMethodCode: params.paymentMethodCode,
536
+ amount: String(params.amount),
537
+ timestamp: Date.now()
538
+ });
539
+ if (result.status === "success") {
540
+ this.setStatus(import_types.CheckoutStatus.PaymentCompleted);
541
+ await this.updateStateAmountToRemaining();
542
+ await this.handlePaymentSuccess({
543
+ orderUuid: this.store.currentOrder.uuid,
544
+ timestamp: Date.now()
545
+ });
546
+ } else {
547
+ throw (0, import_utils.createCheckoutError)(
548
+ import_types.CheckoutErrorType.PaymentFailed,
549
+ "支付处理失败,请重试"
550
+ );
551
+ }
552
+ } catch (error) {
553
+ await this.handleError(error, import_types.CheckoutErrorType.PaymentFailed);
554
+ throw error;
555
+ }
556
+ }
557
+ /**
558
+ * 完成结账
559
+ */
560
+ async completeCheckoutAsync() {
561
+ try {
562
+ if (!this.store.currentOrder) {
563
+ throw (0, import_utils.createCheckoutError)(
564
+ import_types.CheckoutErrorType.ValidationFailed,
565
+ "未找到当前订单"
566
+ );
567
+ }
568
+ const order = await this.payment.getPaymentOrderByUuidAsync(
569
+ this.store.currentOrder.uuid
570
+ );
571
+ if (!order || order.payment_status !== import_types2.PaymentStatus.Finished) {
572
+ throw (0, import_utils.createCheckoutError)(
573
+ import_types.CheckoutErrorType.ValidationFailed,
574
+ "订单支付未完成,无法完成结账"
575
+ );
576
+ }
577
+ this.payment.wallet.clearAllCache();
578
+ this.setStatus(import_types.CheckoutStatus.Completed);
579
+ this.setStep(import_types.CheckoutStep.Complete);
580
+ await this.core.effects.emit(import_types.CheckoutHooks.OnCheckoutCompleted, {
581
+ orderId: order.id,
582
+ timestamp: Date.now()
583
+ });
584
+ console.log("[Checkout] 结账流程完成:", order.id);
585
+ await this.resetStoreStateAsync();
586
+ return {
587
+ success: true,
588
+ orderId: String(order.id)
589
+ };
590
+ } catch (error) {
591
+ await this.handleError(error, import_types.CheckoutErrorType.UnknownError);
592
+ return { success: false };
593
+ }
594
+ }
595
+ /**
596
+ * 取消结账
597
+ */
598
+ async cancelCheckoutAsync() {
599
+ try {
600
+ if (this.store.currentOrder) {
601
+ await this.payment.deletePaymentOrderAsync(
602
+ this.store.currentOrder.uuid
603
+ );
604
+ this.store.currentOrder = void 0;
605
+ }
606
+ this.store.localOrderData = void 0;
607
+ this.store.cartSummary = void 0;
608
+ this.payment.wallet.clearAllCache();
609
+ this.store.cartItems = [];
610
+ this.store.stateAmount = "0.00";
611
+ this.store.balanceDueAmount = "0.00";
612
+ this.store.isOrderSynced = false;
613
+ this.store.currentCustomer = void 0;
614
+ this.setStatus(import_types.CheckoutStatus.Cancelled);
615
+ await this.core.effects.emit(import_types.CheckoutHooks.OnCheckoutCancelled, {
616
+ timestamp: Date.now()
617
+ });
618
+ console.log("[Checkout] 结账流程已取消");
619
+ } catch (error) {
620
+ console.error("[Checkout] 取消结账失败:", error);
621
+ await this.handleError(error, import_types.CheckoutErrorType.UnknownError);
622
+ }
623
+ }
624
+ /**
625
+ * 获取结账状态
626
+ */
627
+ getCheckoutStatus() {
628
+ return {
629
+ status: this.store.status,
630
+ step: this.store.step,
631
+ progress: (0, import_utils.calculateProgress)(this.store.status, this.store.step),
632
+ message: this.getStatusMessage(),
633
+ error: this.store.lastError
634
+ };
635
+ }
636
+ /**
637
+ * 获取结账摘要
638
+ */
639
+ async getCheckoutSummaryAsync() {
640
+ var _a, _b;
641
+ const totalAmount = ((_a = this.store.currentOrder) == null ? void 0 : _a.total_amount) || "0.00";
642
+ const paidAmount = await this.calculatePaidAmountAsync();
643
+ const remainingAmount = await this.calculateRemainingAmountAsync();
644
+ return {
645
+ order: this.store.currentOrder,
646
+ totalAmount,
647
+ paidAmount,
648
+ remainingAmount,
649
+ paymentStatus: ((_b = this.store.currentOrder) == null ? void 0 : _b.payment_status) || import_types2.PaymentStatus.Processing,
650
+ availablePaymentMethods: this.store.paymentMethods
651
+ };
652
+ }
653
+ /**
654
+ * 获取可用支付方式
655
+ */
656
+ async getAvailablePaymentMethodsAsync() {
657
+ return await this.getPaymentMethodsAsync();
658
+ }
659
+ /**
660
+ * 刷新支付方式缓存
661
+ *
662
+ * 强制重新从服务器获取支付方式列表,更新本地缓存
663
+ */
664
+ async refreshPaymentMethodsAsync() {
665
+ console.log("[Checkout] 强制刷新支付方式缓存...");
666
+ try {
667
+ const methods = await this.payment.getPayMethodListAsync();
668
+ this.store.paymentMethods = methods;
669
+ console.log(
670
+ `[Checkout] 强制刷新完成,获取到 ${methods.length} 种支付方式`
671
+ );
672
+ return methods;
673
+ } catch (error) {
674
+ console.error("[Checkout] 强制刷新支付方式失败:", error);
675
+ return this.store.paymentMethods;
676
+ }
677
+ }
678
+ /**
679
+ * 获取订单原始数据
680
+ */
681
+ getOrderOriginalData() {
682
+ var _a;
683
+ return (_a = this.store.currentOrder) == null ? void 0 : _a.order_info;
684
+ }
685
+ /**
686
+ * 获取当前订单基础信息
687
+ *
688
+ * 返回当前订单的基础信息,包括订单状态、金额、支付状态等
689
+ */
690
+ getCurrentOrderInfo() {
691
+ try {
692
+ const { currentOrder, status, step, cartItems, localOrderData } = this.store;
693
+ if (!currentOrder) {
694
+ console.log("[Checkout] 当前没有活跃订单");
695
+ return null;
696
+ }
697
+ const orderInfo = currentOrder.order_info || {};
698
+ const createdAt = orderInfo.created_at || (/* @__PURE__ */ new Date()).toISOString();
699
+ const orderType = (localOrderData == null ? void 0 : localOrderData.type) || orderInfo.type || "virtual";
700
+ const platform = (localOrderData == null ? void 0 : localOrderData.platform) || orderInfo.platform || "pc";
701
+ const result = {
702
+ uuid: currentOrder.uuid,
703
+ orderId: currentOrder.order_id,
704
+ status,
705
+ step,
706
+ totalAmount: currentOrder.total_amount,
707
+ remainingAmount: currentOrder.expect_amount,
708
+ paymentStatus: currentOrder.payment_status,
709
+ isDeposit: Boolean(currentOrder.is_deposit),
710
+ depositAmount: currentOrder.deposit_amount,
711
+ orderType,
712
+ platform,
713
+ createdAt,
714
+ itemCount: cartItems.length,
715
+ hasLocalOrderData: Boolean(localOrderData)
716
+ };
717
+ console.log("[Checkout] 获取当前订单基础信息:", {
718
+ uuid: result.uuid,
719
+ orderId: result.orderId,
720
+ status: result.status,
721
+ totalAmount: result.totalAmount,
722
+ remainingAmount: result.remainingAmount
723
+ });
724
+ return result;
725
+ } catch (error) {
726
+ console.error("[Checkout] 获取当前订单基础信息失败:", error);
727
+ return null;
728
+ }
729
+ }
730
+ /**
731
+ * 获取当前订单的支付项
732
+ *
733
+ * 返回当前订单的所有支付项,包括活跃和已撤销的支付项
734
+ */
735
+ async getCurrentOrderPaymentItemsAsync() {
736
+ try {
737
+ const { currentOrder } = this.store;
738
+ if (!currentOrder) {
739
+ console.log("[Checkout] 当前没有活跃订单,无法获取支付项");
740
+ return [];
741
+ }
742
+ console.log("[Checkout] 获取当前订单支付项:", {
743
+ orderUuid: currentOrder.uuid,
744
+ orderId: currentOrder.order_id
745
+ });
746
+ const paymentItems = await this.payment.getPaymentItemsAsync(
747
+ currentOrder.uuid
748
+ );
749
+ console.log("[Checkout] 成功获取支付项:", {
750
+ orderUuid: currentOrder.uuid,
751
+ paymentItemCount: paymentItems.length,
752
+ activeItems: paymentItems.filter((item) => item.status !== "voided").length,
753
+ voidedItems: paymentItems.filter((item) => item.status === "voided").length,
754
+ totalPaidAmount: paymentItems.filter((item) => item.status !== "voided").reduce((sum, item) => sum + parseFloat(item.amount || "0"), 0).toFixed(2),
755
+ paymentMethods: paymentItems.map((item) => ({
756
+ uuid: item.uuid,
757
+ code: item.code,
758
+ amount: item.amount,
759
+ status: item.status,
760
+ voucher_id: item.voucher_id
761
+ }))
762
+ });
763
+ return paymentItems;
764
+ } catch (error) {
765
+ console.error("[Checkout] 获取当前订单支付项失败:", error);
766
+ return [];
767
+ }
768
+ }
769
+ /**
770
+ * 验证结账前置条件
771
+ */
772
+ async validateCheckoutAsync() {
773
+ const errors = [];
774
+ if (!this.store.cartItems || this.store.cartItems.length === 0) {
775
+ errors.push("购物车为空");
776
+ }
777
+ if (this.store.paymentMethods.length === 0) {
778
+ errors.push("无可用支付方式");
779
+ }
780
+ if (this.store.status === import_types.CheckoutStatus.Error) {
781
+ errors.push("结账流程存在错误");
782
+ }
783
+ return {
784
+ valid: errors.length === 0,
785
+ errors
786
+ };
787
+ }
788
+ /**
789
+ * 重试失败的操作
790
+ */
791
+ async retryFailedOperationAsync() {
792
+ try {
793
+ if (this.store.status === import_types.CheckoutStatus.Error && this.store.lastError) {
794
+ switch (this.store.lastError.type) {
795
+ case import_types.CheckoutErrorType.OrderCreationFailed:
796
+ if (this.store.cartItems.length > 0) {
797
+ await this.createOrderAsync({
798
+ cartItems: this.store.cartItems
799
+ });
800
+ }
801
+ break;
802
+ default:
803
+ console.warn(
804
+ "[Checkout] 无法重试此类型的错误:",
805
+ this.store.lastError.type
806
+ );
807
+ }
808
+ }
809
+ } catch (error) {
810
+ await this.handleError(error, import_types.CheckoutErrorType.UnknownError);
811
+ }
812
+ }
813
+ /**
814
+ * 设置当前步骤
815
+ */
816
+ setCurrentStep(step) {
817
+ const oldStep = this.store.step;
818
+ this.store.step = step;
819
+ this.core.effects.emit(import_types.CheckoutHooks.OnStepChanged, {
820
+ oldStep,
821
+ newStep: step,
822
+ timestamp: Date.now()
823
+ });
824
+ }
825
+ /**
826
+ * 获取订单模块
827
+ */
828
+ getOrderModule() {
829
+ return this.order;
830
+ }
831
+ /**
832
+ * 获取支付模块
833
+ */
834
+ getPaymentModule() {
835
+ return this.payment;
836
+ }
837
+ /**
838
+ * 替换本地订单ID为真实订单ID
839
+ *
840
+ * 当后端订单创建完成后,调用此方法将本地虚拟订单ID替换为真实订单ID
841
+ *
842
+ * @param newOrderId 后端返回的真实订单ID
843
+ * @returns 更新后的订单对象,如果当前没有订单则返回null
844
+ */
845
+ async replaceLocalOrderIdAsync(newOrderId) {
846
+ try {
847
+ if (!this.store.currentOrder) {
848
+ console.warn("[Checkout] 没有当前订单,无法替换订单ID");
849
+ return null;
850
+ }
851
+ const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(
852
+ this.store.currentOrder.uuid,
853
+ newOrderId
854
+ );
855
+ if (updatedOrder) {
856
+ this.store.currentOrder = updatedOrder;
857
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreated, {
858
+ order: updatedOrder,
859
+ timestamp: Date.now()
860
+ });
861
+ console.log("[Checkout] 本地订单ID替换成功:", {
862
+ uuid: updatedOrder.uuid,
863
+ newOrderId: updatedOrder.id
864
+ });
865
+ this.store.isOrderSynced = true;
866
+ await this.updateStateAmountToRemaining();
867
+ }
868
+ return updatedOrder;
869
+ } catch (error) {
870
+ console.error("[Checkout] 替换订单ID失败:", error);
871
+ await this.handleError(error, import_types.CheckoutErrorType.UnknownError);
872
+ return null;
873
+ }
874
+ }
875
+ /**
876
+ * 设置自定义支付金额
877
+ *
878
+ * 允许UI自定义本次支付的金额,通常用于部分支付或调整支付金额场景
879
+ *
880
+ * @param amount 自定义支付金额,必须是有效的数字字符串
881
+ */
882
+ async setStateAmountAsync(amount) {
883
+ try {
884
+ const numAmount = parseFloat(amount);
885
+ if (isNaN(numAmount) || numAmount < 0) {
886
+ throw new Error(`无效的支付金额: ${amount}`);
887
+ }
888
+ const oldAmount = this.store.stateAmount;
889
+ const formattedAmount = numAmount.toFixed(2);
890
+ if (oldAmount === formattedAmount) {
891
+ return;
892
+ }
893
+ this.logInfo("[Checkout] 设置自定义支付金额:", {
894
+ oldAmount,
895
+ newAmount: formattedAmount
896
+ });
897
+ this.store.stateAmount = formattedAmount;
898
+ await this.core.effects.emit(import_types.CheckoutHooks.OnStateAmountChanged, {
899
+ oldAmount,
900
+ newAmount: formattedAmount,
901
+ timestamp: Date.now()
902
+ });
903
+ console.log("[Checkout] 自定义支付金额已更新:", {
904
+ oldAmount,
905
+ newAmount: formattedAmount
906
+ });
907
+ } catch (error) {
908
+ const errorMessage = error instanceof Error ? error.message : "设置支付金额失败";
909
+ console.error("[Checkout] 设置自定义支付金额失败:", errorMessage);
910
+ await this.handleError(
911
+ new Error(errorMessage),
912
+ import_types.CheckoutErrorType.ValidationFailed
913
+ );
914
+ throw error;
915
+ }
916
+ }
917
+ /**
918
+ * 获取当前自定义支付金额
919
+ *
920
+ * @returns 当前设置的自定义支付金额
921
+ */
922
+ getStateAmount() {
923
+ return this.store.stateAmount;
924
+ }
925
+ /**
926
+ * 获取系统计算的待付金额(只读)
927
+ *
928
+ * 此方法返回系统内部计算的实际待付金额,不允许外部修改
929
+ *
930
+ * @returns 当前系统计算的待付金额
931
+ */
932
+ getBalanceDueAmount() {
933
+ return this.store.balanceDueAmount;
934
+ }
935
+ /**
936
+ * 刷新 stateAmount 为当前剩余未支付金额
937
+ *
938
+ * UI 可以调用此方法来主动刷新支付金额状态
939
+ */
940
+ async refreshStateAmountAsync() {
941
+ await this.updateStateAmountToRemaining();
942
+ }
943
+ /**
944
+ * 获取购物车小计数据
945
+ *
946
+ * 返回当前结账流程中的购物车小计项数据,包含各种费用明细
947
+ *
948
+ * @returns 购物车小计数据数组,如果没有则返回 null
949
+ */
950
+ getCartSummary() {
951
+ if (!this.store.cartSummary || this.store.cartSummary.length === 0) {
952
+ console.warn("[Checkout] 没有可用的购物车小计数据");
953
+ return null;
954
+ }
955
+ console.log("[Checkout] 获取购物车小计数据:", {
956
+ itemCount: this.store.cartSummary.length,
957
+ items: this.store.cartSummary.map((item) => ({
958
+ key: item.key,
959
+ value: item.value,
960
+ label: item.label
961
+ }))
962
+ });
963
+ return [...this.store.cartSummary];
964
+ }
965
+ /**
966
+ * 获取提取的金额详细信息
967
+ *
968
+ * 从当前的购物车小计数据中提取结构化的金额信息
969
+ *
970
+ * @returns 提取的金额信息对象,如果没有小计数据则返回 null
971
+ */
972
+ getExtractedAmountInfo() {
973
+ if (!this.store.cartSummary || this.store.cartSummary.length === 0) {
974
+ console.warn("[Checkout] 没有可用的购物车小计数据,无法提取金额信息");
975
+ return null;
976
+ }
977
+ const extractedInfo = (0, import_utils.extractAmountFromCartSummary)(
978
+ this.store.cartSummary
979
+ );
980
+ console.log("[Checkout] 获取提取的金额信息:", extractedInfo);
981
+ return extractedInfo;
982
+ }
983
+ /**
984
+ * 获取支付方式列表
985
+ *
986
+ * 优先使用 store 中的缓存数据,避免重复接口调用。
987
+ * 如果 store 中没有数据,则调用 Payment 模块的方法获取。
988
+ *
989
+ * @returns 支付方式列表
990
+ */
991
+ async getPaymentMethodsAsync() {
992
+ if (this.store.paymentMethods && this.store.paymentMethods.length > 0) {
993
+ console.log(
994
+ `[Checkout] 使用缓存的支付方式数据,共 ${this.store.paymentMethods.length} 种`
995
+ );
996
+ return this.store.paymentMethods;
997
+ }
998
+ console.log("[Checkout] store 中无缓存,从 Payment 模块获取支付方式...");
999
+ try {
1000
+ const methods = await this.payment.getPayMethodListAsync();
1001
+ this.store.paymentMethods = methods;
1002
+ console.log(
1003
+ `[Checkout] 从 Payment 模块获取到 ${methods.length} 种支付方式,已更新缓存`
1004
+ );
1005
+ return methods;
1006
+ } catch (error) {
1007
+ console.error("[Checkout] 获取支付方式失败:", error);
1008
+ return [];
1009
+ }
1010
+ }
1011
+ /**
1012
+ * 为当前订单添加支付项
1013
+ *
1014
+ * 向当前活跃订单添加一个支付项,支付项包含支付方式信息和金额
1015
+ *
1016
+ * @param paymentItem 支付项数据
1017
+ * @throws 当前没有活跃订单时抛出错误
1018
+ */
1019
+ async addPaymentItemAsync(paymentItem) {
1020
+ var _a, _b, _c, _d, _e, _f;
1021
+ this.logInfo("addPaymentItemAsync called", {
1022
+ paymentCode: paymentItem.code,
1023
+ paymentType: paymentItem.type,
1024
+ amount: paymentItem.amount,
1025
+ voucherId: paymentItem.voucher_id,
1026
+ serviceCharge: paymentItem.service_charge,
1027
+ roundingAmount: paymentItem.rounding_amount,
1028
+ hasMetadata: !!paymentItem.metadata,
1029
+ hasCurrentOrder: !!this.store.currentOrder,
1030
+ currentOrderId: (_a = this.store.currentOrder) == null ? void 0 : _a.order_id,
1031
+ isDepositOrder: (_b = this.store.currentOrder) == null ? void 0 : _b.is_deposit
1032
+ });
1033
+ try {
1034
+ if (!this.store.currentOrder) {
1035
+ throw (0, import_utils.createCheckoutError)(
1036
+ import_types.CheckoutErrorType.ValidationFailed,
1037
+ "未找到当前订单,无法添加支付项"
1038
+ );
1039
+ }
1040
+ const orderPaymentType = this.store.currentOrder.is_deposit === 1 ? "deposit" : "normal";
1041
+ const processedPaymentItem = await this.processCashPaymentItem(paymentItem);
1042
+ const metadata = {
1043
+ ...processedPaymentItem.metadata,
1044
+ rounding_rule: this.otherParams.order_rounding_setting,
1045
+ shop_wallet_pass_id: this.otherParams.shop_wallet_pass_id
1046
+ };
1047
+ const paymentItemWithType = {
1048
+ ...processedPaymentItem,
1049
+ order_payment_type: orderPaymentType,
1050
+ metadata
1051
+ };
1052
+ console.log("[Checkout] 为当前订单添加支付项:", {
1053
+ orderUuid: this.store.currentOrder.uuid,
1054
+ paymentItem: {
1055
+ code: paymentItemWithType.code,
1056
+ name: paymentItemWithType.name,
1057
+ type: paymentItemWithType.type,
1058
+ amount: paymentItemWithType.amount,
1059
+ service_charge: paymentItemWithType.service_charge,
1060
+ rounding_amount: paymentItemWithType.rounding_amount,
1061
+ voucher_id: paymentItemWithType.voucher_id,
1062
+ order_payment_type: paymentItemWithType.order_payment_type,
1063
+ metadata: paymentItemWithType.metadata
1064
+ },
1065
+ orderDepositStatus: this.store.currentOrder.is_deposit,
1066
+ calculatedOrderPaymentType: orderPaymentType,
1067
+ // 现金支付找零详情
1068
+ isCashPayment: this.isCashPayment(paymentItem.code, paymentItem.type),
1069
+ originalAmount: paymentItem.amount,
1070
+ processedAmount: paymentItemWithType.amount,
1071
+ actualPaidAmount: (_c = paymentItemWithType.metadata) == null ? void 0 : _c.actual_paid_amount,
1072
+ changeGivenAmount: (_d = paymentItemWithType.metadata) == null ? void 0 : _d.change_given_amount
1073
+ });
1074
+ await this.payment.addPaymentItemAsync(
1075
+ this.store.currentOrder.uuid,
1076
+ paymentItemWithType
1077
+ );
1078
+ console.log("[Checkout] 支付项添加成功");
1079
+ const isEftposPayment = ((_e = paymentItem.type) == null ? void 0 : _e.toLowerCase()) === "eftpos" || ((_f = paymentItem.code) == null ? void 0 : _f.toUpperCase().includes("EFTPOS"));
1080
+ console.log("[Checkout] EFTPOS 支付检查:", {
1081
+ paymentCode: paymentItem.code,
1082
+ paymentType: paymentItem.type,
1083
+ isEftposPayment,
1084
+ currentOrderSynced: this.store.isOrderSynced
1085
+ });
1086
+ if (isEftposPayment) {
1087
+ console.log("[Checkout] 检测到 EFTPOS 支付,立即同步订单到后端...");
1088
+ try {
1089
+ const syncResult = await this.syncOrderToBackendWithReturn(true);
1090
+ console.log("[Checkout] EFTPOS 支付后订单同步完成 (已标记为手动同步):", {
1091
+ orderId: syncResult.orderId,
1092
+ isOrderSynced: this.store.isOrderSynced,
1093
+ backendResponse: syncResult.response
1094
+ });
1095
+ } catch (error) {
1096
+ console.error("[Checkout] EFTPOS 支付后订单同步失败:", error);
1097
+ await this.handleError(
1098
+ new Error(`EFTPOS 支付后订单同步失败: ${error instanceof Error ? error.message : String(error)}`),
1099
+ import_types.CheckoutErrorType.OrderCreationFailed
1100
+ );
1101
+ }
1102
+ }
1103
+ await this.updateStateAmountToRemaining();
1104
+ await this.core.effects.emit(import_types.CheckoutHooks.OnPaymentStarted, {
1105
+ orderUuid: this.store.currentOrder.uuid,
1106
+ paymentMethodCode: paymentItem.code,
1107
+ amount: String(paymentItem.amount),
1108
+ timestamp: Date.now()
1109
+ });
1110
+ } catch (error) {
1111
+ console.error("[Checkout] 添加支付项失败:", error);
1112
+ await this.handleError(error, import_types.CheckoutErrorType.PaymentFailed);
1113
+ throw error;
1114
+ }
1115
+ }
1116
+ /**
1117
+ * 删除当前订单的支付项
1118
+ *
1119
+ * 从当前活跃订单中删除指定的支付项,支付项将被标记为已撤销状态
1120
+ *
1121
+ * @param paymentUuid 要删除的支付项UUID
1122
+ * @throws 当前没有活跃订单时抛出错误
1123
+ * @throws 支付项不存在时抛出错误
1124
+ */
1125
+ async deletePaymentItemAsync(paymentUuid) {
1126
+ try {
1127
+ if (!this.store.currentOrder) {
1128
+ throw (0, import_utils.createCheckoutError)(
1129
+ import_types.CheckoutErrorType.ValidationFailed,
1130
+ "当前没有活跃订单,无法删除支付项"
1131
+ );
1132
+ }
1133
+ console.log("[Checkout] 开始删除支付项:", {
1134
+ orderUuid: this.store.currentOrder.uuid,
1135
+ paymentUuid
1136
+ });
1137
+ const currentPayments = await this.payment.getPaymentItemsAsync(
1138
+ this.store.currentOrder.uuid,
1139
+ true
1140
+ // 包括已撤销的支付项,因为我们需要验证是否存在
1141
+ );
1142
+ const paymentItem = currentPayments.find((p) => p.uuid === paymentUuid);
1143
+ if (!paymentItem) {
1144
+ throw (0, import_utils.createCheckoutError)(
1145
+ import_types.CheckoutErrorType.ValidationFailed,
1146
+ `支付项不存在: ${paymentUuid}`
1147
+ );
1148
+ }
1149
+ console.log("[Checkout] 找到要删除的支付项:", {
1150
+ uuid: paymentItem.uuid,
1151
+ code: paymentItem.code,
1152
+ amount: paymentItem.amount,
1153
+ status: paymentItem.status
1154
+ });
1155
+ await this.payment.deletePaymentAsync(
1156
+ this.store.currentOrder.uuid,
1157
+ paymentUuid
1158
+ );
1159
+ console.log("[Checkout] Payment模块删除完成");
1160
+ const currentOrderId = this.store.currentOrder.order_id;
1161
+ const isCurrentOrderReal = currentOrderId && !(0, import_utils.isVirtualOrderId)(currentOrderId);
1162
+ const updatedOrder = await this.payment.getPaymentOrderByUuidAsync(
1163
+ this.store.currentOrder.uuid
1164
+ );
1165
+ if (updatedOrder) {
1166
+ if (isCurrentOrderReal && (0, import_utils.isVirtualOrderId)(updatedOrder.order_id)) {
1167
+ console.warn(
1168
+ "[Checkout] deletePaymentItemAsync: 检测到订单ID回退,保护真实订单ID:",
1169
+ {
1170
+ currentRealId: currentOrderId,
1171
+ retrievedVirtualId: updatedOrder.order_id
1172
+ }
1173
+ );
1174
+ updatedOrder.order_id = currentOrderId;
1175
+ }
1176
+ this.store.currentOrder = updatedOrder;
1177
+ console.log(
1178
+ "[Checkout] 订单数据已同步,当前支付项数量:",
1179
+ updatedOrder.payment.length
1180
+ );
1181
+ }
1182
+ await this.updateStateAmountToRemaining();
1183
+ await this.core.effects.emit(import_types.CheckoutHooks.OnPaymentStarted, {
1184
+ orderUuid: this.store.currentOrder.uuid,
1185
+ paymentMethodCode: paymentItem.code,
1186
+ amount: `-${paymentItem.amount}`,
1187
+ // 负数表示删除
1188
+ timestamp: Date.now()
1189
+ });
1190
+ console.log("[Checkout] 支付项删除成功");
1191
+ } catch (error) {
1192
+ console.error("[Checkout] 删除支付项失败:", error);
1193
+ await this.handleError(error, import_types.CheckoutErrorType.PaymentFailed);
1194
+ throw error;
1195
+ }
1196
+ }
1197
+ /**
1198
+ * 批量更新当前订单的代金券支付项(覆盖更新)
1199
+ *
1200
+ * 删除所有现有的代金券支付项,然后添加新的代金券支付项。
1201
+ * 这是一个覆盖式更新操作,确保代金券支付项的一致性。
1202
+ *
1203
+ * @param voucherPaymentItems 新的代金券支付项列表,每个都必须包含 voucher_id
1204
+ * @throws 当前没有活跃订单时抛出错误
1205
+ * @throws 支付项缺少 voucher_id 时抛出错误
1206
+ */
1207
+ async updateVoucherPaymentItemsAsync(voucherPaymentItems) {
1208
+ try {
1209
+ if (!this.store.currentOrder) {
1210
+ throw (0, import_utils.createCheckoutError)(
1211
+ import_types.CheckoutErrorType.ValidationFailed,
1212
+ "当前没有活跃订单,无法更新代金券支付项"
1213
+ );
1214
+ }
1215
+ console.log("[Checkout] 开始批量更新代金券支付项:", {
1216
+ orderUuid: this.store.currentOrder.uuid,
1217
+ newVoucherCount: voucherPaymentItems.length,
1218
+ voucherPaymentItems
1219
+ });
1220
+ const orderPaymentType = this.store.currentOrder.is_deposit === 1 ? "deposit" : "normal";
1221
+ const voucherPaymentItemsWithType = voucherPaymentItems.map((item) => {
1222
+ if (!item.voucher_id) {
1223
+ throw (0, import_utils.createCheckoutError)(
1224
+ import_types.CheckoutErrorType.ValidationFailed,
1225
+ `代金券支付项缺少 voucher_id: ${JSON.stringify(item)}`
1226
+ );
1227
+ }
1228
+ const metadata = {
1229
+ ...item.metadata,
1230
+ rounding_rule: this.otherParams.order_rounding_setting,
1231
+ shop_wallet_pass_id: this.otherParams.shop_wallet_pass_id
1232
+ };
1233
+ return {
1234
+ ...item,
1235
+ order_payment_type: orderPaymentType,
1236
+ metadata
1237
+ };
1238
+ });
1239
+ console.log("[Checkout] 代金券支付项订单支付类型设置:", {
1240
+ orderDepositStatus: this.store.currentOrder.is_deposit,
1241
+ calculatedOrderPaymentType: orderPaymentType,
1242
+ itemsCount: voucherPaymentItemsWithType.length
1243
+ });
1244
+ await this.payment.updateVoucherPaymentItemsAsync(
1245
+ this.store.currentOrder.uuid,
1246
+ voucherPaymentItemsWithType
1247
+ );
1248
+ console.log("[Checkout] Payment模块批量更新完成");
1249
+ const currentOrderId = this.store.currentOrder.order_id;
1250
+ const isCurrentOrderReal = currentOrderId && !(0, import_utils.isVirtualOrderId)(currentOrderId);
1251
+ const updatedOrder = await this.payment.getPaymentOrderByUuidAsync(
1252
+ this.store.currentOrder.uuid
1253
+ );
1254
+ if (updatedOrder) {
1255
+ if (isCurrentOrderReal && (0, import_utils.isVirtualOrderId)(updatedOrder.order_id)) {
1256
+ console.warn(
1257
+ "[Checkout] updateVoucherPaymentItemsAsync: 检测到订单ID回退,保护真实订单ID:",
1258
+ {
1259
+ currentRealId: currentOrderId,
1260
+ retrievedVirtualId: updatedOrder.order_id
1261
+ }
1262
+ );
1263
+ updatedOrder.order_id = currentOrderId;
1264
+ }
1265
+ this.store.currentOrder = updatedOrder;
1266
+ console.log(
1267
+ "[Checkout] 订单数据已同步,当前支付项数量:",
1268
+ updatedOrder.payment.length
1269
+ );
1270
+ const voucherItems = updatedOrder.payment.filter(
1271
+ (payment) => payment.voucher_id && payment.status !== "voided"
1272
+ );
1273
+ console.log("[Checkout] 更新后的代金券支付项:", {
1274
+ voucherCount: voucherItems.length,
1275
+ items: voucherItems.map((item) => ({
1276
+ uuid: item.uuid,
1277
+ code: item.code,
1278
+ amount: item.amount,
1279
+ voucher_id: item.voucher_id
1280
+ }))
1281
+ });
1282
+ }
1283
+ await this.updateStateAmountToRemaining();
1284
+ await this.core.effects.emit(import_types.CheckoutHooks.OnPaymentStarted, {
1285
+ orderUuid: this.store.currentOrder.uuid,
1286
+ paymentMethodCode: "VOUCHER_BATCH",
1287
+ amount: voucherPaymentItems.reduce((sum, item) => sum + parseFloat(String(item.amount)), 0).toFixed(2),
1288
+ timestamp: Date.now()
1289
+ });
1290
+ console.log("[Checkout] 代金券支付项批量更新成功");
1291
+ } catch (error) {
1292
+ console.error("[Checkout] 批量更新代金券支付项失败:", error);
1293
+ await this.handleError(error, import_types.CheckoutErrorType.PaymentFailed);
1294
+ throw error;
1295
+ }
1296
+ }
1297
+ /**
1298
+ * 修改当前订单的定金状态
1299
+ *
1300
+ * 更新当前订单的 is_deposit 字段,用于标识订单是否为定金订单
1301
+ *
1302
+ * @param isDeposit 定金状态 (1: 定金订单, 0: 全款订单)
1303
+ * @throws 当前没有活跃订单时抛出错误
1304
+ */
1305
+ async updateOrderDepositStatusAsync(isDeposit) {
1306
+ try {
1307
+ if (isDeposit !== 0 && isDeposit !== 1) {
1308
+ throw (0, import_utils.createCheckoutError)(
1309
+ import_types.CheckoutErrorType.ValidationFailed,
1310
+ "isDeposit 参数只能是 0(全款订单)或 1(定金订单)"
1311
+ );
1312
+ }
1313
+ if (!this.store.currentOrder) {
1314
+ throw (0, import_utils.createCheckoutError)(
1315
+ import_types.CheckoutErrorType.ValidationFailed,
1316
+ "未找到当前订单,无法修改定金状态"
1317
+ );
1318
+ }
1319
+ const newDepositValue = isDeposit;
1320
+ const oldDepositValue = this.store.currentOrder.is_deposit;
1321
+ if (oldDepositValue === newDepositValue) {
1322
+ console.log("[Checkout] 定金状态无变化,跳过更新");
1323
+ return;
1324
+ }
1325
+ console.log("[Checkout] 更新订单定金状态:", {
1326
+ orderUuid: this.store.currentOrder.uuid,
1327
+ orderId: this.store.currentOrder.order_id,
1328
+ oldIsDeposit: oldDepositValue,
1329
+ newIsDeposit: newDepositValue
1330
+ });
1331
+ const updateParams = {
1332
+ is_deposit: newDepositValue
1333
+ };
1334
+ if (isDeposit === 0 && this.store.currentOrder.deposit_amount !== "0.00") {
1335
+ updateParams.deposit_amount = "0.00";
1336
+ console.log("[Checkout] 订单从定金改为全款,清空定金金额");
1337
+ }
1338
+ await this.payment.updateOrderAsync(
1339
+ this.store.currentOrder.uuid,
1340
+ updateParams
1341
+ );
1342
+ this.store.currentOrder = {
1343
+ ...this.store.currentOrder,
1344
+ ...updateParams
1345
+ };
1346
+ if (this.store.localOrderData) {
1347
+ this.store.localOrderData.is_deposit = newDepositValue;
1348
+ }
1349
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCreated, {
1350
+ order: this.store.currentOrder,
1351
+ timestamp: Date.now()
1352
+ });
1353
+ console.log("[Checkout] 订单定金状态更新成功:", {
1354
+ isDeposit: newDepositValue,
1355
+ depositAmount: this.store.currentOrder.deposit_amount
1356
+ });
1357
+ } catch (error) {
1358
+ console.error("[Checkout] 更新订单定金状态失败:", error);
1359
+ await this.handleError(
1360
+ error,
1361
+ import_types.CheckoutErrorType.ValidationFailed
1362
+ );
1363
+ throw error;
1364
+ }
1365
+ }
1366
+ /**
1367
+ * 更新当前订单的客户信息
1368
+ *
1369
+ * 更新当前订单关联的客户信息,用于标识订单的所属客户
1370
+ *
1371
+ * @param customer 客户信息 (customer_id 和/或 customer_name)
1372
+ * @throws 当前没有活跃订单时抛出错误
1373
+ */
1374
+ async updateOrderCustomerAsync(customer) {
1375
+ try {
1376
+ if (!this.store.currentOrder) {
1377
+ throw (0, import_utils.createCheckoutError)(
1378
+ import_types.CheckoutErrorType.ValidationFailed,
1379
+ "未找到当前订单,无法更新客户信息"
1380
+ );
1381
+ }
1382
+ console.log("[Checkout] 更新订单客户信息:", {
1383
+ orderUuid: this.store.currentOrder.uuid,
1384
+ oldCustomer: this.store.currentCustomer,
1385
+ newCustomer: customer
1386
+ });
1387
+ this.store.currentCustomer = {
1388
+ customer_id: customer.customer_id,
1389
+ customer_name: customer.customer_name
1390
+ };
1391
+ if (this.store.localOrderData) {
1392
+ this.store.localOrderData.customer_id = customer.customer_id;
1393
+ this.store.localOrderData.customer_name = customer.customer_name;
1394
+ }
1395
+ console.log(
1396
+ "[Checkout] 订单客户信息更新成功:",
1397
+ this.store.currentCustomer
1398
+ );
1399
+ } catch (error) {
1400
+ console.error("[Checkout] 更新订单客户信息失败:", error);
1401
+ await this.handleError(
1402
+ error,
1403
+ import_types.CheckoutErrorType.ValidationFailed
1404
+ );
1405
+ throw error;
1406
+ }
1407
+ }
1408
+ /**
1409
+ * 获取当前订单的客户信息
1410
+ *
1411
+ * @returns 当前客户信息,如果没有则返回 null
1412
+ */
1413
+ getCurrentCustomer() {
1414
+ return this.store.currentCustomer || null;
1415
+ }
1416
+ /**
1417
+ * 检查订单是否需要手动同步(异步版本)
1418
+ *
1419
+ * 返回订单是否为纯代金券支付且待付金额<=0但未同步的状态
1420
+ * 从 Payment 模块获取最新的支付项数据
1421
+ */
1422
+ async needsManualSyncAsync() {
1423
+ try {
1424
+ if (!this.store.currentOrder || this.store.isOrderSynced) {
1425
+ return false;
1426
+ }
1427
+ const remainingAmount = await this.calculateRemainingAmountAsync();
1428
+ const remainingValue = new import_decimal.default(remainingAmount);
1429
+ if (remainingValue.gt(0)) {
1430
+ return false;
1431
+ }
1432
+ const currentPayments = await this.payment.getPaymentItemsAsync(
1433
+ this.store.currentOrder.uuid,
1434
+ false
1435
+ // 不包括已撤销的支付项
1436
+ );
1437
+ const allPaymentsHaveVoucherId = currentPayments.length > 0 && currentPayments.every(
1438
+ (item) => item.status !== "voided" && item.voucher_id
1439
+ );
1440
+ console.log("[Checkout] needsManualSyncAsync 检查结果:", {
1441
+ orderUuid: this.store.currentOrder.uuid,
1442
+ isOrderSynced: this.store.isOrderSynced,
1443
+ remainingAmount,
1444
+ hasPayments: currentPayments.length > 0,
1445
+ allPaymentsHaveVoucherId,
1446
+ needsManualSync: allPaymentsHaveVoucherId,
1447
+ paymentItems: currentPayments.map((p) => ({
1448
+ code: p.code,
1449
+ amount: p.amount,
1450
+ status: p.status,
1451
+ hasVoucherId: !!p.voucher_id
1452
+ }))
1453
+ });
1454
+ return allPaymentsHaveVoucherId;
1455
+ } catch (error) {
1456
+ console.error("[Checkout] needsManualSyncAsync 检查失败:", error);
1457
+ return false;
1458
+ }
1459
+ }
1460
+ /**
1461
+ * 手动同步订单到后端
1462
+ *
1463
+ * 用于强制同步订单到后端,特别适用于纯代金券支付完成的订单
1464
+ */
1465
+ async manualSyncOrderAsync() {
1466
+ var _a, _b, _c, _d;
1467
+ this.logInfo("manualSyncOrderAsync called", {
1468
+ hasCurrentOrder: !!this.store.currentOrder,
1469
+ currentOrderId: (_a = this.store.currentOrder) == null ? void 0 : _a.order_id,
1470
+ orderUuid: (_b = this.store.currentOrder) == null ? void 0 : _b.uuid,
1471
+ totalAmount: (_c = this.store.currentOrder) == null ? void 0 : _c.total_amount,
1472
+ isOrderSynced: this.store.isOrderSynced,
1473
+ isVirtualOrderId: this.store.currentOrder ? (0, import_utils.isVirtualOrderId)(this.store.currentOrder.order_id) : false
1474
+ });
1475
+ try {
1476
+ if (!this.store.currentOrder) {
1477
+ return {
1478
+ success: false,
1479
+ message: "当前没有活跃订单,无法同步"
1480
+ };
1481
+ }
1482
+ const orderUuid = this.store.currentOrder.uuid;
1483
+ const oldOrderId = this.store.currentOrder.order_id;
1484
+ if (this.store.isOrderSynced) {
1485
+ console.log("[Checkout] 订单已同步过,将执行更新操作");
1486
+ }
1487
+ console.log("[Checkout] 开始手动同步订单到后端:", {
1488
+ orderUuid,
1489
+ orderId: oldOrderId,
1490
+ totalAmount: this.store.currentOrder.total_amount,
1491
+ remainingAmount: await this.calculateRemainingAmountAsync()
1492
+ });
1493
+ const syncResult = await this.syncOrderToBackendWithReturn(true);
1494
+ console.log("[Checkout] 手动同步订单完成:", {
1495
+ orderUuid,
1496
+ syncResult,
1497
+ oldOrderId,
1498
+ realOrderId: syncResult.orderId,
1499
+ isOrderSynced: this.store.isOrderSynced
1500
+ });
1501
+ const finalOrderId = this.store.currentOrder.order_id;
1502
+ const finalIsVirtual = (0, import_utils.isVirtualOrderId)(finalOrderId);
1503
+ console.log("[Checkout] manualSyncOrderAsync 最终状态验证:", {
1504
+ returnedOrderId: syncResult.orderId,
1505
+ storedOrderId: finalOrderId,
1506
+ storedIdIsVirtual: finalIsVirtual,
1507
+ isConsistent: syncResult.orderId === finalOrderId,
1508
+ syncStatus: this.store.isOrderSynced
1509
+ });
1510
+ if (finalIsVirtual) {
1511
+ console.error("[Checkout] 严重警告:手动同步完成后订单ID仍为虚拟ID!");
1512
+ }
1513
+ if (syncResult.orderId !== finalOrderId) {
1514
+ console.error(
1515
+ "[Checkout] 严重警告:返回的订单ID与存储的订单ID不一致!"
1516
+ );
1517
+ }
1518
+ return syncResult;
1519
+ } catch (error) {
1520
+ console.error("[Checkout] 手动同步订单失败:", error);
1521
+ const errorMessage = error instanceof Error ? error.message : "同步失败";
1522
+ return {
1523
+ success: false,
1524
+ message: `订单同步失败: ${errorMessage}`,
1525
+ orderUuid: (_d = this.store.currentOrder) == null ? void 0 : _d.uuid
1526
+ };
1527
+ }
1528
+ }
1529
+ /**
1530
+ * 获取当前订单备注
1531
+ *
1532
+ * @returns 当前订单的备注内容,如果没有则返回空字符串
1533
+ */
1534
+ getOrderNote() {
1535
+ if (!this.store.localOrderData) {
1536
+ console.log("[Checkout] 没有本地订单数据,无法获取备注");
1537
+ return "";
1538
+ }
1539
+ return this.store.localOrderData.shop_note || "";
1540
+ }
1541
+ /**
1542
+ * 获取当前订单ID
1543
+ *
1544
+ * @returns 当前订单的ID,如果没有订单则返回null
1545
+ */
1546
+ getCurrentOrderId() {
1547
+ if (!this.store.currentOrder) {
1548
+ return null;
1549
+ }
1550
+ return this.store.currentOrder.order_id;
1551
+ }
1552
+ /**
1553
+ * 获取当前订单是否已同步到后端
1554
+ *
1555
+ * @returns 当前订单是否已同步状态,如果没有订单则返回false
1556
+ */
1557
+ isCurrentOrderSynced() {
1558
+ if (!this.store.currentOrder) {
1559
+ console.log("[Checkout] 没有当前订单,同步状态为false");
1560
+ return false;
1561
+ }
1562
+ const syncStatus = this.store.isOrderSynced;
1563
+ console.log("[Checkout] 当前订单同步状态:", {
1564
+ orderUuid: this.store.currentOrder.uuid,
1565
+ orderId: this.store.currentOrder.order_id,
1566
+ isOrderSynced: syncStatus
1567
+ });
1568
+ return syncStatus;
1569
+ }
1570
+ /**
1571
+ * 取消当前本地订单
1572
+ *
1573
+ * 只能取消未同步到后端的本地订单,如果订单已同步则不能取消
1574
+ *
1575
+ * @param cancelReason 取消原因(可选)
1576
+ * @returns 取消结果
1577
+ */
1578
+ async cancelCurrentOrderAsync(cancelReason) {
1579
+ var _a, _b;
1580
+ try {
1581
+ console.log("[Checkout] 开始取消当前本地订单:", {
1582
+ hasCurrentOrder: !!this.store.currentOrder,
1583
+ orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid,
1584
+ orderId: (_b = this.store.currentOrder) == null ? void 0 : _b.order_id,
1585
+ isOrderSynced: this.store.isOrderSynced,
1586
+ cancelReason
1587
+ });
1588
+ if (!this.store.currentOrder) {
1589
+ console.log("[Checkout] 没有当前订单,无需取消");
1590
+ return {
1591
+ success: false,
1592
+ message: "没有当前订单可取消"
1593
+ };
1594
+ }
1595
+ const currentOrderUuid = this.store.currentOrder.uuid;
1596
+ const currentOrderId = this.store.currentOrder.order_id;
1597
+ const isOrderSynced = this.store.isOrderSynced;
1598
+ if (isOrderSynced) {
1599
+ console.log("[Checkout] 订单已同步到后端,不能取消:", {
1600
+ orderId: currentOrderId,
1601
+ orderUuid: currentOrderUuid
1602
+ });
1603
+ return {
1604
+ success: false,
1605
+ message: "订单已同步到后端,无法取消",
1606
+ orderId: currentOrderId
1607
+ };
1608
+ }
1609
+ console.log("[Checkout] 订单尚未同步,可以取消");
1610
+ try {
1611
+ console.log("[Checkout] 删除本地订单数据");
1612
+ await this.payment.deletePaymentOrderAsync(currentOrderUuid);
1613
+ console.log("[Checkout] 本地订单数据删除成功");
1614
+ } catch (error) {
1615
+ console.warn("[Checkout] 删除本地订单数据失败,但继续执行:", error);
1616
+ }
1617
+ console.log("[Checkout] 清理订单相关状态");
1618
+ this.store.currentOrder = void 0;
1619
+ this.store.localOrderData = void 0;
1620
+ this.store.stateAmount = "0.00";
1621
+ this.store.balanceDueAmount = "0.00";
1622
+ this.store.isOrderSynced = false;
1623
+ this.store.currentCustomer = void 0;
1624
+ this.payment.wallet.clearAllCache();
1625
+ console.log("[Checkout] 订单状态清理完成,currentOrder已释放");
1626
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCancelled, {
1627
+ orderUuid: currentOrderUuid,
1628
+ orderId: currentOrderId,
1629
+ cancelReason,
1630
+ wasSynced: false,
1631
+ // 只有未同步订单可以被取消
1632
+ timestamp: Date.now()
1633
+ });
1634
+ console.log("[Checkout] 本地订单取消完成:", {
1635
+ orderUuid: currentOrderUuid,
1636
+ orderId: currentOrderId,
1637
+ cancelReason
1638
+ });
1639
+ return {
1640
+ success: true,
1641
+ message: "本地订单已成功取消",
1642
+ orderId: currentOrderId
1643
+ };
1644
+ } catch (error) {
1645
+ console.error("[Checkout] 取消本地订单失败:", error);
1646
+ const errorMessage = error instanceof Error ? error.message : "未知错误";
1647
+ return {
1648
+ success: false,
1649
+ message: `取消订单失败: ${errorMessage}`
1650
+ };
1651
+ }
1652
+ }
1653
+ /**
1654
+ * 保存订单并稍后支付
1655
+ *
1656
+ * 将当前订单保存到后端,但排除代金券类支付项(voucher_id),
1657
+ * 适用于用户想要保存订单但稍后完成支付的场景
1658
+ */
1659
+ async saveForLaterPaymentAsync() {
1660
+ var _a;
1661
+ try {
1662
+ if (!this.store.currentOrder) {
1663
+ return {
1664
+ success: false,
1665
+ message: "当前没有活跃订单,无法保存"
1666
+ };
1667
+ }
1668
+ const orderUuid = this.store.currentOrder.uuid;
1669
+ const currentOrderId = this.store.currentOrder.order_id;
1670
+ console.log("[Checkout] 开始保存订单并稍后支付:", {
1671
+ orderUuid,
1672
+ orderId: currentOrderId,
1673
+ totalAmount: this.store.currentOrder.total_amount
1674
+ });
1675
+ const allPaymentItems = await this.payment.getPaymentItemsAsync(
1676
+ this.store.currentOrder.uuid
1677
+ );
1678
+ const syncResult = await this.syncOrderToBackendWithReturn(
1679
+ false,
1680
+ allPaymentItems
1681
+ );
1682
+ console.log("[Checkout] 保存订单完成:", {
1683
+ orderUuid,
1684
+ oldOrderId: currentOrderId,
1685
+ syncResult,
1686
+ realOrderId: syncResult.orderId,
1687
+ isOrderSynced: this.store.isOrderSynced,
1688
+ filteredPaymentsCount: allPaymentItems.length
1689
+ });
1690
+ const finalOrderId = this.store.currentOrder.order_id;
1691
+ console.log("[Checkout] saveForLaterPaymentAsync 最终状态验证:", {
1692
+ returnedOrderId: syncResult.orderId,
1693
+ storedOrderId: finalOrderId,
1694
+ isConsistent: syncResult.orderId === finalOrderId,
1695
+ syncStatus: this.store.isOrderSynced
1696
+ });
1697
+ return {
1698
+ success: true,
1699
+ message: "订单保存成功,可稍后继续支付",
1700
+ orderId: syncResult.orderId,
1701
+ orderUuid,
1702
+ response: syncResult.response
1703
+ };
1704
+ } catch (error) {
1705
+ console.error("[Checkout] 保存订单失败:", error);
1706
+ const errorMessage = error instanceof Error ? error.message : "保存失败";
1707
+ return {
1708
+ success: false,
1709
+ message: `订单保存失败: ${errorMessage}`,
1710
+ orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid
1711
+ };
1712
+ }
1713
+ }
1714
+ /**
1715
+ * 获取当前商店折扣金额
1716
+ *
1717
+ * @returns 当前的商店折扣金额,如果没有则返回0
1718
+ */
1719
+ getShopDiscount() {
1720
+ var _a;
1721
+ if (((_a = this.store.localOrderData) == null ? void 0 : _a.shop_discount) !== void 0) {
1722
+ return this.store.localOrderData.shop_discount;
1723
+ }
1724
+ if (this.store.cartSummary) {
1725
+ const shopDiscountItem = this.store.cartSummary.find(
1726
+ (item) => item.key === "shop_discount"
1727
+ );
1728
+ if (shopDiscountItem) {
1729
+ return shopDiscountItem.value;
1730
+ }
1731
+ }
1732
+ return 0;
1733
+ }
1734
+ /**
1735
+ * 更新订单商店折扣
1736
+ *
1737
+ * 同时更新cartSummary和localOrderData中的shop_discount值
1738
+ *
1739
+ * @param discountAmount 商店折扣金额
1740
+ */
1741
+ async updateShopDiscountAsync(discountAmount) {
1742
+ var _a, _b;
1743
+ try {
1744
+ const oldDiscount = this.getShopDiscount();
1745
+ console.log("[Checkout] 更新商店折扣:", {
1746
+ orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid,
1747
+ oldDiscount,
1748
+ newDiscount: discountAmount
1749
+ });
1750
+ if (this.store.cartSummary) {
1751
+ const shopDiscountItem = this.store.cartSummary.find(
1752
+ (item) => item.key === "shop_discount"
1753
+ );
1754
+ if (shopDiscountItem) {
1755
+ shopDiscountItem.value = discountAmount;
1756
+ console.log("[Checkout] cartSummary 中的商店折扣已更新");
1757
+ } else {
1758
+ this.store.cartSummary.push({
1759
+ key: "shop_discount",
1760
+ value: discountAmount,
1761
+ hidden: true,
1762
+ label: "Shop Discount"
1763
+ });
1764
+ console.log("[Checkout] cartSummary 中已添加新的商店折扣项");
1765
+ }
1766
+ }
1767
+ if (this.store.localOrderData) {
1768
+ this.store.localOrderData.shop_discount = discountAmount;
1769
+ console.log("[Checkout] localOrderData 中的商店折扣已更新");
1770
+ } else {
1771
+ console.warn("[Checkout] localOrderData 不存在,无法更新商店折扣");
1772
+ }
1773
+ if (this.store.currentOrder && this.store.cartSummary) {
1774
+ const updatedAmountInfo = (0, import_utils.extractAmountFromCartSummary)(
1775
+ this.store.cartSummary
1776
+ );
1777
+ console.log("[Checkout] 重新计算订单金额:", updatedAmountInfo);
1778
+ this.store.currentOrder.total_amount = updatedAmountInfo.totalAmount;
1779
+ this.store.currentOrder.expect_amount = updatedAmountInfo.totalAmount;
1780
+ }
1781
+ await this.updateStateAmountToRemaining();
1782
+ await this.core.effects.emit(import_types.CheckoutHooks.OnShopDiscountChanged, {
1783
+ orderUuid: (_b = this.store.currentOrder) == null ? void 0 : _b.uuid,
1784
+ oldDiscount,
1785
+ newDiscount: discountAmount,
1786
+ timestamp: Date.now()
1787
+ });
1788
+ console.log("[Checkout] 商店折扣更新成功:", {
1789
+ oldDiscount,
1790
+ newDiscount: discountAmount
1791
+ });
1792
+ } catch (error) {
1793
+ console.error("[Checkout] 更新商店折扣失败:", error);
1794
+ await this.handleError(
1795
+ error,
1796
+ import_types.CheckoutErrorType.ValidationFailed
1797
+ );
1798
+ throw error;
1799
+ }
1800
+ }
1801
+ /**
1802
+ * 更新订单备注
1803
+ *
1804
+ * @param note 订单备注内容
1805
+ */
1806
+ async updateOrderNoteAsync(note) {
1807
+ var _a, _b;
1808
+ try {
1809
+ if (!this.store.localOrderData) {
1810
+ throw (0, import_utils.createCheckoutError)(
1811
+ import_types.CheckoutErrorType.ValidationFailed,
1812
+ "没有本地订单数据,无法更新备注"
1813
+ );
1814
+ }
1815
+ console.log("[Checkout] 更新订单备注:", {
1816
+ orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid,
1817
+ oldNote: this.store.localOrderData.shop_note,
1818
+ newNote: note
1819
+ });
1820
+ const oldNote = this.store.localOrderData.shop_note;
1821
+ this.store.localOrderData.shop_note = note;
1822
+ if (this.store.currentOrder) {
1823
+ try {
1824
+ const orderInPayment = await this.payment.getPaymentOrderByUuidAsync(
1825
+ this.store.currentOrder.uuid
1826
+ );
1827
+ if (orderInPayment && orderInPayment.note !== void 0) {
1828
+ console.log("[Checkout] 同步备注到Payment模块的订单数据中");
1829
+ }
1830
+ } catch (syncError) {
1831
+ console.warn(
1832
+ "[Checkout] 同步备注到Payment模块失败,但本地更新成功:",
1833
+ syncError
1834
+ );
1835
+ }
1836
+ }
1837
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderNoteChanged, {
1838
+ orderUuid: (_b = this.store.currentOrder) == null ? void 0 : _b.uuid,
1839
+ oldNote,
1840
+ newNote: note,
1841
+ timestamp: Date.now()
1842
+ });
1843
+ console.log("[Checkout] 订单备注更新成功:", {
1844
+ oldNote,
1845
+ newNote: note
1846
+ });
1847
+ } catch (error) {
1848
+ console.error("[Checkout] 更新订单备注失败:", error);
1849
+ await this.handleError(
1850
+ error,
1851
+ import_types.CheckoutErrorType.ValidationFailed
1852
+ );
1853
+ throw error;
1854
+ }
1855
+ }
1856
+ /**
1857
+ * 设置状态
1858
+ */
1859
+ setStatus(status) {
1860
+ const oldStatus = this.store.status;
1861
+ this.store.status = status;
1862
+ this.core.effects.emit(import_types.CheckoutHooks.OnStatusChanged, {
1863
+ oldStatus,
1864
+ newStatus: status,
1865
+ timestamp: Date.now()
1866
+ });
1867
+ }
1868
+ /**
1869
+ * 设置步骤
1870
+ */
1871
+ setStep(step) {
1872
+ const oldStep = this.store.step;
1873
+ this.store.step = step;
1874
+ this.core.effects.emit(import_types.CheckoutHooks.OnStepChanged, {
1875
+ oldStep,
1876
+ newStep: step,
1877
+ timestamp: Date.now()
1878
+ });
1879
+ }
1880
+ /**
1881
+ * 处理错误
1882
+ */
1883
+ async handleError(error, type) {
1884
+ const checkoutError = error instanceof Error && "type" in error ? error : (0, import_utils.createCheckoutError)(type, error.message, error);
1885
+ this.store.lastError = checkoutError;
1886
+ this.setStatus(import_types.CheckoutStatus.Error);
1887
+ await this.core.effects.emit(import_types.CheckoutHooks.OnError, {
1888
+ error: checkoutError,
1889
+ context: { status: this.store.status, step: this.store.step },
1890
+ timestamp: Date.now()
1891
+ });
1892
+ console.error("[Checkout] 错误:", checkoutError);
1893
+ }
1894
+ /**
1895
+ * 处理支付成功
1896
+ */
1897
+ async handlePaymentSuccess(data) {
1898
+ var _a;
1899
+ this.setStatus(import_types.CheckoutStatus.PaymentCompleted);
1900
+ await this.updateStateAmountToRemaining();
1901
+ await this.core.effects.emit(import_types.CheckoutHooks.OnPaymentSuccess, {
1902
+ orderUuid: data.orderUuid,
1903
+ paymentMethodCode: "",
1904
+ amount: ((_a = this.store.currentOrder) == null ? void 0 : _a.total_amount) || "0",
1905
+ timestamp: data.timestamp
1906
+ });
1907
+ await this.completeCheckoutAsync();
1908
+ }
1909
+ /**
1910
+ * 处理支付错误
1911
+ */
1912
+ async handlePaymentError(data) {
1913
+ var _a;
1914
+ const error = (0, import_utils.createCheckoutError)(
1915
+ import_types.CheckoutErrorType.PaymentFailed,
1916
+ data.error || "支付同步失败"
1917
+ );
1918
+ await this.handleError(
1919
+ error instanceof Error ? error : new Error(String(error)),
1920
+ import_types.CheckoutErrorType.PaymentFailed
1921
+ );
1922
+ await this.core.effects.emit(import_types.CheckoutHooks.OnPaymentFailed, {
1923
+ orderUuid: data.orderUuid,
1924
+ paymentMethodCode: "",
1925
+ amount: ((_a = this.store.currentOrder) == null ? void 0 : _a.total_amount) || "0",
1926
+ timestamp: data.timestamp
1927
+ });
1928
+ }
1929
+ /**
1930
+ * 验证结账参数
1931
+ */
1932
+ validateCheckoutParams(params) {
1933
+ return (0, import_utils.validateCheckoutData)(params);
1934
+ }
1935
+ /**
1936
+ * 处理现金支付项的找零逻辑
1937
+ *
1938
+ * @param paymentItem 原始支付项
1939
+ * @returns 处理后的支付项(包含找零信息)
1940
+ */
1941
+ async processCashPaymentItem(paymentItem) {
1942
+ const isCashPayment = this.isCashPayment(paymentItem.code, paymentItem.type);
1943
+ if (!isCashPayment) {
1944
+ return paymentItem;
1945
+ }
1946
+ try {
1947
+ const remainingAmountStr = await this.calculateRemainingAmountAsync();
1948
+ let remainingAmount = new import_decimal.default(remainingAmountStr);
1949
+ const cashAmount = new import_decimal.default(String(paymentItem.amount));
1950
+ console.log("[Checkout] 现金支付处理:", {
1951
+ cashAmount: cashAmount.toNumber(),
1952
+ remainingAmount: remainingAmount.toNumber(),
1953
+ needsChange: cashAmount.gt(remainingAmount)
1954
+ });
1955
+ if (cashAmount.lte(remainingAmount)) {
1956
+ return paymentItem;
1957
+ }
1958
+ const changeAmount = cashAmount.sub(remainingAmount);
1959
+ if (Number(paymentItem.rounding_amount) > 0) {
1960
+ if (Number(paymentItem.rounding_amount) === changeAmount.toNumber()) {
1961
+ return paymentItem;
1962
+ } else {
1963
+ remainingAmount = remainingAmount.add(new import_decimal.default(paymentItem.rounding_amount || "0"));
1964
+ }
1965
+ }
1966
+ console.log("[Checkout] 现金支付需要找零:", {
1967
+ actualPaidAmount: cashAmount.toFixed(2),
1968
+ chargedAmount: remainingAmount.toFixed(2),
1969
+ changeGivenAmount: changeAmount.toFixed(2)
1970
+ });
1971
+ const processedPaymentItem = {
1972
+ ...paymentItem,
1973
+ amount: remainingAmount.toFixed(2),
1974
+ // 将 amount 设置为剩余待付金额,保留2位小数
1975
+ metadata: {
1976
+ ...paymentItem.metadata,
1977
+ actual_paid_amount: cashAmount.toNumber(),
1978
+ // 实付金额
1979
+ change_given_amount: changeAmount.toNumber()
1980
+ // 找零金额
1981
+ }
1982
+ };
1983
+ this.logInfo("Cash payment with change processed", {
1984
+ originalAmount: cashAmount.toFixed(2),
1985
+ chargedAmount: remainingAmount.toFixed(2),
1986
+ changeAmount: changeAmount.toFixed(2),
1987
+ paymentCode: paymentItem.code,
1988
+ paymentType: paymentItem.type,
1989
+ // 额外的精度验证信息
1990
+ decimalPrecisionCheck: {
1991
+ cashAmountPrecise: cashAmount.toString(),
1992
+ remainingAmountPrecise: remainingAmount.toString(),
1993
+ changeAmountPrecise: changeAmount.toString()
1994
+ }
1995
+ });
1996
+ return processedPaymentItem;
1997
+ } catch (error) {
1998
+ console.error("[Checkout] 处理现金支付项时出错:", error);
1999
+ return paymentItem;
2000
+ }
2001
+ }
2002
+ /**
2003
+ * 判断是否为现金支付
2004
+ *
2005
+ * @param paymentCode 支付代码
2006
+ * @param paymentType 支付类型
2007
+ * @returns 是否为现金支付
2008
+ */
2009
+ isCashPayment(paymentCode, paymentType) {
2010
+ const codeUpper = (paymentCode == null ? void 0 : paymentCode.toUpperCase()) || "";
2011
+ const typeUpper = (paymentType == null ? void 0 : paymentType.toUpperCase()) || "";
2012
+ const cashIdentifiers = ["CASH", "CASHMANUAL", "MANUAL"];
2013
+ return cashIdentifiers.some(
2014
+ (identifier) => codeUpper.includes(identifier) || typeUpper.includes(identifier)
2015
+ );
2016
+ }
2017
+ /**
2018
+ * 预加载支付方式(在初始化时调用)
2019
+ */
2020
+ async preloadPaymentMethods() {
2021
+ try {
2022
+ console.log("[Checkout] 预加载支付方式...");
2023
+ const methods = await this.payment.getPayMethodListAsync();
2024
+ this.store.paymentMethods = methods;
2025
+ console.log(`[Checkout] 预加载完成,共 ${methods.length} 种支付方式`);
2026
+ } catch (error) {
2027
+ console.error("[Checkout] 预加载支付方式失败:", error);
2028
+ this.store.paymentMethods = [];
2029
+ }
2030
+ }
2031
+ /**
2032
+ * 清理过期的已同步订单数据
2033
+ *
2034
+ * 删除本地 IndexDB 中超过指定天数且已同步到后端的订单数据
2035
+ */
2036
+ async cleanupExpiredOrdersAsync() {
2037
+ var _a, _b, _c;
2038
+ try {
2039
+ const cleanupConfig = this.otherParams.orderDataCleanup || {};
2040
+ const isCleanupEnabled = cleanupConfig.enabled !== false;
2041
+ const retentionDays = cleanupConfig.retentionDays || 7;
2042
+ const maxOrdersToDelete = cleanupConfig.maxOrdersToDelete || 100;
2043
+ if (!isCleanupEnabled) {
2044
+ console.log("[Checkout] 订单数据清理功能已禁用");
2045
+ return;
2046
+ }
2047
+ console.log(`[Checkout] 开始清理过期订单数据(保留 ${retentionDays} 天内的数据)...`);
2048
+ const allOrders = await this.payment.getOrderListAsync();
2049
+ if (!allOrders || allOrders.length === 0) {
2050
+ console.log("[Checkout] 没有找到需要清理的订单数据");
2051
+ return;
2052
+ }
2053
+ const thresholdDate = /* @__PURE__ */ new Date();
2054
+ thresholdDate.setDate(thresholdDate.getDate() - retentionDays);
2055
+ let deletedCount = 0;
2056
+ const ordersToDelete = [];
2057
+ for (const order of allOrders) {
2058
+ try {
2059
+ const isSynced = order.order_id && !(0, import_utils.isVirtualOrderId)(order.order_id);
2060
+ if (!isSynced) {
2061
+ continue;
2062
+ }
2063
+ let orderCreatedAt = null;
2064
+ if ((_a = order.order_info) == null ? void 0 : _a.created_at) {
2065
+ orderCreatedAt = new Date(order.order_info.created_at);
2066
+ } else if ((_c = (_b = order.order_info) == null ? void 0 : _b.original_order_data) == null ? void 0 : _c.created_at) {
2067
+ orderCreatedAt = new Date(order.order_info.original_order_data.created_at);
2068
+ }
2069
+ if (!orderCreatedAt || isNaN(orderCreatedAt.getTime())) {
2070
+ continue;
2071
+ }
2072
+ if (orderCreatedAt < thresholdDate) {
2073
+ ordersToDelete.push({
2074
+ uuid: order.uuid,
2075
+ orderId: order.order_id,
2076
+ createdAt: orderCreatedAt.toISOString(),
2077
+ daysSinceCreated: Math.floor((Date.now() - orderCreatedAt.getTime()) / (1e3 * 60 * 60 * 24))
2078
+ });
2079
+ }
2080
+ } catch (error) {
2081
+ console.warn(`[Checkout] 处理订单 ${order.uuid} 时出错:`, error);
2082
+ continue;
2083
+ }
2084
+ }
2085
+ ordersToDelete.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
2086
+ const actualOrdersToDelete = ordersToDelete.slice(0, maxOrdersToDelete);
2087
+ for (const orderInfo of actualOrdersToDelete) {
2088
+ try {
2089
+ await this.payment.deletePaymentOrderAsync(orderInfo.uuid);
2090
+ deletedCount++;
2091
+ console.log(`[Checkout] 已删除过期订单: ${orderInfo.orderId} (${orderInfo.daysSinceCreated} 天前创建)`);
2092
+ } catch (error) {
2093
+ console.error(`[Checkout] 删除订单 ${orderInfo.uuid} 失败:`, error);
2094
+ }
2095
+ }
2096
+ const summary = {
2097
+ totalOrders: allOrders.length,
2098
+ expiredSyncedOrders: ordersToDelete.length,
2099
+ maxOrdersToDelete,
2100
+ actualDeletedOrders: deletedCount,
2101
+ retentionDays,
2102
+ cleanupDate: (/* @__PURE__ */ new Date()).toISOString(),
2103
+ thresholdDate: thresholdDate.toISOString(),
2104
+ skippedOrders: Math.max(0, ordersToDelete.length - maxOrdersToDelete)
2105
+ };
2106
+ this.logInfo("Expired orders cleanup completed", summary);
2107
+ if (ordersToDelete.length > maxOrdersToDelete) {
2108
+ console.log(`[Checkout] 过期订单清理完成: 总计 ${allOrders.length} 个订单,发现 ${ordersToDelete.length} 个过期已同步订单,删除了 ${deletedCount} 个(限制为 ${maxOrdersToDelete} 个)`);
2109
+ } else {
2110
+ console.log(`[Checkout] 过期订单清理完成: 总计 ${allOrders.length} 个订单,删除了 ${deletedCount} 个过期已同步订单`);
2111
+ }
2112
+ } catch (error) {
2113
+ const errorMessage = error instanceof Error ? error.message : String(error);
2114
+ console.error("[Checkout] 清理过期订单数据失败:", error);
2115
+ this.logError("Expired orders cleanup failed", { error: errorMessage });
2116
+ }
2117
+ }
2118
+ /**
2119
+ * 计算已支付金额(从 Payment 模块获取最新数据)
2120
+ */
2121
+ async calculatePaidAmountAsync() {
2122
+ if (!this.store.currentOrder) {
2123
+ console.log("[Checkout] calculatePaidAmountAsync: 没有当前订单");
2124
+ return "0.00";
2125
+ }
2126
+ try {
2127
+ const payments = await this.payment.getPaymentItemsAsync(
2128
+ this.store.currentOrder.uuid,
2129
+ false
2130
+ // 不包括已撤销的支付项
2131
+ );
2132
+ console.log("[Checkout] calculatePaidAmountAsync: 支付项详情:", {
2133
+ paymentCount: payments.length,
2134
+ payments: payments.map((p) => ({
2135
+ uuid: p.uuid,
2136
+ amount: p.amount,
2137
+ code: p.code,
2138
+ status: p.status,
2139
+ rounding_amount: p.rounding_amount
2140
+ }))
2141
+ });
2142
+ const paidAmount = payments.filter((payment) => payment.status !== "voided").reduce((sum, payment) => {
2143
+ const amount = new import_decimal.default(payment.amount || "0");
2144
+ const roundingAmount = new import_decimal.default(payment.rounding_amount || "0");
2145
+ const effectiveAmount = amount.add(roundingAmount.abs());
2146
+ console.log(`[Checkout] 计算支付项: ${payment.code}`, {
2147
+ originalAmount: amount.toFixed(2),
2148
+ roundingAmount: roundingAmount.toFixed(2),
2149
+ effectiveAmount: effectiveAmount.toFixed(2),
2150
+ description: !roundingAmount.isZero() ? `抹零金额 ${roundingAmount.toFixed(2)} 元,有效支付增加 ${roundingAmount.abs().toFixed(2)} 元` : "无抹零",
2151
+ // Decimal 精度验证
2152
+ preciseCalculationValues: {
2153
+ amount: amount.toString(),
2154
+ roundingAmount: roundingAmount.toString(),
2155
+ effectiveAmount: effectiveAmount.toString()
2156
+ }
2157
+ });
2158
+ return sum.add(effectiveAmount);
2159
+ }, new import_decimal.default(0));
2160
+ const result = paidAmount.toFixed(2);
2161
+ console.log("[Checkout] calculatePaidAmountAsync: 计算结果 =", result);
2162
+ return result;
2163
+ } catch (error) {
2164
+ console.error("[Checkout] calculatePaidAmountAsync 失败:", error);
2165
+ return "0.00";
2166
+ }
2167
+ }
2168
+ /**
2169
+ * 计算剩余未支付金额(从 Payment 模块获取最新数据)
2170
+ */
2171
+ async calculateRemainingAmountAsync() {
2172
+ if (!this.store.currentOrder) {
2173
+ console.log("[Checkout] calculateRemainingAmountAsync: 没有当前订单");
2174
+ return "0.00";
2175
+ }
2176
+ const totalAmount = new import_decimal.default(this.store.currentOrder.total_amount || "0");
2177
+ const paidAmountStr = await this.calculatePaidAmountAsync();
2178
+ const paidAmount = new import_decimal.default(paidAmountStr);
2179
+ const remainingAmount = totalAmount.sub(paidAmount);
2180
+ const result = import_decimal.default.max(0, remainingAmount).toFixed(2);
2181
+ console.log("[Checkout] calculateRemainingAmountAsync: 计算详情:", {
2182
+ orderUuid: this.store.currentOrder.uuid,
2183
+ totalAmount: totalAmount.toFixed(2),
2184
+ paidAmount: paidAmount.toFixed(2),
2185
+ calculatedRemaining: remainingAmount.toFixed(2),
2186
+ finalResult: result,
2187
+ description: "已支付金额包含抹零计算(amount + |rounding_amount|)",
2188
+ // Decimal 精度验证
2189
+ preciseCalculationValues: {
2190
+ totalAmount: totalAmount.toString(),
2191
+ paidAmount: paidAmount.toString(),
2192
+ remainingAmount: remainingAmount.toString(),
2193
+ resultAfterMax: import_decimal.default.max(0, remainingAmount).toString()
2194
+ }
2195
+ });
2196
+ return result;
2197
+ }
2198
+ /**
2199
+ * 更新 balanceDueAmount 为当前剩余未支付金额(系统内部计算)
2200
+ */
2201
+ async updateBalanceDueAmount() {
2202
+ var _a;
2203
+ try {
2204
+ const remainingAmount = await this.calculateRemainingAmountAsync();
2205
+ const currentBalanceDueAmount = this.store.balanceDueAmount;
2206
+ console.log("[Checkout] updateBalanceDueAmount: 状态检查:", {
2207
+ calculatedRemainingAmount: remainingAmount,
2208
+ currentBalanceDueAmount,
2209
+ needsUpdate: remainingAmount !== currentBalanceDueAmount,
2210
+ orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid
2211
+ });
2212
+ if (remainingAmount !== currentBalanceDueAmount) {
2213
+ this.store.balanceDueAmount = remainingAmount;
2214
+ await this.core.effects.emit(import_types.CheckoutHooks.OnBalanceDueAmountChanged, {
2215
+ oldAmount: currentBalanceDueAmount,
2216
+ newAmount: remainingAmount,
2217
+ timestamp: Date.now()
2218
+ });
2219
+ console.log("[Checkout] balanceDueAmount 已自动更新:", {
2220
+ oldAmount: currentBalanceDueAmount,
2221
+ newAmount: remainingAmount
2222
+ });
2223
+ } else {
2224
+ console.log("[Checkout] balanceDueAmount 无需更新,当前值已是最新:", {
2225
+ balanceDueAmount: currentBalanceDueAmount,
2226
+ remainingAmount
2227
+ });
2228
+ }
2229
+ } catch (error) {
2230
+ console.error("[Checkout] 更新 balanceDueAmount 失败:", error);
2231
+ }
2232
+ }
2233
+ /**
2234
+ * 更新 stateAmount 为当前剩余未支付金额
2235
+ */
2236
+ async updateStateAmountToRemaining() {
2237
+ var _a;
2238
+ try {
2239
+ const remainingAmount = await this.calculateRemainingAmountAsync();
2240
+ const currentStateAmount = this.store.stateAmount;
2241
+ console.log("[Checkout] updateStateAmountToRemaining: 状态检查:", {
2242
+ calculatedRemainingAmount: remainingAmount,
2243
+ currentStateAmount,
2244
+ needsUpdate: remainingAmount !== currentStateAmount,
2245
+ orderUuid: (_a = this.store.currentOrder) == null ? void 0 : _a.uuid
2246
+ });
2247
+ if (remainingAmount !== currentStateAmount) {
2248
+ this.store.stateAmount = remainingAmount;
2249
+ this.core.effects.emit(import_types.CheckoutHooks.OnStateAmountChanged, {
2250
+ oldAmount: currentStateAmount,
2251
+ newAmount: remainingAmount,
2252
+ timestamp: Date.now()
2253
+ });
2254
+ console.log("[Checkout] stateAmount 已自动更新为剩余金额:", {
2255
+ oldAmount: currentStateAmount,
2256
+ newAmount: remainingAmount
2257
+ });
2258
+ } else {
2259
+ console.log("[Checkout] stateAmount 无需更新,当前值已是最新:", {
2260
+ stateAmount: currentStateAmount,
2261
+ remainingAmount
2262
+ });
2263
+ }
2264
+ await this.updateBalanceDueAmount();
2265
+ await this.checkOrderPaymentCompletion();
2266
+ } catch (error) {
2267
+ console.error("[Checkout] 更新 stateAmount 为剩余金额失败:", error);
2268
+ }
2269
+ }
2270
+ /**
2271
+ * 检查订单支付是否完成
2272
+ *
2273
+ * 当剩余待付款金额 <= 0 时,触发订单支付完成事件
2274
+ */
2275
+ async checkOrderPaymentCompletion() {
2276
+ try {
2277
+ if (!this.store.currentOrder) {
2278
+ return;
2279
+ }
2280
+ const remainingAmount = await this.calculateRemainingAmountAsync();
2281
+ const remainingValue = new import_decimal.default(remainingAmount);
2282
+ if (remainingValue.lte(0)) {
2283
+ const totalAmount = this.store.currentOrder.total_amount;
2284
+ const paidAmount = await this.calculatePaidAmountAsync();
2285
+ console.log("[Checkout] 检测到订单支付完成:", {
2286
+ orderUuid: this.store.currentOrder.uuid,
2287
+ orderId: this.store.currentOrder.order_id,
2288
+ totalAmount,
2289
+ paidAmount,
2290
+ remainingAmount,
2291
+ isOrderSynced: this.store.isOrderSynced
2292
+ });
2293
+ const currentPayments = await this.payment.getPaymentItemsAsync(
2294
+ this.store.currentOrder.uuid,
2295
+ false
2296
+ // 不包括已撤销的支付项
2297
+ );
2298
+ const hasPaymentItems = currentPayments.length > 0;
2299
+ const allPaymentsHaveVoucherId = hasPaymentItems && currentPayments.every(
2300
+ (item) => item.status !== "voided" && item.voucher_id
2301
+ );
2302
+ const shouldAutoSync = hasPaymentItems && !allPaymentsHaveVoucherId;
2303
+ console.log("[Checkout] 自动同步订单条件检查:", {
2304
+ paymentCount: currentPayments.length,
2305
+ hasPaymentItems,
2306
+ allHaveVoucherId: allPaymentsHaveVoucherId,
2307
+ isOrderSynced: this.store.isOrderSynced,
2308
+ shouldAutoSync,
2309
+ reason: shouldAutoSync ? "支付完成,需要同步最终支付状态" : "跳过同步",
2310
+ paymentItems: currentPayments.map((p) => ({
2311
+ uuid: p.uuid,
2312
+ code: p.code,
2313
+ amount: p.amount,
2314
+ rounding_amount: p.rounding_amount,
2315
+ effective_amount: (parseFloat(p.amount || "0") + Math.abs(parseFloat(p.rounding_amount || "0"))).toFixed(2),
2316
+ voucher_id: p.voucher_id,
2317
+ status: p.status
2318
+ }))
2319
+ });
2320
+ if (shouldAutoSync) {
2321
+ console.log("[Checkout] 满足自动同步条件,开始同步订单到后端...");
2322
+ await this.syncOrderToBackend();
2323
+ } else {
2324
+ if (!hasPaymentItems) {
2325
+ console.log("[Checkout] 没有支付项,跳过订单同步");
2326
+ } else if (allPaymentsHaveVoucherId) {
2327
+ console.log("[Checkout] 所有支付项均为代金券类型,跳过订单同步");
2328
+ }
2329
+ }
2330
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderPaymentCompleted, {
2331
+ orderUuid: this.store.currentOrder.uuid,
2332
+ orderId: this.store.currentOrder.order_id,
2333
+ totalAmount,
2334
+ paidAmount,
2335
+ remainingAmount,
2336
+ timestamp: Date.now()
2337
+ });
2338
+ }
2339
+ } catch (error) {
2340
+ console.error("[Checkout] 检查订单支付完成状态失败:", error);
2341
+ }
2342
+ }
2343
+ /**
2344
+ * 同步订单到后端
2345
+ *
2346
+ * 调用后端 /order/checkout 接口创建真实订单
2347
+ */
2348
+ /**
2349
+ * 同步订单到后端并返回真实订单ID
2350
+ *
2351
+ * @param isManual 是否为手动同步,默认为 false
2352
+ * @param customPaymentItems 自定义支付项列表,如果提供则使用此列表而不是从数据库获取
2353
+ * @returns 包含订单ID、UUID和完整后端响应的对象
2354
+ */
2355
+ async syncOrderToBackendWithReturn(isManual = false, customPaymentItems) {
2356
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2357
+ if (!this.store.localOrderData || !this.store.currentOrder) {
2358
+ throw new Error("缺少必要的订单数据,无法同步到后端");
2359
+ }
2360
+ this.logInfo("syncOrderToBackendWithReturn called", {
2361
+ isManual,
2362
+ hasCustomPaymentItems: !!customPaymentItems,
2363
+ customPaymentItemsCount: (customPaymentItems == null ? void 0 : customPaymentItems.length) || 0,
2364
+ currentOrderId: this.store.currentOrder.order_id,
2365
+ orderUuid: this.store.currentOrder.uuid,
2366
+ isOrderSynced: this.store.isOrderSynced,
2367
+ isVirtualOrderId: (0, import_utils.isVirtualOrderId)(this.store.currentOrder.order_id),
2368
+ localOrderDataType: this.store.localOrderData.type,
2369
+ platform: this.store.localOrderData.platform,
2370
+ customerId: (_a = this.store.currentCustomer) == null ? void 0 : _a.customer_id
2371
+ });
2372
+ const syncType = isManual ? "手动" : "自动";
2373
+ const currentOrderId = this.store.currentOrder.order_id;
2374
+ const hasRealOrderId = currentOrderId && !(0, import_utils.isVirtualOrderId)(currentOrderId);
2375
+ let isUpdateOperation = false;
2376
+ let reason = "";
2377
+ if (this.store.isOrderSynced) {
2378
+ isUpdateOperation = true;
2379
+ reason = "订单已同步过";
2380
+ } else if (hasRealOrderId) {
2381
+ isUpdateOperation = true;
2382
+ reason = "有真实订单ID";
2383
+ } else {
2384
+ isUpdateOperation = false;
2385
+ reason = "既未同步也无真实ID";
2386
+ }
2387
+ const operation = isUpdateOperation ? "更新" : "创建";
2388
+ console.log("[Checkout] 操作类型判断详情:", {
2389
+ currentOrderId,
2390
+ hasRealOrderId,
2391
+ isOrderSynced: this.store.isOrderSynced,
2392
+ isManual,
2393
+ reason,
2394
+ finalDecision: operation
2395
+ });
2396
+ console.log(`[Checkout] 开始${syncType}${operation}订单到后端...`, {
2397
+ currentOrderId,
2398
+ isVirtualId: (0, import_utils.isVirtualOrderId)(currentOrderId || ""),
2399
+ operation,
2400
+ orderUuid: this.store.currentOrder.uuid,
2401
+ isOrderSynced: this.store.isOrderSynced
2402
+ });
2403
+ const paymentItems = customPaymentItems || await this.payment.getPaymentItemsAsync(this.store.currentOrder.uuid);
2404
+ console.log("[Checkout] 获取到支付项:", {
2405
+ count: paymentItems.length,
2406
+ isCustomFiltered: !!customPaymentItems,
2407
+ methods: paymentItems.map((p) => p.code),
2408
+ totalAmount: paymentItems.reduce((sum, p) => sum + parseFloat(p.amount), 0).toFixed(2),
2409
+ paymentDetails: paymentItems.map((p) => {
2410
+ var _a2;
2411
+ return {
2412
+ uuid: p.uuid,
2413
+ code: p.code,
2414
+ amount: p.amount,
2415
+ uniquePaymentNumber: (_a2 = p.metadata) == null ? void 0 : _a2.unique_payment_number,
2416
+ voucherId: p.voucher_id,
2417
+ orderPaymentType: p.order_payment_type,
2418
+ metadata: p.metadata
2419
+ };
2420
+ })
2421
+ });
2422
+ const processedPaymentItems = paymentItems.map((item) => {
2423
+ var _a2, _b2;
2424
+ return {
2425
+ ...item,
2426
+ metadata: {
2427
+ ...item.metadata,
2428
+ rounding_rule: ((_a2 = item.metadata) == null ? void 0 : _a2.rounding_rule) || this.otherParams.order_rounding_setting,
2429
+ shop_wallet_pass_id: ((_b2 = item.metadata) == null ? void 0 : _b2.shop_wallet_pass_id) || this.otherParams.shop_wallet_pass_id
2430
+ }
2431
+ };
2432
+ });
2433
+ console.log("[Checkout] 处理后的支付项数据(包含完整metadata):", {
2434
+ originalCount: paymentItems.length,
2435
+ processedCount: processedPaymentItems.length,
2436
+ sampleMetadata: (_b = processedPaymentItems[0]) == null ? void 0 : _b.metadata,
2437
+ allPaymentItems: processedPaymentItems.map((p) => {
2438
+ var _a2, _b2;
2439
+ return {
2440
+ code: p.code,
2441
+ amount: p.amount,
2442
+ voucherId: p.voucher_id,
2443
+ orderPaymentType: p.order_payment_type,
2444
+ metadata: p.metadata,
2445
+ // 现金支付找零信息
2446
+ actualPaidAmount: (_a2 = p.metadata) == null ? void 0 : _a2.actual_paid_amount,
2447
+ changeGivenAmount: (_b2 = p.metadata) == null ? void 0 : _b2.change_given_amount
2448
+ };
2449
+ })
2450
+ });
2451
+ const orderParams = {
2452
+ ...this.store.localOrderData,
2453
+ type: this.store.localOrderData.type,
2454
+ platform: this.store.localOrderData.platform,
2455
+ payments: processedPaymentItems,
2456
+ // 使用处理过的支付项数据
2457
+ customer_id: (_c = this.store.currentCustomer) == null ? void 0 : _c.customer_id,
2458
+ // 添加客户ID
2459
+ is_price_include_tax: this.otherParams.is_price_include_tax,
2460
+ // core 有
2461
+ tax_title: this.otherParams.tax_title,
2462
+ // core 没有
2463
+ tax_rate: this.otherParams.tax_rate,
2464
+ // core 有
2465
+ tax_country_code: this.otherParams.tax_country_code,
2466
+ // core 没有
2467
+ currency_code: this.otherParams.currency_code,
2468
+ currency_symbol: this.otherParams.currency_symbol,
2469
+ currency_format: this.otherParams.currency_format,
2470
+ is_deposit: ((_d = this.store.currentOrder) == null ? void 0 : _d.is_deposit) || 0,
2471
+ deposit_amount: ((_e = this.store.currentOrder) == null ? void 0 : _e.deposit_amount) || "0.00",
2472
+ // surcharge_fee: this.otherParams.surcharge_fee,
2473
+ // surcharges: ,
2474
+ product_tax_fee: this.store.localOrderData.tax_fee,
2475
+ note: this.store.localOrderData.shop_note
2476
+ // deposit_amount:
2477
+ };
2478
+ if (isUpdateOperation) {
2479
+ if ((0, import_utils.isVirtualOrderId)(currentOrderId)) {
2480
+ console.error(
2481
+ "[Checkout] 数据不一致警告:更新操作但订单ID仍为虚拟ID!",
2482
+ {
2483
+ currentOrderId,
2484
+ isOrderSynced: this.store.isOrderSynced,
2485
+ reason,
2486
+ orderUuid: this.store.currentOrder.uuid
2487
+ }
2488
+ );
2489
+ console.log("[Checkout] 尝试数据修复:暂时不包含order_id,让后端处理");
2490
+ console.log(
2491
+ "[Checkout] 注意:这次调用将作为创建操作处理,但后续会修复数据一致性"
2492
+ );
2493
+ } else {
2494
+ orderParams.order_id = currentOrderId;
2495
+ console.log(`[Checkout] 更新订单操作,包含订单ID: ${currentOrderId}`);
2496
+ }
2497
+ } else {
2498
+ console.log("[Checkout] 创建新订单操作");
2499
+ }
2500
+ const startTime = Date.now();
2501
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderSubmitStart, {
2502
+ orderUuid: this.store.currentOrder.uuid,
2503
+ operation: isUpdateOperation ? "update" : "create",
2504
+ isManual,
2505
+ paymentItemCount: paymentItems.length,
2506
+ timestamp: startTime
2507
+ });
2508
+ let checkoutResponse;
2509
+ let submitSuccess = false;
2510
+ let submitError;
2511
+ try {
2512
+ this.logInfo("Calling backend checkout API", {
2513
+ url: "/order/checkout",
2514
+ operation,
2515
+ isManual,
2516
+ orderType: orderParams.type,
2517
+ platform: orderParams.platform,
2518
+ customerId: orderParams.customer_id,
2519
+ isDeposit: orderParams.is_deposit,
2520
+ depositAmount: orderParams.deposit_amount,
2521
+ bookingsCount: ((_f = orderParams.bookings) == null ? void 0 : _f.length) || 0,
2522
+ relationProductsCount: ((_g = orderParams.relation_products) == null ? void 0 : _g.length) || 0,
2523
+ paymentsCount: ((_h = orderParams.payments) == null ? void 0 : _h.length) || 0,
2524
+ paymentMethods: ((_i = orderParams.payments) == null ? void 0 : _i.map((p) => p.code)) || [],
2525
+ hasOrderId: !!orderParams.order_id,
2526
+ orderIdIncluded: orderParams.order_id,
2527
+ productTaxFee: orderParams.product_tax_fee,
2528
+ note: orderParams.note,
2529
+ scheduleDate: orderParams.schedule_date
2530
+ });
2531
+ checkoutResponse = await this.order.createOrderByCheckout(orderParams);
2532
+ submitSuccess = true;
2533
+ console.log("[Checkout] 下单接口调用成功");
2534
+ } catch (error) {
2535
+ submitSuccess = false;
2536
+ submitError = error instanceof Error ? error.message : String(error);
2537
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderSyncFailed, {
2538
+ orderUuid: this.store.currentOrder.uuid,
2539
+ operation: isUpdateOperation ? "update" : "create",
2540
+ isManual,
2541
+ error: submitError,
2542
+ errorType: "network_error",
2543
+ duration: Date.now() - startTime,
2544
+ timestamp: Date.now()
2545
+ });
2546
+ throw error;
2547
+ } finally {
2548
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderSubmitEnd, {
2549
+ success: submitSuccess,
2550
+ orderUuid: this.store.currentOrder.uuid,
2551
+ operation: isUpdateOperation ? "update" : "create",
2552
+ isManual,
2553
+ orderId: submitSuccess ? ((_j = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _j.order_id) || (checkoutResponse == null ? void 0 : checkoutResponse.order_id) : void 0,
2554
+ error: submitError,
2555
+ duration: Date.now() - startTime,
2556
+ timestamp: Date.now()
2557
+ });
2558
+ }
2559
+ console.log("[Checkout] 后端返回的响应数据:", {
2560
+ status: checkoutResponse == null ? void 0 : checkoutResponse.status,
2561
+ code: checkoutResponse == null ? void 0 : checkoutResponse.code,
2562
+ message: checkoutResponse == null ? void 0 : checkoutResponse.message,
2563
+ data: checkoutResponse == null ? void 0 : checkoutResponse.data
2564
+ });
2565
+ const responseStatus = checkoutResponse == null ? void 0 : checkoutResponse.status;
2566
+ const isSuccessResponse = responseStatus === true || responseStatus === 200 || responseStatus === "success" || responseStatus === 1 && (checkoutResponse == null ? void 0 : checkoutResponse.code) === 200;
2567
+ if (!isSuccessResponse) {
2568
+ const errorMessage = (checkoutResponse == null ? void 0 : checkoutResponse.message) || "订单同步失败,后端返回非成功状态";
2569
+ console.error("[Checkout] 订单同步失败,响应状态检查未通过:", {
2570
+ expectedSuccess: true,
2571
+ actualStatus: responseStatus,
2572
+ code: checkoutResponse == null ? void 0 : checkoutResponse.code,
2573
+ message: checkoutResponse == null ? void 0 : checkoutResponse.message,
2574
+ errorMessage
2575
+ });
2576
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderSyncFailed, {
2577
+ orderUuid: this.store.currentOrder.uuid,
2578
+ operation: isUpdateOperation ? "update" : "create",
2579
+ isManual,
2580
+ error: errorMessage,
2581
+ errorType: "api_error",
2582
+ response: checkoutResponse,
2583
+ duration: Date.now() - startTime,
2584
+ timestamp: Date.now()
2585
+ });
2586
+ throw new Error(errorMessage);
2587
+ }
2588
+ console.log("[Checkout] 响应状态检查通过,开始处理订单数据");
2589
+ let realOrderId;
2590
+ if (isUpdateOperation) {
2591
+ realOrderId = currentOrderId;
2592
+ console.log(`[Checkout] 订单更新成功,订单ID: ${realOrderId}`);
2593
+ } else {
2594
+ let extractedOrderId = (_k = checkoutResponse == null ? void 0 : checkoutResponse.data) == null ? void 0 : _k.order_id;
2595
+ if (!extractedOrderId) {
2596
+ extractedOrderId = checkoutResponse == null ? void 0 : checkoutResponse.order_id;
2597
+ }
2598
+ if (extractedOrderId !== void 0 && extractedOrderId !== null) {
2599
+ extractedOrderId = String(extractedOrderId);
2600
+ }
2601
+ if (!extractedOrderId) {
2602
+ throw new Error("后端返回的订单信息中未包含订单ID");
2603
+ }
2604
+ realOrderId = extractedOrderId;
2605
+ console.log("[Checkout] 订单创建成功,真实订单ID:", realOrderId);
2606
+ console.log("[Checkout] 准备替换订单ID:", {
2607
+ orderUuid: this.store.currentOrder.uuid,
2608
+ oldOrderId: this.store.currentOrder.order_id,
2609
+ newOrderId: realOrderId
2610
+ });
2611
+ try {
2612
+ const updatedOrder = await this.payment.replaceOrderIdByUuidAsync(
2613
+ this.store.currentOrder.uuid,
2614
+ realOrderId
2615
+ );
2616
+ console.log("[Checkout] Payment模块替换订单ID结果:", {
2617
+ wasSuccessful: !!updatedOrder,
2618
+ returnedOrderId: updatedOrder == null ? void 0 : updatedOrder.order_id,
2619
+ expectedOrderId: realOrderId
2620
+ });
2621
+ if (updatedOrder) {
2622
+ console.log("[Checkout] Payment模块返回的更新后订单:", {
2623
+ uuid: updatedOrder.uuid,
2624
+ orderId: updatedOrder.order_id,
2625
+ totalAmount: updatedOrder.total_amount
2626
+ });
2627
+ this.store.currentOrder = updatedOrder;
2628
+ console.log(
2629
+ "[Checkout] 订单ID替换成功,当前订单ID:",
2630
+ this.store.currentOrder.order_id
2631
+ );
2632
+ } else {
2633
+ console.error(
2634
+ "[Checkout] Payment模块返回空订单,订单ID替换失败,开始手动替换"
2635
+ );
2636
+ const beforeManualUpdate = this.store.currentOrder.order_id;
2637
+ this.store.currentOrder.order_id = realOrderId;
2638
+ console.log("[Checkout] 手动设置订单ID:", {
2639
+ beforeReplacement: beforeManualUpdate,
2640
+ afterReplacement: this.store.currentOrder.order_id,
2641
+ 目标ID: realOrderId
2642
+ });
2643
+ }
2644
+ } catch (error) {
2645
+ console.error("[Checkout] 调用Payment模块替换订单ID时发生错误:", error);
2646
+ this.store.currentOrder.order_id = realOrderId;
2647
+ console.log("[Checkout] 错误恢复:手动设置订单ID:", realOrderId);
2648
+ }
2649
+ }
2650
+ this.store.isOrderSynced = true;
2651
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderSynced, {
2652
+ orderUuid: this.store.currentOrder.uuid,
2653
+ realOrderId,
2654
+ virtualOrderId: this.store.currentOrder.order_id,
2655
+ timestamp: Date.now(),
2656
+ isManual,
2657
+ response: checkoutResponse
2658
+ });
2659
+ const finalOrderId = this.store.currentOrder.order_id;
2660
+ const finalIsVirtual = (0, import_utils.isVirtualOrderId)(finalOrderId || "");
2661
+ console.log(`[Checkout] ${syncType}${operation}订单到后端完成`, {
2662
+ returnedOrderId: realOrderId,
2663
+ currentStoredOrderId: finalOrderId,
2664
+ isStillVirtualId: finalIsVirtual,
2665
+ isSynced: this.store.isOrderSynced
2666
+ });
2667
+ if (finalIsVirtual && !isUpdateOperation) {
2668
+ console.warn(
2669
+ "[Checkout] 警告:订单创建后,当前订单ID仍然是虚拟ID,可能存在问题"
2670
+ );
2671
+ }
2672
+ return {
2673
+ success: true,
2674
+ message: `订单${operation}成功`,
2675
+ orderId: realOrderId,
2676
+ orderUuid: this.store.currentOrder.uuid,
2677
+ response: checkoutResponse
2678
+ };
2679
+ }
2680
+ async syncOrderToBackend() {
2681
+ try {
2682
+ const syncResult = await this.syncOrderToBackendWithReturn(false);
2683
+ console.log("[Checkout] 自动同步订单完成:", syncResult);
2684
+ } catch (error) {
2685
+ console.error("[Checkout] 同步订单到后端失败:", error);
2686
+ await this.handleError(
2687
+ new Error(
2688
+ `订单同步失败: ${error instanceof Error ? error.message : String(error)}`
2689
+ ),
2690
+ import_types.CheckoutErrorType.OrderCreationFailed
2691
+ );
2692
+ }
2693
+ }
2694
+ /**
2695
+ * 获取状态消息
2696
+ */
2697
+ getStatusMessage() {
2698
+ var _a;
2699
+ switch (this.store.status) {
2700
+ case import_types.CheckoutStatus.Initializing:
2701
+ return "正在初始化结账流程...";
2702
+ case import_types.CheckoutStatus.Ready:
2703
+ return "准备就绪,可以开始结账";
2704
+ case import_types.CheckoutStatus.CreatingOrder:
2705
+ return "正在创建订单...";
2706
+ case import_types.CheckoutStatus.OrderCreated:
2707
+ return "订单创建成功,请选择支付方式";
2708
+ case import_types.CheckoutStatus.ProcessingPayment:
2709
+ return "正在处理支付...";
2710
+ case import_types.CheckoutStatus.PaymentCompleted:
2711
+ return "支付完成";
2712
+ case import_types.CheckoutStatus.Completed:
2713
+ return "结账完成";
2714
+ case import_types.CheckoutStatus.Cancelled:
2715
+ return "结账已取消";
2716
+ case import_types.CheckoutStatus.Error:
2717
+ return ((_a = this.store.lastError) == null ? void 0 : _a.message) || "发生未知错误";
2718
+ default:
2719
+ return "";
2720
+ }
2721
+ }
2722
+ async setOtherParams(params, { cover = false } = {}) {
2723
+ if (cover) {
2724
+ this.otherParams = params;
2725
+ } else {
2726
+ this.otherParams = { ...this.otherParams, ...params };
2727
+ }
2728
+ }
2729
+ /**
2730
+ * 通过订单ID编辑订单备注
2731
+ *
2732
+ * 用于修改已同步到后端的订单备注,通常在支付成功后的弹窗中使用
2733
+ *
2734
+ * @param orderId 后端订单ID
2735
+ * @param note 新的订单备注
2736
+ * @returns 修改结果
2737
+ */
2738
+ async editOrderNoteByOrderIdAsync(orderId, note) {
2739
+ this.logInfo("editOrderNoteByOrderIdAsync called", {
2740
+ orderId,
2741
+ note,
2742
+ noteLength: note.length,
2743
+ isCurrentOrder: this.store.currentOrder && (String(this.store.currentOrder.order_id) === String(orderId) || String(this.store.currentOrder.id) === String(orderId))
2744
+ });
2745
+ try {
2746
+ console.log("[Checkout] 开始编辑订单备注:", {
2747
+ orderId,
2748
+ note,
2749
+ noteLength: note.length
2750
+ });
2751
+ if (!orderId) {
2752
+ return {
2753
+ success: false,
2754
+ message: "订单ID不能为空",
2755
+ orderId
2756
+ };
2757
+ }
2758
+ this.logInfo("Calling order note edit API", {
2759
+ url: `/order/order/${orderId}/note`,
2760
+ method: "PUT",
2761
+ orderId,
2762
+ note,
2763
+ noteLength: note.length
2764
+ });
2765
+ const response = await this.request.put(
2766
+ `/order/order/${orderId}/note`,
2767
+ {
2768
+ note
2769
+ }
2770
+ );
2771
+ console.log("[Checkout] 订单备注编辑响应:", {
2772
+ orderId,
2773
+ status: response.status,
2774
+ message: response.message,
2775
+ response
2776
+ });
2777
+ if (response.status === true || response.status === 200) {
2778
+ console.log(`[Checkout] 订单 ${orderId} 备注修改成功`);
2779
+ if (this.store.currentOrder && (String(this.store.currentOrder.order_id) === String(orderId) || String(this.store.currentOrder.id) === String(orderId))) {
2780
+ console.log("[Checkout] 更新本地订单备注状态");
2781
+ const previousNote = this.getOrderNote();
2782
+ if (this.store.localOrderData) {
2783
+ this.store.localOrderData.shop_note = note;
2784
+ }
2785
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderNoteChanged, {
2786
+ orderUuid: this.store.currentOrder.uuid,
2787
+ oldNote: previousNote,
2788
+ newNote: note,
2789
+ timestamp: Date.now()
2790
+ });
2791
+ }
2792
+ return {
2793
+ success: true,
2794
+ message: response.message || "订单备注修改成功",
2795
+ orderId
2796
+ };
2797
+ } else {
2798
+ const errorMessage = response.message || "订单备注修改失败";
2799
+ console.error(`[Checkout] 订单 ${orderId} 备注修改失败:`, errorMessage);
2800
+ return {
2801
+ success: false,
2802
+ message: errorMessage,
2803
+ orderId
2804
+ };
2805
+ }
2806
+ } catch (error) {
2807
+ console.error("[Checkout] 编辑订单备注失败:", error);
2808
+ const errorMessage = error instanceof Error ? error.message : "网络错误或服务器异常";
2809
+ return {
2810
+ success: false,
2811
+ message: `编辑订单备注失败: ${errorMessage}`,
2812
+ orderId
2813
+ };
2814
+ }
2815
+ }
2816
+ /**
2817
+ * 发送客户支付链接邮件
2818
+ *
2819
+ * 向指定邮箱发送订单支付提醒邮件
2820
+ *
2821
+ * @param params 发送参数
2822
+ * @returns 发送结果
2823
+ */
2824
+ async sendCustomerPayLinkAsync(params) {
2825
+ var _a, _b;
2826
+ this.logInfo("sendCustomerPayLinkAsync called", {
2827
+ orderIds: params.order_ids,
2828
+ orderIdsCount: ((_a = params.order_ids) == null ? void 0 : _a.length) || 0,
2829
+ emails: params.emails,
2830
+ emailsCount: ((_b = params.emails) == null ? void 0 : _b.length) || 0,
2831
+ notifyAction: params.notify_action || "order_payment_reminder"
2832
+ });
2833
+ try {
2834
+ console.log("[Checkout] 开始发送客户支付链接邮件:", {
2835
+ orderIds: params.order_ids,
2836
+ emails: params.emails,
2837
+ notifyAction: params.notify_action || "order_payment_reminder"
2838
+ });
2839
+ if (!params.order_ids || params.order_ids.length === 0) {
2840
+ return {
2841
+ success: false,
2842
+ message: "订单ID列表不能为空"
2843
+ };
2844
+ }
2845
+ if (!params.emails || params.emails.length === 0) {
2846
+ return {
2847
+ success: false,
2848
+ message: "邮箱地址列表不能为空"
2849
+ };
2850
+ }
2851
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2852
+ const invalidEmails = params.emails.filter(
2853
+ (email) => !emailRegex.test(email)
2854
+ );
2855
+ if (invalidEmails.length > 0) {
2856
+ return {
2857
+ success: false,
2858
+ message: `邮箱格式无效: ${invalidEmails.join(", ")}`
2859
+ };
2860
+ }
2861
+ const requestBody = {
2862
+ order_ids: params.order_ids,
2863
+ notify_action: params.notify_action || "order_payment_reminder",
2864
+ emails: params.emails
2865
+ };
2866
+ console.log("[Checkout] 发送支付链接邮件请求参数:", requestBody);
2867
+ this.logInfo("Calling batch email API", {
2868
+ url: "/order/batch-email",
2869
+ orderIds: requestBody.order_ids,
2870
+ orderIdsCount: requestBody.order_ids.length,
2871
+ notifyAction: requestBody.notify_action,
2872
+ emails: requestBody.emails,
2873
+ emailsCount: requestBody.emails.length
2874
+ });
2875
+ const response = await this.request.post(
2876
+ "/order/batch-email",
2877
+ requestBody
2878
+ );
2879
+ console.log("[Checkout] 支付链接邮件发送响应:", {
2880
+ status: response.status,
2881
+ message: response.message,
2882
+ data: response.data,
2883
+ response
2884
+ });
2885
+ if (response.status === true || response.status === 200) {
2886
+ console.log("[Checkout] 支付链接邮件发送成功");
2887
+ return {
2888
+ success: true,
2889
+ message: response.message || "支付链接邮件发送成功"
2890
+ };
2891
+ } else {
2892
+ const errorMessage = response.message || "支付链接邮件发送失败";
2893
+ console.error("[Checkout] 支付链接邮件发送失败:", errorMessage);
2894
+ return {
2895
+ success: false,
2896
+ message: errorMessage
2897
+ };
2898
+ }
2899
+ } catch (error) {
2900
+ console.error("[Checkout] 发送客户支付链接邮件失败:", error);
2901
+ const errorMessage = error instanceof Error ? error.message : "网络错误或服务器异常";
2902
+ return {
2903
+ success: false,
2904
+ message: `发送支付链接邮件失败: ${errorMessage}`
2905
+ };
2906
+ }
2907
+ }
2908
+ /**
2909
+ * 金额舍入
2910
+ *
2911
+ * @param amount 原始金额
2912
+ * @returns 舍入结果详情,包含原始金额、舍入后金额和舍入差额
2913
+ */
2914
+ async roundAmountAsync(amount) {
2915
+ var _a, _b;
2916
+ const result = await this.payment.roundAmountAsync(
2917
+ amount,
2918
+ (_a = this.otherParams.order_rounding_setting) == null ? void 0 : _a.interval,
2919
+ (_b = this.otherParams.order_rounding_setting) == null ? void 0 : _b.type
2920
+ );
2921
+ console.log(
2922
+ `[Checkout] 金额舍入完成 - 原始: ${result.originalAmount}, 舍入后: ${result.roundedAmount}, 差额: ${result.roundingDifference}`
2923
+ );
2924
+ return result;
2925
+ }
2926
+ async destroy() {
2927
+ var _a, _b, _c, _d;
2928
+ this.payment.wallet.clearAllCache();
2929
+ this.core.effects.offByModuleDestroy(this.name);
2930
+ await ((_b = (_a = this.order) == null ? void 0 : _a.destroy) == null ? void 0 : _b.call(_a));
2931
+ await ((_d = (_c = this.payment) == null ? void 0 : _c.destroy) == null ? void 0 : _d.call(_c));
2932
+ this.core.unregisterModule(this);
2933
+ console.log("[Checkout] 已销毁");
2934
+ }
2935
+ /**
2936
+ * 重置 store 状态
2937
+ *
2938
+ * 在创建新订单前调用,确保状态完全干净
2939
+ */
2940
+ async resetStoreStateAsync() {
2941
+ try {
2942
+ const prevOrderInfo = this.store.currentOrder ? {
2943
+ uuid: this.store.currentOrder.uuid,
2944
+ orderId: this.store.currentOrder.order_id
2945
+ } : null;
2946
+ console.log("[Checkout] 重置 store 状态,准备创建新订单", prevOrderInfo);
2947
+ this.store.currentOrder = void 0;
2948
+ this.store.localOrderData = void 0;
2949
+ this.store.cartSummary = void 0;
2950
+ this.store.stateAmount = "0.00";
2951
+ this.store.balanceDueAmount = "0.00";
2952
+ this.store.isOrderSynced = false;
2953
+ this.store.currentCustomer = void 0;
2954
+ this.store.lastError = void 0;
2955
+ this.store.cartItems = [];
2956
+ this.payment.wallet.clearAllCache();
2957
+ this.setStatus(import_types.CheckoutStatus.Ready);
2958
+ this.setStep(import_types.CheckoutStep.OrderConfirmation);
2959
+ console.log("[Checkout] Store 状态重置完成");
2960
+ if (prevOrderInfo) {
2961
+ await this.core.effects.emit(import_types.CheckoutHooks.OnOrderCleared, {
2962
+ previousOrder: prevOrderInfo,
2963
+ timestamp: Date.now()
2964
+ });
2965
+ }
2966
+ } catch (error) {
2967
+ console.error("[Checkout] 重置 store 状态失败:", error);
2968
+ }
2969
+ }
2970
+ /**
2971
+ * 手动清理已完成的订单状态(公开方法)
2972
+ *
2973
+ * 供UI层调用的公开方法,用于手动清理订单状态
2974
+ *
2975
+ * @returns 清理结果
2976
+ */
2977
+ async clearCompletedOrderAsync() {
2978
+ try {
2979
+ const prevOrderInfo = this.store.currentOrder ? {
2980
+ uuid: this.store.currentOrder.uuid,
2981
+ orderId: this.store.currentOrder.order_id
2982
+ } : null;
2983
+ await this.resetStoreStateAsync();
2984
+ return {
2985
+ success: true,
2986
+ message: prevOrderInfo ? "订单状态已成功清理" : "没有需要清理的订单状态",
2987
+ clearedOrder: prevOrderInfo
2988
+ };
2989
+ } catch (error) {
2990
+ console.error("[Checkout] 手动清理订单状态失败:", error);
2991
+ return {
2992
+ success: false,
2993
+ message: error instanceof Error ? error.message : "清理失败"
2994
+ };
2995
+ }
2996
+ }
2997
+ };
2998
+ // Annotate the CommonJS export names for ESM import in node:
2999
+ 0 && (module.exports = {
3000
+ CheckoutImpl,
3001
+ ...require("./types")
3002
+ });