WMS_MAIN/app/lib/qimen_client.js
liufumingren 948f600689 feat(inbox): 回调推送、出站文档、搜索增强、日志与推送状态完善
出站回调:
- 新增 warehouse_notify.json 文档(notify.ping/notify.reply),与 warehouse.json 互跳
- 回调体统一 { method, code, data },method 放 query,body 为业务数据
- MD5 签名: sign=MD5(appSecret+timestamp+bodyJson)
- 回调响应: {code:200} 成功,非200/非code:200 视为失败
- docs 页面支持模拟推送调试

搜索增强(searchStock/searchWarehouseStock):
- 直接查 stock_warehouse,不再依赖 stock_store
- 新增字段: gross_weight/box_spec/packing_requirements/prohibited_type
- 管理标识: is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt
- 条码关联: wms_stock_barcodes
- 图片: wms_file_reference(business_type=stock)+wms_file,返回数组
- id 修正为 stock_warehouse.id

推送状态完善:
- handleApiMessage 增加 push_status 更新(2成功/3失败)
- 未配回调地址 → push_status=3 + error 原因
- 回调异常 catch 也更新 push_status=3 + 写日志
- 出站日志写入 wms_warehouse_log 表(WN-前缀)

消息列表:
- keyword 兼容 content/keyword,支持数组
- keyword 搜索 content/group_name/user_name 三列
- 支持 where+operator 结构化查询(parseWhereConditions)
- storeId=-1 查询无货主消息; storeId=0→IS NULL
- 日期范围: startDate/endDate

其他:
- silent 动作: AI 识别无需回复时跳过回执
- ai_enabled 灰度开关(群级)
- bindCode 文档修正
- store_name 改用 StoreWarehouse.store_remask
2026-08-08 00:17:38 +08:00

270 lines
9.0 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.

'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
// 去掉 buildXmlNode 为数组元素添加的 <item> 包装器:<package><item> → <package>
.replace(/<\s*package\s*>\s*<\s*item\s*>/gi, '<package>')
// 去掉对应的 </item> 包装器闭合,输出标准格式 XML(不再做交错标签变换)
.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 });
}
/**
* 构建奇门请求查询参数。
* @param {string} method 接口方法名
* @param {string} appKey 应用 Key
* @param {string} version 接口版本
* @param {?string} customerId 货主标识
* @param {Function} formatDate 时间格式化函数
* @return {Object} 查询参数对象
*/
getQueryParams(method, appKey, version, customerId, formatDate) {
const queryParams = {
method,
format: 'xml',
app_key: appKey,
v: version,
sign_method: 'md5',
timestamp: formatDate(new Date()),
};
if (customerId != null) {
queryParams.customerId = customerId;
}
return queryParams;
}
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}`;
}
/**
* 发送奇门请求并记录请求日志。
* @param {string} method 接口方法名
* @param {?string} customerId 货主标识
* @param {Object} data 业务请求数据
* @param {Object} runtime 运行时依赖
* @return {Promise<{queryId: *, xmlArray: *}>} 查询结果
*/
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' || method === 'taobao.qimen.stockout.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,
v: '2.0',
url,
created_at: new Date(),
body: '',
result: '',
use_time: 0,
};
if (customerId != null) {
logData.costomer_id = customerId;
}
console.log('发送奇门请求,URL:', url, '请求数据:', queryData);
const result = await this.sendRequest(url, queryData, logData, helpers);
console.log('奇门请求响应:', result);
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 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;