@pisell/pisellos 2.2.244 → 2.2.245

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 (317) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.js +3 -2
  2. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  3. package/dist/model/strategy/adapter/walletPass/utils.js +7 -4
  4. package/dist/modules/BookingContext/index.d.ts +48 -0
  5. package/dist/modules/BookingContext/index.js +566 -0
  6. package/dist/modules/BookingContext/types.d.ts +102 -0
  7. package/dist/modules/BookingContext/types.js +51 -0
  8. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +16 -0
  9. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +284 -0
  10. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +8 -0
  11. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +145 -0
  12. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +76 -0
  13. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.js +218 -0
  14. package/dist/modules/BookingContext/utils/flexible.d.ts +28 -0
  15. package/dist/modules/BookingContext/utils/flexible.js +56 -0
  16. package/dist/modules/BookingContext/utils/formatResourceList.d.ts +8 -0
  17. package/dist/modules/BookingContext/utils/formatResourceList.js +38 -0
  18. package/dist/modules/BookingContext/utils/index.d.ts +11 -0
  19. package/dist/modules/BookingContext/utils/index.js +11 -0
  20. package/dist/modules/BookingContext/utils/noResource.d.ts +13 -0
  21. package/dist/modules/BookingContext/utils/noResource.js +77 -0
  22. package/dist/modules/BookingContext/utils/orderLineDisplay.d.ts +1 -0
  23. package/dist/modules/BookingContext/utils/orderLineDisplay.js +36 -0
  24. package/dist/modules/BookingContext/utils/productExtend.d.ts +72 -0
  25. package/dist/modules/BookingContext/utils/productExtend.js +339 -0
  26. package/dist/modules/BookingContext/utils/resourceErrors.d.ts +41 -0
  27. package/dist/modules/BookingContext/utils/resourceErrors.js +74 -0
  28. package/dist/modules/BookingContext/utils/resourceSelection.d.ts +7 -0
  29. package/dist/modules/BookingContext/utils/resourceSelection.js +24 -0
  30. package/dist/modules/BookingContext/utils/resources.d.ts +80 -0
  31. package/dist/modules/BookingContext/utils/resources.js +486 -0
  32. package/dist/modules/BookingContext/utils/serviceTimes.d.ts +55 -0
  33. package/dist/modules/BookingContext/utils/serviceTimes.js +151 -0
  34. package/dist/modules/BookingContext/utils/timeSlices.d.ts +42 -0
  35. package/dist/modules/BookingContext/utils/timeSlices.js +100 -0
  36. package/dist/modules/Cart/utils/cartProduct.js +24 -3
  37. package/dist/modules/Cart/utils/changePrice.js +11 -11
  38. package/dist/modules/Customer/index.d.ts +20 -0
  39. package/dist/modules/Customer/index.js +172 -83
  40. package/dist/modules/Customer/types.d.ts +2 -0
  41. package/dist/modules/Discount/index.d.ts +1 -1
  42. package/dist/modules/Discount/index.js +13 -6
  43. package/dist/modules/Discount/types.d.ts +1 -0
  44. package/dist/modules/OpenData/index.d.ts +8 -0
  45. package/dist/modules/OpenData/index.js +37 -17
  46. package/dist/modules/Order/index.d.ts +275 -19
  47. package/dist/modules/Order/index.js +3493 -809
  48. package/dist/modules/Order/types.d.ts +286 -31
  49. package/dist/modules/Order/types.js +38 -0
  50. package/dist/modules/Order/utils/manualProductDiscount.d.ts +106 -0
  51. package/dist/modules/Order/utils/manualProductDiscount.js +210 -0
  52. package/dist/modules/Order/utils.d.ts +147 -5
  53. package/dist/modules/Order/utils.js +750 -104
  54. package/dist/modules/Payment/index.d.ts +10 -13
  55. package/dist/modules/Payment/index.js +467 -837
  56. package/dist/modules/Payment/types.d.ts +2 -0
  57. package/dist/modules/Payment/utils.js +2 -1
  58. package/dist/modules/Payment/walletpass.js +41 -25
  59. package/dist/modules/ProductList/index.d.ts +16 -12
  60. package/dist/modules/ProductList/index.js +133 -59
  61. package/dist/modules/ProductList/types.d.ts +14 -0
  62. package/dist/modules/Quotation/index.d.ts +0 -1
  63. package/dist/modules/Quotation/index.js +25 -22
  64. package/dist/modules/Rules/index.d.ts +4 -0
  65. package/dist/modules/Rules/index.js +97 -70
  66. package/dist/modules/Rules/types.d.ts +1 -0
  67. package/dist/modules/SalesSummary/index.d.ts +8 -25
  68. package/dist/modules/SalesSummary/index.js +86 -35
  69. package/dist/modules/SalesSummary/types.d.ts +4 -1
  70. package/dist/modules/SalesSummary/utils.d.ts +2 -25
  71. package/dist/modules/SalesSummary/utils.js +794 -162
  72. package/dist/modules/Schedule/index.d.ts +7 -0
  73. package/dist/modules/Schedule/index.js +24 -2
  74. package/dist/modules/Summary/index.js +4 -3
  75. package/dist/modules/SurchargeList/index.d.ts +16 -0
  76. package/dist/modules/SurchargeList/index.js +162 -0
  77. package/dist/modules/SurchargeList/types.d.ts +11 -0
  78. package/dist/modules/SurchargeList/types.js +1 -0
  79. package/dist/modules/index.d.ts +2 -0
  80. package/dist/modules/index.js +3 -1
  81. package/dist/plugins/request.d.ts +1 -0
  82. package/dist/server/index.d.ts +204 -1
  83. package/dist/server/index.js +3654 -922
  84. package/dist/server/modules/index.d.ts +2 -0
  85. package/dist/server/modules/index.js +2 -0
  86. package/dist/server/modules/order/index.d.ts +120 -3
  87. package/dist/server/modules/order/index.js +1758 -448
  88. package/dist/server/modules/order/types.d.ts +32 -3
  89. package/dist/server/modules/order/types.js +8 -0
  90. package/dist/server/modules/order/utils/filterBookings.js +26 -3
  91. package/dist/server/modules/order/utils/filterOrders.js +23 -8
  92. package/dist/server/modules/payment/index.d.ts +28 -0
  93. package/dist/server/modules/payment/index.js +305 -0
  94. package/dist/server/modules/payment/types.d.ts +9 -0
  95. package/dist/server/modules/payment/types.js +1 -0
  96. package/dist/server/modules/products/index.d.ts +34 -7
  97. package/dist/server/modules/products/index.js +631 -317
  98. package/dist/server/modules/resource/index.d.ts +2 -0
  99. package/dist/server/modules/resource/index.js +29 -3
  100. package/dist/server/modules/schedule/index.d.ts +4 -4
  101. package/dist/server/modules/schedule/index.js +111 -88
  102. package/dist/server/test.json +713 -0
  103. package/dist/server/utils/small-ticket.d.ts +71 -0
  104. package/dist/server/utils/small-ticket.js +840 -0
  105. package/dist/solution/BaseSales/index.d.ts +133 -10
  106. package/dist/solution/BaseSales/index.js +1950 -447
  107. package/dist/solution/BaseSales/types.d.ts +82 -6
  108. package/dist/solution/BaseSales/types.js +5 -4
  109. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +287 -0
  110. package/dist/solution/BaseSales/utils/cartPromotion.js +1438 -0
  111. package/dist/solution/BaseSales/utils/quotationPrice.d.ts +7 -0
  112. package/dist/solution/BaseSales/utils/quotationPrice.js +237 -0
  113. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +1 -0
  114. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +105 -24
  115. package/dist/solution/BaseSales/utils.d.ts +1 -1
  116. package/dist/solution/BaseSales/utils.js +62 -21
  117. package/dist/solution/BookingByStep/index.d.ts +1 -1
  118. package/dist/solution/BookingTicket/index.d.ts +271 -11
  119. package/dist/solution/BookingTicket/index.js +1777 -242
  120. package/dist/solution/BookingTicket/types.d.ts +118 -1
  121. package/dist/solution/BookingTicket/types.js +41 -2
  122. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +117 -0
  123. package/dist/solution/BookingTicket/utils/addProductDecision.js +346 -0
  124. package/dist/solution/BookingTicket/utils/addTimeAvailability.d.ts +35 -0
  125. package/dist/solution/BookingTicket/utils/addTimeAvailability.js +95 -0
  126. package/dist/solution/BookingTicket/utils/bookingStatus.d.ts +40 -0
  127. package/dist/solution/BookingTicket/utils/bookingStatus.js +70 -0
  128. package/dist/solution/BookingTicket/utils/cartView.d.ts +9 -1
  129. package/dist/solution/BookingTicket/utils/cartView.js +94 -7
  130. package/dist/solution/BookingTicket/utils/exampleData.d.ts +123 -0
  131. package/dist/solution/BookingTicket/utils/exampleData.js +183 -0
  132. package/dist/solution/BookingTicket/utils/resolveBestAddTimePlan.d.ts +185 -0
  133. package/dist/solution/BookingTicket/utils/resolveBestAddTimePlan.js +438 -0
  134. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +36 -0
  135. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +400 -0
  136. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +32 -0
  137. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.js +56 -0
  138. package/dist/solution/BookingTicket/utils/scan/index.d.ts +5 -0
  139. package/dist/solution/BookingTicket/utils/scan/index.js +20 -8
  140. package/dist/solution/BookingTicket/utils/scan/scanProductValues.d.ts +21 -0
  141. package/dist/solution/BookingTicket/utils/scan/scanProductValues.js +150 -0
  142. package/dist/solution/BookingTicket/utils/sessionCatalogStale.d.ts +23 -0
  143. package/dist/solution/BookingTicket/utils/sessionCatalogStale.js +78 -0
  144. package/dist/solution/Checkout/index.d.ts +1 -0
  145. package/dist/solution/Checkout/index.js +10 -9
  146. package/dist/solution/RegisterAndLogin/config.js +2 -10
  147. package/dist/solution/ScanOrder/index.d.ts +9 -3
  148. package/dist/solution/ScanOrder/index.js +241 -134
  149. package/dist/solution/ScanOrder/types.d.ts +9 -5
  150. package/dist/solution/ScanOrder/types.js +2 -3
  151. package/dist/solution/ScanOrder/utils.d.ts +1 -1
  152. package/dist/solution/ScanOrder/utils.js +84 -22
  153. package/dist/solution/VenueBooking/index.d.ts +5 -2
  154. package/dist/solution/VenueBooking/index.js +110 -59
  155. package/dist/solution/VenueBooking/sales-section-4-annotated.json +0 -2
  156. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +4 -0
  157. package/dist/solution/VenueBooking/utils/slotMerge.js +10 -0
  158. package/dist/types/index.d.ts +10 -0
  159. package/lib/model/strategy/adapter/promotion/evaluator.js +2 -1
  160. package/lib/model/strategy/adapter/promotion/index.js +49 -0
  161. package/lib/model/strategy/adapter/walletPass/utils.js +3 -2
  162. package/lib/modules/BookingContext/index.d.ts +48 -0
  163. package/lib/modules/BookingContext/index.js +368 -0
  164. package/lib/modules/BookingContext/types.d.ts +102 -0
  165. package/lib/modules/BookingContext/types.js +34 -0
  166. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +16 -0
  167. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +276 -0
  168. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +8 -0
  169. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +151 -0
  170. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +76 -0
  171. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.js +201 -0
  172. package/lib/modules/BookingContext/utils/flexible.d.ts +28 -0
  173. package/lib/modules/BookingContext/utils/flexible.js +80 -0
  174. package/lib/modules/BookingContext/utils/formatResourceList.d.ts +8 -0
  175. package/lib/modules/BookingContext/utils/formatResourceList.js +50 -0
  176. package/lib/modules/BookingContext/utils/index.d.ts +11 -0
  177. package/lib/modules/BookingContext/utils/index.js +43 -0
  178. package/lib/modules/BookingContext/utils/noResource.d.ts +13 -0
  179. package/lib/modules/BookingContext/utils/noResource.js +90 -0
  180. package/lib/modules/BookingContext/utils/orderLineDisplay.d.ts +1 -0
  181. package/lib/modules/BookingContext/utils/orderLineDisplay.js +56 -0
  182. package/lib/modules/BookingContext/utils/productExtend.d.ts +72 -0
  183. package/lib/modules/BookingContext/utils/productExtend.js +283 -0
  184. package/lib/modules/BookingContext/utils/resourceErrors.d.ts +41 -0
  185. package/lib/modules/BookingContext/utils/resourceErrors.js +80 -0
  186. package/lib/modules/BookingContext/utils/resourceSelection.d.ts +7 -0
  187. package/lib/modules/BookingContext/utils/resourceSelection.js +46 -0
  188. package/lib/modules/BookingContext/utils/resources.d.ts +80 -0
  189. package/lib/modules/BookingContext/utils/resources.js +377 -0
  190. package/lib/modules/BookingContext/utils/serviceTimes.d.ts +55 -0
  191. package/lib/modules/BookingContext/utils/serviceTimes.js +162 -0
  192. package/lib/modules/BookingContext/utils/timeSlices.d.ts +42 -0
  193. package/lib/modules/BookingContext/utils/timeSlices.js +124 -0
  194. package/lib/modules/Cart/utils/cartProduct.js +20 -3
  195. package/lib/modules/Cart/utils/changePrice.js +12 -20
  196. package/lib/modules/Customer/index.d.ts +20 -0
  197. package/lib/modules/Customer/index.js +64 -11
  198. package/lib/modules/Customer/types.d.ts +2 -0
  199. package/lib/modules/Discount/index.d.ts +1 -1
  200. package/lib/modules/Discount/index.js +9 -1
  201. package/lib/modules/Discount/types.d.ts +1 -0
  202. package/lib/modules/OpenData/index.d.ts +8 -0
  203. package/lib/modules/OpenData/index.js +19 -5
  204. package/lib/modules/Order/index.d.ts +275 -19
  205. package/lib/modules/Order/index.js +2245 -336
  206. package/lib/modules/Order/types.d.ts +286 -31
  207. package/lib/modules/Order/types.js +1 -0
  208. package/lib/modules/Order/utils/manualProductDiscount.d.ts +106 -0
  209. package/lib/modules/Order/utils/manualProductDiscount.js +206 -0
  210. package/lib/modules/Order/utils.d.ts +147 -5
  211. package/lib/modules/Order/utils.js +615 -46
  212. package/lib/modules/Payment/index.d.ts +10 -13
  213. package/lib/modules/Payment/index.js +18 -150
  214. package/lib/modules/Payment/types.d.ts +2 -0
  215. package/lib/modules/Payment/utils.js +2 -1
  216. package/lib/modules/Payment/walletpass.js +16 -3
  217. package/lib/modules/ProductList/index.d.ts +16 -12
  218. package/lib/modules/ProductList/index.js +41 -4
  219. package/lib/modules/ProductList/types.d.ts +14 -0
  220. package/lib/modules/Quotation/index.d.ts +0 -1
  221. package/lib/modules/Quotation/index.js +19 -16
  222. package/lib/modules/Rules/index.d.ts +4 -0
  223. package/lib/modules/Rules/index.js +137 -120
  224. package/lib/modules/Rules/types.d.ts +1 -0
  225. package/lib/modules/SalesSummary/index.d.ts +8 -25
  226. package/lib/modules/SalesSummary/index.js +30 -4
  227. package/lib/modules/SalesSummary/types.d.ts +4 -1
  228. package/lib/modules/SalesSummary/utils.d.ts +2 -25
  229. package/lib/modules/SalesSummary/utils.js +645 -91
  230. package/lib/modules/Schedule/index.d.ts +7 -0
  231. package/lib/modules/Schedule/index.js +17 -1
  232. package/lib/modules/Summary/index.js +5 -4
  233. package/lib/modules/SurchargeList/index.d.ts +16 -0
  234. package/lib/modules/SurchargeList/index.js +89 -0
  235. package/lib/modules/SurchargeList/types.d.ts +11 -0
  236. package/lib/modules/SurchargeList/types.js +17 -0
  237. package/lib/modules/index.d.ts +2 -0
  238. package/lib/modules/index.js +5 -1
  239. package/lib/plugins/request.d.ts +1 -0
  240. package/lib/server/index.d.ts +204 -1
  241. package/lib/server/index.js +1891 -59
  242. package/lib/server/modules/index.d.ts +2 -0
  243. package/lib/server/modules/index.js +3 -0
  244. package/lib/server/modules/order/index.d.ts +120 -3
  245. package/lib/server/modules/order/index.js +883 -94
  246. package/lib/server/modules/order/types.d.ts +32 -3
  247. package/lib/server/modules/order/utils/filterBookings.js +24 -5
  248. package/lib/server/modules/order/utils/filterOrders.js +15 -6
  249. package/lib/server/modules/payment/index.d.ts +28 -0
  250. package/lib/server/modules/payment/index.js +192 -0
  251. package/lib/server/modules/payment/types.d.ts +9 -0
  252. package/lib/server/modules/payment/types.js +17 -0
  253. package/lib/server/modules/products/index.d.ts +34 -7
  254. package/lib/server/modules/products/index.js +189 -54
  255. package/lib/server/modules/resource/index.d.ts +2 -0
  256. package/lib/server/modules/resource/index.js +27 -3
  257. package/lib/server/modules/schedule/index.d.ts +4 -4
  258. package/lib/server/modules/schedule/index.js +47 -40
  259. package/lib/server/test.json +713 -0
  260. package/lib/server/utils/small-ticket.d.ts +71 -0
  261. package/lib/server/utils/small-ticket.js +800 -0
  262. package/lib/solution/BaseSales/index.d.ts +133 -10
  263. package/lib/solution/BaseSales/index.js +1111 -63
  264. package/lib/solution/BaseSales/types.d.ts +82 -6
  265. package/lib/solution/BaseSales/types.js +3 -1
  266. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +287 -0
  267. package/lib/solution/BaseSales/utils/cartPromotion.js +992 -0
  268. package/lib/solution/BaseSales/utils/quotationPrice.d.ts +7 -0
  269. package/lib/solution/BaseSales/utils/quotationPrice.js +277 -0
  270. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +1 -0
  271. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +106 -18
  272. package/lib/solution/BaseSales/utils.d.ts +1 -1
  273. package/lib/solution/BaseSales/utils.js +54 -10
  274. package/lib/solution/BookingByStep/index.d.ts +1 -1
  275. package/lib/solution/BookingTicket/index.d.ts +271 -11
  276. package/lib/solution/BookingTicket/index.js +922 -29
  277. package/lib/solution/BookingTicket/types.d.ts +118 -1
  278. package/lib/solution/BookingTicket/types.js +11 -0
  279. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +117 -0
  280. package/lib/solution/BookingTicket/utils/addProductDecision.js +318 -0
  281. package/lib/solution/BookingTicket/utils/addTimeAvailability.d.ts +35 -0
  282. package/lib/solution/BookingTicket/utils/addTimeAvailability.js +125 -0
  283. package/lib/solution/BookingTicket/utils/bookingStatus.d.ts +40 -0
  284. package/lib/solution/BookingTicket/utils/bookingStatus.js +44 -2
  285. package/lib/solution/BookingTicket/utils/cartView.d.ts +9 -1
  286. package/lib/solution/BookingTicket/utils/cartView.js +61 -6
  287. package/lib/solution/BookingTicket/utils/exampleData.d.ts +123 -0
  288. package/lib/solution/BookingTicket/utils/exampleData.js +0 -0
  289. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.d.ts +185 -0
  290. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.js +254 -0
  291. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +36 -0
  292. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +169 -0
  293. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +32 -0
  294. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.js +51 -0
  295. package/lib/solution/BookingTicket/utils/scan/index.d.ts +5 -0
  296. package/lib/solution/BookingTicket/utils/scan/index.js +17 -3
  297. package/lib/solution/BookingTicket/utils/scan/scanProductValues.d.ts +21 -0
  298. package/lib/solution/BookingTicket/utils/scan/scanProductValues.js +127 -0
  299. package/lib/solution/BookingTicket/utils/sessionCatalogStale.d.ts +23 -0
  300. package/lib/solution/BookingTicket/utils/sessionCatalogStale.js +85 -0
  301. package/lib/solution/Checkout/index.d.ts +1 -0
  302. package/lib/solution/Checkout/index.js +1 -2
  303. package/lib/solution/RegisterAndLogin/config.js +2 -10
  304. package/lib/solution/ScanOrder/index.d.ts +9 -3
  305. package/lib/solution/ScanOrder/index.js +153 -70
  306. package/lib/solution/ScanOrder/types.d.ts +9 -5
  307. package/lib/solution/ScanOrder/utils.d.ts +1 -1
  308. package/lib/solution/ScanOrder/utils.js +83 -17
  309. package/lib/solution/VenueBooking/index.d.ts +5 -2
  310. package/lib/solution/VenueBooking/index.js +54 -17
  311. package/lib/solution/VenueBooking/sales-section-4-annotated.json +0 -2
  312. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +4 -0
  313. package/lib/solution/VenueBooking/utils/slotMerge.js +10 -0
  314. package/lib/types/index.d.ts +10 -0
  315. package/package.json +1 -1
  316. package/dist/solution/Checkout/appointmentDemo.json +0 -1
  317. 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; }
