@pisell/pisellos 2.3.39 → 2.3.41

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 (226) hide show
  1. package/dist/core/index.d.ts +2 -0
  2. package/dist/core/index.js +7 -0
  3. package/dist/model/strategy/adapter/promotion/adapter.d.ts +4 -0
  4. package/dist/model/strategy/adapter/promotion/adapter.js +23 -0
  5. package/dist/model/strategy/adapter/promotion/evaluator.d.ts +17 -0
  6. package/dist/model/strategy/adapter/promotion/evaluator.js +279 -6
  7. package/dist/model/strategy/adapter/promotion/examples.d.ts +86 -0
  8. package/dist/model/strategy/adapter/promotion/examples.js +99 -0
  9. package/dist/model/strategy/adapter/promotion/index.d.ts +1 -1
  10. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  11. package/dist/model/strategy/adapter/promotion/type.d.ts +90 -2
  12. package/dist/model/strategy/adapter/promotion/type.js +45 -0
  13. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +5 -3
  14. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +6 -3
  15. package/dist/modules/Discount/index.d.ts +0 -1
  16. package/dist/modules/Discount/index.js +11 -40
  17. package/dist/modules/Discount/types.d.ts +0 -1
  18. package/dist/modules/OpenData/index.d.ts +2 -0
  19. package/dist/modules/OpenData/index.js +10 -2
  20. package/dist/modules/Order/index.d.ts +29 -12
  21. package/dist/modules/Order/index.js +750 -509
  22. package/dist/modules/Order/payment-utils.d.ts +26 -0
  23. package/dist/modules/Order/payment-utils.js +225 -0
  24. package/dist/modules/Order/types.d.ts +33 -10
  25. package/dist/modules/Order/utils/orderCollectionIdentity.js +7 -2
  26. package/dist/modules/Order/utils.d.ts +0 -10
  27. package/dist/modules/Order/utils.js +13 -41
  28. package/dist/modules/Payment/index.d.ts +2 -0
  29. package/dist/modules/Payment/index.js +79 -50
  30. package/dist/modules/Payment/types.d.ts +99 -28
  31. package/dist/modules/Payment/types.js +20 -3
  32. package/dist/modules/Payment/walletpass.d.ts +25 -1
  33. package/dist/modules/Payment/walletpass.js +707 -157
  34. package/dist/modules/Product/types.d.ts +0 -1
  35. package/dist/modules/ProductList/index.js +14 -33
  36. package/dist/modules/Quotation/index.d.ts +1 -1
  37. package/dist/modules/Quotation/index.js +2 -2
  38. package/dist/modules/Rules/index.d.ts +1 -0
  39. package/dist/modules/Rules/index.js +89 -96
  40. package/dist/modules/SalesSummary/index.js +13 -12
  41. package/dist/modules/ScanOrderLogger/index.d.ts +0 -2
  42. package/dist/modules/ScanOrderLogger/index.js +2 -15
  43. package/dist/modules/ScanOrderLogger/providers/feishu.js +27 -45
  44. package/dist/modules/ScanOrderLogger/types.d.ts +0 -1
  45. package/dist/modules/Schedule/index.d.ts +1 -3
  46. package/dist/modules/Schedule/index.js +16 -21
  47. package/dist/modules/Summary/utils.js +13 -38
  48. package/dist/modules/index.d.ts +0 -2
  49. package/dist/modules/index.js +1 -3
  50. package/dist/plugins/window.d.ts +0 -1
  51. package/dist/server/index.d.ts +16 -14
  52. package/dist/server/index.js +1925 -1143
  53. package/dist/server/modules/order/index.d.ts +54 -4
  54. package/dist/server/modules/order/index.js +1600 -700
  55. package/dist/server/modules/order/types.d.ts +11 -3
  56. package/dist/server/modules/order/types.js +1 -1
  57. package/dist/solution/BaseSales/index.d.ts +109 -20
  58. package/dist/solution/BaseSales/index.js +1800 -480
  59. package/dist/solution/BaseSales/types.d.ts +52 -0
  60. package/dist/solution/BaseSales/types.js +2 -1
  61. package/dist/solution/BaseSales/utils/cartPromotion.d.ts +3 -1
  62. package/dist/solution/BaseSales/utils/cartPromotion.js +90 -31
  63. package/dist/solution/BaseSales/utils/parseSalesResponse.d.ts +6 -1
  64. package/dist/solution/BookingByStep/index.d.ts +2 -17
  65. package/dist/solution/BookingByStep/index.js +215 -294
  66. package/dist/solution/BookingByStep/types.d.ts +1 -2
  67. package/dist/solution/BookingByStep/types.js +1 -3
  68. package/dist/solution/BookingByStep/utils/capacity.js +1 -17
  69. package/dist/solution/BookingByStep/utils/timeslots.d.ts +1 -3
  70. package/dist/solution/BookingByStep/utils/timeslots.js +12 -19
  71. package/dist/solution/BookingTicket/index.d.ts +7 -3
  72. package/dist/solution/BookingTicket/index.js +132 -49
  73. package/dist/solution/BookingTicket/utils/addProductDecision.js +6 -0
  74. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +8 -0
  75. package/dist/solution/BookingTicket/utils/scan/applyGlobalScan.js +172 -82
  76. package/dist/solution/BookingTicket/utils/weighingProductSku.d.ts +5 -0
  77. package/dist/solution/BookingTicket/utils/weighingProductSku.js +45 -0
  78. package/dist/solution/Sales/index.d.ts +1 -0
  79. package/dist/solution/Sales/index.js +10 -2
  80. package/dist/solution/ScanOrder/index.d.ts +14 -26
  81. package/dist/solution/ScanOrder/index.js +756 -1148
  82. package/dist/solution/ScanOrder/types.d.ts +1 -21
  83. package/dist/solution/ScanOrder/utils.d.ts +0 -8
  84. package/dist/solution/ScanOrder/utils.js +25 -66
  85. package/dist/solution/ShopDiscount/index.d.ts +0 -1
  86. package/dist/solution/ShopDiscount/index.js +87 -125
  87. package/dist/solution/VenueBooking/index.d.ts +11 -39
  88. package/dist/solution/VenueBooking/index.js +860 -1176
  89. package/dist/solution/VenueBooking/types.d.ts +0 -3
  90. package/dist/solution/VenueBooking/utils/resource.js +0 -1
  91. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +4 -4
  92. package/dist/solution/VenueBooking/utils/slotMerge.js +5 -10
  93. package/dist/solution/index.d.ts +0 -1
  94. package/dist/solution/index.js +1 -2
  95. package/dist/types/index.d.ts +1 -1
  96. package/dist/utils/payment-number.d.ts +9 -0
  97. package/dist/utils/payment-number.js +69 -0
  98. package/lib/core/index.d.ts +2 -0
  99. package/lib/core/index.js +4 -0
  100. package/lib/model/strategy/adapter/promotion/adapter.d.ts +4 -0
  101. package/lib/model/strategy/adapter/promotion/adapter.js +20 -0
  102. package/lib/model/strategy/adapter/promotion/evaluator.d.ts +17 -0
  103. package/lib/model/strategy/adapter/promotion/evaluator.js +235 -0
  104. package/lib/model/strategy/adapter/promotion/examples.d.ts +86 -0
  105. package/lib/model/strategy/adapter/promotion/examples.js +91 -0
  106. package/lib/model/strategy/adapter/promotion/index.d.ts +1 -1
  107. package/lib/model/strategy/adapter/promotion/index.js +51 -0
  108. package/lib/model/strategy/adapter/promotion/type.d.ts +90 -2
  109. package/lib/model/strategy/adapter/promotion/type.js +2 -0
  110. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +2 -1
  111. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +2 -1
  112. package/lib/modules/Discount/index.d.ts +0 -1
  113. package/lib/modules/Discount/index.js +0 -9
  114. package/lib/modules/Discount/types.d.ts +0 -1
  115. package/lib/modules/OpenData/index.d.ts +2 -0
  116. package/lib/modules/OpenData/index.js +6 -1
  117. package/lib/modules/Order/index.d.ts +29 -12
  118. package/lib/modules/Order/index.js +196 -86
  119. package/lib/modules/Order/payment-utils.d.ts +26 -0
  120. package/lib/modules/Order/payment-utils.js +224 -0
  121. package/lib/modules/Order/types.d.ts +33 -10
  122. package/lib/modules/Order/utils/orderCollectionIdentity.js +3 -0
  123. package/lib/modules/Order/utils.d.ts +0 -10
  124. package/lib/modules/Order/utils.js +16 -40
  125. package/lib/modules/Payment/index.d.ts +2 -0
  126. package/lib/modules/Payment/index.js +34 -13
  127. package/lib/modules/Payment/types.d.ts +99 -28
  128. package/lib/modules/Payment/types.js +4 -3
  129. package/lib/modules/Payment/walletpass.d.ts +25 -1
  130. package/lib/modules/Payment/walletpass.js +470 -21
  131. package/lib/modules/Product/types.d.ts +0 -1
  132. package/lib/modules/ProductList/index.js +31 -40
  133. package/lib/modules/Quotation/index.d.ts +1 -1
  134. package/lib/modules/Quotation/index.js +2 -2
  135. package/lib/modules/Rules/index.d.ts +1 -0
  136. package/lib/modules/Rules/index.js +47 -40
  137. package/lib/modules/SalesSummary/index.js +7 -6
  138. package/lib/modules/ScanOrderLogger/index.d.ts +0 -2
  139. package/lib/modules/ScanOrderLogger/index.js +1 -13
  140. package/lib/modules/ScanOrderLogger/providers/feishu.js +6 -15
  141. package/lib/modules/ScanOrderLogger/types.d.ts +0 -1
  142. package/lib/modules/Schedule/index.d.ts +1 -3
  143. package/lib/modules/Schedule/index.js +8 -10
  144. package/lib/modules/Summary/utils.js +1 -21
  145. package/lib/modules/index.d.ts +0 -2
  146. package/lib/modules/index.js +1 -5
  147. package/lib/plugins/window.d.ts +0 -1
  148. package/lib/server/index.d.ts +16 -14
  149. package/lib/server/index.js +675 -83
  150. package/lib/server/modules/order/index.d.ts +54 -4
  151. package/lib/server/modules/order/index.js +679 -66
  152. package/lib/server/modules/order/types.d.ts +11 -3
  153. package/lib/solution/BaseSales/index.d.ts +109 -20
  154. package/lib/solution/BaseSales/index.js +883 -70
  155. package/lib/solution/BaseSales/types.d.ts +52 -0
  156. package/lib/solution/BaseSales/types.js +2 -1
  157. package/lib/solution/BaseSales/utils/cartPromotion.d.ts +3 -1
  158. package/lib/solution/BaseSales/utils/cartPromotion.js +63 -12
  159. package/lib/solution/BaseSales/utils/parseSalesResponse.d.ts +6 -1
  160. package/lib/solution/BookingByStep/index.d.ts +2 -17
  161. package/lib/solution/BookingByStep/index.js +18 -60
  162. package/lib/solution/BookingByStep/types.d.ts +1 -2
  163. package/lib/solution/BookingByStep/types.js +0 -5
  164. package/lib/solution/BookingByStep/utils/capacity.js +1 -20
  165. package/lib/solution/BookingByStep/utils/timeslots.d.ts +1 -3
  166. package/lib/solution/BookingByStep/utils/timeslots.js +11 -19
  167. package/lib/solution/BookingTicket/index.d.ts +7 -3
  168. package/lib/solution/BookingTicket/index.js +62 -9
  169. package/lib/solution/BookingTicket/utils/addProductDecision.js +4 -0
  170. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.d.ts +8 -0
  171. package/lib/solution/BookingTicket/utils/scan/applyGlobalScan.js +36 -4
  172. package/lib/solution/BookingTicket/utils/weighingProductSku.d.ts +5 -0
  173. package/lib/solution/BookingTicket/utils/weighingProductSku.js +63 -0
  174. package/lib/solution/Sales/index.d.ts +1 -0
  175. package/lib/solution/Sales/index.js +5 -3
  176. package/lib/solution/ScanOrder/index.d.ts +14 -26
  177. package/lib/solution/ScanOrder/index.js +190 -449
  178. package/lib/solution/ScanOrder/types.d.ts +1 -21
  179. package/lib/solution/ScanOrder/utils.d.ts +0 -8
  180. package/lib/solution/ScanOrder/utils.js +0 -31
  181. package/lib/solution/ShopDiscount/index.d.ts +0 -1
  182. package/lib/solution/ShopDiscount/index.js +0 -14
  183. package/lib/solution/VenueBooking/index.d.ts +11 -39
  184. package/lib/solution/VenueBooking/index.js +123 -328
  185. package/lib/solution/VenueBooking/types.d.ts +0 -3
  186. package/lib/solution/VenueBooking/utils/resource.js +0 -1
  187. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +4 -4
  188. package/lib/solution/VenueBooking/utils/slotMerge.js +4 -6
  189. package/lib/solution/index.d.ts +0 -1
  190. package/lib/solution/index.js +1 -3
  191. package/lib/types/index.d.ts +1 -1
  192. package/lib/utils/payment-number.d.ts +9 -0
  193. package/lib/utils/payment-number.js +64 -0
  194. package/package.json +1 -1
  195. package/dist/modules/Holder/index.d.ts +0 -48
  196. package/dist/modules/Holder/index.js +0 -640
  197. package/dist/modules/Holder/types.d.ts +0 -123
  198. package/dist/modules/Holder/types.js +0 -1
  199. package/dist/modules/Holder/utils.d.ts +0 -13
  200. package/dist/modules/Holder/utils.js +0 -34
  201. package/dist/modules/ResourcePlanner/index.d.ts +0 -24
  202. package/dist/modules/ResourcePlanner/index.js +0 -181
  203. package/dist/modules/ResourcePlanner/planner.d.ts +0 -14
  204. package/dist/modules/ResourcePlanner/planner.js +0 -1069
  205. package/dist/modules/ResourcePlanner/types.d.ts +0 -227
  206. package/dist/modules/ResourcePlanner/types.js +0 -1
  207. package/dist/solution/UnifiedBookingSales/index.d.ts +0 -183
  208. package/dist/solution/UnifiedBookingSales/index.js +0 -1871
  209. package/dist/solution/UnifiedBookingSales/types.d.ts +0 -143
  210. package/dist/solution/UnifiedBookingSales/types.js +0 -11
  211. package/lib/modules/Holder/index.d.ts +0 -48
  212. package/lib/modules/Holder/index.js +0 -402
  213. package/lib/modules/Holder/types.d.ts +0 -123
  214. package/lib/modules/Holder/types.js +0 -17
  215. package/lib/modules/Holder/utils.d.ts +0 -13
  216. package/lib/modules/Holder/utils.js +0 -71
  217. package/lib/modules/ResourcePlanner/index.d.ts +0 -24
  218. package/lib/modules/ResourcePlanner/index.js +0 -148
  219. package/lib/modules/ResourcePlanner/planner.d.ts +0 -14
  220. package/lib/modules/ResourcePlanner/planner.js +0 -933
  221. package/lib/modules/ResourcePlanner/types.d.ts +0 -227
  222. package/lib/modules/ResourcePlanner/types.js +0 -17
  223. package/lib/solution/UnifiedBookingSales/index.d.ts +0 -183
  224. package/lib/solution/UnifiedBookingSales/index.js +0 -1076
  225. package/lib/solution/UnifiedBookingSales/types.d.ts +0 -143
  226. package/lib/solution/UnifiedBookingSales/types.js +0 -33
@@ -7,11 +7,11 @@ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableTo
7
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."); }
8
8
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
9
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; }
12
10
  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; } } }; }
13
11
  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); }
14
12
  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; }
13
+ 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; }
14
+ 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; }
15
15
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
16
16
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
17
17
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
@@ -35,6 +35,7 @@ import dayjs from 'dayjs';
35
35
  import { BaseModule } from "../../../modules/BaseModule";
36
36
  import { applyOrderCollectionUidRemaps, getOrderCollectionPersistentId, getOrderCollectionReferenceUid, getOrderCollectionUid, isSameOrderCollectionItem, mergeOrderCollectionItems, normalizeOrderCollections } from "../../../modules/Order/utils/orderCollectionIdentity";
37
37
  import { OrderHooks } from "./types";
38
+ import { getOrderPaymentIdentityKeys, isIdentifiedPendingOrderPayment, isPendingOrderPayment, mergeOrderPaymentListsByIdentity, mergeOrderPaymentRecord, resolveOrderPaymentIdentity } from "../../../modules/Order/payment-utils";
38
39
 
39
40
  /**
40
41
  * SQLite 存储名称
@@ -48,7 +49,7 @@ var ORDER_SQLITE_DEDUPE_MS = 15000;
48
49
  /** silentRefresh 最小间隔,避免 preload 后立即全量重拉 */
49
50
  var ORDER_SILENT_REFRESH_MIN_INTERVAL_MS = 30000;
50
51
  /** 视为「业务侧刚写入」的来源,pubsub 回声可跳过 SQLite */
51
- var ORDER_BUSINESS_WRITE_SOURCES = new Set(['upsertOrdersFromRemote', 'upsertPendingSyncOrders', 'overwriteExistingOrder', 'markOrderSyncedByExternalSaleNumber']);
52
+ var ORDER_BUSINESS_WRITE_SOURCES = new Set(['upsertOrdersFromRemote', 'upsertPendingSyncOrders', 'upsertLocalDraftOrders', 'overwriteExistingOrder', 'markOrderSyncedByExternalSaleNumber', 'updateLocalPayment']);
52
53
 
53
54
  /**
54
55
  * 合并热路径全表去重自检开关:默认关闭。
@@ -56,6 +57,7 @@ var ORDER_BUSINESS_WRITE_SOURCES = new Set(['upsertOrdersFromRemote', 'upsertPen
56
57
  * 仅用于排查增量身份索引是否遗漏了重复订单,不应在生产常开。
57
58
  */
58
59
  var ORDER_MERGE_SELF_CHECK = false;
60
+ var PENDING_PAYMENT_WITHOUT_UNIQUE_MARKER = '__pisell_os_pending_payment_without_unique_number__';
59
61
  var ORDER_AUTHORITATIVE_COLLECTION_FIELDS = ['products', 'bookings', 'payments'];
