chore(script): 调试脚本移入 temp/ 不再纳入版本控制

This commit is contained in:
liufumingren 2026-08-27 23:38:46 +08:00
parent 80c73bb34b
commit f2fe5311aa
6 changed files with 1 additions and 953 deletions

1
.gitignore vendored
View File

@ -38,3 +38,4 @@ versioning/*
!versioning/.gitkeep
app/public/exports/
script/debug-*.cjs

View File

@ -1,116 +0,0 @@
'use strict';
/**
* 调试脚本:为指定账号铸造 JWT 并调用系统接口完成收货。
* 用法:
* node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1
* node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1 --host=127.0.0.1 --port=6060
*/
const http = require('node:http');
const jwt = require('jsonwebtoken');
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
const JWT_EXPIRES_IN = 14400;
function parseArgs(argv) {
const options = {
receivingId: 0,
accountId: 1,
host: '127.0.0.1',
port: 6060,
remark: '',
};
for (const arg of argv) {
if (!arg.startsWith('--')) {
continue;
}
const [ rawKey, ...rest ] = arg.slice(2).split('=');
const value = rest.join('=');
switch (rawKey) {
case 'receiving-id':
options.receivingId = Number(value || options.receivingId);
break;
case 'account-id':
options.accountId = Number(value || options.accountId);
break;
case 'host':
options.host = value || options.host;
break;
case 'port':
options.port = Number(value || options.port);
break;
case 'remark':
options.remark = value || '';
break;
default:
break;
}
}
return options;
}
function postSystemMethod(options, token, method, body) {
return new Promise((resolve, reject) => {
const bodyJson = JSON.stringify(body);
const path = `/system?method=${encodeURIComponent(method)}&v=1&timestamp=${Math.floor(Date.now() / 1000)}`;
const req = http.request({
hostname: options.host,
port: options.port,
path,
method: 'POST',
headers: {
platform: 'web',
project: 'wms',
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(bodyJson),
},
}, res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
resolve({ status: res.statusCode, body: data });
});
});
req.on('error', reject);
req.write(bodyJson);
req.end();
});
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (!options.receivingId) {
console.error('缺少 --receiving-id');
process.exit(1);
}
const token = jwt.sign({
id: options.accountId,
platform_code: 'web',
current_store_id: 100000,
}, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
console.log(`[debug-complete-receiving] accountId=${options.accountId} receivingId=${options.receivingId}`);
const result = await postSystemMethod(options, token, 'storage.receiving.completeReceiving', {
id: options.receivingId,
remark: options.remark || undefined,
});
console.log(`HTTP ${result.status}`);
try {
console.log(JSON.stringify(JSON.parse(result.body), null, 2).substring(0, 3000));
} catch (_) {
console.log(result.body.substring(0, 1000));
}
}
main().catch(error => {
console.error('[debug-complete-receiving] failed:', error.message);
process.exit(1);
});

View File

@ -1,245 +0,0 @@
'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);
});

View File

