@pisell/pisellos
Version:
一个可扩展的前端模块化SDK框架,支持插件系统
886 lines (870 loc) • 101 kB
JavaScript
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
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."); }
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; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return 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 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 _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 _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 dayjs from 'dayjs';
import { ProductsModule } from "./modules/products";
import { MenuModule } from "./modules/menu";
import { QuotationModule } from "./modules/quotation";
import { ScheduleModuleEx } from "./modules/schedule";
import { ResourceModule } from "./modules/resource";
import { extractScheduleIdsFromMenus, extractTimePointsFromSchedules } from "./utils/schedule";
import { ProductsHooks } from "./modules/products/types";
import { perfMark } from "./utils/product";
import { OrderModule } from "./modules/order";
import { OrderHooks } from "./modules/order/types";
import { filterOrders } from "./modules/order/utils/filterOrders";
import { filterBookingsFromOrders, sortBookings } from "./modules/order/utils/filterBookings";
// 重新导出类型供外部使用
/** 商品查询订阅者 */
/** 订单列表查询订阅者 */
/** 预约列表查询订阅者 */
/**
* Server 类
* 用于注册和管理服务端模块
*/
var Server = /*#__PURE__*/function () {
function Server(core) {
var _this = this,
_this$app;
_classCallCheck(this, Server);
_defineProperty(this, "core", void 0);
_defineProperty(this, "app", void 0);
// App instance
_defineProperty(this, "logger", void 0);
// LoggerManager instance
// 模块实例
_defineProperty(this, "products", void 0);
_defineProperty(this, "menu", void 0);
_defineProperty(this, "quotation", void 0);
_defineProperty(this, "schedule", void 0);
_defineProperty(this, "resource", void 0);
_defineProperty(this, "order", void 0);
// 路由注册表
_defineProperty(this, "router", {
get: {},
post: {},
put: {},
remove: {}
});
// ---- 商品查询订阅者 ----
_defineProperty(this, "productQuerySubscribers", new Map());
// ---- 订单 / 预约列表查询订阅者 ----
_defineProperty(this, "orderQuerySubscribers", new Map());
_defineProperty(this, "bookingQuerySubscribers", new Map());
// 模块注册表 - 定义所有可用的模块配置
_defineProperty(this, "moduleRegistry", {
products: {
name: 'products',
moduleClass: ProductsModule,
moduleName: 'server_products',
version: '1.0.0',
defaultStore: {
list: [],
selectProducts: []
}
},
menu: {
name: 'menu',
moduleClass: MenuModule,
moduleName: 'server_menu',
version: '1.0.0',
defaultStore: {
menuList: []
}
},
quotation: {
name: 'quotation',
moduleClass: QuotationModule,
moduleName: 'server_quotation',
version: '1.0.0',
defaultStore: {
quotationList: []
}
},
schedule: {
name: 'schedule',
moduleClass: ScheduleModuleEx,
moduleName: 'server_schedule',
version: '1.1.0',
defaultStore: {
scheduleList: [],
availabilityDateList: [],
otherProductsIds: []
}
},
order: {
name: 'order',
moduleClass: OrderModule,
moduleName: 'server_order',
version: '1.0.0',
defaultStore: {
list: []
}
},
resource: {
name: 'resource',
moduleClass: ResourceModule,
moduleName: 'server_resource',
version: '1.0.0',
defaultStore: {
list: [],
map: new Map(),
bookings: []
}
}
});
/**
* 处理商品查询请求
* 存储订阅者信息,便于数据变更时推送最新结果
*/
_defineProperty(this, "handleProductQuery", /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
var url, method, data, config, menu_list_ids, schedule_datetime, schedule_date, _ref3, callback, subscriberId;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
url = _ref.url, method = _ref.method, data = _ref.data, config = _ref.config;
console.log('[Server] handleProductQuery:', url, method, data, config);
menu_list_ids = data.menu_list_ids, schedule_datetime = data.schedule_datetime, schedule_date = data.schedule_date;
_ref3 = config || {}, callback = _ref3.callback, subscriberId = _ref3.subscriberId;
_this.logInfo('handleProductQuery: 开始处理商品查询请求', {
menu_list_ids: menu_list_ids,
schedule_datetime: schedule_datetime,
schedule_date: schedule_date
});
// 存储订阅者:后续 pubsub 数据变更时可通过 callback 推送最新结果
if (subscriberId && typeof callback === 'function') {
_this.productQuerySubscribers.set(subscriberId, {
callback: callback,
context: {
menu_list_ids: menu_list_ids,
schedule_date: schedule_date,
schedule_datetime: schedule_datetime
}
});
_this.logInfo('handleProductQuery: 已注册订阅者', {
subscriberId: subscriberId,
totalSubscribers: _this.productQuerySubscribers.size
});
}
return _context.abrupt("return", _this.computeProductQueryResult({
menu_list_ids: menu_list_ids,
schedule_date: schedule_date,
schedule_datetime: schedule_datetime
}));
case 7:
case "end":
return _context.stop();
}
}, _callee);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}());
/**
* 取消商品查询订阅(HTTP 路由入口)
*/
_defineProperty(this, "handleUnsubscribeProductQuery", /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref4) {
var data, _ref6, subscriberId;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
data = _ref4.data;
_ref6 = data || {}, subscriberId = _ref6.subscriberId;
_this.removeProductQuerySubscriber(subscriberId);
return _context2.abrupt("return", {
code: 200,
message: 'ok',
status: true
});
case 4:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function (_x2) {
return _ref5.apply(this, arguments);
};
}());
/**
* 处理订单列表查询
* 存储订阅者信息,本地计算结果;数据变更时通过 callback 推送
*/
_defineProperty(this, "handleOrderList", /*#__PURE__*/function () {
var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref7) {
var url, method, data, config, queryPayload, _ref9, callback, subscriberId;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
url = _ref7.url, method = _ref7.method, data = _ref7.data, config = _ref7.config;
console.log('[Server] handleOrderList:', url, method, data, config);
queryPayload = data && _typeof(data) === 'object' ? _objectSpread({}, data) : {};
_ref9 = config || {}, callback = _ref9.callback, subscriberId = _ref9.subscriberId;
_this.logInfo('handleOrderList: 开始处理订单列表请求', {
data: queryPayload
});
if (subscriberId && typeof callback === 'function') {
_this.orderQuerySubscribers.set(subscriberId, {
callback: callback,
context: queryPayload
});
_this.logInfo('handleOrderList: 已注册订阅者', {
subscriberId: subscriberId,
totalSubscribers: _this.orderQuerySubscribers.size
});
}
return _context3.abrupt("return", _this.computeOrderQueryResult(queryPayload));
case 7:
case "end":
return _context3.stop();
}
}, _callee3);
}));
return function (_x3) {
return _ref8.apply(this, arguments);
};
}());
/**
* 取消订单列表查询订阅(HTTP 路由入口)
*/
_defineProperty(this, "handleUnsubscribeOrderQuery", /*#__PURE__*/function () {
var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref10) {
var data, _ref12, subscriberId;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
data = _ref10.data;
_ref12 = data || {}, subscriberId = _ref12.subscriberId;
if (subscriberId) {
_this.orderQuerySubscribers.delete(subscriberId);
_this.logInfo('handleUnsubscribeOrderQuery: 已移除订阅者', {
subscriberId: subscriberId,
remaining: _this.orderQuerySubscribers.size
});
}
return _context4.abrupt("return", {
code: 200,
message: 'ok',
status: true
});
case 4:
case "end":
return _context4.stop();
}
}, _callee4);
}));
return function (_x4) {
return _ref11.apply(this, arguments);
};
}());
/**
* 处理预约列表查询
* 今天:注册订阅者 + 本地数据筛选;非今天:清理订阅者 + 走真实 API
*/
_defineProperty(this, "handleBookingList", /*#__PURE__*/function () {
var _ref14 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref13) {
var url, method, data, config, queryPayload, _ref15, callback, subscriberId, isToday;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
url = _ref13.url, method = _ref13.method, data = _ref13.data, config = _ref13.config;
console.log('[Server] handleBookingList:', url, method, data, config);
queryPayload = data && _typeof(data) === 'object' ? _objectSpread({}, data) : {};
_ref15 = config || {}, callback = _ref15.callback, subscriberId = _ref15.subscriberId;
isToday = _this.isBookingQueryForToday(queryPayload);
_this.logInfo('handleBookingList: 开始处理预约列表请求', {
data: queryPayload,
isToday: isToday
});
if (!isToday) {
_context5.next = 11;
break;
}
if (subscriberId && typeof callback === 'function') {
_this.bookingQuerySubscribers.set(subscriberId, {
callback: callback,
context: queryPayload
});
_this.logInfo('handleBookingList: 已注册订阅者(今天)', {
subscriberId: subscriberId,
totalSubscribers: _this.bookingQuerySubscribers.size
});
}
return _context5.abrupt("return", _this.computeBookingQueryResult(queryPayload));
case 11:
if (subscriberId) {
_this.bookingQuerySubscribers.delete(subscriberId);
_this.logInfo('handleBookingList: 已清理订阅者(非今天)', {
subscriberId: subscriberId,
remaining: _this.bookingQuerySubscribers.size
});
}
return _context5.abrupt("return", _this.fetchBookingListFromAPI(queryPayload));
case 13:
case "end":
return _context5.stop();
}
}, _callee5);
}));
return function (_x5) {
return _ref14.apply(this, arguments);
};
}());
/**
* 处理资源列表查询
* 转发到资源模块去
*/
_defineProperty(this, "handleResourceList", /*#__PURE__*/function () {
var _ref17 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref16) {
var _this$resource;
var url, method, data, config, list;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
url = _ref16.url, method = _ref16.method, data = _ref16.data, config = _ref16.config;
console.log('[Server] handleResourceList:', url, method, data, config);
list = (_this$resource = _this.resource) === null || _this$resource === void 0 ? void 0 : _this$resource.getResources({
skip: (data === null || data === void 0 ? void 0 : data.skip) || 1,
num: (data === null || data === void 0 ? void 0 : data.num) || 10
});
return _context6.abrupt("return", {
code: 200,
data: {
list: list,
count: (list === null || list === void 0 ? void 0 : list.length) || 0
},
message: '',
status: true
});
case 4:
case "end":
return _context6.stop();
}
}, _callee6);
}));
return function (_x6) {
return _ref17.apply(this, arguments);
};
}());
/**
* 取消预约列表查询订阅(HTTP 路由入口)
*/
_defineProperty(this, "handleUnsubscribeBookingQuery", /*#__PURE__*/function () {
var _ref19 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref18) {
var data, _ref20, subscriberId;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
data = _ref18.data;
_ref20 = data || {}, subscriberId = _ref20.subscriberId;
if (subscriberId) {
_this.bookingQuerySubscribers.delete(subscriberId);
_this.logInfo('handleUnsubscribeBookingQuery: 已移除订阅者', {
subscriberId: subscriberId,
remaining: _this.bookingQuerySubscribers.size
});
}
return _context7.abrupt("return", {
code: 200,
message: 'ok',
status: true
});
case 4:
case "end":
return _context7.stop();
}
}, _callee7);
}));
return function (_x7) {
return _ref19.apply(this, arguments);
};
}());
/**
* 处理获取日程时间段点的请求
* 通过餐牌ID列表获取所有相关日程的时间段点
*/
_defineProperty(this, "handleGetScheduleTimePoints", /*#__PURE__*/function () {
var _ref22 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref21) {
var _menu_list_ids$length;
var url, method, data, config, menu_list_ids, _menu_list_ids$length2, menuList, scheduleIds, scheduleList, timePoints, errorMessage;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
url = _ref21.url, method = _ref21.method, data = _ref21.data, config = _ref21.config;
console.log('[Server] handleGetScheduleTimePoints:', url, method, data, config);
menu_list_ids = data.menu_list_ids;
_this.logInfo('handleGetScheduleTimePoints 开始处理', {
menuListIdsCount: (_menu_list_ids$length = menu_list_ids === null || menu_list_ids === void 0 ? void 0 : menu_list_ids.length) !== null && _menu_list_ids$length !== void 0 ? _menu_list_ids$length : 0,
menu_list_ids: menu_list_ids
});
// 检查必要的模块是否已注册
if (_this.menu) {
_context8.next = 8;
break;
}
console.error('[Server] Menu 模块未注册');
_this.logError('handleGetScheduleTimePoints: Menu 模块未注册');
return _context8.abrupt("return", {
code: 500,
message: 'Menu 模块未注册',
data: [],
status: false
});
case 8:
if (_this.schedule) {
_context8.next = 12;
break;
}
console.error('[Server] Schedule 模块未注册');
_this.logError('handleGetScheduleTimePoints: Schedule 模块未注册');
return _context8.abrupt("return", {
code: 500,
message: 'Schedule 模块未注册',
data: [],
status: false
});
case 12:
if (!(!menu_list_ids || !Array.isArray(menu_list_ids) || menu_list_ids.length === 0)) {
_context8.next = 16;
break;
}
console.error('[Server] menu_list_ids 参数无效');
_this.logWarning('handleGetScheduleTimePoints: menu_list_ids 参数无效', {
menuListIdsCount: (_menu_list_ids$length2 = menu_list_ids === null || menu_list_ids === void 0 ? void 0 : menu_list_ids.length) !== null && _menu_list_ids$length2 !== void 0 ? _menu_list_ids$length2 : 0,
menu_list_ids: menu_list_ids
});
return _context8.abrupt("return", {
code: 400,
message: 'menu_list_ids 参数无效',
data: [],
status: false
});
case 16:
_context8.prev = 16;
// 1. 获取餐牌列表
menuList = _this.menu.getMenuByIds(menu_list_ids);
console.log("[Server] \u627E\u5230 ".concat(menuList.length, " \u4E2A\u9910\u724C"));
_this.logInfo('handleGetScheduleTimePoints: 获取到餐牌列表', {
requestedCount: menu_list_ids.length,
foundCount: menuList.length,
menu_list_ids: menu_list_ids,
menuList: menuList
});
// 2. 提取所有的 schedule IDs
scheduleIds = extractScheduleIdsFromMenus(menuList);
console.log("[Server] \u63D0\u53D6\u5230 ".concat(scheduleIds.length, " \u4E2A\u65E5\u7A0BID:"), scheduleIds);
_this.logInfo('handleGetScheduleTimePoints: 提取到日程 IDs', {
scheduleCount: scheduleIds.length
});
if (!(scheduleIds.length === 0)) {
_context8.next = 26;
break;
}
_this.logInfo('handleGetScheduleTimePoints: 没有找到相关日程', {
menuListIdsCount: menu_list_ids.length
});
return _context8.abrupt("return", {
code: 200,
message: '没有找到相关日程',
data: [],
status: true
});
case 26:
// 3. 获取日程详情
scheduleList = _this.schedule.getScheduleByIds(scheduleIds);
console.log("[Server] \u627E\u5230 ".concat(scheduleList.length, " \u4E2A\u65E5\u7A0B"));
_this.logInfo('handleGetScheduleTimePoints: 获取到日程详情', {
requestedCount: scheduleIds.length,
foundCount: scheduleList.length
});
// 4. 提取时间点
timePoints = extractTimePointsFromSchedules(scheduleList);
console.log("[Server] \u63D0\u53D6\u5230 ".concat(timePoints.length, " \u4E2A\u65F6\u95F4\u70B9:"), timePoints);
_this.logInfo('handleGetScheduleTimePoints 处理完成', {
menuListIdsCount: menu_list_ids.length,
menuCount: menuList.length,
scheduleCount: scheduleList.length,
timePointCount: timePoints.length
});
return _context8.abrupt("return", {
code: 200,
message: '获取成功',
data: timePoints,
status: true
});
case 35:
_context8.prev = 35;
_context8.t0 = _context8["catch"](16);
errorMessage = _context8.t0 instanceof Error ? _context8.t0.message : '未知错误';
console.error('[Server] 获取日程时间点失败:', _context8.t0);
_this.logError('handleGetScheduleTimePoints: 获取日程时间点失败', {
menuListIdsCount: menu_list_ids.length,
error: errorMessage
});
return _context8.abrupt("return", {
code: 500,
message: "\u83B7\u53D6\u5931\u8D25: ".concat(errorMessage),
data: [],
status: false
});
case 41:
case "end":
return _context8.stop();
}
}, _callee8, null, [[16, 35]]);
}));
return function (_x8) {
return _ref22.apply(this, arguments);
};
}());
this.core = core;
var appPlugin = core.getPlugin('app');
this.app = (appPlugin === null || appPlugin === void 0 ? void 0 : appPlugin.getApp()) || null;
this.logger = ((_this$app = this.app) === null || _this$app === void 0 ? void 0 : _this$app.logger) || null;
console.log('[Server] Server 初始化', this.core);
this.logInfo('Server 初始化', {
hasApp: !!this.app,
hasLogger: !!this.logger
});
}
/**
* 注册路由
* @param routes 路由定义数组
*/
_createClass(Server, [{
key: "registerRoutes",
value: function registerRoutes(routes) {
var _this2 = this;
routes.forEach(function (route) {
var method = route.method,
path = route.path,
handler = route.handler;
if (!_this2.router[method]) {
console.warn("[Server] \u4E0D\u652F\u6301\u7684 HTTP \u65B9\u6CD5: ".concat(method));
_this2.logWarning("\u4E0D\u652F\u6301\u7684 HTTP \u65B9\u6CD5", {
method: method,
path: path
});
return;
}
// 检查路由是否已存在
if (_this2.router[method][path]) {
console.warn("[Server] \u8DEF\u7531\u5DF2\u5B58\u5728\uFF0C\u5C06\u88AB\u8986\u76D6: ".concat(method.toUpperCase(), " ").concat(path));
_this2.logWarning("\u8DEF\u7531\u5DF2\u5B58\u5728\uFF0C\u5C06\u88AB\u8986\u76D6", {
method: method,
path: path
});
}
_this2.router[method][path] = handler;
console.log("[Server] \uD83D\uDCDD \u6CE8\u518C\u8DEF\u7531: ".concat(method.toUpperCase(), " ").concat(path));
_this2.logInfo("\u6CE8\u518C\u8DEF\u7531", {
method: method.toUpperCase(),
path: path
});
});
}
/**
* 注册单个模块并自动注册其路由
* @param module 模块实例
* @param options 模块配置
* @param moduleName 模块名称(用于日志)
*/
}, {
key: "registerModuleWithRoutes",
value: (function () {
var _registerModuleWithRoutes = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(module, options, moduleName) {
var routes;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
this.logInfo("\u5F00\u59CB\u6CE8\u518C\u6A21\u5757: ".concat(moduleName), {
moduleName: moduleName,
options: options
});
// 注册模块到 Core
_context9.next = 3;
return this.core.registerModule(module, options);
case 3:
console.log("[Server] \u2705 ".concat(moduleName, " \u6A21\u5757\u5DF2\u6CE8\u518C"));
this.logInfo("\u6A21\u5757\u6CE8\u518C\u6210\u529F: ".concat(moduleName), {
moduleName: moduleName
});
// 自动注册模块的路由
if (typeof module.getRoutes === 'function') {
routes = module.getRoutes();
if (routes && routes.length > 0) {
this.registerRoutes(routes);
this.logInfo("\u6A21\u5757\u8DEF\u7531\u5DF2\u6CE8\u518C: ".concat(moduleName), {
moduleName: moduleName,
routesCount: routes.length
});
}
}
case 6:
case "end":
return _context9.stop();
}
}, _callee9, this);
}));
function registerModuleWithRoutes(_x9, _x10, _x11) {
return _registerModuleWithRoutes.apply(this, arguments);
}
return registerModuleWithRoutes;
}()
/**
* 根据模块名称注册单个模块
* @param moduleConfig 模块配置(可以是字符串或配置对象)
*/
)
}, {
key: "registerModuleByName",
value: (function () {
var _registerModuleByName = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(moduleConfig) {
var moduleName, shouldPreload, customConfig, registryConfig, ModuleClass, moduleInstance, moduleOptions;
return _regeneratorRuntime().wrap(function _callee10$(_context10) {
while (1) switch (_context10.prev = _context10.next) {
case 0:
// 解析配置
moduleName = typeof moduleConfig === 'string' ? moduleConfig : moduleConfig.name;
shouldPreload = _typeof(moduleConfig) === 'object' ? moduleConfig.preload !== false : true;
customConfig = _typeof(moduleConfig) === 'object' ? moduleConfig.config : {};
this.logInfo("\u89E3\u6790\u6A21\u5757\u914D\u7F6E: ".concat(moduleName), {
moduleName: moduleName,
shouldPreload: shouldPreload,
customConfig: customConfig
});
// 查找模块配置
registryConfig = this.moduleRegistry[moduleName];
if (registryConfig) {
_context10.next = 8;
break;
}
this.logError("\u672A\u627E\u5230\u6A21\u5757\u914D\u7F6E: ".concat(moduleName), {
moduleName: moduleName
});
throw new Error("[Server] \u672A\u627E\u5230\u6A21\u5757\u914D\u7F6E: ".concat(moduleName));
case 8:
// 创建模块实例
ModuleClass = registryConfig.moduleClass;
moduleInstance = new ModuleClass(registryConfig.moduleName, registryConfig.version); // 合并配置
moduleOptions = _objectSpread({
store: _objectSpread({}, registryConfig.defaultStore)
}, customConfig); // 注册模块和路由
_context10.next = 13;
return this.registerModuleWithRoutes(moduleInstance, moduleOptions, moduleName.charAt(0).toUpperCase() + moduleName.slice(1));
case 13:
// 保存模块实例
this[moduleName] = moduleInstance;
this.logInfo("\u6A21\u5757\u6CE8\u518C\u5B8C\u6210: ".concat(moduleName), {
moduleName: moduleName,
shouldPreload: shouldPreload,
version: registryConfig.version
});
return _context10.abrupt("return", {
module: moduleInstance,
config: registryConfig,
shouldPreload: shouldPreload
});
case 16:
case "end":
return _context10.stop();
}
}, _callee10, this);
}));
function registerModuleByName(_x12) {
return _registerModuleByName.apply(this, arguments);
}
return registerModuleByName;
}()
/**
* 注册指定的服务端模块
* @param moduleConfigs 要注册的模块配置数组(模块名称或配置对象)
*/
)
}, {
key: "registerModules",
value: (function () {
var _registerModules = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(moduleConfigs) {
var configs, registeredModules, _iterator, _step, config, configName, result, errorMessage;
return _regeneratorRuntime().wrap(function _callee11$(_context11) {
while (1) switch (_context11.prev = _context11.next) {
case 0:
console.log('[Server] 开始注册模块...');
// 如果没有指定模块,则注册所有模块
configs = moduleConfigs || Object.keys(this.moduleRegistry);
this.logInfo('开始批量注册模块', {
moduleConfigs: configs,
totalCount: configs.length
});
registeredModules = [];
_iterator = _createForOfIteratorHelper(configs);
_context11.prev = 5;
_iterator.s();
case 7:
if ((_step = _iterator.n()).done) {
_context11.next = 25;
break;
}
config = _step.value;
configName = typeof config === 'string' ? config : config.name;
_context11.prev = 10;
_context11.next = 13;
return this.registerModuleByName(config);
case 13:
result = _context11.sent;
registeredModules.push(result);
_context11.next = 23;
break;
case 17:
_context11.prev = 17;
_context11.t0 = _context11["catch"](10);
errorMessage = _context11.t0 instanceof Error ? _context11.t0.message : String(_context11.t0);
this.logError("\u6A21\u5757\u6CE8\u518C\u5931\u8D25: ".concat(configName), {
moduleName: configName,
error: errorMessage
});
console.error("[Server] \u6A21\u5757\u6CE8\u518C\u5931\u8D25:", _context11.t0);
throw _context11.t0;
case 23:
_context11.next = 7;
break;
case 25:
_context11.next = 30;
break;
case 27:
_context11.prev = 27;
_context11.t1 = _context11["catch"](5);
_iterator.e(_context11.t1);
case 30:
_context11.prev = 30;
_iterator.f();
return _context11.finish(30);
case 33:
console.log('[Server] ✅ 所有模块注册完成');
this.logInfo('所有模块注册完成', {
registeredCount: registeredModules.length,
moduleNames: registeredModules.map(function (m) {
var _m$config;
return m === null || m === void 0 || (_m$config = m.config) === null || _m$config === void 0 ? void 0 : _m$config.name;
})
});
return _context11.abrupt("return", registeredModules);
case 36:
case "end":
return _context11.stop();
}
}, _callee11, this, [[5, 27, 30, 33], [10, 17]]);
}));
function registerModules(_x13) {
return _registerModules.apply(this, arguments);
}
return registerModules;
}()
/**
* 预加载指定模块的数据
* @param registeredModules 已注册的模块信息
*/
)
}, {
key: "preloadModulesData",
value: (function () {
var _preloadModulesData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(registeredModules, options) {
var modulesToPreload, preloadResults, _iterator2, _step2, _step2$value, module, config, shouldPreload, startTime, _options$onModuleLoad, _options$onModuleLoad2, duration, _duration, errorMessage, successCount, failCount;
return _regeneratorRuntime().wrap(function _callee12$(_context12) {
while (1) switch (_context12.prev = _context12.next) {
case 0:
console.log('[Server] 开始预加载模块数据...');
modulesToPreload = registeredModules.filter(function (m) {
return m.shouldPreload;
});
this.logInfo('开始预加载模块数据', {
totalModules: registeredModules.length,
preloadCount: modulesToPreload.length,
modulesToPreload: modulesToPreload
});
preloadResults = [];
_iterator2 = _createForOfIteratorHelper(registeredModules);
_context12.prev = 5;
_iterator2.s();
case 7:
if ((_step2 = _iterator2.n()).done) {
_context12.next = 40;
break;
}
_step2$value = _step2.value, module = _step2$value.module, config = _step2$value.config, shouldPreload = _step2$value.shouldPreload;
if (shouldPreload) {
_context12.next = 13;
break;
}
console.log("[Server] \u23ED\uFE0F \u8DF3\u8FC7 ".concat(config.name, " \u6A21\u5757\u9884\u52A0\u8F7D"));
this.logInfo("\u8DF3\u8FC7\u6A21\u5757\u9884\u52A0\u8F7D: ".concat(config.name), {
moduleName: config.name,
reason: 'shouldPreload=false'
});
return _context12.abrupt("continue", 38);
case 13:
if (!(typeof module.preload === 'function')) {
_context12.next = 36;
break;
}
startTime = Date.now();
_context12.prev = 15;
this.logInfo("\u5F00\u59CB\u9884\u52A0\u8F7D\u6A21\u5757: ".concat(config.name), {
moduleName: config.name
});
options === null || options === void 0 || (_options$onModuleLoad = options.onModuleLoad) === null || _options$onModuleLoad === void 0 || _options$onModuleLoad.call(options, config.name);
_context12.next = 20;
return module.preload();
case 20:
options === null || options === void 0 || (_options$onModuleLoad2 = options.onModuleLoadComplete) === null || _options$onModuleLoad2 === void 0 || _options$onModuleLoad2.call(options, config.name);
duration = Date.now() - startTime;
console.log("[Server] \u2705 ".concat(config.name, " \u6A21\u5757\u6570\u636E\u5DF2\u9884\u52A0\u8F7D"));
this.logInfo("\u6A21\u5757\u9884\u52A0\u8F7D\u6210\u529F: ".concat(config.name), {
moduleName: config.name,
duration: "".concat(duration, "ms")
});
preloadResults.push({
name: config.name,
success: true
});
_context12.next = 34;
break;
case 27:
_context12.prev = 27;
_context12.t0 = _context12["catch"](15);
_duration = Date.now() - startTime;
errorMessage = _context12.t0 instanceof Error ? _context12.t0.message : String(_context12.t0);
console.error("[Server] \u274C ".concat(config.name, " \u6A21\u5757\u9884\u52A0\u8F7D\u5931\u8D25:"), _context12.t0);
this.logError("\u6A21\u5757\u9884\u52A0\u8F7D\u5931\u8D25: ".concat(config.name), {
moduleName: config.name,
duration: "".concat(_duration, "ms"),
error: errorMessage
});
preloadResults.push({
name: config.name,
success: false,
error: errorMessage
});
case 34:
_context12.next = 38;
break;
case 36: