@pisell/pisellos 2.2.244 → 2.2.246

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 (316) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.js +3 -2
  2. package/dist/model/strategy/adapter/walletPass/utils.js +7 -4
  3. package/dist/modules/BookingContext/index.d.ts +48 -0
  4. package/dist/modules/BookingContext/index.js +566 -0
  5. package/dist/modules/BookingContext/types.d.ts +102 -0
  6. package/dist/modules/BookingContext/types.js +51 -0
  7. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +16 -0
  8. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +284 -0
  9. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +8 -0
  10. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +148 -0
  11. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +76 -0
  12. package/dist/modules/BookingContext/utils/cacheItemToBookingInput.js +218 -0
  13. package/dist/modules/BookingContext/utils/flexible.d.ts +28 -0
  14. package/dist/modules/BookingContext/utils/flexible.js +56 -0
  15. package/dist/modules/BookingContext/utils/formatResourceList.d.ts +8 -0
  16. package/dist/modules/BookingContext/utils/formatResourceList.js +38 -0
  17. package/dist/modules/BookingContext/utils/index.d.ts +11 -0
  18. package/dist/modules/BookingContext/utils/index.js +11 -0
  19. package/dist/modules/BookingContext/utils/noResource.d.ts +13 -0
  20. package/dist/modules/BookingContext/utils/noResource.js +77 -0
  21. package/dist/modules/BookingContext/utils/orderLineDisplay.d.ts +1 -0
  22. package/dist/modules/BookingContext/utils/orderLineDisplay.js +36 -0
  23. package/dist/modules/BookingContext/utils/productExtend.d.ts +72 -0
  24. package/dist/modules/BookingContext/utils/productExtend.js +339 -0
  25. package/dist/modules/BookingContext/utils/resourceErrors.d.ts +41 -0
  26. package/dist/modules/BookingContext/utils/resourceErrors.js +74 -0
  27. package/dist/modules/BookingContext/utils/resourceSelection.d.ts +7 -0
  28. package/dist/modules/BookingContext/utils/resourceSelection.js +24 -0
  29. package/dist/modules/BookingContext/utils/resources.d.ts +80 -0
  30. package/dist/modules/BookingContext/utils/resources.js +486 -0
  31. package/dist/modules/BookingContext/utils/serviceTimes.d.ts +55 -0
  32. package/dist/modules/BookingContext/utils/serviceTimes.js +151 -0
  33. package/dist/modules/BookingContext/utils/timeSlices.d.ts +42 -0
  34. package/dist/modules/BookingContext/utils/timeSlices.js +100 -0
  35. package/dist/modules/Cart/utils/cartProduct.js +24 -3
  36. package/dist/modules/Cart/utils/changePrice.js +11 -11
  37. package/dist/modules/Customer/index.d.ts +20 -0
  38. package/dist/modules/Customer/index.js +172 -83
  39. package/dist/modules/Customer/types.d.ts +2 -0
  40. package/dist/modules/Discount/index.d.ts +1 -1
  41. package/dist/modules/Discount/index.js +13 -6
  42. package/dist/modules/Discount/types.d.ts +1 -0
  43. package/dist/modules/OpenData/index.d.ts +8 -0
  44. package/dist/modules/OpenData/index.js +37 -17
  45. package/dist/modules/Order/index.d.ts +277 -18
  46. package/dist/modules/Order/index.js +3581 -779
  47. package/dist/modules/Order/types.d.ts +286 -31
  48. package/dist/modules/Order/types.js +38 -0
  49. package/dist/modules/Order/utils/manualProductDiscount.d.ts +106 -0
  50. package/dist/modules/Order/utils/manualProductDiscount.js +210 -0
  51. package/dist/modules/Order/utils.d.ts +147 -5
  52. package/dist/modules/Order/utils.js +750 -104
  53. package/dist/modules/Payment/index.d.ts +10 -13
  54. package/dist/modules/Payment/index.js +467 -837
  55. package/dist/modules/Payment/types.d.ts +2 -0
  56. package/dist/modules/Payment/utils.js +2 -1
  57. package/dist/modules/Payment/walletpass.js +41 -25
  58. package/dist/modules/ProductList/index.d.ts +16 -12
  59. package/dist/modules/ProductList/index.js +133 -59
  60. package/dist/modules/ProductList/types.d.ts +14 -0
  61. package/dist/modules/Quotation/index.d.ts +0 -1
  62. package/dist/modules/Quotation/index.js +25 -22
  63. package/dist/modules/Rules/index.d.ts +4 -0
  64. package/dist/modules/Rules/index.js +97 -70
  65. package/dist/modules/Rules/types.d.ts +1 -0
  66. package/dist/modules/SalesSummary/index.d.ts +8 -25
  67. package/dist/modules/SalesSummary/index.js +86 -35
  68. package/dist/modules/SalesSummary/types.d.ts +4 -1
  69. package/dist/modules/SalesSummary/utils.d.ts +2 -25
  70. package/dist/modules/SalesSummary/utils.js +794 -162
  71. package/dist/modules/Schedule/index.d.ts +7 -0
  72. package/dist/modules/Schedule/index.js +24 -2
  73. package/dist/modules/Summary/index.js +4 -3
  74. package/dist/modules/SurchargeList/index.d.ts +16 -0
  75. package/dist/modules/SurchargeList/index.js +162 -0
  76. package/dist/modules/SurchargeList/types.d.ts +11 -0
  77. package/dist/modules/SurchargeList/types.js +1 -0
  78. package/dist/modules/index.d.ts +2 -0
  79. package/dist/modules/index.js +3 -1
  80. package/dist/plugins/request.d.ts +1 -0
  81. package/dist/server/index.d.ts +204 -1
  82. package/dist/server/index.js +3654 -922
  83. package/dist/server/modules/index.d.ts +2 -0
  84. package/dist/server/modules/index.js +2 -0
  85. package/dist/server/modules/order/index.d.ts +120 -3
  86. package/dist/server/modules/order/index.js +1762 -448
  87. package/dist/server/modules/order/types.d.ts +32 -3
  88. package/dist/server/modules/order/types.js +8 -0
  89. package/dist/server/modules/order/utils/filterBookings.js +26 -3
  90. package/dist/server/modules/order/utils/filterOrders.js +23 -8
  91. package/dist/server/modules/payment/index.d.ts +28 -0
  92. package/dist/server/modules/payment/index.js +305 -0
  93. package/dist/server/modules/payment/types.d.ts +9 -0
  94. package/dist/server/modules/payment/types.js +1 -0
  95. package/dist/server/modules/products/index.d.ts +34 -7
  96. package/dist/server/modules/products/index.js +631 -317
  97. package/dist/server/modules/resource/index.d.ts +2 -0
  98. package/dist/server/modules/resource/index.js +29 -3
  99. package/dist/server/modules/schedule/index.d.ts +4 -4
  100. package/dist/server/modules/schedule/index.js +111 -88
  101. package/dist/server/test.json +713 -0
  102. package/dist/server/utils/small-ticket.d.ts +71 -0
  103. package/dist/server/utils/small-ticket.js +840 -0
  104. package/dist/solution/BaseSales/index.d.ts +133 -10
  105. package/dist/solution/BaseSales/index.js +1950 -447
  106. package/dist/solution/BaseSales/types.d.ts +82 -6
  107. package/dist/solution/BaseSales/types.js +5 -4
  108. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +287 -0
  109. package/dist/solution/BaseSales/utils/cartPromotion.js +1438 -0
  110. package/dist/solution/BaseSales/utils/quotationPrice.d.ts +7 -0
  111. package/dist/solution/BaseSales/utils/quotationPrice.js +237 -0
  112. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +1 -0
  113. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +105 -24
  114. package/dist/solution/BaseSales/utils.d.ts +1 -1
  115. package/dist/solution/BaseSales/utils.js +62 -21
  116. package/dist/solution/BookingByStep/index.d.ts +1 -1
  117. package/dist/solution/BookingTicket/index.d.ts +271 -11
  118. package/dist/solution/BookingTicket/index.js +1777 -242
  119. package/dist/solution/BookingTicket/types.d.ts +118 -1
  120. package/dist/solution/BookingTicket/types.js +41 -2
  121. package/dist/solution/BookingTicket/utils/addProductDecision.d.ts +117 -0
  122. package/dist/solution/BookingTicket/utils/addProductDecision.js +346 -0
  123. package/dist/solution/BookingTicket/utils/addTimeAvailability.d.ts +35 -0
  124. package/dist/solution/BookingTicket/utils/addTimeAvailability.js +95 -0
  125. package/dist/solution/BookingTicket/utils/bookingStatus.d.ts +40 -0
  126. package/dist/solution/BookingTicket/utils/bookingStatus.js +70 -0
  127. package/dist/solution/BookingTicket/utils/cartView.d.ts +9 -1
  128. package/dist/solution/BookingTicket/utils/cartView.js +94 -7
  129. package/dist/solution/BookingTicket/utils/exampleData.d.ts +123 -0
  130. package/dist/solution/BookingTicket/utils/exampleData.js +183 -0
  131. package/dist/solution/BookingTicket/utils/resolveBestAddTimePlan.d.ts +185 -0
  132. package/dist/solution/BookingTicket/utils/resolveBestAddTimePlan.js +438 -0
  133. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +36 -0
  134. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +400 -0
  135. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +32 -0
  136. package/dist/solution/BookingTicket/utils/scan/formatGlobalScan.js +56 -0
  137. package/dist/solution/BookingTicket/utils/scan/index.d.ts +5 -0
  138. package/dist/solution/BookingTicket/utils/scan/index.js +20 -8
  139. package/dist/solution/BookingTicket/utils/scan/scanProductValues.d.ts +21 -0
  140. package/dist/solution/BookingTicket/utils/scan/scanProductValues.js +150 -0
  141. package/dist/solution/BookingTicket/utils/sessionCatalogStale.d.ts +23 -0
  142. package/dist/solution/BookingTicket/utils/sessionCatalogStale.js +78 -0
  143. package/dist/solution/Checkout/index.d.ts +1 -0
  144. package/dist/solution/Checkout/index.js +10 -9
  145. package/dist/solution/RegisterAndLogin/config.js +2 -10
  146. package/dist/solution/ScanOrder/index.d.ts +9 -3
  147. package/dist/solution/ScanOrder/index.js +241 -134
  148. package/dist/solution/ScanOrder/types.d.ts +9 -5
  149. package/dist/solution/ScanOrder/types.js +2 -3
  150. package/dist/solution/ScanOrder/utils.d.ts +1 -1
  151. package/dist/solution/ScanOrder/utils.js +84 -22
  152. package/dist/solution/VenueBooking/index.d.ts +5 -2
  153. package/dist/solution/VenueBooking/index.js +110 -59
  154. package/dist/solution/VenueBooking/sales-section-4-annotated.json +0 -2
  155. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +4 -0
  156. package/dist/solution/VenueBooking/utils/slotMerge.js +10 -0
  157. package/dist/types/index.d.ts +10 -0
  158. package/lib/model/strategy/adapter/promotion/evaluator.js +2 -1
  159. package/lib/model/strategy/adapter/promotion/index.js +49 -0
  160. package/lib/model/strategy/adapter/walletPass/utils.js +3 -2
  161. package/lib/modules/BookingContext/index.d.ts +48 -0
  162. package/lib/modules/BookingContext/index.js +368 -0
  163. package/lib/modules/BookingContext/types.d.ts +102 -0
  164. package/lib/modules/BookingContext/types.js +34 -0
  165. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.d.ts +16 -0
  166. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +276 -0
  167. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.d.ts +8 -0
  168. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +154 -0
  169. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.d.ts +76 -0
  170. package/lib/modules/BookingContext/utils/cacheItemToBookingInput.js +201 -0
  171. package/lib/modules/BookingContext/utils/flexible.d.ts +28 -0
  172. package/lib/modules/BookingContext/utils/flexible.js +80 -0
  173. package/lib/modules/BookingContext/utils/formatResourceList.d.ts +8 -0
  174. package/lib/modules/BookingContext/utils/formatResourceList.js +50 -0
  175. package/lib/modules/BookingContext/utils/index.d.ts +11 -0
  176. package/lib/modules/BookingContext/utils/index.js +43 -0
  177. package/lib/modules/BookingContext/utils/noResource.d.ts +13 -0
  178. package/lib/modules/BookingContext/utils/noResource.js +90 -0
  179. package/lib/modules/BookingContext/utils/orderLineDisplay.d.ts +1 -0
  180. package/lib/modules/BookingContext/utils/orderLineDisplay.js +56 -0
  181. package/lib/modules/BookingContext/utils/productExtend.d.ts +72 -0
  182. package/lib/modules/BookingContext/utils/productExtend.js +283 -0
  183. package/lib/modules/BookingContext/utils/resourceErrors.d.ts +41 -0
  184. package/lib/modules/BookingContext/utils/resourceErrors.js +80 -0
  185. package/lib/modules/BookingContext/utils/resourceSelection.d.ts +7 -0
  186. package/lib/modules/BookingContext/utils/resourceSelection.js +46 -0
  187. package/lib/modules/BookingContext/utils/resources.d.ts +80 -0
  188. package/lib/modules/BookingContext/utils/resources.js +377 -0
  189. package/lib/modules/BookingContext/utils/serviceTimes.d.ts +55 -0
  190. package/lib/modules/BookingContext/utils/serviceTimes.js +162 -0
  191. package/lib/modules/BookingContext/utils/timeSlices.d.ts +42 -0
  192. package/lib/modules/BookingContext/utils/timeSlices.js +124 -0
  193. package/lib/modules/Cart/utils/cartProduct.js +20 -3
  194. package/lib/modules/Cart/utils/changePrice.js +12 -20
  195. package/lib/modules/Customer/index.d.ts +20 -0
  196. package/lib/modules/Customer/index.js +64 -11
  197. package/lib/modules/Customer/types.d.ts +2 -0
  198. package/lib/modules/Discount/index.d.ts +1 -1
  199. package/lib/modules/Discount/index.js +9 -1
  200. package/lib/modules/Discount/types.d.ts +1 -0
  201. package/lib/modules/OpenData/index.d.ts +8 -0
  202. package/lib/modules/OpenData/index.js +19 -5
  203. package/lib/modules/Order/index.d.ts +277 -18
  204. package/lib/modules/Order/index.js +2317 -337
  205. package/lib/modules/Order/types.d.ts +286 -31
  206. package/lib/modules/Order/types.js +1 -0
  207. package/lib/modules/Order/utils/manualProductDiscount.d.ts +106 -0
  208. package/lib/modules/Order/utils/manualProductDiscount.js +206 -0
  209. package/lib/modules/Order/utils.d.ts +147 -5
  210. package/lib/modules/Order/utils.js +615 -46
  211. package/lib/modules/Payment/index.d.ts +10 -13
  212. package/lib/modules/Payment/index.js +18 -150
  213. package/lib/modules/Payment/types.d.ts +2 -0
  214. package/lib/modules/Payment/utils.js +2 -1
  215. package/lib/modules/Payment/walletpass.js +16 -3
  216. package/lib/modules/ProductList/index.d.ts +16 -12
  217. package/lib/modules/ProductList/index.js +41 -4
  218. package/lib/modules/ProductList/types.d.ts +14 -0
  219. package/lib/modules/Quotation/index.d.ts +0 -1
  220. package/lib/modules/Quotation/index.js +19 -16
  221. package/lib/modules/Rules/index.d.ts +4 -0
  222. package/lib/modules/Rules/index.js +137 -120
  223. package/lib/modules/Rules/types.d.ts +1 -0
  224. package/lib/modules/SalesSummary/index.d.ts +8 -25
  225. package/lib/modules/SalesSummary/index.js +30 -4
  226. package/lib/modules/SalesSummary/types.d.ts +4 -1
  227. package/lib/modules/SalesSummary/utils.d.ts +2 -25
  228. package/lib/modules/SalesSummary/utils.js +645 -91
  229. package/lib/modules/Schedule/index.d.ts +7 -0
  230. package/lib/modules/Schedule/index.js +17 -1
  231. package/lib/modules/Summary/index.js +5 -4
  232. package/lib/modules/SurchargeList/index.d.ts +16 -0
  233. package/lib/modules/SurchargeList/index.js +89 -0
  234. package/lib/modules/SurchargeList/types.d.ts +11 -0
  235. package/lib/modules/SurchargeList/types.js +17 -0
  236. package/lib/modules/index.d.ts +2 -0
  237. package/lib/modules/index.js +5 -1
  238. package/lib/plugins/request.d.ts +1 -0
  239. package/lib/server/index.d.ts +204 -1
  240. package/lib/server/index.js +1891 -59
  241. package/lib/server/modules/index.d.ts +2 -0
  242. package/lib/server/modules/index.js +3 -0
  243. package/lib/server/modules/order/index.d.ts +120 -3
  244. package/lib/server/modules/order/index.js +887 -94
  245. package/lib/server/modules/order/types.d.ts +32 -3
  246. package/lib/server/modules/order/utils/filterBookings.js +24 -5
  247. package/lib/server/modules/order/utils/filterOrders.js +15 -6
  248. package/lib/server/modules/payment/index.d.ts +28 -0
  249. package/lib/server/modules/payment/index.js +192 -0
  250. package/lib/server/modules/payment/types.d.ts +9 -0
  251. package/lib/server/modules/payment/types.js +17 -0
  252. package/lib/server/modules/products/index.d.ts +34 -7
  253. package/lib/server/modules/products/index.js +189 -54
  254. package/lib/server/modules/resource/index.d.ts +2 -0
  255. package/lib/server/modules/resource/index.js +27 -3
  256. package/lib/server/modules/schedule/index.d.ts +4 -4
  257. package/lib/server/modules/schedule/index.js +47 -40
  258. package/lib/server/test.json +713 -0
  259. package/lib/server/utils/small-ticket.d.ts +71 -0
  260. package/lib/server/utils/small-ticket.js +800 -0
  261. package/lib/solution/BaseSales/index.d.ts +133 -10
  262. package/lib/solution/BaseSales/index.js +1111 -63
  263. package/lib/solution/BaseSales/types.d.ts +82 -6
  264. package/lib/solution/BaseSales/types.js +3 -1
  265. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +287 -0
  266. package/lib/solution/BaseSales/utils/cartPromotion.js +992 -0
  267. package/lib/solution/BaseSales/utils/quotationPrice.d.ts +7 -0
  268. package/lib/solution/BaseSales/utils/quotationPrice.js +277 -0
  269. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +1 -0
  270. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +106 -18
  271. package/lib/solution/BaseSales/utils.d.ts +1 -1
  272. package/lib/solution/BaseSales/utils.js +54 -10
  273. package/lib/solution/BookingByStep/index.d.ts +1 -1
  274. package/lib/solution/BookingTicket/index.d.ts +271 -11
  275. package/lib/solution/BookingTicket/index.js +922 -29
  276. package/lib/solution/BookingTicket/types.d.ts +118 -1
  277. package/lib/solution/BookingTicket/types.js +11 -0
  278. package/lib/solution/BookingTicket/utils/addProductDecision.d.ts +117 -0
  279. package/lib/solution/BookingTicket/utils/addProductDecision.js +318 -0
  280. package/lib/solution/BookingTicket/utils/addTimeAvailability.d.ts +35 -0
  281. package/lib/solution/BookingTicket/utils/addTimeAvailability.js +125 -0
  282. package/lib/solution/BookingTicket/utils/bookingStatus.d.ts +40 -0
  283. package/lib/solution/BookingTicket/utils/bookingStatus.js +44 -2
  284. package/lib/solution/BookingTicket/utils/cartView.d.ts +9 -1
  285. package/lib/solution/BookingTicket/utils/cartView.js +61 -6
  286. package/lib/solution/BookingTicket/utils/exampleData.d.ts +123 -0
  287. package/lib/solution/BookingTicket/utils/exampleData.js +0 -0
  288. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.d.ts +185 -0
  289. package/lib/solution/BookingTicket/utils/resolveBestAddTimePlan.js +254 -0
  290. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +36 -0
  291. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +169 -0
  292. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.d.ts +32 -0
  293. package/lib/solution/BookingTicket/utils/scan/formatGlobalScan.js +51 -0
  294. package/lib/solution/BookingTicket/utils/scan/index.d.ts +5 -0
  295. package/lib/solution/BookingTicket/utils/scan/index.js +17 -3
  296. package/lib/solution/BookingTicket/utils/scan/scanProductValues.d.ts +21 -0
  297. package/lib/solution/BookingTicket/utils/scan/scanProductValues.js +127 -0
  298. package/lib/solution/BookingTicket/utils/sessionCatalogStale.d.ts +23 -0
  299. package/lib/solution/BookingTicket/utils/sessionCatalogStale.js +85 -0
  300. package/lib/solution/Checkout/index.d.ts +1 -0
  301. package/lib/solution/Checkout/index.js +1 -2
  302. package/lib/solution/RegisterAndLogin/config.js +2 -10
  303. package/lib/solution/ScanOrder/index.d.ts +9 -3
  304. package/lib/solution/ScanOrder/index.js +153 -70
  305. package/lib/solution/ScanOrder/types.d.ts +9 -5
  306. package/lib/solution/ScanOrder/utils.d.ts +1 -1
  307. package/lib/solution/ScanOrder/utils.js +83 -17
  308. package/lib/solution/VenueBooking/index.d.ts +5 -2
  309. package/lib/solution/VenueBooking/index.js +54 -17
  310. package/lib/solution/VenueBooking/sales-section-4-annotated.json +0 -2
  311. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +4 -0
  312. package/lib/solution/VenueBooking/utils/slotMerge.js +10 -0
  313. package/lib/types/index.d.ts +10 -0
  314. package/package.json +1 -1
  315. package/dist/solution/Checkout/appointmentDemo.json +0 -1
  316. 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,304 @@ 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