@@ -38,6 +42,12 @@ var INDEXDB_STORE_NAME = 'orders';
38
42
  var ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY = 'server_order_last_full_fetch_at';
39
43
  var ORDER_SYNC_THROTTLE_MS_STORAGE_KEY = 'order_sync_throttle_ms';
40
44
  var DEFAULT_ORDER_SYNC_THROTTLE_MS = 2000;
45
+ /** pubsub 回声写入去重窗口:业务 API 刚写入后,跳过同单 SQLite patch */
46
+ var ORDER_SQLITE_DEDUPE_MS = 15000;
47
+ /** silentRefresh 最小间隔,避免 preload 后立即全量重拉 */
48
+ var ORDER_SILENT_REFRESH_MIN_INTERVAL_MS = 30000;
49
+ /** 视为「业务侧刚写入」的来源,pubsub 回声可跳过 SQLite */
50
+ var ORDER_BUSINESS_WRITE_SOURCES = new Set(['upsertOrdersFromRemote', 'upsertPendingSyncOrders', 'overwriteExistingOrder', 'markOrderSyncedByExternalSaleNumber']);
41
51
 
42
52
  /**
43
53
  * Order 模块 - 基础框架
@@ -63,16 +73,64 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
63
73
  _defineProperty(_assertThisInitialized(_this), "logger", void 0);
64
74
  // LoggerManager 实例
65
75
  _defineProperty(_assertThisInitialized(_this), "storage", void 0);
76
+ _defineProperty(_assertThisInitialized(_this), "orderSQLiteSaveQueue", Promise.resolve());
77
+ /** 按 storageKey 记录最近一次 SQLite 写入来源与时间,用于去重 */
78
+ _defineProperty(_assertThisInitialized(_this), "recentSqliteWriteByStorageKey", new Map());
79
+ /** 最近一次 SSE 全量拉取完成时间 */
80
+ _defineProperty(_assertThisInitialized(_this), "lastServerFullFetchAtMs", 0);
66
81
  return _this;
67
82
  }
83
+
84
+ /**
85
+ * 广播订单变更事件,兼容全量列表订阅并额外携带本次变更订单。
86
+ *
87
+ * @example
88
+ * await this.emitOrdersChanged([freshOrder], 'pubsub.bodyUpsert')
89
+ */
68
90
  _createClass(OrderModule, [{
91
+ key: "emitOrdersChanged",
92
+ value: (function () {
93
+ var _emitOrdersChanged = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
94
+ var _this2 = this;
95
+ var changedOrders,
96
+ source,
97
+ payload,
98
+ _args = arguments;
99
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
100
+ while (1) switch (_context.prev = _context.next) {
101
+ case 0:
102
+ changedOrders = _args.length > 0 && _args[0] !== undefined ? _args[0] : [];
103
+ source = _args.length > 1 ? _args[1] : undefined;
104
+ console.log('触发emitOrdersChanged');
105
+ payload = {
106
+ list: this.store.list,
107
+ changedOrders: changedOrders.map(function (order) {
108
+ return _this2.normalizeOrderForMemoryList(order);
109
+ }),
110
+ source: source
111
+ };
112
+ _context.next = 6;
113
+ return this.core.effects.emit(OrderHooks.onOrdersChanged, payload);
114
+ case 6:
115
+ case "end":
116
+ return _context.stop();
117
+ }
118
+ }, _callee, this);
119
+ }));
120
+ function emitOrdersChanged() {
121
+ return _emitOrdersChanged.apply(this, arguments);
122
+ }
123
+ return emitOrdersChanged;
124
+ }())
125
+ }, {
69
126
  key: "initialize",
70
127
  value: function () {
71
- var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
72
- var _options$initialState;
128
+ var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(core, options) {
129
+ var _options$initialState,
130
+ _this3 = this;
73
131
  var appPlugin, app;
74
- return _regeneratorRuntime().wrap(function _callee$(_context) {
75
- while (1) switch (_context.prev = _context.next) {
132
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
133
+ while (1) switch (_context2.prev = _context2.next) {
76
134
  case 0:
77
135
  this.core = core;
78
136
  this.store = options === null || options === void 0 ? void 0 : options.store;
@@ -86,9 +144,11 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
86
144
  this.updateCreateStore();
87
145
  }
88
146
  if (Array.isArray(options === null || options === void 0 || (_options$initialState = options.initialState) === null || _options$initialState === void 0 ? void 0 : _options$initialState.list)) {
89
- this.store.list = options.initialState.list;
147
+ this.store.list = options.initialState.list.map(function (order) {
148
+ return _this3.normalizeOrderForMemoryList(order);
149
+ });
90
150
  this.syncOrdersMap();
91
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
151
+ this.emitOrdersChanged([], 'initialState');
92
152
  } else {
93
153
  this.store.list = [];
94
154
  this.store.map = new Map();
@@ -102,9 +162,9 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
102
162
  });
103
163
  case 10:
104
164
  case "end":
105
- return _context.stop();
165
+ return _context2.stop();
106
166
  }
107
- }, _callee, this);
167
+ }, _callee2, this);
108
168
  }));
109
169
  function initialize(_x, _x2) {
110
170
  return _initialize.apply(this, arguments);
@@ -152,6 +212,231 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
152
212
  // 日志记录失败不影响主流程
153
213
  }
154
214
  }
215
+ }, {
216
+ key: "logWarning",
217
+ value: function logWarning(title, metadata) {
218
+ try {
219
+ if (this.logger) {
220
+ this.logger.addLog({
221
+ type: 'warning',
222
+ title: "[OrderServerModule] ".concat(title),
223
+ metadata: metadata || {}
224
+ });
225
+ }
226
+ } catch (_unused3) {
227
+ // 日志记录失败不影响主流程
228
+ }
229
+ }
230
+
231
+ /**
232
+ * 记录订单最近一次 SQLite 写入,供 pubsub 回声去重使用。
233
+ *
234
+ * @example
235
+ * this.recordRecentSqliteWrite('upsertOrdersFromRemote', orders)
236
+ */
237
+ }, {
238
+ key: "recordRecentSqliteWrite",
239
+ value: function recordRecentSqliteWrite(source, orders) {
240
+ var now = Date.now();
241
+ var _iterator = _createForOfIteratorHelper(orders),
242
+ _step;
243
+ try {
244
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
245
+ var order = _step.value;
246
+ var storageKey = this.getOrderStorageKey(order);
247
+ if (!storageKey) continue;
248
+ this.recentSqliteWriteByStorageKey.set(storageKey, {
249
+ source: source,
250
+ ts: now
251
+ });
252
+ }
253
+ } catch (err) {
254
+ _iterator.e(err);
255
+ } finally {
256
+ _iterator.f();
257
+ }
258
+ }
259
+
260
+ /**
261
+ * 过滤 pubsub 触发的冗余 SQLite patch(业务 API 刚写入过的 update 回声)。
262
+ *
263
+ * @example
264
+ * const { toWrite, skipped } = this.filterRedundantPatchOrders('pubsub.bodyUpsert', orders, mergeActions)
265
+ */
266
+ }, {
267
+ key: "filterRedundantPatchOrders",
268
+ value: function filterRedundantPatchOrders(source, orders, mergeActions) {
269
+ var eligibleSkipSources = new Set(['pubsub.bodyUpsert', 'pubsub.httpRefresh']);
270
+ if (!eligibleSkipSources.has(source)) {
271
+ return {
272
+ toWrite: orders,
273
+ skipped: []
274
+ };
275
+ }
276
+ var now = Date.now();
277
+ var toWrite = [];
278
+ var skipped = [];
279
+ var _iterator2 = _createForOfIteratorHelper(orders),
280
+ _step2;
281
+ try {
282
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
283
+ var order = _step2.value;
284
+ var storageKey = this.getOrderStorageKey(order);
285
+ if (!storageKey) {
286
+ toWrite.push(order);
287
+ continue;
288
+ }
289
+ var orderKey = order.order_id !== undefined && order.order_id !== null ? this.getIdKey(order.order_id) : '';
290
+ var mergeAction = orderKey ? mergeActions[orderKey] : undefined;
291
+
292
+ // 新增单必须落库,不参与去重
293
+ if (mergeAction === 'insert') {
294
+ toWrite.push(order);
295
+ continue;
296
+ }
297
+ var recent = this.recentSqliteWriteByStorageKey.get(storageKey);
298
+ if (recent && ORDER_BUSINESS_WRITE_SOURCES.has(recent.source) && now - recent.ts < ORDER_SQLITE_DEDUPE_MS) {
299
+ var _order$order_id;
300
+ skipped.push({
301
+ orderId: (_order$order_id = order.order_id) !== null && _order$order_id !== void 0 ? _order$order_id : null,
302
+ storageKey: storageKey,
303
+ reason: 'skip_pubsub_echo_after_business_write',
304
+ lastSource: recent.source,
305
+ elapsedMs: now - recent.ts
306
+ });
307
+ continue;
308
+ }
309
+ toWrite.push(order);
310
+ }
311
+ } catch (err) {
312
+ _iterator2.e(err);
313
+ } finally {
314
+ _iterator2.f();
315
+ }
316
+ return {
317
+ toWrite: toWrite,
318
+ skipped: skipped
319
+ };
320
+ }
321
+
322
+ /**
323
+ * 过滤 pubsub HTTP 增量拉取 ids:本地刚由业务 API 写入的单可跳过 HTTP。
324
+ *
325
+ * @example
326
+ * const ids = this.filterRedundantHttpRefreshIds([99331, 99332])
327
+ */
328
+ }, {
329
+ key: "filterRedundantHttpRefreshIds",
330
+ value: function filterRedundantHttpRefreshIds(ids) {
331
+ var now = Date.now();
332
+ var toFetch = [];
333
+ var skipped = [];
334
+ var _iterator3 = _createForOfIteratorHelper(ids),
335
+ _step3;
336
+ try {
337
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
338
+ var id = _step3.value;
339
+ var existing = this.getOrderByOrderId(id);
340
+ if (!existing) {
341
+ toFetch.push(id);
342
+ continue;
343
+ }
344
+ var storageKey = this.getOrderStorageKey(existing);
345
+ var recent = storageKey ? this.recentSqliteWriteByStorageKey.get(storageKey) : undefined;
346
+ if (recent && recent.source === 'upsertOrdersFromRemote' && now - recent.ts < ORDER_SQLITE_DEDUPE_MS) {
347
+ skipped.push({
348
+ orderId: id,
349
+ lastSource: recent.source,
350
+ elapsedMs: now - recent.ts
351
+ });
352
+ continue;
353
+ }
354
+ toFetch.push(id);
355
+ }
356
+ } catch (err) {
357
+ _iterator3.e(err);
358
+ } finally {
359
+ _iterator3.f();
360
+ }
361
+ return {
362
+ toFetch: toFetch,
363
+ skipped: skipped
364
+ };
365
+ }
366
+
367
+ /**
368
+ * 解析 pubsub 消息会走哪条同步分支,便于对照为何触发 HTTP 重拉或 body 直写。
369
+ *
370
+ * @example
371
+ * this.resolveSyncMessageRoute(msg)
372
+ * // => { route: 'httpRefresh.batchIds', ... }
373
+ */
374
+ }, {
375
+ key: "resolveSyncMessageRoute",
376
+ value: function resolveSyncMessageRoute(msg) {
377
+ var _msg$id, _msg$relation_order_i, _normalizedBody$order5;
378
+ var hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
379
+ var singleIdRaw = (_msg$id = msg.id) !== null && _msg$id !== void 0 ? _msg$id : msg.order_id;
380
+ var hasSingleId = !hasBatchIds && singleIdRaw !== undefined && singleIdRaw !== null;
381
+ var normalizedBody = this.normalizeOrderSyncPayload(msg.body || msg.data);
382
+ if (hasBatchIds) {
383
+ var _normalizedBody$order;
384
+ return {
385
+ route: 'httpRefresh.batchIds',
386
+ hasBatchIds: true,
387
+ hasSingleId: false,
388
+ hasNormalizedBody: !!normalizedBody,
389
+ singleId: null,
390
+ batchIds: msg.ids || [],
391
+ bodyOrderId: (_normalizedBody$order = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order !== void 0 ? _normalizedBody$order : null
392
+ };
393
+ }
394
+ if (hasSingleId && normalizedBody) {
395
+ var _normalizedBody$order2;
396
+ return {
397
+ route: 'bodyUpsert',
398
+ hasBatchIds: false,
399
+ hasSingleId: true,
400
+ hasNormalizedBody: true,
401
+ singleId: singleIdRaw,
402
+ batchIds: [],
403
+ bodyOrderId: (_normalizedBody$order2 = normalizedBody.order_id) !== null && _normalizedBody$order2 !== void 0 ? _normalizedBody$order2 : null
404
+ };
405
+ }
406
+ if (hasSingleId) {
407
+ var _normalizedBody$order3;
408
+ return {
409
+ route: 'httpRefresh.singleId',
410
+ hasBatchIds: false,
411
+ hasSingleId: true,
412
+ hasNormalizedBody: !!normalizedBody,
413
+ singleId: singleIdRaw,
414
+ batchIds: [],
415
+ bodyOrderId: (_normalizedBody$order3 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order3 !== void 0 ? _normalizedBody$order3 : null
416
+ };
417
+ }
418
+ if ((_msg$relation_order_i = msg.relation_order_ids) !== null && _msg$relation_order_i !== void 0 && _msg$relation_order_i.length) {
419
+ var _normalizedBody$order4;
420
+ return {
421
+ route: 'httpRefresh.relationIds',
422
+ hasBatchIds: false,
423
+ hasSingleId: false,
424
+ hasNormalizedBody: !!normalizedBody,
425
+ singleId: null,
426
+ batchIds: msg.relation_order_ids,
427
+ bodyOrderId: (_normalizedBody$order4 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order4 !== void 0 ? _normalizedBody$order4 : null
428
+ };
429
+ }
430
+ return {
431
+ route: 'noop',
432
+ hasBatchIds: false,
433
+ hasSingleId: false,
434
+ hasNormalizedBody: !!normalizedBody,
435
+ singleId: null,
436
+ batchIds: [],
437
+ bodyOrderId: (_normalizedBody$order5 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order5 !== void 0 ? _normalizedBody$order5 : null
438
+ };
439
+ }
155
440
  }, {
156
441
  key: "updateCreateStore",
157
442
  value: function updateCreateStore() {
@@ -207,13 +492,12 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
207
492
  }, {
208
493
  key: "preload",
209
494
  value: function () {
210
- var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
211
- var _this2 = this;
495
+ var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
496
+ var _this4 = this;
212
497
  var getData;
213
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
214
- while (1) switch (_context3.prev = _context3.next) {
498
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
499
+ while (1) switch (_context4.prev = _context4.next) {
215
500
  case 0:
216
- // const cachedOrders = await this.loadOrdersFromSQLite()
217
501
  // const hasPulledInCurrentWindow = this.hasPulledOrdersToday()
218
502
  // // 仅当缓存属于当前统计窗口时才直接复用,避免跨天/跨营业日窗口继续使用旧数据
219
503
  // if (cachedOrders.length > 0 && hasPulledInCurrentWindow) {
@@ -229,30 +513,30 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
229
513
  // return
230
514
  // }
231
515
  getData = /*#__PURE__*/function () {
232
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
516
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
233
517
  var orders;
234
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
235
- while (1) switch (_context2.prev = _context2.next) {
518
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
519
+ while (1) switch (_context3.prev = _context3.next) {
236
520
  case 0:
237
- _context2.next = 2;
238
- return _this2.loadOrdersByServer();
521
+ _context3.next = 2;
522
+ return _this4.loadOrdersByServer();
239
523
  case 2:
240
- orders = _context2.sent;
524
+ orders = _context3.sent;
241
525
  if (!(orders.length === 0)) {
242
- _context2.next = 5;
526
+ _context3.next = 5;
243
527
  break;
244
528
  }
245
- return _context2.abrupt("return");
529
+ return _context3.abrupt("return");
246
530
  case 5:
247
- _this2.store.list = cloneDeep(orders);
248
- _this2.syncOrdersMap();
249
- _this2.core.effects.emit(OrderHooks.onOrdersChanged, _this2.store.list);
250
- _this2.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
531
+ _this4.store.list = cloneDeep(orders);
532
+ _this4.syncOrdersMap();
533
+ _this4.emitOrdersChanged([], 'preload');
534
+ _this4.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
251
535
  case 9:
252
536
  case "end":
253
- return _context2.stop();
537
+ return _context3.stop();
254
538
  }
255
- }, _callee2);
539
+ }, _callee3);
256
540
  }));
257
541
  return function getData() {
258
542
  return _ref.apply(this, arguments);
@@ -261,9 +545,9 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
261
545
  getData();
262
546
  case 2:
263
547
  case "end":
264
- return _context3.stop();
548
+ return _context4.stop();
265
549
  }
266
- }, _callee3);
550
+ }, _callee4);
267
551
  }));
