237 lines
9.9 KiB
TypeScript
237 lines
9.9 KiB
TypeScript
import express from 'express';
|
||
import request from 'supertest';
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
/**
|
||
* 报价单「一客户一单」(2026-10-19 开发者裁决)路由层契约:
|
||
* · 新建:勾 N 个客户 ⇒ 调 N 次建单(每次 1 个客户),返回 created_count=N;
|
||
* · 编辑:本单客户不变;追加的客户若**名下无报价单** ⇒ 以本单数据为模板建新单;
|
||
* · 编辑:追加的客户若**名下已有报价单** ⇒ 400,且不建任何单。
|
||
*/
|
||
|
||
const H = vi.hoisted(() => ({
|
||
createQuoteSheet: vi.fn(),
|
||
applyEdit: vi.fn(),
|
||
poolQuery: vi.fn(),
|
||
idemStore: new Map<string, any>(),
|
||
}));
|
||
|
||
vi.mock('../src/middleware/auth', () => ({
|
||
authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => {
|
||
req.userId = 'u-1';
|
||
next();
|
||
},
|
||
}));
|
||
|
||
vi.mock('../src/modules/workflow/context', () => ({
|
||
getWorkflowCtx: async () => ({ userId: 'u-1', permissions: ['customer_manage'], branchCode: 'BR002', roles: ['admin'] }),
|
||
requireWorkflowPermission: () => undefined,
|
||
}));
|
||
|
||
vi.mock('../src/services/tenantScope', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/tenantScope')>();
|
||
return {
|
||
...actual,
|
||
readOperatingBranchCode: () => 'BR002',
|
||
getEffectiveBranchCode: () => 'BR002',
|
||
invalidateTenantContextCache: () => undefined,
|
||
};
|
||
});
|
||
|
||
vi.mock('../src/services/quoteSheetService', () => ({
|
||
createQuoteSheet: (...args: unknown[]) => H.createQuoteSheet(...args),
|
||
// 幂等读写也在 service(红队 #10:路由层禁止裸 SQL)
|
||
acquireQuoteSheetIdempotencyLock: async () => ({ release: async () => undefined }),
|
||
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(
|
||
'SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1',
|
||
[input.quoteSheetCode]
|
||
);
|
||
const own = (ownRes.rows || []).map((r: any) => String(r.customer_code));
|
||
const extra = input.requestedCustomerCodes.filter((c) => !own.includes(c));
|
||
if (!extra.length) return { ownCustomerCodes: own, customersToCreate: [], takenCustomerCodes: [] };
|
||
const takenRes = await H.poolQuery(
|
||
'SELECT DISTINCT customer_code FROM customer_quote_sheet_customers WHERE customer_code = ANY($1::text[])',
|
||
[extra]
|
||
);
|
||
const taken = (takenRes.rows || []).map((r: any) => String(r.customer_code));
|
||
return {
|
||
ownCustomerCodes: own,
|
||
customersToCreate: extra.filter((c) => !taken.includes(c)),
|
||
takenCustomerCodes: taken,
|
||
};
|
||
},
|
||
}));
|
||
|
||
vi.mock('../src/services/quoteSheetEditService', () => ({
|
||
applyQuoteSheetEditAndRequestDeliveryReview: (...args: unknown[]) => H.applyEdit(...args),
|
||
}));
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => H.poolQuery(...args) },
|
||
getRawPoolQuery: () => H.poolQuery,
|
||
}));
|
||
|
||
const { mountQuoteWorkflowRoutes } = await import('../src/modules/workflow/routes/quoteRoutes');
|
||
|
||
const app = express();
|
||
app.use(express.json());
|
||
const router = express.Router();
|
||
mountQuoteWorkflowRoutes(router);
|
||
app.use('/api/workflow', router);
|
||
|
||
const ITEM = { sku_code: 'SKU1', sale_price: 10, cost_price: 6 };
|
||
|
||
beforeEach(() => {
|
||
H.createQuoteSheet.mockReset();
|
||
H.applyEdit.mockReset();
|
||
H.poolQuery.mockReset();
|
||
H.createQuoteSheet.mockImplementation(async (input: any) => ({
|
||
quote_sheet_code: `QS-${input.customerCodes[0]}`,
|
||
items: [{ sku_code: 'SKU1', sale_price: 10, cost_price: 6, unit: '斤' }],
|
||
title: input.title ?? null,
|
||
quote_cycle: input.quoteCycle ?? null,
|
||
effective_at: input.effectiveAt ?? null,
|
||
}));
|
||
H.applyEdit.mockResolvedValue({ data: { quote_sheet_code: 'QS-A', items: [{ sku_code: 'SKU1', sale_price: 10, cost_price: 6 }] }, delivery_handoff: null });
|
||
// 默认:客户名下一律没有报价单
|
||
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 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
});
|
||
|
||
describe('新建:勾 N 个客户 ⇒ 生成 N 张(一客户一单)', () => {
|
||
it('3 个客户 ⇒ 调 3 次建单,每次只带 1 个客户,created_count=3', async () => {
|
||
const res = await request(app)
|
||
.post('/api/workflow/quote/sheet')
|
||
.send({ customer_codes: ['CUS-A', 'CUS-B', 'CUS-C'], items: [ITEM] });
|
||
|
||
expect(res.status).toBe(200);
|
||
expect(H.createQuoteSheet).toHaveBeenCalledTimes(3);
|
||
const calls = H.createQuoteSheet.mock.calls.map((c) => (c[0] as any).customerCodes);
|
||
expect(calls).toEqual([['CUS-A'], ['CUS-B'], ['CUS-C']]);
|
||
expect(res.body.created_count).toBe(3);
|
||
});
|
||
|
||
it('1 个客户 ⇒ 只建 1 张,created_count=1', async () => {
|
||
const res = await request(app)
|
||
.post('/api/workflow/quote/sheet')
|
||
.send({ customer_codes: ['CUS-A'], items: [ITEM] });
|
||
expect(res.status).toBe(200);
|
||
expect(H.createQuoteSheet).toHaveBeenCalledTimes(1);
|
||
expect(res.body.created_count).toBe(1);
|
||
});
|
||
|
||
it('一个客户都没选 ⇒ 400,不建单', async () => {
|
||
const res = await request(app).post('/api/workflow/quote/sheet').send({ customer_codes: [], items: [ITEM] });
|
||
expect(res.status).toBe(400);
|
||
expect(H.createQuoteSheet).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('编辑:本单客户不变;追加的客户按本单模板新建', () => {
|
||
it('追加一个名下无报价单的客户 ⇒ 保存本单后,为它建 1 张新单', async () => {
|
||
const res = await request(app)
|
||
.put('/api/workflow/quote/sheets/QS-A')
|
||
.send({ customer_codes: ['CUS-A', 'CUS-B'], items: [ITEM] });
|
||
|
||
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);
|
||
});
|
||
|
||
it('追加的客户名下已有报价单 ⇒ 400,且不建任何单', async () => {
|
||
H.poolQuery.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1')) {
|
||
return { rows: [{ customer_code: 'CUS-A' }], rowCount: 1 };
|
||
}
|
||
// 追加客户查重:CUS-B 已有报价单
|
||
if (text.includes('ANY($1::text[])')) {
|
||
return { rows: [{ customer_code: 'CUS-B' }], rowCount: 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
|
||
const res = await request(app)
|
||
.put('/api/workflow/quote/sheets/QS-A')
|
||
.send({ customer_codes: ['CUS-A', 'CUS-B'], items: [ITEM] });
|
||
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error).toBe('customer_already_quoted');
|
||
expect(H.createQuoteSheet).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('只提交本单自己的客户 ⇒ 不新建任何单', async () => {
|
||
const res = await request(app)
|
||
.put('/api/workflow/quote/sheets/QS-A')
|
||
.send({ customer_codes: ['CUS-A'], items: [ITEM] });
|
||
expect(res.status).toBe(200);
|
||
expect(H.createQuoteSheet).not.toHaveBeenCalled();
|
||
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);
|
||
});
|
||
});
|