@pisell/pisellos 2.2.190 → 2.2.191

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 (67) hide show
  1. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  2. package/dist/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +2 -1
  3. package/dist/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +2 -7
  4. package/dist/modules/Cart/utils/cartProduct.js +13 -2
  5. package/dist/modules/Order/index.d.ts +1 -3
  6. package/dist/modules/Order/index.js +69 -95
  7. package/dist/modules/Order/types.d.ts +9 -6
  8. package/dist/modules/Order/utils.d.ts +9 -2
  9. package/dist/modules/Order/utils.js +36 -13
  10. package/dist/modules/SalesSummary/types.d.ts +3 -1
  11. package/dist/modules/SalesSummary/utils.js +7 -3
  12. package/dist/server/modules/order/index.d.ts +126 -6
  13. package/dist/server/modules/order/index.js +1204 -285
  14. package/dist/server/modules/order/types.d.ts +0 -2
  15. package/dist/server/modules/products/index.d.ts +90 -6
  16. package/dist/server/modules/products/index.js +1017 -361
  17. package/dist/solution/BaseSales/index.js +13 -7
  18. package/dist/solution/BaseSales/types.d.ts +8 -5
  19. package/dist/solution/BaseSales/types.js +2 -3
  20. package/dist/solution/BaseSales/utils/cartPromotion.js +7 -7
  21. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +1 -0
  22. package/dist/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +16 -13
  23. package/dist/solution/BaseSales/utils.d.ts +1 -1
  24. package/dist/solution/BaseSales/utils.js +22 -19
  25. package/dist/solution/BookingByStep/index.d.ts +1 -1
  26. package/dist/solution/BookingTicket/index.d.ts +1 -1
  27. package/dist/solution/ScanOrder/index.js +7 -5
  28. package/dist/solution/ScanOrder/types.d.ts +8 -5
  29. package/dist/solution/ScanOrder/types.js +2 -3
  30. package/dist/solution/ScanOrder/utils.d.ts +1 -1
  31. package/dist/solution/ScanOrder/utils.js +26 -23
  32. package/dist/solution/VenueBooking/index.js +5 -3
  33. package/dist/solution/VenueBooking/sales-section-4-annotated.json +0 -2
  34. package/lib/model/strategy/adapter/promotion/index.js +0 -49
  35. package/lib/modules/BookingContext/utils/buildCacheItemFromOrderLine.js +2 -1
  36. package/lib/modules/BookingContext/utils/buildNormalProductCacheItemFromOrderLine.js +2 -1
  37. package/lib/modules/Cart/utils/cartProduct.js +9 -2
  38. package/lib/modules/Order/index.d.ts +1 -3
  39. package/lib/modules/Order/index.js +45 -58
  40. package/lib/modules/Order/types.d.ts +9 -6
  41. package/lib/modules/Order/utils.d.ts +9 -2
  42. package/lib/modules/Order/utils.js +41 -10
  43. package/lib/modules/SalesSummary/types.d.ts +3 -1
  44. package/lib/modules/SalesSummary/utils.js +5 -3
  45. package/lib/server/modules/order/index.d.ts +126 -6
  46. package/lib/server/modules/order/index.js +722 -42
  47. package/lib/server/modules/order/types.d.ts +0 -2
  48. package/lib/server/modules/products/index.d.ts +90 -6
  49. package/lib/server/modules/products/index.js +492 -30
  50. package/lib/solution/BaseSales/index.js +14 -5
  51. package/lib/solution/BaseSales/types.d.ts +8 -5
  52. package/lib/solution/BaseSales/utils/cartPromotion.js +6 -6
  53. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.d.ts +1 -0
  54. package/lib/solution/BaseSales/utils/transformBaseProductToOrderProduct.js +21 -14
  55. package/lib/solution/BaseSales/utils.d.ts +1 -1
  56. package/lib/solution/BaseSales/utils.js +11 -7
  57. package/lib/solution/BookingByStep/index.d.ts +1 -1
  58. package/lib/solution/BookingTicket/index.d.ts +1 -1
  59. package/lib/solution/ScanOrder/index.js +4 -4
  60. package/lib/solution/ScanOrder/types.d.ts +8 -5
  61. package/lib/solution/ScanOrder/utils.d.ts +1 -1
  62. package/lib/solution/ScanOrder/utils.js +12 -8
  63. package/lib/solution/VenueBooking/index.js +2 -2
  64. package/lib/solution/VenueBooking/sales-section-4-annotated.json +0 -2
  65. package/package.json +1 -1
  66. package/dist/solution/Checkout/appointmentDemo.json +0 -1
  67. package/lib/solution/Checkout/appointmentDemo.json +0 -1
@@ -1,13 +1,17 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
1
2
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2
3
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
+ 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; } } }; }
4
5
  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
5
6
  function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
6
7
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
7
8
  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
8
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
9
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
10
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
9
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); }
10
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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
14
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
11
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; }
12
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); } }
13
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); }); }; }
@@ -38,6 +42,21 @@ var INDEXDB_STORE_NAME = 'orders';
38
42
  var ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY = 'server_order_last_full_fetch_at';
39
43
  var ORDER_SYNC_THROTTLE_MS_STORAGE_KEY = 'order_sync_throttle_ms';
40
44
  var DEFAULT_ORDER_SYNC_THROTTLE_MS = 2000;
45
+ /** window 上挂载的订单流程调试日志 key */
46
+ var ORDER_FLOW_LOG_WINDOW_KEY = '__orderModuleFlowLogs';
47
+ /** window 上按订单聚合的 SQLite 写入统计 key */
48
+ var ORDER_WRITE_STATS_WINDOW_KEY = '__orderModuleWriteStats';
49
+ var ORDER_FLOW_LOG_MAX_LENGTH = 1000;
50
+ /** pubsub 回声写入去重窗口:业务 API 刚写入后,跳过同单 SQLite patch */
51
+ var ORDER_SQLITE_DEDUPE_MS = 15000;
52
+ /** silentRefresh 最小间隔,避免 preload 后立即全量重拉 */
53
+ var ORDER_SILENT_REFRESH_MIN_INTERVAL_MS = 30000;
54
+ /** 视为「业务侧刚写入」的来源,pubsub 回声可跳过 SQLite */
55
+ var ORDER_BUSINESS_WRITE_SOURCES = new Set(['upsertOrdersFromRemote', 'overwriteExistingOrder']);
56
+
57
+ /** 订单模块流程调试日志条目 */
58
+
59
+ /** 单笔订单 SQLite 写入记录 */
41
60
 
42
61
  /**
43
62
  * Order 模块 - 基础框架
@@ -64,6 +83,12 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
64
83
  // LoggerManager 实例
65
84
  _defineProperty(_assertThisInitialized(_this), "storage", void 0);
66
85
  _defineProperty(_assertThisInitialized(_this), "orderSQLiteSaveQueue", Promise.resolve());
86
+ /** 全局递增的 SQLite 写入序号,便于日志关联同一次操作 */
87
+ _defineProperty(_assertThisInitialized(_this), "orderFlowWriteSeq", 0);
88
+ /** 按 storageKey 记录最近一次 SQLite 写入来源与时间,用于去重 */
89
+ _defineProperty(_assertThisInitialized(_this), "recentSqliteWriteByStorageKey", new Map());
90
+ /** 最近一次 SSE 全量拉取完成时间 */
91
+ _defineProperty(_assertThisInitialized(_this), "lastServerFullFetchAtMs", 0);
67
92
  return _this;
68
93
  }
69
94
  _createClass(OrderModule, [{
@@ -126,14 +151,21 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
126
151
  this.store.list = [];
127
152
  this.store.map = new Map();
128
153
  }
154
+ this.initOrderFlowLogs();
129
155
  this.initOrderDataSource();
130
156
  this.setupOrderSync();
157
+ this.pushOrderFlowLog('initialize.complete', {
158
+ hasDbManager: !!this.dbManager,
159
+ hasLogger: !!this.logger,
160
+ initialOrderCount: this.store.list.length,
161
+ createdAtQuery: this.store.createdAtQuery || null
162
+ });
131
163
  this.logInfo('OrderServer模块初始化完成', {
132
164
  hasDbManager: !!this.dbManager,
133
165
  hasLogger: !!this.logger,
134
166
  initialOrderCount: this.store.list.length
135
167
  });
136
- case 10:
168
+ case 12:
137
169
  case "end":
138
170
  return _context.stop();
139
171
  }
@@ -184,6 +216,381 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
184
216
  } catch (_unused2) {
185
217
  // 日志记录失败不影响主流程
186
218
  }
