const crypto = require('crypto'); const { Controller, } = require('egg'); const { toSuccess, toFailure } = require('../lib/api_response'); class HomeController extends Controller { async testSendData() { await this.ctx.service.systems.print.index.test(); this.ctx.body = 'ok'; } async index() { const { ctx, } = this; ctx.body = 'pong'; } /** * 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。 * @return {Promise} 无返回值。 */ async qimen() { const { ctx, service, } = this; const startTime = Date.now(); const logId = 'QL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'); ctx.qimenLogId = logId; // 初始化日志数据 const logData = { log_id: logId, from_key: '', to_key: this.app.config.qimen.appKey, method: '', sign: '', costomer_id: '', v: '', url: ctx.request.href, created_at: new Date(), body: '', result: '', use_time: 0, }; const getParams = ctx.query; // 记录基础日志信息 logData.from_key = getParams.app_key || ''; logData.method = getParams.method || ''; logData.sign = getParams.sign || ''; logData.costomer_id = getParams.customerId || getParams.customer_id || ''; logData.v = getParams.v || ''; try { // 验证必要参数 if (!this.validateQimenParams(getParams)) { const errorMsg = '参数缺失或错误'; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } // 处理method参数 const method = getParams.method; const methods = method.split('.'); const actionName = methods.pop(); const className = methods.map((item, index) => (index === methods.length - 1 ? item : item) ).join('.'); const appkey = getParams.app_key; const customerId = getParams.customerId; // 获取XML数据 let xmlData = ''; if (ctx.request.rawBody) { // 使用 rawBody 获取原始请求体 xmlData = ctx.request.rawBody; } else { // 如果没有 rawBody,尝试从流中读取 xmlData = await new Promise((resolve, reject) => { let data = ''; ctx.req.on('data', chunk => { data += chunk; }); ctx.req.on('end', () => { resolve(data); }); ctx.req.on('error', reject); }); } // 确保 xmlData 是字符串 xmlData = xmlData ? String(xmlData) : ''; if (!xmlData || xmlData.trim() === '') { throw new Error('XML数据为空'); } // 解析XML数据 const xmlArray = await service.qimen.parseXmlToArray(xmlData); xmlArray.app_key = appkey; const warehouseCode = this.getQimenWarehouseCode(xmlArray); if (!warehouseCode) { const errorMsg = 'XML数据格式错误,无法提取有效的warehouseCode'; const responseFormat = getParams.format || 'xml'; const response = this.errorResponse(errorMsg, responseFormat); ctx.body = response; ctx.type = responseFormat === 'xml' ? 'application/xml' : 'application/json'; return; } logData.body = xmlData; const erpName = await service.qimen.getErpName(appkey); let api_info = { warehouseCode: '', ownerCode: '', }; if (warehouseCode && customerId) { // 验证接口是否存在且启用 api_info = await service.qimen.validateApi(appkey, customerId, warehouseCode); if (!api_info) { const errorMsg = `奇门${erpName}客户编码${customerId}仓库编码${warehouseCode}未绑定到你的货主或未启用,请联系仓库绑定`; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } if (api_info.contract_auth_status !== 2) { const errorMsg = `货主与仓库签约状态异常,请到WMS核实签约状态${api_info.contract_auth_status}`; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } if (api_info.warehouse_status === 0) { const errorMsg = '仓库状态异常,请联系仓库核实WMS状态'; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } const currentTime = new Date(); const authEndTime = new Date(api_info.warehouse_auth_end); const authEndTime2 = new Date(api_info.auth_end); if (authEndTime2 < currentTime) { const errorMsg = '与仓库合约过期,请到WMS重新发起仓库续约'; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } if (authEndTime < currentTime) { const errorMsg = '仓库订阅过期,请联系仓库核实状态'; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } } // 调用业务方法 const result = await service.qimen.callMethod(className, actionName, xmlArray, api_info.store_id, api_info.warehouse_id, appkey, customerId, warehouseCode, getParams.format); ctx.body = result; ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json'; } catch (error) { const response = this.errorResponse('奇门接口错误: ' + error.message, ctx.query.format || 'xml'); ctx.body = response; ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json'; } finally { // 统一写入日志文件队列 logData.use_time = Date.now() - startTime; logData.result = typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body); 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); } // 日志落盘改为异步投递,避免阻塞主请求响应。 Promise.resolve(this.app.fileWriter.writeRecord('qimen-logs', logData)).catch(writeErr => { ctx.logger.error('[qimen-log-sink] 写入文件失败: ' + writeErr.message); ctx.logger.info('[qimen-log-sink] 日志数据: ', JSON.stringify(logData)); }); } } /** * 归一化奇门字段值,过滤空白内容和占位符字符串。 * @param {string|number|null|undefined} value 待处理字段值。 * @return {string} 归一化后的字段值。 */ normalizeQimenFieldValue(value) { if (value === null || value === undefined) { return ''; } const normalizedValue = String(value).trim(); if (!normalizedValue || normalizedValue === 'warehouseCode') { return ''; } return normalizedValue; } /** * 递归扫描奇门 XML 树,提取指定字段的有效值,只匹配字段名对应的节点。 * @param {Object|Array|string|number|null|undefined} node 待扫描节点。 * @param {string} fieldName 目标字段名。 * @param {Set} [visited=new Set()] 循环引用保护集合。 * @return {string} 找到的有效字段值。 */ findQimenFieldValue(node, fieldName, visited = new Set()) { if (node === null || node === undefined) { return ''; } if (typeof node !== 'object') { return ''; } if (visited.has(node)) { return ''; } visited.add(node); if (Array.isArray(node)) { for (const item of node) { const value = this.findQimenFieldValue(item, fieldName, visited); if (value) { return value; } } return ''; } if (Object.prototype.hasOwnProperty.call(node, fieldName)) { const directValue = this.normalizeQimenFieldValue(node[fieldName]); if (directValue) { return directValue; } const nestedValue = this.findQimenFieldValue(node[fieldName], fieldName, visited); if (nestedValue) { return nestedValue; } } for (const [ key, value ] of Object.entries(node)) { if (key === fieldName) { continue; } if (value === null || value === undefined) { continue; } if (typeof value !== 'object') { continue; } const foundValue = this.findQimenFieldValue(value, fieldName, visited); if (foundValue) { return foundValue; } } return ''; } /** * 从奇门请求体中提取有效的仓库编码,优先读取 request 下的固定路径,再回退到递归扫描。 * @param {Object} xmlArray 解析后的 XML 数据。 * @return {string} 有效的仓库编码。 */ getQimenWarehouseCode(xmlArray) { const request = xmlArray?.request || xmlArray || {}; const fixedPaths = [ request?.deliveryOrder?.warehouseCode, request?.entryOrder?.warehouseCode, request.warehouseCode, ]; for (const value of fixedPaths) { const normalizedValue = this.normalizeQimenFieldValue(value); if (normalizedValue) { return normalizedValue; } } return this.findQimenFieldValue(request, 'warehouseCode') || this.findQimenFieldValue(xmlArray, 'warehouseCode') || ''; } validateParams(params) { const required = [ 'method', 'v', 'format', 'timestamp' ]; for (const field of required) { if (!params[field]) { return false; } } // 验证method格式 if (typeof params.method !== 'string' || !params.method.includes('.')) { return false; } return true; } validateQimenParams(params) { const required = [ 'app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp' ]; for (const field of required) { if (!params[field]) { return false; } } // 验证method格式 if (typeof params.method !== 'string' || !params.method.includes('.')) { return false; } return true; } errorResponse(message, format = 'json') { const timestamp = Math.floor(Date.now() / 1000); if (format.toLowerCase() === 'xml') { return ` failure 0 ${this.escapeXml(message)} `; } return { flag: false, message, code: 0, timestamp, }; } escapeXml(unsafe) { if (!unsafe) return ''; return unsafe.replace(/[<>&'"]/g, c => { switch (c) { case '<': return '<'; case '>': return '>'; case '&': return '&'; case '\'': return '''; case '"': return '"'; default: return c; } }); } async pda() { const { ctx, service, } = this; ctx.query_count = 1; const startTime = Date.now(); const logData = { method: '', v: '', url: ctx.request.href, created_at: new Date(), body: '', headers: JSON.stringify(ctx.headers), result: '', use_time: 0, auth: '', store_id: null, }; try { const getParams = ctx.query; logData.method = getParams.method || ''; logData.v = getParams.v || ''; const requestCheck = service.system.validateRequestContext(getParams, ctx.headers); if (!requestCheck.ok) { const response = toFailure({ message: requestCheck.message, httpStatus: requestCheck.status, code: requestCheck.code, }); logData.result = response; service.system.saveLog(logData, startTime); ctx.body = response; ctx.status = requestCheck.status; ctx.type = 'application/json'; return; } const authHeader = ctx.headers.authorization; // 处理method参数 const method = getParams.method; const methods = method.split('.'); const actionName = methods.pop(); const className = methods.map((item, index) => (index === methods.length - 1 ? item : item) ).join('.'); // 获取JSON数据 let jsonData = ''; if (ctx.request.rawBody) { // 使用 rawBody 获取原始请求体 jsonData = ctx.request.rawBody; } else { // 如果没有 rawBody,尝试从流中读取 jsonData = await new Promise((resolve, reject) => { let data = ''; ctx.req.on('data', chunk => { data += chunk; }); ctx.req.on('end', () => { resolve(data); }); ctx.req.on('error', reject); }); } // 确保 jsonData 是字符串 jsonData = jsonData ? String(jsonData) : ''; logData.body = jsonData; if (!jsonData || jsonData.trim() === '') { throw new Error('json数据为空'); } try { jsonData = JSON.parse(jsonData); } catch (e) { throw new Error('json数据解析错误'); } // 调用业务方法 const { isLog, result } = await service.system.callMethod(className, actionName, jsonData, authHeader); // 记录成功响应 logData.result = typeof result === 'string' ? result : JSON.stringify(result); if (ctx.user) { logData.auth = JSON.stringify(ctx.user); logData.store_id = ctx.user.store_id; } if (isLog) { service.system.saveLog(logData, startTime); } if (result.status && result.status !== 200) { ctx.body = toFailure({ message: result.message || '请求失败', httpStatus: result.status, code: result.code, data: result.data || null, }); } else { ctx.body = toSuccess(result.data); } ctx.type = 'application/json'; ctx.status = result.status || 200; } catch (error) { ctx.status = 500; console.log(error); const response = toFailure({ message: '接口错误: ' + error.message, httpStatus: 500, code: 500, }); logData.result = typeof response === 'string' ? response : JSON.stringify(response); service.system.saveLog(logData, startTime); ctx.body = response; ctx.type = 'application/json'; } } async system() { const { ctx, service, } = this; ctx.query_count = 1; const startTime = Date.now(); const logData = { method: '', v: '', url: ctx.request.href, created_at: new Date(), body: '', headers: JSON.stringify(ctx.headers), result: '', use_time: 0, auth: '', store_id: null, }; try { const getParams = ctx.query; logData.method = getParams.method || ''; logData.v = getParams.v || ''; const requestCheck = service.system.validateRequestContext(getParams, ctx.headers); if (!requestCheck.ok) { const response = toFailure({ message: requestCheck.message, httpStatus: requestCheck.status, code: requestCheck.code, }); logData.result = response; service.system.saveLog(logData, startTime); ctx.body = response; ctx.status = requestCheck.status; ctx.type = 'application/json'; return; } const authHeader = ctx.headers.authorization; ctx.device = ctx.headers.device; ctx.project = ctx.headers.project; // 处理method参数 const method = getParams.method; const methods = method.split('.'); const actionName = methods.pop(); const className = methods.map((item, index) => (index === methods.length - 1 ? item : item) ).join('.'); // 获取JSON数据 let jsonData = ''; if (ctx.request.rawBody) { // 使用 rawBody 获取原始请求体 jsonData = ctx.request.rawBody; } else { // 如果没有 rawBody,尝试从流中读取 jsonData = await new Promise((resolve, reject) => { let data = ''; ctx.req.on('data', chunk => { data += chunk; }); ctx.req.on('end', () => { resolve(data); }); ctx.req.on('error', reject); }); } // 确保 jsonData 是字符串 jsonData = jsonData ? String(jsonData) : ''; logData.body = jsonData; if (!jsonData || jsonData.trim() === '') { throw new Error('json数据为空'); } try { jsonData = JSON.parse(jsonData); } catch (e) { throw new Error('json数据解析错误'); } // 调用业务方法 const { isLog, result } = await service.system.callMethod(className, actionName, jsonData, authHeader); // 记录成功响应 logData.result = typeof result === 'string' ? result : JSON.stringify(result); if (ctx.user) { logData.auth = JSON.stringify(ctx.user); logData.store_id = ctx.user.store_id; } if (isLog) { service.system.saveLog(logData, startTime); } if (result.status && result.status !== 200) { ctx.body = toFailure({ message: result.message || '请求失败', httpStatus: result.status, code: result.code, data: result.data || null, }); } else { ctx.body = toSuccess(result.data); } ctx.type = 'application/json'; ctx.status = result.status || 200; } catch (error) { ctx.status = 500; console.log(error); const response = toFailure({ message: '接口错误: ' + error.message, httpStatus: 500, code: 500, }); logData.result = typeof response === 'string' ? response : JSON.stringify(response); service.system.saveLog(logData, startTime); ctx.body = response; ctx.type = 'application/json'; } } } module.exports = HomeController;