@pisell/pisellos 2.2.243 → 2.2.244

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 (315) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.js +2 -3
  2. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  3. package/dist/model/strategy/adapter/walletPass/utils.js +4 -7
  4. package/dist/modules/Cart/utils/cartProduct.js +3 -24
  5. package/dist/modules/Cart/utils/changePrice.js +11 -11
  6. package/dist/modules/Customer/index.d.ts +0 -20
  7. package/dist/modules/Customer/index.js +83 -172
  8. package/dist/modules/Customer/types.d.ts +0 -2
  9. package/dist/modules/Discount/index.js +3 -4
  10. package/dist/modules/Discount/types.d.ts +0 -1
  11. package/dist/modules/OpenData/index.d.ts +0 -8
  12. package/dist/modules/OpenData/index.js +17 -37
  13. package/dist/modules/Order/index.d.ts +18 -268
  14. package/dist/modules/Order/index.js +757 -3306
  15. package/dist/modules/Order/types.d.ts +31 -279
  16. package/dist/modules/Order/types.js +0 -38
  17. package/dist/modules/Order/utils.d.ts +5 -147
  18. package/dist/modules/Order/utils.js +103 -746
  19. package/dist/modules/Payment/index.d.ts +13 -10
  20. package/dist/modules/Payment/index.js +837 -467
  21. package/dist/modules/Payment/types.d.ts +0 -2
  22. package/dist/modules/Payment/utils.js +1 -2
  23. package/dist/modules/Payment/walletpass.js +7 -14
  24. package/dist/modules/ProductList/index.d.ts +12 -16
  25. package/dist/modules/ProductList/index.js +59 -133
  26. package/dist/modules/ProductList/types.d.ts +0 -14
  27. package/dist/modules/Quotation/index.d.ts +1 -0
  28. package/dist/modules/Quotation/index.js +22 -25
  29. package/dist/modules/Rules/index.d.ts +0 -4
  30. package/dist/modules/Rules/index.js +69 -93
  31. package/dist/modules/Rules/types.d.ts +0 -1
  32. package/dist/modules/SalesSummary/index.d.ts +25 -8
  33. package/dist/modules/SalesSummary/index.js +35 -86
  34. package/dist/modules/SalesSummary/types.d.ts +1 -4
  35. package/dist/modules/SalesSummary/utils.d.ts +25 -2
  36. package/dist/modules/SalesSummary/utils.js +162 -794
  37. package/dist/modules/Schedule/index.d.ts +0 -7
  38. package/dist/modules/Schedule/index.js +2 -24
  39. package/dist/modules/Summary/index.js +3 -4
  40. package/dist/modules/index.d.ts +0 -2
  41. package/dist/modules/index.js +1 -3
  42. package/dist/plugins/request.d.ts +0 -1
  43. package/dist/server/index.d.ts +1 -204
  44. package/dist/server/index.js +928 -3658
  45. package/dist/server/modules/index.d.ts +0 -2
  46. package/dist/server/modules/index.js +0 -2
  47. package/dist/server/modules/order/index.d.ts +4 -120
  48. package/dist/server/modules/order/index.js +483 -1779
  49. package/dist/server/modules/order/types.d.ts +3 -32
  50. package/dist/server/modules/order/types.js +0 -8
  51. package/dist/server/modules/order/utils/filterBookings.js +3 -26
  52. package/dist/server/modules/order/utils/filterOrders.js +8 -23
  53. package/dist/server/modules/products/index.d.ts +7 -34
  54. package/dist/server/modules/products/index.js +317 -631
  55. package/dist/server/modules/resource/index.d.ts +0 -2
  56. package/dist/server/modules/resource/index.js +3 -29
  57. package/dist/server/modules/schedule/index.d.ts +4 -4
  58. package/dist/server/modules/schedule/index.js +88 -111
  59. package/dist/solution/BaseSales/index.d.ts +9 -131
  60. package/dist/solution/BaseSales/index.js +447 -1944
  61. package/dist/solution/BaseSales/types.d.ts +6 -76
  62. package/dist/solution/BaseSales/types.js +4 -5
  63. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +0 -1
  64. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +24 -105
  65. package/dist/solution/BaseSales/utils.d.ts +1 -1
  66. package/dist/solution/BaseSales/utils.js +21 -62
  67. package/dist/solution/BookingByStep/index.d.ts +1 -1
  68. package/dist/solution/BookingTicket/index.d.ts +10 -270
  69. package/dist/solution/BookingTicket/index.js +237 -1772
  70. package/dist/solution/BookingTicket/types.d.ts +1 -118
  71. package/dist/solution/BookingTicket/types.js +2 -41
  72. package/dist/solution/BookingTicket/utils/bookingStatus.d.ts +0 -40
  73. package/dist/solution/BookingTicket/utils/bookingStatus.js +0 -70
  74. package/dist/solution/BookingTicket/utils/cartView.d.ts +1 -9
  75. package/dist/solution/BookingTicket/utils/cartView.js +7 -94
  76. package/dist/solution/BookingTicket/utils/scan/index.d.ts +0 -5
  77. package/dist/solution/BookingTicket/utils/scan/index.js +8 -20
  78. package/dist/solution/Checkout/appointmentDemo.json +1 -0
  79. package/dist/solution/Checkout/index.d.ts +0 -1
  80. package/dist/solution/Checkout/index.js +9 -10
  81. package/dist/solution/RegisterAndLogin/config.js +10 -2
  82. package/dist/solution/ScanOrder/index.d.ts +3 -9
  83. package/dist/solution/ScanOrder/index.js +134 -241
  84. package/dist/solution/ScanOrder/types.d.ts +5 -9
  85. package/dist/solution/ScanOrder/types.js +3 -2
  86. package/dist/solution/ScanOrder/utils.d.ts +1 -1
  87. package/dist/solution/ScanOrder/utils.js +22 -84
  88. package/dist/solution/VenueBooking/index.d.ts +2 -5
  89. package/dist/solution/VenueBooking/index.js +59 -110
  90. package/dist/solution/VenueBooking/sales-section-4-annotated.json +2 -0
  91. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +0 -4
  92. package/dist/solution/VenueBooking/utils/slotMerge.js +0 -10
  93. package/dist/types/index.d.ts +0 -10
  94. package/lib/model/strategy/adapter/promotion/evaluator.js +1 -2
  95. package/lib/model/strategy/adapter/promotion/index.js +0 -49
  96. package/lib/model/strategy/adapter/walletPass/utils.js +2 -3
  97. package/lib/modules/Cart/utils/cartProduct.js +3 -20
  98. package/lib/modules/Cart/utils/changePrice.js +20 -12
  99. package/lib/modules/Customer/index.d.ts +0 -20
  100. package/lib/modules/Customer/index.js +11 -64
  101. package/lib/modules/Customer/types.d.ts +0 -2
  102. package/lib/modules/Discount/index.js +1 -5
  103. package/lib/modules/Discount/types.d.ts +0 -1
  104. package/lib/modules/OpenData/index.d.ts +0 -8
  105. package/lib/modules/OpenData/index.js +5 -19
  106. package/lib/modules/Order/index.d.ts +18 -268
  107. package/lib/modules/Order/index.js +344 -2149
  108. package/lib/modules/Order/types.d.ts +31 -279
  109. package/lib/modules/Order/types.js +0 -1
  110. package/lib/modules/Order/utils.d.ts +5 -147
  111. package/lib/modules/Order/utils.js +46 -614
  112. package/lib/modules/Payment/index.d.ts +13 -10
  113. package/lib/modules/Payment/index.js +150 -18
  114. package/lib/modules/Payment/types.d.ts +0 -2
  115. package/lib/modules/Payment/utils.js +1 -2
  116. package/lib/modules/Payment/walletpass.js +3 -7
  117. package/lib/modules/ProductList/index.d.ts +12 -16
  118. package/lib/modules/ProductList/index.js +4 -41
  119. package/lib/modules/ProductList/types.d.ts +0 -14
  120. package/lib/modules/Quotation/index.d.ts +1 -0
  121. package/lib/modules/Quotation/index.js +16 -19
  122. package/lib/modules/Rules/index.d.ts +0 -4
  123. package/lib/modules/Rules/index.js +120 -136
  124. package/lib/modules/Rules/types.d.ts +0 -1
  125. package/lib/modules/SalesSummary/index.d.ts +25 -8
  126. package/lib/modules/SalesSummary/index.js +4 -30
  127. package/lib/modules/SalesSummary/types.d.ts +1 -4
  128. package/lib/modules/SalesSummary/utils.d.ts +25 -2
  129. package/lib/modules/SalesSummary/utils.js +91 -645
  130. package/lib/modules/Schedule/index.d.ts +0 -7
  131. package/lib/modules/Schedule/index.js +1 -17
  132. package/lib/modules/Summary/index.js +4 -5
  133. package/lib/modules/index.d.ts +0 -2
  134. package/lib/modules/index.js +1 -5
  135. package/lib/plugins/request.d.ts +0 -1
  136. package/lib/server/index.d.ts +1 -204
  137. package/lib/server/index.js +57 -1888
  138. package/lib/server/modules/index.d.ts +0 -2
  139. package/lib/server/modules/index.js +0 -3
  140. package/lib/server/modules/order/index.d.ts +4 -120
  141. package/lib/server/modules/order/index.js +142 -919
  142. package/lib/server/modules/order/types.d.ts +3 -32
  143. package/lib/server/modules/order/utils/filterBookings.js +5 -24
  144. package/lib/server/modules/order/utils/filterOrders.js +6 -15
  145. package/lib/server/modules/products/index.d.ts +7 -34
  146. package/lib/server/modules/products/index.js +54 -189
  147. package/lib/server/modules/resource/index.d.ts +0 -2
  148. package/lib/server/modules/resource/index.js +3 -27
  149. package/lib/server/modules/schedule/index.d.ts +4 -4
  150. package/lib/server/modules/schedule/index.js +40 -47
  151. package/lib/solution/BaseSales/index.d.ts +9 -131
  152. package/lib/solution/BaseSales/index.js +63 -1106
  153. package/lib/solution/BaseSales/types.d.ts +6 -76
  154. package/lib/solution/BaseSales/types.js +1 -3
  155. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +0 -1
  156. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +18 -106
  157. package/lib/solution/BaseSales/utils.d.ts +1 -1
  158. package/lib/solution/BaseSales/utils.js +10 -54
  159. package/lib/solution/BookingByStep/index.d.ts +1 -1
  160. package/lib/solution/BookingTicket/index.d.ts +10 -270
  161. package/lib/solution/BookingTicket/index.js +29 -922
  162. package/lib/solution/BookingTicket/types.d.ts +1 -118
  163. package/lib/solution/BookingTicket/types.js +0 -11
  164. package/lib/solution/BookingTicket/utils/bookingStatus.d.ts +0 -40
  165. package/lib/solution/BookingTicket/utils/bookingStatus.js +2 -44
  166. package/lib/solution/BookingTicket/utils/cartView.d.ts +1 -9
  167. package/lib/solution/BookingTicket/utils/cartView.js +6 -61
  168. package/lib/solution/BookingTicket/utils/scan/index.d.ts +0 -5
  169. package/lib/solution/BookingTicket/utils/scan/index.js +3 -17
  170. package/lib/solution/Checkout/appointmentDemo.json +1 -0
  171. package/lib/solution/Checkout/index.d.ts +0 -1
  172. package/lib/solution/Checkout/index.js +2 -1
  173. package/lib/solution/RegisterAndLogin/config.js +10 -2
  174. package/lib/solution/ScanOrder/index.d.ts +3 -9
  175. package/lib/solution/ScanOrder/index.js +70 -153
  176. package/lib/solution/ScanOrder/types.d.ts +5 -9
  177. package/lib/solution/ScanOrder/utils.d.ts +1 -1
  178. package/lib/solution/ScanOrder/utils.js +17 -83
  179. package/lib/solution/VenueBooking/index.d.ts +2 -5
  180. package/lib/solution/VenueBooking/index.js +17 -54
  181. package/lib/solution/VenueBooking/sales-section-4-annotated.json +2 -0
  182. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +0 -4
  183. package/lib/solution/VenueBooking/utils/slotMerge.js +0 -10
  184. package/lib/types/index.d.ts +0 -10
  185. package/package.json +1 -1
  186. package/dist/modules/BookingContext/index.d.ts +0 -48
  187. package/dist/modules/BookingContext/index.js +0 -566
  188. package/dist/modules/BookingContext/types.d.ts +0 -102
  189. package/dist/modules/BookingContext/types.js +0 -51
  190. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +0 -16
  191. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +0 -284
  192. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +0 -8
  193. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +0 -145
  194. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +0 -76
  195. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.js +0 -218
  196. package/dist/modules/BookingContext/utils/flexible.d.ts +0 -28
  197. package/dist/modules/BookingContext/utils/flexible.js +0 -56
  198. package/dist/modules/BookingContext/utils/formatResourceList.d.ts +0 -8
  199. package/dist/modules/BookingContext/utils/formatResourceList.js +0 -38
  200. package/dist/modules/BookingContext/utils/index.d.ts +0 -11
  201. package/dist/modules/BookingContext/utils/index.js +0 -11
  202. package/dist/modules/BookingContext/utils/noResource.d.ts +0 -13
  203. package/dist/modules/BookingContext/utils/noResource.js +0 -77
  204. package/dist/modules/BookingContext/utils/orderLineDisplay.d.ts +0 -1
  205. package/dist/modules/BookingContext/utils/orderLineDisplay.js +0 -36
  206. package/dist/modules/BookingContext/utils/productExtend.d.ts +0 -72
  207. package/dist/modules/BookingContext/utils/productExtend.js +0 -339
  208. package/dist/modules/BookingContext/utils/resourceErrors.d.ts +0 -41
  209. package/dist/modules/BookingContext/utils/resourceErrors.js +0 -74
  210. package/dist/modules/BookingContext/utils/resourceSelection.d.ts +0 -7
  211. package/dist/modules/BookingContext/utils/resourceSelection.js +0 -24
  212. package/dist/modules/BookingContext/utils/resources.d.ts +0 -80
  213. package/dist/modules/BookingContext/utils/resources.js +0 -486
  214. package/dist/modules/BookingContext/utils/serviceTimes.d.ts +0 -55
  215. package/dist/modules/BookingContext/utils/serviceTimes.js +0 -151
  216. package/dist/modules/BookingContext/utils/timeSlices.d.ts +0 -42
  217. package/dist/modules/BookingContext/utils/timeSlices.js +0 -100
  218. package/dist/modules/Order/utils/manualProductDiscount.d.ts +0 -106
  219. package/dist/modules/Order/utils/manualProductDiscount.js +0 -210
  220. package/dist/modules/SurchargeList/index.d.ts +0 -16
  221. package/dist/modules/SurchargeList/index.js +0 -162
  222. package/dist/modules/SurchargeList/types.d.ts +0 -11
  223. package/dist/modules/SurchargeList/types.js +0 -1
  224. package/dist/server/modules/payment/index.d.ts +0 -28
  225. package/dist/server/modules/payment/index.js +0 -305
  226. package/dist/server/modules/payment/types.d.ts +0 -9
  227. package/dist/server/modules/payment/types.js +0 -1
  228. package/dist/server/test.json +0 -713
  229. package/dist/server/utils/small-ticket.d.ts +0 -71
  230. package/dist/server/utils/small-ticket.js +0 -830
  231. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +0 -287
  232. package/dist/solution/BaseSales/utils/cartPromotion.js +0 -1438
  233. package/dist/solution/BaseSales/utils/quotationPrice.d.ts +0 -7
  234. package/dist/solution/BaseSales/utils/quotationPrice.js +0 -237
  235. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +0 -117
  236. package/dist/solution/BookingTicket/utils/addProductDecision.js +0 -346
  237. package/dist/solution/BookingTicket/utils/addTimeAvailability.d.ts +0 -35
  238. package/dist/solution/BookingTicket/utils/addTimeAvailability.js +0 -95
  239. package/dist/solution/BookingTicket/utils/exampleData.d.ts +0 -123
  240. package/dist/solution/BookingTicket/utils/exampleData.js +0 -183
  241. package/dist/solution/BookingTicket/utils/resolveBestAddTimePlan.d.ts +0 -185
  242. package/dist/solution/BookingTicket/utils/resolveBestAddTimePlan.js +0 -438
  243. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +0 -36
  244. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +0 -399
  245. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +0 -32
  246. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.js +0 -56
  247. package/dist/solution/BookingTicket/utils/scan/scanProductValues.d.ts +0 -21
  248. package/dist/solution/BookingTicket/utils/scan/scanProductValues.js +0 -150
  249. package/dist/solution/BookingTicket/utils/sessionCatalogStale.d.ts +0 -23
  250. package/dist/solution/BookingTicket/utils/sessionCatalogStale.js +0 -78
  251. package/lib/modules/BookingContext/index.d.ts +0 -48
  252. package/lib/modules/BookingContext/index.js +0 -368
  253. package/lib/modules/BookingContext/types.d.ts +0 -102
  254. package/lib/modules/BookingContext/types.js +0 -34
  255. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +0 -16
  256. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +0 -276
  257. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +0 -8
  258. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +0 -151
  259. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +0 -76
  260. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.js +0 -201
  261. package/lib/modules/BookingContext/utils/flexible.d.ts +0 -28
  262. package/lib/modules/BookingContext/utils/flexible.js +0 -80
  263. package/lib/modules/BookingContext/utils/formatResourceList.d.ts +0 -8
  264. package/lib/modules/BookingContext/utils/formatResourceList.js +0 -50
  265. package/lib/modules/BookingContext/utils/index.d.ts +0 -11
  266. package/lib/modules/BookingContext/utils/index.js +0 -43
  267. package/lib/modules/BookingContext/utils/noResource.d.ts +0 -13
  268. package/lib/modules/BookingContext/utils/noResource.js +0 -90
  269. package/lib/modules/BookingContext/utils/orderLineDisplay.d.ts +0 -1
  270. package/lib/modules/BookingContext/utils/orderLineDisplay.js +0 -56
  271. package/lib/modules/BookingContext/utils/productExtend.d.ts +0 -72
  272. package/lib/modules/BookingContext/utils/productExtend.js +0 -283
  273. package/lib/modules/BookingContext/utils/resourceErrors.d.ts +0 -41
  274. package/lib/modules/BookingContext/utils/resourceErrors.js +0 -80
  275. package/lib/modules/BookingContext/utils/resourceSelection.d.ts +0 -7
  276. package/lib/modules/BookingContext/utils/resourceSelection.js +0 -46
  277. package/lib/modules/BookingContext/utils/resources.d.ts +0 -80
  278. package/lib/modules/BookingContext/utils/resources.js +0 -377
  279. package/lib/modules/BookingContext/utils/serviceTimes.d.ts +0 -55
  280. package/lib/modules/BookingContext/utils/serviceTimes.js +0 -162
  281. package/lib/modules/BookingContext/utils/timeSlices.d.ts +0 -42
  282. package/lib/modules/BookingContext/utils/timeSlices.js +0 -124
  283. package/lib/modules/Order/utils/manualProductDiscount.d.ts +0 -106
  284. package/lib/modules/Order/utils/manualProductDiscount.js +0 -206
  285. package/lib/modules/SurchargeList/index.d.ts +0 -16
  286. package/lib/modules/SurchargeList/index.js +0 -89
  287. package/lib/modules/SurchargeList/types.d.ts +0 -11
  288. package/lib/modules/SurchargeList/types.js +0 -17
  289. package/lib/server/modules/payment/index.d.ts +0 -28
  290. package/lib/server/modules/payment/index.js +0 -192
  291. package/lib/server/modules/payment/types.d.ts +0 -9
  292. package/lib/server/modules/payment/types.js +0 -17
  293. package/lib/server/test.json +0 -713
  294. package/lib/server/utils/small-ticket.d.ts +0 -71
  295. package/lib/server/utils/small-ticket.js +0 -781
  296. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +0 -287
  297. package/lib/solution/BaseSales/utils/cartPromotion.js +0 -992
  298. package/lib/solution/BaseSales/utils/quotationPrice.d.ts +0 -7
  299. package/lib/solution/BaseSales/utils/quotationPrice.js +0 -277
  300. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +0 -117
  301. package/lib/solution/BookingTicket/utils/addProductDecision.js +0 -318
  302. package/lib/solution/BookingTicket/utils/addTimeAvailability.d.ts +0 -35
  303. package/lib/solution/BookingTicket/utils/addTimeAvailability.js +0 -125
  304. package/lib/solution/BookingTicket/utils/exampleData.d.ts +0 -123
  305. package/lib/solution/BookingTicket/utils/exampleData.js +0 -0
  306. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.d.ts +0 -185
  307. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.js +0 -254
  308. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +0 -36
  309. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +0 -168
  310. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +0 -32
  311. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.js +0 -51
  312. package/lib/solution/BookingTicket/utils/scan/scanProductValues.d.ts +0 -21
  313. package/lib/solution/BookingTicket/utils/scan/scanProductValues.js +0 -127
  314. package/lib/solution/BookingTicket/utils/sessionCatalogStale.d.ts +0 -23
  315. package/lib/solution/BookingTicket/utils/sessionCatalogStale.js +0 -85
@@ -37,157 +37,37 @@ var import_types = require("./types");
37
37
  var import_utils = require("./utils");
38
38
  var import_utils2 = require("../Product/utils");
39
39
  var import_dayjs = __toESM(require("dayjs"));
40
- var import_cartPromotion = require("../../solution/BaseSales/utils/cartPromotion");
41
40
  var import_utils3 = require("../../solution/ScanOrder/utils");
42
- var import_manualProductDiscount = require("./utils/manualProductDiscount");
43
41
  var import_Discount = require("../Discount");
44
42
  var import_Rules = require("../Rules");
45
43
  var import_types2 = require("../Rules/types");
46
44
  var import_decimal = __toESM(require("decimal.js"));
47
45
  var import_lodash_es = require("lodash-es");
