588 lines
18 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.

const {
Controller,
} = require('egg');
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';
}
async v1() {
const {
ctx,
service,
} = this;
const startTime = Date.now();
// 初始化日志数据
const logData = {
app_key: '',
method: '',
sign: '',
costomer_id: '',
v: '',
url: ctx.request.href,
created_at: new Date(),
body: '',
result: '',
use_time: 0,
};
try {
const getParams = ctx.query;
logData.method = getParams.method || '';
logData.v = getParams.v || '';
// 验证必要参数
if (!this.validateParams(getParams)) {
const errorMsg = '参数缺失或错误';
const response = this.errorResponse(errorMsg, 'json');
logData.result = response;
await this.saveLog(logData, startTime);
ctx.body = response;
ctx.type = 'application/json';
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('.');
// 获取XML数据
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);
});
}
// 确保 xmlData 是字符串
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 result = await service.api.callMethod(className, actionName, jsonData, getParams.format);
// 记录成功响应
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
await this.saveLog(logData, startTime);
ctx.body = result;
ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json';
} catch (error) {
ctx.logger.error('调用接口失败返回数据', error);
const response = this.errorResponse('接口错误: ' + error.message, ctx.query.format || 'json');
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
await this.saveLog(logData, startTime);
ctx.body = response;
ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json';
}
}
async qimen() {
const {
ctx,
service,
} = this;
const startTime = Date.now();
// 初始化日志数据
const logData = {
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 || '';
ctx.qimenLogId = await service.qimen.saveQimenLog(logData, startTime);
try {
// 验证必要参数
if (!this.validateQimenParams(getParams)) {
const errorMsg = '参数缺失或错误';
const response = this.errorResponse(errorMsg, 'xml');
await service.qimen.saveQimenLogResult(response);
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;
let warehouseCode = xmlArray.request.warehouseCode || '';
const ownerCode = customerId;
await service.qimen.saveQimenLogBody(xmlData);
const erpName = await service.qimen.getErpName(appkey);
let api_info = {
warehouseCode: '',
ownerCode: '',
};
if (!warehouseCode || !customerId) {
// 入库单提取
try {
warehouseCode = xmlArray.request?.entryOrder?.warehouseCode ||
xmlArray.request?.deliveryOrder?.warehouseCode ||
'';
} catch (e) {}
}
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');
await service.qimen.saveQimenLogResult(response);
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');
await service.qimen.saveQimenLogResult(response);
ctx.body = response;
ctx.type = 'application/xml';
return;
}
if (api_info.warehouse_status == 0) {
const errorMsg = '仓库状态异常,请联系仓库核实WMS状态';
const response = this.errorResponse(errorMsg, 'xml');
await service.qimen.saveQimenLogResult(response);
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');
await service.qimen.saveQimenLogResult(response);
ctx.body = response;
ctx.type = 'application/xml';
return;
}
if (authEndTime < currentTime) {
const errorMsg = '仓库订阅过期,请联系仓库核实状态';
const response = this.errorResponse(errorMsg, 'xml');
await service.qimen.saveQimenLogResult(response);
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);
// 记录成功响应
const logData_result = typeof result === 'string' ? result : JSON.stringify(result);
await service.qimen.saveQimenLogResult(logData_result);
ctx.body = result;
ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json';
} catch (error) {
const response = this.errorResponse('奇门接口错误: ' + error.message, ctx.query.format || 'xml');
await service.qimen.saveQimenLogResult(response);
ctx.body = response;
ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json';
}
}
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 `<?xml version="1.0" encoding="UTF-8"?>
<response>
<flag>failure</flag>
<code>0</code>
<message>${this.escapeXml(message)}</message>
</response>`;
}
return {
flag: false,
message,
code: 0,
timestamp,
};
}
escapeXml(unsafe) {
if (!unsafe) return '';
return unsafe.replace(/[<>&'"]/g, c => {
switch (c) {
case '<':
return '&lt;';
case '>':
return '&gt;';
case '&':
return '&amp;';
case '\'':
return '&apos;';
case '"':
return '&quot;';
default:
return c;
}
});
}
async saveLog(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_api_log', {
method: logData.method || '',
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;
} catch (error) {
ctx.logger.error('保存奇门接口日志失败: ' + error.message);
// 可以选择记录到文件日志作为备用
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
}
}
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 || '';
// 验证必要参数
if (!service.system.validateParams(getParams)) {
const errorMsg = '参数缺失或错误';
const response = this.errorResponse(errorMsg, 'json');
logData.result = response;
service.system.saveLog(logData, startTime);
ctx.body = response;
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);
}
ctx.body = result.data;
ctx.type = 'application/json';
ctx.status = result.status || 200;
} catch (error) {
ctx.status = 500;
console.log(error);
const response = this.errorResponse('接口错误: ' + error.message, 'json');
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
service.system.saveLog(logData, startTime);
ctx.body = response;
ctx.type = 'application/json';
}
}
async store() {
}
async warehouse() {
}
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 || '';
// 验证必要参数
if (!service.system.validateParams(getParams)) {
const errorMsg = '参数缺失或错误';
const response = this.errorResponse(errorMsg, 'json');
logData.result = response;
service.system.saveLog(logData, startTime);
ctx.body = response;
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);
}
ctx.body = result.data;
ctx.type = 'application/json';
ctx.status = result.status || 200;
} catch (error) {
ctx.status = 500;
console.log(error);
const response = this.errorResponse('接口错误: ' + error.message, 'json');
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
service.system.saveLog(logData, startTime);
ctx.body = response;
ctx.type = 'application/json';
}
}
}
module.exports = HomeController;