219
+ this.pushOrderFlowLog("error.".concat(title), metadata);
220
+ }
221
+
222
+ /**
223
+ * 初始化 window 上的订单流程调试日志数组及辅助方法。
224
+ *
225
+ * @example
226
+ * window.clearOrderModuleFlowLogs()
227
+ * // 操作完成后:
228
+ * copy(window.exportOrderModuleFlowLogs?.() || '[]')
229
+ */
230
+ }, {
231
+ key: "initOrderFlowLogs",
232
+ value: function initOrderFlowLogs() {
233
+ var _this2 = this;
234
+ try {
235
+ var win = typeof globalThis !== 'undefined' ? globalThis.window : undefined;
236
+ if (!win) return;
237
+ win[ORDER_FLOW_LOG_WINDOW_KEY] = [];
238
+ win[ORDER_WRITE_STATS_WINDOW_KEY] = {};
239
+ win.clearOrderModuleFlowLogs = function () {
240
+ win[ORDER_FLOW_LOG_WINDOW_KEY] = [];
241
+ win[ORDER_WRITE_STATS_WINDOW_KEY] = {};
242
+ _this2.orderFlowWriteSeq = 0;
243
+ _this2.recentSqliteWriteByStorageKey.clear();
244
+ _this2.lastServerFullFetchAtMs = 0;
245
+ _this2.pushOrderFlowLog('debug.clear', {});
246
+ };
247
+ win.exportOrderModuleFlowLogs = function () {
248
+ var logs = win[ORDER_FLOW_LOG_WINDOW_KEY] || [];
249
+ return JSON.stringify(logs, null, 2);
250
+ };
251
+ win.exportOrderModuleWriteStats = function () {
252
+ var stats = win[ORDER_WRITE_STATS_WINDOW_KEY] || {};
253
+ return JSON.stringify(stats, null, 2);
254
+ };
255
+ win.summarizeOrderModuleWrites = function () {
256
+ var topN = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 20;
257
+ var stats = win[ORDER_WRITE_STATS_WINDOW_KEY] || {};
258
+ return Object.entries(stats).map(function (_ref) {
259
+ var _last$orderId;
260
+ var _ref2 = _slicedToArray(_ref, 2),
261
+ storageKey = _ref2[0],
262
+ entries = _ref2[1];
263
+ var list = entries || [];
264
+ var sources = _toConsumableArray(new Set(list.map(function (item) {
265
+ return item.source;
266
+ })));
267
+ var last = list[list.length - 1];
268
+ return {
269
+ storageKey: storageKey,
270
+ orderId: (_last$orderId = last === null || last === void 0 ? void 0 : last.orderId) !== null && _last$orderId !== void 0 ? _last$orderId : null,
271
+ writeCount: list.length,
272
+ sources: sources,
273
+ lastWriteAt: (last === null || last === void 0 ? void 0 : last.ts) || ''
274
+ };
275
+ }).sort(function (a, b) {
276
+ return b.writeCount - a.writeCount;
277
+ }).slice(0, topN);
278
+ };
279
+ this.pushOrderFlowLog('debug.init', {
280
+ logKey: ORDER_FLOW_LOG_WINDOW_KEY,
281
+ writeStatsKey: ORDER_WRITE_STATS_WINDOW_KEY,
282
+ helpers: ['clearOrderModuleFlowLogs', 'exportOrderModuleFlowLogs', 'exportOrderModuleWriteStats', 'summarizeOrderModuleWrites']
283
+ });
284
+ } catch (_unused3) {
285
+ // window 不可用时忽略
286
+ }
287
+ }
288
+
289
+ /**
290
+ * 写入 window 订单流程调试日志。
291
+ *
292
+ * @example
293
+ * this.pushOrderFlowLog('mergeOrdersToStore.start', { count: 3 })
294
+ */
295
+ }, {
296
+ key: "pushOrderFlowLog",
297
+ value: function pushOrderFlowLog(step, metadata) {
298
+ try {
299
+ var win = typeof globalThis !== 'undefined' ? globalThis.window : undefined;
300
+ if (!win) return;
301
+ if (!Array.isArray(win[ORDER_FLOW_LOG_WINDOW_KEY])) {
302
+ win[ORDER_FLOW_LOG_WINDOW_KEY] = [];
303
+ }
304
+ var entry = {
305
+ ts: new Date().toISOString(),
306
+ step: step,
307
+ metadata: metadata || {}
308
+ };
309
+ win[ORDER_FLOW_LOG_WINDOW_KEY].push(entry);
310
+ var logs = win[ORDER_FLOW_LOG_WINDOW_KEY];
311
+ if (logs.length > ORDER_FLOW_LOG_MAX_LENGTH) {
312
+ logs.splice(0, logs.length - ORDER_FLOW_LOG_MAX_LENGTH);
313
+ }
314
+ console.log("[OrderFlow] ".concat(step), metadata || {});
315
+ } catch (_unused4) {
316
+ // 调试日志失败不影响主流程
317
+ }
318
+ }
319
+
320
+ /** 当前内存 store 快照信息,供流程日志使用 */
321
+ }, {
322
+ key: "getOrderStoreSnapshot",
323
+ value: function getOrderStoreSnapshot() {
324
+ return {
325
+ storeListCount: this.store.list.length,
326
+ storeMapCount: this.store.map.size,
327
+ pendingSyncCount: this.pendingSyncMessages.length,
328
+ isProcessingSyncBatch: this.isProcessingSyncBatch,
329
+ isIdlePhase: this.isIdlePhase
330
+ };
331
+ }
332
+
333
+ /**
334
+ * 记录一次 SQLite 写入到 window 统计,用于排查同一订单被多次写入的原因。
335
+ *
336
+ * @example
337
+ * this.trackOrderWrite('upsertOrdersFromRemote', 'bulkUpdate', orders, 'insert')
338
+ */
339
+ }, {
340
+ key: "trackOrderWrite",
341
+ value: function trackOrderWrite(source, writeMethod, orders) {
342
+ var mergeActions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
343
+ var defaultMergeAction = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'update';
344
+ this.orderFlowWriteSeq += 1;
345
+ var writeSeq = this.orderFlowWriteSeq;
346
+ try {
347
+ var win = typeof globalThis !== 'undefined' ? globalThis.window : undefined;
348
+ if (!win) return writeSeq;
349
+ if (!win[ORDER_WRITE_STATS_WINDOW_KEY]) {
350
+ win[ORDER_WRITE_STATS_WINDOW_KEY] = {};
351
+ }
352
+ var stats = win[ORDER_WRITE_STATS_WINDOW_KEY];
353
+ var _iterator = _createForOfIteratorHelper(orders),
354
+ _step;
355
+ try {
356
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
357
+ var _order$order_id;
358
+ var order = _step.value;
359
+ var storageKey = this.getOrderStorageKey(order);
360
+ if (!storageKey) continue;
361
+ var orderKey = order.order_id !== undefined && order.order_id !== null ? this.getIdKey(order.order_id) : '';
362
+ var mergeAction = orderKey && mergeActions[orderKey] || defaultMergeAction;
363
+ var entry = {
364
+ ts: new Date().toISOString(),
365
+ writeSeq: writeSeq,
366
+ source: source,
367
+ writeMethod: writeMethod,
368
+ orderId: (_order$order_id = order.order_id) !== null && _order$order_id !== void 0 ? _order$order_id : null,
369
+ storageKey: storageKey,
370
+ mergeAction: mergeAction
371
+ };
372
+ if (!stats[storageKey]) stats[storageKey] = [];
373
+ stats[storageKey].push(entry);
374
+ }
375
+ } catch (err) {
376
+ _iterator.e(err);
377
+ } finally {
378
+ _iterator.f();
379
+ }
380
+ } catch (_unused5) {
381
+ // 统计失败不影响主流程
382
+ }
383
+ return writeSeq;
384
+ }
385
+
386
+ /**
387
+ * 记录订单最近一次 SQLite 写入,供 pubsub 回声去重使用。
388
+ *
389
+ * @example
390
+ * this.recordRecentSqliteWrite('upsertOrdersFromRemote', orders)
391
+ */
392
+ }, {
393
+ key: "recordRecentSqliteWrite",
394
+ value: function recordRecentSqliteWrite(source, orders) {
395
+ var now = Date.now();
396
+ var _iterator2 = _createForOfIteratorHelper(orders),
397
+ _step2;
398
+ try {
399
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
400
+ var order = _step2.value;
401
+ var storageKey = this.getOrderStorageKey(order);
402
+ if (!storageKey) continue;
403
+ this.recentSqliteWriteByStorageKey.set(storageKey, {
404
+ source: source,
405
+ ts: now
406
+ });
407
+ }
408
+ } catch (err) {
409
+ _iterator2.e(err);
410
+ } finally {
411
+ _iterator2.f();
412
+ }
413
+ }
414
+
415
+ /**
416
+ * 过滤 pubsub 触发的冗余 SQLite patch(业务 API 刚写入过的 update 回声)。
417
+ *
418
+ * @example
419
+ * const { toWrite, skipped } = this.filterRedundantPatchOrders('pubsub.bodyUpsert', orders, mergeActions)
420
+ */
421
+ }, {
422
+ key: "filterRedundantPatchOrders",
423
+ value: function filterRedundantPatchOrders(source, orders, mergeActions) {
424
+ var eligibleSkipSources = new Set(['pubsub.bodyUpsert', 'pubsub.httpRefresh']);
425
+ if (!eligibleSkipSources.has(source)) {
426
+ return {
427
+ toWrite: orders,
428
+ skipped: []
429
+ };
430
+ }
431
+ var now = Date.now();
432
+ var toWrite = [];
433
+ var skipped = [];
434
+ var _iterator3 = _createForOfIteratorHelper(orders),
435
+ _step3;
436
+ try {
437
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
438
+ var order = _step3.value;
439
+ var storageKey = this.getOrderStorageKey(order);
440
+ if (!storageKey) {
441
+ toWrite.push(order);
442
+ continue;
443
+ }
444
+ var orderKey = order.order_id !== undefined && order.order_id !== null ? this.getIdKey(order.order_id) : '';
445
+ var mergeAction = orderKey ? mergeActions[orderKey] : undefined;
446
+
447
+ // 新增单必须落库,不参与去重
448
+ if (mergeAction === 'insert') {
449
+ toWrite.push(order);
450
+ continue;
451
+ }
452
+ var recent = this.recentSqliteWriteByStorageKey.get(storageKey);
453
+ if (recent && ORDER_BUSINESS_WRITE_SOURCES.has(recent.source) && now - recent.ts < ORDER_SQLITE_DEDUPE_MS) {
454
+ var _order$order_id2;
455
+ skipped.push({
456
+ orderId: (_order$order_id2 = order.order_id) !== null && _order$order_id2 !== void 0 ? _order$order_id2 : null,
457
+ storageKey: storageKey,
458
+ reason: 'skip_pubsub_echo_after_business_write',
459
+ lastSource: recent.source,
460
+ elapsedMs: now - recent.ts
461
+ });
462
+ continue;
463
+ }
464
+ toWrite.push(order);
465
+ }
466
+ } catch (err) {
467
+ _iterator3.e(err);
468
+ } finally {
469
+ _iterator3.f();
470
+ }
471
+ return {
472
+ toWrite: toWrite,
473
+ skipped: skipped
474
+ };
475
+ }
476
+
477
+ /**
478
+ * 过滤 pubsub HTTP 增量拉取 ids:本地刚由业务 API 写入的单可跳过 HTTP。
479
+ *
480
+ * @example
481
+ * const ids = this.filterRedundantHttpRefreshIds([99331, 99332])
482
+ */
483
+ }, {
484
+ key: "filterRedundantHttpRefreshIds",
485
+ value: function filterRedundantHttpRefreshIds(ids) {
486
+ var now = Date.now();
487
+ var toFetch = [];
488
+ var skipped = [];
489
+ var _iterator4 = _createForOfIteratorHelper(ids),
490
+ _step4;
491
+ try {
492
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
493
+ var id = _step4.value;
494
+ var existing = this.getOrderByOrderId(id);
495
+ if (!existing) {
496
+ toFetch.push(id);
497
+ continue;
498
+ }
499
+ var storageKey = this.getOrderStorageKey(existing);
500
+ var recent = storageKey ? this.recentSqliteWriteByStorageKey.get(storageKey) : undefined;
501
+ if (recent && recent.source === 'upsertOrdersFromRemote' && now - recent.ts < ORDER_SQLITE_DEDUPE_MS) {
502
+ skipped.push({
503
+ orderId: id,
504
+ lastSource: recent.source,
505
+ elapsedMs: now - recent.ts
506
+ });
507
+ continue;
508
+ }
509
+ toFetch.push(id);
510
+ }
511
+ } catch (err) {
512
+ _iterator4.e(err);
513
+ } finally {
514
+ _iterator4.f();
515
+ }
516
+ return {
517
+ toFetch: toFetch,
518
+ skipped: skipped
519
+ };
520
+ }
521
+
522
+ /**
523
+ * 解析 pubsub 消息会走哪条同步分支,便于对照为何触发 HTTP 重拉或 body 直写。
524
+ *
525
+ * @example
526
+ * this.resolveSyncMessageRoute(msg)
527
+ * // => { route: 'httpRefresh.batchIds', ... }
528
+ */
529
+ }, {
530
+ key: "resolveSyncMessageRoute",
531
+ value: function resolveSyncMessageRoute(msg) {
532
+ var _msg$id, _msg$relation_order_i, _normalizedBody$order5;
533
+ var hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
534
+ var singleIdRaw = (_msg$id = msg.id) !== null && _msg$id !== void 0 ? _msg$id : msg.order_id;
535
+ var hasSingleId = !hasBatchIds && singleIdRaw !== undefined && singleIdRaw !== null;
536
+ var normalizedBody = this.normalizeOrderSyncPayload(msg.body || msg.data);
537
+ if (hasBatchIds) {
538
+ var _normalizedBody$order;
539
+ return {
540
+ route: 'httpRefresh.batchIds',
541
+ hasBatchIds: true,
542
+ hasSingleId: false,
543
+ hasNormalizedBody: !!normalizedBody,
544
+ singleId: null,
545
+ batchIds: msg.ids || [],
546
+ bodyOrderId: (_normalizedBody$order = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order !== void 0 ? _normalizedBody$order : null
547
+ };
548
+ }
549
+ if (hasSingleId && normalizedBody) {
550
+ var _normalizedBody$order2;
551
+ return {
552
+ route: 'bodyUpsert',
553
+ hasBatchIds: false,
554
+ hasSingleId: true,
555
+ hasNormalizedBody: true,
556
+ singleId: singleIdRaw,
557
+ batchIds: [],
558
+ bodyOrderId: (_normalizedBody$order2 = normalizedBody.order_id) !== null && _normalizedBody$order2 !== void 0 ? _normalizedBody$order2 : null
559
+ };
560
+ }
561
+ if (hasSingleId) {
562
+ var _normalizedBody$order3;
563
+ return {
564
+ route: 'httpRefresh.singleId',
565
+ hasBatchIds: false,
566
+ hasSingleId: true,
567
+ hasNormalizedBody: !!normalizedBody,
568
+ singleId: singleIdRaw,
569
+ batchIds: [],
570
+ bodyOrderId: (_normalizedBody$order3 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order3 !== void 0 ? _normalizedBody$order3 : null
571
+ };
572
+ }
573
+ if ((_msg$relation_order_i = msg.relation_order_ids) !== null && _msg$relation_order_i !== void 0 && _msg$relation_order_i.length) {
574
+ var _normalizedBody$order4;
575
+ return {
576
+ route: 'httpRefresh.relationIds',
577
+ hasBatchIds: false,
578
+ hasSingleId: false,
579
+ hasNormalizedBody: !!normalizedBody,
580
+ singleId: null,
581
+ batchIds: msg.relation_order_ids,
582
+ bodyOrderId: (_normalizedBody$order4 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order4 !== void 0 ? _normalizedBody$order4 : null
583
+ };
584
+ }
585
+ return {
586
+ route: 'noop',
587
+ hasBatchIds: false,
588
+ hasSingleId: false,
589
+ hasNormalizedBody: !!normalizedBody,
590
+ singleId: null,
591
+ batchIds: [],
592
+ bodyOrderId: (_normalizedBody$order5 = normalizedBody === null || normalizedBody === void 0 ? void 0 : normalizedBody.order_id) !== null && _normalizedBody$order5 !== void 0 ? _normalizedBody$order5 : null
593
+ };
187
594
  }
188
595
  }, {
189
596
  key: "getOrderSyncThrottleMs",
@@ -199,12 +606,12 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
199
606
  key: "preload",
200
607
  value: function () {
201
608
  var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
202
- var _this2 = this;
609
+ var _this3 = this;
203
610
  var getData;
204
611
  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
205
612
  while (1) switch (_context3.prev = _context3.next) {
206
613
  case 0:
207
- // const cachedOrders = await this.loadOrdersFromSQLite()
614
+ this.pushOrderFlowLog('preload.start', this.getOrderStoreSnapshot());
208
615
  // const hasPulledInCurrentWindow = this.hasPulledOrdersToday()
209
616
  // // 仅当缓存属于当前统计窗口时才直接复用,避免跨天/跨营业日窗口继续使用旧数据
210
617
  // if (cachedOrders.length > 0 && hasPulledInCurrentWindow) {
@@ -213,6 +620,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
213
620
  // this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list)
214
621
  // return
215
622
  // }
623
+
216
624
  // if (hasPulledInCurrentWindow) {
217
625
  // this.logInfo('当天已完成全量订单拉取,跳过本次全量拉取', {
218
626
  // lastFullFetchAt: this.getStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY),
@@ -220,41 +628,45 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
220
628
  // return
221
629
  // }
222
630
  getData = /*#__PURE__*/function () {
223
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
631
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
224
632
  var orders;
225
633
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
226
634
  while (1) switch (_context2.prev = _context2.next) {
227
635
  case 0:
228
636
  _context2.next = 2;
229
- return _this2.loadOrdersByServer();
637
+ return _this3.loadOrdersByServer();
230
638
  case 2:
231
639
  orders = _context2.sent;
232
640
  if (!(orders.length === 0)) {
233
- _context2.next = 5;
641
+ _context2.next = 6;
234
642
  break;
235
643
  }
644
+ _this3.pushOrderFlowLog('preload.empty', _this3.getOrderStoreSnapshot());
236
645
  return _context2.abrupt("return");
237
- case 5:
238
- _this2.store.list = cloneDeep(orders);
239
- _this2.syncOrdersMap();
240
- _this2.core.effects.emit(OrderHooks.onOrdersChanged, _this2.store.list);
241
- _this2.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
242
- case 9:
646
+ case 6:
647
+ _this3.store.list = cloneDeep(orders);
648
+ _this3.syncOrdersMap();
649
+ _this3.core.effects.emit(OrderHooks.onOrdersChanged, _this3.store.list);
650
+ _this3.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
651
+ _this3.pushOrderFlowLog('preload.done', _objectSpread(_objectSpread({}, _this3.getOrderStoreSnapshot()), {}, {
652
+ loadedCount: orders.length
653
+ }));
654
+ case 11:
243
655
  case "end":
244
656
  return _context2.stop();
245
657
  }
246
658
  }, _callee2);
247
659
  }));
248
660
  return function getData() {
249
- return _ref.apply(this, arguments);
661
+ return _ref3.apply(this, arguments);
250
662
  };
251
663
  }();
252
664
  getData();
253
- case 2:
665
+ case 3:
254
666
  case "end":
255
667
  return _context3.stop();
256
668
  }
