246 lines
7.9 KiB
JavaScript
246 lines
7.9 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 站内信消息推送调试脚本(模拟 IM 桥向仓库推送入站消息,走真实验签链路)。
|
||
*
|
||
* 用法:
|
||
* node script/debug-inbox-push.cjs
|
||
* 默认: 向 test-stock-group 推送「查退回 <随机不存在运单号>」
|
||
* node script/debug-inbox-push.cjs --content "查退回 888888888888888"
|
||
* node script/debug-inbox-push.cjs --waybill 888888888888888 --groupId test-stock-group --userName 测试用户
|
||
*
|
||
* 行为:
|
||
* 1. 按 app/lib/api_sign.js 规则签名,POST /warehouse?method=inbox.push
|
||
* 2. 等待 AI 异步处理(默认 15s)
|
||
* 3. 回查本地库: 入站消息 / AI 思考过程 / 回信内容 / wms_return_query_log 登记
|
||
*/
|
||
|
||
const crypto = require('crypto');
|
||
const http = require('http');
|
||
const mysql = require('mysql2/promise');
|
||
|
||
// ========================== 稳定序列化(与 app/lib/api_sign.js 一致) ==========================
|
||
|
||
function isPlainObject(value) {
|
||
return Object.prototype.toString.call(value) === '[object Object]';
|
||
}
|
||
|
||
function stableStringify(value) {
|
||
if (value === undefined) return '';
|
||
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
||
if (Array.isArray(value)) {
|
||
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
||
}
|
||
if (!isPlainObject(value)) return JSON.stringify(value);
|
||
const keys = Object.keys(value).sort();
|
||
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
|
||
}
|
||
|
||
function md5(str) {
|
||
return crypto.createHash('md5').update(str, 'utf8').digest('hex')
|
||
.toLowerCase();
|
||
}
|
||
|
||
function buildSign(query, body, secret) {
|
||
const ignoreSet = new Set([ 'sign', 'signature' ]);
|
||
const keys = Object.keys(query)
|
||
.filter(key => !ignoreSet.has(String(key).toLowerCase()))
|
||
.filter(key => query[key] !== undefined)
|
||
.sort();
|
||
const canonicalQuery = keys.map(key => {
|
||
const v = query[key];
|
||
if (v === undefined || v === null) return `${key}=`;
|
||
if (typeof v === 'object') return `${key}=${stableStringify(v)}`;
|
||
return `${key}=${String(v)}`;
|
||
}).join('&');
|
||
const bodySign = md5(stableStringify(body));
|
||
const signText = `${canonicalQuery}${secret}${bodySign}`;
|
||
return { canonicalQuery, bodySign, sign: md5(signText) };
|
||
}
|
||
|
||
// ========================== 参数解析 ==========================
|
||
|
||
const ARGS = {};
|
||
for (let i = 2; i < process.argv.length; i++) {
|
||
const arg = process.argv[i];
|
||
const match = arg.match(/^--([^=]+)=(.*)$/);
|
||
if (match) {
|
||
ARGS[match[1]] = match[2];
|
||
} else if (arg.startsWith('--')) {
|
||
ARGS[arg.slice(2)] = process.argv[i + 1];
|
||
i++;
|
||
}
|
||
}
|
||
|
||
const CONFIG = {
|
||
baseUrl: ARGS.baseUrl || 'http://127.0.0.1:6060',
|
||
appKey: ARGS.appKey || 'APP2025011514315678',
|
||
appSecret: ARGS.appSecret || 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890',
|
||
groupId: ARGS.groupId || 'test-stock-group',
|
||
groupName: ARGS.groupName || '库存查询测试群',
|
||
userId: ARGS.userId || 'debug_user',
|
||
userName: ARGS.userName || '测试用户',
|
||
waitMs: Number(ARGS.waitMs || 15000),
|
||
waybill: ARGS.waybill || `${Date.now()}99`,
|
||
};
|
||
|
||
if (ARGS.content) {
|
||
CONFIG.content = ARGS.content;
|
||
} else {
|
||
CONFIG.content = `查退回 ${CONFIG.waybill}`;
|
||
}
|
||
|
||
// ========================== HTTP 推送 ==========================
|
||
|
||
function postWarehouse(method, body) {
|
||
const query = {
|
||
method,
|
||
v: '1.0',
|
||
timestamp: Math.floor(Date.now() / 1000),
|
||
app_key: CONFIG.appKey,
|
||
};
|
||
const { sign } = buildSign(query, body, CONFIG.appSecret);
|
||
query.sign = sign;
|
||
|
||
const qs = Object.entries(query)
|
||
.map(([ k, v ]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
|
||
.join('&');
|
||
const bodyStr = JSON.stringify(body);
|
||
const url = `${CONFIG.baseUrl}/warehouse?${qs}`;
|
||
|
||
return new Promise((resolve, reject) => {
|
||
const req = http.request(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
'Content-Length': Buffer.byteLength(bodyStr),
|
||
},
|
||
timeout: 20000,
|
||
}, res => {
|
||
let data = '';
|
||
res.on('data', chunk => (data += chunk));
|
||
res.on('end', () => {
|
||
try { resolve({ status: res.statusCode, body: JSON.parse(data) }); } catch (e) { resolve({ status: res.statusCode, body: data }); }
|
||
});
|
||
});
|
||
req.on('error', reject);
|
||
req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); });
|
||
req.write(bodyStr);
|
||
req.end();
|
||
});
|
||
}
|
||
|
||
function sleep(ms) {
|
||
return new Promise(resolve => setTimeout(resolve, ms));
|
||
}
|
||
|
||
// ========================== 本地库回查 ==========================
|
||
|
||
async function queryDb(sql) {
|
||
const conn = await mysql.createConnection({
|
||
host: '127.0.0.1',
|
||
port: 3307,
|
||
user: 'wms',
|
||
password: 'dspxmRwRdRbWtbm7',
|
||
database: 'wms',
|
||
});
|
||
try {
|
||
const [ rows ] = await conn.query(sql);
|
||
return rows;
|
||
} finally {
|
||
await conn.end();
|
||
}
|
||
}
|
||
|
||
// ========================== 主流程 ==========================
|
||
|
||
(async () => {
|
||
const requestId = `debug-return-${Date.now()}`;
|
||
console.log('========== 站内信模拟推送 ==========');
|
||
console.log(` 群: ${CONFIG.groupId} (${CONFIG.groupName})`);
|
||
console.log(` 用户: ${CONFIG.userName}`);
|
||
console.log(` 内容: ${CONFIG.content}`);
|
||
console.log(` requestId: ${requestId}`);
|
||
|
||
const r = await postWarehouse('inbox.push', {
|
||
requestId,
|
||
content: CONFIG.content,
|
||
groupId: CONFIG.groupId,
|
||
groupName: CONFIG.groupName,
|
||
userId: CONFIG.userId,
|
||
userName: CONFIG.userName,
|
||
targetType: 'im',
|
||
});
|
||
|
||
console.log(` HTTP ${r.status}: ${JSON.stringify(r.body).slice(0, 300)}`);
|
||
if (r.status !== 200 || (r.body && r.body.ok === false)) {
|
||
console.error('推送失败,请检查签名与仓库应用配置');
|
||
process.exit(1);
|
||
}
|
||
|
||
console.log(`\n等待 AI 异步处理 ${CONFIG.waitMs / 1000}s ...`);
|
||
await sleep(CONFIG.waitMs);
|
||
|
||
const extId = `api:${CONFIG.appKey}:${requestId}`;
|
||
|
||
// 1. 入站消息 + AI 思考
|
||
const inbound = await queryDb(
|
||
`SELECT id, direction, content, ai_thoughts, push_status, created_at
|
||
FROM wms_inbox_message WHERE ext_id='${extId}' ORDER BY id DESC LIMIT 1`
|
||
);
|
||
console.log('\n[入站消息]');
|
||
if (inbound.length === 0) {
|
||
console.log(' 未找到(消息可能尚未入库)');
|
||
} else {
|
||
console.log(` id=${inbound[0].id} push_status=${inbound[0].push_status}`);
|
||
console.log(` content: ${inbound[0].content}`);
|
||
const thoughts = inbound[0].ai_thoughts;
|
||
if (thoughts && typeof thoughts === 'string') {
|
||
try {
|
||
const parsed = JSON.parse(thoughts);
|
||
console.log(` ai_thoughts: ${JSON.stringify(parsed).slice(0, 400)}`);
|
||
} catch (e) {
|
||
console.log(` ai_thoughts(raw): ${String(thoughts).slice(0, 400)}`);
|
||
}
|
||
} else {
|
||
console.log(' ai_thoughts: 无');
|
||
}
|
||
}
|
||
|
||
// 2. 回信内容
|
||
const outbound = await queryDb(
|
||
`SELECT id, direction, content, created_at
|
||
FROM wms_inbox_message
|
||
WHERE direction='outbound' AND group_id='${CONFIG.groupId}'
|
||
ORDER BY id DESC LIMIT 1`
|
||
);
|
||
console.log('\n[最新回信]');
|
||
if (outbound.length === 0) {
|
||
console.log(' 无回信');
|
||
} else {
|
||
console.log(` id=${outbound[0].id} created_at=${outbound[0].created_at}`);
|
||
console.log(` content:\n${outbound[0].content}`);
|
||
}
|
||
|
||
// 3. 退回查询登记
|
||
const waybill = CONFIG.waybill;
|
||
const queryLog = await queryDb(
|
||
`SELECT id, warehouse_id, store_id, waybill_code, remark, is_notified, is_back, created_at
|
||
FROM wms_return_query_log WHERE waybill_code='${waybill}' ORDER BY id DESC LIMIT 3`
|
||
);
|
||
console.log('\n[wms_return_query_log 登记]');
|
||
if (queryLog.length === 0) {
|
||
console.log(' 无登记');
|
||
} else {
|
||
queryLog.forEach(row => {
|
||
console.log(` id=${row.id} store_id=${row.store_id} is_back=${row.is_back} is_notified=${row.is_notified} remark=${row.remark} ${row.created_at}`);
|
||
});
|
||
}
|
||
|
||
console.log('\n完成。测试记录按需保留,无需删除。');
|
||
process.exit(0);
|
||
})().catch(e => {
|
||
console.error('异常:', e.message);
|
||
process.exit(1);
|
||
});
|