Files
SupplierSystem/server/scripts/split-multi-customer-quote-sheets.ts
T
Ubuntu 375a32b6d8
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
feat(报价单+权限): 一客户一单(新建按客户拆分/编辑追加建新单/老数据脚本)+ 角色权限改管理员维护 + 散客改为客户下拉项 + 竞价状态与软删收尾
2026-10-19 17:33:55 +08:00

165 lines
7.4 KiB
TypeScript
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.
/**
* 老数据拆分:把「一张报价单挂多个客户」的存量数据拆成「一客户一单」。
*
* 背景(2026-10-19 开发者裁决):报价单从「一单可多客户」改为「一客户一单」。
* 新建/编辑已按新口径实现;本脚本处理**存量**:
* · 原单**保留第一个客户**(按关联表建立顺序);
* · 其余每个客户各生成一张新单(新单号、生效),明细/价格/周期/生效日与原单一致。
*
* 用法:
* npx tsx server/scripts/split-multi-customer-quote-sheets.ts # dry-run(默认,只读)
* npx tsx server/scripts/split-multi-customer-quote-sheets.ts --execute # 真正执行
* npx tsx server/scripts/split-multi-customer-quote-sheets.ts --branch BR002
*
* 纪律:
* · dry-run 不发任何写 SQL;
* · --execute 前请先备份;脚本按单张事务执行,单张失败不影响其它;
* · 幂等:拆完后每个 quote_sheet_code 只剩 1 个客户,再跑一次不会产生新单。
*/
import { pool } from '../src/db';
import { newSheetCode } from '../src/services/quoteSheetService';
type SheetRow = { quote_sheet_code: string; branch_code: string; title: string | null };
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() : '';
async function tenantSchemas(): Promise<string[]> {
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 runExecute(schemas: string[]) {
let created = 0;
let failed = 0;
for (const schema of schemas) {
const { rows: sheets } = await pool.query<SheetRow>(
`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' : ''}`,
branchFilter ? [branchFilter] : []
);
for (const sheet of sheets) {
const client = await pool.connect();
try {
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 customer_code`,
[sheet.quote_sheet_code]
);
const extras = customers.slice(1).map((c) => c.customer_code);
if (!extras.length) { client.release(); continue; }
// 列清单(去掉主键 code 列),用于整行复制
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 <> 'quote_sheet_code' 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 <> 'quote_sheet_code' ORDER BY ordinal_position`,
[schema]
);
const itemColList = itemCols.map((c) => `"${c.column_name}"`).join(', ');
await client.query('BEGIN');
for (const extra of extras) {
const 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, sheet.quote_sheet_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, sheet.quote_sheet_code]
);
await client.query(
`INSERT INTO ${schema}.customer_quote_sheet_customers (quote_sheet_code, customer_code) VALUES ($1, $2)`,
[nextCode, extra]
);
created += 1;
console.log(` [${schema}] ${sheet.quote_sheet_code} → 新单 ${nextCode}(客户 ${extra})`);
}
// 原单只保留第一个客户
await client.query(
`DELETE FROM ${schema}.customer_quote_sheet_customers
WHERE quote_sheet_code = $1 AND customer_code <> $2`,
[sheet.quote_sheet_code, customers[0].customer_code]
);
await client.query('COMMIT');
} catch (error: any) {
await client.query('ROLLBACK').catch(() => undefined);
failed += 1;
console.error(` ❌ ${sheet.quote_sheet_code} 失败:${error?.message || error}`);
} finally {
client.release();
}
}
}
console.log(`\n执行完成:新建 ${created} 张,失败 ${failed} 张`);
}
async function main() {
const schemas = await tenantSchemas();
let multiSheets = 0;
let willSplitCustomers = 0;
for (const schema of schemas) {
const { rows: sheets } = await pool.query<SheetRow>(
`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] : []
);
if (!sheets.length) continue;
console.log(`\n[${schema}] 一单多客户的报价单:${sheets.length} 张`);
for (const sheet of sheets) {
const { rows: customers } = await pool.query<{ customer_code: string }>(
`SELECT customer_code FROM ${schema}.customer_quote_sheet_customers
WHERE quote_sheet_code = $1 ORDER BY customer_code`,
[sheet.quote_sheet_code]
);
const { rows: items } = await pool.query<{ n: number }>(
`SELECT count(*)::int AS n FROM ${schema}.customer_quote_sheet_items WHERE quote_sheet_code = $1`,
[sheet.quote_sheet_code]
);
const keep = customers[0]?.customer_code || '-';
const extras = customers.slice(1).map((c) => c.customer_code);
multiSheets += 1;
willSplitCustomers += extras.length;
console.log(
` ${sheet.quote_sheet_code} | 客户 ${customers.length}(${customers.map((c) => c.customer_code).join(', ')})` +
` | 明细 ${items[0]?.n ?? 0} 行 | 保留 ${keep} | 将为 ${extras.join(', ') || '-'} 各建一张`
);
}
}
console.log(
`\n汇总:一单多客户 ${multiSheets} 张;预计新建 ${willSplitCustomers} 张;模式=${execute ? 'EXECUTE(会写库)' : 'DRY-RUN(只读)'}`
);
if (execute) {
await runExecute(schemas);
}
await pool.end();
}
main().catch((error) => {
console.error('拆分脚本失败:', error?.message || error);
process.exit(1);
});