257
- }, _callee3);
669
+ }, _callee3, this);
258
670
  }));
259
671
  function preload() {
260
672
  return _preload.apply(this, arguments);
@@ -282,7 +694,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
282
694
  key: "getLocalOrderByOrderId",
283
695
  value: function () {
284
696
  var _getLocalOrderByOrderId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(orderId) {
285
- var _this3 = this;
697
+ var _this4 = this;
286
698
  var key, memoryOrder, orders, localOrder;
287
699
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
288
700
  while (1) switch (_context4.prev = _context4.next) {
@@ -290,32 +702,40 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
290
702
  key = this.getIdKey(orderId);
291
703
  memoryOrder = this.store.map.get(key);
292
704
  if (!memoryOrder) {
293
- _context4.next = 4;
705
+ _context4.next = 5;
294
706
  break;
295
707
  }
708
+ this.pushOrderFlowLog('getLocalOrderByOrderId.hitMemory', {
709
+ orderId: orderId,
710
+ key: key
711
+ });
296
712
  return _context4.abrupt("return", memoryOrder);
297
- case 4:
298
- _context4.next = 6;
713
+ case 5:
714
+ this.pushOrderFlowLog('getLocalOrderByOrderId.missMemory', {
715
+ orderId: orderId,
716
+ key: key
717
+ });
718
+ _context4.next = 8;
299
719
  return this.loadOrdersFromSQLite();
300
- case 6:
720
+ case 8:
301
721
  orders = _context4.sent;
302
722
  localOrder = orders.find(function (order) {
303
723
  var shopOrderNumber = order === null || order === void 0 ? void 0 : order.shop_order_number;
304
- if (shopOrderNumber && _this3.getIdKey(shopOrderNumber) === key) return true;
724
+ if (shopOrderNumber && _this4.getIdKey(shopOrderNumber) === key) return true;
305
725
  var id = order === null || order === void 0 ? void 0 : order.order_id;
306
726
  if (id === undefined || id === null) return false;
307
- return _this3.getIdKey(id) === key;
727
+ return _this4.getIdKey(id) === key;
308
728
  });
309
729
  if (localOrder) {
310
- _context4.next = 10;
730
+ _context4.next = 12;
311
731
  break;
312
732
  }
313
733
  return _context4.abrupt("return", null);
314
- case 10:
734
+ case 12:
315
735
  this.store.list = orders;
316
736
  this.syncOrdersMap();
317
737
  return _context4.abrupt("return", localOrder);
318
- case 13:
738
+ case 15:
319
739
  case "end":
320
740
  return _context4.stop();
321
741
  }
@@ -330,57 +750,69 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
330
750
  key: "loadOrdersByServer",
331
751
  value: function () {
332
752
  var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
333
- var _this$store;
753
+ var _this$store, _this$store2;
334
754
  var orderList, data;
335
755
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
336
756
  while (1) switch (_context5.prev = _context5.next) {
337
757
  case 0:
338
758
  orderList = [];
759
+ this.pushOrderFlowLog('loadOrdersByServer.start', _objectSpread(_objectSpread({}, this.getOrderStoreSnapshot()), {}, {
760
+ query: ((_this$store = this.store) === null || _this$store === void 0 ? void 0 : _this$store.createdAtQuery) || null,
761
+ hasOrderDataSource: !!this.orderDataSource
762
+ }));
339
763
  this.logInfo('loadOrdersByServer-开始', {
340
764
  hasOrderDataSource: !!this.orderDataSource,
341
- query: ((_this$store = this.store) === null || _this$store === void 0 ? void 0 : _this$store.createdAtQuery) || null
765
+ query: ((_this$store2 = this.store) === null || _this$store2 === void 0 ? void 0 : _this$store2.createdAtQuery) || null
342
766
  });
343
767
  if (!this.orderDataSource) {
344
- _context5.next = 16;
768
+ _context5.next = 20;
345
769
  break;
346
770
  }
347
- _context5.prev = 3;
348
- _context5.next = 6;
771
+ _context5.prev = 4;
772
+ _context5.next = 7;
349
773
  return this.orderDataSource.run({
350
774
  sse: {
351
775
  query: this.store.createdAtQuery
352
776
  }
353
777
  });
354
- case 6:
778
+ case 7:
355
779
  data = _context5.sent;
356
780
  orderList = data || [];
781
+ this.pushOrderFlowLog('loadOrdersByServer.sseSuccess', {
782
+ count: orderList.length
783
+ });
357
784
  this.logInfo('loadOrdersByServer-SSE拉取成功', {
358
785
  count: orderList.length
359
786
  });
360
787
  this.markOrderPulledAtNow();
361
- _context5.next = 16;
788
+ this.lastServerFullFetchAtMs = Date.now();
789
+ _context5.next = 20;
362
790
  break;
363
- case 12:
364
- _context5.prev = 12;
365
- _context5.t0 = _context5["catch"](3);
791
+ case 15:
792
+ _context5.prev = 15;
793
+ _context5.t0 = _context5["catch"](4);
366
794
  orderList = [];
795
+ this.pushOrderFlowLog('loadOrdersByServer.sseFailed', {});
367
796
  this.logInfo('loadOrdersByServer-SSE拉取失败,回退为空数组');
368
- case 16:
369
- _context5.next = 18;
370
- return this.saveOrdersToSQLite(orderList);
371
- case 18:
797
+ case 20:
798
+ _context5.next = 22;
799
+ return this.replaceOrdersSnapshotInSQLite(orderList, 'loadOrdersByServer');
800
+ case 22:
801
+ this.pushOrderFlowLog('loadOrdersByServer.done', _objectSpread({
802
+ count: orderList.length
803
+ }, this.getOrderStoreSnapshot()));
372
804
  this.logInfo('loadOrdersByServer-结束', {
373
805
  count: orderList.length
374
806
  });
375
- _context5.next = 21;
807
+ _context5.next = 26;
376
808
  return this.core.effects.emit(OrderHooks.onOrdersLoaded, orderList);
377
- case 21:
809
+ case 26:
378
810
  return _context5.abrupt("return", orderList);
379
- case 22:
811
+ case 27:
380
812
  case "end":
381
813
  return _context5.stop();
382
814
  }
383
- }, _callee5, this, [[3, 12]]);
815
+ }, _callee5, this, [[4, 15]]);
384
816
  }));
385
817
  function loadOrdersByServer() {
386
818
  return _loadOrdersByServer.apply(this, arguments);
@@ -396,51 +828,72 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
396
828
  key: "silentRefresh",
397
829
  value: (function () {
398
830
  var _silentRefresh = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
399
- var startTime, orders, errorMessage;
831
+ var startTime, elapsedSinceFullFetch, orders, errorMessage;
400
832
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
401
833
  while (1) switch (_context6.prev = _context6.next) {
402
834
  case 0:
403
835
  startTime = Date.now();
836
+ elapsedSinceFullFetch = Date.now() - this.lastServerFullFetchAtMs;
837
+ if (!(this.lastServerFullFetchAtMs > 0 && elapsedSinceFullFetch < ORDER_SILENT_REFRESH_MIN_INTERVAL_MS)) {
838
+ _context6.next = 5;
839
+ break;
840
+ }
841
+ this.pushOrderFlowLog('silentRefresh.skipped', _objectSpread({
842
+ elapsedMs: elapsedSinceFullFetch,
843
+ minIntervalMs: ORDER_SILENT_REFRESH_MIN_INTERVAL_MS
844
+ }, this.getOrderStoreSnapshot()));
845
+ return _context6.abrupt("return", this.store.list);
846
+ case 5:
847
+ this.pushOrderFlowLog('silentRefresh.start', _objectSpread(_objectSpread({}, this.getOrderStoreSnapshot()), {}, {
848
+ callerHint: 'Server.refreshOrdersInBackground 或其他调用方'
849
+ }));
404
850
  this.logInfo('silentRefresh 开始');
405
- _context6.prev = 2;
406
- _context6.next = 5;
851
+ _context6.prev = 7;
852
+ _context6.next = 10;
407
853
  return this.loadOrdersByServer();
408
- case 5:
854
+ case 10:
409
855
  orders = _context6.sent;
410
856
  if (!(orders.length > 0)) {
411
- _context6.next = 15;
857
+ _context6.next = 21;
412
858
  break;
413
859
  }
414
860
  this.store.list = cloneDeep(orders);
415
861
  this.syncOrdersMap();
416
862
  this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
417
- _context6.next = 12;
863
+ _context6.next = 17;
418
864
  return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
419
- case 12:
865
+ case 17:
866
+ this.pushOrderFlowLog('silentRefresh.done', _objectSpread({
867
+ orderCount: orders.length,
868
+ durationMs: Date.now() - startTime
869
+ }, this.getOrderStoreSnapshot()));
420
870
  this.logInfo('silentRefresh 完成', {
421
871
  orderCount: orders.length,
422
872
  duration: "".concat(Date.now() - startTime, "ms")
423
873
  });
424
- _context6.next = 16;
874
+ _context6.next = 23;
425
875
  break;
426
- case 15:
876
+ case 21:
877
+ this.pushOrderFlowLog('silentRefresh.empty', {
878
+ durationMs: Date.now() - startTime
879
+ });
427
880
  this.logInfo('silentRefresh: 服务器未返回数据');
428
- case 16:
881
+ case 23:
429
882
  return _context6.abrupt("return", this.store.list);
430
- case 19:
431
- _context6.prev = 19;
432
- _context6.t0 = _context6["catch"](2);
883
+ case 26:
884
+ _context6.prev = 26;
885
+ _context6.t0 = _context6["catch"](7);
433
886
  errorMessage = _context6.t0 instanceof Error ? _context6.t0.message : String(_context6.t0);
434
887
  this.logError('silentRefresh 失败', {
435
888
  duration: "".concat(Date.now() - startTime, "ms"),
436
889
  error: errorMessage
437
890
  });
438
891
  return _context6.abrupt("return", this.store.list);
439
- case 24:
892
+ case 31:
440
893
  case "end":
441
894
  return _context6.stop();
442
895
  }
443
- }, _callee6, this, [[2, 19]]);
896
+ }, _callee6, this, [[7, 26]]);
444
897
  }));
