@pisell/pisellos 0.0.568 → 0.0.569

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (413) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.js +3 -2
  2. package/dist/model/strategy/adapter/walletPass/utils.js +7 -4
  3. package/dist/modules/BaseModule.d.ts +2 -2
  4. package/dist/modules/BaseModule.js +4 -4
  5. package/dist/modules/BookingContext/index.d.ts +48 -0
  6. package/dist/modules/BookingContext/index.js +566 -0
  7. package/dist/modules/BookingContext/types.d.ts +102 -0
  8. package/dist/modules/BookingContext/types.js +51 -0
  9. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +16 -0
  10. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +302 -0
  11. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +8 -0
  12. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +149 -0
  13. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +76 -0
  14. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.js +249 -0
  15. package/dist/modules/BookingContext/utils/flexible.d.ts +28 -0
  16. package/dist/modules/BookingContext/utils/flexible.js +56 -0
  17. package/dist/modules/BookingContext/utils/formatResourceList.d.ts +8 -0
  18. package/dist/modules/BookingContext/utils/formatResourceList.js +38 -0
  19. package/dist/modules/BookingContext/utils/index.d.ts +11 -0
  20. package/dist/modules/BookingContext/utils/index.js +11 -0
  21. package/dist/modules/BookingContext/utils/noResource.d.ts +13 -0
  22. package/dist/modules/BookingContext/utils/noResource.js +77 -0
  23. package/dist/modules/BookingContext/utils/orderLineDisplay.d.ts +1 -0
  24. package/dist/modules/BookingContext/utils/orderLineDisplay.js +36 -0
  25. package/dist/modules/BookingContext/utils/productExtend.d.ts +72 -0
  26. package/dist/modules/BookingContext/utils/productExtend.js +339 -0
  27. package/dist/modules/BookingContext/utils/resourceErrors.d.ts +41 -0
  28. package/dist/modules/BookingContext/utils/resourceErrors.js +74 -0
  29. package/dist/modules/BookingContext/utils/resourceSelection.d.ts +7 -0
  30. package/dist/modules/BookingContext/utils/resourceSelection.js +24 -0
  31. package/dist/modules/BookingContext/utils/resources.d.ts +80 -0
  32. package/dist/modules/BookingContext/utils/resources.js +486 -0
  33. package/dist/modules/BookingContext/utils/serviceTimes.d.ts +55 -0
  34. package/dist/modules/BookingContext/utils/serviceTimes.js +151 -0
  35. package/dist/modules/BookingContext/utils/timeSlices.d.ts +42 -0
  36. package/dist/modules/BookingContext/utils/timeSlices.js +100 -0
  37. package/dist/modules/Cart/utils/cartProduct.js +26 -5
  38. package/dist/modules/Cart/utils/changePrice.js +27 -20
  39. package/dist/modules/Customer/index.d.ts +20 -0
  40. package/dist/modules/Customer/index.js +172 -83
  41. package/dist/modules/Customer/types.d.ts +2 -0
  42. package/dist/modules/Discount/index.d.ts +2 -1
  43. package/dist/modules/Discount/index.js +37 -9
  44. package/dist/modules/Discount/types.d.ts +1 -0
  45. package/dist/modules/OpenData/index.d.ts +8 -0
  46. package/dist/modules/OpenData/index.js +36 -16
  47. package/dist/modules/Order/index.d.ts +448 -23
  48. package/dist/modules/Order/index.js +5417 -561
  49. package/dist/modules/Order/types.d.ts +693 -88
  50. package/dist/modules/Order/types.js +68 -1
  51. package/dist/modules/Order/utils/bundleDiscountHydration.d.ts +5 -0
  52. package/dist/modules/Order/utils/bundleDiscountHydration.js +144 -0
  53. package/dist/modules/Order/utils/manualProductDiscount.d.ts +106 -0
  54. package/dist/modules/Order/utils/manualProductDiscount.js +210 -0
  55. package/dist/modules/Order/utils/orderCollectionIdentity.d.ts +53 -0
  56. package/dist/modules/Order/utils/orderCollectionIdentity.js +405 -0
  57. package/dist/modules/Order/utils.d.ts +167 -18
  58. package/dist/modules/Order/utils.js +960 -165
  59. package/dist/modules/Payment/index.d.ts +10 -9
  60. package/dist/modules/Payment/index.js +465 -703
  61. package/dist/modules/Payment/types.d.ts +40 -16
  62. package/dist/modules/Payment/utils.d.ts +1 -1
  63. package/dist/modules/Payment/utils.js +4 -3
  64. package/dist/modules/Payment/walletpass.js +44 -29
  65. package/dist/modules/Product/types.d.ts +29 -7
  66. package/dist/modules/ProductList/index.d.ts +17 -13
  67. package/dist/modules/ProductList/index.js +184 -74
  68. package/dist/modules/ProductList/types.d.ts +17 -0
  69. package/dist/modules/Quotation/index.d.ts +22 -2
  70. package/dist/modules/Quotation/index.js +108 -42
  71. package/dist/modules/Quotation/types.d.ts +19 -0
  72. package/dist/modules/ResourcePlanner/index.d.ts +24 -0
  73. package/dist/modules/ResourcePlanner/index.js +181 -0
  74. package/dist/modules/ResourcePlanner/planner.d.ts +14 -0
  75. package/dist/modules/ResourcePlanner/planner.js +1069 -0
  76. package/dist/modules/ResourcePlanner/types.d.ts +227 -0
  77. package/dist/modules/ResourcePlanner/types.js +1 -0
  78. package/dist/modules/Rules/index.d.ts +8 -10
  79. package/dist/modules/Rules/index.js +221 -109
  80. package/dist/modules/Rules/types.d.ts +14 -3
  81. package/dist/modules/SalesSummary/index.d.ts +23 -26
  82. package/dist/modules/SalesSummary/index.js +152 -46
  83. package/dist/modules/SalesSummary/types.d.ts +9 -1
  84. package/dist/modules/SalesSummary/utils.d.ts +3 -22
  85. package/dist/modules/SalesSummary/utils.js +803 -163
  86. package/dist/modules/Schedule/getDateIsInSchedule.js +14 -7
  87. package/dist/modules/Schedule/index.d.ts +18 -5
  88. package/dist/modules/Schedule/index.js +78 -24
  89. package/dist/modules/Schedule/types.d.ts +2 -0
  90. package/dist/modules/Summary/index.js +4 -3
  91. package/dist/modules/SurchargeList/index.d.ts +18 -0
  92. package/dist/modules/SurchargeList/index.js +185 -0
  93. package/dist/modules/SurchargeList/types.d.ts +15 -0
  94. package/dist/modules/SurchargeList/types.js +1 -0
  95. package/dist/modules/index.d.ts +3 -0
  96. package/dist/modules/index.js +4 -1
  97. package/dist/plugins/app.d.ts +2 -0
  98. package/dist/plugins/request.d.ts +1 -0
  99. package/dist/server/index.d.ts +462 -8
  100. package/dist/server/index.js +6112 -656
  101. package/dist/server/modules/floor-plan/index.d.ts +39 -0
  102. package/dist/server/modules/floor-plan/index.js +595 -0
  103. package/dist/server/modules/floor-plan/types.d.ts +43 -0
  104. package/dist/server/modules/floor-plan/types.js +13 -0
  105. package/dist/server/modules/index.d.ts +7 -2
  106. package/dist/server/modules/index.js +6 -0
  107. package/dist/server/modules/order/index.d.ts +207 -14
  108. package/dist/server/modules/order/index.js +2326 -379
  109. package/dist/server/modules/order/types.d.ts +76 -5
  110. package/dist/server/modules/order/types.js +14 -1
  111. package/dist/server/modules/order/utils/filterBookings.d.ts +7 -1
  112. package/dist/server/modules/order/utils/filterBookings.js +118 -11
  113. package/dist/server/modules/order/utils/filterOrders.js +242 -14
  114. package/dist/server/modules/payment/index.d.ts +28 -0
  115. package/dist/server/modules/payment/index.js +305 -0
  116. package/dist/server/modules/payment/types.d.ts +9 -0
  117. package/dist/server/modules/payment/types.js +1 -0
  118. package/dist/server/modules/products/index.d.ts +105 -14
  119. package/dist/server/modules/products/index.js +1393 -516
  120. package/dist/server/modules/products/types.d.ts +34 -1
  121. package/dist/server/modules/products/types.js +4 -0
  122. package/dist/server/modules/quotation/index.d.ts +39 -0
  123. package/dist/server/modules/quotation/index.js +278 -66
  124. package/dist/server/modules/resource/index.d.ts +2 -3
  125. package/dist/server/modules/resource/index.js +108 -86
  126. package/dist/server/modules/schedule/index.d.ts +6 -4
  127. package/dist/server/modules/schedule/index.js +116 -85
  128. package/dist/server/test.json +713 -0
  129. package/dist/server/types.d.ts +2 -0
  130. package/dist/server/utils/product.js +2 -2
  131. package/dist/server/utils/small-ticket.d.ts +71 -0
  132. package/dist/server/utils/small-ticket.js +963 -0
  133. package/dist/solution/BaseSales/index.d.ts +378 -0
  134. package/dist/solution/BaseSales/index.js +4006 -0
  135. package/dist/solution/BaseSales/types.d.ts +394 -0
  136. package/dist/solution/BaseSales/types.js +40 -0
  137. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +287 -0
  138. package/dist/solution/BaseSales/utils/cartPromotion.js +1450 -0
  139. package/dist/solution/BaseSales/utils/parseSalesResponse.d.ts +144 -0
  140. package/dist/solution/BaseSales/utils/parseSalesResponse.js +157 -0
  141. package/dist/solution/BaseSales/utils/quotationPrice.d.ts +18 -0
  142. package/dist/solution/BaseSales/utils/quotationPrice.js +250 -0
  143. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +63 -0
  144. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +218 -0
  145. package/dist/solution/BaseSales/utils.d.ts +40 -0
  146. package/dist/solution/BaseSales/utils.js +263 -0
  147. package/dist/solution/BookingByStep/index.d.ts +1 -1
  148. package/dist/solution/BookingTicket/index.d.ts +394 -25
  149. package/dist/solution/BookingTicket/index.js +2506 -443
  150. package/dist/solution/BookingTicket/types.d.ts +191 -6
  151. package/dist/solution/BookingTicket/types.js +83 -10
  152. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +117 -0
  153. package/dist/solution/BookingTicket/utils/addProductDecision.js +346 -0
  154. package/dist/solution/BookingTicket/utils/addTimeAvailability.d.ts +35 -0
  155. package/dist/solution/BookingTicket/utils/addTimeAvailability.js +95 -0
  156. package/dist/solution/BookingTicket/utils/bookingStatus.d.ts +77 -0
  157. package/dist/solution/BookingTicket/utils/bookingStatus.js +136 -0
  158. package/dist/solution/BookingTicket/utils/cartView.d.ts +29 -0
  159. package/dist/solution/BookingTicket/utils/cartView.js +209 -0
  160. package/dist/solution/BookingTicket/utils/exampleData.d.ts +123 -0
  161. package/dist/solution/BookingTicket/utils/exampleData.js +183 -0
  162. package/dist/solution/BookingTicket/utils/orderCustomer.d.ts +4 -0
  163. package/dist/solution/BookingTicket/utils/orderCustomer.js +31 -0
  164. package/dist/solution/BookingTicket/utils/resolveBestAddTimePlan.d.ts +185 -0
  165. package/dist/solution/BookingTicket/utils/resolveBestAddTimePlan.js +438 -0
  166. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +36 -0
  167. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +400 -0
  168. package/dist/solution/BookingTicket/utils/scan/cloudSearch.d.ts +4 -0
  169. package/dist/solution/BookingTicket/utils/scan/cloudSearch.js +41 -1
  170. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +32 -0
  171. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.js +56 -0
  172. package/dist/solution/BookingTicket/utils/scan/handleScan.d.ts +3 -1
  173. package/dist/solution/BookingTicket/utils/scan/handleScan.js +11 -3
  174. package/dist/solution/BookingTicket/utils/scan/index.d.ts +5 -0
  175. package/dist/solution/BookingTicket/utils/scan/index.js +20 -8
  176. package/dist/solution/BookingTicket/utils/scan/scanProductValues.d.ts +21 -0
  177. package/dist/solution/BookingTicket/utils/scan/scanProductValues.js +150 -0
  178. package/dist/solution/BookingTicket/utils/sessionCatalogStale.d.ts +23 -0
  179. package/dist/solution/BookingTicket/utils/sessionCatalogStale.js +78 -0
  180. package/dist/solution/Checkout/index.d.ts +1 -0
  181. package/dist/solution/Checkout/index.js +25 -34
  182. package/dist/solution/Checkout/utils/index.js +4 -4
  183. package/dist/solution/RegisterAndLogin/config.js +2 -10
  184. package/dist/solution/Sales/index.d.ts +50 -5
  185. package/dist/solution/Sales/index.js +484 -92
  186. package/dist/solution/Sales/types.d.ts +26 -2
  187. package/dist/solution/ScanOrder/index.d.ts +27 -21
  188. package/dist/solution/ScanOrder/index.js +499 -434
  189. package/dist/solution/ScanOrder/types.d.ts +33 -11
  190. package/dist/solution/ScanOrder/types.js +4 -5
  191. package/dist/solution/ScanOrder/utils.d.ts +4 -1
  192. package/dist/solution/ScanOrder/utils.js +109 -34
  193. package/dist/solution/ShopDiscount/index.js +4 -4
  194. package/dist/solution/UnifiedBookingSales/index.d.ts +183 -0
  195. package/dist/solution/UnifiedBookingSales/index.js +1871 -0
  196. package/dist/solution/UnifiedBookingSales/types.d.ts +143 -0
  197. package/dist/solution/UnifiedBookingSales/types.js +11 -0
  198. package/dist/solution/VenueBooking/index.d.ts +29 -20
  199. package/dist/solution/VenueBooking/index.js +301 -213
  200. package/dist/solution/VenueBooking/sales-section-4-annotated.json +0 -2
  201. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +6 -0
  202. package/dist/solution/VenueBooking/utils/slotMerge.js +9 -3
  203. package/dist/solution/index.d.ts +2 -0
  204. package/dist/solution/index.js +3 -1
  205. package/dist/types/index.d.ts +11 -1
  206. package/lib/model/strategy/adapter/promotion/evaluator.js +3 -2
  207. package/lib/model/strategy/adapter/walletPass/utils.js +6 -4
  208. package/lib/modules/BaseModule.d.ts +2 -2
  209. package/lib/modules/BaseModule.js +4 -4
  210. package/lib/modules/BookingContext/index.d.ts +48 -0
  211. package/lib/modules/BookingContext/index.js +390 -0
  212. package/lib/modules/BookingContext/types.d.ts +102 -0
  213. package/lib/modules/BookingContext/types.js +48 -0
  214. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +16 -0
  215. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +286 -0
  216. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +8 -0
  217. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +148 -0
  218. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +76 -0
  219. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.js +242 -0
  220. package/lib/modules/BookingContext/utils/flexible.d.ts +28 -0
  221. package/lib/modules/BookingContext/utils/flexible.js +63 -0
  222. package/lib/modules/BookingContext/utils/formatResourceList.d.ts +8 -0
  223. package/lib/modules/BookingContext/utils/formatResourceList.js +35 -0
  224. package/lib/modules/BookingContext/utils/index.d.ts +11 -0
  225. package/lib/modules/BookingContext/utils/index.js +126 -0
  226. package/lib/modules/BookingContext/utils/noResource.d.ts +13 -0
  227. package/lib/modules/BookingContext/utils/noResource.js +78 -0
  228. package/lib/modules/BookingContext/utils/orderLineDisplay.d.ts +1 -0
  229. package/lib/modules/BookingContext/utils/orderLineDisplay.js +29 -0
  230. package/lib/modules/BookingContext/utils/productExtend.d.ts +72 -0
  231. package/lib/modules/BookingContext/utils/productExtend.js +330 -0
  232. package/lib/modules/BookingContext/utils/resourceErrors.d.ts +41 -0
  233. package/lib/modules/BookingContext/utils/resourceErrors.js +80 -0
  234. package/lib/modules/BookingContext/utils/resourceSelection.d.ts +7 -0
  235. package/lib/modules/BookingContext/utils/resourceSelection.js +24 -0
  236. package/lib/modules/BookingContext/utils/resources.d.ts +80 -0
  237. package/lib/modules/BookingContext/utils/resources.js +419 -0
  238. package/lib/modules/BookingContext/utils/serviceTimes.d.ts +55 -0
  239. package/lib/modules/BookingContext/utils/serviceTimes.js +161 -0
  240. package/lib/modules/BookingContext/utils/timeSlices.d.ts +42 -0
  241. package/lib/modules/BookingContext/utils/timeSlices.js +114 -0
  242. package/lib/modules/Cart/utils/cartProduct.js +27 -5
  243. package/lib/modules/Cart/utils/changePrice.js +20 -14
  244. package/lib/modules/Customer/index.d.ts +20 -0
  245. package/lib/modules/Customer/index.js +63 -10
  246. package/lib/modules/Customer/types.d.ts +2 -0
  247. package/lib/modules/Discount/index.d.ts +2 -1
  248. package/lib/modules/Discount/index.js +18 -2
  249. package/lib/modules/Discount/types.d.ts +1 -0
  250. package/lib/modules/OpenData/index.d.ts +8 -0
  251. package/lib/modules/OpenData/index.js +21 -3
  252. package/lib/modules/Order/index.d.ts +448 -23
  253. package/lib/modules/Order/index.js +3641 -308
  254. package/lib/modules/Order/types.d.ts +693 -88
  255. package/lib/modules/Order/types.js +55 -1
  256. package/lib/modules/Order/utils/bundleDiscountHydration.d.ts +5 -0
  257. package/lib/modules/Order/utils/bundleDiscountHydration.js +106 -0
  258. package/lib/modules/Order/utils/manualProductDiscount.d.ts +106 -0
  259. package/lib/modules/Order/utils/manualProductDiscount.js +207 -0
  260. package/lib/modules/Order/utils/orderCollectionIdentity.d.ts +53 -0
  261. package/lib/modules/Order/utils/orderCollectionIdentity.js +353 -0
  262. package/lib/modules/Order/utils.d.ts +167 -18
  263. package/lib/modules/Order/utils.js +974 -138
  264. package/lib/modules/Payment/index.d.ts +10 -9
  265. package/lib/modules/Payment/index.js +30 -124
  266. package/lib/modules/Payment/types.d.ts +40 -16
  267. package/lib/modules/Payment/utils.d.ts +1 -1
  268. package/lib/modules/Payment/utils.js +4 -3
  269. package/lib/modules/Payment/walletpass.js +16 -6
  270. package/lib/modules/Product/types.d.ts +29 -7
  271. package/lib/modules/ProductList/index.d.ts +17 -13
  272. package/lib/modules/ProductList/index.js +92 -51
  273. package/lib/modules/ProductList/types.d.ts +17 -0
  274. package/lib/modules/Quotation/index.d.ts +22 -2
  275. package/lib/modules/Quotation/index.js +76 -20
  276. package/lib/modules/Quotation/types.d.ts +19 -0
  277. package/lib/modules/ResourcePlanner/index.d.ts +24 -0
  278. package/lib/modules/ResourcePlanner/index.js +147 -0
  279. package/lib/modules/ResourcePlanner/planner.d.ts +14 -0
  280. package/lib/modules/ResourcePlanner/planner.js +895 -0
  281. package/lib/modules/ResourcePlanner/types.d.ts +227 -0
  282. package/lib/modules/ResourcePlanner/types.js +5 -0
  283. package/lib/modules/Rules/index.d.ts +8 -10
  284. package/lib/modules/Rules/index.js +152 -60
  285. package/lib/modules/Rules/types.d.ts +14 -3
  286. package/lib/modules/SalesSummary/index.d.ts +23 -26
  287. package/lib/modules/SalesSummary/index.js +84 -16
  288. package/lib/modules/SalesSummary/types.d.ts +9 -1
  289. package/lib/modules/SalesSummary/utils.d.ts +3 -22
  290. package/lib/modules/SalesSummary/utils.js +616 -111
  291. package/lib/modules/Schedule/getDateIsInSchedule.js +14 -7
  292. package/lib/modules/Schedule/index.d.ts +18 -5
  293. package/lib/modules/Schedule/index.js +49 -14
  294. package/lib/modules/Schedule/types.d.ts +2 -0
  295. package/lib/modules/Summary/index.js +2 -2
  296. package/lib/modules/SurchargeList/index.d.ts +18 -0
  297. package/lib/modules/SurchargeList/index.js +95 -0
  298. package/lib/modules/SurchargeList/types.d.ts +15 -0
  299. package/lib/modules/SurchargeList/types.js +5 -0
  300. package/lib/modules/index.d.ts +3 -0
  301. package/lib/modules/index.js +33 -0
  302. package/lib/plugins/app.d.ts +2 -0
  303. package/lib/plugins/request.d.ts +1 -0
  304. package/lib/server/index.d.ts +462 -8
  305. package/lib/server/index.js +3901 -205
  306. package/lib/server/modules/floor-plan/index.d.ts +39 -0
  307. package/lib/server/modules/floor-plan/index.js +306 -0
  308. package/lib/server/modules/floor-plan/types.d.ts +43 -0
  309. package/lib/server/modules/floor-plan/types.js +19 -0
  310. package/lib/server/modules/index.d.ts +7 -2
  311. package/lib/server/modules/index.js +21 -0
  312. package/lib/server/modules/order/index.d.ts +207 -14
  313. package/lib/server/modules/order/index.js +1324 -141
  314. package/lib/server/modules/order/types.d.ts +76 -5
  315. package/lib/server/modules/order/types.js +11 -1
  316. package/lib/server/modules/order/utils/filterBookings.d.ts +7 -1
  317. package/lib/server/modules/order/utils/filterBookings.js +119 -11
  318. package/lib/server/modules/order/utils/filterOrders.js +238 -13
  319. package/lib/server/modules/payment/index.d.ts +28 -0
  320. package/lib/server/modules/payment/index.js +168 -0
  321. package/lib/server/modules/payment/types.d.ts +9 -0
  322. package/lib/server/modules/payment/types.js +5 -0
  323. package/lib/server/modules/products/index.d.ts +105 -14
  324. package/lib/server/modules/products/index.js +588 -97
  325. package/lib/server/modules/products/types.d.ts +34 -1
  326. package/lib/server/modules/products/types.js +3 -0
  327. package/lib/server/modules/quotation/index.d.ts +39 -0
  328. package/lib/server/modules/quotation/index.js +145 -1
  329. package/lib/server/modules/resource/index.d.ts +2 -3
  330. package/lib/server/modules/resource/index.js +71 -45
  331. package/lib/server/modules/schedule/index.d.ts +6 -4
  332. package/lib/server/modules/schedule/index.js +55 -44
  333. package/lib/server/test.json +713 -0
  334. package/lib/server/types.d.ts +2 -0
  335. package/lib/server/utils/product.js +2 -2
  336. package/lib/server/utils/small-ticket.d.ts +71 -0
  337. package/lib/server/utils/small-ticket.js +926 -0
  338. package/lib/solution/BaseSales/index.d.ts +378 -0
  339. package/lib/solution/BaseSales/index.js +2367 -0
  340. package/lib/solution/BaseSales/types.d.ts +394 -0
  341. package/lib/solution/BaseSales/types.js +47 -0
  342. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +287 -0
  343. package/lib/solution/BaseSales/utils/cartPromotion.js +1155 -0
  344. package/lib/solution/BaseSales/utils/parseSalesResponse.d.ts +144 -0
  345. package/lib/solution/BaseSales/utils/parseSalesResponse.js +140 -0
  346. package/lib/solution/BaseSales/utils/quotationPrice.d.ts +18 -0
  347. package/lib/solution/BaseSales/utils/quotationPrice.js +231 -0
  348. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +63 -0
  349. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +215 -0
  350. package/lib/solution/BaseSales/utils.d.ts +40 -0
  351. package/lib/solution/BaseSales/utils.js +259 -0
  352. package/lib/solution/BookingByStep/index.d.ts +1 -1
  353. package/lib/solution/BookingTicket/index.d.ts +394 -25
  354. package/lib/solution/BookingTicket/index.js +1350 -76
  355. package/lib/solution/BookingTicket/types.d.ts +191 -6
  356. package/lib/solution/BookingTicket/types.js +71 -10
  357. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +117 -0
  358. package/lib/solution/BookingTicket/utils/addProductDecision.js +353 -0
  359. package/lib/solution/BookingTicket/utils/addTimeAvailability.d.ts +35 -0
  360. package/lib/solution/BookingTicket/utils/addTimeAvailability.js +94 -0
  361. package/lib/solution/BookingTicket/utils/bookingStatus.d.ts +77 -0
  362. package/lib/solution/BookingTicket/utils/bookingStatus.js +136 -0
  363. package/lib/solution/BookingTicket/utils/cartView.d.ts +29 -0
  364. package/lib/solution/BookingTicket/utils/cartView.js +200 -0
  365. package/lib/solution/BookingTicket/utils/exampleData.d.ts +123 -0
  366. package/lib/solution/BookingTicket/utils/exampleData.js +185 -0
  367. package/lib/solution/BookingTicket/utils/orderCustomer.d.ts +4 -0
  368. package/lib/solution/BookingTicket/utils/orderCustomer.js +35 -0
  369. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.d.ts +185 -0
  370. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.js +387 -0
  371. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +36 -0
  372. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +220 -0
  373. package/lib/solution/BookingTicket/utils/scan/cloudSearch.d.ts +4 -0
  374. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +24 -3
  375. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +32 -0
  376. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.js +64 -0
  377. package/lib/solution/BookingTicket/utils/scan/handleScan.d.ts +3 -1
  378. package/lib/solution/BookingTicket/utils/scan/handleScan.js +4 -2
  379. package/lib/solution/BookingTicket/utils/scan/index.d.ts +5 -0
  380. package/lib/solution/BookingTicket/utils/scan/index.js +14 -2
  381. package/lib/solution/BookingTicket/utils/scan/scanProductValues.d.ts +21 -0
  382. package/lib/solution/BookingTicket/utils/scan/scanProductValues.js +115 -0
  383. package/lib/solution/BookingTicket/utils/sessionCatalogStale.d.ts +23 -0
  384. package/lib/solution/BookingTicket/utils/sessionCatalogStale.js +83 -0
  385. package/lib/solution/Checkout/index.d.ts +1 -0
  386. package/lib/solution/Checkout/index.js +18 -19
  387. package/lib/solution/Checkout/utils/index.js +4 -4
  388. package/lib/solution/RegisterAndLogin/config.js +2 -10
  389. package/lib/solution/Sales/index.d.ts +50 -5
  390. package/lib/solution/Sales/index.js +296 -39
  391. package/lib/solution/Sales/types.d.ts +26 -2
  392. package/lib/solution/ScanOrder/index.d.ts +27 -21
  393. package/lib/solution/ScanOrder/index.js +144 -103
  394. package/lib/solution/ScanOrder/types.d.ts +33 -11
  395. package/lib/solution/ScanOrder/types.js +4 -5
  396. package/lib/solution/ScanOrder/utils.d.ts +4 -1
  397. package/lib/solution/ScanOrder/utils.js +98 -26
  398. package/lib/solution/ShopDiscount/index.js +3 -3
  399. package/lib/solution/UnifiedBookingSales/index.d.ts +183 -0
  400. package/lib/solution/UnifiedBookingSales/index.js +1050 -0
  401. package/lib/solution/UnifiedBookingSales/types.d.ts +143 -0
  402. package/lib/solution/UnifiedBookingSales/types.js +14 -0
  403. package/lib/solution/VenueBooking/index.d.ts +29 -20
  404. package/lib/solution/VenueBooking/index.js +169 -94
  405. package/lib/solution/VenueBooking/sales-section-4-annotated.json +0 -2
  406. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +6 -0
  407. package/lib/solution/VenueBooking/utils/slotMerge.js +9 -3
  408. package/lib/solution/index.d.ts +2 -0
  409. package/lib/solution/index.js +22 -0
  410. package/lib/types/index.d.ts +11 -1
  411. package/package.json +1 -1
  412. package/dist/solution/Checkout/appointmentDemo.json +0 -1
  413. package/lib/solution/Checkout/appointmentDemo.json +0 -1
