Files
SupplierSystem/server/tests/mainSystemQuoteCostSyncApi.test.ts
T
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

216 lines
8.9 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 { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* 报价单成本价同步 —— **接口封装层**契约守卫(`server/src/services/mainSystem/api/quoteCostSync.ts`)。
*
* 钉住四类做反就返工的行为:
* ① URL 只在端点表里拼(含 `MAIN_SYSTEM_QUOTE_COST_SYNC_PATH` 覆盖),业务层不硬编码;
* ② 字段名照契约(snake_case),`supplier_code` **不进 body**(只由 token 决定);
* ③ 403 判成**语义拒绝**(不是网络故障),503/5xx 判成"对方不可用"(可重试);
* ④ 2xx 但回执不可识别 ⇒ 失败(绝不把"没同步"当"已同步")。
*/
const enabled = vi.hoisted(() => ({ value: true }));
vi.mock('../src/services/mainSystem/config', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystem/config')>();
return {
...actual,
isMainSystemIntegrationEnabled: () => enabled.value,
mainSystemBaseUrl: () => 'http://main-system.example',
};
});
const getMainSystemToken = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystem/token', () => ({
getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args),
}));
const fetchMock = vi.hoisted(() => vi.fn());
vi.stubGlobal('fetch', fetchMock);
import {
normalizeQuoteCostSyncData,
readQuoteCostSyncErrorCode,
submitQuoteCostSync,
} from '../src/services/mainSystem/api/quoteCostSync';
function jsonResponse(status: number, body: unknown) {
return {
ok: status >= 200 && status < 300,
status,
json: async () => body,
};
}
const BODY = {
client_request_id: '11111111-1111-1111-1111-111111111111',
supplier_quote_sheet_code: 'QS1792200796033LUTV',
main_branch_code: 'BR002',
activated_at: '2026-10-18T02:00:00.000Z',
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 12.34 }],
};
const OK_PAYLOAD = {
success: true,
data: {
client_request_id: BODY.client_request_id,
replayed: false,
main_branch_code: 'BR002',
updated: 2,
sheets: ['QS-A', 'QS-B'],
skipped: [{ reason: 'unit_mismatch', sku_code: 'SKU9', detail: '斤 vs 袋' }],
warnings: [],
},
};
beforeEach(() => {
fetchMock.mockReset();
getMainSystemToken.mockReset();
enabled.value = true;
delete process.env.MAIN_SYSTEM_QUOTE_COST_SYNC_PATH;
getMainSystemToken.mockResolvedValue({
kind: 'ok',
token: 'tok-1',
branchCode: 'BR002',
expiresAt: Date.now() + 60_000,
});
});
describe('URL 与请求(端点表唯一拼装)', () => {
it('默认路径 = /api/supplier/quote-sheets/cost-sync,POST + Bearer + JSON', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, OK_PAYLOAD));
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP37831443', body: BODY });
expect(outcome.kind).toBe('ok');
const [url, init] = fetchMock.mock.calls[0] as [string, any];
expect(url).toBe('http://main-system.example/api/supplier/quote-sheets/cost-sync');
expect(init.method).toBe('POST');
expect(init.headers.Authorization).toBe('Bearer tok-1');
expect(init.headers['Content-Type']).toBe('application/json');
const sent = JSON.parse(init.body);
expect(sent).toEqual(BODY);
// supplier_code 只由 token 决定,**不得**出现在请求体里
expect(Object.keys(sent)).not.toContain('supplier_code');
});
it('`MAIN_SYSTEM_QUOTE_COST_SYNC_PATH` 可覆盖端点路径', async () => {
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC_PATH = '/custom/cost-sync';
fetchMock.mockResolvedValue(jsonResponse(200, OK_PAYLOAD));
await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect((fetchMock.mock.calls[0] as [string])[0]).toBe('http://main-system.example/custom/cost-sync');
});
});
describe('回执归一', () => {
it('200 ⇒ ok + 字段归一(replayed / updated / sheets / skipped)', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, OK_PAYLOAD));
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind).toBe('ok');
if (outcome.kind !== 'ok') return;
expect(outcome.data.replayed).toBe(false);
expect(outcome.data.updated).toBe(2);
expect(outcome.data.sheets).toEqual(['QS-A', 'QS-B']);
expect(outcome.data.skipped).toEqual([{ reason: 'unit_mismatch', sku_code: 'SKU9', detail: '斤 vs 袋' }]);
});
it('回执缺字段不炸(一律兜空值)', () => {
expect(normalizeQuoteCostSyncData({})).toEqual({
client_request_id: '',
replayed: false,
main_branch_code: '',
updated: 0,
sheets: [],
skipped: [],
warnings: [],
});
});
it('2xx 但回执不可识别(data 非对象)⇒ unavailable,绝不判成功', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, { success: true, data: null }));
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind).toBe('unavailable');
expect((outcome as any).code).toBe('invalid_main_system_response');
});
it('非 JSON(网关 HTML)⇒ unavailable,不判成功', async () => {
fetchMock.mockResolvedValue({
ok: true,
status: 200,
json: async () => {
throw new Error('Unexpected token < in JSON');
},
});
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind).toBe('unavailable');
});
});
describe('错误归类(决定台账状态与是否重试)', () => {
it('403 branch_not_bound ⇒ rejected(语义拒绝,不是网络故障)', async () => {
fetchMock.mockResolvedValue(jsonResponse(403, { error: 'branch_not_bound', error_description: '未绑定该分公司' }));
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind).toBe('rejected');
expect((outcome as any).status).toBe(403);
expect((outcome as any).code).toBe('branch_not_bound');
});
it('409 幂等冲突 ⇒ rejected(默认 4xx 口径)', async () => {
fetchMock.mockResolvedValue(jsonResponse(409, { error: 'idempotency_conflict' }));
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind).toBe('rejected');
expect((outcome as any).code).toBe('idempotency_conflict');
});
it('503 feature_disabled / 500 ⇒ unavailable(可重试)', async () => {
for (const status of [503, 500]) {
fetchMock.mockResolvedValueOnce(jsonResponse(status, { error: status === 503 ? 'feature_disabled' : 'server_error' }));
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind, String(status)).toBe('unavailable');
}
});
it('网络抛错 ⇒ unavailable(不抛给业务层)', async () => {
fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind).toBe('unavailable');
});
it('401 ⇒ 强制刷新 token 后重试一次', async () => {
fetchMock
.mockResolvedValueOnce(jsonResponse(401, { error: 'unauthorized' }))
.mockResolvedValueOnce(jsonResponse(200, OK_PAYLOAD));
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind).toBe('ok');
expect(getMainSystemToken).toHaveBeenCalledTimes(2);
expect((getMainSystemToken.mock.calls[1] as unknown[])[1]).toEqual({ forceRefresh: true });
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('token 换不到 ⇒ unavailable,一个业务请求都不发', async () => {
getMainSystemToken.mockResolvedValue({ kind: 'unavailable', reason: '被撤权' });
const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY });
expect(outcome.kind).toBe('unavailable');
expect(fetchMock).not.toHaveBeenCalled();
});
it('未配置对接 / 缺 supplier_code / 空 items ⇒ 本地直接判失败,零出站', async () => {
enabled.value = false;
expect((await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY })).kind).toBe('not_configured');
enabled.value = true;
expect((await submitQuoteCostSync({ supplierCode: '', body: BODY })).kind).toBe('not_configured');
const empty = await submitQuoteCostSync({ supplierCode: 'SUP1', body: { ...BODY, items: [] } });
expect(empty.kind).toBe('rejected');
expect((empty as any).code).toBe('items_required');
expect(fetchMock).not.toHaveBeenCalled();
});
it('错误码兜底(没带 error 时按状态码)', () => {
expect(readQuoteCostSyncErrorCode({ error: 'branch_not_bound' }, 403)).toBe('branch_not_bound');
expect(readQuoteCostSyncErrorCode(null, 401)).toBe('unauthorized');
expect(readQuoteCostSyncErrorCode(null, 403)).toBe('forbidden');
expect(readQuoteCostSyncErrorCode(null, 409)).toBe('idempotency_conflict');
expect(readQuoteCostSyncErrorCode(null, 503)).toBe('feature_disabled');
expect(readQuoteCostSyncErrorCode(null, 500)).toBe('main_system_error');
});
});