+ preferIncomingProducts: true
1068
+ });
1069
+ pendingMap.delete(_storageKey);
1070
+ memoryPendingMap.delete(_storageKey);
1071
+ mergeActions[_storageKey] = 'update';
1072
+ case 44:
1073
+ _context11.next = 35;
1074
+ break;
1075
+ case 46:
1076
+ _context11.next = 51;
1077
+ break;
1078
+ case 48:
1079
+ _context11.prev = 48;
1080
+ _context11.t1 = _context11["catch"](33);
1081
+ _iterator5.e(_context11.t1);
1082
+ case 51:
1083
+ _context11.prev = 51;
1084
+ _iterator5.f();
1085
+ return _context11.finish(51);
1086
+ case 54:
1087
+ _iterator6 = _createForOfIteratorHelper(memoryPendingMap.entries());
1088
+ try {
1089
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1090
+ _step6$value = _slicedToArray(_step6.value, 2), _storageKey2 = _step6$value[0], _order = _step6$value[1];
1091
+ mergeActions[_storageKey2] = 'insert';
1092
+ updatedList.push(_order);
1093
+ }
1094
+ } catch (err) {
1095
+ _iterator6.e(err);
1096
+ } finally {
1097
+ _iterator6.f();
1098
+ }
1099
+ this.store.list = this.compactOrderListByIdentity(updatedList, 'upsertPendingSyncOrders.store').list;
1100
+ this.syncOrdersMap();
1101
+ _context11.next = 60;
1102
+ return this.patchOrdersInSQLite(patchedOrders, 'upsertPendingSyncOrders', mergeActions);
1103
+ case 60:
1104
+ this.logInfo('upsertPendingSyncOrders-结束', {
1105
+ count: patchedOrders.length,
1106
+ storeOrderCountAfter: this.store.list.length
1107
+ });
1108
+ _context11.next = 63;
1109
+ return this.emitOrdersChanged(patchedOrders, 'upsertPendingSyncOrders');
1110
+ case 63:
1111
+ case "end":
1112
+ return _context11.stop();
1113
+ }
1114
+ }, _callee11, this, [[6, 19, 22, 25], [33, 48, 51, 54]]);
1115
+ }));
1116
+ function upsertPendingSyncOrders(_x7) {
1117
+ return _upsertPendingSyncOrders.apply(this, arguments);
1118
+ }
1119
+ return upsertPendingSyncOrders;
1120
+ }()
1121
+ /**
1122
+ * 通过 SSE 按自定义 query 拉取订单(支持 select/with 精简字段)
1123
+ */
1124
+ )
1125
+ }, {
1126
+ key: "fetchOrdersBySSE",
1127
+ value: (function () {
1128
+ var _fetchOrdersBySSE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1129
+ var query,
1130
+ data,
1131
+ _args12 = arguments;
1132
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1133
+ while (1) switch (_context12.prev = _context12.next) {
1134
+ case 0:
1135
+ query = _args12.length > 0 && _args12[0] !== undefined ? _args12[0] : {};
1136
+ if (this.orderDataSource) {
1137
+ _context12.next = 3;
1138
+ break;
1139
+ }
1140
+ return _context12.abrupt("return", []);
1141
+ case 3:
1142
+ _context12.prev = 3;
1143
+ _context12.next = 6;
1144
+ return this.orderDataSource.run({
1145
+ sse: {
1146
+ query: query
1147
+ }
1148
+ });
1149
+ case 6:
1150
+ data = _context12.sent;
1151
+ return _context12.abrupt("return", data || []);
1152
+ case 10:
1153
+ _context12.prev = 10;
1154
+ _context12.t0 = _context12["catch"](3);
1155
+ this.logError('fetchOrdersBySSE-失败', {
1156
+ error: _context12.t0 instanceof Error ? _context12.t0.message : String(_context12.t0)
1157
+ });
1158
+ return _context12.abrupt("return", []);
1159
+ case 14:
1160
+ case "end":
1161
+ return _context12.stop();
1162
+ }
1163
+ }, _callee12, this, [[3, 10]]);
1164
+ }));
1165
+ function fetchOrdersBySSE() {
1166
+ return _fetchOrdersBySSE.apply(this, arguments);
1167
+ }
1168
+ return fetchOrdersBySSE;
1169
+ }())
1170
+ }, {
1171
+ key: "getRoutes",
1172
+ value: function getRoutes() {
1173
+ return [];
1174
+ }
1175
+ }, {
1176
+ key: "destroy",
1177
+ value: function destroy() {
634
1178
  var _this$orderDataSource;
635
1179
  if (this.syncTimer) {
636
1180
  clearTimeout(this.syncTimer);
@@ -644,45 +1188,120 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
644
1188
  }, {
645
1189
  key: "syncOrdersMap",
646
1190
  value: function syncOrdersMap() {
647
- var _this6 = this;
1191
+ var _this11 = this;
648
1192
  this.store.map.clear();
649
1193
  this.resourceIdIndex.clear();
650
- var _iterator = _createForOfIteratorHelper(this.store.list),
651
- _step;
1194
+ var _iterator7 = _createForOfIteratorHelper(this.store.list),
1195
+ _step7;
652
1196
  try {
653
1197
  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;
1198
+ var order = _step7.value;
1199
+ var primaryIdentity = _this11.getOrderMapKey(order);
1200
+ if (!primaryIdentity) return 1; // continue
1201
+ _this11.store.map.set(primaryIdentity, order);
1202
+ var resourceIds = _this11.extractResourceIds(order);
1203
+ var _iterator8 = _createForOfIteratorHelper(resourceIds),
1204
+ _step8;
661
1205
  try {
662
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
663
- var resourceId = _step2.value;
1206
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1207
+ var resourceId = _step8.value;
664
1208
  var key = String(resourceId);
665
- var existing = _this6.resourceIdIndex.get(key) || [];
1209
+ var existing = _this11.resourceIdIndex.get(key) || [];
666
1210
  if (existing.some(function (eid) {
667
- return _this6.getIdKey(eid) === _this6.getIdKey(id);
1211
+ return _this11.getIdKey(eid) === primaryIdentity;
668
1212
  })) continue;
669
- existing.push(id);
670
- _this6.resourceIdIndex.set(key, existing);
1213
+ existing.push(primaryIdentity);
1214
+ _this11.resourceIdIndex.set(key, existing);
671
1215
  }
672
1216
  } catch (err) {
673
- _iterator2.e(err);
1217
+ _iterator8.e(err);
674
1218
  } finally {
675
- _iterator2.f();
1219
+ _iterator8.f();
676
1220
  }
677
1221
  };
678
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1222
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
679
1223
  if (_loop()) continue;
680
1224
  }
681
1225
  } catch (err) {
682
- _iterator.e(err);
1226
+ _iterator7.e(err);
683
1227
  } finally {
684
- _iterator.f();
1228
+ _iterator7.f();
1229
+ }
1230
+ }
1231
+ }, {
1232
+ key: "getOrderMapKey",
1233
+ value: function getOrderMapKey(order) {
1234
+ if (!order) return '';
1235
+ if (!this.isBlankIdentityValue(order.order_id)) {
1236
+ return this.getIdKey(order.order_id);
1237
+ }
1238
+ var externalSaleNumber = order.external_sale_number;
1239
+ if (!this.isBlankIdentityValue(externalSaleNumber)) {
1240
+ return this.getIdKey(externalSaleNumber);
1241
+ }
1242
+ return '';
1243
+ }
1244
+ }, {
1245
+ key: "isBlankIdentityValue",
1246
+ value: function isBlankIdentityValue(value) {
1247
+ return value === undefined || value === null || value === '';
1248
+ }
1249
+ }, {
1250
+ key: "getOrderIdentityEntries",
1251
+ value: function getOrderIdentityEntries(order) {
1252
+ var _this12 = this;
1253
+ if (!order) return [];
1254
+ var record = order;
1255
+ var candidates = [{
1256
+ field: 'order_id',
1257
+ value: order.order_id
1258
+ }, {
1259
+ field: 'external_sale_number',
1260
+ value: record.external_sale_number
1261
+ }, {
1262
+ field: 'order_number',
1263
+ value: record.order_number
1264
+ }, {
1265
+ field: 'shop_order_number',
1266
+ value: record.shop_order_number
1267
+ }];
1268
+ var entries = [];
1269
+ var _loop2 = function _loop2() {
1270
+ var candidate = _candidates[_i];
1271
+ if (_this12.isBlankIdentityValue(candidate.value)) return 0; // continue
1272
+ var key = _this12.getIdKey(candidate.value);
1273
+ if (entries.some(function (entry) {
1274
+ return entry.field === candidate.field && entry.key === key;
1275
+ })) return 0; // continue
1276
+ entries.push({
1277
+ field: candidate.field,
1278
+ key: key
1279
+ });
1280
+ },
1281
+ _ret;
1282
+ for (var _i = 0, _candidates = candidates; _i < _candidates.length; _i++) {
1283
+ _ret = _loop2();
1284
+ if (_ret === 0) continue;
685
1285
  }
1286
+ return entries;
1287
+ }
1288
+ }, {
1289
+ key: "getOrderIdentityKeys",
1290
+ value: function getOrderIdentityKeys(order) {
1291
+ var keys = [];
1292
+ var _iterator9 = _createForOfIteratorHelper(this.getOrderIdentityEntries(order)),
1293
+ _step9;
1294
+ try {
1295
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1296
+ var entry = _step9.value;
1297
+ if (!keys.includes(entry.key)) keys.push(entry.key);
1298
+ }
1299
+ } catch (err) {
1300
+ _iterator9.e(err);
1301
+ } finally {
1302
+ _iterator9.f();
1303
+ }
1304
+ return keys;
686
1305
  }
