WMS_MAIN/app/lib/qimen_client.js
liufumingren 5ce689d771 1
Co-authored-by: Copilot <copilot@github.com>
2026-04-30 19:20:31 +08:00

243 lines
7.9 KiB
JavaScript

'use strict';
const https = require('https');
const http = require('http');
class QimenClient {
constructor(app) {
this.app = app;
}
resolveRuntime(runtime = {}) {
const ctx = runtime.ctx || {};
const qimenService = ctx.service && ctx.service.qimen ? ctx.service.qimen : null;
const signService = ctx.service && ctx.service.systems && ctx.service.systems.sign ? ctx.service.systems.sign : null;
return {
ctx,
qimenLogId: runtime.qimenLogId ?? ctx.qimenLogId ?? null,
toXml: runtime.toXml || (signService && typeof signService.toXml === 'function'
? signService.toXml.bind(signService)
: qimenService && typeof qimenService.formatResponse === 'function'
? qimenService.formatResponse.bind(qimenService)
: null),
parseXmlToArray: runtime.parseXmlToArray || (qimenService && typeof qimenService.parseXmlToArray === 'function'
? qimenService.parseXmlToArray.bind(qimenService)
: null),
saveQimenLog: runtime.saveQimenLog || (qimenService && typeof qimenService.saveQimenLog === 'function'
? qimenService.saveQimenLog.bind(qimenService)
: async () => null),
signTopRequest: runtime.signTopRequest || (signService && typeof signService.signTopRequest === 'function'
? signService.signTopRequest.bind(signService)
: null),
formatDate: runtime.formatDate || ctx.app?.formatDate || this.app.formatDate || (date => (date && typeof date.toISOString === 'function' ? date.toISOString() : String(date))),
};
}
normalizeRequestPayload(data) {
if (!data || typeof data !== 'object' || Array.isArray(data)) {
return { request: data };
}
if (Object.prototype.hasOwnProperty.call(data, 'request')) {
return data;
}
return { request: data };
}
replaceXmlTagsWithString(xmlString, oldTag, newTag) {
const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi');
const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi');
const selfClosingRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?\\s*/>`, 'gi');
return xmlString
.replace(startTagRegex, (match, attributes = '') => `<${newTag}${attributes}>`)
.replace(endTagRegex, `</${newTag}>`)
.replace(selfClosingRegex, (match, attributes = '') => `<${newTag}${attributes}/>`);
}
replaceDeliveryConfirmOrderLineTags(xmlString) {
const orderLinesBlockRegex = /<\s*orderLines(\s+[^>]*)?>[\s\S]*?<\s*\/\s*orderLines\s*>/gi;
return String(xmlString || '').replace(orderLinesBlockRegex, block => {
return this.replaceXmlTagsWithString(block, 'item', 'orderLine');
});
}
replaceDeliveryConfirmPackageTags(xmlString) {
const packagesBlockRegex = /<\s*packages(\s+[^>]*)?>[\s\S]*?<\s*\/\s*packages\s*>/gi;
return String(xmlString || '').replace(packagesBlockRegex, block => {
return block
.replace(/<\s*package\s*>\s*<\s*item\s*>/gi, '<package>')
.replace(/<\s*\/\s*item\s*>\s*<\s*item\s*>/gi, '</package><package>')
.replace(/<\s*\/\s*item\s*>\s*<\s*\/\s*package\s*>/gi, '</package>');
});
}
replaceDeliveryConfirmPayloadTags(xmlString) {
const withPackages = this.replaceDeliveryConfirmPackageTags(xmlString);
return this.replaceDeliveryConfirmOrderLineTags(withPackages);
}
addSign(baseQueryParams, sign) {
return Object.assign({}, baseQueryParams, { sign });
}
getQueryParams(method, appKey, version, customerId, formatDate) {
return {
method,
format: 'xml',
app_key: appKey,
v: version,
sign_method: 'md5',
customerId,
timestamp: formatDate(new Date()),
};
}
generateUrlWithParams(baseUrl, params) {
if (!params || Object.keys(params).length === 0) {
return baseUrl;
}
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
const separator = baseUrl.includes('?') ? '&' : '?';
return `${baseUrl}${separator}${queryString}`;
}
async send(method, customerId, data, runtime = {}) {
const helpers = this.resolveRuntime(runtime);
if (!helpers.toXml) {
throw new Error('缺少奇门 XML 转换器');
}
if (!helpers.parseXmlToArray) {
throw new Error('缺少奇门响应解析器');
}
if (!helpers.signTopRequest) {
throw new Error('缺少奇门签名器');
}
const wmsAppKey = this.app.config.qimen.appKey;
const baseQueryParams = this.getQueryParams(method, wmsAppKey, '2.0', customerId, helpers.formatDate);
const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service';
const requestPayload = this.normalizeRequestPayload(data);
const xmlData = await helpers.toXml(requestPayload);
const queryData = method === 'taobao.qimen.deliveryorder.confirm'
? this.replaceDeliveryConfirmPayloadTags(xmlData)
: this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine');
const sign = await helpers.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5');
const queryParams = this.addSign(baseQueryParams, sign);
const url = this.generateUrlWithParams(baseUrl, queryParams);
const logData = {
from_key: this.app.config.qimen.appKey,
to_key: wmsAppKey,
method,
sign,
costomer_id: customerId,
v: '2.0',
url,
created_at: new Date(),
body: '',
result: '',
use_time: 0,
};
const result = await this.sendRequest(url, queryData, logData, helpers);
const xmlArray = await helpers.parseXmlToArray(result.res);
return { queryId: result.queryId, xmlArray };
}
async sendRequest(url, requestData, logData = {}, runtime = {}) {
const helpers = this.resolveRuntime(runtime);
const startTime = Date.now();
const { ctx } = helpers;
const requestLogData = Object.assign({
body: requestData,
result: '',
log_id: helpers.qimenLogId,
}, logData);
requestLogData.body = requestLogData.body || requestData;
requestLogData.result = requestLogData.result || '';
requestLogData.log_id = requestLogData.log_id || helpers.qimenLogId || null;
const httpquery = url.indexOf('https://') > -1 ? https : http;
let requestXml;
try {
if (typeof requestData === 'string') {
requestXml = requestData;
if (requestXml.trim() === '') {
throw new Error('请求数据为空字符串');
}
} else {
requestXml = await helpers.toXml(requestData);
}
if (!requestXml || requestXml.trim() === '') {
throw new Error('XML内容为空');
}
} catch (error) {
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
await helpers.saveQimenLog(requestLogData, startTime);
throw error;
}
const header = {
'Content-Type': 'application/xml',
'Content-Length': Buffer.byteLength(requestXml, 'utf8'),
'User-Agent': 'EggJS Client',
};
const options = {
method: 'POST',
headers: header,
};
let res;
try {
res = await new Promise((resolve, reject) => {
let req;
try {
req = httpquery.request(url, options, response => {
let datas = '';
response.on('data', chunk => {
datas += chunk;
});
response.on('end', () => {
resolve(datas);
});
});
} catch (error) {
reject(error);
return;
}
req.on('error', error => {
reject(error);
});
req.write(requestXml);
req.end();
});
} catch (error) {
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
await helpers.saveQimenLog(requestLogData, startTime);
throw error;
}
requestLogData.result = res;
const queryId = await helpers.saveQimenLog(requestLogData, startTime);
return { queryId, res };
}
}
module.exports = QimenClient;