445
898
  function silentRefresh() {
446
899
  return _silentRefresh.apply(this, arguments);
@@ -450,10 +903,10 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
450
903
  }, {
451
904
  key: "getOrdersByResourceId",
452
905
  value: function getOrdersByResourceId(resourceId) {
453
- var _this4 = this;
906
+ var _this5 = this;
454
907
  var ids = this.resourceIdIndex.get(String(resourceId)) || [];
455
908
  return ids.map(function (id) {
456
- return _this4.store.map.get(id);
909
+ return _this5.store.map.get(id);
457
910
  }).filter(function (order) {
458
911
  return !!order;
459
912
  });
@@ -467,7 +920,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
467
920
  key: "overwriteExistingOrder",
468
921
  value: (function () {
469
922
  var _overwriteExistingOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(fresh) {
470
- var _this5 = this;
923
+ var _this6 = this;
471
924
  var orderId, key;
472
925
  return _regeneratorRuntime().wrap(function _callee7$(_context7) {
473
926
  while (1) switch (_context7.prev = _context7.next) {
@@ -494,6 +947,12 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
494
947
  overwritten: false
495
948
  });
496
949
  case 8:
950
+ this.pushOrderFlowLog('overwriteExistingOrder.start', _objectSpread(_objectSpread({
951
+ orderId: orderId,
952
+ storageKey: this.getOrderStorageKey(fresh)
953
+ }, this.getOrderStoreSnapshot()), {}, {
954
+ callerHint: 'Server.handleUpdateLocalOrder 本地已存在时'
955
+ }));
497
956
  this.logInfo('overwriteExistingOrder-开始覆盖', {
498
957
  orderId: orderId,
499
958
  storeOrderCountBefore: this.store.list.length
@@ -501,23 +960,26 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
501
960
  this.store.list = this.store.list.map(function (order) {
502
961
  var id = order === null || order === void 0 ? void 0 : order.order_id;
503
962
  if (id === undefined || id === null) return order;
504
- return _this5.getIdKey(id) === key ? fresh : order;
963
+ return _this6.getIdKey(id) === key ? fresh : order;
505
964
  });
506
965
  this.syncOrdersMap();
507
- _context7.next = 13;
508
- return this.saveOrdersToSQLite(this.store.list);
509
- case 13:
966
+ _context7.next = 14;
967
+ return this.updateOrderInSQLite(fresh, 'overwriteExistingOrder');
968
+ case 14:
969
+ this.pushOrderFlowLog('overwriteExistingOrder.done', _objectSpread({
970
+ orderId: orderId
971
+ }, this.getOrderStoreSnapshot()));
510
972
  this.logInfo('overwriteExistingOrder-结束', {
511
973
  orderId: orderId,
512
974
  storeOrderCountAfter: this.store.list.length
513
975
  });
514
- _context7.next = 16;
976
+ _context7.next = 18;
515
977
  return this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
516
- case 16:
978
+ case 18:
517
979
  return _context7.abrupt("return", {
518
980
  overwritten: true
519
981
  });
520
- case 17:
982
+ case 19:
521
983
  case "end":
522
984
  return _context7.stop();
523
985
  }
@@ -547,12 +1009,21 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
547
1009
  this.logInfo('upsertOrdersFromRemote-订单列表为空', {});
548
1010
  return _context8.abrupt("return");
549
1011
  case 3:
1012
+ this.pushOrderFlowLog('upsertOrdersFromRemote.start', {
1013
+ count: freshOrders.length,
1014
+ orderIds: freshOrders.map(function (o) {
1015
+ return o.order_id;
1016
+ }).filter(function (id) {
1017
+ return id !== undefined && id !== null;
1018
+ }),
1019
+ callerHint: 'Server.handleUpdateLocalOrder / handleOrderSalesDetail / handleUpdateLocalOrdersBatch'
1020
+ });
550
1021
  this.logInfo('upsertOrdersFromRemote-开始', {
551
1022
  count: freshOrders.length
552
1023
  });
553
- _context8.next = 6;
554
- return this.mergeOrdersToStore(freshOrders);
555
- case 6:
1024
+ _context8.next = 7;
1025
+ return this.mergeOrdersToStore(freshOrders, 'upsertOrdersFromRemote');
1026
+ case 7:
556
1027
  case "end":
557
1028
  return _context8.stop();
558
1029
  }
@@ -633,44 +1104,44 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
633
1104
  }, {
634
1105
  key: "syncOrdersMap",
635
1106
  value: function syncOrdersMap() {
636
- var _this6 = this;
1107
+ var _this7 = this;
637
1108
  this.store.map.clear();
638
1109
  this.resourceIdIndex.clear();
639
- var _iterator = _createForOfIteratorHelper(this.store.list),
640
- _step;
1110
+ var _iterator5 = _createForOfIteratorHelper(this.store.list),
1111
+ _step5;
641
1112
  try {
642
1113
  var _loop = function _loop() {
643
- var order = _step.value;
1114
+ var order = _step5.value;
644
1115
  var id = order.order_id;
645
1116
  if (id === undefined || id === null) return 1; // continue
646
- _this6.store.map.set(_this6.getIdKey(id), order);
647
- var resourceIds = _this6.extractResourceIds(order);
648
- var _iterator2 = _createForOfIteratorHelper(resourceIds),
649
- _step2;
1117
+ _this7.store.map.set(_this7.getIdKey(id), order);
1118
+ var resourceIds = _this7.extractResourceIds(order);
1119
+ var _iterator6 = _createForOfIteratorHelper(resourceIds),
1120
+ _step6;
650
1121
  try {
651
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
652
- var resourceId = _step2.value;
1122
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1123
+ var resourceId = _step6.value;
653
1124
  var key = String(resourceId);
654
- var existing = _this6.resourceIdIndex.get(key) || [];
1125
+ var existing = _this7.resourceIdIndex.get(key) || [];
655
1126
  if (existing.some(function (eid) {
656
- return _this6.getIdKey(eid) === _this6.getIdKey(id);
1127
+ return _this7.getIdKey(eid) === _this7.getIdKey(id);
657
1128
  })) continue;
658
1129
  existing.push(id);
659
- _this6.resourceIdIndex.set(key, existing);
1130
+ _this7.resourceIdIndex.set(key, existing);
660
1131
  }
661
1132
  } catch (err) {
662
- _iterator2.e(err);
1133
+ _iterator6.e(err);
663
1134
  } finally {
664
- _iterator2.f();
1135
+ _iterator6.f();
665
1136
  }
666
1137
  };
667
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1138
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
668
1139
  if (_loop()) continue;
669
1140
  }
670
1141
  } catch (err) {
671
- _iterator.e(err);
1142
+ _iterator5.e(err);
672
1143
  } finally {
673
- _iterator.f();
1144
+ _iterator5.f();
674
1145
  }
675
1146
  }
676
1147
  }, {
@@ -725,28 +1196,38 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
725
1196
  }, {
726
1197
  key: "setupOrderSync",
727
1198
  value: function setupOrderSync() {
728
- var _this7 = this;
1199
+ var _this8 = this;
729
1200
  if (!this.orderDataSource) return;
730
1201
  this.orderDataSource.run({
731
1202
  pubsub: {
732
1203
  callback: function callback(res) {
733
- var _message$id, _message$order_id, _message$type;
734
- console.log('orderDataSource');
1204
+ var _message$id, _message$order_id, _message$type, _message$id2, _message$order_id2, _message$type2;
1205
+ console.log('orderDataSource', res);
735
1206
  var pubsubReceivedAt = Date.now();
736
- var message = _this7.normalizeOrderSyncMessage(res);
1207
+ var message = _this8.normalizeOrderSyncMessage(res);
737
1208
  if (!message) return;
738
1209
  message._pubsubReceivedAt = pubsubReceivedAt;
739
- _this7.pendingSyncMessages.push(message);
740
- var throttleMs = _this7.getOrderSyncThrottleMs();
741
- _this7.logInfo('orderSync-收到消息并入队', {
1210
+ _this8.pendingSyncMessages.push(message);
1211
+ var throttleMs = _this8.getOrderSyncThrottleMs();
1212
+ var routeInfo = _this8.resolveSyncMessageRoute(message);
1213
+ _this8.pushOrderFlowLog('orderSync.received', _objectSpread(_objectSpread({
742
1214
  id: (_message$id = message.id) !== null && _message$id !== void 0 ? _message$id : null,
743
1215
  order_id: (_message$order_id = message.order_id) !== null && _message$order_id !== void 0 ? _message$order_id : null,
744
1216
  type: (_message$type = message.type) !== null && _message$type !== void 0 ? _message$type : null,
745
- pendingCount: _this7.pendingSyncMessages.length,
1217
+ pendingCount: _this8.pendingSyncMessages.length,
1218
+ throttleMs: throttleMs
1219
+ }, routeInfo), {}, {
1220
+ duplicateRiskHint: routeInfo.route === 'httpRefresh.batchIds' && routeInfo.hasNormalizedBody ? '有 body 但被 ids 优先,会走 HTTP 重拉' : routeInfo.route === 'bodyUpsert' ? 'body 直写,可能与 upsertOrdersFromRemote 重复' : null
1221
+ }));
1222
+ _this8.logInfo('orderSync-收到消息并入队', {
1223
+ id: (_message$id2 = message.id) !== null && _message$id2 !== void 0 ? _message$id2 : null,
1224
+ order_id: (_message$order_id2 = message.order_id) !== null && _message$order_id2 !== void 0 ? _message$order_id2 : null,
1225
+ type: (_message$type2 = message.type) !== null && _message$type2 !== void 0 ? _message$type2 : null,
1226
+ pendingCount: _this8.pendingSyncMessages.length,
746
1227
  throttleMs: throttleMs,
747
1228
  pubsubReceivedAt: new Date(pubsubReceivedAt).toISOString()
748
1229
  });
749
- _this7.scheduleOrderSyncThrottle();
1230
+ _this8.scheduleOrderSyncThrottle();
750
1231
  }
751
1232
  }
752
1233
  }).catch(function () {
@@ -763,19 +1244,26 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
763
1244
  }, {
764
1245
  key: "scheduleOrderSyncThrottle",
765
1246
  value: function scheduleOrderSyncThrottle() {
766
- var _this8 = this;
1247
+ var _this9 = this;
767
1248
  if (this.isProcessingSyncBatch) return;
768
1249
  if (this.isIdlePhase) {
769
1250
  this.isIdlePhase = false;
1251
+ this.pushOrderFlowLog('orderSync.flushImmediate', {
1252
+ pendingCount: this.pendingSyncMessages.length
1253
+ });
770
1254
  this.logInfo('orderSync-首条消息立即触发处理');
771
1255
  void this.flushOrderSyncMessagesByThrottle();
772
1256
  return;
773
1257
  }
774
1258
  if (this.syncTimer) return;
775
1259
  var throttleMs = this.getOrderSyncThrottleMs();
1260
+ this.pushOrderFlowLog('orderSync.flushScheduled', {
1261
+ pendingCount: this.pendingSyncMessages.length,
1262
+ throttleMs: throttleMs
1263
+ });
776
1264
  this.syncTimer = setTimeout(function () {
777
- _this8.syncTimer = undefined;
778
- void _this8.flushOrderSyncMessagesByThrottle();
1265
+ _this9.syncTimer = undefined;
1266
+ void _this9.flushOrderSyncMessagesByThrottle();
779
1267
  }, throttleMs);
780
1268
  }
781
1269
 
@@ -804,23 +1292,26 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
804
1292
  return _context10.abrupt("return");
805
1293
  case 5:
806
1294
  this.isProcessingSyncBatch = true;
807
- _context10.prev = 6;
808
- _context10.next = 9;
1295
+ this.pushOrderFlowLog('orderSync.flushStart', {
1296
+ pendingCount: this.pendingSyncMessages.length
1297
+ });
1298
+ _context10.prev = 7;
1299
+ _context10.next = 10;
809
1300
  return this.processOrderSyncMessages();
810
- case 9:
811
- _context10.prev = 9;
1301
+ case 10:
1302
+ _context10.prev = 10;
812
1303
  this.isProcessingSyncBatch = false;
813
1304
  if (this.pendingSyncMessages.length > 0) {
814
1305
  this.scheduleOrderSyncThrottle();
815
1306
  } else {
816
1307
  this.isIdlePhase = true;
817
1308
  }
818
- return _context10.finish(9);
819
- case 13:
1309
+ return _context10.finish(10);
1310
+ case 14:
820
1311
  case "end":
821
1312
  return _context10.stop();
822
1313
  }
823
- }, _callee10, this, [[6,, 9, 13]]);
1314
+ }, _callee10, this, [[7,, 10, 14]]);
824
1315
  }));
825
1316
  function flushOrderSyncMessagesByThrottle() {
826
1317
  return _flushOrderSyncMessagesByThrottle.apply(this, arguments);
@@ -843,7 +1334,8 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
843
1334
  key: "processOrderSyncMessages",
844
1335
  value: (function () {
845
1336
  var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
846
- var messages, batchProcessStartAt, earliestReceivedAt, upsertOrders, refreshIds, _iterator3, _step3, _msg$id, _msg$relation_order_i, msg, hasBatchIds, singleId, hasSingleId, rawBody, normalizedBody, uniqueRefreshIds, upsertList, freshOrders, batchProcessEndAt;
1337
+ var _this10 = this;
1338
+ var messages, batchProcessStartAt, earliestReceivedAt, upsertOrders, refreshIds, uniqueRefreshIds, upsertList, _this$filterRedundant, toFetch, skipped, freshOrders, batchProcessEndAt;
847
1339
  return _regeneratorRuntime().wrap(function _callee11$(_context11) {
848
1340
  while (1) switch (_context11.prev = _context11.next) {
849
1341
  case 0:
@@ -856,6 +1348,9 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
856
1348
  return _context11.abrupt("return");
857
1349
  case 4:
858
1350
  batchProcessStartAt = Date.now();
1351
+ this.pushOrderFlowLog('processOrderSyncMessages.start', _objectSpread({
1352
+ messageCount: messages.length
1353
+ }, this.getOrderStoreSnapshot()));
859
1354
  earliestReceivedAt = Math.min.apply(Math, _toConsumableArray(messages.map(function (m) {
860
1355
  var _m$_pubsubReceivedAt;
861
1356
  return (_m$_pubsubReceivedAt = m._pubsubReceivedAt) !== null && _m$_pubsubReceivedAt !== void 0 ? _m$_pubsubReceivedAt : batchProcessStartAt;
@@ -868,91 +1363,105 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
868
1363
  });
869
1364
  upsertOrders = new Map();
870
1365
  refreshIds = [];
871
- _iterator3 = _createForOfIteratorHelper(messages);
872
- _context11.prev = 10;
873
- _iterator3.s();
874
- case 12:
875
- if ((_step3 = _iterator3.n()).done) {
876
- _context11.next = 25;
877
- break;
878
- }
879
- msg = _step3.value;
880
- hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
881
- singleId = (_msg$id = msg.id) !== null && _msg$id !== void 0 ? _msg$id : msg.order_id;
882
- hasSingleId = !hasBatchIds && singleId !== undefined && singleId !== null;
883
- rawBody = msg.body || msg.data;
884
- normalizedBody = this.normalizeOrderSyncPayload(rawBody);
885
- if (!(hasSingleId && normalizedBody)) {
886
- _context11.next = 22;
887
- break;
888
- }
889
- upsertOrders.set(this.getIdKey(normalizedBody.order_id), normalizedBody);
890
- return _context11.abrupt("continue", 23);
891
- case 22:
892
- if (hasBatchIds) refreshIds.push.apply(refreshIds, _toConsumableArray(msg.ids));else if (hasSingleId) refreshIds.push(singleId);else if ((_msg$relation_order_i = msg.relation_order_ids) !== null && _msg$relation_order_i !== void 0 && _msg$relation_order_i.length) refreshIds.push.apply(refreshIds, _toConsumableArray(msg.relation_order_ids));
893
- case 23:
894
- _context11.next = 12;
895
- break;
896
- case 25:
897
- _context11.next = 30;
898
- break;
899
- case 27:
900
- _context11.prev = 27;
901
- _context11.t0 = _context11["catch"](10);
902
- _iterator3.e(_context11.t0);
903
- case 30:
904
- _context11.prev = 30;
905
- _iterator3.f();
906
- return _context11.finish(30);
907
- case 33:
1366
+ messages.forEach(function (msg, msgIndex) {
1367
+ var routeInfo = _this10.resolveSyncMessageRoute(msg);
1368
+ _this10.pushOrderFlowLog('processOrderSyncMessages.messageRoute', _objectSpread({
1369
+ msgIndex: msgIndex
1370
+ }, routeInfo));
1371
+ var hasBatchIds = routeInfo.hasBatchIds;
1372
+ var singleId = routeInfo.singleId;
1373
+ var hasSingleId = routeInfo.hasSingleId;
1374
+ var normalizedBody = _this10.normalizeOrderSyncPayload(msg.body || msg.data);
1375
+ if (routeInfo.route === 'bodyUpsert' && normalizedBody) {
1376
+ upsertOrders.set(_this10.getIdKey(normalizedBody.order_id), normalizedBody);
1377
+ return;
1378
+ }
1379
+ 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));
1380
+ });
908
1381
  uniqueRefreshIds = this.uniqueOrderIds(refreshIds);
909
1382
  upsertList = _toConsumableArray(upsertOrders.values());
1383
+ this.pushOrderFlowLog('processOrderSyncMessages.deduped', {
1384
+ upsertCount: upsertList.length,
1385
+ upsertOrderIds: upsertList.map(function (o) {
1386
+ return o.order_id;
1387
+ }),
1388
+ refreshIdCount: uniqueRefreshIds.length,
1389
+ refreshIds: uniqueRefreshIds,
1390
+ willCallMergeTimes: (upsertList.length > 0 ? 1 : 0) + (uniqueRefreshIds.length > 0 ? 1 : 0)
1391
+ });
910
1392
  this.logInfo('processOrderSyncMessages-去重完成', {
911
1393
  upsertCount: upsertList.length,
912
1394
  refreshIdCount: uniqueRefreshIds.length
913
1395
  });
914
1396
  if (!(upsertList.length > 0)) {
915
- _context11.next = 39;
1397
+ _context11.next = 18;
916
1398
  break;
917
1399
  }
918
- _context11.next = 39;
919
- return this.mergeOrdersToStore(upsertList);
920
- case 39:
1400
+ _context11.next = 18;
1401
+ return this.mergeOrdersToStore(upsertList, 'pubsub.bodyUpsert');
1402
+ case 18:
921
1403
  if (!(uniqueRefreshIds.length > 0)) {
922
- _context11.next = 46;
1404
+ _context11.next = 31;
923
1405
  break;
924
1406
  }
925
- _context11.next = 42;
926
- return this.fetchOrdersByHttp(uniqueRefreshIds);
927
- case 42:
1407
+ _this$filterRedundant = this.filterRedundantHttpRefreshIds(uniqueRefreshIds), toFetch = _this$filterRedundant.toFetch, skipped = _this$filterRedundant.skipped;
1408
+ if (skipped.length > 0) {
1409
+ this.pushOrderFlowLog('processOrderSyncMessages.httpRefreshFiltered', {
1410
+ requestedIds: uniqueRefreshIds,
1411
+ skippedIds: skipped.map(function (item) {
1412
+ return item.orderId;
1413
+ }),
1414
+ skipped: skipped
1415
+ });
1416
+ }
1417
+ if (!(toFetch.length > 0)) {
1418
+ _context11.next = 31;
1419
+ break;
1420
+ }
1421
+ _context11.next = 24;
1422
+ return this.fetchOrdersByHttp(toFetch);
1423
+ case 24:
928
1424
  freshOrders = _context11.sent;
929
1425
  if (!(freshOrders.length > 0)) {
930
- _context11.next = 46;
1426
+ _context11.next = 30;
931
1427
  break;
932
1428
  }
933
- _context11.next = 46;
934
- return this.mergeOrdersToStore(freshOrders);
935
- case 46:
1429
+ _context11.next = 28;
1430
+ return this.mergeOrdersToStore(freshOrders, 'pubsub.httpRefresh');
1431
+ case 28:
1432
+ _context11.next = 31;
1433
+ break;
1434
+ case 30:
1435
+ this.pushOrderFlowLog('processOrderSyncMessages.httpRefreshEmpty', {
1436
+ refreshIds: toFetch
1437
+ });
1438
+ case 31:
936
1439
  if (!(upsertList.length === 0 && uniqueRefreshIds.length === 0)) {
937
- _context11.next = 48;
1440
+ _context11.next = 34;
938
1441
  break;
939
1442
  }
1443
+ this.pushOrderFlowLog('processOrderSyncMessages.noop', {});
940
1444
  return _context11.abrupt("return");
941
- case 48:
1445
+ case 34:
942
1446
  batchProcessEndAt = Date.now();
1447
+ this.pushOrderFlowLog('processOrderSyncMessages.done', _objectSpread({
1448
+ upsertCount: upsertList.length,
1449
+ refreshIdCount: uniqueRefreshIds.length,
1450
+ batchProcessDurationMs: batchProcessEndAt - batchProcessStartAt
1451
+ }, this.getOrderStoreSnapshot()));
943
1452
  this.logInfo('processOrderSyncMessages-结束', {
944
1453
  upsertCount: upsertList.length,
945
1454
  refreshIdCount: uniqueRefreshIds.length,
946
1455
  batchProcessDurationMs: batchProcessEndAt - batchProcessStartAt,
947
1456
  totalFromPubsubToProcessedMs: batchProcessEndAt - earliestReceivedAt
948
1457
  });
949
- _context11.next = 52;
1458
+ _context11.next = 39;
950
1459
  return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
951
- case 52:
1460
+ case 39:
952
1461
  case "end":
953
1462
  return _context11.stop();
954
1463
  }
955
- }, _callee11, this, [[10, 27, 30, 33]]);
1464
+ }, _callee11, this);
956
1465
  }));