@ -1,252 +0,0 @@
'use strict';
const path = require('node:path');
const urllib = require('urllib');
const DEFAULT_FILE_URL = 'https://ye4s.file.gzxunren.com/exports/receiving/completed/100000/20260405/%E6%94%B6%E8%B4%A7%E5%AE%8C%E6%88%90_R20547058.xlsx';
const DEFAULT_FILE_NAME = '收货完成_R20547058.xlsx';
function parseArgs(argv) {
const options = {
url: process.env.WEBHOOK_DEBUG_URL || '',
textUrl: process.env.WEBHOOK_DEBUG_TEXT_URL || '',
fileUrl: process.env.WEBHOOK_DEBUG_FILE_URL || '',
mode: process.env.WEBHOOK_DEBUG_MODE || 'both',
warehouseId: Number(process.env.WEBHOOK_DEBUG_WAREHOUSE_ID || 100000),
storeId: Number(process.env.WEBHOOK_DEBUG_STORE_ID || 1000016),
receivingId: Number(process.env.WEBHOOK_DEBUG_RECEIVING_ID || 202604050001),
receivingNumber: process.env.WEBHOOK_DEBUG_RECEIVING_NUMBER || 'SIM202604050001',
fileResourceUrl: process.env.WEBHOOK_DEBUG_REPORT_URL || DEFAULT_FILE_URL,
fileName: process.env.WEBHOOK_DEBUG_REPORT_FILE || DEFAULT_FILE_NAME,
timeout: Number(process.env.WEBHOOK_DEBUG_TIMEOUT || 10000),
};
for (const arg of argv) {
if (!arg.startsWith('--')) {
continue;
}
const [rawKey, ...rest] = arg.slice(2).split('=');
const value = rest.join('=');
switch (rawKey) {
case 'url':
options.url = value || options.url;
break;
case 'text-url':
options.textUrl = value || options.textUrl;
break;
case 'file-url':
options.fileUrl = value || options.fileUrl;
break;
case 'mode':
options.mode = value || options.mode;
break;
case 'warehouse-id':
options.warehouseId = Number(value || options.warehouseId);
break;
case 'store-id':
options.storeId = Number(value || options.storeId);
break;
case 'receiving-id':
options.receivingId = Number(value || options.receivingId);
break;
case 'receiving-number':
options.receivingNumber = value || options.receivingNumber;
break;
case 'report-url':
options.fileResourceUrl = value || options.fileResourceUrl;
break;
case 'report-file':
options.fileName = value || options.fileName;
break;
case 'timeout':
options.timeout = Number(value || options.timeout);
break;
case 'help':
options.help = true;
break;
default:
break;
}
}
if (!options.textUrl) {
options.textUrl = options.url;
}
if (!options.fileUrl) {
options.fileUrl = options.url;
}
return options;
}
function printHelp() {
console.log(`用法:\n npm run debug:webhook:receiving -- --url=http://127.0.0.1:7071/notic\n npm run debug:webhook:receiving -- --text-url=http://127.0.0.1:7071/notic --file-url=http://127.0.0.1:7071/notic2\n\n说明:\n - 默认发送两次请求:text + file\n - 默认模拟 warehouseId=100000, storeId=1000016 的收货完成通知\n - 可通过 --mode=text 或 --mode=file 只发送一种\n`);
}
function buildBasePayload(options) {
return {
traceId: `debug_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`,
event: 'receiving_completed',
businessName: 'receiving',
warehouseId: Number(options.warehouseId),
storeId: Number(options.storeId),
businessId: Number(options.receivingId),
occurredAt: new Date().toISOString(),
subject: {
id: Number(options.warehouseId),
type: 'warehouse',
name: `测试仓${options.warehouseId}`,
code: '',
config: {
max_notice_webhook_count: 5,
},
},
store: {
id: Number(options.storeId),
name: `测试货主${options.storeId}`,
businessLicense: `BL-${options.storeId}`,
storeRemask: `货主${options.storeId}备注`,
},
sender: {
id: 90001,
name: '调试脚本',
},
receivers: [],
metadata: {
debug: true,
sourceScript: path.basename(__filename),
receivingId: Number(options.receivingId),
receivingNumber: options.receivingNumber,
warehouseId: Number(options.warehouseId),
storeId: Number(options.storeId),
stats: {
total_details: 10,
matched_details: 10,
unmatched_details: 0,
total_quantity: 120,
},
completionReport: null,
},
};
}
function buildTextPayload(options) {
const payload = buildBasePayload(options);
const title = `收货单${options.receivingNumber}已完成`;
const content = `收货单${options.receivingNumber}已完成,匹配商品10件,未匹配商品0件,总数量120,完成人调试脚本。`;
payload.message = {
type: 'text',
title,
content,
url: '',
fileName: '',
mimeType: '',
body: content,
};
return payload;
}
function buildFilePayload(options) {
const payload = buildBasePayload(options);
const title = `收货单${options.receivingNumber}已完成`;
const content = `收货单${options.receivingNumber}已完成,匹配商品10件,未匹配商品0件,总数量120,完成人调试脚本。`;
payload.message = {
type: 'file',
title,
content,
url: options.fileResourceUrl,
fileName: options.fileName,
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
body: content,
};
payload.metadata.completionReport = {
fileKey: options.fileName,
url: options.fileResourceUrl,
};
return payload;
}
async function postJson(url, data, timeout) {
const response = await urllib.request(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
data: JSON.stringify(data),
timeout: Number(timeout) || 10000,
dataType: 'text',
});
return {
status: response.status,
body: String(response.data || ''),
};
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
printHelp();
return;
}
if (!options.textUrl && !options.fileUrl) {
throw new Error('请通过 --url 或 --text-url/--file-url 指定接收端地址');
}
const tasks = [];
if ([ 'both', 'text' ].includes(options.mode) && options.textUrl) {
tasks.push({
label: 'text',
url: options.textUrl,
payload: buildTextPayload(options),
});
}
if ([ 'both', 'file' ].includes(options.mode) && options.fileUrl) {
tasks.push({
label: 'file',
url: options.fileUrl,
payload: buildFilePayload(options),
});
}
if (tasks.length === 0) {
throw new Error(`mode=${options.mode} 下没有可发送的 webhook 请求`);
}
const results = [];
for (const task of tasks) {
console.log(`\n[send] ${task.label.toUpperCase()} -> ${task.url}`);
const response = await postJson(task.url, task.payload, options.timeout);
console.log(`[response] status=${response.status} body=${response.body}`);
results.push({
label: task.label,
url: task.url,
status: response.status,
body: response.body,
traceId: task.payload.traceId,
event: task.payload.event,
});
}
const failedCount = results.filter(item => Number(item.status) < 200 || Number(item.status) >= 300).length;
console.log('\n[summary]');
console.log(JSON.stringify({
options: {
...options,
timeout: Number(options.timeout),
},
results,
failedCount,
}, null, 2));
if (failedCount > 0) {
process.exitCode = 1;
}
}
main().catch(error => {
console.error('[debug-send-receiving-webhooks] failed:', error.message);
process.exit(1);
});

