@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,82 +1,116 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ generateRequestUniqueId: true,
8
+ PaymentModule: true
16
9
  };
17
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/modules/Payment/index.ts
21
- var Payment_exports = {};
22
- __export(Payment_exports, {
23
- PaymentModule: () => PaymentModule,
24
- generateRequestUniqueId: () => generateRequestUniqueId
10
+ exports.PaymentModule = void 0;
11
+ exports.generateRequestUniqueId = generateRequestUniqueId;
12
+ var _BaseModule = require("../BaseModule");
13
+ var _types = require("./types");
14
+ Object.keys(_types).forEach(function (key) {
15
+ if (key === "default" || key === "__esModule") return;
16
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
17
+ if (key in exports && exports[key] === _types[key]) return;
18
+ Object.defineProperty(exports, key, {
19
+ enumerable: true,
20
+ get: function () {
21
+ return _types[key];
22
+ }
23
+ });
25
24
  });
26
- module.exports = __toCommonJS(Payment_exports);
27
- var import_BaseModule = require("../BaseModule");
28
- var import_types = require("./types");
29
- var import_utils = require("../Cart/utils");
30
- var import_cash = require("./cash");
31
- var import_eftpos = require("./eftpos");
32
- var import_walletpass = require("./walletpass");
33
- var import_decimal = require("decimal.js");
34
- __reExport(Payment_exports, require("./types"), module.exports);
25
+ var _utils = require("../Cart/utils");
26
+ var _cash = require("./cash");
27
+ var _eftpos = require("./eftpos");
28
+ var _walletpass = require("./walletpass");
29
+ var _decimal = require("decimal.js");
30
+ /**
31
+ * 格式化金额为保留两位小数的字符串
32
+ */
35
33
  function formatAmount(amount) {
36
34
  try {
37
- const decimal = new import_decimal.Decimal(amount);
35
+ const decimal = new _decimal.Decimal(amount);
38
36
  return decimal.toFixed(2);
39
37
  } catch (error) {
40
38
  console.warn(`[PaymentModule] 金额格式化失败: ${amount},使用默认值 0.00`);
41
- return "0.00";
39
+ return '0.00';
42
40
  }
43
41
  }
42
+
43
+ /**
44
+ * 格式化日期时间为字符串
45
+ * 格式: YYYY-MM-DD HH:mm:ss
46
+ * 示例: 2025-12-10 16:14:50
47
+ */
44
48
  function formatDateTime(date) {
45
49
  const year = date.getFullYear();
46
- const month = String(date.getMonth() + 1).padStart(2, "0");
47
- const day = String(date.getDate()).padStart(2, "0");
48
- const hours = String(date.getHours()).padStart(2, "0");
49
- const minutes = String(date.getMinutes()).padStart(2, "0");
50
- const seconds = String(date.getSeconds()).padStart(2, "0");
50
+ const month = String(date.getMonth() + 1).padStart(2, '0');
51
+ const day = String(date.getDate()).padStart(2, '0');
52
+ const hours = String(date.getHours()).padStart(2, '0');
53
+ const minutes = String(date.getMinutes()).padStart(2, '0');
54
+ const seconds = String(date.getSeconds()).padStart(2, '0');
51
55
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
52
56
  }
57
+
58
+ /**
59
+ * 生成请求唯一ID
60
+ * 格式: 年月日时分秒毫秒+4位随机数
61
+ * 示例: 20241201143025123456
62
+ */
53
63
  function generateRequestUniqueId() {
54
- const now = /* @__PURE__ */ new Date();
64
+ const now = new Date();
55
65
  const year = now.getFullYear();
56
- const month = String(now.getMonth() + 1).padStart(2, "0");
57
- const day = String(now.getDate()).padStart(2, "0");
58
- const hour = String(now.getHours()).padStart(2, "0");
59
- const minute = String(now.getMinutes()).padStart(2, "0");
60
- const second = String(now.getSeconds()).padStart(2, "0");
61
- const millisecond = String(now.getMilliseconds()).padStart(3, "0");
62
- const randomDigits = Math.floor(Math.random() * 9e3) + 1e3;
66
+ const month = String(now.getMonth() + 1).padStart(2, '0');
67
+ const day = String(now.getDate()).padStart(2, '0');
68
+ const hour = String(now.getHours()).padStart(2, '0');
69
+ const minute = String(now.getMinutes()).padStart(2, '0');
70
+ const second = String(now.getSeconds()).padStart(2, '0');
71
+ const millisecond = String(now.getMilliseconds()).padStart(3, '0');
72
+ const randomDigits = Math.floor(Math.random() * 9000) + 1000; // 1000-9999的4位随机数
73
+
63
74
  return `${year}${month}${day}${hour}${minute}${second}${millisecond}${randomDigits}`;
64
75
  }
65
- var PaymentModule = class extends import_BaseModule.BaseModule {
76
+ function normalizeCustomPaymentId(paymentItem) {
77
+ const rawId = paymentItem.custom_payment_id ?? paymentItem.id ?? 0;
78
+ const parsedId = Number(rawId);
79
+ if (!Number.isFinite(parsedId)) return 0;
80
+ return parsedId;
81
+ }
82
+
83
+ /**
84
+ * 支付模块实现
85
+ *
86
+ * 负责处理支付相关的数据管理和本地存储
87
+ */
88
+ class PaymentModule extends _BaseModule.BaseModule {
89
+ defaultName = 'pay';
90
+ defaultVersion = '1.0.0';
91
+ request;
92
+ app; // App instance
93
+ store;
94
+ window; // WindowPlugin 实例
95
+ dbManager; // IndexDBManager 实例
96
+ logger; // LoggerManager 实例
97
+ voucherUpdateLockByOrderUuid = new Map();
98
+ otherParams = {};
99
+
100
+ // 支付方式实例
101
+ cash;
102
+ eftpos;
103
+ wallet;
66
104
  constructor(name, version) {
67
105
  super(name || "payment", version);
68
- this.defaultName = "pay";
69
- this.defaultVersion = "1.0.0";
70
- // LoggerManager 实例
71
- this.voucherUpdateLockByOrderUuid = /* @__PURE__ */ new Map();
72
- this.otherParams = {};
73
- this.cash = new import_cash.CashPaymentImpl(this);
74
- this.eftpos = new import_eftpos.EftposPaymentImpl(this);
75
- this.wallet = new import_walletpass.WalletPassPaymentImpl(this);
106
+ // 初始化支付方式实例
107
+ this.cash = new _cash.CashPaymentImpl(this);
108
+ this.eftpos = new _eftpos.EftposPaymentImpl(this);
109
+ this.wallet = new _walletpass.WalletPassPaymentImpl(this);
76
110
  }
77
111
  runVoucherUpdateLocked(orderUuid, task) {
78
112
  const previous = this.voucherUpdateLockByOrderUuid.get(orderUuid) || Promise.resolve();
79
- const next = previous.catch(() => void 0).then(task).finally(() => {
113
+ const next = previous.catch(() => undefined).then(task).finally(() => {
80
114
  if (this.voucherUpdateLockByOrderUuid.get(orderUuid) === next) {
81
115
  this.voucherUpdateLockByOrderUuid.delete(orderUuid);
82
116
  }
@@ -85,18 +119,21 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
85
119
  return next;
86
120
  }
87
121
  normalizeVoucherPaymentItems(voucherPaymentItems) {
88
- const normalized = /* @__PURE__ */ new Map();
122
+ const normalized = new Map();
89
123
  for (const item of voucherPaymentItems || []) {
90
- if (!(item == null ? void 0 : item.voucher_id)) {
124
+ if (!item?.voucher_id) {
91
125
  throw new Error(`代金券支付项缺少 voucher_id: ${JSON.stringify(item)}`);
92
126
  }
93
- const orderPaymentType = item.order_payment_type || "normal";
127
+ const orderPaymentType = item.order_payment_type || 'normal';
94
128
  const key = `${item.voucher_id}|${orderPaymentType}`;
95
- normalized.set(key, { ...item, order_payment_type: orderPaymentType });
129
+ normalized.set(key, {
130
+ ...item,
131
+ order_payment_type: orderPaymentType
132
+ });
96
133
  }
97
134
  return {
98
135
  items: Array.from(normalized.values()),
99
- originalCount: (voucherPaymentItems == null ? void 0 : voucherPaymentItems.length) || 0,
136
+ originalCount: voucherPaymentItems?.length || 0,
100
137
  normalizedCount: normalized.size
101
138
  };
102
139
  }
@@ -104,30 +141,48 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
104
141
  this.core = core;
105
142
  this.store = options.store;
106
143
  this.otherParams = options.otherParams || {};
107
- this.request = core.getPlugin("request");
108
- const appPlugin = core.getPlugin("app");
109
- this.window = core.getPlugin("window");
144
+
145
+ // 获取依赖的插件
146
+ this.request = core.getPlugin('request');
147
+ const appPlugin = core.getPlugin('app');
148
+ this.window = core.getPlugin('window');
110
149
  if (!this.request) {
111
- throw new Error("支付模块需要 request 插件支持");
150
+ throw new Error('支付模块需要 request 插件支持');
112
151
  }
113
152
  if (!appPlugin) {
114
- throw new Error("支付模块需要 app 插件支持");
153
+ throw new Error('支付模块需要 app 插件支持');
115
154
  }
116
155
  this.app = appPlugin.getApp();
117
156
  this.dbManager = this.app.dbManager;
118
157
  this.logger = this.app.logger;
119
- await this.ensurePaymentTables();
158
+
159
+ // 确保支付模块所需的对象存储已创建
160
+ // await this.ensurePaymentTables();
161
+
120
162
  this.registerNetworkHandlers();
121
- console.log("[PaymentModule] 初始化完成");
122
- this.logInfo("PaymentModule initialized successfully");
163
+
164
+ // // 预连接数据库
165
+ // this.dbManager.connect()
166
+
167
+ this.logInfo('PaymentModule initialized successfully');
123
168
  }
169
+
170
+ /**
171
+ * 更新父级解决方案透传的运行态参数,主要用于日志父模块等上下文。
172
+ *
173
+ * @example
174
+ * paymentModule.updateOtherParams({ fatherModule: 'bookingTicket' });
175
+ */
176
+ updateOtherParams(params) {
177
+ this.otherParams = params || {};
178
+ }
179
+
124
180
  /**
125
181
  * 记录信息日志
126
182
  */
127
183
  logInfo(title, metadata) {
128
- var _a, _b;
129
- if ((_a = this.otherParams) == null ? void 0 : _a.fatherModule) {
130
- const fatherModule = this.core.getModule((_b = this.otherParams) == null ? void 0 : _b.fatherModule);
184
+ if (this.otherParams?.fatherModule) {
185
+ const fatherModule = this.core.getModule(this.otherParams?.fatherModule);
131
186
  if (fatherModule) {
132
187
  fatherModule.logInfo(`${title}`, metadata);
133
188
  return;
@@ -135,31 +190,33 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
135
190
  }
136
191
  if (this.logger) {
137
192
  this.logger.addLog({
138
- type: "info",
193
+ type: 'info',
139
194
  title: `[PaymentModule] ${title}`,
140
195
  metadata: metadata || {}
141
196
  });
142
197
  }
143
198
  }
199
+
144
200
  /**
145
201
  * 记录警告日志
146
202
  */
147
203
  logWarning(title, metadata) {
148
204
  if (this.logger) {
149
205
  this.logger.addLog({
150
- type: "warning",
206
+ type: 'warning',
151
207
  title: `[PaymentModule] ${title}`,
152
208
  metadata: metadata || {}
153
209
  });
154
210
  }
155
211
  }
212
+
156
213
  /**
157
214
  * 记录错误日志
158
215
  */
159
216
  logError(title, error, metadata) {
160
217
  if (this.logger) {
161
218
  this.logger.addLog({
162
- type: "error",
219
+ type: 'error',
163
220
  title: `[PaymentModule] ${title}`,
164
221
  metadata: {
165
222
  error: error ? {
@@ -167,246 +224,182 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
167
224
  stack: error.stack,
168
225
  code: error.code,
169
226
  ...error
170
- } : void 0,
171
- ...metadata || {}
227
+ } : undefined,
228
+ ...(metadata || {})
172
229
  }
173
230
  });
174
231
  }
175
232
  }
233
+
176
234
  /**
177
235
  * 记录调试日志
178
236
  */
179
237
  logDebug(title, metadata) {
180
238
  if (this.logger) {
181
239
  this.logger.addLog({
182
- type: "debug",
240
+ type: 'debug',
183
241
  title: `[PaymentModule] ${title}`,
184
242
  metadata: metadata || {}
185
243
  });
186
244
  }
187
245
  }
246
+
188
247
  /**
189
248
  * 网络恢复以后,尝试执行队列
190
249
  *
191
250
  */
192
251
  registerNetworkHandlers() {
193
- const network = this.app.plugins.get("network");
194
- this.logInfo("Registering network status listener");
195
- network == null ? void 0 : network.addListener("networkStatusChange", async (status) => {
196
- console.log("网络状态:", status.connected);
197
- this.logInfo("Network status changed", {
252
+ const network = this.app.plugins.get('network');
253
+ this.logInfo('Registering network status listener');
254
+ network?.addListener('networkStatusChange', async status => {
255
+ this.logInfo('Network status changed', {
198
256
  connected: status.connected,
199
257
  previousStatus: status.previousStatus
200
258
  });
201
259
  if (status.connected) {
202
- this.logInfo("Network reconnected");
260
+ this.logInfo('Network reconnected');
261
+ // 网络恢复时的处理逻辑可以在这里添加
203
262
  }
204
263
  });
205
264
  }
206
- async filterPayMethods(payMethods) {
207
- payMethods = payMethods.filter((method) => method.status === 1 && method.disable === 0);
208
- const walletPassMethod = payMethods.find((method) => method.code === "WALLET_PASS");
209
- if (walletPassMethod) {
210
- payMethods.forEach((method) => {
211
- if (method.code === "PRODUCTVOUCHER" || method.code === "GIFTCARD" || method.code === "POINTCARD") {
212
- method.channel_application = walletPassMethod.channel_application;
213
- }
214
- });
215
- } else {
216
- payMethods = payMethods.filter((method) => method.code !== "PRODUCTVOUCHER" && method.code !== "GIFTCARD" && method.code !== "POINTCARD");
217
- }
218
- return payMethods;
219
- }
265
+
220
266
  /**
221
267
  * 获取支付方式列表
222
268
  */
223
269
  async getPayMethodListAsync() {
224
- this.logInfo("Starting getPayMethodListAsync");
270
+ this.logInfo('Starting getPayMethodListAsync');
225
271
  try {
226
- let cachedMethods = [];
227
- try {
228
- cachedMethods = await this.dbManager.getAll("pay_method");
229
- } catch (dbError) {
230
- console.warn("[PaymentModule] pay_method 表不存在,将从服务器获取数据");
231
- }
232
- const hasCache = cachedMethods.length > 0;
233
- if (hasCache) {
234
- this.refreshPaymentMethodsInBackground(cachedMethods);
235
- return cachedMethods;
236
- }
237
- const response = await this.request.get("/pay/custom-payment/all");
238
- response.data = this.filterPayMethods(response.data);
239
- const payMethods = response.data || [];
240
- try {
241
- for (const method of payMethods) {
242
- await this.dbManager.update("pay_method", method);
243
- }
244
- } catch (dbError) {
245
- console.warn("[PaymentModule] 无法缓存支付方式,pay_method 表不存在");
246
- }
247
- await this.core.effects.emit(
248
- `${this.name}:onPaymentMethodsLoaded`,
249
- payMethods
250
- );
251
- this.logInfo("getPayMethodListAsync completed successfully", {
272
+ const response = await this.request.get('/pay/custom-payment/all', {
273
+ filterPaymentMethods: true
274
+ }, {
275
+ osServer: true
276
+ });
277
+ const payMethods = response?.data || response || [];
278
+ this.logInfo('getPayMethodListAsync completed successfully', {
252
279
  payMethods
253
280
  });
254
281
  return payMethods;
255
282
  } catch (error) {
256
- console.error("[PaymentModule] 获取支付方式列表失败", error);
257
- this.logError("getPayMethodListAsync failed", error);
283
+ console.error('[PaymentModule] 获取支付方式列表失败', error);
284
+ this.logError('getPayMethodListAsync failed', error);
285
+ // 如果所有操作都失败,返回空数组
258
286
  return [];
259
287
  }
260
288
  }
261
- /**
262
- * 后台刷新支付方式列表
263
- */
264
- async refreshPaymentMethodsInBackground(cachedMethods) {
265
- this.logInfo("Starting refreshPaymentMethodsInBackground", {
266
- cachedMethodsCount: cachedMethods.length
267
- });
268
- try {
269
- console.log("[PaymentModule] 后台刷新支付方式列表...");
270
- const response = await this.request.get("/pay/custom-payment/all");
271
- response.data = this.filterPayMethods(response.data);
272
- const newPayMethods = response.data || [];
273
- const hasChanges = this.hasPaymentMethodsChanged(
274
- cachedMethods,
275
- newPayMethods
276
- );
277
- if (hasChanges) {
278
- console.log("[PaymentModule] 支付方式列表已更新");
279
- this.logInfo("Payment methods updated in background", {
280
- oldCount: cachedMethods.length,
281
- newCount: newPayMethods.length
282
- });
283
- try {
284
- for (const method of cachedMethods) {
285
- await this.dbManager.delete("pay_method", method.id);
286
- }
287
- for (const method of newPayMethods) {
288
- await this.dbManager.update("pay_method", method);
289
- }
290
- } catch (dbError) {
291
- console.warn("[PaymentModule] 无法更新支付方式缓存", dbError);
292
- }
293
- const eventData = {
294
- oldMethods: cachedMethods,
295
- newMethods: newPayMethods
296
- };
297
- await this.core.effects.emit(
298
- `${this.name}:onPaymentMethodsChanged`,
299
- eventData
300
- );
301
- } else {
302
- console.log("[PaymentModule] 支付方式列表无变化");
303
- }
304
- } catch (error) {
305
- console.error("[PaymentModule] 后台刷新支付方式失败", error);
306
- }
307
- }
308
- /**
309
- * 检查支付方式列表是否有变化
310
- */
311
- hasPaymentMethodsChanged(oldMethods, newMethods) {
312
- if (oldMethods.length !== newMethods.length) {
313
- return true;
314
- }
315
- const oldMethodsMap = new Map(
316
- oldMethods.map((method) => [method.id, method])
317
- );
318
- for (const newMethod of newMethods) {
319
- const oldMethod = oldMethodsMap.get(newMethod.id);
320
- if (!oldMethod) {
321
- return true;
322
- }
323
- if (oldMethod.code !== newMethod.code || oldMethod.name !== newMethod.name || oldMethod.type !== newMethod.type || oldMethod.description !== newMethod.description || oldMethod.status !== newMethod.status || oldMethod.disable !== newMethod.disable || oldMethod.is_surcharge !== newMethod.is_surcharge || oldMethod.fixed !== newMethod.fixed || oldMethod.percentage !== newMethod.percentage || oldMethod.enabled !== newMethod.enabled || JSON.stringify(oldMethod.channel_application || []) !== JSON.stringify(newMethod.channel_application || []) || JSON.stringify(oldMethod.companies || []) !== JSON.stringify(newMethod.companies || []) || JSON.stringify(oldMethod.metadata || {}) !== JSON.stringify(newMethod.metadata || {})) {
324
- console.log(`[PaymentModule] 支付方式 ${newMethod.id} (${newMethod.code}) 发生变化:`, {
325
- id: newMethod.id,
326
- changes: {
327
- code: oldMethod.code !== newMethod.code ? { old: oldMethod.code, new: newMethod.code } : void 0,
328
- name: oldMethod.name !== newMethod.name ? { old: oldMethod.name, new: newMethod.name } : void 0,
329
- type: oldMethod.type !== newMethod.type ? { old: oldMethod.type, new: newMethod.type } : void 0,
330
- description: oldMethod.description !== newMethod.description ? { old: oldMethod.description, new: newMethod.description } : void 0,
331
- status: oldMethod.status !== newMethod.status ? { old: oldMethod.status, new: newMethod.status } : void 0,
332
- disable: oldMethod.disable !== newMethod.disable ? { old: oldMethod.disable, new: newMethod.disable } : void 0,
333
- is_surcharge: oldMethod.is_surcharge !== newMethod.is_surcharge ? { old: oldMethod.is_surcharge, new: newMethod.is_surcharge } : void 0,
334
- fixed: oldMethod.fixed !== newMethod.fixed ? { old: oldMethod.fixed, new: newMethod.fixed } : void 0,
335
- percentage: oldMethod.percentage !== newMethod.percentage ? { old: oldMethod.percentage, new: newMethod.percentage } : void 0,
336
- enabled: oldMethod.enabled !== newMethod.enabled ? { old: oldMethod.enabled, new: newMethod.enabled } : void 0,
337
- channel_application: JSON.stringify(oldMethod.channel_application || []) !== JSON.stringify(newMethod.channel_application || []) ? { old: oldMethod.channel_application, new: newMethod.channel_application } : void 0,
338
- companies: JSON.stringify(oldMethod.companies || []) !== JSON.stringify(newMethod.companies || []) ? { old: oldMethod.companies, new: newMethod.companies } : void 0,
339
- metadata: JSON.stringify(oldMethod.metadata || {}) !== JSON.stringify(newMethod.metadata || {}) ? { old: oldMethod.metadata, new: newMethod.metadata } : void 0
340
- }
341
- });
342
- return true;
343
- }
344
- }
345
- return false;
346
- }
289
+
347
290
  /**
348
291
  * 获取订单列表
349
292
  */
293
+ /** @deprecated */
350
294
  async getOrderListAsync() {
351
295
  try {
352
- return await this.dbManager.getAll("order");
296
+ return await this.dbManager.getAll('order');
353
297
  } catch (error) {
354
- console.error("[PaymentModule] 获取订单列表失败", error);
298
+ console.error('[PaymentModule] 获取订单列表失败', error);
355
299
  return [];
356
300
  }
357
301
  }
302
+
358
303
  /**
359
304
  * 根据订单UUID获取支付订单(新方法)
360
305
  */
361
306
  async getPaymentOrderByUuidAsync(orderUuid) {
362
307
  try {
363
- return await this.dbManager.get("order", orderUuid, true);
308
+ return await this.dbManager.get('order', orderUuid, true);
364
309
  } catch (error) {
365
- console.error("[PaymentModule] 获取支付订单失败", error);
310
+ console.error('[PaymentModule] 获取支付订单失败', error);
366
311
  return null;
367
312
  }
368
313
  }
314
+
369
315
  /**
370
316
  * 创建支付订单(新方法,专注支付数据)
371
317
  */
372
318
  async createPaymentOrderAsync(params) {
373
- this.logInfo("Starting createPaymentOrderAsync", {
319
+ this.logInfo('Starting createPaymentOrderAsync', {
374
320
  orderId: params.order_id,
375
321
  totalAmount: params.total_amount
376
322
  });
377
323
  try {
324
+ // 检测是否有重复的 order_id
325
+ // console.time('createLocalOrderAsync: getExistingOrder')
326
+ // const existingOrder = await this.dbManager.get('order', params.order_id);
327
+ // const existingOrders = await this.dbManager.getAll('order');
328
+ // const existingOrder = existingOrders.find(
329
+ // (order: PaymentOrder) => String(order.id) === String(params.order_id),
330
+ // );
331
+
332
+ // this.logInfo('createPaymentOrderAsync existingOrder', {
333
+ // existingOrder
334
+ // });
335
+ // console.timeEnd('createLocalOrderAsync: getExistingOrder')
336
+ // const existingOrder = existingOrders.find(
337
+ // (order: PaymentOrder) => String(order.id) === String(params.order_id),
338
+ // );
339
+
340
+ // if (existingOrder) {
341
+ // // 如果存在相同 order_id 的订单,更新该订单信息
342
+ // this.logInfo(
343
+ // `createPaymentOrderAsync found duplicate order ID: ${params.order_id}, updating existing payment order`,
344
+ // );
345
+
346
+ // // const originalOrder = { ...existingOrder };
347
+ // existingOrder.order_info = params.order_info;
348
+ // existingOrder.total_amount = params.total_amount;
349
+ // existingOrder.is_deposit = params.is_deposit || 0;
350
+ // existingOrder.deposit_amount = params.deposit_amount || '0.00';
351
+
352
+ // // 重新计算待付金额
353
+ // this.recalculateOrderAmount(existingOrder);
354
+
355
+ // // 更新到数据库
356
+ // await this.dbManager.update('order', existingOrder);
357
+
358
+ // // 触发更新事件
359
+ // this.core.effects.emit(
360
+ // `${this.name}:onOrderUpdated`,
361
+ // existingOrder,
362
+ // );
363
+
364
+ // return existingOrder;
365
+ // } else {
366
+ // 创建新的支付订单
378
367
  const newOrder = {
379
- uuid: (0, import_utils.getUniqueId)("pay_order_"),
368
+ uuid: (0, _utils.getUniqueId)('pay_order_'),
380
369
  id: params.order_id,
381
370
  order_id: params.order_id,
382
371
  order_info: params.order_info,
383
- payment_status: import_types.PaymentStatus.Processing,
372
+ payment_status: _types.PaymentStatus.Processing,
384
373
  payment: [],
385
374
  adjust_offline_payments: [],
386
375
  total_amount: params.total_amount,
387
376
  expect_amount: params.total_amount,
388
- tax_fee: "0.00",
377
+ tax_fee: '0.00',
389
378
  is_deposit: params.is_deposit || 0,
390
- deposit_amount: params.deposit_amount || "0.00"
379
+ deposit_amount: params.deposit_amount || '0.00'
391
380
  };
381
+
382
+ // 🔧 新增: 处理云端已存在的支付项
392
383
  if (params.existPayment && params.existPayment.length > 0) {
393
- const currentTime = formatDateTime(/* @__PURE__ */ new Date());
394
- newOrder.payment = params.existPayment.map((payment) => ({
384
+ const currentTime = formatDateTime(new Date());
385
+ newOrder.payment = params.existPayment.map(payment => ({
395
386
  ...payment,
396
387
  isSynced: true,
397
388
  // 标记为已同步
398
- status: payment.status || "active",
389
+ status: payment.status || 'active',
399
390
  // 如果云端支付项已有时间戳,则保留;否则使用当前时间
400
391
  created_at: payment.created_at || currentTime,
401
392
  updated_at: payment.updated_at || currentTime
402
393
  }));
394
+
395
+ // 重新计算待付金额
403
396
  this.recalculateOrderAmount(newOrder);
404
- this.logInfo("创建订单时包含云端支付项", {
397
+ this.logInfo('创建订单时包含云端支付项', {
405
398
  orderId: params.order_id,
406
399
  existPaymentCount: params.existPayment.length,
407
400
  totalAmount: newOrder.total_amount,
408
401
  expectAmount: newOrder.expect_amount,
409
- paymentDetails: params.existPayment.map((p) => ({
402
+ paymentDetails: params.existPayment.map(p => ({
410
403
  uuid: p.uuid,
411
404
  code: p.code,
412
405
  amount: p.amount,
@@ -416,67 +409,75 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
416
409
  }))
417
410
  });
418
411
  }
412
+
413
+ // 🚀 性能监控:记录数据库添加操作耗时
419
414
  const dbAddStartTime = Date.now();
420
- await this.dbManager.add("order", newOrder, true);
415
+ await this.dbManager.add('order', newOrder, true);
421
416
  const dbAddDuration = Date.now() - dbAddStartTime;
422
- this.logInfo("Database add operation completed", {
423
- operation: "dbManager.add",
424
- table: "order",
417
+ this.logInfo('Database add operation completed', {
418
+ operation: 'dbManager.add',
419
+ table: 'order',
425
420
  orderUuid: newOrder.uuid,
426
421
  orderId: newOrder.order_id,
427
422
  duration: `${dbAddDuration}ms`,
428
- performance: dbAddDuration > 100 ? "slow" : dbAddDuration > 50 ? "medium" : "fast"
423
+ performance: dbAddDuration > 100 ? 'slow' : dbAddDuration > 50 ? 'medium' : 'fast'
429
424
  });
430
425
  setTimeout(() => {
431
426
  this.core.effects.emit(`${this.name}:onOrderAdded`, newOrder);
432
427
  }, 0);
433
428
  return newOrder;
429
+ // }
434
430
  } catch (error) {
435
- console.error("[PaymentModule] 创建支付订单失败", error);
436
- this.logError("createPaymentOrderAsync failed", error, {
431
+ console.error('[PaymentModule] 创建支付订单失败', error);
432
+ this.logError('createPaymentOrderAsync failed', error, {
437
433
  orderId: params.order_id
438
434
  });
439
435
  throw error;
440
436
  }
441
437
  }
438
+
442
439
  /**
443
440
  * 删除支付订单(新方法)
444
441
  */
445
442
  async deletePaymentOrderAsync(orderUuid) {
446
443
  try {
447
- const order = await this.dbManager.get("order", orderUuid);
444
+ const order = await this.dbManager.get('order', orderUuid);
448
445
  if (order) {
449
- await this.dbManager.delete("order", orderUuid);
446
+ await this.dbManager.delete('order', orderUuid);
450
447
  await this.core.effects.emit(`${this.name}:onOrderDeleted`, order);
451
- console.log("[PaymentModule] 支付订单删除成功:", orderUuid);
452
448
  }
453
449
  } catch (error) {
454
- console.error("[PaymentModule] 删除支付订单失败", error);
450
+ console.error('[PaymentModule] 删除支付订单失败', error);
455
451
  throw error;
456
452
  }
457
453
  }
454
+
458
455
  /**
459
456
  * 更新订单
460
457
  */
461
458
  async updateOrderAsync(orderUuid, params) {
462
459
  try {
463
- const order = await this.dbManager.get("order", orderUuid);
460
+ const order = await this.dbManager.get('order', orderUuid);
464
461
  if (order) {
465
- const updatedOrder = { ...order, ...params };
462
+ const updatedOrder = {
463
+ ...order,
464
+ ...params
465
+ };
466
466
  this.recalculateOrderAmount(updatedOrder);
467
- await this.dbManager.update("order", updatedOrder);
467
+ await this.dbManager.update('order', updatedOrder);
468
468
  await this.core.effects.emit(`${this.name}:onOrderUpdated`, updatedOrder);
469
469
  await this.core.effects.emit(`${this.name}:onOrderChanged`, {
470
- action: "update",
470
+ action: 'update',
471
471
  order: updatedOrder,
472
472
  originalOrder: order
473
473
  });
474
474
  }
475
475
  } catch (error) {
476
- console.error("[PaymentModule] 更新订单失败", error);
476
+ console.error('[PaymentModule] 更新订单失败', error);
477
477
  throw error;
478
478
  }
479
479
  }
480
+
480
481
  /**
481
482
  * 基于UUID替换订单ID
482
483
  *
@@ -488,28 +489,35 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
488
489
  * @returns 更新后的订单对象,如果订单不存在则返回null
489
490
  */
490
491
  async replaceOrderIdByUuidAsync(orderUuid, newOrderId) {
491
- this.logInfo("Starting replaceOrderIdByUuidAsync", {
492
+ this.logInfo('Starting replaceOrderIdByUuidAsync', {
492
493
  orderUuid,
493
494
  newOrderId
494
495
  });
495
496
  try {
496
- const existingOrder = await this.dbManager.get("order", orderUuid);
497
+ // 获取现有订单
498
+ const existingOrder = await this.dbManager.get('order', orderUuid);
497
499
  if (!existingOrder) {
498
- this.logWarning("Order not found for UUID replacement", { orderUuid });
500
+ this.logWarning('Order not found for UUID replacement', {
501
+ orderUuid
502
+ });
499
503
  return null;
500
504
  }
501
- const allOrders = await this.dbManager.getAll("order");
502
- const duplicateOrder = allOrders.find(
503
- (order) => String(order.order_id) === String(newOrderId) && order.uuid !== orderUuid
504
- );
505
+
506
+ // 检查新的订单ID是否已经存在
507
+ const allOrders = await this.dbManager.getAll('order');
508
+ const duplicateOrder = allOrders.find(order => String(order.order_id) === String(newOrderId) && order.uuid !== orderUuid);
505
509
  if (duplicateOrder) {
506
- this.logWarning("New order ID already exists", {
510
+ this.logWarning('New order ID already exists', {
507
511
  newOrderId,
508
512
  existingOrderUuid: duplicateOrder.uuid
509
513
  });
510
514
  throw new Error(`订单ID ${newOrderId} 已存在`);
511
515
  }
516
+
517
+ // 保存原始订单ID用于日志
512
518
  const originalOrderId = existingOrder.id;
519
+
520
+ // 更新订单ID
513
521
  const updatedOrder = {
514
522
  ...existingOrder,
515
523
  id: newOrderId,
@@ -520,13 +528,17 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
520
528
  order_id: newOrderId,
521
529
  // 保留原始本地订单ID作为参考
522
530
  original_local_order_id: originalOrderId,
523
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
531
+ updated_at: new Date().toISOString()
524
532
  }
525
533
  };
526
- await this.dbManager.update("order", updatedOrder);
534
+
535
+ // 更新到数据库
536
+ await this.dbManager.update('order', updatedOrder);
537
+
538
+ // 触发事件
527
539
  await this.core.effects.emit(`${this.name}:onOrderUpdated`, updatedOrder);
528
540
  await this.core.effects.emit(`${this.name}:onOrderChanged`, {
529
- action: "order_id_replaced",
541
+ action: 'order_id_replaced',
530
542
  order: updatedOrder,
531
543
  originalOrder: existingOrder,
532
544
  metadata: {
@@ -534,22 +546,22 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
534
546
  newOrderId
535
547
  }
536
548
  });
537
- this.logInfo("Order ID replacement completed successfully", {
549
+ this.logInfo('Order ID replacement completed successfully', {
538
550
  orderUuid,
539
551
  originalOrderId,
540
552
  newOrderId
541
553
  });
542
- console.log(`[PaymentModule] 订单ID替换成功: ${originalOrderId} → ${newOrderId}`);
543
554
  return updatedOrder;
544
555
  } catch (error) {
545
- console.error("[PaymentModule] 替换订单ID失败", error);
546
- this.logError("replaceOrderIdByUuidAsync failed", error, {
556
+ console.error('[PaymentModule] 替换订单ID失败', error);
557
+ this.logError('replaceOrderIdByUuidAsync failed', error, {
547
558
  orderUuid,
548
559
  newOrderId
549
560
  });
550
561
  throw error;
551
562
  }
552
563
  }
564
+
553
565
  /**
554
566
  * 获取支付项(新方法)
555
567
  *
@@ -559,15 +571,18 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
559
571
  */
560
572
  async getPaymentItemsAsync(orderUuid, includeVoided = false) {
561
573
  if (!orderUuid) {
562
- throw new Error("orderUuid is required");
574
+ throw new Error('orderUuid is required');
563
575
  }
564
576
  const order = await this.getPaymentOrderByUuidAsync(orderUuid);
565
- const allPayments = (order == null ? void 0 : order.payment) || [];
577
+ const allPayments = order?.payment || [];
566
578
  if (includeVoided) {
567
579
  return allPayments;
568
580
  }
569
- return allPayments.filter((payment) => payment.status !== "voided");
581
+
582
+ // 默认只返回活跃的支付项
583
+ return allPayments.filter(payment => payment.status !== 'voided');
570
584
  }
585
+
571
586
  /**
572
587
  * 获取所有支付项(包括已撤销的)
573
588
  *
@@ -577,47 +592,51 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
577
592
  async getAllPaymentItemsAsync(orderUuid) {
578
593
  return this.getPaymentItemsAsync(orderUuid, true);
579
594
  }
595
+
580
596
  /**
581
597
  * 为某个订单添加支付项(新方法)
582
598
  */
583
599
  async addPaymentItemAsync(orderUuid, paymentItem) {
584
- var _a, _b, _c, _d;
585
- this.logInfo("Starting addPaymentItemAsync", {
600
+ this.logInfo('Starting addPaymentItemAsync', {
586
601
  orderUuid,
587
602
  paymentAmount: paymentItem.amount,
588
603
  paymentCode: paymentItem.code,
589
604
  orderPaymentType: paymentItem.order_payment_type
590
605
  });
591
606
  try {
592
- this.logInfo("准备获取订单", {
607
+ this.logInfo('准备获取订单', {
593
608
  orderUuid
594
609
  });
595
610
  const order = await this.getPaymentOrderByUuidAsync(orderUuid);
596
- this.logInfo("获取订单信息成功", {
611
+ this.logInfo('获取订单信息成功', {
597
612
  orderUuid,
598
613
  order
599
614
  });
600
615
  if (!order) {
601
616
  throw new Error(`Order not found: ${orderUuid}`);
602
617
  }
603
- const expectAmount = new import_decimal.Decimal(order.expect_amount);
618
+
619
+ // 🔒 支付锁检查:如果订单待付金额已经为0,不允许继续添加支付项
620
+ const expectAmount = new _decimal.Decimal(order.expect_amount);
604
621
  const paidDepositAmount = order.payment.reduce((sum, payment) => {
605
- if (payment.order_payment_type === "deposit" && payment.status !== "voided") {
606
- return sum.plus(new import_decimal.Decimal(payment.amount));
622
+ if (payment.order_payment_type === 'deposit' && payment.status !== 'voided') {
623
+ return sum.plus(new _decimal.Decimal(payment.amount));
607
624
  }
608
625
  return sum;
609
- }, new import_decimal.Decimal(0));
610
- const expectedDepositAmount = new import_decimal.Decimal(order.deposit_amount || "0").sub(paidDepositAmount);
626
+ }, new _decimal.Decimal(0));
627
+ const expectedDepositAmount = new _decimal.Decimal(order.deposit_amount || '0').sub(paidDepositAmount);
628
+
629
+ // 有一种特殊情况,订单金额为 0,但是定金金额>0,且此时是定金状态的,允许添加支付项
611
630
  if (expectAmount.lte(0) && expectedDepositAmount.eq(0)) {
612
631
  const warningMessage = `订单 ${orderUuid} 待付金额已为0,不允许添加新的支付项`;
613
- console.warn("[PaymentModule] Payment lock triggered:", {
632
+ console.warn('[PaymentModule] Payment lock triggered:', {
614
633
  orderUuid,
615
634
  expectAmount: order.expect_amount,
616
635
  attemptedPaymentAmount: paymentItem.amount,
617
636
  attemptedPaymentCode: paymentItem.code,
618
- reason: "Order already fully paid"
637
+ reason: 'Order already fully paid'
619
638
  });
620
- this.logError("addPaymentItemAsync blocked by payment lock", new Error(warningMessage), {
639
+ this.logError('addPaymentItemAsync blocked by payment lock', new Error(warningMessage), {
621
640
  orderUuid,
622
641
  expectAmount: order.expect_amount,
623
642
  paymentItem
@@ -625,129 +644,134 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
625
644
  throw new Error(warningMessage);
626
645
  }
627
646
  let paymentUuid;
628
- if ((_a = paymentItem.metadata) == null ? void 0 : _a.unique_payment_number) {
647
+ if (paymentItem.metadata?.unique_payment_number) {
629
648
  paymentUuid = paymentItem.metadata.unique_payment_number;
630
649
  } else {
631
- paymentUuid = (0, import_utils.getUniqueId)("payment_");
650
+ paymentUuid = (0, _utils.getUniqueId)('payment_');
632
651
  }
633
- const currentTime = formatDateTime(/* @__PURE__ */ new Date());
652
+ const currentTime = formatDateTime(new Date());
634
653
  const newPaymentItem = {
635
654
  uuid: paymentUuid,
636
- custom_payment_id: paymentItem.custom_payment_id || 0,
655
+ custom_payment_id: normalizeCustomPaymentId(paymentItem),
637
656
  name: paymentItem.name,
638
657
  code: paymentItem.code,
639
658
  type: paymentItem.type,
640
659
  amount: formatAmount(paymentItem.amount),
641
- voucher_id: paymentItem.voucher_id || "",
642
- rounding_amount: paymentItem.rounding_amount || "0.00",
660
+ voucher_id: paymentItem.voucher_id || '',
661
+ wallet_pass_usage_unit: paymentItem.wallet_pass_usage_unit,
662
+ wallet_pass_use_value: paymentItem.wallet_pass_use_value,
663
+ rounding_amount: paymentItem.rounding_amount || '0.00',
643
664
  service_charge: paymentItem.service_charge,
644
- status: "active",
665
+ status: 'active',
645
666
  // 新支付项默认为活跃状态
646
- order_payment_type: paymentItem.order_payment_type || "normal",
667
+ order_payment_type: paymentItem.order_payment_type || 'normal',
647
668
  // 默认为正常支付
648
669
  created_at: currentTime,
649
670
  // 创建时间
650
671
  updated_at: currentTime,
651
672
  // 更新时间
652
- wallet_pass_usage_unit: paymentItem == null ? void 0 : paymentItem.wallet_pass_usage_unit,
653
- wallet_pass_use_value: paymentItem == null ? void 0 : paymentItem.wallet_pass_use_value,
654
673
  metadata: {
655
674
  ...paymentItem.metadata,
656
675
  // 保留传入的所有 metadata 字段
657
- unique_payment_number: paymentUuid
658
- // 设置唯一支付号为支付项的 uuid
676
+ unique_payment_number: paymentUuid // 设置唯一支付号为支付项的 uuid
659
677
  }
660
678
  };
661
679
  order.payment.push(newPaymentItem);
662
680
  this.recalculateOrderAmount(order);
663
- this.logInfo("开始更新订单支付项", {
681
+ this.logInfo('开始更新订单支付项', {
664
682
  orderUuid,
665
683
  order
666
684
  });
667
- await this.dbManager.update("order", order, true);
668
- this.logInfo("更新订单支付项完成", {
685
+ await this.dbManager.update('order', order, true);
686
+ this.logInfo('更新订单支付项完成', {
669
687
  orderUuid
670
688
  });
671
689
  this.core.effects.emit(`${this.name}:onPaymentAdded`, {
672
690
  orderUuid,
673
691
  payment: newPaymentItem
674
692
  });
675
- this.logInfo("addPaymentItemAsync completed successfully", {
693
+ this.logInfo('addPaymentItemAsync completed successfully', {
676
694
  orderUuid,
677
695
  paymentUuid: newPaymentItem.uuid,
678
- uniquePaymentNumber: (_b = newPaymentItem.metadata) == null ? void 0 : _b.unique_payment_number,
696
+ uniquePaymentNumber: newPaymentItem.metadata?.unique_payment_number,
679
697
  newExpectAmount: order.expect_amount,
680
698
  paymentAmount: newPaymentItem.amount,
681
699
  paymentCode: newPaymentItem.code,
682
700
  orderPaymentType: newPaymentItem.order_payment_type,
683
701
  metadataFields: Object.keys(newPaymentItem.metadata || {}),
684
702
  // 现金支付找零信息
685
- actualPaidAmount: (_c = newPaymentItem.metadata) == null ? void 0 : _c.actual_paid_amount,
686
- changeGivenAmount: (_d = newPaymentItem.metadata) == null ? void 0 : _d.change_given_amount
703
+ actualPaidAmount: newPaymentItem.metadata?.actual_paid_amount,
704
+ changeGivenAmount: newPaymentItem.metadata?.change_given_amount
687
705
  });
688
706
  } catch (error) {
689
- console.error("[PaymentModule] 添加支付项失败", error);
690
- this.logError("addPaymentItemAsync failed", error, {
707
+ console.error('[PaymentModule] 添加支付项失败', error);
708
+ this.logError('addPaymentItemAsync failed', error, {
691
709
  orderUuid,
692
710
  paymentItem
693
711
  });
694
712
  throw error;
695
713
  }
696
714
  }
715
+
697
716
  /**
698
717
  * 删除一个支付项 - 标记删除而非物理删除
699
718
  */
700
719
  async deletePaymentAsync(orderUuid, paymentUuid) {
701
- this.logInfo("Starting deletePaymentAsync (mark as voided)", { orderUuid, paymentUuid });
720
+ this.logInfo('Starting deletePaymentAsync (mark as voided)', {
721
+ orderUuid,
722
+ paymentUuid
723
+ });
702
724
  try {
703
- const order = await this.dbManager.get("order", orderUuid);
725
+ const order = await this.dbManager.get('order', orderUuid);
704
726
  if (!order) {
705
- throw new Error("订单不存在");
727
+ throw new Error('订单不存在');
706
728
  }
707
- const paymentItem = order.payment.find(
708
- (payment) => payment.uuid === paymentUuid
709
- );
729
+ const paymentItem = order.payment.find(payment => payment.uuid === paymentUuid);
710
730
  if (!paymentItem) {
711
731
  throw new Error(`支付项不存在: ${paymentUuid}`);
712
732
  }
713
- if (paymentItem.status === "voided") {
733
+
734
+ // 检查是否已经被删除(撤销)
735
+ if (paymentItem.status === 'voided') {
714
736
  console.warn(`[PaymentModule] 支付项 ${paymentUuid} 已经被删除,跳过操作`);
715
737
  return;
716
738
  }
717
- paymentItem.status = "voided";
718
- paymentItem.origin_amount = paymentItem.amount;
719
- paymentItem.amount = "0.00";
720
- console.log(`[PaymentModule] 支付项标记为删除:`, {
721
- uuid: paymentItem.uuid,
722
- originalAmount: paymentItem.origin_amount,
723
- status: paymentItem.status
724
- });
739
+
740
+ // 标记删除而不是物理删除
741
+ paymentItem.status = 'voided';
742
+ paymentItem.origin_amount = paymentItem.amount; // 保存原始金额
743
+ paymentItem.amount = '0.00'; // 将金额设为0,不参与订单金额计算
744
+
745
+ // 重新计算待付金额
725
746
  this.recalculateOrderAmount(order);
726
- await this.dbManager.update("order", order);
747
+
748
+ // 更新到 IndexDB
749
+ await this.dbManager.update('order', order);
727
750
  await this.core.effects.emit(`${this.name}:onPaymentDeleted`, {
728
751
  order,
729
- paymentItem
752
+ paymentItem: paymentItem
730
753
  });
731
754
  await this.core.effects.emit(`${this.name}:onOrderChanged`, {
732
- action: "payment_delete",
755
+ action: 'payment_delete',
733
756
  order,
734
- paymentItem
757
+ paymentItem: paymentItem
735
758
  });
736
- this.logInfo("deletePaymentAsync completed successfully (marked as voided)", {
759
+ this.logInfo('deletePaymentAsync completed successfully (marked as voided)', {
737
760
  orderUuid,
738
761
  paymentUuid,
739
762
  originalAmount: paymentItem.origin_amount,
740
763
  newExpectAmount: order.expect_amount
741
764
  });
742
765
  } catch (error) {
743
- console.error("[PaymentModule] 删除支付项失败", error);
744
- this.logError("deletePaymentAsync failed", error, {
766
+ console.error('[PaymentModule] 删除支付项失败', error);
767
+ this.logError('deletePaymentAsync failed', error, {
745
768
  orderUuid,
746
769
  paymentUuid
747
770
  });
748
771
  throw error;
749
772
  }
750
773
  }
774
+
751
775
  /**
752
776
  * 批量更新代金券类支付项(覆盖更新)
753
777
  *
@@ -756,12 +780,16 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
756
780
  */
757
781
  async updateVoucherPaymentItemsAsync(orderUuid, voucherPaymentItems) {
758
782
  return this.runVoucherUpdateLocked(orderUuid, async () => {
759
- const { items: normalizedVoucherItems, originalCount, normalizedCount } = this.normalizeVoucherPaymentItems(voucherPaymentItems);
760
- this.logInfo("Starting updateVoucherPaymentItemsAsync", {
783
+ const {
784
+ items: normalizedVoucherItems,
785
+ originalCount,
786
+ normalizedCount
787
+ } = this.normalizeVoucherPaymentItems(voucherPaymentItems);
788
+ this.logInfo('Starting updateVoucherPaymentItemsAsync', {
761
789
  orderUuid,
762
790
  originalVoucherCount: originalCount,
763
791
  normalizedVoucherCount: normalizedCount,
764
- voucherItems: normalizedVoucherItems.map((item) => ({
792
+ voucherItems: normalizedVoucherItems.map(item => ({
765
793
  code: item.code,
766
794
  amount: item.amount,
767
795
  voucher_id: item.voucher_id,
@@ -769,7 +797,7 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
769
797
  }))
770
798
  });
771
799
  if (originalCount !== normalizedCount) {
772
- console.warn("[PaymentModule] voucherPaymentItems detected duplicates (deduped by voucher_id + order_payment_type)", {
800
+ console.warn('[PaymentModule] voucherPaymentItems detected duplicates (deduped by voucher_id + order_payment_type)', {
773
801
  orderUuid,
774
802
  originalCount,
775
803
  normalizedCount
@@ -780,71 +808,52 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
780
808
  if (!order) {
781
809
  throw new Error(`订单不存在: ${orderUuid}`);
782
810
  }
783
- const existingVoucherItems = order.payment.filter(
784
- (payment) => payment.voucher_id && payment.status !== "voided" && !payment.isSynced
785
- );
786
- console.log("[PaymentModule] 发现现有代金券支付项:", {
787
- orderUuid,
788
- existingVoucherCount: existingVoucherItems.length,
789
- existingItems: existingVoucherItems.map((item) => ({
790
- uuid: item.uuid,
791
- code: item.code,
792
- amount: item.amount,
793
- voucher_id: item.voucher_id,
794
- isSynced: item.isSynced
795
- }))
796
- });
811
+
812
+ // 1. 查找所有现有的代金券类支付项(带 voucher_id 且状态不是 voided)并且还没有同步给后端
813
+ // 如果同步给了后端的voucher 不允许删除
814
+ const existingVoucherItems = order.payment.filter(payment => payment.voucher_id && payment.status !== 'voided' && !payment.isSynced);
815
+ // 2. 删除所有现有的代金券支付项(仅删除未同步的)
797
816
  for (const voucherItem of existingVoucherItems) {
798
- console.log(`[PaymentModule] 删除现有代金券支付项: ${voucherItem.uuid}`);
799
817
  await this.deletePaymentAsync(orderUuid, voucherItem.uuid);
800
818
  }
819
+
820
+ // 3. 添加新的代金券支付项(幂等:如果已存在同 voucher_id + order_payment_type 的 active 项则跳过)
801
821
  const orderAfterDelete = await this.getPaymentOrderByUuidAsync(orderUuid);
802
822
  if (!orderAfterDelete) {
803
823
  throw new Error(`订单不存在: ${orderUuid}`);
804
824
  }
805
- const existingActiveVoucherKeys = new Set(
806
- orderAfterDelete.payment.filter((p) => p.voucher_id && p.status !== "voided" && !p.isSynced).map((p) => `${p.voucher_id}|${p.order_payment_type || "normal"}`)
807
- );
808
- console.log("[PaymentModule] 添加新的代金券支付项:", {
809
- orderUuid,
810
- newItemCount: normalizedVoucherItems.length
811
- });
825
+ const existingActiveVoucherKeys = new Set(orderAfterDelete.payment.filter(p => p.voucher_id && p.status !== 'voided' && !p.isSynced).map(p => `${p.voucher_id}|${p.order_payment_type || 'normal'}`));
812
826
  for (const voucherItem of normalizedVoucherItems) {
813
- const orderPaymentType = voucherItem.order_payment_type || "normal";
827
+ const orderPaymentType = voucherItem.order_payment_type || 'normal';
814
828
  const key = `${voucherItem.voucher_id}|${orderPaymentType}`;
815
829
  if (existingActiveVoucherKeys.has(key)) {
816
- console.warn("[PaymentModule] Skip adding voucher payment item because it already exists (active)", {
830
+ console.warn('[PaymentModule] Skip adding voucher payment item because it already exists (active)', {
817
831
  orderUuid,
818
832
  voucher_id: voucherItem.voucher_id,
819
833
  order_payment_type: orderPaymentType
820
834
  });
821
835
  continue;
822
836
  }
823
- console.log(`[PaymentModule] 添加代金券支付项:`, {
824
- code: voucherItem.code,
825
- amount: voucherItem.amount,
826
- voucher_id: voucherItem.voucher_id,
827
- order_payment_type: orderPaymentType
828
- });
829
837
  await this.addPaymentItemAsync(orderUuid, voucherItem);
830
838
  existingActiveVoucherKeys.add(key);
831
839
  }
840
+
841
+ // 4. 触发支付项更新事件
832
842
  const updatedOrder = await this.getPaymentOrderByUuidAsync(orderUuid);
833
843
  await this.core.effects.emit(`${this.name}:onPaymentAdded`, {
834
844
  orderUuid,
835
845
  order: updatedOrder,
836
- payment: null
837
- // 批量操作不提供单个支付项
846
+ payment: null // 批量操作不提供单个支付项
838
847
  });
839
- this.logInfo("updateVoucherPaymentItemsAsync completed successfully", {
848
+ this.logInfo('updateVoucherPaymentItemsAsync completed successfully', {
840
849
  orderUuid,
841
850
  removedVoucherCount: existingVoucherItems.length,
842
851
  addedVoucherCount: normalizedVoucherItems.length,
843
- finalExpectAmount: updatedOrder == null ? void 0 : updatedOrder.expect_amount
852
+ finalExpectAmount: updatedOrder?.expect_amount
844
853
  });
845
854
  } catch (error) {
846
- console.error("[PaymentModule] 批量更新代金券支付项失败:", error);
847
- this.logError("updateVoucherPaymentItemsAsync failed", error, {
855
+ console.error('[PaymentModule] 批量更新代金券支付项失败:', error);
856
+ this.logError('updateVoucherPaymentItemsAsync failed', error, {
848
857
  orderUuid,
849
858
  voucherPaymentItems
850
859
  });
@@ -852,79 +861,94 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
852
861
  }
853
862
  });
854
863
  }
864
+
855
865
  /**
856
866
  * 更新一个支付项
857
867
  */
858
868
  async updatePaymentAsync(orderUuid, paymentUuid, params) {
859
869
  try {
860
- const order = await this.dbManager.get("order", orderUuid);
870
+ const order = await this.dbManager.get('order', orderUuid);
861
871
  if (!order) {
862
- throw new Error("订单不存在");
872
+ throw new Error('订单不存在');
863
873
  }
864
- const paymentItem = order.payment.find(
865
- (payment) => payment.uuid === paymentUuid
866
- );
874
+ const paymentItem = order.payment.find(payment => payment.uuid === paymentUuid);
867
875
  if (paymentItem) {
868
- const formattedParams = { ...params };
869
- if ("amount" in formattedParams && formattedParams.amount !== void 0) {
876
+ // 如果更新参数中包含 amount,先格式化
877
+ const formattedParams = {
878
+ ...params
879
+ };
880
+ if ('amount' in formattedParams && formattedParams.amount !== undefined) {
870
881
  formattedParams.amount = formatAmount(formattedParams.amount);
871
882
  }
872
883
  Object.assign(paymentItem, formattedParams);
884
+
885
+ // 重新计算待付金额
873
886
  this.recalculateOrderAmount(order);
874
- await this.dbManager.update("order", order);
887
+
888
+ // 更新到 IndexDB
889
+ await this.dbManager.update('order', order);
875
890
  await this.core.effects.emit(`${this.name}:onPaymentUpdated`, {
876
891
  order,
877
892
  paymentItem
878
893
  });
879
894
  await this.core.effects.emit(`${this.name}:onOrderChanged`, {
880
- action: "payment_update",
895
+ action: 'payment_update',
881
896
  order,
882
897
  paymentItem
883
898
  });
884
899
  }
885
900
  } catch (error) {
886
- console.error("[PaymentModule] 更新支付项失败", error);
901
+ console.error('[PaymentModule] 更新支付项失败', error);
887
902
  throw error;
888
903
  }
889
904
  }
905
+
890
906
  /**
891
907
  * 提交支付
892
908
  */
893
909
  async submitPayAsync(orderUuid) {
894
- this.logInfo("Starting submitPayAsync", { orderUuid });
910
+ this.logInfo('Starting submitPayAsync', {
911
+ orderUuid
912
+ });
895
913
  try {
896
914
  let orderToSubmit;
897
915
  if (orderUuid) {
898
- const order = await this.dbManager.get("order", orderUuid);
916
+ const order = await this.dbManager.get('order', orderUuid);
899
917
  orderToSubmit = order ? [order] : [];
900
918
  } else {
901
- const allOrders = await this.dbManager.getAll("order");
902
- orderToSubmit = allOrders.filter(
903
- (order) => order.payment_status === import_types.PaymentStatus.Processing || order.payment_status === import_types.PaymentStatus.PartiallyPaid
904
- );
919
+ const allOrders = await this.dbManager.getAll('order');
920
+ // 包括正在处理中的订单和部分支付的订单(可能添加了新的支付项)
921
+ orderToSubmit = allOrders.filter(order => order.payment_status === _types.PaymentStatus.Processing || order.payment_status === _types.PaymentStatus.PartiallyPaid);
905
922
  }
906
923
  for (const order of orderToSubmit) {
907
924
  await this.submitSingleOrderPayment(order);
908
925
  }
909
- const result = { status: "success" };
910
- this.logInfo("submitPayAsync completed", {
926
+ const result = {
927
+ status: 'success'
928
+ };
929
+ this.logInfo('submitPayAsync completed', {
911
930
  result: result.status,
912
931
  processedOrdersCount: orderToSubmit.length
913
932
  });
914
933
  return result;
915
934
  } catch (error) {
916
- console.error("[PaymentModule] 提交支付失败", error);
917
- this.logError("submitPayAsync failed", error, { orderUuid });
918
- return { status: "failed" };
935
+ console.error('[PaymentModule] 提交支付失败', error);
936
+ this.logError('submitPayAsync failed', error, {
937
+ orderUuid
938
+ });
939
+ return {
940
+ status: 'failed'
941
+ };
919
942
  }
920
943
  }
944
+
921
945
  /**
922
946
  * 提交单个订单的支付(推送到任务队列)
923
947
  */
924
948
  async submitSingleOrderPayment(order) {
925
949
  try {
926
950
  const paymentData = {
927
- payments: order.payment.map((payment) => ({
951
+ payments: order.payment.map(payment => ({
928
952
  uuid: payment.uuid,
929
953
  amount: payment.amount,
930
954
  code: payment.code,
@@ -936,37 +960,41 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
936
960
  rounding_amount: payment.rounding_amount,
937
961
  service_charge: payment.service_charge
938
962
  })),
939
- payment_status: "pending"
963
+ payment_status: 'pending'
940
964
  };
941
- const totalPaidAmount = paymentData.payments.reduce(
942
- (sum, payment) => sum.plus(payment.amount),
943
- new import_decimal.Decimal(0)
944
- );
945
- const orderTotalAmount = new import_decimal.Decimal(order.total_amount);
965
+
966
+ // 计算总支付金额
967
+ const totalPaidAmount = paymentData.payments.reduce((sum, payment) => sum.plus(payment.amount), new _decimal.Decimal(0));
968
+ const orderTotalAmount = new _decimal.Decimal(order.total_amount);
969
+
970
+ // 根据支付金额判断订单状态
946
971
  if (totalPaidAmount.gte(orderTotalAmount)) {
947
- order.payment_status = import_types.PaymentStatus.Finished;
948
- console.log(
949
- `[PaymentModule] 订单 ${order.uuid} 支付完成,金额: ${totalPaidAmount.toString()}/${orderTotalAmount.toString()}`
950
- );
972
+ // 支付金额足够,标记为已完成
973
+ order.payment_status = _types.PaymentStatus.Finished;
951
974
  } else {
952
- order.payment_status = import_types.PaymentStatus.PartiallyPaid;
953
- console.log(
954
- `[PaymentModule] 订单 ${order.uuid} 部分支付,金额: ${totalPaidAmount.toString()}/${orderTotalAmount.toString()}`
955
- );
975
+ // 支付金额不足,标记为部分支付
976
+ order.payment_status = _types.PaymentStatus.PartiallyPaid;
956
977
  }
957
- paymentData.payment_status = order.payment_status === import_types.PaymentStatus.Finished ? "paid" : "partially_paid";
958
- await this.dbManager.update("order", order);
978
+
979
+ // 给后端标记一下是全部支付(paid)还是部分支付
980
+ paymentData.payment_status = order.payment_status === _types.PaymentStatus.Finished ? 'paid' : 'partially_paid';
981
+
982
+ // 更新订单状态到数据库
983
+ await this.dbManager.update('order', order);
984
+
985
+ // 检查支付列表是否为空
959
986
  if (paymentData.payments.length === 0) {
960
- console.log(`[PaymentModule] 订单 ${order.uuid} 支付列表为空,跳过支付处理`);
961
- this.logWarning("Empty payment list", {
987
+ this.logWarning('Empty payment list', {
962
988
  orderUuid: order.uuid,
963
989
  orderId: order.order_id
964
990
  });
965
991
  return;
966
992
  }
993
+
994
+ // 触发支付提交事件
967
995
  await this.core.effects.emit(`${this.name}:onPaymentSubmitted`, order);
968
996
  await this.core.effects.emit(`${this.name}:onOrderChanged`, {
969
- action: "submit",
997
+ action: 'submit',
970
998
  order
971
999
  });
972
1000
  } catch (error) {
@@ -974,168 +1002,165 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
974
1002
  throw error;
975
1003
  }
976
1004
  }
1005
+
977
1006
  /**
978
1007
  * 获取订单剩余待付金额
979
1008
  */
980
1009
  async getRemainingOrderAmountAsync(orderUuid) {
981
1010
  const order = await this.getPaymentOrderByUuidAsync(orderUuid);
982
1011
  if (!order) {
983
- throw new Error("订单不存在");
1012
+ throw new Error('订单不存在');
984
1013
  }
985
- return new import_decimal.Decimal(order.expect_amount).toNumber();
1014
+ return new _decimal.Decimal(order.expect_amount).toNumber();
986
1015
  }
1016
+
987
1017
  /**
988
1018
  * 在比如现金支付界面的地方,用户输入了一个金额,在下方显示剩余多少金额,通过此方法获取
989
1019
  */
990
1020
  async getRemainingOrderAmountWithInputAsync(inputAmount, orderUuid) {
991
1021
  const order = await this.getPaymentOrderByUuidAsync(orderUuid);
992
1022
  if (!order) {
993
- throw new Error("订单不存在");
1023
+ throw new Error('订单不存在');
994
1024
  }
995
- if (inputAmount === null || inputAmount === void 0) {
996
- return new import_decimal.Decimal(order.expect_amount).toNumber();
1025
+
1026
+ // 对输入金额做保护,确保是有效的数字
1027
+ if (inputAmount === null || inputAmount === undefined) {
1028
+ // 如果输入为空,返回原始的待付金额
1029
+ return new _decimal.Decimal(order.expect_amount).toNumber();
997
1030
  }
998
- if (typeof inputAmount === "string") {
999
- if (inputAmount.trim() === "") {
1000
- return new import_decimal.Decimal(order.expect_amount).toNumber();
1031
+
1032
+ // 处理字符串类型的输入
1033
+ if (typeof inputAmount === 'string') {
1034
+ if (inputAmount.trim() === '') {
1035
+ // 如果输入为空字符串,返回原始的待付金额
1036
+ return new _decimal.Decimal(order.expect_amount).toNumber();
1001
1037
  }
1002
1038
  }
1003
- if (typeof inputAmount === "number") {
1039
+
1040
+ // 处理数字类型的输入
1041
+ if (typeof inputAmount === 'number') {
1004
1042
  if (isNaN(inputAmount) || !isFinite(inputAmount)) {
1005
- console.warn(
1006
- `[PaymentModule] 输入金额不是有效数字: ${inputAmount},返回原始待付金额`
1007
- );
1008
- return new import_decimal.Decimal(order.expect_amount).toNumber();
1043
+ // 如果输入是 NaN 或无穷大,返回原始的待付金额
1044
+ console.warn(`[PaymentModule] 输入金额不是有效数字: ${inputAmount},返回原始待付金额`);
1045
+ return new _decimal.Decimal(order.expect_amount).toNumber();
1009
1046
  }
1010
1047
  }
1011
1048
  try {
1012
- const inputDecimal = new import_decimal.Decimal(inputAmount);
1013
- return new import_decimal.Decimal(order.expect_amount).minus(inputDecimal).toNumber();
1049
+ const inputDecimal = new _decimal.Decimal(inputAmount);
1050
+ return new _decimal.Decimal(order.expect_amount).minus(inputDecimal).toNumber();
1014
1051
  } catch (error) {
1015
- console.warn(
1016
- `[PaymentModule] 输入金额格式无效: ${inputAmount},返回原始待付金额`
1017
- );
1018
- return new import_decimal.Decimal(order.expect_amount).toNumber();
1052
+ // 如果输入不是有效的数字,返回原始的待付金额
1053
+ console.warn(`[PaymentModule] 输入金额格式无效: ${inputAmount},返回原始待付金额`);
1054
+ return new _decimal.Decimal(order.expect_amount).toNumber();
1019
1055
  }
1020
1056
  }
1057
+
1021
1058
  /**
1022
1059
  * 重新计算订单金额
1023
1060
  */
1024
1061
  recalculateOrderAmount(order) {
1025
- const totalAmount = new import_decimal.Decimal(order.total_amount);
1026
- const paidAmount = order.payment.reduce(
1027
- (sum, payment) => {
1028
- try {
1029
- if (payment.status === "voided") {
1030
- return sum;
1031
- }
1032
- const paymentAmount = new import_decimal.Decimal(payment.amount || 0);
1033
- const roundingAmount = new import_decimal.Decimal(payment.rounding_amount || 0);
1034
- const effectiveAmount = paymentAmount.minus(roundingAmount);
1035
- return sum.plus(effectiveAmount);
1036
- } catch (error) {
1037
- console.warn(`[PaymentModule] 无效的支付金额: amount=${payment.amount}, rounding_amount=${payment.rounding_amount},跳过计算`);
1062
+ const totalAmount = new _decimal.Decimal(order.total_amount);
1063
+ const paidAmount = order.payment.reduce((sum, payment) => {
1064
+ try {
1065
+ // 忽略已撤销的支付项
1066
+ if (payment.status === 'voided') {
1038
1067
  return sum;
1039
1068
  }
1040
- },
1041
- new import_decimal.Decimal(0)
1042
- );
1043
- const remainingAmount = order.is_deposit === 1 ? new import_decimal.Decimal(order.deposit_amount).minus(paidAmount) : totalAmount.minus(paidAmount);
1044
- order.expect_amount = import_decimal.Decimal.max(0, remainingAmount).toFixed(2);
1045
- console.log(`[PaymentModule] 重新计算订单金额:`, {
1046
- orderUuid: order.uuid,
1047
- totalAmount: order.total_amount,
1048
- effectivePaidAmount: paidAmount.toFixed(2),
1049
- remainingAmount: order.expect_amount,
1050
- activePayments: order.payment.filter((p) => p.status !== "voided").length,
1051
- voidedPayments: order.payment.filter((p) => p.status === "voided").length,
1052
- paymentDetails: order.payment.filter((p) => p.status !== "voided").map((p) => ({
1053
- code: p.code,
1054
- amount: p.amount,
1055
- rounding_amount: p.rounding_amount || "0.00",
1056
- effective_amount: new import_decimal.Decimal(p.amount || 0).minus(new import_decimal.Decimal(p.rounding_amount || 0)).toFixed(2)
1057
- })),
1058
- 说明: "有效支付金额包含抹零计算(amount + |rounding_amount|)"
1059
- });
1069
+
1070
+ // 计算有效支付金额:支付金额 + 抹零金额的绝对值
1071
+ // 当 rounding_amount 为负数时,表示抹掉的金额,按绝对值计算有效支付
1072
+ // 例如:amount=15, rounding_amount=-0.2,有效支付=15.2(抹掉0.2元零头)
1073
+ // 例2:amount=15,rounding_amount=0.2,有效支付 14.8
1074
+ const paymentAmount = new _decimal.Decimal(payment.amount || 0);
1075
+ const roundingAmount = new _decimal.Decimal(payment.rounding_amount || 0);
1076
+ const effectiveAmount = paymentAmount.minus(roundingAmount);
1077
+ return sum.plus(effectiveAmount);
1078
+ } catch (error) {
1079
+ console.warn(`[PaymentModule] 无效的支付金额: amount=${payment.amount}, rounding_amount=${payment.rounding_amount},跳过计算`);
1080
+ return sum;
1081
+ }
1082
+ }, new _decimal.Decimal(0));
1083
+ // 如果是定金模式,则使用deposit_amount 去减已付款金额
1084
+ const remainingAmount = order.is_deposit === 1 ? new _decimal.Decimal(order.deposit_amount).minus(paidAmount) : totalAmount.minus(paidAmount);
1085
+ order.expect_amount = _decimal.Decimal.max(0, remainingAmount).toFixed(2);
1060
1086
  }
1087
+
1061
1088
  /**
1062
1089
  * 获取现金支付方式
1063
1090
  */
1064
1091
  async getCashPaymentMethod() {
1065
1092
  try {
1066
- const payMethods = await this.dbManager.getAll("pay_method");
1067
- return payMethods.find(
1068
- (method) => method.code === import_types.PaymentMethodType.Cash
1069
- ) || null;
1093
+ const payMethods = await this.dbManager.getAll('pay_method');
1094
+ return payMethods.find(method => method.code === _types.PaymentMethodType.Cash) || null;
1070
1095
  } catch (error) {
1071
- console.error("[PaymentModule] 获取现金支付方式失败", error);
1096
+ console.error('[PaymentModule] 获取现金支付方式失败', error);
1072
1097
  return null;
1073
1098
  }
1074
1099
  }
1100
+
1075
1101
  /**
1076
1102
  * 获取Eftpos支付方式
1077
1103
  */
1078
1104
  async getEftposPaymentMethod() {
1079
1105
  try {
1080
- const payMethods = await this.dbManager.getAll("pay_method");
1081
- return payMethods.find(
1082
- (method) => method.code === import_types.PaymentMethodType.Eftpos
1083
- ) || null;
1106
+ const payMethods = await this.dbManager.getAll('pay_method');
1107
+ return payMethods.find(method => method.code === _types.PaymentMethodType.Eftpos) || null;
1084
1108
  } catch (error) {
1085
- console.error("[PaymentModule] 获取Eftpos支付方式失败", error);
1109
+ console.error('[PaymentModule] 获取Eftpos支付方式失败', error);
1086
1110
  return null;
1087
1111
  }
1088
1112
  }
1113
+
1089
1114
  /**
1090
1115
  * 获取钱包支付方式
1091
1116
  */
1092
1117
  async getWalletPaymentMethod() {
1093
1118
  try {
1094
- const payMethods = await this.dbManager.getAll("pay_method");
1095
- return payMethods.find(
1096
- (method) => method.code === import_types.PaymentMethodType.Wallet
1097
- ) || null;
1119
+ const payMethods = await this.dbManager.getAll('pay_method');
1120
+ return payMethods.find(method => method.code === _types.PaymentMethodType.Wallet) || null;
1098
1121
  } catch (error) {
1099
- console.error("[PaymentModule] 获取钱包支付方式失败", error);
1122
+ console.error('[PaymentModule] 获取钱包支付方式失败', error);
1100
1123
  return null;
1101
1124
  }
1102
1125
  }
1126
+
1103
1127
  /**
1104
1128
  * 确保支付模块所需的数据库表已创建
1105
1129
  */
1130
+ /** @deprecated */
1106
1131
  async ensurePaymentTables() {
1107
1132
  try {
1108
- await this.dbManager.getAll("pay_method");
1133
+ // 尝试访问 pay_method 表,如果不存在会抛出错误
1134
+ await this.dbManager.getAll('pay_method');
1109
1135
  } catch (error) {
1110
- console.warn(
1111
- "[PaymentModule] pay_method 表不存在,请在数据库配置中添加以下配置:"
1112
- );
1136
+ console.warn('[PaymentModule] pay_method 表不存在,请在数据库配置中添加以下配置:');
1113
1137
  console.warn('{ name: "pay_method", keyPath: "id" }');
1114
1138
  }
1115
1139
  try {
1116
- await this.dbManager.getAll("order");
1140
+ // 尝试访问 order 表,如果不存在会抛出错误
1141
+ await this.dbManager.getAll('order');
1117
1142
  } catch (error) {
1118
- console.warn(
1119
- "[PaymentModule] order 表不存在,请在数据库配置中添加以下配置:"
1120
- );
1143
+ console.warn('[PaymentModule] order 表不存在,请在数据库配置中添加以下配置:');
1121
1144
  console.warn('{ name: "order", keyPath: "uuid" }');
1122
1145
  }
1123
1146
  }
1147
+
1124
1148
  /**
1125
1149
  * 获取部分支付的订单
1126
1150
  */
1151
+ /** @deprecated */
1127
1152
  async getPartiallyPaidOrdersAsync() {
1128
1153
  try {
1129
- const allOrders = await this.dbManager.getAll("order");
1130
- return allOrders.filter(
1131
- (order) => order.payment_status === import_types.PaymentStatus.PartiallyPaid
1132
- );
1154
+ const allOrders = await this.dbManager.getAll('order');
1155
+ return allOrders.filter(order => order.payment_status === _types.PaymentStatus.PartiallyPaid);
1133
1156
  } catch (error) {
1134
- console.error("[PaymentModule] 获取部分支付订单失败", error);
1157
+ console.error('[PaymentModule] 获取部分支付订单失败', error);
1135
1158
  return [];
1136
1159
  }
1137
1160
  }
1161
+
1138
1162
  // === 新的 API 方法实现 ===
1163
+
1139
1164
  /**
1140
1165
  * 智能金额舍入
1141
1166
  *
@@ -1148,63 +1173,78 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
1148
1173
  */
1149
1174
  async roundAmountAsync(originalAmount, interval, rule) {
1150
1175
  try {
1151
- const amount = new import_decimal.Decimal(originalAmount);
1152
- const roundingInterval = new import_decimal.Decimal(interval);
1176
+ // 参数验证
1177
+ const amount = new _decimal.Decimal(originalAmount);
1178
+ const roundingInterval = new _decimal.Decimal(interval);
1153
1179
  if (roundingInterval.lte(0)) {
1154
- throw new Error("舍入间隔必须大于 0");
1180
+ throw new Error('舍入间隔必须大于 0');
1155
1181
  }
1182
+
1183
+ // 支持的舍入间隔
1156
1184
  const supportedIntervals = [0.05, 0.1, 0.5, 1];
1157
1185
  const intervalValue = roundingInterval.toNumber();
1158
1186
  if (!supportedIntervals.includes(intervalValue)) {
1159
- console.warn(`[PaymentModule] 不支持的舍入间隔: ${intervalValue}, 支持的间隔: ${supportedIntervals.join(", ")}`);
1187
+ console.warn(`[PaymentModule] 不支持的舍入间隔: ${intervalValue}, 支持的间隔: ${supportedIntervals.join(', ')}`);
1160
1188
  }
1189
+
1190
+ // 计算基础值:x / interval
1161
1191
  const baseValue = amount.div(roundingInterval);
1162
- console.log(`[PaymentModule] 舍入计算 - 原始金额: ${amount.toString()}, 间隔: ${intervalValue}, 基础值: ${baseValue.toString()}, 规则: ${rule}`);
1163
1192
  let roundedValue;
1193
+
1194
+ // 根据舍入规则处理
1164
1195
  switch (rule) {
1165
- case import_types.RoundingRule.Standard:
1166
- case "standard":
1196
+ case _types.RoundingRule.Standard:
1197
+ case 'standard':
1198
+ // 标准舍入(中点向上)
1167
1199
  roundedValue = this.standardRound(baseValue, true);
1168
1200
  break;
1169
- case import_types.RoundingRule.StandardDown:
1170
- case "standard_down":
1201
+ case _types.RoundingRule.StandardDown:
1202
+ case 'standard_down':
1203
+ // 标准舍入(中点向下)
1171
1204
  roundedValue = this.standardRound(baseValue, false);
1172
1205
  break;
1173
- case import_types.RoundingRule.AlwaysUp:
1174
- case "always_up":
1206
+ case _types.RoundingRule.AlwaysUp:
1207
+ case 'always_up':
1208
+ // 总是向上舍入
1175
1209
  roundedValue = baseValue.ceil();
1176
1210
  break;
1177
- case import_types.RoundingRule.AlwaysDown:
1178
- case "always_down":
1211
+ case _types.RoundingRule.AlwaysDown:
1212
+ case 'always_down':
1213
+ // 总是向下舍入
1179
1214
  roundedValue = baseValue.floor();
1180
1215
  break;
1181
1216
  default:
1182
1217
  throw new Error(`不支持的舍入规则: ${rule}`);
1183
1218
  }
1219
+
1220
+ // 计算最终金额:roundedValue * interval
1184
1221
  const finalAmount = roundedValue.mul(roundingInterval);
1185
1222
  const originalAmountStr = amount.toFixed(2);
1223
+
1224
+ // 如果最终金额是 0 元,则不采用舍入金额,返回原始金额
1186
1225
  if (finalAmount.eq(0)) {
1187
- console.log(`[PaymentModule] 最终金额为0,返回原始金额: ${originalAmountStr}`);
1188
1226
  return {
1189
1227
  originalAmount: originalAmountStr,
1190
1228
  roundedAmount: originalAmountStr,
1191
- roundingDifference: "0.00"
1229
+ roundingDifference: '0.00'
1192
1230
  };
1193
1231
  }
1194
1232
  const roundedAmountStr = finalAmount.toFixed(2);
1233
+
1234
+ // 计算舍入差额
1195
1235
  const roundingDifference = finalAmount.sub(amount);
1196
1236
  const roundingDifferenceStr = roundingDifference.toFixed(2);
1197
- console.log(`[PaymentModule] 舍入结果 - 原始金额: ${originalAmountStr}, 舍入后金额: ${roundedAmountStr}, 舍入差额: ${roundingDifferenceStr}`);
1198
1237
  return {
1199
1238
  originalAmount: originalAmountStr,
1200
1239
  roundedAmount: roundedAmountStr,
1201
1240
  roundingDifference: roundingDifferenceStr
1202
1241
  };
1203
1242
  } catch (error) {
1204
- console.error("[PaymentModule] 金额舍入失败:", error);
1243
+ console.error('[PaymentModule] 金额舍入失败:', error);
1205
1244
  throw new Error(`金额舍入失败: ${error instanceof Error ? error.message : String(error)}`);
1206
1245
  }
1207
1246
  }
1247
+
1208
1248
  /**
1209
1249
  * 标准舍入处理(处理中点情况)
1210
1250
  *
@@ -1215,18 +1255,18 @@ var PaymentModule = class extends import_BaseModule.BaseModule {
1215
1255
  standardRound(value, midpointUp) {
1216
1256
  const floorValue = value.floor();
1217
1257
  const fractionalPart = value.minus(floorValue);
1258
+
1259
+ // 检查是否是中点(小数部分 = 0.5)
1218
1260
  if (fractionalPart.eq(0.5)) {
1261
+ // 中点情况,根据规则决定
1219
1262
  return midpointUp ? floorValue.plus(1) : floorValue;
1220
1263
  } else if (fractionalPart.gt(0.5)) {
1264
+ // 大于中点,向上舍入
1221
1265
  return floorValue.plus(1);
1222
1266
  } else {
1267
+ // 小于中点,向下舍入
1223
1268
  return floorValue;
1224
1269
  }
1225
1270
  }
1226
- };
1227
- // Annotate the CommonJS export names for ESM import in node:
1228
- 0 && (module.exports = {
1229
- PaymentModule,
1230
- generateRequestUniqueId,
1231
- ...require("./types")
1232
- });
1271
+ }
1272
+ exports.PaymentModule = PaymentModule;