Files
SupplierSystem/server/tests/preparationsAmendProxy.test.ts
Ubuntu de14fb01f0
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
feat: 供应商系统 2026-11 阶段成果(分公司模板/真还原预览、商品远程搜索、主系统联调、加工幂等修复)
- 分公司类型模板:超管配置隐藏路由/菜单 + 中文文案覆盖,仅对挂类型的分公司生效(后端 service/routes、前端 Provider/守卫/配置页)
- 超管模板 iframe 真还原预览:28 个业务页注册、白名单点选编辑、空/示例数据 fixture、白名单漂移检测工具
- 商品/SKU 下拉远程搜索:服务端关键词搜索 + 前端 useRemoteOptionSearch/SearchableSelect 接入(订单/采购/商品等页)
- 主系统联调:子系统主动解绑主系统授权(幂等重试/本地兜底)、追加修改 price_amend 视图代理与 amend-price 转发
- 修复:仓内加工重复建单幂等(已完成需求单 guard、order 任务一商品一单 guard)
- 修复:出入库记录只取前 100 条 → 服务端分页 + 真实总数
- 其它:库存/订单若干修复、分公司管理响应式布局、i18n 文案、设计文档与回归测试
2026-11-07 20:10:48 +08:00

412 lines
15 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 { beforeEach, describe, expect, it, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import path from 'node:path';
/**
* 主系统「结算后追加修改」联调(2026-11-06)——接口封装 + 代理映射的行为守卫。
*
* 钉住四类做反就返工的行为:
* ① 视图行**保留主系统全部字段**(尤其 order_qty/received_qty/demand_qty/actual_qty),
* 并保留 `price_amend_window_hours`;响应加 `source:'main_system'`;
* ② 提交时**只传调用方实际提供的字段** —— 只给价时请求体里不出现 `prepare_qty`/`unit`;
* ③ 主系统错误码不静默:403→403、401→502、404→502、5xx→502;提交 400/403/404/409 原样映射;
* ④ 开关 `MAIN_SYSTEM_AMEND_PRICE_PROXY` 默认开,路由同时保留旧本地分支(off 才走)。
*/
const integrationEnabled = 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: () => integrationEnabled.value,
mainSystemBaseUrl: () => 'http://main-system.example',
};
});
const getMainSystemToken = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystem/token', () => ({
getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args),
}));
import {
fetchMainSystemPriceAmendView,
submitMainSystemAmendPrice,
} from '../src/services/mainSystem/api/preparationsAmend';
import {
loadPriceAmendViewProxy,
mapPriceAmendViewPayload,
submitAmendPriceProxy,
} from '../src/services/supplierPrepAmendProxy';
const fetchMock = vi.fn();
function jsonResponse(status: number, body: unknown) {
return {
ok: status >= 200 && status < 300,
status,
json: async () => body,
};
}
/** 主系统真实行(2026-11-06 实测 ORD_WEB_20261105_BR002_0007)裁剪成测试用全量字段集 */
const CONTRACT_ROW = {
id: 'f4a76044-437b-4497-916e-8964e12ea010',
order_code: 'ORD_WEB_20261101_BR002_0008',
sku_code: 'SKU87652265348',
prepare_qty: '1.00',
unit: '件',
order_qty: '1.000',
order_unit: '件',
actual_qty: null,
received_qty: '1.000',
received_unit: '件',
demand_qty: '1.000',
demand_unit: '件',
amend_request: null,
requires_quality_report: false,
};
function viewPayload(overrides: Record<string, unknown> = {}) {
return {
data: [CONTRACT_ROW],
supplier_code: 'SUP37831443',
view: 'price_amend',
total: 1,
has_more: false,
limit: 500,
offset: 0,
next_cursor: null,
confirm_required: false,
allow_zero_cost: false,
delivery_date: null,
price_amend_window_hours: 72,
...overrides,
};
}
beforeEach(() => {
fetchMock.mockReset();
getMainSystemToken.mockReset();
integrationEnabled.value = true;
getMainSystemToken.mockResolvedValue({
kind: 'ok',
token: 'tok-1',
branchCode: 'BR002',
expiresAt: Date.now() + 60_000,
});
});
describe('fetchMainSystemPriceAmendView(接口封装)', () => {
it('GET view=price_amend:URL/token 正确,行字段原样保留 + window 小时', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, viewPayload()));
const outcome = await fetchMainSystemPriceAmendView({
supplierCode: 'SUP37831443',
deliveryDate: '2026-11-02',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('ok');
if (outcome.kind !== 'ok') return;
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toContain('http://main-system.example/api/supplier/preparations?');
expect(String(url)).toContain('view=price_amend');
expect(String(url)).toContain('delivery_date=2026-11-02');
expect(init.method).toBe('GET');
expect(init.headers.Authorization).toBe('Bearer tok-1');
expect(outcome.windowHours).toBe(72);
// 契约字段逐个在(不裁字段,不做 camelCase 改名)
for (const key of [
'id',
'order_code',
'sku_code',
'prepare_qty',
'unit',
'order_qty',
'order_unit',
'actual_qty',
'received_qty',
'received_unit',
'demand_qty',
'demand_unit',
'amend_request',
]) {
expect(outcome.rows[0]).toHaveProperty(key);
}
expect(outcome.rows[0]).toEqual(CONTRACT_ROW);
});
it('主系统 200 但 data 不是数组 ⇒ unavailable(不静默空列表)', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, { data: null, price_amend_window_hours: 24 }));
const outcome = await fetchMainSystemPriceAmendView({
supplierCode: 'SUP37831443',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('unavailable');
if (outcome.kind !== 'unavailable') return;
expect(outcome.reason).toMatch(/data 数组/);
});
it('主系统 403 判为 unavailable 但保留状态码与主系统文案', async () => {
fetchMock.mockResolvedValue(
jsonResponse(403, { error: 'forbidden', error_description: '该分公司未开放供应商追加改价' })
);
const outcome = await fetchMainSystemPriceAmendView({
supplierCode: 'SUP37831443',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('unavailable');
if (outcome.kind !== 'unavailable') return;
expect(outcome.status).toBe(403);
expect(outcome.reason).toMatch(/未开放供应商追加改价/);
});
it.each([401, 404, 500])('主系统 %i 保留状态码(路由层据此映射 502)', async (status) => {
fetchMock.mockResolvedValue(jsonResponse(status, { error: 'upstream_error' }));
const outcome = await fetchMainSystemPriceAmendView({
supplierCode: 'SUP37831443',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).not.toBe('ok');
expect((outcome as { status?: number }).status).toBe(status);
});
it('未配置对接 ⇒ not_configured', async () => {
integrationEnabled.value = false;
const outcome = await fetchMainSystemPriceAmendView({ supplierCode: 'SUP37831443' });
expect(outcome.kind).toBe('not_configured');
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe('submitMainSystemAmendPrice(只传调用方实际提供的字段)', () => {
it('只传 {id, purchase_price}:body 不含 prepare_qty / unit', async () => {
fetchMock.mockResolvedValue(
jsonResponse(200, { data: { request_id: 'req-1', status: 'pending', overwritten: false } })
);
const result = await submitMainSystemAmendPrice({
supplierCode: 'SUP37831443',
id: 'f4a76044-437b-4497-916e-8964e12ea010',
purchasePrice: 5.5,
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(result.kind).toBe('ok');
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://main-system.example/api/supplier/preparations/amend-price');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toEqual({
id: 'f4a76044-437b-4497-916e-8964e12ea010',
purchase_price: 5.5,
});
});
it('显式提供 prepare_qty / unit 时才进 body', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, { data: { request_id: 'req-2', status: 'pending' } }));
await submitMainSystemAmendPrice({
supplierCode: 'SUP37831443',
id: 'prep-1',
purchasePrice: 6,
prepareQty: 30,
unit: '斤',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
id: 'prep-1',
purchase_price: 6,
prepare_qty: 30,
unit: '斤',
});
});
it('prepare_qty=null / unit 空串 ⇒ 字段省略(不补默认值)', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, { data: { request_id: 'req-3', status: 'pending' } }));
await submitMainSystemAmendPrice({
supplierCode: 'SUP37831443',
id: 'prep-1',
purchasePrice: 6,
prepareQty: null,
unit: ' ',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
id: 'prep-1',
purchase_price: 6,
});
});
it('主系统 409 保留 rejected + 状态码(已有待审/超时窗)', async () => {
fetchMock.mockResolvedValue(
jsonResponse(409, { error: 'conflict', error_description: '追加改价已超过时限' })
);
const result = await submitMainSystemAmendPrice({
supplierCode: 'SUP37831443',
id: 'prep-1',
purchasePrice: 6,
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(result.kind).toBe('rejected');
if (result.kind !== 'rejected') return;
expect(result.status).toBe(409);
expect(result.reason).toMatch(/超过时限/);
});
it('主系统 400 保留 rejected;403 归为 unavailable 但状态码保留', async () => {
fetchMock.mockResolvedValueOnce(jsonResponse(400, { error: 'invalid_request', error_description: '采购价必须大于 0' }));
const bad = await submitMainSystemAmendPrice({
supplierCode: 'SUP37831443',
id: 'prep-1',
purchasePrice: 0,
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(bad.kind).toBe('rejected');
expect((bad as { status?: number }).status).toBe(400);
fetchMock.mockResolvedValueOnce(jsonResponse(403, { error: 'forbidden', error_description: '未开放' }));
const forbidden = await submitMainSystemAmendPrice({
supplierCode: 'SUP37831443',
id: 'prep-1',
purchasePrice: 6,
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(forbidden.kind).toBe('unavailable');
expect((forbidden as { status?: number }).status).toBe(403);
});
});
describe('代理映射(supplierPrepAmendProxy)', () => {
it('视图载荷原样保留 + source/view/window(字段不裁剪)', () => {
const payload = viewPayload();
const mapped = mapPriceAmendViewPayload(payload);
expect(mapped).not.toBeNull();
expect(mapped!.source).toBe('main_system');
expect(mapped!.view).toBe('price_amend');
expect(mapped!.price_amend_window_hours).toBe(72);
expect((mapped!.data as unknown[])[0]).toEqual(CONTRACT_ROW);
});
it('视图 403 ⇒ 403 forbidden(透传主系统文案)', async () => {
fetchMock.mockResolvedValue(
jsonResponse(403, { error: 'forbidden', error_description: '该分公司未开放供应商追加改价' })
);
const outcome = await loadPriceAmendViewProxy({
supplierCode: 'SUP37831443',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('error');
if (outcome.kind !== 'error') return;
expect(outcome.error.status).toBe(403);
expect(outcome.error.code).toBe('forbidden');
expect(outcome.error.message).toMatch(/未开放/);
});
it.each([
[401, 502, 'main_system_unauthorized'],
[404, 502, 'main_system_not_found'],
[500, 502, 'main_system_unavailable'],
[400, 400, 'invalid_request'],
])('视图主系统 %i ⇒ %i %s', async (upstream, expected, code) => {
fetchMock.mockResolvedValue(jsonResponse(upstream, { error: 'upstream', error_description: 'boom' }));
const outcome = await loadPriceAmendViewProxy({
supplierCode: 'SUP37831443',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('error');
if (outcome.kind !== 'error') return;
expect(outcome.error.status).toBe(expected);
expect(outcome.error.code).toBe(code);
});
it('视图成功 ⇒ 返回既有形状(data/window + source)', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, viewPayload()));
const outcome = await loadPriceAmendViewProxy({
supplierCode: 'SUP37831443',
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('ok');
if (outcome.kind !== 'ok') return;
expect(outcome.body.source).toBe('main_system');
expect(outcome.body.price_amend_window_hours).toBe(72);
expect(Array.isArray(outcome.body.data)).toBe(true);
});
it('提交成功归一:status=pending + request_id + 固定提示语', async () => {
fetchMock.mockResolvedValue(
jsonResponse(200, { data: { request_id: 'req-1', status: 'pending', overwritten: true } })
);
const outcome = await submitAmendPriceProxy({
supplierCode: 'SUP37831443',
id: 'prep-1',
purchasePrice: 8,
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('ok');
if (outcome.kind !== 'ok') return;
expect(outcome.body).toEqual({
data: {
status: 'pending',
request_id: 'req-1',
overwritten: true,
message: '已提交修改申请,请等待管理员确认',
},
});
});
it.each([
[400, 400, 'invalid_request'],
[403, 403, 'forbidden'],
[404, 404, 'not_found'],
[409, 409, 'conflict'],
[401, 502, 'main_system_unauthorized'],
[503, 502, 'main_system_unavailable'],
])('提交主系统 %i ⇒ %i %s', async (upstream, expected, code) => {
fetchMock.mockResolvedValue(jsonResponse(upstream, { error: 'upstream', error_description: 'boom' }));
const outcome = await submitAmendPriceProxy({
supplierCode: 'SUP37831443',
id: 'prep-1',
purchasePrice: 8,
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('error');
if (outcome.kind !== 'error') return;
expect(outcome.error.status).toBe(expected);
expect(outcome.error.code).toBe(code);
});
it('提交 200 但形状不可识别 ⇒ 502 bad_response(不把未落地当成功)', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, 'ok'));
const outcome = await submitAmendPriceProxy({
supplierCode: 'SUP37831443',
id: 'prep-1',
purchasePrice: 8,
fetchImpl: fetchMock as unknown as typeof fetch,
});
expect(outcome.kind).toBe('error');
if (outcome.kind !== 'error') return;
expect(outcome.error.status).toBe(502);
expect(outcome.error.code).toBe('main_system_bad_response');
});
});
describe('路由接线(开关 on 走主系统 / off 保留本地)', () => {
const routeSource = readFileSync(
path.join(__dirname, '..', 'src', 'routes', 'supplier', 'supplierBusinessRoutes.ts'),
'utf8'
);
it('GET/POST 都有代理分支,且 off 时旧本地 submitPrepAmendRequest 仍在', () => {
expect(routeSource).toContain('isMainSystemAmendPriceProxyEnabled()');
expect(routeSource).toContain('loadPriceAmendViewProxy');
expect(routeSource).toContain('submitAmendPriceProxy');
expect(routeSource).toContain('submitPrepAmendRequest');
expect(routeSource).toContain('resolveMainSupplierCodeForBranch');
});
it('不调用 plan-change(语义不同,禁止)', () => {
// 只允许出现在注释里的"禁止"提醒;实现不得引用 plan-change 端点/函数
expect(routeSource).not.toContain('mainSystemPlanChangePath');
expect(routeSource).not.toContain('submitMainSystemPlanChange');
});
});