957
1466
  function processOrderSyncMessages() {
958
1467
  return _processOrderSyncMessages.apply(this, arguments);
@@ -984,18 +1493,27 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
984
1493
  }
985
1494
  return _context12.abrupt("return", []);
986
1495
  case 2:
987
- _context12.prev = 2;
1496
+ this.pushOrderFlowLog('fetchOrdersByHttp.start', {
1497
+ ids: ids,
1498
+ count: ids.length
1499
+ });
1500
+ _context12.prev = 3;
988
1501
  if (!(typeof this.orderDataSource.fetchOrdersByIds === 'function')) {
989
- _context12.next = 8;
1502
+ _context12.next = 10;
990
1503
  break;
991
1504
  }
992
- _context12.next = 6;
1505
+ _context12.next = 7;
993
1506
  return this.orderDataSource.fetchOrdersByIds(ids);
994
- case 6:
1507
+ case 7:
995
1508
  _orderList = _context12.sent;
1509
+ this.pushOrderFlowLog('fetchOrdersByHttp.done', {
1510
+ ids: ids,
1511
+ count: (_orderList === null || _orderList === void 0 ? void 0 : _orderList.length) || 0,
1512
+ via: 'fetchOrdersByIds'
1513
+ });
996
1514
  return _context12.abrupt("return", _orderList || []);
997
- case 8:
998
- _context12.next = 10;
1515
+ case 10:
1516
+ _context12.next = 12;
999
1517
  return this.orderDataSource.run({
1000
1518
  http: {
1001
1519
  query: {
@@ -1003,18 +1521,26 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1003
1521
  }
1004
1522
  }
1005
1523
  });
1006
- case 10:
1524
+ case 12:
1007
1525
  orderList = _context12.sent;
