@pisell/pisellos
Version:
一个可扩展的前端模块化SDK框架,支持插件系统
837 lines (811 loc) • 50.8 kB
JavaScript
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _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 _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 _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 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 _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 { WalletPassHooks } from "./types";
import { formatWalletPassList2PreparePayments as formatWalletPassList2PreparePaymentsUtils, sortUserIdentificationCodeList } from "./utils";
/**
* 钱包支付实现
*/
export var WalletPassPaymentImpl = /*#__PURE__*/function () {
function WalletPassPaymentImpl(paymentModule) {
_classCallCheck(this, WalletPassPaymentImpl);
_defineProperty(this, "walletRecommendList", []);
_defineProperty(this, "userIdentificationCodes", []);
_defineProperty(this, "searchResults", []);
_defineProperty(this, "walletParams", null);
_defineProperty(this, "walletInitData", null);
this.paymentModule = paymentModule;
}
/**
* 发送事件的辅助方法
* 支持使用WalletPassHooks或PaymentHooks
*/
_createClass(WalletPassPaymentImpl, [{
key: "emitEvent",
value: function emitEvent(hook, data) {
try {
// 提取事件名称,去掉模块前缀
var eventName = hook.split(':')[1] || hook.replace(/^[A-Z][a-z]+/, '').replace(/^On/, '').toLowerCase();
var fullEventName = "".concat(this.paymentModule.name, ":").concat(eventName);
this.paymentModule.core.effects.emit(fullEventName, data);
} catch (error) {
this.paymentModule.logError('[WalletPass] 发送事件失败', error, {
hook: hook
});
}
}
/**
* 生成钱包API默认参数
* 根据业务数据生成标准的钱包API参数,并存储在模块中
*/
}, {
key: "generateWalletParams",
value: function generateWalletParams(businessData) {
var _holder$form_record, _walletParams$product;
var customer_id = businessData.customer_id,
holder = businessData.holder,
amountInfo = businessData.amountInfo,
products = businessData.products,
order_wait_pay_amount = businessData.order_wait_pay_amount,
payment_order_id = businessData.payment_order_id,
is_price_include_tax = businessData.is_price_include_tax;
// 转换金额为数字类型
var totalAmount = Number(amountInfo.totalAmount);
var subTotal = Number(amountInfo.subTotal);
var walletParams = {
is_price_include_tax: is_price_include_tax,
sale_channel: 'pos',
customer_id: customer_id || 0,
// 提供默认值,确保类型为 number
holder_id: (holder === null || holder === void 0 || (_holder$form_record = holder.form_record) === null || _holder$form_record === void 0 ? void 0 : _holder$form_record[0]) || undefined,
order_expect_amount: totalAmount,
// 订单小计金额
order_product_amount: subTotal,
// 订单待支付金额
order_wait_pay_amount: order_wait_pay_amount || (amountInfo !== null && amountInfo !== void 0 && amountInfo.isDeposit ? Number(amountInfo === null || amountInfo === void 0 ? void 0 : amountInfo.depositAmount) : totalAmount),
// order_behavior_count_customer_id: 1,
products: products,
prepare_payments: [],
payment_order_id: payment_order_id
};
// 存储生成的参数到模块中
this.walletParams = walletParams;
this.paymentModule.logInfo('[WalletPass] 钱包默认参数已生成并存储', {
customer_id: walletParams.customer_id,
holder_id: walletParams.holder_id,
order_expect_amount: walletParams.order_expect_amount,
order_product_amount: walletParams.order_product_amount,
order_wait_pay_amount: walletParams.order_wait_pay_amount,
products_count: ((_walletParams$product = walletParams.products) === null || _walletParams$product === void 0 ? void 0 : _walletParams$product.length) || 0
});
this.walletInitData = {
transformList: [],
noApplicableVoucher: [],
products: products || []
};
return walletParams;
}
/**
* 获取已存储的钱包参数
* 返回之前生成并存储的钱包参数
*/
}, {
key: "getStoredWalletParams",
value: function getStoredWalletParams() {
return this.walletParams;
}
/**
* 清理已存储的钱包参数
* 清除之前存储的钱包参数
*/
}, {
key: "clearStoredWalletParams",
value: function clearStoredWalletParams() {
this.walletParams = null;
this.paymentModule.logInfo('[WalletPass] 已存储的钱包参数已清理');
}
/**
* 从业务数据初始化钱包数据
* 内部生成参数,然后调用标准的初始化流程
*/
}, {
key: "initializeWalletDataFromBusinessAsync",
value: (function () {
var _initializeWalletDataFromBusinessAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(businessData) {
var _businessData$amountI, _businessData$amountI2, _businessData$amountI3, _businessData$amountI4, _businessData$product;
var startTime, walletParams, _result$walletRecomme, _result$userIdentific, result, endTime, duration, _businessData$amountI5, _endTime, _duration;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
startTime = Date.now();
walletParams = this.generateWalletParams(businessData);
if (!(Number((businessData === null || businessData === void 0 || (_businessData$amountI = businessData.amountInfo) === null || _businessData$amountI === void 0 ? void 0 : _businessData$amountI.totalAmount) || 0) < 0 || Number((businessData === null || businessData === void 0 || (_businessData$amountI2 = businessData.amountInfo) === null || _businessData$amountI2 === void 0 ? void 0 : _businessData$amountI2.subTotal) || 0) < 0)) {
_context.next = 4;
break;
}
return _context.abrupt("return", {
walletRecommendList: [],
userIdentificationCodes: [],
transformList: [],
noApplicableVoucher: [],
products: []
});
case 4:
if (![1, 0].includes((walletParams === null || walletParams === void 0 ? void 0 : walletParams.customer_id) || 0)) {
_context.next = 6;
break;
}
return _context.abrupt("return", {
walletRecommendList: [],
userIdentificationCodes: []
});
case 6:
// 发送初始化开始事件
this.emitEvent(WalletPassHooks.OnWalletInitializationStarted, {
businessData: businessData,
startTime: startTime
});
this.paymentModule.logInfo('[WalletPass] 开始从业务数据初始化钱包数据', {
customer_id: businessData.customer_id,
totalAmount: (_businessData$amountI3 = businessData.amountInfo) === null || _businessData$amountI3 === void 0 ? void 0 : _businessData$amountI3.totalAmount,
subTotal: (_businessData$amountI4 = businessData.amountInfo) === null || _businessData$amountI4 === void 0 ? void 0 : _businessData$amountI4.subTotal,
order_wait_pay_amount: businessData.order_wait_pay_amount,
products_count: ((_businessData$product = businessData.products) === null || _businessData$product === void 0 ? void 0 : _businessData$product.length) || 0
});
_context.prev = 8;
_context.next = 11;
return this.initializeWalletDataAsync(walletParams);
case 11:
result = _context.sent;
endTime = Date.now();
duration = endTime - startTime; // 发送初始化完成事件
this.emitEvent(WalletPassHooks.OnWalletInitializationCompleted, {
businessData: businessData,
result: result,
startTime: startTime,
endTime: endTime,
duration: duration
});
this.paymentModule.logInfo("[WalletPass] \u4ECE\u4E1A\u52A1\u6570\u636E\u521D\u59CB\u5316\u94B1\u5305\u6570\u636E\u6210\u529F", {
duration: "".concat(duration, "ms"),
walletRecommendList_count: ((_result$walletRecomme = result.walletRecommendList) === null || _result$walletRecomme === void 0 ? void 0 : _result$walletRecomme.length) || 0,
userIdentificationCodes_count: ((_result$userIdentific = result.userIdentificationCodes) === null || _result$userIdentific === void 0 ? void 0 : _result$userIdentific.length) || 0
});
return _context.abrupt("return", result);
case 19:
_context.prev = 19;
_context.t0 = _context["catch"](8);
_endTime = Date.now();
_duration = _endTime - startTime; // 发送初始化失败事件
this.emitEvent(WalletPassHooks.OnWalletInitializationFailed, {
businessData: businessData,
error: _context.t0,
startTime: startTime,
endTime: _endTime,
duration: _duration
});
this.paymentModule.logError("[WalletPass] \u4ECE\u4E1A\u52A1\u6570\u636E\u521D\u59CB\u5316\u94B1\u5305\u6570\u636E\u5931\u8D25", _context.t0, {
duration: "".concat(_duration, "ms"),
customer_id: businessData.customer_id,
totalAmount: (_businessData$amountI5 = businessData.amountInfo) === null || _businessData$amountI5 === void 0 ? void 0 : _businessData$amountI5.totalAmount
});
throw _context.t0;
case 26:
case "end":
return _context.stop();
}
}, _callee, this, [[8, 19]]);
}));
function initializeWalletDataFromBusinessAsync(_x) {
return _initializeWalletDataFromBusinessAsync.apply(this, arguments);
}
return initializeWalletDataFromBusinessAsync;
}()
/**
* 获取订单基础详情
*/
)
}, {
key: "getOrderBasicDetailAsync",
value: (function () {
var _getOrderBasicDetailAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(orderId) {
var response;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return this.paymentModule.request.get("/order/order/".concat(orderId, "/basic-detail"));
case 3:
response = _context2.sent;
return _context2.abrupt("return", (response === null || response === void 0 ? void 0 : response.data) || {});
case 7:
_context2.prev = 7;
_context2.t0 = _context2["catch"](0);
throw _context2.t0;
case 10:
case "end":
return _context2.stop();
}
}, _callee2, this, [[0, 7]]);
}));
function getOrderBasicDetailAsync(_x2) {
return _getOrderBasicDetailAsync.apply(this, arguments);
}
return getOrderBasicDetailAsync;
}()
/**
* 初始化钱包数据
* 先获取推荐列表,再获取用户识别码列表(顺序执行)
*/
)
}, {
key: "initializeWalletDataAsync",
value: (function () {
var _initializeWalletDataAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(baseParams) {
var _this$paymentModule$w, _this$paymentModule$w2, identificationParams, _yield$Promise$all, _yield$Promise$all2, allList, orderBasicDetail, walletPassEvaluator, products, res, recommended, transformList, noApplicableVoucher, recommendedAmount;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
// 格式化用户识别码列表参数
identificationParams = _objectSpread(_objectSpread({}, baseParams), {}, {
available: 2,
prepare_payments: [],
other_exact_codes: [],
filter_prepare_wallet_pass: 1
}); // 并行获取用户识别码列表和订单详情
_context3.next = 4;
return Promise.all([this.getUserIdentificationCodeListAsync(identificationParams), baseParams.payment_order_id ? this.getOrderBasicDetailAsync(baseParams.payment_order_id) : Promise.resolve(null)]);
case 4:
_yield$Promise$all = _context3.sent;
_yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
allList = _yield$Promise$all2[0];
orderBasicDetail = _yield$Promise$all2[1];
walletPassEvaluator = (_this$paymentModule$w = this.paymentModule.window) === null || _this$paymentModule$w === void 0 || (_this$paymentModule$w2 = _this$paymentModule$w.getWalletPassEvaluator) === null || _this$paymentModule$w2 === void 0 ? void 0 : _this$paymentModule$w2.call(_this$paymentModule$w);
if (walletPassEvaluator) {
_context3.next = 11;
break;
}
return _context3.abrupt("return", {
walletRecommendList: [],
userIdentificationCodes: [],
transformList: [],
noApplicableVoucher: [],
products: []
});
case 11:
products = (orderBasicDetail === null || orderBasicDetail === void 0 ? void 0 : orderBasicDetail.detail) || baseParams.products;
res = walletPassEvaluator === null || walletPassEvaluator === void 0 ? void 0 : walletPassEvaluator.getRecommendedVouchers({
orderTotalAmount: baseParams.order_wait_pay_amount,
products: products,
vouchers: allList
});
recommended = res.recommended, transformList = res.transformList, noApplicableVoucher = res.noApplicableVoucher, recommendedAmount = res.recommendedAmount;
console.log(res, 'resres12');
this.walletRecommendList = recommended;
// 存储初始化数据到内存中,供 useWalletPass 使用
this.walletInitData = {
transformList: transformList,
noApplicableVoucher: noApplicableVoucher,
products: products || []
};
// // 再获取用户识别码列表
// const userIdentificationCodes =
// await this.getUserIdentificationCodeListAsync(identificationParams);
return _context3.abrupt("return", {
walletRecommendList: recommended,
userIdentificationCodes: allList,
transformList: transformList,
noApplicableVoucher: noApplicableVoucher,
products: products || []
});
case 20:
_context3.prev = 20;
_context3.t0 = _context3["catch"](0);
this.paymentModule.logError('[WalletPass] 初始化钱包数据失败', _context3.t0, {
customer_id: baseParams.customer_id,
order_expect_amount: baseParams.order_expect_amount
});
throw _context3.t0;
case 24:
case "end":
return _context3.stop();
}
}, _callee3, this, [[0, 20]]);
}));
function initializeWalletDataAsync(_x3) {
return _initializeWalletDataAsync.apply(this, arguments);
}
return initializeWalletDataAsync;
}())
}, {
key: "getWalletPassRecommendListAsync",
value: function () {
var _getWalletPassRecommendListAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(params) {
var _this$walletParams, response;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
_context4.prev = 0;
this.paymentModule.logInfo('[WalletPass] 开始获取钱包推荐列表', {
customer_id: params.customer_id,
order_expect_amount: params.order_expect_amount,
sale_channel: params.sale_channel,
payment_order_id: (_this$walletParams = this.walletParams) === null || _this$walletParams === void 0 ? void 0 : _this$walletParams.payment_order_id
});
_context4.next = 4;
return this.paymentModule.request.post('/machinecode/prepare/deduction/recommend', params // 将 params 作为请求体数据
);
case 4:
response = _context4.sent;
this.walletRecommendList = (response === null || response === void 0 ? void 0 : response.data) || [];
// 发送钱包推荐列表更新事件(使用专用的WalletPassHooks)
this.emitEvent(WalletPassHooks.OnWalletRecommendListUpdated, {
walletRecommendList: this.walletRecommendList
});
this.paymentModule.logInfo('[WalletPass] 钱包推荐列表已更新', {
count: this.walletRecommendList.length,
items: this.walletRecommendList.map(function (item) {
return {
voucher_id: item.voucher_id,
name: item.name,
amount: item.amount,
tag: item.tag
};
})
});
return _context4.abrupt("return", this.walletRecommendList);
case 11:
_context4.prev = 11;
_context4.t0 = _context4["catch"](0);
this.paymentModule.logError('[WalletPass] 获取钱包推荐列表失败', _context4.t0, {
customer_id: params.customer_id,
order_expect_amount: params.order_expect_amount,
sale_channel: params.sale_channel
});
// throw error;
return _context4.abrupt("return", []);
case 15:
case "end":
return _context4.stop();
}
}, _callee4, this, [[0, 11]]);
}));
function getWalletPassRecommendListAsync(_x4) {
return _getWalletPassRecommendListAsync.apply(this, arguments);
}
return getWalletPassRecommendListAsync;
}()
}, {
key: "formatWalletPassList2PreparePayments",
value: function formatWalletPassList2PreparePayments(list) {
return formatWalletPassList2PreparePaymentsUtils(list);
}
}, {
key: "getUserIdentificationCodeListAsync",
value: function () {
var _getUserIdentificationCodeListAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(params) {
var _newParams$prepare_pa, _this$walletParams2, newParams, response, sortedData;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_context5.prev = 0;
newParams = _objectSpread(_objectSpread({}, this.walletParams), params);
this.paymentModule.logInfo('[WalletPass] 开始获取用户识别码列表', {
customer_id: newParams.customer_id,
available: newParams.available,
prepare_payments_count: ((_newParams$prepare_pa = newParams.prepare_payments) === null || _newParams$prepare_pa === void 0 ? void 0 : _newParams$prepare_pa.length) || 0,
filter_prepare_wallet_pass: newParams.filter_prepare_wallet_pass,
payment_order_id: (_this$walletParams2 = this.walletParams) === null || _this$walletParams2 === void 0 ? void 0 : _this$walletParams2.payment_order_id
});
_context5.next = 5;
return this.paymentModule.request.post('/machinecode/prepare/deduction', newParams);
case 5:
response = _context5.sent;
// 对获取到的数据进行排序,将错误码为 500100、500200、500300 的项目排到最后
sortedData = sortUserIdentificationCodeList((response === null || response === void 0 ? void 0 : response.data) || []);
this.userIdentificationCodes = sortedData;
// 发送用户识别码列表更新事件(使用专用的WalletPassHooks)
this.emitEvent(WalletPassHooks.OnUserIdentificationCodesUpdated, {
userIdentificationCodes: this.userIdentificationCodes
});
this.paymentModule.logInfo('[WalletPass] 用户识别码列表已更新', {
count: this.userIdentificationCodes.length,
sorted_items: this.userIdentificationCodes.slice(0, 5).map(function (item) {
return {
code: item.code,
error_code: item.error_code,
error_msg: item.error_msg
};
})
});
return _context5.abrupt("return", this.userIdentificationCodes);
case 13:
_context5.prev = 13;
_context5.t0 = _context5["catch"](0);
this.paymentModule.logError('[WalletPass] 获取用户识别码列表失败', _context5.t0, {
customer_id: params.customer_id,
available: params.available
});
return _context5.abrupt("return", []);
case 17:
case "end":
return _context5.stop();
}
}, _callee5, this, [[0, 13]]);
}));
function getUserIdentificationCodeListAsync(_x5) {
return _getUserIdentificationCodeListAsync.apply(this, arguments);
}
return getUserIdentificationCodeListAsync;
}()
/**
* 搜索识别码信息
* 通过识别码搜索相关的钱包通行证信息
* 基于 WalletDeductionRecommendParams 参数结构
* 特殊逻辑:当识别码长度为9位且前3位为"000"时,调用 /wallet/detail/search 接口
*/
}, {
key: "searchIdentificationCodeAsync",
value: (function () {
var _searchIdentificationCodeAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(params) {
var config,
_ref,
_response2,
code,
isWalletCode,
walletDetailParams,
_response,
_searchResults,
baseWalletParams,
searchParams,
response,
searchResults,
_this$searchResults,
existingCodes,
newResults,
_args6 = arguments;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
config = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {};
_context6.prev = 1;
code = params.code;
this.paymentModule.logInfo('[WalletPass] 开始搜索识别码', {
code: code,
code_length: code.length,
noCache: config.noCache || false
});
// 检查识别码是否为9位且前3位为"000"
isWalletCode = code.length === 9 && code.startsWith('000'); // 测试环境先使用 WL
// const isWalletCode = code.startsWith('WL');
if (!isWalletCode) {
_context6.next = 14;
break;
}
// 钱包识别码直接调用专门接口,不缓存,直接返回
walletDetailParams = {
code: code,
with_customer: 1,
with: ['wallet']
};
this.paymentModule.logInfo('[WalletPass] 搜索钱包识别码', {
code: code,
with_customer: walletDetailParams.with_customer,
with: walletDetailParams.with
});
_context6.next = 10;
return this.paymentModule.request.post('/wallet/detail/search', walletDetailParams);
case 10:
_response = _context6.sent;
_searchResults = (_response === null || _response === void 0 ? void 0 : _response.data) || [];
this.paymentModule.logInfo('[WalletPass] 钱包识别码搜索完成', {
code: code,
results_count: _searchResults.length,
type: 'walletCode'
});
return _context6.abrupt("return", {
type: 'walletCode',
data: _searchResults
});
case 14:
// 合并钱包参数和搜索参数
baseWalletParams = this.walletParams; // 构建完整的搜索参数,包含钱包扣款推荐的所有参数
searchParams = {
// 基础钱包参数
sale_channel: params.sale_channel || (baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.sale_channel) || 'pos',
customer_id: params.customer_id || (baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.customer_id),
order_expect_amount: params.order_expect_amount || (baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.order_expect_amount),
order_product_amount: params.order_product_amount || (baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.order_product_amount),
order_wait_pay_amount: params.order_wait_pay_amount || (baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.order_wait_pay_amount),
order_behavior_count_customer_id: params.order_behavior_count_customer_id || (baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.order_behavior_count_customer_id),
products: params.products || (baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.products),
prepare_payments: params.prepare_payments || (baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.prepare_payments),
multiple: 1,
// 搜索特有参数
code: params.code,
payment_order_id: baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.payment_order_id
};
this.paymentModule.logInfo('[WalletPass] 搜索普通识别码', {
code: searchParams.code,
customer_id: searchParams.customer_id,
order_expect_amount: searchParams.order_expect_amount,
multiple: searchParams.multiple,
payment_order_id: baseWalletParams === null || baseWalletParams === void 0 ? void 0 : baseWalletParams.payment_order_id
});
if (!(!searchParams.products || ((_ref = searchParams.products || []) === null || _ref === void 0 ? void 0 : _ref.length) === 0)) {
_context6.next = 21;
break;
}
response = {
data: []
};
_context6.next = 24;
break;
case 21:
_context6.next = 23;
return this.paymentModule.request.post('/machinecode/prepare/deduction/search', searchParams);
case 23:
response = _context6.sent;
case 24:
searchResults = ((_response2 = response) === null || _response2 === void 0 ? void 0 : _response2.data) || [];
if (!config.noCache) {
_context6.next = 27;
break;
}
return _context6.abrupt("return", {
type: 'normalCode',
data: searchResults
});
case 27:
// 将搜索结果存储到缓存数组中
if (searchResults.length > 0) {
// 避免重复存储相同的识别码
existingCodes = new Set(this.searchResults.map(function (item) {
return item.code;
}));
newResults = searchResults.filter(function (item) {
return !existingCodes.has(item.code);
});
(_this$searchResults = this.searchResults).push.apply(_this$searchResults, _toConsumableArray(newResults));
}
// 通过事件暴露当前搜索结果和缓存结果
this.emitEvent(WalletPassHooks.OnSearchIdentificationCodeCompleted, {
searchCode: params.code,
currentSearchResults: searchResults,
cachedSearchResults: _toConsumableArray(this.searchResults),
searchParams: params
});
this.paymentModule.logInfo('[WalletPass] 普通识别码搜索完成', {
code: params.code,
results_count: searchResults.length,
cached_results_count: this.searchResults.length,
type: 'normalCode'
});
return _context6.abrupt("return", {
type: 'normalCode',
data: searchResults
});
case 33:
_context6.prev = 33;
_context6.t0 = _context6["catch"](1);
this.paymentModule.logError('[WalletPass] 搜索识别码信息失败', _context6.t0, {
code: params.code,
customer_id: params.customer_id,
order_expect_amount: params.order_expect_amount
});
throw _context6.t0;
case 37:
case "end":
return _context6.stop();
}
}, _callee6, this, [[1, 33]]);
}));
function searchIdentificationCodeAsync(_x6) {
return _searchIdentificationCodeAsync.apply(this, arguments);
}
return searchIdentificationCodeAsync;
}())
}, {
key: "processWalletPayment",
value: function () {
var _processWalletPayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(amount, orderUuid, voucherId) {
var walletMethod, paymentItem;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
this.paymentModule.logInfo('[WalletPass] 开始处理钱包支付', {
amount: amount,
orderUuid: orderUuid,
voucherId: voucherId || 'none'
});
_context7.next = 3;
return this.paymentModule.getWalletPaymentMethod();
case 3:
walletMethod = _context7.sent;
if (walletMethod) {
_context7.next = 7;
break;
}
this.paymentModule.logError('[WalletPass] 钱包支付方式未找到', null, {
amount: amount,
orderUuid: orderUuid,
voucherId: voucherId
});
throw new Error('钱包支付方式未找到');
case 7:
paymentItem = {
amount: amount.toString(),
code: walletMethod.code,
custom_payment_id: walletMethod.id,
name: walletMethod.name,
type: walletMethod.type,
voucher_id: voucherId || ''
};
_context7.next = 10;
return this.paymentModule.addPaymentItemAsync(orderUuid, paymentItem);
case 10:
this.paymentModule.logInfo('[WalletPass] 钱包支付处理完成', {
amount: amount,
orderUuid: orderUuid,
voucherId: voucherId || 'none',
payment_method: walletMethod.name
});
case 11:
case "end":
return _context7.stop();
}
}, _callee7, this);
}));
function processWalletPayment(_x7, _x8, _x9) {
return _processWalletPayment.apply(this, arguments);
}
return processWalletPayment;
}()
}, {
key: "getWalletBalance",
value: function () {
var _getWalletBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(voucherId) {
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
return _context8.abrupt("return", 0);
case 1:
case "end":
return _context8.stop();
}
}, _callee8);
}));
function getWalletBalance(_x10) {
return _getWalletBalance.apply(this, arguments);
}
return getWalletBalance;
}()
/**
* 获取缓存的钱包推荐列表
*/
}, {
key: "getWalletRecommendList",
value: function getWalletRecommendList() {
return this.walletRecommendList;
}
/**
* 获取缓存的用户识别码列表
*/
}, {
key: "getUserIdentificationCodes",
value: function getUserIdentificationCodes() {
return this.userIdentificationCodes;
}
/**
* 清除钱包推荐列表
*/
}, {
key: "clearWalletRecommendList",
value: function clearWalletRecommendList() {
this.walletRecommendList = [];
// 发送钱包推荐列表清除事件
this.emitEvent(WalletPassHooks.OnWalletRecommendListCleared, {
clearedTypes: ['walletRecommendList']
});
this.paymentModule.logInfo('[WalletPass] 钱包推荐列表已清除');
}
/**
* 清除用户识别码列表
*/
}, {
key: "clearUserIdentificationCodes",
value: function clearUserIdentificationCodes() {
this.userIdentificationCodes = [];
// 发送用户识别码列表清除事件
this.emitEvent(WalletPassHooks.OnUserIdentificationCodesCleared, {
clearedTypes: ['userIdentificationCodes']
});
this.paymentModule.logInfo('[WalletPass] 用户识别码列表已清除');
}
/**
* 获取缓存的搜索结果列表
*/
}, {
key: "getSearchResults",
value: function getSearchResults() {
return this.searchResults;
}
/**
* 根据识别码查找搜索结果
*/
}, {
key: "findSearchResultByCode",
value: function findSearchResultByCode(code) {
return this.searchResults.find(function (item) {
return item.code === code;
});
}
/**
* 清除搜索结果缓存
*/
}, {
key: "clearSearchResults",
value: function clearSearchResults() {
this.searchResults = [];
this.paymentModule.logInfo('[WalletPass] 搜索结果缓存已清除');
}
/**
* 获取存储的钱包初始化数据
*/
}, {
key: "getStoredWalletInitData",
value: function getStoredWalletInitData() {
return this.walletInitData;
}
/**
* 清除存储的钱包初始化数据
*/
}, {
key: "clearStoredWalletInitData",
value: function clearStoredWalletInitData() {
this.walletInitData = null;
this.paymentModule.logInfo('[WalletPass] 钱包初始化数据已清除');
}
/**
* 清除所有缓存数据
*/
}, {
key: "clearAllCache",
value: function clearAllCache() {
this.walletRecommendList = [];
this.userIdentificationCodes = [];
this.searchResults = [];
this.walletParams = null;
this.walletInitData = null;
// 发送所有缓存清除事件
this.emitEvent(WalletPassHooks.OnWalletCacheCleared, {
clearedTypes: ['all']
});
this.paymentModule.logInfo('[WalletPass] 所有缓存数据已清除', {
cleared_types: ['walletRecommendList', 'userIdentificationCodes', 'searchResults', 'walletParams', 'walletInitData']
});
}
}]);
return WalletPassPaymentImpl;
}();