Files
SupplierSystem/server/tests/quotePriceProposalMergeDb.integration.test.ts
Ubuntu 3e4bc35b26 feat(报价单): 双向价格传递/改价审核/SKU 映射/成本同步推送(供应商侧)
- 报价单生效自动推销售价 → 配送成本价(台账+重试+rearm,映射优先)
- 编辑生效单改价走内部审核(quote_sheet_change_requests)
- 双向价格传递:A 提交配送商审核 / B 拉回并反查映射后写价、D3 回执
- SKU 映射:D4 字典推送、D5 完整拉取(截断不删)、只读本地副本
- 迁移登记 tenant_business_tables(三张租户表数组互相补齐,避免顺序敏感)
2026-10-18 20:10:58 +08:00

489 lines
20 KiB
TypeScript
Raw Permalink 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.
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* 报价单双向价格传递 · **方向 B 合并语义真库 integration**(默认 skip)
*
* 跑法:
* cd server && QUOTE_PRICE_PROPOSAL_DB_TEST=1 \
* npx vitest run tests/quotePriceProposalMergeDb.integration.test.ts
*
* 为什么必须真库(mock 覆盖不到):
* · **T3 硬判据**:`approvePriceProposal` 只对 payload 里出现的 SKU 逐行 `UPDATE`,
* **不 INSERT / 不 DELETE / 不整表替换**。脚本化 mock 只认 SQL 字符串,
* 证明不了「其余 SKU 行原样存在、`customer_quote_sheet_items` 行总数不变」;
* · **T2**:按 `MAIN_<main_branch_code>` 解析唯一生效单,0 张 ⇒ 409 `no_quote_sheet`、
* 多张 ⇒ 409 `ambiguous_sheet`,且失败时**零写价**、提案仍 pending;
* · **并发 approve 10 次**:`SELECT ... FOR UPDATE` + `status='pending'` 条件更新必须恰好应用一次;
* · **T4**:B 通过不生成 `quote_sheet_change_requests`(不二次内部审核);
* · **A21**:驳回零写价、零推送。
*
* 造数隔离:真库临时分公司 `BR_QPPQA`(schema `tenant_br_qppqa`),全部行 `QPP_QA*` 前缀;
* 出站/审计按契约 mock(不出站、不落 operation_logs)。跑完 DROP SCHEMA + 删 registry/branches/提案,
* 并断言 0 残留;不碰 BR001/BR002 既有业务行。
*/
vi.hoisted(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = 'true';
});
const triggerSpy = vi.hoisted(() => vi.fn());
const resolveSupplierSpy = vi.hoisted(() => vi.fn(async () => null));
vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystemQuoteCostSync')>();
return {
...actual,
triggerQuoteCostSync: (...args: unknown[]) => triggerSpy(...args),
resolveMainSupplierCode: (...args: unknown[]) => resolveSupplierSpy(...args),
};
});
const auditSpy = vi.hoisted(() => vi.fn(async () => undefined));
vi.mock('../src/services/auditService', () => ({
writeAuditLog: (...args: unknown[]) => auditSpy(...args),
}));
const DB_TEST = process.env.QUOTE_PRICE_PROPOSAL_DB_TEST === '1';
const BRANCH = 'BR_QPPQA';
const SCHEMA = 'tenant_br_qppqa';
const MERGE_SHEET = 'QPP_QA_QS_MERGE';
const AMB_A = 'QPP_QA_QS_AMB_A';
const AMB_B = 'QPP_QA_QS_AMB_B';
import { pool } from '../src/db';
import { runWithTenantDbContext } from '../src/services/tenantDbContext';
import {
approvePriceProposal,
rejectPriceProposal,
} from '../src/services/quotePriceProposalService';
const uuid = () => crypto.randomUUID();
async function q<T = Record<string, unknown>>(sql: string, params: unknown[] = []): Promise<T[]> {
return (await pool.query(sql, params)).rows as T[];
}
type ItemRow = {
id: string;
quote_sheet_code: string;
sku_code: string;
unit: string | null;
price: string;
cost_price: string;
sale_price: string;
sort_order: number;
};
/** 本用例造的全部明细行(含 id,用于证明没有 INSERT/DELETE/整表替换) */
async function itemRows(): Promise<ItemRow[]> {
return q(
`SELECT id::text AS id, quote_sheet_code, sku_code, unit, price::text, cost_price::text,
sale_price::text, sort_order
FROM ${SCHEMA}.customer_quote_sheet_items
WHERE quote_sheet_code LIKE 'QPP_QA_%'
ORDER BY quote_sheet_code, sku_code`
);
}
async function priceSnapshot(): Promise<{ count: number; md5: string }> {
const [row] = await q<{ count: number; md5: string }>(
`SELECT COUNT(*)::int AS count,
COALESCE(md5(string_agg(
id::text || '|' || quote_sheet_code || '|' || sku_code || '|' ||
COALESCE(unit, '') || '|' || COALESCE(price::text, '') || '|' ||
COALESCE(cost_price::text, '') || '|' || COALESCE(sale_price::text, '') || '|' ||
COALESCE(sort_order::text, ''),
';' ORDER BY quote_sheet_code, sku_code, id::text
)), '') AS md5
FROM ${SCHEMA}.customer_quote_sheet_items
WHERE quote_sheet_code LIKE 'QPP_QA_%'`
);
return row!;
}
async function createProposal(input: {
mainBranchCode: string;
items: Array<{ sku_code: string; unit?: string | null; price: number }>;
quoteSheetCode?: string;
branchCode?: string;
}): Promise<string> {
const [row] = await q<{ id: string }>(
`INSERT INTO ${SCHEMA}.quote_price_proposals
(branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash, status,
client_request_id, requested_at)
VALUES ($1, $2, $3, 'from_delivery', $4::jsonb, 'qpp-qa-hash', 'pending', $5, NOW())
RETURNING id::text AS id`,
[
input.branchCode || BRANCH,
input.quoteSheetCode || 'QPP_QA_PLACEHOLDER',
input.mainBranchCode,
JSON.stringify(input.items),
uuid(),
]
);
return row!.id;
}
async function proposalStatus(id: string): Promise<string> {
const [row] = await q<{ status: string }>(
`SELECT status FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`,
[id]
);
return row!.status;
}
async function resetFixtures(): Promise<void> {
await runWithTenantDbContext(BRANCH, async () => {
await q(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE quote_sheet_code LIKE 'QPP_QA_%'`);
await q(`DELETE FROM ${SCHEMA}.quote_sheet_change_requests WHERE quote_sheet_code LIKE 'QPP_QA_%'`);
await q(`DELETE FROM ${SCHEMA}.customer_quote_sheet_customers WHERE quote_sheet_code LIKE 'QPP_QA_%'`);
await q(`DELETE FROM ${SCHEMA}.customer_quote_sheet_items WHERE quote_sheet_code LIKE 'QPP_QA_%'`);
await q(`DELETE FROM ${SCHEMA}.customer_quote_sheets WHERE quote_sheet_code LIKE 'QPP_QA_%'`);
const sheet = async (code: string, customers: string[], itemCount: number) => {
await q(
`INSERT INTO ${SCHEMA}.customer_quote_sheets
(quote_sheet_code, title, status, approval_status, effective_at, expires_at, branch_code)
VALUES ($1, $1, 1, 30, NOW(), NOW() + interval '30 day', $2)`,
[code, BRANCH]
);
for (const customer of customers) {
await q(
`INSERT INTO ${SCHEMA}.customer_quote_sheet_customers (quote_sheet_code, customer_code)
VALUES ($1, $2)`,
[code, customer]
);
}
for (let i = 1; i <= itemCount; i += 1) {
await q(
`INSERT INTO ${SCHEMA}.customer_quote_sheet_items
(quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order)
VALUES ($1, $2, $2, '斤', 10, 8, 10, $3)`,
[code, `QPP_QA_SKU_${i}`, i]
);
}
};
await sheet(MERGE_SHEET, ['MAIN_BR_QPPQA'], 5);
// 同一 MAIN_ 客户两张生效单 ⇒ T2 ambiguous_sheet
await sheet(AMB_A, ['MAIN_BR_QPPQAMB'], 1);
await sheet(AMB_B, ['MAIN_BR_QPPQAMB'], 1);
});
}
async function cleanup(): Promise<void> {
await q(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`);
await q(`DELETE FROM public.tenant_schema_registry WHERE branch_code = $1`, [BRANCH]);
await q(`DELETE FROM public.branches WHERE branch_code = $1`, [BRANCH]);
}
beforeAll(async () => {
if (!DB_TEST) return;
await cleanup();
await q(
`INSERT INTO public.branches (branch_code, branch_name, status)
VALUES ($1, 'QPP QA 测试分公司', 1) ON CONFLICT (branch_code) DO NOTHING`,
[BRANCH]
);
await q(`SELECT public.clone_tenant_schema($1, 'active')`, [BRANCH]);
await runWithTenantDbContext(BRANCH, async () => {
for (const customer of ['MAIN_BR_QPPQA', 'MAIN_BR_QPPQAMB']) {
await q(
`INSERT INTO ${SCHEMA}.customers (customer_code, company_name, branch_code, status)
VALUES ($1, $1, $2, 10) ON CONFLICT (customer_code) DO NOTHING`,
[customer, BRANCH]
);
}
});
}, 120_000);
beforeEach(async () => {
if (!DB_TEST) return;
auditSpy.mockClear();
triggerSpy.mockClear();
await resetFixtures();
});
afterAll(async () => {
if (!DB_TEST) return;
await cleanup();
const [left] = await q<{ registry: number; branch: number; schema: number }>(
`SELECT
(SELECT COUNT(*)::int FROM public.tenant_schema_registry WHERE branch_code = $1) AS registry,
(SELECT COUNT(*)::int FROM public.branches WHERE branch_code = $1) AS branch,
(SELECT COUNT(*)::int FROM information_schema.schemata WHERE schema_name = $2) AS schema`,
[BRANCH, SCHEMA]
);
console.log('[QPP QA 供应商侧清理后残留]', JSON.stringify(left));
expect(left).toEqual({ registry: 0, branch: 0, schema: 0 });
await pool.end().catch(() => undefined);
}, 120_000);
describe.skipIf(!DB_TEST)('真库 T3 硬判据:B approve 只按行 UPDATE,其余 SKU 行原样存在', () => {
it('payload 只含 2 个 SKU ⇒ 只更新这 2 行,另外 3 行逐字段不变,行总数不变(无 INSERT/DELETE)', async () => {
const before = await itemRows();
const mergeRows = before.filter((row) => row.quote_sheet_code === MERGE_SHEET);
expect(mergeRows).toHaveLength(5);
const untouched = mergeRows.filter((row) => !['QPP_QA_SKU_1', 'QPP_QA_SKU_2'].includes(row.sku_code));
const id = await createProposal({
mainBranchCode: 'BR_QPPQA',
items: [
{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 12.34 },
{ sku_code: 'QPP_QA_SKU_2', unit: '斤', price: 22.22 },
],
});
const result = await runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never })
);
expect(result.applied).toMatchObject({ updated: 2, unchanged: 0, skipped: [] });
expect(result.proposal.status).toBe('approved');
const after = await itemRows();
// 行总数不变 + id 集合完全一致 ⇒ 没有 INSERT / DELETE / 整表替换
expect(after).toHaveLength(before.length);
expect(new Set(after.map((row) => row.id))).toEqual(new Set(before.map((row) => row.id)));
const afterMerge = after.filter((row) => row.quote_sheet_code === MERGE_SHEET);
expect(afterMerge.find((row) => row.sku_code === 'QPP_QA_SKU_1')).toMatchObject({
price: '12.34',
sale_price: '12.34',
cost_price: '8.00',
});
expect(afterMerge.find((row) => row.sku_code === 'QPP_QA_SKU_2')).toMatchObject({
price: '22.22',
sale_price: '22.22',
cost_price: '8.00',
});
// 其余 3 行逐字段原样(T3 硬判据)
for (const row of untouched) {
expect(after.find((item) => item.id === row.id)).toEqual(row);
}
// 提案落库 + 指向解析出的唯一生效单
const [proposal] = await q<{ status: string; quote_sheet_code: string; applied_at: string | null }>(
`SELECT status, quote_sheet_code, applied_at::text
FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`,
[id]
);
expect(proposal).toMatchObject({ status: 'approved', quote_sheet_code: MERGE_SHEET });
expect(proposal!.applied_at).toBeTruthy();
});
it('缺 SKU / 单位不一致 / 金额非法 ⇒ 跳过并记录,命中行照写;T4 不生成内部变更单', async () => {
const before = await itemRows();
const changeReqBefore = await q<{ n: number }>(
`SELECT COUNT(*)::int AS n FROM ${SCHEMA}.quote_sheet_change_requests`
);
const id = await createProposal({
mainBranchCode: 'BR_QPPQA',
items: [
{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 11.11 },
{ sku_code: 'QPP_QA_SKU_3', unit: 'kg', price: 33.33 },
{ sku_code: 'QPP_QA_SKU_4', unit: '斤', price: 0 },
{ sku_code: 'QPP_QA_SKU_MISSING', unit: '斤', price: 44.44 },
],
});
const result = await runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never })
);
expect(result.applied.updated).toBe(1);
const reasons = result.applied.skipped.map((row) => `${row.sku_code}:${row.reason}`);
expect(reasons).toEqual(
expect.arrayContaining([
'QPP_QA_SKU_3:unit_mismatch',
'QPP_QA_SKU_4:invalid_price',
'QPP_QA_SKU_MISSING:sku_not_in_sheet',
])
);
const after = await itemRows();
expect(after).toHaveLength(before.length);
expect(
after.find((row) => row.quote_sheet_code === MERGE_SHEET && row.sku_code === 'QPP_QA_SKU_1')!
.sale_price
).toBe('11.11');
expect(
after.find((row) => row.quote_sheet_code === MERGE_SHEET && row.sku_code === 'QPP_QA_SKU_3')!
.sale_price
).toBe('10.00');
// T4:B 通过不再走内部审核(零新增变更单)
const changeReqAfter = await q<{ n: number }>(
`SELECT COUNT(*)::int AS n FROM ${SCHEMA}.quote_sheet_change_requests`
);
expect(changeReqAfter[0]!.n).toBe(changeReqBefore[0]!.n);
});
it('每行变更一条审计 + 提交后 triggerQuoteCostSync 恰好一次;重复 approve ⇒ 409 already_decided', async () => {
const id = await createProposal({
mainBranchCode: 'BR_QPPQA',
items: [
{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 12.34 },
{ sku_code: 'QPP_QA_SKU_2', unit: '斤', price: 22.22 },
],
});
await runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never })
);
const rowAudits = auditSpy.mock.calls.filter(
(call) => (call[0] as { operationType?: string }).operationType === 'quote_price_proposal_apply'
);
expect(rowAudits).toHaveLength(2);
expect(triggerSpy).toHaveBeenCalledTimes(1);
expect(triggerSpy).toHaveBeenCalledWith({ branchCode: BRANCH, quoteSheetCode: MERGE_SHEET });
const snapshot = await priceSnapshot();
await expect(
runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never })
)
).rejects.toMatchObject({ status: 409, code: 'already_decided' });
expect(await priceSnapshot()).toEqual(snapshot);
expect(triggerSpy).toHaveBeenCalledTimes(1);
});
});
describe.skipIf(!DB_TEST)('真库 T2:目标单解析 0 张 / 多张 ⇒ 409,零写价、提案仍 pending', () => {
it('0 张生效单 ⇒ 409 no_quote_sheet;2 张 ⇒ 409 ambiguous_sheet;两者都不写价', async () => {
const before = await priceSnapshot();
const missing = await createProposal({
mainBranchCode: 'BR_QPPQANONE',
quoteSheetCode: 'QPP_QA_PLACEHOLDER_NONE',
items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }],
});
await expect(
runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id: missing, ctx: { branchCode: BRANCH } as never })
)
).rejects.toMatchObject({ status: 409, code: 'no_quote_sheet' });
const ambiguous = await createProposal({
mainBranchCode: 'BR_QPPQAMB',
quoteSheetCode: 'QPP_QA_PLACEHOLDER_AMB',
items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }],
});
await expect(
runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id: ambiguous, ctx: { branchCode: BRANCH } as never })
)
).rejects.toMatchObject({ status: 409, code: 'ambiguous_sheet' });
expect(await priceSnapshot()).toEqual(before);
expect(await proposalStatus(missing)).toBe('pending');
expect(await proposalStatus(ambiguous)).toBe('pending');
expect(triggerSpy).not.toHaveBeenCalled();
});
});
describe.skipIf(!DB_TEST)('真库并发:approve 恰好应用一次', () => {
it('10 路并发 approve ⇒ 1 成功 + 9 个 409;价格只写一次、trigger 只 1 次', async () => {
const id = await createProposal({
mainBranchCode: 'BR_QPPQA',
quoteSheetCode: 'QPP_QA_PLACEHOLDER_RACE',
items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 12.34 }],
});
const results = await Promise.allSettled(
Array.from({ length: 10 }, () =>
runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never })
)
)
);
const fulfilled = results.filter(
(r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof approvePriceProposal>>> =>
r.status === 'fulfilled'
);
const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected');
expect(fulfilled).toHaveLength(1);
expect(rejected).toHaveLength(9);
for (const row of rejected) {
expect(row.reason).toMatchObject({ status: 409, code: 'already_decided' });
}
expect(fulfilled[0]!.value.applied.updated).toBe(1);
expect(triggerSpy).toHaveBeenCalledTimes(1);
const after = await itemRows();
expect(
after.find((row) => row.quote_sheet_code === MERGE_SHEET && row.sku_code === 'QPP_QA_SKU_1')!
.sale_price
).toBe('12.34');
});
});
describe.skipIf(!DB_TEST)('真库 B 驳回 / 跨分公司 / 跨租户 / 开关', () => {
it('驳回:只改状态 + 理由,零写价、零推送(A21)', async () => {
const before = await priceSnapshot();
const id = await createProposal({
mainBranchCode: 'BR_QPPQA',
quoteSheetCode: 'QPP_QA_PLACEHOLDER_REJECT',
items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }],
});
const result = await runWithTenantDbContext(BRANCH, () =>
rejectPriceProposal({
id,
reason: '真库:不接受该成本价',
ctx: { branchCode: BRANCH } as never,
})
);
expect(result.proposal.status).toBe('rejected');
expect(await priceSnapshot()).toEqual(before);
expect(triggerSpy).not.toHaveBeenCalled();
const [row] = await q<{ status: string; reject_reason: string }>(
`SELECT status, reject_reason FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`,
[id]
);
expect(row).toEqual({ status: 'rejected', reject_reason: '真库:不接受该成本价' });
});
it('跨分公司提案(同 schema 不同 branch_code)⇒ 403 branch_mismatch,零写价', async () => {
const before = await priceSnapshot();
const id = await createProposal({
branchCode: 'BR001',
mainBranchCode: 'BR_QPPQA',
quoteSheetCode: 'QPP_QA_PLACEHOLDER_CROSS',
items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }],
});
await expect(
runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never })
)
).rejects.toMatchObject({ status: 403, code: 'branch_mismatch' });
expect(await priceSnapshot()).toEqual(before);
expect(await proposalStatus(id)).toBe('pending');
});
it('其它分公司上下文 ⇒ 404 proposal_not_found(跨租户不可见),零写价', async () => {
const before = await priceSnapshot();
const id = await createProposal({
mainBranchCode: 'BR_QPPQA',
quoteSheetCode: 'QPP_QA_PLACEHOLDER_OTHER',
items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }],
});
await expect(
runWithTenantDbContext('BR001', () =>
approvePriceProposal({ id, ctx: { branchCode: 'BR001' } as never })
)
).rejects.toMatchObject({ status: 404, code: 'proposal_not_found' });
expect(await priceSnapshot()).toEqual(before);
});
it('开关关闭 ⇒ 503 feature_disabled,零写价、零推送(A39)', async () => {
const before = await priceSnapshot();
const id = await createProposal({
mainBranchCode: 'BR_QPPQA',
quoteSheetCode: 'QPP_QA_PLACEHOLDER_OFF',
items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }],
});
const saved = process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL;
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = 'false';
try {
await expect(
runWithTenantDbContext(BRANCH, () =>
approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never })
)
).rejects.toMatchObject({ status: 503, code: 'feature_disabled' });
} finally {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = saved;
}
expect(await priceSnapshot()).toEqual(before);
expect(triggerSpy).not.toHaveBeenCalled();
expect(await proposalStatus(id)).toBe('pending');
});
});