@@ -1,10 +1,14 @@
1
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3
1
  function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
3
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
5
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
4
6
  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
5
7
  function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
6
8
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
7
9
  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
10
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
11
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
8
12
  function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
9
13
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
10
14
  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
@@ -29,6 +33,7 @@ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e
29
33
  import { cloneDeep } from 'lodash-es';
30
34
  import dayjs from 'dayjs';
31
35
  import { BaseModule } from "../../../modules/BaseModule";
36
+ import { applyOrderCollectionUidRemaps, getOrderCollectionPersistentId, getOrderCollectionReferenceUid, getOrderCollectionUid, isSameOrderCollectionItem, mergeOrderCollectionItems, normalizeOrderCollections } from "../../../modules/Order/utils/orderCollectionIdentity";
32
37
  import { OrderHooks } from "./types";
33
38
 
34
39
  /**
@@ -36,6 +41,27 @@ import { OrderHooks } from "./types";
36
41
  */
37
42
  var INDEXDB_STORE_NAME = 'orders';
38
43
  var ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY = 'server_order_last_full_fetch_at';
44
+ var ORDER_SYNC_THROTTLE_MS_STORAGE_KEY = 'order_sync_throttle_ms';
45
+ var DEFAULT_ORDER_SYNC_THROTTLE_MS = 2000;
46
+ /** pubsub 回声写入去重窗口:业务 API 刚写入后,跳过同单 SQLite patch */
47
+ var ORDER_SQLITE_DEDUPE_MS = 15000;
48
+ /** silentRefresh 最小间隔,避免 preload 后立即全量重拉 */
49
+ var ORDER_SILENT_REFRESH_MIN_INTERVAL_MS = 30000;
50
+ /** 视为「业务侧刚写入」的来源,pubsub 回声可跳过 SQLite */
51
+ var ORDER_BUSINESS_WRITE_SOURCES = new Set(['upsertOrdersFromRemote', 'upsertPendingSyncOrders', 'overwriteExistingOrder', 'markOrderSyncedByExternalSaleNumber']);
52
+
53
+ /**
54
+ * 合并热路径全表去重自检开关:默认关闭。
55
+ * 开启后每次合并会额外对整张 store 做一次 O(n^2) 重复检测并告警,
56
+ * 仅用于排查增量身份索引是否遗漏了重复订单,不应在生产常开。
57
+ */
58
+ var ORDER_MERGE_SELF_CHECK = false;
59
+ var ORDER_AUTHORITATIVE_COLLECTION_FIELDS = ['products', 'bookings', 'payments'];
60
+ var ORDER_COLLECTION_KIND_BY_FIELD = {
61
+ products: 'product',
62
+ bookings: 'booking',
63
+ payments: 'payment'
64
+ };
39
65
 
40
66
  /**
41
67
  * Order 模块 - 基础框架
@@ -54,22 +80,68 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
54
80
  _defineProperty(_assertThisInitialized(_this), "orderDataSource", void 0);
55
81
  _defineProperty(_assertThisInitialized(_this), "pendingSyncMessages", []);
56
82
  _defineProperty(_assertThisInitialized(_this), "syncTimer", void 0);
57
- _defineProperty(_assertThisInitialized(_this), "ORDER_SYNC_DEBOUNCE_MS", 5000);
58
- // Map<resource_id, OrderId[]> 资源到订单的倒排索引
59
- _defineProperty(_assertThisInitialized(_this), "resourceIdIndex", new Map());
83
+ _defineProperty(_assertThisInitialized(_this), "isProcessingSyncBatch", false);
84
+ _defineProperty(_assertThisInitialized(_this), "isIdlePhase", true);
60
85
  _defineProperty(_assertThisInitialized(_this), "logger", void 0);
61
86
  // LoggerManager 实例
62
87
  _defineProperty(_assertThisInitialized(_this), "storage", void 0);
88
+ _defineProperty(_assertThisInitialized(_this), "orderSQLiteSaveQueue", Promise.resolve());
89
+ /** 按 storageKey 记录最近一次 SQLite 写入来源与时间,用于去重 */
90
+ _defineProperty(_assertThisInitialized(_this), "recentSqliteWriteByStorageKey", new Map());
91
+ /** 最近一次 SSE 全量拉取完成时间 */
92
+ _defineProperty(_assertThisInitialized(_this), "lastServerFullFetchAtMs", 0);
63
93
  return _this;
64
94
  }
95
+
96
+ /**
97
+ * 广播订单变更事件,兼容全量列表订阅并额外携带本次变更订单。
98
+ *
99
+ * @example
100
+ * await this.emitOrdersChanged([freshOrder], 'pubsub.bodyUpsert')
101
+ */
65
102
  _createClass(OrderModule, [{
66
- key: "initialize",
67
- value: function () {
68
- var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
69
- var _options$initialState;
70
- var appPlugin, app, _this$store$createdAt, coreData, today, operatingDayBoundary, boundaryTime, boundaryStart, boundaryEnd;
103
+ key: "emitOrdersChanged",
104
+ value: (function () {
105
+ var _emitOrdersChanged = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
106
+ var _this2 = this;
107
+ var changedOrders,
108
+ source,
109
+ payload,
110
+ _args = arguments;
71
111
  return _regeneratorRuntime().wrap(function _callee$(_context) {
72
112
  while (1) switch (_context.prev = _context.next) {
113
+ case 0:
114
+ changedOrders = _args.length > 0 && _args[0] !== undefined ? _args[0] : [];
115
+ source = _args.length > 1 ? _args[1] : undefined;
116
+ payload = {
117
+ list: this.store.list,
118
+ changedOrders: changedOrders.map(function (order) {
119
+ return _this2.normalizeOrderForMemoryList(order);
120
+ }),
121
+ source: source
122
+ };
123
+ _context.next = 5;
124
+ return this.core.effects.emit(OrderHooks.onOrdersChanged, payload);
125
+ case 5:
126
+ case "end":
127
+ return _context.stop();
128
+ }
129
+ }, _callee, this);
130
+ }));
131
+ function emitOrdersChanged() {
132
+ return _emitOrdersChanged.apply(this, arguments);
133
+ }
134
+ return emitOrdersChanged;
135
+ }())
136
+ }, {
137
+ key: "initialize",
138
+ value: function () {
139
+ var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(core, options) {
140
+ var _options$initialState,
141
+ _this3 = this;
142
+ var appPlugin, app;
143
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
144
+ while (1) switch (_context2.prev = _context2.next) {
73
145
  case 0:
74
146
  this.core = core;
75
147
  this.store = options === null || options === void 0 ? void 0 : options.store;
@@ -80,42 +152,14 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
80
152
  this.dbManager = app.sqlite;
81
153
  this.logger = app.logger;
82
154
  this.storage = app.storage;
83
- coreData = app.data.store.getStore().getDataByModel('core');
84
- if (!((_this$store$createdAt = this.store.createdAtQuery) !== null && _this$store$createdAt !== void 0 && _this$store$createdAt.sales_time_between) && coreData !== null && coreData !== void 0 && coreData.core) {
85
- today = dayjs();
86
- if (coreData !== null && coreData !== void 0 && coreData.core.operating_day_boundary) {
87
- operatingDayBoundary = coreData.core.operating_day_boundary;
88
- if (operatingDayBoundary.type === 'start_time') {
89
- boundaryTime = String(operatingDayBoundary.time || '').trim();
90
- boundaryStart = dayjs("".concat(today.format('YYYY-MM-DD'), " ").concat(boundaryTime));
91
- boundaryEnd = boundaryStart.add(1, 'day');
92
- if (boundaryStart.isValid()) {
93
- this.store.createdAtQuery = {
94
- sales_time_between: [boundaryStart.format('YYYY-MM-DD HH:mm:ss'), boundaryEnd.format('YYYY-MM-DD HH:mm:ss')]
95
- };
96
- } else {
97
- // 边界时间异常时回退到自然日,避免 createdAtQuery 为空导致后续查询异常
98
- this.store.createdAtQuery = {
99
- sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
100
- };
101
- }
102
- } else {
103
- this.store.createdAtQuery = {
104
- sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
105
- };
106
- }
107
- } else {
108
- // TODO: 这里后续可能需要使用店铺营业时间查询
109
- this.store.createdAtQuery = {
110
- sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
111
- };
112
- }
113
- }
155
+ this.updateCreateStore();
114
156
  }
115
157
  if (Array.isArray(options === null || options === void 0 || (_options$initialState = options.initialState) === null || _options$initialState === void 0 ? void 0 : _options$initialState.list)) {
116
- this.store.list = options.initialState.list;
158
+ this.store.list = options.initialState.list.map(function (order) {
159
+ return _this3.normalizeOrderForMemoryList(order);
160
+ });
117
161
  this.syncOrdersMap();
118
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
162
+ this.emitOrdersChanged([], 'initialState');
119
163
  } else {
120
164
  this.store.list = [];
121
165
  this.store.map = new Map();
@@ -129,9 +173,9 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
129
173
  });
130
174
  case 10:
131
175
  case "end":
132
- return _context.stop();
176
+ return _context2.stop();
133
177
  }
134
- }, _callee, this);
178
+ }, _callee2, this);
135
179
  }));
136
180
  function initialize(_x, _x2) {
137
181
  return _initialize.apply(this, arguments);
@@ -139,10 +183,10 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
139
183
  return initialize;
140
184
  }()
141
185
  /**
142
- * 记录信息日志
143
- * @param title 日志标题
144
- * @param metadata 日志元数据
145
- */
186
+ * 记录信息日志
187
+ * @param title 日志标题
188
+ * @param metadata 日志元数据
189
+ */
146
190
  }, {
147
191
  key: "logInfo",
148
192
  value: function logInfo(title, metadata) {
@@ -179,32 +223,439 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
179
223
  // 日志记录失败不影响主流程
180
224
  }
181
225
  }