687
1306
  }, {
688
1307
  key: "extractResourceIds",
@@ -708,8 +1327,8 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
708
1327
  value: function getOrderDateKey(order) {
709
1328
  var _order$bookings, _order$bookings2;
710
1329
  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];
1330
+ for (var _i2 = 0, _candidates2 = candidates; _i2 < _candidates2.length; _i2++) {
1331
+ var v = _candidates2[_i2];
713
1332
  if (!v) continue;
714
1333
  var text = String(v);
715
1334
  if (!text) continue;
@@ -736,28 +1355,30 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
736
1355
  }, {
737
1356
  key: "setupOrderSync",
738
1357
  value: function setupOrderSync() {
739
- var _this7 = this;
1358
+ var _this13 = this;
740
1359
  if (!this.orderDataSource) return;
741
1360
  this.orderDataSource.run({
742
1361
  pubsub: {
743
1362
  callback: function callback(res) {
744
1363
  var _message$id, _message$order_id, _message$type;
745
- console.log('orderDataSource');
1364
+ console.log('orderDataSource', res);
746
1365
  var pubsubReceivedAt = Date.now();
747
- var message = _this7.normalizeOrderSyncMessage(res);
1366
+ var message = _this13.normalizeOrderSyncMessage(res);
748
1367
  if (!message) return;
749
1368
  message._pubsubReceivedAt = pubsubReceivedAt;
750
- _this7.pendingSyncMessages.push(message);
751
- var throttleMs = _this7.getOrderSyncThrottleMs();
752
- _this7.logInfo('orderSync-收到消息并入队', {
1369
+ _this13.pendingSyncMessages.push(message);
1370
+ var throttleMs = _this13.getOrderSyncThrottleMs();
1371
+ var routeInfo = _this13.resolveSyncMessageRoute(message);
1372
+ _this13.logInfo('orderSync-收到消息并入队', {
753
1373
  id: (_message$id = message.id) !== null && _message$id !== void 0 ? _message$id : null,
754
1374
  order_id: (_message$order_id = message.order_id) !== null && _message$order_id !== void 0 ? _message$order_id : null,
755
1375
  type: (_message$type = message.type) !== null && _message$type !== void 0 ? _message$type : null,
756
- pendingCount: _this7.pendingSyncMessages.length,
1376
+ pendingCount: _this13.pendingSyncMessages.length,
757
1377
  throttleMs: throttleMs,
758
- pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString()
1378
+ pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString(),
1379
+ fullMessage: JSON.stringify(message)
759
1380
  });
760
- _this7.scheduleOrderSyncThrottle();
1381
+ _this13.scheduleOrderSyncThrottle();
761
1382
  }
762
1383
  }
763
1384
  }).catch(function () {
@@ -774,7 +1395,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
774
1395
  }, {
775
1396
  key: "scheduleOrderSyncThrottle",
776
1397
  value: function scheduleOrderSyncThrottle() {
777
- var _this8 = this;
1398
+ var _this14 = this;
778
1399
  if (this.isProcessingSyncBatch) return;
779
1400
  if (this.isIdlePhase) {
780
1401
  this.isIdlePhase = false;
@@ -785,8 +1406,8 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
785
1406
  if (this.syncTimer) return;
786
1407
  var throttleMs = this.getOrderSyncThrottleMs();
787
1408
  this.syncTimer = setTimeout(function () {
788
- _this8.syncTimer = undefined;
789
- void _this8.flushOrderSyncMessagesByThrottle();
1409
+ _this14.syncTimer = undefined;
1410
+ void _this14.flushOrderSyncMessagesByThrottle();
790
1411
  }, throttleMs);
791
1412
  }
792
1413
 
@@ -797,41 +1418,41 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
797
1418
  }, {
798
1419
  key: "flushOrderSyncMessagesByThrottle",
799
1420
  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) {
1421
+ var _flushOrderSyncMessagesByThrottle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
1422
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1423
+ while (1) switch (_context13.prev = _context13.next) {
803
1424
  case 0:
804
1425
  if (!this.isProcessingSyncBatch) {
805
- _context10.next = 2;
1426
+ _context13.next = 2;
806
1427
  break;
807
1428
  }
808
- return _context10.abrupt("return");
1429
+ return _context13.abrupt("return");
809
1430
  case 2:
810
1431
  if (!(this.pendingSyncMessages.length === 0)) {
811
- _context10.next = 5;
1432
+ _context13.next = 5;
812
1433
  break;
813
1434
  }
814
1435
  this.isIdlePhase = true;
815
- return _context10.abrupt("return");
1436
+ return _context13.abrupt("return");
816
1437
  case 5:
817
1438
  this.isProcessingSyncBatch = true;
818
- _context10.prev = 6;
819
- _context10.next = 9;
1439
+ _context13.prev = 6;
1440
+ _context13.next = 9;
820
1441
  return this.processOrderSyncMessages();
821
1442
  case 9:
822
- _context10.prev = 9;
1443
+ _context13.prev = 9;
823
1444
  this.isProcessingSyncBatch = false;
824
1445
  if (this.pendingSyncMessages.length > 0) {
825
1446
  this.scheduleOrderSyncThrottle();
826
1447
  } else {
827
1448
  this.isIdlePhase = true;
828
1449
  }
829
- return _context10.finish(9);
1450
+ return _context13.finish(9);
830
1451
  case 13:
831
1452
  case "end":
832
- return _context10.stop();
1453
+ return _context13.stop();
833
1454
  }
834
- }, _callee10, this, [[6,, 9, 13]]);
1455
+ }, _callee13, this, [[6,, 9, 13]]);
835
1456
  }));
836
1457
  function flushOrderSyncMessagesByThrottle() {
837
1458
  return _flushOrderSyncMessagesByThrottle.apply(this, arguments);
@@ -853,18 +1474,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
853
1474
  }, {
854
1475
  key: "processOrderSyncMessages",
855
1476
  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) {
1477
+ var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
1478
+ var _this15 = this;
1479
+ var messages, batchProcessStartAt, earliestReceivedAt, upsertOrders, refreshIds, uniqueRefreshIds, upsertList, _this$filterRedundant, toFetch, skipped, freshOrders, batchProcessEndAt;
1480
+ return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1481
+ while (1) switch (_context14.prev = _context14.next) {
860
1482
  case 0:
861
1483
  messages = _toConsumableArray(this.pendingSyncMessages);
862
1484
  this.pendingSyncMessages = [];
863
1485
  if (!(messages.length === 0)) {
864
- _context11.next = 4;
1486
+ _context14.next = 4;
865
1487
  break;
866
1488
  }
867
- return _context11.abrupt("return");
1489
+ return _context14.abrupt("return");
868
1490
  case 4:
869
1491
  batchProcessStartAt = Date.now();
870
1492
  earliestReceivedAt = Math.min.apply(Math, _toConsumableArray(messages.map(function (m) {
@@ -879,43 +1501,18 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
879
1501
  });
880
1502
  upsertOrders = new Map();
881
1503
  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:
1504
+ messages.forEach(function (msg, msgIndex) {
1505
+ var routeInfo = _this15.resolveSyncMessageRoute(msg);
1506
+ var hasBatchIds = routeInfo.hasBatchIds;
1507
+ var singleId = routeInfo.singleId;
1508
+ var hasSingleId = routeInfo.hasSingleId;
1509
+ var normalizedBody = _this15.normalizeOrderSyncPayload(msg.body || msg.data);
1510
+ if (routeInfo.route === 'bodyUpsert' && normalizedBody) {
1511
+ upsertOrders.set(_this15.getIdKey(normalizedBody.order_id), normalizedBody);
1512
+ return;
1513
+ }
1514
+ 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));
1515
+ });
919
1516
  uniqueRefreshIds = this.uniqueOrderIds(refreshIds);
920
1517
  upsertList = _toConsumableArray(upsertOrders.values());
921
1518
  this.logInfo('processOrderSyncMessages-去重完成', {
@@ -923,33 +1520,42 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
923
1520
  refreshIdCount: uniqueRefreshIds.length
924
1521
  });
925
1522
  if (!(upsertList.length > 0)) {
926
- _context11.next = 39;
1523
+ _context14.next = 16;
927
1524
  break;
928
1525
  }
929
- _context11.next = 39;
930
- return this.mergeOrdersToStore(upsertList);
931
- case 39:
1526
+ _context14.next = 16;
1527
+ return this.mergeOrdersToStore(upsertList, 'pubsub.bodyUpsert');
1528
+ case 16:
932
1529
  if (!(uniqueRefreshIds.length > 0)) {
933
- _context11.next = 46;
1530
+ _context14.next = 28;
1531
+ break;
1532
+ }
1533
+ _this$filterRedundant = this.filterRedundantHttpRefreshIds(uniqueRefreshIds), toFetch = _this$filterRedundant.toFetch, skipped = _this$filterRedundant.skipped;
1534
+ if (skipped.length > 0) {}
1535
+ if (!(toFetch.length > 0)) {
1536
+ _context14.next = 28;
934
1537
  break;
935
1538
  }
936
- _context11.next = 42;
937
- return this.fetchOrdersByHttp(uniqueRefreshIds);
938
- case 42:
939
- freshOrders = _context11.sent;
1539
+ _context14.next = 22;
1540
+ return this.fetchOrdersByHttp(toFetch);
1541
+ case 22:
1542
+ freshOrders = _context14.sent;
940
1543
  if (!(freshOrders.length > 0)) {
941
- _context11.next = 46;
1544
+ _context14.next = 28;
942
1545
  break;
943
1546
  }
944
- _context11.next = 46;
945
- return this.mergeOrdersToStore(freshOrders);
946
- case 46:
1547
+ _context14.next = 26;
1548
+ return this.mergeOrdersToStore(freshOrders, 'pubsub.httpRefresh');
1549
+ case 26:
1550
+ _context14.next = 28;
1551
+ break;
1552
+ case 28:
947
1553
  if (!(upsertList.length === 0 && uniqueRefreshIds.length === 0)) {
948
- _context11.next = 48;
1554
+ _context14.next = 30;
949
1555
  break;
950
1556
  }
951
- return _context11.abrupt("return");
952
- case 48:
1557
+ return _context14.abrupt("return");
1558
+ case 30:
953
1559
  batchProcessEndAt = Date.now();
954
1560
  this.logInfo('processOrderSyncMessages-结束', {
955
1561
  upsertCount: upsertList.length,
@@ -957,13 +1563,13 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
957
1563
  batchProcessDurationMs: batchProcessEndAt - batchProcessStartAt,
958
1564
  totalFromPubsubToProcessedMs: batchProcessEndAt - earliestReceivedAt
959
1565
  });
960
- _context11.next = 52;
1566
+ _context14.next = 34;
961
1567
  return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
962
- case 52:
1568
+ case 34:
963
1569
  case "end":
964
- return _context11.stop();
1570
+ return _context14.stop();
965
1571
  }
966
- }, _callee11, this, [[10, 27, 30, 33]]);
1572
+ }, _callee14, this);
967
1573
  }));
