来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
241 lines
9.3 KiB
JavaScript
241 lines
9.3 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 生产环境安全脏数据清理(不删真实业务订单)
|
||
*
|
||
* 清理项:
|
||
* - 演示客户 CUST001/CUST002(无订单、名称含「(客户)」)
|
||
* - E2E 测试账号(固定 UUID,不含 superadmin)
|
||
* - 订单已不存在的孤立采购单、备货单、验收记录
|
||
* - 无关联订单的孤立异常工单
|
||
* - 过期的备货延误类异常工单(prep_delay,无 related_order_code)
|
||
* - 同步角色默认:仓管/配送 关闭拍照验收、拍照送达
|
||
*
|
||
* 用法:
|
||
* node --env-file=.env scripts/prod-safe-cleanup.mjs
|
||
* node --env-file=.env scripts/prod-safe-cleanup.mjs --execute
|
||
*/
|
||
import pg from 'pg';
|
||
import dotenv from 'dotenv';
|
||
import path from 'path';
|
||
import { fileURLToPath } from 'url';
|
||
|
||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||
dotenv.config({ path: path.join(__dirname, '..', '.env') });
|
||
|
||
const EXECUTE = process.argv.includes('--execute');
|
||
const DRY = !EXECUTE;
|
||
|
||
const E2E_USER_IDS = [
|
||
'a0000000-0000-0000-0000-000000000002',
|
||
'a0000000-0000-0000-0000-000000000003',
|
||
'a0000000-0000-0000-0000-000000000004',
|
||
'a0000000-0000-0000-0000-000000000005',
|
||
'a0000000-0000-0000-0000-000000000006',
|
||
'b0000000-0000-0000-0000-000000000001',
|
||
'b0000000-0000-0000-0000-000000000002',
|
||
'b0000000-0000-0000-0000-000000000003',
|
||
];
|
||
|
||
const SUPER_ADMIN = 'a0000000-0000-0000-0000-000000000001';
|
||
|
||
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
||
|
||
async function runStep(client, label, sql, params = []) {
|
||
if (DRY) {
|
||
const preview = await client.query(sql.replace(/^DELETE/i, 'SELECT count(*)::int AS c FROM').replace(/^UPDATE/i, 'SELECT count(*)::int AS c FROM'), params).catch(async () => {
|
||
const r = await client.query(`SELECT 1 AS c LIMIT 0`);
|
||
return r;
|
||
});
|
||
console.log(` [dry] ${label}`);
|
||
return 0;
|
||
}
|
||
const r = await client.query(sql, params);
|
||
console.log(` ${label}: ${r.rowCount}`);
|
||
return r.rowCount;
|
||
}
|
||
|
||
async function main() {
|
||
console.log(`=== 生产安全脏数据清理 (${DRY ? 'DRY-RUN' : 'EXECUTE'}) ===`);
|
||
const client = await pool.connect();
|
||
try {
|
||
const demoCustomers = (
|
||
await client.query(
|
||
`SELECT c.customer_code, c.company_name,
|
||
(SELECT count(*)::int FROM orders o WHERE o.customer_code = c.customer_code) AS order_count
|
||
FROM customers c
|
||
WHERE c.customer_code IN ('CUST001', 'CUST002')
|
||
OR c.company_name LIKE '%(客户)%'`
|
||
)
|
||
).rows;
|
||
console.log('\n--- 演示客户 ---');
|
||
console.log(JSON.stringify(demoCustomers, null, 2));
|
||
|
||
const e2eUsers = (
|
||
await client.query(`SELECT id, username FROM profiles WHERE id = ANY($1::uuid[])`, [E2E_USER_IDS])
|
||
).rows;
|
||
console.log('\n--- E2E 测试账号 ---');
|
||
console.log(JSON.stringify(e2eUsers, null, 2));
|
||
|
||
const orphanExceptions = (
|
||
await client.query(
|
||
`SELECT ticket_code, related_order_code FROM exception_tickets et
|
||
WHERE et.related_order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = et.related_order_code)`
|
||
)
|
||
).rows;
|
||
console.log('\n--- 孤立异常工单 ---');
|
||
console.log(JSON.stringify(orphanExceptions, null, 2));
|
||
|
||
const orphanPurchases = (
|
||
await client.query(
|
||
`SELECT count(*)::int AS c FROM purchase_orders po
|
||
WHERE po.order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = po.order_code)`
|
||
)
|
||
).rows[0]?.c ?? 0;
|
||
const orphanPrep = (
|
||
await client.query(
|
||
`SELECT count(*)::int AS c FROM supplier_preparations sp
|
||
WHERE sp.order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = sp.order_code)`
|
||
)
|
||
).rows[0]?.c ?? 0;
|
||
const orphanInspections = (
|
||
await client.query(
|
||
`SELECT count(*)::int AS c FROM inspections i
|
||
WHERE i.order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = i.order_code)`
|
||
)
|
||
).rows[0]?.c ?? 0;
|
||
console.log('\n--- 孤立业务数据 ---');
|
||
console.log(JSON.stringify({ orphanPurchases, orphanPrep, orphanInspections }, null, 2));
|
||
|
||
const staleExceptions = (
|
||
await client.query(
|
||
`SELECT ticket_code, ticket_type, handle_remark FROM exception_tickets
|
||
WHERE ticket_type = 'prep_delay' AND related_order_code IS NULL`
|
||
)
|
||
).rows;
|
||
console.log('\n--- 过期备货延误异常 ---');
|
||
console.log(JSON.stringify(staleExceptions, null, 2));
|
||
|
||
if (DRY) {
|
||
console.log('\n--- 将执行 ---');
|
||
console.log(' 删除无订单的演示客户及门户绑定');
|
||
console.log(' 删除 E2E 测试账号(若存在)');
|
||
console.log(` 删除 ${orphanPurchases} 条孤立采购单、${orphanPrep} 条孤立备货单、${orphanInspections} 条孤立验收`);
|
||
console.log(' 删除孤立/过期异常工单');
|
||
console.log(' 同步 warehouse/delivery 角色:关闭 inspection_photo、delivery_sign_photo');
|
||
console.log('\n加 --execute 执行');
|
||
return;
|
||
}
|
||
|
||
await client.query('BEGIN');
|
||
|
||
for (const row of demoCustomers) {
|
||
if (Number(row.order_count) > 0) {
|
||
console.log(` skip demo customer ${row.customer_code} (has orders)`);
|
||
continue;
|
||
}
|
||
const code = row.customer_code;
|
||
await client.query(`DELETE FROM customer_portal_users WHERE customer_code = $1`, [code]);
|
||
await client.query(`DELETE FROM customer_skus WHERE customer_code = $1`, [code]);
|
||
await client.query(`DELETE FROM customer_sku_aliases WHERE customer_code = $1`, [code]);
|
||
await client.query(`DELETE FROM customer_image_aliases WHERE customer_code = $1`, [code]);
|
||
await client.query(`DELETE FROM customers WHERE customer_code = $1`, [code]);
|
||
console.log(` removed demo customer ${code}`);
|
||
}
|
||
|
||
for (const userId of E2E_USER_IDS) {
|
||
if (userId === SUPER_ADMIN) continue;
|
||
await client.query(`DELETE FROM purchaser_users WHERE user_id = $1`, [userId]);
|
||
await client.query(`DELETE FROM supplier_users WHERE user_id = $1`, [userId]);
|
||
await client.query(`DELETE FROM delivery_person_users WHERE user_id = $1`, [userId]);
|
||
await client.query(`DELETE FROM customer_portal_users WHERE user_id = $1`, [userId]);
|
||
await client.query(`DELETE FROM user_roles WHERE user_id = $1`, [userId]);
|
||
await client.query(`DELETE FROM profiles WHERE id = $1`, [userId]);
|
||
await client.query(`DELETE FROM auth.users WHERE id = $1`, [userId]);
|
||
}
|
||
console.log(` cleaned E2E test users (${E2E_USER_IDS.length} ids checked)`);
|
||
|
||
const delPo = await client.query(
|
||
`DELETE FROM purchase_orders po
|
||
WHERE po.order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = po.order_code)`
|
||
);
|
||
console.log(` removed orphan purchase_orders: ${delPo.rowCount}`);
|
||
|
||
const delPrep = await client.query(
|
||
`DELETE FROM supplier_preparations sp
|
||
WHERE sp.order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = sp.order_code)`
|
||
);
|
||
console.log(` removed orphan supplier_preparations: ${delPrep.rowCount}`);
|
||
|
||
const orphanOrderCodes = (
|
||
await client.query(
|
||
`SELECT DISTINCT i.order_code FROM inspections i
|
||
WHERE i.order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = i.order_code)`
|
||
)
|
||
).rows.map((r) => r.order_code);
|
||
|
||
if (orphanOrderCodes.length) {
|
||
const delInvByBatch = await client.query(
|
||
`DELETE FROM inventory inv
|
||
WHERE inv.batch_no IN (
|
||
SELECT i.batch_no FROM inspections i
|
||
WHERE i.order_code = ANY($1::text[]) AND i.batch_no IS NOT NULL
|
||
)`,
|
||
[orphanOrderCodes]
|
||
);
|
||
console.log(` removed inventory for orphan orders: ${delInvByBatch.rowCount}`);
|
||
}
|
||
|
||
const delIns = await client.query(
|
||
`DELETE FROM inspections i
|
||
WHERE i.order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = i.order_code)`
|
||
);
|
||
console.log(` removed orphan inspections: ${delIns.rowCount}`);
|
||
|
||
const delInvLogs = await client.query(
|
||
`DELETE FROM inventory_logs il
|
||
WHERE il.related_order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = il.related_order_code)`
|
||
);
|
||
console.log(` removed orphan inventory_logs: ${delInvLogs.rowCount}`);
|
||
|
||
const delExc = await client.query(
|
||
`DELETE FROM exception_tickets et
|
||
WHERE (et.related_order_code IS NOT NULL
|
||
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = et.related_order_code))
|
||
OR (et.ticket_type = 'prep_delay' AND et.related_order_code IS NULL)`
|
||
);
|
||
console.log(` removed stale exception tickets: ${delExc.rowCount}`);
|
||
|
||
await client.query(
|
||
`DELETE FROM role_permissions rp
|
||
USING permissions p
|
||
WHERE rp.permission_id = p.id
|
||
AND p.permission_code IN ('inspection_photo', 'delivery_sign_photo')
|
||
AND rp.role IN ('warehouse', 'delivery')`
|
||
);
|
||
console.log(' synced warehouse/delivery photo permissions off');
|
||
|
||
await client.query('COMMIT');
|
||
console.log('\n完成。');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
await pool.end();
|
||
}
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error);
|
||
process.exit(1);
|
||
});
|