226
+ }, {
227
+ key: "logWarning",
228
+ value: function logWarning(title, metadata) {
229
+ try {
230
+ if (this.logger) {
231
+ this.logger.addLog({
232
+ type: 'warning',
233
+ title: "[OrderServerModule] ".concat(title),
234
+ metadata: metadata || {}
235
+ });
236
+ }
237
+ } catch (_unused3) {
238
+ // 日志记录失败不影响主流程
239
+ }
240
+ }
241
+
242
+ /**
243
+ * 在订单进入内存或 SQLite 前统一压缩子项强身份重复并补齐协议 UID。
244
+ * 仅记录计数与订单标识,不输出商品、预约、支付或客户明细。
245
+ */
246
+ }, {
247
+ key: "normalizeOrderCollectionsForIngress",
248
+ value: function normalizeOrderCollectionsForIngress(order, source) {
249
+ var result = normalizeOrderCollections(order);
250
+ var kinds = ['product', 'booking', 'payment'];
251
+ var hasChanges = kinds.some(function (kind) {
252
+ var stats = result.stats[kind];
253
+ return stats.backfilledUidCount > 0 || stats.collapsedDuplicateCount > 0 || stats.uidConflictCount > 0 || stats.anonymousRowCount > 0;
254
+ });
255
+ if (hasChanges) {
256
+ var _order$order_id, _external_sale_number;
257
+ var summarize = function summarize(stats) {
258
+ return {
259
+ backfilled_uid_count: stats.backfilledUidCount,
260
+ collapsed_duplicate_count: stats.collapsedDuplicateCount,
261
+ uid_conflict_count: stats.uidConflictCount,
262
+ anonymous_row_count: stats.anonymousRowCount
263
+ };
264
+ };
265
+ var context = {
266
+ source: source,
267
+ order_id: (_order$order_id = order === null || order === void 0 ? void 0 : order.order_id) !== null && _order$order_id !== void 0 ? _order$order_id : null,
268
+ external_sale_number: (_external_sale_number = order === null || order === void 0 ? void 0 : order.external_sale_number) !== null && _external_sale_number !== void 0 ? _external_sale_number : null,
269
+ products: summarize(result.stats.product),
270
+ bookings: summarize(result.stats.booking),
271
+ payments: summarize(result.stats.payment)
272
+ };
273
+ var hasUnsafeIdentity = kinds.some(function (kind) {
274
+ var stats = result.stats[kind];
275
+ return stats.uidConflictCount > 0 || stats.anonymousRowCount > 0;
276
+ });
277
+ if (hasUnsafeIdentity) {
278
+ this.logWarning('订单子项身份存在冲突或匿名行', context);
279
+ } else {
280
+ this.logInfo('订单子项身份已规范化', context);
281
+ }
282
+ }
283
+ return result.order;
284
+ }
285
+
286
+ /**
287
+ * incoming 决定权威成员集合;同一持久化行仍从 existing 补齐 incoming 省略的本地展示字段。
288
+ */
289
+ }, {
290
+ key: "mergeAuthoritativeOrderCollection",
291
+ value: function mergeAuthoritativeOrderCollection(field, existing, incoming) {
292
+ var uidRemaps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
293
+ var kind = ORDER_COLLECTION_KIND_BY_FIELD[field];
294
+ var existingItems = Array.isArray(existing) ? existing : [];
295
+ return incoming.map(function (incomingItem) {
296
+ var existingItem = existingItems.find(function (item) {
297
+ return isSameOrderCollectionItem(kind, item, incomingItem);
298
+ });
299
+ if (!existingItem) return cloneDeep(incomingItem);
300
+ var mergedItem = mergeOrderCollectionItems(kind, existingItem, incomingItem);
301
+ var mergedUid = getOrderCollectionUid(kind, mergedItem);
302
+ if (mergedUid) {
303
+ var _iterator = _createForOfIteratorHelper(new Set([getOrderCollectionReferenceUid(kind, existingItem), getOrderCollectionReferenceUid(kind, incomingItem)])),
304
+ _step;
305
+ try {
306
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
307
+ var from = _step.value;
308
+ if (!from || from === mergedUid) continue;
309
+ uidRemaps.push({
310
+ kind: kind,
311
+ from: from,
312
+ to: mergedUid,
313
+ persistentId: getOrderCollectionPersistentId(kind, incomingItem) || getOrderCollectionPersistentId(kind, existingItem)
314
+ });
315
+ }
316
+ } catch (err) {
317
+ _iterator.e(err);
318
+ } finally {
319
+ _iterator.f();
320
+ }
321
+ }
322
+ return mergedItem;
323
+ });
324
+ }
325
+ }, {
326
+ key: "reconcileOverwriteOrderCollections",
327
+ value: function reconcileOverwriteOrderCollections(existing, incoming) {
328
+ var reconciled = cloneDeep(incoming);
329
+ var existingRecord = existing;
330
+ var incomingRecord = incoming;
331
+ var uidRemaps = [];
332
+ for (var _i = 0, _ORDER_AUTHORITATIVE_ = ORDER_AUTHORITATIVE_COLLECTION_FIELDS; _i < _ORDER_AUTHORITATIVE_.length; _i++) {
333
+ var field = _ORDER_AUTHORITATIVE_[_i];
334
+ if (!Array.isArray(incomingRecord[field])) continue;
335
+ reconciled[field] = this.mergeAuthoritativeOrderCollection(field, existingRecord[field], incomingRecord[field], uidRemaps);
336
+ }
337
+ return this.normalizeOrderCollectionsForIngress(applyOrderCollectionUidRemaps(reconciled, uidRemaps), 'overwriteExistingOrder.reconciled');
338
+ }
339
+
340
+ /**
341
+ * 记录订单最近一次 SQLite 写入,供 pubsub 回声去重使用。
342
+ *
343
+ * @example
344
+ * this.recordRecentSqliteWrite('upsertOrdersFromRemote', orders)
345
+ */
346
+ }, {
347
+ key: "recordRecentSqliteWrite",
348
+ value: function recordRecentSqliteWrite(source, orders) {
349
+ var now = Date.now();
350
+ var _iterator2 = _createForOfIteratorHelper(orders),
351
+ _step2;
352
+ try {
353
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
354
+ var order = _step2.value;
355
+ var storageKey = this.getOrderStorageKey(order);
356
+ if (!storageKey) continue;
357
+ this.recentSqliteWriteByStorageKey.set(storageKey, {
358
+ source: source,
359
+ ts: now
360
+ });
361
+ }
362
+ } catch (err) {
363
+ _iterator2.e(err);
364
+ } finally {
365
+ _iterator2.f();
366
+ }
367
+ }
368
+
369
+ /**
370
+ * 过滤 pubsub 触发的冗余 SQLite patch(业务 API 刚写入过的 update 回声)。
371
+ *
372
+ * @example
373
+ * const { toWrite, skipped } = this.filterRedundantPatchOrders('pubsub.bodyUpsert', orders, mergeActions)
374
+ */
375
+ }, {
376
+ key: "filterRedundantPatchOrders",
377
+ value: function filterRedundantPatchOrders(source, orders, mergeActions) {
378
+ var eligibleSkipSources = new Set(['pubsub.bodyUpsert', 'pubsub.httpRefresh']);
379
+ if (!eligibleSkipSources.has(source)) {
380
+ return {
381
+ toWrite: orders,
382
+ skipped: []
383
+ };
384
+ }
385
+ var now = Date.now();
386
+ var toWrite = [];
387
+ var skipped = [];
388
+ var _iterator3 = _createForOfIteratorHelper(orders),
389
+ _step3;
390
+ try {
391
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
392
+ var order = _step3.value;
393
+ var storageKey = this.getOrderStorageKey(order);
394
+ if (!storageKey) {
395
+ toWrite.push(order);
396
+ continue;
397
+ }
398
+ var orderKey = order.order_id !== undefined && order.order_id !== null ? this.getIdKey(order.order_id) : '';
399
+ var mergeAction = orderKey ? mergeActions[orderKey] : undefined;
400
+
401
+ // 新增单必须落库,不参与去重
402
+ if (mergeAction === 'insert') {
403
+ toWrite.push(order);
404
+ continue;
405
+ }
406
+ var recent = this.recentSqliteWriteByStorageKey.get(storageKey);
407
+ if (recent && ORDER_BUSINESS_WRITE_SOURCES.has(recent.source) && now - recent.ts < ORDER_SQLITE_DEDUPE_MS) {
408
+ var _order$order_id2;
409
+ skipped.push({
410
+ orderId: (_order$order_id2 = order.order_id) !== null && _order$order_id2 !== void 0 ? _order$order_id2 : null,
411
+ storageKey: storageKey,
412
+ reason: 'skip_pubsub_echo_after_business_write',
413
+ lastSource: recent.source,
414
+ elapsedMs: now - recent.ts
415
+ });
416
+ continue;
417
+ }
418
+ toWrite.push(order);
419
+ }
420
+ } catch (err) {
421
+ _iterator3.e(err);
422
+ } finally {
423
+ _iterator3.f();
424
+ }
425
+ return {
426
+ toWrite: toWrite,
427
+ skipped: skipped
428
+ };
429
+ }
430
+
431
+ /**
432
+ * 过滤 pubsub HTTP 增量拉取 ids:本地刚由业务 API 写入的单可跳过 HTTP。
433
+ *
434
+ * @example
435
+ * const ids = this.filterRedundantHttpRefreshIds([99331, 99332])
436
+ */
437
+ }, {
438
+ key: "filterRedundantHttpRefreshIds",
439
+ value: function filterRedundantHttpRefreshIds(ids) {
440
+ var now = Date.now();
441
+ var toFetch = [];
442
+ var skipped = [];
443
+ var _iterator4 = _createForOfIteratorHelper(ids),
444
+ _step4;
445
+ try {
446
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
447
+ var id = _step4.value;
448
+ var existing = this.getOrderByOrderId(id);
449
+ if (!existing) {
450
+ toFetch.push(id);
451
+ continue;
452
+ }
453
+ var storageKey = this.getOrderStorageKey(existing);
454
+ var recent = storageKey ? this.recentSqliteWriteByStorageKey.get(storageKey) : undefined;
455
+ if (recent && recent.source === 'upsertOrdersFromRemote' && now - recent.ts < ORDER_SQLITE_DEDUPE_MS) {
456
+ skipped.push({
457
+ orderId: id,
458
+ lastSource: recent.source,
459
+ elapsedMs: now - recent.ts
460
+ });
461
+ continue;
462
+ }
463
+ toFetch.push(id);
464
+ }
465
+ } catch (err) {
466
+ _iterator4.e(err);
467
+ } finally {
468
+ _iterator4.f();
469
+ }
470
+ return {
471
+ toFetch: toFetch,
472
+ skipped: skipped
473
+ };
474
+ }
475
+
476
+ /**
477
+ * 解析 pubsub 消息会走哪条同步分支,便于对照为何触发 HTTP 重拉或 body 直写。
478
+ *
479
+ * @example
480
+ * this.resolveSyncMessageRoute(msg)
481
+ * // => { route: 'httpRefresh.batchIds', ... }
482
+ */
483
+ }, {
484
+ key: "resolveSyncMessageRoute",
485
+ value: function resolveSyncMessageRoute(msg) {
486
+ var _msg$id, _msg$relation_order_i, _normalizedBody$order5;
487
+ var hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
488
+ var singleIdRaw = (_msg$id = msg.id) !== null && _msg$id !== void 0 ? _msg$id : msg.order_id;
489
+ var hasSingleId = !hasBatchIds && singleIdRaw !== undefined && singleIdRaw !== null;
490
+ var normalizedBody = this.normalizeOrderSyncPayload(msg.body || msg.data);
491
+ if (hasBatchIds) {
492
+ var _normalizedBody$order;
493
+ return {
494
+ route: 'httpRefresh.batchIds',
495
+ hasBatchIds: true,
496
+ hasSingleId: false,
497
+ hasNormalizedBody: !!normalizedBody,
498
+ singleId: null,
499
+ batchIds: msg.ids || [],
500
+ bodyOrderId: (_normalizedBody$order = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order !== void 0 ? _normalizedBody$order : null
501
+ };
502
+ }
503
+ if (hasSingleId && normalizedBody) {
504
+ var _normalizedBody$order2;
505
+ return {
506
+ route: 'bodyUpsert',
507
+ hasBatchIds: false,
508
+ hasSingleId: true,
509
+ hasNormalizedBody: true,
510
+ singleId: singleIdRaw,
511
+ batchIds: [],
512
+ bodyOrderId: (_normalizedBody$order2 = normalizedBody.order_id) !== null && _normalizedBody$order2 !== void 0 ? _normalizedBody$order2 : null
513
+ };
514
+ }
515
+ if (hasSingleId) {
516
+ var _normalizedBody$order3;
517
+ return {
518
+ route: 'httpRefresh.singleId',
519
+ hasBatchIds: false,
520
+ hasSingleId: true,
521
+ hasNormalizedBody: !!normalizedBody,
522
+ singleId: singleIdRaw,
523
+ batchIds: [],
524
+ bodyOrderId: (_normalizedBody$order3 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order3 !== void 0 ? _normalizedBody$order3 : null
525
+ };
526
+ }
527
+ if ((_msg$relation_order_i = msg.relation_order_ids) !== null && _msg$relation_order_i !== void 0 && _msg$relation_order_i.length) {
528
+ var _normalizedBody$order4;
529
+ return {
530
+ route: 'httpRefresh.relationIds',
531
+ hasBatchIds: false,
532
+ hasSingleId: false,
533
+ hasNormalizedBody: !!normalizedBody,
534
+ singleId: null,
535
+ batchIds: msg.relation_order_ids,
536
+ bodyOrderId: (_normalizedBody$order4 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order4 !== void 0 ? _normalizedBody$order4 : null
537
+ };
538
+ }
539
+ return {
540
+ route: 'noop',
541
+ hasBatchIds: false,
542
+ hasSingleId: false,
543
+ hasNormalizedBody: !!normalizedBody,
544
+ singleId: null,
545
+ batchIds: [],
546
+ bodyOrderId: (_normalizedBody$order5 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order5 !== void 0 ? _normalizedBody$order5 : null
547
+ };
548
+ }
549
+ }, {
550
+ key: "updateCreateStore",
551
+ value: function updateCreateStore() {
552
+ var appPlugin = this.core.getPlugin('app');
553
+ var app = appPlugin === null || appPlugin === void 0 ? void 0 : appPlugin.getApp();
554
+ if (app) {
555
+ var coreData = app.data.store.getStore().getDataByModel('core');
556
+ if (coreData !== null && coreData !== void 0 && coreData.core) {
557
+ var today = dayjs();
558
+ if (coreData !== null && coreData !== void 0 && coreData.core.operating_day_boundary) {
559
+ var operatingDayBoundary = coreData.core.operating_day_boundary;
560
+ if (operatingDayBoundary.type === 'start_time') {
561
+ var boundaryTime = String(operatingDayBoundary.time || '').trim();
562
+ var boundaryStart = dayjs("".concat(today.format('YYYY-MM-DD'), " ").concat(boundaryTime));
563
+ if (boundaryStart.isValid()) {
564
+ var isAfterBoundary = today.isAfter(boundaryStart);
565
+ var queryStart = isAfterBoundary ? today.startOf('day') : today.subtract(1, 'day').startOf('day');
566
+ var queryEnd = isAfterBoundary ? today.add(1, 'day').endOf('day') : today.endOf('day');
567
+ this.store.createdAtQuery = {
568
+ sales_time_between: [queryStart.format('YYYY-MM-DD HH:mm:ss'), queryEnd.format('YYYY-MM-DD HH:mm:ss')]
569
+ };
570
+ } else {
571
+ // 边界时间异常时回退到自然日,避免 createdAtQuery 为空导致后续查询异常
572
+ this.store.createdAtQuery = {
573
+ sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
574
+ };
575
+ }
576
+ } else {
577
+ this.store.createdAtQuery = {
578
+ sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
579
+ };
580
+ }
581
+ } else {
582
+ // TODO: 这里后续可能需要使用店铺营业时间查询
583
+ this.store.createdAtQuery = {
584
+ sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
585
+ };
586
+ }
587
+ }
588
+ }
589
+ }
590
+ }, {
591
+ key: "getOrderSyncThrottleMs",
592
+ value: function getOrderSyncThrottleMs() {
593
+ var raw = localStorage.getItem(ORDER_SYNC_THROTTLE_MS_STORAGE_KEY);
594
+ if (raw !== null) {
595
+ var parsed = Number(raw);
596
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
597
+ }
598
+ return DEFAULT_ORDER_SYNC_THROTTLE_MS;
599
+ }
182
600
  }, {
183
601
  key: "preload",
184
602
  value: function () {
185
- var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
186
- var orders;
187
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
188
- while (1) switch (_context2.prev = _context2.next) {
603
+ var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
604
+ var _this4 = this;
605
+ var getData;
606
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
607
+ while (1) switch (_context4.prev = _context4.next) {
189
608
  case 0:
190
- _context2.next = 2;
191
- return this.loadOrdersByServer();
609
+ // const hasPulledInCurrentWindow = this.hasPulledOrdersToday()
610
+ // // 仅当缓存属于当前统计窗口时才直接复用,避免跨天/跨营业日窗口继续使用旧数据
611
+ // if (cachedOrders.length > 0 && hasPulledInCurrentWindow) {
612
+ // this.store.list = cloneDeep(cachedOrders)
613
+ // this.syncOrdersMap()
614
+ // this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list)
615
+ // return
616
+ // }
617
+ // if (hasPulledInCurrentWindow) {
618
+ // this.logInfo('当天已完成全量订单拉取,跳过本次全量拉取', {
619
+ // lastFullFetchAt: this.getStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY),
620
+ // })
621
+ // return
622
+ // }
623
+ getData = /*#__PURE__*/function () {
624
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
625
+ var orders;
626
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
627
+ while (1) switch (_context3.prev = _context3.next) {
628
+ case 0:
629
+ _context3.next = 2;
630
+ return _this4.loadOrdersByServer();
631
+ case 2:
632
+ orders = _context3.sent;
633
+ if (!(orders.length === 0)) {
634
+ _context3.next = 5;
635
+ break;
636
+ }
637
+ return _context3.abrupt("return");
638
+ case 5:
639
+ _this4.store.list = cloneDeep(orders);
640
+ _this4.syncOrdersMap();
641
+ _this4.emitOrdersChanged([], 'preload');
642
+ _this4.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
643
+ case 9:
644
+ case "end":
645
+ return _context3.stop();
646
+ }
647
+ }, _callee3);
648
+ }));
649
+ return function getData() {
650
+ return _ref.apply(this, arguments);
651
+ };
652
+ }();
653
+ getData();
192
654
  case 2:
193
- orders = _context2.sent;
194
- if (!(orders.length === 0)) {
195
- _context2.next = 5;
196
- break;
197
- }
198
- return _context2.abrupt("return");
199
- case 5:
200
- this.store.list = cloneDeep(orders);
201
- this.syncOrdersMap();
202
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
203
- case 8:
204
655
  case "end":
205
- return _context2.stop();
656
+ return _context4.stop();
206
657
  }
207
- }, _callee2, this);
658
+ }, _callee4);
208
659
  }));
209
660
  function preload() {
210
661
  return _preload.apply(this, arguments);
@@ -222,72 +673,620 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
222
673
  return this.store.map.get(this.getIdKey(id));
223
674
  }
224
675
 
225
- /** 按 order_id 查询(推荐) */
676
+ /** 按 order_id 查询内存订单。 */
226
677
  }, {
227
678
  key: "getOrderByOrderId",
228
679
  value: function getOrderByOrderId(orderId) {
229
680
  return this.store.map.get(this.getIdKey(orderId));
230
681
  }
682
+ }, {
683
+ key: "getLocalOrderFromMemoryByLookup",
684
+ value: function getLocalOrderFromMemoryByLookup(lookup) {
685
+ var _this5 = this;
686
+ var key = this.getIdKey(lookup);
687
+ var memoryOrderById = this.store.map.get(key);
688
+ if (memoryOrderById) return memoryOrderById;
689
+ var memoryOrder = this.store.list.find(function (order) {
690
+ return _this5.isOrderLookupMatch(order, key);
691
+ });
692
+ return memoryOrder || null;
693
+ }
694
+ }, {
695
+ key: "getLocalOrderByLookup",
696
+ value: function () {
697
+ var _getLocalOrderByLookup = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(lookup) {
698
+ var _this6 = this;
699
+ var key, memoryOrderById, memoryOrder, orders, localOrder;
700
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
701
+ while (1) switch (_context5.prev = _context5.next) {
702
+ case 0:
703
+ key = this.getIdKey(lookup);
704
+ memoryOrderById = this.store.map.get(key);
705
+ if (!memoryOrderById) {
706
+ _context5.next = 4;
707
+ break;
708
+ }
709
+ return _context5.abrupt("return", memoryOrderById);
710
+ case 4:
711
+ memoryOrder = this.store.list.find(function (order) {
712
+ return _this6.isOrderLookupMatch(order, key);
713
+ });
714
+ if (!memoryOrder) {
715
+ _context5.next = 7;
716
+ break;
717
+ }
718
+ return _context5.abrupt("return", memoryOrder);
719
+ case 7:
720
+ _context5.next = 9;
721
+ return this.loadOrdersFromSQLite();
722
+ case 9:
723
+ orders = _context5.sent;
724
+ localOrder = orders.find(function (order) {
725
+ return _this6.isOrderLookupMatch(order, key);
726
+ });
727
+ if (localOrder) {
728
+ _context5.next = 13;
729
+ break;
730
+ }
731
+ return _context5.abrupt("return", null);
732
+ case 13:
733
+ this.store.list = orders.map(function (order) {
734
+ return _this6.normalizeOrderForMemoryList(order);
735
+ });
736
+ this.syncOrdersMap();
737
+ return _context5.abrupt("return", this.normalizeOrderForMemoryList(localOrder));
738
+ case 16:
739
+ case "end":
740
+ return _context5.stop();
741
+ }
742
+ }, _callee5, this);
743
+ }));
744
+ function getLocalOrderByLookup(_x3) {
745
+ return _getLocalOrderByLookup.apply(this, arguments);
746
+ }
747
+ return getLocalOrderByLookup;
748
+ }()
231
749
  }, {
232
750
  key: "loadOrdersByServer",
233
751
  value: function () {
234
- var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
235
- var orderList, data;
236
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
237
- while (1) switch (_context3.prev = _context3.next) {
752
+ var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
753
+ var _this$store,
754
+ _this7 = this;
755
+ var orderList, data, mergedOrders, memoryOrders;
756
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
757
+ while (1) switch (_context6.prev = _context6.next) {
238
758
  case 0:
239
759
  orderList = [];
760
+ this.logInfo('loadOrdersByServer-开始', {
761
+ hasOrderDataSource: !!this.orderDataSource,
762
+ query: ((_this$store = this.store) === null || _this$store === void 0 ? void 0 : _this$store.createdAtQuery) || null
763
+ });
240
764
  if (!this.orderDataSource) {
241
- _context3.next = 13;
765
+ _context6.next = 17;
242
766
  break;
243
767
  }
244
- _context3.prev = 2;
245
- _context3.next = 5;
768
+ _context6.prev = 3;
769
+ _context6.next = 6;
246
770
  return this.orderDataSource.run({
247
- http: {
771
+ sse: {
248
772
  query: this.store.createdAtQuery
249
773
  }
250
774
  });
251
- case 5:
252
- data = _context3.sent;
775
+ case 6:
776
+ data = _context6.sent;
253
777
  orderList = data || [];
778
+ this.logInfo('loadOrdersByServer-SSE拉取成功', {
779
+ count: orderList.length
780
+ });
254
781
  this.markOrderPulledAtNow();
255
- _context3.next = 13;
782
+ this.lastServerFullFetchAtMs = Date.now();
783
+ _context6.next = 17;
256
784
  break;
257
- case 10:
258
- _context3.prev = 10;
259
- _context3.t0 = _context3["catch"](2);
260
- orderList = [];
261
785
  case 13:
262
- _context3.next = 15;
263
- return this.saveOrdersToSQLite(orderList);
264
- case 15:
265
- _context3.next = 17;
266
- return this.core.effects.emit(OrderHooks.onOrdersLoaded, orderList);
786
+ _context6.prev = 13;
787
+ _context6.t0 = _context6["catch"](3);
788
+ this.logInfo('loadOrdersByServer-SSE拉取失败,保持当前内存订单');
789
+ return _context6.abrupt("return", this.store.list);
267
790
  case 17:
268
- return _context3.abrupt("return", orderList);
269
- case 18:
791
+ _context6.next = 19;
792
+ return this.replaceOrdersSnapshotInSQLite(orderList, 'loadOrdersByServer');
793
+ case 19:
794
+ mergedOrders = _context6.sent;
795
+ memoryOrders = mergedOrders.map(function (order) {
796
+ return _this7.normalizeOrderForMemoryList(order);
797
+ });
798
+ this.logInfo('loadOrdersByServer-结束', {
799
+ count: memoryOrders.length
800
+ });
801
+ _context6.next = 24;
802
+ return this.core.effects.emit(OrderHooks.onOrdersLoaded, memoryOrders);
803
+ case 24:
804
+ return _context6.abrupt("return", memoryOrders);
805
+ case 25:
270
806
  case "end":
271
- return _context3.stop();
807
+ return _context6.stop();
272
808
  }
273
- }, _callee3, this, [[2, 10]]);
809
+ }, _callee6, this, [[3, 13]]);
274
810
  }));
