WMS_MAIN/app/service/qimen.js
liufumingren cf3b9092c6 fix(qimen): 出站请求日志使用独立 log_id 并幂等消费日志队列
- qimen_client.sendRequest 出站日志改为 generateLogId() 生成 QL-<时间戳>-<随机>,
  不再复用入站 ctx.qimenLogId,避免与入站文件队列落库撞 wms_qimen_log.log_id 唯一索引
- qimen.saveQimenLog 去掉 ctx.qimenLogId 兜底;saveQimenLogResult / saveQimenLogBody
  改为按 log_id 定位更新(原先按 id 字段更新与调用语义不符)
- schedule/consume_qimen_logs 插入遇 ER_DUP_ENTRY 视为幂等命中跳过并推进消费进度,
  避免重复日志卡死文件队列
- test: qimen_query.test.js 断言改为校验新 log_id 格式
2026-09-13 15:29:43 +08:00

305 lines
9.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
const { XMLParser } = require('fast-xml-parser');
class QimenService extends Service {
/**
* 验证接口是否存在且启用
* @param {string} appkey 应用编码
* @param {string} customerId 客户编码
* @param {string} warehouseCode 仓库编码
*/
async validateApi(appkey, customerId, warehouseCode) {
try {
const result = await this.ctx.service.main.findQimenAppWithContract(appkey, customerId, warehouseCode);
return result;
} catch (error) {
this.ctx.logger.error('验证接口配置失败: ' + error.message);
return false;
}
}
async getErpName(appkey) {
const { app } = this;
const result = await app.model.QimenApp.findOne({
attributes: [
'id',
'name',
],
where: {
app_key: appkey,
},
raw: true,
});
if (result) {
return result.name;
}
return '未知ERP';
}
/**
* 解析XML到数组
* @param {string} xmlString XML 字符串
*/
async parseXmlToArray(xmlString) {
const cleanedXml = this.cleanXmlString(xmlString);
if (!cleanedXml || cleanedXml.trim() === '') {
throw new Error('XML数据为空');
}
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@_',
allowBooleanAttributes: true,
// 关闭值解析,保持原始字符串
parseTagValue: false,
parseAttributeValue: false,
trimValues: false, // 也关闭trim,保持原始格式
ignoreDeclaration: true,
// 保持 fast-xml-parser 的真实叶子文本值,避免把标签名误当成字段值。
tagValueProcessor: (tagName, tagValue) => tagValue,
});
try {
const result = parser.parse(cleanedXml);
return result;
} catch (error) {
throw new Error('XML解析错误: ' + error.message);
}
}
/**
* 清理XML字符串
* @param {string} xmlString XML 字符串
*/
cleanXmlString(xmlString) {
if (!xmlString) return '';
// 移除UTF-8 BOM
let cleaned = xmlString.replace(/^\uFEFF/, '');
// 移除XML声明前面的空白字符
cleaned = cleaned.trim();
// 如果XML声明不在开头,尝试找到并移动到开头
const xmlDeclarationMatch = cleaned.match(/<\?xml[^?>]+\?>/);
if (xmlDeclarationMatch && cleaned.indexOf(xmlDeclarationMatch[0]) > 0) {
const xmlDeclaration = xmlDeclarationMatch[0];
// 移除原有的XML声明
cleaned = cleaned.replace(/<\?xml[^?>]+\?>/, '');
// 将XML声明放到开头
cleaned = xmlDeclaration + '\n' + cleaned.trim();
}
return cleaned.trim();
}
/**
* 调用业务方法
* @param {string} className 类名
* @param {string} actionName 方法名
* @param {Object} xmlData 解析后的 XML 数据
* @param {number} storeId 货主ID
* @param {number} warehouseId 仓库ID
* @param {string} appKey 应用编码
* @param {string} customerId 客户编码
* @param {string} warehouseCode 仓库编码
* @return {Promise<Object>} 调用结果
*/
async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode) {
try {
// 构建服务类路径
const servicePath = `${className}`;
const classs = servicePath.split('.');
let qimenMethods = this.ctx.service.qimenMethods;
for (let i = 0; i < classs.length; i++) {
const className = classs[i];
qimenMethods = qimenMethods[className];
}
// 检查服务是否存在
if (!qimenMethods) {
throw new Error(`服务 ${servicePath} 不存在`);
}
const serviceInstance = qimenMethods;
// 检查方法是否存在
if (typeof serviceInstance[actionName] !== 'function') {
throw new Error(`方法 ${actionName} 不存在`);
}
// 调用方法
await serviceInstance.setInfo(storeId, warehouseId, appKey, customerId, warehouseCode);
const result = await serviceInstance[actionName](xmlData);
// 根据format参数返回相应格式
return this.formatResponse(result);
} catch (error) {
throw error;
}
}
/**
* 格式化响应
* @param {Object} data 响应数据
*/
formatResponse(data) {
return this.xmlResponse(data);
}
/**
* XML响应
* @param {Object} data 响应数据
*/
xmlResponse(data) {
let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
xml += '<response>\n';
// 处理固定字段
xml += ` <flag>${data.flag || 'failure'}</flag>\n`;
xml += ` <code>${data.code || '0'}</code>\n`;
xml += ` <message>${this.escapeXml(data.message || '操作成功')}</message>\n`;
// 添加其他数据字段
for (const [ key, value ] of Object.entries(data)) {
if (![ 'flag', 'code', 'message' ].includes(key)) {
xml += this.buildXmlNode(key, value, 1);
}
}
xml += '</response>';
return xml;
}
/**
* 构建XML节点 - 支持多层级
* @param {string} key 节点名
* @param {*} value 节点值
* @param {number} level 缩进层级
*/
buildXmlNode(key, value, level = 0) {
const indent = ' '.repeat(level);
let xml = '';
if (Array.isArray(value)) {
// 数字索引数组
if (value.every((_, index) => index in value)) {
xml += `${indent}<${key}>\n`;
value.forEach(item => {
if (Array.isArray(item) || typeof item === 'object') {
xml += this.buildXmlNode('item', item, level + 1);
} else {
xml += `${indent} <item>${this.escapeXml(item)}</item>\n`;
}
});
xml += `${indent}</${key}>\n`;
}
} else if (typeof value === 'object' && value !== null) {
// 对象
xml += `${indent}<${key}>\n`;
for (const [ subKey, subValue ] of Object.entries(value)) {
xml += this.buildXmlNode(subKey, subValue, level + 1);
}
xml += `${indent}</${key}>\n`;
} else {
// 简单值
xml += `${indent}<${key}>${this.escapeXml(value)}</${key}>\n`;
}
return xml;
}
/**
* XML转义
* @param {*} unsafe 待转义值
*/
escapeXml(unsafe) {
if (unsafe === null || unsafe === undefined) return '';
const str = String(unsafe);
return str.replace(/[<>&'"]/g, c => {
switch (c) {
case '<': return '&lt;';
case '>': return '&gt;';
case '&': return '&amp;';
case '\'': return '&apos;';
case '"': return '&quot;';
default: return c;
}
});
}
/**
* 保存出站奇门请求日志(直接落库)。
* 仅用于出站请求(qimenClient.sendRequest)的日志落库;
* 入站请求日志统一走文件队列异步消费落库,避免同一 log_id 双写入冲突。
* @param {Object} logData 日志数据,需包含 log_id 等字段。
* @param {number} startTime 请求开始时间戳。
* @return {Promise<number|undefined>} 新增日志主键 ID,失败时返回 undefined。
*/
async saveQimenLog(logData, startTime) {
const {
ctx,
} = this;
try {
// 限制日志内容长度
if (logData.body && logData.body.length > 65535) {
logData.body = logData.body.substring(0, 65535);
}
if (logData.result && logData.result.length > 65535) {
logData.result = logData.result.substring(0, 65535);
}
logData.use_time = Date.now() - startTime;
// 不再回退使用 ctx.qimenLogId:入站 log_id 已由文件队列消费落库,
// 出站复用会触发唯一索引冲突,出站日志必须使用自身生成的 log_id。
const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', {
log_id: logData.log_id || null,
from_key: logData.from_key || '',
to_key: logData.to_key || '',
method: logData.method || '',
sign: logData.sign || '',
costomer_id: logData.costomer_id || '',
v: logData.v || '',
url: logData.url || '',
created_at: ctx.app.mysql.get('wms').literals.now,
body: logData.body || '',
result: logData.result || '',
use_time: logData.use_time || 0,
});
return result.insertId;
} catch (error) {
ctx.logger.error('保存奇门接口日志失败: ' + error.message);
// 可以选择记录到文件日志作为备用
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
}
}
/**
* 按 log_id 更新奇门请求日志的响应内容。
* @param {string} result 响应内容。
* @return {Promise<Object>} 数据库更新结果。
*/
async saveQimenLogResult(result) {
const { ctx } = this;
await ctx.app.mysql.get('wms').update('wms_qimen_log', { result }, {
where: { log_id: ctx.qimenLogId },
});
}
/**
* 按 log_id 更新奇门请求日志的请求体内容。
* @param {string} body 请求体内容。
* @return {Promise<Object>} 数据库更新结果。
*/
async saveQimenLogBody(body) {
const { ctx } = this;
await ctx.app.mysql.get('wms').update('wms_qimen_log', { body }, {
where: { log_id: ctx.qimenLogId },
});
}
}
module.exports = QimenService;