View File

@ -1,206 +0,0 @@
'use strict';
/**
* 仓库接口消息推送 — 本地调试接收服务。
* 模拟外部适配器:接收 WMS 出站推送(notify.reply / notify.event 等),
* 打印完整回信(query 签名参数 + headers + body)到控制台与日志文件,方便调试。
*
* 默认配置匹配线上仓库「仓库管理系统oms」:
* app_key=APP2025011514315678
* app_secret=sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890
* callback_url=http://localhost:6061/push
*
* 用法:
* npm run debug:warehouse:push-receiver
* node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log
* node script/debug-warehouse-push-receiver.cjs --no-verify # 跳过 MD5 验签
*/
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { URL } = require('node:url');
const DEFAULT_HOST = '127.0.0.1';
const DEFAULT_PORT = 6061;
const DEFAULT_PATH = '/push';
const DEFAULT_APP_KEY = 'APP2025011514315678';
const DEFAULT_APP_SECRET = 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890';
const DEFAULT_LOG_FILE = path.join(process.cwd(), 'run', 'warehouse-push-receiver.log');
function parseArgs(argv) {
const options = {
host: process.env.PUSH_RECEIVER_HOST || DEFAULT_HOST,
port: Number(process.env.PUSH_RECEIVER_PORT || DEFAULT_PORT),
path: process.env.PUSH_RECEIVER_PATH || DEFAULT_PATH,
appKey: process.env.PUSH_RECEIVER_APP_KEY || DEFAULT_APP_KEY,
appSecret: process.env.PUSH_RECEIVER_APP_SECRET || DEFAULT_APP_SECRET,
logFile: process.env.PUSH_RECEIVER_LOG_FILE || DEFAULT_LOG_FILE,
verifySign: ![ '0', 'false' ].includes(String(process.env.PUSH_RECEIVER_VERIFY_SIGN || '1').toLowerCase()),
help: false,
};
for (const arg of argv) {
if (!arg.startsWith('--')) {
continue;
}
const [ rawKey, ...rest ] = arg.slice(2).split('=');
const value = rest.join('=');
switch (rawKey) {
case 'host':
options.host = value || options.host;
break;
case 'port':
options.port = Number(value || options.port);
break;
case 'path':
options.path = value.startsWith('/') ? value : `/${value}`;
break;
case 'app-key':
options.appKey = value || options.appKey;
break;
case 'app-secret':
options.appSecret = value || options.appSecret;
break;
case 'log-file':
options.logFile = value || options.logFile;
break;
case 'no-verify':
options.verifySign = false;
break;
case 'help':
options.help = true;
break;
default:
break;
}
}
return options;
}
function printHelp() {
console.log(`用法:
npm run debug:warehouse:push-receiver
node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log
node script/debug-warehouse-push-receiver.cjs --no-verify
参数:
--host=127.0.0.1 监听地址
--port=6061 监听端口
--path=/push 接收路径
--app-key=... 期望的 app_key(仅用于展示)
--app-secret=... 验签密钥(MD5(appSecret + timestamp + bodyJson))
--log-file=... 日志文件(默认 run/warehouse-push-receiver.log)
--no-verify 跳过 MD5 验签
环境变量:
PUSH_RECEIVER_HOST / PUSH_RECEIVER_PORT / PUSH_RECEIVER_PATH
PUSH_RECEIVER_APP_KEY / PUSH_RECEIVER_APP_SECRET / PUSH_RECEIVER_LOG_FILE
PUSH_RECEIVER_VERIFY_SIGN=0 关闭验签`);
}
function readRequestBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function writeLog(logFile, text) {
const line = text.endsWith('\n') ? text : text + '\n';
try {
fs.appendFileSync(logFile, line, 'utf8');
console.log(`[push-receiver] 已写入日志文件: ${logFile}`);
} catch (error) {
console.error('[push-receiver] 写日志文件失败:', error.message);
}
}
function md5(value) {
return crypto.createHash('md5').update(value).digest('hex');
}
async function start() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
printHelp();
return;
}
const logFile = path.resolve(options.logFile);
const logDir = path.dirname(logFile);
fs.mkdirSync(logDir, { recursive: true });
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`);
const startedAt = new Date().toISOString();
const rawBody = await readRequestBody(req);
const query = Object.fromEntries(url.searchParams.entries());
if (url.pathname === '/health') {
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, service: 'warehouse-push-receiver' }));
return;
}
if (req.method !== 'POST' || url.pathname !== options.path) {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.end(`404 Not Found(接收路径为 ${options.path})`);
return;
}
// MD5 验签:sign = MD5(appSecret + timestamp + bodyJson)
const timestamp = String(query.timestamp || '');
const providedSign = String(query.sign || '');
const expectedSign = options.appSecret ? md5(options.appSecret + timestamp + rawBody) : '';
const signOk = !options.verifySign || (timestamp && providedSign === expectedSign);
let parsedBody = rawBody;
try {
parsedBody = rawBody ? JSON.parse(rawBody) : null;
} catch (_) {
// keep raw text
}
const logText = [
'================ 收到仓库接口推送 ================',
`[time] ${startedAt}`,
`[route] POST ${url.pathname}`,
`[query] ${JSON.stringify(query, null, 2)}`,
options.verifySign
? `[sign] ${signOk ? '验签通过' : `验签失败(期望 ${expectedSign})`}`
: '[sign] 已关闭验签',
`[header] ${JSON.stringify(req.headers, null, 2)}`,
`[body] ${JSON.stringify(parsedBody, null, 2)}`,
'==================================================',
].join('\n');
console.log('\n' + logText);
writeLog(logFile, `${logText}\n`);
// 始终返回 HTTP 200 + code=200,便于 WMS 判定推送成功
const responseBody = JSON.stringify({ code: 200, message: 'ok', received_at: startedAt });
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
res.end(responseBody);
});
server.listen(options.port, options.host, () => {
console.log('[warehouse-push-receiver] listening on http://' + options.host + ':' + options.port + options.path);
console.log(`[warehouse-push-receiver] app_key=${options.appKey}`);
console.log(`[warehouse-push-receiver] app_secret=${options.appSecret ? options.appSecret.slice(0, 8) + '…' : '(空)'}`);
console.log(`[warehouse-push-receiver] 验签=${options.verifySign ? '开启' : '关闭'}`);
console.log(`[warehouse-push-receiver] 日志文件=${logFile}`);
console.log(`[warehouse-push-receiver] 健康检查: GET http://${options.host}:${options.port}/health`);
console.log('[warehouse-push-receiver] 按 Ctrl+C 停止');
});
}
start().catch(error => {
console.error('[warehouse-push-receiver] failed:', error);
process.exit(1);
});