968
1574
  function processOrderSyncMessages() {
969
1575
  return _processOrderSyncMessages.apply(this, arguments);
@@ -984,29 +1590,29 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
984
1590
  }, {
985
1591
  key: "fetchOrdersByHttp",
986
1592
  value: (function () {
987
- var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(ids) {
1593
+ var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(ids) {
988
1594
  var _orderList, orderList;
989
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
990
- while (1) switch (_context12.prev = _context12.next) {
1595
+ return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1596
+ while (1) switch (_context15.prev = _context15.next) {
991
1597
  case 0:
992
1598
  if (!(!this.orderDataSource || ids.length === 0)) {
993
- _context12.next = 2;
1599
+ _context15.next = 2;
994
1600
  break;
995
1601
  }
996
- return _context12.abrupt("return", []);
1602
+ return _context15.abrupt("return", []);
997
1603
  case 2:
998
- _context12.prev = 2;
1604
+ _context15.prev = 2;
999
1605
  if (!(typeof this.orderDataSource.fetchOrdersByIds === 'function')) {
1000
- _context12.next = 8;
1606
+ _context15.next = 8;
1001
1607
  break;
1002
1608
  }
1003
- _context12.next = 6;
1609
+ _context15.next = 6;
1004
1610
  return this.orderDataSource.fetchOrdersByIds(ids);
1005
1611
  case 6:
1006
- _orderList = _context12.sent;
1007
- return _context12.abrupt("return", _orderList || []);
1612
+ _orderList = _context15.sent;
1613
+ return _context15.abrupt("return", _orderList || []);
1008
1614
  case 8:
1009
- _context12.next = 10;
1615
+ _context15.next = 10;
1010
1616
  return this.orderDataSource.run({
1011
1617
  http: {
1012
1618
  query: {
@@ -1015,19 +1621,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1015
1621
  }
1016
1622
  });
1017
1623
  case 10:
1018
- orderList = _context12.sent;
1019
- return _context12.abrupt("return", orderList || []);
1624
+ orderList = _context15.sent;
1625
+ return _context15.abrupt("return", orderList || []);
1020
1626
  case 14:
1021
- _context12.prev = 14;
1022
- _context12.t0 = _context12["catch"](2);
1023
- return _context12.abrupt("return", []);
1627
+ _context15.prev = 14;
1628
+ _context15.t0 = _context15["catch"](2);
1629
+ return _context15.abrupt("return", []);
1024
1630
  case 17:
1025
1631
  case "end":
1026
- return _context12.stop();
1632
+ return _context15.stop();
1027
1633
  }
1028
- }, _callee12, this, [[2, 14]]);
1634
+ }, _callee15, this, [[2, 14]]);
1029
1635
  }));
