/** * 老数据拆分:把「一张报价单挂多个客户」拆成「一客户一单」(2026-10-19 开发者裁决)。 * * 规则: * · 原单**保留第一个客户**(按关联表顺序); * · 其余每个客户各生成一张新单(新单号、整行复制单头与明细),生效状态沿用原单; * · 幂等:拆完后每个 quote_sheet_code 只剩 1 个客户,再跑不会重复建单。 * * 用法(npx 在本机会撞 npm 缓存权限,直接用仓库里的 tsx 二进制): * server/node_modules/.bin/tsx --env-file=server/.env server/scripts/split-multi-customer-quote-sheets.ts # dry-run(默认,只读) * server/node_modules/.bin/tsx --env-file=server/.env server/scripts/split-multi-customer-quote-sheets.ts --execute # 真正执行 * ... --branch BR002 # 只处理某分公司 * * ⚠️ 本库业务表启用 **RLS**:不带 `app.branch_code` 时查询恒为 0 行(2026-10-18 实测)。 * 所以所有查询/写入都必须在 `withTenant()` 内执行。 */ import { pool } from '../dist/db'; import { newSheetCode } from '../dist/services/quoteSheetService'; const argv = process.argv.slice(2); const execute = argv.includes('--execute'); const branchArgIdx = argv.indexOf('--branch'); const branchFilter = branchArgIdx >= 0 ? String(argv[branchArgIdx + 1] || '').trim() : ''; type SheetRow = { quote_sheet_code: string; branch_code: string; title: string | null }; type MultiSheet = { code: string; customers: string[]; items: number }; /** tenant_br002 → BR002;legacy_public / tenant_template 跳过 */ function branchOfSchema(schema: string): string | null { const m = /^tenant_(br\d+)$/i.exec(schema); return m ? m[1].toUpperCase() : null; } /** 在租户上下文里执行(RLS 必需) */ async function withTenant(schema: string, fn: (client: any) => Promise): Promise { const branch = branchOfSchema(schema); if (!branch) return null; const client = await pool.connect(); try { await client.query('BEGIN'); await client.query(`SELECT set_config('app.branch_code', $1, true)`, [branch]); const out = await fn(client); await client.query('COMMIT'); return out; } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); } } async function tenantSchemas(): Promise { const { rows } = await pool.query<{ schema_name: string }>( `SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE 'tenant_%' AND schema_name <> 'tenant_template' ORDER BY 1` ); return rows.map((r) => r.schema_name); } async function findMultiCustomerSheets(client: any, schema: string): Promise { const { rows: sheets } = await client.query( `SELECT s.quote_sheet_code, s.branch_code, s.title FROM ${schema}.customer_quote_sheets s WHERE (SELECT count(*) FROM ${schema}.customer_quote_sheet_customers c WHERE c.quote_sheet_code = s.quote_sheet_code) > 1 ${branchFilter ? 'AND s.branch_code = $1' : ''} ORDER BY s.quote_sheet_code`, branchFilter ? [branchFilter] : [] ); const out: MultiSheet[] = []; for (const sheet of sheets) { const { rows: customers } = await client.query<{ customer_code: string }>( `SELECT customer_code FROM ${schema}.customer_quote_sheet_customers WHERE quote_sheet_code = $1 ORDER BY created_at NULLS LAST, customer_code`, [sheet.quote_sheet_code] ); const { rows: items } = await client.query<{ n: number }>( `SELECT count(*)::int AS n FROM ${schema}.customer_quote_sheet_items WHERE quote_sheet_code = $1`, [sheet.quote_sheet_code] ); out.push({ code: sheet.quote_sheet_code, customers: customers.map((c) => c.customer_code), items: items[0]?.n ?? 0, }); } return out; } async function main() { const schemas = await tenantSchemas(); let multiSheets = 0; let willCreate = 0; for (const schema of schemas) { const rows = await withTenant(schema, (client) => findMultiCustomerSheets(client, schema)); if (!rows || !rows.length) continue; console.log(`\n[${schema}] 一单多客户:${rows.length} 张`); for (const r of rows) { multiSheets += 1; willCreate += r.customers.length - 1; console.log( ` ${r.code} | 客户 ${r.customers.length}(${r.customers.join(', ')}) | 明细 ${r.items} 行 | 保留 ${r.customers[0]} | 将新建 ${r.customers.length - 1} 张` ); } } console.log(`\n汇总:一单多客户 ${multiSheets} 张;预计新建 ${willCreate} 张;模式=${execute ? 'EXECUTE' : 'DRY-RUN(只读)'}`); if (!execute) { await pool.end(); return; } let created = 0; let failed = 0; /** * 每张单**独立事务**(verifier S7):原来按 schema 一个事务, * 内层失败会 abort 整个事务 ⇒ 后续每张都 25P02 失败、COMMIT 实为 ROLLBACK 却仍计数。 */ for (const schema of schemas) { const branch = branchOfSchema(schema); if (!branch) continue; // 先用只读事务列出待拆单 const rows = (await withTenant(schema, (client) => findMultiCustomerSheets(client, schema))) || []; for (const row of rows) { const client = await pool.connect(); try { await client.query('BEGIN'); await client.query(`SELECT set_config('app.branch_code', $1, true)`, [branch]); const { rows: cols } = await client.query<{ column_name: string }>( `SELECT column_name FROM information_schema.columns WHERE table_schema = $1 AND table_name = 'customer_quote_sheets' AND column_name NOT IN ('quote_sheet_code', 'id', 'created_at', 'updated_at') ORDER BY ordinal_position`, [schema] ); const colList = cols.map((c) => `"${c.column_name}"`).join(', '); const { rows: itemCols } = await client.query<{ column_name: string }>( `SELECT column_name FROM information_schema.columns WHERE table_schema = $1 AND table_name = 'customer_quote_sheet_items' AND column_name NOT IN ('quote_sheet_code', 'id', 'created_at', 'updated_at') ORDER BY ordinal_position`, [schema] ); const itemColList = itemCols.map((c) => `"${c.column_name}"`).join(', '); const createdCodes: string[] = []; for (const extra of row.customers.slice(1)) { /** * 红队 #6(e):该客户名下若已有**生效**报价单,则不再拆出(避免两张生效单)。 * 红队 #6(c):同时复制该客户在版本表里的行并挂到新单,否则新单查不到报价价。 */ // 红队 #13:必须排除源单自身,否则源单 status=1 时每个追加客户都"命中自己"→全部跳过、随后又被删关联(客户彻底失去报价) const active = await client.query( `SELECT 1 FROM ${schema}.customer_quote_sheets s JOIN ${schema}.customer_quote_sheet_customers c ON c.quote_sheet_code = s.quote_sheet_code WHERE c.customer_code = $1 AND s.status = 1 AND s.quote_sheet_code <> $2 LIMIT 1`, [extra, row.code] ); if (active.rowCount) { console.log(` ⚠ 跳过客户 ${extra}:名下已有生效报价单`); continue; } let nextCode = newSheetCode(); for (let attempt = 0; attempt < 20; attempt += 1) { const exists = await client.query( `SELECT 1 FROM ${schema}.customer_quote_sheets WHERE quote_sheet_code = $1`, [nextCode] ); if (!exists.rowCount) break; nextCode = newSheetCode(); } await client.query( `INSERT INTO ${schema}.customer_quote_sheets (quote_sheet_code, ${colList}) SELECT $1, ${colList} FROM ${schema}.customer_quote_sheets WHERE quote_sheet_code = $2`, [nextCode, row.code] ); await client.query( `INSERT INTO ${schema}.customer_quote_sheet_items (quote_sheet_code, ${itemColList}) SELECT $1, ${itemColList} FROM ${schema}.customer_quote_sheet_items WHERE quote_sheet_code = $2`, [nextCode, row.code] ); await client.query( `INSERT INTO ${schema}.customer_quote_sheet_customers (quote_sheet_code, customer_code) VALUES ($1, $2)`, [nextCode, extra] ); // 版本行复制(只复制该客户的行,并改挂到新单) const { rows: vcols } = await client.query<{ column_name: string }>( `SELECT column_name FROM information_schema.columns WHERE table_schema = $1 AND table_name = 'customer_quote_versions' AND column_name NOT IN ('id', 'created_at', 'quote_version_code', 'quote_sheet_code') ORDER BY ordinal_position`, [schema] ); const vList = vcols.map((c) => `"${c.column_name}"`).join(', '); await client.query( `INSERT INTO ${schema}.customer_quote_versions (quote_version_code, quote_sheet_code, ${vList}) SELECT 'QV' || to_char(now(), 'YYYYMMDDHH24MISS') || substr(md5(random()::text), 1, 6), $3, ${vList} FROM ${schema}.customer_quote_versions WHERE quote_sheet_code = $1 AND customer_code = $2`, [row.code, extra, nextCode] ); // 强制生效 + 互斥该客户其它生效单 await client.query( `UPDATE ${schema}.customer_quote_sheets SET status = 1, approval_status = 30, updated_at = NOW() WHERE quote_sheet_code = $1`, [nextCode] ); await client.query( `UPDATE ${schema}.customer_quote_sheets SET status = 3, updated_at = NOW() WHERE status = 1 AND quote_sheet_code <> $1 AND quote_sheet_code <> $3 AND quote_sheet_code IN ( SELECT quote_sheet_code FROM ${schema}.customer_quote_sheet_customers WHERE customer_code = $2 )`, [nextCode, extra, row.code] ); createdCodes.push(`${extra}=${nextCode}`); } await client.query( `DELETE FROM ${schema}.customer_quote_sheet_customers WHERE quote_sheet_code = $1 AND customer_code <> $2`, [row.code, row.customers[0]] ); await client.query('COMMIT'); // 只有真实提交成功才计数 created += createdCodes.length; console.log(` [${schema}] ${row.code} 拆出 ${createdCodes.length} 张:${createdCodes.join(', ')}`); } catch (error: any) { await client.query('ROLLBACK').catch(() => undefined); failed += 1; console.error(` ❌ ${row.code} 失败(已回滚):${error?.message || error}`); } finally { client.release(); } } } console.log(`\n执行完成:新建 ${created} 张,失败 ${failed} 张`); await pool.end(); } main().catch((error) => { console.error('拆分脚本失败:', error?.message || error); process.exit(1); });