'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} 调用结果 */ 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 = '\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 {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} ${this.escapeXml(item)}\n`; } }); xml += `${indent}\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}\n`; } else { // 简单值 xml += `${indent}<${key}>${this.escapeXml(value)}\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; } }); } /** * 保存奇门请求日志。 * @param {Object} logData 日志数据。 * @param {number} startTime 请求开始时间戳。 * @return {Promise} 新增日志ID。 */ 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', { log_id: logData.log_id || ctx.qimenLogId || 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)); } } 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;