1526
+ this.pushOrderFlowLog('fetchOrdersByHttp.done', {
1527
+ ids: ids,
1528
+ count: (orderList === null || orderList === void 0 ? void 0 : orderList.length) || 0,
1529
+ via: 'run.http'
1530
+ });
1008
1531
  return _context12.abrupt("return", orderList || []);
1009
- case 14:
1010
- _context12.prev = 14;
1011
- _context12.t0 = _context12["catch"](2);
1012
- return _context12.abrupt("return", []);
1013
1532
  case 17:
1533
+ _context12.prev = 17;
1534
+ _context12.t0 = _context12["catch"](3);
1535
+ this.pushOrderFlowLog('fetchOrdersByHttp.failed', {
1536
+ ids: ids
1537
+ });
1538
+ return _context12.abrupt("return", []);
1539
+ case 21:
1014
1540
  case "end":
1015
1541
  return _context12.stop();
1016
1542
  }
1017
- }, _callee12, this, [[2, 14]]);
1543
+ }, _callee12, this, [[3, 17]]);
1018
1544
  }));
1019
1545
  function fetchOrdersByHttp(_x6) {
1020
1546
  return _fetchOrdersByHttp.apply(this, arguments);
@@ -1028,87 +1554,123 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1028
1554
  }, {
1029
1555
  key: "mergeOrdersToStore",
1030
1556
  value: (function () {
1031
- var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(freshOrders) {
1032
- var _this9 = this;
1033
- var freshMap, _iterator4, _step4, order, id, uniqueFreshCount, updatedList, _iterator5, _step5, _order;
1557
+ var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(freshOrders, source) {
1558
+ var _this11 = this;
1559
+ var freshMap, _iterator7, _step7, order, id, uniqueFreshCount, patchedOrders, mergeActions, updatedList, _iterator8, _step8, _order, _id, insertCount, updateCount;
1034
1560
  return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1035
1561
  while (1) switch (_context13.prev = _context13.next) {
1036
1562
  case 0:
1563
+ this.pushOrderFlowLog('mergeOrdersToStore.start', _objectSpread({
1564
+ source: source,
1565
+ freshOrderCount: freshOrders.length,
1566
+ freshOrderIds: freshOrders.map(function (o) {
1567
+ return o.order_id;
1568
+ }).filter(function (id) {
1569
+ return id !== undefined && id !== null;
1570
+ })
1571
+ }, this.getOrderStoreSnapshot()));
1037
1572
  this.logInfo('mergeOrdersToStore-开始', {
1038
1573
  freshOrderCount: freshOrders.length,
1039
1574
  storeOrderCountBefore: this.store.list.length
1040
1575
  });
1041
1576
  freshMap = new Map();
1042
- _iterator4 = _createForOfIteratorHelper(freshOrders);
1043
- _context13.prev = 3;
1044
- _iterator4.s();
1045
- case 5:
1046
- if ((_step4 = _iterator4.n()).done) {
1047
- _context13.next = 13;
1577
+ _iterator7 = _createForOfIteratorHelper(freshOrders);
1578
+ _context13.prev = 4;
1579
+ _iterator7.s();
1580
+ case 6:
1581
+ if ((_step7 = _iterator7.n()).done) {
1582
+ _context13.next = 14;
1048
1583
  break;
1049
1584
  }
1050
- order = _step4.value;
1585
+ order = _step7.value;
1051
1586
  id = order === null || order === void 0 ? void 0 : order.order_id;
1052
1587
  if (!(id === undefined || id === null)) {
1053
- _context13.next = 10;
1588
+ _context13.next = 11;
1054
1589
  break;
1055
1590
  }
1056
- return _context13.abrupt("continue", 11);
1057
- case 10:
1058
- freshMap.set(this.getIdKey(id), order);
1591
+ return _context13.abrupt("continue", 12);
1059
1592
  case 11:
1060
- _context13.next = 5;
1593
+ freshMap.set(this.getIdKey(id), order);
1594
+ case 12:
1595
+ _context13.next = 6;
1061
1596
  break;
1062
- case 13:
1063
- _context13.next = 18;
1597
+ case 14:
1598
+ _context13.next = 19;
1064
1599
  break;
1065
- case 15:
1066
- _context13.prev = 15;
1067
- _context13.t0 = _context13["catch"](3);
1068
- _iterator4.e(_context13.t0);
1069
- case 18:
1070
- _context13.prev = 18;
1071
- _iterator4.f();
1072
- return _context13.finish(18);
1073
- case 21:
1600
+ case 16:
1601
+ _context13.prev = 16;
1602
+ _context13.t0 = _context13["catch"](4);
1603
+ _iterator7.e(_context13.t0);
1604
+ case 19:
1605
+ _context13.prev = 19;
1606
+ _iterator7.f();
1607
+ return _context13.finish(19);
1608
+ case 22:
1074
1609
  uniqueFreshCount = freshMap.size;
1610
+ patchedOrders = _toConsumableArray(freshMap.values());
1611
+ mergeActions = {};
1075
1612
  updatedList = this.store.list.map(function (order) {
1076
1613
  var id = order.order_id;
1077
1614
  if (id === undefined || id === null) return order;
1078
- var key = _this9.getIdKey(id);
1615
+ var key = _this11.getIdKey(id);
1079
1616
  if (!freshMap.has(key)) return order;
1080
1617
  var fresh = freshMap.get(key);
1081
1618
  freshMap.delete(key);
1619
+ mergeActions[key] = 'update';
1082
1620
  return fresh;
1083
1621
  });
1084
- _iterator5 = _createForOfIteratorHelper(freshMap.values());
1622
+ _iterator8 = _createForOfIteratorHelper(freshMap.values());
1085
1623
  try {
1086
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
1087
- _order = _step5.value;
1624
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1625
+ _order = _step8.value;
1626
+ _id = _order.order_id;
1627
+ if (_id !== undefined && _id !== null) {
1628
+ mergeActions[this.getIdKey(_id)] = 'insert';
1629
+ }
1088
1630
  updatedList.push(_order);
1089
1631
  }
1090
1632
  } catch (err) {
1091
- _iterator5.e(err);
1633
+ _iterator8.e(err);
1092
1634
  } finally {
1093
- _iterator5.f();
1635
+ _iterator8.f();
1094
1636
  }
1637
+ insertCount = Object.values(mergeActions).filter(function (v) {
1638
+ return v === 'insert';
1639
+ }).length;
1640
+ updateCount = Object.values(mergeActions).filter(function (v) {
1641
+ return v === 'update';
1642
+ }).length;
1095
1643
  this.store.list = updatedList;
1096
1644
  this.syncOrdersMap();
1097
- _context13.next = 29;
1098
- return this.saveOrdersToSQLite(this.store.list);
1099
- case 29:
1645
+ _context13.next = 34;
1646
+ return this.patchOrdersInSQLite(patchedOrders, source, mergeActions);
1647
+ case 34:
1648
+ this.pushOrderFlowLog('mergeOrdersToStore.done', _objectSpread({
1649
+ source: source,
1650
+ uniqueFreshCount: uniqueFreshCount,
1651
+ insertCount: insertCount,
1652
+ updateCount: updateCount,
1653
+ patchedCount: patchedOrders.length,
1654
+ patchedOrderIds: patchedOrders.map(function (o) {
1655
+ return o.order_id;
1656
+ }),
1657
+ patchedStorageKeys: patchedOrders.map(function (o) {
1658
+ return _this11.getOrderStorageKey(o);
1659
+ }),
1660
+ mergeActions: mergeActions
1661
+ }, this.getOrderStoreSnapshot()));
1100
1662
  this.logInfo('mergeOrdersToStore-结束', {
1101
1663
  uniqueFreshCount: uniqueFreshCount,
1102
1664
  storeOrderCountAfter: this.store.list.length
1103
1665
  });
1104
1666
  this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
1105
- case 31:
1667
+ case 37:
1106
1668
  case "end":
1107
1669
  return _context13.stop();
1108
1670
  }
1109
- }, _callee13, this, [[3, 15, 18, 21]]);
1671
+ }, _callee13, this, [[4, 16, 19, 22]]);
1110
1672
  }));
1111
- function mergeOrdersToStore(_x7) {
1673
+ function mergeOrdersToStore(_x7, _x8) {
1112
1674
  return _mergeOrdersToStore.apply(this, arguments);
1113
1675
  }
1114
1676
  return mergeOrdersToStore;
@@ -1145,17 +1707,17 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1145
1707
  key: "uniqueOrderIds",
1146
1708
  value: function uniqueOrderIds(ids) {
1147
1709
  var idMap = new Map();
1148
- var _iterator6 = _createForOfIteratorHelper(ids),
1149
- _step6;
1710
+ var _iterator9 = _createForOfIteratorHelper(ids),
1711
+ _step9;
1150
1712
  try {
1151
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1152
- var id = _step6.value;
1713
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1714
+ var id = _step9.value;
1153
1715
  idMap.set(this.getIdKey(id), id);
1154
1716
  }
1155
1717
  } catch (err) {
1156
- _iterator6.e(err);
1718
+ _iterator9.e(err);
1157
1719
  } finally {
1158
- _iterator6.f();
1720
+ _iterator9.f();
1159
1721
  }
1160
1722
  return _toConsumableArray(idMap.values());
1161
1723
  }
@@ -1165,6 +1727,27 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1165
1727
  return String(id);
1166
1728
  }
1167
1729
 
1730
+ /**
1731
+ * 解析订单 SQLite 主键,规则与宿主 OrderDataSource.getOrderStorageKey 一致。
1732
+ *
1733
+ * @example
1734
+ * const key = this.getOrderStorageKey({ order_id: 1001, external_sale_number: 'S-1001' })
1735
+ * // => 'S-1001'
1736
+ */
1737
+ }, {
1738
+ key: "getOrderStorageKey",
1739
+ value: function getOrderStorageKey(order) {
1740
+ var externalSaleNumber = order === null || order === void 0 ? void 0 : order.external_sale_number;
1741
+ if (externalSaleNumber !== undefined && externalSaleNumber !== null && externalSaleNumber !== '') {
1742
+ return String(externalSaleNumber);
1743
+ }
1744
+ var orderId = order === null || order === void 0 ? void 0 : order.order_id;
1745
+ if (orderId !== undefined && orderId !== null && orderId !== '') {
1746
+ return String(orderId);
1747
+ }
1748
+ return '';
1749
+ }
1750
+
1168
1751
  /**
1169
1752
  * 当前订单拉取窗口:
1170
1753
  * - 优先使用 createdAtQuery.sales_time_between(已按营业日边界初始化)
@@ -1173,9 +1756,9 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1173
1756
  }, {
1174
1757
  key: "getCurrentPullWindow",
1175
1758
  value: function getCurrentPullWindow() {
1176
- var _this$store2;
1759
+ var _this$store3;
1177
1760
  var now = dayjs();
1178
- var range = (_this$store2 = this.store) === null || _this$store2 === void 0 || (_this$store2 = _this$store2.createdAtQuery) === null || _this$store2 === void 0 ? void 0 : _this$store2.sales_time_between;
1761
+ var range = (_this$store3 = this.store) === null || _this$store3 === void 0 || (_this$store3 = _this$store3.createdAtQuery) === null || _this$store3 === void 0 ? void 0 : _this$store3.sales_time_between;
1179
1762
  if (Array.isArray(range) && range.length >= 2) {
1180
1763
  var _startAt = dayjs(range[0]);
1181
1764
  var endExclusiveAt = dayjs(range[1]);
@@ -1221,7 +1804,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1221
1804
  if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
1222
1805
  return globalThis.localStorage.getItem(key);
1223
1806
  }
1224
- } catch (_unused5) {
1807
+ } catch (_unused8) {
1225
1808
  // 忽略存储异常,避免影响主流程
1226
1809
  }
1227
1810
  return null;
@@ -1238,7 +1821,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1238
1821
  if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
1239
1822
  globalThis.localStorage.setItem(key, value);
1240
1823
  }
1241
- } catch (_unused6) {
1824
+ } catch (_unused9) {
1242
1825
  // 忽略存储异常,避免影响主流程
1243
1826
  }
1244
1827
  }
@@ -1278,12 +1861,11 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1278
1861
  return loadOrdersFromSQLite;
1279
1862
  }()
1280
1863
  /**
1281
- * 串行执行订单 SQLite 保存任务,保证 clear + bulkAdd 组合不会被其它订单保存插入。
1864
+ * 串行执行订单 SQLite 写入任务,避免快照替换与增量 upsert 并发交错。
1282
1865
  *
1283
1866
  * @example
1284
1867
  * await this.runInOrderSQLiteSaveQueue(async () => {
1285
- * await this.dbManager.clear(INDEXDB_STORE_NAME)
1286
- * await this.dbManager.bulkAdd(INDEXDB_STORE_NAME, orders)
1868
+ * await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, orders)
1287
1869
  * })
1288
1870
  */
1289
1871
  }, {
@@ -1307,88 +1889,425 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1307
1889
  }