60
62
  var ORDER_COLLECTION_KIND_BY_FIELD = {
61
63
  products: 'product',
@@ -138,8 +140,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
138
140
  key: "initialize",
139
141
  value: function () {
140
142
  var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(core, options) {
141
- var _options$initialState,
142
- _this3 = this;
143
+ var _options$initialState;
143
144
  var appPlugin, app;
144
145
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
145
146
  while (1) switch (_context2.prev = _context2.next) {
@@ -156,9 +157,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
156
157
  this.updateCreateStore();
157
158
  }
158
159
  if (Array.isArray(options === null || options === void 0 || (_options$initialState = options.initialState) === null || _options$initialState === void 0 ? void 0 : _options$initialState.list)) {
159
- this.store.list = options.initialState.list.map(function (order) {
160
- return _this3.normalizeOrderForMemoryList(order);
161
- });
160
+ this.store.list = this.normalizeOrdersForMemoryList(options.initialState.list, 'initialState');
162
161
  this.syncOrdersMap();
163
162
  this.emitOrdersChanged([], 'initialState');
164
163
  } else {
@@ -247,7 +246,31 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
247
246
  }, {
248
247
  key: "normalizeOrderCollectionsForIngress",
249
248
  value: function normalizeOrderCollectionsForIngress(order, source) {
250
- var result = normalizeOrderCollections(order);
249
+ var sourceOrder = cloneDeep(order);
250
+ var sourceOrderRecord = sourceOrder;
251
+ if (Array.isArray(sourceOrderRecord.payments)) {
252
+ sourceOrderRecord.payments = sourceOrderRecord.payments.map(function (payment) {
253
+ if (!isPendingOrderPayment(payment) || getOrderPaymentIdentityKeys(payment).some(function (key) {
254
+ return key.startsWith('unique_payment_number:');
255
+ })) {
256
+ return payment;
257
+ }
258
+ return _objectSpread(_objectSpread({}, payment), {}, _defineProperty({}, PENDING_PAYMENT_WITHOUT_UNIQUE_MARKER, true));
259
+ });
260
+ }
261
+ var result = normalizeOrderCollections(sourceOrder);
262
+ var normalizedOrderRecord = result.order;
263
+ if (Array.isArray(normalizedOrderRecord.payments)) {
264
+ normalizedOrderRecord.payments = normalizedOrderRecord.payments.map(function (payment) {
265
+ if (!(payment !== null && payment !== void 0 && payment[PENDING_PAYMENT_WITHOUT_UNIQUE_MARKER])) return payment;
266
+ var nextPayment = _objectSpread({}, payment);
267
+ var metadata = _objectSpread({}, nextPayment.metadata || {});
268
+ delete metadata.unique_payment_number;
269
+ delete nextPayment[PENDING_PAYMENT_WITHOUT_UNIQUE_MARKER];
270
+ nextPayment.metadata = metadata;
271
+ return nextPayment;
272
+ });
273
+ }
251
274
  var kinds = ['product', 'booking', 'payment'];
252
275
  var hasChanges = kinds.some(function (kind) {
253
276
  var stats = result.stats[kind];
@@ -291,8 +314,14 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
291
314
  key: "mergeAuthoritativeOrderCollection",
292
315
  value: function mergeAuthoritativeOrderCollection(field, existing, incoming) {
293
316
  var uidRemaps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
317
+ var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
294
318
  var kind = ORDER_COLLECTION_KIND_BY_FIELD[field];
295
319
  var existingItems = Array.isArray(existing) ? existing : [];
320
+ if (field === 'payments' && options.preserveIdentifiedPendingPayments) {
321
+ return mergeOrderPaymentListsByIdentity(existingItems, incoming, {
322
+ preserveUnmatchedExistingWhen: isIdentifiedPendingOrderPayment
323
+ });
324
+ }
296
325
  return incoming.map(function (incomingItem) {
297
326
  var existingItem = existingItems.find(function (item) {
298
327
  return isSameOrderCollectionItem(kind, item, incomingItem);
@@ -601,62 +630,27 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
601
630
  }, {
602
631
  key: "preload",
603
632
  value: function () {
604
- var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
605
- var _this4 = this;
606
- var getData;
607
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
608
- while (1) switch (_context4.prev = _context4.next) {
633
+ var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
634
+ var orders;
635
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
636
+ while (1) switch (_context3.prev = _context3.next) {
609
637
  case 0:
610
- // const hasPulledInCurrentWindow = this.hasPulledOrdersToday()
611
- // // 仅当缓存属于当前统计窗口时才直接复用,避免跨天/跨营业日窗口继续使用旧数据
612
- // if (cachedOrders.length > 0 && hasPulledInCurrentWindow) {
613
- // this.store.list = cloneDeep(cachedOrders)
614
- // this.syncOrdersMap()
615
- // this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list)
616
- // return
617
- // }
618
- // if (hasPulledInCurrentWindow) {
619
- // this.logInfo('当天已完成全量订单拉取,跳过本次全量拉取', {
620
- // lastFullFetchAt: this.getStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY),
621
- // })
622
- // return
623
- // }
624
- getData = /*#__PURE__*/function () {
625
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
626
- var orders;
627
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
628
- while (1) switch (_context3.prev = _context3.next) {
629
- case 0:
630
- _context3.next = 2;
631
- return _this4.loadOrdersByServer();
632
- case 2:
633
- orders = _context3.sent;
634
- if (!(orders.length === 0)) {
635
- _context3.next = 5;
636
- break;
637
- }
638
- return _context3.abrupt("return");
639
- case 5:
640
- _this4.store.list = cloneDeep(orders);
641
- _this4.syncOrdersMap();
642
- _this4.emitOrdersChanged([], 'preload');
643
- _this4.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
644
- case 9:
645
- case "end":
646
- return _context3.stop();
647
- }
648
- }, _callee3);
649
- }));
650
- return function getData() {
651
- return _ref.apply(this, arguments);
652
- };
653
- }();
654
- getData();
638
+ _context3.next = 2;
639
+ return this.loadOrdersByServer();
655
640
  case 2:
641
+ orders = _context3.sent;
642
+ this.store.list = cloneDeep(orders);
643
+ this.syncOrdersMap();
644
+ _context3.next = 7;
645
+ return this.emitOrdersChanged([], 'preload');
646
+ case 7:
647
+ _context3.next = 9;
648
+ return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
649
+ case 9:
656
650
  case "end":
657
- return _context4.stop();
651
+ return _context3.stop();
658
652
  }
659
- }, _callee4);
653
+ }, _callee3, this);
660
654
  }));
661
655
  function preload() {
662
656
  return _preload.apply(this, arguments);
@@ -680,67 +674,125 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
680
674
  value: function getOrderByOrderId(orderId) {
681
675
  return this.store.map.get(this.getIdKey(orderId));
682
676
  }
677
+ }, {
678
+ key: "buildLocalPaymentOrderLogContext",
679
+ value: function buildLocalPaymentOrderLogContext(order) {
680
+ var _order$order_id3, _order$external_sale_, _order$order_number, _order$shop_order_num, _order$shop_full_orde, _order$status, _order$payment_status, _order$platform, _order$business_code, _order$order_sales_ch, _order$sales_channel, _order$type;
681
+ if (!order) return {};
682
+ return {
683
+ order_id: (_order$order_id3 = order.order_id) !== null && _order$order_id3 !== void 0 ? _order$order_id3 : null,
684
+ external_sale_number: (_order$external_sale_ = order.external_sale_number) !== null && _order$external_sale_ !== void 0 ? _order$external_sale_ : null,
685
+ order_number: (_order$order_number = order.order_number) !== null && _order$order_number !== void 0 ? _order$order_number : null,
686
+ shop_order_number: (_order$shop_order_num = order.shop_order_number) !== null && _order$shop_order_num !== void 0 ? _order$shop_order_num : null,
687
+ shop_full_order_number: (_order$shop_full_orde = order.shop_full_order_number) !== null && _order$shop_full_orde !== void 0 ? _order$shop_full_orde : null,
688
+ order_status: (_order$status = order.status) !== null && _order$status !== void 0 ? _order$status : null,
689
+ payment_status: (_order$payment_status = order.payment_status) !== null && _order$payment_status !== void 0 ? _order$payment_status : null,
690
+ is_draft_order: Number(order.is_draft_order || 0),
691
+ need_sync: Number(order.need_sync || 0),
692
+ platform: (_order$platform = order.platform) !== null && _order$platform !== void 0 ? _order$platform : null,
693
+ business_code: (_order$business_code = order.business_code) !== null && _order$business_code !== void 0 ? _order$business_code : null,
694
+ order_sales_channel: (_order$order_sales_ch = order.order_sales_channel) !== null && _order$order_sales_ch !== void 0 ? _order$order_sales_ch : null,
695
+ sales_channel: (_order$sales_channel = order.sales_channel) !== null && _order$sales_channel !== void 0 ? _order$sales_channel : null,
696
+ order_type: (_order$type = order.type) !== null && _order$type !== void 0 ? _order$type : null,
697
+ payments_count: Array.isArray(order.payments) ? order.payments.length : 0
698
+ };
699
+ }
683
700
  }, {
684
701
  key: "getLocalOrderFromMemoryByLookup",
685
702
  value: function getLocalOrderFromMemoryByLookup(lookup) {
686
- var _this5 = this;
703
+ var _this3 = this;
687
704
  var key = this.getIdKey(lookup);
688
705
  var memoryOrderById = this.store.map.get(key);
689
706
  if (memoryOrderById) return memoryOrderById;
690
707
  var memoryOrder = this.store.list.find(function (order) {
691
- return _this5.isOrderLookupMatch(order, key);
708
+ return _this3.isOrderLookupMatch(order, key);
692
709
  });
693
710
  return memoryOrder || null;
694
711
  }
695
712
  }, {
696
713
  key: "getLocalOrderByLookup",
697
714
  value: function () {
698
- var _getLocalOrderByLookup = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(lookup) {
699
- var _this6 = this;
700
- var key, memoryOrderById, memoryOrder, orders, localOrder;
701
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
702
- while (1) switch (_context5.prev = _context5.next) {
715
+ var _getLocalOrderByLookup = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(lookup) {
716
+ var _this4 = this;
717
+ var options,
718
+ key,
719
+ logContext,
720
+ memoryOrderById,
721
+ memoryOrder,
722
+ orders,
723
+ localOrder,
724
+ normalizedOrder,
725
+ _args4 = arguments;
726
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
727
+ while (1) switch (_context4.prev = _context4.next) {
703
728
  case 0:
729
+ options = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : {};
704
730
  key = this.getIdKey(lookup);
731
+ logContext = {
732
+ operation_id: options.operationId,
733
+ lookup: key,
734
+ memory_order_count: this.store.list.length
735
+ };
736
+ if (options.operationId) {
737
+ this.logInfo('getLocalOrderByLookup-localPayment-开始', logContext);
738
+ }
705
739
  memoryOrderById = this.store.map.get(key);
706
740
  if (!memoryOrderById) {
707
- _context5.next = 4;
741
+ _context4.next = 8;
708
742
  break;
709
743
  }
710
- return _context5.abrupt("return", memoryOrderById);
711
- case 4:
744
+ if (options.operationId) {
745
+ this.logInfo('getLocalOrderByLookup-localPayment-命中内存映射', _objectSpread(_objectSpread({}, logContext), this.buildLocalPaymentOrderLogContext(memoryOrderById)));
746
+ }
747
+ return _context4.abrupt("return", memoryOrderById);
748
+ case 8:
712
749
  memoryOrder = this.store.list.find(function (order) {
713
- return _this6.isOrderLookupMatch(order, key);
750
+ return _this4.isOrderLookupMatch(order, key);
714
751
  });
715
752
  if (!memoryOrder) {
716
- _context5.next = 7;
753
+ _context4.next = 12;
717
754
  break;
718
755
  }
719
- return _context5.abrupt("return", memoryOrder);
720
- case 7:
721
- _context5.next = 9;
756
+ if (options.operationId) {
757
+ this.logInfo('getLocalOrderByLookup-localPayment-命中内存列表', _objectSpread(_objectSpread({}, logContext), this.buildLocalPaymentOrderLogContext(memoryOrder)));
758
+ }
759
+ return _context4.abrupt("return", memoryOrder);
760
+ case 12:
761
+ if (options.operationId) {
762
+ this.logInfo('getLocalOrderByLookup-localPayment-开始读取SQLite', logContext);
763
+ }
764
+ _context4.next = 15;
722
765
  return this.loadOrdersFromSQLite();
723
- case 9:
724
- orders = _context5.sent;
766
+ case 15:
767
+ orders = _context4.sent;
725
768
  localOrder = orders.find(function (order) {
726
- return _this6.isOrderLookupMatch(order, key);
769
+ return _this4.isOrderLookupMatch(order, key);
727
770
  });
728
771
  if (localOrder) {
729
- _context5.next = 13;
772
+ _context4.next = 20;
730
773
  break;
731
774
  }
732
- return _context5.abrupt("return", null);
733
- case 13:
734
- this.store.list = orders.map(function (order) {
735
- return _this6.normalizeOrderForMemoryList(order);
736
- });
775
+ if (options.operationId) {
776
+ this.logWarning('getLocalOrderByLookup-localPayment-SQLite未命中', _objectSpread(_objectSpread({}, logContext), {}, {
777
+ sqlite_order_count: orders.length
778
+ }));
779
+ }
780
+ return _context4.abrupt("return", null);
781
+ case 20:
782
+ this.store.list = this.normalizeOrdersForMemoryList(orders, 'getLocalOrderByLookup.sqliteMemory');
737
783
  this.syncOrdersMap();
738
- return _context5.abrupt("return", this.normalizeOrderForMemoryList(localOrder));
739
- case 16:
784
+ normalizedOrder = this.normalizeOrderForMemoryList(localOrder);
785
+ if (options.operationId) {
786
+ this.logInfo('getLocalOrderByLookup-localPayment-SQLite命中', _objectSpread(_objectSpread({}, logContext), {}, {
787
+ sqlite_order_count: orders.length
788
+ }, this.buildLocalPaymentOrderLogContext(normalizedOrder)));
789
+ }
790
+ return _context4.abrupt("return", normalizedOrder);
791
+ case 25:
740
792
  case "end":
741
- return _context5.stop();
793
+ return _context4.stop();
742
794
  }
743
- }, _callee5, this);
795
+ }, _callee4, this);
744
796
  }));
745
797
  function getLocalOrderByLookup(_x3) {
746
798
  return _getLocalOrderByLookup.apply(this, arguments);
@@ -748,66 +800,254 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
748
800
  return getLocalOrderByLookup;
749
801
  }()
750
802
  }, {
751
- key: "loadOrdersByServer",
803
+ key: "getLocalPayment",
804
+ value: function () {
805
+ var _getLocalPayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(params) {
806
+ var logContext, order, payments, match;
807
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
808
+ while (1) switch (_context5.prev = _context5.next) {
809
+ case 0:
810
+ logContext = {
811
+ operation_id: params.operationId,
812
+ sale_id: params.saleId,
813
+ payment_number: params.paymentNumber
814
+ };
815
+ this.logInfo('getLocalPayment-开始', logContext);
816
+ _context5.prev = 2;
817
+ _context5.next = 5;
818
+ return this.getLocalOrderByLookup(params.saleId, {
819
+ operationId: params.operationId
820
+ });
821
+ case 5:
822
+ order = _context5.sent;
823
+ if (order) {
824
+ _context5.next = 9;
825
+ break;
826
+ }
827
+ this.logWarning('getLocalPayment-订单未命中', logContext);
828
+ return _context5.abrupt("return", null);
829
+ case 9:
830
+ payments = order.payments || [];
831
+ match = resolveOrderPaymentIdentity(payments, params.paymentNumber, 'compat');
832
+ if (match) {
833
+ _context5.next = 14;
834
+ break;
835
+ }
836
+ this.logWarning('getLocalPayment-支付项未命中', _objectSpread(_objectSpread(_objectSpread({}, logContext), this.buildLocalPaymentOrderLogContext(order)), {}, {
837
+ payments: payments
838
+ }));
839
+ return _context5.abrupt("return", null);
840
+ case 14:
841
+ this.logInfo('getLocalPayment-支付项命中', _objectSpread(_objectSpread(_objectSpread({}, logContext), this.buildLocalPaymentOrderLogContext(order)), {}, {
842
+ matched_by: match.matchedBy,
843
+ payment_index: match.index,
844
+ payment: match.payment
845
+ }));
846
+ return _context5.abrupt("return", {
847
+ order: order,
848
+ payment: match.payment,
849
+ paymentIndex: match.index,
850
+ matchedBy: match.matchedBy
851
+ });
852
+ case 18:
853
+ _context5.prev = 18;
854
+ _context5.t0 = _context5["catch"](2);
855
+ this.logError('getLocalPayment-查询失败', _objectSpread(_objectSpread({}, logContext), {}, {
856
+ error: _context5.t0 instanceof Error ? _context5.t0.message : String(_context5.t0)
857
+ }));
858
+ throw _context5.t0;
859
+ case 22:
860
+ case "end":
861
+ return _context5.stop();
862
+ }
863
+ }, _callee5, this, [[2, 18]]);
864
+ }));
865
+ function getLocalPayment(_x4) {
866
+ return _getLocalPayment.apply(this, arguments);
867
+ }
868
+ return getLocalPayment;
869
+ }()
870
+ }, {
871
+ key: "updateLocalPayment",
752
872
  value: function () {
753
- var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
754
- var _this$store,
755
- _this7 = this;
756
- var orderList, data, mergedOrders, memoryOrders;
873
+ var _updateLocalPayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(params) {
874
+ var logContext, found, previousPayment, nextPayment, nextOrder, paymentContext, targetIndex, shouldKeepInMemory, previousList, storageOrder, _storageOrder$order_i, _storageOrder$order_i2, _storageOrder$order_i3;
757
875
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
758
876
  while (1) switch (_context6.prev = _context6.next) {
877
+ case 0:
878
+ logContext = {
879
+ operation_id: params.operationId,
880
+ sale_id: params.saleId,
881
+ payment_number: params.paymentNumber,
882
+ incoming_payment_update: params.updates
883
+ };
884
+ this.logInfo('updateLocalPayment-开始', logContext);
885
+ _context6.next = 4;
886
+ return this.getLocalPayment(params);
887
+ case 4:
888
+ found = _context6.sent;
889
+ if (found) {
890
+ _context6.next = 8;
891
+ break;
892
+ }
893
+ this.logWarning('updateLocalPayment-支付项未命中', logContext);
894
+ return _context6.abrupt("return", null);
895
+ case 8:
896
+ previousPayment = cloneDeep(found.payment);
897
+ nextPayment = mergeOrderPaymentRecord(found.payment, _objectSpread(_objectSpread({}, params.updates), {}, {
898
+ updated_at: params.updates.updated_at || dayjs().format('YYYY-MM-DD HH:mm:ss')
899
+ }));
900
+ nextOrder = _objectSpread(_objectSpread({}, found.order), {}, {
901
+ payments: (found.order.payments || []).map(function (payment, index) {
902
+ return index === found.paymentIndex ? nextPayment : payment;
903
+ }),
904
+ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss')
905
+ });
906
+ paymentContext = _objectSpread(_objectSpread(_objectSpread({}, logContext), {}, {
907
+ matched_by: found.matchedBy,
908
+ payment_index: found.paymentIndex
909
+ }, this.buildLocalPaymentOrderLogContext(nextOrder)), {}, {
910
+ previous_payment: previousPayment,
911
+ payment: nextPayment
912
+ });
913
+ this.logInfo('updateLocalPayment-支付项合并完成', paymentContext);
914
+ targetIndex = this.findOrderIndexByIdentity(this.store.list, found.order);
915
+ shouldKeepInMemory = this.shouldKeepOrderInMemory(nextOrder);
916
+ if (!(targetIndex < 0 && shouldKeepInMemory)) {
917
+ _context6.next = 18;
918
+ break;
919
+ }
920
+ this.logError('updateLocalPayment-订单Store索引未命中', paymentContext);
921
+ return _context6.abrupt("return", null);
922
+ case 18:
923
+ previousList = this.store.list;
924
+ this.store.list = shouldKeepInMemory ? this.store.list.map(function (order, index) {
925
+ return index === targetIndex ? nextOrder : order;
926
+ }) : this.store.list.filter(function (_, index) {
927
+ return index !== targetIndex;
928
+ });
929
+ this.syncOrdersMap();
930
+ storageOrder = this.withoutSyntheticDraftOrderId(nextOrder);
931
+ _context6.prev = 22;
932
+ this.logInfo('updateLocalPayment-SQLite写入开始', _objectSpread(_objectSpread({}, paymentContext), {}, {
933
+ storage_order_id: (_storageOrder$order_i = storageOrder.order_id) !== null && _storageOrder$order_i !== void 0 ? _storageOrder$order_i : null
934
+ }));
935
+ _context6.next = 26;
936
+ return this.updateOrderInSQLite(storageOrder, 'updateLocalPayment', {
937
+ throwOnError: true
938
+ });
939
+ case 26:
940
+ this.logInfo('updateLocalPayment-SQLite写入完成', _objectSpread(_objectSpread({}, paymentContext), {}, {
941
+ storage_order_id: (_storageOrder$order_i2 = storageOrder.order_id) !== null && _storageOrder$order_i2 !== void 0 ? _storageOrder$order_i2 : null
942
+ }));
943
+ _context6.next = 35;
944
+ break;
945
+ case 29:
946
+ _context6.prev = 29;
947
+ _context6.t0 = _context6["catch"](22);
948
+ this.store.list = previousList;
949
+ this.syncOrdersMap();
950
+ this.logError('updateLocalPayment-SQLite写入失败并回滚内存', _objectSpread(_objectSpread({}, paymentContext), {}, {
951
+ storage_order_id: (_storageOrder$order_i3 = storageOrder.order_id) !== null && _storageOrder$order_i3 !== void 0 ? _storageOrder$order_i3 : null,
952
+ error: _context6.t0 instanceof Error ? _context6.t0.message : String(_context6.t0)
953
+ }));
954
+ throw _context6.t0;
955
+ case 35:
956
+ if (!(shouldKeepInMemory || targetIndex >= 0)) {
957
+ _context6.next = 38;
958
+ break;
959
+ }
960
+ _context6.next = 38;
961
+ return this.emitOrdersChanged(shouldKeepInMemory ? [nextOrder] : [], shouldKeepInMemory ? 'updateLocalPayment' : 'updateLocalPayment.sqliteOnlyDraft');
962
+ case 38:
963
+ this.logInfo('updateLocalPayment-变更事件完成', paymentContext);
964
+ return _context6.abrupt("return", {
965
+ order: nextOrder,
966
+ payment: nextPayment,
967
+ previousPayment: previousPayment
968
+ });
969
+ case 40:
970
+ case "end":
971
+ return _context6.stop();
972
+ }
973
+ }, _callee6, this, [[22, 29]]);
974
+ }));
975
+ function updateLocalPayment(_x5) {
976
+ return _updateLocalPayment.apply(this, arguments);
977
+ }
978
+ return updateLocalPayment;
979
+ }()
980
+ }, {
981
+ key: "loadOrdersByServer",
982
+ value: function () {
983
+ var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
984
+ var _this5 = this,
985
+ _this$store;
986
+ var orderList, protectedOrdersBeforeRemoteFetch, data, mergedOrders, memoryOrders;
987
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
988
+ while (1) switch (_context7.prev = _context7.next) {
759
989
  case 0:
760
990
  orderList = [];
991
+ _context7.next = 3;
992
+ return this.loadOrdersFromSQLite();
993
+ case 3:
994
+ protectedOrdersBeforeRemoteFetch = _context7.sent.filter(function (order) {
995
+ return _this5.shouldProtectLocalOrderFromRemoteSnapshot(order);
996
+ });
761
997
  this.logInfo('loadOrdersByServer-开始', {
762
998
  hasOrderDataSource: !!this.orderDataSource,
763
- query: ((_this$store = this.store) === null || _this$store === void 0 ? void 0 : _this$store.createdAtQuery) || null
999
+ query: ((_this$store = this.store) === null || _this$store === void 0 ? void 0 : _this$store.createdAtQuery) || null,
1000
+ protectedLocalOrderCount: protectedOrdersBeforeRemoteFetch.length,
1001
+ protectedPendingPaymentCount: protectedOrdersBeforeRemoteFetch.reduce(function (count, order) {
1002
+ return count + _this5.getIdentifiedPendingPayments(order).length;
1003
+ }, 0)
764
1004
  });
765
1005
  if (!this.orderDataSource) {
766
- _context6.next = 17;
1006
+ _context7.next = 20;
767
1007
  break;
768
1008
  }
769
- _context6.prev = 3;
770
- _context6.next = 6;
1009
+ _context7.prev = 6;
1010
+ _context7.next = 9;
771
1011
  return this.orderDataSource.run({
772
1012
  sse: {
773
1013
  query: this.store.createdAtQuery
774
1014
  }
775
1015
  });
776
- case 6:
777
- data = _context6.sent;
1016
+ case 9:
1017
+ data = _context7.sent;
778
1018
  orderList = data || [];
779
1019
  this.logInfo('loadOrdersByServer-SSE拉取成功', {
780
1020
  count: orderList.length
781
1021
  });
782
1022
  this.markOrderPulledAtNow();
783
1023
  this.lastServerFullFetchAtMs = Date.now();
784
- _context6.next = 17;
1024
+ _context7.next = 20;
785
1025
  break;
786
- case 13:
787
- _context6.prev = 13;
788
- _context6.t0 = _context6["catch"](3);
1026
+ case 16:
1027
+ _context7.prev = 16;
1028
+ _context7.t0 = _context7["catch"](6);
789
1029
  this.logInfo('loadOrdersByServer-SSE拉取失败,保持当前内存订单');
790
- return _context6.abrupt("return", this.store.list);
791
- case 17:
792
- _context6.next = 19;
793
- return this.replaceOrdersSnapshotInSQLite(orderList, 'loadOrdersByServer');
794
- case 19:
795
- mergedOrders = _context6.sent;
796
- memoryOrders = mergedOrders.map(function (order) {
797
- return _this7.normalizeOrderForMemoryList(order);
798
- });
1030
+ return _context7.abrupt("return", this.store.list);
1031
+ case 20:
1032
+ _context7.next = 22;
1033
+ return this.replaceOrdersSnapshotInSQLite(orderList, 'loadOrdersByServer', protectedOrdersBeforeRemoteFetch);
1034
+ case 22:
1035
+ mergedOrders = _context7.sent;
1036
+ memoryOrders = this.normalizeOrdersForMemoryList(mergedOrders, 'loadOrdersByServer.memory');
799
1037
  this.logInfo('loadOrdersByServer-结束', {
800
- count: memoryOrders.length
1038
+ count: memoryOrders.length,
1039
+ persistedCount: mergedOrders.length,
1040
+ sqliteOnlyDraftCount: mergedOrders.length - memoryOrders.length
801
1041
  });
802
- _context6.next = 24;
1042
+ _context7.next = 27;
803
1043
  return this.core.effects.emit(OrderHooks.onOrdersLoaded, memoryOrders);
804
- case 24:
805
- return _context6.abrupt("return", memoryOrders);
806
- case 25:
1044
+ case 27:
1045
+ return _context7.abrupt("return", memoryOrders);
1046
+ case 28:
807
1047
  case "end":
808
- return _context6.stop();
1048
+ return _context7.stop();
809
1049
  }
810
- }, _callee6, this, [[3, 13]]);
1050
+ }, _callee7, this, [[6, 16]]);
811
1051
  }));