View File

@ -1,134 +0,0 @@
'use strict';
const http = require('node:http');
const { URL } = require('node:url');
function parseArgs(argv) {
const options = {
host: process.env.WEBHOOK_DEBUG_HOST || '127.0.0.1',
port: Number(process.env.WEBHOOK_DEBUG_PORT || 7071),
defaultResponse: process.env.WEBHOOK_DEBUG_RESPONSE || '1',
noticResponse: process.env.WEBHOOK_DEBUG_NOTIC_RESPONSE || '',
notic2Response: process.env.WEBHOOK_DEBUG_NOTIC2_RESPONSE || '',
};
for (const arg of argv) {
if (!arg.startsWith('--')) {
continue;
}
const [rawKey, ...rest] = arg.slice(2).split('=');
const value = rest.join('=');
switch (rawKey) {
case 'host':
options.host = value || options.host;
break;
case 'port':
options.port = Number(value || options.port);
break;
case 'response':
options.defaultResponse = value || options.defaultResponse;
break;
case 'notic-response':
options.noticResponse = value || options.noticResponse;
break;
case 'notic2-response':
options.notic2Response = value || options.notic2Response;
break;
case 'help':
options.help = true;
break;
default:
break;
}
}
return options;
}
function printHelp() {
console.log(`用法:\n npm run debug:webhook:receiver\n npm run debug:webhook:receiver -- --port=7071 --notic-response=1 --notic2-response=0\n\n环境变量:\n WEBHOOK_DEBUG_PORT=7071\n WEBHOOK_DEBUG_RESPONSE=1\n WEBHOOK_DEBUG_NOTIC_RESPONSE=1\n WEBHOOK_DEBUG_NOTIC2_RESPONSE=0\n`);
}
function readRequestBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function buildResponseBody(pathname, options) {
if (pathname === '/notic2' && options.notic2Response) {
return options.notic2Response;
}
if (pathname === '/notic' && options.noticResponse) {
return options.noticResponse;
}
return options.defaultResponse;
}
async function start() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
printHelp();
return;
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`);
const startedAt = new Date().toISOString();
const rawBody = await readRequestBody(req);
let parsedBody = rawBody;
try {
parsedBody = rawBody ? JSON.parse(rawBody) : null;
} catch (_) {
// keep raw text
}
console.log('\n================ WEBHOOK DEBUG RECEIVER ================');
console.log(`[time] ${startedAt}`);
console.log(`[route] ${req.method} ${url.pathname}`);
console.log('[query] ', Object.fromEntries(url.searchParams.entries()));
console.log('[header]', req.headers);
console.log('[body] ', JSON.stringify(parsedBody, null, 2));
if (![ '/notic', '/notic2', '/health' ].includes(url.pathname)) {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.end('404 Not Found');
return;
}
if (url.pathname === '/health') {
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, service: 'webhook-debug-receiver' }));
return;
}
const responseBody = buildResponseBody(url.pathname, options);
const statusCode = String(responseBody).startsWith('{') || String(responseBody).startsWith('[') ? 200 : 200;
const contentType = String(responseBody).startsWith('{') || String(responseBody).startsWith('[')
? 'application/json; charset=utf-8'
: 'text/plain; charset=utf-8';
res.writeHead(statusCode, { 'content-type': contentType });
res.end(responseBody);
console.log(`[reply] ${url.pathname} -> ${responseBody}`);
console.log('========================================================\n');
});
server.listen(options.port, options.host, () => {
console.log(`[webhook-debug-receiver] listening on http://${options.host}:${options.port}`);
console.log(`[webhook-debug-receiver] endpoints:`);
console.log(` - POST http://${options.host}:${options.port}/notic`);
console.log(` - POST http://${options.host}:${options.port}/notic2`);
console.log(` - GET http://${options.host}:${options.port}/health`);
});
}
start().catch(error => {
console.error('[webhook-debug-receiver] failed:', error);
process.exit(1);
});