275
811
  function loadOrdersByServer() {
276
812
  return _loadOrdersByServer.apply(this, arguments);
277
813
  }
278
814
  return loadOrdersByServer;
279
815
  }()
816
+ /**
817
+ * 静默全量刷新:后台重新拉取全量 SSE 订单数据并更新本地
818
+ * 拿到完整数据后一次性替换 store,触发订单变更与同步完成事件
819
+ * @returns 刷新后的订单列表
820
+ */
821
+ }, {
822
+ key: "silentRefresh",
823
+ value: (function () {
824
+ var _silentRefresh = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
825
+ var startTime, elapsedSinceFullFetch, orders, errorMessage;
826
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
827
+ while (1) switch (_context7.prev = _context7.next) {
828
+ case 0:
829
+ startTime = Date.now();
830
+ elapsedSinceFullFetch = Date.now() - this.lastServerFullFetchAtMs;
831
+ if (!(this.lastServerFullFetchAtMs > 0 && elapsedSinceFullFetch < ORDER_SILENT_REFRESH_MIN_INTERVAL_MS)) {
832
+ _context7.next = 4;
833
+ break;
834
+ }
835
+ return _context7.abrupt("return", this.store.list);
836
+ case 4:
837
+ this.logInfo('silentRefresh 开始');
838
+ _context7.prev = 5;
839
+ // 刷新前,需要更新当前营业日边界(store.createdAtQuery)
840
+ this.updateCreateStore();
841
+ _context7.next = 9;
842
+ return this.loadOrdersByServer();
843
+ case 9:
844
+ orders = _context7.sent;
845
+ if (!(orders.length > 0)) {
846
+ _context7.next = 19;
847
+ break;
848
+ }
849
+ this.store.list = cloneDeep(orders);
850
+ this.syncOrdersMap();
851
+ this.emitOrdersChanged([], 'silentRefresh');
852
+ _context7.next = 16;
853
+ return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
854
+ case 16:
855
+ this.logInfo('silentRefresh 完成', {
856
+ orderCount: orders.length,
857
+ duration: "".concat(Date.now() - startTime, "ms")
858
+ });
859
+ _context7.next = 20;
860
+ break;
861
+ case 19:
862
+ this.logInfo('silentRefresh: 服务器未返回数据');
863
+ case 20:
864
+ return _context7.abrupt("return", this.store.list);
865
+ case 23:
866
+ _context7.prev = 23;
867
+ _context7.t0 = _context7["catch"](5);
868
+ errorMessage = _context7.t0 instanceof Error ? _context7.t0.message : String(_context7.t0);
869
+ this.logError('silentRefresh 失败', {
870
+ duration: "".concat(Date.now() - startTime, "ms"),
871
+ error: errorMessage
872
+ });
873
+ return _context7.abrupt("return", this.store.list);
874
+ case 28:
875
+ case "end":
876
+ return _context7.stop();
877
+ }
878
+ }, _callee7, this, [[5, 23]]);
879
+ }));
880
+ function silentRefresh() {
881
+ return _silentRefresh.apply(this, arguments);
882
+ }
883
+ return silentRefresh;
884
+ }())
280
885
  }, {
281
- key: "getOrdersByResourceId",
282
- value: function getOrdersByResourceId(resourceId) {
283
- var _this2 = this;
284
- var ids = this.resourceIdIndex.get(String(resourceId)) || [];
285
- return ids.map(function (id) {
286
- return _this2.store.map.get(id);
287
- }).filter(function (order) {
288
- return !!order;
886
+ key: "normalizeOrderForMemoryList",
887
+ value: function normalizeOrderForMemoryList(order) {
888
+ var source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'normalizeOrderForMemoryList';
889
+ var normalizedOrder = this.normalizeOrderCollectionsForIngress(order, source);
890
+ var externalSaleNumber = normalizedOrder === null || normalizedOrder === void 0 ? void 0 : normalizedOrder.external_sale_number;
891
+ if ((normalizedOrder === null || normalizedOrder === void 0 ? void 0 : normalizedOrder.order_id) !== undefined && (normalizedOrder === null || normalizedOrder === void 0 ? void 0 : normalizedOrder.order_id) !== null && (normalizedOrder === null || normalizedOrder === void 0 ? void 0 : normalizedOrder.order_id) !== '') {
892
+ return normalizedOrder;
893
+ }
894
+ if (externalSaleNumber === undefined || externalSaleNumber === null || externalSaleNumber === '') {
895
+ return normalizedOrder;
896
+ }
897
+ return _objectSpread(_objectSpread({}, normalizedOrder), {}, {
898
+ order_id: externalSaleNumber
289
899
  });
290
900
  }
901
+
902
+ /**
903
+ * 仅覆盖本地已存在的订单;不存在则直接跳过,不落库、不 emit。
904
+ * 适用于"按 order_id 主动刷新本地订单详情"的代理场景。
905
+ */
906
+ }, {
907
+ key: "overwriteExistingOrder",
908
+ value: (function () {
909
+ var _overwriteExistingOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(fresh) {
910
+ var _this8 = this;
911
+ var orderId, key, normalizedFresh, existingOrder, reconciledFresh;
912
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
913
+ while (1) switch (_context8.prev = _context8.next) {
914
+ case 0:
915
+ orderId = fresh === null || fresh === void 0 ? void 0 : fresh.order_id;
916
+ if (!(orderId === undefined || orderId === null)) {
917
+ _context8.next = 4;
918
+ break;
919
+ }
920
+ this.logError('overwriteExistingOrder-入参缺少 order_id');
921
+ return _context8.abrupt("return", {
922
+ overwritten: false
923
+ });
924
+ case 4:
925
+ key = this.getIdKey(orderId);
926
+ if (this.store.map.has(key)) {
927
+ _context8.next = 8;
928
+ break;
929
+ }
930
+ this.logInfo('overwriteExistingOrder-本地不存在该订单,跳过', {
931
+ orderId: orderId
932
+ });
933
+ return _context8.abrupt("return", {
934
+ overwritten: false
935
+ });
936
+ case 8:
937
+ this.logInfo('overwriteExistingOrder-开始覆盖', {
938
+ orderId: orderId,
939
+ storeOrderCountBefore: this.store.list.length
940
+ });
941
+ normalizedFresh = this.normalizeOrderForMemoryList(fresh, 'overwriteExistingOrder.incoming');
942
+ existingOrder = this.store.map.get(key);
943
+ reconciledFresh = this.reconcileOverwriteOrderCollections(existingOrder, normalizedFresh);
944
+ this.store.list = this.store.list.map(function (order) {
945
+ var id = order === null || order === void 0 ? void 0 : order.order_id;
946
+ if (id === undefined || id === null) {
947
+ return _this8.normalizeOrderForMemoryList(order, 'overwriteExistingOrder.existingMemory');
948
+ }
949
+ return _this8.getIdKey(id) === key ? reconciledFresh : _this8.normalizeOrderForMemoryList(order, 'overwriteExistingOrder.existingMemory');
950
+ });
951
+ this.syncOrdersMap();
952
+ _context8.next = 16;
953
+ return this.updateOrderInSQLite(reconciledFresh, 'overwriteExistingOrder');
954
+ case 16:
955
+ this.logInfo('overwriteExistingOrder-结束', {
956
+ orderId: orderId,
957
+ storeOrderCountAfter: this.store.list.length
958
+ });
959
+ _context8.next = 19;
960
+ return this.emitOrdersChanged([reconciledFresh], 'overwriteExistingOrder');
961
+ case 19:
962
+ return _context8.abrupt("return", {
963
+ overwritten: true
964
+ });
965
+ case 20:
966
+ case "end":
967
+ return _context8.stop();
968
+ }
969
+ }, _callee8, this);
970
+ }));
971
+ function overwriteExistingOrder(_x4) {
972
+ return _overwriteExistingOrder.apply(this, arguments);
973
+ }
974
+ return overwriteExistingOrder;
975
+ }()
976
+ /**
977
+ * 将远端拉取的订单合并进本地 store(已存在则更新,不存在则追加),落库并 emit onOrdersChanged。
978
+ * 供 /update/localOrder 等在「本地尚无该单」时写入新建单。
979
+ */
980
+ )
981
+ }, {
982
+ key: "upsertOrdersFromRemote",
983
+ value: (function () {
984
+ var _upsertOrdersFromRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(freshOrders) {
985
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
986
+ while (1) switch (_context9.prev = _context9.next) {
987
+ case 0:
988
+ if (freshOrders !== null && freshOrders !== void 0 && freshOrders.length) {
989
+ _context9.next = 3;
990
+ break;
991
+ }
992
+ this.logInfo('upsertOrdersFromRemote-订单列表为空', {});
993
+ return _context9.abrupt("return");
994
+ case 3:
995
+ this.logInfo('upsertOrdersFromRemote-开始', {
996
+ count: freshOrders.length
997
+ });
998
+ _context9.next = 6;
999
+ return this.mergeOrdersToStore(freshOrders, 'upsertOrdersFromRemote');
1000
+ case 6:
1001
+ case "end":
1002
+ return _context9.stop();
1003
+ }
1004
+ }, _callee9, this);
1005
+ }));
1006
+ function upsertOrdersFromRemote(_x5) {
1007
+ return _upsertOrdersFromRemote.apply(this, arguments);
1008
+ }
1009
+ return upsertOrdersFromRemote;
1010
+ }())
1011
+ }, {
1012
+ key: "markOrderSyncedByExternalSaleNumber",
1013
+ value: function () {
1014
+ var _markOrderSyncedByExternalSaleNumber = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(params) {
1015
+ var _this9 = this,
1016
+ _existing$external_sa,
1017
+ _nextOrder$order_id;
1018
+ var externalSaleNumber, key, targetIndex, existing, nextOrder, storageKey;
1019
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1020
+ while (1) switch (_context10.prev = _context10.next) {
1021
+ case 0:
1022
+ externalSaleNumber = params.externalSaleNumber;
1023
+ if (!(externalSaleNumber === undefined || externalSaleNumber === null || externalSaleNumber === '')) {
1024
+ _context10.next = 4;
1025
+ break;
1026
+ }
1027
+ this.logError('markOrderSyncedByExternalSaleNumber-缺少 external_sale_number');
1028
+ return _context10.abrupt("return", {
1029
+ updated: false
1030
+ });
1031
+ case 4:
1032
+ key = this.getIdKey(externalSaleNumber);
1033
+ targetIndex = this.store.list.findIndex(function (order) {
1034
+ var value = order === null || order === void 0 ? void 0 : order.external_sale_number;
1035
+ if (value === undefined || value === null || value === '') return false;
1036
+ return _this9.getIdKey(value) === key;
1037
+ });
1038
+ if (!(targetIndex < 0)) {
1039
+ _context10.next = 9;
1040
+ break;
1041
+ }
1042
+ this.logInfo('markOrderSyncedByExternalSaleNumber-本地订单不存在,跳过', {
1043
+ external_sale_number: externalSaleNumber
1044
+ });
1045
+ return _context10.abrupt("return", {
1046
+ updated: false
1047
+ });
1048
+ case 9:
1049
+ existing = this.store.list[targetIndex];
1050
+ nextOrder = this.normalizeRemoteSyncedOrder(_objectSpread(_objectSpread(_objectSpread({}, existing), params.patch || {}), {}, {
1051
+ external_sale_number: (_existing$external_sa = existing.external_sale_number) !== null && _existing$external_sa !== void 0 ? _existing$external_sa : externalSaleNumber,
1052
+ need_sync: 0
1053
+ }));
1054
+ storageKey = this.getOrderStorageKey(nextOrder) || key;
1055
+ this.store.list = this.store.list.map(function (order, index) {
1056
+ if (index !== targetIndex) return order;
1057
+ return nextOrder;
1058
+ });
1059
+ this.syncOrdersMap();
1060
+ _context10.next = 16;
1061
+ return this.patchOrdersInSQLite([nextOrder], 'markOrderSyncedByExternalSaleNumber', _defineProperty({}, storageKey, 'update'));
1062
+ case 16:
1063
+ this.logInfo('markOrderSyncedByExternalSaleNumber-完成', {
1064
+ external_sale_number: externalSaleNumber,
1065
+ order_id: (_nextOrder$order_id = nextOrder.order_id) !== null && _nextOrder$order_id !== void 0 ? _nextOrder$order_id : null
1066
+ });
1067
+ _context10.next = 19;
1068
+ return this.emitOrdersChanged([nextOrder], 'markOrderSyncedByExternalSaleNumber');
1069
+ case 19:
1070
+ return _context10.abrupt("return", {
1071
+ updated: true,
1072
+ order: nextOrder
1073
+ });
1074
+ case 20:
1075
+ case "end":
1076
+ return _context10.stop();
1077
+ }
1078
+ }, _callee10, this);
1079
+ }));
1080
+ function markOrderSyncedByExternalSaleNumber(_x6) {
1081
+ return _markOrderSyncedByExternalSaleNumber.apply(this, arguments);
1082
+ }
1083
+ return markOrderSyncedByExternalSaleNumber;
1084
+ }()
1085
+ /**
1086
+ * 将本地待同步订单按 SQLite storage key 合并进 store 并落库。
1087
+ * checkout 离线兜底可能没有 order_id,但通常会有 external_sale_number。
1088
+ */
1089
+ }, {
1090
+ key: "upsertPendingSyncOrders",
1091
+ value: (function () {
1092
+ var _upsertPendingSyncOrders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(pendingOrders) {
1093
+ var _this10 = this;
1094
+ var pendingMap, memoryPendingMap, _iterator5, _step5, order, normalizedOrder, storageKey, mergeActions, updatedList, identityKeyToIndex, index, _iterator6, _step6, key, _iterator7, _step7, _step7$value, _storageKey, pendingOrder, matchIndex, existingOrder, mergedOrder, pendingSnapshot, insertIndex, patchedOrders;
1095
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1096
+ while (1) switch (_context11.prev = _context11.next) {
1097
+ case 0:
1098
+ if (pendingOrders !== null && pendingOrders !== void 0 && pendingOrders.length) {
1099
+ _context11.next = 3;
1100
+ break;
1101
+ }
1102
+ this.logInfo('upsertPendingSyncOrders-订单列表为空', {});
1103
+ return _context11.abrupt("return");
1104
+ case 3:
1105
+ pendingMap = new Map();
1106
+ memoryPendingMap = new Map();
1107
+ _iterator5 = _createForOfIteratorHelper(pendingOrders);
1108
+ _context11.prev = 6;
1109
+ _iterator5.s();
1110
+ case 8:
1111
+ if ((_step5 = _iterator5.n()).done) {
1112
+ _context11.next = 18;
1113
+ break;
1114
+ }
1115
+ order = _step5.value;
1116
+ normalizedOrder = this.normalizeOrderCollectionsForIngress(order, 'upsertPendingSyncOrders.incoming');
1117
+ storageKey = this.getOrderStorageKey(normalizedOrder);
1118
+ if (storageKey) {
1119
+ _context11.next = 14;
1120
+ break;
1121
+ }
1122
+ return _context11.abrupt("continue", 16);
1123
+ case 14:
1124
+ pendingMap.set(storageKey, normalizedOrder);
1125
+ memoryPendingMap.set(storageKey, this.normalizeOrderForMemoryList(normalizedOrder, 'upsertPendingSyncOrders.memory'));
1126
+ case 16:
1127
+ _context11.next = 8;
1128
+ break;
1129
+ case 18:
1130
+ _context11.next = 23;
1131
+ break;
1132
+ case 20:
1133
+ _context11.prev = 20;
1134
+ _context11.t0 = _context11["catch"](6);
1135
+ _iterator5.e(_context11.t0);
1136
+ case 23:
1137
+ _context11.prev = 23;
1138
+ _iterator5.f();
1139
+ return _context11.finish(23);
1140
+ case 26:
1141
+ if (!(pendingMap.size === 0)) {
1142
+ _context11.next = 29;
1143
+ break;
1144
+ }
1145
+ this.logError('upsertPendingSyncOrders-订单缺少可落库标识', {
1146
+ count: pendingOrders.length
1147
+ });
1148
+ return _context11.abrupt("return");
1149
+ case 29:
1150
+ this.logInfo('upsertPendingSyncOrders-开始', {
1151
+ count: pendingMap.size
1152
+ });
1153
+ mergeActions = {};
1154
+ updatedList = this.store.list.map(function (order) {
1155
+ return _this10.normalizeOrderForMemoryList(order, 'upsertPendingSyncOrders.existingMemory');
1156
+ }); // 与 mergeOrdersToStore 一致:基于身份键(field:value)建立索引,把「查找已存在订单」
1157
+ // 从 O(n) 线性扫描降为 O(1),整体复杂度由 O(n^2) 降为 O(n + m)。
1158
+ identityKeyToIndex = new Map();
1159
+ for (index = 0; index < updatedList.length; index += 1) {
1160
+ _iterator6 = _createForOfIteratorHelper(this.getOrderIdentityMatchKeys(updatedList[index]));
1161
+ try {
1162
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1163
+ key = _step6.value;
1164
+ // 同一 key 命中多张时保留最靠前的下标,与原 findIndex「取首个匹配」一致
1165
+ if (!identityKeyToIndex.has(key)) identityKeyToIndex.set(key, index);
1166
+ }
1167
+ } catch (err) {
1168
+ _iterator6.e(err);
1169
+ } finally {
1170
+ _iterator6.f();
1171
+ }
1172
+ }
1173
+ _iterator7 = _createForOfIteratorHelper(memoryPendingMap.entries());
1174
+ _context11.prev = 35;
1175
+ _iterator7.s();
1176
+ case 37:
1177
+ if ((_step7 = _iterator7.n()).done) {
1178
+ _context11.next = 55;
1179
+ break;
1180
+ }
1181
+ _step7$value = _slicedToArray(_step7.value, 2), _storageKey = _step7$value[0], pendingOrder = _step7$value[1];
1182
+ matchIndex = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, this.getOrderIdentityMatchKeys(pendingOrder));
1183
+ if (!(matchIndex >= 0)) {
1184
+ _context11.next = 49;
1185
+ break;
1186
+ }
1187
+ existingOrder = updatedList[matchIndex];
1188
+ mergedOrder = this.mergeOrderRecords(existingOrder, pendingOrder);
1189
+ updatedList[matchIndex] = mergedOrder;
1190
+ pendingSnapshot = pendingMap.get(_storageKey);
1191
+ if (pendingSnapshot) {
1192
+ pendingMap.set(_storageKey, this.reconcileOverwriteOrderCollections(existingOrder, pendingSnapshot));
1193
+ }
1194
+ // 合并后身份字段可能新增(如挂单拿到 order_id),同步登记,供同批后续 pending 命中同一槽位
1195
+ this.registerOrderIdentityKeys(identityKeyToIndex, mergedOrder, matchIndex);
1196
+ mergeActions[_storageKey] = 'update';
1197
+ return _context11.abrupt("continue", 53);
1198
+ case 49:
1199
+ insertIndex = updatedList.length;
1200
+ updatedList.push(pendingOrder);
1201
+ this.registerOrderIdentityKeys(identityKeyToIndex, pendingOrder, insertIndex);
1202
+ mergeActions[_storageKey] = 'insert';
1203
+ case 53:
1204
+ _context11.next = 37;
1205
+ break;
1206
+ case 55:
1207
+ _context11.next = 60;
1208
+ break;
1209
+ case 57:
1210
+ _context11.prev = 57;
1211
+ _context11.t1 = _context11["catch"](35);
1212
+ _iterator7.e(_context11.t1);
1213
+ case 60:
1214
+ _context11.prev = 60;
1215
+ _iterator7.f();
1216
+ return _context11.finish(60);
1217
+ case 63:
1218
+ patchedOrders = _toConsumableArray(pendingMap.values()); // 增量索引已保证 store 去重不变量,无需再对全表做 O(n^2) 压缩;仅自检开关开启时兜底。
1219
+ this.store.list = this.runOrderStoreSelfCheck(updatedList, 'upsertPendingSyncOrders.store');
1220
+ this.syncOrdersMap();
1221
+ _context11.next = 68;
1222
+ return this.patchOrdersInSQLite(patchedOrders, 'upsertPendingSyncOrders', mergeActions);
1223
+ case 68:
1224
+ this.logInfo('upsertPendingSyncOrders-结束', {
1225
+ count: patchedOrders.length,
1226
+ storeOrderCountAfter: this.store.list.length
1227
+ });
1228
+ _context11.next = 71;
1229
+ return this.emitOrdersChanged(patchedOrders, 'upsertPendingSyncOrders');
1230
+ case 71:
1231
+ case "end":
1232
+ return _context11.stop();
1233
+ }
1234
+ }, _callee11, this, [[6, 20, 23, 26], [35, 57, 60, 63]]);
1235
+ }));
1236
+ function upsertPendingSyncOrders(_x7) {
1237
+ return _upsertPendingSyncOrders.apply(this, arguments);
1238
+ }
1239
+ return upsertPendingSyncOrders;
1240
+ }()
1241
+ /**
1242
+ * 通过 SSE 按自定义 query 拉取订单(支持 select/with 精简字段)
1243
+ */
1244
+ )
1245
+ }, {
1246
+ key: "fetchOrdersBySSE",
1247
+ value: (function () {
1248
+ var _fetchOrdersBySSE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1249
+ var query,
1250
+ data,
1251
+ _args12 = arguments;
1252
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1253
+ while (1) switch (_context12.prev = _context12.next) {
1254
+ case 0:
1255
+ query = _args12.length > 0 && _args12[0] !== undefined ? _args12[0] : {};
1256
+ if (this.orderDataSource) {
1257
+ _context12.next = 3;
1258
+ break;
1259
+ }
1260
+ return _context12.abrupt("return", []);
1261
+ case 3:
1262
+ _context12.prev = 3;
1263
+ _context12.next = 6;
1264
+ return this.orderDataSource.run({
1265
+ sse: {
1266
+ query: query
1267
+ }
1268
+ });
1269
+ case 6:
1270
+ data = _context12.sent;
1271
+ return _context12.abrupt("return", data || []);
1272
+ case 10:
1273
+ _context12.prev = 10;
1274
+ _context12.t0 = _context12["catch"](3);
1275
+ this.logError('fetchOrdersBySSE-失败', {
1276
+ error: _context12.t0 instanceof Error ? _context12.t0.message : String(_context12.t0)
1277
+ });
1278
+ return _context12.abrupt("return", []);
1279
+ case 14:
1280
+ case "end":
1281
+ return _context12.stop();
1282
+ }
1283
+ }, _callee12, this, [[3, 10]]);
1284
+ }));
1285
+ function fetchOrdersBySSE() {
1286
+ return _fetchOrdersBySSE.apply(this, arguments);
1287
+ }
1288
+ return fetchOrdersBySSE;
1289
+ }())
291
1290
  }, {
292
1291
  key: "getRoutes",
293
1292
  value: function getRoutes() {
@@ -301,6 +1300,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
301
1300
  clearTimeout(this.syncTimer);
302
1301
  this.syncTimer = undefined;
303
1302
  }
1303
+ this.isProcessingSyncBatch = false;
304
1304
  this.pendingSyncMessages = [];
305
1305
  if ((_this$orderDataSource = this.orderDataSource) !== null && _this$orderDataSource !== void 0 && _this$orderDataSource.destroy) this.orderDataSource.destroy();
306
1306
  _get(_getPrototypeOf(OrderModule.prototype), "destroy", this).call(this);
@@ -308,72 +1308,104 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
308
1308
  }, {
309
1309
  key: "syncOrdersMap",
310
1310
  value: function syncOrdersMap() {
311
- var _this3 = this;
312
1311
  this.store.map.clear();
313
- this.resourceIdIndex.clear();
314
- var _iterator = _createForOfIteratorHelper(this.store.list),
315
- _step;
1312
+ var _iterator8 = _createForOfIteratorHelper(this.store.list),
1313
+ _step8;
316
1314
  try {
317
- var _loop = function _loop() {
318
- var order = _step.value;
319
- var id = order.order_id;
320
- if (id === undefined || id === null) return 1; // continue
321
- _this3.store.map.set(_this3.getIdKey(id), order);
322
- var resourceIds = _this3.extractResourceIds(order);
323
- var _iterator2 = _createForOfIteratorHelper(resourceIds),
324
- _step2;
325
- try {
326
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
327
- var resourceId = _step2.value;
328
- var key = String(resourceId);
329
- var existing = _this3.resourceIdIndex.get(key) || [];
330
- if (existing.some(function (eid) {
331
- return _this3.getIdKey(eid) === _this3.getIdKey(id);
332
- })) continue;
333
- existing.push(id);
334
- _this3.resourceIdIndex.set(key, existing);
335
- }
336
- } catch (err) {
337
- _iterator2.e(err);
338
- } finally {
339
- _iterator2.f();
340
- }
341
- };
342
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
343
- if (_loop()) continue;
1315
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1316
+ var order = _step8.value;
1317
+ var primaryIdentity = this.getOrderMapKey(order);
1318
+ if (!primaryIdentity) continue;
1319
+ this.store.map.set(primaryIdentity, order);
344
1320
  }
345
1321
  } catch (err) {
346
- _iterator.e(err);
1322
+ _iterator8.e(err);
347
1323
  } finally {
348
- _iterator.f();
1324
+ _iterator8.f();
349
1325
  }
