Files
SupplierSystem/scripts/prod-cleanup-orphan-order-refs.cjs
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

157 lines
5.3 KiB
JavaScript

#!/usr/bin/env node
/**
* 清除「order_code 有值,但 orders 表中不存在该订单」的孤儿数据。
* 不删除 order_code IS NULL 的期间成本(如未分摊人工/固定成本分摊余额)。
*
* 用法(生产):
* NODE_PATH=./node_modules node --env-file=.env /tmp/prod-cleanup-orphan-order-refs.cjs
* NODE_PATH=./node_modules node --env-file=.env /tmp/prod-cleanup-orphan-order-refs.cjs --execute
*/
const { Pool } = require('pg');
const EXECUTE = process.argv.includes('--execute');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
/** table, column, optional extra WHERE */
const TARGETS = [
{ table: 'cost_details', column: 'order_code' },
{ table: 'purchase_orders', column: 'order_code' },
{ table: 'supplier_preparations', column: 'order_code' },
{ table: 'inspections', column: 'order_code' },
{ table: 'inspection_returns', column: 'order_code' },
{ table: 'inspection_loss_confirmations', column: 'order_code' },
{ table: 'processing_tasks', column: 'order_code' },
{ table: 'processing_logs', column: 'order_code' },
{ table: 'delivery_tasks', column: 'order_code' },
{ table: 'delivery_signatures', column: 'order_code' },
{ table: 'delivery_person_locations', column: 'order_code' },
{ table: 'sign_records', column: 'order_code' },
{ table: 'picking_tasks', column: 'order_code' },
{ table: 'picking_items', column: 'order_code' },
{ table: 'allocation_tasks', column: 'order_code' },
{ table: 'order_items', column: 'order_code' },
{ table: 'after_sales', column: 'order_code' },
{ table: 'product_substitutions', column: 'order_code' },
{ table: 'statement_lines', column: 'order_code' },
{ table: 'exception_tickets', column: 'related_order_code' },
{ table: 'cost_adjustments', column: 'order_code' },
];
async function tableExists(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 columnExists(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 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 summary = [];
try {
// 先列 distinct orphan codes 样本
const sampleCodes = new Set();
for (const t of TARGETS) {
if (!(await tableExists(client, t.table))) {
summary.push({ table: t.table, status: 'skip_no_table' });
continue;
}
if (!(await columnExists(client, t.table, t.column))) {
summary.push({ table: t.table, status: 'skip_no_column', column: t.column });
continue;
}
const countSql = `
SELECT COUNT(*)::int AS cnt
FROM ${t.table} x
WHERE x.${t.column} IS NOT NULL
AND TRIM(x.${t.column}::text) <> ''
AND NOT EXISTS (
SELECT 1 FROM orders o WHERE o.order_code = x.${t.column}
)`;
const cnt = Number((await client.query(countSql)).rows[0]?.cnt) || 0;
if (cnt > 0) {
const codes = await client.query(
`SELECT DISTINCT x.${t.column}::text AS order_code
FROM ${t.table} x
WHERE x.${t.column} IS NOT NULL
AND TRIM(x.${t.column}::text) <> ''
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = x.${t.column})
LIMIT 30`
);
for (const row of codes.rows) sampleCodes.add(row.order_code);
}
let deleted = 0;
if (EXECUTE && cnt > 0) {
const del = await client.query(
`DELETE FROM ${t.table} x
WHERE x.${t.column} IS NOT NULL
AND TRIM(x.${t.column}::text) <> ''
AND NOT EXISTS (
SELECT 1 FROM orders o WHERE o.order_code = x.${t.column}
)`
);
deleted = del.rowCount || 0;
}
summary.push({
table: t.table,
column: t.column,
orphan_count: cnt,
deleted: EXECUTE ? deleted : 0,
});
console.log(
`${t.table}.${t.column}: orphan=${cnt}${EXECUTE ? `, deleted=${deleted}` : ' (dry-run)'}`
);
}
// cost_details 额外金额汇总
if (await tableExists(client, 'cost_details')) {
const amt = await client.query(
`SELECT COALESCE(SUM(COALESCE(amount,0)),0)::numeric AS total
FROM cost_details cd
WHERE cd.order_code IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code)`
);
console.log(`\ncost_details 孤儿金额合计: ¥${amt.rows[0].total}`);
}
console.log('\n孤儿订单号样本:', [...sampleCodes].slice(0, 40));
console.log('\n汇总:', JSON.stringify(summary, null, 2));
if (!EXECUTE) {
console.log('\n[dry-run] 未删除。加上 --execute 执行清理。');
} else {
console.log('\n清理完成。期间成本(order_code 为空)已保留。');
}
} finally {
client.release();
await pool.end();
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});