812
1052
  function loadOrdersByServer() {
813
1053
  return _loadOrdersByServer.apply(this, arguments);
@@ -822,61 +1062,54 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
822
1062
  }, {
823
1063
  key: "silentRefresh",
824
1064
  value: (function () {
825
- var _silentRefresh = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
1065
+ var _silentRefresh = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
826
1066
  var startTime, elapsedSinceFullFetch, orders, errorMessage;
827
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
828
- while (1) switch (_context7.prev = _context7.next) {
1067
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1068
+ while (1) switch (_context8.prev = _context8.next) {
829
1069
  case 0:
830
1070
  startTime = Date.now();
831
1071
  elapsedSinceFullFetch = Date.now() - this.lastServerFullFetchAtMs;
832
1072
  if (!(this.lastServerFullFetchAtMs > 0 && elapsedSinceFullFetch < ORDER_SILENT_REFRESH_MIN_INTERVAL_MS)) {
833
- _context7.next = 4;
1073
+ _context8.next = 4;
834
1074
  break;
835
1075
  }
836
- return _context7.abrupt("return", this.store.list);
1076
+ return _context8.abrupt("return", this.store.list);
837
1077
  case 4:
838
1078
  this.logInfo('silentRefresh 开始');
839
- _context7.prev = 5;
1079
+ _context8.prev = 5;
840
1080
  // 刷新前,需要更新当前营业日边界(store.createdAtQuery)
841
1081
  this.updateCreateStore();
842
- _context7.next = 9;
1082
+ _context8.next = 9;
843
1083
  return this.loadOrdersByServer();
844
1084
  case 9:
845
- orders = _context7.sent;
846
- if (!(orders.length > 0)) {
847
- _context7.next = 19;
848
- break;
849
- }
1085
+ orders = _context8.sent;
850
1086
  this.store.list = cloneDeep(orders);
851
1087
  this.syncOrdersMap();
852
- this.emitOrdersChanged([], 'silentRefresh');
853
- _context7.next = 16;
1088
+ _context8.next = 14;
1089
+ return this.emitOrdersChanged([], 'silentRefresh');
1090
+ case 14:
1091
+ _context8.next = 16;
854
1092
  return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
855
1093
  case 16:
856
1094
  this.logInfo('silentRefresh 完成', {
857
1095
  orderCount: orders.length,
858
1096
  duration: "".concat(Date.now() - startTime, "ms")
859
1097
  });
860
- _context7.next = 20;
861
- break;
862
- case 19:
863
- this.logInfo('silentRefresh: 服务器未返回数据');
1098
+ return _context8.abrupt("return", this.store.list);
864
1099
  case 20:
865
- return _context7.abrupt("return", this.store.list);
866
- case 23:
867
- _context7.prev = 23;
868
- _context7.t0 = _context7["catch"](5);
869
- errorMessage = _context7.t0 instanceof Error ? _context7.t0.message : String(_context7.t0);
1100
+ _context8.prev = 20;
1101
+ _context8.t0 = _context8["catch"](5);
1102
+ errorMessage = _context8.t0 instanceof Error ? _context8.t0.message : String(_context8.t0);
870
1103
  this.logError('silentRefresh 失败', {
871
1104
  duration: "".concat(Date.now() - startTime, "ms"),
872
1105
  error: errorMessage
873
1106
  });
874
- return _context7.abrupt("return", this.store.list);
875
- case 28:
1107
+ return _context8.abrupt("return", this.store.list);
1108
+ case 25:
876
1109
  case "end":
877
- return _context7.stop();
1110
+ return _context8.stop();
878
1111
  }
879
- }, _callee7, this, [[5, 23]]);
1112
+ }, _callee8, this, [[5, 20]]);
880
1113
  }));
881
1114
  function silentRefresh() {
882
1115
  return _silentRefresh.apply(this, arguments);
@@ -889,6 +1122,9 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
889
1122
  var source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'normalizeOrderForMemoryList';
890
1123
  var normalizedOrder = this.normalizeOrderCollectionsForIngress(order, source);
891
1124
  var externalSaleNumber = normalizedOrder === null || normalizedOrder === void 0 ? void 0 : normalizedOrder.external_sale_number;
1125
+ if (this.isDraftOrder(normalizedOrder) && !this.hasRealOrderId(normalizedOrder)) {
1126
+ return normalizedOrder;
1127
+ }
892
1128
  if ((normalizedOrder === null || normalizedOrder === void 0 ? void 0 : normalizedOrder.order_id) !== undefined && (normalizedOrder === null || normalizedOrder === void 0 ? void 0 : normalizedOrder.order_id) !== null && (normalizedOrder === null || normalizedOrder === void 0 ? void 0 : normalizedOrder.order_id) !== '') {
893
1129
  return normalizedOrder;
894
1130
  }
@@ -899,6 +1135,39 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
899
1135
  order_id: externalSaleNumber
900
1136
  });
901
1137
  }
1138
+ }, {
1139
+ key: "normalizeOrdersForMemoryList",
1140
+ value: function normalizeOrdersForMemoryList(orders, source) {
1141
+ var _this6 = this;
1142
+ return orders.map(function (order) {
1143
+ return _this6.normalizeOrderForMemoryList(order, source);
1144
+ }).filter(function (order) {
1145
+ return _this6.shouldKeepOrderInMemory(order);
1146
+ });
1147
+ }
1148
+ }, {
1149
+ key: "hasRealOrderId",
1150
+ value: function hasRealOrderId(order) {
1151
+ if (!order || this.isBlankIdentityValue(order.order_id)) return false;
1152
+ var externalSaleNumber = order.external_sale_number;
1153
+ return !(this.isDraftOrder(order) && !this.isBlankIdentityValue(externalSaleNumber) && String(order.order_id) === String(externalSaleNumber));
1154
+ }
1155
+ }, {
1156
+ key: "shouldKeepOrderInMemory",
1157
+ value: function shouldKeepOrderInMemory(order) {
1158
+ return !this.isDraftOrder(order) || this.hasRealOrderId(order);
1159
+ }
1160
+ }, {
1161
+ key: "withoutSyntheticDraftOrderId",
1162
+ value: function withoutSyntheticDraftOrderId(order) {
1163
+ var externalSaleNumber = order.external_sale_number;
1164
+ if (Number(order.is_draft_order || 0) !== 1 || order.order_id === undefined || externalSaleNumber === undefined || String(order.order_id) !== String(externalSaleNumber)) {
1165
+ return order;
1166
+ }
1167
+ var next = _objectSpread({}, order);
1168
+ delete next.order_id;
1169
+ return next;
1170
+ }
902
1171
 
903
1172
  /**
904
1173
  * 仅覆盖本地已存在的订单;不存在则直接跳过,不落库、不 emit。
@@ -907,31 +1176,31 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
907
1176
  }, {
908
1177
  key: "overwriteExistingOrder",
909
1178
  value: (function () {
910
- var _overwriteExistingOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(fresh) {
911
- var _this8 = this;
1179
+ var _overwriteExistingOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(fresh) {
1180
+ var _this7 = this;
912
1181
  var orderId, key, normalizedFresh, existingOrder, reconciledFresh;
913
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
914
- while (1) switch (_context8.prev = _context8.next) {
1182
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1183
+ while (1) switch (_context9.prev = _context9.next) {
915
1184
  case 0:
916
1185
  orderId = fresh === null || fresh === void 0 ? void 0 : fresh.order_id;
917
1186
  if (!(orderId === undefined || orderId === null)) {
918
- _context8.next = 4;
1187
+ _context9.next = 4;
919
1188
  break;
920
1189
  }
921
1190
  this.logError('overwriteExistingOrder-入参缺少 order_id');
922
- return _context8.abrupt("return", {
1191
+ return _context9.abrupt("return", {
923
1192
  overwritten: false
924
1193
  });
925
1194
  case 4:
926
1195
  key = this.getIdKey(orderId);
927
1196
  if (this.store.map.has(key)) {
928
- _context8.next = 8;
1197
+ _context9.next = 8;
929
1198
  break;
930
1199
  }
931
1200
  this.logInfo('overwriteExistingOrder-本地不存在该订单,跳过', {
932
1201
  orderId: orderId
933
1202
  });
934
- return _context8.abrupt("return", {
1203
+ return _context9.abrupt("return", {
935
1204
  overwritten: false
936
1205
  });
937
1206
  case 8:
@@ -945,31 +1214,31 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
945
1214
  this.store.list = this.store.list.map(function (order) {
946
1215
  var id = order === null || order === void 0 ? void 0 : order.order_id;
947
1216
  if (id === undefined || id === null) {
948
- return _this8.normalizeOrderForMemoryList(order, 'overwriteExistingOrder.existingMemory');
1217
+ return _this7.normalizeOrderForMemoryList(order, 'overwriteExistingOrder.existingMemory');
949
1218
  }
950
- return _this8.getIdKey(id) === key ? reconciledFresh : _this8.normalizeOrderForMemoryList(order, 'overwriteExistingOrder.existingMemory');
1219
+ return _this7.getIdKey(id) === key ? reconciledFresh : _this7.normalizeOrderForMemoryList(order, 'overwriteExistingOrder.existingMemory');
951
1220
  });
952
1221
  this.syncOrdersMap();
953
- _context8.next = 16;
1222
+ _context9.next = 16;
954
1223
  return this.updateOrderInSQLite(reconciledFresh, 'overwriteExistingOrder');
955
1224
  case 16:
956
1225
  this.logInfo('overwriteExistingOrder-结束', {
957
1226
  orderId: orderId,
958
1227
  storeOrderCountAfter: this.store.list.length
959
1228
  });
960
- _context8.next = 19;
1229
+ _context9.next = 19;
961
1230
  return this.emitOrdersChanged([reconciledFresh], 'overwriteExistingOrder');
962
1231
  case 19:
963
- return _context8.abrupt("return", {
1232
+ return _context9.abrupt("return", {
964
1233
  overwritten: true
965
1234
  });
966
1235
  case 20:
967
1236
  case "end":
968
- return _context8.stop();
1237
+ return _context9.stop();
969
1238
  }
970
- }, _callee8, this);
1239
+ }, _callee9, this);
971
1240
  }));
972
- function overwriteExistingOrder(_x4) {
1241
+ function overwriteExistingOrder(_x6) {
973
1242
  return _overwriteExistingOrder.apply(this, arguments);
974
1243
  }
975
1244
  return overwriteExistingOrder;
@@ -982,29 +1251,33 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
982
1251
  }, {
983
1252
  key: "upsertOrdersFromRemote",
984
1253
  value: (function () {
985
- var _upsertOrdersFromRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(freshOrders) {
986
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
987
- while (1) switch (_context9.prev = _context9.next) {
1254
+ var _upsertOrdersFromRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(freshOrders) {
1255
+ var source,
1256
+ _args10 = arguments;
1257
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1258
+ while (1) switch (_context10.prev = _context10.next) {
988
1259
  case 0:
1260
+ source = _args10.length > 1 && _args10[1] !== undefined ? _args10[1] : 'upsertOrdersFromRemote';
989
1261
  if (freshOrders !== null && freshOrders !== void 0 && freshOrders.length) {
990
- _context9.next = 3;
1262
+ _context10.next = 4;
991
1263
  break;
992
1264
  }
993
1265
  this.logInfo('upsertOrdersFromRemote-订单列表为空', {});
994
- return _context9.abrupt("return");
995
- case 3:
1266
+ return _context10.abrupt("return");
1267
+ case 4:
996
1268
  this.logInfo('upsertOrdersFromRemote-开始', {
997
- count: freshOrders.length
1269
+ count: freshOrders.length,
1270
+ source: source
998
1271
  });
999
- _context9.next = 6;
1000
- return this.mergeOrdersToStore(freshOrders, 'upsertOrdersFromRemote');
1001
- case 6:
1272
+ _context10.next = 7;
1273
+ return this.mergeOrdersToStore(freshOrders, source);
1274
+ case 7:
1002
1275
  case "end":
1003
- return _context9.stop();
1276
+ return _context10.stop();
1004
1277
  }
1005
- }, _callee9, this);
1278
+ }, _callee10, this);
1006
1279
  }));
1007
- function upsertOrdersFromRemote(_x5) {
1280
+ function upsertOrdersFromRemote(_x7) {
1008
1281
  return _upsertOrdersFromRemote.apply(this, arguments);
1009
1282
  }
1010
1283
  return upsertOrdersFromRemote;
@@ -1012,21 +1285,21 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1012
1285
  }, {
1013
1286
  key: "markOrderSyncedByExternalSaleNumber",
1014
1287
  value: function () {
1015
- var _markOrderSyncedByExternalSaleNumber = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(params) {
1016
- var _this9 = this,
1288
+ var _markOrderSyncedByExternalSaleNumber = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(params) {
1289
+ var _this8 = this,
1017
1290
  _existing$external_sa,
1018
1291
  _nextOrder$order_id;
1019
1292
  var externalSaleNumber, key, targetIndex, existing, nextOrder, storageKey;
1020
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1021
- while (1) switch (_context10.prev = _context10.next) {
1293
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1294
+ while (1) switch (_context11.prev = _context11.next) {
1022
1295
  case 0:
1023
1296
  externalSaleNumber = params.externalSaleNumber;
1024
1297
  if (!(externalSaleNumber === undefined || externalSaleNumber === null || externalSaleNumber === '')) {
1025
- _context10.next = 4;
1298
+ _context11.next = 4;
1026
1299
  break;
1027
1300
  }
1028
1301
  this.logError('markOrderSyncedByExternalSaleNumber-缺少 external_sale_number');
1029
- return _context10.abrupt("return", {
1302
+ return _context11.abrupt("return", {
1030
1303
  updated: false
1031
1304
  });
1032
1305
  case 4:
@@ -1034,23 +1307,24 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1034
1307
  targetIndex = this.store.list.findIndex(function (order) {
1035
1308
  var value = order === null || order === void 0 ? void 0 : order.external_sale_number;
1036
1309
  if (value === undefined || value === null || value === '') return false;
1037
- return _this9.getIdKey(value) === key;
1310
+ return _this8.getIdKey(value) === key;
1038
1311
  });
1039
1312
  if (!(targetIndex < 0)) {
1040
- _context10.next = 9;
1313
+ _context11.next = 9;
1041
1314
  break;
1042
1315
  }
1043
1316
  this.logInfo('markOrderSyncedByExternalSaleNumber-本地订单不存在,跳过', {
1044
1317
  external_sale_number: externalSaleNumber
1045
1318
  });
1046
- return _context10.abrupt("return", {
1319
+ return _context11.abrupt("return", {
1047
1320
  updated: false
1048
1321
  });
1049
1322
  case 9:
1050
1323
  existing = this.store.list[targetIndex];
1051
1324
  nextOrder = this.normalizeRemoteSyncedOrder(_objectSpread(_objectSpread(_objectSpread({}, existing), params.patch || {}), {}, {
1052
1325
  external_sale_number: (_existing$external_sa = existing.external_sale_number) !== null && _existing$external_sa !== void 0 ? _existing$external_sa : externalSaleNumber,
1053
- need_sync: 0
1326
+ need_sync: 0,
1327
+ is_draft_order: 0
1054
1328
  }));
1055
1329
  storageKey = this.getOrderStorageKey(nextOrder) || key;
1056
1330
  this.store.list = this.store.list.map(function (order, index) {
@@ -1058,27 +1332,27 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1058
1332
  return nextOrder;
1059
1333
  });
1060
1334
  this.syncOrdersMap();
1061
- _context10.next = 16;
1335
+ _context11.next = 16;
1062
1336
  return this.patchOrdersInSQLite([nextOrder], 'markOrderSyncedByExternalSaleNumber', _defineProperty({}, storageKey, 'update'));
1063
1337
  case 16:
1064
1338
  this.logInfo('markOrderSyncedByExternalSaleNumber-完成', {
1065
1339
  external_sale_number: externalSaleNumber,
1066
1340
  order_id: (_nextOrder$order_id = nextOrder.order_id) !== null && _nextOrder$order_id !== void 0 ? _nextOrder$order_id : null
1067
1341
  });
1068
- _context10.next = 19;
1342
+ _context11.next = 19;
1069
1343
  return this.emitOrdersChanged([nextOrder], 'markOrderSyncedByExternalSaleNumber');
1070
1344
  case 19:
1071
- return _context10.abrupt("return", {
1345
+ return _context11.abrupt("return", {
1072
1346
  updated: true,
1073
1347
  order: nextOrder
1074
1348
  });
1075
1349
  case 20:
1076
1350
  case "end":
1077
- return _context10.stop();
1351
+ return _context11.stop();
1078
1352
  }
1079
- }, _callee10, this);
1353
+ }, _callee11, this);
1080
1354
  }));
1081
- function markOrderSyncedByExternalSaleNumber(_x6) {
1355
+ function markOrderSyncedByExternalSaleNumber(_x8) {
1082
1356
  return _markOrderSyncedByExternalSaleNumber.apply(this, arguments);
1083
1357
  }
1084
1358
  return markOrderSyncedByExternalSaleNumber;
@@ -1090,70 +1364,104 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1090
1364
  }, {
1091
1365
  key: "upsertPendingSyncOrders",
1092
1366
  value: (function () {
1093
- var _upsertPendingSyncOrders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(pendingOrders) {
1094
- var _this10 = this;
1095
- var pendingMap, memoryPendingMap, _iterator5, _step5, order, normalizedOrder, storageKey, mergeActions, updatedList, identityKeyToIndex, index, _iterator6, _step6, key, _iterator7, _step7, _step7$value, _storageKey, pendingOrder, matchIndex, existingOrder, mergedOrder, pendingSnapshot, insertIndex, patchedOrders;
1096
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1097
- while (1) switch (_context11.prev = _context11.next) {
1367
+ var _upsertPendingSyncOrders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(pendingOrders) {
1368
+ var _this9 = this;
1369
+ var options,
1370
+ pendingMap,
1371
+ memoryPendingMap,
1372
+ _iterator5,
1373
+ _step5,
1374
+ order,
1375
+ normalizedOrder,
1376
+ pendingOrder,
1377
+ storageKey,
1378
+ mergeActions,
1379
+ updatedList,
1380
+ identityKeyToIndex,
1381
+ index,
1382
+ _iterator6,
1383
+ _step6,
1384
+ key,
1385
+ _iterator7,
1386
+ _step7,
1387
+ _step7$value,
1388
+ _storageKey,
1389
+ _pendingOrder,
1390
+ matchIndex,
1391
+ existingOrder,
1392
+ mergedOrder,
1393
+ nextOrder,
1394
+ pendingSnapshot,
1395
+ insertIndex,
1396
+ patchedOrders,
1397
+ previousList,
1398
+ _args12 = arguments;
1399
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1400
+ while (1) switch (_context12.prev = _context12.next) {
1098
1401
  case 0:
1402
+ options = _args12.length > 1 && _args12[1] !== undefined ? _args12[1] : {};
1099
1403
  if (pendingOrders !== null && pendingOrders !== void 0 && pendingOrders.length) {
1100
- _context11.next = 3;
1404
+ _context12.next = 4;
1101
1405
  break;
1102
1406
  }
1103
1407
  this.logInfo('upsertPendingSyncOrders-订单列表为空', {});
1104
- return _context11.abrupt("return");
1105
- case 3:
1408
+ return _context12.abrupt("return");
1409
+ case 4:
1106
1410
  pendingMap = new Map();
1107
1411
  memoryPendingMap = new Map();
1108
1412
  _iterator5 = _createForOfIteratorHelper(pendingOrders);
1109
- _context11.prev = 6;
1413
+ _context12.prev = 7;
1110
1414
  _iterator5.s();
1111
- case 8:
1415
+ case 9:
1112
1416
  if ((_step5 = _iterator5.n()).done) {
1113
- _context11.next = 18;
1417
+ _context12.next = 20;
1114
1418
  break;
1115
1419
  }
1116
1420
  order = _step5.value;
1117
1421
  normalizedOrder = this.normalizeOrderCollectionsForIngress(order, 'upsertPendingSyncOrders.incoming');
1118
- storageKey = this.getOrderStorageKey(normalizedOrder);
1422
+ pendingOrder = _objectSpread(_objectSpread({}, normalizedOrder), {}, {
1423
+ need_sync: 1,
1424
+ is_draft_order: 0
1425
+ });
1426
+ storageKey = this.getOrderStorageKey(pendingOrder);
1119
1427
  if (storageKey) {
1120
- _context11.next = 14;
1428
+ _context12.next = 16;
1121
1429
  break;
1122
1430
  }
1123
- return _context11.abrupt("continue", 16);
1124
- case 14:
1125
- pendingMap.set(storageKey, normalizedOrder);
1126
- memoryPendingMap.set(storageKey, this.normalizeOrderForMemoryList(normalizedOrder, 'upsertPendingSyncOrders.memory'));
1431
+ return _context12.abrupt("continue", 18);
1127
1432
  case 16:
1128
- _context11.next = 8;
1129
- break;
1433
+ pendingMap.set(storageKey, pendingOrder);
1434
+ memoryPendingMap.set(storageKey, this.normalizeOrderForMemoryList(pendingOrder, 'upsertPendingSyncOrders.memory'));
1130
1435
  case 18:
1131
- _context11.next = 23;
1436
+ _context12.next = 9;
1132
1437
  break;
1133
1438
  case 20:
1134
- _context11.prev = 20;
1135
- _context11.t0 = _context11["catch"](6);
1136
- _iterator5.e(_context11.t0);
1137
- case 23:
1138
- _context11.prev = 23;
1439
+ _context12.next = 25;
1440
+ break;
1441
+ case 22:
1442
+ _context12.prev = 22;
1443
+ _context12.t0 = _context12["catch"](7);
1444
+ _iterator5.e(_context12.t0);
1445
+ case 25:
1446
+ _context12.prev = 25;
1139
1447
  _iterator5.f();
1140
- return _context11.finish(23);
1141
- case 26:
1448
+ return _context12.finish(25);
1449
+ case 28:
1142
1450
  if (!(pendingMap.size === 0)) {
1143
- _context11.next = 29;
1451
+ _context12.next = 31;
1144
1452
  break;
1145
1453
  }
1146
1454
  this.logError('upsertPendingSyncOrders-订单缺少可落库标识', {
1147
1455
  count: pendingOrders.length
1148
1456
  });
1149
- return _context11.abrupt("return");
1150
- case 29:
1457
+ return _context12.abrupt("return");
1458
+ case 31:
1151
1459
  this.logInfo('upsertPendingSyncOrders-开始', {
1152
1460
  count: pendingMap.size
1153
1461
  });
1154
1462
  mergeActions = {};
1155
1463
  updatedList = this.store.list.map(function (order) {
1156
- return _this10.normalizeOrderForMemoryList(order, 'upsertPendingSyncOrders.existingMemory');
1464
+ return _this9.normalizeOrderForMemoryList(order, 'upsertPendingSyncOrders.existingMemory');
1157
1465
  }); // 与 mergeOrdersToStore 一致:基于身份键(field:value)建立索引,把「查找已存在订单」
1158
1466
  // 从 O(n) 线性扫描降为 O(1),整体复杂度由 O(n^2) 降为 O(n + m)。
1159
1467
  identityKeyToIndex = new Map();
@@ -1172,116 +1480,318 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1172
1480
  }
1173
1481
  }
1174
1482
  _iterator7 = _createForOfIteratorHelper(memoryPendingMap.entries());
1175
- _context11.prev = 35;
1483
+ _context12.prev = 37;
1176
1484
  _iterator7.s();
1177
- case 37:
1485
+ case 39:
1178
1486
  if ((_step7 = _iterator7.n()).done) {
1179
- _context11.next = 55;
1487
+ _context12.next = 58;
1180
1488
  break;
1181
1489
  }
1182
- _step7$value = _slicedToArray(_step7.value, 2), _storageKey = _step7$value[0], pendingOrder = _step7$value[1];
1183
- matchIndex = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, this.getOrderIdentityMatchKeys(pendingOrder));
1490
+ _step7$value = _slicedToArray(_step7.value, 2), _storageKey = _step7$value[0], _pendingOrder = _step7$value[1];
1491
+ matchIndex = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, this.getOrderIdentityMatchKeys(_pendingOrder));
1184
1492
  if (!(matchIndex >= 0)) {
1185
- _context11.next = 49;
1493
+ _context12.next = 52;
1186
1494
  break;
1187
1495
  }
1188
1496
  existingOrder = updatedList[matchIndex];
1189
- mergedOrder = this.mergeOrderRecords(existingOrder, pendingOrder);
1190
- updatedList[matchIndex] = mergedOrder;
1497
+ mergedOrder = this.mergeOrderRecords(existingOrder, _pendingOrder);
1498
+ nextOrder = _objectSpread(_objectSpread({}, mergedOrder), {}, {
1499
+ need_sync: 1,
1500
+ is_draft_order: 0
1501
+ });
1502
+ updatedList[matchIndex] = nextOrder;
1191
1503
  pendingSnapshot = pendingMap.get(_storageKey);
1192
1504
  if (pendingSnapshot) {
1193
1505
  pendingMap.set(_storageKey, this.reconcileOverwriteOrderCollections(existingOrder, pendingSnapshot));
1194
1506
  }
1195
1507
  // 合并后身份字段可能新增(如挂单拿到 order_id),同步登记,供同批后续 pending 命中同一槽位
1196
- this.registerOrderIdentityKeys(identityKeyToIndex, mergedOrder, matchIndex);
1508
+ this.registerOrderIdentityKeys(identityKeyToIndex, nextOrder, matchIndex);
1197
1509
  mergeActions[_storageKey] = 'update';
1198
- return _context11.abrupt("continue", 53);
1199
- case 49:
1510
+ return _context12.abrupt("continue", 56);
1511
+ case 52:
1200
1512
  insertIndex = updatedList.length;
1201
- updatedList.push(pendingOrder);
1202
- this.registerOrderIdentityKeys(identityKeyToIndex, pendingOrder, insertIndex);
1513
+ updatedList.push(_pendingOrder);
1514
+ this.registerOrderIdentityKeys(identityKeyToIndex, _pendingOrder, insertIndex);
1203
1515
  mergeActions[_storageKey] = 'insert';
1204
- case 53:
1205
- _context11.next = 37;
1516
+ case 56:
1517
+ _context12.next = 39;
1206
1518
  break;
1207
- case 55:
1208
- _context11.next = 60;
1519
+ case 58:
1520
+ _context12.next = 63;
1209
1521
  break;
1210
- case 57:
1211
- _context11.prev = 57;
1212
- _context11.t1 = _context11["catch"](35);
1213
- _iterator7.e(_context11.t1);
1214
1522
  case 60:
1215
- _context11.prev = 60;
1216
- _iterator7.f();
1217
- return _context11.finish(60);
1523
+ _context12.prev = 60;
1524
+ _context12.t1 = _context12["catch"](37);
1525
+ _iterator7.e(_context12.t1);
1218
1526
  case 63:
1527
+ _context12.prev = 63;
1528
+ _iterator7.f();
1529
+ return _context12.finish(63);
1530
+ case 66:
1219
1531
  patchedOrders = _toConsumableArray(pendingMap.values()); // 增量索引已保证 store 去重不变量,无需再对全表做 O(n^2) 压缩;仅自检开关开启时兜底。
1532
+ previousList = this.store.list;
1220
1533
  this.store.list = this.runOrderStoreSelfCheck(updatedList, 'upsertPendingSyncOrders.store');
1221
1534
  this.syncOrdersMap();
1222
- _context11.next = 68;
1223
- return this.patchOrdersInSQLite(patchedOrders, 'upsertPendingSyncOrders', mergeActions);
1224
- case 68:
1535
+ _context12.prev = 70;
1536
+ _context12.next = 73;
1537
+ return this.patchOrdersInSQLite(patchedOrders, 'upsertPendingSyncOrders', mergeActions, options);
1538
+ case 73:
1539
+ _context12.next = 80;
1540
+ break;
1541
+ case 75:
1542
+ _context12.prev = 75;
1543
+ _context12.t2 = _context12["catch"](70);
1544
+ this.store.list = previousList;
1545
+ this.syncOrdersMap();
1546
+ throw _context12.t2;
1547
+ case 80:
1225
1548
  this.logInfo('upsertPendingSyncOrders-结束', {
1226
1549
  count: patchedOrders.length,
1227
1550
  storeOrderCountAfter: this.store.list.length
1228
1551
  });
1229
- _context11.next = 71;
1552
+ _context12.next = 83;
1230
1553
  return this.emitOrdersChanged(patchedOrders, 'upsertPendingSyncOrders');
1231
- case 71:
1554
+ case 83:
1232
1555
  case "end":
1233
- return _context11.stop();
1556
+ return _context12.stop();
1234
1557
  }
1235
- }, _callee11, this, [[6, 20, 23, 26], [35, 57, 60, 63]]);
1558
+ }, _callee12, this, [[7, 22, 25, 28], [37, 60, 63, 66], [70, 75]]);
1236
1559
  }));
1237
- function upsertPendingSyncOrders(_x7) {
1560
+ function upsertPendingSyncOrders(_x9) {
1238
1561
  return _upsertPendingSyncOrders.apply(this, arguments);
1239
1562
  }
1240
1563
  return upsertPendingSyncOrders;
1241
1564
  }()
1242
1565
  /**
1243
- * 通过 SSE 按自定义 query 拉取订单(支持 select/with 精简字段)
1566
+ * POS 草稿订单按 SQLite storage key 落库。
1567
+ * 只有具备真实 order_id 的草稿进入 store;其余草稿仅供本地恢复查询。
1244
1568
  */
1245
1569
  )
