@pisell/pisellos
Version:
一个可扩展的前端模块化SDK框架,支持插件系统
584 lines (582 loc) • 21 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/modules/Payment/walletpass.ts
var walletpass_exports = {};
__export(walletpass_exports, {
WalletPassPaymentImpl: () => WalletPassPaymentImpl
});
module.exports = __toCommonJS(walletpass_exports);
var import_types = require("./types");
var import_utils = require("./utils");
var WalletPassPaymentImpl = class {
constructor(paymentModule) {
this.paymentModule = paymentModule;
this.walletRecommendList = [];
this.userIdentificationCodes = [];
this.searchResults = [];
this.walletParams = null;
this.walletInitData = null;
}
/**
* 发送事件的辅助方法
* 支持使用WalletPassHooks或PaymentHooks
*/
emitEvent(hook, data) {
try {
const eventName = hook.split(":")[1] || hook.replace(/^[A-Z][a-z]+/, "").replace(/^On/, "").toLowerCase();
const fullEventName = `${this.paymentModule.name}:${eventName}`;
this.paymentModule.core.effects.emit(fullEventName, data);
} catch (error) {
this.paymentModule.logError("[WalletPass] 发送事件失败", error, {
hook
});
}
}
/**
* 生成钱包API默认参数
* 根据业务数据生成标准的钱包API参数,并存储在模块中
*/
generateWalletParams(businessData) {
var _a, _b;
const {
customer_id,
holder,
amountInfo,
products,
order_wait_pay_amount,
payment_order_id,
is_price_include_tax
} = businessData;
const totalAmount = Number(amountInfo.totalAmount);
const subTotal = Number(amountInfo.subTotal);
const walletParams = {
is_price_include_tax,
sale_channel: "pos",
customer_id: customer_id || 0,
// 提供默认值,确保类型为 number
holder_id: ((_a = holder == null ? void 0 : holder.form_record) == null ? void 0 : _a[0]) || void 0,
order_expect_amount: totalAmount,
// 订单小计金额
order_product_amount: subTotal,
// 订单待支付金额
order_wait_pay_amount: order_wait_pay_amount || ((amountInfo == null ? void 0 : amountInfo.isDeposit) ? Number(amountInfo == null ? void 0 : amountInfo.depositAmount) : totalAmount),
// order_behavior_count_customer_id: 1,
products,
prepare_payments: [],
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: ((_b = walletParams.products) == null ? void 0 : _b.length) || 0
});
this.walletInitData = {
transformList: [],
noApplicableVoucher: [],
products: products || []
};
return walletParams;
}
/**
* 获取已存储的钱包参数
* 返回之前生成并存储的钱包参数
*/
getStoredWalletParams() {
return this.walletParams;
}
/**
* 清理已存储的钱包参数
* 清除之前存储的钱包参数
*/
clearStoredWalletParams() {
this.walletParams = null;
this.paymentModule.logInfo("[WalletPass] 已存储的钱包参数已清理");
}
/**
* 从业务数据初始化钱包数据
* 内部生成参数,然后调用标准的初始化流程
*/
async initializeWalletDataFromBusinessAsync(businessData) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const startTime = Date.now();
const walletParams = this.generateWalletParams(businessData);
if (Number(((_a = businessData == null ? void 0 : businessData.amountInfo) == null ? void 0 : _a.totalAmount) || 0) < 0 || Number(((_b = businessData == null ? void 0 : businessData.amountInfo) == null ? void 0 : _b.subTotal) || 0) < 0) {
return {
walletRecommendList: [],
userIdentificationCodes: [],
transformList: [],
noApplicableVoucher: [],
products: []
};
}
if ([1, 0].includes((walletParams == null ? void 0 : walletParams.customer_id) || 0)) {
return {
walletRecommendList: [],
userIdentificationCodes: []
};
}
this.emitEvent(import_types.WalletPassHooks.OnWalletInitializationStarted, {
businessData,
startTime
});
this.paymentModule.logInfo("[WalletPass] 开始从业务数据初始化钱包数据", {
customer_id: businessData.customer_id,
totalAmount: (_c = businessData.amountInfo) == null ? void 0 : _c.totalAmount,
subTotal: (_d = businessData.amountInfo) == null ? void 0 : _d.subTotal,
order_wait_pay_amount: businessData.order_wait_pay_amount,
products_count: ((_e = businessData.products) == null ? void 0 : _e.length) || 0
});
try {
const result = await this.initializeWalletDataAsync(walletParams);
const endTime = Date.now();
const duration = endTime - startTime;
this.emitEvent(import_types.WalletPassHooks.OnWalletInitializationCompleted, {
businessData,
result,
startTime,
endTime,
duration
});
this.paymentModule.logInfo(`[WalletPass] 从业务数据初始化钱包数据成功`, {
duration: `${duration}ms`,
walletRecommendList_count: ((_f = result.walletRecommendList) == null ? void 0 : _f.length) || 0,
userIdentificationCodes_count: ((_g = result.userIdentificationCodes) == null ? void 0 : _g.length) || 0
});
return result;
} catch (error) {
const endTime = Date.now();
const duration = endTime - startTime;
this.emitEvent(import_types.WalletPassHooks.OnWalletInitializationFailed, {
businessData,
error,
startTime,
endTime,
duration
});
this.paymentModule.logError(
`[WalletPass] 从业务数据初始化钱包数据失败`,
error,
{
duration: `${duration}ms`,
customer_id: businessData.customer_id,
totalAmount: (_h = businessData.amountInfo) == null ? void 0 : _h.totalAmount
}
);
throw error;
}
}
/**
* 获取订单基础详情
*/
async getOrderBasicDetailAsync(orderId) {
try {
const response = await this.paymentModule.request.get(
`/order/order/${orderId}/basic-detail`
);
return (response == null ? void 0 : response.data) || {};
} catch (error) {
throw error;
}
}
/**
* 初始化钱包数据
* 先获取推荐列表,再获取用户识别码列表(顺序执行)
*/
async initializeWalletDataAsync(baseParams) {
var _a, _b;
try {
const identificationParams = {
...baseParams,
available: 2,
prepare_payments: [],
other_exact_codes: [],
filter_prepare_wallet_pass: 1
};
const [allList, orderBasicDetail] = await Promise.all([
this.getUserIdentificationCodeListAsync(identificationParams),
baseParams.payment_order_id ? this.getOrderBasicDetailAsync(baseParams.payment_order_id) : Promise.resolve(null)
]);
const walletPassEvaluator = (_b = (_a = this.paymentModule.window) == null ? void 0 : _a.getWalletPassEvaluator) == null ? void 0 : _b.call(_a);
if (!walletPassEvaluator) {
return {
walletRecommendList: [],
userIdentificationCodes: [],
transformList: [],
noApplicableVoucher: [],
products: []
};
}
const products = (orderBasicDetail == null ? void 0 : orderBasicDetail.detail) || baseParams.products;
const res = walletPassEvaluator == null ? void 0 : walletPassEvaluator.getRecommendedVouchers({
orderTotalAmount: baseParams.order_wait_pay_amount,
products,
vouchers: allList
});
const { recommended, transformList, noApplicableVoucher, recommendedAmount } = res;
console.log(res, "resres12");
this.walletRecommendList = recommended;
this.walletInitData = {
transformList,
noApplicableVoucher,
products: products || []
};
return {
walletRecommendList: recommended,
userIdentificationCodes: allList,
transformList,
noApplicableVoucher,
products: products || []
};
} catch (error) {
this.paymentModule.logError("[WalletPass] 初始化钱包数据失败", error, {
customer_id: baseParams.customer_id,
order_expect_amount: baseParams.order_expect_amount
});
throw error;
}
}
async getWalletPassRecommendListAsync(params) {
var _a;
try {
this.paymentModule.logInfo("[WalletPass] 开始获取钱包推荐列表", {
customer_id: params.customer_id,
order_expect_amount: params.order_expect_amount,
sale_channel: params.sale_channel,
payment_order_id: (_a = this.walletParams) == null ? void 0 : _a.payment_order_id
});
const response = await this.paymentModule.request.post(
"/machinecode/prepare/deduction/recommend",
params
// 将 params 作为请求体数据
);
this.walletRecommendList = (response == null ? void 0 : response.data) || [];
this.emitEvent(import_types.WalletPassHooks.OnWalletRecommendListUpdated, {
walletRecommendList: this.walletRecommendList
});
this.paymentModule.logInfo("[WalletPass] 钱包推荐列表已更新", {
count: this.walletRecommendList.length,
items: this.walletRecommendList.map((item) => ({
voucher_id: item.voucher_id,
name: item.name,
amount: item.amount,
tag: item.tag
}))
});
return this.walletRecommendList;
} catch (error) {
this.paymentModule.logError("[WalletPass] 获取钱包推荐列表失败", error, {
customer_id: params.customer_id,
order_expect_amount: params.order_expect_amount,
sale_channel: params.sale_channel
});
return [];
}
}
formatWalletPassList2PreparePayments(list) {
return (0, import_utils.formatWalletPassList2PreparePayments)(list);
}
async getUserIdentificationCodeListAsync(params) {
var _a, _b;
try {
const newParams = {
...this.walletParams,
...params
};
this.paymentModule.logInfo("[WalletPass] 开始获取用户识别码列表", {
customer_id: newParams.customer_id,
available: newParams.available,
prepare_payments_count: ((_a = newParams.prepare_payments) == null ? void 0 : _a.length) || 0,
filter_prepare_wallet_pass: newParams.filter_prepare_wallet_pass,
payment_order_id: (_b = this.walletParams) == null ? void 0 : _b.payment_order_id
});
const response = await this.paymentModule.request.post(
"/machinecode/prepare/deduction",
newParams
);
const sortedData = (0, import_utils.sortUserIdentificationCodeList)((response == null ? void 0 : response.data) || []);
this.userIdentificationCodes = sortedData;
this.emitEvent(import_types.WalletPassHooks.OnUserIdentificationCodesUpdated, {
userIdentificationCodes: this.userIdentificationCodes
});
this.paymentModule.logInfo("[WalletPass] 用户识别码列表已更新", {
count: this.userIdentificationCodes.length,
sorted_items: this.userIdentificationCodes.slice(0, 5).map((item) => ({
code: item.code,
error_code: item.error_code,
error_msg: item.error_msg
}))
});
return this.userIdentificationCodes;
} catch (error) {
this.paymentModule.logError(
"[WalletPass] 获取用户识别码列表失败",
error,
{
customer_id: params.customer_id,
available: params.available
}
);
return [];
}
}
/**
* 搜索识别码信息
* 通过识别码搜索相关的钱包通行证信息
* 基于 WalletDeductionRecommendParams 参数结构
* 特殊逻辑:当识别码长度为9位且前3位为"000"时,调用 /wallet/detail/search 接口
*/
async searchIdentificationCodeAsync(params, config = {}) {
var _a;
try {
const { code } = params;
this.paymentModule.logInfo("[WalletPass] 开始搜索识别码", {
code,
code_length: code.length,
noCache: config.noCache || false
});
const isWalletCode = code.length === 9 && code.startsWith("000");
if (isWalletCode) {
const walletDetailParams = {
code,
with_customer: 1,
with: ["wallet"]
};
this.paymentModule.logInfo("[WalletPass] 搜索钱包识别码", {
code,
with_customer: walletDetailParams.with_customer,
with: walletDetailParams.with
});
const response2 = await this.paymentModule.request.post(
"/wallet/detail/search",
walletDetailParams
);
const searchResults2 = (response2 == null ? void 0 : response2.data) || [];
this.paymentModule.logInfo("[WalletPass] 钱包识别码搜索完成", {
code,
results_count: searchResults2.length,
type: "walletCode"
});
return {
type: "walletCode",
data: searchResults2
};
}
const baseWalletParams = this.walletParams;
const searchParams = {
// 基础钱包参数
sale_channel: params.sale_channel || (baseWalletParams == null ? void 0 : baseWalletParams.sale_channel) || "pos",
customer_id: params.customer_id || (baseWalletParams == null ? void 0 : baseWalletParams.customer_id),
order_expect_amount: params.order_expect_amount || (baseWalletParams == null ? void 0 : baseWalletParams.order_expect_amount),
order_product_amount: params.order_product_amount || (baseWalletParams == null ? void 0 : baseWalletParams.order_product_amount),
order_wait_pay_amount: params.order_wait_pay_amount || (baseWalletParams == null ? void 0 : baseWalletParams.order_wait_pay_amount),
order_behavior_count_customer_id: params.order_behavior_count_customer_id || (baseWalletParams == null ? void 0 : baseWalletParams.order_behavior_count_customer_id),
products: params.products || (baseWalletParams == null ? void 0 : baseWalletParams.products),
prepare_payments: params.prepare_payments || (baseWalletParams == null ? void 0 : baseWalletParams.prepare_payments),
multiple: 1,
// 搜索特有参数
code: params.code,
payment_order_id: baseWalletParams == null ? 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 ? void 0 : baseWalletParams.payment_order_id
});
let response;
if (!searchParams.products || ((_a = searchParams.products || []) == null ? void 0 : _a.length) === 0) {
response = {
data: []
};
} else {
response = await this.paymentModule.request.post(
"/machinecode/prepare/deduction/search",
searchParams
);
}
const searchResults = (response == null ? void 0 : response.data) || [];
if (config.noCache) {
return {
type: "normalCode",
data: searchResults
};
}
if (searchResults.length > 0) {
const existingCodes = new Set(
this.searchResults.map((item) => item.code)
);
const newResults = searchResults.filter(
(item) => !existingCodes.has(item.code)
);
this.searchResults.push(...newResults);
}
this.emitEvent(import_types.WalletPassHooks.OnSearchIdentificationCodeCompleted, {
searchCode: params.code,
currentSearchResults: searchResults,
cachedSearchResults: [...this.searchResults],
searchParams: params
});
this.paymentModule.logInfo("[WalletPass] 普通识别码搜索完成", {
code: params.code,
results_count: searchResults.length,
cached_results_count: this.searchResults.length,
type: "normalCode"
});
return {
type: "normalCode",
data: searchResults
};
} catch (error) {
this.paymentModule.logError("[WalletPass] 搜索识别码信息失败", error, {
code: params.code,
customer_id: params.customer_id,
order_expect_amount: params.order_expect_amount
});
throw error;
}
}
async processWalletPayment(amount, orderUuid, voucherId) {
this.paymentModule.logInfo("[WalletPass] 开始处理钱包支付", {
amount,
orderUuid,
voucherId: voucherId || "none"
});
const walletMethod = await this.paymentModule.getWalletPaymentMethod();
if (!walletMethod) {
this.paymentModule.logError("[WalletPass] 钱包支付方式未找到", null, {
amount,
orderUuid,
voucherId
});
throw new Error("钱包支付方式未找到");
}
const paymentItem = {
amount: amount.toString(),
code: walletMethod.code,
custom_payment_id: walletMethod.id,
name: walletMethod.name,
type: walletMethod.type,
voucher_id: voucherId || ""
};
await this.paymentModule.addPaymentItemAsync(orderUuid, paymentItem);
this.paymentModule.logInfo("[WalletPass] 钱包支付处理完成", {
amount,
orderUuid,
voucherId: voucherId || "none",
payment_method: walletMethod.name
});
}
async getWalletBalance(voucherId) {
return 0;
}
/**
* 获取缓存的钱包推荐列表
*/
getWalletRecommendList() {
return this.walletRecommendList;
}
/**
* 获取缓存的用户识别码列表
*/
getUserIdentificationCodes() {
return this.userIdentificationCodes;
}
/**
* 清除钱包推荐列表
*/
clearWalletRecommendList() {
this.walletRecommendList = [];
this.emitEvent(import_types.WalletPassHooks.OnWalletRecommendListCleared, {
clearedTypes: ["walletRecommendList"]
});
this.paymentModule.logInfo("[WalletPass] 钱包推荐列表已清除");
}
/**
* 清除用户识别码列表
*/
clearUserIdentificationCodes() {
this.userIdentificationCodes = [];
this.emitEvent(import_types.WalletPassHooks.OnUserIdentificationCodesCleared, {
clearedTypes: ["userIdentificationCodes"]
});
this.paymentModule.logInfo("[WalletPass] 用户识别码列表已清除");
}
/**
* 获取缓存的搜索结果列表
*/
getSearchResults() {
return this.searchResults;
}
/**
* 根据识别码查找搜索结果
*/
findSearchResultByCode(code) {
return this.searchResults.find((item) => item.code === code);
}
/**
* 清除搜索结果缓存
*/
clearSearchResults() {
this.searchResults = [];
this.paymentModule.logInfo("[WalletPass] 搜索结果缓存已清除");
}
/**
* 获取存储的钱包初始化数据
*/
getStoredWalletInitData() {
return this.walletInitData;
}
/**
* 清除存储的钱包初始化数据
*/
clearStoredWalletInitData() {
this.walletInitData = null;
this.paymentModule.logInfo("[WalletPass] 钱包初始化数据已清除");
}
/**
* 清除所有缓存数据
*/
clearAllCache() {
this.walletRecommendList = [];
this.userIdentificationCodes = [];
this.searchResults = [];
this.walletParams = null;
this.walletInitData = null;
this.emitEvent(import_types.WalletPassHooks.OnWalletCacheCleared, {
clearedTypes: ["all"]
});
this.paymentModule.logInfo("[WalletPass] 所有缓存数据已清除", {
cleared_types: [
"walletRecommendList",
"userIdentificationCodes",
"searchResults",
"walletParams",
"walletInitData"
]
});
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WalletPassPaymentImpl
});