来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
265 lines
9.5 KiB
JavaScript
265 lines
9.5 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 清除生产「财务结算」模块中与现有订单无关联的数据。
|
||
*
|
||
* 清理范围:
|
||
* 1) cost_details / statement_lines 等:order_code 有值但 orders 中不存在
|
||
* 2) cost_details:order_code 为空且不是自由成本(free_overhead)
|
||
* —— 含误录期间人工、未分摊期间池等;保留 free_overhead、fixed_costs 主表
|
||
* 3) 结算单头:删除后无任何明细行的空结算单
|
||
* 4) 级联:对应 disputes / payments / invoices / 指向已删成本的 adjustments
|
||
*
|
||
* 用法:
|
||
* NODE_PATH=./node_modules node --env-file=.env /tmp/prod-cleanup-finance-orphan.cjs
|
||
* NODE_PATH=./node_modules node --env-file=.env /tmp/prod-cleanup-finance-orphan.cjs --execute
|
||
*/
|
||
const { Pool } = require('pg');
|
||
|
||
const EXECUTE = process.argv.includes('--execute');
|
||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||
|
||
async function exists(client, table) {
|
||
const r = await client.query(
|
||
`SELECT 1 FROM information_schema.tables
|
||
WHERE table_schema='public' AND table_name=$1 LIMIT 1`,
|
||
[table]
|
||
);
|
||
return r.rowCount > 0;
|
||
}
|
||
|
||
async function hasCol(client, table, column) {
|
||
const r = await client.query(
|
||
`SELECT 1 FROM information_schema.columns
|
||
WHERE table_schema='public' AND table_name=$1 AND column_name=$2 LIMIT 1`,
|
||
[table, column]
|
||
);
|
||
return r.rowCount > 0;
|
||
}
|
||
|
||
async function count(client, sql, params = []) {
|
||
const r = await client.query(sql, params);
|
||
return Number(r.rows[0]?.c || r.rows[0]?.cnt || 0);
|
||
}
|
||
|
||
async function main() {
|
||
if (!process.env.DATABASE_URL) {
|
||
console.error('缺少 DATABASE_URL');
|
||
process.exit(1);
|
||
}
|
||
|
||
console.log(`=== 财务结算孤儿数据清理 (${EXECUTE ? 'EXECUTE' : 'DRY-RUN'}) ===\n`);
|
||
const client = await pool.connect();
|
||
const report = {};
|
||
|
||
try {
|
||
// ---- preview counts ----
|
||
report.cost_details_missing_order = await count(
|
||
client,
|
||
`SELECT COUNT(*)::int AS c FROM cost_details cd
|
||
WHERE cd.order_code IS NOT NULL AND TRIM(cd.order_code) <> ''
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code)`
|
||
);
|
||
report.cost_details_period_no_order = await count(
|
||
client,
|
||
`SELECT COUNT(*)::int AS c FROM cost_details cd
|
||
WHERE (cd.order_code IS NULL OR TRIM(cd.order_code) = '')
|
||
AND cd.cost_type IS DISTINCT FROM 'free_overhead'`
|
||
);
|
||
report.cost_details_period_amount = (
|
||
await client.query(
|
||
`SELECT COALESCE(SUM(COALESCE(amount,0)),0)::numeric AS t FROM cost_details cd
|
||
WHERE (cd.order_code IS NULL OR TRIM(cd.order_code) = '')
|
||
AND cd.cost_type IS DISTINCT FROM 'free_overhead'`
|
||
)
|
||
).rows[0].t;
|
||
|
||
report.statement_lines_missing_order = (await exists(client, 'statement_lines'))
|
||
? await count(
|
||
client,
|
||
`SELECT COUNT(*)::int AS c FROM statement_lines sl
|
||
WHERE sl.order_code IS NOT NULL AND TRIM(sl.order_code) <> ''
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = sl.order_code)`
|
||
)
|
||
: 0;
|
||
|
||
report.free_overhead_kept = await count(
|
||
client,
|
||
`SELECT COUNT(*)::int AS c FROM cost_details WHERE cost_type = 'free_overhead'`
|
||
);
|
||
|
||
console.log(JSON.stringify(report, null, 2));
|
||
|
||
if (!EXECUTE) {
|
||
console.log('\n[dry-run] 未删除。加上 --execute 执行。');
|
||
console.log('将保留: free_overhead、fixed_costs 主表、仍有有效明细的结算单。');
|
||
return;
|
||
}
|
||
|
||
await client.query('BEGIN');
|
||
|
||
// 1) 先删指向将删结算行的争议
|
||
if (await exists(client, 'statement_disputes') && (await exists(client, 'statement_lines'))) {
|
||
const d1 = await client.query(
|
||
`DELETE FROM statement_disputes sd
|
||
WHERE sd.line_id IS NOT NULL
|
||
AND EXISTS (
|
||
SELECT 1 FROM statement_lines sl
|
||
WHERE sl.id = sd.line_id
|
||
AND sl.order_code IS NOT NULL AND TRIM(sl.order_code) <> ''
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = sl.order_code)
|
||
)`
|
||
);
|
||
console.log(`statement_disputes (via orphan lines): ${d1.rowCount}`);
|
||
}
|
||
|
||
// 2) 结算明细孤儿
|
||
if (await exists(client, 'statement_lines')) {
|
||
const d2 = await client.query(
|
||
`DELETE FROM statement_lines sl
|
||
WHERE sl.order_code IS NOT NULL AND TRIM(sl.order_code) <> ''
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = sl.order_code)`
|
||
);
|
||
console.log(`statement_lines missing order: ${d2.rowCount}`);
|
||
}
|
||
|
||
// 3) 成本明细:缺失订单
|
||
const d3 = await client.query(
|
||
`DELETE FROM cost_details cd
|
||
WHERE cd.order_code IS NOT NULL AND TRIM(cd.order_code) <> ''
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code)
|
||
RETURNING id`
|
||
);
|
||
console.log(`cost_details missing order: ${d3.rowCount}`);
|
||
|
||
// 4) 成本明细:无订单挂靠且非自由成本
|
||
const d4 = await client.query(
|
||
`DELETE FROM cost_details cd
|
||
WHERE (cd.order_code IS NULL OR TRIM(cd.order_code) = '')
|
||
AND cd.cost_type IS DISTINCT FROM 'free_overhead'
|
||
RETURNING id, cost_type, amount, cycle_code`
|
||
);
|
||
console.log(`cost_details period/no-order (non free): ${d4.rowCount}`);
|
||
if (d4.rows.length) {
|
||
console.table(
|
||
d4.rows.slice(0, 20).map((r) => ({
|
||
id: String(r.id).slice(0, 8),
|
||
type: r.cost_type,
|
||
amount: r.amount,
|
||
cycle: r.cycle_code,
|
||
}))
|
||
);
|
||
}
|
||
|
||
// 5) 成本调整:指向已不存在的 cost_detail
|
||
if ((await exists(client, 'cost_adjustments')) && (await hasCol(client, 'cost_adjustments', 'cost_detail_id'))) {
|
||
const d5 = await client.query(
|
||
`DELETE FROM cost_adjustments ca
|
||
WHERE ca.cost_detail_id IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM cost_details cd WHERE cd.id = ca.cost_detail_id)`
|
||
);
|
||
console.log(`cost_adjustments orphan detail: ${d5.rowCount}`);
|
||
}
|
||
|
||
// 6) 空结算单 + 其发票/付款/争议
|
||
for (const [table, type] of [
|
||
['customer_statements', 'customer'],
|
||
['supplier_statements', 'supplier'],
|
||
]) {
|
||
if (!(await exists(client, table))) continue;
|
||
|
||
const empty = await client.query(
|
||
`SELECT st.statement_no FROM ${table} st
|
||
WHERE NOT EXISTS (
|
||
SELECT 1 FROM statement_lines sl
|
||
WHERE sl.statement_no = st.statement_no
|
||
AND (sl.statement_type = $1 OR sl.statement_type IS NULL OR TRIM(sl.statement_type)='')
|
||
)
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM statement_lines sl2
|
||
WHERE sl2.statement_no = st.statement_no
|
||
)`,
|
||
[type]
|
||
);
|
||
// Simpler: no lines at all for this statement_no
|
||
const empty2 = await client.query(
|
||
`SELECT st.statement_no FROM ${table} st
|
||
WHERE NOT EXISTS (
|
||
SELECT 1 FROM statement_lines sl WHERE sl.statement_no = st.statement_no
|
||
)`
|
||
);
|
||
const nos = empty2.rows.map((r) => r.statement_no);
|
||
if (!nos.length) {
|
||
console.log(`${table} empty: 0`);
|
||
continue;
|
||
}
|
||
|
||
if (await exists(client, 'statement_disputes')) {
|
||
await client.query(
|
||
`DELETE FROM statement_disputes WHERE statement_no = ANY($1::text[])`,
|
||
[nos]
|
||
);
|
||
}
|
||
if (await exists(client, 'statement_payments')) {
|
||
const dp = await client.query(
|
||
`DELETE FROM statement_payments WHERE statement_no = ANY($1::text[])`,
|
||
[nos]
|
||
);
|
||
console.log(`statement_payments for empty ${table}: ${dp.rowCount}`);
|
||
}
|
||
if (await exists(client, 'invoices') && (await hasCol(client, 'invoices', 'statement_no'))) {
|
||
const di = await client.query(
|
||
`DELETE FROM invoices WHERE statement_no = ANY($1::text[])`,
|
||
[nos]
|
||
);
|
||
console.log(`invoices for empty ${table}: ${di.rowCount}`);
|
||
}
|
||
const ds = await client.query(
|
||
`DELETE FROM ${table} WHERE statement_no = ANY($1::text[])`,
|
||
[nos]
|
||
);
|
||
console.log(`${table} empty deleted: ${ds.rowCount}`);
|
||
}
|
||
|
||
// 7) 发票挂不存在的结算单
|
||
if ((await exists(client, 'invoices')) && (await hasCol(client, 'invoices', 'statement_no'))) {
|
||
const di2 = await client.query(
|
||
`DELETE FROM invoices inv
|
||
WHERE inv.statement_no IS NOT NULL AND TRIM(inv.statement_no) <> ''
|
||
AND NOT EXISTS (SELECT 1 FROM customer_statements cs WHERE cs.statement_no = inv.statement_no)
|
||
AND NOT EXISTS (SELECT 1 FROM supplier_statements ss WHERE ss.statement_no = inv.statement_no)`
|
||
);
|
||
console.log(`invoices orphan statement: ${di2.rowCount}`);
|
||
}
|
||
|
||
await client.query('COMMIT');
|
||
|
||
// verify
|
||
const leftMissing = await count(
|
||
client,
|
||
`SELECT COUNT(*)::int AS c FROM cost_details cd
|
||
WHERE cd.order_code IS NOT NULL AND TRIM(cd.order_code) <> ''
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code)`
|
||
);
|
||
const leftPeriod = await count(
|
||
client,
|
||
`SELECT COUNT(*)::int AS c FROM cost_details cd
|
||
WHERE (cd.order_code IS NULL OR TRIM(cd.order_code) = '')
|
||
AND cd.cost_type IS DISTINCT FROM 'free_overhead'`
|
||
);
|
||
console.log('\n清理完成。');
|
||
console.log(`剩余 cost_details 挂死订单: ${leftMissing}`);
|
||
console.log(`剩余 cost_details 无订单非自由成本: ${leftPeriod}`);
|
||
} catch (e) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw e;
|
||
} finally {
|
||
client.release();
|
||
await pool.end();
|
||
}
|
||
}
|
||
|
||
main().catch((e) => {
|
||
console.error(e);
|
||
process.exit(1);
|
||
});
|