1246
1570
  }, {
1247
- key: "fetchOrdersBySSE",
1571
+ key: "upsertLocalDraftOrders",
1248
1572
  value: (function () {
1249
- var _fetchOrdersBySSE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1250
- var query,
1251
- data,
1252
- _args12 = arguments;
1253
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1254
- while (1) switch (_context12.prev = _context12.next) {
1573
+ var _upsertLocalDraftOrders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(draftOrders) {
1574
+ var _this10 = this;
1575
+ var draftMap, memoryDraftMap, _iterator8, _step8, order, draftOrder, storageKey, memoryDraftOrder, mergeActions, updatedList, identityKeyToIndex, index, _iterator9, _step9, key, _iterator10, _step10, _step10$value, _storageKey2, _draftOrder, matchIndex, existingOrder, reconciledDraftOrder, mergedOrder, nextOrder, insertIndex, patchedOrders, previousList, removedLegacyMemoryDraft;
1576
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1577
+ while (1) switch (_context13.prev = _context13.next) {
1255
1578
  case 0:
1256
- query = _args12.length > 0 && _args12[0] !== undefined ? _args12[0] : {};
1257
- if (this.orderDataSource) {
1258
- _context12.next = 3;
1579
+ if (draftOrders !== null && draftOrders !== void 0 && draftOrders.length) {
1580
+ _context13.next = 3;
1259
1581
  break;
1260
1582
  }
1261
- return _context12.abrupt("return", []);
1583
+ this.logInfo('upsertLocalDraftOrders-订单列表为空', {});
1584
+ return _context13.abrupt("return");
1262
1585
  case 3:
1263
- _context12.prev = 3;
1264
- _context12.next = 6;
1265
- return this.orderDataSource.run({
1266
- sse: {
1267
- query: query
1268
- }
1269
- });
1586
+ draftMap = new Map();
1587
+ memoryDraftMap = new Map();
1588
+ _iterator8 = _createForOfIteratorHelper(draftOrders);
1589
+ _context13.prev = 6;
1590
+ _iterator8.s();
1591
+ case 8:
1592
+ if ((_step8 = _iterator8.n()).done) {
1593
+ _context13.next = 19;
1594
+ break;
1595
+ }
1596
+ order = _step8.value;
1597
+ draftOrder = _objectSpread(_objectSpread({}, order), {}, {
1598
+ need_sync: 0,
1599
+ is_draft_order: 1
1600
+ });
1601
+ storageKey = this.getOrderStorageKey(draftOrder);
1602
+ if (storageKey) {
1603
+ _context13.next = 14;
1604
+ break;
1605
+ }
1606
+ return _context13.abrupt("continue", 17);
1607
+ case 14:
1608
+ draftMap.set(storageKey, draftOrder);
1609
+ memoryDraftOrder = this.normalizeOrderForMemoryList(draftOrder);
1610
+ if (this.shouldKeepOrderInMemory(memoryDraftOrder)) {
1611
+ memoryDraftMap.set(storageKey, memoryDraftOrder);
1612
+ }
1613
+ case 17:
1614
+ _context13.next = 8;
1615
+ break;
1616
+ case 19:
1617
+ _context13.next = 24;
1618
+ break;
1619
+ case 21:
1620
+ _context13.prev = 21;
1621
+ _context13.t0 = _context13["catch"](6);
1622
+ _iterator8.e(_context13.t0);
1623
+ case 24:
1624
+ _context13.prev = 24;
1625
+ _iterator8.f();
1626
+ return _context13.finish(24);
1627
+ case 27:
1628
+ if (!(draftMap.size === 0)) {
1629
+ _context13.next = 30;
1630
+ break;
1631
+ }
1632
+ this.logError('upsertLocalDraftOrders-订单缺少可落库标识', {
1633
+ count: draftOrders.length
1634
+ });
1635
+ return _context13.abrupt("return");
1636
+ case 30:
1637
+ this.logInfo('upsertLocalDraftOrders-开始', {
1638
+ count: draftMap.size,
1639
+ memoryDraftCount: memoryDraftMap.size,
1640
+ sqliteOnlyDraftCount: draftMap.size - memoryDraftMap.size
1641
+ });
1642
+ mergeActions = {};
1643
+ updatedList = this.store.list.filter(function (order) {
1644
+ return _this10.shouldKeepOrderInMemory(order);
1645
+ });
1646
+ identityKeyToIndex = new Map();
1647
+ for (index = 0; index < updatedList.length; index += 1) {
1648
+ _iterator9 = _createForOfIteratorHelper(this.getOrderIdentityMatchKeys(updatedList[index]));
1649
+ try {
1650
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1651
+ key = _step9.value;
1652
+ if (!identityKeyToIndex.has(key)) identityKeyToIndex.set(key, index);
1653
+ }
1654
+ } catch (err) {
1655
+ _iterator9.e(err);
1656
+ } finally {
1657
+ _iterator9.f();
1658
+ }
1659
+ }
1660
+ _iterator10 = _createForOfIteratorHelper(memoryDraftMap.entries());
1661
+ _context13.prev = 36;
1662
+ _iterator10.s();
1663
+ case 38:
1664
+ if ((_step10 = _iterator10.n()).done) {
1665
+ _context13.next = 57;
1666
+ break;
1667
+ }
1668
+ _step10$value = _slicedToArray(_step10.value, 2), _storageKey2 = _step10$value[0], _draftOrder = _step10$value[1];
1669
+ matchIndex = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, this.getOrderIdentityMatchKeys(_draftOrder));
1670
+ if (!(matchIndex >= 0)) {
1671
+ _context13.next = 51;
1672
+ break;
1673
+ }
1674
+ existingOrder = updatedList[matchIndex];
1675
+ reconciledDraftOrder = this.preserveExistingBusinessCodeForDraft(existingOrder, _draftOrder);
1676
+ mergedOrder = this.mergeOrderRecords(existingOrder, reconciledDraftOrder);
1677
+ nextOrder = _objectSpread(_objectSpread({}, mergedOrder), {}, {
1678
+ need_sync: 0,
1679
+ is_draft_order: 1
1680
+ });
1681
+ updatedList[matchIndex] = nextOrder;
1682
+ // SQLite 必须与内存中的草稿保持同一份 business_code,避免下次 hydrate 再次丢失分类。
1683
+ draftMap.set(_storageKey2, reconciledDraftOrder);
1684
+ this.registerOrderIdentityKeys(identityKeyToIndex, nextOrder, matchIndex);
1685
+ mergeActions[_storageKey2] = 'update';
1686
+ return _context13.abrupt("continue", 55);
1687
+ case 51:
1688
+ insertIndex = updatedList.length;
1689
+ updatedList.push(_draftOrder);
1690
+ this.registerOrderIdentityKeys(identityKeyToIndex, _draftOrder, insertIndex);
1691
+ mergeActions[_storageKey2] = 'insert';
1692
+ case 55:
1693
+ _context13.next = 38;
1694
+ break;
1695
+ case 57:
1696
+ _context13.next = 62;
1697
+ break;
1698
+ case 59:
1699
+ _context13.prev = 59;
1700
+ _context13.t1 = _context13["catch"](36);
1701
+ _iterator10.e(_context13.t1);
1702
+ case 62:
1703
+ _context13.prev = 62;
1704
+ _iterator10.f();
1705
+ return _context13.finish(62);
1706
+ case 65:
1707
+ patchedOrders = _toConsumableArray(draftMap.values());
1708
+ previousList = this.store.list;
1709
+ this.store.list = this.runOrderStoreSelfCheck(updatedList, 'upsertLocalDraftOrders.store');
1710
+ this.syncOrdersMap();
1711
+ _context13.prev = 69;
1712
+ _context13.next = 72;
1713
+ return this.patchOrdersInSQLite(patchedOrders, 'upsertLocalDraftOrders', mergeActions, {
1714
+ throwOnError: true
1715
+ });
1716
+ case 72:
1717
+ _context13.next = 79;
1718
+ break;
1719
+ case 74:
1720
+ _context13.prev = 74;
1721
+ _context13.t2 = _context13["catch"](69);
1722
+ this.store.list = previousList;
1723
+ this.syncOrdersMap();
1724
+ throw _context13.t2;
1725
+ case 79:
1726
+ this.logInfo('upsertLocalDraftOrders-结束', {
1727
+ count: patchedOrders.length,
1728
+ storeOrderCountAfter: this.store.list.length
1729
+ });
1730
+ removedLegacyMemoryDraft = previousList.some(function (order) {
1731
+ return !_this10.shouldKeepOrderInMemory(order);
1732
+ });
1733
+ if (!(memoryDraftMap.size > 0 || removedLegacyMemoryDraft)) {
1734
+ _context13.next = 84;
1735
+ break;
1736
+ }
1737
+ _context13.next = 84;
1738
+ return this.emitOrdersChanged(patchedOrders.filter(function (order) {
1739
+ return _this10.shouldKeepOrderInMemory(order);
1740
+ }), 'upsertLocalDraftOrders');
1741
+ case 84:
1742
+ case "end":
1743
+ return _context13.stop();
1744
+ }
1745
+ }, _callee13, this, [[6, 21, 24, 27], [36, 59, 62, 65], [69, 74]]);
1746
+ }));
1747
+ function upsertLocalDraftOrders(_x10) {
1748
+ return _upsertLocalDraftOrders.apply(this, arguments);
1749
+ }
1750
+ return upsertLocalDraftOrders;
1751
+ }()
1752
+ /**
1753
+ * 通过 SSE 按自定义 query 拉取订单(支持 select/with 精简字段)
1754
+ */
1755
+ )
1756
+ }, {
1757
+ key: "fetchOrdersBySSE",
1758
+ value: (function () {
1759
+ var _fetchOrdersBySSE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
1760
+ var query,
1761
+ data,
1762
+ _args14 = arguments;
1763
+ return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1764
+ while (1) switch (_context14.prev = _context14.next) {
1765
+ case 0:
1766
+ query = _args14.length > 0 && _args14[0] !== undefined ? _args14[0] : {};
1767
+ if (this.orderDataSource) {
1768
+ _context14.next = 3;
1769
+ break;
1770
+ }
1771
+ return _context14.abrupt("return", []);
1772
+ case 3:
1773
+ _context14.prev = 3;
1774
+ _context14.next = 6;
1775
+ return this.orderDataSource.run({
1776
+ sse: {
1777
+ query: query
1778
+ }
1779
+ });
1270
1780
  case 6:
1271
- data = _context12.sent;
1272
- return _context12.abrupt("return", data || []);
1781
+ data = _context14.sent;
1782
+ return _context14.abrupt("return", data || []);
1273
1783
  case 10:
1274
- _context12.prev = 10;
1275
- _context12.t0 = _context12["catch"](3);
1784
+ _context14.prev = 10;
1785
+ _context14.t0 = _context14["catch"](3);
1276
1786
  this.logError('fetchOrdersBySSE-失败', {
1277
- error: _context12.t0 instanceof Error ? _context12.t0.message : String(_context12.t0)
1787
+ error: _context14.t0 instanceof Error ? _context14.t0.message : String(_context14.t0)
1278
1788
  });
1279
- return _context12.abrupt("return", []);
1789
+ return _context14.abrupt("return", []);
1280
1790
  case 14:
1281
1791
  case "end":
1282
- return _context12.stop();
1792
+ return _context14.stop();
1283
1793
  }
1284
- }, _callee12, this, [[3, 10]]);
1794
+ }, _callee14, this, [[3, 10]]);
1285
1795
  }));
1286
1796
  function fetchOrdersBySSE() {
1287
1797
  return _fetchOrdersBySSE.apply(this, arguments);
@@ -1309,20 +1819,24 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1309
1819
  }, {
1310
1820
  key: "syncOrdersMap",
1311
1821
  value: function syncOrdersMap() {
1822
+ var _this11 = this;
1823
+ this.store.list = this.store.list.filter(function (order) {
1824
+ return _this11.shouldKeepOrderInMemory(order);
1825
+ });
1312
1826
  this.store.map.clear();
1313
- var _iterator8 = _createForOfIteratorHelper(this.store.list),
1314
- _step8;
1827
+ var _iterator11 = _createForOfIteratorHelper(this.store.list),
1828
+ _step11;
1315
1829
  try {
1316
- for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1317
- var order = _step8.value;
1830
+ for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
1831
+ var order = _step11.value;
1318
1832
  var primaryIdentity = this.getOrderMapKey(order);
1319
1833
  if (!primaryIdentity) continue;
1320
1834
  this.store.map.set(primaryIdentity, order);
1321
1835
  }
1322
1836
  } catch (err) {
1323
- _iterator8.e(err);
1837
+ _iterator11.e(err);
1324
1838
  } finally {
1325
- _iterator8.f();
1839
+ _iterator11.f();
1326
1840
  }
1327
1841
  }