350
1326
  }
351
1327
  }, {
352
- key: "extractResourceIds",
353
- value: function extractResourceIds(order) {
354
- var ids = new Set();
355
- var visitResources = function visitResources(resources) {
356
- if (!Array.isArray(resources)) return;
357
- resources.forEach(function (resource) {
358
- var rid = resource === null || resource === void 0 ? void 0 : resource.relation_id;
359
- if (rid !== undefined && rid !== null && rid !== '') ids.add(String(rid));
360
- if (Array.isArray(resource === null || resource === void 0 ? void 0 : resource.children)) visitResources(resource.children);
361
- });
362
- };
363
- if (Array.isArray(order === null || order === void 0 ? void 0 : order.bookings)) {
364
- order.bookings.forEach(function (booking) {
365
- return visitResources((booking === null || booking === void 0 ? void 0 : booking.resources) || []);
366
- });
1328
+ key: "getOrderMapKey",
1329
+ value: function getOrderMapKey(order) {
1330
+ if (!order) return '';
1331
+ if (!this.isBlankIdentityValue(order.order_id)) {
1332
+ return this.getIdKey(order.order_id);
367
1333
  }
368
- return _toConsumableArray(ids);
1334
+ var externalSaleNumber = order.external_sale_number;
1335
+ if (!this.isBlankIdentityValue(externalSaleNumber)) {
1336
+ return this.getIdKey(externalSaleNumber);
1337
+ }
1338
+ return '';
1339
+ }
1340
+ }, {
1341
+ key: "isBlankIdentityValue",
1342
+ value: function isBlankIdentityValue(value) {
1343
+ return value === undefined || value === null || value === '';
1344
+ }
1345
+ }, {
1346
+ key: "getOrderIdentityEntries",
1347
+ value: function getOrderIdentityEntries(order) {
1348
+ var _this11 = this;
1349
+ if (!order) return [];
1350
+ var record = order;
1351
+ var candidates = [{
1352
+ field: 'order_id',
1353
+ value: order.order_id
1354
+ }, {
1355
+ field: 'external_sale_number',
1356
+ value: record.external_sale_number
1357
+ }, {
1358
+ field: 'order_number',
1359
+ value: record.order_number
1360
+ }, {
1361
+ field: 'shop_order_number',
1362
+ value: record.shop_order_number
1363
+ }];
1364
+ var entries = [];
1365
+ var _loop = function _loop() {
1366
+ var candidate = _candidates[_i2];
1367
+ if (_this11.isBlankIdentityValue(candidate.value)) return 0; // continue
1368
+ var key = _this11.getIdKey(candidate.value);
1369
+ if (entries.some(function (entry) {
1370
+ return entry.field === candidate.field && entry.key === key;
1371
+ })) return 0; // continue
1372
+ entries.push({
1373
+ field: candidate.field,
1374
+ key: key
1375
+ });
1376
+ },
1377
+ _ret;
1378
+ for (var _i2 = 0, _candidates = candidates; _i2 < _candidates.length; _i2++) {
1379
+ _ret = _loop();
1380
+ if (_ret === 0) continue;
1381
+ }
1382
+ return entries;
1383
+ }
1384
+ }, {
1385
+ key: "getOrderIdentityKeys",
1386
+ value: function getOrderIdentityKeys(order) {
1387
+ var keys = [];
1388
+ var _iterator9 = _createForOfIteratorHelper(this.getOrderIdentityEntries(order)),
1389
+ _step9;
1390
+ try {
1391
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1392
+ var entry = _step9.value;
1393
+ if (!keys.includes(entry.key)) keys.push(entry.key);
1394
+ }
1395
+ } catch (err) {
1396
+ _iterator9.e(err);
1397
+ } finally {
1398
+ _iterator9.f();
1399
+ }
1400
+ return keys;
369
1401
  }
370
1402
  }, {
371
1403
  key: "getOrderDateKey",
372
1404
  value: function getOrderDateKey(order) {
373
1405
  var _order$bookings, _order$bookings2;
374
1406
  var candidates = [order === null || order === void 0 ? void 0 : order.schedule_date, order === null || order === void 0 ? void 0 : order.create_date, order === null || order === void 0 ? void 0 : order.created_at, order === null || order === void 0 || (_order$bookings = order.bookings) === null || _order$bookings === void 0 || (_order$bookings = _order$bookings[0]) === null || _order$bookings === void 0 ? void 0 : _order$bookings.start_date, order === null || order === void 0 || (_order$bookings2 = order.bookings) === null || _order$bookings2 === void 0 || (_order$bookings2 = _order$bookings2[0]) === null || _order$bookings2 === void 0 ? void 0 : _order$bookings2.select_date];
375
- for (var _i = 0, _candidates = candidates; _i < _candidates.length; _i++) {
376
- var v = _candidates[_i];
1407
+ for (var _i3 = 0, _candidates2 = candidates; _i3 < _candidates2.length; _i3++) {
1408
+ var v = _candidates2[_i3];
377
1409
  if (!v) continue;
378
1410
  var text = String(v);
379
1411
  if (!text) continue;
@@ -395,137 +1427,225 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
395
1427
  }
396
1428
 
397
1429
  /**
398
- * 初始化 pubsub 订阅,监听订单变更
1430
+ * 初始化 pubsub 订阅,监听订单变更(纯订阅,不拉数据;全量 SSE 由 loadOrdersByServer 负责)
399
1431
  */
400
1432
  }, {
401
1433
  key: "setupOrderSync",
402
1434
  value: function setupOrderSync() {
403
- var _this4 = this;
1435
+ var _this12 = this;
404
1436
  if (!this.orderDataSource) return;
405
- var shouldSkipHttpPull = this.hasPulledOrdersToday();
406
- var syncPayload = {
1437
+ this.orderDataSource.run({
407
1438
  pubsub: {
408
1439
  callback: function callback(res) {
409
- var message = _this4.normalizeOrderSyncMessage(res);
1440
+ var _message$id, _message$order_id, _message$type;
1441
+ var pubsubReceivedAt = Date.now();
1442
+ var message = _this12.normalizeOrderSyncMessage(res);
410
1443
  if (!message) return;
411
- _this4.pendingSyncMessages.push(message);
412
- if (_this4.syncTimer) clearTimeout(_this4.syncTimer);
413
- _this4.syncTimer = setTimeout(function () {
414
- _this4.processOrderSyncMessages();
415
- }, _this4.ORDER_SYNC_DEBOUNCE_MS);
1444
+ message._pubsubReceivedAt = pubsubReceivedAt;
1445
+ _this12.pendingSyncMessages.push(message);
1446
+ var throttleMs = _this12.getOrderSyncThrottleMs();
1447
+ var routeInfo = _this12.resolveSyncMessageRoute(message);
1448
+ _this12.logInfo('orderSync-收到消息并入队', {
1449
+ id: (_message$id = message.id) !== null && _message$id !== void 0 ? _message$id : null,
1450
+ order_id: (_message$order_id = message.order_id) !== null && _message$order_id !== void 0 ? _message$order_id : null,
1451
+ type: (_message$type = message.type) !== null && _message$type !== void 0 ? _message$type : null,
1452
+ pendingCount: _this12.pendingSyncMessages.length,
1453
+ throttleMs: throttleMs,
1454
+ pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString(),
1455
+ fullMessage: JSON.stringify(message)
1456
+ });
1457
+ _this12.scheduleOrderSyncThrottle();
416
1458
  }
417
1459
  }
418
- };
419
- syncPayload.http = {
420
- query: this.store.createdAtQuery,
421
- skipHttp: shouldSkipHttpPull
422
- };
423
- this.orderDataSource.run(syncPayload).then(function () {
424
- if (!shouldSkipHttpPull) _this4.markOrderPulledAtNow();
425
1460
  }).catch(function () {
426
1461
  // 忽略同步初始化异常,避免影响主流程
427
1462
  });
428
1463
  }
429
1464
 
430
1465
  /**
431
- * 处理防抖后的同步消息批次
1466
+ * 调度订单同步节流窗口(leading-edge throttle):
1467
+ * - 空闲状态下收到的第一条消息立即触发批处理,无需等待;
1468
+ * - 首条处理后进入冷却窗口,窗口期间的后续消息聚合,窗口结束后批量处理;
1469
+ * - 若当前批处理执行中,则由批处理结束后决定是否开启下一轮窗口。
1470
+ */
1471
+ }, {
1472
+ key: "scheduleOrderSyncThrottle",
1473
+ value: function scheduleOrderSyncThrottle() {
1474
+ var _this13 = this;
1475
+ if (this.isProcessingSyncBatch) return;
1476
+ if (this.isIdlePhase) {
1477
+ this.isIdlePhase = false;
1478
+ this.logInfo('orderSync-首条消息立即触发处理');
1479
+ void this.flushOrderSyncMessagesByThrottle();
1480
+ return;
1481
+ }
1482
+ if (this.syncTimer) return;
1483
+ var throttleMs = this.getOrderSyncThrottleMs();
1484
+ this.syncTimer = setTimeout(function () {
1485
+ _this13.syncTimer = undefined;
1486
+ void _this13.flushOrderSyncMessagesByThrottle();
1487
+ }, throttleMs);
1488
+ }
1489
+
1490
+ /**
1491
+ * 执行一次节流批处理并在需要时续约下一轮窗口。
1492
+ * 批处理完成且无后续消息时恢复空闲状态,下一条消息将立即触发。
1493
+ */
1494
+ }, {
1495
+ key: "flushOrderSyncMessagesByThrottle",
1496
+ value: (function () {
1497
+ var _flushOrderSyncMessagesByThrottle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
1498
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1499
+ while (1) switch (_context13.prev = _context13.next) {
1500
+ case 0:
1501
+ if (!this.isProcessingSyncBatch) {
1502
+ _context13.next = 2;
1503
+ break;
1504
+ }
1505
+ return _context13.abrupt("return");
1506
+ case 2:
1507
+ if (!(this.pendingSyncMessages.length === 0)) {
1508
+ _context13.next = 5;
1509
+ break;
1510
+ }
1511
+ this.isIdlePhase = true;
1512
+ return _context13.abrupt("return");
1513
+ case 5:
1514
+ this.isProcessingSyncBatch = true;
1515
+ _context13.prev = 6;
1516
+ _context13.next = 9;
1517
+ return this.processOrderSyncMessages();
1518
+ case 9:
1519
+ _context13.prev = 9;
1520
+ this.isProcessingSyncBatch = false;
1521
+ if (this.pendingSyncMessages.length > 0) {
1522
+ this.scheduleOrderSyncThrottle();
1523
+ } else {
1524
+ this.isIdlePhase = true;
1525
+ }
1526
+ return _context13.finish(9);
1527
+ case 13:
1528
+ case "end":
1529
+ return _context13.stop();
1530
+ }
1531
+ }, _callee13, this, [[6,, 9, 13]]);
1532
+ }));
1533
+ function flushOrderSyncMessagesByThrottle() {
1534
+ return _flushOrderSyncMessagesByThrottle.apply(this, arguments);
1535
+ }
1536
+ return flushOrderSyncMessagesByThrottle;
1537
+ }()
1538
+ /**
1539
+ * 处理节流窗口内聚合后的同步消息批次
432
1540
  *
433
1541
  * 后端统一发送 change 消息,不再区分新增/编辑/删除。
434
1542
  * - 单条(id/order_id):若携带 body/data 则直接 upsert 到本地
435
1543
  * - 批量(ids):通过 HTTP 按 ids 增量拉取,再 merge 到本地
1544
+ *
1545
+ * @example
1546
+ * // pending 队列中存在 8 条消息时,仅处理一次批次并统一 merge
1547
+ * await this.processOrderSyncMessages()
436
1548
  */
1549
+ )
437
1550
  }, {
438
1551
  key: "processOrderSyncMessages",
439
1552
  value: (function () {
440
- var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
441
- var messages, upsertOrders, refreshIds, _iterator3, _step3, _msg$id, _msg$relation_order_i, msg, hasBatchIds, singleId, hasSingleId, rawBody, normalizedBody, uniqueRefreshIds, upsertList, freshOrders;
442
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
443
- while (1) switch (_context4.prev = _context4.next) {
1553
+ var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
1554
+ var _this14 = this;
1555
+ var messages, batchProcessStartAt, earliestReceivedAt, upsertOrders, refreshIds, uniqueRefreshIds, upsertList, _this$filterRedundant, toFetch, skipped, freshOrders, batchProcessEndAt;
1556
+ return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1557
+ while (1) switch (_context14.prev = _context14.next) {
444
1558
  case 0:
445
1559
  messages = _toConsumableArray(this.pendingSyncMessages);
446
1560
  this.pendingSyncMessages = [];
447
1561
  if (!(messages.length === 0)) {
448
- _context4.next = 4;
1562
+ _context14.next = 4;
449
1563
  break;
450
1564
  }
451
- return _context4.abrupt("return");
1565
+ return _context14.abrupt("return");
452
1566
  case 4:
1567
+ batchProcessStartAt = Date.now();
1568
+ earliestReceivedAt = Math.min.apply(Math, _toConsumableArray(messages.map(function (m) {
1569
+ var _m$_pubsubReceivedAt;
1570
+ return (_m$_pubsubReceivedAt = m._pubsubReceivedAt) !== null && _m$_pubsubReceivedAt !== void 0 ? _m$_pubsubReceivedAt : batchProcessStartAt;
1571
+ })));
1572
+ this.logInfo('processOrderSyncMessages-开始', {
1573
+ messageCount: messages.length,
1574
+ earliestReceivedAt: new Date(earliestReceivedAt).toISOString(),
1575
+ batchProcessStartAt: new Date(batchProcessStartAt).toISOString(),
1576
+ waitDurationMs: batchProcessStartAt - earliestReceivedAt
1577
+ });
453
1578
  upsertOrders = new Map();
454
1579
  refreshIds = [];
455
- _iterator3 = _createForOfIteratorHelper(messages);
456
- _context4.prev = 7;
457
- _iterator3.s();
458
- case 9:
459
- if ((_step3 = _iterator3.n()).done) {
460
- _context4.next = 22;
461
- break;
462
- }
463
- msg = _step3.value;
464
- hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
465
- singleId = (_msg$id = msg.id) !== null && _msg$id !== void 0 ? _msg$id : msg.order_id;
466
- hasSingleId = !hasBatchIds && singleId !== undefined && singleId !== null;
467
- rawBody = msg.body || msg.data;
468
- normalizedBody = this.normalizeOrderSyncPayload(rawBody);
469
- if (!(hasSingleId && normalizedBody)) {
470
- _context4.next = 19;
471
- break;
472
- }
473
- upsertOrders.set(this.getIdKey(normalizedBody.order_id), normalizedBody);
474
- return _context4.abrupt("continue", 20);
475
- case 19:
476
- if (hasBatchIds) refreshIds.push.apply(refreshIds, _toConsumableArray(msg.ids));else if (hasSingleId) refreshIds.push(singleId);else if ((_msg$relation_order_i = msg.relation_order_ids) !== null && _msg$relation_order_i !== void 0 && _msg$relation_order_i.length) refreshIds.push.apply(refreshIds, _toConsumableArray(msg.relation_order_ids));
477
- case 20:
478
- _context4.next = 9;
479
- break;
480
- case 22:
481
- _context4.next = 27;
482
- break;
483
- case 24:
484
- _context4.prev = 24;
485
- _context4.t0 = _context4["catch"](7);
486
- _iterator3.e(_context4.t0);
487
- case 27:
488
- _context4.prev = 27;
489
- _iterator3.f();
490
- return _context4.finish(27);
491
- case 30:
1580
+ messages.forEach(function (msg, msgIndex) {
1581
+ var routeInfo = _this14.resolveSyncMessageRoute(msg);
1582
+ var hasBatchIds = routeInfo.hasBatchIds;
1583
+ var singleId = routeInfo.singleId;
1584
+ var hasSingleId = routeInfo.hasSingleId;
1585
+ var normalizedBody = _this14.normalizeOrderSyncPayload(msg.body || msg.data);
1586
+ if (routeInfo.route === 'bodyUpsert' && normalizedBody) {
1587
+ upsertOrders.set(_this14.getIdKey(normalizedBody.order_id), normalizedBody);
1588
+ return;
1589
+ }
1590
+ if (hasBatchIds) refreshIds.push.apply(refreshIds, _toConsumableArray(routeInfo.batchIds));else if (routeInfo.route === 'httpRefresh.singleId' && singleId !== null) refreshIds.push(singleId);else if (routeInfo.route === 'httpRefresh.relationIds') refreshIds.push.apply(refreshIds, _toConsumableArray(routeInfo.batchIds));
1591
+ });
492
1592
  uniqueRefreshIds = this.uniqueOrderIds(refreshIds);
493
1593
  upsertList = _toConsumableArray(upsertOrders.values());
1594
+ this.logInfo('processOrderSyncMessages-去重完成', {
1595
+ upsertCount: upsertList.length,
1596
+ refreshIdCount: uniqueRefreshIds.length
1597
+ });
494
1598
  if (!(upsertList.length > 0)) {
495
- _context4.next = 35;
1599
+ _context14.next = 16;
496
1600
  break;
497
1601
  }
498
- _context4.next = 35;
499
- return this.mergeOrdersToStore(upsertList);
500
- case 35:
1602
+ _context14.next = 16;
1603
+ return this.mergeOrdersToStore(upsertList, 'pubsub.bodyUpsert');
1604
+ case 16:
501
1605
  if (!(uniqueRefreshIds.length > 0)) {
502
- _context4.next = 42;
1606
+ _context14.next = 28;
503
1607
  break;
504
1608
  }
505
- _context4.next = 38;
506
- return this.fetchOrdersByHttp(uniqueRefreshIds);
507
- case 38:
508
- freshOrders = _context4.sent;
1609
+ _this$filterRedundant = this.filterRedundantHttpRefreshIds(uniqueRefreshIds), toFetch = _this$filterRedundant.toFetch, skipped = _this$filterRedundant.skipped;
1610
+ if (skipped.length > 0) {}
1611
+ if (!(toFetch.length > 0)) {
1612
+ _context14.next = 28;
1613
+ break;
1614
+ }
1615
+ _context14.next = 22;
1616
+ return this.fetchOrdersByHttp(toFetch);
1617
+ case 22:
1618
+ freshOrders = _context14.sent;
509
1619
  if (!(freshOrders.length > 0)) {
510
- _context4.next = 42;
1620
+ _context14.next = 28;
511
1621
  break;
512
1622
  }
513
- _context4.next = 42;
514
- return this.mergeOrdersToStore(freshOrders);
515
- case 42:
1623
+ _context14.next = 26;
1624
+ return this.mergeOrdersToStore(freshOrders, 'pubsub.httpRefresh');
1625
+ case 26:
1626
+ _context14.next = 28;
1627
+ break;
1628
+ case 28:
516
1629
  if (!(upsertList.length === 0 && uniqueRefreshIds.length === 0)) {
517
- _context4.next = 44;
1630
+ _context14.next = 30;
518
1631
  break;
519
1632
  }
520
- return _context4.abrupt("return");
521
- case 44:
522
- _context4.next = 46;
1633
+ return _context14.abrupt("return");
1634
+ case 30:
1635
+ batchProcessEndAt = Date.now();
1636
+ this.logInfo('processOrderSyncMessages-结束', {
1637
+ upsertCount: upsertList.length,
1638
+ refreshIdCount: uniqueRefreshIds.length,
1639
+ batchProcessDurationMs: batchProcessEndAt - batchProcessStartAt,
1640
+ totalFromPubsubToProcessedMs: batchProcessEndAt - earliestReceivedAt
1641
+ });
1642
+ _context14.next = 34;
523
1643
  return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
524
- case 46:
1644
+ case 34:
525
1645
  case "end":
526
- return _context4.stop();
1646
+ return _context14.stop();
527
1647
  }
528
- }, _callee4, this, [[7, 24, 27, 30]]);
1648
+ }, _callee14, this);
529
1649
  }));