1030
- function fetchOrdersByHttp(_x6) {
1636
+ function fetchOrdersByHttp(_x8) {
1031
1637
  return _fetchOrdersByHttp.apply(this, arguments);
1032
1638
  }
1033
1639
  return fetchOrdersByHttp;
@@ -1039,87 +1645,126 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1039
1645
  }, {
1040
1646
  key: "mergeOrdersToStore",
1041
1647
  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) {
1648
+ var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(freshOrders, source) {
1649
+ var normalizedFreshOrders, _iterator10, _step10, order, id, uniqueFreshOrders, uniqueFreshCount, patchedOrders, mergeActions, updatedList, _iterator11, _step11, fresh, matchIndex, storageKey, mergeKey, mergedOrder, insertCount, updateCount;
1650
+ return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1651
+ while (1) switch (_context16.prev = _context16.next) {
1047
1652
  case 0:
1048
1653
  this.logInfo('mergeOrdersToStore-开始', {
1049
1654
  freshOrderCount: freshOrders.length,
1050
- storeOrderCountBefore: this.store.list.length
1655
+ storeOrderCountBefore: this.store.list.length,
1656
+ source: source
1051
1657
  });
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;
1658
+ this.logDuplicateOrders("".concat(source, ".beforeMerge"), this.store.list);
1659
+ normalizedFreshOrders = [];
1660
+ _iterator10 = _createForOfIteratorHelper(freshOrders);
1661
+ _context16.prev = 4;
1662
+ _iterator10.s();
1663
+ case 6:
1664
+ if ((_step10 = _iterator10.n()).done) {
1665
+ _context16.next = 14;
1059
1666
  break;
1060
1667
  }
1061
- order = _step4.value;
1668
+ order = _step10.value;
1062
1669
  id = order === null || order === void 0 ? void 0 : order.order_id;
1063
1670
  if (!(id === undefined || id === null)) {
1064
- _context13.next = 10;
1671
+ _context16.next = 11;
1065
1672
  break;
1066
1673
  }
1067
- return _context13.abrupt("continue", 11);
1068
- case 10:
1069
- freshMap.set(this.getIdKey(id), order);
1674
+ return _context16.abrupt("continue", 12);
1070
1675
  case 11:
1071
- _context13.next = 5;
1676
+ normalizedFreshOrders.push(this.normalizeRemoteSyncedOrder(order));
1677
+ case 12:
1678
+ _context16.next = 6;
1072
1679
  break;
1073
- case 13:
1074
- _context13.next = 18;
1680
+ case 14:
1681
+ _context16.next = 19;
1075
1682
  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();
1683
+ case 16:
1684
+ _context16.prev = 16;
1685
+ _context16.t0 = _context16["catch"](4);
1686
+ _iterator10.e(_context16.t0);
1687
+ case 19:
1688
+ _context16.prev = 19;
1689
+ _iterator10.f();
1690
+ return _context16.finish(19);
1691
+ case 22:
1692
+ uniqueFreshOrders = this.compactOrderListByIdentity(normalizedFreshOrders, "".concat(source, ".incoming")).list;
1693
+ uniqueFreshCount = uniqueFreshOrders.length;
1694
+ patchedOrders = [];
1695
+ mergeActions = {};
1696
+ updatedList = _toConsumableArray(this.store.list);
1697
+ _iterator11 = _createForOfIteratorHelper(uniqueFreshOrders);
1698
+ _context16.prev = 28;
1699
+ _iterator11.s();
1700
+ case 30:
1701
+ if ((_step11 = _iterator11.n()).done) {
1702
+ _context16.next = 46;
1703
+ break;
1105
1704
  }
1106
- this.store.list = updatedList;
1705
+ fresh = _step11.value;
1706
+ matchIndex = this.findOrderIndexByIdentity(updatedList, fresh);
1707
+ storageKey = this.getOrderStorageKey(fresh);
1708
+ mergeKey = storageKey || (fresh.order_id !== undefined && fresh.order_id !== null ? this.getIdKey(fresh.order_id) : '');
1709
+ if (!(matchIndex >= 0)) {
1710
+ _context16.next = 41;
1711
+ break;
1712
+ }
1713
+ mergedOrder = this.mergeOrderRecords(updatedList[matchIndex], fresh);
1714
+ updatedList[matchIndex] = mergedOrder;
1715
+ patchedOrders.push(mergedOrder);
1716
+ if (mergeKey) mergeActions[mergeKey] = 'update';
1717
+ return _context16.abrupt("continue", 44);
1718
+ case 41:
1719
+ updatedList.push(fresh);
1720
+ patchedOrders.push(fresh);
1721
+ if (mergeKey) mergeActions[mergeKey] = 'insert';
1722
+ case 44:
1723
+ _context16.next = 30;
1724
+ break;
1725
+ case 46:
1726
+ _context16.next = 51;
1727
+ break;
1728
+ case 48:
1729
+ _context16.prev = 48;
1730
+ _context16.t1 = _context16["catch"](28);
1731
+ _iterator11.e(_context16.t1);
1732
+ case 51:
1733
+ _context16.prev = 51;
1734
+ _iterator11.f();
1735
+ return _context16.finish(51);
1736
+ case 54:
1737
+ insertCount = Object.values(mergeActions).filter(function (v) {
1738
+ return v === 'insert';
1739
+ }).length;
1740
+ updateCount = Object.values(mergeActions).filter(function (v) {
1741
+ return v === 'update';
1742
+ }).length;
1743
+ this.logInfo('mergeOrdersToStore-合并完成', {
1744
+ insertCount: insertCount,
1745
+ updateCount: updateCount,
1746
+ storeOrderCountAfter: this.store.list.length
1747
+ });
1748
+ this.store.list = this.compactOrderListByIdentity(updatedList, "".concat(source, ".store")).list;
1107
1749
  this.syncOrdersMap();
1108
- _context13.next = 29;
1109
- return this.saveOrdersToSQLite(this.store.list);
1110
- case 29:
1750
+ _context16.next = 61;
1751
+ return this.patchOrdersInSQLite(patchedOrders, source, mergeActions);
1752
+ case 61:
1111
1753
  this.logInfo('mergeOrdersToStore-结束', {
1112
1754
  uniqueFreshCount: uniqueFreshCount,
1113
- storeOrderCountAfter: this.store.list.length
1755
+ storeOrderCountAfter: this.store.list.length,
1756
+ insertCount: insertCount,
1757
+ updateCount: updateCount
1114
1758
  });
1115
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
1116
- case 31:
1759
+ _context16.next = 64;
1760
+ return this.emitOrdersChanged(patchedOrders, source);
1761
+ case 64:
1117
1762
  case "end":
1118
- return _context13.stop();
1763
+ return _context16.stop();
1119
1764
  }
1120
- }, _callee13, this, [[3, 15, 18, 21]]);
1765
+ }, _callee16, this, [[4, 16, 19, 22], [28, 48, 51, 54]]);
1121
1766
  }));
1122
- function mergeOrdersToStore(_x7) {
1767
+ function mergeOrdersToStore(_x9, _x10) {
1123
1768
  return _mergeOrdersToStore.apply(this, arguments);
1124
1769
  }
1125
1770
  return mergeOrdersToStore;
@@ -1156,17 +1801,17 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1156
1801
  key: "uniqueOrderIds",
1157
1802
  value: function uniqueOrderIds(ids) {
1158
1803
  var idMap = new Map();
1159
- var _iterator6 = _createForOfIteratorHelper(ids),
1160
- _step6;
1804
+ var _iterator12 = _createForOfIteratorHelper(ids),
1805
+ _step12;
1161
1806
  try {
1162
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1163
- var id = _step6.value;
1807
+ for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
1808
+ var id = _step12.value;
1164
1809
  idMap.set(this.getIdKey(id), id);
1165
1810
  }
1166
1811
  } catch (err) {
1167
- _iterator6.e(err);
1812
+ _iterator12.e(err);
1168
1813
  } finally {
1169
- _iterator6.f();
1814
+ _iterator12.f();
1170
1815
  }
1171
1816
  return _toConsumableArray(idMap.values());
1172
1817
  }
@@ -1175,6 +1820,278 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1175
1820
  value: function getIdKey(id) {
1176
1821
  return String(id);
1177
1822
  }
