Files
SupplierSystem/server/scripts/diag-price-invert-caliber-ab.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

143 lines
6.1 KiB
TypeScript
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.
/**
* 诊断:采购风险表「成本口径」改动前/后对照(只读,不写任何业务数据)。
*
* 做法:从指定提交里取出旧版 `priceInvertRiskQueryService.ts`,临时落到同目录(相对 import 才能解析),
* 用同一个窗口分别调用新旧两个服务,输出各分公司「旧 N 行 → 新 M 行 / 新增 / 消失」及新增行明细。
* 期望:**只增不减**(成本改为 GREATEST(供给价, 订单行成本) 不会让既有风险行消失)。
*
* ⚠️ 只允许对本地库运行(脚本会拒绝非 localhost 的 DATABASE_URL)。
* 运行(server 目录):
* npm run diag:price-invert-caliber
* npm run diag:price-invert-caliber -- --old-commit 1f80c750 --from 2026-01-01 --to 2026-12-31
*
* 取数结论(本地镜像库,2026-09-22 记录):
* BR004 2026-09-22~09-25:旧 1 → 新 2(新增「米块」:实采价 5 / 订单行成本 10 / 售价 6)
* 四分公司 2026 全年:旧 38 → 新 40(+BR002「榨菜」、+BR004「米块」),消失 0
*/
import { execFileSync } from 'node:child_process';
import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import pg from 'pg';
import { runWithTenantDbContext } from '../src/services/tenantDbContext';
const { Pool } = pg;
const OLD_COMMIT_DEFAULT = '1f80c750';
const TMP_BASENAME = '__old_priceInvertRiskQueryService';
type Args = { oldCommit: string; from: string; to: string; branches: string[]; dateField: string };
function parseArgs(argv: string[]): Args {
const out: Args = {
oldCommit: OLD_COMMIT_DEFAULT,
from: '2026-01-01',
to: '2026-12-31',
branches: ['BR001', 'BR002', 'BR003', 'BR004'],
dateField: 'created_at',
};
for (let i = 0; i < argv.length; i += 1) {
const [flag, value] = [argv[i], argv[i + 1]];
if (flag === '--old-commit' && value) out.oldCommit = value;
if (flag === '--from' && value) out.from = value;
if (flag === '--to' && value) out.to = value;
if (flag === '--date-field' && value) out.dateField = value;
if (flag === '--branches' && value) out.branches = value.split(',').map((b) => b.trim().toUpperCase());
}
return out;
}
function assertLocalDatabase(url: string) {
const host = (() => {
try {
return new URL(url).hostname;
} catch {
return '';
}
})();
if (!['127.0.0.1', 'localhost', '::1'].includes(host)) {
throw new Error(`拒绝运行:DATABASE_URL 指向非本地库 (${host || 'unknown'})`);
}
}
/** 旧版服务:从 git 取出源码临时放入 services/ 同目录(相对 import 才能解析),由 tsx 即时编译 */
function materializeOldService(commit: string) {
const dir = path.join(__dirname, '..', 'src', 'services');
const target = path.join(dir, `${TMP_BASENAME}.ts`);
const src = execFileSync(
'git',
['show', `${commit}:server/src/services/priceInvertRiskQueryService.ts`],
{ cwd: path.join(__dirname, '..', '..'), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 }
);
// 旧文件可能与新文件重名导出互不干扰;仅去掉文件头注释以免误导
writeFileSync(target, `/* 由 diag-price-invert-caliber-ab.ts 从 ${commit} 临时取出,运行结束会删除 */\n${src}`);
return target;
}
const keyOf = (r: { kind: string; order_code: string; purchase_code?: string | null; row_code?: string }) =>
`${r.kind}|${r.order_code}|${r.purchase_code || r.row_code}`;
async function main() {
const url = String(process.env.DATABASE_URL || '');
if (!url) throw new Error('缺少 DATABASE_URL(用 npm run diag:price-invert-caliber 会带 --env-file=.env)');
assertLocalDatabase(url);
const args = parseArgs(process.argv.slice(2));
const tmp = materializeOldService(args.oldCommit);
const pool = new Pool({ connectionString: url, max: 4 });
try {
const oldSvc = (await import(`../src/services/${TMP_BASENAME}`)) as typeof import('../src/services/priceInvertRiskQueryService');
const newSvc = (await import('../src/services/priceInvertRiskQueryService')) as typeof import('../src/services/priceInvertRiskQueryService');
console.log(`旧口径来自提交 ${args.oldCommit};窗口 ${args.from}~${args.to}(dateField=${args.dateField})\n`);
let anyRemoved = 0;
for (const br of args.branches) {
const ctx = {
userId: 'diag',
roles: ['admin'],
isSuperAdmin: true,
permissions: [] as string[],
branchCode: br,
branchCodes: [br],
};
await runWithTenantDbContext(br, async () => {
const input = { dateFrom: args.from, dateTo: args.to, dateField: args.dateField };
const before = await oldSvc.listPriceInvertRisks(ctx as never, br, input);
const after = await newSvc.listPriceInvertRisks(ctx as never, br, input);
const beforeKeys = new Set(before.rows.map(keyOf));
const afterKeys = new Set(after.rows.map(keyOf));
const added = after.rows.filter((r) => !beforeKeys.has(keyOf(r)));
const removed = before.rows.filter((r) => !afterKeys.has(keyOf(r)));
anyRemoved += removed.length;
console.log(
`${br}: 旧 ${before.rows.length} 行 → 新 ${after.rows.length} 行 | 新增 ${added.length} 消失 ${removed.length}`
);
for (const r of added) {
console.log(
` + [${r.kind}] ${r.product_name} ${r.order_code} 成本=${r.cost_price}` +
`(采购价=${r.purchase_price} 实采价=${r.actual_price})售价=${r.sale_price}`
);
}
for (const r of removed) {
console.log(` - [${r.kind}] ${r.product_name} ${r.order_code} 成本=${r.cost_price} 售价=${r.sale_price}`);
}
});
}
console.log(
anyRemoved === 0
? '\n✔ 无任何既有风险行消失(口径改动为严格增量)'
: `\n✘ 有 ${anyRemoved} 行消失,需排查`
);
if (anyRemoved !== 0) process.exitCode = 1;
} finally {
await pool.end();
if (existsSync(tmp)) unlinkSync(tmp);
}
}
main().then(
() => process.exit(process.exitCode || 0),
(e) => {
console.error('FATAL', (e as Error).message);
process.exit(1);
}
);