From bb8acfc0baffd78780f649520ec790ca586661e9 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 19 Oct 2026 18:09:30 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E6=8A=A5=E4=BB=B7=E5=8D=95):=20=E4=BF=AE?= =?UTF-8?q?=E7=BA=A2=E9=98=9F=E4=BA=8C=E8=BD=AE=E9=AB=98=E5=8D=B1=E2=80=94?= =?UTF-8?q?=E2=80=94=E6=8B=86=E5=8D=95=E9=A2=84=E6=A3=80=E6=8E=92=E9=99=A4?= =?UTF-8?q?=E6=BA=90=E5=8D=95(=E9=98=B2=E9=9D=99=E9=BB=98=E5=88=A0?= =?UTF-8?q?=E5=AE=A2=E6=88=B7)=E3=80=81=E7=89=88=E6=9C=AC=E8=A1=8C?= =?UTF-8?q?=E6=98=BE=E5=BC=8F=E6=8C=82=E6=96=B0=E5=8D=95=E5=8F=B7=E3=80=81?= =?UTF-8?q?=E9=94=81=E9=94=AE=E5=B8=A6=E5=88=86=E5=85=AC=E5=8F=B8=E3=80=81?= =?UTF-8?q?=E5=B9=82=E7=AD=89SQL=E7=A7=BB=E5=85=A5service=E3=80=81?= =?UTF-8?q?=E6=8C=89=E5=BB=BA=E7=AB=8B=E6=97=B6=E9=97=B4=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E9=A6=96=E5=AE=A2=E6=88=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../split-multi-customer-quote-sheets.ts | 15 ++++++----- .../modules/workflow/routes/quoteRoutes.ts | 25 +++++++----------- server/src/services/quoteSheetService.ts | 26 ++++++++++++++++++- server/tests/quoteSplitByCustomer.test.ts | 15 +++++++++++ 4 files changed, 57 insertions(+), 24 deletions(-) diff --git a/server/scripts/split-multi-customer-quote-sheets.ts b/server/scripts/split-multi-customer-quote-sheets.ts index 370de9b..5e9fb18 100644 --- a/server/scripts/split-multi-customer-quote-sheets.ts +++ b/server/scripts/split-multi-customer-quote-sheets.ts @@ -72,7 +72,7 @@ async function findMultiCustomerSheets(client: any, schema: string): Promise( `SELECT customer_code FROM ${schema}.customer_quote_sheet_customers - WHERE quote_sheet_code = $1 ORDER BY customer_code`, + 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 }>( @@ -151,11 +151,12 @@ async function main() { * 红队 #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 LIMIT 1`, - [extra] + 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}:名下已有生效报价单`); @@ -188,17 +189,17 @@ async function main() { 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') + 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, ${vList}) - SELECT 'QV' || to_char(now(), 'YYYYMMDDHH24MISS') || substr(md5(random()::text), 1, 6), ${vList} + `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] + [row.code, extra, nextCode] ); // 强制生效 + 互斥该客户其它生效单 await client.query( diff --git a/server/src/modules/workflow/routes/quoteRoutes.ts b/server/src/modules/workflow/routes/quoteRoutes.ts index 2eb0320..6021ffd 100644 --- a/server/src/modules/workflow/routes/quoteRoutes.ts +++ b/server/src/modules/workflow/routes/quoteRoutes.ts @@ -49,18 +49,14 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon .digest('hex'); let idemClient: any = null; if (idemKey) { - const { pool } = await import('../../../db'); - idemClient = pool; - const existing = await pool.query( - `SELECT request_hash, response_json FROM public.quote_sheet_idempotency WHERE branch_code = $1 AND idem_key = $2`, - [operatingBranch || '', idemKey] - ); - if (existing.rowCount) { - const row = existing.rows[0] as { request_hash: string; response_json: any }; - if (row.request_hash !== requestHash) { + const { readQuoteSheetIdempotency } = await import('../../../services/quoteSheetService'); + idemClient = true; + const existing = await readQuoteSheetIdempotency({ branchCode: operatingBranch || '', idemKey }); + if (existing) { + if (existing.request_hash !== requestHash) { return res.status(409).json({ error: 'idempotency_conflict', error_description: '相同幂等键但请求内容不同,请更换幂等键' }); } - return res.json(row.response_json); + return res.json(existing.response_json as any); } } @@ -94,12 +90,9 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon failed_count: failed.length, failed, }; - if (idemClient && idemKey && (created.length > 0 || failed.length === 0)) { - await idemClient.query( - `INSERT INTO public.quote_sheet_idempotency (branch_code, idem_key, request_hash, response_json) - VALUES ($1, $2, $3, $4::jsonb) ON CONFLICT (branch_code, idem_key) DO NOTHING`, - [operatingBranch || '', idemKey, requestHash, JSON.stringify(payload)] - ); + if (idemClient && idemKey) { + const { writeQuoteSheetIdempotency } = await import('../../../services/quoteSheetService'); + await writeQuoteSheetIdempotency({ branchCode: operatingBranch || '', idemKey, requestHash, response: payload }); } if (!created.length && failed.length) { return res.status(500).json({ error: 'all_failed', error_description: '全部客户建单失败', failed }); diff --git a/server/src/services/quoteSheetService.ts b/server/src/services/quoteSheetService.ts index 5dd42b9..11d8003 100644 --- a/server/src/services/quoteSheetService.ts +++ b/server/src/services/quoteSheetService.ts @@ -195,6 +195,30 @@ export async function resolveEditCustomerSplit(input: { }; } +/** 读取幂等记录(routeLayerBoundary:路由层禁止裸 SQL,故放 service) */ +export async function readQuoteSheetIdempotency(input: { branchCode: string; idemKey: string }) { + const { rows } = await pool.query<{ request_hash: string; response_json: unknown }>( + `SELECT request_hash, response_json FROM public.quote_sheet_idempotency + WHERE branch_code = $1 AND idem_key = $2`, + [input.branchCode || '', input.idemKey] + ); + return rows[0] ?? null; +} + +/** 写入幂等记录(同 key 并发时 ON CONFLICT DO NOTHING,先写者胜) */ +export async function writeQuoteSheetIdempotency(input: { + branchCode: string; + idemKey: string; + requestHash: string; + response: unknown; +}) { + await pool.query( + `INSERT INTO public.quote_sheet_idempotency (branch_code, idem_key, request_hash, response_json) + VALUES ($1, $2, $3, $4::jsonb) ON CONFLICT (branch_code, idem_key) DO NOTHING`, + [input.branchCode || '', input.idemKey, input.requestHash, JSON.stringify(input.response)] + ); +} + export async function createQuoteSheet(input: { title?: string; customerCodes: string[]; @@ -229,7 +253,7 @@ export async function createQuoteSheet(input: { */ for (const code of customerCodes) { await client.query(`SELECT pg_advisory_xact_lock(hashtext($1))`, [ - `quote-sheet:${input.branchCode || ''}:${String(code).toUpperCase()}`, + `quote-sheet:${input.branchCode || input.operatingBranchCode || ''}:${String(code).toUpperCase()}`, ]); } await client.query( diff --git a/server/tests/quoteSplitByCustomer.test.ts b/server/tests/quoteSplitByCustomer.test.ts index c24c324..9c7ad4a 100644 --- a/server/tests/quoteSplitByCustomer.test.ts +++ b/server/tests/quoteSplitByCustomer.test.ts @@ -40,6 +40,21 @@ vi.mock('../src/services/tenantScope', async (importOriginal) => { vi.mock('../src/services/quoteSheetService', () => ({ createQuoteSheet: (...args: unknown[]) => H.createQuoteSheet(...args), + // 幂等读写也在 service(红队 #10:路由层禁止裸 SQL) + readQuoteSheetIdempotency: async (input: { branchCode: string; idemKey: string }) => { + return H.idemStore.get(`${input.branchCode}::${input.idemKey}`) ?? null; + }, + writeQuoteSheetIdempotency: async (input: { + branchCode: string; + idemKey: string; + requestHash: string; + response: unknown; + }) => { + H.idemStore.set(`${input.branchCode}::${input.idemKey}`, { + request_hash: input.requestHash, + response_json: input.response, + }); + }, // 真实实现在 service 里(路由不再裸 SQL);测试里用同一套 SQL 断言脚本复刻 resolveEditCustomerSplit: async (input: { quoteSheetCode: string; requestedCustomerCodes: string[] }) => { const ownRes = await H.poolQuery(