1823
+ }, {
1824
+ key: "isOrderLookupMatch",
1825
+ value: function isOrderLookupMatch(order, lookupKey) {
1826
+ var _this16 = this;
1827
+ if (!order || !lookupKey) return false;
1828
+ var candidates = [order.order_id, order.external_sale_number, order.order_number, order.shop_order_number, order.shop_full_order_number];
1829
+ return candidates.some(function (value) {
1830
+ if (value === undefined || value === null || value === '') return false;
1831
+ return _this16.getIdKey(value) === lookupKey;
1832
+ });
1833
+ }
1834
+
1835
+ /**
1836
+ * 解析订单 SQLite 主键,规则与宿主 OrderDataSource.getOrderStorageKey 一致。
1837
+ *
1838
+ * @example
1839
+ * const key = this.getOrderStorageKey({ order_id: 1001, external_sale_number: 'S-1001' })
1840
+ * // => 'S-1001'
1841
+ */
1842
+ }, {
1843
+ key: "getOrderStorageKey",
1844
+ value: function getOrderStorageKey(order) {
1845
+ var externalSaleNumber = order === null || order === void 0 ? void 0 : order.external_sale_number;
1846
+ if (externalSaleNumber !== undefined && externalSaleNumber !== null && externalSaleNumber !== '') {
1847
+ return String(externalSaleNumber);
1848
+ }
1849
+ var orderId = order === null || order === void 0 ? void 0 : order.order_id;
1850
+ if (orderId !== undefined && orderId !== null && orderId !== '') {
1851
+ return String(orderId);
1852
+ }
1853
+ return '';
1854
+ }
1855
+ }, {
1856
+ key: "getOrderIdentityMatchKeys",
1857
+ value: function getOrderIdentityMatchKeys(order) {
1858
+ return this.getOrderIdentityEntries(order).map(function (entry) {
1859
+ return "".concat(entry.field, ":").concat(entry.key);
1860
+ });
1861
+ }
1862
+ }, {
1863
+ key: "doOrdersShareIdentity",
1864
+ value: function doOrdersShareIdentity(left, right) {
1865
+ var leftKeys = new Set(this.getOrderIdentityMatchKeys(left));
1866
+ if (leftKeys.size === 0) return false;
1867
+ return this.getOrderIdentityMatchKeys(right).some(function (key) {
1868
+ return leftKeys.has(key);
1869
+ });
1870
+ }
1871
+ }, {
1872
+ key: "findOrderIndexByIdentity",
1873
+ value: function findOrderIndexByIdentity(orders, target) {
1874
+ var _this17 = this;
1875
+ if (this.getOrderIdentityMatchKeys(target).length === 0) return -1;
1876
+ return orders.findIndex(function (order) {
1877
+ return _this17.doOrdersShareIdentity(order, target);
1878
+ });
1879
+ }
1880
+ }, {
1881
+ key: "getOrderCompletenessScore",
1882
+ value: function getOrderCompletenessScore(order) {
1883
+ var record = order;
1884
+ var score = this.isPendingSyncOrder(order) ? 0 : 100;
1885
+ if (!this.isBlankIdentityValue(order.order_id) && order.order_id !== record.external_sale_number) score += 30;
1886
+ score += this.getOrderIdentityMatchKeys(order).length * 5;
1887
+ if (Array.isArray(order.products)) score += Math.min(order.products.length, 10);
1888
+ if (Array.isArray(order.bookings)) score += Math.min(order.bookings.length, 10);
1889
+ if (Array.isArray(order.payments)) score += Math.min(order.payments.length, 10);
1890
+ if (record.updated_at) score += 1;
1891
+ return score;
1892
+ }
1893
+ }, {
1894
+ key: "pickPreferredOrder",
1895
+ value: function pickPreferredOrder(left, right) {
1896
+ var leftScore = this.getOrderCompletenessScore(left);
1897
+ var rightScore = this.getOrderCompletenessScore(right);
1898
+ if (rightScore >= leftScore) return right;
1899
+ return left;
1900
+ }
1901
+ }, {
1902
+ key: "getProductMergeKey",
1903
+ value: function getProductMergeKey(product) {
1904
+ var _record$metadata;
1905
+ var record = product;
1906
+ if (!record) return '';
1907
+ var metadataUid = (_record$metadata = record.metadata) === null || _record$metadata === void 0 ? void 0 : _record$metadata.unique_identification_number;
1908
+ if (!this.isBlankIdentityValue(metadataUid)) return "uid:".concat(String(metadataUid));
1909
+ var topLevelUid = record.unique_identification_number;
1910
+ if (!this.isBlankIdentityValue(topLevelUid)) return "uid:".concat(String(topLevelUid));
1911
+ var orderDetailId = record.order_detail_id;
1912
+ if (!this.isBlankIdentityValue(orderDetailId)) return "detail:".concat(String(orderDetailId));
1913
+ var bookingUid = record.booking_uid;
1914
+ if (!this.isBlankIdentityValue(bookingUid)) return "booking:".concat(String(bookingUid));
1915
+ return '';
1916
+ }
1917
+ }, {
1918
+ key: "mergeOrderProductLists",
1919
+ value: function mergeOrderProductLists(preferred, secondary) {
1920
+ var preferredList = Array.isArray(preferred) ? preferred : [];
1921
+ var secondaryList = Array.isArray(secondary) ? secondary : [];
1922
+ if (secondaryList.length === 0) return preferredList;
1923
+ if (preferredList.length === 0) return secondaryList;
1924
+ var seenKeys = new Set();
1925
+ var _iterator13 = _createForOfIteratorHelper(preferredList),
1926
+ _step13;
1927
+ try {
1928
+ for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
1929
+ var item = _step13.value;
1930
+ var key = this.getProductMergeKey(item);
1931
+ if (key) seenKeys.add(key);
1932
+ }
1933
+ } catch (err) {
1934
+ _iterator13.e(err);
1935
+ } finally {
1936
+ _iterator13.f();
1937
+ }
1938
+ var result = _toConsumableArray(preferredList);
1939
+ var _iterator14 = _createForOfIteratorHelper(secondaryList),
1940
+ _step14;
1941
+ try {
1942
+ for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
1943
+ var _item = _step14.value;
1944
+ var _key = this.getProductMergeKey(_item);
1945
+ if (!_key || seenKeys.has(_key)) continue;
1946
+ seenKeys.add(_key);
1947
+ result.push(cloneDeep(_item));
1948
+ }
1949
+ } catch (err) {
1950
+ _iterator14.e(err);
1951
+ } finally {
1952
+ _iterator14.f();
1953
+ }
1954
+ return result;
1955
+ }
1956
+ }, {
1957
+ key: "mergeOrderRecords",
1958
+ value: function mergeOrderRecords(existing, incoming, options) {
1959
+ var preferred = this.pickPreferredOrder(existing, incoming);
1960
+ var secondary = preferred === existing ? incoming : existing;
1961
+ var merged = _objectSpread(_objectSpread({}, secondary), preferred);
1962
+ var fieldsToPreserve = ['order_id', 'external_sale_number', 'order_number', 'shop_order_number', 'shop_full_order_number'];
1963
+ var incomingPatchFields = ['payment_status', 'status', 'shipping_status', 'updated_at', 'shop_discount', 'summary', 'payments', 'products', 'bookings'];
1964
+ var mergedRecord = merged;
1965
+ var preferredRecord = preferred;
1966
+ var secondaryRecord = secondary;
1967
+ var incomingRecord = incoming;
1968
+ for (var _i3 = 0, _fieldsToPreserve = fieldsToPreserve; _i3 < _fieldsToPreserve.length; _i3++) {
1969
+ var field = _fieldsToPreserve[_i3];
1970
+ if (!this.isBlankIdentityValue(preferredRecord[field])) {
1971
+ mergedRecord[field] = preferredRecord[field];
1972
+ continue;
1973
+ }
1974
+ if (!this.isBlankIdentityValue(secondaryRecord[field])) {
1975
+ mergedRecord[field] = secondaryRecord[field];
1976
+ }
1977
+ }
1978
+ var hasIncomingProducts = Object.prototype.hasOwnProperty.call(incomingRecord, 'products');
1979
+ var shouldUseIncomingProductsSnapshot = (options === null || options === void 0 ? void 0 : options.preferIncomingProducts) === true && hasIncomingProducts && incomingRecord.products !== undefined && incomingRecord.products !== null;
1980
+ for (var _i4 = 0, _incomingPatchFields = incomingPatchFields; _i4 < _incomingPatchFields.length; _i4++) {
1981
+ var _field = _incomingPatchFields[_i4];
1982
+ if (!Object.prototype.hasOwnProperty.call(incomingRecord, _field)) continue;
1983
+ if (incomingRecord[_field] === undefined || incomingRecord[_field] === null) continue;
1984
+ if (typeof incomingRecord[_field] === 'string' && incomingRecord[_field] === '') continue;
1985
+ mergedRecord[_field] = cloneDeep(incomingRecord[_field]);
1986
+ }
1987
+ mergedRecord.products = shouldUseIncomingProductsSnapshot ? cloneDeep(incomingRecord.products) : this.mergeOrderProductLists(preferredRecord.products, secondaryRecord.products);
1988
+ if (!this.isPendingSyncOrder(preferred) || !this.isPendingSyncOrder(secondary)) {
1989
+ merged.need_sync = 0;
1990
+ }
1991
+ return merged;
1992
+ }
1993
+ }, {
1994
+ key: "summarizeDuplicateOrders",
1995
+ value: function summarizeDuplicateOrders(orders) {
1996
+ var groups = new Map();
1997
+ var _iterator15 = _createForOfIteratorHelper(orders),
1998
+ _step15;
1999
+ try {
2000
+ for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
2001
+ var order = _step15.value;
2002
+ var _iterator16 = _createForOfIteratorHelper(this.getOrderIdentityMatchKeys(order)),
2003
+ _step16;
2004
+ try {
2005
+ for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
2006
+ var key = _step16.value;
2007
+ var group = groups.get(key) || [];
2008
+ group.push(order);
2009
+ groups.set(key, group);
2010
+ }
2011
+ } catch (err) {
2012
+ _iterator16.e(err);
2013
+ } finally {
2014
+ _iterator16.f();
2015
+ }
2016
+ }
2017
+ } catch (err) {
2018
+ _iterator15.e(err);
2019
+ } finally {
2020
+ _iterator15.f();
2021
+ }
2022
+ return _toConsumableArray(groups.entries()).filter(function (_ref2) {
2023
+ var _ref3 = _slicedToArray(_ref2, 2),
2024
+ group = _ref3[1];
2025
+ return group.length > 1;
2026
+ }).slice(0, 20).map(function (_ref4) {
2027
+ var _ref5 = _slicedToArray(_ref4, 2),
2028
+ key = _ref5[0],
2029
+ group = _ref5[1];
2030
+ return {
2031
+ key: key,
2032
+ count: group.length,
2033
+ orders: group.map(function (order) {
2034
+ var _order$order_id2, _external_sale_number, _shop_order_number, _shop_full_order_numb, _order$need_sync;
2035
+ return {
2036
+ order_id: (_order$order_id2 = order.order_id) !== null && _order$order_id2 !== void 0 ? _order$order_id2 : null,
2037
+ external_sale_number: (_external_sale_number = order.external_sale_number) !== null && _external_sale_number !== void 0 ? _external_sale_number : null,
2038
+ shop_order_number: (_shop_order_number = order.shop_order_number) !== null && _shop_order_number !== void 0 ? _shop_order_number : null,
2039
+ 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,
2040
+ need_sync: (_order$need_sync = order.need_sync) !== null && _order$need_sync !== void 0 ? _order$need_sync : null
2041
+ };
2042
+ })
2043
+ };
2044
+ });
2045
+ }
2046
+ }, {
2047
+ key: "logDuplicateOrders",
2048
+ value: function logDuplicateOrders(source, orders) {
2049
+ var duplicateGroups = this.summarizeDuplicateOrders(orders);
2050
+ if (duplicateGroups.length === 0) return;
2051
+ this.logWarning('检测到重复订单身份键', {
2052
+ source: source,
2053
+ duplicateGroupCount: duplicateGroups.length,
2054
+ duplicateGroups: duplicateGroups
2055
+ });
2056
+ }
2057
+ }, {
2058
+ key: "compactOrderListByIdentity",
2059
+ value: function compactOrderListByIdentity(orders, source) {
2060
+ var list = [];
2061
+ var removedCount = 0;
2062
+ var _iterator17 = _createForOfIteratorHelper(orders),
2063
+ _step17;
2064
+ try {
2065
+ for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
2066
+ var order = _step17.value;
2067
+ var matchIndex = this.findOrderIndexByIdentity(list, order);
2068
+ if (matchIndex < 0) {
2069
+ list.push(order);
2070
+ continue;
2071
+ }
2072
+ list[matchIndex] = this.mergeOrderRecords(list[matchIndex], order);
2073
+ removedCount += 1;
2074
+ }
2075
+ } catch (err) {
2076
+ _iterator17.e(err);
2077
+ } finally {
2078
+ _iterator17.f();
2079
+ }
2080
+ if (removedCount > 0) {
2081
+ this.logWarning('订单列表重复项已压缩', {
2082
+ source: source,
2083
+ beforeCount: orders.length,
2084
+ afterCount: list.length,
2085
+ removedCount: removedCount
2086
+ });
2087
+ } else {
2088
+ this.logDuplicateOrders(source, orders);
2089
+ }
2090
+ return {
2091
+ list: list,
2092
+ removedCount: removedCount
2093
+ };
2094
+ }
1178
2095
 