530
1650
  function processOrderSyncMessages() {
531
1651
  return _processOrderSyncMessages.apply(this, arguments);
@@ -533,35 +1653,42 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
533
1653
  return processOrderSyncMessages;
534
1654
  }()
535
1655
  /**
536
- * 通过 HTTP 按 ids 增量拉取订单
1656
+ * 通过 HTTP 按 ids 批量拉取订单详情(走 orderDataSource)。
1657
+ *
1658
+ * - 优先使用 `orderDataSource.fetchOrdersByIds`(如适配器实现了该方法)
1659
+ * - 否则回退到 `orderDataSource.run({ http: { query: { ids } } })`
1660
+ * - 失败统一返回空数组(由调用方按"返回缺失的 id" 判断单笔失败)
1661
+ *
1662
+ * @example
1663
+ * const fresh = await orderModule.fetchOrdersByHttp(['96971', '96972'])
537
1664
  */
538
1665
  )
539
1666
  }, {
540
1667
  key: "fetchOrdersByHttp",
541
1668
  value: (function () {
542
- var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(ids) {
543
- var _orderList, orderList;
544
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
545
- while (1) switch (_context5.prev = _context5.next) {
1669
+ var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(ids) {
1670
+ var _orderList, orderList;
1671
+ return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1672
+ while (1) switch (_context15.prev = _context15.next) {
546
1673
  case 0:
547
1674
  if (!(!this.orderDataSource || ids.length === 0)) {
548
- _context5.next = 2;
1675
+ _context15.next = 2;
549
1676
  break;
550
1677
  }
551
- return _context5.abrupt("return", []);
1678
+ return _context15.abrupt("return", []);
552
1679
  case 2:
553
- _context5.prev = 2;
1680
+ _context15.prev = 2;
554
1681
  if (!(typeof this.orderDataSource.fetchOrdersByIds === 'function')) {
555
- _context5.next = 8;
1682
+ _context15.next = 8;
556
1683
  break;
557
1684
  }
558
- _context5.next = 6;
1685
+ _context15.next = 6;
559
1686
  return this.orderDataSource.fetchOrdersByIds(ids);
560
1687
  case 6:
561
- _orderList = _context5.sent;
562
- return _context5.abrupt("return", _orderList || []);
1688
+ _orderList = _context15.sent;
1689
+ return _context15.abrupt("return", _orderList || []);
563
1690
  case 8:
564
- _context5.next = 10;
1691
+ _context15.next = 10;
565
1692
  return this.orderDataSource.run({
566
1693
  http: {
567
1694
  query: {
@@ -570,19 +1697,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
570
1697
  }
571
1698
  });
572
1699
  case 10:
573
- orderList = _context5.sent;
574
- return _context5.abrupt("return", orderList || []);
1700
+ orderList = _context15.sent;
1701
+ return _context15.abrupt("return", orderList || []);
575
1702
  case 14:
576
- _context5.prev = 14;
577
- _context5.t0 = _context5["catch"](2);
578
- return _context5.abrupt("return", []);
1703
+ _context15.prev = 14;
1704
+ _context15.t0 = _context15["catch"](2);
1705
+ return _context15.abrupt("return", []);
579
1706
  case 17:
580
1707
  case "end":
581
- return _context5.stop();
1708
+ return _context15.stop();
582
1709
  }
583
- }, _callee5, this, [[2, 14]]);
1710
+ }, _callee15, this, [[2, 14]]);
584
1711
  }));
585
- function fetchOrdersByHttp(_x3) {
1712
+ function fetchOrdersByHttp(_x8) {
586
1713
  return _fetchOrdersByHttp.apply(this, arguments);
587
1714
  }
588
1715
  return fetchOrdersByHttp;
@@ -594,82 +1721,256 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
594
1721
  }, {
595
1722
  key: "mergeOrdersToStore",
596
1723
  value: (function () {
597
- var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(freshOrders) {
598
- var _this5 = this;
599
- var freshMap, _iterator4, _step4, order, id, updatedList, _iterator5, _step5, _order;
600
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
601
- while (1) switch (_context6.prev = _context6.next) {
1724
+ var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(freshOrders, source) {
1725
+ var _this15 = this;
1726
+ var storeOrderCountBefore, normalizedFreshOrders, _iterator10, _step10, order, id, uniqueFreshOrders, uniqueFreshCount, patchedOrders, mergeActions, updatedList, identityKeyToIndex, index, identityKeys, _iterator11, _step11, key, _iterator12, _step12, fresh, freshIdentityKeys, matchIndex, storageKey, mergeKey, existingOrder, _ref2, _existingOrder$order_, _ref3, _external_sale_number2, _existingOrder$paymen, _fresh$payment_status, _existingOrder$need_s, _fresh$need_sync, mergedOrder, insertIndex, insertCount, updateCount;
1727
+ return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1728
+ while (1) switch (_context16.prev = _context16.next) {
602
1729
  case 0:
603
- freshMap = new Map();
604
- _iterator4 = _createForOfIteratorHelper(freshOrders);
605
- _context6.prev = 2;
606
- _iterator4.s();
607
- case 4:
608
- if ((_step4 = _iterator4.n()).done) {
609
- _context6.next = 12;
1730
+ storeOrderCountBefore = this.store.list.length;
1731
+ this.logInfo('mergeOrdersToStore-开始', {
1732
+ freshOrderCount: freshOrders.length,
1733
+ storeOrderCountBefore: storeOrderCountBefore,
1734
+ source: source
1735
+ });
1736
+ this.logDuplicateOrders("".concat(source, ".beforeMerge"), this.store.list);
1737
+ normalizedFreshOrders = [];
1738
+ _iterator10 = _createForOfIteratorHelper(freshOrders);
1739
+ _context16.prev = 5;
1740
+ _iterator10.s();
1741
+ case 7:
1742
+ if ((_step10 = _iterator10.n()).done) {
1743
+ _context16.next = 15;
610
1744
  break;
611
1745
  }
612
- order = _step4.value;
1746
+ order = _step10.value;
613
1747
  id = order === null || order === void 0 ? void 0 : order.order_id;
614
1748
  if (!(id === undefined || id === null)) {
615
- _context6.next = 9;
1749
+ _context16.next = 12;
616
1750
  break;
617
1751
  }
618
- return _context6.abrupt("continue", 10);
619
- case 9:
620
- freshMap.set(this.getIdKey(id), order);
621
- case 10:
622
- _context6.next = 4;
623
- break;
1752
+ return _context16.abrupt("continue", 13);
624
1753
  case 12:
625
- _context6.next = 17;
1754
+ normalizedFreshOrders.push(this.normalizeRemoteSyncedOrder(order));
1755
+ case 13:
1756
+ _context16.next = 7;
1757
+ break;
1758
+ case 15:
1759
+ _context16.next = 20;
626
1760
  break;
627
- case 14:
628
- _context6.prev = 14;
629
- _context6.t0 = _context6["catch"](2);
630
- _iterator4.e(_context6.t0);
631
1761
  case 17:
632
- _context6.prev = 17;
633
- _iterator4.f();
634
- return _context6.finish(17);
1762
+ _context16.prev = 17;
1763
+ _context16.t0 = _context16["catch"](5);
1764
+ _iterator10.e(_context16.t0);
635
1765
  case 20:
1766
+ _context16.prev = 20;
1767
+ _iterator10.f();
1768
+ return _context16.finish(20);
1769
+ case 23:
1770
+ // 先对本批新单做去重(批内规模 m 很小),保证每条 fresh 身份唯一
1771
+ uniqueFreshOrders = this.compactOrderListByIdentity(normalizedFreshOrders, "".concat(source, ".incoming")).list;
1772
+ uniqueFreshCount = uniqueFreshOrders.length;
1773
+ patchedOrders = [];
1774
+ mergeActions = {};
636
1775
  updatedList = this.store.list.map(function (order) {
637
- var id = order.order_id;
638
- if (id === undefined || id === null) return order;
639
- var key = _this5.getIdKey(id);
640
- if (!freshMap.has(key)) return order;
641
- var fresh = freshMap.get(key);
642
- freshMap.delete(key);
643
- return fresh;
644
- });
645
- _iterator5 = _createForOfIteratorHelper(freshMap.values());
646
- try {
647
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
648
- _order = _step5.value;
649
- updatedList.push(_order);
1776
+ return _this15.normalizeOrderForMemoryList(order, "".concat(source, ".existingMemory"));
1777
+ }); // 基于身份键(field:value)建立索引,把「查找已存在订单」从 O(n) 线性扫描降为 O(1),
1778
+ // 整体合并复杂度由 O(n^2) 降为 O(n + m)。索引语义与 doOrdersShareIdentity 完全一致:
1779
+ // 任一身份字段(order_id/external_sale_number/order_number/shop_order_number)同值即同一单。
1780
+ identityKeyToIndex = new Map();
1781
+ for (index = 0; index < updatedList.length; index += 1) {
1782
+ identityKeys = this.getOrderIdentityMatchKeys(updatedList[index]);
1783
+ _iterator11 = _createForOfIteratorHelper(identityKeys);
1784
+ try {
1785
+ for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
1786
+ key = _step11.value;
1787
+ // 同一 key 命中多张时保留最靠前的下标,与原 findIndex「取首个匹配」一致
1788
+ if (!identityKeyToIndex.has(key)) identityKeyToIndex.set(key, index);
1789
+ }
1790
+ } catch (err) {
1791
+ _iterator11.e(err);
1792
+ } finally {
1793
+ _iterator11.f();
650
1794
  }
651
- } catch (err) {
652
- _iterator5.e(err);
653
- } finally {
654
- _iterator5.f();
655
1795
  }
656
- this.store.list = updatedList;
1796
+ _iterator12 = _createForOfIteratorHelper(uniqueFreshOrders);
1797
+ _context16.prev = 31;
1798
+ _iterator12.s();
1799
+ case 33:
1800
+ if ((_step12 = _iterator12.n()).done) {
1801
+ _context16.next = 57;
1802
+ break;
1803
+ }
1804
+ fresh = _step12.value;
1805
+ freshIdentityKeys = this.getOrderIdentityMatchKeys(fresh);
1806
+ matchIndex = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, freshIdentityKeys);
1807
+ storageKey = this.getOrderStorageKey(fresh);
1808
+ mergeKey = storageKey || (fresh.order_id !== undefined && fresh.order_id !== null ? this.getIdKey(fresh.order_id) : '');
1809
+ if (!(matchIndex >= 0)) {
1810
+ _context16.next = 50;
1811
+ break;
1812
+ }
1813
+ existingOrder = updatedList[matchIndex];
1814
+ if (!(this.isPendingSyncOrder(existingOrder) && this.isRemoteEchoMergeSource(source))) {
1815
+ _context16.next = 44;
1816
+ break;
1817
+ }
1818
+ this.logInfo('mergeOrdersToStore-跳过 pending 订单远端覆盖', {
1819
+ source: source,
1820
+ order_id: (_ref2 = (_existingOrder$order_ = existingOrder.order_id) !== null && _existingOrder$order_ !== void 0 ? _existingOrder$order_ : fresh.order_id) !== null && _ref2 !== void 0 ? _ref2 : null,
1821
+ external_sale_number: (_ref3 = (_external_sale_number2 = existingOrder.external_sale_number) !== null && _external_sale_number2 !== void 0 ? _external_sale_number2 : fresh.external_sale_number) !== null && _ref3 !== void 0 ? _ref3 : null,
1822
+ local_payment_status: (_existingOrder$paymen = existingOrder.payment_status) !== null && _existingOrder$paymen !== void 0 ? _existingOrder$paymen : null,
1823
+ remote_payment_status: (_fresh$payment_status = fresh.payment_status) !== null && _fresh$payment_status !== void 0 ? _fresh$payment_status : null,
1824
+ local_need_sync: (_existingOrder$need_s = existingOrder.need_sync) !== null && _existingOrder$need_s !== void 0 ? _existingOrder$need_s : null,
1825
+ remote_need_sync: (_fresh$need_sync = fresh.need_sync) !== null && _fresh$need_sync !== void 0 ? _fresh$need_sync : null,
1826
+ reason: 'protect_pending_sync_order_from_remote_echo'
1827
+ });
1828
+ return _context16.abrupt("continue", 55);
1829
+ case 44:
1830
+ mergedOrder = this.mergeOrderRecords(existingOrder, fresh);
1831
+ updatedList[matchIndex] = mergedOrder;
1832
+ // 合并后身份字段可能新增(如挂单拿到 order_id),同步登记到索引,
1833
+ // 供同批后续 fresh 命中同一槽位,避免重复插入
1834
+ this.registerOrderIdentityKeys(identityKeyToIndex, mergedOrder, matchIndex);
1835
+ patchedOrders.push(mergedOrder);
1836
+ if (mergeKey) mergeActions[mergeKey] = 'update';
1837
+ return _context16.abrupt("continue", 55);
1838
+ case 50:
1839
+ insertIndex = updatedList.length;
1840
+ updatedList.push(fresh);
1841
+ this.registerOrderIdentityKeys(identityKeyToIndex, fresh, insertIndex);
1842
+ patchedOrders.push(fresh);
1843
+ if (mergeKey) mergeActions[mergeKey] = 'insert';
1844
+ case 55:
1845
+ _context16.next = 33;
1846
+ break;
1847
+ case 57:
1848
+ _context16.next = 62;
1849
+ break;
1850
+ case 59:
1851
+ _context16.prev = 59;
1852
+ _context16.t1 = _context16["catch"](31);
1853
+ _iterator12.e(_context16.t1);
1854
+ case 62:
1855
+ _context16.prev = 62;
1856
+ _iterator12.f();
1857
+ return _context16.finish(62);
1858
+ case 65:
1859
+ insertCount = Object.values(mergeActions).filter(function (v) {
1860
+ return v === 'insert';
1861
+ }).length;
1862
+ updateCount = Object.values(mergeActions).filter(function (v) {
1863
+ return v === 'update';
1864
+ }).length;
1865
+ this.logInfo('mergeOrdersToStore-合并完成', {
1866
+ insertCount: insertCount,
1867
+ updateCount: updateCount,
1868
+ storeOrderCountAfter: this.store.list.length
1869
+ });
1870
+ // 增量索引已保证 store 去重不变量,无需再对全表做 O(n^2) 压缩;
1871
+ // 仅在自检开关开启时做一次兜底校验。
1872
+ this.store.list = this.runOrderStoreSelfCheck(updatedList, "".concat(source, ".store"));
657
1873
  this.syncOrdersMap();
658
- _context6.next = 27;
659
- return this.saveOrdersToSQLite(this.store.list);
660
- case 27:
661
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
662
- case 28:
1874
+ _context16.next = 72;
1875
+ return this.patchOrdersInSQLite(patchedOrders, source, mergeActions);
1876
+ case 72:
1877
+ this.logInfo('mergeOrdersToStore-结束', {
1878
+ uniqueFreshCount: uniqueFreshCount,
1879
+ storeOrderCountAfter: this.store.list.length,
1880
+ insertCount: insertCount,
1881
+ updateCount: updateCount
1882
+ });
1883
+ _context16.next = 75;
1884
+ return this.emitOrdersChanged(patchedOrders, source);
1885
+ case 75:
663
1886
  case "end":
664
- return _context6.stop();
1887
+ return _context16.stop();
665
1888
  }
666
- }, _callee6, this, [[2, 14, 17, 20]]);
1889
+ }, _callee16, this, [[5, 17, 20, 23], [31, 59, 62, 65]]);
667
1890
  }));
