来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
184 lines
7.8 KiB
TypeScript
184 lines
7.8 KiB
TypeScript
/**
|
||
* 验证:订单「彻底删除」清干净子表,且**保留 `inventory_logs` 台账**。
|
||
*
|
||
* 用法(只允许本地库):
|
||
* cd server && npx tsx --env-file=.env scripts/verify-order-purge-orphans.ts
|
||
*
|
||
* 做法:在 tenant_br004 里造一单 + 11 张子表各 1 行 → 调真正的
|
||
* `deleteOrderWithDependencies` → 逐表比对 → **整体 ROLLBACK**,不留数据。
|
||
* 唯一会落库的是 `writeAuditLog`(它走自己的连接,不在本事务内),末尾单独清掉。
|
||
*/
|
||
import { pool } from '../src/db';
|
||
import type { TenantContext } from '../src/services/tenantScope';
|
||
import { deleteOrderWithDependencies } from '../src/services/orderDeleteService';
|
||
|
||
const SCHEMA = 'tenant_br004';
|
||
const BRANCH = 'BR004';
|
||
const CODE = 'SYNTH-PURGE-VERIFY';
|
||
const ITEM_ID = '11111111-1111-4111-8111-111111111111';
|
||
const PREP_ID = '22222222-2222-4222-8222-222222222222';
|
||
const USER_ID = '33333333-3333-4333-8333-333333333333';
|
||
|
||
/** 应当被清掉的表(key = 标签,value = where 片段) */
|
||
const SHOULD_BE_CLEARED: Array<[string, string]> = [
|
||
['order_items', `order_code = '${CODE}'`],
|
||
['order_item_fulfillments', `order_code = '${CODE}'`],
|
||
['order_item_returns', `order_code = '${CODE}'`],
|
||
['picking_items', `order_code = '${CODE}'`],
|
||
['picking_containers', `order_code = '${CODE}'`],
|
||
['picking_tasks', `order_code = '${CODE}'`],
|
||
['inventory_reservations', `order_code = '${CODE}'`],
|
||
['bid_rounds', `order_code = '${CODE}'`],
|
||
['supplier_prep_amend_requests', `order_code = '${CODE}'`],
|
||
['notifications', `related_order_code = '${CODE}'`],
|
||
];
|
||
|
||
/** 应当**保留**的表(台账定性) */
|
||
const SHOULD_BE_KEPT: Array<[string, string]> = [
|
||
['inventory_logs', `related_order_code = '${CODE}'`],
|
||
];
|
||
|
||
function assertLocalDb() {
|
||
const url = String(process.env.DATABASE_URL || '');
|
||
if (!/127\.0\.0\.1|localhost/.test(url)) {
|
||
throw new Error(`拒绝执行:DATABASE_URL 不是本地库(${url.replace(/:[^:@]*@/, ':***@')})`);
|
||
}
|
||
}
|
||
|
||
async function main() {
|
||
assertLocalDb();
|
||
const client = await pool.connect();
|
||
const ctx: TenantContext = {
|
||
userId: USER_ID,
|
||
roles: ['admin'],
|
||
permissions: [],
|
||
branchCode: BRANCH,
|
||
supplierCode: null,
|
||
purchaserCode: null,
|
||
isSuperAdmin: true,
|
||
isBranchAdmin: false,
|
||
isInternalStaff: true,
|
||
isSupplierAccount: false,
|
||
};
|
||
|
||
try {
|
||
await client.query('BEGIN');
|
||
await client.query(`SELECT set_config('search_path', $1, true)`, [`${SCHEMA}, public`]);
|
||
|
||
// ---- 造数据:1 单 + 11 张子表各 1 行 ----
|
||
await client.query(
|
||
`INSERT INTO orders (order_code, cycle_code, bid_code, order_status, branch_code, customer_code,
|
||
total_amount, delivery_date, deleted_at)
|
||
VALUES ($1, '', '', 20, $2, 'SYNTH-CUST', 0, CURRENT_DATE, NOW())`,
|
||
[CODE, BRANCH]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO order_items (id, order_code, sku_code, item_name, quantity, price, amount)
|
||
VALUES ($1, $2, 'SYNTH-SKU', '合成测试品', 1, 1, 1)`,
|
||
[ITEM_ID, CODE]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO order_item_fulfillments (order_item_id, order_code, inventory_cover_qty) VALUES ($1, $2, 1)`,
|
||
[ITEM_ID, CODE]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO order_item_returns (return_code, order_code, order_item_id, stock_action) VALUES ('SYNTH-RET', $1, $2, 'none')`,
|
||
[CODE, ITEM_ID]
|
||
);
|
||
// picking_tasks 先插:picking_items.pick_code 有 FK → picking_tasks(pick_code)
|
||
await client.query(`INSERT INTO picking_tasks (pick_code, order_code) VALUES ('SYNTH-PICK', $1)`, [CODE]);
|
||
await client.query(
|
||
`INSERT INTO picking_items (order_code, pick_code, required_qty, picked_qty, review_status, loaded_qty, picked_weight, loading_photos)
|
||
VALUES ($1, 'SYNTH-PICK', 1, 1, 30, 1, 1, ARRAY[]::text[])`,
|
||
[CODE]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO picking_containers (container_code, order_code) VALUES ('SYNTH-CONT', $1)`,
|
||
[CODE]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO inventory_reservations (order_item_id, order_code, sku_code, qty) VALUES ($1, $2, 'SYNTH-SKU', 1)`,
|
||
[ITEM_ID, CODE]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO bid_rounds (round_code, cycle_mode, scope_type, order_code) VALUES ('SYNTH-RND', 'per_order', 'category', $1)`,
|
||
[CODE]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO supplier_prep_amend_requests (preparation_id, proposed_price, order_code) VALUES ($1, 1, $2)`,
|
||
[PREP_ID, CODE]
|
||
);
|
||
// 台账:验收入库流水(这是「必须留下」的那一行)
|
||
await client.query(
|
||
`INSERT INTO inventory_logs (sku_code, batch_no, operation_type, quantity, before_qty, after_qty, related_order_code)
|
||
VALUES ('SYNTH-SKU', 'SYNTH-BATCH', 'inspection_in', 1, 0, 1, $1)`,
|
||
[CODE]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO notifications (user_id, notify_type, title, content, related_order_code)
|
||
VALUES ($1, 'delivery_task_created', '合成', '合成', $2)`,
|
||
[USER_ID, CODE]
|
||
);
|
||
|
||
const countAll = async (): Promise<Array<{ label: string; table: string; before: number; after: number }>> => {
|
||
const out: Array<{ label: string; table: string; before: number; after: number }> = [];
|
||
for (const [table, where] of [...SHOULD_BE_CLEARED, ...SHOULD_BE_KEPT]) {
|
||
const r = await client.query(`SELECT count(*)::int AS n FROM ${table} WHERE ${where}`);
|
||
out.push({ label: table, table, before: r.rows[0].n, after: -1 });
|
||
}
|
||
return out;
|
||
};
|
||
|
||
const rows = await countAll();
|
||
|
||
// ---- 调真正的服务 ----
|
||
const result = await deleteOrderWithDependencies(CODE, ctx, client, { requireTrashed: false });
|
||
|
||
for (const row of rows) {
|
||
const r = await client.query(`SELECT count(*)::int AS n FROM ${row.table} WHERE ${
|
||
[...SHOULD_BE_CLEARED, ...SHOULD_BE_KEPT].find(([t]) => t === row.table)![1]
|
||
}`);
|
||
row.after = r.rows[0].n;
|
||
}
|
||
const orderLeft = await client.query(`SELECT count(*)::int AS n FROM orders WHERE order_code = $1`, [CODE]);
|
||
|
||
console.log('\n=== 场景:tenant_br004 合成 1 单 + 11 张子表各 1 行,硬删后 ===\n');
|
||
console.log('表'.padEnd(34), '删除前', '删除后', '判定');
|
||
let failed = 0;
|
||
for (const row of rows) {
|
||
const shouldKeep = SHOULD_BE_KEPT.some(([t]) => t === row.table);
|
||
const ok = shouldKeep ? row.after === 1 : row.after === 0;
|
||
if (!ok) failed += 1;
|
||
console.log(
|
||
row.label.padEnd(34),
|
||
String(row.before).padStart(6),
|
||
String(row.after).padStart(6),
|
||
ok ? (shouldKeep ? '✅ 保留(台账)' : '✅ 已清') : shouldKeep ? '❌ 被误删' : '❌ 仍留孤儿'
|
||
);
|
||
}
|
||
console.log('\norders 剩余行数:', orderLeft.rows[0].n, orderLeft.rows[0].n === 0 ? '✅ 已硬删' : '❌');
|
||
console.log('deleted_related(服务返回):');
|
||
for (const [k, v] of Object.entries(result.deleted_related).sort()) {
|
||
if (v > 0) console.log(' ', k, '=', v);
|
||
}
|
||
console.log('\n结论:', failed === 0 ? 'PASS' : `FAIL(${failed} 张表不符合预期)`);
|
||
} finally {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
client.release();
|
||
// 清掉 writeAuditLog 落在事务外的审计行(它走独立连接,ROLLBACK 管不到)
|
||
try {
|
||
await pool.query(`DELETE FROM ${SCHEMA}.operation_logs WHERE operation_type = 'order_purge' AND target_id = $1`, [CODE]);
|
||
} catch (error: any) {
|
||
console.warn('清理合成审计行失败(可手动删):', error?.message);
|
||
}
|
||
const residue = await pool.query(`SELECT count(*)::int AS n FROM ${SCHEMA}.orders WHERE order_code = $1`, [CODE]);
|
||
console.log('回滚后残留订单行数:', residue.rows[0].n, residue.rows[0].n === 0 ? '(无残留)' : '⚠️ 有残留');
|
||
await pool.end();
|
||
}
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error);
|
||
process.exit(1);
|
||
});
|