1179
2096
  /**
1180
2097
  * 当前订单拉取窗口:
@@ -1232,7 +2149,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1232
2149
  if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
1233
2150
  return globalThis.localStorage.getItem(key);
1234
2151
  }
1235
- } catch (_unused5) {
2152
+ } catch (_unused6) {
1236
2153
  // 忽略存储异常,避免影响主流程
1237
2154
  }
1238
2155
  return null;
@@ -1249,39 +2166,39 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1249
2166
  if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
1250
2167
  globalThis.localStorage.setItem(key, value);
1251
2168
  }
1252
- } catch (_unused6) {
2169
+ } catch (_unused7) {
1253
2170
  // 忽略存储异常,避免影响主流程
1254
2171
  }
1255
2172
  }
1256
2173
  }, {
1257
2174
  key: "loadOrdersFromSQLite",
1258
2175
  value: function () {
1259
- var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
2176
+ var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17() {
1260
2177
  var orders;
1261
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1262
- while (1) switch (_context14.prev = _context14.next) {
2178
+ return _regeneratorRuntime().wrap(function _callee17$(_context17) {
2179
+ while (1) switch (_context17.prev = _context17.next) {
1263
2180
  case 0:
1264
2181
  if (this.dbManager) {
1265
- _context14.next = 2;
2182
+ _context17.next = 2;
1266
2183
  break;
1267
2184
  }
1268
- return _context14.abrupt("return", []);
2185
+ return _context17.abrupt("return", []);
1269
2186
  case 2:
1270
- _context14.prev = 2;
1271
- _context14.next = 5;
2187
+ _context17.prev = 2;
2188
+ _context17.next = 5;
1272
2189
  return this.dbManager.getAll(INDEXDB_STORE_NAME);
1273
2190
  case 5:
1274
- orders = _context14.sent;
1275
- return _context14.abrupt("return", orders || []);
2191
+ orders = _context17.sent;
2192
+ return _context17.abrupt("return", orders || []);
1276
2193
  case 9:
1277
- _context14.prev = 9;
1278
- _context14.t0 = _context14["catch"](2);
1279
- return _context14.abrupt("return", []);
2194
+ _context17.prev = 9;
2195
+ _context17.t0 = _context17["catch"](2);
2196
+ return _context17.abrupt("return", []);
1280
2197
  case 12:
1281
2198
  case "end":
1282
- return _context14.stop();
2199
+ return _context17.stop();
1283
2200
  }
1284
- }, _callee14, this, [[2, 9]]);
2201
+ }, _callee17, this, [[2, 9]]);
1285
2202
  }));
1286
2203
  function loadOrdersFromSQLite() {
1287
2204
  return _loadOrdersFromSQLite.apply(this, arguments);
@@ -1289,91 +2206,488 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1289
2206
  return loadOrdersFromSQLite;
1290
2207
  }()
1291
2208
  }, {
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) {
2209
+ key: "isPendingSyncOrder",
2210
+ value: function isPendingSyncOrder(order) {
2211
+ return Number(order === null || order === void 0 ? void 0 : order.need_sync) === 1;
2212
+ }
2213
+ }, {
2214
+ key: "normalizeRemoteSyncedOrder",
2215
+ value: function normalizeRemoteSyncedOrder(order) {
2216
+ if (this.isPendingSyncOrder(order)) return order;
2217
+ return _objectSpread(_objectSpread({}, order), {}, {
2218
+ need_sync: 0
2219
+ });
2220
+ }
2221
+ }, {
2222
+ key: "mergeRemoteSnapshotWithPendingOrders",
2223
+ value: function mergeRemoteSnapshotWithPendingOrders(remoteOrders, existingOrders) {
2224
+ var _this18 = this;
2225
+ var merged = remoteOrders.map(function (order) {
2226
+ return _this18.normalizeRemoteSyncedOrder(order);
2227
+ });
2228
+ var _iterator18 = _createForOfIteratorHelper(existingOrders),
2229
+ _step18;
2230
+ try {
2231
+ for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
2232
+ var order = _step18.value;
2233
+ if (!this.isPendingSyncOrder(order)) continue;
2234
+ var matchIndex = this.findOrderIndexByIdentity(merged, order);
2235
+ if (matchIndex >= 0) {
2236
+ merged[matchIndex] = this.mergeOrderRecords(order, merged[matchIndex]);
2237
+ continue;
2238
+ }
2239
+ if (!this.getOrderStorageKey(order)) continue;
2240
+ merged.push(order);
2241
+ }
2242
+ } catch (err) {
2243
+ _iterator18.e(err);
2244
+ } finally {
2245
+ _iterator18.f();
2246
+ }
2247
+ return this.compactOrderListByIdentity(merged, 'mergeRemoteSnapshotWithPendingOrders').list;
2248
+ }
2249
+
2250
+ /**
2251
+ * 串行执行订单 SQLite 写入任务,避免快照替换与增量 upsert 并发交错。
2252
+ *
2253
+ * @example
2254
+ * await this.runInOrderSQLiteSaveQueue(async () => {
2255
+ * await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, orders)
2256
+ * })
2257
+ */
2258
+ }, {
2259
+ key: "runInOrderSQLiteSaveQueue",
2260
+ value: (function () {
2261
+ var _runInOrderSQLiteSaveQueue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(task) {
2262
+ var queuedTask;
2263
+ return _regeneratorRuntime().wrap(function _callee18$(_context18) {
2264
+ while (1) switch (_context18.prev = _context18.next) {
1297
2265
  case 0:
1298
- if (this.dbManager) {
1299
- _context15.next = 2;
2266
+ queuedTask = this.orderSQLiteSaveQueue.then(task, task);
2267
+ this.orderSQLiteSaveQueue = queuedTask.then(function () {
2268
+ return undefined;
2269
+ }, function () {
2270
+ return undefined;
2271
+ });
2272
+ return _context18.abrupt("return", queuedTask);
2273
+ case 3:
2274
+ case "end":
2275
+ return _context18.stop();
2276
+ }
2277
+ }, _callee18, this);
2278
+ }));
2279
+ function runInOrderSQLiteSaveQueue(_x11) {
2280
+ return _runInOrderSQLiteSaveQueue.apply(this, arguments);
2281
+ }
2282
+ return runInOrderSQLiteSaveQueue;
2283
+ }()
2284
+ /**
2285
+ * 批量增量 upsert 订单到 SQLite,不清空表;用于 pubsub / HTTP 增量合并。
2286
+ *
2287
+ * @example
2288
+ * await this.patchOrdersInSQLite(freshOrders)
2289
+ */
2290
+ )
2291
+ }, {
2292
+ key: "patchOrdersInSQLite",
2293
+ value: (function () {
2294
+ var _patchOrdersInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(orders, source) {
2295
+ var _this19 = this;
2296
+ var mergeActions,
2297
+ ordersSnapshot,
2298
+ _this$filterRedundant2,
2299
+ toWrite,
2300
+ skipped,
2301
+ compactedToWrite,
2302
+ _args20 = arguments;
2303
+ return _regeneratorRuntime().wrap(function _callee20$(_context20) {
2304
+ while (1) switch (_context20.prev = _context20.next) {
2305
+ case 0:
2306
+ mergeActions = _args20.length > 2 && _args20[2] !== undefined ? _args20[2] : {};
2307
+ if (!(!this.dbManager || orders.length === 0)) {
2308
+ _context20.next = 3;
1300
2309
  break;
1301
2310
  }
1302
- return _context15.abrupt("return");
1303
- case 2:
1304
- _context15.prev = 2;
1305
- this.logInfo('saveOrdersToSQLite-开始', {
1306
- count: orderList.length
2311
+ return _context20.abrupt("return");
2312
+ case 3:
2313
+ ordersSnapshot = cloneDeep(orders).filter(function (order) {
2314
+ return _this19.getOrderStorageKey(order);
1307
2315
  });
1308
- _context15.next = 6;
1309
- return this.dbManager.clear(INDEXDB_STORE_NAME);
2316
+ if (!(ordersSnapshot.length === 0)) {
2317
+ _context20.next = 6;
2318
+ break;
2319
+ }
2320
+ return _context20.abrupt("return");
1310
2321
  case 6:
1311
- this.logInfo('saveOrdersToSQLite-clear完成', {
1312
- count: orderList.length
1313
- });
1314
- if (!(orderList.length === 0)) {
1315
- _context15.next = 9;
2322
+ _this$filterRedundant2 = this.filterRedundantPatchOrders(source, ordersSnapshot, mergeActions), toWrite = _this$filterRedundant2.toWrite, skipped = _this$filterRedundant2.skipped;
2323
+ if (!(toWrite.length === 0)) {
2324
+ _context20.next = 9;
1316
2325
  break;
1317
2326
  }
1318
- return _context15.abrupt("return");
2327
+ return _context20.abrupt("return");
1319
2328
  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
2329
+ compactedToWrite = this.compactOrderListByIdentity(toWrite, "".concat(source, ".sqlitePatch")).list;
2330
+ if (!(compactedToWrite.length === 0)) {
2331
+ _context20.next = 12;
2332
+ break;
2333
+ }
2334
+ return _context20.abrupt("return");
2335
+ case 12:
2336
+ _context20.prev = 12;
2337
+ _context20.next = 15;
2338
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19() {
2339
+ var writeMethod, _iterator19, _step19, order;
2340
+ return _regeneratorRuntime().wrap(function _callee19$(_context19) {
2341
+ while (1) switch (_context19.prev = _context19.next) {
2342
+ case 0:
2343
+ writeMethod = 'none';
2344
+ _this19.logInfo('patchOrdersInSQLite-开始', {
2345
+ source: source,
2346
+ count: compactedToWrite.length,
2347
+ dedupedCount: skipped.length
2348
+ });
2349
+ if (!(typeof _this19.dbManager.bulkUpdate === 'function')) {
2350
+ _context19.next = 8;
2351
+ break;
2352
+ }
2353
+ writeMethod = 'bulkUpdate';
2354
+ _context19.next = 6;
2355
+ return _this19.dbManager.bulkUpdate(INDEXDB_STORE_NAME, compactedToWrite);
2356
+ case 6:
2357
+ _context19.next = 33;
2358
+ break;
2359
+ case 8:
2360
+ if (!(typeof _this19.dbManager.bulkAdd === 'function')) {
2361
+ _context19.next = 14;
2362
+ break;
2363
+ }
2364
+ writeMethod = 'bulkAdd';
2365
+ _context19.next = 12;
2366
+ return _this19.dbManager.bulkAdd(INDEXDB_STORE_NAME, compactedToWrite);
2367
+ case 12:
2368
+ _context19.next = 33;
2369
+ break;
2370
+ case 14:
2371
+ if (!(typeof _this19.dbManager.update === 'function')) {
2372
+ _context19.next = 33;
2373
+ break;
2374
+ }
2375
+ writeMethod = 'update';
2376
+ _iterator19 = _createForOfIteratorHelper(compactedToWrite);
2377
+ _context19.prev = 17;
2378
+ _iterator19.s();
2379
+ case 19:
2380
+ if ((_step19 = _iterator19.n()).done) {
2381
+ _context19.next = 25;
2382
+ break;
2383
+ }
2384
+ order = _step19.value;
2385
+ _context19.next = 23;
2386
+ return _this19.dbManager.update(INDEXDB_STORE_NAME, order);
2387
+ case 23:
2388
+ _context19.next = 19;
2389
+ break;
2390
+ case 25:
2391
+ _context19.next = 30;
2392
+ break;
2393
+ case 27:
2394
+ _context19.prev = 27;
2395
+ _context19.t0 = _context19["catch"](17);
2396
+ _iterator19.e(_context19.t0);
2397
+ case 30:
2398
+ _context19.prev = 30;
2399
+ _iterator19.f();
2400
+ return _context19.finish(30);
2401
+ case 33:
2402
+ _this19.recordRecentSqliteWrite(source, compactedToWrite);
2403
+ _this19.logInfo('patchOrdersInSQLite-完成', {
2404
+ source: source,
2405
+ count: compactedToWrite.length,
2406
+ writeMethod: writeMethod,
2407
+ dedupedCount: skipped.length
2408
+ });
2409
+ case 35:
2410
+ case "end":
2411
+ return _context19.stop();
2412
+ }
2413
+ }, _callee19, null, [[17, 27, 30, 33]]);
2414
+ })));
2415
+ case 15:
2416
+ _context20.next = 20;
2417
+ break;
2418
+ case 17:
2419
+ _context20.prev = 17;
2420
+ _context20.t0 = _context20["catch"](12);
2421
+ this.logError('增量保存订单到 SQLite 失败', {
2422
+ error: _context20.t0 instanceof Error ? _context20.t0.message : String(_context20.t0),
2423
+ orderCount: ordersSnapshot.length
2424
+ });
2425
+ case 20:
2426
+ case "end":
2427
+ return _context20.stop();
2428
+ }
2429
+ }, _callee20, this, [[12, 17]]);
2430
+ }));
2431
+ function patchOrdersInSQLite(_x12, _x13) {
2432
+ return _patchOrdersInSQLite.apply(this, arguments);
2433
+ }
2434
+ return patchOrdersInSQLite;
2435
+ }()
2436
+ /**
2437
+ * 单条 upsert 订单到 SQLite;用于 overwriteExistingOrder 等单条覆盖场景。
2438
+ *
2439
+ * @example
2440
+ * await this.updateOrderInSQLite(freshOrder)
2441
+ */
2442
+ )
2443
+ }, {
2444
+ key: "updateOrderInSQLite",
2445
+ value: (function () {
2446
+ var _updateOrderInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(order, source) {
2447
+ var _this20 = this;
2448
+ var orderSnapshot, _orderSnapshot$order_3;
2449
+ return _regeneratorRuntime().wrap(function _callee22$(_context22) {
2450
+ while (1) switch (_context22.prev = _context22.next) {
2451
+ case 0:
2452
+ if (!(!this.dbManager || !this.getOrderStorageKey(order))) {
2453
+ _context22.next = 2;
2454
+ break;
2455
+ }
2456
+ return _context22.abrupt("return");
2457
+ case 2:
2458
+ orderSnapshot = cloneDeep(order);
2459
+ _context22.prev = 3;
2460
+ _context22.next = 6;
2461
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21() {
2462
+ var _orderSnapshot$order_, _orderSnapshot$order_2;
2463
+ var writeMethod;
2464
+ return _regeneratorRuntime().wrap(function _callee21$(_context21) {
2465
+ while (1) switch (_context21.prev = _context21.next) {
2466
+ case 0:
2467
+ writeMethod = 'none';
2468
+ _this20.logInfo('updateOrderInSQLite-开始', {
2469
+ source: source,
2470
+ orderId: (_orderSnapshot$order_ = orderSnapshot.order_id) !== null && _orderSnapshot$order_ !== void 0 ? _orderSnapshot$order_ : null,
2471
+ storageKey: _this20.getOrderStorageKey(orderSnapshot)
2472
+ });
2473
+ if (!(typeof _this20.dbManager.update === 'function')) {
2474
+ _context21.next = 8;
2475
+ break;
2476
+ }
2477
+ writeMethod = 'update';
2478
+ _context21.next = 6;
2479
+ return _this20.dbManager.update(INDEXDB_STORE_NAME, orderSnapshot);
2480
+ case 6:
2481
+ _context21.next = 18;
2482
+ break;
2483
+ case 8:
2484
+ if (!(typeof _this20.dbManager.bulkUpdate === 'function')) {
2485
+ _context21.next = 14;
2486
+ break;
2487
+ }
2488
+ writeMethod = 'bulkUpdate';
2489
+ _context21.next = 12;
2490
+ return _this20.dbManager.bulkUpdate(INDEXDB_STORE_NAME, [orderSnapshot]);
2491
+ case 12:
2492
+ _context21.next = 18;
2493
+ break;
2494
+ case 14:
2495
+ if (!(typeof _this20.dbManager.bulkAdd === 'function')) {
2496
+ _context21.next = 18;
2497
+ break;
2498
+ }
2499
+ writeMethod = 'bulkAdd';
2500
+ _context21.next = 18;
2501
+ return _this20.dbManager.bulkAdd(INDEXDB_STORE_NAME, [orderSnapshot]);
2502
+ case 18:
2503
+ _this20.recordRecentSqliteWrite(source, [orderSnapshot]);
2504
+ _this20.logInfo('updateOrderInSQLite-完成', {
2505
+ source: source,
2506
+ orderId: (_orderSnapshot$order_2 = orderSnapshot.order_id) !== null && _orderSnapshot$order_2 !== void 0 ? _orderSnapshot$order_2 : null,
2507
+ writeMethod: writeMethod
2508
+ });
2509
+ case 20:
2510
+ case "end":
2511
+ return _context21.stop();
2512
+ }
2513
+ }, _callee21);
2514
+ })));
2515
+ case 6:
2516
+ _context22.next = 11;
2517
+ break;
2518
+ case 8:
2519
+ _context22.prev = 8;
2520
+ _context22.t0 = _context22["catch"](3);
2521
+ this.logError('单条保存订单到 SQLite 失败', {
2522
+ error: _context22.t0 instanceof Error ? _context22.t0.message : String(_context22.t0),
2523
+ orderId: (_orderSnapshot$order_3 = orderSnapshot.order_id) !== null && _orderSnapshot$order_3 !== void 0 ? _orderSnapshot$order_3 : null
1325
2524
  });
1326
- _context15.next = 17;
2525
+ case 11:
2526
+ case "end":
2527
+ return _context22.stop();
2528
+ }
2529
+ }, _callee22, this, [[3, 8]]);
2530
+ }));
2531
+ function updateOrderInSQLite(_x14, _x15) {
2532
+ return _updateOrderInSQLite.apply(this, arguments);
2533
+ }
2534
+ return updateOrderInSQLite;
2535
+ }()
2536
+ /**
2537
+ * 全量快照替换 orders 表(clear + bulkAdd),用于 SSE 全量拉取与营业日窗口裁剪。
2538
+ *
2539
+ * @example
2540
+ * await this.replaceOrdersSnapshotInSQLite(orderList)
2541
+ */
2542
+ )
2543
+ }, {
2544
+ key: "replaceOrdersSnapshotInSQLite",
2545
+ value: (function () {
2546
+ var _replaceOrdersSnapshotInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(orderList, source) {
2547
+ var _this21 = this;
2548
+ var remoteSnapshot, mergedSnapshot;
2549
+ return _regeneratorRuntime().wrap(function _callee24$(_context24) {
2550
+ while (1) switch (_context24.prev = _context24.next) {
2551
+ case 0:
2552
+ if (this.dbManager) {
2553
+ _context24.next = 2;
2554
+ break;
2555
+ }
2556
+ return _context24.abrupt("return", this.compactOrderListByIdentity(orderList.map(function (order) {
2557
+ return _this21.normalizeRemoteSyncedOrder(order);
2558
+ }), "".concat(source, ".snapshotNoDb")).list);
2559
+ case 2:
2560
+ remoteSnapshot = cloneDeep(orderList);
2561
+ mergedSnapshot = this.compactOrderListByIdentity(remoteSnapshot.map(function (order) {
2562
+ return _this21.normalizeRemoteSyncedOrder(order);
2563
+ }), "".concat(source, ".remoteSnapshot")).list;
2564
+ _context24.prev = 4;
2565
+ _context24.next = 7;
2566
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23() {
2567
+ var existingOrders, orderListSnapshot;
2568
+ return _regeneratorRuntime().wrap(function _callee23$(_context23) {
2569
+ while (1) switch (_context23.prev = _context23.next) {
2570
+ case 0:
2571
+ if (!(typeof _this21.dbManager.getAll === 'function')) {
2572
+ _context23.next = 6;
2573
+ break;
2574
+ }
2575
+ _context23.next = 3;
2576
+ return _this21.dbManager.getAll(INDEXDB_STORE_NAME);
2577
+ case 3:
2578
+ _context23.t0 = _context23.sent;
2579
+ _context23.next = 7;
2580
+ break;
2581
+ case 6:
2582
+ _context23.t0 = [];
2583
+ case 7:
2584
+ existingOrders = _context23.t0;
2585
+ orderListSnapshot = _this21.mergeRemoteSnapshotWithPendingOrders(remoteSnapshot, existingOrders || []);
2586
+ mergedSnapshot = _this21.compactOrderListByIdentity(orderListSnapshot, "".concat(source, ".sqliteSnapshot")).list;
2587
+ _this21.logInfo('replaceOrdersSnapshotInSQLite-开始', {
2588
+ source: source,
2589
+ count: mergedSnapshot.length,
2590
+ remoteCount: remoteSnapshot.length,
2591
+ preservedPendingCount: mergedSnapshot.length - remoteSnapshot.length
2592
+ });
2593
+ _context23.next = 13;
2594
+ return _this21.dbManager.clear(INDEXDB_STORE_NAME);
2595
+ case 13:
2596
+ _this21.logInfo('replaceOrdersSnapshotInSQLite-clear完成', {
2597
+ count: mergedSnapshot.length
2598
+ });
2599
+ if (!(mergedSnapshot.length === 0)) {
2600
+ _context23.next = 16;
2601
+ break;
2602
+ }
2603
+ return _context23.abrupt("return");
2604
+ case 16:
2605
+ _context23.next = 18;
2606
+ return _this21.dbManager.bulkAdd(INDEXDB_STORE_NAME, mergedSnapshot);
2607
+ case 18:
2608
+ _this21.recordRecentSqliteWrite(source, mergedSnapshot);
2609
+ _this21.logInfo('replaceOrdersSnapshotInSQLite-bulkAdd完成', {
2610
+ source: source,
2611
+ count: mergedSnapshot.length
2612
+ });
2613
+ case 20:
2614
+ case "end":
2615
+ return _context23.stop();
2616
+ }
2617
+ }, _callee23);
2618
+ })));
2619
+ case 7:
2620
+ _context24.next = 12;
1327
2621
  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
2622
+ case 9:
2623
+ _context24.prev = 9;
2624
+ _context24.t0 = _context24["catch"](4);
2625
+ this.logError('全量保存订单到 SQLite 失败', {
2626
+ error: _context24.t0 instanceof Error ? _context24.t0.message : String(_context24.t0),
2627
+ orderList: remoteSnapshot.length
1335
2628
  });
1336
- case 17:
2629
+ case 12:
2630
+ return _context24.abrupt("return", mergedSnapshot);
2631
+ case 13:
1337
2632
  case "end":
1338
- return _context15.stop();
2633
+ return _context24.stop();
1339
2634
  }
1340
- }, _callee15, this, [[2, 14]]);
2635
+ }, _callee24, this, [[4, 9]]);
1341
2636
  }));