668
- function mergeOrdersToStore(_x4) {
1891
+ function mergeOrdersToStore(_x9, _x10) {
669
1892
  return _mergeOrdersToStore.apply(this, arguments);
670
1893
  }
671
1894
  return mergeOrdersToStore;
672
- }())
1895
+ }()
1896
+ /**
1897
+ * 在身份索引中查找与目标订单共享任一身份键的已存在订单下标。
1898
+ * 返回所有命中键里最小的下标,等价于原 findOrderIndexByIdentity 的「取首个匹配」语义。
1899
+ *
1900
+ * @example
1901
+ * const idx = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, freshIdentityKeys)
1902
+ */
1903
+ )
1904
+ }, {
1905
+ key: "lookupOrderIndexByIdentityKeys",
1906
+ value: function lookupOrderIndexByIdentityKeys(identityKeyToIndex, identityKeys) {
1907
+ var matchIndex = -1;
1908
+ var _iterator13 = _createForOfIteratorHelper(identityKeys),
1909
+ _step13;
1910
+ try {
1911
+ for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
1912
+ var key = _step13.value;
1913
+ var index = identityKeyToIndex.get(key);
1914
+ if (index === undefined) continue;
1915
+ if (matchIndex < 0 || index < matchIndex) matchIndex = index;
1916
+ }
1917
+ } catch (err) {
1918
+ _iterator13.e(err);
1919
+ } finally {
1920
+ _iterator13.f();
1921
+ }
1922
+ return matchIndex;
1923
+ }
1924
+ }, {
1925
+ key: "isRemoteEchoMergeSource",
1926
+ value: function isRemoteEchoMergeSource(source) {
1927
+ return source === 'pubsub.bodyUpsert' || source === 'pubsub.httpRefresh';
1928
+ }
1929
+
1930
+ /**
1931
+ * 将订单的全部身份键登记到索引并指向其在列表中的下标。
1932
+ * 合并后订单新增的身份字段(如挂单同步后拿到 order_id)也会被登记。
1933
+ *
1934
+ * @example
1935
+ * this.registerOrderIdentityKeys(identityKeyToIndex, mergedOrder, matchIndex)
1936
+ */
1937
+ }, {
1938
+ key: "registerOrderIdentityKeys",
1939
+ value: function registerOrderIdentityKeys(identityKeyToIndex, order, index) {
1940
+ var identityKeys = this.getOrderIdentityMatchKeys(order);
1941
+ var _iterator14 = _createForOfIteratorHelper(identityKeys),
1942
+ _step14;
1943
+ try {
1944
+ for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
1945
+ var key = _step14.value;
1946
+ identityKeyToIndex.set(key, index);
1947
+ }
1948
+ } catch (err) {
1949
+ _iterator14.e(err);
1950
+ } finally {
1951
+ _iterator14.f();
1952
+ }
1953
+ }
1954
+
1955
+ /**
1956
+ * 合并热路径去重兜底:默认直接返回原列表(增量索引已保证无重复)。
1957
+ * 仅当 ORDER_MERGE_SELF_CHECK 开启时,额外做一次全表压缩并在发现残留重复时告警。
1958
+ */
1959
+ }, {
1960
+ key: "runOrderStoreSelfCheck",
1961
+ value: function runOrderStoreSelfCheck(orders, source) {
1962
+ if (!ORDER_MERGE_SELF_CHECK) return orders;
1963
+ var _this$compactOrderLis = this.compactOrderListByIdentity(orders, source),
1964
+ list = _this$compactOrderLis.list,
1965
+ removedCount = _this$compactOrderLis.removedCount;
1966
+ if (removedCount > 0) {
1967
+ this.logWarning('合并自检发现残留重复订单,已压缩', {
1968
+ source: source,
1969
+ removedCount: removedCount
1970
+ });
1971
+ }
1972
+ return list;
1973
+ }
673
1974
  }, {
674
1975
  key: "normalizeOrderSyncMessage",
675
1976
  value: function normalizeOrderSyncMessage(res) {
@@ -702,17 +2003,17 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
702
2003
  key: "uniqueOrderIds",
703
2004
  value: function uniqueOrderIds(ids) {
704
2005
  var idMap = new Map();
705
- var _iterator6 = _createForOfIteratorHelper(ids),
706
- _step6;
2006
+ var _iterator15 = _createForOfIteratorHelper(ids),
2007
+ _step15;
707
2008
  try {
708
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
709
- var id = _step6.value;
2009
+ for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
2010
+ var id = _step15.value;
710
2011
  idMap.set(this.getIdKey(id), id);
711
2012
  }
712
2013
  } catch (err) {
713
- _iterator6.e(err);
2014
+ _iterator15.e(err);
714
2015
  } finally {
715
- _iterator6.f();
2016
+ _iterator15.f();
716
2017
  }
717
2018
  return _toConsumableArray(idMap.values());
718
2019
  }
@@ -721,6 +2022,238 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
721
2022
  value: function getIdKey(id) {
722
2023
  return String(id);
723
2024
  }
2025
+ }, {
2026
+ key: "isOrderLookupMatch",
2027
+ value: function isOrderLookupMatch(order, lookupKey) {
2028
+ var _this16 = this;
2029
+ if (!order || !lookupKey) return false;
2030
+ var candidates = [order.order_id, order.external_sale_number, order.order_number, order.shop_order_number, order.shop_full_order_number];
2031
+ return candidates.some(function (value) {
2032
+ if (value === undefined || value === null || value === '') return false;
2033
+ return _this16.getIdKey(value) === lookupKey;
2034
+ });
2035
+ }
2036
+
2037
+ /**
2038
+ * 解析订单 SQLite 主键,规则与宿主 OrderDataSource.getOrderStorageKey 一致。
2039
+ *
2040
+ * @example
2041
+ * const key = this.getOrderStorageKey({ order_id: 1001, external_sale_number: 'S-1001' })
2042
+ * // => 'S-1001'
2043
+ */
2044
+ }, {
2045
+ key: "getOrderStorageKey",
2046
+ value: function getOrderStorageKey(order) {
2047
+ var externalSaleNumber = order === null || order === void 0 ? void 0 : order.external_sale_number;
2048
+ if (externalSaleNumber !== undefined && externalSaleNumber !== null && externalSaleNumber !== '') {
2049
+ return String(externalSaleNumber);
2050
+ }
2051
+ var orderId = order === null || order === void 0 ? void 0 : order.order_id;
2052
+ if (orderId !== undefined && orderId !== null && orderId !== '') {
2053
+ return String(orderId);
2054
+ }
2055
+ return '';
2056
+ }
2057
+ }, {
2058
+ key: "getOrderIdentityMatchKeys",
2059
+ value: function getOrderIdentityMatchKeys(order) {
2060
+ return this.getOrderIdentityEntries(order).map(function (entry) {
2061
+ return "".concat(entry.field, ":").concat(entry.key);
2062
+ });
2063
+ }
2064
+ }, {
2065
+ key: "doOrdersShareIdentity",
2066
+ value: function doOrdersShareIdentity(left, right) {
2067
+ var leftKeys = new Set(this.getOrderIdentityMatchKeys(left));
2068
+ if (leftKeys.size === 0) return false;
2069
+ return this.getOrderIdentityMatchKeys(right).some(function (key) {
2070
+ return leftKeys.has(key);
2071
+ });
2072
+ }
2073
+ }, {
2074
+ key: "findOrderIndexByIdentity",
2075
+ value: function findOrderIndexByIdentity(orders, target) {
2076
+ var _this17 = this;
2077
+ if (this.getOrderIdentityMatchKeys(target).length === 0) return -1;
2078
+ return orders.findIndex(function (order) {
2079
+ return _this17.doOrdersShareIdentity(order, target);
2080
+ });
2081
+ }
2082
+ }, {
2083
+ key: "getOrderCompletenessScore",
2084
+ value: function getOrderCompletenessScore(order) {
2085
+ var record = order;
2086
+ var score = this.isPendingSyncOrder(order) ? 0 : 100;
2087
+ if (!this.isBlankIdentityValue(order.order_id) && order.order_id !== record.external_sale_number) score += 30;
2088
+ score += this.getOrderIdentityMatchKeys(order).length * 5;
2089
+ if (Array.isArray(order.products)) score += Math.min(order.products.length, 10);
2090
+ if (Array.isArray(order.bookings)) score += Math.min(order.bookings.length, 10);
2091
+ if (Array.isArray(order.payments)) score += Math.min(order.payments.length, 10);
2092
+ if (record.updated_at) score += 1;
2093
+ return score;
2094
+ }
2095
+ }, {
2096
+ key: "pickPreferredOrder",
2097
+ value: function pickPreferredOrder(left, right) {
2098
+ var leftScore = this.getOrderCompletenessScore(left);
2099
+ var rightScore = this.getOrderCompletenessScore(right);
2100
+ if (rightScore >= leftScore) return right;
2101
+ return left;
2102
+ }
2103
+ }, {
2104
+ key: "mergeOrderRecords",
2105
+ value: function mergeOrderRecords(existing, incoming) {
2106
+ var preferred = this.pickPreferredOrder(existing, incoming);
2107
+ var secondary = preferred === existing ? incoming : existing;
2108
+ var merged = _objectSpread(_objectSpread({}, secondary), preferred);
2109
+ var fieldsToPreserve = ['order_id', 'external_sale_number', 'order_number', 'shop_order_number', 'shop_full_order_number'];
2110
+ var incomingPatchFields = ['payment_status', 'status', 'shipping_status', 'updated_at', 'shop_discount', 'summary', 'note', 'customer_id', 'customer_name', 'customer', 'holder', 'contacts_info', 'phone', 'email', 'relation_forms'];
2111
+ var mergedRecord = merged;
2112
+ var preferredRecord = preferred;
2113
+ var secondaryRecord = secondary;
2114
+ var existingRecord = existing;
2115
+ var incomingRecord = incoming;
2116
+ var childUidRemaps = [];
2117
+ for (var _i4 = 0, _fieldsToPreserve = fieldsToPreserve; _i4 < _fieldsToPreserve.length; _i4++) {
2118
+ var field = _fieldsToPreserve[_i4];
2119
+ if (!this.isBlankIdentityValue(preferredRecord[field])) {
2120
+ mergedRecord[field] = preferredRecord[field];
2121
+ continue;
2122
+ }
2123
+ if (!this.isBlankIdentityValue(secondaryRecord[field])) {
2124
+ mergedRecord[field] = secondaryRecord[field];
2125
+ }
2126
+ }
2127
+ for (var _i5 = 0, _incomingPatchFields = incomingPatchFields; _i5 < _incomingPatchFields.length; _i5++) {
2128
+ var _field = _incomingPatchFields[_i5];
2129
+ if (!Object.prototype.hasOwnProperty.call(incomingRecord, _field)) continue;
2130
+ if (incomingRecord[_field] === undefined || incomingRecord[_field] === null) continue;
2131
+ if (typeof incomingRecord[_field] === 'string' && incomingRecord[_field] === '') continue;
2132
+ mergedRecord[_field] = cloneDeep(incomingRecord[_field]);
2133
+ }
2134
+
2135
+ // 子项数组遵循完整快照语义:incoming 自有且为数组(包括 [])时权威替换;
2136
+ // 字段缺席或不是数组时视为稀疏 patch,继续保留 existing。
2137
+ for (var _i6 = 0, _ORDER_AUTHORITATIVE_2 = ORDER_AUTHORITATIVE_COLLECTION_FIELDS; _i6 < _ORDER_AUTHORITATIVE_2.length; _i6++) {
2138
+ var _field2 = _ORDER_AUTHORITATIVE_2[_i6];
2139
+ if (Array.isArray(incomingRecord[_field2])) {
2140
+ mergedRecord[_field2] = this.mergeAuthoritativeOrderCollection(_field2, existingRecord[_field2], incomingRecord[_field2], childUidRemaps);
2141
+ continue;
2142
+ }
2143
+ if (Object.prototype.hasOwnProperty.call(existingRecord, _field2)) {
2144
+ mergedRecord[_field2] = cloneDeep(existingRecord[_field2]);
2145
+ } else {
2146
+ delete mergedRecord[_field2];
2147
+ }
2148
+ }
2149
+ if (!this.isPendingSyncOrder(preferred) || !this.isPendingSyncOrder(secondary)) {
2150
+ merged.need_sync = 0;
2151
+ }
2152
+ return this.normalizeOrderCollectionsForIngress(applyOrderCollectionUidRemaps(merged, childUidRemaps), 'mergeOrderRecords');
2153
+ }
2154
+ }, {
2155
+ key: "summarizeDuplicateOrders",
2156
+ value: function summarizeDuplicateOrders(orders) {
2157
+ var groups = new Map();
2158
+ var _iterator16 = _createForOfIteratorHelper(orders),
2159
+ _step16;
2160
+ try {
2161
+ for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
2162
+ var order = _step16.value;
2163
+ var _iterator17 = _createForOfIteratorHelper(this.getOrderIdentityMatchKeys(order)),
2164
+ _step17;
2165
+ try {
2166
+ for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
2167
+ var key = _step17.value;
2168
+ var group = groups.get(key) || [];
2169
+ group.push(order);
2170
+ groups.set(key, group);
2171
+ }
2172
+ } catch (err) {
2173
+ _iterator17.e(err);
2174
+ } finally {
2175
+ _iterator17.f();
2176
+ }
2177
+ }
2178
+ } catch (err) {
2179
+ _iterator16.e(err);
2180
+ } finally {
2181
+ _iterator16.f();
2182
+ }
2183
+ return _toConsumableArray(groups.entries()).filter(function (_ref4) {
2184
+ var _ref5 = _slicedToArray(_ref4, 2),
2185
+ group = _ref5[1];
2186
+ return group.length > 1;
2187
+ }).slice(0, 20).map(function (_ref6) {
2188
+ var _ref7 = _slicedToArray(_ref6, 2),
2189
+ key = _ref7[0],
2190
+ group = _ref7[1];
2191
+ return {
2192
+ key: key,
2193
+ count: group.length,
2194
+ orders: group.map(function (order) {
2195
+ var _order$order_id3, _external_sale_number3, _shop_order_number, _shop_full_order_numb, _order$need_sync;
2196
+ return {
2197
+ order_id: (_order$order_id3 = order.order_id) !== null && _order$order_id3 !== void 0 ? _order$order_id3 : null,
2198
+ external_sale_number: (_external_sale_number3 = order.external_sale_number) !== null && _external_sale_number3 !== void 0 ? _external_sale_number3 : null,
2199
+ shop_order_number: (_shop_order_number = order.shop_order_number) !== null && _shop_order_number !== void 0 ? _shop_order_number : null,
2200
+ shop_full_order_number: (_shop_full_order_numb = order.shop_full_order_number) !== null && _shop_full_order_numb !== void 0 ? _shop_full_order_numb : null,
2201
+ need_sync: (_order$need_sync = order.need_sync) !== null && _order$need_sync !== void 0 ? _order$need_sync : null
2202
+ };
2203
+ })
2204
+ };
2205
+ });
2206
+ }
2207
+ }, {
2208
+ key: "logDuplicateOrders",
2209
+ value: function logDuplicateOrders(source, orders) {
2210
+ var duplicateGroups = this.summarizeDuplicateOrders(orders);
2211
+ if (duplicateGroups.length === 0) return;
2212
+ this.logWarning('检测到重复订单身份键', {
2213
+ source: source,
2214
+ duplicateGroupCount: duplicateGroups.length,
2215
+ duplicateGroups: duplicateGroups
2216
+ });
2217
+ }
2218
+ }, {
2219
+ key: "compactOrderListByIdentity",
2220
+ value: function compactOrderListByIdentity(orders, source) {
2221
+ var list = [];
2222
+ var removedCount = 0;
2223
+ var _iterator18 = _createForOfIteratorHelper(orders),
2224
+ _step18;
2225
+ try {
2226
+ for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
2227
+ var order = _step18.value;
2228
+ var normalizedOrder = this.normalizeOrderCollectionsForIngress(order, "".concat(source, ".order"));
2229
+ var matchIndex = this.findOrderIndexByIdentity(list, normalizedOrder);
2230
+ if (matchIndex < 0) {
2231
+ list.push(normalizedOrder);
2232
+ continue;
2233
+ }
2234
+ list[matchIndex] = this.mergeOrderRecords(list[matchIndex], normalizedOrder);
2235
+ removedCount += 1;
2236
+ }
2237
+ } catch (err) {
2238
+ _iterator18.e(err);
2239
+ } finally {
2240
+ _iterator18.f();
2241
+ }
2242
+ if (removedCount > 0) {
2243
+ this.logWarning('订单列表重复项已压缩', {
2244
+ source: source,
2245
+ beforeCount: orders.length,
2246
+ afterCount: list.length,
2247
+ removedCount: removedCount
2248
+ });
2249
+ } else {
2250
+ this.logDuplicateOrders(source, orders);
2251
+ }
2252
+ return {
2253
+ list: list,
2254
+ removedCount: removedCount
2255
+ };
2256
+ }
724
2257
 
