diff --git a/migrations/20261066_quote_sheet_idempotency.sql b/migrations/20261066_quote_sheet_idempotency.sql new file mode 100644 index 0000000..65bf859 --- /dev/null +++ b/migrations/20261066_quote_sheet_idempotency.sql @@ -0,0 +1,13 @@ +-- 报价单批量建单的幂等键(2026-10-19 开发者裁决 (c)) +-- 目的:勾 N 个客户一次新建 N 张,客户端重试/双击时用同一 Idempotency-Key 直接返回上次结果,不重复建单。 +-- 纪律:只做 DDL;不含数据修复。 +CREATE TABLE IF NOT EXISTS public.quote_sheet_idempotency ( + branch_code text NOT NULL, + idem_key text NOT NULL, + request_hash text NOT NULL, + response_json jsonb, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (branch_code, idem_key) +); +CREATE INDEX IF NOT EXISTS idx_quote_sheet_idempotency_created_at + ON public.quote_sheet_idempotency (created_at); diff --git a/server/src/modules/workflow/routes/quoteRoutes.ts b/server/src/modules/workflow/routes/quoteRoutes.ts index 05f60f2..2eb0320 100644 --- a/server/src/modules/workflow/routes/quoteRoutes.ts +++ b/server/src/modules/workflow/routes/quoteRoutes.ts @@ -1,4 +1,5 @@ import { Router, Response } from 'express'; +import { createHash } from 'node:crypto'; import { authMiddleware, type AuthRequest } from '../../../middleware/auth'; import { getEffectiveBranchCode, readOperatingBranchCode } from '../../../services/tenantScope'; import { getWorkflowCtx, requireWorkflowPermission } from '../context'; @@ -38,24 +39,72 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon markup_ratio: item.markup_ratio == null ? null : Number(item.markup_ratio), sku_name: item.sku_name ? String(item.sku_name) : undefined, })); - const created: any[] = []; - for (const customerCode of targetCustomerCodes) { - const sheet = await createQuoteSheet({ - title: req.body?.title ? String(req.body.title) : undefined, - autoSalePriceByCost: req.body?.auto_sale_price_by_cost === undefined - ? undefined - : req.body.auto_sale_price_by_cost === true, - customerCodes: [customerCode], - items: normalizedItems, - quoteCycle: req.body?.quote_cycle ? String(req.body.quote_cycle) : undefined, - effectiveAt: req.body?.effective_at ? String(req.body.effective_at) : undefined, - createdBy: req.userId, - ctx, - operatingBranchCode: operatingBranch, - }); - created.push(sheet); + /** + * (b) 批内失败不整体回滚:逐客户 try/catch,返回「已建 / 失败」两份清单; + * (c) 幂等:请求头 `Idempotency-Key` + 该分公司幂等表,重试直接返回上次结果(不重复建单)。 + */ + const idemKey = String(req.header('Idempotency-Key') || req.body?.idempotency_key || '').trim(); + const requestHash = createHash('sha256') + .update(JSON.stringify({ targetCustomerCodes, items: normalizedItems, title: req.body?.title ?? null, cycle: req.body?.quote_cycle ?? null, effectiveAt: req.body?.effective_at ?? null })) + .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) { + return res.status(409).json({ error: 'idempotency_conflict', error_description: '相同幂等键但请求内容不同,请更换幂等键' }); + } + return res.json(row.response_json); + } } - return res.json({ data: created[0] ?? null, sheets: created, created_count: created.length }); + + const created: any[] = []; + const failed: Array<{ customer_code: string; error: string }> = []; + for (const customerCode of targetCustomerCodes) { + try { + const sheet = await createQuoteSheet({ + title: req.body?.title ? String(req.body.title) : undefined, + autoSalePriceByCost: req.body?.auto_sale_price_by_cost === undefined + ? undefined + : req.body.auto_sale_price_by_cost === true, + customerCodes: [customerCode], + items: normalizedItems, + quoteCycle: req.body?.quote_cycle ? String(req.body.quote_cycle) : undefined, + effectiveAt: req.body?.effective_at ? String(req.body.effective_at) : undefined, + createdBy: req.userId, + ctx, + operatingBranchCode: operatingBranch, + }); + created.push(sheet); + } catch (itemError: any) { + failed.push({ customer_code: customerCode, error: String(itemError?.message || itemError) }); + } + } + + const payload = { + data: created[0] ?? null, + sheets: created, + created_count: created.length, + 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 (!created.length && failed.length) { + return res.status(500).json({ error: 'all_failed', error_description: '全部客户建单失败', failed }); + } + return res.json(payload); } catch (error: any) { return res.status(error?.status || 500).json({ error: 'server_error', error_description: error?.message || '创建报价单失败' }); } diff --git a/server/tests/quoteSplitByCustomer.test.ts b/server/tests/quoteSplitByCustomer.test.ts index e5cb48d..c24c324 100644 --- a/server/tests/quoteSplitByCustomer.test.ts +++ b/server/tests/quoteSplitByCustomer.test.ts @@ -13,6 +13,7 @@ const H = vi.hoisted(() => ({ createQuoteSheet: vi.fn(), applyEdit: vi.fn(), poolQuery: vi.fn(), + idemStore: new Map(), })); vi.mock('../src/middleware/auth', () => ({ @@ -93,8 +94,18 @@ beforeEach(() => { })); H.applyEdit.mockResolvedValue({ data: { quote_sheet_code: 'QS-A', items: [{ sku_code: 'SKU1', sale_price: 10, cost_price: 6 }] }, delivery_handoff: null }); // 默认:客户名下一律没有报价单 - H.poolQuery.mockImplementation(async (sql: string) => { + H.idemStore.clear(); + H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => { const text = String(sql); + if (text.includes('FROM public.quote_sheet_idempotency')) { + const key = `${params[0]}::${params[1]}`; + const hit = H.idemStore.get(key); + return { rows: hit ? [hit] : [], rowCount: hit ? 1 : 0 }; + } + if (text.includes('INSERT INTO public.quote_sheet_idempotency')) { + H.idemStore.set(`${params[0]}::${params[1]}`, { request_hash: params[2], response_json: JSON.parse(String(params[3])) }); + return { rows: [], rowCount: 1 }; + } if (text.includes('FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1')) { return { rows: [{ customer_code: 'CUS-A' }], rowCount: 1 }; } @@ -178,3 +189,32 @@ describe('编辑:本单客户不变;追加的客户按本单模板新建', ( expect(res.body.created_count).toBe(0); }); }); + +describe('(b) 批内失败 / (c) 幂等键', () => { + it('第 2 个客户建单失败 ⇒ 200,返回已建 1 张 + 失败 1 条(不整体回滚)', async () => { + let call = 0; + H.createQuoteSheet.mockImplementation(async (input: any) => { + call += 1; + if (call === 2) throw new Error('客户不存在'); + return { quote_sheet_code: `QS-${input.customerCodes[0]}`, items: [] }; + }); + const res = await request(app) + .post('/api/workflow/quote/sheet') + .send({ customer_codes: ['CUS-A', 'CUS-B'], items: [ITEM] }); + expect(res.status).toBe(200); + expect(res.body.created_count).toBe(1); + expect(res.body.failed_count).toBe(1); + expect(res.body.failed[0].customer_code).toBe('CUS-B'); + }); + + it('同一 Idempotency-Key 重试 ⇒ 直接返回上次结果,不重复建单', async () => { + const payload = { customer_codes: ['CUS-A', 'CUS-B'], items: [ITEM] }; + const first = await request(app).post('/api/workflow/quote/sheet').set('Idempotency-Key', 'K1').send(payload); + expect(first.status).toBe(200); + const callsAfterFirst = H.createQuoteSheet.mock.calls.length; + const second = await request(app).post('/api/workflow/quote/sheet').set('Idempotency-Key', 'K1').send(payload); + expect(second.status).toBe(200); + expect(H.createQuoteSheet.mock.calls.length).toBe(callsAfterFirst); + expect(second.body.created_count).toBe(first.body.created_count); + }); +});