@pisell/pisellos 3.0.76 → 3.0.77

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