725
2258
  /**
726
2259
  * 当前订单拉取窗口:
@@ -730,9 +2263,9 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
730
2263
  }, {
731
2264
  key: "getCurrentPullWindow",
732
2265
  value: function getCurrentPullWindow() {
733
- var _this$store;
2266
+ var _this$store2;
734
2267
  var now = dayjs();
735
- var range = (_this$store = this.store) === null || _this$store === void 0 || (_this$store = _this$store.createdAtQuery) === null || _this$store === void 0 ? void 0 : _this$store.sales_time_between;
2268
+ var range = (_this$store2 = this.store) === null || _this$store2 === void 0 || (_this$store2 = _this$store2.createdAtQuery) === null || _this$store2 === void 0 ? void 0 : _this$store2.sales_time_between;
736
2269
  if (Array.isArray(range) && range.length >= 2) {
737
2270
  var _startAt = dayjs(range[0]);
738
2271
  var endExclusiveAt = dayjs(range[1]);
@@ -778,7 +2311,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
778
2311
  if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
779
2312
  return globalThis.localStorage.getItem(key);
780
2313
  }
781
- } catch (_unused5) {
2314
+ } catch (_unused6) {
782
2315
  // 忽略存储异常,避免影响主流程
783
2316
  }
784
2317
  return null;
@@ -795,39 +2328,42 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
795
2328
  if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
796
2329
  globalThis.localStorage.setItem(key, value);
797
2330
  }
798
- } catch (_unused6) {
2331
+ } catch (_unused7) {
799
2332
  // 忽略存储异常,避免影响主流程
800
2333
  }
801
2334
  }
802
2335
  }, {
803
2336
  key: "loadOrdersFromSQLite",
804
2337
  value: function () {
805
- var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
2338
+ var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17() {
2339
+ var _this18 = this;
806
2340
  var orders;
807
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
808
- while (1) switch (_context7.prev = _context7.next) {
2341
+ return _regeneratorRuntime().wrap(function _callee17$(_context17) {
2342
+ while (1) switch (_context17.prev = _context17.next) {
809
2343
  case 0:
810
2344
  if (this.dbManager) {
811
- _context7.next = 2;
2345
+ _context17.next = 2;
812
2346
  break;
813
2347
  }
814
- return _context7.abrupt("return", []);
2348
+ return _context17.abrupt("return", []);
815
2349
  case 2:
816
- _context7.prev = 2;
817
- _context7.next = 5;
2350
+ _context17.prev = 2;
2351
+ _context17.next = 5;
818
2352
  return this.dbManager.getAll(INDEXDB_STORE_NAME);
819
2353
  case 5:
820
- orders = _context7.sent;
821
- return _context7.abrupt("return", orders || []);
2354
+ orders = _context17.sent;
2355
+ return _context17.abrupt("return", (orders || []).map(function (order) {
2356
+ return _this18.normalizeOrderCollectionsForIngress(order, 'loadOrdersFromSQLite');
2357
+ }));
822
2358
  case 9:
823
- _context7.prev = 9;
824
- _context7.t0 = _context7["catch"](2);
825
- return _context7.abrupt("return", []);
2359
+ _context17.prev = 9;
2360
+ _context17.t0 = _context17["catch"](2);
2361
+ return _context17.abrupt("return", []);
826
2362
  case 12:
827
2363
  case "end":
828
- return _context7.stop();
2364
+ return _context17.stop();
829
2365
  }
830
- }, _callee7, this, [[2, 9]]);
2366
+ }, _callee17, this, [[2, 9]]);
831
2367
  }));
832
2368
  function loadOrdersFromSQLite() {
833
2369
  return _loadOrdersFromSQLite.apply(this, arguments);
@@ -835,82 +2371,493 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
835
2371
  return loadOrdersFromSQLite;
836
2372
  }()
837
2373
  }, {
838
- key: "saveOrdersToSQLite",
839
- value: function () {
840
- var _saveOrdersToSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(orderList) {
841
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
842
- while (1) switch (_context8.prev = _context8.next) {
2374
+ key: "isPendingSyncOrder",
2375
+ value: function isPendingSyncOrder(order) {
2376
+ return Number(order === null || order === void 0 ? void 0 : order.need_sync) === 1;
2377
+ }
2378
+ }, {
2379
+ key: "normalizeRemoteSyncedOrder",
2380
+ value: function normalizeRemoteSyncedOrder(order) {
2381
+ var normalizedOrder = this.normalizeOrderCollectionsForIngress(order, 'normalizeRemoteSyncedOrder');
2382
+ if (this.isPendingSyncOrder(normalizedOrder)) return normalizedOrder;
2383
+ return _objectSpread(_objectSpread({}, normalizedOrder), {}, {
2384
+ need_sync: 0
2385
+ });
2386
+ }
2387
+ }, {
2388
+ key: "mergeRemoteSnapshotWithPendingOrders",
2389
+ value: function mergeRemoteSnapshotWithPendingOrders(remoteOrders, existingOrders) {
2390
+ var _this19 = this;
2391
+ var merged = remoteOrders.map(function (order) {
2392
+ return _this19.normalizeRemoteSyncedOrder(order);
2393
+ });
2394
+ var _iterator19 = _createForOfIteratorHelper(existingOrders),
2395
+ _step19;
2396
+ try {
2397
+ for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
2398
+ var rawOrder = _step19.value;
2399
+ var order = this.normalizeOrderCollectionsForIngress(rawOrder, 'mergeRemoteSnapshotWithPendingOrders.existingSQLite');
2400
+ if (!this.isPendingSyncOrder(order)) continue;
2401
+ var matchIndex = this.findOrderIndexByIdentity(merged, order);
2402
+ if (matchIndex >= 0) {
2403
+ merged[matchIndex] = this.mergeOrderRecords(order, merged[matchIndex]);
2404
+ continue;
2405
+ }
2406
+ if (!this.getOrderStorageKey(order)) continue;
2407
+ merged.push(order);
2408
+ }
2409
+ } catch (err) {
2410
+ _iterator19.e(err);
2411
+ } finally {
2412
+ _iterator19.f();
2413
+ }
2414
+ return this.compactOrderListByIdentity(merged, 'mergeRemoteSnapshotWithPendingOrders').list;
2415
+ }
2416
+
2417
+ /**
2418
+ * 串行执行订单 SQLite 写入任务,避免快照替换与增量 upsert 并发交错。
2419
+ *
2420
+ * @example
2421
+ * await this.runInOrderSQLiteSaveQueue(async () => {
2422
+ * await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, orders)
2423
+ * })
2424
+ */
2425
+ }, {
2426
+ key: "runInOrderSQLiteSaveQueue",
2427
+ value: (function () {
2428
+ var _runInOrderSQLiteSaveQueue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(task) {
2429
+ var queuedTask;
2430
+ return _regeneratorRuntime().wrap(function _callee18$(_context18) {
2431
+ while (1) switch (_context18.prev = _context18.next) {
843
2432
  case 0:
844
- if (this.dbManager) {
845
- _context8.next = 2;
2433
+ queuedTask = this.orderSQLiteSaveQueue.then(task, task);
2434
+ this.orderSQLiteSaveQueue = queuedTask.then(function () {
2435
+ return undefined;
2436
+ }, function () {
2437
+ return undefined;
2438
+ });
2439
+ return _context18.abrupt("return", queuedTask);
2440
+ case 3:
2441
+ case "end":
2442
+ return _context18.stop();
2443
+ }
2444
+ }, _callee18, this);
2445
+ }));
2446
+ function runInOrderSQLiteSaveQueue(_x11) {
2447
+ return _runInOrderSQLiteSaveQueue.apply(this, arguments);
2448
+ }
2449
+ return runInOrderSQLiteSaveQueue;
2450
+ }()
2451
+ /**
2452
+ * 批量增量 upsert 订单到 SQLite,不清空表;用于 pubsub / HTTP 增量合并。
2453
+ *
2454
+ * @example
2455
+ * await this.patchOrdersInSQLite(freshOrders)
2456
+ */
2457
+ )
2458
+ }, {
2459
+ key: "patchOrdersInSQLite",
2460
+ value: (function () {
2461
+ var _patchOrdersInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(orders, source) {
2462
+ var _this20 = this;
2463
+ var mergeActions,
2464
+ ordersSnapshot,
2465
+ _this$filterRedundant2,
2466
+ toWrite,
2467
+ skipped,
2468
+ compactedToWrite,
2469
+ _args20 = arguments;
2470
+ return _regeneratorRuntime().wrap(function _callee20$(_context20) {
2471
+ while (1) switch (_context20.prev = _context20.next) {
2472
+ case 0:
2473
+ mergeActions = _args20.length > 2 && _args20[2] !== undefined ? _args20[2] : {};
2474
+ if (!(!this.dbManager || orders.length === 0)) {
2475
+ _context20.next = 3;
846
2476
  break;
847
2477
  }
848
- return _context8.abrupt("return");
849
- case 2:
850
- _context8.prev = 2;
851
- _context8.next = 5;
852
- return this.dbManager.clear(INDEXDB_STORE_NAME);
853
- case 5:
854
- if (!(orderList.length === 0)) {
855
- _context8.next = 7;
2478
+ return _context20.abrupt("return");
2479
+ case 3:
2480
+ ordersSnapshot = cloneDeep(orders).map(function (order) {
2481
+ return _this20.normalizeOrderCollectionsForIngress(order, "".concat(source, ".sqliteIngress"));
2482
+ }).filter(function (order) {
2483
+ return _this20.getOrderStorageKey(order);
2484
+ });
2485
+ if (!(ordersSnapshot.length === 0)) {
2486
+ _context20.next = 6;
856
2487
  break;
857
2488
  }
858
- return _context8.abrupt("return");
859
- case 7:
860
- _context8.next = 9;
861
- return this.dbManager.bulkAdd(INDEXDB_STORE_NAME, orderList);
2489
+ return _context20.abrupt("return");
2490
+ case 6:
2491
+ _this$filterRedundant2 = this.filterRedundantPatchOrders(source, ordersSnapshot, mergeActions), toWrite = _this$filterRedundant2.toWrite, skipped = _this$filterRedundant2.skipped;
2492
+ if (!(toWrite.length === 0)) {
2493
+ _context20.next = 9;
2494
+ break;
2495
+ }
2496
+ return _context20.abrupt("return");
862
2497
  case 9:
863
- _context8.next = 14;
2498
+ compactedToWrite = this.compactOrderListByIdentity(toWrite, "".concat(source, ".sqlitePatch")).list;
2499
+ if (!(compactedToWrite.length === 0)) {
2500
+ _context20.next = 12;
2501
+ break;
2502
+ }
2503
+ return _context20.abrupt("return");
2504
+ case 12:
2505
+ _context20.prev = 12;
2506
+ _context20.next = 15;
2507
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19() {
2508
+ var writeMethod, _iterator20, _step20, order;
2509
+ return _regeneratorRuntime().wrap(function _callee19$(_context19) {
2510
+ while (1) switch (_context19.prev = _context19.next) {
2511
+ case 0:
2512
+ writeMethod = 'none';
2513
+ _this20.logInfo('patchOrdersInSQLite-开始', {
2514
+ source: source,
2515
+ count: compactedToWrite.length,
2516
+ dedupedCount: skipped.length
2517
+ });
2518
+ if (!(typeof _this20.dbManager.bulkUpdate === 'function')) {
2519
+ _context19.next = 8;
2520
+ break;
2521
+ }
2522
+ writeMethod = 'bulkUpdate';
2523
+ _context19.next = 6;
2524
+ return _this20.dbManager.bulkUpdate(INDEXDB_STORE_NAME, compactedToWrite);
2525
+ case 6:
2526
+ _context19.next = 33;
2527
+ break;
2528
+ case 8:
2529
+ if (!(typeof _this20.dbManager.bulkAdd === 'function')) {
2530
+ _context19.next = 14;
2531
+ break;
2532
+ }
2533
+ writeMethod = 'bulkAdd';
2534
+ _context19.next = 12;
2535
+ return _this20.dbManager.bulkAdd(INDEXDB_STORE_NAME, compactedToWrite);
2536
+ case 12:
2537
+ _context19.next = 33;
2538
+ break;
2539
+ case 14:
2540
+ if (!(typeof _this20.dbManager.update === 'function')) {
2541
+ _context19.next = 33;
2542
+ break;
2543
+ }
2544
+ writeMethod = 'update';
2545
+ _iterator20 = _createForOfIteratorHelper(compactedToWrite);
2546
+ _context19.prev = 17;
2547
+ _iterator20.s();
2548
+ case 19:
2549
+ if ((_step20 = _iterator20.n()).done) {
2550
+ _context19.next = 25;
2551
+ break;
2552
+ }
2553
+ order = _step20.value;
2554
+ _context19.next = 23;
2555
+ return _this20.dbManager.update(INDEXDB_STORE_NAME, order);
2556
+ case 23:
2557
+ _context19.next = 19;
2558
+ break;
2559
+ case 25:
2560
+ _context19.next = 30;
2561
+ break;
2562
+ case 27:
2563
+ _context19.prev = 27;
2564
+ _context19.t0 = _context19["catch"](17);
2565
+ _iterator20.e(_context19.t0);
2566
+ case 30:
2567
+ _context19.prev = 30;
2568
+ _iterator20.f();
2569
+ return _context19.finish(30);
2570
+ case 33:
2571
+ _this20.recordRecentSqliteWrite(source, compactedToWrite);
2572
+ _this20.logInfo('patchOrdersInSQLite-完成', {
2573
+ source: source,
2574
+ count: compactedToWrite.length,
2575
+ writeMethod: writeMethod,
2576
+ dedupedCount: skipped.length
2577
+ });
2578
+ case 35:
2579
+ case "end":
2580
+ return _context19.stop();
2581
+ }
2582
+ }, _callee19, null, [[17, 27, 30, 33]]);
2583
+ })));
2584
+ case 15:
2585
+ _context20.next = 20;
2586
+ break;
2587
+ case 17:
2588
+ _context20.prev = 17;
2589
+ _context20.t0 = _context20["catch"](12);
2590
+ this.logError('增量保存订单到 SQLite 失败', {
2591
+ error: _context20.t0 instanceof Error ? _context20.t0.message : String(_context20.t0),
2592
+ orderCount: ordersSnapshot.length
2593
+ });
2594
+ case 20:
2595
+ case "end":
2596
+ return _context20.stop();
2597
+ }
2598
+ }, _callee20, this, [[12, 17]]);
2599
+ }));
2600
+ function patchOrdersInSQLite(_x12, _x13) {
2601
+ return _patchOrdersInSQLite.apply(this, arguments);
2602
+ }
2603
+ return patchOrdersInSQLite;
2604
+ }()
2605
+ /**
2606
+ * 单条 upsert 订单到 SQLite;用于 overwriteExistingOrder 等单条覆盖场景。
2607
+ *
2608
+ * @example
2609
+ * await this.updateOrderInSQLite(freshOrder)
2610
+ */
2611
+ )
2612
+ }, {
2613
+ key: "updateOrderInSQLite",
2614
+ value: (function () {
2615
+ var _updateOrderInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(order, source) {
2616
+ var _this21 = this;
2617
+ var orderSnapshot, _orderSnapshot$order_3;
2618
+ return _regeneratorRuntime().wrap(function _callee22$(_context22) {
2619
+ while (1) switch (_context22.prev = _context22.next) {
2620
+ case 0:
2621
+ if (!(!this.dbManager || !this.getOrderStorageKey(order))) {
2622
+ _context22.next = 2;
2623
+ break;
2624
+ }
2625
+ return _context22.abrupt("return");
2626
+ case 2:
2627
+ orderSnapshot = this.normalizeOrderCollectionsForIngress(cloneDeep(order), "".concat(source, ".sqliteIngress"));
2628
+ _context22.prev = 3;
2629
+ _context22.next = 6;
2630
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21() {
2631
+ var _orderSnapshot$order_, _orderSnapshot$order_2;
2632
+ var writeMethod;
2633
+ return _regeneratorRuntime().wrap(function _callee21$(_context21) {
2634
+ while (1) switch (_context21.prev = _context21.next) {
2635
+ case 0:
2636
+ writeMethod = 'none';
2637
+ _this21.logInfo('updateOrderInSQLite-开始', {
2638
+ source: source,
2639
+ orderId: (_orderSnapshot$order_ = orderSnapshot.order_id) !== null && _orderSnapshot$order_ !== void 0 ? _orderSnapshot$order_ : null,
2640
+ storageKey: _this21.getOrderStorageKey(orderSnapshot)
2641
+ });
2642
+ if (!(typeof _this21.dbManager.update === 'function')) {
2643
+ _context21.next = 8;
2644
+ break;
2645
+ }
2646
+ writeMethod = 'update';
2647
+ _context21.next = 6;
2648
+ return _this21.dbManager.update(INDEXDB_STORE_NAME, orderSnapshot);
2649
+ case 6:
2650
+ _context21.next = 18;
2651
+ break;
2652
+ case 8:
2653
+ if (!(typeof _this21.dbManager.bulkUpdate === 'function')) {
2654
+ _context21.next = 14;
2655
+ break;
2656
+ }
2657
+ writeMethod = 'bulkUpdate';
2658
+ _context21.next = 12;
2659
+ return _this21.dbManager.bulkUpdate(INDEXDB_STORE_NAME, [orderSnapshot]);
2660
+ case 12:
2661
+ _context21.next = 18;
2662
+ break;
2663
+ case 14:
2664
+ if (!(typeof _this21.dbManager.bulkAdd === 'function')) {
2665
+ _context21.next = 18;
2666
+ break;
2667
+ }
2668
+ writeMethod = 'bulkAdd';
2669
+ _context21.next = 18;
2670
+ return _this21.dbManager.bulkAdd(INDEXDB_STORE_NAME, [orderSnapshot]);
2671
+ case 18:
2672
+ _this21.recordRecentSqliteWrite(source, [orderSnapshot]);
2673
+ _this21.logInfo('updateOrderInSQLite-完成', {
2674
+ source: source,
2675
+ orderId: (_orderSnapshot$order_2 = orderSnapshot.order_id) !== null && _orderSnapshot$order_2 !== void 0 ? _orderSnapshot$order_2 : null,
2676
+ writeMethod: writeMethod
2677
+ });
2678
+ case 20:
2679
+ case "end":
2680
+ return _context21.stop();
2681
+ }
2682
+ }, _callee21);
2683
+ })));
2684
+ case 6:
2685
+ _context22.next = 11;
864
2686
  break;
2687
+ case 8:
2688
+ _context22.prev = 8;
2689
+ _context22.t0 = _context22["catch"](3);
2690
+ this.logError('单条保存订单到 SQLite 失败', {
2691
+ error: _context22.t0 instanceof Error ? _context22.t0.message : String(_context22.t0),
2692
+ orderId: (_orderSnapshot$order_3 = orderSnapshot.order_id) !== null && _orderSnapshot$order_3 !== void 0 ? _orderSnapshot$order_3 : null
2693
+ });
865
2694
  case 11:
866
- _context8.prev = 11;
867
- _context8.t0 = _context8["catch"](2);
868
- // SQLite 异常,避免影响主流程
869
- this.logError('保存订单到 SQLite 失败', {
870
- error: _context8.t0 instanceof Error ? _context8.t0.message : String(_context8.t0),
871
- orderList: orderList.length
2695
+ case "end":
2696
+ return _context22.stop();
2697
+ }
2698
+ }, _callee22, this, [[3, 8]]);
2699
+ }));
2700
+ function updateOrderInSQLite(_x14, _x15) {
2701
+ return _updateOrderInSQLite.apply(this, arguments);
2702
+ }
2703
+ return updateOrderInSQLite;
2704
+ }()
2705
+ /**
2706
+ * 全量快照替换 orders 表(clear + bulkAdd),用于 SSE 全量拉取与营业日窗口裁剪。
2707
+ *
2708
+ * @example
2709
+ * await this.replaceOrdersSnapshotInSQLite(orderList)
2710
+ */
2711
+ )
2712
+ }, {
2713
+ key: "replaceOrdersSnapshotInSQLite",
2714
+ value: (function () {
2715
+ var _replaceOrdersSnapshotInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(orderList, source) {
2716
+ var _this22 = this;
2717
+ var remoteSnapshot, mergedSnapshot;
2718
+ return _regeneratorRuntime().wrap(function _callee24$(_context24) {
2719
+ while (1) switch (_context24.prev = _context24.next) {
2720
+ case 0:
2721
+ if (this.dbManager) {
2722
+ _context24.next = 2;
2723
+ break;
2724
+ }
2725
+ return _context24.abrupt("return", this.compactOrderListByIdentity(orderList.map(function (order) {
2726
+ return _this22.normalizeRemoteSyncedOrder(order);
2727
+ }), "".concat(source, ".snapshotNoDb")).list);
2728
+ case 2:
2729
+ remoteSnapshot = cloneDeep(orderList).map(function (order) {
2730
+ return _this22.normalizeOrderCollectionsForIngress(order, "".concat(source, ".remoteIngress"));
872
2731
  });
873
- case 14:
2732
+ mergedSnapshot = this.compactOrderListByIdentity(remoteSnapshot.map(function (order) {
2733
+ return _this22.normalizeRemoteSyncedOrder(order);
2734
+ }), "".concat(source, ".remoteSnapshot")).list;
2735
+ _context24.prev = 4;
2736
+ _context24.next = 7;
2737
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23() {
2738
+ var existingOrders, orderListSnapshot;
2739
+ return _regeneratorRuntime().wrap(function _callee23$(_context23) {
2740
+ while (1) switch (_context23.prev = _context23.next) {
2741
+ case 0:
2742
+ if (!(typeof _this22.dbManager.getAll === 'function')) {
2743
+ _context23.next = 6;
2744
+ break;
2745
+ }
2746
+ _context23.next = 3;
2747
+ return _this22.dbManager.getAll(INDEXDB_STORE_NAME);
2748
+ case 3:
2749
+ _context23.t0 = _context23.sent;
2750
+ _context23.next = 7;
2751
+ break;
2752
+ case 6:
2753
+ _context23.t0 = [];
2754
+ case 7:
2755
+ existingOrders = _context23.t0;
2756
+ orderListSnapshot = _this22.mergeRemoteSnapshotWithPendingOrders(remoteSnapshot, existingOrders || []);
2757
+ mergedSnapshot = _this22.compactOrderListByIdentity(orderListSnapshot, "".concat(source, ".sqliteSnapshot")).list;
2758
+ _this22.logInfo('replaceOrdersSnapshotInSQLite-开始', {
2759
+ source: source,
2760
+ count: mergedSnapshot.length,
2761
+ remoteCount: remoteSnapshot.length,
2762
+ preservedPendingCount: mergedSnapshot.length - remoteSnapshot.length
2763
+ });
2764
+ _context23.next = 13;
2765
+ return _this22.dbManager.clear(INDEXDB_STORE_NAME);
2766
+ case 13:
2767
+ _this22.logInfo('replaceOrdersSnapshotInSQLite-clear完成', {
2768
+ count: mergedSnapshot.length
2769
+ });
2770
+ if (!(mergedSnapshot.length === 0)) {
2771
+ _context23.next = 16;
2772
+ break;
2773
+ }
2774
+ return _context23.abrupt("return");
2775
+ case 16:
2776
+ _context23.next = 18;
2777
+ return _this22.dbManager.bulkAdd(INDEXDB_STORE_NAME, mergedSnapshot);
2778
+ case 18:
2779
+ _this22.recordRecentSqliteWrite(source, mergedSnapshot);
2780
+ _this22.logInfo('replaceOrdersSnapshotInSQLite-bulkAdd完成', {
2781
+ source: source,
2782
+ count: mergedSnapshot.length
2783
+ });
2784
+ case 20:
2785
+ case "end":
2786
+ return _context23.stop();
2787
+ }
2788
+ }, _callee23);
2789
+ })));
2790
+ case 7:
2791
+ _context24.next = 12;
2792
+ break;
2793
+ case 9:
2794
+ _context24.prev = 9;
2795
+ _context24.t0 = _context24["catch"](4);
2796
+ this.logError('全量保存订单到 SQLite 失败', {
2797
+ error: _context24.t0 instanceof Error ? _context24.t0.message : String(_context24.t0),
2798
+ orderList: remoteSnapshot.length
2799
+ });
2800
+ case 12:
2801
+ return _context24.abrupt("return", mergedSnapshot);
2802
+ case 13:
874
2803
  case "end":
875
- return _context8.stop();
2804
+ return _context24.stop();
876
2805
  }
877
- }, _callee8, this, [[2, 11]]);
2806
+ }, _callee24, this, [[4, 9]]);
878
2807
  }));
879
- function saveOrdersToSQLite(_x5) {
880
- return _saveOrdersToSQLite.apply(this, arguments);
2808
+ function replaceOrdersSnapshotInSQLite(_x16, _x17) {
2809
+ return _replaceOrdersSnapshotInSQLite.apply(this, arguments);
881
2810
  }
882
- return saveOrdersToSQLite;
2811
+ return replaceOrdersSnapshotInSQLite;
883
2812
  }()
2813
+ /**
2814
+ * 清空订单模块的内存数据和本地 SQLite 订单表。
2815
+ *
2816
+ * @example
2817
+ * await orderModule.clear()
2818
+ */
2819
+ )
884
2820
  }, {
885
2821
  key: "clear",
886
- value: function () {
887
- var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
888
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
889
- while (1) switch (_context9.prev = _context9.next) {
2822
+ value: (function () {
2823
+ var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26() {
2824
+ var _this23 = this;
2825
+ return _regeneratorRuntime().wrap(function _callee26$(_context26) {
2826
+ while (1) switch (_context26.prev = _context26.next) {
890
2827
  case 0:
891
2828
  this.store.list = [];
892
2829
  this.store.map = new Map();
893
- this.resourceIdIndex.clear();
894
2830
  if (!this.dbManager) {
895
- _context9.next = 6;
2831
+ _context26.next = 5;
896
2832
  break;
897
2833
  }
898
- _context9.next = 6;
899
- return this.dbManager.clear(INDEXDB_STORE_NAME);
900
- case 6:
2834
+ _context26.next = 5;
2835
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25() {
2836
+ return _regeneratorRuntime().wrap(function _callee25$(_context25) {
2837
+ while (1) switch (_context25.prev = _context25.next) {
2838
+ case 0:
2839
+ _context25.next = 2;
2840
+ return _this23.dbManager.clear(INDEXDB_STORE_NAME);
2841
+ case 2:
2842
+ case "end":
2843
+ return _context25.stop();
2844
+ }
2845
+ }, _callee25);
2846
+ })));
2847
+ case 5:
901
2848
  this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, '');
902
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
903
- case 8:
2849
+ this.emitOrdersChanged([], 'clear');
2850
+ case 7:
904
2851
  case "end":
905
- return _context9.stop();
2852
+ return _context26.stop();
906
2853
  }
907
- }, _callee9, this);
2854
+ }, _callee26, this);
908
2855
  }));
909
2856
  function clear() {
910
2857
  return _clear.apply(this, arguments);
911
2858
  }
912
2859
  return clear;
913
- }()
2860
+ }())
914
2861
  }]);
915
2862
  return OrderModule;
916
2863
  }(BaseModule);