268
552
  function preload() {
269
553
  return _preload.apply(this, arguments);
@@ -281,68 +565,88 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
281
565
  return this.store.map.get(this.getIdKey(id));
282
566
  }
283
567
 
284
- /** 按 order_id 查询(推荐) */
568
+ /** 按 order_id 查询内存订单。 */
285
569
  }, {
286
570
  key: "getOrderByOrderId",
287
571
  value: function getOrderByOrderId(orderId) {
288
572
  return this.store.map.get(this.getIdKey(orderId));
289
573
  }
290
574
  }, {
291
- key: "getLocalOrderByOrderId",
575
+ key: "getLocalOrderFromMemoryByLookup",
576
+ value: function getLocalOrderFromMemoryByLookup(lookup) {
577
+ var _this5 = this;
578
+ var key = this.getIdKey(lookup);
579
+ var memoryOrderById = this.store.map.get(key);
580
+ if (memoryOrderById) return memoryOrderById;
581
+ var memoryOrder = this.store.list.find(function (order) {
582
+ return _this5.isOrderLookupMatch(order, key);
583
+ });
584
+ return memoryOrder || null;
585
+ }
586
+ }, {
587
+ key: "getLocalOrderByLookup",
292
588
  value: function () {
293
- var _getLocalOrderByOrderId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(orderId) {
294
- var _this3 = this;
295
- var key, memoryOrder, orders, localOrder;
296
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
297
- while (1) switch (_context4.prev = _context4.next) {
589
+ var _getLocalOrderByLookup = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(lookup) {
590
+ var _this6 = this;
591
+ var key, memoryOrderById, memoryOrder, orders, localOrder;
592
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
593
+ while (1) switch (_context5.prev = _context5.next) {
298
594
  case 0:
299
- key = this.getIdKey(orderId);
300
- memoryOrder = this.store.map.get(key);
301
- if (!memoryOrder) {
302
- _context4.next = 4;
595
+ key = this.getIdKey(lookup);
596
+ memoryOrderById = this.store.map.get(key);
597
+ if (!memoryOrderById) {
598
+ _context5.next = 4;
303
599
  break;
304
600
  }
305
- return _context4.abrupt("return", memoryOrder);
601
+ return _context5.abrupt("return", memoryOrderById);
306
602
  case 4:
307
- _context4.next = 6;
603
+ memoryOrder = this.store.list.find(function (order) {
604
+ return _this6.isOrderLookupMatch(order, key);
605
+ });
606
+ if (!memoryOrder) {
607
+ _context5.next = 7;
608
+ break;
609
+ }
610
+ return _context5.abrupt("return", memoryOrder);
611
+ case 7:
612
+ _context5.next = 9;
308
613
  return this.loadOrdersFromSQLite();
309
- case 6:
310
- orders = _context4.sent;
614
+ case 9:
615
+ orders = _context5.sent;
311
616
  localOrder = orders.find(function (order) {
312
- var shopOrderNumber = order === null || order === void 0 ? void 0 : order.shop_order_number;
313
- if (shopOrderNumber && _this3.getIdKey(shopOrderNumber) === key) return true;
314
- var id = order === null || order === void 0 ? void 0 : order.order_id;
315
- if (id === undefined || id === null) return false;
316
- return _this3.getIdKey(id) === key;
617
+ return _this6.isOrderLookupMatch(order, key);
317
618
  });
318
619
  if (localOrder) {
319
- _context4.next = 10;
620
+ _context5.next = 13;
320
621
  break;
321
622
  }
322
- return _context4.abrupt("return", null);
323
- case 10:
324
- this.store.list = orders;
325
- this.syncOrdersMap();
326
- return _context4.abrupt("return", localOrder);
623
+ return _context5.abrupt("return", null);
327
624
  case 13:
625
+ this.store.list = orders.map(function (order) {
626
+ return _this6.normalizeOrderForMemoryList(order);
627
+ });
628
+ this.syncOrdersMap();
629
+ return _context5.abrupt("return", this.normalizeOrderForMemoryList(localOrder));
630
+ case 16:
328
631
  case "end":
329
- return _context4.stop();
632
+ return _context5.stop();
330
633
  }
331
- }, _callee4, this);
634
+ }, _callee5, this);
332
635
  }));
333
- function getLocalOrderByOrderId(_x3) {
334
- return _getLocalOrderByOrderId.apply(this, arguments);
636
+ function getLocalOrderByLookup(_x3) {
637
+ return _getLocalOrderByLookup.apply(this, arguments);
335
638
  }
336
- return getLocalOrderByOrderId;
639
+ return getLocalOrderByLookup;
337
640
  }()
338
641
  }, {
339
642
  key: "loadOrdersByServer",
340
643
  value: function () {
341
- var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
342
- var _this$store;
343
- var orderList, data;
344
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
345
- while (1) switch (_context5.prev = _context5.next) {
644
+ var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
645
+ var _this$store,
646
+ _this7 = this;
647
+ var orderList, data, mergedOrders, memoryOrders;
648
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
649
+ while (1) switch (_context6.prev = _context6.next) {
346
650
  case 0:
347
651
  orderList = [];
348
652
  this.logInfo('loadOrdersByServer-开始', {
@@ -350,46 +654,51 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
350
654
  query: ((_this$store = this.store) === null || _this$store === void 0 ? void 0 : _this$store.createdAtQuery) || null
351
655
  });
352
656
  if (!this.orderDataSource) {
353
- _context5.next = 16;
657
+ _context6.next = 17;
354
658
  break;
355
659
  }
356
- _context5.prev = 3;
357
- _context5.next = 6;
660
+ _context6.prev = 3;
661
+ _context6.next = 6;
358
662
  return this.orderDataSource.run({
359
663
  sse: {
360
664
  query: this.store.createdAtQuery
361
665
  }
362
666
  });
363
667
  case 6:
364
- data = _context5.sent;
668
+ data = _context6.sent;
365
669
  orderList = data || [];
366
670
  this.logInfo('loadOrdersByServer-SSE拉取成功', {
367
671
  count: orderList.length
368
672
  });
369
673
  this.markOrderPulledAtNow();
370
- _context5.next = 16;
674
+ this.lastServerFullFetchAtMs = Date.now();
675
+ _context6.next = 17;
371
676
  break;
372
- case 12:
373
- _context5.prev = 12;
374
- _context5.t0 = _context5["catch"](3);
375
- orderList = [];
376
- this.logInfo('loadOrdersByServer-SSE拉取失败,回退为空数组');
377
- case 16:
378
- _context5.next = 18;
379
- return this.saveOrdersToSQLite(orderList);
380
- case 18:
677
+ case 13:
678
+ _context6.prev = 13;
679
+ _context6.t0 = _context6["catch"](3);
680
+ this.logInfo('loadOrdersByServer-SSE拉取失败,保持当前内存订单');
681
+ return _context6.abrupt("return", this.store.list);
682
+ case 17:
683
+ _context6.next = 19;
684
+ return this.replaceOrdersSnapshotInSQLite(orderList, 'loadOrdersByServer');
685
+ case 19:
686
+ mergedOrders = _context6.sent;
687
+ memoryOrders = mergedOrders.map(function (order) {
688
+ return _this7.normalizeOrderForMemoryList(order);
689
+ });
381
690
  this.logInfo('loadOrdersByServer-结束', {
382
- count: orderList.length
691
+ count: memoryOrders.length
383
692
  });
384
- _context5.next = 21;
385
- return this.core.effects.emit(OrderHooks.onOrdersLoaded, orderList);
386
- case 21:
387
- return _context5.abrupt("return", orderList);
388
- case 22:
693
+ _context6.next = 24;
694
+ return this.core.effects.emit(OrderHooks.onOrdersLoaded, memoryOrders);
695
+ case 24:
696
+ return _context6.abrupt("return", memoryOrders);
697
+ case 25:
389
698
  case "end":
390
- return _context5.stop();
699
+ return _context6.stop();
391
700
  }
392
- }, _callee5, this, [[3, 12]]);
701
+ }, _callee6, this, [[3, 13]]);
393
702
  }));
394
703
  function loadOrdersByServer() {
395
704
  return _loadOrdersByServer.apply(this, arguments);
@@ -404,54 +713,61 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
404
713
  }, {
405
714
  key: "silentRefresh",
406
715
  value: (function () {
407
- var _silentRefresh = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
408
- var startTime, orders, errorMessage;
409
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
410
- while (1) switch (_context6.prev = _context6.next) {
716
+ var _silentRefresh = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
717
+ var startTime, elapsedSinceFullFetch, orders, errorMessage;
718
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
719
+ while (1) switch (_context7.prev = _context7.next) {
411
720
  case 0:
412
721
  startTime = Date.now();
722
+ elapsedSinceFullFetch = Date.now() - this.lastServerFullFetchAtMs;
723
+ if (!(this.lastServerFullFetchAtMs > 0 && elapsedSinceFullFetch < ORDER_SILENT_REFRESH_MIN_INTERVAL_MS)) {
724
+ _context7.next = 4;
725
+ break;
726
+ }
727
+ return _context7.abrupt("return", this.store.list);
728
+ case 4:
413
729
  this.logInfo('silentRefresh 开始');
414
- _context6.prev = 2;
730
+ _context7.prev = 5;
415
731
  // 刷新前,需要更新当前营业日边界(store.createdAtQuery)
416
732
  this.updateCreateStore();
417
- _context6.next = 6;
733
+ _context7.next = 9;
418
734
  return this.loadOrdersByServer();
419
- case 6:
420
- orders = _context6.sent;
735
+ case 9:
736
+ orders = _context7.sent;
421
737
  if (!(orders.length > 0)) {
422
- _context6.next = 16;
738
+ _context7.next = 19;
423
739
  break;
424
740
  }
425
741
  this.store.list = cloneDeep(orders);
426
742
  this.syncOrdersMap();
427
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
428
- _context6.next = 13;
743
+ this.emitOrdersChanged([], 'silentRefresh');
744
+ _context7.next = 16;
429
745
  return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
430
- case 13:
746
+ case 16:
431
747
  this.logInfo('silentRefresh 完成', {
432
748
  orderCount: orders.length,
433
749
  duration: "".concat(Date.now() - startTime, "ms")
434
750
  });
435
- _context6.next = 17;
751
+ _context7.next = 20;
436
752
  break;
437
- case 16:
753
+ case 19:
438
754
  this.logInfo('silentRefresh: 服务器未返回数据');
439
- case 17:
440
- return _context6.abrupt("return", this.store.list);
441
755
  case 20:
442
- _context6.prev = 20;
443
- _context6.t0 = _context6["catch"](2);
444
- errorMessage = _context6.t0 instanceof Error ? _context6.t0.message : String(_context6.t0);
756
+ return _context7.abrupt("return", this.store.list);
757
+ case 23:
758
+ _context7.prev = 23;
759
+ _context7.t0 = _context7["catch"](5);
760
+ errorMessage = _context7.t0 instanceof Error ? _context7.t0.message : String(_context7.t0);
445
761
  this.logError('silentRefresh 失败', {
446
762
  duration: "".concat(Date.now() - startTime, "ms"),
447
763
  error: errorMessage
448
764
  });
449
- return _context6.abrupt("return", this.store.list);
450
- case 25:
765
+ return _context7.abrupt("return", this.store.list);
766
+ case 28:
451
767
  case "end":
452
- return _context6.stop();
768
+ return _context7.stop();
453
769
  }
454
- }, _callee6, this, [[2, 20]]);
770
+ }, _callee7, this, [[5, 23]]);
455
771
  }));
