Files
SupplierSystem/server/tests/t1BoundaryBiz13.test.ts
T
Ubuntu 5fa2bbfd55
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
2026-10-19 16:16:51 +08:00

217 lines
8.5 KiB
TypeScript
Raw 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 express from 'express';
import request from 'supertest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T1 · BIZ-13 独立边界复核(2026-10-19,tester)。
*
* 与 dev 的 `quotePriceProposalInvalidPriceSkipped.test.ts` 独立:补三条它没覆盖的边界 ——
* ① 0 价与负价**同时**出现 ⇒ skipped 两条都在、payload 只有有效行(且顺序不乱);
* ② 全部非法 ⇒ 路由 400,错误体 `skipped` 明细完整、`error_description` 可读、未出站;
* ③ 命中「同 payload 回放」路径时 `skipped` 仍随响应返回(回放不得丢掉跳过原因)。
*/
const H = vi.hoisted(() => ({
poolQuery: vi.fn(),
clientQuery: vi.fn(),
release: vi.fn(),
submitRemote: vi.fn(),
resolveSupplier: vi.fn(),
loadSheet: vi.fn(),
mappingStats: vi.fn(),
audit: vi.fn(),
ctx: {
userId: 'user-1',
roles: ['admin'],
permissions: ['customer_manage'],
branchCode: 'BR002',
supplierCode: null,
purchaserCode: null,
isSuperAdmin: false,
isBranchAdmin: false,
isInternalStaff: true,
isSupplierAccount: false,
} as Record<string, unknown>,
}));
const BRANCH = 'BR002';
const SHEET = 'QS1';
vi.mock('../src/db', () => ({
pool: {
query: (...args: unknown[]) => H.poolQuery(...args),
connect: async () => ({
query: (...args: unknown[]) => H.clientQuery(...args),
release: () => H.release(),
}),
},
getRawPoolQuery: () => H.poolQuery,
}));
vi.mock('../src/middleware/auth', () => ({
authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => {
req.userId = 'user-1';
next();
},
}));
vi.mock('../src/modules/workflow/context', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/modules/workflow/context')>();
return { ...actual, getWorkflowCtx: async () => H.ctx };
});
vi.mock('../src/services/quoteSheetService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/quoteSheetService')>();
return { ...actual, loadQuoteSheetForUpdate: (...args: unknown[]) => H.loadSheet(...args) };
});
vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystemQuoteCostSync')>();
return { ...actual, resolveMainSupplierCode: (...args: unknown[]) => H.resolveSupplier(...args) };
});
vi.mock('../src/services/mainSystem/api/quotePriceProposals', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystem/api/quotePriceProposals')>();
return { ...actual, submitQuotePriceProposal: (...args: unknown[]) => H.submitRemote(...args) };
});
vi.mock('../src/services/skuMappingService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/skuMappingService')>();
return { ...actual, getSheetMappingStats: (...args: unknown[]) => H.mappingStats(...args) };
});
vi.mock('../src/services/auditService', () => ({
writeAuditLog: (...args: unknown[]) => H.audit(...args),
}));
import { submitPriceProposal } from '../src/services/quotePriceProposalService';
import { mountQuoteWorkflowRoutes } from '../src/modules/workflow/routes/quoteRoutes';
const app = express();
app.use(express.json());
const router = express.Router();
mountQuoteWorkflowRoutes(router);
app.use('/api/workflow', router);
type Row = Record<string, any>;
const state = {
sheetItems: [] as Row[],
pending: null as Row | null,
/** 上一条 INSERT 的 payload 快照(回放用例复用) */
inserted: null as Row | null,
};
function sheetItem(skuCode: string, price: number): Row {
return { sku_code: skuCode, sku_name: skuCode, unit: '斤', sale_price: String(price), price: String(price) };
}
beforeEach(() => {
process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1';
state.sheetItems = [];
state.pending = null;
state.inserted = null;
H.poolQuery.mockReset();
H.clientQuery.mockReset();
H.release.mockReset();
H.submitRemote.mockReset();
H.resolveSupplier.mockReset();
H.loadSheet.mockReset();
H.mappingStats.mockReset();
H.audit.mockReset();
H.resolveSupplier.mockResolvedValue('SUP1');
H.loadSheet.mockResolvedValue({ quote_sheet_code: SHEET, branch_code: BRANCH });
H.mappingStats.mockResolvedValue({ quote_sheet_code: SHEET, total: 0, mapped: 0, unmapped: 0, unmapped_skus: [] });
H.submitRemote.mockResolvedValue({ kind: 'ok', status: 200, data: { proposal_id: 'remote-1', replayed: false } });
H.audit.mockResolvedValue(undefined);
H.poolQuery.mockImplementation((sql: string, params?: unknown[]) => {
const text = String(sql);
if (text.includes('FROM customer_quote_sheet_customers') && text.includes('ORDER BY customer_code')) {
return { rows: [{ customer_code: 'MAIN_BR002' }], rowCount: 1 };
}
if (text.includes('FROM customer_quote_sheet_items')) {
return { rows: state.sheetItems, rowCount: state.sheetItems.length };
}
if (text.includes('FROM quote_price_proposals') && text.includes("status = 'pending'")) {
return { rows: state.pending ? [state.pending] : [], rowCount: state.pending ? 1 : 0 };
}
return { rows: [], rowCount: 0 };
});
H.clientQuery.mockImplementation((sql: string, params: unknown[] = []) => {
const text = String(sql);
if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) return { rows: [], rowCount: 0 };
if (text.includes('INSERT INTO quote_price_proposals')) {
const row = {
id: 'local-1',
branch_code: params?.[0],
quote_sheet_code: params?.[1],
main_branch_code: params?.[2],
direction: 'to_delivery',
items: JSON.parse(String(params?.[3] || '[]')),
payload_hash: params?.[4],
status: 'pending',
client_request_id: params?.[5],
remote_proposal_id: params?.[6],
requested_by: params?.[7] ?? null,
};
state.inserted = row;
return { rows: [row], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
});
});
describe('BIZ-13 边界①:0 价 + 负价 + 有效行混合', () => {
it('skipped 两条都在,payload 只含有效行且保持原顺序', async () => {
state.sheetItems = [sheetItem('SKU1', 10), sheetItem('SKU2', 0), sheetItem('SKU3', -2.5), sheetItem('SKU4', 8)];
const result = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: H.ctx as never });
expect(result.skipped).toEqual([
{ sku_code: 'SKU2', reason: 'invalid_price' },
{ sku_code: 'SKU3', reason: 'invalid_price' },
]);
const submitted = H.submitRemote.mock.calls[0][0] as Row;
expect(submitted.items.map((item: Row) => item.sku_code)).toEqual(['SKU1', 'SKU4']);
expect(submitted.items.every((item: Row) => item.price > 0)).toBe(true);
// 本地 pending 的 items 同样不得含 0/负价行
expect((state.inserted as Row).items.map((item: Row) => item.sku_code)).toEqual(['SKU1', 'SKU4']);
});
});
describe('BIZ-13 边界②:路由 400 错误体带完整 skipped', () => {
it('全部为 0/负价 ⇒ 400、error_description 可读、skipped 完整、未出站', async () => {
state.sheetItems = [sheetItem('SKU2', 0), sheetItem('SKU3', -1)];
const res = await request(app).post(`/api/workflow/quote/sheets/${SHEET}/price-proposals`).send({});
expect(res.status).toBe(400);
expect(res.body.error).toBe('items_required');
expect(String(res.body.error_description)).toContain('没有可提交的商品行');
expect(res.body.skipped).toEqual([
{ sku_code: 'SKU2', reason: 'invalid_price' },
{ sku_code: 'SKU3', reason: 'invalid_price' },
]);
expect(H.submitRemote).not.toHaveBeenCalled();
});
});
describe('BIZ-13 边界③:同 payload 回放路径仍返回 skipped', () => {
it('第二次提交命中回放 ⇒ replayed=true 且 skipped 与首次一致,不重复出站', async () => {
state.sheetItems = [sheetItem('SKU1', 10), sheetItem('SKU2', 0)];
const first = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: H.ctx as never });
expect(first.replayed).toBe(false);
expect(first.skipped).toEqual([{ sku_code: 'SKU2', reason: 'invalid_price' }]);
// 用本次真实写入的 pending 行构造「同 hash 回放」;同 sheet/分公司/价格 ⇒ hash 必然一致
state.pending = { ...(state.inserted as Row) };
const second = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: H.ctx as never });
expect(second.replayed).toBe(true);
expect(second.skipped).toEqual([{ sku_code: 'SKU2', reason: 'invalid_price' }]);
expect(H.submitRemote).toHaveBeenCalledTimes(1);
});
});