1308
1890
  }, _callee15, this);
1309
1891
  }));
1310
- function runInOrderSQLiteSaveQueue(_x8) {
1892
+ function runInOrderSQLiteSaveQueue(_x9) {
1311
1893
  return _runInOrderSQLiteSaveQueue.apply(this, arguments);
1312
1894
  }
1313
1895
  return runInOrderSQLiteSaveQueue;
1314
1896
  }()
1315
1897
  /**
1316
- * 保存订单列表到 SQLite,内部会先清空 orders 表再批量写入当前快照。
1898
+ * 批量增量 upsert 订单到 SQLite,不清空表;用于 pubsub / HTTP 增量合并。
1317
1899
  *
1318
1900
  * @example
1319
- * await this.saveOrdersToSQLite(this.store.list)
1901
+ * await this.patchOrdersInSQLite(freshOrders)
1320
1902
  */
1321
1903
  )
1322
1904
  }, {
1323
- key: "saveOrdersToSQLite",
1905
+ key: "patchOrdersInSQLite",
1324
1906
  value: (function () {
1325
- var _saveOrdersToSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(orderList) {
1326
- var _this10 = this;
1327
- var orderListSnapshot;
1907
+ var _patchOrdersInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(orders, source) {
1908
+ var _this12 = this;
1909
+ var mergeActions,
1910
+ ordersSnapshot,
1911
+ _this$filterRedundant2,
1912
+ toWrite,
1913
+ skipped,
1914
+ _args17 = arguments;
1328
1915
  return _regeneratorRuntime().wrap(function _callee17$(_context17) {
1329
1916
  while (1) switch (_context17.prev = _context17.next) {
1330
1917
  case 0:
1331
- if (this.dbManager) {
1332
- _context17.next = 2;
1918
+ mergeActions = _args17.length > 2 && _args17[2] !== undefined ? _args17[2] : {};
1919
+ if (!(!this.dbManager || orders.length === 0)) {
1920
+ _context17.next = 4;
1333
1921
  break;
1334
1922
  }
1923
+ this.pushOrderFlowLog('patchOrdersInSQLite.skip', {
1924
+ source: source,
1925
+ hasDbManager: !!this.dbManager,
1926
+ inputCount: orders.length
1927
+ });
1335
1928
  return _context17.abrupt("return");
1336
- case 2:
1337
- orderListSnapshot = cloneDeep(orderList);
1338
- _context17.prev = 3;
1339
- _context17.next = 6;
1929
+ case 4:
1930
+ ordersSnapshot = cloneDeep(orders).filter(function (order) {
1931
+ return _this12.getOrderStorageKey(order);
1932
+ });
1933
+ if (!(ordersSnapshot.length === 0)) {
1934
+ _context17.next = 8;
1935
+ break;
1936
+ }
1937
+ this.pushOrderFlowLog('patchOrdersInSQLite.skipNoStorageKey', {
1938
+ source: source,
1939
+ inputCount: orders.length
1940
+ });
1941
+ return _context17.abrupt("return");
1942
+ case 8:
1943
+ _this$filterRedundant2 = this.filterRedundantPatchOrders(source, ordersSnapshot, mergeActions), toWrite = _this$filterRedundant2.toWrite, skipped = _this$filterRedundant2.skipped;
1944
+ if (skipped.length > 0) {
1945
+ this.pushOrderFlowLog('patchOrdersInSQLite.dedupeSkipped', {
1946
+ source: source,
1947
+ skippedCount: skipped.length,
1948
+ skipped: skipped
1949
+ });
1950
+ }
1951
+ if (!(toWrite.length === 0)) {
1952
+ _context17.next = 13;
1953
+ break;
1954
+ }
1955
+ this.pushOrderFlowLog('patchOrdersInSQLite.skipAllDeduped', {
1956
+ source: source,
1957
+ inputCount: ordersSnapshot.length,
1958
+ skipped: skipped
1959
+ });
1960
+ return _context17.abrupt("return");
1961
+ case 13:
1962
+ _context17.prev = 13;
1963
+ _context17.next = 16;
1340
1964
  return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16() {
1965
+ var writeMethod, _iterator10, _step10, order, writeSeq;
1341
1966
  return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1342
1967
  while (1) switch (_context16.prev = _context16.next) {
1343
1968
  case 0:
1344
- _this10.logInfo('saveOrdersToSQLite-开始', {
1969
+ writeMethod = 'none';
1970
+ _this12.pushOrderFlowLog('patchOrdersInSQLite.start', {
1971
+ source: source,
1972
+ count: toWrite.length,
1973
+ orderIds: toWrite.map(function (o) {
1974
+ return o.order_id;
1975
+ }),
1976
+ storageKeys: toWrite.map(function (o) {
1977
+ return _this12.getOrderStorageKey(o);
1978
+ }),
1979
+ dedupedCount: skipped.length
1980
+ });
1981
+ _this12.logInfo('patchOrdersInSQLite-开始', {
1982
+ source: source,
1983
+ count: toWrite.length
1984
+ });
1985
+ if (!(typeof _this12.dbManager.bulkUpdate === 'function')) {
1986
+ _context16.next = 9;
1987
+ break;
1988
+ }
1989
+ writeMethod = 'bulkUpdate';
1990
+ _context16.next = 7;
1991
+ return _this12.dbManager.bulkUpdate(INDEXDB_STORE_NAME, toWrite);
1992
+ case 7:
1993
+ _context16.next = 34;
1994
+ break;
1995
+ case 9:
1996
+ if (!(typeof _this12.dbManager.bulkAdd === 'function')) {
1997
+ _context16.next = 15;
1998
+ break;
1999
+ }
2000
+ writeMethod = 'bulkAdd';
2001
+ _context16.next = 13;
2002
+ return _this12.dbManager.bulkAdd(INDEXDB_STORE_NAME, toWrite);
2003
+ case 13:
2004
+ _context16.next = 34;
2005
+ break;
2006
+ case 15:
2007
+ if (!(typeof _this12.dbManager.update === 'function')) {
2008
+ _context16.next = 34;
2009
+ break;
2010
+ }
2011
+ writeMethod = 'update';
2012
+ _iterator10 = _createForOfIteratorHelper(toWrite);
2013
+ _context16.prev = 18;
2014
+ _iterator10.s();
2015
+ case 20:
2016
+ if ((_step10 = _iterator10.n()).done) {
2017
+ _context16.next = 26;
2018
+ break;
2019
+ }
2020
+ order = _step10.value;
2021
+ _context16.next = 24;
2022
+ return _this12.dbManager.update(INDEXDB_STORE_NAME, order);
2023
+ case 24:
2024
+ _context16.next = 20;
2025
+ break;
2026
+ case 26:
2027
+ _context16.next = 31;
2028
+ break;
2029
+ case 28:
2030
+ _context16.prev = 28;
2031
+ _context16.t0 = _context16["catch"](18);
2032
+ _iterator10.e(_context16.t0);
2033
+ case 31:
2034
+ _context16.prev = 31;
2035
+ _iterator10.f();
2036
+ return _context16.finish(31);
2037
+ case 34:
2038
+ writeSeq = _this12.trackOrderWrite(source, writeMethod, toWrite, mergeActions);
2039
+ _this12.recordRecentSqliteWrite(source, toWrite);
2040
+ _this12.pushOrderFlowLog('patchOrdersInSQLite.done', {
2041
+ source: source,
2042
+ writeSeq: writeSeq,
2043
+ count: toWrite.length,
2044
+ writeMethod: writeMethod,
2045
+ dedupedCount: skipped.length
2046
+ });
2047
+ _this12.logInfo('patchOrdersInSQLite-完成', {
2048
+ source: source,
2049
+ count: toWrite.length,
2050
+ dedupedCount: skipped.length
2051
+ });
2052
+ case 38:
2053
+ case "end":
2054
+ return _context16.stop();
2055
+ }
2056
+ }, _callee16, null, [[18, 28, 31, 34]]);
2057
+ })));
2058
+ case 16:
2059
+ _context17.next = 22;
2060
+ break;
2061
+ case 18:
2062
+ _context17.prev = 18;
2063
+ _context17.t0 = _context17["catch"](13);
2064
+ this.pushOrderFlowLog('patchOrdersInSQLite.error', {
2065
+ source: source,
2066
+ error: _context17.t0 instanceof Error ? _context17.t0.message : String(_context17.t0),
2067
+ orderCount: ordersSnapshot.length
2068
+ });
2069
+ this.logError('增量保存订单到 SQLite 失败', {
2070
+ error: _context17.t0 instanceof Error ? _context17.t0.message : String(_context17.t0),
2071
+ orderCount: ordersSnapshot.length
2072
+ });
2073
+ case 22:
2074
+ case "end":
2075
+ return _context17.stop();
2076
+ }
2077
+ }, _callee17, this, [[13, 18]]);
2078
+ }));
2079
+ function patchOrdersInSQLite(_x10, _x11) {
2080
+ return _patchOrdersInSQLite.apply(this, arguments);
2081
+ }
2082
+ return patchOrdersInSQLite;
2083
+ }()
2084
+ /**
2085
+ * 单条 upsert 订单到 SQLite;用于 overwriteExistingOrder 等单条覆盖场景。
2086
+ *
2087
+ * @example
2088
+ * await this.updateOrderInSQLite(freshOrder)
2089
+ */
2090
+ )
2091
+ }, {
2092
+ key: "updateOrderInSQLite",
2093
+ value: (function () {
2094
+ var _updateOrderInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19(order, source) {
2095
+ var _this13 = this;
2096
+ var _order$order_id3, orderSnapshot, _orderSnapshot$order_5, _orderSnapshot$order_6;
2097
+ return _regeneratorRuntime().wrap(function _callee19$(_context19) {
2098
+ while (1) switch (_context19.prev = _context19.next) {
2099
+ case 0:
2100
+ if (!(!this.dbManager || !this.getOrderStorageKey(order))) {
2101
+ _context19.next = 3;
2102
+ break;
2103
+ }
2104
+ this.pushOrderFlowLog('updateOrderInSQLite.skip', {
2105
+ source: source,
2106
+ hasDbManager: !!this.dbManager,
2107
+ orderId: (_order$order_id3 = order === null || order === void 0 ? void 0 : order.order_id) !== null && _order$order_id3 !== void 0 ? _order$order_id3 : null
2108
+ });
2109
+ return _context19.abrupt("return");
2110
+ case 3:
2111
+ orderSnapshot = cloneDeep(order);
2112
+ _context19.prev = 4;
2113
+ _context19.next = 7;
2114
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18() {
2115
+ var _orderSnapshot$order_, _orderSnapshot$order_2, _orderSnapshot$order_3, _orderSnapshot$order_4;
2116
+ var writeMethod, writeSeq;
2117
+ return _regeneratorRuntime().wrap(function _callee18$(_context18) {
2118
+ while (1) switch (_context18.prev = _context18.next) {
2119
+ case 0:
2120
+ writeMethod = 'none';
2121
+ _this13.pushOrderFlowLog('updateOrderInSQLite.start', {
2122
+ source: source,
2123
+ orderId: (_orderSnapshot$order_ = orderSnapshot.order_id) !== null && _orderSnapshot$order_ !== void 0 ? _orderSnapshot$order_ : null,
2124
+ storageKey: _this13.getOrderStorageKey(orderSnapshot)
2125
+ });
2126
+ _this13.logInfo('updateOrderInSQLite-开始', {
2127
+ source: source,
2128
+ orderId: (_orderSnapshot$order_2 = orderSnapshot.order_id) !== null && _orderSnapshot$order_2 !== void 0 ? _orderSnapshot$order_2 : null,
2129
+ storageKey: _this13.getOrderStorageKey(orderSnapshot)
2130
+ });
2131
+ if (!(typeof _this13.dbManager.update === 'function')) {
2132
+ _context18.next = 9;
2133
+ break;
2134
+ }
2135
+ writeMethod = 'update';
2136
+ _context18.next = 7;
2137
+ return _this13.dbManager.update(INDEXDB_STORE_NAME, orderSnapshot);
2138
+ case 7:
2139
+ _context18.next = 19;
2140
+ break;
2141
+ case 9:
2142
+ if (!(typeof _this13.dbManager.bulkUpdate === 'function')) {
2143
+ _context18.next = 15;
2144
+ break;
2145
+ }
2146
+ writeMethod = 'bulkUpdate';
2147
+ _context18.next = 13;
2148
+ return _this13.dbManager.bulkUpdate(INDEXDB_STORE_NAME, [orderSnapshot]);
2149
+ case 13:
2150
+ _context18.next = 19;
2151
+ break;
2152
+ case 15:
2153
+ if (!(typeof _this13.dbManager.bulkAdd === 'function')) {
2154
+ _context18.next = 19;
2155
+ break;
2156
+ }
2157
+ writeMethod = 'bulkAdd';
2158
+ _context18.next = 19;
2159
+ return _this13.dbManager.bulkAdd(INDEXDB_STORE_NAME, [orderSnapshot]);
2160
+ case 19:
2161
+ writeSeq = _this13.trackOrderWrite(source, writeMethod, [orderSnapshot], {}, 'singleUpdate');
2162
+ _this13.recordRecentSqliteWrite(source, [orderSnapshot]);
2163
+ _this13.pushOrderFlowLog('updateOrderInSQLite.done', {
2164
+ source: source,
2165
+ writeSeq: writeSeq,
2166
+ orderId: (_orderSnapshot$order_3 = orderSnapshot.order_id) !== null && _orderSnapshot$order_3 !== void 0 ? _orderSnapshot$order_3 : null,
2167
+ storageKey: _this13.getOrderStorageKey(orderSnapshot),
2168
+ writeMethod: writeMethod
2169
+ });
2170
+ _this13.logInfo('updateOrderInSQLite-完成', {
2171
+ orderId: (_orderSnapshot$order_4 = orderSnapshot.order_id) !== null && _orderSnapshot$order_4 !== void 0 ? _orderSnapshot$order_4 : null
2172
+ });
2173
+ case 23:
2174
+ case "end":
2175
+ return _context18.stop();
2176
+ }
2177
+ }, _callee18);
2178
+ })));
2179
+ case 7:
2180
+ _context19.next = 13;
2181
+ break;
2182
+ case 9:
2183
+ _context19.prev = 9;
2184
+ _context19.t0 = _context19["catch"](4);
2185
+ this.pushOrderFlowLog('updateOrderInSQLite.error', {
2186
+ source: source,
2187
+ error: _context19.t0 instanceof Error ? _context19.t0.message : String(_context19.t0),
2188
+ orderId: (_orderSnapshot$order_5 = orderSnapshot.order_id) !== null && _orderSnapshot$order_5 !== void 0 ? _orderSnapshot$order_5 : null
2189
+ });
2190
+ this.logError('单条保存订单到 SQLite 失败', {
2191
+ error: _context19.t0 instanceof Error ? _context19.t0.message : String(_context19.t0),
2192
+ orderId: (_orderSnapshot$order_6 = orderSnapshot.order_id) !== null && _orderSnapshot$order_6 !== void 0 ? _orderSnapshot$order_6 : null
2193
+ });
2194
+ case 13:
2195
+ case "end":
2196
+ return _context19.stop();
2197
+ }
2198
+ }, _callee19, this, [[4, 9]]);
2199
+ }));
2200
+ function updateOrderInSQLite(_x12, _x13) {
2201
+ return _updateOrderInSQLite.apply(this, arguments);
2202
+ }
2203
+ return updateOrderInSQLite;
2204
+ }()
2205
+ /**
2206
+ * 全量快照替换 orders 表(clear + bulkAdd),用于 SSE 全量拉取与营业日窗口裁剪。
2207
+ *
2208
+ * @example
2209
+ * await this.replaceOrdersSnapshotInSQLite(orderList)
2210
+ */
2211
+ )
2212
+ }, {
2213
+ key: "replaceOrdersSnapshotInSQLite",
2214
+ value: (function () {
2215
+ var _replaceOrdersSnapshotInSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(orderList, source) {
2216
+ var _this14 = this;
2217
+ var orderListSnapshot;
2218
+ return _regeneratorRuntime().wrap(function _callee21$(_context21) {
2219
+ while (1) switch (_context21.prev = _context21.next) {
2220
+ case 0:
2221
+ if (this.dbManager) {
2222
+ _context21.next = 3;
2223
+ break;
2224
+ }
2225
+ this.pushOrderFlowLog('replaceOrdersSnapshotInSQLite.skip', {
2226
+ source: source,
2227
+ count: orderList.length
2228
+ });
2229
+ return _context21.abrupt("return");
2230
+ case 3:
2231
+ orderListSnapshot = cloneDeep(orderList);
2232
+ _context21.prev = 4;
2233
+ _context21.next = 7;
2234
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20() {
2235
+ var writeSeq;
2236
+ return _regeneratorRuntime().wrap(function _callee20$(_context20) {
2237
+ while (1) switch (_context20.prev = _context20.next) {
2238
+ case 0:
2239
+ _this14.pushOrderFlowLog('replaceOrdersSnapshotInSQLite.start', {
2240
+ source: source,
2241
+ count: orderListSnapshot.length
2242
+ });
2243
+ _this14.logInfo('replaceOrdersSnapshotInSQLite-开始', {
2244
+ source: source,
1345
2245
  count: orderListSnapshot.length
1346
2246
  });
1347
- _context16.next = 3;
1348
- return _this10.dbManager.clear(INDEXDB_STORE_NAME);
1349
- case 3:
1350
- _this10.logInfo('saveOrdersToSQLite-clear完成', {
2247
+ _context20.next = 4;
2248
+ return _this14.dbManager.clear(INDEXDB_STORE_NAME);
2249
+ case 4:
2250
+ _this14.pushOrderFlowLog('replaceOrdersSnapshotInSQLite.cleared', {
2251
+ source: source,
2252
+ count: orderListSnapshot.length
2253
+ });
2254
+ _this14.logInfo('replaceOrdersSnapshotInSQLite-clear完成', {
1351
2255
  count: orderListSnapshot.length
1352
2256
  });
1353
2257
  if (!(orderListSnapshot.length === 0)) {
1354
- _context16.next = 6;
2258
+ _context20.next = 9;
1355
2259
  break;
1356
2260
  }
1357
- return _context16.abrupt("return");
1358
- case 6:
1359
- _context16.next = 8;
1360
- return _this10.dbManager.bulkAdd(INDEXDB_STORE_NAME, orderListSnapshot);
1361
- case 8:
1362
- _this10.logInfo('saveOrdersToSQLite-bulkAdd完成', {
1363
- count: orderListSnapshot.length
2261
+ _this14.pushOrderFlowLog('replaceOrdersSnapshotInSQLite.doneEmpty', {
2262
+ source: source
1364
2263
  });
2264
+ return _context20.abrupt("return");
1365
2265
  case 9:
2266
+ _context20.next = 11;
2267
+ return _this14.dbManager.bulkAdd(INDEXDB_STORE_NAME, orderListSnapshot);
2268
+ case 11:
2269
+ writeSeq = _this14.trackOrderWrite(source, 'clear+bulkAdd', orderListSnapshot, {}, 'snapshot');
2270
+ _this14.recordRecentSqliteWrite(source, orderListSnapshot);
2271
+ _this14.pushOrderFlowLog('replaceOrdersSnapshotInSQLite.done', {
2272
+ source: source,
2273
+ writeSeq: writeSeq,
2274
+ count: orderListSnapshot.length,
2275
+ writeMethod: 'clear+bulkAdd'
2276
+ });
2277
+ _this14.logInfo('replaceOrdersSnapshotInSQLite-bulkAdd完成', {
2278
+ count: orderListSnapshot.length
2279
+ });
2280
+ case 15:
1366
2281
  case "end":
1367
- return _context16.stop();
2282
+ return _context20.stop();
1368
2283
  }
1369
- }, _callee16);
2284
+ }, _callee20);
1370
2285
  })));
1371
- case 6:
1372
- _context17.next = 11;
2286
+ case 7:
2287
+ _context21.next = 13;
1373
2288
  break;
1374
- case 8:
1375
- _context17.prev = 8;
1376
- _context17.t0 = _context17["catch"](3);
1377
- // SQLite 异常,避免影响主流程
1378
- this.logError('保存订单到 SQLite 失败', {
1379
- error: _context17.t0 instanceof Error ? _context17.t0.message : String(_context17.t0),
2289
+ case 9:
2290
+ _context21.prev = 9;
2291
+ _context21.t0 = _context21["catch"](4);
2292
+ this.pushOrderFlowLog('replaceOrdersSnapshotInSQLite.error', {
2293
+ source: source,
2294
+ error: _context21.t0 instanceof Error ? _context21.t0.message : String(_context21.t0),
1380
2295
  orderList: orderListSnapshot.length
1381
2296
  });
1382
- case 11:
2297
+ this.logError('全量保存订单到 SQLite 失败', {
2298
+ error: _context21.t0 instanceof Error ? _context21.t0.message : String(_context21.t0),
2299
+ orderList: orderListSnapshot.length
2300
+ });
2301
+ case 13:
1383
2302
  case "end":
1384
- return _context17.stop();
2303
+ return _context21.stop();
1385
2304
  }
1386
- }, _callee17, this, [[3, 8]]);
2305
+ }, _callee21, this, [[4, 9]]);
1387
2306
  }));
