@pisell/pisellos
Version:
一个可扩展的前端模块化SDK框架,支持插件系统
872 lines (862 loc) • 52.2 kB
JavaScript
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; }
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; }
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); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
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."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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; } } }; }
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); }
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; }
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; }
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); } }
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); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { cloneDeep } from 'lodash-es';
import dayjs from 'dayjs';
import { BaseModule } from "../../../modules/BaseModule";
import { OrderHooks } from "./types";
/**
* SQLite 存储名称
*/
var INDEXDB_STORE_NAME = 'orders';
var ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY = 'server_order_last_full_fetch_at';
/**
* Order 模块 - 基础框架
*/
export var OrderModule = /*#__PURE__*/function (_BaseModule) {
_inherits(OrderModule, _BaseModule);
var _super = _createSuper(OrderModule);
function OrderModule(name, version) {
var _this;
_classCallCheck(this, OrderModule);
_this = _super.call(this, name, version);
_defineProperty(_assertThisInitialized(_this), "defaultName", 'order');
_defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0');
_defineProperty(_assertThisInitialized(_this), "store", void 0);
_defineProperty(_assertThisInitialized(_this), "dbManager", void 0);
_defineProperty(_assertThisInitialized(_this), "orderDataSource", void 0);
_defineProperty(_assertThisInitialized(_this), "pendingSyncMessages", []);
_defineProperty(_assertThisInitialized(_this), "syncTimer", void 0);
_defineProperty(_assertThisInitialized(_this), "ORDER_SYNC_DEBOUNCE_MS", 5000);
// Map<resource_id, OrderId[]> 资源到订单的倒排索引
_defineProperty(_assertThisInitialized(_this), "resourceIdIndex", new Map());
_defineProperty(_assertThisInitialized(_this), "logger", void 0);
// LoggerManager 实例
_defineProperty(_assertThisInitialized(_this), "storage", void 0);
return _this;
}
_createClass(OrderModule, [{
key: "initialize",
value: function () {
var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
var _options$initialState;
var appPlugin, app, _this$store$createdAt, coreData, today, operatingDayBoundary, boundaryTime, boundaryStart, boundaryEnd;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
this.core = core;
this.store = options === null || options === void 0 ? void 0 : options.store;
if (!this.store.map) this.store.map = new Map();
appPlugin = core.getPlugin('app');
app = appPlugin === null || appPlugin === void 0 ? void 0 : appPlugin.getApp();
if (app) {
this.dbManager = app.sqlite;
this.logger = app.logger;
this.storage = app.storage;
coreData = app.data.store.getStore().getDataByModel('core');
if (!((_this$store$createdAt = this.store.createdAtQuery) !== null && _this$store$createdAt !== void 0 && _this$store$createdAt.sales_time_between) && coreData !== null && coreData !== void 0 && coreData.core) {
today = dayjs();
if (coreData !== null && coreData !== void 0 && coreData.core.operating_day_boundary) {
operatingDayBoundary = coreData.core.operating_day_boundary;
if (operatingDayBoundary.type === 'start_time') {
boundaryTime = String(operatingDayBoundary.time || '').trim();
boundaryStart = dayjs("".concat(today.format('YYYY-MM-DD'), " ").concat(boundaryTime));
boundaryEnd = boundaryStart.add(1, 'day');
if (boundaryStart.isValid()) {
this.store.createdAtQuery = {
sales_time_between: [boundaryStart.format('YYYY-MM-DD HH:mm:ss'), boundaryEnd.format('YYYY-MM-DD HH:mm:ss')]
};
} else {
// 边界时间异常时回退到自然日,避免 createdAtQuery 为空导致后续查询异常
this.store.createdAtQuery = {
sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
};
}
} else {
this.store.createdAtQuery = {
sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
};
}
} else {
// TODO: 这里后续可能需要使用店铺营业时间查询
this.store.createdAtQuery = {
sales_time_between: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
};
}
}
}
if (Array.isArray(options === null || options === void 0 || (_options$initialState = options.initialState) === null || _options$initialState === void 0 ? void 0 : _options$initialState.list)) {
this.store.list = options.initialState.list;
this.syncOrdersMap();
this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
} else {
this.store.list = [];
this.store.map = new Map();
}
this.initOrderDataSource();
this.setupOrderSync();
this.logInfo('OrderServer模块初始化完成', {
hasDbManager: !!this.dbManager,
hasLogger: !!this.logger,
initialOrderCount: this.store.list.length
});
case 10:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function initialize(_x, _x2) {
return _initialize.apply(this, arguments);
}
return initialize;
}()
/**
* 记录信息日志
* @param title 日志标题
* @param metadata 日志元数据
*/
}, {
key: "logInfo",
value: function logInfo(title, metadata) {
try {
if (this.logger) {
this.logger.addLog({
type: 'info',
title: "[OrderServerModule] ".concat(title),
metadata: metadata || {}
});
}
} catch (_unused) {
// 日志记录失败不影响主流程
}
}
/**
* 记录错误日志
* @param title 日志标题
* @param metadata 日志元数据
*/
}, {
key: "logError",
value: function logError(title, metadata) {
try {
if (this.logger) {
this.logger.addLog({
type: 'error',
title: "[OrderServerModule] ".concat(title),
metadata: metadata || {}
});
}
} catch (_unused2) {
// 日志记录失败不影响主流程
}
}
}, {
key: "preload",
value: function () {
var _preload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var orders;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.loadOrdersByServer();
case 2:
orders = _context2.sent;
if (!(orders.length === 0)) {
_context2.next = 5;
break;
}
return _context2.abrupt("return");
case 5:
this.store.list = cloneDeep(orders);
this.syncOrdersMap();
this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
case 8:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function preload() {
return _preload.apply(this, arguments);
}
return preload;
}()
}, {
key: "getOrders",
value: function getOrders() {
return this.store.list;
}
}, {
key: "getOrderById",
value: function getOrderById(id) {
return this.store.map.get(this.getIdKey(id));
}
/** 按 order_id 查询(推荐) */
}, {
key: "getOrderByOrderId",
value: function getOrderByOrderId(orderId) {
return this.store.map.get(this.getIdKey(orderId));
}
}, {
key: "loadOrdersByServer",
value: function () {
var _loadOrdersByServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
var orderList, data;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
orderList = [];
if (!this.orderDataSource) {
_context3.next = 13;
break;
}
_context3.prev = 2;
_context3.next = 5;
return this.orderDataSource.run({
http: {
query: this.store.createdAtQuery
}
});
case 5:
data = _context3.sent;
orderList = data || [];
this.markOrderPulledAtNow();
_context3.next = 13;
break;
case 10:
_context3.prev = 10;
_context3.t0 = _context3["catch"](2);
orderList = [];
case 13:
_context3.next = 15;
return this.saveOrdersToSQLite(orderList);
case 15:
_context3.next = 17;
return this.core.effects.emit(OrderHooks.onOrdersLoaded, orderList);
case 17:
return _context3.abrupt("return", orderList);
case 18:
case "end":
return _context3.stop();
}
}, _callee3, this, [[2, 10]]);
}));
function loadOrdersByServer() {
return _loadOrdersByServer.apply(this, arguments);
}
return loadOrdersByServer;
}()
}, {
key: "getOrdersByResourceId",
value: function getOrdersByResourceId(resourceId) {
var _this2 = this;
var ids = this.resourceIdIndex.get(String(resourceId)) || [];
return ids.map(function (id) {
return _this2.store.map.get(id);
}).filter(function (order) {
return !!order;
});
}
}, {
key: "getRoutes",
value: function getRoutes() {
return [];
}
}, {
key: "destroy",
value: function destroy() {
var _this$orderDataSource;
if (this.syncTimer) {
clearTimeout(this.syncTimer);
this.syncTimer = undefined;
}
this.pendingSyncMessages = [];
if ((_this$orderDataSource = this.orderDataSource) !== null && _this$orderDataSource !== void 0 && _this$orderDataSource.destroy) this.orderDataSource.destroy();
_get(_getPrototypeOf(OrderModule.prototype), "destroy", this).call(this);
}
}, {
key: "syncOrdersMap",
value: function syncOrdersMap() {
var _this3 = this;
this.store.map.clear();
this.resourceIdIndex.clear();
var _iterator = _createForOfIteratorHelper(this.store.list),
_step;
try {
var _loop = function _loop() {
var order = _step.value;
var id = order.order_id;
if (id === undefined || id === null) return 1; // continue
_this3.store.map.set(_this3.getIdKey(id), order);
var resourceIds = _this3.extractResourceIds(order);
var _iterator2 = _createForOfIteratorHelper(resourceIds),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var resourceId = _step2.value;
var key = String(resourceId);
var existing = _this3.resourceIdIndex.get(key) || [];
if (existing.some(function (eid) {
return _this3.getIdKey(eid) === _this3.getIdKey(id);
})) continue;
existing.push(id);
_this3.resourceIdIndex.set(key, existing);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
};
for (_iterator.s(); !(_step = _iterator.n()).done;) {
if (_loop()) continue;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
}, {
key: "extractResourceIds",
value: function extractResourceIds(order) {
var ids = new Set();
var visitResources = function visitResources(resources) {
if (!Array.isArray(resources)) return;
resources.forEach(function (resource) {
var rid = resource === null || resource === void 0 ? void 0 : resource.relation_id;
if (rid !== undefined && rid !== null && rid !== '') ids.add(String(rid));
if (Array.isArray(resource === null || resource === void 0 ? void 0 : resource.children)) visitResources(resource.children);
});
};
if (Array.isArray(order === null || order === void 0 ? void 0 : order.bookings)) {
order.bookings.forEach(function (booking) {
return visitResources((booking === null || booking === void 0 ? void 0 : booking.resources) || []);
});
}
return _toConsumableArray(ids);
}
}, {
key: "getOrderDateKey",
value: function getOrderDateKey(order) {
var _order$bookings, _order$bookings2;
var candidates = [order === null || order === void 0 ? void 0 : order.schedule_date, order === null || order === void 0 ? void 0 : order.create_date, order === null || order === void 0 ? void 0 : order.created_at, order === null || order === void 0 || (_order$bookings = order.bookings) === null || _order$bookings === void 0 || (_order$bookings = _order$bookings[0]) === null || _order$bookings === void 0 ? void 0 : _order$bookings.start_date, order === null || order === void 0 || (_order$bookings2 = order.bookings) === null || _order$bookings2 === void 0 || (_order$bookings2 = _order$bookings2[0]) === null || _order$bookings2 === void 0 ? void 0 : _order$bookings2.select_date];
for (var _i = 0, _candidates = candidates; _i < _candidates.length; _i++) {
var v = _candidates[_i];
if (!v) continue;
var text = String(v);
if (!text) continue;
return text.split('T')[0].split(' ')[0];
}
return undefined;
}
/**
* 初始化 OrderDataSource 实例
*/
}, {
key: "initOrderDataSource",
value: function initOrderDataSource() {
var _serverOptions;
var OrderDataSourceClass = (_serverOptions = this.core.serverOptions) === null || _serverOptions === void 0 || (_serverOptions = _serverOptions.All_DATA_SOURCES) === null || _serverOptions === void 0 ? void 0 : _serverOptions.OrderDataSource;
if (!OrderDataSourceClass) return;
this.orderDataSource = new OrderDataSourceClass();
}
/**
* 初始化 pubsub 订阅,监听订单变更
*/
}, {
key: "setupOrderSync",
value: function setupOrderSync() {
var _this4 = this;
if (!this.orderDataSource) return;
var shouldSkipHttpPull = this.hasPulledOrdersToday();
var syncPayload = {
pubsub: {
callback: function callback(res) {
var message = _this4.normalizeOrderSyncMessage(res);
if (!message) return;
_this4.pendingSyncMessages.push(message);
if (_this4.syncTimer) clearTimeout(_this4.syncTimer);
_this4.syncTimer = setTimeout(function () {
_this4.processOrderSyncMessages();
}, _this4.ORDER_SYNC_DEBOUNCE_MS);
}
}
};
syncPayload.http = {
query: this.store.createdAtQuery,
skipHttp: shouldSkipHttpPull
};
this.orderDataSource.run(syncPayload).then(function () {
if (!shouldSkipHttpPull) _this4.markOrderPulledAtNow();
}).catch(function () {
// 忽略同步初始化异常,避免影响主流程
});
}
/**
* 处理防抖后的同步消息批次
*
* 后端统一发送 change 消息,不再区分新增/编辑/删除。
* - 单条(id/order_id):若携带 body/data 则直接 upsert 到本地
* - 批量(ids):通过 HTTP 按 ids 增量拉取,再 merge 到本地
*/
}, {
key: "processOrderSyncMessages",
value: (function () {
var _processOrderSyncMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
var messages, upsertOrders, refreshIds, _iterator3, _step3, _msg$id, _msg$relation_order_i, msg, hasBatchIds, singleId, hasSingleId, rawBody, normalizedBody, uniqueRefreshIds, upsertList, freshOrders;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
messages = _toConsumableArray(this.pendingSyncMessages);
this.pendingSyncMessages = [];
if (!(messages.length === 0)) {
_context4.next = 4;
break;
}
return _context4.abrupt("return");
case 4:
upsertOrders = new Map();
refreshIds = [];
_iterator3 = _createForOfIteratorHelper(messages);
_context4.prev = 7;
_iterator3.s();
case 9:
if ((_step3 = _iterator3.n()).done) {
_context4.next = 22;
break;
}
msg = _step3.value;
hasBatchIds = Array.isArray(msg.ids) && msg.ids.length > 0;
singleId = (_msg$id = msg.id) !== null && _msg$id !== void 0 ? _msg$id : msg.order_id;
hasSingleId = !hasBatchIds && singleId !== undefined && singleId !== null;
rawBody = msg.body || msg.data;
normalizedBody = this.normalizeOrderSyncPayload(rawBody);
if (!(hasSingleId && normalizedBody)) {
_context4.next = 19;
break;
}
upsertOrders.set(this.getIdKey(normalizedBody.order_id), normalizedBody);
return _context4.abrupt("continue", 20);
case 19:
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));
case 20:
_context4.next = 9;
break;
case 22:
_context4.next = 27;
break;
case 24:
_context4.prev = 24;
_context4.t0 = _context4["catch"](7);
_iterator3.e(_context4.t0);
case 27:
_context4.prev = 27;
_iterator3.f();
return _context4.finish(27);
case 30:
uniqueRefreshIds = this.uniqueOrderIds(refreshIds);
upsertList = _toConsumableArray(upsertOrders.values());
if (!(upsertList.length > 0)) {
_context4.next = 35;
break;
}
_context4.next = 35;
return this.mergeOrdersToStore(upsertList);
case 35:
if (!(uniqueRefreshIds.length > 0)) {
_context4.next = 42;
break;
}
_context4.next = 38;
return this.fetchOrdersByHttp(uniqueRefreshIds);
case 38:
freshOrders = _context4.sent;
if (!(freshOrders.length > 0)) {
_context4.next = 42;
break;
}
_context4.next = 42;
return this.mergeOrdersToStore(freshOrders);
case 42:
if (!(upsertList.length === 0 && uniqueRefreshIds.length === 0)) {
_context4.next = 44;
break;
}
return _context4.abrupt("return");
case 44:
_context4.next = 46;
return this.core.effects.emit(OrderHooks.onOrdersSyncCompleted, null);
case 46:
case "end":
return _context4.stop();
}
}, _callee4, this, [[7, 24, 27, 30]]);
}));
function processOrderSyncMessages() {
return _processOrderSyncMessages.apply(this, arguments);
}
return processOrderSyncMessages;
}()
/**
* 通过 HTTP 按 ids 增量拉取订单
*/
)
}, {
key: "fetchOrdersByHttp",
value: (function () {
var _fetchOrdersByHttp = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(ids) {
var _orderList, orderList;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
if (!(!this.orderDataSource || ids.length === 0)) {
_context5.next = 2;
break;
}
return _context5.abrupt("return", []);
case 2:
_context5.prev = 2;
if (!(typeof this.orderDataSource.fetchOrdersByIds === 'function')) {
_context5.next = 8;
break;
}
_context5.next = 6;
return this.orderDataSource.fetchOrdersByIds(ids);
case 6:
_orderList = _context5.sent;
return _context5.abrupt("return", _orderList || []);
case 8:
_context5.next = 10;
return this.orderDataSource.run({
http: {
query: {
ids: ids
}
}
});
case 10:
orderList = _context5.sent;
return _context5.abrupt("return", orderList || []);
case 14:
_context5.prev = 14;
_context5.t0 = _context5["catch"](2);
return _context5.abrupt("return", []);
case 17:
case "end":
return _context5.stop();
}
}, _callee5, this, [[2, 14]]);
}));
function fetchOrdersByHttp(_x3) {
return _fetchOrdersByHttp.apply(this, arguments);
}
return fetchOrdersByHttp;
}()
/**
* 将增量订单合并到 store
*/
)
}, {
key: "mergeOrdersToStore",
value: (function () {
var _mergeOrdersToStore = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(freshOrders) {
var _this5 = this;
var freshMap, _iterator4, _step4, order, id, updatedList, _iterator5, _step5, _order;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
freshMap = new Map();
_iterator4 = _createForOfIteratorHelper(freshOrders);
_context6.prev = 2;
_iterator4.s();
case 4:
if ((_step4 = _iterator4.n()).done) {
_context6.next = 12;
break;
}
order = _step4.value;
id = order === null || order === void 0 ? void 0 : order.order_id;
if (!(id === undefined || id === null)) {
_context6.next = 9;
break;
}
return _context6.abrupt("continue", 10);
case 9:
freshMap.set(this.getIdKey(id), order);
case 10:
_context6.next = 4;
break;
case 12:
_context6.next = 17;
break;
case 14:
_context6.prev = 14;
_context6.t0 = _context6["catch"](2);
_iterator4.e(_context6.t0);
case 17:
_context6.prev = 17;
_iterator4.f();
return _context6.finish(17);
case 20:
updatedList = this.store.list.map(function (order) {
var id = order.order_id;
if (id === undefined || id === null) return order;
var key = _this5.getIdKey(id);
if (!freshMap.has(key)) return order;
var fresh = freshMap.get(key);
freshMap.delete(key);
return fresh;
});
_iterator5 = _createForOfIteratorHelper(freshMap.values());
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
_order = _step5.value;
updatedList.push(_order);
}
} catch (err) {
_iterator5.e(err);
} finally {
_iterator5.f();
}
this.store.list = updatedList;
this.syncOrdersMap();
_context6.next = 27;
return this.saveOrdersToSQLite(this.store.list);
case 27:
this.core.effects.emit(OrderHooks.onOrdersChanged, this.store.list);
case 28:
case "end":
return _context6.stop();
}
}, _callee6, this, [[2, 14, 17, 20]]);
}));
function mergeOrdersToStore(_x4) {
return _mergeOrdersToStore.apply(this, arguments);
}
return mergeOrdersToStore;
}())
}, {
key: "normalizeOrderSyncMessage",
value: function normalizeOrderSyncMessage(res) {
var data = (res === null || res === void 0 ? void 0 : res.data) || res;
if (!data) return null;
var payload = data !== null && data !== void 0 && data.data && _typeof(data.data) === 'object' ? data.data : undefined;
var normalized = _objectSpread(_objectSpread({}, data), {}, {
_channelKey: data.module || 'sales_sync'
});
if (!normalized.type && typeof data.event === 'string') normalized.type = data.event;
if (!normalized.id && data.id !== undefined) normalized.id = data.id;
if (!normalized.id && data.order_id !== undefined) normalized.id = data.order_id;
if (!normalized.order_id && data.order_id !== undefined) normalized.order_id = data.order_id;
if (!normalized.order_id && (payload === null || payload === void 0 ? void 0 : payload.order_id) !== undefined) normalized.order_id = payload.order_id;
if (!normalized.body && (payload === null || payload === void 0 ? void 0 : payload.order_id) !== undefined) normalized.body = payload;
if (!normalized.data && (payload === null || payload === void 0 ? void 0 : payload.order_id) !== undefined) normalized.data = payload;
return normalized;
}
}, {
key: "normalizeOrderSyncPayload",
value: function normalizeOrderSyncPayload(payload) {
if (!payload) return null;
var orderId = payload.order_id;
if (orderId === undefined || orderId === null) return null;
return _objectSpread(_objectSpread({}, payload), {}, {
order_id: orderId
});
}
}, {
key: "uniqueOrderIds",
value: function uniqueOrderIds(ids) {
var idMap = new Map();
var _iterator6 = _createForOfIteratorHelper(ids),
_step6;
try {
for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
var id = _step6.value;
idMap.set(this.getIdKey(id), id);
}
} catch (err) {
_iterator6.e(err);
} finally {
_iterator6.f();
}
return _toConsumableArray(idMap.values());
}
}, {
key: "getIdKey",
value: function getIdKey(id) {
return String(id);
}
/**
* 当前订单拉取窗口:
* - 优先使用 createdAtQuery.sales_time_between(已按营业日边界初始化)
* - 无法解析时退化为自然日窗口
*/
}, {
key: "getCurrentPullWindow",
value: function getCurrentPullWindow() {
var _this$store;
var now = dayjs();
var range = (_this$store = this.store) === null || _this$store === void 0 || (_this$store = _this$store.createdAtQuery) === null || _this$store === void 0 ? void 0 : _this$store.sales_time_between;
if (Array.isArray(range) && range.length >= 2) {
var _startAt = dayjs(range[0]);
var endExclusiveAt = dayjs(range[1]);
if (_startAt.isValid() && endExclusiveAt.isValid() && endExclusiveAt.isAfter(_startAt)) {
return {
startAt: _startAt,
endExclusiveAt: endExclusiveAt
};
}
}
var startAt = now.startOf('day');
return {
startAt: startAt,
endExclusiveAt: startAt.add(1, 'day')
};
}
}, {
key: "hasPulledOrdersToday",
value: function hasPulledOrdersToday() {
var lastFullFetchAt = this.getStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY);
if (!lastFullFetchAt) return false;
var parsed = dayjs(lastFullFetchAt);
if (!parsed.isValid()) return false;
// 按当前拉取窗口判断,而不是自然日判断。
// 这样在营业日跨日边界(start_time)场景下也能正确判定是否需要重新拉取。
var _this$getCurrentPullW = this.getCurrentPullWindow(),
startAt = _this$getCurrentPullW.startAt,
endExclusiveAt = _this$getCurrentPullW.endExclusiveAt;
return (parsed.isAfter(startAt) || parsed.isSame(startAt)) && parsed.isBefore(endExclusiveAt);
}
}, {
key: "markOrderPulledAtNow",
value: function markOrderPulledAtNow() {
this.setStorageItem(ORDER_LAST_FULL_FETCH_AT_STORAGE_KEY, dayjs().format('YYYY-MM-DD HH:mm:ss'));
}
}, {
key: "getStorageItem",
value: function getStorageItem(key) {
try {
var _this$storage;
if ((_this$storage = this.storage) !== null && _this$storage !== void 0 && _this$storage.getStorage) return this.storage.getStorage(key);
if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
return globalThis.localStorage.getItem(key);
}
} catch (_unused5) {
// 忽略存储异常,避免影响主流程
}
return null;
}
}, {
key: "setStorageItem",
value: function setStorageItem(key, value) {
try {
var _this$storage2;
if ((_this$storage2 = this.storage) !== null && _this$storage2 !== void 0 && _this$storage2.setStorage) {
this.storage.setStorage(key, value);
return;
}
if (typeof globalThis !== 'undefined' && globalThis !== null && globalThis !== void 0 && globalThis.localStorage) {
globalThis.localStorage.setItem(key, value);
}
} catch (_unused6) {
// 忽略存储异常,避免影响主流程
}
}
}, {
key: "loadOrdersFromSQLite",
value: function () {
var _loadOrdersFromSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
var orders;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
if (this.dbManager) {
_context7.next = 2;
break;
}
return _context7.abrupt("return", []);
case 2:
_context7.prev = 2;
_context7.next = 5;
return this.dbManager.getAll(INDEXDB_STORE_NAME);
case 5:
orders = _context7.sent;
return _context7.abrupt("return", orders || []);
case 9:
_context7.prev = 9;
_context7.t0 = _context7["catch"](2);
return _context7.abrupt("return", []);
case 12:
case "end":
return _context7.stop();
}
}, _callee7, this, [[2, 9]]);
}));
function loadOrdersFromSQLite() {
return _loadOrdersFromSQLite.apply(this, arguments);
}
return loadOrdersFromSQLite;
}()
}, {
key: "saveOrdersToSQLite",
value: function () {
var _saveOrdersToSQLite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(orderList) {
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
if (this.dbManager) {
_context8.next = 2;
break;
}
return _context8.abrupt("return");
case 2:
_context8.prev = 2;
_context8.next = 5;
return this.dbManager.clear(INDEXDB_STORE_NAME);
case 5:
if (!(orderList.length === 0)) {
_context8.next = 7;
break;
}
return _context8.abrupt("return");
case 7:
_context8.next = 9;
return this.dbManager.bulkAdd(INDEXDB_STORE_NAME, orderList);
case 9:
_context8.next = 14;
break;
case 11:
_context8.prev = 11;
_context8.t0 = _context8["catch"](2);
// SQLite 异常,避免影响主流程
this.logError('保存订单到 SQLite 失败', {
error: _context8.t0 instanceof Error ? _context8.t0.message : String(_context8.t0),
orderList: orderList.length