Files
SupplierSystem/server/scripts/audit-main-bindings.mjs
T
Ubuntu bea53592e5 chore(审计脚本): 加环境横幅 —— 光看 BASE_URL 分不出「本机 dev 栈 / 生产 dump」
主系统在 §4.5.22 更正了一条事实:8443 域名入口的上游其实是本机 dev 栈(API 3001),
而本地主系统库是生产 dump 的副本(同一单号、同一批供应商)⇒ 我方此前的
「定时对账从线上拉回了货」实为「本机 dev 栈 + 生产 dump 库」,只能靠运行日志分辨。

两个只读审计脚本(audit-main-bindings / audit-mirror-pollution)现在先打印环境横幅:
我方库 / 主系统 BASE_URL(标注是否本机)/ 主系统库 / 主系统对接客户端数
(0 ⇒ 该库签不出对接 Token,生产当前即 0),并显式提示域名入口≠线上。

新增 server/scripts/lib/auditEnv.mjs 供两个脚本共用。
2026-10-13 12:35:34 +08:00

139 lines
6.1 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.
#!/usr/bin/env node
/**
* 只读对照:**我方绑定** × **主系统授权** × **接入编码是否绑上**(2026-10-13)
*
* 起因:开发者「供应商系统的编码明明没有给主系统绑定,但是就是分配过来了」。
* 结论:主系统侧 `supplier_integration_client_suppliers` 的「凭据→供应商」授权**不要求**填
* `subsystem_code`(我方接入编码)—— 空码行照样能换 Token 拉到货;我方侧当时又因**迁移回填的
* 通配绑定**主动去拉,于是"没绑也收到了货"。
*
* 本脚本把三张表摆在一起(**全只读**):
* ① 我方 `public.main_supplier_bindings`(谁绑了我们、来源是什么、还能不能自动拉)
* ② 我方 `public.branches`(分公司当前接入编码)
* ③ 主系统 `public.supplier_integration_client_suppliers`(凭据→供应商授权 + `subsystem_code`)
*
* 用法:
* node server/scripts/audit-main-bindings.mjs # 表格
* node server/scripts/audit-main-bindings.mjs --json
*
* 主系统库连接:优先 `MAIN_SYSTEM_DATABASE_URL`,否则读同机主系统 checkout 的 server/.env。
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import pg from 'pg';
import { printAuditEnv } from './lib/auditEnv.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const SERVER_DIR = path.resolve(HERE, '..');
const MAIN_ENV_CANDIDATES = ['/home/ubuntu/harness/ai-fresh-delivery/server/.env'];
function readDatabaseUrl(envPath) {
const text = fs.readFileSync(envPath, 'utf8');
const m = text.match(/^DATABASE_URL=(.*)$/m);
if (!m) throw new Error(`${envPath} 里没有 DATABASE_URL`);
return m[1].trim().replace(/^"|"$/g, '');
}
const jsonMode = process.argv.includes('--json');
const ourUrl = process.env.DATABASE_URL || readDatabaseUrl(path.join(SERVER_DIR, '.env'));
const mainUrl =
process.env.MAIN_SYSTEM_DATABASE_URL ||
MAIN_ENV_CANDIDATES.map((p) => (fs.existsSync(p) ? readDatabaseUrl(p) : null)).find(Boolean);
if (!mainUrl) {
console.error('缺少主系统库连接:请设 MAIN_SYSTEM_DATABASE_URL');
process.exit(2);
}
const ours = new pg.Client({ connectionString: ourUrl });
const main = new pg.Client({ connectionString: mainUrl });
await ours.connect();
await main.connect();
await printAuditEnv(main);
const branches = (
await ours.query(
`SELECT branch_code, branch_name, access_code, main_supplier_code FROM public.branches ORDER BY branch_code`
)
).rows;
const bindings = (
await ours.query(
`SELECT branch_code, access_code, main_branch_code, main_supplier_code, status, source, bound_at
FROM public.main_supplier_bindings ORDER BY branch_code, main_supplier_code`
)
).rows;
const clients = (
await main.query(
`SELECT client_id, name, status FROM public.supplier_integration_clients ORDER BY client_id`
)
).rows;
const auths = (
await main.query(
`SELECT client_id, branch_code, supplier_code, status, subsystem_code, granted_source,
granted_at, disabled_at
FROM public.supplier_integration_client_suppliers
ORDER BY client_id, branch_code, supplier_code`
)
).rows;
const accessCodeByBranch = new Map(branches.map((b) => [String(b.branch_code), String(b.access_code || '')]));
/** 与 `branchAccessCode.listAutoPullableBindingsForBranch` 同口径:这条绑定能不能自动拉货 */
function autoPullable(binding) {
if (String(binding.status) !== 'active') return { ok: false, why: '非 active' };
if (String(binding.source) === 'backfill') return { ok: false, why: '迁移回填(无主系统证据)' };
const rowCode = String(binding.access_code || '').trim().toUpperCase();
if (!rowCode) return { ok: false, why: '空接入编码' };
const current = String(accessCodeByBranch.get(String(binding.branch_code)) || '').trim().toUpperCase();
if (!current) return { ok: false, why: '分公司当前无接入编码' };
if (rowCode !== current) return { ok: false, why: '编码已换(残留旧行)' };
return { ok: true, why: '' };
}
const result = {
branches,
bindings: bindings.map((b) => ({ ...b, auto_pullable: autoPullable(b) })),
mainClients: clients,
mainAuthorizations: auths.map((a) => ({
...a,
/** ⚠️ 空码 = 主系统侧"授权了凭据但没绑接入编码"⇒ 任何拿到该凭据的进程都能拉这家供应商的货 */
bound_with_our_code: Boolean(String(a.subsystem_code || '').trim()),
})),
};
if (jsonMode) {
console.log(JSON.stringify(result, null, 2));
} else {
console.log('== 我方分公司(接入编码)==');
for (const b of branches) {
console.log(` ${b.branch_code} ${b.branch_name} | access_code=${b.access_code || '(无)'}`);
}
console.log('\n== 我方绑定(能否自动拉货)==');
for (const b of result.bindings) {
console.log(
` [${b.status}] ${b.branch_code} ← ${b.main_branch_code}/${b.main_supplier_code}` +
` code=${b.access_code || '(空)'} source=${b.source}` +
` 自动拉=${b.auto_pullable.ok ? '✅' : `❌ ${b.auto_pullable.why}`}`
);
}
console.log('\n== 主系统侧:凭据 → 供应商 授权(subsystem_code = 我方接入编码)==');
for (const a of result.mainAuthorizations) {
console.log(
` [${a.status === 1 ? '启用' : a.status}] ${a.branch_code}/${a.supplier_code}` +
` client=${a.client_id} subsystem_code=${a.subsystem_code || '(空码)'}` +
`${a.disabled_at ? ` 已停用@${a.disabled_at.toISOString?.() || a.disabled_at}` : ''}` +
`${a.bound_with_our_code ? '' : ' ⚠️ 未绑接入编码(对方仍会授权拉货)'}`
);
}
const gap = result.mainAuthorizations.filter((a) => !a.bound_with_our_code);
console.log(
`\n小结:主系统侧 ${result.mainAuthorizations.length} 条授权,其中 **${gap.length} 条未绑我方接入编码**` +
`${gap.length ? `(${gap.map((a) => a.supplier_code).join('、')})` : ''};` +
`我方侧 ${result.bindings.length} 条绑定,可自动拉 ${result.bindings.filter((b) => b.auto_pullable.ok).length} 条。`
);
}
await ours.end();
await main.end();