1342
- function saveOrdersToSQLite(_x8) {
1343
- return _saveOrdersToSQLite.apply(this, arguments);
2637
+ function replaceOrdersSnapshotInSQLite(_x16, _x17) {
2638
+ return _replaceOrdersSnapshotInSQLite.apply(this, arguments);
1344
2639
  }
1345
- return saveOrdersToSQLite;
2640
+ return replaceOrdersSnapshotInSQLite;
1346
2641
  }()
2642
+ /**
2643
+ * 清空订单模块的内存数据和本地 SQLite 订单表。
2644
+ *
2645
+ * @example
2646
+ * await orderModule.clear()
2647
+ */
2648
+ )
1347
2649
  }, {
1348
2650
  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) {
2651
+ value: (function () {
2652
+ var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26() {
2653
+ var _this22 = this;
2654
+ return _regeneratorRuntime().wrap(function _callee26$(_context26) {
2655
+ while (1) switch (_context26.prev = _context26.next) {
1353
2656
  case 0:
1354
2657
  this.store.list = [];
1355
2658
  this.store.map = new Map();
1356
2659
  this.resourceIdIndex.clear();
1357
2660
  if (!this.dbManager) {
1358
- _context16.next = 6;
2661
+ _context26.next = 6;
1359
2662
  break;
1360
2663
  }
1361
- _context16.next = 6;
1362
- return this.dbManager.clear(INDEXDB_STORE_NAME);
2664
+ _context26.next = 6;
2665
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25() {
2666
+ return _regeneratorRuntime().wrap(function _callee25$(_context25) {
2667
+ while (1) switch (_context25.prev = _context25.next) {
2668
+ case 0:
2669
+ _context25.next = 2;
2670
+ return _this22.dbManager.clear(INDEXDB_STORE_NAME);
2671
+ case 2:
2672
+ case "end":
2673
+ return _context25.stop();
2674
+ }
2675
+ }, _callee25);
2676
+ })));
1363
2677
  case 6:
1364
2678
  this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, '');
1365
- this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
2679
+ this.emitOrdersChanged([], 'clear');
1366
2680
  case 8:
1367
2681
  case "end":
1368
- return _context16.stop();
2682
+ return _context26.stop();
1369
2683
  }
1370
- }, _callee16, this);
2684
+ }, _callee26, this);
1371
2685
  }));
1372
2686
  function clear() {
1373
2687
  return _clear.apply(this, arguments);
1374
2688
  }
1375
2689
  return clear;
1376
- }()
2690
+ }())
1377
2691
  }]);
1378
2692
  return OrderModule;
1379
2693
  }(BaseModule);