From 82bc0af32fddf3e1a2b1d17d853fceecd18ade23 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 19 Oct 2026 17:38:59 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E6=8A=A5=E4=BB=B7=E5=8D=95=E6=8B=86?= =?UTF-8?q?=E5=88=86):=20=E4=BF=AE=20verifier=20=E9=98=BB=E6=96=AD?= =?UTF-8?q?=E9=A1=B9=E2=80=94=E2=80=94=E5=90=8E=E7=AB=AF=20tsc=20=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E3=80=81=E7=BC=96=E8=BE=91=E5=8F=AA=E5=9B=9E=E4=BC=A0?= =?UTF-8?q?=E6=9C=AC=E5=8D=95=E5=AE=A2=E6=88=B7=EF=BC=88=E9=98=B2=E6=9C=AC?= =?UTF-8?q?=E5=8D=95=E5=8F=98=E5=A4=9A=E5=AE=A2=E6=88=B7/=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0=E5=AE=A2=E6=88=B7=E6=8C=82=E4=B8=A4=E5=BC=A0=E5=8D=95?= =?UTF-8?q?=EF=BC=89=E3=80=81=E6=8B=86=E5=88=86=E8=84=9A=E6=9C=AC=E6=8E=92?= =?UTF-8?q?=E9=99=A4=E4=B8=BB=E9=94=AE=E5=B9=B6=E6=94=B9=E6=8F=90=E4=BA=A4?= =?UTF-8?q?=E5=90=8E=E8=AE=A1=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../split-multi-customer-quote-sheets.ts | 268 ++++++++++-------- .../modules/workflow/routes/quoteRoutes.ts | 28 +- server/tests/quoteSplitByCustomer.test.ts | 3 + 3 files changed, 171 insertions(+), 128 deletions(-) diff --git a/server/scripts/split-multi-customer-quote-sheets.ts b/server/scripts/split-multi-customer-quote-sheets.ts index 2a8c17d..4bccb2a 100644 --- a/server/scripts/split-multi-customer-quote-sheets.ts +++ b/server/scripts/split-multi-customer-quote-sheets.ts @@ -1,160 +1,184 @@ /** - * 老数据拆分:把「一张报价单挂多个客户」的存量数据拆成「一客户一单」。 + * 老数据拆分:把「一张报价单挂多个客户」拆成「一客户一单」(2026-10-19 开发者裁决)。 * - * 背景(2026-10-19 开发者裁决):报价单从「一单可多客户」改为「一客户一单」。 - * 新建/编辑已按新口径实现;本脚本处理**存量**: - * · 原单**保留第一个客户**(按关联表建立顺序); - * · 其余每个客户各生成一张新单(新单号、生效),明细/价格/周期/生效日与原单一致。 + * 规则: + * · 原单**保留第一个客户**(按关联表顺序); + * · 其余每个客户各生成一张新单(新单号、整行复制单头与明细),生效状态沿用原单; + * · 幂等:拆完后每个 quote_sheet_code 只剩 1 个客户,再跑不会重复建单。 * - * 用法: - * 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 + * 用法(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 # 只处理某分公司 * - * 纪律: - * · dry-run 不发任何写 SQL; - * · --execute 前请先备份;脚本按单张事务执行,单张失败不影响其它; - * · 幂等:拆完后每个 quote_sheet_code 只剩 1 个客户,再跑一次不会产生新单。 + * ⚠️ 本库业务表启用 **RLS**:不带 `app.branch_code` 时查询恒为 0 行(2026-10-18 实测)。 + * 所以所有查询/写入都必须在 `withTenant()` 内执行。 */ 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() : ''; +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` + `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( - `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] : [] +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 customer_code`, + [sheet.quote_sheet_code] ); - 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(); - } - } + 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, + }); } - console.log(`\n执行完成:新建 ${created} 张,失败 ${failed} 张`); + return out; } async function main() { const schemas = await tenantSchemas(); let multiSheets = 0; - let willSplitCustomers = 0; + let willCreate = 0; for (const schema of schemas) { - const { rows: sheets } = await pool.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] : [] - ); - 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); + 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; - willSplitCustomers += extras.length; + willCreate += r.customers.length - 1; console.log( - ` ${sheet.quote_sheet_code} | 客户 ${customers.length}(${customers.map((c) => c.customer_code).join(', ')})` + - ` | 明细 ${items[0]?.n ?? 0} 行 | 保留 ${keep} | 将为 ${extras.join(', ') || '-'} 各建一张` + ` ${r.code} | 客户 ${r.customers.length}(${r.customers.join(', ')}) | 明细 ${r.items} 行 | 保留 ${r.customers[0]} | 将新建 ${r.customers.length - 1} 张` ); } } - console.log( - `\n汇总:一单多客户 ${multiSheets} 张;预计新建 ${willSplitCustomers} 张;模式=${execute ? 'EXECUTE(会写库)' : 'DRY-RUN(只读)'}` - ); - if (execute) { - await runExecute(schemas); + console.log(`\n汇总:一单多客户 ${multiSheets} 张;预计新建 ${willCreate} 张;模式=${execute ? 'EXECUTE' : 'DRY-RUN(只读)'}`); + + if (!execute) { + await pool.end(); + return; } + + let created = 0; + let failed = 0; + for (const schema of schemas) { + const createdThisSchema: string[] = []; + await withTenant(schema, async (client) => { + const rows = await findMultiCustomerSheets(client, schema); + for (const row of rows) { + try { + 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(', '); + for (const extra of row.customers.slice(1)) { + // 单号防撞:生成后先查重(撞了就再生成),避免 pkey 冲突 + 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] + ); + createdThisSchema.push(` [${schema}] ${row.code} → 新单 ${nextCode}(客户 ${extra})`); + } + await client.query( + `DELETE FROM ${schema}.customer_quote_sheet_customers + WHERE quote_sheet_code = $1 AND customer_code <> $2`, + [row.code, row.customers[0]] + ); + } catch (error: any) { + failed += 1; + console.error(` ❌ ${row.code} 失败:${error?.message || error}`); + } + } + return null; + }); + // 只有整个 schema 事务提交成功后才计入(回滚不虚报) + created += createdThisSchema.length; + for (const line of createdThisSchema) console.log(line); + } + console.log(`\n执行完成:新建 ${created} 张,失败 ${failed} 张`); await pool.end(); } diff --git a/server/src/modules/workflow/routes/quoteRoutes.ts b/server/src/modules/workflow/routes/quoteRoutes.ts index 21c14ad..a7acab1 100644 --- a/server/src/modules/workflow/routes/quoteRoutes.ts +++ b/server/src/modules/workflow/routes/quoteRoutes.ts @@ -12,8 +12,8 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon const operatingBranch = readOperatingBranchCode(req); requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']); const { createQuoteSheet } = await import('../../../services/quoteSheetService'); - const customerCodes = Array.isArray(req.body?.customer_codes) - ? req.body.customer_codes.map(String) + const customerCodes: string[] = Array.isArray(req.body?.customer_codes) + ? (req.body.customer_codes as unknown[]).map((c) => String(c)) : req.body?.customer_code ? [String(req.body.customer_code)] : []; @@ -23,7 +23,9 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon * 新建时勾了 N 个客户 ⇒ 逐张新建 N 张(各取新单号),不再是 1 张挂 N 个客户。 * 明细/价格/周期/生效日全部复制;每张都走 activate 生效。 */ - const targetCustomerCodes = Array.from(new Set(customerCodes.map((c) => String(c || '').trim()).filter(Boolean))); + const targetCustomerCodes: string[] = Array.from( + new Set(customerCodes.map((c: string) => c.trim()).filter((c: string) => Boolean(c))) + ); if (targetCustomerCodes.length === 0) { return res.status(400).json({ error: 'invalid_request', error_description: '请选择客户' }); } @@ -105,8 +107,14 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res: const operatingBranch = readOperatingBranchCode(req); requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']); const { applyQuoteSheetEditAndRequestDeliveryReview } = await import('../../../services/quoteSheetEditService'); - const rawCustomerCodes = Array.isArray(req.body?.customer_codes) - ? Array.from(new Set(req.body.customer_codes.map((c: unknown) => String(c || '').trim()).filter(Boolean))) + const rawCustomerCodes: string[] | undefined = Array.isArray(req.body?.customer_codes) + ? Array.from( + new Set( + req.body.customer_codes + .map((c: unknown) => String(c || '').trim()) + .filter((c: string) => Boolean(c)) + ) + ) : undefined; /** * 2026-10-19 开发者裁决(编辑阶段): @@ -115,6 +123,8 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res: * · 追加的客户若名下**已有**报价单 ⇒ 拒绝(请去编辑它自己那张,避免一份数据两个来源)。 */ let customersToCreate: string[] = []; + /** 本单当前挂的客户(编辑时必须原样回传,保证"本单客户不变") */ + let ownCustomerCodes: string[] | undefined; if (rawCustomerCodes && rawCustomerCodes.length) { const { pool } = await import('../../../db'); const current = await pool.query<{ customer_code: string }>( @@ -122,6 +132,7 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res: [req.params.code] ); const currentCodes = new Set(current.rows.map((r) => String(r.customer_code))); + ownCustomerCodes = Array.from(currentCodes); const extra = rawCustomerCodes.filter((c) => !currentCodes.has(c)); if (extra.length) { const taken = await pool.query<{ customer_code: string }>( @@ -137,7 +148,12 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res: customersToCreate = extra; } } - const customerCodes = rawCustomerCodes ? rawCustomerCodes.filter((c) => c) : undefined; + /** + * ⚠️ 只有"本单自己的客户"能传给编辑服务: + * 若把「本单客户 + 追加客户」一起传下去,updateQuoteSheet 会把本单改成多客户, + * 同时又给追加客户另建一张 ⇒ 该客户挂两张生效单(verifier S4/S5 实测阻断项)。 + */ + const customerCodes = ownCustomerCodes; const items = Array.isArray(req.body?.items) ? req.body.items.map((item: any) => ({ sku_code: String(item.sku_code || ''), diff --git a/server/tests/quoteSplitByCustomer.test.ts b/server/tests/quoteSplitByCustomer.test.ts index 6b48f5f..42edd17 100644 --- a/server/tests/quoteSplitByCustomer.test.ts +++ b/server/tests/quoteSplitByCustomer.test.ts @@ -119,6 +119,9 @@ describe('编辑:本单客户不变;追加的客户按本单模板新建', ( expect(res.status).toBe(200); expect(H.applyEdit).toHaveBeenCalledTimes(1); + // ⚠️ 钉住 verifier S4/S5 阻断项:编辑服务只能收到**本单自己的客户**; + // 若把追加客户也传下去,本单会被改成多客户、且追加客户会挂两张生效单。 + expect((H.applyEdit.mock.calls[0][0] as any).customerCodes).toEqual(['CUS-A']); expect(H.createQuoteSheet).toHaveBeenCalledTimes(1); expect((H.createQuoteSheet.mock.calls[0][0] as any).customerCodes).toEqual(['CUS-B']); expect(res.body.created_count).toBe(1);