456
772
  function silentRefresh() {
457
773
  return _silentRefresh.apply(this, arguments);
@@ -461,14 +777,28 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
461
777
  }, {
462
778
  key: "getOrdersByResourceId",
463
779
  value: function getOrdersByResourceId(resourceId) {
464
- var _this4 = this;
780
+ var _this8 = this;
465
781
  var ids = this.resourceIdIndex.get(String(resourceId)) || [];
466
782
  return ids.map(function (id) {
467
- return _this4.store.map.get(id);
783
+ return _this8.store.map.get(id);
468
784
  }).filter(function (order) {
469
785
  return !!order;
470
786
  });
471
787
  }
788
+ }, {
789
+ key: "normalizeOrderForMemoryList",
790
+ value: function normalizeOrderForMemoryList(order) {
791
+ var externalSaleNumber = order === null || order === void 0 ? void 0 : order.external_sale_number;
792
+ if ((order === null || order === void 0 ? void 0 : order.order_id) !== undefined && (order === null || order === void 0 ? void 0 : order.order_id) !== null && (order === null || order === void 0 ? void 0 : order.order_id) !== '') {
793
+ return order;
794
+ }
795
+ if (externalSaleNumber === undefined || externalSaleNumber === null || externalSaleNumber === '') {
796
+ return order;
797
+ }
798
+ return _objectSpread(_objectSpread({}, order), {}, {
799
+ order_id: externalSaleNumber
800
+ });
801
+ }
472
802
 
473
803
  /**
474
804
  * 仅覆盖本地已存在的订单;不存在则直接跳过,不落库、不 emit。
@@ -477,31 +807,31 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
477
807
  }, {
478
808
  key: "overwriteExistingOrder",
479
809
  value: (function () {
480
- var _overwriteExistingOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(fresh) {
481
- var _this5 = this;
810
+ var _overwriteExistingOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(fresh) {
811
+ var _this9 = this;
482
812
  var orderId, key;
483
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
484
- while (1) switch (_context7.prev = _context7.next) {
813
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
814
+ while (1) switch (_context8.prev = _context8.next) {
485
815
  case 0:
486
816
  orderId = fresh === null || fresh === void 0 ? void 0 : fresh.order_id;
487
817
  if (!(orderId === undefined || orderId === null)) {
488
- _context7.next = 4;
818
+ _context8.next = 4;
489
819
  break;
490
820
  }
491
821
  this.logError('overwriteExistingOrder-入参缺少 order_id');
492
- return _context7.abrupt("return", {
822
+ return _context8.abrupt("return", {
493
823
  overwritten: false
494
824
  });
495
825
  case 4:
496
826
  key = this.getIdKey(orderId);
497
827
  if (this.store.map.has(key)) {
498
- _context7.next = 8;
828
+ _context8.next = 8;
499
829
  break;
500
830
  }
501
831
  this.logInfo('overwriteExistingOrder-本地不存在该订单,跳过', {
502
832
  orderId: orderId
503
833
  });
504
- return _context7.abrupt("return", {
834
+ return _context8.abrupt("return", {
505
835
  overwritten: false
506
836
  });
507
837
  case 8:
@@ -512,27 +842,27 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
512
842
  this.store.list = this.store.list.map(function (order) {
513
843
  var id = order === null || order === void 0 ? void 0 : order.order_id;
514
844
  if (id === undefined || id === null) return order;
515
- return _this5.getIdKey(id) === key ? fresh : order;
845
+ return _this9.getIdKey(id) === key ? fresh : order;
516
846
  });
517
847
  this.syncOrdersMap();
518
- _context7.next = 13;
519
- return this.saveOrdersToSQLite(this.store.list);
848
+ _context8.next = 13;
849
+ return this.updateOrderInSQLite(fresh, 'overwriteExistingOrder');
520
850
  case 13:
521
851
  this.logInfo('overwriteExistingOrder-结束', {
522
852
  orderId: orderId,
523
853
  storeOrderCountAfter: this.store.list.length
524
854
  });
525
- _context7.next = 16;
526
- return this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
855
+ _context8.next = 16;
856
+ return this.emitOrdersChanged([fresh], 'overwriteExistingOrder');
527
857
  case 16:
528
- return _context7.abrupt("return", {
858
+ return _context8.abrupt("return", {
529
859
  overwritten: true
530
860
  });
531
861
  case 17:
532
862
  case "end":
533
- return _context7.stop();
863
+ return _context8.stop();
534
864
  }
535
- }, _callee7, this);
865
+ }, _callee8, this);
536
866
  }));
537
867
  function overwriteExistingOrder(_x4) {
538
868
  return _overwriteExistingOrder.apply(this, arguments);
@@ -547,90 +877,302 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
547
877
  }, {
548
878
  key: "upsertOrdersFromRemote",
549
879
  value: (function () {
550
- var _upsertOrdersFromRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(freshOrders) {
551
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
552
- while (1) switch (_context8.prev = _context8.next) {
880
+ var _upsertOrdersFromRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(freshOrders) {
881
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
882
+ while (1) switch (_context9.prev = _context9.next) {
553
883
  case 0:
554
884
  if (freshOrders !== null && freshOrders !== void 0 && freshOrders.length) {
555
- _context8.next = 3;
885
+ _context9.next = 3;
556
886
  break;
557
887
  }
558
888
  this.logInfo('upsertOrdersFromRemote-订单列表为空', {});
559
- return _context8.abrupt("return");
889
+ return _context9.abrupt("return");
560
890
  case 3:
561
891
  this.logInfo('upsertOrdersFromRemote-开始', {
562
892
  count: freshOrders.length
563
893
  });
564
- _context8.next = 6;
565
- return this.mergeOrdersToStore(freshOrders);
894
+ _context9.next = 6;
895
+ return this.mergeOrdersToStore(freshOrders, 'upsertOrdersFromRemote');
566
896
  case 6:
567
897
  case "end":
568
- return _context8.stop();
898
+ return _context9.stop();
569
899
  }
570
- }, _callee8, this);
900
+ }, _callee9, this);
571
901
  }));
572
902
  function upsertOrdersFromRemote(_x5) {
573
903
  return _upsertOrdersFromRemote.apply(this, arguments);
574
904
  }
575
905
  return upsertOrdersFromRemote;
576
- }()
577
- /**
578
- * 通过 SSE 按自定义 query 拉取订单(支持 select/with 精简字段)
579
- */
580
- )
906
+ }())
581
907
  }, {
582
- key: "fetchOrdersBySSE",
583
- value: (function () {
584
- var _fetchOrdersBySSE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
585
- var query,
586
- data,
587
- _args9 = arguments;
588
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
589
- while (1) switch (_context9.prev = _context9.next) {
908
+ key: "markOrderSyncedByExternalSaleNumber",
909
+ value: function () {
910
+ var _markOrderSyncedByExternalSaleNumber = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(params) {
911
+ var _this10 = this,
912
+ _existing$external_sa,
913
+ _nextOrder$order_id;
914
+ var externalSaleNumber, key, targetIndex, existing, nextOrder, storageKey;
915
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
916
+ while (1) switch (_context10.prev = _context10.next) {
590
917
  case 0:
591
- query = _args9.length > 0 && _args9[0] !== undefined ? _args9[0] : {};
592
- if (this.orderDataSource) {
593
- _context9.next = 3;
918
+ externalSaleNumber = params.externalSaleNumber;
919
+ if (!(externalSaleNumber === undefined || externalSaleNumber === null || externalSaleNumber === '')) {
920
+ _context10.next = 4;
594
921
  break;
595
922
  }
596
- return _context9.abrupt("return", []);
597
- case 3:
598
- _context9.prev = 3;
599
- _context9.next = 6;
600
- return this.orderDataSource.run({
601
- sse: {
602
- query: query
603
- }
923
+ this.logError('markOrderSyncedByExternalSaleNumber-缺少 external_sale_number');
924
+ return _context10.abrupt("return", {
925
+ updated: false
604
926
  });
605
- case 6:
606
- data = _context9.sent;
607
- return _context9.abrupt("return", data || []);
608
- case 10:
609
- _context9.prev = 10;
610
- _context9.t0 = _context9["catch"](3);
611
- this.logError('fetchOrdersBySSE-失败', {
612
- error: _context9.t0 instanceof Error ? _context9.t0.message : String(_context9.t0)
927
+ case 4:
928
+ key = this.getIdKey(externalSaleNumber);
929
+ targetIndex = this.store.list.findIndex(function (order) {
930
+ var value = order === null || order === void 0 ? void 0 : order.external_sale_number;
931
+ if (value === undefined || value === null || value === '') return false;
932
+ return _this10.getIdKey(value) === key;
613
933
  });
614
- return _context9.abrupt("return", []);
615
- case 14:
934
+ if (!(targetIndex < 0)) {
935
+ _context10.next = 9;
936
+ break;
937
+ }
938
+ this.logInfo('markOrderSyncedByExternalSaleNumber-本地订单不存在,跳过', {
939
+ external_sale_number: externalSaleNumber
940
+ });
941
+ return _context10.abrupt("return", {
942
+ updated: false
943
+ });
944
+ case 9:
945
+ existing = this.store.list[targetIndex];
946
+ nextOrder = this.normalizeRemoteSyncedOrder(_objectSpread(_objectSpread(_objectSpread({}, existing), params.patch || {}), {}, {
947
+ external_sale_number: (_existing$external_sa = existing.external_sale_number) !== null && _existing$external_sa !== void 0 ? _existing$external_sa : externalSaleNumber,
948
+ need_sync: 0
949
+ }));
950
+ storageKey = this.getOrderStorageKey(nextOrder) || key;
951
+ this.store.list = this.store.list.map(function (order, index) {
952
+ if (index !== targetIndex) return order;
953
+ return nextOrder;
954
+ });
955
+ this.syncOrdersMap();
956
+ _context10.next = 16;
957
+ return this.patchOrdersInSQLite([nextOrder], 'markOrderSyncedByExternalSaleNumber', _defineProperty({}, storageKey, 'update'));
958
+ case 16:
959
+ this.logInfo('markOrderSyncedByExternalSaleNumber-完成', {
960
+ external_sale_number: externalSaleNumber,
961
+ order_id: (_nextOrder$order_id = nextOrder.order_id) !== null && _nextOrder$order_id !== void 0 ? _nextOrder$order_id : null
962
+ });
963
+ _context10.next = 19;
964
+ return this.emitOrdersChanged([nextOrder], 'markOrderSyncedByExternalSaleNumber');
965
+ case 19:
966
+ return _context10.abrupt("return", {
967
+ updated: true,
968
+ order: nextOrder
969
+ });
970
+ case 20:
616
971
  case "end":
617
- return _context9.stop();
972
+ return _context10.stop();
618
973
  }
619
- }, _callee9, this, [[3, 10]]);
974
+ }, _callee10, this);
620
975
  }));
621
- function fetchOrdersBySSE() {
622
- return _fetchOrdersBySSE.apply(this, arguments);
976
+ function markOrderSyncedByExternalSaleNumber(_x6) {
977
+ return _markOrderSyncedByExternalSaleNumber.apply(this, arguments);
623
978
  }
624
- return fetchOrdersBySSE;
625
- }())
626
- }, {
627
- key: "getRoutes",
628
- value: function getRoutes() {
629
- return [];
630
- }
979
+ return markOrderSyncedByExternalSaleNumber;
980
+ }()
981
+ /**
982
+ * 将本地待同步订单按 SQLite storage key 合并进 store 并落库。
983
+ * checkout 离线兜底可能没有 order_id,但通常会有 external_sale_number。
984
+ */
631
985
  }, {
632
- key: "destroy",
633
- value: function destroy() {
986
+ key: "upsertPendingSyncOrders",
987
+ value: (function () {
988
+ var _upsertPendingSyncOrders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(pendingOrders) {
989
+ var pendingMap, memoryPendingMap, _iterator4, _step4, order, storageKey, patchedOrders, mergeActions, updatedList, _iterator5, _step5, _step5$value, _storageKey, pendingOrder, matchIndex, _iterator6, _step6, _step6$value, _storageKey2, _order;
990
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
991
+ while (1) switch (_context11.prev = _context11.next) {
992
+ case 0:
993
+ if (pendingOrders !== null && pendingOrders !== void 0 && pendingOrders.length) {
994
+ _context11.next = 3;
995
+ break;
996
+ }
997
+ this.logInfo('upsertPendingSyncOrders-订单列表为空', {});
998
+ return _context11.abrupt("return");
999
+ case 3:
1000
+ pendingMap = new Map();
1001
+ memoryPendingMap = new Map();
1002
+ _iterator4 = _createForOfIteratorHelper(pendingOrders);
1003
+ _context11.prev = 6;
1004
+ _iterator4.s();
1005
+ case 8:
1006
+ if ((_step4 = _iterator4.n()).done) {
1007
+ _context11.next = 17;
1008
+ break;
1009
+ }
1010
+ order = _step4.value;
1011
+ storageKey = this.getOrderStorageKey(order);
1012
+ if (storageKey) {
1013
+ _context11.next = 13;
1014
+ break;
1015
+ }
1016
+ return _context11.abrupt("continue", 15);
1017
+ case 13:
1018
+ pendingMap.set(storageKey, order);
1019
+ memoryPendingMap.set(storageKey, this.normalizeOrderForMemoryList(order));
1020
+ case 15:
1021
+ _context11.next = 8;
1022
+ break;
1023
+ case 17:
1024
+ _context11.next = 22;
1025
+ break;
1026
+ case 19:
1027
+ _context11.prev = 19;
1028
+ _context11.t0 = _context11["catch"](6);
1029
+ _iterator4.e(_context11.t0);
1030
+ case 22:
1031
+ _context11.prev = 22;
1032
+ _iterator4.f();
1033
+ return _context11.finish(22);
1034
+ case 25:
1035
+ if (!(pendingMap.size === 0)) {
1036
+ _context11.next = 28;
1037
+ break;
1038
+ }
1039
+ this.logError('upsertPendingSyncOrders-订单缺少可落库标识', {
1040
+ count: pendingOrders.length
1041
+ });
1042
+ return _context11.abrupt("return");
1043
+ case 28:
1044
+ this.logInfo('upsertPendingSyncOrders-开始', {
1045
+ count: pendingMap.size
1046
+ });
1047
+ patchedOrders = _toConsumableArray(pendingMap.values());
1048
+ mergeActions = {};
1049
+ updatedList = _toConsumableArray(this.store.list);
1050
+ _iterator5 = _createForOfIteratorHelper(memoryPendingMap.entries());
1051
+ _context11.prev = 33;
1052
+ _iterator5.s();
1053
+ case 35:
1054
+ if ((_step5 = _iterator5.n()).done) {
1055
+ _context11.next = 46;
1056
+ break;
1057
+ }
1058
+ _step5$value = _slicedToArray(_step5.value, 2), _storageKey = _step5$value[0], pendingOrder = _step5$value[1];
1059
+ matchIndex = this.findOrderIndexByIdentity(updatedList, pendingOrder);
1060
+ if (!(matchIndex < 0)) {
1061
+ _context11.next = 40;
1062
+ break;
1063
+ }
1064
+ return _context11.abrupt("continue", 44);
1065
+ case 40:
1066
+ updatedList[matchIndex] = this.mergeOrderRecords(updatedList[matchIndex], pendingOrder);
1067
+ pendingMap.delete(_storageKey);
1068
+ memoryPendingMap.delete(_storageKey);
1069
+ mergeActions[_storageKey] = 'update';
1070
+ case 44:
1071
+ _context11.next = 35;
1072
+ break;
1073
+ case 46:
1074
+ _context11.next = 51;
1075
+ break;
1076
+ case 48:
1077
+ _context11.prev = 48;
1078
+ _context11.t1 = _context11["catch"](33);
1079
+ _iterator5.e(_context11.t1);
1080
+ case 51:
1081
+ _context11.prev = 51;
1082
+ _iterator5.f();
1083
+ return _context11.finish(51);
1084
+ case 54:
1085
+ _iterator6 = _createForOfIteratorHelper(memoryPendingMap.entries());
1086
+ try {
1087
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1088
+ _step6$value = _slicedToArray(_step6.value, 2), _storageKey2 = _step6$value[0], _order = _step6$value[1];
1089
+ mergeActions[_storageKey2] = 'insert';
1090
+ updatedList.push(_order);
1091
+ }
1092
+ } catch (err) {
1093
+ _iterator6.e(err);
1094
+ } finally {
1095
+ _iterator6.f();
1096
+ }
1097
+ this.store.list = this.compactOrderListByIdentity(updatedList, 'upsertPendingSyncOrders.store').list;
1098
+ this.syncOrdersMap();
1099
+ _context11.next = 60;
1100
+ return this.patchOrdersInSQLite(patchedOrders, 'upsertPendingSyncOrders', mergeActions);
1101
+ case 60:
1102
+ this.logInfo('upsertPendingSyncOrders-结束', {
1103
+ count: patchedOrders.length,
1104
+ storeOrderCountAfter: this.store.list.length
1105
+ });
1106
+ _context11.next = 63;
1107
+ return this.emitOrdersChanged(patchedOrders, 'upsertPendingSyncOrders');
1108
+ case 63:
1109
+ case "end":
1110
+ return _context11.stop();
1111
+ }
1112
+ }, _callee11, this, [[6, 19, 22, 25], [33, 48, 51, 54]]);
1113
+ }));
1114
+ function upsertPendingSyncOrders(_x7) {
1115
+ return _upsertPendingSyncOrders.apply(this, arguments);
1116
+ }
1117
+ return upsertPendingSyncOrders;
1118
+ }()
1119
+ /**
1120
+ * 通过 SSE 按自定义 query 拉取订单(支持 select/with 精简字段)
1121
+ */
1122
+ )
1123
+ }, {
1124
+ key: "fetchOrdersBySSE",
1125
+ value: (function () {
1126
+ var _fetchOrdersBySSE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1127
+ var query,
1128
+ data,
1129
+ _args12 = arguments;
1130
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1131
+ while (1) switch (_context12.prev = _context12.next) {
1132
+ case 0:
1133
+ query = _args12.length > 0 && _args12[0] !== undefined ? _args12[0] : {};
1134
+ if (this.orderDataSource) {
1135
+ _context12.next = 3;
1136
+ break;
1137
+ }
1138
+ return _context12.abrupt("return", []);
1139
+ case 3:
1140
+ _context12.prev = 3;
1141
+ _context12.next = 6;
1142
+ return this.orderDataSource.run({
1143
+ sse: {
1144
+ query: query
1145
+ }
1146
+ });
1147
+ case 6:
1148
+ data = _context12.sent;
1149
+ return _context12.abrupt("return", data || []);
1150
+ case 10:
1151
+ _context12.prev = 10;
1152
+ _context12.t0 = _context12["catch"](3);
1153
+ this.logError('fetchOrdersBySSE-失败', {
1154
+ error: _context12.t0 instanceof Error ? _context12.t0.message : String(_context12.t0)
1155
+ });
1156
+ return _context12.abrupt("return", []);
1157
+ case 14:
1158
+ case "end":
1159
+ return _context12.stop();
1160
+ }
1161
+ }, _callee12, this, [[3, 10]]);
1162
+ }));
1163
+ function fetchOrdersBySSE() {
1164
+ return _fetchOrdersBySSE.apply(this, arguments);
1165
+ }
1166
+ return fetchOrdersBySSE;
1167
+ }())
1168
+ }, {
1169
+ key: "getRoutes",
1170
+ value: function getRoutes() {
1171
+ return [];
1172
+ }
1173
+ }, {
1174
+ key: "destroy",
1175
+ value: function destroy() {
634
1176
  var _this$orderDataSource;
635
1177
  if (this.syncTimer) {
636
1178
  clearTimeout(this.syncTimer);
@@ -644,45 +1186,120 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
644
1186
  }, {
645
1187
  key: "syncOrdersMap",
646
1188
  value: function syncOrdersMap() {
647
- var _this6 = this;
1189
+ var _this11 = this;
648
1190
  this.store.map.clear();
649
1191
  this.resourceIdIndex.clear();
650
- var _iterator = _createForOfIteratorHelper(this.store.list),
651
- _step;
1192
+ var _iterator7 = _createForOfIteratorHelper(this.store.list),
1193
+ _step7;
652
1194
  try {
653
1195
  var _loop = function _loop() {
654
- var order = _step.value;
655
- var id = order.order_id;
656
- if (id === undefined || id === null) return 1; // continue
657
- _this6.store.map.set(_this6.getIdKey(id), order);
658
- var resourceIds = _this6.extractResourceIds(order);
659
- var _iterator2 = _createForOfIteratorHelper(resourceIds),
660
- _step2;
1196
+ var order = _step7.value;
1197
+ var primaryIdentity = _this11.getOrderMapKey(order);
1198
+ if (!primaryIdentity) return 1; // continue
1199
+ _this11.store.map.set(primaryIdentity, order);
1200
+ var resourceIds = _this11.extractResourceIds(order);
1201
+ var _iterator8 = _createForOfIteratorHelper(resourceIds),
1202
+ _step8;
661
1203
  try {
662
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
663
- var resourceId = _step2.value;
1204
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1205
+ var resourceId = _step8.value;
664
1206
  var key = String(resourceId);
665
- var existing = _this6.resourceIdIndex.get(key) || [];
1207
+ var existing = _this11.resourceIdIndex.get(key) || [];
666
1208
  if (existing.some(function (eid) {
667
- return _this6.getIdKey(eid) === _this6.getIdKey(id);
1209
+ return _this11.getIdKey(eid) === primaryIdentity;
668
1210
  })) continue;
669
- existing.push(id);
670
- _this6.resourceIdIndex.set(key, existing);
1211
+ existing.push(primaryIdentity);
1212
+ _this11.resourceIdIndex.set(key, existing);
671
1213
  }
672
1214
  } catch (err) {
673
- _iterator2.e(err);
1215
+ _iterator8.e(err);
674
1216
  } finally {
675
- _iterator2.f();
1217
+ _iterator8.f();
676
1218
  }
677
1219
  };
678
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1220
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
679
1221
  if (_loop()) continue;
680
1222
  }
681
1223
  } catch (err) {
682
- _iterator.e(err);
1224
+ _iterator7.e(err);
683
1225
  } finally {
684
- _iterator.f();
1226
+ _iterator7.f();
1227
+ }
1228
+ }
1229
+ }, {
1230
+ key: "getOrderMapKey",
1231
+ value: function getOrderMapKey(order) {
1232
+ if (!order) return '';
1233
+ if (!this.isBlankIdentityValue(order.order_id)) {
1234
+ return this.getIdKey(order.order_id);
1235
+ }
1236
+ var externalSaleNumber = order.external_sale_number;
1237
+ if (!this.isBlankIdentityValue(externalSaleNumber)) {
1238
+ return this.getIdKey(externalSaleNumber);
1239
+ }
1240
+ return '';
1241
+ }
1242
+ }, {
1243
+ key: "isBlankIdentityValue",
1244
+ value: function isBlankIdentityValue(value) {
1245
+ return value === undefined || value === null || value === '';
1246
+ }
1247
+ }, {
1248
+ key: "getOrderIdentityEntries",
1249
+ value: function getOrderIdentityEntries(order) {
1250
+ var _this12 = this;
1251
+ if (!order) return [];
1252
+ var record = order;
1253
+ var candidates = [{
1254
+ field: 'order_id',
1255
+ value: order.order_id
1256
+ }, {
1257
+ field: 'external_sale_number',
1258
+ value: record.external_sale_number
1259
+ }, {
1260
+ field: 'order_number',
1261
+ value: record.order_number
1262
+ }, {
1263
+ field: 'shop_order_number',
1264
+ value: record.shop_order_number
1265
+ }];
1266
+ var entries = [];
1267
+ var _loop2 = function _loop2() {
1268
+ var candidate = _candidates[_i];
1269
+ if (_this12.isBlankIdentityValue(candidate.value)) return 0; // continue
1270
+ var key = _this12.getIdKey(candidate.value);
1271
+ if (entries.some(function (entry) {
1272
+ return entry.field === candidate.field && entry.key === key;
1273
+ })) return 0; // continue
1274
+ entries.push({
1275
+ field: candidate.field,
1276
+ key: key
1277
+ });
1278
+ },
1279
+ _ret;
1280
+ for (var _i = 0, _candidates = candidates; _i < _candidates.length; _i++) {
1281
+ _ret = _loop2();
1282
+ if (_ret === 0) continue;
685
1283
  }
1284
+ return entries;
1285
+ }
1286
+ }, {
1287
+ key: "getOrderIdentityKeys",
1288
+ value: function getOrderIdentityKeys(order) {
1289
+ var keys = [];
1290
+ var _iterator9 = _createForOfIteratorHelper(this.getOrderIdentityEntries(order)),
1291
+ _step9;
1292
+ try {
1293
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1294
+ var entry = _step9.value;
1295
+ if (!keys.includes(entry.key)) keys.push(entry.key);
1296
+ }
1297
+ } catch (err) {
1298
+ _iterator9.e(err);
1299
+ } finally {
1300
+ _iterator9.f();
1301
+ }
1302
+ return keys;
686
1303
  }
