UNPKG

@pisell/pisellos

Version:

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

745 lines (722 loc) 257 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 _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 _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 _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 _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 _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 _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 _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 "../../modules/BaseModule"; import Decimal from 'decimal.js'; import { OrderModule } from "../../modules/Order"; import { PaymentModule } from "../../modules/Payment"; import { CheckoutErrorType } from "./types"; import { PaymentStatus, PaymentHooks } from "../../modules/Payment/types"; import { validateCheckoutData, createCheckoutError, validateLocalOrderData, generateLocalOrderId, formatDateTime, extractAmountFromCartSummary, isVirtualOrderId, isCashPayment } from "./utils"; import { getProductDeposit } from "../../modules/Cart/utils"; export * from "./types"; /** * 结账解决方案实现 * * 整合订单处理和支付功能,提供完整的结账流程管理。 * 支持多种支付方式,提供实时状态跟踪和错误处理。 */ export var CheckoutImpl = /*#__PURE__*/function (_BaseModule) { _inherits(CheckoutImpl, _BaseModule); var _super = _createSuper(CheckoutImpl); function CheckoutImpl(name, version) { var _this; _classCallCheck(this, CheckoutImpl); _this = _super.call(this, name || 'checkout', version || '1.0.0'); _defineProperty(_assertThisInitialized(_this), "defaultName", 'checkout'); _defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0'); _defineProperty(_assertThisInitialized(_this), "isSolution", true); _defineProperty(_assertThisInitialized(_this), "request", void 0); _defineProperty(_assertThisInitialized(_this), "store", void 0); _defineProperty(_assertThisInitialized(_this), "otherParams", {}); _defineProperty(_assertThisInitialized(_this), "logger", void 0); // LoggerManager 实例 // 计算缓存(用于性能优化) _defineProperty(_assertThisInitialized(_this), "calculationCache", {}); // 同步订单到后端锁(按订单维度),防止短时间内重复触发导致同一订单多次同步 _defineProperty(_assertThisInitialized(_this), "syncOrderToBackendInFlightByOrderKey", new Map()); // 直接挂载的模块 _defineProperty(_assertThisInitialized(_this), "order", void 0); _defineProperty(_assertThisInitialized(_this), "payment", void 0); return _this; } _createClass(CheckoutImpl, [{ key: "initialize", value: function () { var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) { var appPlugin, app; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: this.core = core; this.otherParams = options.otherParams || {}; // 获取依赖的插件 this.request = core.getPlugin('request'); if (this.request) { _context.next = 5; break; } throw new Error('Checkout 解决方案需要 request 插件支持'); case 5: // 获取 logger 实例 appPlugin = core.getPlugin('app'); if (appPlugin) { _context.next = 8; break; } throw new Error('Checkout 解决方案需要 app 插件支持'); case 8: app = appPlugin.getApp(); this.logger = app.logger; // 初始化模块 this.order = new OrderModule(); this.payment = new PaymentModule(); // 初始化状态 this.store = { cartItems: [], paymentMethods: [], stateAmount: '0.00', balanceDueAmount: '0.00', cartSummary: undefined, isOrderSynced: false, currentCustomer: undefined }; // 注册并初始化子模块 _context.next = 15; return this.initializeSubModules(core, options); case 15: _context.next = 17; return this.preloadPaymentMethods(); case 17: _context.next = 19; return this.cleanupExpiredOrdersAsync(); case 19: console.log('[Checkout] 初始化完成'); _context.next = 22; return this.core.effects.emit("".concat(this.name, ":onCheckoutInitialized"), { timestamp: Date.now() }); case 22: this.logInfo('CheckoutModule initialized successfully'); case 23: 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) { if (this.logger) { this.logger.addLog({ type: 'info', title: "[CheckoutModule] ".concat(this.getCurrentOrderId(), " ").concat(title), metadata: metadata || {} }); } } /** * 记录警告日志 */ }, { key: "logWarning", value: function logWarning(title, metadata) { if (this.logger) { this.logger.addLog({ type: 'warning', title: "[CheckoutModule] ".concat(title), metadata: metadata || {} }); } } /** * 记录错误日志 */ }, { key: "logError", value: function logError(title, metadata) { if (this.logger) { this.logger.addLog({ type: 'error', title: "[CheckoutModule] ".concat(title), metadata: metadata || {} }); } } /** * 初始化子模块 */ }, { key: "initializeSubModules", value: (function () { var _initializeSubModules = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(core, options) { var _options$store, _options$store2; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: // 初始化订单模块 core.registerModule(this.order, { store: ((_options$store = options.store) === null || _options$store === void 0 ? void 0 : _options$store.order) || {}, otherParams: _objectSpread(_objectSpread({}, this.otherParams), {}, { fatherModule: this.name }) }); // 初始化支付模块 core.registerModule(this.payment, { store: ((_options$store2 = options.store) === null || _options$store2 === void 0 ? void 0 : _options$store2.payment) || {}, otherParams: _objectSpread(_objectSpread({}, this.otherParams), {}, { fatherModule: this.name }) }); // 监听支付模块事件 this.setupPaymentEventListeners(); case 3: case "end": return _context2.stop(); } }, _callee2, this); })); function initializeSubModules(_x3, _x4) { return _initializeSubModules.apply(this, arguments); } return initializeSubModules; }() /** * 设置支付模块事件监听 */ ) }, { key: "setupPaymentEventListeners", value: function setupPaymentEventListeners() { var _this2 = this; // 监听支付成功事件 this.core.effects.on('payment:onPaymentSyncSuccess', /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(data) { var _this2$store$currentO; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (!(((_this2$store$currentO = _this2.store.currentOrder) === null || _this2$store$currentO === void 0 ? void 0 : _this2$store$currentO.uuid) === data.orderUuid)) { _context3.next = 3; break; } _context3.next = 3; return _this2.handlePaymentSuccess(data); case 3: case "end": return _context3.stop(); } }, _callee3); })); return function (_x5) { return _ref.apply(this, arguments); }; }()); // 监听支付失败事件 this.core.effects.on('payment:onPaymentSyncError', /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(data) { var _this2$store$currentO2; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: if (!(((_this2$store$currentO2 = _this2.store.currentOrder) === null || _this2$store$currentO2 === void 0 ? void 0 : _this2$store$currentO2.uuid) === data.orderUuid)) { _context4.next = 3; break; } _context4.next = 3; return _this2.handlePaymentError(data); case 3: case "end": return _context4.stop(); } }, _callee4); })); return function (_x6) { return _ref2.apply(this, arguments); }; }()); // 监听支付方式加载完成事件 this.core.effects.on(PaymentHooks.OnPaymentMethodsLoaded, /*#__PURE__*/function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(methods) { return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: console.log('[Checkout] 收到支付方式加载完成事件:', methods.length); _this2.store.paymentMethods = methods; case 2: case "end": return _context5.stop(); } }, _callee5); })); return function (_x7) { return _ref3.apply(this, arguments); }; }()); // 监听支付方式变更事件 this.core.effects.on(PaymentHooks.OnPaymentMethodsChanged, /*#__PURE__*/function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(data) { return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: console.log('[Checkout] 收到支付方式变更事件:', { oldCount: data.oldMethods.length, newCount: data.newMethods.length }); _this2.store.paymentMethods = data.newMethods; case 2: case "end": return _context6.stop(); } }, _callee6); })); return function (_x8) { return _ref4.apply(this, arguments); }; }()); } /** * 初始化结账流程 */ }, { key: "initializeCheckoutAsync", value: (function () { var _initializeCheckoutAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(params) { var _params$cartItems; var validation; return _regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: this.logInfo('initializeCheckoutAsync called', { cartItemsCount: ((_params$cartItems = params.cartItems) === null || _params$cartItems === void 0 ? void 0 : _params$cartItems.length) || 0, orderType: params.orderType, platform: params.platform }); _context7.prev = 1; // 验证参数 validation = this.validateCheckoutParams(params); if (validation.valid) { _context7.next = 5; break; } throw createCheckoutError(CheckoutErrorType.ValidationFailed, "\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25: ".concat(validation.errors.join(', '))); case 5: // 保存购物车数据 this.store.cartItems = params.cartItems; console.log('[Checkout] 结账流程初始化完成'); _context7.next = 14; break; case 9: _context7.prev = 9; _context7.t0 = _context7["catch"](1); _context7.next = 13; return this.handleError(_context7.t0, CheckoutErrorType.UnknownError); case 13: throw _context7.t0; case 14: case "end": return _context7.stop(); } }, _callee7, this, [[1, 9]]); })); function initializeCheckoutAsync(_x9) { return _initializeCheckoutAsync.apply(this, arguments); } return initializeCheckoutAsync; }()) }, { key: "getHolderIdFromBooking", value: function getHolderIdFromBooking(obj) { var _obj$holder; if (!obj) return undefined; var ret = obj.holder_id || ((_obj$holder = obj.holder) === null || _obj$holder === void 0 ? void 0 : _obj$holder.form_record); if (Array.isArray(ret)) { return ret.length > 0 ? Number(ret[0]) : undefined; } return Number(ret) || undefined; } }, { key: "getProductListByOrder", value: function getProductListByOrder() { var _this$store$currentOr, _this3 = this, _this$store$currentOr2; if (!this.store.currentOrder) { return []; } var getDiscountListAmount = function getDiscountListAmount(list) { return list.reduce(function (pre, item) { return pre + (item.amount || 0); }, 0); }; var formatProduct = function formatProduct(items) { return items.map(function (item) { var _item$is_charge_tax; return { product_id: item.product_id, product_variant_id: item.product_variant_id, quantity: item.num, is_price_include_tax: item.is_price_include_tax, // 商品是否含税:1;0 is_charge_tax: (_item$is_charge_tax = item.is_charge_tax) !== null && _item$is_charge_tax !== void 0 ? _item$is_charge_tax : 0, // 若商品不含税,计算得到的税费,单位(元) tax_fee: item.tax_fee, // 整个商品折扣后的总金额 selling_price: item.calculated_selling_price, // 使用者id holder_id: item.holder_id, // 整个商品折扣前的总金额 original_price: item.calculated_original_price, // 主商品折扣前金额,不包含套餐子商品 main_product_original_price: item.price, // 主商品折扣后金额,不包含套餐子商品 main_product_selling_price: item.main_product_selling_price, metadata: { // 主商品+非原价(加减价)子商品税费 "main_product_attached_bundle_tax_fee": item.metadata.main_product_attached_bundle_tax_fee, // 主商品+非原价(加减价)子商品附加费 "main_product_attached_bundle_surcharge_fee": item.metadata.main_product_attached_bundle_surcharge_fee, // 可选,附加费均摊舍入金额 "surcharge_rounding_remainder": item.metadata.surcharge_rounding_remainder }, product_bundle: (item.product_bundle || []).map(function (bundle) { return { is_price_include_tax: item.is_price_include_tax, bundle_id: bundle.bundle_id, bundle_product_id: bundle.bundle_product_id, bundle_variant_id: bundle.bundle_variant_id, price_type: bundle.price_type, price_type_ext: bundle.price_type_ext, // 套餐子商品总价,不包含折扣金额 bundle_sum_price: bundle.bundle_sum_price, // 套餐子商品折扣后金额 bundle_selling_price: bundle.bundle_selling_price, num: bundle.num, is_charge_tax: bundle.is_charge_tax, tax_fee: bundle.tax_fee, metadata: { // 子商品单数量附加费 "surcharge_fee": bundle.metadata.surcharge_fee, // 可选,附加费均摊舍入金额 "surcharge_rounding_remainder": bundle.metadata.surcharge_rounding_remainder } }; }) }; }) || []; }; var productList = formatProduct(((_this$store$currentOr = this.store.currentOrder.order_info) === null || _this$store$currentOr === void 0 || (_this$store$currentOr = _this$store$currentOr.original_order_data) === null || _this$store$currentOr === void 0 || (_this$store$currentOr = _this$store$currentOr.bookings) === null || _this$store$currentOr === void 0 ? void 0 : _this$store$currentOr.map(function (item) { return _objectSpread(_objectSpread({}, item.product), {}, { holder_id: _this3.getHolderIdFromBooking(item) }); })) || []); var relationProducts = formatProduct(((_this$store$currentOr2 = this.store.currentOrder.order_info) === null || _this$store$currentOr2 === void 0 || (_this$store$currentOr2 = _this$store$currentOr2.original_order_data) === null || _this$store$currentOr2 === void 0 ? void 0 : _this$store$currentOr2.relation_products) || []); return [].concat(_toConsumableArray(productList), _toConsumableArray(relationProducts)); } }, { key: "initWalletData", value: function () { var _initWalletData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(params) { var _this$store$currentOr3, _this$store$currentCu, _this$store$currentOr4, _this$store$currentOr5, _this$store$currentOr6, _this$store$currentOr8, amountInfo, walletBusinessData, _this$store$currentOr7; return _regeneratorRuntime().wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { case 0: this.logInfo('initWalletData called', { params: params }); _context8.prev = 1; amountInfo = (_this$store$currentOr3 = this.store.currentOrder) === null || _this$store$currentOr3 === void 0 || (_this$store$currentOr3 = _this$store$currentOr3.order_info) === null || _this$store$currentOr3 === void 0 ? void 0 : _this$store$currentOr3.amount_breakdown; if (amountInfo) { _context8.next = 6; break; } this.logInfo('initWalletData amountInfo not found', { params: params }); return _context8.abrupt("return"); case 6: // 准备钱包初始化的业务数据 walletBusinessData = _objectSpread({ customer_id: (_this$store$currentCu = this.store.currentCustomer) !== null && _this$store$currentCu !== void 0 && _this$store$currentCu.customer_id ? Number(this.store.currentCustomer.customer_id) : undefined, holder: (_this$store$currentOr4 = this.store.currentOrder) === null || _this$store$currentOr4 === void 0 || (_this$store$currentOr4 = _this$store$currentOr4.order_info) === null || _this$store$currentOr4 === void 0 || (_this$store$currentOr4 = _this$store$currentOr4.original_order_data) === null || _this$store$currentOr4 === void 0 ? void 0 : _this$store$currentOr4.holder, amountInfo: { totalAmount: amountInfo.totalAmount, subTotal: amountInfo.subTotal, depositAmount: (_this$store$currentOr5 = this.store.currentOrder) === null || _this$store$currentOr5 === void 0 ? void 0 : _this$store$currentOr5.deposit_amount, isDeposit: (_this$store$currentOr6 = this.store.currentOrder) === null || _this$store$currentOr6 === void 0 ? void 0 : _this$store$currentOr6.is_deposit }, products: this.getProductListByOrder(), is_price_include_tax: this.otherParams.is_price_include_tax }, params); // 判断订单是否已经同步,如果是则追加payment_order_id参数 if (this.store.isOrderSynced) { walletBusinessData.payment_order_id = (_this$store$currentOr7 = this.store.currentOrder) === null || _this$store$currentOr7 === void 0 ? void 0 : _this$store$currentOr7.order_id; } this.logInfo('开始拉取:initializeWalletDataFromBusinessAsync', { walletBusinessData: walletBusinessData }); _context8.next = 11; return this.payment.wallet.initializeWalletDataFromBusinessAsync(walletBusinessData); case 11: this.logInfo('调用结束:initializeWalletDataFromBusinessAsync', { walletBusinessData: walletBusinessData }); // 因为上面是接口 这里最好检查一下还有没有 currentOrder 了,如果没有,则不触发事件 if (this.store.currentOrder) { _context8.next = 14; break; } return _context8.abrupt("return"); case 14: this.logInfo('initWalletData currentOrder found', { currentOrder: this.store.currentOrder }); // 触发钱包数据初始化完成事件 _context8.next = 17; return this.core.effects.emit("".concat(this.name, ":onWalletDataInitialized"), { orderUuid: (_this$store$currentOr8 = this.store.currentOrder) === null || _this$store$currentOr8 === void 0 ? void 0 : _this$store$currentOr8.uuid, customerId: walletBusinessData.customer_id, walletBusinessData: { customer_id: walletBusinessData.customer_id, amountInfo: walletBusinessData.amountInfo, order_wait_pay_amount: params === null || params === void 0 ? void 0 : params.order_wait_pay_amount }, timestamp: Date.now() }); case 17: _context8.next = 23; break; case 19: _context8.prev = 19; _context8.t0 = _context8["catch"](1); this.logError('initWalletData error', { error: _context8.t0 instanceof Error ? _context8.t0.message : String(_context8.t0) }); throw _context8.t0; case 23: case "end": return _context8.stop(); } }, _callee8, this, [[1, 19]]); })); function initWalletData(_x10) { return _initWalletData.apply(this, arguments); } return initWalletData; }() }, { key: "checkIsNeedDepositAsync", value: function checkIsNeedDepositAsync(bookings, relationProducts) { var summaryDeposit = { total: 0, protocols: [], hasDeposit: false }; bookings === null || bookings === void 0 || bookings.forEach(function (item) { var total = item.product.calculated_selling_price; var deposit = getProductDeposit({ cartItem: { total: total }, product: item.product, bundle: item.bundle, options: item.options, num: item.num }); item.deposit = deposit; if (deposit !== null && deposit !== void 0 && deposit.total && Number(deposit.total) > 0) { summaryDeposit.protocols = summaryDeposit.protocols.concat(deposit.protocols); summaryDeposit.total = new Decimal(summaryDeposit.total).plus(deposit.total).toNumber(); summaryDeposit.hasDeposit = true; } }); relationProducts === null || relationProducts === void 0 || relationProducts.forEach(function (item) { var deposit = getProductDeposit({ cartItem: { total: item.price * item.num }, product: item, bundle: item.product_bundle, options: item.product_option_item, num: item.num }); item.deposit = deposit; if (deposit !== null && deposit !== void 0 && deposit.total && Number(deposit.total) > 0) { // 需要减去商品券折扣卡抵扣的金额 summaryDeposit.total = new Decimal(summaryDeposit.total).plus(deposit.total).toNumber(); item.discount_list.forEach(function (discount) { summaryDeposit.total = new Decimal(summaryDeposit.total).minus(discount.amount || 0).toNumber(); }); summaryDeposit.protocols = summaryDeposit.protocols.concat(deposit.protocols); summaryDeposit.hasDeposit = true; } }); // 将总金额四舍五入到两位小数 summaryDeposit.total = new Decimal(summaryDeposit.total).toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber(); return summaryDeposit; } /** * 创建本地订单 (前端模拟下单流程) * * 此方法用于在前端模拟整个下单流程,创建一个本地的虚拟订单。 * 用户在购物车点击下单时,会把购物车参数传递给此方法, * 方法会记录参数并创建本地虚拟订单,然后用 Payment 模块管理支付流程。 */ }, { key: "createLocalOrderAsync", value: (function () { var _createLocalOrderAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(params) { var _params$orderData, _params$orderData2, _params$orderData3, _params$orderData4, _params$orderData5, _params$cartSummary; var _params$totalInfo, _params$totalInfo2, _params$totalInfo3, _params$totalInfo4, validation, localOrderId, amountInfo, customerInfo, isNeedDeposit, paymentOrder, updateAmountStartTime, updateAmountDuration; return _regeneratorRuntime().wrap(function _callee9$(_context9) { while (1) switch (_context9.prev = _context9.next) { case 0: this.logInfo('createLocalOrderAsync called', { orderDataType: (_params$orderData = params.orderData) === null || _params$orderData === void 0 ? void 0 : _params$orderData.type, platform: (_params$orderData2 = params.orderData) === null || _params$orderData2 === void 0 ? void 0 : _params$orderData2.platform, bookingsCount: ((_params$orderData3 = params.orderData) === null || _params$orderData3 === void 0 || (_params$orderData3 = _params$orderData3.bookings) === null || _params$orderData3 === void 0 ? void 0 : _params$orderData3.length) || 0, relationProductsCount: ((_params$orderData4 = params.orderData) === null || _params$orderData4 === void 0 || (_params$orderData4 = _params$orderData4.relation_products) === null || _params$orderData4 === void 0 ? void 0 : _params$orderData4.length) || 0, customerId: (_params$orderData5 = params.orderData) === null || _params$orderData5 === void 0 ? void 0 : _params$orderData5.customer_id, autoPayment: params.autoPayment, cartSummaryCount: ((_params$cartSummary = params.cartSummary) === null || _params$cartSummary === void 0 ? void 0 : _params$cartSummary.length) || 0, totalInfoKeys: params.totalInfo ? Object.keys(params.totalInfo) : [] }); _context9.prev = 1; // 🔧 修改:在创建新订单前,直接重置 store 状态(同步执行) this.resetStoreState(); // 验证订单数据 validation = validateLocalOrderData(params.orderData); if (validation.valid) { _context9.next = 6; break; } throw createCheckoutError(CheckoutErrorType.ValidationFailed, "\u8BA2\u5355\u6570\u636E\u9A8C\u8BC1\u5931\u8D25: ".concat(validation.errors.join(', '))); case 6: // 生成本地虚拟订单ID (后续可以被真实订单ID替换) localOrderId = generateLocalOrderId(); // 从购物车小计数据中提取金额信息 amountInfo = extractAmountFromCartSummary(params.cartSummary); // TODO: 外面传的是 pos ,但是现在 后端只有 shop 和 kiosk params.orderData.platform = 'pos'; // 补充 created_at 时间 (YYYY-MM-DD hh:mm:ss 格式) params.orderData.created_at = formatDateTime(new Date()); // 补充附加费信息 params.orderData.surcharge_fee = (_params$totalInfo = params.totalInfo) === null || _params$totalInfo === void 0 || (_params$totalInfo = _params$totalInfo.total) === null || _params$totalInfo === void 0 ? void 0 : _params$totalInfo.otherAmount; params.orderData.surcharges = (_params$totalInfo2 = params.totalInfo) === null || _params$totalInfo2 === void 0 || (_params$totalInfo2 = _params$totalInfo2.total) === null || _params$totalInfo2 === void 0 ? void 0 : _params$totalInfo2.surcharge; // 补充订单折扣信息 params.orderData.shop_discount = (_params$totalInfo3 = params.totalInfo) === null || _params$totalInfo3 === void 0 || (_params$totalInfo3 = _params$totalInfo3.total) === null || _params$totalInfo3 === void 0 ? void 0 : _params$totalInfo3.shopDiscount; // 补充税费信息 params.orderData.tax_fee = (_params$totalInfo4 = params.totalInfo) === null || _params$totalInfo4 === void 0 || (_params$totalInfo4 = _params$totalInfo4.total) === null || _params$totalInfo4 === void 0 ? void 0 : _params$totalInfo4.tax; // 保存原始订单数据和小计数据到状态中 this.store.localOrderData = params.orderData; this.store.cartSummary = params.cartSummary; // 提取并保存客户信息(如果有) customerInfo = { customer_id: params.orderData.customer_id, customer_name: params.orderData.customer_name }; // 只有在有客户信息时才存储 if (customerInfo.customer_id || customerInfo.customer_name) { this.store.currentCustomer = customerInfo; console.log('[Checkout] 保存客户信息:', customerInfo); } else { this.store.currentCustomer = undefined; console.log('[Checkout] 未提供客户信息'); } // 计算是否需要支付定金,如果需要默认切换到定金模式,以及记录定金总金额,并把当前默认待付金额调整为定金总金额 isNeedDeposit = this.checkIsNeedDepositAsync(params.orderData.bookings, params.orderData.relation_products); // 创建支付订单对象 _context9.next = 21; return this.payment.createPaymentOrderAsync({ order_id: localOrderId, total_amount: amountInfo.totalAmount, is_deposit: isNeedDeposit.hasDeposit ? 1 : 0, deposit_amount: isNeedDeposit.total ? isNeedDeposit.total.toString() : '0.00', order_info: { original_order_data: params.orderData, cart_summary: params.cartSummary, created_at: new Date().toISOString(), platform: params.orderData.platform, type: params.orderData.type, schedule_date: params.orderData.schedule_date, shop_note: params.orderData.shop_note, amount_breakdown: amountInfo } }); case 21: paymentOrder = _context9.sent; this.store.currentOrder = paymentOrder; // // 如果设置了自动支付,直接跳转到支付步骤 // if (params.autoPayment) { // // 自动支付模式标记 // } this.core.effects.emit("".concat(this.name, ":onOrderCreated"), { order: paymentOrder, timestamp: Date.now() }); // 自动设置 stateAmount 为剩余未支付金额 // 🚀 性能监控:记录 updateStateAmountToRemaining 操作耗时 updateAmountStartTime = Date.now(); _context9.next = 27; return this.updateStateAmountToRemaining(false); case 27: updateAmountDuration = Date.now() - updateAmountStartTime; this.logInfo('updateStateAmountToRemaining operation completed', { operation: 'updateStateAmountToRemaining', orderUuid: paymentOrder.uuid, orderId: paymentOrder.order_id, duration: "".concat(updateAmountDuration, "ms"), performance: updateAmountDuration > 200 ? 'slow' : updateAmountDuration > 100 ? 'medium' : 'fast' }); this.logInfo('本地订单创建成功:', { localOrderId: localOrderId, uuid: paymentOrder.uuid, totalAmount: amountInfo.totalAmount, subTotal: amountInfo.subTotal, taxAmount: amountInfo.taxAmount, stateAmount: this.store.stateAmount }); this.initWalletData(); return _context9.abrupt("return", paymentOrder); case 34: _context9.prev = 34; _context9.t0 = _context9["catch"](1); _context9.next = 38; return this.handleError(_context9.t0, CheckoutErrorType.OrderCreationFailed); case 38: this.logError('本地订单创建失败:', _context9.t0); this.core.effects.emit("".concat(this.name, ":onOrderCreationFailed"), { error: this.store.lastError, timestamp: Date.now() }); th