48
- function normalizeDiscountListSignature(discountList) {
49
- return (discountList || []).map((item) => ({
50
- type: (item == null ? void 0 : item.type) ?? "",
51
- discount_id: (item == null ? void 0 : item.discount_id) ?? null,
52
- order_discount_id: (item == null ? void 0 : item.order_discount_id) ?? null,
53
- amount: new import_decimal.default(Number(item == null ? void 0 : item.amount) || 0).toFixed(2)
54
- }));
55
- }
56
- function isSameDiscountList(left, right) {
57
- if (!Array.isArray(left) || !Array.isArray(right))
58
- return false;
59
- return JSON.stringify(normalizeDiscountListSignature(left)) === JSON.stringify(
60
- normalizeDiscountListSignature(right)
61
- );
62
- }
63
- function isManualProductDiscountProduct(product) {
64
- var _a, _b;
65
- return ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.is_manual_discount) === true || ((_b = product == null ? void 0 : product.metadata) == null ? void 0 : _b.is_manual_discount) === 1 || ((product == null ? void 0 : product.discount_list) || []).some((item) => (item == null ? void 0 : item.type) === "product");
66
- }
46
+ var LOCAL_ORDER_STORE_NAME = "orders";
67
47
  var OrderModule = class extends import_BaseModule.BaseModule {
68
48
  constructor(name, version) {
69
49
  super(name || "order", version);
70
50
  this.defaultName = "order";
71
51
  this.defaultVersion = "1.0.0";
72
- // ─── 促销/赠品 ────────────────────────────────────
73
- /** 评估器引用;由 SalesSdkProvider 注入,未注入时 applyPromotion 静默跳过 */
74
- this.promotionEvaluator = null;
75
- /** 赠品选择 resolver;由 SDK host bridge 注入 */
76
- this.giftSelectResolver = null;
77
- /** applyPromotion 递归保护 flag(写路径同步调 applyPromotion,禁止重入) */
78
- this.isApplyingPromotion = false;
79
- /** 最近一次 applyPromotion 的未满足促销提示 */
80
- this.lastUnfulfilledPromotions = [];
81
- /** 最近一次 applyPromotion 的赠品操作 diff(debug / SDK 读取使用) */
82
- this.lastGiftActions = null;
83
- /**
84
- * 是否将 tempOrder 写入 IndexedDB 草稿(orders store)。
85
- * BigSale 弹窗等短生命周期场景通过 setEnableTempOrderPersist(false) 关闭。
86
- */
87
- this.draftPersistEnabled = true;
88
- }
89
- collectHydratedEditDiscounts(products) {
90
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
91
- const discountMap = /* @__PURE__ */ new Map();
92
- for (const product of products || []) {
93
- for (const item of (product == null ? void 0 : product.discount_list) || []) {
94
- const type = (item == null ? void 0 : item.type) ?? (item == null ? void 0 : item.tag);
95
- if (!type || type === "product")
96
- continue;
97
- const resourceId = ((_a = item == null ? void 0 : item.discount) == null ? void 0 : _a.resource_id) ?? (item == null ? void 0 : item.resource_id) ?? (item == null ? void 0 : item.discount_id) ?? (item == null ? void 0 : item.order_discount_id);
98
- if (resourceId === void 0 || resourceId === null || resourceId === "")
99
- continue;
100
- const id = Number(resourceId);
101
- const key = Number.isFinite(id) ? id : String(resourceId);
102
- const title = ((_b = item == null ? void 0 : item.discount) == null ? void 0 : _b.title) ?? {};
103
- const amount = Number((item == null ? void 0 : item.amount) || 0);
104
- const detail = {
105
- amount: String((item == null ? void 0 : item.amount) ?? "0"),
106
- type,
107
- resource_id: key,
108
- title,
109
- original_amount: String(((_c = item == null ? void 0 : item.discount) == null ? void 0 : _c.original_amount) ?? (item == null ? void 0 : item.amount) ?? "0"),
110
- num: Number(((_d = item == null ? void 0 : item.metadata) == null ? void 0 : _d.num) ?? (product == null ? void 0 : product.num) ?? (product == null ? void 0 : product.product_quantity) ?? 1) || 1,
111
- metadata: item == null ? void 0 : item.metadata,
112
- discount: item == null ? void 0 : item.discount,
113
- _num: Number(((_e = item == null ? void 0 : item.metadata) == null ? void 0 : _e.num) ?? (product == null ? void 0 : product.num) ?? (product == null ? void 0 : product.product_quantity) ?? 1) || 1
114
- };
115
- discountMap.set(key, {
116
- id: key,
117
- product_name: "",
118
- encoded: "",
119
- code: "",
120
- tag: type,
121
- product_id: ((_f = item == null ? void 0 : item.discount) == null ? void 0 : _f.discount_product_id) ?? (product == null ? void 0 : product.product_id) ?? 0,
122
- relation_type: "",
123
- par_value: String(((_g = item == null ? void 0 : item.discount) == null ? void 0 : _g.original_amount) ?? (item == null ? void 0 : item.amount) ?? "0"),
124
- used_par_value: String((item == null ? void 0 : item.amount) ?? "0"),
125
- limit_status: "enable",
126
- limited_relation_product_data: {
127
- id: 0,
128
- type: "products",
129
- product_ids: [product == null ? void 0 : product.product_id].filter((value) => value !== void 0 && value !== null),
130
- product_collection_id: [],
131
- filter: 0,
132
- exclude_product_ids: []
133
- },
134
- balance: String((item == null ? void 0 : item.amount) ?? "0"),
135
- format_title: title,
136
- product: {
137
- id: (product == null ? void 0 : product.product_id) ?? 0,
138
- title: "",
139
- is_charge_tax: (product == null ? void 0 : product.is_charge_tax) ?? 0,
140
- base_price: String((product == null ? void 0 : product.original_price) ?? (product == null ? void 0 : product.selling_price) ?? "0")
141
- },
142
- type,
143
- resource_id: key,
144
- isEditMode: true,
145
- isSelected: true,
146
- isAvailable: true,
147
- isUsed: true,
148
- isDisabled: true,
149
- amount,
150
- discount: {
151
- ...(item == null ? void 0 : item.discount) || {},
152
- resource_id: key,
153
- discount_product_id: ((_h = item == null ? void 0 : item.discount) == null ? void 0 : _h.discount_product_id) ?? (product == null ? void 0 : product.product_id) ?? 0,
154
- discount_calculation_mode: ((_i = item == null ? void 0 : item.discount) == null ? void 0 : _i.discount_calculation_mode) ?? "item_level"
155
- },
156
- applicableProductDetails: [detail],
157
- appliedProductDetails: [detail]
158
- });
159
- }
160
- }
161
- return Array.from(discountMap.values());
162
52
  }
163
53
  /**
164
54
  * Populate `savedAmount` on each discount based on product-level discount details.
165
55
  * Only selected discounts get a non-zero value.
166
56
  */
167
57
  static populateSavedAmounts(productList, discountList) {
58
+ var _a, _b;
168
59
  const savedMap = /* @__PURE__ */ new Map();
169
- const addDiscountAmount = (discount, quantity) => {
170
- var _a, _b;
171
- const discountKey = ((_a = discount.discount) == null ? void 0 : _a.resource_id) || discount.id;
172
- if (discountKey == null)
173
- return;
174
- const qty = Number(quantity) || 1;
175
- const amount = new import_decimal.default(discount.amount || 0).times(qty).plus(((_b = discount.metadata) == null ? void 0 : _b.product_discount_difference) || 0);
176
- savedMap.set(
177
- discountKey,
178
- (savedMap.get(discountKey) || new import_decimal.default(0)).plus(amount)
179
- );
180
- };
181
60
  for (const product of productList) {
182
61
  const qty = product.num || 1;
183
62
  for (const pd of product.discount_list || []) {
184
- addDiscountAmount(pd, qty);
185
- }
186
- for (const bundle of product.product_bundle || []) {
187
- const bundleQty = new import_decimal.default(Number(qty) || 1).times(Number((bundle == null ? void 0 : bundle.num) ?? (bundle == null ? void 0 : bundle.quantity) ?? 1) || 1).toNumber();
188
- for (const pd of (bundle == null ? void 0 : bundle.discount_list) || []) {
189
- addDiscountAmount(pd, bundleQty);
190
- }
63
+ const discountKey = ((_a = pd.discount) == null ? void 0 : _a.resource_id) || pd.id;
64
+ if (discountKey == null)
65
+ continue;
66
+ const amount = new import_decimal.default(pd.amount || 0).times(qty).plus(((_b = pd.metadata) == null ? void 0 : _b.product_discount_difference) || 0);
67
+ savedMap.set(
68
+ discountKey,
69
+ (savedMap.get(discountKey) || new import_decimal.default(0)).plus(amount)
70
+ );
191
71
  }
192
72
  }
193
73
  for (const d of discountList) {
@@ -195,32 +75,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
195
75
  d.savedAmount = d.isSelected && key != null && savedMap.has(key) ? savedMap.get(key).toNumber() : 0;
196
76
  }
197
77
  }
198
- applyProductDiscountPrices(products) {
199
- return (products || []).map((product) => {
200
- var _a, _b;
201
- if (isManualProductDiscountProduct(product))
202
- return product;
203
- const discountItems = Array.isArray(product.discount_list) ? product.discount_list : [];
204
- const hasOnlyPersistedDiscountSnapshots = product.order_detail_id !== void 0 && product.order_detail_id !== null && discountItems.length > 0 && discountItems.every((discount) => (discount == null ? void 0 : discount.order_discount_id) !== void 0 && (discount == null ? void 0 : discount.order_discount_id) !== null);
205
- if (hasOnlyPersistedDiscountSnapshots) {
206
- return product;
207
- }
208
- const totalPerUnitDiscount = (0, import_utils.resolveEffectivePerUnitDiscount)(product);
209
- const optionSum = (0, import_utils.sumOptionUnitPrice)((0, import_utils.getProductSkuOptions)(product));
210
- const sourcePrice = ((_a = product.metadata) == null ? void 0 : _a.source_product_price) ?? (((_b = product.metadata) == null ? void 0 : _b.main_product_original_price) != null ? new import_decimal.default(Number(product.metadata.main_product_original_price) || 0).minus(optionSum).toFixed(2) : product.original_price ?? "0");
211
- const newSourceSellingPrice = new import_decimal.default(Number(sourcePrice) || 0).minus(totalPerUnitDiscount).toDecimalPlaces(2).toString();
212
- const newMainSellingPrice = new import_decimal.default(Number(newSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
213
- if (product.metadata) {
214
- product.metadata.main_product_selling_price = newMainSellingPrice;
215
- product.metadata.price_schema_version = 2;
216
- }
217
- product.selling_price = (0, import_utils.composeLinePrice)({
218
- mainPrice: newMainSellingPrice,
219
- bundle: product.product_bundle
220
- });
221
- return product;
222
- });
223
- }
224
78
  async initialize(core, options) {
225
79
  var _a, _b, _c;
226
80
  this.core = core;
@@ -238,32 +92,18 @@ var OrderModule = class extends import_BaseModule.BaseModule {
238
92
  }
239
93
  const app = appPlugin.getApp();
240
94
  this.logger = app.logger;
95
+ this.dbManager = app.sqlite;
241
96
  this.window = this.core.getPlugin("window");
242
97
  const otherParams = options.otherParams || {};
243
98
  this.cacheId = otherParams.cacheId;
244
99
  this.salesSummaryModuleName = otherParams.salesSummaryModuleName;
245
100
  this.rulesHooksOverride = (_a = otherParams.rules) == null ? void 0 : _a.hooks;
246
- this.moduleHooksOverride = options.hooks;
247
- this.orderHooks = this.moduleHooksOverride || ((_b = otherParams.order) == null ? void 0 : _b.hooks) || ((_c = otherParams.hooks) == null ? void 0 : _c.order);
101
+ this.orderHooks = options.hooks || ((_b = otherParams.order) == null ? void 0 : _b.hooks) || ((_c = otherParams.hooks) == null ? void 0 : _c.order);
248
102
  this.otherParams = otherParams;
249
103
  this.registerDiscountModules(options);
104
+ this.restoreTempOrderFromStorage();
250
105
  this.logInfo("OrderModule initialized successfully");
251
106
  }
252
- /**
253
- * 更新父级解决方案透传的运行态参数,并同步 Order 内部依赖的派生字段。
254
- *
255
- * @example
256
- * orderModule.updateOtherParams({ cacheId: 'cache-2', channel: 'pos' });
257
- */
258
- updateOtherParams(params) {
259
- var _a, _b, _c;
260
- const otherParams = params || {};
261
- this.cacheId = otherParams.cacheId;
262
- this.salesSummaryModuleName = otherParams.salesSummaryModuleName;
263
- this.rulesHooksOverride = (_a = otherParams.rules) == null ? void 0 : _a.hooks;
264
- this.orderHooks = this.moduleHooksOverride || ((_b = otherParams.order) == null ? void 0 : _b.hooks) || ((_c = otherParams.hooks) == null ? void 0 : _c.order);
265
- this.otherParams = otherParams;
266
- }
267
107
  /**
268
108
  * 记录信息日志
269
109
  */
@@ -334,57 +174,26 @@ var OrderModule = class extends import_BaseModule.BaseModule {
334
174
  }
335
175
  // ─── Discount: 公共 API ───
336
176
  async loadDiscountConfig(params) {
337
- var _a, _b, _c, _d, _e, _f, _g;
338
- const orderId = params.orderId || ((_a = this.store.tempOrder) == null ? void 0 : _a.order_id) || void 0;
339
- const discountList = await ((_b = this.store.discount) == null ? void 0 : _b.loadPrepareConfig({
177
+ var _a, _b, _c, _d;
178
+ const discountList = await ((_a = this.store.discount) == null ? void 0 : _a.loadPrepareConfig({
340
179
  customer_id: params.customerId,
341
- action: params.action || (orderId ? "edit" : "create"),
180
+ action: params.action || "create",
342
181
  with_good_pass: 1,
343
182
  with_discount_card: 1,
344
183
  with_wallet_pass_holder: 1,
345
- request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
346
- ...orderId ? { order_id: orderId } : {}
184
+ request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
347
185
  }));
348
186
  if (discountList) {
349
- const currentEditDiscounts = (((_c = this.store.discount) == null ? void 0 : _c.getDiscountList()) || []).filter((discount) => discount == null ? void 0 : discount.isEditMode);
350
- const currentEditDiscountIds = new Set(
351
- currentEditDiscounts.map((discount) => discount == null ? void 0 : discount.id)
352
- );
353
- const mergedDiscountList = [
354
- ...currentEditDiscounts,
355
- ...discountList.filter((discount) => !currentEditDiscountIds.has(discount == null ? void 0 : discount.id))
356
- ];
357
- await ((_d = this.store.discount) == null ? void 0 : _d.setOriginalDiscountList(mergedDiscountList));
358
- await ((_e = this.store.discount) == null ? void 0 : _e.setDiscountList(mergedDiscountList));
187
+ (_b = this.store.discount) == null ? void 0 : _b.setDiscountList(discountList);
359
188
  }
360
- if (params.apply !== false && ((_g = (_f = this.store.tempOrder) == null ? void 0 : _f.products) == null ? void 0 : _g.length)) {
189
+ if ((_d = (_c = this.store.tempOrder) == null ? void 0 : _c.products) == null ? void 0 : _d.length) {
361
190
  this.applyDiscount();
362
191
  }
363
- return this.getDiscountList();
364
192
  }
365
193
  getDiscountList() {
366
194
  var _a;
367
195
  return ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList()) || [];
368
196
  }
369
- async ensureEditDiscountConfigForProductChange(tempOrder) {
370
- var _a, _b, _c, _d, _e, _f;
371
- const orderId = tempOrder.order_id;
372
- const customerId = Number(
373
- tempOrder.customer_id || ((_a = tempOrder.customer) == null ? void 0 : _a.id) || ((_c = (_b = tempOrder._extend) == null ? void 0 : _b.customerSnapshot) == null ? void 0 : _c.id) || ((_e = (_d = tempOrder._extend) == null ? void 0 : _d.customerSnapshot) == null ? void 0 : _e.customer_id) || 0
374
- );
375
- if (!orderId || !customerId || customerId === 1)
376
- return;
377
- const currentDiscountList = ((_f = this.store.discount) == null ? void 0 : _f.getDiscountList()) || [];
378
- const hasRuntimeDiscounts = currentDiscountList.some((discount) => !(discount == null ? void 0 : discount.isEditMode));
379
- if (hasRuntimeDiscounts)
380
- return;
381
- await this.loadDiscountConfig({
382
- customerId,
383
- action: "edit",
384
- orderId: Number(orderId),
385
- apply: false
386
- });
387
- }
388
197
  async scanCode(code, customerId) {
389
198
  var _a, _b, _c, _d, _e;
390
199
  const resultDiscountWithReason = await ((_a = this.store.discount) == null ? void 0 : _a.batchSearch(code, { customerId })) || { discountList: [], unavailableReasonKey: null };
@@ -395,7 +204,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
395
204
  type: "clientCalc",
396
205
  isAvailable: false,
397
206
  discountList: this.getDiscountList(),
398
- scannedDiscountList: resultDiscountList,
399
207
  unavailableReason: import_types2.UnavailableReason.Unknown
400
208
  };
401
209
  }
@@ -404,7 +212,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
404
212
  type: "server",
405
213
  isAvailable: false,
406
214
  discountList: this.getDiscountList(),
407
- scannedDiscountList: resultDiscountList,
408
215
  unavailableReasonKey
409
216
  };
410
217
  }
@@ -417,8 +224,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
417
224
  return {
418
225
  type: "clientCalc",
419
226
  isAvailable: true,
420
- discountList: this.getDiscountList(),
421
- scannedDiscountList: resultDiscountList
227
+ discountList: this.getDiscountList()
422
228
  };
423
229
  }
424
230
  const tempOrder = this.store.tempOrder;
@@ -439,7 +245,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
439
245
  type: "clientCalc",
440
246
  isAvailable: isAvailable || false,
441
247
  discountList: newDiscountList || this.getDiscountList(),
442
- scannedDiscountList: resultDiscountList,
443
248
  unavailableReason
444
249
  };
445
250
  }
@@ -448,7 +253,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
448
253
  const tempOrder = this.store.tempOrder;
449
254
  if (!tempOrder)
450
255
  return;
451
- delete tempOrder.discount_list;
452
256
  const rulesModule = this.store.rules;
453
257
  if (!rulesModule)
454
258
  return;
@@ -462,26 +266,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
462
266
  orderTotalAmount: Number(((_d = this.store.summary) == null ? void 0 : _d.total_amount) || 0)
463
267
  });
464
268
  if (result == null ? void 0 : result.productList) {
465
- const previousProductsByUid = (0, import_utils.indexOrderProductsByUid)(tempOrder.products);
466
- tempOrder.products = this.applyProductDiscountPrices(
467
- (result.productList || []).map((product, index) => {
468
- const uid = (0, import_utils.getOrderProductLineUid)(product);
469
- const previous = (uid ? previousProductsByUid.get(uid) : void 0) ?? previousProductsByUid.get(`__index__:${index}`);
470
- if (isManualProductDiscountProduct(previous)) {
471
- return previous;
472
- }
473
- const mergedProduct = previous ? (0, import_utils.mergeOrderProductDisplayFields)(previous, product) : product;
474
- return {
475
- ...mergedProduct,
476
- discount_list: (0, import_utils.normalizeOrderProductDiscountList)(
477
- (0, import_manualProductDiscount.syncManualProductDiscountProductNum)(
478
- mergedProduct.discount_list,
479
- mergedProduct.num
480
- )
481
- )
482
- };
483
- })
484
- );
269
+ tempOrder.products = result.productList;
485
270
  }
486
271
  if (result == null ? void 0 : result.discountList) {
487
272
  OrderModule.populateSavedAmounts(
@@ -489,201 +274,80 @@ var OrderModule = class extends import_BaseModule.BaseModule {
489
274
  result.discountList
490
275
  );
491
276
  (_e = this.store.discount) == null ? void 0 : _e.setDiscountList(result.discountList);
277
+ tempOrder.discount_list = result.discountList.filter(
278
+ (d) => d.isSelected
279
+ );
492
280
  }
493
281
  }
494
- // ─── 促销/赠品 ──────────────────────────────────────
495
- /**
496
- * 注入促销评估器。
497
- *
498
- * @example
499
- * order.setPromotionEvaluator(appHelper.utils.promotionEvaluator);
500
- */
501
- setPromotionEvaluator(evaluator) {
502
- this.promotionEvaluator = evaluator || null;
503
- }
504
- /**
505
- * 注入赠品选择 resolver。OS 需要补赠品时会 await 调用 resolver;缺省时跳过新增并 console.warn。
506
- *
507
- * @example
508
- * order.setGiftSelectResolver(async (ctx) => {
509
- * // SDK 内部决定弹窗 or 自动选第一项,返回完整 OrderProduct[]
510
- * return giftSelectBridge.request(ctx);
511
- * });
512
- */
513
- setGiftSelectResolver(resolver) {
514
- this.giftSelectResolver = resolver || null;
282
+ // ─── TempOrder: 初始化入口 ───
283
+ initTempOrder(params) {
284
+ if (params.cacheId !== void 0)
285
+ this.cacheId = params.cacheId;
286
+ if (params.salesSummaryModuleName !== void 0)
287
+ this.salesSummaryModuleName = params.salesSummaryModuleName;
288
+ this.restoreTempOrderFromStorage();
515
289
  }
516
- /**
517
- * 为商品目录追加促销标签,供上层 Sales 门面复用。
518
- *
519
- * @example
520
- * const products = order.appendPromotionTags(catalogProducts);
521
- */
522
- appendPromotionTags(products) {
523
- return (0, import_cartPromotion.appendPromotionTags)(products, this.promotionEvaluator);
290
+ // ─── TempOrder: localStorage 持久化 ───
291
+ getTempOrderStorageKey() {
292
+ if (!this.cacheId)
293
+ return null;
294
+ return `scanOrder:tempOrder:${this.cacheId}`;
524
295
  }
525
- /**
526
- * 应用购物车促销:计算 → 差异化赠品 → 写回 tempOrder.products → emit onPromotionApplied。
527
- *
528
- * 调用时机:写路径(add/update/remove/clear/setCustomer)末尾自动触发;外部一般无需手动调。
529
- *
530
- * 关键约束:
531
- * - 不调用任何公开 CRUD API(如 removeProductFromOrder),全部内部 mutate tempOrder.products,避免事件风暴;
532
- * - 用 `isApplyingPromotion` 防递归;
533
- * - 多选项赠品依赖 giftSelectResolver,未注入则跳过且 console.warn;
534
- * - 不主动调用 applyDiscount / recalculateSummary,调用方负责跟进。
535
- */
536
- async applyPromotion() {
537
- var _a;
538
- if (this.isApplyingPromotion) {
296
+ restoreTempOrderFromStorage() {
297
+ var _a, _b;
298
+ const key = this.getTempOrderStorageKey();
299
+ if (!key)
539
300
  return;
540
- }
541
- if (!this.promotionEvaluator) {
301
+ if (!this.window)
542
302
  return;
543
- }
544
- const tempOrder = this.store.tempOrder;
545
- if (!tempOrder) {
303
+ const cachedData = this.window.localStorage.getItem(key);
304
+ if (!cachedData)
546
305
  return;
547
- }
548
- this.isApplyingPromotion = true;
549
306
  try {
550
- const result = (0, import_cartPromotion.processCartPromotion)(
551
- tempOrder.products,
552
- this.promotionEvaluator
553
- );
554
- if (result.giftActions.toRemove.length > 0) {
555
- const removeSet = new Set(result.giftActions.toRemove.map(String));
556
- result.products = result.products.filter((p) => {
557
- const uid = (0, import_cartPromotion.getOrderProductUid)(p);
558
- return uid ? !removeSet.has(String(uid)) : true;
559
- });
560
- }
561
- for (const reduce of result.giftActions.toReduce) {
562
- for (const item of reduce.items) {
563
- const product = result.products.find(
564
- (p) => (0, import_cartPromotion.getOrderProductUid)(p) === item.uid
565
- );
566
- if (product) {
567
- product.num = item.newQuantity;
568
- }
569
- }
307
+ const parsedData = JSON.parse(cachedData);
308
+ if (!(0, import_utils.isTempOrder)(parsedData)) {
309
+ this.window.localStorage.removeItem(key);
310
+ return;
570
311
  }
571
- if (result.giftActions.toAdd.length > 0) {
572
- if (!this.giftSelectResolver) {
573
- if (result.giftActions.toAdd.some((g) => g.giftOptions.length > 1)) {
574
- console.warn(
575
- "[OrderModule] giftSelectResolver not set, skip applying gifts",
576
- result.giftActions.toAdd
577
- );
578
- } else {
579
- console.warn(
580
- "[OrderModule] giftSelectResolver not set, skip applying single-option gifts",
581
- result.giftActions.toAdd
582
- );
312
+ if (Array.isArray(parsedData.products)) {
313
+ for (let i = 0; i < parsedData.products.length; i++) {
314
+ const p = parsedData.products[i];
315
+ if (!p || typeof p !== "object")
316
+ continue;
317
+ if (!Array.isArray(p.product_option_item)) {
318
+ p.product_option_item = [];
583
319
  }
584
- } else {
585
- for (const addAction of result.giftActions.toAdd) {
586
- if (addAction.giftOptions.length === 1) {
587
- const sameStrategy = result.products.find(
588
- (p) => {
589
- var _a2, _b;
590
- return ((_b = (_a2 = p.metadata) == null ? void 0 : _a2._giftInfo) == null ? void 0 : _b.strategyId) === addAction.strategyId;
591
- }
592
- );
593
- if (sameStrategy && !sameStrategy.booking_uid && !((_a = sameStrategy.metadata) == null ? void 0 : _a.booking_uid)) {
594
- sameStrategy.num = (Number(sameStrategy.num) || 0) + (addAction.giftCount || 1);
595
- continue;
596
- }
597
- }
598
- try {
599
- const giftResult = await this.giftSelectResolver({
600
- strategyId: addAction.strategyId,
601
- strategyName: addAction.strategyName,
602
- giftCount: addAction.giftCount,
603
- giftOptions: addAction.giftOptions,
604
- sourceProductIds: addAction.sourceProductIds
605
- });
606
- const giftProducts = Array.isArray(giftResult) ? giftResult : giftResult == null ? void 0 : giftResult.products;
607
- const giftBookings = Array.isArray(giftResult) ? [] : (giftResult == null ? void 0 : giftResult.bookings) || [];
608
- if (Array.isArray(giftProducts) && giftProducts.length > 0) {
609
- for (const [index, gp] of giftProducts.entries()) {
610
- if (!gp)
611
- continue;
612
- const booking = giftBookings[index];
613
- if (booking) {
614
- const linked = this.createLinkedProductAndBooking({
615
- product: gp,
616
- booking
617
- });
618
- result.products.push(linked.product);
619
- tempOrder.bookings = [...tempOrder.bookings || [], linked.booking];
620
- continue;
621
- }
622
- result.products.push(gp);
623
- }
624
- }
625
- } catch (error) {
626
- console.warn(
627
- "[OrderModule] giftSelectResolver rejected, skip add gift",
628
- addAction.strategyId,
629
- error
630
- );
631
- }
320
+ if (!Array.isArray(p.product_bundle)) {
321
+ p.product_bundle = [];
632
322
  }
323
+ const row = p;
324
+ parsedData.products[i] = (0, import_utils3.normalizeOrderProduct)(row);
633
325
  }
634
326
  }
635
- tempOrder.products = result.products;
636
- this.lastUnfulfilledPromotions = result.unfulfilledPromotions;
637
- this.lastGiftActions = result.giftActions;
638
- const payload = {
639
- unfulfilledPromotions: result.unfulfilledPromotions,
640
- giftActions: result.giftActions,
641
- gifts: result.gifts.map((g) => ({
642
- strategyId: g.strategyId,
643
- strategyName: g.strategyName,
644
- giftCount: g.giftCount,
645
- giftOptions: g.giftOptions
646
- })),
647
- products: tempOrder.products
648
- };
649
- this.effectsEmit("onPromotionApplied", payload);
650
- } catch (error) {
651
- console.error("[OrderModule] applyPromotion failed", error);
652
- } finally {
653
- this.isApplyingPromotion = false;
327
+ const parsedRecord = parsedData;
328
+ this.store.summary = parsedRecord.summary || (0, import_utils.createEmptySummary)();
329
+ delete parsedData.summary;
330
+ if (parsedRecord.lastOrderInfo) {
331
+ this.store.lastOrderInfo = parsedRecord.lastOrderInfo;
332
+ delete parsedData.lastOrderInfo;
333
+ }
334
+ if (!parsedData._extend || typeof parsedData._extend !== "object") {
335
+ parsedData._extend = { productsByUid: {} };
336
+ } else if (!parsedData._extend.productsByUid) {
337
+ parsedData._extend.productsByUid = {};
338
+ }
339
+ this.store.tempOrder = parsedData;
340
+ } catch {
341
+ (_b = (_a = this.window) == null ? void 0 : _a.localStorage) == null ? void 0 : _b.removeItem(key);
654
342
  }
655
343
  }
656
- /** 最近一次 applyPromotion 输出的未满足促销列表 */
657
- getUnfulfilledPromotions() {
658
- return this.lastUnfulfilledPromotions;
659
- }
660
- /** 最近一次 applyPromotion 输出的赠品操作 diff */
661
- getLastGiftActions() {
662
- return this.lastGiftActions;
663
- }
664
- // ─── TempOrder: 初始化入口 ───
665
- initTempOrder(params) {
666
- if (params.cacheId !== void 0)
667
- this.cacheId = params.cacheId;
668
- if (params.salesSummaryModuleName !== void 0)
669
- this.salesSummaryModuleName = params.salesSummaryModuleName;
670
- }
671
- /**
672
- * 控制 IndexedDB 草稿(saveDraft)是否写入。
673
- * localStorage 版 tempOrder 持久化已废弃,此方法仅影响 saveDraft。
674
- *
675
- * @example
676
- * order.setEnableTempOrderPersist(false); // BigSale 弹窗:跳过 ~1s 的 dbUpdate
677
- */
678
- setEnableTempOrderPersist(enabled) {
679
- this.draftPersistEnabled = enabled;
680
- }
681
- /** 是否允许 saveDraft 写入 IndexedDB 草稿。 */
682
- isTempOrderPersistEnabled() {
683
- return this.draftPersistEnabled;
684
- }
685
- /** @deprecated OrderModule 不再负责 tempOrder localStorage 持久化;草稿保存请使用 IndexedDB saveDraft。 */
686
344
  persistTempOrder() {
345
+ const key = this.getTempOrderStorageKey();
346
+ if (!key || !this.store.tempOrder)
347
+ return;
348
+ if (!this.window)
349
+ return;
350
+ this.window.localStorage.setItem(key, JSON.stringify(this.store.tempOrder));
687
351
  }
688
352
  // ─── TempOrder: 创建 & 获取 ───
689
353
  createDefaultTempOrderInstance() {
@@ -727,18 +391,107 @@ var OrderModule = class extends import_BaseModule.BaseModule {
727
391
  }
728
392
  return tempOrder.request_unique_idempotency_token;
729
393
  }
730
- buildPaymentSyncIdempotencyToken(tempOrder, payments) {
731
- const baseToken = this.ensureRequestUniqueIdempotencyToken(tempOrder);
732
- const paidPaymentsCount = (payments || []).filter((payment) => {
733
- return String((payment == null ? void 0 : payment.status) || "").toLowerCase() === "paid";
734
- }).length;
735
- const paidCount = paidPaymentsCount > 0 ? paidPaymentsCount : payments.length;
736
- return `${baseToken}_payment_${paidCount}`;
394
+ hasLocalDatabase() {
395
+ return !!this.dbManager;
737
396
  }
738
- async saveDraft() {
397
+ buildLocalOrderRecord(tempOrder) {
398
+ const externalSaleNumber = this.ensureExternalSaleNumber(tempOrder);
399
+ return {
400
+ ...tempOrder,
401
+ id: tempOrder.order_id ?? externalSaleNumber,
402
+ external_sale_number: externalSaleNumber,
403
+ summary: this.store.summary || (0, import_utils.createEmptySummary)(),
404
+ lastOrderInfo: this.store.lastOrderInfo
405
+ };
406
+ }
407
+ async getLocalOrderByOrderId(orderId) {
408
+ var _a, _b, _c, _d;
409
+ if (!this.dbManager || orderId === void 0 || orderId === null)
410
+ return null;
411
+ try {
412
+ const direct = await ((_b = (_a = this.dbManager).get) == null ? void 0 : _b.call(
413
+ _a,
414
+ LOCAL_ORDER_STORE_NAME,
415
+ orderId
416
+ ));
417
+ if (direct)
418
+ return direct;
419
+ const orders = await ((_d = (_c = this.dbManager).getAll) == null ? void 0 : _d.call(_c, LOCAL_ORDER_STORE_NAME));
420
+ return (orders || []).find(
421
+ (order) => String(order == null ? void 0 : order.order_id) === String(orderId)
422
+ ) || null;
423
+ } catch (error) {
424
+ this.logWarning("getLocalOrderByOrderId failed", {
425
+ orderId,
426
+ error: error instanceof Error ? error.message : String(error)
427
+ });
428
+ return null;
429
+ }
430
+ }
431
+ async getLocalOrderByOrderNumber(orderNumber) {
432
+ var _a, _b, _c, _d;
433
+ if (!this.dbManager || !orderNumber)
434
+ return null;
435
+ try {
436
+ const direct = await ((_b = (_a = this.dbManager).get) == null ? void 0 : _b.call(
437
+ _a,
438
+ LOCAL_ORDER_STORE_NAME,
439
+ orderNumber
440
+ ));
441
+ if (direct)
442
+ return direct;
443
+ const orders = await ((_d = (_c = this.dbManager).getAll) == null ? void 0 : _d.call(_c, LOCAL_ORDER_STORE_NAME));
444
+ return (orders || []).find(
445
+ (order) => String(order == null ? void 0 : order.order_number) === String(orderNumber)
446
+ ) || null;
447
+ } catch (error) {
448
+ this.logWarning("getLocalOrderByOrderNumber failed", {
449
+ orderNumber,
450
+ error: error instanceof Error ? error.message : String(error)
451
+ });
452
+ return null;
453
+ }
454
+ }
455
+ async getLocalOrderByExternalSaleNumber(externalSaleNumber) {
456
+ var _a, _b, _c, _d;
457
+ if (!this.dbManager || !externalSaleNumber)
458
+ return null;
459
+ try {
460
+ const direct = await ((_b = (_a = this.dbManager).get) == null ? void 0 : _b.call(
461
+ _a,
462
+ LOCAL_ORDER_STORE_NAME,
463
+ externalSaleNumber
464
+ ));
465
+ if (direct)
466
+ return direct;
467
+ const orders = await ((_d = (_c = this.dbManager).getAll) == null ? void 0 : _d.call(_c, LOCAL_ORDER_STORE_NAME));
468
+ return (orders || []).find(
469
+ (order) => String(order == null ? void 0 : order.external_sale_number) === String(externalSaleNumber)
470
+ ) || null;
471
+ } catch (error) {
472
+ this.logWarning("getLocalOrderByExternalSaleNumber failed", {
473
+ externalSaleNumber,
474
+ error: error instanceof Error ? error.message : String(error)
475
+ });
476
+ return null;
477
+ }
739
478
  }
740
- saveDraftInBackground() {
741
- void this.saveDraft();
479
+ async saveDraft() {
480
+ var _a, _b;
481
+ if (!this.dbManager)
482
+ return;
483
+ const tempOrder = this.ensureTempOrder();
484
+ const record = this.buildLocalOrderRecord(tempOrder);
485
+ try {
486
+ await ((_b = (_a = this.dbManager).update) == null ? void 0 : _b.call(_a, LOCAL_ORDER_STORE_NAME, record));
487
+ } catch (error) {
488
+ this.logWarning("saveDraft failed", {
489
+ externalSaleNumber: tempOrder.external_sale_number,
490
+ orderNumber: tempOrder.order_number,
491
+ orderId: tempOrder.order_id,
492
+ error: error instanceof Error ? error.message : String(error)
493
+ });
494
+ }
742
495
  }
743
496
  async hydrateTempOrderFromLocalRecord(record) {
744
497
  return this.hydrateTempOrderFromRecord(record);
@@ -747,163 +500,15 @@ var OrderModule = class extends import_BaseModule.BaseModule {
747
500
  var _a, _b;
748
501
  return ((_a = result == null ? void 0 : result.data) == null ? void 0 : _a.order_id) ?? (result == null ? void 0 : result.order_id) ?? ((_b = result == null ? void 0 : result.data) == null ? void 0 : _b.id) ?? (result == null ? void 0 : result.id) ?? null;
749
502
  }
750
- calculatePaymentEffectiveAmount(payment) {
751
- const amount = new import_decimal.default(payment.amount || 0).minus(new import_decimal.default(payment.service_fee || 0));
752
- const rounding = new import_decimal.default(payment.rounding_amount || 0);
753
- return amount.minus(rounding);
754
- }
755
503
  calculatePaymentTotal(payments) {
756
504
  return (0, import_utils.mapPaymentItemsToOrderPayments)(payments, {
757
505
  includeVoided: false
758
506
  }).reduce((sum, payment) => {
759
- return sum.plus(this.calculatePaymentEffectiveAmount(payment));
507
+ const amount = new import_decimal.default(payment.amount || 0);
508
+ const rounding = new import_decimal.default(payment.rounding_amount || 0);
509
+ return sum.plus(amount.minus(rounding));
760
510
  }, new import_decimal.default(0));
761
511
  }
762
- getDepositAmount(tempOrder, summary) {
763
- return new import_decimal.default(summary.deposit_amount || tempOrder.deposit_amount || "0.00");
764
- }
765
- isDepositOrder(tempOrder, depositAmount) {
766
- return tempOrder.is_deposit === 1 || depositAmount.gt(0);
767
- }
768
- getOrderExpectedAmount(summary) {
769
- return new import_decimal.default(summary.expect_amount || summary.total_amount || 0);
770
- }
771
- isDepositCovered(params) {
772
- const depositAmount = this.getDepositAmount(params.tempOrder, params.summary);
773
- if (!this.isDepositOrder(params.tempOrder, depositAmount))
774
- return false;
775
- if (depositAmount.lte(0))
776
- return false;
777
- return params.paidAmount.gte(depositAmount);
778
- }
779
- normalizePaymentSource(payment, options) {
780
- const paymentRecord = payment;
781
- const metadata = paymentRecord.metadata && typeof paymentRecord.metadata === "object" ? { ...paymentRecord.metadata } : {};
782
- if (!metadata.unique_payment_number) {
783
- metadata.unique_payment_number = (0, import_utils.createUuidV4)();
784
- }
785
- const normalized = {
786
- ...paymentRecord,
787
- metadata,
788
- origin_amount: paymentRecord.origin_amount ?? paymentRecord.amount ?? "0.00"
789
- };
790
- if (paymentRecord.status !== void 0) {
791
- normalized.status = paymentRecord.status;
792
- } else if ((options == null ? void 0 : options.defaultPaid) !== false) {
793
- normalized.status = "paid";
794
- }
795
- return normalized;
796
- }
797
- updateTempOrderPaymentStatus(tempOrder, options) {
798
- const summary = (options == null ? void 0 : options.summary) || this.store.summary || (0, import_utils.createEmptySummary)();
799
- const paymentTotal = this.calculatePaymentTotal(tempOrder.payments || []);
800
- const refundAmount = this.getSummaryRefundAmount(summary);
801
- const netPaymentTotal = import_decimal.default.max(paymentTotal.minus(refundAmount), 0);
802
- const targetAmount = this.calculatePaymentTargetAmount(
803
- tempOrder,
804
- summary,
805
- netPaymentTotal
806
- );
807
- if (this.shouldKeepPaymentStatusAfterAmountRecalc(tempOrder.payment_status, {
808
- netPaymentTotal,
809
- paymentTotal,
810
- refundAmount,
811
- targetAmount,
812
- previousSummary: options == null ? void 0 : options.previousSummary,
813
- tempOrder
814
- })) {
815
- return;
816
- }
817
- if (targetAmount.lte(0)) {
818
- tempOrder.payment_status = "paid";
819
- return;
820
- }
821
- if (netPaymentTotal.lte(0)) {
822
- tempOrder.payment_status = "payment_processing";
823
- return;
824
- }
825
- tempOrder.payment_status = netPaymentTotal.gte(targetAmount) ? "paid" : "partially_paid";
826
- }
827
- shouldKeepPaymentStatusAfterAmountRecalc(paymentStatus, params) {
828
- const normalizedStatus = String(paymentStatus || "").trim().toLowerCase();
829
- if (normalizedStatus !== "refunded" && normalizedStatus !== "partially_refunded") {
830
- return false;
831
- }
832
- if (params.refundAmount.lte(0))
833
- return false;
834
- if (params.previousSummary) {
835
- const previousTargetAmount = this.calculatePaymentTargetAmount(
836
- params.tempOrder,
837
- params.previousSummary,
838
- params.netPaymentTotal
839
- );
840
- if (!previousTargetAmount.eq(params.targetAmount))
841
- return false;
842
- }
843
- if (normalizedStatus === "refunded") {
844
- return params.refundAmount.gte(params.paymentTotal);
845
- }
846
- return params.netPaymentTotal.gte(params.targetAmount);
847
- }
848
- resolveWalletPassUseValue(payment, amount) {
849
- const usageUnit = payment.wallet_pass_usage_unit && typeof payment.wallet_pass_usage_unit === "object" ? payment.wallet_pass_usage_unit : null;
850
- if (!usageUnit)
851
- return payment.wallet_pass_use_value;
852
- const price = new import_decimal.default(usageUnit.price || 0);
853
- const points = new import_decimal.default(usageUnit.points || 0);
854
- if (price.lte(0) || points.lte(0))
855
- return payment.wallet_pass_use_value;
856
- return amount.div(price).times(points).toDecimalPlaces(2).toFixed(2);
857
- }
858
- adjustVoucherFundRecord(params) {
859
- var _a;
860
- const fundRecord = params.voucher.fund_record && typeof params.voucher.fund_record === "object" && !Array.isArray(params.voucher.fund_record) ? { ...params.voucher.fund_record } : null;
861
- if (!fundRecord || fundRecord.using_before_value === void 0 || fundRecord.using_before_value === null) {
862
- return fundRecord || void 0;
863
- }
864
- const code = String(params.voucher.code || "").toUpperCase();
865
- const isPointCard = code === "POINTCARD" || String(((_a = params.voucher.fund_record) == null ? void 0 : _a.tag) || "").toLowerCase() === "point_card";
866
- const usingValue = isPointCard ? new import_decimal.default(params.walletPassUseValue || 0) : params.amount;
867
- fundRecord.using_after_value = new import_decimal.default(fundRecord.using_before_value || 0).minus(usingValue).toDecimalPlaces(2).toFixed(2);
868
- return fundRecord;
869
- }
870
- capVoucherPaymentsByRemainingAmount(params) {
871
- const targetAmount = this.getPaymentTargetAmount();
872
- const nonVoucherTotal = this.calculatePaymentTotal(params.nonVoucherPayments);
873
- if (targetAmount.lte(0))
874
- return [];
875
- let remainingAmount = import_decimal.default.max(
876
- targetAmount.minus(nonVoucherTotal),
877
- 0
878
- );
879
- const cappedVouchers = [];
880
- for (const voucher of params.vouchers) {
881
- if (remainingAmount.lte(0))
882
- break;
883
- const voucherAmount = import_decimal.default.max(new import_decimal.default(voucher.amount || 0), 0);
884
- if (voucherAmount.lte(0))
885
- continue;
886
- const cappedAmount = import_decimal.default.min(voucherAmount, remainingAmount);
887
- const amountText = cappedAmount.toDecimalPlaces(2).toFixed(2);
888
- const walletPassUseValue = this.resolveWalletPassUseValue(
889
- voucher,
890
- cappedAmount
891
- );
892
- cappedVouchers.push({
893
- ...voucher,
894
- amount: amountText,
895
- origin_amount: amountText,
896
- wallet_pass_use_value: walletPassUseValue,
897
- fund_record: this.adjustVoucherFundRecord({
898
- voucher,
899
- amount: cappedAmount,
900
- walletPassUseValue
901
- })
902
- });
903
- remainingAmount = remainingAmount.minus(cappedAmount);
904
- }
905
- return cappedVouchers;
906
- }
907
512
  calculatePaidPaymentSummary(payments) {
908
513
  return (payments || []).reduce(
909
514
  (summary, payment) => {
@@ -913,17 +518,13 @@ var OrderModule = class extends import_BaseModule.BaseModule {
913
518
  return {
914
519
  customerPaidAmount: summary.customerPaidAmount.plus(paymentRecord.amount || 0),
915
520
  orderPaidAmount: summary.orderPaidAmount.plus(paymentRecord.origin_amount || 0),
916
- gapPaidAmount: summary.gapPaidAmount.plus(this.calculatePaymentGapAmount(paymentRecord)),
917
- payServiceChargeAmount: summary.payServiceChargeAmount.plus(this.calculatePaymentServiceFee(paymentRecord)),
918
- roundingAmount: summary.roundingAmount.plus(this.calculatePaymentRoundingAmount(paymentRecord))
521
+ payServiceChargeAmount: summary.payServiceChargeAmount.plus(this.calculatePaymentServiceFee(paymentRecord))
919
522
  };
920
523
  },
921
524
  {
922
525
  customerPaidAmount: new import_decimal.default(0),
923
526
  orderPaidAmount: new import_decimal.default(0),
924
- gapPaidAmount: new import_decimal.default(0),
925
- payServiceChargeAmount: new import_decimal.default(0),
926
- roundingAmount: new import_decimal.default(0)
527
+ payServiceChargeAmount: new import_decimal.default(0)
927
528
  }
928
529
  );
929
530
  }
@@ -936,363 +537,15 @@ var OrderModule = class extends import_BaseModule.BaseModule {
936
537
  const fixedAmount = new import_decimal.default(serviceCharge.amount || 0);
937
538
  return new import_decimal.default(payment.amount || 0).times(percentage).plus(fixedAmount);
938
539
  }
939
- calculatePaymentGapAmount(payment) {
940
- if (payment.origin_amount === void 0 || payment.origin_amount === null || payment.origin_amount === "") {
941
- return new import_decimal.default(0);
942
- }
943
- const rounding = new import_decimal.default(payment.rounding_amount || 0);
944
- return new import_decimal.default(payment.origin_amount || 0).minus(rounding);
945
- }
946
- calculatePaymentRoundingAmount(payment) {
947
- if (payment.rounding_amount === void 0 || payment.rounding_amount === null || payment.rounding_amount === "") {
948
- return new import_decimal.default(0);
949
- }
950
- return new import_decimal.default(payment.rounding_amount || 0);
951
- }
952
- formatSummaryMetadataMoney(value) {
953
- if (value === void 0 || value === null || value === "")
954
- return void 0;
955
- if (value instanceof import_decimal.default)
956
- return value.toFixed(2);
957
- return new import_decimal.default(String(value || 0)).toFixed(2);
958
- }
959
- syncSummaryProductMetadata(products) {
960
- const moneyKeys = [
961
- "main_product_attached_bundle_surcharge_fee",
962
- "main_product_attached_bundle_tax_fee",
963
- "surcharge_rounding_remainder",
964
- "tax_fee_rounding_remainder"
965
- ];
966
- const metadataMoneyKeys = [
967
- "main_product_attached_bundle_selling_price",
968
- "main_product_attached_bundle_payment_price"
969
- ];
970
- for (const product of products || []) {
971
- const productRecord = product;
972
- const metadata = productRecord.metadata && typeof productRecord.metadata === "object" ? { ...productRecord.metadata } : {};
973
- let hasMetadataPatch = false;
974
- for (const key of moneyKeys) {
975
- const value = this.formatSummaryMetadataMoney(productRecord[key]);
976
- if (value === void 0)
977
- continue;
978
- metadata[key] = value;
979
- hasMetadataPatch = true;
980
- }
981
- for (const key of metadataMoneyKeys) {
982
- const value = this.formatSummaryMetadataMoney(metadata[key]);
983
- if (value === void 0)
984
- continue;
985
- metadata[key] = value;
986
- hasMetadataPatch = true;
987
- }
988
- if (metadata.average_discount_amount_rate !== void 0) {
989
- hasMetadataPatch = true;
990
- }
991
- if (Array.isArray(productRecord.relation_surcharge_ids)) {
992
- metadata.relation_surcharge_ids = productRecord.relation_surcharge_ids;
993
- hasMetadataPatch = true;
994
- }
995
- const productPaymentPrice = this.formatSummaryMetadataMoney(
996
- productRecord.payment_price
997
- );
998
- if (productPaymentPrice !== void 0) {
999
- productRecord.payment_price = productPaymentPrice;
1000
- }
1001
- if (hasMetadataPatch)
1002
- productRecord.metadata = metadata;
1003
- if (!Array.isArray(productRecord.product_bundle))
1004
- continue;
1005
- for (const bundle of productRecord.product_bundle) {
1006
- const bundleRecord = bundle;
1007
- const bundleMetadata = bundleRecord.metadata && typeof bundleRecord.metadata === "object" ? { ...bundleRecord.metadata } : {};
1008
- let hasBundleMetadataPatch = false;
1009
- const bundleSurchargeFee = this.formatSummaryMetadataMoney(
1010
- bundleRecord.surcharge_fee
1011
- );
1012
- if (bundleSurchargeFee !== void 0) {
1013
- bundleMetadata.surcharge_fee = bundleSurchargeFee;
1014
- hasBundleMetadataPatch = true;
1015
- }
1016
- const bundlePaymentPrice = this.formatSummaryMetadataMoney(
1017
- bundleRecord.bundle_payment_price
1018
- );
1019
- if (bundlePaymentPrice !== void 0) {
1020
- bundleRecord.bundle_payment_price = bundlePaymentPrice;
1021
- }
1022
- if (Array.isArray(bundleRecord.relation_surcharge_ids)) {
1023
- bundleMetadata.relation_surcharge_ids = bundleRecord.relation_surcharge_ids;
1024
- hasBundleMetadataPatch = true;
1025
- }
1026
- if (hasBundleMetadataPatch)
1027
- bundleRecord.metadata = bundleMetadata;
1028
- }
1029
- }
1030
- }
1031
- calculateSummaryAmountGap(params) {
1032
- const { tempOrder, summary, orderPaidAmount } = params;
1033
- const refundAmount = this.getSummaryRefundAmount(summary);
1034
- const netOrderPaidAmount = import_decimal.default.max(orderPaidAmount.minus(refundAmount), 0);
1035
- const targetAmount = this.calculatePaymentTargetAmount(
1036
- tempOrder,
1037
- summary,
1038
- netOrderPaidAmount
1039
- );
1040
- return targetAmount.minus(netOrderPaidAmount).toFixed(2);
1041
- }
1042
- getSummaryRefundAmount(summary) {
1043
- return import_decimal.default.max(new import_decimal.default((summary == null ? void 0 : summary.total_refund_amount) || 0), 0);
1044
- }
1045
- calculatePaymentTargetAmount(tempOrder, summary, paidAmount = new import_decimal.default(0)) {
1046
- const depositAmount = this.getDepositAmount(tempOrder, summary);
1047
- if (!this.isDepositOrder(tempOrder, depositAmount)) {
1048
- return this.getOrderExpectedAmount(summary);
1049
- }
1050
- if (this.isDepositCovered({ tempOrder, summary, paidAmount })) {
1051
- return this.getOrderExpectedAmount(summary);
1052
- }
1053
- return depositAmount;
1054
- }
1055
- normalizeFingerprintMoney(value) {
1056
- if (value === void 0 || value === null || value === "")
1057
- return "";
1058
- try {
1059
- const parsed = new import_decimal.default(String(value || 0));
1060
- return parsed.toFixed(4);
1061
- } catch {
1062
- return String(value);
1063
- }
1064
- }
1065
- normalizeFingerprintValue(value) {
1066
- if (Array.isArray(value)) {
1067
- return value.map((item) => this.normalizeFingerprintValue(item));
1068
- }
1069
- if (!value || typeof value !== "object")
1070
- return value ?? "";
1071
- return Object.keys(value).sort().reduce((result, key) => {
1072
- result[key] = this.normalizeFingerprintValue(value[key]);
1073
- return result;
1074
- }, {});
1075
- }
1076
- buildProductFingerprintItem(product) {
1077
- const sku = (product == null ? void 0 : product.product_sku) || {};
1078
- const metadata = (product == null ? void 0 : product.metadata) || {};
1079
- const discountTypes = ((product == null ? void 0 : product.discount_list) || []).map((discount) => (discount == null ? void 0 : discount.type) ?? (discount == null ? void 0 : discount.tag));
1080
- const extensionType = (product == null ? void 0 : product.extension_type) || (discountTypes.includes("good_pass") ? "good_pass" : "normal");
1081
- return {
1082
- product_id: (product == null ? void 0 : product.product_id) ?? null,
1083
- product_variant_id: (product == null ? void 0 : product.product_variant_id) ?? null,
1084
- extension_type: extensionType,
1085
- num: (0, import_utils3.getSafeProductNum)((product == null ? void 0 : product.num) ?? (product == null ? void 0 : product.product_quantity)),
1086
- selling_price: this.normalizeFingerprintMoney(product == null ? void 0 : product.selling_price),
1087
- original_price: this.normalizeFingerprintMoney(product == null ? void 0 : product.original_price),
1088
- payment_price: this.normalizeFingerprintMoney((product == null ? void 0 : product.payment_price) ?? (product == null ? void 0 : product.selling_price)),
1089
- metadata: {
1090
- source_product_price: this.normalizeFingerprintMoney(metadata.source_product_price),
1091
- main_product_selling_price: this.normalizeFingerprintMoney(metadata.main_product_selling_price),
1092
- main_product_original_price: this.normalizeFingerprintMoney(metadata.main_product_original_price),
1093
- product_discount_difference: this.normalizeFingerprintMoney(metadata.product_discount_difference)
1094
- },
1095
- product_sku: this.normalizeFingerprintValue({
1096
- code: sku.code ?? "",
1097
- barcode: sku.barcode ?? "",
1098
- variant_id: sku.variant_id ?? (product == null ? void 0 : product.product_variant_id) ?? 0,
1099
- variant: sku.variant || [],
1100
- option: (0, import_utils.getProductSkuOptions)(product || {}).map((option) => ({
1101
- id: (option == null ? void 0 : option.id) ?? (option == null ? void 0 : option.option_group_item_id) ?? null,
1102
- option_group_id: (option == null ? void 0 : option.option_group_id) ?? null,
1103
- option_group_item_id: (option == null ? void 0 : option.option_group_item_id) ?? (option == null ? void 0 : option.id) ?? null,
1104
- num: Number((option == null ? void 0 : option.num) ?? 1) || 1,
1105
- add_price: this.normalizeFingerprintMoney((option == null ? void 0 : option.add_price) ?? (option == null ? void 0 : option.price))
1106
- }))
1107
- }),
1108
- product_bundle: this.normalizeFingerprintValue(((product == null ? void 0 : product.product_bundle) || []).map((bundle) => ({
1109
- bundle_product_id: (bundle == null ? void 0 : bundle.bundle_product_id) ?? (bundle == null ? void 0 : bundle._bundle_product_id) ?? (bundle == null ? void 0 : bundle.product_id) ?? null,
1110
- bundle_variant_id: (bundle == null ? void 0 : bundle.bundle_variant_id) ?? (bundle == null ? void 0 : bundle.product_variant_id) ?? 0,
1111
- num: (0, import_utils3.getSafeProductNum)((bundle == null ? void 0 : bundle.num) ?? (bundle == null ? void 0 : bundle.quantity)),
1112
- price: this.normalizeFingerprintMoney(bundle == null ? void 0 : bundle.price),
1113
- bundle_selling_price: this.normalizeFingerprintMoney(bundle == null ? void 0 : bundle.bundle_selling_price),
1114
- price_type: (bundle == null ? void 0 : bundle.price_type) ?? "",
1115
- price_type_ext: (bundle == null ? void 0 : bundle.price_type_ext) ?? ""
1116
- }))),
1117
- discount_list: this.normalizeFingerprintValue(((product == null ? void 0 : product.discount_list) || []).map((discount) => {
1118
- var _a;
1119
- return {
1120
- type: (discount == null ? void 0 : discount.type) ?? (discount == null ? void 0 : discount.tag) ?? "",
1121
- discount_id: (discount == null ? void 0 : discount.discount_id) ?? (discount == null ? void 0 : discount.order_discount_id) ?? ((_a = discount == null ? void 0 : discount.discount) == null ? void 0 : _a.resource_id) ?? null,
1122
- amount: this.normalizeFingerprintMoney(discount == null ? void 0 : discount.amount)
1123
- };
1124
- }))
1125
- };
1126
- }
1127
- buildOrderProductsFingerprint(products) {
1128
- const items = (products || []).map((product) => this.buildProductFingerprintItem(product));
1129
- items.sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));
1130
- return JSON.stringify(items);
1131
- }
1132
- buildProductStructuralFingerprintItem(product) {
1133
- const sku = (product == null ? void 0 : product.product_sku) || {};
1134
- const metadata = (product == null ? void 0 : product.metadata) || {};
1135
- const discountTypes = ((product == null ? void 0 : product.discount_list) || []).map((discount) => (discount == null ? void 0 : discount.type) ?? (discount == null ? void 0 : discount.tag));
1136
- const extensionType = (product == null ? void 0 : product.extension_type) || (discountTypes.includes("good_pass") ? "good_pass" : "normal");
1137
- return {
1138
- product_id: (product == null ? void 0 : product.product_id) ?? null,
1139
- product_variant_id: (product == null ? void 0 : product.product_variant_id) ?? null,
1140
- extension_type: extensionType,
1141
- num: (0, import_utils3.getSafeProductNum)((product == null ? void 0 : product.num) ?? (product == null ? void 0 : product.product_quantity)),
1142
- metadata: {
1143
- unique_identification_number: metadata.unique_identification_number ?? (product == null ? void 0 : product.unique_identification_number) ?? "",
1144
- price_override: metadata.price_override ?? "",
1145
- is_manual_discount: metadata.is_manual_discount ?? "",
1146
- product_discount_reason: metadata.product_discount_reason ?? ""
1147
- },
1148
- product_sku: this.normalizeFingerprintValue({
1149
- code: sku.code ?? "",
1150
- barcode: sku.barcode ?? "",
1151
- variant_id: sku.variant_id ?? (product == null ? void 0 : product.product_variant_id) ?? 0,
1152
- variant: sku.variant || [],
1153
- option: (0, import_utils.getProductSkuOptions)(product || {}).map((option) => ({
1154
- id: (option == null ? void 0 : option.id) ?? (option == null ? void 0 : option.option_group_item_id) ?? null,
1155
- option_group_id: (option == null ? void 0 : option.option_group_id) ?? null,
1156
- option_group_item_id: (option == null ? void 0 : option.option_group_item_id) ?? (option == null ? void 0 : option.id) ?? null,
1157
- num: Number((option == null ? void 0 : option.num) ?? 1) || 1,
1158
- add_price: this.normalizeFingerprintMoney((option == null ? void 0 : option.add_price) ?? (option == null ? void 0 : option.price))
1159
- }))
1160
- }),
1161
- product_bundle: this.normalizeFingerprintValue(((product == null ? void 0 : product.product_bundle) || []).map((bundle) => ({
1162
- bundle_id: (bundle == null ? void 0 : bundle.bundle_id) ?? (bundle == null ? void 0 : bundle.id) ?? null,
1163
- bundle_group_id: (bundle == null ? void 0 : bundle.bundle_group_id) ?? (bundle == null ? void 0 : bundle.group_id) ?? null,
1164
- bundle_product_id: (bundle == null ? void 0 : bundle.bundle_product_id) ?? (bundle == null ? void 0 : bundle._bundle_product_id) ?? (bundle == null ? void 0 : bundle.product_id) ?? null,
1165
- bundle_variant_id: (bundle == null ? void 0 : bundle.bundle_variant_id) ?? (bundle == null ? void 0 : bundle.product_variant_id) ?? 0,
1166
- num: (0, import_utils3.getSafeProductNum)((bundle == null ? void 0 : bundle.num) ?? (bundle == null ? void 0 : bundle.quantity)),
1167
- price_type: (bundle == null ? void 0 : bundle.price_type) ?? "",
1168
- price_type_ext: (bundle == null ? void 0 : bundle.price_type_ext) ?? "",
1169
- option: this.normalizeFingerprintValue(((bundle == null ? void 0 : bundle.option) || []).map((option) => ({
1170
- id: (option == null ? void 0 : option.id) ?? (option == null ? void 0 : option.option_group_item_id) ?? null,
1171
- option_group_id: (option == null ? void 0 : option.option_group_id) ?? null,
1172
- option_group_item_id: (option == null ? void 0 : option.option_group_item_id) ?? (option == null ? void 0 : option.id) ?? null,
1173
- num: Number((option == null ? void 0 : option.num) ?? 1) || 1,
1174
- add_price: this.normalizeFingerprintMoney((option == null ? void 0 : option.add_price) ?? (option == null ? void 0 : option.price))
1175
- })))
1176
- }))),
1177
- discount_list: this.normalizeFingerprintValue(((product == null ? void 0 : product.discount_list) || []).map((discount) => {
1178
- var _a;
1179
- return {
1180
- type: (discount == null ? void 0 : discount.type) ?? (discount == null ? void 0 : discount.tag) ?? "",
1181
- discount_id: (discount == null ? void 0 : discount.discount_id) ?? (discount == null ? void 0 : discount.order_discount_id) ?? ((_a = discount == null ? void 0 : discount.discount) == null ? void 0 : _a.resource_id) ?? null,
1182
- amount: this.normalizeFingerprintMoney(discount == null ? void 0 : discount.amount)
1183
- };
1184
- }))
1185
- };
1186
- }
1187
- buildOrderProductsStructuralFingerprint(products) {
1188
- const items = (products || []).map((product) => this.buildProductStructuralFingerprintItem(product));
1189
- items.sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));
1190
- return JSON.stringify(items);
1191
- }
1192
- getOriginalSalesSnapshot(tempOrder) {
1193
- var _a;
1194
- const snapshot = (_a = tempOrder._extend) == null ? void 0 : _a.originalSalesSnapshot;
1195
- if (!snapshot || typeof snapshot !== "object")
1196
- return null;
1197
- if (typeof snapshot.productFingerprint !== "string")
1198
- return null;
1199
- return snapshot;
1200
- }
1201
- isSnapshotPayableAmountUnchanged(tempOrder, snapshot, snapshotSummary) {
1202
- const currentPaidPaymentSummary = this.calculatePaidPaymentSummary(tempOrder.payments || []);
1203
- const currentAmountGap = this.calculateSummaryAmountGap({
1204
- tempOrder,
1205
- summary: snapshotSummary,
1206
- orderPaidAmount: currentPaidPaymentSummary.gapPaidAmount
1207
- });
1208
- const snapshotPaidPaymentSummary = this.calculatePaidPaymentSummary(
1209
- Array.isArray(snapshot.payments) ? snapshot.payments : []
1210
- );
1211
- const snapshotAmountGap = this.calculateSummaryAmountGap({
1212
- tempOrder,
1213
- summary: snapshotSummary,
1214
- orderPaidAmount: snapshotPaidPaymentSummary.gapPaidAmount
1215
- });
1216
- return currentAmountGap === snapshotAmountGap;
1217
- }
1218
- restoreOriginalSnapshotIfProductsUnchanged(tempOrder) {
1219
- const snapshot = this.getOriginalSalesSnapshot(tempOrder);
1220
- if (!snapshot)
1221
- return null;
1222
- const currentFingerprint = this.buildOrderProductsFingerprint(tempOrder.products);
1223
- if (currentFingerprint !== snapshot.productFingerprint) {
1224
- const currentStructuralFingerprint = this.buildOrderProductsStructuralFingerprint(tempOrder.products);
1225
- const snapshotStructuralFingerprint = this.buildOrderProductsStructuralFingerprint(
1226
- Array.isArray(snapshot.products) ? snapshot.products : []
1227
- );
1228
- if (currentStructuralFingerprint !== snapshotStructuralFingerprint)
1229
- return null;
1230
- }
1231
- const summary = {
1232
- ...(0, import_utils.createEmptySummary)(),
1233
- ...(0, import_lodash_es.cloneDeep)(snapshot.summary || {})
1234
- };
1235
- if (!this.isSnapshotPayableAmountUnchanged(tempOrder, snapshot, summary))
1236
- return null;
1237
- if (Array.isArray(snapshot.products)) {
1238
- tempOrder.products = (0, import_lodash_es.cloneDeep)(snapshot.products);
1239
- }
1240
- if (Array.isArray(snapshot.surcharges)) {
1241
- tempOrder.surcharges = (0, import_lodash_es.cloneDeep)(snapshot.surcharges);
1242
- }
1243
- tempOrder.surcharge_fee = summary.surcharge_fee || tempOrder.surcharge_fee;
1244
- tempOrder.deposit_amount = summary.deposit_amount || "0.00";
1245
- tempOrder.is_deposit = summary.deposit_amount !== "0.00" ? 1 : 0;
1246
- this.store.summary = summary;
1247
- return summary;
1248
- }
1249
- clearPersistedAmountFieldsForFullRecalc(products) {
1250
- const moneyKeys = [
1251
- "surcharge_fee",
1252
- "main_product_attached_bundle_surcharge_fee",
1253
- "surcharge_rounding_remainder",
1254
- "main_product_attached_bundle_tax_fee",
1255
- "tax_fee",
1256
- "original_tax_fee",
1257
- "tax_fee_rounding_remainder",
1258
- "original_tax_fee_rounding_remainder"
1259
- ];
1260
- const metadataMoneyKeys = [
1261
- "main_product_attached_bundle_surcharge_fee",
1262
- "surcharge_rounding_remainder",
1263
- "main_product_attached_bundle_tax_fee",
1264
- "tax_fee_rounding_remainder"
1265
- ];
1266
- for (const product of products || []) {
1267
- const record = product;
1268
- for (const key of moneyKeys)
1269
- delete record[key];
1270
- if (record.metadata && typeof record.metadata === "object") {
1271
- record.metadata = { ...record.metadata };
1272
- for (const key of metadataMoneyKeys)
1273
- delete record.metadata[key];
1274
- }
1275
- for (const bundle of record.product_bundle || []) {
1276
- for (const key of moneyKeys)
1277
- delete bundle[key];
1278
- if (bundle.metadata && typeof bundle.metadata === "object") {
1279
- bundle.metadata = { ...bundle.metadata };
1280
- for (const key of metadataMoneyKeys)
1281
- delete bundle.metadata[key];
1282
- }
1283
- }
1284
- }
1285
- }
1286
540
  getPaymentTargetAmount() {
1287
541
  const tempOrder = this.ensureTempOrder();
1288
542
  const summary = this.store.summary || (0, import_utils.createEmptySummary)();
1289
- const paidPaymentSummary = this.calculatePaidPaymentSummary(tempOrder.payments || []);
1290
- const refundAmount = this.getSummaryRefundAmount(summary);
1291
- const netPaidAmount = import_decimal.default.max(
1292
- paidPaymentSummary.gapPaidAmount.minus(refundAmount),
1293
- 0
1294
- );
1295
- return this.calculatePaymentTargetAmount(tempOrder, summary, netPaidAmount);
543
+ if (tempOrder.is_deposit === 1) {
544
+ return new import_decimal.default(
545
+ tempOrder.deposit_amount || summary.deposit_amount || 0
546
+ );
547
+ }
548
+ return new import_decimal.default(summary.total_amount || summary.expect_amount || 0);
1296
549
  }
1297
550
  ensureTempOrder() {
1298
551
  if (this.store.tempOrder) {
@@ -1306,43 +559,17 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1306
559
  return newOrder;
1307
560
  }
1308
561
  restoreOrder() {
1309
- var _a, _b;
1310
562
  const freshTempOrder = this.createDefaultTempOrderInstance();
1311
563
  this.ensureExternalSaleNumber(freshTempOrder);
1312
564
  this.store.tempOrder = freshTempOrder;
1313
565
  this.store.summary = (0, import_utils.createEmptySummary)();
1314
566
  this.store.lastOrderInfo = void 0;
1315
- this.store.syncState = void 0;
1316
- void ((_a = this.store.discount) == null ? void 0 : _a.setOriginalDiscountList([]));
1317
- void ((_b = this.store.discount) == null ? void 0 : _b.setDiscountList([]));
1318
567
  this.persistTempOrder();
1319
568
  return freshTempOrder;
1320
569
  }
1321
570
  getTempOrder() {
1322
571
  return this.store.tempOrder;
1323
572
  }
1324
- async replaceTempOrder(tempOrder, options) {
1325
- if (!(0, import_utils.isTempOrder)(tempOrder)) {
1326
- throw new Error("无效的 tempOrder 数据");
1327
- }
1328
- const nextTempOrder = this.normalizeTempOrderForRuntime(
1329
- (0, import_lodash_es.cloneDeep)(tempOrder),
1330
- { ensureIdentity: false }
1331
- );
1332
- this.store.tempOrder = nextTempOrder;
1333
- if ((options == null ? void 0 : options.recalculateSummary) !== false) {
1334
- await this.recalculateSummary({ createIfMissing: false });
1335
- } else {
1336
- this.store.summary = (0, import_utils.createEmptySummary)();
1337
- }
1338
- if ((options == null ? void 0 : options.persist) !== false) {
1339
- this.persistTempOrder();
1340
- }
1341
- if (options == null ? void 0 : options.saveDraft) {
1342
- await this.saveDraft();
1343
- }
1344
- return nextTempOrder;
1345
- }
1346
573
  getOrderIdentity() {
1347
574
  var _a;
1348
575
  const tempOrder = this.store.tempOrder;
@@ -1378,12 +605,9 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1378
605
  return null;
1379
606
  const summary = this.store.summary || (0, import_utils.createEmptySummary)();
1380
607
  const depositAmount = tempOrder.deposit_amount || summary.deposit_amount || "0.00";
1381
- const paidPaymentSummary = this.calculatePaidPaymentSummary(tempOrder.payments || []);
1382
- const amountGap = this.calculateSummaryAmountGap({
1383
- tempOrder,
1384
- summary,
1385
- orderPaidAmount: paidPaymentSummary.gapPaidAmount
1386
- });
608
+ const targetAmount = tempOrder.is_deposit === 1 ? new import_decimal.default(depositAmount || 0) : new import_decimal.default(summary.total_amount || summary.expect_amount || 0);
609
+ const paymentTotal = this.calculatePaymentTotal(tempOrder.payments || []);
610
+ const amountGap = import_decimal.default.max(0, targetAmount.minus(paymentTotal)).toFixed(2);
1387
611
  return {
1388
612
  isDeposit: tempOrder.is_deposit === 1 || depositAmount !== "0.00",
1389
613
  depositAmount,
@@ -1426,9 +650,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1426
650
  this.ensureExternalSaleNumber(tempOrder);
1427
651
  await this.recalculateSummary({ createIfMissing: true });
1428
652
  this.persistTempOrder();
1429
- if (this.draftPersistEnabled) {
1430
- await this.saveDraft();
1431
- }
653
+ await this.saveDraft();
1432
654
  return tempOrder;
1433
655
  }
1434
656
  getOrderProducts() {
@@ -1442,17 +664,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1442
664
  product.metadata = metadata;
1443
665
  return String(uid);
1444
666
  }
1445
- sanitizeOrderProductForTempOrder(product) {
1446
- if (product.metadata && typeof product.metadata === "object") {
1447
- delete product.metadata.origin;
1448
- }
1449
- return product;
1450
- }
1451
- sanitizeTempOrderProducts(tempOrder) {
1452
- tempOrder.products = (tempOrder.products || []).map(
1453
- (product) => this.sanitizeOrderProductForTempOrder(product)
1454
- );
1455
- }
1456
667
  ensureExtend(tempOrder) {
1457
668
  if (!tempOrder._extend || typeof tempOrder._extend !== "object") {
1458
669
  tempOrder._extend = { productsByUid: {} };
@@ -1486,7 +697,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1486
697
  );
1487
698
  productMetadata.unique_identification_number = productUid;
1488
699
  bookingMetadata.unique_identification_number = bookingUid;
1489
- this.syncBookingMetadataHolder(params.booking, bookingMetadata);
1490
700
  return {
1491
701
  productUid,
1492
702
  bookingUid,
@@ -1508,256 +718,44 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1508
718
  }
1509
719
  };
1510
720
  }
1511
- /**
1512
- * booking.holder 是提交真源;metadata.holder 作为详情/回显冗余字段同步保存。
1513
- *
1514
- * @example
1515
- * this.syncBookingMetadataHolder(booking, metadata);
1516
- */
1517
- syncBookingMetadataHolder(booking, metadata) {
1518
- if ((booking == null ? void 0 : booking.holder) !== void 0) {
1519
- metadata.holder = booking.holder;
1520
- }
1521
- }
1522
- /**
1523
- * 从单条 booking 的 holder / metadata 中收集 holder form_record。
1524
- *
1525
- * @example
1526
- * const ids = this.collectBookingHolderRecords(booking);
1527
- */
1528
- collectBookingHolderRecords(booking) {
1529
- var _a;
1530
- const holder = (booking == null ? void 0 : booking.holder) && typeof booking.holder === "object" ? booking.holder : null;
1531
- const source = (holder == null ? void 0 : holder.form_record) ?? ((_a = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a.holder_id);
1532
- const records = Array.isArray(source) ? source : [source];
1533
- return records.filter((record) => record !== void 0 && record !== null && record !== "");
1534
- }
1535
- /**
1536
- * 按 form_record 顺序读取 booking holder 的主字段名称。
1537
- *
1538
- * @example
1539
- * const names = this.collectBookingHolderNames(booking);
1540
- */
1541
- collectBookingHolderNames(booking) {
1542
- const holder = (booking == null ? void 0 : booking.holder) && typeof booking.holder === "object" ? booking.holder : null;
1543
- const rawName = holder == null ? void 0 : holder.name;
1544
- if (Array.isArray(rawName)) {
1545
- return rawName.map((name) => String(name || "").trim());
1546
- }
1547
- if (typeof rawName === "string") {
1548
- return rawName.split(",").map((name) => name.trim());
1549
- }
1550
- return [];
1551
- }
1552
- /**
1553
- * 按老 ticketBooking `formatHolder` 语义汇总订单顶层 holder。
1554
- *
1555
- * @example
1556
- * const holder = this.buildTempOrderHolderFromBookings(tempOrder);
1557
- */
1558
- buildTempOrderHolderFromBookings(tempOrder) {
1559
- var _a, _b;
1560
- const holderRecords = [];
1561
- const holderNames = [];
1562
- let baseHolder = null;
1563
- const seen = /* @__PURE__ */ new Set();
1564
- for (const booking of tempOrder.bookings || []) {
1565
- const holder = (booking == null ? void 0 : booking.holder) && typeof booking.holder === "object" ? booking.holder : null;
1566
- if (!baseHolder && holder) {
1567
- baseHolder = holder;
1568
- }
1569
- const records = this.collectBookingHolderRecords(booking);
1570
- const names = this.collectBookingHolderNames(booking);
1571
- for (const [index, record] of records.entries()) {
1572
- const key = String(record);
1573
- if (seen.has(key))
1574
- continue;
1575
- seen.add(key);
1576
- holderRecords.push(record);
1577
- if (names[index]) {
1578
- holderNames.push(names[index]);
1579
- }
1580
- }
1581
- }
1582
- if (!holderRecords.length) {
1583
- return null;
1584
- }
1585
- const nextHolder = {
1586
- customer_id: (baseHolder == null ? void 0 : baseHolder.customer_id) ?? tempOrder.customer_id,
1587
- form_id: (baseHolder == null ? void 0 : baseHolder.form_id) ?? ((_a = tempOrder.holder) == null ? void 0 : _a.form_id) ?? 0,
1588
- form_record: holderRecords
1589
- };
1590
- if (holderNames.length) {
1591
- nextHolder.name = holderNames.join(",");
1592
- }
1593
- if ((baseHolder == null ? void 0 : baseHolder.is_source_shop) || ((_b = this.otherParams) == null ? void 0 : _b.isFranchisee)) {
1594
- nextHolder.is_source_shop = 1;
1595
- }
1596
- return nextHolder;
1597
- }
1598
- /**
1599
- * 将 booking 级 holder 汇总到 tempOrder 顶层 holder。
1600
- *
1601
- * @example
1602
- * this.syncTempOrderHolderFromBookings(tempOrder);
1603
- */
1604
- syncTempOrderHolderFromBookings(tempOrder) {
1605
- const bookings = tempOrder.bookings || [];
1606
- const hasHolderSource = bookings.some((booking) => {
1607
- var _a;
1608
- return (booking == null ? void 0 : booking.holder) !== void 0 || ((_a = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a.holder_id) !== void 0;
1609
- });
1610
- const nextHolder = this.buildTempOrderHolderFromBookings(tempOrder);
1611
- if (nextHolder || hasHolderSource || bookings.length === 0) {
1612
- tempOrder.holder = nextHolder;
1613
- }
1614
- }
1615
- getBookingUniqueIdentificationNumber(booking) {
1616
- var _a;
1617
- const uid = (_a = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a.unique_identification_number;
1618
- if (uid === void 0 || uid === null || uid === "")
1619
- return null;
1620
- return String(uid);
1621
- }
1622
- findBookingIndexByUniqueIdentificationNumber(tempOrder, uniqueIdentificationNumber) {
1623
- return (tempOrder.bookings || []).findIndex((booking) => {
1624
- return this.getBookingUniqueIdentificationNumber(booking) === uniqueIdentificationNumber;
1625
- });
1626
- }
1627
- removeLinkedBookingsForProduct(tempOrder, product) {
1628
- var _a, _b;
1629
- const productUid = ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.unique_identification_number) || (product == null ? void 0 : product.unique_identification_number);
1630
- const bookingUid = (product == null ? void 0 : product.booking_uid) || ((_b = product == null ? void 0 : product.metadata) == null ? void 0 : _b.booking_uid);
1631
- if (!productUid && !bookingUid)
1632
- return;
1633
- tempOrder.bookings = (tempOrder.bookings || []).filter((booking) => {
1634
- const currentBookingUid = this.getBookingUniqueIdentificationNumber(booking);
1635
- if (bookingUid && currentBookingUid === String(bookingUid))
1636
- return false;
1637
- if (productUid && String((booking == null ? void 0 : booking.product_uid) || "") === String(productUid))
1638
- return false;
1639
- return true;
1640
- });
1641
- }
1642
721
  // ─── TempOrder: 金额汇总 ───
1643
722
  getSalesSummary() {
1644
723
  if (!this.salesSummaryModuleName)
1645
724
  return null;
1646
725
  return this.core.getModule(this.salesSummaryModuleName);
1647
726
  }
1648
- applyOrderProductsDepositSummary(tempOrder, summary) {
1649
- var _a;
1650
- const depositSummary = (0, import_utils.calculateOrderProductsDeposit)(tempOrder.products || [], {
1651
- productsByUid: (_a = tempOrder._extend) == null ? void 0 : _a.productsByUid
1652
- });
1653
- const nextSummary = {
1654
- ...summary,
1655
- deposit_amount: depositSummary.totalText,
1656
- deposit: depositSummary.hasDeposit ? {
1657
- total: depositSummary.totalText,
1658
- deposit_policy_ids: depositSummary.deposit_policy_ids,
1659
- deposit_policy_data: depositSummary.protocols,
1660
- hasDeposit: true
1661
- } : void 0
1662
- };
1663
- tempOrder.deposit_amount = depositSummary.totalText;
1664
- tempOrder.is_deposit = depositSummary.hasDeposit ? 1 : 0;
1665
- return nextSummary;
1666
- }
1667
727
  async recalculateSummary(options) {
1668
728
  const tempOrder = (options == null ? void 0 : options.createIfMissing) ? this.ensureTempOrder() : this.store.tempOrder;
1669
729
  if (!tempOrder)
1670
730
  return null;
1671
- this.sanitizeTempOrderProducts(tempOrder);
1672
- const snapshotSummary = this.restoreOriginalSnapshotIfProductsUnchanged(tempOrder);
1673
- if (snapshotSummary)
1674
- return snapshotSummary;
1675
- const shouldFullRecalculateFromSnapshot = Boolean(this.getOriginalSalesSnapshot(tempOrder));
1676
- const summaryProducts = shouldFullRecalculateFromSnapshot ? (0, import_lodash_es.cloneDeep)(tempOrder.products || []) : tempOrder.products;
1677
- if (shouldFullRecalculateFromSnapshot) {
1678
- this.clearPersistedAmountFieldsForFullRecalc(summaryProducts || []);
1679
- }
1680
731
  const salesSummary = this.getSalesSummary();
1681
732
  const existedSummary = this.store.summary || (0, import_utils.createEmptySummary)();
1682
- const totalRefundAmount = existedSummary.total_refund_amount || "0.00";
1683
733
  const paidPaymentSummary = this.calculatePaidPaymentSummary(
1684
734
  tempOrder.payments || []
1685
735
  );
1686
736
  if (!salesSummary) {
1687
- const emptyBaseSummary = {
737
+ const emptySummary = {
1688
738
  ...(0, import_utils.createEmptySummary)(),
1689
- ...existedSummary,
1690
- total_refund_amount: totalRefundAmount
1691
- };
1692
- const emptySummaryBase = {
1693
- ...emptyBaseSummary,
739
+ total_refund_amount: existedSummary.total_refund_amount || "0.00",
1694
740
  customer_paid_amount: paidPaymentSummary.customerPaidAmount.toFixed(2),
1695
741
  order_paid_amount: paidPaymentSummary.orderPaidAmount.toFixed(2),
1696
- pay_service_charge_amount: paidPaymentSummary.payServiceChargeAmount.toFixed(2),
1697
- rounding_amount: paidPaymentSummary.roundingAmount.toFixed(2)
1698
- };
1699
- const emptySummaryWithDeposit = this.applyOrderProductsDepositSummary(
1700
- tempOrder,
1701
- emptySummaryBase
1702
- );
1703
- const emptySummary = {
1704
- ...emptySummaryWithDeposit,
1705
- amount_gap: this.calculateSummaryAmountGap({
1706
- tempOrder,
1707
- summary: emptySummaryWithDeposit,
1708
- orderPaidAmount: paidPaymentSummary.gapPaidAmount
1709
- })
742
+ pay_service_charge_amount: paidPaymentSummary.payServiceChargeAmount.toFixed(2)
1710
743
  };
1711
- tempOrder.surcharge_fee = emptySummary.surcharge_fee;
1712
744
  this.store.summary = emptySummary;
1713
- this.updateTempOrderPaymentStatus(tempOrder, {
1714
- previousSummary: existedSummary,
1715
- summary: emptySummary
1716
- });
745
+ tempOrder.surcharge_fee = emptySummary.surcharge_fee;
1717
746
  return this.store.summary;
1718
747
  }
1719
748
  const salesSummaryResult = await salesSummary.getSummary({
1720
- products: summaryProducts,
749
+ products: tempOrder.products,
1721
750
  isPriceIncludeTax: tempOrder.is_price_include_tax,
1722
751
  shopDiscount: tempOrder.shop_discount
1723
752
  });
1724
- if (shouldFullRecalculateFromSnapshot) {
1725
- tempOrder.products = summaryProducts;
1726
- }
1727
- this.syncSummaryProductMetadata(tempOrder.products || []);
1728
- const roundingAmount = paidPaymentSummary.roundingAmount;
1729
- const payServiceChargeAmount = paidPaymentSummary.payServiceChargeAmount;
1730
- const hasSalesSummaryAmount = salesSummaryResult.expect_amount !== void 0 || salesSummaryResult.total_amount !== void 0;
1731
- const expectAmount = hasSalesSummaryAmount ? new import_decimal.default(salesSummaryResult.expect_amount ?? salesSummaryResult.total_amount ?? 0) : null;
1732
- const amountPaymentPatch = hasSalesSummaryAmount || !roundingAmount.eq(0) || !payServiceChargeAmount.eq(0) ? {
1733
- rounding_amount: roundingAmount.toFixed(2),
1734
- ...expectAmount ? {
1735
- total_amount: import_decimal.default.max(
1736
- 0,
1737
- expectAmount.plus(roundingAmount).plus(payServiceChargeAmount)
1738
- ).toFixed(2)
1739
- } : {}
1740
- } : {};
1741
- const normalizedExpectAmountPatch = expectAmount && salesSummaryResult.expect_amount === void 0 ? { expect_amount: expectAmount.toFixed(2) } : {};
1742
- const summaryForGap = this.applyOrderProductsDepositSummary(tempOrder, {
1743
- ...salesSummaryResult,
1744
- total_refund_amount: totalRefundAmount,
1745
- ...amountPaymentPatch,
1746
- ...normalizedExpectAmountPatch
1747
- });
1748
753
  const summary = {
1749
- ...summaryForGap,
1750
- total_refund_amount: totalRefundAmount,
754
+ ...salesSummaryResult,
755
+ total_refund_amount: existedSummary.total_refund_amount || "0.00",
1751
756
  customer_paid_amount: paidPaymentSummary.customerPaidAmount.toFixed(2),
1752
757
  order_paid_amount: paidPaymentSummary.orderPaidAmount.toFixed(2),
1753
- ...amountPaymentPatch,
1754
- ...normalizedExpectAmountPatch,
1755
- amount_gap: this.calculateSummaryAmountGap({
1756
- tempOrder,
1757
- summary: summaryForGap,
1758
- orderPaidAmount: paidPaymentSummary.gapPaidAmount
1759
- }),
1760
- pay_service_charge_amount: payServiceChargeAmount.toFixed(2)
758
+ pay_service_charge_amount: paidPaymentSummary.payServiceChargeAmount.toFixed(2)
1761
759
  };
1762
760
  this.store.summary = summary;
1763
761
  if (summary.is_price_include_tax !== void 0) {
@@ -1768,10 +766,8 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1768
766
  }
1769
767
  tempOrder.surcharge_fee = summary.surcharge_fee;
1770
768
  tempOrder.surcharges = summary.surcharges || [];
1771
- this.updateTempOrderPaymentStatus(tempOrder, {
1772
- previousSummary: existedSummary,
1773
- summary
1774
- });
769
+ tempOrder.deposit_amount = summary.deposit_amount || "0.00";
770
+ tempOrder.is_deposit = summary.deposit_amount !== "0.00" ? 1 : 0;
1775
771
  return this.store.summary;
1776
772
  }
1777
773
  async getOrderSummary() {
@@ -1781,22 +777,13 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1781
777
  this.persistTempOrder();
1782
778
  return summary;
1783
779
  }
1784
- updateTempOrderNote(note, sync = false) {
780
+ // ─── TempOrder: 备注 ───
781
+ updateTempOrderNote(note) {
1785
782
  const tempOrder = this.ensureTempOrder();
1786
783
  tempOrder.note = String(note || "");
1787
784
  this.persistTempOrder();
1788
- if (sync) {
1789
- const orderId = tempOrder.order_id;
1790
- if (!orderId)
1791
- return tempOrder.note;
1792
- return this.syncTempOrderNoteToRemote(orderId, tempOrder.note);
1793
- }
1794
785
  return tempOrder.note;
1795
786
  }
1796
- async syncTempOrderNoteToRemote(orderId, note) {
1797
- await this.request.put(`/order/order/${orderId}/note`, { note });
1798
- return note;
1799
- }
1800
787
  getTempOrderNote() {
1801
788
  var _a;
1802
789
  return ((_a = this.store.tempOrder) == null ? void 0 : _a.note) || "";
@@ -1820,77 +807,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1820
807
  this.persistTempOrder();
1821
808
  return tempOrder.contacts_info;
1822
809
  }
1823
- buildTempOrderCustomer(params) {
1824
- if (!params.customerId)
1825
- return null;
1826
- const source = params.source ? (0, import_lodash_es.cloneDeep)(params.source) : {};
1827
- const name = source.name ?? source.display_name ?? source.customerName ?? source.customer_name ?? params.customerName;
1828
- const customerName = source.customer_name ?? source.customerName ?? source.display_name ?? source.name ?? params.customerName;
1829
- return {
1830
- ...source,
1831
- id: source.id ?? params.customerId,
1832
- customer_id: source.customer_id ?? params.customerId,
1833
- name: String(name || ""),
1834
- customer_name: String(customerName || ""),
1835
- country_calling_code: String(
1836
- source.country_calling_code ?? source.countryCallingCode ?? params.countryCallingCode
1837
- ),
1838
- phone: String(source.phone ?? params.phone),
1839
- email: String(source.email ?? params.email)
1840
- };
1841
- }
1842
- isCustomerBoundDiscount(discount) {
1843
- const type = (discount == null ? void 0 : discount.type) ?? (discount == null ? void 0 : discount.tag);
1844
- return type === "good_pass" || type === "discount_card" || type === "product_discount_card";
1845
- }
1846
- clearCustomerBoundDiscounts(tempOrder) {
1847
- var _a, _b, _c, _d;
1848
- const filterDiscountList = (discountList) => {
1849
- if (!Array.isArray(discountList))
1850
- return [];
1851
- return discountList.filter((discount) => !this.isCustomerBoundDiscount(discount));
1852
- };
1853
- tempOrder.products = (tempOrder.products || []).map((product) => {
1854
- const nextProduct = {
1855
- ...product,
1856
- discount_list: filterDiscountList(product.discount_list)
1857
- };
1858
- if (Array.isArray(nextProduct.product_bundle)) {
1859
- nextProduct.product_bundle = nextProduct.product_bundle.map((bundle) => ({
1860
- ...bundle,
1861
- discount_list: filterDiscountList(bundle.discount_list)
1862
- }));
1863
- }
1864
- return nextProduct;
1865
- });
1866
- delete tempOrder.discount_list;
1867
- const discountModule = this.store.discount;
1868
- if (!discountModule)
1869
- return;
1870
- const currentDiscounts = ((_a = discountModule.getDiscountList) == null ? void 0 : _a.call(discountModule)) || [];
1871
- const currentOriginalDiscounts = ((_b = discountModule.getOriginalDiscountList) == null ? void 0 : _b.call(discountModule)) || [];
1872
- const nextDiscounts = currentDiscounts.filter((discount) => {
1873
- if (discount == null ? void 0 : discount.isEditMode)
1874
- return true;
1875
- return !this.isCustomerBoundDiscount(discount);
1876
- });
1877
- const nextOriginalDiscounts = currentOriginalDiscounts.filter((discount) => {
1878
- if (discount == null ? void 0 : discount.isEditMode)
1879
- return true;
1880
- return !this.isCustomerBoundDiscount(discount);
1881
- });
1882
- void ((_c = discountModule.setDiscountList) == null ? void 0 : _c.call(discountModule, nextDiscounts));
1883
- void ((_d = discountModule.setOriginalDiscountList) == null ? void 0 : _d.call(discountModule, nextOriginalDiscounts));
1884
- }
1885
810
  /**
1886
811
  * 更新当前 tempOrder 的客户协议字段。
1887
812
  *
1888
- * PaymentModal 只需要修改订单里的客户事实;如果外部还有客户模块需要同步,
813
+ * PaymentModal 只需要修改订单里的客户字段;如果外部还有客户模块需要同步,
1889
814
  * 应由调用方通过回调处理,不能把外部 UI 状态写进 tempOrder。
1890
815
  */
1891
816
  updateTempOrderCustomer(customer) {
1892
817
  const tempOrder = this.ensureTempOrder();
1893
- const previousCustomerId = tempOrder.customer_id ?? null;
1894
818
  const customerId = customer.customer_id ?? customer.customerId ?? customer.id ?? null;
1895
819
  const customerName = customer.customer_name ?? customer.customerName ?? customer.display_name ?? customer.name ?? "";
1896
820
  tempOrder.customer_id = customerId === null || customerId === void 0 || customerId === "" ? null : Number(customerId);
@@ -1900,15 +824,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1900
824
  );
1901
825
  tempOrder.phone = String(customer.phone || "");
1902
826
  tempOrder.email = String(customer.email || "");
1903
- tempOrder.customer = this.buildTempOrderCustomer({
1904
- source: customer,
1905
- customerId: tempOrder.customer_id,
1906
- customerName: tempOrder.customer_name,
1907
- countryCallingCode: tempOrder.country_calling_code,
1908
- phone: tempOrder.phone,
1909
- email: tempOrder.email
1910
- });
1911
- const nextCustomerId = tempOrder.customer_id ?? null;
1912
827
  this.persistTempOrder();
1913
828
  return {
1914
829
  customerId: tempOrder.customer_id,
@@ -1923,20 +838,11 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1923
838
  return;
1924
839
  }
1925
840
  const tempOrder = this.ensureTempOrder();
1926
- const previousCustomerId = tempOrder.customer_id ?? null;
1927
841
  tempOrder.customer_id = patch.customer_id || patch.id || null;
1928
842
  tempOrder.customer_name = String(patch.customer_name || "");
1929
843
  tempOrder.country_calling_code = String(patch.country_calling_code || "");
1930
844
  tempOrder.phone = String(patch.phone || "");
1931
845
  tempOrder.email = String(patch.email || "");
1932
- tempOrder.customer = this.buildTempOrderCustomer({
1933
- source: snapshot || null,
1934
- customerId: tempOrder.customer_id,
1935
- customerName: tempOrder.customer_name,
1936
- countryCallingCode: tempOrder.country_calling_code,
1937
- phone: tempOrder.phone,
1938
- email: tempOrder.email
1939
- });
1940
846
  if (snapshot !== void 0) {
1941
847
  const extend = this.ensureExtend(tempOrder);
1942
848
  if (snapshot === null)
@@ -1944,20 +850,12 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1944
850
  else
1945
851
  extend.customerSnapshot = (0, import_lodash_es.cloneDeep)(snapshot);
1946
852
  }
1947
- const nextCustomerId = tempOrder.customer_id ?? null;
1948
- if (String(previousCustomerId ?? "") !== String(nextCustomerId ?? "")) {
1949
- (0, import_utils.clearTempOrderHolderAssignments)(tempOrder);
1950
- this.clearCustomerBoundDiscounts(tempOrder);
1951
- }
1952
853
  this.persistTempOrder();
1953
- this.saveDraftInBackground();
1954
- if (String(previousCustomerId ?? "") !== String(nextCustomerId ?? "")) {
1955
- this.emitOrderCustomerChange();
1956
- }
854
+ this.emitOrderCustomerChange();
1957
855
  }
1958
856
  getOrderCustomer() {
1959
857
  const tempOrder = this.store.tempOrder;
1960
- if (!tempOrder || !tempOrder.customer_id) {
858
+ if (!tempOrder || tempOrder.customer_id === null || tempOrder.customer_id === void 0) {
1961
859
  return null;
1962
860
  }
1963
861
  return {
@@ -1975,18 +873,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
1975
873
  }
1976
874
  clearOrderCustomer() {
1977
875
  const tempOrder = this.ensureTempOrder();
1978
- (0, import_utils.clearTempOrderHolderAssignments)(tempOrder);
1979
876
  tempOrder.customer_id = null;
1980
877
  tempOrder.customer_name = "";
1981
878
  tempOrder.country_calling_code = "";
1982
879
  tempOrder.phone = "";
1983
880
  tempOrder.email = "";
1984
- tempOrder.customer = null;
1985
881
  if (tempOrder._extend)
1986
882
  delete tempOrder._extend.customerSnapshot;
1987
- this.clearCustomerBoundDiscounts(tempOrder);
1988
883
  this.persistTempOrder();
1989
- this.saveDraftInBackground();
1990
884
  this.core.effects.emit(import_types.OrderHooks.OnOrderCustomerChange, null);
1991
885
  }
1992
886
  emitOrderCustomerChange() {
@@ -2026,20 +920,10 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2026
920
  }
2027
921
  /** 追加单个支付项,并立即持久化当前 tempOrder。 */
2028
922
  addOrderPayment(payment) {
2029
- this.logInfo("addOrderPayment", {
2030
- payment
2031
- });
2032
923
  const tempOrder = this.ensureTempOrder();
2033
- const mapped = (0, import_utils.mapPaymentItemsToOrderPayments)([
2034
- this.normalizePaymentSource(payment, { defaultPaid: true })
2035
- ]);
924
+ const mapped = (0, import_utils.mapPaymentItemsToOrderPayments)([payment]);
2036
925
  tempOrder.payments = [...tempOrder.payments || [], ...mapped];
2037
926
  this.persistTempOrder();
2038
- void this.recalculateSummary({ createIfMissing: true }).catch((error) => {
2039
- this.logError("recalculate summary after addOrderPayment failed", {
2040
- error: error instanceof Error ? error.message : String(error)
2041
- });
2042
- });
2043
927
  return tempOrder.payments;
2044
928
  }
2045
929
  /**
@@ -2105,48 +989,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2105
989
  */
2106
990
  updateVoucherOrderPayments(payments) {
2107
991
  const tempOrder = this.ensureTempOrder();
2108
- const isVoucherPayment = (payment) => {
2109
- return payment.voucher_id !== void 0 && Number(payment.voucher_id) !== 0;
2110
- };
2111
- const hasSyncedOrderPayment = (payment) => {
2112
- return payment.order_payment_id !== void 0 && payment.order_payment_id !== null;
2113
- };
2114
- const mappedVouchers = (0, import_utils.mapPaymentItemsToOrderPayments)(
2115
- payments.map(
2116
- (payment) => this.normalizePaymentSource(payment, { defaultPaid: true })
2117
- )
2118
- ).filter((payment) => {
2119
- return isVoucherPayment(payment);
2120
- });
2121
- const nonVoucherPayments = (tempOrder.payments || []).filter((payment) => {
2122
- return !isVoucherPayment(payment);
2123
- });
2124
- const syncedVoucherPayments = (tempOrder.payments || []).filter((payment) => {
2125
- return isVoucherPayment(payment) && hasSyncedOrderPayment(payment);
2126
- });
2127
- const syncedVoucherPaymentIds = new Set(
2128
- syncedVoucherPayments.map((payment) => String(payment.order_payment_id))
992
+ const mappedVouchers = (0, import_utils.mapPaymentItemsToOrderPayments)(payments).filter(
993
+ (payment) => payment.voucher_id !== void 0 && Number(payment.voucher_id) !== 0
2129
994
  );
2130
- const replaceableVouchers = mappedVouchers.filter((payment) => {
2131
- if (!hasSyncedOrderPayment(payment))
2132
- return true;
2133
- return !syncedVoucherPaymentIds.has(String(payment.order_payment_id));
2134
- });
2135
- const cappedVouchers = this.capVoucherPaymentsByRemainingAmount({
2136
- vouchers: replaceableVouchers,
2137
- nonVoucherPayments: [
2138
- ...nonVoucherPayments,
2139
- ...syncedVoucherPayments
2140
- ]
995
+ const nonVoucherPayments = (tempOrder.payments || []).filter((payment) => {
996
+ return payment.voucher_id === void 0 || Number(payment.voucher_id) === 0;
2141
997
  });
2142
- tempOrder.payments = [...nonVoucherPayments, ...syncedVoucherPayments, ...cappedVouchers];
2143
- this.updateTempOrderPaymentStatus(tempOrder);
998
+ tempOrder.payments = [...nonVoucherPayments, ...mappedVouchers];
2144
999
  this.persistTempOrder();
2145
- void this.recalculateSummary({ createIfMissing: true }).catch((error) => {
2146
- this.logError("recalculate summary after updateVoucherOrderPayments failed", {
2147
- error: error instanceof Error ? error.message : String(error)
2148
- });
2149
- });
2150
1000
  return tempOrder.payments;
2151
1001
  }
2152
1002
  async shouldMergeProductToOrder(params) {
@@ -2156,107 +1006,46 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2156
1006
  return true;
2157
1007
  const result = await onBeforeMergeProductToOrder({
2158
1008
  ...params,
2159
- defaultShouldMerge: true
2160
- });
2161
- if (typeof result === "boolean")
2162
- return result;
2163
- if (result && typeof result === "object" && typeof result.shouldMerge === "boolean") {
2164
- return result.shouldMerge;
2165
- }
2166
- return true;
2167
- }
2168
- hasOrderProductLineNote(product) {
2169
- return typeof (product == null ? void 0 : product.note) === "string" && product.note.trim().length > 0;
2170
- }
2171
- /**
2172
- * 判断商品行是否显式绑定了 booking。
2173
- *
2174
- * @example
2175
- * this.hasLinkedBookingUid({ metadata: { booking_uid: 'booking-1' } });
2176
- */
2177
- hasLinkedBookingUid(product) {
2178
- var _a;
2179
- const bookingUid = (product == null ? void 0 : product.booking_uid) ?? ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.booking_uid);
2180
- return bookingUid !== void 0 && bookingUid !== null && String(bookingUid) !== "";
2181
- }
2182
- // ─── TempOrder: 商品 CRUD ───
2183
- /**
2184
- * 预约商品加车后的统一收尾:促销、折扣、summary 重算与持久化(批量拆行时只调用一次)。
2185
- *
2186
- * @example
2187
- * await this.finalizeProductOrderMutation(tempOrder);
2188
- */
2189
- async finalizeProductOrderMutation(tempOrder, options) {
2190
- this.syncTempOrderHolderFromBookings(tempOrder);
2191
- if (!(options == null ? void 0 : options.skipEditDiscountConfigRefresh)) {
2192
- await this.ensureEditDiscountConfigForProductChange(tempOrder);
2193
- }
2194
- if (!(options == null ? void 0 : options.skipDiscountRecalculation)) {
2195
- await this.applyPromotion();
2196
- }
2197
- if (!(options == null ? void 0 : options.skipDiscountRecalculation)) {
2198
- this.applyDiscount();
1009
+ defaultShouldMerge: true
1010
+ });
1011
+ if (typeof result === "boolean")
1012
+ return result;
1013
+ if (result && typeof result === "object" && typeof result.shouldMerge === "boolean") {
1014
+ return result.shouldMerge;
2199
1015
  }
2200
- this.sanitizeTempOrderProducts(tempOrder);
2201
- await this.recalculateSummary({ createIfMissing: true });
2202
- this.persistTempOrder();
1016
+ return true;
2203
1017
  }
2204
- /**
2205
- * tempOrder 追加一条商品行(及可选 booking),不触发 summary 重算。
2206
- * 带 booking 且 num>1 时由 `addProductToOrder` 拆成多次本方法调用(每次 num=1)。
2207
- *
2208
- * @example
2209
- * await this.appendProductLineToTempOrder(tempOrder, { product_id: 1, num: 1 }, booking);
2210
- */
2211
- async appendProductLineToTempOrder(tempOrder, product, booking) {
2212
- var _a, _b;
1018
+ // ─── TempOrder: 商品 CRUD ───
1019
+ async addProductToOrder(product, booking) {
1020
+ var _a;
1021
+ const tempOrder = this.ensureTempOrder();
2213
1022
  const linked = booking ? this.createLinkedProductAndBooking({ product, booking }) : null;
2214
1023
  const productToAdd = (linked == null ? void 0 : linked.product) || product;
2215
1024
  const incomingFingerprint = (0, import_utils3.buildProductLineFingerprint)(
2216
- (0, import_utils.getProductSkuOptions)(productToAdd),
1025
+ productToAdd.product_option_item,
2217
1026
  productToAdd.product_bundle
2218
1027
  );
2219
- const normalizedIncoming = (0, import_utils.mergeOrderProductDisplayFields)(
2220
- productToAdd,
2221
- (0, import_utils3.normalizeOrderProduct)(productToAdd)
2222
- );
2223
- const incomingBookingUid = productToAdd.booking_uid ?? ((_a = productToAdd.metadata) == null ? void 0 : _a.booking_uid);
2224
- if (incomingBookingUid !== void 0 && incomingBookingUid !== null && String(incomingBookingUid) !== "") {
2225
- normalizedIncoming.booking_uid = String(incomingBookingUid);
2226
- normalizedIncoming.metadata = {
2227
- ...normalizedIncoming.metadata || {},
2228
- booking_uid: String(incomingBookingUid)
2229
- };
2230
- }
2231
- normalizedIncoming.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
2232
- normalizedIncoming.discount_list
2233
- );
1028
+ const normalizedIncoming = (0, import_utils3.normalizeOrderProduct)(productToAdd);
2234
1029
  const hasIncomingGoodPass = this.hasGoodPassDiscount(
2235
1030
  normalizedIncoming
2236
1031
  );
2237
- const hasIncomingProductNote = this.hasOrderProductLineNote(normalizedIncoming);
2238
- const hasIncomingBookingUid = this.hasLinkedBookingUid(productToAdd) || this.hasLinkedBookingUid(normalizedIncoming);
2239
- const shouldForceNewLine = !!booking || hasIncomingProductNote || hasIncomingBookingUid;
1032
+ const shouldForceNewLine = !!booking;
2240
1033
  const matchedIndex = hasIncomingGoodPass || shouldForceNewLine ? -1 : tempOrder.products.findIndex((item) => {
2241
1034
  if (this.hasGoodPassDiscount(item))
2242
1035
  return false;
2243
- if (this.hasOrderProductLineNote(item))
2244
- return false;
2245
- if (item.order_detail_id !== void 0 && item.order_detail_id !== null)
2246
- return false;
2247
1036
  if (item.product_id !== productToAdd.product_id)
2248
1037
  return false;
2249
1038
  if (item.product_variant_id !== productToAdd.product_variant_id)
2250
1039
  return false;
2251
1040
  const existedFingerprint2 = (0, import_utils3.buildProductLineFingerprint)(
2252
- (0, import_utils.getProductSkuOptions)(item),
1041
+ item.product_option_item,
2253
1042
  item.product_bundle
2254
1043
  );
2255
1044
  return existedFingerprint2 === incomingFingerprint;
2256
1045
  });
2257
1046
  const matchedProduct = matchedIndex === -1 ? null : tempOrder.products[matchedIndex];
2258
1047
  const existedFingerprint = matchedProduct ? (0, import_utils3.buildProductLineFingerprint)(
2259
- (0, import_utils.getProductSkuOptions)(matchedProduct),
1048
+ matchedProduct.product_option_item,
2260
1049
  matchedProduct.product_bundle
2261
1050
  ) : "";
2262
1051
  const shouldMerge = matchedProduct ? await this.shouldMergeProductToOrder({
@@ -2282,58 +1071,28 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2282
1071
  booking_uid: linked.bookingUid
2283
1072
  };
2284
1073
  }
2285
- tempOrder.products = [...tempOrder.products, normalizedIncoming];
1074
+ tempOrder.products.push(normalizedIncoming);
2286
1075
  } else {
2287
1076
  const targetProduct = matchedProduct;
2288
- const targetUid = (_b = targetProduct.metadata) == null ? void 0 : _b.unique_identification_number;
2289
- const normalizedProduct = (0, import_utils.mergeOrderProductDisplayFields)(
2290
- targetProduct,
2291
- (0, import_utils3.normalizeOrderProduct)({
2292
- ...productToAdd,
2293
- metadata: {
2294
- ...productToAdd.metadata || {},
2295
- unique_identification_number: targetUid
2296
- }
2297
- })
2298
- );
2299
- normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
2300
- normalizedProduct.discount_list
2301
- );
2302
- const nextNum = (0, import_utils3.getSafeProductNum)(targetProduct.num + normalizedProduct.num);
2303
- const targetIsManualProductDiscount = isManualProductDiscountProduct(targetProduct);
2304
- const nextDiscountList = targetIsManualProductDiscount ? (0, import_utils.normalizeOrderProductDiscountList)(
2305
- (0, import_manualProductDiscount.syncManualProductDiscountProductNum)(
2306
- targetProduct.discount_list,
2307
- nextNum
2308
- )
2309
- ) : normalizedProduct.discount_list;
1077
+ const targetUid = (_a = targetProduct.metadata) == null ? void 0 : _a.unique_identification_number;
1078
+ const normalizedProduct = (0, import_utils3.normalizeOrderProduct)({
1079
+ ...productToAdd,
1080
+ metadata: {
1081
+ ...productToAdd.metadata || {},
1082
+ unique_identification_number: targetUid
1083
+ }
1084
+ });
2310
1085
  tempOrder.products[matchedIndex] = {
2311
1086
  ...targetProduct,
2312
1087
  ...normalizedProduct,
2313
- discount_list: nextDiscountList,
2314
1088
  metadata: {
2315
1089
  ...targetProduct.metadata || {},
2316
1090
  ...normalizedProduct.metadata || {},
2317
1091
  unique_identification_number: targetUid
2318
1092
  },
2319
- product_sku: {
2320
- ...targetProduct.product_sku || { option: [] },
2321
- ...normalizedProduct.product_sku || { option: [] },
2322
- option: (0, import_utils.getProductSkuOptions)(normalizedProduct)
2323
- },
2324
- ...targetIsManualProductDiscount ? {
2325
- selling_price: targetProduct.selling_price,
2326
- original_price: targetProduct.original_price,
2327
- payment_price: targetProduct.payment_price,
2328
- metadata: {
2329
- ...normalizedProduct.metadata || {},
2330
- ...targetProduct.metadata || {},
2331
- unique_identification_number: targetUid
2332
- }
2333
- } : {},
2334
1093
  note: targetProduct.note,
2335
1094
  order_detail_id: targetProduct.order_detail_id,
2336
- num: nextNum
1095
+ num: (0, import_utils3.getSafeProductNum)(targetProduct.num + normalizedProduct.num)
2337
1096
  };
2338
1097
  this.captureProductRuntime(
2339
1098
  tempOrder,
@@ -2345,79 +1104,9 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2345
1104
  if (linked) {
2346
1105
  tempOrder.bookings = [...tempOrder.bookings || [], linked.booking];
2347
1106
  }
2348
- }
2349
- /**
2350
- * 添加商品行。带 booking 时强制独立行;num>1 时拆成多条 num=1 的 product+booking(对齐 BookingByStep / ticketBooking addService)。
2351
- *
2352
- * @example
2353
- * await order.addProductToOrder({ product_id: 1, num: 3 }, { start_time: '10:00' });
2354
- * // → tempOrder.products 新增 3 行,每行 num=1,bookings 3 条
2355
- */
2356
- async addProductToOrder(product, booking) {
2357
- const tempOrder = this.ensureTempOrder();
2358
- if (booking) {
2359
- const productRecord = product;
2360
- const splitCount = (0, import_utils3.getSafeProductNum)(
2361
- productRecord.num ?? productRecord.product_quantity ?? 1
2362
- );
2363
- if (splitCount > 1) {
2364
- for (let i = 0; i < splitCount; i += 1) {
2365
- const singleLine = (0, import_lodash_es.cloneDeep)(productRecord);
2366
- singleLine.num = 1;
2367
- delete singleLine.product_quantity;
2368
- await this.appendProductLineToTempOrder(
2369
- tempOrder,
2370
- singleLine,
2371
- (0, import_lodash_es.cloneDeep)(booking)
2372
- );
2373
- }
2374
- await this.finalizeProductOrderMutation(tempOrder);
2375
- return tempOrder.products;
2376
- }
2377
- }
2378
- await this.appendProductLineToTempOrder(tempOrder, product, booking);
2379
- await this.finalizeProductOrderMutation(tempOrder);
2380
- return tempOrder.products;
2381
- }
2382
- /**
2383
- * 批量添加商品行,所有行追加完成后只触发一次促销、折扣、summary 重算与持久化。
2384
- *
2385
- * @example
2386
- * await order.addProductsToOrder([
2387
- * { product: { product_id: 1, product_variant_id: 0, num: 1 } },
2388
- * { product: { product_id: 2, product_variant_id: 0, num: 1 } },
2389
- * ]);
2390
- */
2391
- async addProductsToOrder(items, options) {
2392
- const tempOrder = this.ensureTempOrder();
2393
- if (!Array.isArray(items) || items.length === 0)
2394
- return tempOrder.products;
2395
- for (const item of items || []) {
2396
- const { product, booking } = item;
2397
- if (!product)
2398
- continue;
2399
- if (booking) {
2400
- const productRecord = product;
2401
- const splitCount = (0, import_utils3.getSafeProductNum)(
2402
- productRecord.num ?? productRecord.product_quantity ?? 1
2403
- );
2404
- if (splitCount > 1) {
2405
- for (let i = 0; i < splitCount; i += 1) {
2406
- const singleLine = (0, import_lodash_es.cloneDeep)(productRecord);
2407
- singleLine.num = 1;
2408
- delete singleLine.product_quantity;
2409
- await this.appendProductLineToTempOrder(
2410
- tempOrder,
2411
- singleLine,
2412
- (0, import_lodash_es.cloneDeep)(booking)
2413
- );
2414
- }
2415
- continue;
2416
- }
2417
- }
2418
- await this.appendProductLineToTempOrder(tempOrder, product, booking);
2419
- }
2420
- await this.finalizeProductOrderMutation(tempOrder, options);
1107
+ this.applyDiscount();
1108
+ await this.recalculateSummary({ createIfMissing: true });
1109
+ this.persistTempOrder();
2421
1110
  return tempOrder.products;
2422
1111
  }
2423
1112
  hasGoodPassDiscount(product) {
@@ -2438,55 +1127,15 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2438
1127
  (item) => (item == null ? void 0 : item.type) === "good_pass" || (item == null ? void 0 : item.tag) === "good_pass"
2439
1128
  );
2440
1129
  }
2441
- getBundleRuntimeIdentity(bundle) {
2442
- if (!bundle || typeof bundle !== "object")
2443
- return "";
2444
- return [
2445
- bundle.bundle_id ?? bundle.id ?? "",
2446
- bundle.bundle_group_id ?? bundle.group_id ?? "",
2447
- bundle.bundle_product_id ?? bundle._bundle_product_id ?? bundle.product_id ?? "",
2448
- bundle.bundle_variant_id ?? bundle.product_variant_id ?? 0
2449
- ].join("|");
2450
- }
2451
- preservePersistedBundlePriceFields(previousBundles, nextBundles) {
2452
- if (!Array.isArray(nextBundles))
2453
- return nextBundles;
2454
- if (!Array.isArray(previousBundles) || previousBundles.length === 0)
2455
- return nextBundles;
2456
- const previousByIdentity = /* @__PURE__ */ new Map();
2457
- previousBundles.forEach((bundle) => {
2458
- const identity = this.getBundleRuntimeIdentity(bundle);
2459
- if (identity)
2460
- previousByIdentity.set(identity, bundle);
2461
- });
2462
- return nextBundles.map((bundle, index) => {
2463
- if (!bundle || typeof bundle !== "object")
2464
- return bundle;
2465
- const previous = previousByIdentity.get(this.getBundleRuntimeIdentity(bundle)) || previousBundles[index];
2466
- if (!previous || typeof previous !== "object")
2467
- return bundle;
2468
- return {
2469
- ...bundle,
2470
- price: previous.price,
2471
- custom_price: previous.custom_price,
2472
- bundle_payment_price: previous.bundle_payment_price,
2473
- bundle_selling_price: previous.bundle_selling_price,
2474
- original_price: previous.original_price,
2475
- product_price: previous.product_price
2476
- };
2477
- });
2478
- }
2479
- async updateOrderProduct(params) {
2480
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
1130
+ async updateProductInOrder(params) {
1131
+ var _a, _b, _c, _d, _e;
2481
1132
  const {
2482
1133
  product_id,
2483
1134
  product_variant_id,
2484
1135
  updates,
2485
1136
  unique_identification_number,
2486
- identity_key,
2487
- product_sku,
2488
- product_bundle,
2489
- booking
1137
+ product_option_item,
1138
+ product_bundle
2490
1139
  } = params;
2491
1140
  const tempOrder = this.ensureTempOrder();
2492
1141
  const identityLookup = {
@@ -2495,30 +1144,12 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2495
1144
  };
2496
1145
  if (unique_identification_number !== void 0) {
2497
1146
  identityLookup.unique_identification_number = unique_identification_number;
2498
- if (identity_key === void 0) {
2499
- identityLookup.identity_key = unique_identification_number;
2500
- }
2501
1147
  }
2502
- if (identity_key !== void 0) {
2503
- identityLookup.identity_key = identity_key;
2504
- }
2505
- if (product_sku !== void 0)
2506
- identityLookup.product_sku = product_sku;
1148
+ if (product_option_item !== void 0)
1149
+ identityLookup.product_option_item = product_option_item;
2507
1150
  if (product_bundle !== void 0)
2508
1151
  identityLookup.product_bundle = product_bundle;
2509
- let productIndex = -1;
2510
- if (unique_identification_number !== void 0) {
2511
- const targetUid = String(unique_identification_number);
2512
- productIndex = tempOrder.products.findIndex((item) => {
2513
- var _a2;
2514
- return String(
2515
- ((_a2 = item.metadata) == null ? void 0 : _a2.unique_identification_number) || item.unique_identification_number || ""
2516
- ) === targetUid;
2517
- });
2518
- }
2519
- if (productIndex === -1) {
2520
- productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
2521
- }
1152
+ const productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
2522
1153
  if (productIndex === -1) {
2523
1154
  throw new Error("[Order] 目标商品不存在,无法更新");
2524
1155
  }
@@ -2532,49 +1163,12 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2532
1163
  ...targetProduct.metadata || {},
2533
1164
  ...(updates == null ? void 0 : updates.metadata) || {},
2534
1165
  unique_identification_number: ((_a = targetProduct.metadata) == null ? void 0 : _a.unique_identification_number) || unique_identification_number
2535
- },
2536
- product_sku: {
2537
- ...targetProduct.product_sku || { option: [] },
2538
- ...(updates == null ? void 0 : updates.product_sku) && typeof updates.product_sku === "object" ? updates.product_sku : {},
2539
- option: Array.isArray((_b = updates == null ? void 0 : updates.product_sku) == null ? void 0 : _b.option) ? updates.product_sku.option : (0, import_utils.getProductSkuOptions)(targetProduct)
2540
1166
  }
2541
1167
  };
2542
1168
  nextProduct.num = (0, import_utils3.getSafeProductNum)(nextProduct.num);
2543
1169
  const callerUpdatesTopPrice = Object.prototype.hasOwnProperty.call(updates || {}, "selling_price") || Object.prototype.hasOwnProperty.call(updates || {}, "original_price");
2544
- const callerUpdatesMainMeta = ((_c = updates == null ? void 0 : updates.metadata) == null ? void 0 : _c.main_product_selling_price) !== void 0 || ((_d = updates == null ? void 0 : updates.metadata) == null ? void 0 : _d.main_product_original_price) !== void 0 || ((_e = updates == null ? void 0 : updates.metadata) == null ? void 0 : _e.source_product_price) !== void 0;
2545
- const isPersistedOrderLine = targetProduct.order_detail_id !== void 0 && targetProduct.order_detail_id !== null;
2546
- const callerChangesDiscountList = Array.isArray(updates == null ? void 0 : updates.discount_list) && updates.discount_list.length > 0 && !isSameDiscountList(updates.discount_list, targetProduct.discount_list);
2547
- const callerUpdatesManualPrice = ((_f = updates == null ? void 0 : updates.metadata) == null ? void 0 : _f.price_override) !== void 0 || ((_g = updates == null ? void 0 : updates.metadata) == null ? void 0 : _g.is_manual_discount) !== void 0 || ((_h = updates == null ? void 0 : updates.metadata) == null ? void 0 : _h.product_discount_reason) !== void 0 || callerChangesDiscountList;
2548
- const callerAllowsBookingReprice = (() => {
2549
- if (params.allow_booking_reprice !== true || !booking || !callerUpdatesTopPrice || !callerUpdatesMainMeta) {
2550
- return false;
2551
- }
2552
- const hasChangedPrice = (nextValue, currentValue) => {
2553
- if (nextValue === void 0 || nextValue === null || nextValue === "") {
2554
- return false;
2555
- }
2556
- return !new import_decimal.default(Number(nextValue) || 0).equals(
2557
- new import_decimal.default(Number(currentValue) || 0)
2558
- );
2559
- };
2560
- return hasChangedPrice(updates.selling_price, targetProduct.selling_price) || hasChangedPrice(updates.original_price, targetProduct.original_price);
2561
- })();
2562
- if (isPersistedOrderLine && !callerUpdatesManualPrice && !callerAllowsBookingReprice) {
2563
- nextProduct.selling_price = targetProduct.selling_price;
2564
- nextProduct.original_price = targetProduct.original_price;
2565
- nextProduct.payment_price = targetProduct.payment_price;
2566
- nextProduct.metadata = {
2567
- ...nextProduct.metadata || {},
2568
- source_product_price: (_i = targetProduct.metadata) == null ? void 0 : _i.source_product_price,
2569
- main_product_selling_price: (_j = targetProduct.metadata) == null ? void 0 : _j.main_product_selling_price,
2570
- main_product_original_price: (_k = targetProduct.metadata) == null ? void 0 : _k.main_product_original_price,
2571
- price_schema_version: ((_l = targetProduct.metadata) == null ? void 0 : _l.price_schema_version) ?? 2
2572
- };
2573
- nextProduct.product_bundle = this.preservePersistedBundlePriceFields(
2574
- targetProduct.product_bundle,
2575
- nextProduct.product_bundle
2576
- );
2577
- } else if (callerUpdatesTopPrice && !callerUpdatesMainMeta) {
1170
+ const callerUpdatesMainMeta = ((_b = updates == null ? void 0 : updates.metadata) == null ? void 0 : _b.main_product_selling_price) !== void 0 || ((_c = updates == null ? void 0 : updates.metadata) == null ? void 0 : _c.main_product_original_price) !== void 0 || ((_d = updates == null ? void 0 : updates.metadata) == null ? void 0 : _d.source_product_price) !== void 0;
1171
+ if (callerUpdatesTopPrice && !callerUpdatesMainMeta) {
2578
1172
  const existedMeta = nextProduct.metadata || {};
2579
1173
  nextProduct.metadata = { ...existedMeta };
2580
1174
  delete nextProduct.metadata.source_product_price;
@@ -2582,280 +1176,39 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2582
1176
  delete nextProduct.metadata.main_product_original_price;
2583
1177
  delete nextProduct.metadata.price_schema_version;
2584
1178
  }
2585
- let normalizedProduct = (0, import_utils.mergeOrderProductDisplayFields)(
2586
- nextProduct,
2587
- (0, import_utils3.normalizeOrderProduct)(nextProduct)
2588
- );
2589
- normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
2590
- normalizedProduct.discount_list
2591
- );
2592
- const preservedBookingUid = nextProduct.booking_uid || ((_m = nextProduct.metadata) == null ? void 0 : _m.booking_uid) || targetProduct.booking_uid || ((_n = targetProduct.metadata) == null ? void 0 : _n.booking_uid);
2593
- if (!booking && preservedBookingUid) {
2594
- normalizedProduct.booking_uid = preservedBookingUid;
2595
- normalizedProduct.metadata = {
2596
- ...normalizedProduct.metadata || {},
2597
- booking_uid: preservedBookingUid
2598
- };
2599
- }
2600
- if (booking) {
2601
- const productUid = String(
2602
- ((_o = normalizedProduct.metadata) == null ? void 0 : _o.unique_identification_number) || ((_p = targetProduct.metadata) == null ? void 0 : _p.unique_identification_number) || unique_identification_number || (0, import_utils.createUuidV4)()
2603
- );
2604
- normalizedProduct.metadata = {
2605
- ...normalizedProduct.metadata || {},
2606
- unique_identification_number: productUid
2607
- };
2608
- const linked = this.createLinkedProductAndBooking({
2609
- product: {
2610
- ...normalizedProduct,
2611
- unique_identification_number: productUid
2612
- },
2613
- booking
2614
- });
2615
- this.removeLinkedBookingsForProduct(tempOrder, targetProduct);
2616
- normalizedProduct = {
2617
- ...normalizedProduct,
2618
- booking_uid: linked.bookingUid,
2619
- metadata: {
2620
- ...normalizedProduct.metadata || {},
2621
- booking_uid: linked.bookingUid,
2622
- unique_identification_number: productUid
2623
- }
2624
- };
2625
- tempOrder.bookings = [...tempOrder.bookings || [], linked.booking];
2626
- }
2627
- tempOrder.products[productIndex] = normalizedProduct;
2628
- this.syncTempOrderHolderFromBookings(tempOrder);
1179
+ tempOrder.products[productIndex] = (0, import_utils3.normalizeOrderProduct)(nextProduct);
2629
1180
  this.captureProductRuntime(
2630
1181
  tempOrder,
2631
1182
  updates,
2632
1183
  tempOrder.products[productIndex],
2633
- (_q = tempOrder.products[productIndex].metadata) == null ? void 0 : _q.unique_identification_number
2634
- );
2635
- await this.applyPromotion();
2636
- this.applyDiscount();
2637
- this.sanitizeTempOrderProducts(tempOrder);
2638
- await this.recalculateSummary({ createIfMissing: true });
2639
- this.persistTempOrder();
2640
- return tempOrder.products;
2641
- }
2642
- async updateOrderProductQuantity(params) {
2643
- var _a;
2644
- const {
2645
- product_id,
2646
- product_variant_id,
2647
- num,
2648
- unique_identification_number,
2649
- identity_key,
2650
- product_sku,
2651
- product_bundle
2652
- } = params;
2653
- const tempOrder = this.ensureTempOrder();
2654
- const identityLookup = {
2655
- product_id,
2656
- product_variant_id
2657
- };
2658
- if (unique_identification_number !== void 0) {
2659
- identityLookup.unique_identification_number = unique_identification_number;
2660
- if (identity_key === void 0) {
2661
- identityLookup.identity_key = unique_identification_number;
2662
- }
2663
- }
2664
- if (identity_key !== void 0)
2665
- identityLookup.identity_key = identity_key;
2666
- if (product_sku !== void 0)
2667
- identityLookup.product_sku = product_sku;
2668
- if (product_bundle !== void 0)
2669
- identityLookup.product_bundle = product_bundle;
2670
- let productIndex = -1;
2671
- if (unique_identification_number !== void 0) {
2672
- const targetUid = String(unique_identification_number);
2673
- productIndex = tempOrder.products.findIndex((item) => {
2674
- var _a2;
2675
- return String(
2676
- ((_a2 = item.metadata) == null ? void 0 : _a2.unique_identification_number) || item.unique_identification_number || ""
2677
- ) === targetUid;
2678
- });
2679
- }
2680
- if (productIndex === -1) {
2681
- productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
2682
- }
2683
- if (productIndex === -1) {
2684
- throw new Error("[Order] 目标商品不存在,无法更新数量");
2685
- }
2686
- const targetProduct = tempOrder.products[productIndex];
2687
- const normalizedProduct = (0, import_utils3.normalizeOrderProduct)({
2688
- ...targetProduct,
2689
- num: (0, import_utils3.getSafeProductNum)(num),
2690
- metadata: {
2691
- ...targetProduct.metadata || {},
2692
- unique_identification_number: ((_a = targetProduct.metadata) == null ? void 0 : _a.unique_identification_number) || unique_identification_number
2693
- }
2694
- });
2695
- normalizedProduct.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
2696
- normalizedProduct.discount_list
1184
+ (_e = tempOrder.products[productIndex].metadata) == null ? void 0 : _e.unique_identification_number
2697
1185
  );
2698
- tempOrder.products[productIndex] = normalizedProduct;
2699
- await this.applyPromotion();
2700
1186
  this.applyDiscount();
2701
- this.sanitizeTempOrderProducts(tempOrder);
2702
1187
  await this.recalculateSummary({ createIfMissing: true });
2703
1188
  this.persistTempOrder();
2704
1189
  return tempOrder.products;
2705
1190
  }
2706
- updateOrderBooking(params) {
2707
- const { unique_identification_number, updates } = params;
1191
+ async removeProductFromOrder(identity) {
2708
1192
  const tempOrder = this.ensureTempOrder();
2709
- const bookingUid = String(unique_identification_number || "");
2710
- const bookingIndex = this.findBookingIndexByUniqueIdentificationNumber(
2711
- tempOrder,
2712
- bookingUid
1193
+ tempOrder.products = tempOrder.products.filter(
1194
+ (item) => !(0, import_utils3.isIdentityMatch)(item, identity)
2713
1195
  );
2714
- if (!bookingUid || bookingIndex === -1) {
2715
- throw new Error("[Order] 目标 booking 不存在,无法更新");
2716
- }
2717
- const targetBooking = tempOrder.bookings[bookingIndex] || {};
2718
- const nextBooking = {
2719
- ...targetBooking,
2720
- ...updates,
2721
- metadata: {
2722
- ...targetBooking.metadata || {},
2723
- ...updates.metadata || {},
2724
- unique_identification_number: bookingUid
2725
- }
2726
- };
2727
- this.syncBookingMetadataHolder(nextBooking, nextBooking.metadata);
2728
- nextBooking.is_all = (0, import_utils.normalizeBookingIsAll)(nextBooking);
2729
- nextBooking.sub_type = (0, import_utils.normalizeBookingSubType)(nextBooking);
2730
- tempOrder.bookings[bookingIndex] = nextBooking;
2731
- this.syncTempOrderHolderFromBookings(tempOrder);
2732
- this.persistTempOrder();
2733
- return tempOrder.bookings;
2734
- }
2735
- /**
2736
- * 商品行写路径收尾:促销 → 折扣 → 清洗 → summary → 持久化。
2737
- * 批量删除等多行变更场景只应调用一次,避免 N 次 applyPromotion。
2738
- *
2739
- * @example
2740
- * await this.finalizeAfterProductsMutation(tempOrder);
2741
- */
2742
- async finalizeAfterProductsMutation(tempOrder) {
2743
- this.syncTempOrderHolderFromBookings(tempOrder);
2744
- await this.applyPromotion();
2745
1196
  this.applyDiscount();
2746
- this.sanitizeTempOrderProducts(tempOrder);
2747
1197
  await this.recalculateSummary({ createIfMissing: true });
2748
1198
  this.persistTempOrder();
2749
- }
2750
- /**
2751
- * 批量按 identity 删除购物车行,末尾仅一次促销重算。
2752
- *
2753
- * @example
2754
- * await order.removeProductsFromOrder([identityA, identityB]);
2755
- */
2756
- async removeProductsFromOrder(identities) {
2757
- const tempOrder = this.ensureTempOrder();
2758
- if (!identities.length) {
2759
- return tempOrder.products;
2760
- }
2761
- const removedProducts = [];
2762
- tempOrder.products = tempOrder.products.filter((item) => {
2763
- const shouldRemove = identities.some((identity) => (0, import_utils3.isIdentityMatch)(item, identity));
2764
- if (shouldRemove)
2765
- removedProducts.push(item);
2766
- return !shouldRemove;
2767
- });
2768
- for (const product of removedProducts) {
2769
- this.removeLinkedBookingsForProduct(tempOrder, product);
2770
- }
2771
- await this.finalizeAfterProductsMutation(tempOrder);
2772
1199
  return tempOrder.products;
2773
1200
  }
2774
- async removeProductFromOrder(identity) {
2775
- return this.removeProductsFromOrder([identity]);
2776
- }
2777
- /**
2778
- * 仅清空购物车行(products / bookings),不重置整单。
2779
- * 用于「仅清空商品」;客户、备注、支付等协议字段保持不变。
2780
- */
2781
- async clearOrderCartLines() {
2782
- const tempOrder = this.ensureTempOrder();
2783
- tempOrder.products = [];
2784
- tempOrder.bookings = [];
2785
- this.syncTempOrderHolderFromBookings(tempOrder);
2786
- if (tempOrder._extend && typeof tempOrder._extend === "object") {
2787
- tempOrder._extend = {
2788
- ...tempOrder._extend,
2789
- productsByUid: {}
2790
- };
2791
- }
2792
- await this.applyPromotion();
2793
- this.applyDiscount();
2794
- this.sanitizeTempOrderProducts(tempOrder);
2795
- await this.recalculateSummary({ createIfMissing: true });
2796
- this.persistTempOrder();
2797
- return tempOrder;
2798
- }
2799
1201
  // ─── TempOrder: 提交 ───
2800
- buildCurrentSubmitPayloadForLocalPrint(params) {
2801
- var _a, _b, _c;
2802
- const tempOrder = this.ensureTempOrder();
2803
- this.persistTempOrder();
2804
- const payload = (0, import_utils.buildSubmitPayload)({
2805
- tempOrder,
2806
- cacheId: (params == null ? void 0 : params.cacheId) ?? this.cacheId,
2807
- platform: (params == null ? void 0 : params.platform) || ((_a = this.otherParams) == null ? void 0 : _a.platform),
2808
- businessCode: (params == null ? void 0 : params.businessCode) ?? ((_b = this.otherParams) == null ? void 0 : _b.businessCode) ?? ((_c = this.otherParams) == null ? void 0 : _c.business_code),
2809
- channel: params == null ? void 0 : params.channel,
2810
- type: params == null ? void 0 : params.type,
2811
- summary: this.store.summary || (0, import_utils.createEmptySummary)(),
2812
- enhance: (nextPayload) => ({
2813
- ...nextPayload,
2814
- order_number: tempOrder.order_number ?? nextPayload.order_number ?? null,
2815
- shop_order_number: tempOrder.shop_order_number ?? nextPayload.shop_order_number ?? null,
2816
- shop_full_order_number: tempOrder.shop_full_order_number ?? nextPayload.shop_full_order_number ?? null,
2817
- small_ticket_data_flag: 1
2818
- })
2819
- });
2820
- payload.created_at = void 0;
2821
- return payload;
2822
- }
2823
- async applyLocalPrintOrderNumbers(order) {
2824
- const tempOrder = this.ensureTempOrder();
2825
- if (!order || typeof order !== "object")
2826
- return tempOrder;
2827
- const shopOrderNumber = order.shop_order_number;
2828
- const shopFullOrderNumber = order.shop_full_order_number;
2829
- if (shopOrderNumber !== void 0 && shopOrderNumber !== null && shopOrderNumber !== "") {
2830
- tempOrder.shop_order_number = String(shopOrderNumber);
2831
- }
2832
- if (shopFullOrderNumber !== void 0 && shopFullOrderNumber !== null && shopFullOrderNumber !== "") {
2833
- tempOrder.shop_full_order_number = String(shopFullOrderNumber);
2834
- }
2835
- this.persistTempOrder();
2836
- await this.saveDraft();
2837
- return tempOrder;
2838
- }
2839
1202
  /**
2840
1203
  * 提交当前 Sales tempOrder。
2841
1204
  *
2842
1205
  * smallTicketDataFlag 用于 B 端 checkout 小票数据返回。PaymentModal 在支付提交时
2843
- * 应传 1,确保 /shop/order/sales/checkout 返回打印所需数据。
1206
+ * 应传 1,确保 /order/sales/checkout 返回打印所需数据。
2844
1207
  */
2845
1208
  async submitTempOrder(params) {
2846
- return this.runSubmitTempOrder(params);
2847
- }
2848
- async submitTempOrderAsync(params) {
2849
- return this.runSubmitTempOrder({
2850
- ...params,
2851
- syncMode: true
2852
- });
2853
- }
2854
- async runSubmitTempOrder(params) {
2855
- var _a, _b, _c, _d, _e;
1209
+ var _a, _b, _c;
2856
1210
  const tempOrder = this.ensureTempOrder();
2857
1211
  this.persistTempOrder();
2858
- const latestSummary = await this.recalculateSummary({ createIfMissing: true }) || this.store.summary || (0, import_utils.createEmptySummary)();
2859
1212
  const effectiveCacheId = (params == null ? void 0 : params.cacheId) ?? this.cacheId;
2860
1213
  const hasPaymentOverride = (params == null ? void 0 : params.payments) !== void 0;
2861
1214
  const hasPaymentStatusOverride = (params == null ? void 0 : params.paymentStatus) !== void 0;
@@ -2871,37 +1224,26 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2871
1224
  ...hasPaymentStatusOverride ? { payment_status: params == null ? void 0 : params.paymentStatus } : {},
2872
1225
  ...hasSmallTicketDataFlagOverride ? { small_ticket_data_flag: params == null ? void 0 : params.smallTicketDataFlag } : {}
2873
1226
  };
2874
- const enhancedPayload = (params == null ? void 0 : params.enhancePayload) ? params.enhancePayload(nextPayload, ctx) : nextPayload;
2875
- return enhancedPayload;
1227
+ return (params == null ? void 0 : params.enhancePayload) ? params.enhancePayload(nextPayload, ctx) : nextPayload;
2876
1228
  } : void 0;
2877
1229
  const payload = (0, import_utils.buildSubmitPayload)({
2878
1230
  tempOrder,
2879
1231
  cacheId: effectiveCacheId,
2880
1232
  platform: (params == null ? void 0 : params.platform) || ((_a = this.otherParams) == null ? void 0 : _a.platform),
2881
- businessCode: (params == null ? void 0 : params.businessCode) ?? ((_b = this.otherParams) == null ? void 0 : _b.businessCode) ?? ((_c = this.otherParams) == null ? void 0 : _c.business_code),
1233
+ businessCode: params == null ? void 0 : params.businessCode,
2882
1234
  channel: params == null ? void 0 : params.channel,
2883
1235
  type: params == null ? void 0 : params.type,
2884
- summary: latestSummary,
2885
- request_unique_idempotency_token: params == null ? void 0 : params.request_unique_idempotency_token,
2886
1236
  enhance: enhancePayload
2887
1237
  });
2888
- if (params == null ? void 0 : params.syncMode) {
2889
- payload.sync_mode = true;
2890
- }
2891
- if (!payload.created_at) {
2892
- payload.created_at = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
2893
- }
2894
1238
  await this.saveDraft();
2895
1239
  let result;
2896
1240
  try {
2897
1241
  this.logInfo("submitTempOrder calling sales checkout", {
2898
1242
  orderId: payload.order_id,
2899
1243
  externalSaleNumber: payload.external_sale_number,
2900
- requestUniqueIdempotencyToken: payload.request_unique_idempotency_token,
2901
1244
  paymentStatus: payload.payment_status,
2902
- paymentsCount: ((_d = payload.payments) == null ? void 0 : _d.length) || 0,
2903
- smallTicketDataFlag: payload.small_ticket_data_flag,
2904
- syncMode: payload.sync_mode
1245
+ paymentsCount: ((_b = payload.payments) == null ? void 0 : _b.length) || 0,
1246
+ smallTicketDataFlag: payload.small_ticket_data_flag
2905
1247
  });
2906
1248
  result = await this.submitSalesOrder({
2907
1249
  query: payload
@@ -2919,7 +1261,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2919
1261
  orderId: payload.order_id,
2920
1262
  externalSaleNumber: payload.external_sale_number,
2921
1263
  paymentStatus: payload.payment_status,
2922
- paymentsCount: ((_e = payload.payments) == null ? void 0 : _e.length) || 0
1264
+ paymentsCount: ((_c = payload.payments) == null ? void 0 : _c.length) || 0
2923
1265
  });
2924
1266
  throw error;
2925
1267
  }
@@ -2929,11 +1271,6 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2929
1271
  return result;
2930
1272
  }
2931
1273
  const submittedOrderId = this.extractOrderIdFromSubmitResult(result);
2932
- this.logInfo("runSubmitTempOrder: 提交成功", {
2933
- submittedOrderId,
2934
- result,
2935
- tempOrder
2936
- });
2937
1274
  if (submittedOrderId !== null && submittedOrderId !== void 0) {
2938
1275
  tempOrder.order_id = submittedOrderId;
2939
1276
  const resultRecord = result;
@@ -2941,43 +1278,23 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2941
1278
  submittedOrderId,
2942
1279
  (resultRecord == null ? void 0 : resultRecord.data) || resultRecord || {}
2943
1280
  );
2944
- } else if (this.isLocalPendingSubmitResult(result)) {
2945
- this.store.syncState = "local";
2946
- } else {
2947
- this.store.syncState = "submitted";
2948
1281
  }
2949
1282
  return result;
2950
1283
  }
2951
1284
  async markLocalOrderSynced(orderId, remoteOrder) {
2952
1285
  const tempOrder = this.ensureTempOrder();
2953
1286
  tempOrder.order_id = orderId;
2954
- this.applyRemoteOrderNumbersToTempOrder(tempOrder, remoteOrder);
2955
1287
  this.store.lastOrderInfo = remoteOrder;
2956
1288
  this.store.syncState = "submitted";
2957
1289
  this.persistTempOrder();
2958
1290
  await this.saveDraft();
2959
1291
  }
2960
- applyRemoteOrderNumbersToTempOrder(tempOrder, remoteOrder) {
2961
- const applyOrderNumber = (key) => {
2962
- const value = remoteOrder == null ? void 0 : remoteOrder[key];
2963
- if (value !== void 0 && value !== null && value !== "") {
2964
- tempOrder[key] = String(value);
2965
- }
2966
- };
2967
- applyOrderNumber("order_number");
2968
- applyOrderNumber("shop_order_number");
2969
- applyOrderNumber("shop_full_order_number");
2970
- }
2971
1292
  isSubmitResponseRejected(response) {
2972
1293
  const isErrorCode = (response == null ? void 0 : response.code) !== void 0 && response.code !== 200 && response.code !== "200";
2973
1294
  const isErrorStatus = (response == null ? void 0 : response.status) === false || typeof (response == null ? void 0 : response.status) === "number" && response.status >= 400;
2974
1295
  const isErrorSuccess = (response == null ? void 0 : response.success) === false;
2975
1296
  return isErrorCode || isErrorStatus || isErrorSuccess;
2976
1297
  }
2977
- isLocalPendingSubmitResult(response) {
2978
- const data = (response == null ? void 0 : response.data) && typeof response.data === "object" ? response.data : response;
2979
- return Number(data == null ? void 0 : data.need_sync) === 1;
2980
- }
2981
1298
  isSubmitErrorResponse(response) {
2982
1299
  if (!response || typeof response !== "object")
2983
1300
  return false;
@@ -3005,51 +1322,26 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3005
1322
  }
3006
1323
  });
3007
1324
  }
3008
- generateIdempotencyToken() {
3009
- const tempOrder = this.ensureTempOrder();
3010
- const token = this.buildPaymentSyncIdempotencyToken(
3011
- tempOrder,
3012
- tempOrder.payments
3013
- );
3014
- return `${token}_${Date.now()}`;
3015
- }
3016
1325
  async syncPaymentsToOrder(params) {
3017
1326
  const tempOrder = this.ensureTempOrder();
3018
1327
  const mappedPayments = (0, import_utils.mapPaymentItemsToOrderPayments)(
3019
1328
  params.payments || []
3020
1329
  );
3021
- const paymentTotal = this.calculatePaymentTotal(mappedPayments);
3022
- const targetAmount = this.getPaymentTargetAmount();
3023
- const isFullyPaid = targetAmount.lte(0) ? true : paymentTotal.gte(targetAmount);
3024
- const paymentStatus = isFullyPaid ? params.paymentStatus || "paid" : "partially_paid";
3025
1330
  tempOrder.payments = mappedPayments;
3026
- tempOrder.payment_status = paymentStatus;
1331
+ if (params.paymentStatus)
1332
+ tempOrder.payment_status = params.paymentStatus;
3027
1333
  this.persistTempOrder();
3028
1334
  await this.saveDraft();
3029
- if (!params.submitWhenPaid) {
3030
- return { isFullyPaid };
3031
- }
3032
- if (this.store.syncState === "submitting") {
1335
+ const paymentTotal = this.calculatePaymentTotal(mappedPayments);
1336
+ const targetAmount = this.getPaymentTargetAmount();
1337
+ const isFullyPaid = targetAmount.lte(0) ? false : paymentTotal.gte(targetAmount);
1338
+ if (!isFullyPaid || !params.submitWhenPaid) {
3033
1339
  return { isFullyPaid };
3034
1340
  }
3035
- this.store.syncState = "submitting";
3036
- const paymentSyncIdempotencyToken = this.buildPaymentSyncIdempotencyToken(
3037
- tempOrder,
3038
- mappedPayments
3039
- );
3040
1341
  const submitResult = await this.submitTempOrder({
3041
1342
  payments: mappedPayments,
3042
- paymentStatus,
3043
- smallTicketDataFlag: params.smallTicketDataFlag,
3044
- businessCode: params.businessCode,
3045
- channel: params.channel,
3046
- enhancePayload: (payload) => {
3047
- const nextPayload = {
3048
- ...payload,
3049
- request_unique_idempotency_token: paymentSyncIdempotencyToken
3050
- };
3051
- return nextPayload;
3052
- }
1343
+ paymentStatus: params.paymentStatus || "paid",
1344
+ smallTicketDataFlag: params.smallTicketDataFlag
3053
1345
  });
3054
1346
  return { isFullyPaid, submitResult };
3055
1347
  }
@@ -3185,7 +1477,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3185
1477
  * Checkout 专用:创建订单到后端
3186
1478
  *
3187
1479
  * 专门为 Checkout 模块设计的订单创建方法,
3188
- * 通过 OS Server 调用 checkout 接口创建订单
1480
+ * 直接调用 /order/checkout 接口创建订单
3189
1481
  * 接收已经处理好的订单数据,无需再处理购物车
3190
1482
  *
3191
1483
  * @param params Checkout 订单参数(已处理的订单数据)
@@ -3254,7 +1546,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3254
1546
  orderData.schedule_date = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
3255
1547
  }
3256
1548
  console.log("[Order] 调用后端接口创建订单:", {
3257
- url: "/shop/order/checkout",
1549
+ url: "/order/checkout",
3258
1550
  orderType: orderData.type,
3259
1551
  platform: orderData.platform,
3260
1552
  isDeposit: orderData.is_deposit,
@@ -3265,7 +1557,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3265
1557
  paymentsMethods: ((_m = orderData.payments) == null ? void 0 : _m.map((p) => p.code)) || []
3266
1558
  });
3267
1559
  this.logInfo("Calling backend checkout API", {
3268
- url: "/shop/order/checkout",
1560
+ url: "/order/checkout",
3269
1561
  orderType: orderData.type,
3270
1562
  platform: orderData.platform,
3271
1563
  isDeposit: orderData.is_deposit,
@@ -3287,11 +1579,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3287
1579
  hasOrderId: !!orderData.order_id,
3288
1580
  smallTicketDataFlag: orderData.small_ticket_data_flag
3289
1581
  });
3290
- const response = await this.request.post("/order/checkout", orderData, {
3291
- osServer: true,
3292
- customToast: () => {
3293
- }
3294
- });
1582
+ const response = await this.request.post("/order/checkout", orderData);
3295
1583
  this.logInfo("Order API called successfully", {
3296
1584
  response
3297
1585
  });
@@ -3311,7 +1599,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3311
1599
  async submitSalesOrder(params) {
3312
1600
  const { url, query } = params;
3313
1601
  const fetchUrl = url || "/order/sales/checkout";
3314
- return this.request.post(fetchUrl, query, { osServer: true, customToast: () => {
1602
+ return this.request.post(fetchUrl, query, { customToast: () => {
3315
1603
  } });
3316
1604
  }
3317
1605
  /**
@@ -3335,18 +1623,13 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3335
1623
  emails: params.emails
3336
1624
  });
3337
1625
  }
3338
- async getSalesOrderByLookup(params) {
3339
- const lookup = params.lookup === void 0 || params.lookup === null ? "" : String(params.lookup).trim();
3340
- if (!lookup) {
3341
- throw new Error("加载销售详情需要 lookup");
3342
- }
3343
- if (lookup.startsWith("LOCAL_")) {
3344
- params.forceRemote = false;
3345
- }
3346
- const res = await this.request.get(`/order/sales/${encodeURIComponent(lookup)}`, {
3347
- with: ["products", "bookings", "payments", "customer", "summary", "contacts_info"],
3348
- ...params.forceRemote ? { forceRemote: true } : {}
3349
- }, { osServer: true });
1626
+ // TODO 获取详情的接口
1627
+ async getOrderInfoByRemote(order_id) {
1628
+ const res = await this.request.get(`/order/sales/${order_id}`, {
1629
+ with: ["products", "bookings", "payments", "customer", "summary", "contacts_info"]
1630
+ }, {
1631
+ osServer: true
1632
+ });
3350
1633
  if (res.code === 200) {
3351
1634
  this.store.lastOrderInfo = res.data;
3352
1635
  }
@@ -3359,64 +1642,58 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3359
1642
  * 例如数组字段、商品行唯一值、价格 metadata、summary 派生状态和 _extend。
3360
1643
  */
3361
1644
  async hydrateTempOrderFromRecord(record, options) {
3362
- var _a, _b, _c;
3363
1645
  const raw = record && typeof record === "object" && record.data && record.order_id == null ? record.data : record || {};
3364
- const nextTempOrder = this.normalizeTempOrderForRuntime(raw);
3365
- const rawSummary = raw.summary && typeof raw.summary === "object" ? raw.summary : {};
3366
- const summarySurcharges = Array.isArray(rawSummary.surcharges) ? rawSummary.surcharges.map((s) => ({ ...s || {} })) : (0, import_lodash_es.cloneDeep)(nextTempOrder.surcharges || []);
3367
- this.store.tempOrder = nextTempOrder;
3368
- this.store.summary = {
3369
- ...(0, import_utils.createEmptySummary)(),
3370
- ...rawSummary,
3371
- surcharges: summarySurcharges
3372
- };
3373
- nextTempOrder._extend = {
3374
- ...nextTempOrder._extend || {},
3375
- originalSalesSnapshot: {
3376
- summary: (0, import_lodash_es.cloneDeep)(this.store.summary),
3377
- products: (0, import_lodash_es.cloneDeep)(nextTempOrder.products || []),
3378
- payments: (0, import_lodash_es.cloneDeep)(nextTempOrder.payments || []),
3379
- surcharges: (0, import_lodash_es.cloneDeep)(nextTempOrder.surcharges || []),
3380
- productFingerprint: this.buildOrderProductsFingerprint(nextTempOrder.products || [])
3381
- }
3382
- };
3383
- this.store.lastOrderInfo = raw.lastOrderInfo || raw;
3384
- const hydratedEditDiscounts = this.collectHydratedEditDiscounts(nextTempOrder.products);
3385
- const currentDiscounts = typeof ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList) === "function" ? this.store.discount.getDiscountList() || [] : [];
3386
- const shouldSkipEmptyDiscountSync = hydratedEditDiscounts.length === 0 && currentDiscounts.length === 0;
3387
- if (!shouldSkipEmptyDiscountSync) {
3388
- await ((_b = this.store.discount) == null ? void 0 : _b.setOriginalDiscountList(hydratedEditDiscounts));
3389
- await ((_c = this.store.discount) == null ? void 0 : _c.setDiscountList(hydratedEditDiscounts));
3390
- }
3391
- if (options == null ? void 0 : options.recalcOnHydrate) {
3392
- await this.recalculateSummary({ createIfMissing: false });
3393
- }
3394
- this.persistTempOrder();
3395
- return nextTempOrder;
3396
- }
3397
- normalizeTempOrderForRuntime(raw, options) {
3398
- var _a, _b;
1646
+ const defaults = this.createDefaultTempOrderInstance();
3399
1647
  const nextTempOrder = {
3400
- ...this.createDefaultTempOrderInstance(),
3401
- ...raw || {}
1648
+ ...defaults
3402
1649
  };
3403
- delete nextTempOrder.summary;
3404
- delete nextTempOrder.lastOrderInfo;
3405
- delete nextTempOrder.discount_list;
3406
- delete nextTempOrder.shop_id;
3407
- delete nextTempOrder.create_date;
3408
- delete nextTempOrder.total_amount;
3409
- delete nextTempOrder.expect_amount;
3410
- delete nextTempOrder.paid_amount;
3411
- delete nextTempOrder.shop_note;
3412
- delete nextTempOrder.start_time;
3413
- delete nextTempOrder.tax_fee;
3414
- delete nextTempOrder.total_refund_amount;
3415
- delete nextTempOrder.holder_id;
1650
+ const TEMP_ORDER_KEYS = [
1651
+ "order_id",
1652
+ "external_sale_number",
1653
+ "order_number",
1654
+ "shop_order_number",
1655
+ "shop_full_order_number",
1656
+ "type",
1657
+ "business_code",
1658
+ "platform",
1659
+ "sales_channel",
1660
+ "order_sales_channel",
1661
+ "vouchers",
1662
+ "status",
1663
+ "payment_status",
1664
+ "shipping_status",
1665
+ "customer_id",
1666
+ "customer_name",
1667
+ "country_calling_code",
1668
+ "phone",
1669
+ "email",
1670
+ "customer",
1671
+ "is_price_include_tax",
1672
+ "tax_title",
1673
+ "tax_country_code",
1674
+ "currency_code",
1675
+ "currency_symbol",
1676
+ "currency_format",
1677
+ "is_deposit",
1678
+ "deposit_amount",
1679
+ "shop_discount",
1680
+ "surcharge_fee",
1681
+ "note",
1682
+ "buzzer",
1683
+ "delivery_type",
1684
+ "table_number",
1685
+ "schedule_date",
1686
+ "created_at",
1687
+ "request_unique_idempotency_token"
1688
+ ];
1689
+ TEMP_ORDER_KEYS.forEach((key) => {
1690
+ if (raw[key] !== void 0) {
1691
+ nextTempOrder[key] = raw[key];
1692
+ }
1693
+ });
3416
1694
  nextTempOrder.metadata = raw.metadata && typeof raw.metadata === "object" ? { ...raw.metadata } : {};
3417
1695
  nextTempOrder.holder = raw.holder && typeof raw.holder === "object" ? { ...raw.holder } : null;
3418
- const rawProducts = Array.isArray(raw.products) ? raw.products : [];
3419
- nextTempOrder.products = rawProducts.length > 0 ? rawProducts.map((p) => this.normalizeHydratedOrderProduct(p)) : [];
1696
+ nextTempOrder.products = Array.isArray(raw.products) ? raw.products.map((p) => this.normalizeHydratedOrderProduct(p)) : [];
3420
1697
  nextTempOrder.bookings = Array.isArray(raw.bookings) ? raw.bookings.map((b) => ({
3421
1698
  ...b || {},
3422
1699
  is_all: (0, import_utils.normalizeBookingIsAll)(b || {}),
@@ -3424,6 +1701,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3424
1701
  })) : [];
3425
1702
  nextTempOrder.payments = Array.isArray(raw.payments) ? raw.payments.map((p) => ({ ...p || {} })) : [];
3426
1703
  nextTempOrder.surcharges = Array.isArray(raw.surcharges) ? raw.surcharges.map((s) => ({ ...s || {} })) : [];
1704
+ nextTempOrder.discount_list = Array.isArray(raw.discount_list) ? raw.discount_list.map((d) => ({ ...d || {} })) : [];
3427
1705
  nextTempOrder.relation_forms = Array.isArray(raw.relation_forms) ? raw.relation_forms.map((f) => ({ ...f || {} })) : [];
3428
1706
  nextTempOrder.contacts = Array.isArray(raw.contacts) ? raw.contacts.map((c) => ({ ...c || {} })) : [];
3429
1707
  nextTempOrder.contacts_info = raw.contacts_info && typeof raw.contacts_info === "object" && !Array.isArray(raw.contacts_info) ? { ...raw.contacts_info } : null;
@@ -3431,120 +1709,35 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3431
1709
  ...raw._extend,
3432
1710
  productsByUid: raw._extend.productsByUid || {}
3433
1711
  } : { productsByUid: {} };
3434
- const tempOrderExtend = nextTempOrder._extend;
3435
- const productsByUid = tempOrderExtend.productsByUid || {};
3436
- for (const [index, product] of nextTempOrder.products.entries()) {
3437
- const uid = (_a = product.metadata) == null ? void 0 : _a.unique_identification_number;
3438
- if (!uid)
3439
- continue;
3440
- const existed = productsByUid[uid] && typeof productsByUid[uid] === "object" ? productsByUid[uid] : {};
3441
- const rawProduct = rawProducts[index] && typeof rawProducts[index] === "object" ? rawProducts[index] : product;
3442
- const origin = existed.origin ?? rawProduct._origin ?? ((_b = rawProduct.metadata) == null ? void 0 : _b.origin) ?? rawProduct;
3443
- const originSnapshot = (0, import_lodash_es.cloneDeep)(origin);
3444
- const productOptionString = this.buildHydratedProductOptionString(rawProduct) || this.buildHydratedProductOptionString(product);
3445
- if (productOptionString && originSnapshot && typeof originSnapshot === "object") {
3446
- if (originSnapshot.product_option_string === void 0) {
3447
- originSnapshot.product_option_string = productOptionString;
3448
- }
3449
- if (originSnapshot.product_options_stirng === void 0) {
3450
- originSnapshot.product_options_stirng = productOptionString;
3451
- }
3452
- }
3453
- productsByUid[uid] = {
3454
- ...existed,
3455
- origin: originSnapshot
3456
- };
3457
- }
3458
- tempOrderExtend.productsByUid = productsByUid;
3459
- if ((options == null ? void 0 : options.ensureIdentity) !== false) {
3460
- this.ensureExternalSaleNumber(nextTempOrder);
1712
+ this.ensureExternalSaleNumber(nextTempOrder);
1713
+ this.store.tempOrder = nextTempOrder;
1714
+ this.store.summary = raw.summary && typeof raw.summary === "object" ? { ...(0, import_utils.createEmptySummary)(), ...raw.summary } : (0, import_utils.createEmptySummary)();
1715
+ this.store.lastOrderInfo = raw.lastOrderInfo || raw;
1716
+ if (options == null ? void 0 : options.recalcOnHydrate) {
1717
+ await this.recalculateSummary({ createIfMissing: false });
3461
1718
  }
3462
- nextTempOrder.vouchers = raw.vouchers || [];
1719
+ this.persistTempOrder();
3463
1720
  return nextTempOrder;
3464
1721
  }
3465
- pickHydratedDisplayText(value) {
3466
- if (value === void 0 || value === null)
3467
- return "";
3468
- if (typeof value === "string")
3469
- return value;
3470
- if (typeof value !== "object")
3471
- return String(value);
3472
- return value.auto || value.original || value.en || value["zh-CN"] || value["zh-HK"] || "";
3473
- }
3474
- formatHydratedNamePair(group, item) {
3475
- const groupText = this.pickHydratedDisplayText(group);
3476
- const itemText = this.pickHydratedDisplayText(item);
3477
- if (groupText && itemText)
3478
- return `${groupText}:${itemText}`;
3479
- return groupText || itemText;
3480
- }
3481
- buildHydratedProductOptionString(product) {
3482
- const segments = [];
3483
- const sku = (product == null ? void 0 : product.product_sku) || {};
3484
- if (Array.isArray(sku.variant)) {
3485
- for (const variant of sku.variant) {
3486
- const segment = this.formatHydratedNamePair(variant == null ? void 0 : variant.group, variant == null ? void 0 : variant.item);
3487
- if (segment)
3488
- segments.push(segment);
3489
- }
3490
- }
3491
- return segments.join(", ");
3492
- }
3493
- normalizeHydratedProductOptionItem(optionItem) {
3494
- const rawNum = (optionItem == null ? void 0 : optionItem.num) ?? (optionItem == null ? void 0 : optionItem.quantity) ?? 1;
3495
- const parsedNum = Number(rawNum);
3496
- const rawPrice = (optionItem == null ? void 0 : optionItem.add_price) ?? (optionItem == null ? void 0 : optionItem.price) ?? 0;
3497
- const parsedPrice = Number(rawPrice);
3498
- const normalized = {
3499
- ...optionItem,
3500
- option_group_item_id: optionItem == null ? void 0 : optionItem.option_group_item_id,
3501
- option_group_id: optionItem == null ? void 0 : optionItem.option_group_id,
3502
- num: Number.isFinite(parsedNum) && parsedNum > 0 ? parsedNum : 1,
3503
- add_price: Number.isFinite(parsedPrice) ? parsedPrice : 0
3504
- };
3505
- delete normalized.price;
3506
- if ((optionItem == null ? void 0 : optionItem.name) !== void 0)
3507
- normalized.name = optionItem.name;
3508
- if ((optionItem == null ? void 0 : optionItem.group_name) !== void 0)
3509
- normalized.group_name = optionItem.group_name;
3510
- if ((optionItem == null ? void 0 : optionItem.id) !== void 0)
3511
- normalized.id = optionItem.id;
3512
- return normalized;
3513
- }
3514
1722
  normalizeHydratedOrderProduct(product) {
3515
1723
  const row = { ...product || {} };
3516
1724
  if (row.num === void 0 && row.product_quantity !== void 0) {
3517
1725
  row.num = row.product_quantity;
3518
1726
  }
3519
- const productSku = (0, import_utils.ensureProductSku)(row);
3520
- row.product_sku = {
3521
- ...productSku,
3522
- option: (0, import_utils.normalizeProductSkuOptions)(
3523
- productSku.option.map(
3524
- (optionItem) => this.normalizeHydratedProductOptionItem(optionItem || {})
3525
- )
3526
- )
3527
- };
3528
- delete row[`product_${"option"}_item`];
1727
+ if (!Array.isArray(row.product_option_item))
1728
+ row.product_option_item = [];
3529
1729
  if (!Array.isArray(row.product_bundle))
3530
1730
  row.product_bundle = [];
3531
1731
  if (!row.metadata || typeof row.metadata !== "object")
3532
1732
  row.metadata = {};
3533
- if (row.booking_uid && !row.metadata.booking_uid) {
3534
- row.metadata.booking_uid = row.booking_uid;
3535
- }
3536
1733
  const existingIdentity = row.metadata.unique_identification_number || row.unique_identification_number;
3537
1734
  if (!existingIdentity) {
3538
1735
  row.metadata.unique_identification_number = (0, import_utils.createUuidV4)();
3539
1736
  }
3540
1737
  const normalized = (0, import_utils3.normalizeOrderProduct)(row);
3541
- normalized.discount_list = (0, import_utils.normalizeOrderProductDiscountList)(
3542
- normalized.discount_list
3543
- );
3544
1738
  const result = {
3545
1739
  ...row,
3546
1740
  ...normalized,
3547
- product_sku: normalized.product_sku,
3548
1741
  metadata: {
3549
1742
  ...row.metadata,
3550
1743
  ...normalized.metadata
@@ -3552,7 +1745,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3552
1745
  };
3553
1746
  if (result.metadata)
3554
1747
  delete result.metadata.price_schema_version;
3555
- return this.sanitizeOrderProductForTempOrder(result);
1748
+ return result;
3556
1749
  }
3557
1750
  getLastOrderInfo() {
3558
1751
  var _a;
@@ -3561,6 +1754,8 @@ var OrderModule = class extends import_BaseModule.BaseModule {
3561
1754
  async getOrderInfo(order_id) {
3562
1755
  const res = await this.request.get(`/order/sales/${order_id}`, {
3563
1756
  with: ["products", "bookings"]
1757
+ }, {
1758
+ osServer: true
3564
1759
  });
3565
1760
  return res;
3566
1761
  }