687
1304
  }, {
688
1305
  key: "extractResourceIds",
@@ -708,8 +1325,8 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
708
1325
  value: function getOrderDateKey(order) {
709
1326
  var _order$bookings, _order$bookings2;
710
1327
  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];
711
- for (var _i = 0, _candidates = candidates; _i < _candidates.length; _i++) {
712
- var v = _candidates[_i];
1328
+ for (var _i2 = 0, _candidates2 = candidates; _i2 < _candidates2.length; _i2++) {
1329
+ var v = _candidates2[_i2];
713
1330
  if (!v) continue;
714
1331
  var text = String(v);
715
1332
  if (!text) continue;
@@ -736,28 +1353,30 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
736
1353
  }, {
737
1354
  key: "setupOrderSync",
738
1355
  value: function setupOrderSync() {
739
- var _this7 = this;
1356
+ var _this13 = this;
740
1357
  if (!this.orderDataSource) return;
741
1358
  this.orderDataSource.run({
742
1359
  pubsub: {
743
1360
  callback: function callback(res) {
744
1361
  var _message$id, _message$order_id, _message$type;
745
- console.log('orderDataSource');
1362
+ console.log('orderDataSource', res);
746
1363
  var pubsubReceivedAt = Date.now();
747
- var message = _this7.normalizeOrderSyncMessage(res);
1364
+ var message = _this13.normalizeOrderSyncMessage(res);
748
1365
  if (!message) return;
749
1366
  message._pubsubReceivedAt = pubsubReceivedAt;
750
- _this7.pendingSyncMessages.push(message);
751
- var throttleMs = _this7.getOrderSyncThrottleMs();
752
- _this7.logInfo('orderSync-收到消息并入队', {
1367
+ _this13.pendingSyncMessages.push(message);
1368
+ var throttleMs = _this13.getOrderSyncThrottleMs();
1369
+ var routeInfo = _this13.resolveSyncMessageRoute(message);
1370
+ _this13.logInfo('orderSync-收到消息并入队', {
753
1371
  id: (_message$id = message.id) !== null && _message$id !== void 0 ? _message$id : null,
754
1372
  order_id: (_message$order_id = message.order_id) !== null && _message$order_id !== void 0 ? _message$order_id : null,
755
1373
  type: (_message$type = message.type) !== null && _message$type !== void 0 ? _message$type : null,
756
- pendingCount: _this7.pendingSyncMessages.length,
1374
+ pendingCount: _this13.pendingSyncMessages.length,
757
1375
  throttleMs: throttleMs,
758
- pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString()
1376
+ pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString(),
1377
+ fullMessage: JSON.stringify(message)
759
1378
  });
760
- _this7.scheduleOrderSyncThrottle();
1379
+ _this13.scheduleOrderSyncThrottle();
761
1380
  }
762
1381
  }
763
1382
  }).catch(function () {
@@ -774,7 +1393,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
774
1393
  }, {
775
1394
  key: "scheduleOrderSyncThrottle",
776
1395
  value: function scheduleOrderSyncThrottle() {
777
- var _this8 = this;
1396
+ var _this14 = this;
778
1397
  if (this.isProcessingSyncBatch) return;
779
1398
  if (this.isIdlePhase) {
780
1399
  this.isIdlePhase = false;
@@ -785,8 +1404,8 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
785
1404
  if (this.syncTimer) return;
786
1405
  var throttleMs = this.getOrderSyncThrottleMs();
787
1406
  this.syncTimer = setTimeout(function () {
788
- _this8.syncTimer = undefined;
789
- void _this8.flushOrderSyncMessagesByThrottle();
1407
+ _this14.syncTimer = undefined;
1408
+ void _this14.flushOrderSyncMessagesByThrottle();
790
1409
  }, throttleMs);
791
1410
  }
792
1411
 
@@ -797,41 +1416,41 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
797
1416
  }, {
798
1417
  key: "flushOrderSyncMessagesByThrottle",
799
1418
  value: (function () {
800
- var _flushOrderSyncMessagesByThrottle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
801
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
802
- while (1) switch (_context10.prev = _context10.next) {
1419
+ var _flushOrderSyncMessagesByThrottle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
1420
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1421
+ while (1) switch (_context13.prev = _context13.next) {
803
1422
  case 0:
804
1423
  if (!this.isProcessingSyncBatch) {
805
- _context10.next = 2;
1424
+ _context13.next = 2;
806
1425
  break;
807
1426
  }
808
- return _context10.abrupt("return");
1427
+ return _context13.abrupt("return");
809
1428
  case 2:
810
1429
  if (!(this.pendingSyncMessages.length === 0)) {
811
- _context10.next = 5;
1430
+ _context13.next = 5;
812
1431
  break;
813
1432
  }
814
1433
  this.isIdlePhase = true;
815
- return _context10.abrupt("return");
1434
+ return _context13.abrupt("return");
816
1435
  case 5:
817
1436
  this.isProcessingSyncBatch = true;
818
- _context10.prev = 6;
819
- _context10.next = 9;
1437
+ _context13.prev = 6;
1438
+ _context13.next = 9;
820
1439
  return this.processOrderSyncMessages();
821
1440
  case 9:
822
- _context10.prev = 9;
1441
+ _context13.prev = 9;
823
1442
  this.isProcessingSyncBatch = false;
824
1443
  if (this.pendingSyncMessages.length > 0) {
825
1444
  this.scheduleOrderSyncThrottle();
826
1445
  } else {
827
1446
  this.isIdlePhase = true;
828
1447
  }
829
- return _context10.finish(9);
1448
+ return _context13.finish(9);
830
1449
  case 13:
831
1450
  case "end":
832
- return _context10.stop();
1451
+ return _context13.stop();
833
1452
  }
834
- }, _callee10, this, [[6,, 9, 13]]);
1453
+ }, _callee13, this, [[6,, 9, 13]]);
835
1454
  }));
836
1455
  function flushOrderSyncMessagesByThrottle() {
837
1456
  return _flushOrderSyncMessagesByThrottle.apply(this, arguments);
@@ -853,18 +1472,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
853
1472
  }, {
854
1473
  key: "processOrderSyncMessages",
855
1474
  value: (function () {
856
- var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
857
- var messages, batchProcessStartAt, earliestReceivedAt, upsertOrders, refreshIds, _iterator3, _step3, _msg$id, _msg$relation_order_i, msg, hasBatchIds, singleId, hasSingleId, rawBody, normalizedBody, uniqueRefreshIds, upsertList, freshOrders, batchProcessEndAt;
858
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
859
- while (1) switch (_context11.prev = _context11.next) {
1475
+ var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
1476
+ var _this15 = this;
1477
+ var messages, batchProcessStartAt, earliestReceivedAt, upsertOrders, refreshIds, uniqueRefreshIds, upsertList, _this$filterRedundant, toFetch, skipped, freshOrders, batchProcessEndAt;
1478
+ return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1479
+ while (1) switch (_context14.prev = _context14.next) {
860
1480
  case 0:
861
1481
  messages = _toConsumableArray(this.pendingSyncMessages);
862
1482
  this.pendingSyncMessages = [];
863
1483
  if (!(messages.length === 0)) {
864
- _context11.next = 4;
1484
+ _context14.next = 4;
865
1485
  break;
866
1486
  }
867
- return _context11.abrupt("return");
1487
+ return _context14.abrupt("return");
868
1488
  case 4:
869
1489
  batchProcessStartAt = Date.now();
870
1490
  earliestReceivedAt = Math.min.apply(Math, _toConsumableArray(messages.map(function (m) {
@@ -879,43 +1499,18 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
879
1499
  });
880
1500
  upsertOrders = new Map();
881
1501
  refreshIds = [];
882
- _iterator3 = _createForOfIteratorHelper(messages);
883
- _context11.prev = 10;
884
- _iterator3.s();
885
- case 12:
886
- if ((_step3 = _iterator3.n()).done) {
887
- _context11.next = 25;
888
- break;
889
- }
890
- msg = _step3.value;
891
- hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
892
- singleId = (_msg$id = msg.id) !== null && _msg$id !== void 0 ? _msg$id : msg.order_id;
893
- hasSingleId = !hasBatchIds && singleId !== undefined && singleId !== null;
894
- rawBody = msg.body || msg.data;
895
- normalizedBody = this.normalizeOrderSyncPayload(rawBody);
896
- if (!(hasSingleId && normalizedBody)) {
897
- _context11.next = 22;
898
- break;
899
- }
900
- upsertOrders.set(this.getIdKey(normalizedBody.order_id), normalizedBody);
901
- return _context11.abrupt("continue", 23);
902
- case 22:
903
- 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));
904
- case 23:
905
- _context11.next = 12;
906
- break;
907
- case 25:
908
- _context11.next = 30;
909
- break;
910
- case 27:
911
- _context11.prev = 27;
912
- _context11.t0 = _context11["catch"](10);
913
- _iterator3.e(_context11.t0);
914
- case 30:
915
- _context11.prev = 30;
916
- _iterator3.f();
917
- return _context11.finish(30);
918
- case 33:
1502
+ messages.forEach(function (msg, msgIndex) {
1503
+ var routeInfo = _this15.resolveSyncMessageRoute(msg);
1504
+ var hasBatchIds = routeInfo.hasBatchIds;
1505
+ var singleId = routeInfo.singleId;
1506
+ var hasSingleId = routeInfo.hasSingleId;
1507
+ var normalizedBody = _this15.normalizeOrderSyncPayload(msg.body || msg.data);
1508
+ if (routeInfo.route === 'bodyUpsert' && normalizedBody) {
1509
+ upsertOrders.set(_this15.getIdKey(normalizedBody.order_id), normalizedBody);
1510
+ return;
1511
+ }
1512
+ 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));
1513
+ });
919
1514
  uniqueRefreshIds = this.uniqueOrderIds(refreshIds);
920
1515
  upsertList = _toConsumableArray(upsertOrders.values());
921
1516
  this.logInfo('processOrderSyncMessages-去重完成', {
@@ -923,33 +1518,42 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
923
1518
  refreshIdCount: uniqueRefreshIds.length
924
1519
  });
925
1520
  if (!(upsertList.length > 0)) {
926
- _context11.next = 39;
1521
+ _context14.next = 16;
927
1522
  break;
928
1523
  }
929
- _context11.next = 39;
930
- return this.mergeOrdersToStore(upsertList);
931
- case 39:
1524
+ _context14.next = 16;
1525
+ return this.mergeOrdersToStore(upsertList, 'pubsub.bodyUpsert');
1526
+ case 16:
932
1527
  if (!(uniqueRefreshIds.length > 0)) {
933
- _context11.next = 46;
1528
+ _context14.next = 28;
934
1529
  break;
935
1530
  }
936
- _context11.next = 42;
937
- return this.fetchOrdersByHttp(uniqueRefreshIds);
938
- case 42:
939
- freshOrders = _context11.sent;
1531
+ _this$filterRedundant = this.filterRedundantHttpRefreshIds(uniqueRefreshIds), toFetch = _this$filterRedundant.toFetch, skipped = _this$filterRedundant.skipped;
1532
+ if (skipped.length > 0) {}
1533
+ if (!(toFetch.length > 0)) {
1534
+ _context14.next = 28;
1535
+ break;
1536
+ }
1537
+ _context14.next = 22;
1538
+ return this.fetchOrdersByHttp(toFetch);
1539
+ case 22:
1540
+ freshOrders = _context14.sent;
940
1541
  if (!(freshOrders.length > 0)) {
941
- _context11.next = 46;
1542
+ _context14.next = 28;
942
1543
  break;
943
1544
  }
944
- _context11.next = 46;
945
- return this.mergeOrdersToStore(freshOrders);
946
- case 46:
1545
+ _context14.next = 26;
1546
+ return this.mergeOrdersToStore(freshOrders, 'pubsub.httpRefresh');
1547
+ case 26:
1548
+ _context14.next = 28;
1549
+ break;
1550
+ case 28:
947
1551
  if (!(upsertList.length === 0 && uniqueRefreshIds.length === 0)) {
948
- _context11.next = 48;
1552
+ _context14.next = 30;
949
1553
  break;
950
1554
  }
951
- return _context11.abrupt("return");
952
- case 48:
1555
+ return _context14.abrupt("return");
1556
+ case 30:
953
1557
  batchProcessEndAt = Date.now();
954
1558
  this.logInfo('processOrderSyncMessages-结束', {
955
1559
  upsertCount: upsertList.length,
@@ -957,13 +1561,13 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
957
1561
  batchProcessDurationMs: batchProcessEndAt - batchProcessStartAt,
958
1562
  totalFromPubsubToProcessedMs: batchProcessEndAt - earliestReceivedAt
959
1563
  });
960
- _context11.next = 52;
1564
+ _context14.next = 34;
961
1565
  return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
962
- case 52:
1566
+ case 34:
963
1567
  case "end":
964
- return _context11.stop();
1568
+ return _context14.stop();
965
1569
  }
966
- }, _callee11, this, [[10, 27, 30, 33]]);
1570
+ }, _callee14, this);
967
1571
  }));
