@pisell/pisellos 0.0.567 → 0.0.569

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