Files
SupplierSystem/server/scripts/prod-delete-all-orders.mjs
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

226 lines
7.4 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
/**
* 删除生产环境全部订单及关联履约数据(保留客户、商品、供应商、用户等主数据)。
*
* 用法(在 API 服务器 /opt/ai-fresh-delivery/server):
* node scripts/prod-delete-all-orders.mjs
* node scripts/prod-delete-all-orders.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_RUN = !EXECUTE;
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
async function tableExists(client, table) {
const r = await client.query(`SELECT to_regclass('public.' || $1) IS NOT NULL AS ok`, [table]);
return Boolean(r.rows[0]?.ok);
}
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`,
[table, column]
);
return r.rowCount > 0;
}
async function deleteAllOrders(client, orderCodes, dryRun = DRY_RUN) {
if (!orderCodes.length) return;
const pickCodes = (
await client.query(`SELECT pick_code FROM picking_tasks WHERE order_code = ANY($1::text[])`, [orderCodes])
).rows.map((r) => r.pick_code);
const inspectionIds = (
await client.query(`SELECT id FROM inspections WHERE order_code = ANY($1::text[])`, [orderCodes])
).rows.map((r) => r.id);
const batchNos = (
await client.query(
`SELECT DISTINCT batch_no FROM inspections
WHERE order_code = ANY($1::text[]) AND batch_no IS NOT NULL`,
[orderCodes]
)
).rows.map((r) => r.batch_no);
const steps = [];
if (pickCodes.length && (await tableExists(client, 'picking_scan_logs'))) {
steps.push({
label: 'picking_scan_logs',
sql: `DELETE FROM picking_scan_logs WHERE pick_code = ANY($1::text[])`,
params: [pickCodes],
});
}
if (pickCodes.length && (await tableExists(client, 'picking_items'))) {
steps.push({
label: 'picking_items',
sql: `DELETE FROM picking_items WHERE pick_code = ANY($1::text[])`,
params: [pickCodes],
});
}
if (pickCodes.length && (await tableExists(client, 'picking_containers'))) {
steps.push({
label: 'picking_containers',
sql: `DELETE FROM picking_containers WHERE pick_code = ANY($1::text[])`,
params: [pickCodes],
});
}
if (pickCodes.length && (await tableExists(client, 'picking_tasks'))) {
steps.push({
label: 'picking_tasks',
sql: `DELETE FROM picking_tasks WHERE pick_code = ANY($1::text[])`,
params: [pickCodes],
});
}
if (inspectionIds.length && (await tableExists(client, 'inspection_returns'))) {
steps.push({
label: 'inspection_returns',
sql: `DELETE FROM inspection_returns WHERE inspection_id = ANY($1::uuid[])`,
params: [inspectionIds],
});
}
if (inspectionIds.length && (await tableExists(client, 'inspection_loss_confirmations'))) {
steps.push({
label: 'inspection_loss_confirmations',
sql: `DELETE FROM inspection_loss_confirmations WHERE inspection_id = ANY($1::uuid[])`,
params: [inspectionIds],
});
}
if (inspectionIds.length && (await tableExists(client, 'processing_logs')) && (await columnExists(client, 'processing_logs', 'inspection_id'))) {
steps.push({
label: 'processing_logs',
sql: `DELETE FROM processing_logs WHERE inspection_id = ANY($1::uuid[])`,
params: [inspectionIds],
});
}
const orderTables = (
await client.query(
`SELECT DISTINCT table_name FROM information_schema.columns
WHERE table_schema = 'public' AND column_name = 'order_code' AND table_name <> 'orders'
ORDER BY table_name`
)
).rows.map((r) => r.table_name);
for (const table of orderTables) {
steps.push({
label: table,
sql: `DELETE FROM ${table} WHERE order_code = ANY($1::text[])`,
params: [orderCodes],
});
}
if (batchNos.length && (await tableExists(client, 'inventory'))) {
steps.push({
label: 'inventory(batch_no)',
sql: `DELETE FROM inventory WHERE batch_no = ANY($1::text[])`,
params: [batchNos],
});
}
if (await columnExists(client, 'inventory_logs', 'related_order_code')) {
steps.push({
label: 'inventory_logs(related_order_code)',
sql: `DELETE FROM inventory_logs WHERE related_order_code = ANY($1::text[])`,
params: [orderCodes],
});
}
if (await columnExists(client, 'exception_tickets', 'related_order_code')) {
steps.push({
label: 'exception_tickets(related_order_code)',
sql: `DELETE FROM exception_tickets WHERE related_order_code = ANY($1::text[])`,
params: [orderCodes],
});
}
steps.push({
label: 'orders',
sql: `DELETE FROM orders WHERE order_code = ANY($1::text[])`,
params: [orderCodes],
});
for (const step of steps) {
if (dryRun) {
const countSql = step.sql.replace(/^DELETE FROM/i, 'SELECT count(*)::int AS c FROM');
const preview = await client.query(countSql, step.params);
console.log(` [dry] ${step.label}: ${preview.rows[0]?.c ?? 0} rows`);
continue;
}
const r = await client.query(step.sql, step.params);
console.log(` deleted ${step.label}: ${r.rowCount}`);
}
}
async function main() {
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL required');
}
console.log(`=== 删除全部订单 (${DRY_RUN ? 'DRY-RUN,加 --execute 执行' : 'EXECUTE'}) ===`);
const client = await pool.connect();
try {
const summary = await client.query(`
SELECT
(SELECT count(*)::int FROM orders) AS orders,
(SELECT count(*)::int FROM order_items) AS order_items,
(SELECT count(*)::int FROM purchase_orders) AS purchase_orders,
(SELECT count(*)::int FROM supplier_preparations) AS supplier_preparations,
(SELECT count(*)::int FROM inspections) AS inspections,
(SELECT count(*)::int FROM picking_tasks) AS picking_tasks,
(SELECT count(*)::int FROM delivery_tasks) AS delivery_tasks
`);
console.log('当前数据量:', summary.rows[0]);
const orderCodes = (await client.query(`SELECT order_code FROM orders ORDER BY order_code`)).rows.map(
(r) => r.order_code
);
console.log(`\n待删除订单: ${orderCodes.length} 笔`);
if (orderCodes.length <= 20) {
console.log(orderCodes.join(', '));
} else {
console.log(`${orderCodes.slice(0, 10).join(', ')} ... ${orderCodes.slice(-3).join(', ')}`);
}
if (!orderCodes.length) {
console.log('无订单,无需删除。');
return;
}
if (DRY_RUN) {
console.log('\n--- 将删除的行数预览 ---');
await deleteAllOrders(client, orderCodes, true);
console.log('\n确认后执行: node scripts/prod-delete-all-orders.mjs --execute');
return;
}
await client.query('BEGIN');
try {
await deleteAllOrders(client, orderCodes, false);
await client.query('COMMIT');
console.log('\n已全部删除并提交。');
const after = await client.query(`SELECT count(*)::int AS orders FROM orders`);
console.log('剩余订单:', after.rows[0]?.orders ?? 0);
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
} finally {
client.release();
await pool.end();
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});