968
1572
  function processOrderSyncMessages() {
969
1573
  return _processOrderSyncMessages.apply(this, arguments);
@@ -984,29 +1588,29 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
984
1588
  }, {
985
1589
  key: "fetchOrdersByHttp",
986
1590
  value: (function () {
987
- var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(ids) {
1591
+ var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(ids) {
988
1592
  var _orderList, orderList;
989
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
990
- while (1) switch (_context12.prev = _context12.next) {
1593
+ return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1594
+ while (1) switch (_context15.prev = _context15.next) {
991
1595
  case 0:
992
1596
  if (!(!this.orderDataSource || ids.length === 0)) {
993
- _context12.next = 2;
1597
+ _context15.next = 2;
994
1598
  break;
995
1599
  }
996
- return _context12.abrupt("return", []);
1600
+ return _context15.abrupt("return", []);
997
1601
  case 2:
998
- _context12.prev = 2;
1602
+ _context15.prev = 2;
999
1603
  if (!(typeof this.orderDataSource.fetchOrdersByIds === 'function')) {
1000
- _context12.next = 8;
1604
+ _context15.next = 8;
1001
1605
  break;
1002
1606
  }
1003
- _context12.next = 6;
1607
+ _context15.next = 6;
1004
1608
  return this.orderDataSource.fetchOrdersByIds(ids);
1005
1609
  case 6:
1006
- _orderList = _context12.sent;
1007
- return _context12.abrupt("return", _orderList || []);
1610
+ _orderList = _context15.sent;
1611
+ return _context15.abrupt("return", _orderList || []);
1008
1612
  case 8:
1009
- _context12.next = 10;
1613
+ _context15.next = 10;
1010
1614
  return this.orderDataSource.run({
1011
1615
  http: {
1012
1616
  query: {
@@ -1015,19 +1619,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1015
1619
  }
1016
1620
  });
1017
1621
  case 10:
1018
- orderList = _context12.sent;
1019
- return _context12.abrupt("return", orderList || []);
1622
+ orderList = _context15.sent;
1623
+ return _context15.abrupt("return", orderList || []);
1020
1624
  case 14:
1021
- _context12.prev = 14;
1022
- _context12.t0 = _context12["catch"](2);
1023
- return _context12.abrupt("return", []);
1625
+ _context15.prev = 14;
1626
+ _context15.t0 = _context15["catch"](2);
1627
+ return _context15.abrupt("return", []);
1024
1628
  case 17:
1025
1629
  case "end":
1026
- return _context12.stop();
1630
+ return _context15.stop();
1027
1631
  }
1028
- }, _callee12, this, [[2, 14]]);
1632
+ }, _callee15, this, [[2, 14]]);
1029
1633
  }));
1030
- function fetchOrdersByHttp(_x6) {
1634
+ function fetchOrdersByHttp(_x8) {
1031
1635
  return _fetchOrdersByHttp.apply(this, arguments);
1032
1636
  }
1033
1637
  return fetchOrdersByHttp;
@@ -1039,87 +1643,126 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1039
1643
  }, {
1040
1644
  key: "mergeOrdersToStore",
1041
1645
  value: (function () {
1042
- var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(freshOrders) {
1043
- var _this9 = this;
1044
- var freshMap, _iterator4, _step4, order, id, uniqueFreshCount, updatedList, _iterator5, _step5, _order;
1045
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1046
- while (1) switch (_context13.prev = _context13.next) {
1646
+ var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(freshOrders, source) {
1647
+ var normalizedFreshOrders, _iterator10, _step10, order, id, uniqueFreshOrders, uniqueFreshCount, patchedOrders, mergeActions, updatedList, _iterator11, _step11, fresh, matchIndex, storageKey, mergeKey, mergedOrder, insertCount, updateCount;
1648
+ return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1649
+ while (1) switch (_context16.prev = _context16.next) {
1047
1650
  case 0:
1048
1651
  this.logInfo('mergeOrdersToStore-开始', {
1049
1652
  freshOrderCount: freshOrders.length,
1050
- storeOrderCountBefore: this.store.list.length
1653
+ storeOrderCountBefore: this.store.list.length,
1654
+ source: source
1051
1655
  });
1052
- freshMap = new Map();
1053
- _iterator4 = _createForOfIteratorHelper(freshOrders);
1054
- _context13.prev = 3;
1055
- _iterator4.s();
1056
- case 5:
1057
- if ((_step4 = _iterator4.n()).done) {
1058
- _context13.next = 13;
1656
+ this.logDuplicateOrders("".concat(source, ".beforeMerge"), this.store.list);
1657
+ normalizedFreshOrders = [];
1658
+ _iterator10 = _createForOfIteratorHelper(freshOrders);
1659
+ _context16.prev = 4;
1660
+ _iterator10.s();
1661
+ case 6:
1662
+ if ((_step10 = _iterator10.n()).done) {
1663
+ _context16.next = 14;
1059
1664
  break;
1060
1665
  }
1061
- order = _step4.value;
1666
+ order = _step10.value;
1062
1667
  id = order === null || order === void 0 ? void 0 : order.order_id;
1063
1668
  if (!(id === undefined || id === null)) {
1064
- _context13.next = 10;
1669
+ _context16.next = 11;
1065
1670
  break;
1066
1671
  }
1067
- return _context13.abrupt("continue", 11);
1068
- case 10:
1069
- freshMap.set(this.getIdKey(id), order);
1672
+ return _context16.abrupt("continue", 12);
1070
1673
  case 11:
1071
- _context13.next = 5;
1674
+ normalizedFreshOrders.push(this.normalizeRemoteSyncedOrder(order));
1675
+ case 12:
1676
+ _context16.next = 6;
1072
1677
  break;
1073
- case 13:
1074
- _context13.next = 18;
1678
+ case 14:
1679
+ _context16.next = 19;
1075
1680
  break;
1076
- case 15:
1077
- _context13.prev = 15;
1078
- _context13.t0 = _context13["catch"](3);
1079
- _iterator4.e(_context13.t0);
1080
- case 18:
1081
- _context13.prev = 18;
1082
- _iterator4.f();
1083
- return _context13.finish(18);
1084
- case 21:
1085
- uniqueFreshCount = freshMap.size;
1086
- updatedList = this.store.list.map(function (order) {
1087
- var id = order.order_id;
1088
- if (id === undefined || id === null) return order;
1089
- var key = _this9.getIdKey(id);
1090
- if (!freshMap.has(key)) return order;
1091
- var fresh = freshMap.get(key);
1092
- freshMap.delete(key);
1093
- return fresh;
1094
- });
1095
- _iterator5 = _createForOfIteratorHelper(freshMap.values());
1096
- try {
1097
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
1098
- _order = _step5.value;
1099
- updatedList.push(_order);
1100
- }
1101
- } catch (err) {
1102
- _iterator5.e(err);
1103
- } finally {
1104
- _iterator5.f();
1681
+ case 16:
1682
+ _context16.prev = 16;
1683
+ _context16.t0 = _context16["catch"](4);
1684
+ _iterator10.e(_context16.t0);
1685
+ case 19:
1686
+ _context16.prev = 19;
1687
+ _iterator10.f();
1688
+ return _context16.finish(19);
1689
+ case 22:
1690
+ uniqueFreshOrders = this.compactOrderListByIdentity(normalizedFreshOrders, "".concat(source, ".incoming")).list;
1691
+ uniqueFreshCount = uniqueFreshOrders.length;
1692
+ patchedOrders = [];
1693
+ mergeActions = {};
1694
+ updatedList = _toConsumableArray(this.store.list);
1695
+ _iterator11 = _createForOfIteratorHelper(uniqueFreshOrders);
1696
+ _context16.prev = 28;
1697
+ _iterator11.s();
1698
+ case 30:
1699
+ if ((_step11 = _iterator11.n()).done) {
1700
+ _context16.next = 46;
1701
+ break;
1105
1702
  }
1106
- this.store.list = updatedList;
1703
+ fresh = _step11.value;
1704
+ matchIndex = this.findOrderIndexByIdentity(updatedList, fresh);
1705
+ storageKey = this.getOrderStorageKey(fresh);
1706
+ mergeKey = storageKey || (fresh.order_id !== undefined && fresh.order_id !== null ? this.getIdKey(fresh.order_id) : '');
1707
+ if (!(matchIndex >= 0)) {
1708
+ _context16.next = 41;
1709
+ break;
1710
+ }
1711
+ mergedOrder = this.mergeOrderRecords(updatedList[matchIndex], fresh);
1712
+ updatedList[matchIndex] = mergedOrder;
1713
+ patchedOrders.push(mergedOrder);
1714
+ if (mergeKey) mergeActions[mergeKey] = 'update';
1715
+ return _context16.abrupt("continue", 44);
1716
+ case 41:
1717
+ updatedList.push(fresh);
1718
+ patchedOrders.push(fresh);
1719
+ if (mergeKey) mergeActions[mergeKey] = 'insert';
1720
+ case 44:
1721
+ _context16.next = 30;
1722
+ break;
1723
+ case 46:
1724
+ _context16.next = 51;
1725
+ break;
1726
+ case 48:
1727
+ _context16.prev = 48;
1728
+ _context16.t1 = _context16["catch"](28);
1729
+ _iterator11.e(_context16.t1);
1730
+ case 51:
1731
+ _context16.prev = 51;
1732
+ _iterator11.f();
1733
+ return _context16.finish(51);
1734
+ case 54:
1735
+ insertCount = Object.values(mergeActions).filter(function (v) {
1736
+ return v === 'insert';
1737
+ }).length;
1738
+ updateCount = Object.values(mergeActions).filter(function (v) {
1739
+ return v === 'update';
1740
+ }).length;
1741
+ this.logInfo('mergeOrdersToStore-合并完成', {
1742
+ insertCount: insertCount,
1743
+ updateCount: updateCount,
1744
+ storeOrderCountAfter: this.store.list.length
1745
+ });
1746
+ this.store.list = this.compactOrderListByIdentity(updatedList, "".concat(source, ".store")).list;
1107
1747
  this.syncOrdersMap();
1108
- _context13.next = 29;
1109
- return this.saveOrdersToSQLite(this.store.list);
1110
- case 29:
1748
+ _context16.next = 61;
1749
+ return this.patchOrdersInSQLite(patchedOrders, source, mergeActions);
1750
+ case 61:
1111
1751
  this.logInfo('mergeOrdersToStore-结束', {
1112
1752
  uniqueFreshCount: uniqueFreshCount,
1113
- storeOrderCountAfter: this.store.list.length
1753
+ storeOrderCountAfter: this.store.list.length,
1754
+ insertCount: insertCount,
1755
+ updateCount: updateCount
1114
1756
  });
1115
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
1116
- case 31:
1757
+ _context16.next = 64;
1758
+ return this.emitOrdersChanged(patchedOrders, source);
1759
+ case 64:
1117
1760
  case "end":
1118
- return _context13.stop();
1761
+ return _context16.stop();
1119
1762
  }
1120
- }, _callee13, this, [[3, 15, 18, 21]]);
1763
+ }, _callee16, this, [[4, 16, 19, 22], [28, 48, 51, 54]]);
1121
1764
  }));
1122
- function mergeOrdersToStore(_x7) {
1765
+ function mergeOrdersToStore(_x9, _x10) {
1123
1766
  return _mergeOrdersToStore.apply(this, arguments);
1124
1767
  }
1125
1768
  return mergeOrdersToStore;
@@ -1156,17 +1799,17 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1156
1799
  key: "uniqueOrderIds",
1157
1800
  value: function uniqueOrderIds(ids) {
1158
1801
  var idMap = new Map();
1159
- var _iterator6 = _createForOfIteratorHelper(ids),
1160
- _step6;
1802
+ var _iterator12 = _createForOfIteratorHelper(ids),
1803
+ _step12;
1161
1804
  try {
1162
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1163
- var id = _step6.value;
1805
+ for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
1806
+ var id = _step12.value;
1164
1807
  idMap.set(this.getIdKey(id), id);
1165
1808
  }
1166
1809
  } catch (err) {
1167
- _iterator6.e(err);
1810
+ _iterator12.e(err);
1168
1811
  } finally {
1169
- _iterator6.f();
1812
+ _iterator12.f();
1170
1813
  }
1171
1814
  return _toConsumableArray(idMap.values());
1172
1815
  }
@@ -1175,6 +1818,276 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1175
1818
  value: function getIdKey(id) {
1176
1819
  return String(id);
1177
1820
  }