1328
1842
  }, {
@@ -1343,10 +1857,27 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1343
1857
  value: function isBlankIdentityValue(value) {
1344
1858
  return value === undefined || value === null || value === '';
1345
1859
  }
1860
+
1861
+ /**
1862
+ * `/sales/draft` 的旧调用方可能把未设置的 business_code 传成空串。
1863
+ * 对同一真实订单,空值不能覆盖已有的分类,否则 booking 查询会把该订单从 Party 列表过滤掉。
1864
+ */
1865
+ }, {
1866
+ key: "preserveExistingBusinessCodeForDraft",
1867
+ value: function preserveExistingBusinessCodeForDraft(existingOrder, draftOrder) {
1868
+ var existingBusinessCode = existingOrder.business_code;
1869
+ var draftBusinessCode = draftOrder.business_code;
1870
+ var hasExistingBusinessCode = typeof existingBusinessCode === 'string' && existingBusinessCode.trim() !== '';
1871
+ var hasDraftBusinessCode = typeof draftBusinessCode === 'string' && draftBusinessCode.trim() !== '';
1872
+ if (!hasExistingBusinessCode || hasDraftBusinessCode) return draftOrder;
1873
+ return _objectSpread(_objectSpread({}, draftOrder), {}, {
1874
+ business_code: existingBusinessCode
1875
+ });
1876
+ }
1346
1877
  }, {
1347
1878
  key: "getOrderIdentityEntries",
1348
1879
  value: function getOrderIdentityEntries(order) {
1349
- var _this11 = this;
1880
+ var _this12 = this;
1350
1881
  if (!order) return [];
1351
1882
  var record = order;
1352
1883
  var candidates = [{
@@ -1365,8 +1896,8 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1365
1896
  var entries = [];
1366
1897
  var _loop = function _loop() {
1367
1898
  var candidate = _candidates[_i2];
1368
- if (_this11.isBlankIdentityValue(candidate.value)) return 0; // continue
1369
- var key = _this11.getIdKey(candidate.value);
1899
+ if (_this12.isBlankIdentityValue(candidate.value)) return 0; // continue
1900
+ var key = _this12.getIdKey(candidate.value);
1370
1901
  if (entries.some(function (entry) {
1371
1902
  return entry.field === candidate.field && entry.key === key;
1372
1903
  })) return 0; // continue
@@ -1386,17 +1917,17 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1386
1917
  key: "getOrderIdentityKeys",
1387
1918
  value: function getOrderIdentityKeys(order) {
1388
1919
  var keys = [];
1389
- var _iterator9 = _createForOfIteratorHelper(this.getOrderIdentityEntries(order)),
1390
- _step9;
1920
+ var _iterator12 = _createForOfIteratorHelper(this.getOrderIdentityEntries(order)),
1921
+ _step12;
1391
1922
  try {
1392
- for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1393
- var entry = _step9.value;
1923
+ for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
1924
+ var entry = _step12.value;
1394
1925
  if (!keys.includes(entry.key)) keys.push(entry.key);
1395
1926
  }
1396
1927
  } catch (err) {
1397
- _iterator9.e(err);
1928
+ _iterator12.e(err);
1398
1929
  } finally {
1399
- _iterator9.f();
1930
+ _iterator12.f();
1400
1931
  }
1401
1932
  return keys;
1402
1933
  }
@@ -1433,7 +1964,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1433
1964
  }, {
1434
1965
  key: "setupOrderSync",
1435
1966
  value: function setupOrderSync() {
1436
- var _this12 = this;
1967
+ var _this13 = this;
1437
1968
  if (!this.orderDataSource) return;
1438
1969
  this.orderDataSource.run({
1439
1970
  pubsub: {
@@ -1441,22 +1972,22 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1441
1972
  var _message$id, _message$order_id, _message$type;
1442
1973
  console.log('orderDataSource', res);
1443
1974
  var pubsubReceivedAt = Date.now();
1444
- var message = _this12.normalizeOrderSyncMessage(res);
1975
+ var message = _this13.normalizeOrderSyncMessage(res);
1445
1976
  if (!message) return;
1446
1977
  message._pubsubReceivedAt = pubsubReceivedAt;
1447
- _this12.pendingSyncMessages.push(message);
1448
- var throttleMs = _this12.getOrderSyncThrottleMs();
1449
- var routeInfo = _this12.resolveSyncMessageRoute(message);
1450
- _this12.logInfo('orderSync-收到消息并入队', {
1978
+ _this13.pendingSyncMessages.push(message);
1979
+ var throttleMs = _this13.getOrderSyncThrottleMs();
1980
+ var routeInfo = _this13.resolveSyncMessageRoute(message);
1981
+ _this13.logInfo('orderSync-收到消息并入队', {
1451
1982
  id: (_message$id = message.id) !== null && _message$id !== void 0 ? _message$id : null,
1452
1983
  order_id: (_message$order_id = message.order_id) !== null && _message$order_id !== void 0 ? _message$order_id : null,
1453
1984
  type: (_message$type = message.type) !== null && _message$type !== void 0 ? _message$type : null,
1454
- pendingCount: _this12.pendingSyncMessages.length,
1985
+ pendingCount: _this13.pendingSyncMessages.length,
1455
1986
  throttleMs: throttleMs,
1456
1987
  pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString(),
1457
1988
  fullMessage: JSON.stringify(message)
1458
1989
  });
1459
- _this12.scheduleOrderSyncThrottle();
1990
+ _this13.scheduleOrderSyncThrottle();
1460
1991
  }
1461
1992
  }
1462
1993
  }).catch(function () {
@@ -1473,7 +2004,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1473
2004
  }, {
1474
2005
  key: "scheduleOrderSyncThrottle",
1475
2006
  value: function scheduleOrderSyncThrottle() {
1476
- var _this13 = this;
2007
+ var _this14 = this;
1477
2008
  if (this.isProcessingSyncBatch) return;
1478
2009
  if (this.isIdlePhase) {
1479
2010
  this.isIdlePhase = false;
@@ -1484,8 +2015,8 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1484
2015
  if (this.syncTimer) return;
1485
2016
  var throttleMs = this.getOrderSyncThrottleMs();
1486
2017
  this.syncTimer = setTimeout(function () {
1487
- _this13.syncTimer = undefined;
1488
- void _this13.flushOrderSyncMessagesByThrottle();
2018
+ _this14.syncTimer = undefined;
2019
+ void _this14.flushOrderSyncMessagesByThrottle();
1489
2020
  }, throttleMs);
1490
2021
  }
1491
2022
 
@@ -1496,41 +2027,41 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1496
2027
  }, {
1497
2028
  key: "flushOrderSyncMessagesByThrottle",
1498
2029
  value: (function () {
1499
- var _flushOrderSyncMessagesByThrottle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
1500
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1501
- while (1) switch (_context13.prev = _context13.next) {
2030
+ var _flushOrderSyncMessagesByThrottle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15() {
2031
+ return _regeneratorRuntime().wrap(function _callee15$(_context15) {
2032
+ while (1) switch (_context15.prev = _context15.next) {
1502
2033
  case 0:
1503
2034
  if (!this.isProcessingSyncBatch) {
1504
- _context13.next = 2;
2035
+ _context15.next = 2;
1505
2036
  break;
1506
2037
  }
1507
- return _context13.abrupt("return");
2038
+ return _context15.abrupt("return");
1508
2039
  case 2:
1509
2040
  if (!(this.pendingSyncMessages.length === 0)) {
1510
- _context13.next = 5;
2041
+ _context15.next = 5;
1511
2042
  break;
1512
2043
  }
1513
2044
  this.isIdlePhase = true;
1514
- return _context13.abrupt("return");
2045
+ return _context15.abrupt("return");
1515
2046
  case 5:
1516
2047
  this.isProcessingSyncBatch = true;
1517
- _context13.prev = 6;
1518
- _context13.next = 9;
2048
+ _context15.prev = 6;
2049
+ _context15.next = 9;
1519
2050
  return this.processOrderSyncMessages();
1520
2051
  case 9:
1521
- _context13.prev = 9;
2052
+ _context15.prev = 9;
1522
2053
  this.isProcessingSyncBatch = false;
1523
2054
  if (this.pendingSyncMessages.length > 0) {
1524
2055
  this.scheduleOrderSyncThrottle();
1525
2056
  } else {
1526
2057
  this.isIdlePhase = true;
1527
2058
  }
1528
- return _context13.finish(9);
2059
+ return _context15.finish(9);
1529
2060
  case 13:
1530
2061
  case "end":
1531
- return _context13.stop();
2062
+ return _context15.stop();
1532
2063
  }
1533
- }, _callee13, this, [[6,, 9, 13]]);
2064
+ }, _callee15, this, [[6,, 9, 13]]);
1534
2065
  }));
1535
2066
  function flushOrderSyncMessagesByThrottle() {
1536
2067
  return _flushOrderSyncMessagesByThrottle.apply(this, arguments);
@@ -1552,19 +2083,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1552
2083
  }, {
1553
2084
  key: "processOrderSyncMessages",
1554
2085
  value: (function () {
1555
- var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
1556
- var _this14 = this;
2086
+ var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16() {
2087
+ var _this15 = this;
1557
2088
  var messages, batchProcessStartAt, earliestReceivedAt, upsertOrders, refreshIds, uniqueRefreshIds, upsertList, _this$filterRedundant, toFetch, skipped, freshOrders, batchProcessEndAt;
1558
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1559
- while (1) switch (_context14.prev = _context14.next) {
2089
+ return _regeneratorRuntime().wrap(function _callee16$(_context16) {
2090
+ while (1) switch (_context16.prev = _context16.next) {
1560
2091
  case 0:
1561
2092
  messages = _toConsumableArray(this.pendingSyncMessages);
1562
2093
  this.pendingSyncMessages = [];
1563
2094
  if (!(messages.length === 0)) {
1564
- _context14.next = 4;
2095
+ _context16.next = 4;
1565
2096
  break;
1566
2097
  }
1567
- return _context14.abrupt("return");
2098
+ return _context16.abrupt("return");
1568
2099
  case 4:
1569
2100
  batchProcessStartAt = Date.now();
1570
2101
  earliestReceivedAt = Math.min.apply(Math, _toConsumableArray(messages.map(function (m) {
@@ -1580,13 +2111,13 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1580
2111
  upsertOrders = new Map();
1581
2112
  refreshIds = [];
1582
2113
  messages.forEach(function (msg, msgIndex) {
1583
- var routeInfo = _this14.resolveSyncMessageRoute(msg);
2114
+ var routeInfo = _this15.resolveSyncMessageRoute(msg);
1584
2115
  var hasBatchIds = routeInfo.hasBatchIds;
1585
2116
  var singleId = routeInfo.singleId;
1586
2117
  var hasSingleId = routeInfo.hasSingleId;
1587
- var normalizedBody = _this14.normalizeOrderSyncPayload(msg.body || msg.data);
2118
+ var normalizedBody = _this15.normalizeOrderSyncPayload(msg.body || msg.data);
1588
2119
  if (routeInfo.route === 'bodyUpsert' && normalizedBody) {
1589
- upsertOrders.set(_this14.getIdKey(normalizedBody.order_id), normalizedBody);
2120
+ upsertOrders.set(_this15.getIdKey(normalizedBody.order_id), normalizedBody);
1590
2121
  return;
1591
2122
  }
1592
2123
  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));
@@ -1598,41 +2129,41 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1598
2129
  refreshIdCount: uniqueRefreshIds.length
1599
2130
  });
1600
2131
  if (!(upsertList.length > 0)) {
1601
- _context14.next = 16;
2132
+ _context16.next = 16;
1602
2133
  break;
1603
2134
  }
1604
- _context14.next = 16;
2135
+ _context16.next = 16;
1605
2136
  return this.mergeOrdersToStore(upsertList, 'pubsub.bodyUpsert');
1606
2137
  case 16:
1607
2138
  if (!(uniqueRefreshIds.length > 0)) {
1608
- _context14.next = 28;
2139
+ _context16.next = 28;
1609
2140
  break;
1610
2141
  }
1611
2142
  _this$filterRedundant = this.filterRedundantHttpRefreshIds(uniqueRefreshIds), toFetch = _this$filterRedundant.toFetch, skipped = _this$filterRedundant.skipped;
1612
2143
  if (skipped.length > 0) {}
1613
2144
  if (!(toFetch.length > 0)) {
1614
- _context14.next = 28;
2145
+ _context16.next = 28;
1615
2146
  break;
1616
2147
  }
1617
- _context14.next = 22;
2148
+ _context16.next = 22;
1618
2149
  return this.fetchOrdersByHttp(toFetch);
1619
2150
  case 22:
1620
- freshOrders = _context14.sent;
2151
+ freshOrders = _context16.sent;
1621
2152
  if (!(freshOrders.length > 0)) {
1622
- _context14.next = 28;
2153
+ _context16.next = 28;
1623
2154
  break;
1624
2155
  }
1625
- _context14.next = 26;
2156
+ _context16.next = 26;
1626
2157
  return this.mergeOrdersToStore(freshOrders, 'pubsub.httpRefresh');
1627
2158
  case 26:
1628
- _context14.next = 28;
2159
+ _context16.next = 28;
1629
2160
  break;
1630
2161
  case 28:
1631
2162
  if (!(upsertList.length === 0 && uniqueRefreshIds.length === 0)) {
1632
- _context14.next = 30;
2163
+ _context16.next = 30;
1633
2164
  break;
1634
2165
  }
1635
- return _context14.abrupt("return");
2166
+ return _context16.abrupt("return");
1636
2167
  case 30:
1637
2168
  batchProcessEndAt = Date.now();
1638
2169
  this.logInfo('processOrderSyncMessages-结束', {
@@ -1641,13 +2172,13 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1641
2172
  batchProcessDurationMs: batchProcessEndAt - batchProcessStartAt,
1642
2173
  totalFromPubsubToProcessedMs: batchProcessEndAt - earliestReceivedAt
1643
2174
  });
1644
- _context14.next = 34;
2175
+ _context16.next = 34;
1645
2176
  return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
1646
2177
  case 34:
1647
2178
  case "end":
1648
- return _context14.stop();
2179
+ return _context16.stop();
1649
2180
  }
1650
- }, _callee14, this);
2181
+ }, _callee16, this);
1651
2182
  }));
1652
2183
  function processOrderSyncMessages() {
1653
2184
  return _processOrderSyncMessages.apply(this, arguments);
@@ -1668,29 +2199,29 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1668
2199
  }, {
1669
2200
  key: "fetchOrdersByHttp",
1670
2201
  value: (function () {
1671
- var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(ids) {
2202
+ var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(ids) {
1672
2203
  var _orderList, orderList;
1673
- return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1674
- while (1) switch (_context15.prev = _context15.next) {
2204
+ return _regeneratorRuntime().wrap(function _callee17$(_context17) {
2205
+ while (1) switch (_context17.prev = _context17.next) {
1675
2206
  case 0:
1676
2207
  if (!(!this.orderDataSource || ids.length === 0)) {
1677
- _context15.next = 2;
2208
+ _context17.next = 2;
1678
2209
  break;
1679
2210
  }
1680
- return _context15.abrupt("return", []);
2211
+ return _context17.abrupt("return", []);
1681
2212
  case 2:
1682
- _context15.prev = 2;
2213
+ _context17.prev = 2;
1683
2214
  if (!(typeof this.orderDataSource.fetchOrdersByIds === 'function')) {
1684
- _context15.next = 8;
2215
+ _context17.next = 8;
1685
2216
  break;
1686
2217
  }
1687
- _context15.next = 6;
2218
+ _context17.next = 6;
1688
2219
  return this.orderDataSource.fetchOrdersByIds(ids);
1689
2220
  case 6:
1690
- _orderList = _context15.sent;
1691
- return _context15.abrupt("return", _orderList || []);
2221
+ _orderList = _context17.sent;
2222
+ return _context17.abrupt("return", _orderList || []);
1692
2223
  case 8:
1693
- _context15.next = 10;
2224
+ _context17.next = 10;
1694
2225
  return this.orderDataSource.run({
1695
2226
  http: {
1696
2227
  query: {
@@ -1699,19 +2230,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1699
2230
  }
1700
2231
  });
1701
2232
  case 10:
1702
- orderList = _context15.sent;
1703
- return _context15.abrupt("return", orderList || []);
2233
+ orderList = _context17.sent;
2234
+ return _context17.abrupt("return", orderList || []);
1704
2235
  case 14:
1705
- _context15.prev = 14;
1706
- _context15.t0 = _context15["catch"](2);
1707
- return _context15.abrupt("return", []);
2236
+ _context17.prev = 14;
2237
+ _context17.t0 = _context17["catch"](2);
2238
+ return _context17.abrupt("return", []);
1708
2239
  case 17:
1709
2240
  case "end":
1710
- return _context15.stop();
2241
+ return _context17.stop();
1711
2242
  }
1712
- }, _callee15, this, [[2, 14]]);
2243
+ }, _callee17, this, [[2, 14]]);
1713
2244
  }));
1714
- function fetchOrdersByHttp(_x8) {
2245
+ function fetchOrdersByHttp(_x11) {
1715
2246
  return _fetchOrdersByHttp.apply(this, arguments);
1716
2247
  }
1717
2248
  return fetchOrdersByHttp;
@@ -1723,11 +2254,11 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1723
2254
  }, {
1724
2255
  key: "mergeOrdersToStore",
1725
2256
  value: (function () {
1726
- var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(freshOrders, source) {
1727
- var _this15 = this;
1728
- var storeOrderCountBefore, normalizedFreshOrders, _iterator10, _step10, order, id, uniqueFreshOrders, uniqueFreshCount, patchedOrders, mergeActions, updatedList, identityKeyToIndex, index, identityKeys, _iterator11, _step11, key, _iterator12, _step12, fresh, freshIdentityKeys, matchIndex, storageKey, mergeKey, existingOrder, _ref2, _existingOrder$order_, _ref3, _external_sale_number2, _existingOrder$paymen, _fresh$payment_status, _existingOrder$need_s, _fresh$need_sync, mergedOrder, insertIndex, insertCount, updateCount;
1729
- return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1730
- while (1) switch (_context16.prev = _context16.next) {
2257
+ var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(freshOrders, source) {
2258
+ var _this16 = this;
2259
+ var storeOrderCountBefore, normalizedFreshOrders, _iterator13, _step13, order, id, uniqueFreshOrders, uniqueFreshCount, patchedOrders, mergeActions, updatedList, identityKeyToIndex, index, identityKeys, _iterator14, _step14, key, _iterator15, _step15, fresh, freshIdentityKeys, matchIndex, storageKey, mergeKey, existingOrder, _ref, _existingOrder$order_, _ref2, _external_sale_number2, _existingOrder$paymen, _fresh$payment_status, _existingOrder$need_s, _fresh$need_sync, _ref3, _existingOrder$order_2, _ref4, _external_sale_number3, _existingOrder$is_dra, _fresh$is_draft_order, mergedOrder, adjustedMatchIndex, duplicateIndexes, _iterator16, _step16, _key2, _duplicateIndex, _iterator17, _step17, duplicateIndex, _index, _iterator18, _step18, _key, insertIndex, insertCount, updateCount;
2260
+ return _regeneratorRuntime().wrap(function _callee18$(_context18) {
2261
+ while (1) switch (_context18.prev = _context18.next) {
1731
2262
  case 0:
1732
2263
  storeOrderCountBefore = this.store.list.length;
1733
2264
  this.logInfo('mergeOrdersToStore-开始', {
@@ -1737,37 +2268,37 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1737
2268
  });
1738
2269
  this.logDuplicateOrders("".concat(source, ".beforeMerge"), this.store.list);
1739
2270
  normalizedFreshOrders = [];
1740
- _iterator10 = _createForOfIteratorHelper(freshOrders);
1741
- _context16.prev = 5;
1742
- _iterator10.s();
2271
+ _iterator13 = _createForOfIteratorHelper(freshOrders);
2272
+ _context18.prev = 5;
2273
+ _iterator13.s();
1743
2274
  case 7:
1744
- if ((_step10 = _iterator10.n()).done) {
1745
- _context16.next = 15;
2275
+ if ((_step13 = _iterator13.n()).done) {
2276
+ _context18.next = 15;
1746
2277
  break;
1747
2278
  }
1748
- order = _step10.value;
2279
+ order = _step13.value;
1749
2280
  id = order === null || order === void 0 ? void 0 : order.order_id;
1750
2281
  if (!(id === undefined || id === null)) {
1751
- _context16.next = 12;
2282
+ _context18.next = 12;
1752
2283
  break;
1753
2284
  }
1754
- return _context16.abrupt("continue", 13);
2285
+ return _context18.abrupt("continue", 13);
1755
2286
  case 12:
1756
2287
  normalizedFreshOrders.push(this.normalizeRemoteSyncedOrder(order));
1757
2288
  case 13:
1758
- _context16.next = 7;
2289
+ _context18.next = 7;
1759
2290
  break;
1760
2291
  case 15:
1761
- _context16.next = 20;
2292
+ _context18.next = 20;
1762
2293
  break;
1763
2294
  case 17:
1764
- _context16.prev = 17;
1765
- _context16.t0 = _context16["catch"](5);
1766
- _iterator10.e(_context16.t0);
2295
+ _context18.prev = 17;
2296
+ _context18.t0 = _context18["catch"](5);
2297
+ _iterator13.e(_context18.t0);
1767
2298
  case 20:
1768
- _context16.prev = 20;
1769
- _iterator10.f();
1770
- return _context16.finish(20);
2299
+ _context18.prev = 20;
2300
+ _iterator13.f();
2301
+ return _context18.finish(20);
1771
2302
  case 23:
1772
2303
  // 先对本批新单做去重(批内规模 m 很小),保证每条 fresh 身份唯一
1773
2304
  uniqueFreshOrders = this.compactOrderListByIdentity(normalizedFreshOrders, "".concat(source, ".incoming")).list;
@@ -1775,89 +2306,168 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1775
2306
  patchedOrders = [];
1776
2307
  mergeActions = {};
1777
2308
  updatedList = this.store.list.map(function (order) {
1778
- return _this15.normalizeOrderForMemoryList(order, "".concat(source, ".existingMemory"));
2309
+ return _this16.normalizeOrderForMemoryList(order, "".concat(source, ".existingMemory"));
1779
2310
  }); // 基于身份键(field:value)建立索引,把「查找已存在订单」从 O(n) 线性扫描降为 O(1),
1780
2311
  // 整体合并复杂度由 O(n^2) 降为 O(n + m)。索引语义与 doOrdersShareIdentity 完全一致:
1781
2312
  // 任一身份字段(order_id/external_sale_number/order_number/shop_order_number)同值即同一单。
1782
2313
  identityKeyToIndex = new Map();
1783
2314
  for (index = 0; index < updatedList.length; index += 1) {
1784
2315
  identityKeys = this.getOrderIdentityMatchKeys(updatedList[index]);
1785
- _iterator11 = _createForOfIteratorHelper(identityKeys);
2316
+ _iterator14 = _createForOfIteratorHelper(identityKeys);
1786
2317
  try {
1787
- for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
1788
- key = _step11.value;
2318
+ for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
2319
+ key = _step14.value;
1789
2320
  // 同一 key 命中多张时保留最靠前的下标,与原 findIndex「取首个匹配」一致
1790
2321
  if (!identityKeyToIndex.has(key)) identityKeyToIndex.set(key, index);
1791
2322
  }
1792
2323
  } catch (err) {
1793
- _iterator11.e(err);
2324
+ _iterator14.e(err);
1794
2325
  } finally {
1795
- _iterator11.f();
2326
+ _iterator14.f();
1796
2327
  }
1797
2328
  }
1798
- _iterator12 = _createForOfIteratorHelper(uniqueFreshOrders);
1799
- _context16.prev = 31;
1800
- _iterator12.s();
2329
+ _iterator15 = _createForOfIteratorHelper(uniqueFreshOrders);
2330
+ _context18.prev = 31;
2331
+ _iterator15.s();
1801
2332
  case 33:
1802
- if ((_step12 = _iterator12.n()).done) {
1803
- _context16.next = 57;
2333
+ if ((_step15 = _iterator15.n()).done) {
2334
+ _context18.next = 82;
1804
2335
  break;
1805
2336
  }
1806
- fresh = _step12.value;
2337
+ fresh = _step15.value;
1807
2338
  freshIdentityKeys = this.getOrderIdentityMatchKeys(fresh);
1808
2339
  matchIndex = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, freshIdentityKeys);
1809
2340
  storageKey = this.getOrderStorageKey(fresh);
1810
2341
  mergeKey = storageKey || (fresh.order_id !== undefined && fresh.order_id !== null ? this.getIdKey(fresh.order_id) : '');
1811
2342
  if (!(matchIndex >= 0)) {
1812
- _context16.next = 50;
2343
+ _context18.next = 75;
1813
2344
  break;
1814
2345
  }
1815
2346
  existingOrder = updatedList[matchIndex];
1816
2347
  if (!(this.isPendingSyncOrder(existingOrder) && this.isRemoteEchoMergeSource(source))) {
1817
- _context16.next = 44;
2348
+ _context18.next = 44;
1818
2349
  break;
1819
2350
  }
1820
2351
  this.logInfo('mergeOrdersToStore-跳过 pending 订单远端覆盖', {
1821
2352
  source: source,
1822
- order_id: (_ref2 = (_existingOrder$order_ = existingOrder.order_id) !== null && _existingOrder$order_ !== void 0 ? _existingOrder$order_ : fresh.order_id) !== null && _ref2 !== void 0 ? _ref2 : null,
1823
- external_sale_number: (_ref3 = (_external_sale_number2 = existingOrder.external_sale_number) !== null && _external_sale_number2 !== void 0 ? _external_sale_number2 : fresh.external_sale_number) !== null && _ref3 !== void 0 ? _ref3 : null,
2353
+ order_id: (_ref = (_existingOrder$order_ = existingOrder.order_id) !== null && _existingOrder$order_ !== void 0 ? _existingOrder$order_ : fresh.order_id) !== null && _ref !== void 0 ? _ref : null,
2354
+ external_sale_number: (_ref2 = (_external_sale_number2 = existingOrder.external_sale_number) !== null && _external_sale_number2 !== void 0 ? _external_sale_number2 : fresh.external_sale_number) !== null && _ref2 !== void 0 ? _ref2 : null,
1824
2355
  local_payment_status: (_existingOrder$paymen = existingOrder.payment_status) !== null && _existingOrder$paymen !== void 0 ? _existingOrder$paymen : null,
1825
2356
  remote_payment_status: (_fresh$payment_status = fresh.payment_status) !== null && _fresh$payment_status !== void 0 ? _fresh$payment_status : null,
1826
2357
  local_need_sync: (_existingOrder$need_s = existingOrder.need_sync) !== null && _existingOrder$need_s !== void 0 ? _existingOrder$need_s : null,
1827
2358
  remote_need_sync: (_fresh$need_sync = fresh.need_sync) !== null && _fresh$need_sync !== void 0 ? _fresh$need_sync : null,
1828
2359
  reason: 'protect_pending_sync_order_from_remote_echo'
1829
2360
  });
1830
- return _context16.abrupt("continue", 55);
2361
+ return _context18.abrupt("continue", 80);
1831
2362
  case 44:
2363
+ if (!(this.isDraftOrder(existingOrder) && this.shouldProtectDraftOrderFromIncoming(source))) {
2364
+ _context18.next = 47;
2365
+ break;
2366
+ }
2367
+ this.logInfo('mergeOrdersToStore-跳过 draft 订单远端覆盖', {
2368
+ source: source,
2369
+ order_id: (_ref3 = (_existingOrder$order_2 = existingOrder.order_id) !== null && _existingOrder$order_2 !== void 0 ? _existingOrder$order_2 : fresh.order_id) !== null && _ref3 !== void 0 ? _ref3 : null,
2370
+ external_sale_number: (_ref4 = (_external_sale_number3 = existingOrder.external_sale_number) !== null && _external_sale_number3 !== void 0 ? _external_sale_number3 : fresh.external_sale_number) !== null && _ref4 !== void 0 ? _ref4 : null,
2371
+ local_is_draft_order: (_existingOrder$is_dra = existingOrder.is_draft_order) !== null && _existingOrder$is_dra !== void 0 ? _existingOrder$is_dra : null,
2372
+ remote_is_draft_order: (_fresh$is_draft_order = fresh.is_draft_order) !== null && _fresh$is_draft_order !== void 0 ? _fresh$is_draft_order : null,
2373
+ reason: 'protect_draft_order_from_remote_echo'
2374
+ });
2375
+ return _context18.abrupt("continue", 80);
2376
+ case 47:
1832
2377
  mergedOrder = this.mergeOrderRecords(existingOrder, fresh);
1833
- updatedList[matchIndex] = mergedOrder;
2378
+ adjustedMatchIndex = matchIndex;
2379
+ duplicateIndexes = new Set();
2380
+ _iterator16 = _createForOfIteratorHelper(freshIdentityKeys);
2381
+ _context18.prev = 51;
2382
+ _iterator16.s();
2383
+ case 53:
2384
+ if ((_step16 = _iterator16.n()).done) {
2385
+ _context18.next = 61;
2386
+ break;
2387
+ }
2388
+ _key2 = _step16.value;
2389
+ _duplicateIndex = identityKeyToIndex.get(_key2);
2390
+ if (!(_duplicateIndex === undefined || _duplicateIndex === matchIndex)) {
2391
+ _context18.next = 58;
2392
+ break;
2393
+ }
2394
+ return _context18.abrupt("continue", 59);
2395
+ case 58:
2396
+ duplicateIndexes.add(_duplicateIndex);
2397
+ case 59:
2398
+ _context18.next = 53;
2399
+ break;
2400
+ case 61:
2401
+ _context18.next = 66;
2402
+ break;
2403
+ case 63:
2404
+ _context18.prev = 63;
2405
+ _context18.t1 = _context18["catch"](51);
2406
+ _iterator16.e(_context18.t1);
2407
+ case 66:
2408
+ _context18.prev = 66;
2409
+ _iterator16.f();
2410
+ return _context18.finish(66);
2411
+ case 69:
2412
+ if (duplicateIndexes.size > 0) {
2413
+ _iterator17 = _createForOfIteratorHelper(_toConsumableArray(duplicateIndexes).sort(function (left, right) {
2414
+ return right - left;
2415
+ }));
2416
+ try {
2417
+ for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
2418
+ duplicateIndex = _step17.value;
2419
+ mergedOrder = this.mergeOrderRecords(mergedOrder, updatedList[duplicateIndex]);
2420
+ updatedList.splice(duplicateIndex, 1);
2421
+ if (duplicateIndex < adjustedMatchIndex) adjustedMatchIndex -= 1;
2422
+ }
2423
+ } catch (err) {
2424
+ _iterator17.e(err);
2425
+ } finally {
2426
+ _iterator17.f();
2427
+ }
2428
+ identityKeyToIndex.clear();
2429
+ for (_index = 0; _index < updatedList.length; _index += 1) {
2430
+ _iterator18 = _createForOfIteratorHelper(this.getOrderIdentityMatchKeys(updatedList[_index]));
2431
+ try {
2432
+ for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
2433
+ _key = _step18.value;
2434
+ if (!identityKeyToIndex.has(_key)) identityKeyToIndex.set(_key, _index);
2435
+ }
2436
+ } catch (err) {
2437
+ _iterator18.e(err);
2438
+ } finally {
2439
+ _iterator18.f();
2440
+ }
2441
+ }
2442
+ }
2443
+ updatedList[adjustedMatchIndex] = mergedOrder;
1834
2444
  // 合并后身份字段可能新增(如挂单拿到 order_id),同步登记到索引,
1835
2445
  // 供同批后续 fresh 命中同一槽位,避免重复插入
1836
- this.registerOrderIdentityKeys(identityKeyToIndex, mergedOrder, matchIndex);
2446
+ this.registerOrderIdentityKeys(identityKeyToIndex, mergedOrder, adjustedMatchIndex);
1837
2447
  patchedOrders.push(mergedOrder);
1838
2448
  if (mergeKey) mergeActions[mergeKey] = 'update';
1839
- return _context16.abrupt("continue", 55);
1840
- case 50:
2449
+ return _context18.abrupt("continue", 80);
2450
+ case 75:
1841
2451
  insertIndex = updatedList.length;
1842
2452
  updatedList.push(fresh);
1843
2453
  this.registerOrderIdentityKeys(identityKeyToIndex, fresh, insertIndex);
1844
2454
  patchedOrders.push(fresh);
1845
2455
  if (mergeKey) mergeActions[mergeKey] = 'insert';
1846
- case 55:
1847
- _context16.next = 33;
2456
+ case 80:
2457
+ _context18.next = 33;
1848
2458
  break;
1849
- case 57:
1850
- _context16.next = 62;
2459
+ case 82:
2460
+ _context18.next = 87;
1851
2461
  break;
1852
- case 59:
1853
- _context16.prev = 59;
1854
- _context16.t1 = _context16["catch"](31);
1855
- _iterator12.e(_context16.t1);
1856
- case 62:
1857
- _context16.prev = 62;
1858
- _iterator12.f();
1859
- return _context16.finish(62);
1860
- case 65:
2462
+ case 84:
2463
+ _context18.prev = 84;
2464
+ _context18.t2 = _context18["catch"](31);
2465
+ _iterator15.e(_context18.t2);
2466
+ case 87:
2467
+ _context18.prev = 87;
2468
+ _iterator15.f();
2469
+ return _context18.finish(87);
2470
+ case 90:
1861
2471
  insertCount = Object.values(mergeActions).filter(function (v) {
1862
2472
  return v === 'insert';
1863
2473
  }).length;
@@ -1873,24 +2483,24 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1873
2483
  // 仅在自检开关开启时做一次兜底校验。
1874
2484
  this.store.list = this.runOrderStoreSelfCheck(updatedList, "".concat(source, ".store"));
1875
2485
  this.syncOrdersMap();
1876
- _context16.next = 72;
2486
+ _context18.next = 97;
1877
2487
  return this.patchOrdersInSQLite(patchedOrders, source, mergeActions);
1878
- case 72:
2488
+ case 97:
1879
2489
  this.logInfo('mergeOrdersToStore-结束', {
1880
2490
  uniqueFreshCount: uniqueFreshCount,
1881
2491
  storeOrderCountAfter: this.store.list.length,
1882
2492
  insertCount: insertCount,
1883
2493
  updateCount: updateCount
1884
2494
  });
1885
- _context16.next = 75;
2495
+ _context18.next = 100;
1886
2496
  return this.emitOrdersChanged(patchedOrders, source);
1887
- case 75:
2497
+ case 100:
1888
2498
  case "end":
1889
- return _context16.stop();
2499
+ return _context18.stop();
1890
2500
  }
1891
- }, _callee16, this, [[5, 17, 20, 23], [31, 59, 62, 65]]);
2501
+ }, _callee18, this, [[5, 17, 20, 23], [31, 84, 87, 90], [51, 63, 66, 69]]);
1892
2502
  }));
1893
- function mergeOrdersToStore(_x9, _x10) {
2503
+ function mergeOrdersToStore(_x12, _x13) {
1894
2504
  return _mergeOrdersToStore.apply(this, arguments);
1895
2505
  }
1896
2506
  return mergeOrdersToStore;
@@ -1907,19 +2517,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1907
2517
  key: "lookupOrderIndexByIdentityKeys",
1908
2518
  value: function lookupOrderIndexByIdentityKeys(identityKeyToIndex, identityKeys) {
1909
2519
  var matchIndex = -1;
1910
- var _iterator13 = _createForOfIteratorHelper(identityKeys),
1911
- _step13;
2520
+ var _iterator19 = _createForOfIteratorHelper(identityKeys),
2521
+ _step19;
1912
2522
  try {
1913
- for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
1914
- var key = _step13.value;
2523
+ for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
2524
+ var key = _step19.value;
1915
2525
  var index = identityKeyToIndex.get(key);
1916
2526
  if (index === undefined) continue;
1917
2527
  if (matchIndex < 0 || index < matchIndex) matchIndex = index;
1918
2528
  }
1919
2529
  } catch (err) {
1920
- _iterator13.e(err);
2530
+ _iterator19.e(err);
1921
2531
  } finally {
1922
- _iterator13.f();
2532
+ _iterator19.f();
1923
2533
  }
1924
2534
  return matchIndex;
1925
2535
  }
@@ -1940,17 +2550,17 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1940
2550
  key: "registerOrderIdentityKeys",
1941
2551
  value: function registerOrderIdentityKeys(identityKeyToIndex, order, index) {
1942
2552
  var identityKeys = this.getOrderIdentityMatchKeys(order);
1943
- var _iterator14 = _createForOfIteratorHelper(identityKeys),
1944
- _step14;
2553
+ var _iterator20 = _createForOfIteratorHelper(identityKeys),
2554
+ _step20;
1945
2555
  try {
1946
- for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
1947
- var key = _step14.value;
2556
+ for (_iterator20.s(); !(_step20 = _iterator20.n()).done;) {
2557
+ var key = _step20.value;
1948
2558
  identityKeyToIndex.set(key, index);
1949
2559
  }
1950
2560
  } catch (err) {
1951
- _iterator14.e(err);
2561
+ _iterator20.e(err);
1952
2562
  } finally {
1953
- _iterator14.f();
2563
+ _iterator20.f();
1954
2564
  }
1955
2565
  }
1956
2566
 
@@ -2005,17 +2615,17 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2005
2615
  key: "uniqueOrderIds",
2006
2616
  value: function uniqueOrderIds(ids) {
2007
2617
  var idMap = new Map();
2008
- var _iterator15 = _createForOfIteratorHelper(ids),
2009
- _step15;
2618
+ var _iterator21 = _createForOfIteratorHelper(ids),
2619
+ _step21;
2010
2620
  try {
2011
- for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
2012
- var id = _step15.value;
2621
+ for (_iterator21.s(); !(_step21 = _iterator21.n()).done;) {
2622
+ var id = _step21.value;
2013
2623
  idMap.set(this.getIdKey(id), id);
2014
2624
  }
2015
2625
  } catch (err) {
2016
- _iterator15.e(err);
2626
+ _iterator21.e(err);
2017
2627
  } finally {
2018
- _iterator15.f();
2628
+ _iterator21.f();
2019
2629
  }
2020
2630
  return _toConsumableArray(idMap.values());
2021
2631
  }
@@ -2027,12 +2637,12 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2027
2637
  }, {
2028
2638
  key: "isOrderLookupMatch",
2029
2639
  value: function isOrderLookupMatch(order, lookupKey) {
2030
- var _this16 = this;
2640
+ var _this17 = this;
2031
2641
  if (!order || !lookupKey) return false;
2032
2642
  var candidates = [order.order_id, order.external_sale_number, order.order_number, order.shop_order_number, order.shop_full_order_number];
2033
2643
  return candidates.some(function (value) {
2034
2644
  if (value === undefined || value === null || value === '') return false;
2035
- return _this16.getIdKey(value) === lookupKey;
2645
+ return _this17.getIdKey(value) === lookupKey;
2036
2646
  });
2037
2647
  }
2038
2648
 
@@ -2075,10 +2685,10 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2075
2685
  }, {
2076
2686
  key: "findOrderIndexByIdentity",
2077
2687
  value: function findOrderIndexByIdentity(orders, target) {
2078
- var _this17 = this;
2688
+ var _this18 = this;
2079
2689
  if (this.getOrderIdentityMatchKeys(target).length === 0) return -1;
2080
2690
  return orders.findIndex(function (order) {
2081
- return _this17.doOrdersShareIdentity(order, target);
2691
+ return _this18.doOrdersShareIdentity(order, target);
2082
2692
  });
2083
2693
  }
2084
2694
  }, {
@@ -2102,6 +2712,121 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2102
2712
  if (rightScore >= leftScore) return right;
2103
2713
  return left;
2104
2714
  }
2715
+ }, {
2716
+ key: "getProductIdentityKeys",
2717
+ value: function getProductIdentityKeys(product) {
2718
+ var _record$metadata;
2719
+ var record = product;
2720
+ if (!record) return [];
2721
+ var keys = [];
2722
+ var metadataUid = (_record$metadata = record.metadata) === null || _record$metadata === void 0 ? void 0 : _record$metadata.unique_identification_number;
2723
+ if (!this.isBlankIdentityValue(metadataUid)) keys.push("uid:".concat(String(metadataUid)));
2724
+ var topLevelUid = record.unique_identification_number;
2725
+ if (!this.isBlankIdentityValue(topLevelUid)) keys.push("uid:".concat(String(topLevelUid)));
2726
+ var orderDetailId = record.order_detail_id;
2727
+ if (!this.isBlankIdentityValue(orderDetailId)) keys.push("detail:".concat(String(orderDetailId)));
2728
+ var bookingUid = record.booking_uid;
2729
+ if (!this.isBlankIdentityValue(bookingUid)) keys.push("booking:".concat(String(bookingUid)));
2730
+ return keys;
2731
+ }
2732
+ }, {
2733
+ key: "mergeOrderProductLists",
2734
+ value: function mergeOrderProductLists(preferred, secondary) {
2735
+ var preferredList = Array.isArray(preferred) ? preferred : [];
2736
+ var secondaryList = Array.isArray(secondary) ? secondary : [];
2737
+ if (secondaryList.length === 0) return preferredList;
2738
+ if (preferredList.length === 0) return secondaryList;
2739
+ var seenKeys = new Set();
2740
+ var _iterator22 = _createForOfIteratorHelper(preferredList),
2741
+ _step22;
2742
+ try {
2743
+ for (_iterator22.s(); !(_step22 = _iterator22.n()).done;) {
2744
+ var item = _step22.value;
2745
+ var keys = this.getProductIdentityKeys(item);
2746
+ var _iterator24 = _createForOfIteratorHelper(keys),
2747
+ _step24;
2748
+ try {
2749
+ for (_iterator24.s(); !(_step24 = _iterator24.n()).done;) {
2750
+ var key = _step24.value;
2751
+ seenKeys.add(key);
2752
+ }
2753
+ } catch (err) {
2754
+ _iterator24.e(err);
2755
+ } finally {
2756
+ _iterator24.f();
2757
+ }
2758
+ }
2759
+ } catch (err) {
2760
+ _iterator22.e(err);
2761
+ } finally {
2762
+ _iterator22.f();
2763
+ }
2764
+ var result = _toConsumableArray(preferredList);
2765
+ var _iterator23 = _createForOfIteratorHelper(secondaryList),
2766
+ _step23;
2767
+ try {
2768
+ for (_iterator23.s(); !(_step23 = _iterator23.n()).done;) {
2769
+ var _item = _step23.value;
2770
+ var _keys = this.getProductIdentityKeys(_item);
2771
+ if (_keys.length === 0 || _keys.some(function (key) {
2772
+ return seenKeys.has(key);
2773
+ })) continue;
2774
+ var _iterator25 = _createForOfIteratorHelper(_keys),
2775
+ _step25;
2776
+ try {
2777
+ for (_iterator25.s(); !(_step25 = _iterator25.n()).done;) {
2778
+ var _key3 = _step25.value;
2779
+ seenKeys.add(_key3);
2780
+ }
2781
+ } catch (err) {
2782
+ _iterator25.e(err);
2783
+ } finally {
2784
+ _iterator25.f();
2785
+ }
2786
+ result.push(cloneDeep(_item));
2787
+ }
2788
+ } catch (err) {
2789
+ _iterator23.e(err);
2790
+ } finally {
2791
+ _iterator23.f();
2792
+ }
2793
+ return result;
2794
+ }
2795
+ }, {
2796
+ key: "mergeOrderPaymentLists",
2797
+ value: function mergeOrderPaymentLists(existing, incoming) {
2798
+ var existingList = Array.isArray(existing) ? existing : [];
2799
+ var incomingList = Array.isArray(incoming) ? incoming : [];
2800
+ if (incomingList.length === 0) return cloneDeep(existingList);
2801
+ return mergeOrderPaymentListsByIdentity(existingList, incomingList);
2802
+ }
2803
+ }, {
2804
+ key: "getIdentifiedPendingPayments",
2805
+ value: function getIdentifiedPendingPayments(order) {
2806
+ var payments = Array.isArray(order === null || order === void 0 ? void 0 : order.payments) ? order.payments : [];
2807
+ return payments.filter(function (payment) {
2808
+ return isIdentifiedPendingOrderPayment(payment);
2809
+ });
2810
+ }
2811
+ }, {
2812
+ key: "shouldProtectLocalOrderFromRemoteSnapshot",
2813
+ value: function shouldProtectLocalOrderFromRemoteSnapshot(order) {
2814
+ return this.isPendingSyncOrder(order) || this.isDraftOrder(order) || this.getIdentifiedPendingPayments(order).length > 0;
2815
+ }
2816
+ }, {
2817
+ key: "getUnmatchedIdentifiedPendingPayments",
2818
+ value: function getUnmatchedIdentifiedPendingPayments(existing, incoming) {
2819
+ var existingPayments = Array.isArray(existing) ? existing : [];
2820
+ var incomingPayments = Array.isArray(incoming) ? incoming : [];
2821
+ var incomingIdentityKeys = new Set(incomingPayments.flatMap(function (payment) {
2822
+ return getOrderPaymentIdentityKeys(payment);
2823
+ }));
2824
+ return existingPayments.filter(function (payment) {
2825
+ return isIdentifiedPendingOrderPayment(payment) && !getOrderPaymentIdentityKeys(payment).some(function (key) {
2826
+ return incomingIdentityKeys.has(key);
2827
+ });
2828
+ });
2829
+ }
2105
2830
  }, {
2106
2831
  key: "mergeOrderRecords",
2107
2832
  value: function mergeOrderRecords(existing, incoming) {
@@ -2109,7 +2834,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2109
2834
  var secondary = preferred === existing ? incoming : existing;
2110
2835
  var merged = _objectSpread(_objectSpread({}, secondary), preferred);
2111
2836
  var fieldsToPreserve = ['order_id', 'external_sale_number', 'order_number', 'shop_order_number', 'shop_full_order_number'];
2112
- var incomingPatchFields = ['payment_status', 'status', 'shipping_status', 'updated_at', 'shop_discount', 'summary', 'note', 'customer_id', 'customer_name', 'customer', 'holder', 'contacts_info', 'phone', 'email', 'relation_forms'];
2837
+ var incomingPatchFields = ['payment_status', 'status', 'shipping_status', 'updated_at', 'shop_discount', 'summary', 'note', 'customer_id', 'customer_name', 'customer', 'holder', 'contacts_info', 'phone', 'email', 'relation_forms', 'is_draft_order'];
2113
2838
  var mergedRecord = merged;
2114
2839
  var preferredRecord = preferred;
2115
2840
  var secondaryRecord = secondary;
@@ -2139,7 +2864,23 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2139
2864
  for (var _i6 = 0, _ORDER_AUTHORITATIVE_2 = ORDER_AUTHORITATIVE_COLLECTION_FIELDS; _i6 < _ORDER_AUTHORITATIVE_2.length; _i6++) {
2140
2865
  var _field2 = _ORDER_AUTHORITATIVE_2[_i6];
2141
2866
  if (Array.isArray(incomingRecord[_field2])) {
2142
- mergedRecord[_field2] = this.mergeAuthoritativeOrderCollection(_field2, existingRecord[_field2], incomingRecord[_field2], childUidRemaps);
2867
+ if (_field2 === 'payments') {
2868
+ var preservedPending = this.getUnmatchedIdentifiedPendingPayments(existingRecord[_field2], incomingRecord[_field2]);
2869
+ if (preservedPending.length > 0) {
2870
+ var _ref5, _existing$order_id, _ref6, _existingRecord$exter;
2871
+ this.logInfo('mergeOrderRecords-保留本地 pending 支付项', {
2872
+ order_id: (_ref5 = (_existing$order_id = existing.order_id) !== null && _existing$order_id !== void 0 ? _existing$order_id : incoming.order_id) !== null && _ref5 !== void 0 ? _ref5 : null,
2873
+ external_sale_number: (_ref6 = (_existingRecord$exter = existingRecord.external_sale_number) !== null && _existingRecord$exter !== void 0 ? _existingRecord$exter : incomingRecord.external_sale_number) !== null && _ref6 !== void 0 ? _ref6 : null,
2874
+ preserved_pending_count: preservedPending.length,
2875
+ preserved_payment_identities: preservedPending.map(function (payment) {
2876
+ return getOrderPaymentIdentityKeys(payment);
2877
+ })
2878
+ });
2879
+ }
2880
+ }
2881
+ mergedRecord[_field2] = this.mergeAuthoritativeOrderCollection(_field2, existingRecord[_field2], incomingRecord[_field2], childUidRemaps, {
2882
+ preserveIdentifiedPendingPayments: _field2 === 'payments'
2883
+ });
2143
2884
  continue;
2144
2885
  }
2145
2886
  if (Object.prototype.hasOwnProperty.call(existingRecord, _field2)) {
@@ -2157,50 +2898,51 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2157
2898
  key: "summarizeDuplicateOrders",
2158
2899
  value: function summarizeDuplicateOrders(orders) {
2159
2900
  var groups = new Map();
2160
- var _iterator16 = _createForOfIteratorHelper(orders),
2161
- _step16;
2901
+ var _iterator26 = _createForOfIteratorHelper(orders),
2902
+ _step26;
2162
2903
  try {
2163
- for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
2164
- var order = _step16.value;
2165
- var _iterator17 = _createForOfIteratorHelper(this.getOrderIdentityMatchKeys(order)),
2166
- _step17;
2904
+ for (_iterator26.s(); !(_step26 = _iterator26.n()).done;) {
2905
+ var order = _step26.value;
2906
+ var _iterator27 = _createForOfIteratorHelper(this.getOrderIdentityMatchKeys(order)),
2907
+ _step27;
2167
2908
  try {
2168
- for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
2169
- var key = _step17.value;
2909
+ for (_iterator27.s(); !(_step27 = _iterator27.n()).done;) {
2910
+ var key = _step27.value;
2170
2911
  var group = groups.get(key) || [];
2171
2912
  group.push(order);
2172
2913
  groups.set(key, group);
2173
2914
  }
2174
2915
  } catch (err) {
2175
- _iterator17.e(err);
2916
+ _iterator27.e(err);
2176
2917
  } finally {
2177
- _iterator17.f();
2918
+ _iterator27.f();
2178
2919
  }
2179
2920
  }
2180
2921
  } catch (err) {
2181
- _iterator16.e(err);
2922
+ _iterator26.e(err);
2182
2923
  } finally {
2183
- _iterator16.f();
2924
+ _iterator26.f();
2184
2925
  }
2185
- return _toConsumableArray(groups.entries()).filter(function (_ref4) {
2186
- var _ref5 = _slicedToArray(_ref4, 2),
2187
- group = _ref5[1];
2926
+ return _toConsumableArray(groups.entries()).filter(function (_ref7) {
2927
+ var _ref8 = _slicedToArray(_ref7, 2),
2928
+ group = _ref8[1];
2188
2929
  return group.length > 1;
2189
- }).slice(0, 20).map(function (_ref6) {
2190
- var _ref7 = _slicedToArray(_ref6, 2),
2191
- key = _ref7[0],
2192
- group = _ref7[1];
2930
+ }).slice(0, 20).map(function (_ref9) {
2931
+ var _ref10 = _slicedToArray(_ref9, 2),
2932
+ key = _ref10[0],
2933
+ group = _ref10[1];
2193
2934
  return {
2194
2935
  key: key,
2195
2936
  count: group.length,
2196
2937
  orders: group.map(function (order) {
2197
- var _order$order_id3, _external_sale_number3, _shop_order_number, _shop_full_order_numb, _order$need_sync;
2938
+ var _order$order_id4, _external_sale_number4, _shop_order_number, _shop_full_order_numb, _order$need_sync, _order$is_draft_order;
2198
2939
  return {
2199
- order_id: (_order$order_id3 = order.order_id) !== null && _order$order_id3 !== void 0 ? _order$order_id3 : null,
2200
- external_sale_number: (_external_sale_number3 = order.external_sale_number) !== null && _external_sale_number3 !== void 0 ? _external_sale_number3 : null,
2940
+ order_id: (_order$order_id4 = order.order_id) !== null && _order$order_id4 !== void 0 ? _order$order_id4 : null,
2941
+ external_sale_number: (_external_sale_number4 = order.external_sale_number) !== null && _external_sale_number4 !== void 0 ? _external_sale_number4 : null,
2201
2942
  shop_order_number: (_shop_order_number = order.shop_order_number) !== null && _shop_order_number !== void 0 ? _shop_order_number : null,
2202
2943
  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,
2203
- need_sync: (_order$need_sync = order.need_sync) !== null && _order$need_sync !== void 0 ? _order$need_sync : null
2944
+ need_sync: (_order$need_sync = order.need_sync) !== null && _order$need_sync !== void 0 ? _order$need_sync : null,
2945
+ is_draft_order: (_order$is_draft_order = order.is_draft_order) !== null && _order$is_draft_order !== void 0 ? _order$is_draft_order : null
2204
2946
  };
2205
2947
  })
2206
2948
  };
@@ -2222,11 +2964,11 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2222
2964
  value: function compactOrderListByIdentity(orders, source) {
2223
2965
  var list = [];
2224
2966
  var removedCount = 0;
2225
- var _iterator18 = _createForOfIteratorHelper(orders),
2226
- _step18;
2967
+ var _iterator28 = _createForOfIteratorHelper(orders),
2968
+ _step28;
2227
2969
  try {
2228
- for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
2229
- var order = _step18.value;
2970
+ for (_iterator28.s(); !(_step28 = _iterator28.n()).done;) {
2971
+ var order = _step28.value;
2230
2972
  var normalizedOrder = this.normalizeOrderCollectionsForIngress(order, "".concat(source, ".order"));
2231
2973
  var matchIndex = this.findOrderIndexByIdentity(list, normalizedOrder);
2232
2974
  if (matchIndex < 0) {
@@ -2237,9 +2979,9 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2237
2979
  removedCount += 1;
2238
2980
  }
2239
2981
  } catch (err) {
2240
- _iterator18.e(err);
2982
+ _iterator28.e(err);
2241
2983
  } finally {
2242
- _iterator18.f();
2984
+ _iterator28.f();
2243
2985
  }
2244
2986
  if (removedCount > 0) {
2245
2987
  this.logWarning('订单列表重复项已压缩', {
@@ -2337,35 +3079,35 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2337
3079
  }, {
2338
3080
  key: "loadOrdersFromSQLite",
2339
3081
  value: function () {
2340
- var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17() {
2341
- var _this18 = this;
3082
+ var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19() {
3083
+ var _this19 = this;
2342
3084
  var orders;
2343
- return _regeneratorRuntime().wrap(function _callee17$(_context17) {
2344
- while (1) switch (_context17.prev = _context17.next) {
3085
+ return _regeneratorRuntime().wrap(function _callee19$(_context19) {
3086
+ while (1) switch (_context19.prev = _context19.next) {
2345
3087
  case 0:
2346
3088
  if (this.dbManager) {
2347
- _context17.next = 2;
3089
+ _context19.next = 2;
2348
3090
  break;
2349
3091
  }
2350
- return _context17.abrupt("return", []);
3092
+ return _context19.abrupt("return", []);
2351
3093
  case 2:
2352
- _context17.prev = 2;
2353
- _context17.next = 5;
3094
+ _context19.prev = 2;
3095
+ _context19.next = 5;
2354
3096
  return this.dbManager.getAll(INDEXDB_STORE_NAME);
2355
3097
  case 5:
2356
- orders = _context17.sent;
2357
- return _context17.abrupt("return", (orders || []).map(function (order) {
2358
- return _this18.normalizeOrderCollectionsForIngress(order, 'loadOrdersFromSQLite');
3098
+ orders = _context19.sent;
3099
+ return _context19.abrupt("return", (orders || []).map(function (order) {
3100
+ return _this19.normalizeOrderCollectionsForIngress(order, 'loadOrdersFromSQLite');
2359
3101
  }));
2360
3102
  case 9:
2361
- _context17.prev = 9;
2362
- _context17.t0 = _context17["catch"](2);
2363
- return _context17.abrupt("return", []);
3103
+ _context19.prev = 9;
3104
+ _context19.t0 = _context19["catch"](2);
3105
+ return _context19.abrupt("return", []);
2364
3106
  case 12:
2365
3107
  case "end":
2366
- return _context17.stop();
3108
+ return _context19.stop();
2367
3109
  }
2368
- }, _callee17, this, [[2, 9]]);
3110
+ }, _callee19, this, [[2, 9]]);
2369
3111
  }));
2370
3112
  function loadOrdersFromSQLite() {
2371
3113
  return _loadOrdersFromSQLite.apply(this, arguments);
@@ -2377,41 +3119,71 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2377
3119
  value: function isPendingSyncOrder(order) {
2378
3120
  return Number(order === null || order === void 0 ? void 0 : order.need_sync) === 1;
2379
3121
  }
3122
+ }, {
3123
+ key: "isDraftOrder",
3124
+ value: function isDraftOrder(order) {
3125
+ return Number(order === null || order === void 0 ? void 0 : order.is_draft_order) === 1;
3126
+ }
3127
+ }, {
3128
+ key: "shouldProtectDraftOrderFromIncoming",
3129
+ value: function shouldProtectDraftOrderFromIncoming(source) {
3130
+ return source !== 'checkoutSync';
3131
+ }
2380
3132
  }, {
2381
3133
  key: "normalizeRemoteSyncedOrder",
2382
3134
  value: function normalizeRemoteSyncedOrder(order) {
2383
3135
  var normalizedOrder = this.normalizeOrderCollectionsForIngress(order, 'normalizeRemoteSyncedOrder');
2384
- if (this.isPendingSyncOrder(normalizedOrder)) return normalizedOrder;
3136
+ if (this.isPendingSyncOrder(normalizedOrder)) return _objectSpread(_objectSpread({}, normalizedOrder), {}, {
3137
+ is_draft_order: 0
3138
+ });
2385
3139
  return _objectSpread(_objectSpread({}, normalizedOrder), {}, {
2386
- need_sync: 0
3140
+ need_sync: 0,
3141
+ is_draft_order: 0
2387
3142
  });
2388
3143
  }
3144
+ }, {
3145
+ key: "mergeRemoteIdentityIntoDraftOrder",
3146
+ value: function mergeRemoteIdentityIntoDraftOrder(draftOrder, remoteOrder) {
3147
+ var merged = _objectSpread({}, this.withoutSyntheticDraftOrderId(draftOrder));
3148
+ var remote = remoteOrder;
3149
+ for (var _i7 = 0, _arr = ['order_id', 'order_number', 'shop_order_number', 'shop_full_order_number']; _i7 < _arr.length; _i7++) {
3150
+ var field = _arr[_i7];
3151
+ if (this.isBlankIdentityValue(merged[field]) && !this.isBlankIdentityValue(remote[field])) {
3152
+ merged[field] = remote[field];
3153
+ }
3154
+ }
3155
+ return this.normalizeOrderCollectionsForIngress(merged, 'mergeRemoteIdentityIntoDraftOrder');
3156
+ }
2389
3157
  }, {
2390
3158
  key: "mergeRemoteSnapshotWithPendingOrders",
2391
3159
  value: function mergeRemoteSnapshotWithPendingOrders(remoteOrders, existingOrders) {
2392
- var _this19 = this;
3160
+ var _this20 = this;
2393
3161
  var merged = remoteOrders.map(function (order) {
2394
- return _this19.normalizeRemoteSyncedOrder(order);
3162
+ return _this20.normalizeRemoteSyncedOrder(order);
2395
3163
  });
2396
- var _iterator19 = _createForOfIteratorHelper(existingOrders),
2397
- _step19;
3164
+ var _iterator29 = _createForOfIteratorHelper(existingOrders),
3165
+ _step29;
2398
3166
  try {
2399
- for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
2400
- var rawOrder = _step19.value;
3167
+ for (_iterator29.s(); !(_step29 = _iterator29.n()).done;) {
3168
+ var rawOrder = _step29.value;
2401
3169
  var order = this.normalizeOrderCollectionsForIngress(rawOrder, 'mergeRemoteSnapshotWithPendingOrders.existingSQLite');
2402
- if (!this.isPendingSyncOrder(order)) continue;
3170
+ if (!this.shouldProtectLocalOrderFromRemoteSnapshot(order)) continue;
2403
3171
  var matchIndex = this.findOrderIndexByIdentity(merged, order);
2404
3172
  if (matchIndex >= 0) {
2405
- merged[matchIndex] = this.mergeOrderRecords(order, merged[matchIndex]);
3173
+ if (this.isDraftOrder(order)) {
3174
+ merged[matchIndex] = this.mergeRemoteIdentityIntoDraftOrder(order, merged[matchIndex]);
3175
+ } else {
3176
+ merged[matchIndex] = this.mergeOrderRecords(order, merged[matchIndex]);
3177
+ }
2406
3178
  continue;
2407
3179
  }
2408
3180
  if (!this.getOrderStorageKey(order)) continue;
2409
3181
  merged.push(order);
2410
3182
  }
2411
3183
  } catch (err) {
2412
- _iterator19.e(err);
3184
+ _iterator29.e(err);
2413
3185
  } finally {
2414
- _iterator19.f();
3186
+ _iterator29.f();
2415
3187
  }
2416
3188
  return this.compactOrderListByIdentity(merged, 'mergeRemoteSnapshotWithPendingOrders').list;
2417
3189
  }
@@ -2427,10 +3199,10 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2427
3199
  }, {
2428
3200
  key: "runInOrderSQLiteSaveQueue",
2429
3201
  value: (function () {
2430
- var _runInOrderSQLiteSaveQueue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(task) {
3202
+ var _runInOrderSQLiteSaveQueue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(task) {
2431
3203
  var queuedTask;
2432
- return _regeneratorRuntime().wrap(function _callee18$(_context18) {
2433
- while (1) switch (_context18.prev = _context18.next) {
3204
+ return _regeneratorRuntime().wrap(function _callee20$(_context20) {
3205
+ while (1) switch (_context20.prev = _context20.next) {
2434
3206
  case 0:
2435
3207
  queuedTask = this.orderSQLiteSaveQueue.then(task, task);
2436
3208
  this.orderSQLiteSaveQueue = queuedTask.then(function () {
@@ -2438,14 +3210,14 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2438
3210
  }, function () {
2439
3211
  return undefined;
2440
3212
  });
2441
- return _context18.abrupt("return", queuedTask);
3213
+ return _context20.abrupt("return", queuedTask);
2442
3214
  case 3:
2443
3215
  case "end":
2444
- return _context18.stop();
3216
+ return _context20.stop();
2445
3217
  }
2446
- }, _callee18, this);
3218
+ }, _callee20, this);
2447
3219
  }));
2448
- function runInOrderSQLiteSaveQueue(_x11) {
3220
+ function runInOrderSQLiteSaveQueue(_x14) {
2449
3221
  return _runInOrderSQLiteSaveQueue.apply(this, arguments);
2450
3222
  }
2451
3223
  return runInOrderSQLiteSaveQueue;
@@ -2460,146 +3232,174 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2460
3232
  }, {
2461
3233
  key: "patchOrdersInSQLite",
2462
3234
  value: (function () {
2463
- var _patchOrdersInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(orders, source) {
2464
- var _this20 = this;
3235
+ var _patchOrdersInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(orders, source) {
3236
+ var _this21 = this;
2465
3237
  var mergeActions,
3238
+ options,
2466
3239
  ordersSnapshot,
2467
3240
  _this$filterRedundant2,
2468
3241
  toWrite,
2469
3242
  skipped,
2470
3243
  compactedToWrite,
2471
- _args20 = arguments;
2472
- return _regeneratorRuntime().wrap(function _callee20$(_context20) {
2473
- while (1) switch (_context20.prev = _context20.next) {
3244
+ _args22 = arguments;
3245
+ return _regeneratorRuntime().wrap(function _callee22$(_context22) {
3246
+ while (1) switch (_context22.prev = _context22.next) {
2474
3247
  case 0:
2475
- mergeActions = _args20.length > 2 && _args20[2] !== undefined ? _args20[2] : {};
2476
- if (!(!this.dbManager || orders.length === 0)) {
2477
- _context20.next = 3;
3248
+ mergeActions = _args22.length > 2 && _args22[2] !== undefined ? _args22[2] : {};
3249
+ options = _args22.length > 3 && _args22[3] !== undefined ? _args22[3] : {};
3250
+ if (!(orders.length === 0)) {
3251
+ _context22.next = 4;
2478
3252
  break;
2479
3253
  }
2480
- return _context20.abrupt("return");
2481
- case 3:
3254
+ return _context22.abrupt("return");
3255
+ case 4:
3256
+ if (this.dbManager) {
3257
+ _context22.next = 8;
3258
+ break;
3259
+ }
3260
+ if (!options.throwOnError) {
3261
+ _context22.next = 7;
3262
+ break;
3263
+ }
3264
+ throw new Error('订单 SQLite 数据库未初始化');
3265
+ case 7:
3266
+ return _context22.abrupt("return");
3267
+ case 8:
2482
3268
  ordersSnapshot = cloneDeep(orders).map(function (order) {
2483
- return _this20.normalizeOrderCollectionsForIngress(order, "".concat(source, ".sqliteIngress"));
3269
+ return _this21.normalizeOrderCollectionsForIngress(order, "".concat(source, ".sqliteIngress"));
2484
3270
  }).filter(function (order) {
2485
- return _this20.getOrderStorageKey(order);
3271
+ return _this21.getOrderStorageKey(order);
2486
3272
  });
2487
3273
  if (!(ordersSnapshot.length === 0)) {
2488
- _context20.next = 6;
3274
+ _context22.next = 11;
2489
3275
  break;
2490
3276
  }
2491
- return _context20.abrupt("return");
2492
- case 6:
3277
+ return _context22.abrupt("return");
3278
+ case 11:
2493
3279
  _this$filterRedundant2 = this.filterRedundantPatchOrders(source, ordersSnapshot, mergeActions), toWrite = _this$filterRedundant2.toWrite, skipped = _this$filterRedundant2.skipped;
2494
3280
  if (!(toWrite.length === 0)) {
2495
- _context20.next = 9;
3281
+ _context22.next = 14;
2496
3282
  break;
2497
3283
  }
2498
- return _context20.abrupt("return");
2499
- case 9:
3284
+ return _context22.abrupt("return");
3285
+ case 14:
2500
3286
  compactedToWrite = this.compactOrderListByIdentity(toWrite, "".concat(source, ".sqlitePatch")).list;
2501
3287
  if (!(compactedToWrite.length === 0)) {
2502
- _context20.next = 12;
3288
+ _context22.next = 17;
2503
3289
  break;
2504
3290
  }
2505
- return _context20.abrupt("return");
2506
- case 12:
2507
- _context20.prev = 12;
2508
- _context20.next = 15;
2509
- return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19() {
2510
- var writeMethod, _iterator20, _step20, order;
2511
- return _regeneratorRuntime().wrap(function _callee19$(_context19) {
2512
- while (1) switch (_context19.prev = _context19.next) {
3291
+ return _context22.abrupt("return");
3292
+ case 17:
3293
+ _context22.prev = 17;
3294
+ _context22.next = 20;
3295
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21() {
3296
+ var writeMethod, _iterator30, _step30, order;
3297
+ return _regeneratorRuntime().wrap(function _callee21$(_context21) {
3298
+ while (1) switch (_context21.prev = _context21.next) {
2513
3299
  case 0:
2514
3300
  writeMethod = 'none';
2515
- _this20.logInfo('patchOrdersInSQLite-开始', {
3301
+ _this21.logInfo('patchOrdersInSQLite-开始', {
2516
3302
  source: source,
2517
3303
  count: compactedToWrite.length,
2518
3304
  dedupedCount: skipped.length
2519
3305
  });
2520
- if (!(typeof _this20.dbManager.bulkUpdate === 'function')) {
2521
- _context19.next = 8;
3306
+ if (!(typeof _this21.dbManager.bulkUpdate === 'function')) {
3307
+ _context21.next = 8;
2522
3308
  break;
2523
3309
  }
2524
3310
  writeMethod = 'bulkUpdate';
2525
- _context19.next = 6;
2526
- return _this20.dbManager.bulkUpdate(INDEXDB_STORE_NAME, compactedToWrite);
3311
+ _context21.next = 6;
3312
+ return _this21.dbManager.bulkUpdate(INDEXDB_STORE_NAME, compactedToWrite);
2527
3313
  case 6:
2528
- _context19.next = 33;
3314
+ _context21.next = 37;
2529
3315
  break;
2530
3316
  case 8:
2531
- if (!(typeof _this20.dbManager.bulkAdd === 'function')) {
2532
- _context19.next = 14;
3317
+ if (!(typeof _this21.dbManager.bulkAdd === 'function')) {
3318
+ _context21.next = 14;
2533
3319
  break;
2534
3320
  }
2535
3321
  writeMethod = 'bulkAdd';
2536
- _context19.next = 12;
2537
- return _this20.dbManager.bulkAdd(INDEXDB_STORE_NAME, compactedToWrite);
3322
+ _context21.next = 12;
3323
+ return _this21.dbManager.bulkAdd(INDEXDB_STORE_NAME, compactedToWrite);
2538
3324
  case 12:
2539
- _context19.next = 33;
3325
+ _context21.next = 37;
2540
3326
  break;
2541
3327
  case 14:
2542
- if (!(typeof _this20.dbManager.update === 'function')) {
2543
- _context19.next = 33;
3328
+ if (!(typeof _this21.dbManager.update === 'function')) {
3329
+ _context21.next = 35;
2544
3330
  break;
2545
3331
  }
2546
3332
  writeMethod = 'update';
2547
- _iterator20 = _createForOfIteratorHelper(compactedToWrite);
2548
- _context19.prev = 17;
2549
- _iterator20.s();
3333
+ _iterator30 = _createForOfIteratorHelper(compactedToWrite);
3334
+ _context21.prev = 17;
3335
+ _iterator30.s();
2550
3336
  case 19:
2551
- if ((_step20 = _iterator20.n()).done) {
2552
- _context19.next = 25;
3337
+ if ((_step30 = _iterator30.n()).done) {
3338
+ _context21.next = 25;
2553
3339
  break;
2554
3340
  }
2555
- order = _step20.value;
2556
- _context19.next = 23;
2557
- return _this20.dbManager.update(INDEXDB_STORE_NAME, order);
3341
+ order = _step30.value;
3342
+ _context21.next = 23;
3343
+ return _this21.dbManager.update(INDEXDB_STORE_NAME, order);
2558
3344
  case 23:
2559
- _context19.next = 19;
3345
+ _context21.next = 19;
2560
3346
  break;
2561
3347
  case 25:
2562
- _context19.next = 30;
3348
+ _context21.next = 30;
2563
3349
  break;
2564
3350
  case 27:
2565
- _context19.prev = 27;
2566
- _context19.t0 = _context19["catch"](17);
2567
- _iterator20.e(_context19.t0);
3351
+ _context21.prev = 27;
3352
+ _context21.t0 = _context21["catch"](17);
3353
+ _iterator30.e(_context21.t0);
2568
3354
  case 30:
2569
- _context19.prev = 30;
2570
- _iterator20.f();
2571
- return _context19.finish(30);
3355
+ _context21.prev = 30;
3356
+ _iterator30.f();
3357
+ return _context21.finish(30);
2572
3358
  case 33:
2573
- _this20.recordRecentSqliteWrite(source, compactedToWrite);
2574
- _this20.logInfo('patchOrdersInSQLite-完成', {
3359
+ _context21.next = 37;
3360
+ break;
3361
+ case 35:
3362
+ if (!options.throwOnError) {
3363
+ _context21.next = 37;
3364
+ break;
3365
+ }
3366
+ throw new Error('订单 SQLite 数据库不支持写入');
3367
+ case 37:
3368
+ _this21.recordRecentSqliteWrite(source, compactedToWrite);
3369
+ _this21.logInfo('patchOrdersInSQLite-完成', {
2575
3370
  source: source,
2576
3371
  count: compactedToWrite.length,
2577
3372
  writeMethod: writeMethod,
2578
3373
  dedupedCount: skipped.length
2579
3374
  });
2580
- case 35:
3375
+ case 39:
2581
3376
  case "end":
2582
- return _context19.stop();
3377
+ return _context21.stop();
2583
3378
  }
2584
- }, _callee19, null, [[17, 27, 30, 33]]);
3379
+ }, _callee21, null, [[17, 27, 30, 33]]);
2585
3380
  })));
2586
- case 15:
2587
- _context20.next = 20;
3381
+ case 20:
3382
+ _context22.next = 27;
2588
3383
  break;
2589
- case 17:
2590
- _context20.prev = 17;
2591
- _context20.t0 = _context20["catch"](12);
3384
+ case 22:
3385
+ _context22.prev = 22;
3386
+ _context22.t0 = _context22["catch"](17);
2592
3387
  this.logError('增量保存订单到 SQLite 失败', {
2593
- error: _context20.t0 instanceof Error ? _context20.t0.message : String(_context20.t0),
3388
+ error: _context22.t0 instanceof Error ? _context22.t0.message : String(_context22.t0),
2594
3389
  orderCount: ordersSnapshot.length
2595
3390
  });
2596
- case 20:
3391
+ if (!options.throwOnError) {
3392
+ _context22.next = 27;
3393
+ break;
3394
+ }
3395
+ throw _context22.t0;
3396
+ case 27:
2597
3397
  case "end":
2598
- return _context20.stop();
3398
+ return _context22.stop();
2599
3399
  }
2600
- }, _callee20, this, [[12, 17]]);
3400
+ }, _callee22, this, [[17, 22]]);
2601
3401
  }));
2602
- function patchOrdersInSQLite(_x12, _x13) {
3402
+ function patchOrdersInSQLite(_x15, _x16) {
2603
3403
  return _patchOrdersInSQLite.apply(this, arguments);
2604
3404
  }
2605
3405
  return patchOrdersInSQLite;
@@ -2614,98 +3414,135 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2614
3414
  }, {
2615
3415
  key: "updateOrderInSQLite",
2616
3416
  value: (function () {
2617
- var _updateOrderInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(order, source) {
2618
- var _this21 = this;
2619
- var orderSnapshot, _orderSnapshot$order_3;
2620
- return _regeneratorRuntime().wrap(function _callee22$(_context22) {
2621
- while (1) switch (_context22.prev = _context22.next) {
3417
+ var _updateOrderInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(order, source) {
3418
+ var _this22 = this;
3419
+ var options,
3420
+ orderSnapshot,
3421
+ _orderSnapshot$order_3,
3422
+ _args24 = arguments;
3423
+ return _regeneratorRuntime().wrap(function _callee24$(_context24) {
3424
+ while (1) switch (_context24.prev = _context24.next) {
2622
3425
  case 0:
2623
- if (!(!this.dbManager || !this.getOrderStorageKey(order))) {
2624
- _context22.next = 2;
3426
+ options = _args24.length > 2 && _args24[2] !== undefined ? _args24[2] : {};
3427
+ if (this.getOrderStorageKey(order)) {
3428
+ _context24.next = 5;
2625
3429
  break;
2626
3430
  }
2627
- return _context22.abrupt("return");
2628
- case 2:
3431
+ if (!options.throwOnError) {
3432
+ _context24.next = 4;
3433
+ break;
3434
+ }
3435
+ throw new Error('订单缺少可用的 SQLite 存储主键');
3436
+ case 4:
3437
+ return _context24.abrupt("return");
3438
+ case 5:
3439
+ if (this.dbManager) {
3440
+ _context24.next = 9;
3441
+ break;
3442
+ }
3443
+ if (!options.throwOnError) {
3444
+ _context24.next = 8;
3445
+ break;
3446
+ }
3447
+ throw new Error('订单 SQLite 数据库未初始化');
3448
+ case 8:
3449
+ return _context24.abrupt("return");
3450
+ case 9:
2629
3451
  orderSnapshot = this.normalizeOrderCollectionsForIngress(cloneDeep(order), "".concat(source, ".sqliteIngress"));
2630
- _context22.prev = 3;
2631
- _context22.next = 6;
2632
- return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21() {
3452
+ _context24.prev = 10;
3453
+ _context24.next = 13;
3454
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23() {
2633
3455
  var _orderSnapshot$order_, _orderSnapshot$order_2;
2634
3456
  var writeMethod;
2635
- return _regeneratorRuntime().wrap(function _callee21$(_context21) {
2636
- while (1) switch (_context21.prev = _context21.next) {
3457
+ return _regeneratorRuntime().wrap(function _callee23$(_context23) {
3458
+ while (1) switch (_context23.prev = _context23.next) {
2637
3459
  case 0:
2638
3460
  writeMethod = 'none';
2639
- _this21.logInfo('updateOrderInSQLite-开始', {
3461
+ _this22.logInfo('updateOrderInSQLite-开始', {
2640
3462
  source: source,
2641
3463
  orderId: (_orderSnapshot$order_ = orderSnapshot.order_id) !== null && _orderSnapshot$order_ !== void 0 ? _orderSnapshot$order_ : null,
2642
- storageKey: _this21.getOrderStorageKey(orderSnapshot)
3464
+ storageKey: _this22.getOrderStorageKey(orderSnapshot)
2643
3465
  });
2644
- if (!(typeof _this21.dbManager.update === 'function')) {
2645
- _context21.next = 8;
3466
+ if (!(typeof _this22.dbManager.update === 'function')) {
3467
+ _context23.next = 8;
2646
3468
  break;
2647
3469
  }
2648
3470
  writeMethod = 'update';
2649
- _context21.next = 6;
2650
- return _this21.dbManager.update(INDEXDB_STORE_NAME, orderSnapshot);
3471
+ _context23.next = 6;
3472
+ return _this22.dbManager.update(INDEXDB_STORE_NAME, orderSnapshot);
2651
3473
  case 6:
2652
- _context21.next = 18;
3474
+ _context23.next = 22;
2653
3475
  break;
2654
3476
  case 8:
2655
- if (!(typeof _this21.dbManager.bulkUpdate === 'function')) {
2656
- _context21.next = 14;
3477
+ if (!(typeof _this22.dbManager.bulkUpdate === 'function')) {
3478
+ _context23.next = 14;
2657
3479
  break;
2658
3480
  }
2659
3481
  writeMethod = 'bulkUpdate';
2660
- _context21.next = 12;
2661
- return _this21.dbManager.bulkUpdate(INDEXDB_STORE_NAME, [orderSnapshot]);
3482
+ _context23.next = 12;
3483
+ return _this22.dbManager.bulkUpdate(INDEXDB_STORE_NAME, [orderSnapshot]);
2662
3484
  case 12:
2663
- _context21.next = 18;
3485
+ _context23.next = 22;
2664
3486
  break;
2665
3487
  case 14:
2666
- if (!(typeof _this21.dbManager.bulkAdd === 'function')) {
2667
- _context21.next = 18;
3488
+ if (!(typeof _this22.dbManager.bulkAdd === 'function')) {
3489
+ _context23.next = 20;
2668
3490
  break;
2669
3491
  }
2670
3492
  writeMethod = 'bulkAdd';
2671
- _context21.next = 18;
2672
- return _this21.dbManager.bulkAdd(INDEXDB_STORE_NAME, [orderSnapshot]);
3493
+ _context23.next = 18;
3494
+ return _this22.dbManager.bulkAdd(INDEXDB_STORE_NAME, [orderSnapshot]);
2673
3495
  case 18:
2674
- _this21.recordRecentSqliteWrite(source, [orderSnapshot]);
2675
- _this21.logInfo('updateOrderInSQLite-完成', {
3496
+ _context23.next = 22;
3497
+ break;
3498
+ case 20:
3499
+ if (!options.throwOnError) {
3500
+ _context23.next = 22;
3501
+ break;
3502
+ }
3503
+ throw new Error('订单 SQLite 数据库不支持写入');
3504
+ case 22:
3505
+ _this22.recordRecentSqliteWrite(source, [orderSnapshot]);
3506
+ _this22.logInfo('updateOrderInSQLite-完成', {
2676
3507
  source: source,
2677
3508
  orderId: (_orderSnapshot$order_2 = orderSnapshot.order_id) !== null && _orderSnapshot$order_2 !== void 0 ? _orderSnapshot$order_2 : null,
2678
3509
  writeMethod: writeMethod
2679
3510
  });
2680
- case 20:
3511
+ case 24:
2681
3512
  case "end":
2682
- return _context21.stop();
3513
+ return _context23.stop();
2683
3514
  }
2684
- }, _callee21);
3515
+ }, _callee23);
2685
3516
  })));
2686
- case 6:
2687
- _context22.next = 11;
3517
+ case 13:
3518
+ _context24.next = 20;
2688
3519
  break;
2689
- case 8:
2690
- _context22.prev = 8;
2691
- _context22.t0 = _context22["catch"](3);
3520
+ case 15:
3521
+ _context24.prev = 15;
3522
+ _context24.t0 = _context24["catch"](10);
2692
3523
  this.logError('单条保存订单到 SQLite 失败', {
2693
- error: _context22.t0 instanceof Error ? _context22.t0.message : String(_context22.t0),
3524
+ error: _context24.t0 instanceof Error ? _context24.t0.message : String(_context24.t0),
2694
3525
  orderId: (_orderSnapshot$order_3 = orderSnapshot.order_id) !== null && _orderSnapshot$order_3 !== void 0 ? _orderSnapshot$order_3 : null
2695
3526
  });
2696
- case 11:
3527
+ if (!options.throwOnError) {
3528
+ _context24.next = 20;
3529
+ break;
3530
+ }
3531
+ throw _context24.t0;
3532
+ case 20:
2697
3533
  case "end":
2698
- return _context22.stop();
3534
+ return _context24.stop();
2699
3535
  }
2700
- }, _callee22, this, [[3, 8]]);
3536
+ }, _callee24, this, [[10, 15]]);
2701
3537
  }));
2702
- function updateOrderInSQLite(_x14, _x15) {
3538
+ function updateOrderInSQLite(_x17, _x18) {
2703
3539
  return _updateOrderInSQLite.apply(this, arguments);
2704
3540
  }
2705
3541
  return updateOrderInSQLite;
2706
3542
  }()
2707
3543
  /**
2708
- * 全量快照替换 orders 表(clear + bulkAdd),用于 SSE 全量拉取与营业日窗口裁剪。
3544
+ * 全量快照替换 orders 表(clear + bulkAdd),并保留本地 draft / need_sync / pending 支付订单。
3545
+ * 用于 SSE 全量拉取与营业日窗口裁剪。
2709
3546
  *
2710
3547
  * @example
2711
3548
  * await this.replaceOrdersSnapshotInSQLite(orderList)
@@ -2714,100 +3551,163 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2714
3551
  }, {
2715
3552
  key: "replaceOrdersSnapshotInSQLite",
2716
3553
  value: (function () {
2717
- var _replaceOrdersSnapshotInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(orderList, source) {
2718
- var _this22 = this;
2719
- var remoteSnapshot, mergedSnapshot;
2720
- return _regeneratorRuntime().wrap(function _callee24$(_context24) {
2721
- while (1) switch (_context24.prev = _context24.next) {
3554
+ var _replaceOrdersSnapshotInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26(orderList, source) {
3555
+ var _this23 = this;
3556
+ var protectedOrdersBeforeRemoteFetch,
3557
+ remoteSnapshot,
3558
+ mergedSnapshot,
3559
+ _args26 = arguments;
3560
+ return _regeneratorRuntime().wrap(function _callee26$(_context26) {
3561
+ while (1) switch (_context26.prev = _context26.next) {
2722
3562
  case 0:
3563
+ protectedOrdersBeforeRemoteFetch = _args26.length > 2 && _args26[2] !== undefined ? _args26[2] : [];
2723
3564
  if (this.dbManager) {
2724
- _context24.next = 2;
3565
+ _context26.next = 3;
2725
3566
  break;
2726
3567
  }
2727
- return _context24.abrupt("return", this.compactOrderListByIdentity(orderList.map(function (order) {
2728
- return _this22.normalizeRemoteSyncedOrder(order);
3568
+ return _context26.abrupt("return", this.compactOrderListByIdentity(orderList.map(function (order) {
3569
+ return _this23.normalizeRemoteSyncedOrder(order);
2729
3570
  }), "".concat(source, ".snapshotNoDb")).list);
2730
- case 2:
3571
+ case 3:
2731
3572
  remoteSnapshot = cloneDeep(orderList).map(function (order) {
2732
- return _this22.normalizeOrderCollectionsForIngress(order, "".concat(source, ".remoteIngress"));
3573
+ return _this23.normalizeOrderCollectionsForIngress(order, "".concat(source, ".remoteIngress"));
2733
3574
  });
2734
3575
  mergedSnapshot = this.compactOrderListByIdentity(remoteSnapshot.map(function (order) {
2735
- return _this22.normalizeRemoteSyncedOrder(order);
3576
+ return _this23.normalizeRemoteSyncedOrder(order);
2736
3577
  }), "".concat(source, ".remoteSnapshot")).list;
2737
- _context24.prev = 4;
2738
- _context24.next = 7;
2739
- return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23() {
2740
- var existingOrders, orderListSnapshot;
2741
- return _regeneratorRuntime().wrap(function _callee23$(_context23) {
2742
- while (1) switch (_context23.prev = _context23.next) {
3578
+ _context26.prev = 5;
3579
+ _context26.next = 8;
3580
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25() {
3581
+ var existingOrders, protectedLocalOrders, _iterator31, _step31, rawCurrentOrder, currentOrder, protectedIndex, currentNeedsProtection, orderListSnapshot;
3582
+ return _regeneratorRuntime().wrap(function _callee25$(_context25) {
3583
+ while (1) switch (_context25.prev = _context25.next) {
2743
3584
  case 0:
2744
- if (!(typeof _this22.dbManager.getAll === 'function')) {
2745
- _context23.next = 6;
3585
+ if (!(typeof _this23.dbManager.getAll === 'function')) {
3586
+ _context25.next = 6;
2746
3587
  break;
2747
3588
  }
2748
- _context23.next = 3;
2749
- return _this22.dbManager.getAll(INDEXDB_STORE_NAME);
3589
+ _context25.next = 3;
3590
+ return _this23.dbManager.getAll(INDEXDB_STORE_NAME);
2750
3591
  case 3:
2751
- _context23.t0 = _context23.sent;
2752
- _context23.next = 7;
3592
+ _context25.t0 = _context25.sent;
3593
+ _context25.next = 7;
2753
3594
  break;
2754
3595
  case 6:
2755
- _context23.t0 = [];
3596
+ _context25.t0 = [];
2756
3597
  case 7:
2757
- existingOrders = _context23.t0;
2758
- orderListSnapshot = _this22.mergeRemoteSnapshotWithPendingOrders(remoteSnapshot, existingOrders || []);
2759
- mergedSnapshot = _this22.compactOrderListByIdentity(orderListSnapshot, "".concat(source, ".sqliteSnapshot")).list;
2760
- _this22.logInfo('replaceOrdersSnapshotInSQLite-开始', {
3598
+ existingOrders = _context25.t0;
3599
+ protectedLocalOrders = protectedOrdersBeforeRemoteFetch.map(function (order) {
3600
+ return _this23.normalizeOrderCollectionsForIngress(order, "".concat(source, ".protectedBeforeRemoteFetch"));
3601
+ }).filter(function (order) {
3602
+ return _this23.shouldProtectLocalOrderFromRemoteSnapshot(order);
3603
+ });
3604
+ _iterator31 = _createForOfIteratorHelper(existingOrders || []);
3605
+ _context25.prev = 10;
3606
+ _iterator31.s();
3607
+ case 12:
3608
+ if ((_step31 = _iterator31.n()).done) {
3609
+ _context25.next = 23;
3610
+ break;
3611
+ }
3612
+ rawCurrentOrder = _step31.value;
3613
+ currentOrder = _this23.normalizeOrderCollectionsForIngress(rawCurrentOrder, "".concat(source, ".currentSQLite"));
3614
+ protectedIndex = _this23.findOrderIndexByIdentity(protectedLocalOrders, currentOrder);
3615
+ currentNeedsProtection = _this23.shouldProtectLocalOrderFromRemoteSnapshot(currentOrder);
3616
+ if (!(protectedIndex >= 0)) {
3617
+ _context25.next = 20;
3618
+ break;
3619
+ }
3620
+ if (currentNeedsProtection) {
3621
+ protectedLocalOrders[protectedIndex] = currentOrder;
3622
+ } else {
3623
+ protectedLocalOrders.splice(protectedIndex, 1);
3624
+ }
3625
+ return _context25.abrupt("continue", 21);
3626
+ case 20:
3627
+ if (currentNeedsProtection) protectedLocalOrders.push(currentOrder);
3628
+ case 21:
3629
+ _context25.next = 12;
3630
+ break;
3631
+ case 23:
3632
+ _context25.next = 28;
3633
+ break;
3634
+ case 25:
3635
+ _context25.prev = 25;
3636
+ _context25.t1 = _context25["catch"](10);
3637
+ _iterator31.e(_context25.t1);
3638
+ case 28:
3639
+ _context25.prev = 28;
3640
+ _iterator31.f();
3641
+ return _context25.finish(28);
3642
+ case 31:
3643
+ orderListSnapshot = _this23.mergeRemoteSnapshotWithPendingOrders(remoteSnapshot, protectedLocalOrders);
3644
+ mergedSnapshot = _this23.compactOrderListByIdentity(orderListSnapshot, "".concat(source, ".sqliteSnapshot")).list;
3645
+ _this23.logInfo('replaceOrdersSnapshotInSQLite-开始', {
2761
3646
  source: source,
2762
3647
  count: mergedSnapshot.length,
2763
3648
  remoteCount: remoteSnapshot.length,
2764
- preservedPendingCount: mergedSnapshot.length - remoteSnapshot.length
3649
+ protectedBeforeRemoteFetchCount: protectedOrdersBeforeRemoteFetch.length,
3650
+ protectedLocalOrderCount: protectedLocalOrders.length,
3651
+ preservedLocalUnsyncedCount: mergedSnapshot.length - remoteSnapshot.length,
3652
+ protectedPendingPaymentCount: protectedLocalOrders.reduce(function (count, order) {
3653
+ return count + _this23.getIdentifiedPendingPayments(order).length;
3654
+ }, 0),
3655
+ protectedPendingPaymentIdentities: protectedLocalOrders.flatMap(function (order) {
3656
+ return _this23.getIdentifiedPendingPayments(order).map(function (payment) {
3657
+ var _order$order_id5, _external_sale_number5;
3658
+ return {
3659
+ order_id: (_order$order_id5 = order.order_id) !== null && _order$order_id5 !== void 0 ? _order$order_id5 : null,
3660
+ external_sale_number: (_external_sale_number5 = order.external_sale_number) !== null && _external_sale_number5 !== void 0 ? _external_sale_number5 : null,
3661
+ payment_identities: getOrderPaymentIdentityKeys(payment)
3662
+ };
3663
+ });
3664
+ })
2765
3665
  });
2766
- _context23.next = 13;
2767
- return _this22.dbManager.clear(INDEXDB_STORE_NAME);
2768
- case 13:
2769
- _this22.logInfo('replaceOrdersSnapshotInSQLite-clear完成', {
3666
+ _context25.next = 36;
3667
+ return _this23.dbManager.clear(INDEXDB_STORE_NAME);
3668
+ case 36:
3669
+ _this23.logInfo('replaceOrdersSnapshotInSQLite-clear完成', {
2770
3670
  count: mergedSnapshot.length
2771
3671
  });
2772
3672
  if (!(mergedSnapshot.length === 0)) {
2773
- _context23.next = 16;
3673
+ _context25.next = 39;
2774
3674
  break;
2775
3675
  }
2776
- return _context23.abrupt("return");
2777
- case 16:
2778
- _context23.next = 18;
2779
- return _this22.dbManager.bulkAdd(INDEXDB_STORE_NAME, mergedSnapshot);
2780
- case 18:
2781
- _this22.recordRecentSqliteWrite(source, mergedSnapshot);
2782
- _this22.logInfo('replaceOrdersSnapshotInSQLite-bulkAdd完成', {
3676
+ return _context25.abrupt("return");
3677
+ case 39:
3678
+ _context25.next = 41;
3679
+ return _this23.dbManager.bulkAdd(INDEXDB_STORE_NAME, mergedSnapshot);
3680
+ case 41:
3681
+ _this23.recordRecentSqliteWrite(source, mergedSnapshot);
3682
+ _this23.logInfo('replaceOrdersSnapshotInSQLite-bulkAdd完成', {
2783
3683
  source: source,
2784
3684
  count: mergedSnapshot.length
2785
3685
  });
2786
- case 20:
3686
+ case 43:
2787
3687
  case "end":
2788
- return _context23.stop();
3688
+ return _context25.stop();
2789
3689
  }
2790
- }, _callee23);
3690
+ }, _callee25, null, [[10, 25, 28, 31]]);
2791
3691
  })));
2792
- case 7:
2793
- _context24.next = 12;
3692
+ case 8:
3693
+ _context26.next = 13;
2794
3694
  break;
2795
- case 9:
2796
- _context24.prev = 9;
2797
- _context24.t0 = _context24["catch"](4);
3695
+ case 10:
3696
+ _context26.prev = 10;
3697
+ _context26.t0 = _context26["catch"](5);
2798
3698
  this.logError('全量保存订单到 SQLite 失败', {
2799
- error: _context24.t0 instanceof Error ? _context24.t0.message : String(_context24.t0),
3699
+ error: _context26.t0 instanceof Error ? _context26.t0.message : String(_context26.t0),
2800
3700
  orderList: remoteSnapshot.length
2801
3701
  });
2802
- case 12:
2803
- return _context24.abrupt("return", mergedSnapshot);
2804
3702
  case 13:
3703
+ return _context26.abrupt("return", mergedSnapshot);
3704
+ case 14:
2805
3705
  case "end":
2806
- return _context24.stop();
3706
+ return _context26.stop();
2807
3707
  }
2808
- }, _callee24, this, [[4, 9]]);
3708
+ }, _callee26, this, [[5, 10]]);
2809
3709
  }));
2810
- function replaceOrdersSnapshotInSQLite(_x16, _x17) {
3710
+ function replaceOrdersSnapshotInSQLite(_x19, _x20) {
2811
3711
  return _replaceOrdersSnapshotInSQLite.apply(this, arguments);
2812
3712
  }
2813
3713
  return replaceOrdersSnapshotInSQLite;
@@ -2822,38 +3722,38 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
2822
3722
  }, {
2823
3723
  key: "clear",
2824
3724
  value: (function () {
2825
- var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26() {
2826
- var _this23 = this;
2827
- return _regeneratorRuntime().wrap(function _callee26$(_context26) {
2828
- while (1) switch (_context26.prev = _context26.next) {
3725
+ var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee28() {
3726
+ var _this24 = this;
3727
+ return _regeneratorRuntime().wrap(function _callee28$(_context28) {
3728
+ while (1) switch (_context28.prev = _context28.next) {
2829
3729
  case 0:
2830
3730
  this.store.list = [];
2831
3731
  this.store.map = new Map();
2832
3732
  if (!this.dbManager) {
2833
- _context26.next = 5;
3733
+ _context28.next = 5;
2834
3734
  break;
2835
3735
  }
2836
- _context26.next = 5;
2837
- return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25() {
2838
- return _regeneratorRuntime().wrap(function _callee25$(_context25) {
2839
- while (1) switch (_context25.prev = _context25.next) {
3736
+ _context28.next = 5;
3737
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee27() {
3738
+ return _regeneratorRuntime().wrap(function _callee27$(_context27) {
3739
+ while (1) switch (_context27.prev = _context27.next) {
2840
3740
  case 0:
2841
- _context25.next = 2;
2842
- return _this23.dbManager.clear(INDEXDB_STORE_NAME);
3741
+ _context27.next = 2;
3742
+ return _this24.dbManager.clear(INDEXDB_STORE_NAME);
2843
3743
  case 2:
2844
3744
  case "end":
2845
- return _context25.stop();
3745
+ return _context27.stop();
2846
3746
  }
2847
- }, _callee25);
3747
+ }, _callee27);
2848
3748
  })));
2849
3749
  case 5:
2850
3750
  this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, '');
2851
3751
  this.emitOrdersChanged([], 'clear');
2852
3752
  case 7:
2853
3753
  case "end":
2854
- return _context26.stop();
3754
+ return _context28.stop();
2855
3755
  }
2856
- }, _callee26, this);
3756
+ }, _callee28, this);
2857
3757
  }));
2858
3758
  function clear() {
2859
3759
  return _clear.apply(this, arguments);