UNPKG

@pisell/pisellos

Version:

一个可扩展的前端模块化SDK框架,支持插件系统

900 lines (879 loc) 116 kB
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 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 _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 _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 _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 { BaseModule } from "../BaseModule"; import { PaymentStatus, PaymentMethodType, RoundingRule } from "./types"; import { getUniqueId } from "../Cart/utils"; import { CashPaymentImpl } from "./cash"; import { EftposPaymentImpl } from "./eftpos"; import { WalletPassPaymentImpl } from "./walletpass"; import { Decimal } from 'decimal.js'; export * from "./types"; export { generateRequestUniqueId }; /** * 格式化金额为保留两位小数的字符串 */ function formatAmount(amount) { try { var decimal = new Decimal(amount); return decimal.toFixed(2); } catch (error) { console.warn("[PaymentModule] \u91D1\u989D\u683C\u5F0F\u5316\u5931\u8D25: ".concat(amount, "\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u503C 0.00")); return '0.00'; } } /** * 格式化日期时间为字符串 * 格式: YYYY-MM-DD HH:mm:ss * 示例: 2025-12-10 16:14:50 */ function formatDateTime(date) { var year = date.getFullYear(); var month = String(date.getMonth() + 1).padStart(2, '0'); var day = String(date.getDate()).padStart(2, '0'); var hours = String(date.getHours()).padStart(2, '0'); var minutes = String(date.getMinutes()).padStart(2, '0'); var seconds = String(date.getSeconds()).padStart(2, '0'); return "".concat(year, "-").concat(month, "-").concat(day, " ").concat(hours, ":").concat(minutes, ":").concat(seconds); } /** * 生成请求唯一ID * 格式: 年月日时分秒毫秒+4位随机数 * 示例: 20241201143025123456 */ function generateRequestUniqueId() { var now = new Date(); var year = now.getFullYear(); var month = String(now.getMonth() + 1).padStart(2, '0'); var day = String(now.getDate()).padStart(2, '0'); var hour = String(now.getHours()).padStart(2, '0'); var minute = String(now.getMinutes()).padStart(2, '0'); var second = String(now.getSeconds()).padStart(2, '0'); var millisecond = String(now.getMilliseconds()).padStart(3, '0'); var randomDigits = Math.floor(Math.random() * 9000) + 1000; // 1000-9999的4位随机数 return "".concat(year).concat(month).concat(day).concat(hour).concat(minute).concat(second).concat(millisecond).concat(randomDigits); } /** * 支付模块实现 * * 负责处理支付相关的数据管理和本地存储 */ export var PaymentModule = /*#__PURE__*/function (_BaseModule) { _inherits(PaymentModule, _BaseModule); var _super = _createSuper(PaymentModule); function PaymentModule(name, version) { var _this; _classCallCheck(this, PaymentModule); _this = _super.call(this, name || "payment", version); // 初始化支付方式实例 _defineProperty(_assertThisInitialized(_this), "defaultName", 'pay'); _defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0'); _defineProperty(_assertThisInitialized(_this), "request", void 0); _defineProperty(_assertThisInitialized(_this), "app", void 0); // App instance _defineProperty(_assertThisInitialized(_this), "store", void 0); _defineProperty(_assertThisInitialized(_this), "window", void 0); // WindowPlugin 实例 _defineProperty(_assertThisInitialized(_this), "dbManager", void 0); // IndexDBManager 实例 _defineProperty(_assertThisInitialized(_this), "logger", void 0); // LoggerManager 实例 _defineProperty(_assertThisInitialized(_this), "voucherUpdateLockByOrderUuid", new Map()); _defineProperty(_assertThisInitialized(_this), "otherParams", {}); // 支付方式实例 _defineProperty(_assertThisInitialized(_this), "cash", void 0); _defineProperty(_assertThisInitialized(_this), "eftpos", void 0); _defineProperty(_assertThisInitialized(_this), "wallet", void 0); _this.cash = new CashPaymentImpl(_assertThisInitialized(_this)); _this.eftpos = new EftposPaymentImpl(_assertThisInitialized(_this)); _this.wallet = new WalletPassPaymentImpl(_assertThisInitialized(_this)); return _this; } _createClass(PaymentModule, [{ key: "runVoucherUpdateLocked", value: function runVoucherUpdateLocked(orderUuid, task) { var _this2 = this; var previous = this.voucherUpdateLockByOrderUuid.get(orderUuid) || Promise.resolve(); var next = previous.catch(function () { return undefined; }).then(task).finally(function () { if (_this2.voucherUpdateLockByOrderUuid.get(orderUuid) === next) { _this2.voucherUpdateLockByOrderUuid.delete(orderUuid); } }); this.voucherUpdateLockByOrderUuid.set(orderUuid, next); return next; } }, { key: "normalizeVoucherPaymentItems", value: function normalizeVoucherPaymentItems(voucherPaymentItems) { var normalized = new Map(); var _iterator = _createForOfIteratorHelper(voucherPaymentItems || []), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var item = _step.value; if (!(item !== null && item !== void 0 && item.voucher_id)) { throw new Error("\u4EE3\u91D1\u5238\u652F\u4ED8\u9879\u7F3A\u5C11 voucher_id: ".concat(JSON.stringify(item))); } var orderPaymentType = item.order_payment_type || 'normal'; var key = "".concat(item.voucher_id, "|").concat(orderPaymentType); normalized.set(key, _objectSpread(_objectSpread({}, item), {}, { order_payment_type: orderPaymentType })); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return { items: Array.from(normalized.values()), originalCount: (voucherPaymentItems === null || voucherPaymentItems === void 0 ? void 0 : voucherPaymentItems.length) || 0, normalizedCount: normalized.size }; } }, { key: "initialize", value: function () { var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) { var appPlugin; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: this.core = core; this.store = options.store; this.otherParams = options.otherParams || {}; // 获取依赖的插件 this.request = core.getPlugin('request'); appPlugin = core.getPlugin('app'); this.window = core.getPlugin('window'); if (this.request) { _context.next = 8; break; } throw new Error('支付模块需要 request 插件支持'); case 8: if (appPlugin) { _context.next = 10; break; } throw new Error('支付模块需要 app 插件支持'); case 10: this.app = appPlugin.getApp(); this.dbManager = this.app.dbManager; this.logger = this.app.logger; // 确保支付模块所需的对象存储已创建 _context.next = 15; return this.ensurePaymentTables(); case 15: this.registerNetworkHandlers(); // // 预连接数据库 // this.dbManager.connect() console.log('[PaymentModule] 初始化完成'); this.logInfo('PaymentModule initialized successfully'); case 18: case "end": return _context.stop(); } }, _callee, this); })); function initialize(_x, _x2) { return _initialize.apply(this, arguments); } return initialize; }() /** * 记录信息日志 */ }, { key: "logInfo", value: function logInfo(title, metadata) { var _this$otherParams; if ((_this$otherParams = this.otherParams) !== null && _this$otherParams !== void 0 && _this$otherParams.fatherModule) { var _this$otherParams2; var fatherModule = this.core.getModule((_this$otherParams2 = this.otherParams) === null || _this$otherParams2 === void 0 ? void 0 : _this$otherParams2.fatherModule); if (fatherModule) { fatherModule.logInfo("".concat(title), metadata); return; } } if (this.logger) { this.logger.addLog({ type: 'info', title: "[PaymentModule] ".concat(title), metadata: metadata || {} }); } } /** * 记录警告日志 */ }, { key: "logWarning", value: function logWarning(title, metadata) { if (this.logger) { this.logger.addLog({ type: 'warning', title: "[PaymentModule] ".concat(title), metadata: metadata || {} }); } } /** * 记录错误日志 */ }, { key: "logError", value: function logError(title, error, metadata) { if (this.logger) { this.logger.addLog({ type: 'error', title: "[PaymentModule] ".concat(title), metadata: _objectSpread({ error: error ? _objectSpread({ message: error.message, stack: error.stack, code: error.code }, error) : undefined }, metadata || {}) }); } } /** * 记录调试日志 */ }, { key: "logDebug", value: function logDebug(title, metadata) { if (this.logger) { this.logger.addLog({ type: 'debug', title: "[PaymentModule] ".concat(title), metadata: metadata || {} }); } } /** * 网络恢复以后,尝试执行队列 * */ }, { key: "registerNetworkHandlers", value: function registerNetworkHandlers() { var _this3 = this; var network = this.app.plugins.get('network'); this.logInfo('Registering network status listener'); network === null || network === void 0 || network.addListener('networkStatusChange', /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(status) { return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: console.log('网络状态:', status.connected); _this3.logInfo('Network status changed', { connected: status.connected, previousStatus: status.previousStatus }); if (status.connected) { _this3.logInfo('Network reconnected'); // 网络恢复时的处理逻辑可以在这里添加 } case 3: case "end": return _context2.stop(); } }, _callee2); })); return function (_x3) { return _ref.apply(this, arguments); }; }()); } }, { key: "filterPayMethods", value: function () { var _filterPayMethods = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(payMethods) { var walletPassMethod; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: // 1. 筛选 status === 1 && disable === 0的数据 // 2. 检查列表里是否有 code=WALLET_PASS的数据,如果没有,则列表里如果有 PRODUCTVOUCHER 、 GIFTCARD 、 POINTCARD 则删除他们 // 如果有 code = WALLET_PASS的数据,则列表里PRODUCTVOUCHER 、 GIFTCARD 、 POINTCARD 的channel_application 指向 WALLET_PASS 的 channel_application payMethods = payMethods.filter(function (method) { return method.status === 1 && method.disable === 0; }); walletPassMethod = payMethods.find(function (method) { return method.code === 'WALLET_PASS'; }); if (walletPassMethod) { payMethods.forEach(function (method) { if (method.code === 'PRODUCTVOUCHER' || method.code === 'GIFTCARD' || method.code === 'POINTCARD') { method.channel_application = walletPassMethod.channel_application; } }); } else { payMethods = payMethods.filter(function (method) { return method.code !== 'PRODUCTVOUCHER' && method.code !== 'GIFTCARD' && method.code !== 'POINTCARD'; }); } return _context3.abrupt("return", payMethods); case 4: case "end": return _context3.stop(); } }, _callee3); })); function filterPayMethods(_x4) { return _filterPayMethods.apply(this, arguments); } return filterPayMethods; }() /** * 获取支付方式列表 */ }, { key: "getPayMethodListAsync", value: (function () { var _getPayMethodListAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { var cachedMethods, hasCache, response, payMethods, _iterator2, _step2, method; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: this.logInfo('Starting getPayMethodListAsync'); _context4.prev = 1; // 先尝试从 IndexDB 获取缓存 cachedMethods = []; _context4.prev = 3; _context4.next = 6; return this.dbManager.getAll('pay_method'); case 6: cachedMethods = _context4.sent; _context4.next = 12; break; case 9: _context4.prev = 9; _context4.t0 = _context4["catch"](3); console.warn('[PaymentModule] pay_method 表不存在,将从服务器获取数据'); case 12: // 如果有缓存,先返回缓存数据 hasCache = cachedMethods.length > 0; if (!hasCache) { _context4.next = 16; break; } // 后台异步获取最新数据 this.refreshPaymentMethodsInBackground(cachedMethods); return _context4.abrupt("return", cachedMethods); case 16: _context4.next = 18; return this.request.get('/pay/custom-payment/all'); case 18: response = _context4.sent; response.data = this.filterPayMethods(response.data); payMethods = response.data || []; // 尝试缓存到 IndexDB _context4.prev = 21; _iterator2 = _createForOfIteratorHelper(payMethods); _context4.prev = 23; _iterator2.s(); case 25: if ((_step2 = _iterator2.n()).done) { _context4.next = 31; break; } method = _step2.value; _context4.next = 29; return this.dbManager.update('pay_method', method); case 29: _context4.next = 25; break; case 31: _context4.next = 36; break; case 33: _context4.prev = 33; _context4.t1 = _context4["catch"](23); _iterator2.e(_context4.t1); case 36: _context4.prev = 36; _iterator2.f(); return _context4.finish(36); case 39: _context4.next = 44; break; case 41: _context4.prev = 41; _context4.t2 = _context4["catch"](21); console.warn('[PaymentModule] 无法缓存支付方式,pay_method 表不存在'); case 44: _context4.next = 46; return this.core.effects.emit("".concat(this.name, ":onPaymentMethodsLoaded"), payMethods); case 46: this.logInfo('getPayMethodListAsync completed successfully', { payMethods: payMethods }); return _context4.abrupt("return", payMethods); case 50: _context4.prev = 50; _context4.t3 = _context4["catch"](1); console.error('[PaymentModule] 获取支付方式列表失败', _context4.t3); this.logError('getPayMethodListAsync failed', _context4.t3); // 如果所有操作都失败,返回空数组 return _context4.abrupt("return", []); case 55: case "end": return _context4.stop(); } }, _callee4, this, [[1, 50], [3, 9], [21, 41], [23, 33, 36, 39]]); })); function getPayMethodListAsync() { return _getPayMethodListAsync.apply(this, arguments); } return getPayMethodListAsync; }() /** * 后台刷新支付方式列表 */ ) }, { key: "refreshPaymentMethodsInBackground", value: (function () { var _refreshPaymentMethodsInBackground = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(cachedMethods) { var response, newPayMethods, hasChanges, _iterator3, _step3, method, _iterator4, _step4, _method, eventData; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: this.logInfo('Starting refreshPaymentMethodsInBackground', { cachedMethodsCount: cachedMethods.length }); _context5.prev = 1; console.log('[PaymentModule] 后台刷新支付方式列表...'); // 从服务器获取最新数据 _context5.next = 5; return this.request.get('/pay/custom-payment/all'); case 5: response = _context5.sent; response.data = this.filterPayMethods(response.data); newPayMethods = response.data || []; // 检查是否有变化 hasChanges = this.hasPaymentMethodsChanged(cachedMethods, newPayMethods); if (!hasChanges) { _context5.next = 57; break; } console.log('[PaymentModule] 支付方式列表已更新'); this.logInfo('Payment methods updated in background', { oldCount: cachedMethods.length, newCount: newPayMethods.length }); // 更新缓存 _context5.prev = 12; // 先清除旧数据 _iterator3 = _createForOfIteratorHelper(cachedMethods); _context5.prev = 14; _iterator3.s(); case 16: if ((_step3 = _iterator3.n()).done) { _context5.next = 22; break; } method = _step3.value; _context5.next = 20; return this.dbManager.delete('pay_method', method.id); case 20: _context5.next = 16; break; case 22: _context5.next = 27; break; case 24: _context5.prev = 24; _context5.t0 = _context5["catch"](14); _iterator3.e(_context5.t0); case 27: _context5.prev = 27; _iterator3.f(); return _context5.finish(27); case 30: // 添加新数据 _iterator4 = _createForOfIteratorHelper(newPayMethods); _context5.prev = 31; _iterator4.s(); case 33: if ((_step4 = _iterator4.n()).done) { _context5.next = 39; break; } _method = _step4.value; _context5.next = 37; return this.dbManager.update('pay_method', _method); case 37: _context5.next = 33; break; case 39: _context5.next = 44; break; case 41: _context5.prev = 41; _context5.t1 = _context5["catch"](31); _iterator4.e(_context5.t1); case 44: _context5.prev = 44; _iterator4.f(); return _context5.finish(44); case 47: _context5.next = 52; break; case 49: _context5.prev = 49; _context5.t2 = _context5["catch"](12); console.warn('[PaymentModule] 无法更新支付方式缓存', _context5.t2); case 52: // 通知外部支付方式已变化 eventData = { oldMethods: cachedMethods, newMethods: newPayMethods }; _context5.next = 55; return this.core.effects.emit("".concat(this.name, ":onPaymentMethodsChanged"), eventData); case 55: _context5.next = 58; break; case 57: console.log('[PaymentModule] 支付方式列表无变化'); case 58: _context5.next = 63; break; case 60: _context5.prev = 60; _context5.t3 = _context5["catch"](1); console.error('[PaymentModule] 后台刷新支付方式失败', _context5.t3); case 63: case "end": return _context5.stop(); } }, _callee5, this, [[1, 60], [12, 49], [14, 24, 27, 30], [31, 41, 44, 47]]); })); function refreshPaymentMethodsInBackground(_x5) { return _refreshPaymentMethodsInBackground.apply(this, arguments); } return refreshPaymentMethodsInBackground; }() /** * 检查支付方式列表是否有变化 */ ) }, { key: "hasPaymentMethodsChanged", value: function hasPaymentMethodsChanged(oldMethods, newMethods) { if (oldMethods.length !== newMethods.length) { return true; } // 创建旧数据的 Map 便于查找 var oldMethodsMap = new Map(oldMethods.map(function (method) { return [method.id, method]; })); // 检查每个新方法是否与旧方法相同 var _iterator5 = _createForOfIteratorHelper(newMethods), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var newMethod = _step5.value; var oldMethod = oldMethodsMap.get(newMethod.id); if (!oldMethod) { return true; // 新增方法 } // 检查关键字段是否有变化 if (oldMethod.code !== newMethod.code || oldMethod.name !== newMethod.name || oldMethod.type !== newMethod.type || oldMethod.description !== newMethod.description || oldMethod.status !== newMethod.status || oldMethod.disable !== newMethod.disable || oldMethod.is_surcharge !== newMethod.is_surcharge || oldMethod.fixed !== newMethod.fixed || oldMethod.percentage !== newMethod.percentage || oldMethod.enabled !== newMethod.enabled || JSON.stringify(oldMethod.channel_application || []) !== JSON.stringify(newMethod.channel_application || []) || JSON.stringify(oldMethod.companies || []) !== JSON.stringify(newMethod.companies || []) || JSON.stringify(oldMethod.metadata || {}) !== JSON.stringify(newMethod.metadata || {})) { console.log("[PaymentModule] \u652F\u4ED8\u65B9\u5F0F ".concat(newMethod.id, " (").concat(newMethod.code, ") \u53D1\u751F\u53D8\u5316:"), { id: newMethod.id, changes: { code: oldMethod.code !== newMethod.code ? { old: oldMethod.code, new: newMethod.code } : undefined, name: oldMethod.name !== newMethod.name ? { old: oldMethod.name, new: newMethod.name } : undefined, type: oldMethod.type !== newMethod.type ? { old: oldMethod.type, new: newMethod.type } : undefined, description: oldMethod.description !== newMethod.description ? { old: oldMethod.description, new: newMethod.description } : undefined, status: oldMethod.status !== newMethod.status ? { old: oldMethod.status, new: newMethod.status } : undefined, disable: oldMethod.disable !== newMethod.disable ? { old: oldMethod.disable, new: newMethod.disable } : undefined, is_surcharge: oldMethod.is_surcharge !== newMethod.is_surcharge ? { old: oldMethod.is_surcharge, new: newMethod.is_surcharge } : undefined, fixed: oldMethod.fixed !== newMethod.fixed ? { old: oldMethod.fixed, new: newMethod.fixed } : undefined, percentage: oldMethod.percentage !== newMethod.percentage ? { old: oldMethod.percentage, new: newMethod.percentage } : undefined, enabled: oldMethod.enabled !== newMethod.enabled ? { old: oldMethod.enabled, new: newMethod.enabled } : undefined, channel_application: JSON.stringify(oldMethod.channel_application || []) !== JSON.stringify(newMethod.channel_application || []) ? { old: oldMethod.channel_application, new: newMethod.channel_application } : undefined, companies: JSON.stringify(oldMethod.companies || []) !== JSON.stringify(newMethod.companies || []) ? { old: oldMethod.companies, new: newMethod.companies } : undefined, metadata: JSON.stringify(oldMethod.metadata || {}) !== JSON.stringify(newMethod.metadata || {}) ? { old: oldMethod.metadata, new: newMethod.metadata } : undefined } }); return true; // 方法属性有变化 } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return false; } /** * 获取订单列表 */ }, { key: "getOrderListAsync", value: (function () { var _getOrderListAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() { return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: _context6.prev = 0; _context6.next = 3; return this.dbManager.getAll('order'); case 3: return _context6.abrupt("return", _context6.sent); case 6: _context6.prev = 6; _context6.t0 = _context6["catch"](0); console.error('[PaymentModule] 获取订单列表失败', _context6.t0); return _context6.abrupt("return", []); case 10: case "end": return _context6.stop(); } }, _callee6, this, [[0, 6]]); })); function getOrderListAsync() { return _getOrderListAsync.apply(this, arguments); } return getOrderListAsync; }() /** * 根据订单UUID获取支付订单(新方法) */ ) }, { key: "getPaymentOrderByUuidAsync", value: (function () { var _getPaymentOrderByUuidAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(orderUuid) { return _regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: _context7.prev = 0; _context7.next = 3; return this.dbManager.get('order', orderUuid, true); case 3: return _context7.abrupt("return", _context7.sent); case 6: _context7.prev = 6; _context7.t0 = _context7["catch"](0); console.error('[PaymentModule] 获取支付订单失败', _context7.t0); return _context7.abrupt("return", null); case 10: case "end": return _context7.stop(); } }, _callee7, this, [[0, 6]]); })); function getPaymentOrderByUuidAsync(_x6) { return _getPaymentOrderByUuidAsync.apply(this, arguments); } return getPaymentOrderByUuidAsync; }() /** * 创建支付订单(新方法,专注支付数据) */ ) }, { key: "createPaymentOrderAsync", value: (function () { var _createPaymentOrderAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(params) { var _this4 = this; var newOrder, currentTime, dbAddStartTime, dbAddDuration; return _regeneratorRuntime().wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { case 0: this.logInfo('Starting createPaymentOrderAsync', { orderId: params.order_id, totalAmount: params.total_amount }); _context8.prev = 1; // 检测是否有重复的 order_id // console.time('createLocalOrderAsync: getExistingOrder') // const existingOrder = await this.dbManager.get('order', params.order_id); // const existingOrders = await this.dbManager.getAll('order'); // const existingOrder = existingOrders.find( // (order: PaymentOrder) => String(order.id) === String(params.order_id), // ); // this.logInfo('createPaymentOrderAsync existingOrder', { // existingOrder // }); // console.timeEnd('createLocalOrderAsync: getExistingOrder') // const existingOrder = existingOrders.find( // (order: PaymentOrder) => String(order.id) === String(params.order_id), // ); // if (existingOrder) { // // 如果存在相同 order_id 的订单,更新该订单信息 // this.logInfo( // `createPaymentOrderAsync found duplicate order ID: ${params.order_id}, updating existing payment order`, // ); // // const originalOrder = { ...existingOrder }; // existingOrder.order_info = params.order_info; // existingOrder.total_amount = params.total_amount; // existingOrder.is_deposit = params.is_deposit || 0; // existingOrder.deposit_amount = params.deposit_amount || '0.00'; // // 重新计算待付金额 // this.recalculateOrderAmount(existingOrder); // // 更新到数据库 // await this.dbManager.update('order', existingOrder); // // 触发更新事件 // this.core.effects.emit( // `${this.name}:onOrderUpdated`, // existingOrder, // ); // return existingOrder; // } else { // 创建新的支付订单 newOrder = { uuid: getUniqueId('pay_order_'), id: params.order_id, order_id: params.order_id, order_info: params.order_info, payment_status: PaymentStatus.Processing, payment: [], adjust_offline_payments: [], total_amount: params.total_amount, expect_amount: params.total_amount, tax_fee: '0.00', is_deposit: params.is_deposit || 0, deposit_amount: params.deposit_amount || '0.00' }; // 🔧 新增: 处理云端已存在的支付项 if (params.existPayment && params.existPayment.length > 0) { currentTime = formatDateTime(new Date()); newOrder.payment = params.existPayment.map(function (payment) { return _objectSpread(_objectSpread({}, payment), {}, { isSynced: true, // 标记为已同步 status: payment.status || 'active', // 如果云端支付项已有时间戳,则保留;否则使用当前时间 created_at: payment.created_at || currentTime, updated_at: payment.updated_at || currentTime }); }); // 重新计算待付金额 this.recalculateOrderAmount(newOrder); this.logInfo('创建订单时包含云端支付项', { orderId: params.order_id, existPaymentCount: params.existPayment.length, totalAmount: newOrder.total_amount, expectAmount: newOrder.expect_amount, paymentDetails: params.existPayment.map(function (p) { return { uuid: p.uuid, code: p.code, amount: p.amount, status: p.status, created_at: p.created_at, updated_at: p.updated_at }; }) }); } // 🚀 性能监控:记录数据库添加操作耗时 dbAddStartTime = Date.now(); _context8.next = 7; return this.dbManager.add('order', newOrder, true); case 7: dbAddDuration = Date.now() - dbAddStartTime; this.logInfo('Database add operation completed', { operation: 'dbManager.add', table: 'order', orderUuid: newOrder.uuid, orderId: newOrder.order_id, duration: "".concat(dbAddDuration, "ms"), performance: dbAddDuration > 100 ? 'slow' : dbAddDuration > 50 ? 'medium' : 'fast' }); setTimeout(function () { _this4.core.effects.emit("".concat(_this4.name, ":onOrderAdded"), newOrder); }, 0); return _context8.abrupt("return", newOrder); case 13: _context8.prev = 13; _context8.t0 = _context8["catch"](1); console.error('[PaymentModule] 创建支付订单失败', _context8.t0); this.logError('createPaymentOrderAsync failed', _context8.t0, { orderId: params.order_id }); throw _context8.t0; case 18: case "end": return _context8.stop(); } }, _callee8, this, [[1, 13]]); })); function createPaymentOrderAsync(_x7) { return _createPaymentOrderAsync.apply(this, arguments); } return createPaymentOrderAsync; }() /** * 删除支付订单(新方法) */ ) }, { key: "deletePaymentOrderAsync", value: (function () { var _del