1821
+ }, {
1822
+ key: "isOrderLookupMatch",
1823
+ value: function isOrderLookupMatch(order, lookupKey) {
1824
+ var _this16 = this;
1825
+ if (!order || !lookupKey) return false;
1826
+ var candidates = [order.order_id, order.external_sale_number, order.order_number, order.shop_order_number, order.shop_full_order_number];
1827
+ return candidates.some(function (value) {
1828
+ if (value === undefined || value === null || value === '') return false;
1829
+ return _this16.getIdKey(value) === lookupKey;
1830
+ });
1831
+ }
1832
+
1833
+ /**
1834
+ * 解析订单 SQLite 主键,规则与宿主 OrderDataSource.getOrderStorageKey 一致。
1835
+ *
1836
+ * @example
1837
+ * const key = this.getOrderStorageKey({ order_id: 1001, external_sale_number: 'S-1001' })
1838
+ * // => 'S-1001'
1839
+ */
1840
+ }, {
1841
+ key: "getOrderStorageKey",
1842
+ value: function getOrderStorageKey(order) {
1843
+ var externalSaleNumber = order === null || order === void 0 ? void 0 : order.external_sale_number;
1844
+ if (externalSaleNumber !== undefined && externalSaleNumber !== null && externalSaleNumber !== '') {
1845
+ return String(externalSaleNumber);
1846
+ }
1847
+ var orderId = order === null || order === void 0 ? void 0 : order.order_id;
1848
+ if (orderId !== undefined && orderId !== null && orderId !== '') {
1849
+ return String(orderId);
1850
+ }
1851
+ return '';
1852
+ }
1853
+ }, {
1854
+ key: "getOrderIdentityMatchKeys",
1855
+ value: function getOrderIdentityMatchKeys(order) {
1856
+ return this.getOrderIdentityEntries(order).map(function (entry) {
1857
+ return "".concat(entry.field, ":").concat(entry.key);
1858
+ });
1859
+ }
1860
+ }, {
1861
+ key: "doOrdersShareIdentity",
1862
+ value: function doOrdersShareIdentity(left, right) {
1863
+ var leftKeys = new Set(this.getOrderIdentityMatchKeys(left));
1864
+ if (leftKeys.size === 0) return false;
1865
+ return this.getOrderIdentityMatchKeys(right).some(function (key) {
1866
+ return leftKeys.has(key);
1867
+ });
1868
+ }
1869
+ }, {
1870
+ key: "findOrderIndexByIdentity",
1871
+ value: function findOrderIndexByIdentity(orders, target) {
1872
+ var _this17 = this;
1873
+ if (this.getOrderIdentityMatchKeys(target).length === 0) return -1;
1874
+ return orders.findIndex(function (order) {
1875
+ return _this17.doOrdersShareIdentity(order, target);
1876
+ });
1877
+ }
1878
+ }, {
1879
+ key: "getOrderCompletenessScore",
1880
+ value: function getOrderCompletenessScore(order) {
1881
+ var record = order;
1882
+ var score = this.isPendingSyncOrder(order) ? 0 : 100;
1883
+ if (!this.isBlankIdentityValue(order.order_id) && order.order_id !== record.external_sale_number) score += 30;
1884
+ score += this.getOrderIdentityMatchKeys(order).length * 5;
1885
+ if (Array.isArray(order.products)) score += Math.min(order.products.length, 10);
1886
+ if (Array.isArray(order.bookings)) score += Math.min(order.bookings.length, 10);
1887
+ if (Array.isArray(order.payments)) score += Math.min(order.payments.length, 10);
1888
+ if (record.updated_at) score += 1;
1889
+ return score;
1890
+ }
1891
+ }, {
1892
+ key: "pickPreferredOrder",
1893
+ value: function pickPreferredOrder(left, right) {
1894
+ var leftScore = this.getOrderCompletenessScore(left);
1895
+ var rightScore = this.getOrderCompletenessScore(right);
1896
+ if (rightScore >= leftScore) return right;
1897
+ return left;
1898
+ }
1899
+ }, {
1900
+ key: "getProductMergeKey",
1901
+ value: function getProductMergeKey(product) {
1902
+ var _record$metadata;
1903
+ var record = product;
1904
+ if (!record) return '';
1905
+ var metadataUid = (_record$metadata = record.metadata) === null || _record$metadata === void 0 ? void 0 : _record$metadata.unique_identification_number;
1906
+ if (!this.isBlankIdentityValue(metadataUid)) return "uid:".concat(String(metadataUid));
1907
+ var topLevelUid = record.unique_identification_number;
1908
+ if (!this.isBlankIdentityValue(topLevelUid)) return "uid:".concat(String(topLevelUid));
1909
+ var orderDetailId = record.order_detail_id;
1910
+ if (!this.isBlankIdentityValue(orderDetailId)) return "detail:".concat(String(orderDetailId));
1911
+ var bookingUid = record.booking_uid;
1912
+ if (!this.isBlankIdentityValue(bookingUid)) return "booking:".concat(String(bookingUid));
1913
+ return '';
1914
+ }
1915
+ }, {
1916
+ key: "mergeOrderProductLists",
1917
+ value: function mergeOrderProductLists(preferred, secondary) {
1918
+ var preferredList = Array.isArray(preferred) ? preferred : [];
1919
+ var secondaryList = Array.isArray(secondary) ? secondary : [];
1920
+ if (secondaryList.length === 0) return preferredList;
1921
+ if (preferredList.length === 0) return secondaryList;
1922
+ var seenKeys = new Set();
1923
+ var _iterator13 = _createForOfIteratorHelper(preferredList),
1924
+ _step13;
1925
+ try {
1926
+ for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
1927
+ var item = _step13.value;
1928
+ var key = this.getProductMergeKey(item);
1929
+ if (key) seenKeys.add(key);
1930
+ }
1931
+ } catch (err) {
1932
+ _iterator13.e(err);
1933
+ } finally {
1934
+ _iterator13.f();
1935
+ }
1936
+ var result = _toConsumableArray(preferredList);
1937
+ var _iterator14 = _createForOfIteratorHelper(secondaryList),
1938
+ _step14;
1939
+ try {
1940
+ for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
1941
+ var _item = _step14.value;
1942
+ var _key = this.getProductMergeKey(_item);
1943
+ if (!_key || seenKeys.has(_key)) continue;
1944
+ seenKeys.add(_key);
1945
+ result.push(cloneDeep(_item));
1946
+ }
1947
+ } catch (err) {
1948
+ _iterator14.e(err);
1949
+ } finally {
1950
+ _iterator14.f();
1951
+ }
1952
+ return result;
1953
+ }
1954
+ }, {
1955
+ key: "mergeOrderRecords",
1956
+ value: function mergeOrderRecords(existing, incoming) {
1957
+ var preferred = this.pickPreferredOrder(existing, incoming);
1958
+ var secondary = preferred === existing ? incoming : existing;
1959
+ var merged = _objectSpread(_objectSpread({}, secondary), preferred);
1960
+ var fieldsToPreserve = ['order_id', 'external_sale_number', 'order_number', 'shop_order_number', 'shop_full_order_number'];
1961
+ var incomingPatchFields = ['payment_status', 'status', 'shipping_status', 'updated_at', 'shop_discount', 'summary', 'payments', 'products', 'bookings'];
1962
+ var mergedRecord = merged;
1963
+ var preferredRecord = preferred;
1964
+ var secondaryRecord = secondary;
1965
+ var incomingRecord = incoming;
1966
+ for (var _i3 = 0, _fieldsToPreserve = fieldsToPreserve; _i3 < _fieldsToPreserve.length; _i3++) {
1967
+ var field = _fieldsToPreserve[_i3];
1968
+ if (!this.isBlankIdentityValue(preferredRecord[field])) {
1969
+ mergedRecord[field] = preferredRecord[field];
1970
+ continue;
1971
+ }
1972
+ if (!this.isBlankIdentityValue(secondaryRecord[field])) {
1973
+ mergedRecord[field] = secondaryRecord[field];
1974
+ }
1975
+ }
1976
+ for (var _i4 = 0, _incomingPatchFields = incomingPatchFields; _i4 < _incomingPatchFields.length; _i4++) {
1977
+ var _field = _incomingPatchFields[_i4];
1978
+ if (!Object.prototype.hasOwnProperty.call(incomingRecord, _field)) continue;
1979
+ if (incomingRecord[_field] === undefined || incomingRecord[_field] === null) continue;
1980
+ if (typeof incomingRecord[_field] === 'string' && incomingRecord[_field] === '') continue;
1981
+ mergedRecord[_field] = cloneDeep(incomingRecord[_field]);
1982
+ }
1983
+ mergedRecord.products = this.mergeOrderProductLists(preferredRecord.products, secondaryRecord.products);
1984
+ if (!this.isPendingSyncOrder(preferred) || !this.isPendingSyncOrder(secondary)) {
1985
+ merged.need_sync = 0;
1986
+ }
1987
+ return merged;
1988
+ }
1989
+ }, {
1990
+ key: "summarizeDuplicateOrders",
1991
+ value: function summarizeDuplicateOrders(orders) {
1992
+ var groups = new Map();
1993
+ var _iterator15 = _createForOfIteratorHelper(orders),
1994
+ _step15;
1995
+ try {
1996
+ for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
1997
+ var order = _step15.value;
1998
+ var _iterator16 = _createForOfIteratorHelper(this.getOrderIdentityMatchKeys(order)),
1999
+ _step16;
2000
+ try {
2001
+ for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
2002
+ var key = _step16.value;
2003
+ var group = groups.get(key) || [];
2004
+ group.push(order);
2005
+ groups.set(key, group);
2006
+ }
2007
+ } catch (err) {
2008
+ _iterator16.e(err);
2009
+ } finally {
2010
+ _iterator16.f();
2011
+ }
2012
+ }
2013
+ } catch (err) {
2014
+ _iterator15.e(err);
2015
+ } finally {
2016
+ _iterator15.f();
2017
+ }
2018
+ return _toConsumableArray(groups.entries()).filter(function (_ref2) {
2019
+ var _ref3 = _slicedToArray(_ref2, 2),
2020
+ group = _ref3[1];
2021
+ return group.length > 1;
2022
+ }).slice(0, 20).map(function (_ref4) {
2023
+ var _ref5 = _slicedToArray(_ref4, 2),
2024
+ key = _ref5[0],
2025
+ group = _ref5[1];
2026
+ return {
2027
+ key: key,
2028
+ count: group.length,
2029
+ orders: group.map(function (order) {
2030
+ var _order$order_id2, _external_sale_number, _shop_order_number, _shop_full_order_numb, _order$need_sync;
2031
+ return {
2032
+ order_id: (_order$order_id2 = order.order_id) !== null && _order$order_id2 !== void 0 ? _order$order_id2 : null,
2033
+ external_sale_number: (_external_sale_number = order.external_sale_number) !== null && _external_sale_number !== void 0 ? _external_sale_number : null,
2034
+ shop_order_number: (_shop_order_number = order.shop_order_number) !== null && _shop_order_number !== void 0 ? _shop_order_number : null,
2035
+ 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,
2036
+ need_sync: (_order$need_sync = order.need_sync) !== null && _order$need_sync !== void 0 ? _order$need_sync : null
2037
+ };
2038
+ })
2039
+ };
2040
+ });
2041
+ }
2042
+ }, {
2043
+ key: "logDuplicateOrders",
2044
+ value: function logDuplicateOrders(source, orders) {
2045
+ var duplicateGroups = this.summarizeDuplicateOrders(orders);
2046
+ if (duplicateGroups.length === 0) return;
2047
+ this.logWarning('检测到重复订单身份键', {
2048
+ source: source,
2049
+ duplicateGroupCount: duplicateGroups.length,
2050
+ duplicateGroups: duplicateGroups
2051
+ });
2052
+ }
2053
+ }, {
2054
+ key: "compactOrderListByIdentity",
2055
+ value: function compactOrderListByIdentity(orders, source) {
2056
+ var list = [];
2057
+ var removedCount = 0;
2058
+ var _iterator17 = _createForOfIteratorHelper(orders),
2059
+ _step17;
2060
+ try {
2061
+ for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
2062
+ var order = _step17.value;
2063
+ var matchIndex = this.findOrderIndexByIdentity(list, order);
2064
+ if (matchIndex < 0) {
2065
+ list.push(order);
2066
+ continue;
2067
+ }
2068
+ list[matchIndex] = this.mergeOrderRecords(list[matchIndex], order);
2069
+ removedCount += 1;
2070
+ }
2071
+ } catch (err) {
2072
+ _iterator17.e(err);
2073
+ } finally {
2074
+ _iterator17.f();
2075
+ }
2076
+ if (removedCount > 0) {
2077
+ this.logWarning('订单列表重复项已压缩', {
2078
+ source: source,
2079
+ beforeCount: orders.length,
2080
+ afterCount: list.length,
2081
+ removedCount: removedCount
2082
+ });
2083
+ } else {
2084
+ this.logDuplicateOrders(source, orders);
2085
+ }
2086
+ return {
2087
+ list: list,
2088
+ removedCount: removedCount
2089
+ };
2090
+ }
1178
2091
 
1179
2092
  /**
1180
2093
  * 当前订单拉取窗口:
@@ -1232,7 +2145,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1232
2145
  if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
1233
2146
  return globalThis.localStorage.getItem(key);
1234
2147
  }
1235
- } catch (_unused5) {
2148
+ } catch (_unused6) {
1236
2149
  // 忽略存储异常,避免影响主流程
1237
2150
  }
1238
2151
  return null;
@@ -1249,39 +2162,39 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1249
2162
  if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
1250
2163
  globalThis.localStorage.setItem(key, value);
1251
2164
  }
1252
- } catch (_unused6) {
2165
+ } catch (_unused7) {
1253
2166
  // 忽略存储异常,避免影响主流程
1254
2167
  }
1255
2168
  }
1256
2169
  }, {
1257
2170
  key: "loadOrdersFromSQLite",
1258
2171
  value: function () {
1259
- var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
2172
+ var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17() {
1260
2173
  var orders;
1261
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1262
- while (1) switch (_context14.prev = _context14.next) {
2174
+ return _regeneratorRuntime().wrap(function _callee17$(_context17) {
2175
+ while (1) switch (_context17.prev = _context17.next) {
1263
2176
  case 0:
1264
2177
  if (this.dbManager) {
1265
- _context14.next = 2;
2178
+ _context17.next = 2;
1266
2179
  break;
1267
2180
  }
1268
- return _context14.abrupt("return", []);
2181
+ return _context17.abrupt("return", []);
1269
2182
  case 2:
1270
- _context14.prev = 2;
1271
- _context14.next = 5;
2183
+ _context17.prev = 2;
2184
+ _context17.next = 5;
1272
2185
  return this.dbManager.getAll(INDEXDB_STORE_NAME);
1273
2186
  case 5:
1274
- orders = _context14.sent;
1275
- return _context14.abrupt("return", orders || []);
2187
+ orders = _context17.sent;
2188
+ return _context17.abrupt("return", orders || []);
1276
2189
  case 9:
1277
- _context14.prev = 9;
1278
- _context14.t0 = _context14["catch"](2);
1279
- return _context14.abrupt("return", []);
2190
+ _context17.prev = 9;
2191
+ _context17.t0 = _context17["catch"](2);
2192
+ return _context17.abrupt("return", []);
1280
2193
  case 12:
1281
2194
  case "end":
1282
- return _context14.stop();
2195
+ return _context17.stop();
1283
2196
  }
1284
- }, _callee14, this, [[2, 9]]);
2197
+ }, _callee17, this, [[2, 9]]);
1285
2198
  }));
1286
2199
  function loadOrdersFromSQLite() {
1287
2200
  return _loadOrdersFromSQLite.apply(this, arguments);
@@ -1289,91 +2202,488 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1289
2202
  return loadOrdersFromSQLite;
1290
2203
  }()
1291
2204
  }, {
1292
- key: "saveOrdersToSQLite",
1293
- value: function () {
1294
- var _saveOrdersToSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(orderList) {
1295
- return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1296
- while (1) switch (_context15.prev = _context15.next) {
2205
+ key: "isPendingSyncOrder",
2206
+ value: function isPendingSyncOrder(order) {
2207
+ return Number(order === null || order === void 0 ? void 0 : order.need_sync) === 1;
2208
+ }
2209
+ }, {
2210
+ key: "normalizeRemoteSyncedOrder",
2211
+ value: function normalizeRemoteSyncedOrder(order) {
2212
+ if (this.isPendingSyncOrder(order)) return order;
2213
+ return _objectSpread(_objectSpread({}, order), {}, {
2214
+ need_sync: 0
2215
+ });
2216
+ }
2217
+ }, {
2218
+ key: "mergeRemoteSnapshotWithPendingOrders",
2219
+ value: function mergeRemoteSnapshotWithPendingOrders(remoteOrders, existingOrders) {
2220
+ var _this18 = this;
2221
+ var merged = remoteOrders.map(function (order) {
2222
+ return _this18.normalizeRemoteSyncedOrder(order);
2223
+ });
2224
+ var _iterator18 = _createForOfIteratorHelper(existingOrders),
2225
+ _step18;
2226
+ try {
2227
+ for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
2228
+ var order = _step18.value;
2229
+ if (!this.isPendingSyncOrder(order)) continue;
2230
+ var matchIndex = this.findOrderIndexByIdentity(merged, order);
2231
+ if (matchIndex >= 0) {
2232
+ merged[matchIndex] = this.mergeOrderRecords(order, merged[matchIndex]);
2233
+ continue;
2234
+ }
2235
+ if (!this.getOrderStorageKey(order)) continue;
2236
+ merged.push(order);
2237
+ }
2238
+ } catch (err) {
2239
+ _iterator18.e(err);
2240
+ } finally {
2241
+ _iterator18.f();
2242
+ }
2243
+ return this.compactOrderListByIdentity(merged, 'mergeRemoteSnapshotWithPendingOrders').list;
2244
+ }
2245
+
2246
+ /**
2247
+ * 串行执行订单 SQLite 写入任务,避免快照替换与增量 upsert 并发交错。
2248
+ *
2249
+ * @example
2250
+ * await this.runInOrderSQLiteSaveQueue(async () => {
2251
+ * await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, orders)
2252
+ * })
2253
+ */
2254
+ }, {
2255
+ key: "runInOrderSQLiteSaveQueue",
2256
+ value: (function () {
2257
+ var _runInOrderSQLiteSaveQueue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(task) {
2258
+ var queuedTask;
2259
+ return _regeneratorRuntime().wrap(function _callee18$(_context18) {
2260
+ while (1) switch (_context18.prev = _context18.next) {
1297
2261
  case 0:
1298
- if (this.dbManager) {
1299
- _context15.next = 2;
2262
+ queuedTask = this.orderSQLiteSaveQueue.then(task, task);
2263
+ this.orderSQLiteSaveQueue = queuedTask.then(function () {
2264
+ return undefined;
2265
+ }, function () {
2266
+ return undefined;
2267
+ });
2268
+ return _context18.abrupt("return", queuedTask);
2269
+ case 3:
2270
+ case "end":
2271
+ return _context18.stop();
2272
+ }
2273
+ }, _callee18, this);
2274
+ }));
2275
+ function runInOrderSQLiteSaveQueue(_x11) {
2276
+ return _runInOrderSQLiteSaveQueue.apply(this, arguments);
2277
+ }
2278
+ return runInOrderSQLiteSaveQueue;
2279
+ }()
2280
+ /**
2281
+ * 批量增量 upsert 订单到 SQLite,不清空表;用于 pubsub / HTTP 增量合并。
2282
+ *
2283
+ * @example
2284
+ * await this.patchOrdersInSQLite(freshOrders)
2285
+ */
2286
+ )
2287
+ }, {
2288
+ key: "patchOrdersInSQLite",
2289
+ value: (function () {
2290
+ var _patchOrdersInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(orders, source) {
2291
+ var _this19 = this;
2292
+ var mergeActions,
2293
+ ordersSnapshot,
2294
+ _this$filterRedundant2,
2295
+ toWrite,
2296
+ skipped,
2297
+ compactedToWrite,
2298
+ _args20 = arguments;
2299
+ return _regeneratorRuntime().wrap(function _callee20$(_context20) {
2300
+ while (1) switch (_context20.prev = _context20.next) {
2301
+ case 0:
2302
+ mergeActions = _args20.length > 2 && _args20[2] !== undefined ? _args20[2] : {};
2303
+ if (!(!this.dbManager || orders.length === 0)) {
2304
+ _context20.next = 3;
1300
2305
  break;
1301
2306
  }
1302
- return _context15.abrupt("return");
1303
- case 2:
1304
- _context15.prev = 2;
1305
- this.logInfo('saveOrdersToSQLite-开始', {
1306
- count: orderList.length
2307
+ return _context20.abrupt("return");
2308
+ case 3:
2309
+ ordersSnapshot = cloneDeep(orders).filter(function (order) {
2310
+ return _this19.getOrderStorageKey(order);
1307
2311
  });
1308
- _context15.next = 6;
1309
- return this.dbManager.clear(INDEXDB_STORE_NAME);
2312
+ if (!(ordersSnapshot.length === 0)) {
2313
+ _context20.next = 6;
2314
+ break;
2315
+ }
2316
+ return _context20.abrupt("return");
1310
2317
  case 6:
1311
- this.logInfo('saveOrdersToSQLite-clear完成', {
1312
- count: orderList.length
1313
- });
1314
- if (!(orderList.length === 0)) {
1315
- _context15.next = 9;
2318
+ _this$filterRedundant2 = this.filterRedundantPatchOrders(source, ordersSnapshot, mergeActions), toWrite = _this$filterRedundant2.toWrite, skipped = _this$filterRedundant2.skipped;
2319
+ if (!(toWrite.length === 0)) {
2320
+ _context20.next = 9;
1316
2321
  break;
1317
2322
  }
1318
- return _context15.abrupt("return");
2323
+ return _context20.abrupt("return");
1319
2324
  case 9:
1320
- _context15.next = 11;
1321
- return this.dbManager.bulkAdd(INDEXDB_STORE_NAME, orderList);
1322
- case 11:
1323
- this.logInfo('saveOrdersToSQLite-bulkAdd完成', {
1324
- count: orderList.length
2325
+ compactedToWrite = this.compactOrderListByIdentity(toWrite, "".concat(source, ".sqlitePatch")).list;
2326
+ if (!(compactedToWrite.length === 0)) {
2327
+ _context20.next = 12;
2328
+ break;
2329
+ }
2330
+ return _context20.abrupt("return");
2331
+ case 12:
2332
+ _context20.prev = 12;
2333
+ _context20.next = 15;
2334
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19() {
2335
+ var writeMethod, _iterator19, _step19, order;
2336
+ return _regeneratorRuntime().wrap(function _callee19$(_context19) {
2337
+ while (1) switch (_context19.prev = _context19.next) {
2338
+ case 0:
2339
+ writeMethod = 'none';
2340
+ _this19.logInfo('patchOrdersInSQLite-开始', {
2341
+ source: source,
2342
+ count: compactedToWrite.length,
2343
+ dedupedCount: skipped.length
2344
+ });
2345
+ if (!(typeof _this19.dbManager.bulkUpdate === 'function')) {
2346
+ _context19.next = 8;
2347
+ break;
2348
+ }
2349
+ writeMethod = 'bulkUpdate';
2350
+ _context19.next = 6;
2351
+ return _this19.dbManager.bulkUpdate(INDEXDB_STORE_NAME, compactedToWrite);
2352
+ case 6:
2353
+ _context19.next = 33;
2354
+ break;
2355
+ case 8:
2356
+ if (!(typeof _this19.dbManager.bulkAdd === 'function')) {
2357
+ _context19.next = 14;
2358
+ break;
2359
+ }
2360
+ writeMethod = 'bulkAdd';
2361
+ _context19.next = 12;
2362
+ return _this19.dbManager.bulkAdd(INDEXDB_STORE_NAME, compactedToWrite);
2363
+ case 12:
2364
+ _context19.next = 33;
2365
+ break;
2366
+ case 14:
2367
+ if (!(typeof _this19.dbManager.update === 'function')) {
2368
+ _context19.next = 33;
2369
+ break;
2370
+ }
2371
+ writeMethod = 'update';
2372
+ _iterator19 = _createForOfIteratorHelper(compactedToWrite);
2373
+ _context19.prev = 17;
2374
+ _iterator19.s();
2375
+ case 19:
2376
+ if ((_step19 = _iterator19.n()).done) {
2377
+ _context19.next = 25;
2378
+ break;
2379
+ }
2380
+ order = _step19.value;
2381
+ _context19.next = 23;
2382
+ return _this19.dbManager.update(INDEXDB_STORE_NAME, order);
2383
+ case 23:
2384
+ _context19.next = 19;
2385
+ break;
2386
+ case 25:
2387
+ _context19.next = 30;
2388
+ break;
2389
+ case 27:
2390
+ _context19.prev = 27;
2391
+ _context19.t0 = _context19["catch"](17);
2392
+ _iterator19.e(_context19.t0);
2393
+ case 30:
2394
+ _context19.prev = 30;
2395
+ _iterator19.f();
2396
+ return _context19.finish(30);
2397
+ case 33:
2398
+ _this19.recordRecentSqliteWrite(source, compactedToWrite);
2399
+ _this19.logInfo('patchOrdersInSQLite-完成', {
2400
+ source: source,
2401
+ count: compactedToWrite.length,
2402
+ writeMethod: writeMethod,
2403
+ dedupedCount: skipped.length
2404
+ });
2405
+ case 35:
2406
+ case "end":
2407
+ return _context19.stop();
2408
+ }
2409
+ }, _callee19, null, [[17, 27, 30, 33]]);
2410
+ })));
2411
+ case 15:
2412
+ _context20.next = 20;
2413
+ break;
2414
+ case 17:
2415
+ _context20.prev = 17;
2416
+ _context20.t0 = _context20["catch"](12);
2417
+ this.logError('增量保存订单到 SQLite 失败', {
2418
+ error: _context20.t0 instanceof Error ? _context20.t0.message : String(_context20.t0),
2419
+ orderCount: ordersSnapshot.length
1325
2420
  });
1326
- _context15.next = 17;
2421
+ case 20:
2422
+ case "end":
2423
+ return _context20.stop();
2424
+ }
2425
+ }, _callee20, this, [[12, 17]]);
2426
+ }));
2427
+ function patchOrdersInSQLite(_x12, _x13) {
2428
+ return _patchOrdersInSQLite.apply(this, arguments);
2429
+ }
2430
+ return patchOrdersInSQLite;
2431
+ }()
2432
+ /**
2433
+ * 单条 upsert 订单到 SQLite;用于 overwriteExistingOrder 等单条覆盖场景。
2434
+ *
2435
+ * @example
2436
+ * await this.updateOrderInSQLite(freshOrder)
2437
+ */
2438
+ )
2439
+ }, {
2440
+ key: "updateOrderInSQLite",
2441
+ value: (function () {
2442
+ var _updateOrderInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(order, source) {
2443
+ var _this20 = this;
2444
+ var orderSnapshot, _orderSnapshot$order_3;
2445
+ return _regeneratorRuntime().wrap(function _callee22$(_context22) {
2446
+ while (1) switch (_context22.prev = _context22.next) {
2447
+ case 0:
2448
+ if (!(!this.dbManager || !this.getOrderStorageKey(order))) {
2449
+ _context22.next = 2;
2450
+ break;
2451
+ }
2452
+ return _context22.abrupt("return");
2453
+ case 2:
2454
+ orderSnapshot = cloneDeep(order);
2455
+ _context22.prev = 3;
2456
+ _context22.next = 6;
2457
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21() {
2458
+ var _orderSnapshot$order_, _orderSnapshot$order_2;
2459
+ var writeMethod;
2460
+ return _regeneratorRuntime().wrap(function _callee21$(_context21) {
2461
+ while (1) switch (_context21.prev = _context21.next) {
2462
+ case 0:
2463
+ writeMethod = 'none';
2464
+ _this20.logInfo('updateOrderInSQLite-开始', {
2465
+ source: source,
2466
+ orderId: (_orderSnapshot$order_ = orderSnapshot.order_id) !== null && _orderSnapshot$order_ !== void 0 ? _orderSnapshot$order_ : null,
2467
+ storageKey: _this20.getOrderStorageKey(orderSnapshot)
2468
+ });
2469
+ if (!(typeof _this20.dbManager.update === 'function')) {
2470
+ _context21.next = 8;
2471
+ break;
2472
+ }
2473
+ writeMethod = 'update';
2474
+ _context21.next = 6;
2475
+ return _this20.dbManager.update(INDEXDB_STORE_NAME, orderSnapshot);
2476
+ case 6:
2477
+ _context21.next = 18;
2478
+ break;
2479
+ case 8:
2480
+ if (!(typeof _this20.dbManager.bulkUpdate === 'function')) {
2481
+ _context21.next = 14;
2482
+ break;
2483
+ }
2484
+ writeMethod = 'bulkUpdate';
2485
+ _context21.next = 12;
2486
+ return _this20.dbManager.bulkUpdate(INDEXDB_STORE_NAME, [orderSnapshot]);
2487
+ case 12:
2488
+ _context21.next = 18;
2489
+ break;
2490
+ case 14:
2491
+ if (!(typeof _this20.dbManager.bulkAdd === 'function')) {
2492
+ _context21.next = 18;
2493
+ break;
2494
+ }
2495
+ writeMethod = 'bulkAdd';
2496
+ _context21.next = 18;
2497
+ return _this20.dbManager.bulkAdd(INDEXDB_STORE_NAME, [orderSnapshot]);
2498
+ case 18:
2499
+ _this20.recordRecentSqliteWrite(source, [orderSnapshot]);
2500
+ _this20.logInfo('updateOrderInSQLite-完成', {
2501
+ source: source,
2502
+ orderId: (_orderSnapshot$order_2 = orderSnapshot.order_id) !== null && _orderSnapshot$order_2 !== void 0 ? _orderSnapshot$order_2 : null,
2503
+ writeMethod: writeMethod
2504
+ });
2505
+ case 20:
2506
+ case "end":
2507
+ return _context21.stop();
2508
+ }
2509
+ }, _callee21);
2510
+ })));
2511
+ case 6:
2512
+ _context22.next = 11;
1327
2513
  break;
1328
- case 14:
1329
- _context15.prev = 14;
1330
- _context15.t0 = _context15["catch"](2);
1331
- // SQLite 异常,避免影响主流程
1332
- this.logError('保存订单到 SQLite 失败', {
1333
- error: _context15.t0 instanceof Error ? _context15.t0.message : String(_context15.t0),
1334
- orderList: orderList.length
2514
+ case 8:
2515
+ _context22.prev = 8;
2516
+ _context22.t0 = _context22["catch"](3);
2517
+ this.logError('单条保存订单到 SQLite 失败', {
2518
+ error: _context22.t0 instanceof Error ? _context22.t0.message : String(_context22.t0),
2519
+ orderId: (_orderSnapshot$order_3 = orderSnapshot.order_id) !== null && _orderSnapshot$order_3 !== void 0 ? _orderSnapshot$order_3 : null
1335
2520
  });
1336
- case 17:
2521
+ case 11:
1337
2522
  case "end":
1338
- return _context15.stop();
2523
+ return _context22.stop();
1339
2524
  }
1340
- }, _callee15, this, [[2, 14]]);
2525
+ }, _callee22, this, [[3, 8]]);
2526
+ }));
2527
+ function updateOrderInSQLite(_x14, _x15) {
2528
+ return _updateOrderInSQLite.apply(this, arguments);
2529
+ }
2530
+ return updateOrderInSQLite;
2531
+ }()
2532
+ /**
2533
+ * 全量快照替换 orders 表(clear + bulkAdd),用于 SSE 全量拉取与营业日窗口裁剪。
2534
+ *
2535
+ * @example
2536
+ * await this.replaceOrdersSnapshotInSQLite(orderList)
2537
+ */
2538
+ )
2539
+ }, {
2540
+ key: "replaceOrdersSnapshotInSQLite",
2541
+ value: (function () {
2542
+ var _replaceOrdersSnapshotInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(orderList, source) {
2543
+ var _this21 = this;
2544
+ var remoteSnapshot, mergedSnapshot;
2545
+ return _regeneratorRuntime().wrap(function _callee24$(_context24) {
2546
+ while (1) switch (_context24.prev = _context24.next) {
2547
+ case 0:
2548
+ if (this.dbManager) {
2549
+ _context24.next = 2;
2550
+ break;
2551
+ }
2552
+ return _context24.abrupt("return", this.compactOrderListByIdentity(orderList.map(function (order) {
2553
+ return _this21.normalizeRemoteSyncedOrder(order);
2554
+ }), "".concat(source, ".snapshotNoDb")).list);
2555
+ case 2:
2556
+ remoteSnapshot = cloneDeep(orderList);
2557
+ mergedSnapshot = this.compactOrderListByIdentity(remoteSnapshot.map(function (order) {
2558
+ return _this21.normalizeRemoteSyncedOrder(order);
2559
+ }), "".concat(source, ".remoteSnapshot")).list;
2560
+ _context24.prev = 4;
2561
+ _context24.next = 7;
2562
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23() {
2563
+ var existingOrders, orderListSnapshot;
2564
+ return _regeneratorRuntime().wrap(function _callee23$(_context23) {
2565
+ while (1) switch (_context23.prev = _context23.next) {
2566
+ case 0:
2567
+ if (!(typeof _this21.dbManager.getAll === 'function')) {
2568
+ _context23.next = 6;
2569
+ break;
2570
+ }
2571
+ _context23.next = 3;
2572
+ return _this21.dbManager.getAll(INDEXDB_STORE_NAME);
2573
+ case 3:
2574
+ _context23.t0 = _context23.sent;
2575
+ _context23.next = 7;
2576
+ break;
2577
+ case 6:
2578
+ _context23.t0 = [];
2579
+ case 7:
2580
+ existingOrders = _context23.t0;
2581
+ orderListSnapshot = _this21.mergeRemoteSnapshotWithPendingOrders(remoteSnapshot, existingOrders || []);
2582
+ mergedSnapshot = _this21.compactOrderListByIdentity(orderListSnapshot, "".concat(source, ".sqliteSnapshot")).list;
2583
+ _this21.logInfo('replaceOrdersSnapshotInSQLite-开始', {
2584
+ source: source,
2585
+ count: mergedSnapshot.length,
2586
+ remoteCount: remoteSnapshot.length,
2587
+ preservedPendingCount: mergedSnapshot.length - remoteSnapshot.length
2588
+ });
2589
+ _context23.next = 13;
2590
+ return _this21.dbManager.clear(INDEXDB_STORE_NAME);
2591
+ case 13:
2592
+ _this21.logInfo('replaceOrdersSnapshotInSQLite-clear完成', {
2593
+ count: mergedSnapshot.length
2594
+ });
2595
+ if (!(mergedSnapshot.length === 0)) {
2596
+ _context23.next = 16;
2597
+ break;
2598
+ }
2599
+ return _context23.abrupt("return");
2600
+ case 16:
2601
+ _context23.next = 18;
2602
+ return _this21.dbManager.bulkAdd(INDEXDB_STORE_NAME, mergedSnapshot);
2603
+ case 18:
2604
+ _this21.recordRecentSqliteWrite(source, mergedSnapshot);
2605
+ _this21.logInfo('replaceOrdersSnapshotInSQLite-bulkAdd完成', {
2606
+ source: source,
2607
+ count: mergedSnapshot.length
2608
+ });
2609
+ case 20:
2610
+ case "end":
2611
+ return _context23.stop();
2612
+ }
2613
+ }, _callee23);
2614
+ })));
2615
+ case 7:
2616
+ _context24.next = 12;
2617
+ break;
2618
+ case 9:
2619
+ _context24.prev = 9;
2620
+ _context24.t0 = _context24["catch"](4);
2621
+ this.logError('全量保存订单到 SQLite 失败', {
2622
+ error: _context24.t0 instanceof Error ? _context24.t0.message : String(_context24.t0),
2623
+ orderList: remoteSnapshot.length
2624
+ });
2625
+ case 12:
2626
+ return _context24.abrupt("return", mergedSnapshot);
2627
+ case 13:
2628
+ case "end":
2629
+ return _context24.stop();
2630
+ }
2631
+ }, _callee24, this, [[4, 9]]);
1341
2632
  }));
1342
- function saveOrdersToSQLite(_x8) {
1343
- return _saveOrdersToSQLite.apply(this, arguments);
2633
+ function replaceOrdersSnapshotInSQLite(_x16, _x17) {
2634
+ return _replaceOrdersSnapshotInSQLite.apply(this, arguments);
1344
2635
  }
1345
- return saveOrdersToSQLite;
2636
+ return replaceOrdersSnapshotInSQLite;
1346
2637
  }()
2638
+ /**
2639
+ * 清空订单模块的内存数据和本地 SQLite 订单表。
2640
+ *
2641
+ * @example
2642
+ * await orderModule.clear()
2643
+ */
2644
+ )
1347
2645
  }, {
1348
2646
  key: "clear",
1349
- value: function () {
1350
- var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16() {
1351
- return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1352
- while (1) switch (_context16.prev = _context16.next) {
2647
+ value: (function () {
2648
+ var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26() {
2649
+ var _this22 = this;
2650
+ return _regeneratorRuntime().wrap(function _callee26$(_context26) {
2651
+ while (1) switch (_context26.prev = _context26.next) {
1353
2652
  case 0:
1354
2653
  this.store.list = [];
1355
2654
  this.store.map = new Map();
1356
2655
  this.resourceIdIndex.clear();
1357
2656
  if (!this.dbManager) {
1358
- _context16.next = 6;
2657
+ _context26.next = 6;
1359
2658
  break;
1360
2659
  }
1361
- _context16.next = 6;
1362
- return this.dbManager.clear(INDEXDB_STORE_NAME);
2660
+ _context26.next = 6;
2661
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25() {
2662
+ return _regeneratorRuntime().wrap(function _callee25$(_context25) {
2663
+ while (1) switch (_context25.prev = _context25.next) {
2664
+ case 0:
2665
+ _context25.next = 2;
2666
+ return _this22.dbManager.clear(INDEXDB_STORE_NAME);
2667
+ case 2:
2668
+ case "end":
2669
+ return _context25.stop();
2670
+ }
2671
+ }, _callee25);
2672
+ })));
1363
2673
  case 6:
1364
2674
  this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, '');
1365
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
2675
+ this.emitOrdersChanged([], 'clear');
1366
2676
  case 8:
1367
2677
  case "end":
1368
- return _context16.stop();
2678
+ return _context26.stop();
1369
2679
  }
1370
- }, _callee16, this);
2680
+ }, _callee26, this);
1371
2681
  }));
1372
2682
  function clear() {
1373
2683
  return _clear.apply(this, arguments);
1374
2684
  }
1375
2685
  return clear;
1376
- }()
2686
+ }())
1377
2687
  }]);
1378
2688
  return OrderModule;
1379
2689
  }(BaseModule);