1388
- function saveOrdersToSQLite(_x9) {
1389
- return _saveOrdersToSQLite.apply(this, arguments);
2307
+ function replaceOrdersSnapshotInSQLite(_x14, _x15) {
2308
+ return _replaceOrdersSnapshotInSQLite.apply(this, arguments);
1390
2309
  }
1391
- return saveOrdersToSQLite;
2310
+ return replaceOrdersSnapshotInSQLite;
1392
2311
  }()
1393
2312
  /**
1394
2313
  * 清空订单模块的内存数据和本地 SQLite 订单表。
@@ -1400,39 +2319,39 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
1400
2319
  }, {
1401
2320
  key: "clear",
1402
2321
  value: (function () {
1403
- var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19() {
1404
- var _this11 = this;
1405
- return _regeneratorRuntime().wrap(function _callee19$(_context19) {
1406
- while (1) switch (_context19.prev = _context19.next) {
2322
+ var _clear = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23() {
2323
+ var _this15 = this;
2324
+ return _regeneratorRuntime().wrap(function _callee23$(_context23) {
2325
+ while (1) switch (_context23.prev = _context23.next) {
1407
2326
  case 0:
1408
2327
  this.store.list = [];
1409
2328
  this.store.map = new Map();
1410
2329
  this.resourceIdIndex.clear();
1411
2330
  if (!this.dbManager) {
1412
- _context19.next = 6;
2331
+ _context23.next = 6;
1413
2332
  break;
1414
2333
  }
1415
- _context19.next = 6;
1416
- return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18() {
1417
- return _regeneratorRuntime().wrap(function _callee18$(_context18) {
1418
- while (1) switch (_context18.prev = _context18.next) {
2334
+ _context23.next = 6;
2335
+ return this.runInOrderSQLiteSaveQueue( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22() {
2336
+ return _regeneratorRuntime().wrap(function _callee22$(_context22) {
2337
+ while (1) switch (_context22.prev = _context22.next) {
1419
2338
  case 0:
1420
- _context18.next = 2;
1421
- return _this11.dbManager.clear(INDEXDB_STORE_NAME);
2339
+ _context22.next = 2;
2340
+ return _this15.dbManager.clear(INDEXDB_STORE_NAME);
1422
2341
  case 2:
1423
2342
  case "end":
1424
- return _context18.stop();
2343
+ return _context22.stop();
1425
2344
  }
1426
- }, _callee18);
2345
+ }, _callee22);
1427
2346
  })));
1428
2347
  case 6:
1429
2348
  this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, '');
1430
2349
  this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
1431
2350
  case 8:
1432
2351
  case "end":
1433
- return _context19.stop();
2352
+ return _context23.stop();
1434
2353
  }
1435
- }, _callee19, this);
2354
+ }, _callee23, this);
1436
2355
  }));
1437
2356
  function clear() {
1438
2357
  return _clear.apply(this, arguments);