'use strict';
const Service = require('egg').Service;
const { XMLParser } = require('fast-xml-parser');
class QimenService extends Service {
/**
* 验证接口是否存在且启用
* @param appkey
* @param customerId
* @param warehouseCode
*/
async validateApi(appkey, customerId, warehouseCode) {
try {
const { ctx } = this;
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 xmlString
*/
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,
// 添加标签值处理器,手动控制转换
tagValueProcessor: (tagName, tagValue, jPath, hasAttributes, isLeafNode) => {
// 如果是叶子节点且需要保持字符串格式的标签,可以在这里特殊处理
// 默认返回原始值
return tagValue;
},
});
try {
const result = parser.parse(cleanedXml);
return result;
} catch (error) {
throw new Error('XML解析错误: ' + error.message);
}
}
/**
* 清理XML字符串
* @param xmlString
*/
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 className
* @param actionName
* @param xmlData
* @param storeId
* @param warehouseId
* @param appKey
* @param customerId
* @param warehouseCode
* @param format
*/
async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode, format = 'xml') {
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 data
*/
formatResponse(data) {
return this.xmlResponse(data);
}
/**
* XML响应
* @param data
*/
xmlResponse(data) {
let xml = '\n';
xml += '\n';
// 处理固定字段
xml += ` ${data.flag || 'failure'}\n`;
xml += ` ${data.code || '0'}\n`;
xml += ` ${this.escapeXml(data.message || '操作成功')}\n`;
// 添加其他数据字段
for (const [ key, value ] of Object.entries(data)) {
if (![ 'flag', 'code', 'message' ].includes(key)) {
xml += this.buildXmlNode(key, value, 1);
}
}
xml += '';
return xml;
}
/**
* 构建XML节点 - 支持多层级
* @param key
* @param value
* @param 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} - ${this.escapeXml(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 '<';
case '>': return '>';
case '&': return '&';
case '\'': return ''';
case '"': return '"';
default: return c;
}
});
}
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;
// 使用 egg-mysql 保存日志到数据库
const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', {
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));
}
}
async saveQimenLogResult(result) {
await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { result, id: this.ctx.qimenLogId });
}
async saveQimenLogBody(body) {
await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { body, id: this.ctx.qimenLogId });
}
}
module.exports = QimenService;