Files
SupplierSystem/server/tests/capability-registry.test.ts
T
雨天 2c659966e6 feat(运营): 售后与异常合并为一个入口(异常改名预警管理)
两个平级菜单合成 /ops 一个入口(两个 Tab,按权限显隐);底层两张表、两套后端、两枚权限码不变;/after-sales、/exceptions 保留为重定向不废深链。异常管理连同权限名与三语文案改名「预警管理」。设计见 docs/design/20261012-售后与异常合并为一个入口.md。
2026-10-13 09:52:23 +08:00

587 lines
22 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 { describe, expect, it } from 'vitest';
import { OPEN_PAGE_BY_TOOL } from '../src/mcp/orderEntryTools';
import { executeCapability, listCapabilityToolSchemas, listCapableModuleIds, inferWriteActionType } from '../src/capabilities/registry';
import { ASSISTANT_MODULES } from '../src/capabilities/modules';
import { registerBuiltinCapabilities } from '../src/capabilities/registerBuiltins';
import { missingRequiredFields, toToolSchema } from '../src/capabilities/types';
import { routeModules } from '../src/capabilities/routeModules';
import type { TenantContext } from '../src/services/tenantScope';
registerBuiltinCapabilities();
const superAdmin: TenantContext = {
userId: 'u1',
roles: ['super_admin'],
permissions: [],
branchCode: 'BR001',
supplierCode: null,
purchaserCode: null,
isSuperAdmin: true,
isBranchAdmin: false,
isInternalStaff: true,
isSupplierAccount: false,
};
const supplier: TenantContext = {
userId: 's1',
roles: ['supplier'],
permissions: [],
branchCode: 'BR001',
supplierCode: 'SUP1',
purchaserCode: null,
isSuperAdmin: false,
isBranchAdmin: false,
isInternalStaff: false,
isSupplierAccount: true,
};
describe('capability registry', () => {
it('reports missing required fields without confirm', () => {
expect(
missingRequiredFields(
{ required: ['customer_code', 'text', 'confirm'], type: 'object' },
{ customer_code: '', text: '土豆' }
)
).toEqual(['customer_code']);
});
it('blocks write even if model sends confirm=true', async () => {
const result = await executeCapability('submit_order', {
userId: 'u1',
ctx: superAdmin,
args: { customer_code: 'C1', items: [{ item_name: '土豆', quantity: 1 }], confirm: true },
surface: 'api',
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.code).toBe('need_confirm');
expect(result.action_id).toBe('submit_order');
expect(result.preview?.capability).toBe('submit_order');
expect(result.preview?.action_type).toBe('update');
}
});
it('does not expose confirm on model schema', () => {
const schema = listCapabilityToolSchemas({ ctx: superAdmin, surface: 'api' }).find((t) => t.name === 'submit_order');
expect(schema).toBeTruthy();
const props = (schema?.inputSchema.properties || {}) as Record<string, unknown>;
expect(props.confirm).toBeUndefined();
});
it('returns need_input for parse without customer', async () => {
const result = await executeCapability('parse_order_text', {
userId: 'u1',
ctx: superAdmin,
args: { text: '土豆10斤' },
surface: 'web',
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.code).toBe('need_input');
expect(result.missing).toContain('customer_code');
}
});
it('hides submit_order on web and miniprogram', () => {
const webNames = listCapabilityToolSchemas({ ctx: superAdmin, surface: 'web' }).map((t) => t.name);
expect(webNames).not.toContain('submit_order');
expect(webNames).toContain('open_page');
expect(webNames).toContain('parse_order_text');
const mpNames = listCapabilityToolSchemas({ ctx: superAdmin, surface: 'miniprogram' }).map((t) => t.name);
expect(mpNames).not.toContain('submit_order');
const apiNames = listCapabilityToolSchemas({ ctx: superAdmin, surface: 'api' }).map((t) => t.name);
expect(apiNames).toContain('submit_order');
});
it('lets supplier open shell but forbids parse', async () => {
const names = listCapabilityToolSchemas({ ctx: supplier, surface: 'web' }).map((t) => t.name);
expect(names).toContain('open_page');
expect(names).not.toContain('parse_order_text');
const result = await executeCapability('parse_order_text', {
userId: 's1',
ctx: supplier,
args: { customer_code: 'C1', text: '土豆10斤' },
surface: 'web',
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.code).toBe('forbidden');
});
it('empty modules array means no specialist tools', () => {
const names = listCapabilityToolSchemas({
ctx: superAdmin,
surface: 'web',
modules: [],
}).map((t) => t.name);
expect(names).toEqual([]);
});
it('does not include parse when Host is limited to navigate', () => {
const names = listCapabilityToolSchemas({
ctx: superAdmin,
surface: 'web',
modules: ['navigate'],
}).map((t) => t.name);
expect(names).toContain('open_page');
expect(names).toContain('set_page_fields');
expect(names).toContain('run_page_action');
expect(names).not.toContain('parse_order_text');
expect(names).not.toContain('patch_order_draft');
});
it('set_page_fields still emits ui when snapshot missing so FAB can apply after navigate', async () => {
const result = await executeCapability('set_page_fields', {
userId: 'u1',
ctx: superAdmin,
args: { patches: [{ name: 'date_from', value: '2026-09-02' }] },
surface: 'web',
});
expect(result.ok).toBe(true);
if (result.ok) {
const data = result.data as { ui?: { type: string; patches?: Array<{ name: string }> } };
expect(data.ui?.type).toBe('set_fields');
expect(data.ui?.patches?.[0]?.name).toBe('date_from');
}
});
it('rejects price patches in set_page_fields', async () => {
await expect(
executeCapability('set_page_fields', {
userId: 'u1',
ctx: superAdmin,
args: { patches: [{ name: 'price', value: 9 }] },
surface: 'web',
snapshot: { pageId: 'customer-order' },
})
).rejects.toMatchObject({ code: 'forbidden_field' });
});
});
describe('routeModules · 自然说法(2026-09-22 可用性核查修复)', () => {
const all = ASSISTANT_MODULES.map((row) => row.id);
const modulesOf = (text: string) => routeModules({ text, visibleModuleIds: all }).modules;
it('「查一下…的订单」这类查询走订单管理,且不带录单写工具', () => {
for (const text of ['查一下 2026-09-21 的订单', '看一下订单', '查查昨天的订单']) {
const modules = modulesOf(text);
expect(modules, text).toContain('order-management');
expect(modules, text).not.toContain('order-entry');
}
});
it('库存/采购/验收/加工/结算单等自然说法能落到对应模块', () => {
expect(modulesOf('查一下库存')).toContain('inventory-stock');
expect(modulesOf('查一下采购')).toContain('self-purchase');
expect(modulesOf('昨天的验收情况')).toContain('inbound-list');
expect(modulesOf('查一下加工任务')).toContain('processing');
expect(modulesOf('查一下结算单')).toContain('customer-statements');
expect(modulesOf('看一下客户')).toContain('customers');
});
it('明确录单意图时仍保留录单模块(量词/录一下)', () => {
const modules = modulesOf('客户张三要 5 斤土豆,帮我录一下');
expect(modules).toContain('order-entry');
expect(modulesOf('给张记食堂:土豆10斤')).toContain('order-entry');
});
});
describe('routeModules', () => {
it('routes potato order text to order-entry', () => {
const result = routeModules({
text: '给张记食堂:土豆10斤',
visibleModuleIds: ['navigate', 'order-entry'],
});
expect(result.modules).toContain('order-entry');
expect(result.modules).toContain('navigate');
});
it('does not route to parse module without order-entry visible', () => {
const result = routeModules({
text: '给张记食堂:土豆10斤',
visibleModuleIds: ['navigate'],
});
expect(result.modules).not.toContain('order-entry');
});
it('keeps hint on follow-up quantity change', () => {
const result = routeModules({
text: '改成20斤',
visibleModuleIds: ['navigate', 'order-entry'],
hintModule: 'order-entry',
});
expect(result.modules).toContain('order-entry');
});
it('marks finance as placeholder without tools', () => {
const result = routeModules({
text: '对账单在哪看',
visibleModuleIds: ['navigate', 'order-entry', 'finance'],
});
expect(result.placeholders).toContain('finance');
});
it('routes self-purchase talk to self-purchase and navigate', () => {
const result = routeModules({
text: '打开自采管理',
visibleModuleIds: ['navigate', 'order-entry', 'self-purchase'],
});
expect(result.modules).toContain('self-purchase');
expect(result.modules).toContain('navigate');
expect(result.modules).not.toContain('order-entry');
});
it('keeps potato text on order-entry even if self-purchase is visible', () => {
const result = routeModules({
text: '给张记食堂:土豆10斤',
visibleModuleIds: ['navigate', 'order-entry', 'self-purchase'],
});
expect(result.modules).toContain('order-entry');
expect(result.modules).not.toContain('self-purchase');
});
it('prefers self-purchase over order-entry when text has 自采 and 下单', () => {
const result = routeModules({
text: '查询一下昨天自采下单了多少条商品',
visibleModuleIds: ['navigate', 'order-entry', 'self-purchase'],
});
expect(result.modules).toContain('self-purchase');
expect(result.modules).not.toContain('order-entry');
});
it('prefers order-management over order-entry for 昨天订单多少条', () => {
const result = routeModules({
text: '昨天订单多少条',
visibleModuleIds: ['navigate', 'order-entry', 'order-management', 'self-purchase'],
});
expect(result.modules).toContain('order-management');
expect(result.modules).not.toContain('order-entry');
expect(result.modules).not.toContain('self-purchase');
});
it('prefers order-management when asking if yesterday orders contain a sku', () => {
const result = routeModules({
text: '帮我看看昨天的订单是否存在土豆',
visibleModuleIds: ['navigate', 'order-entry', 'order-management', 'self-purchase'],
});
expect(result.modules).toContain('order-management');
expect(result.modules).not.toContain('order-entry');
});
it('prefers order-management for 查询最近7日土豆 without 订单', () => {
const result = routeModules({
text: '查询一下最近7日的土豆',
visibleModuleIds: ['navigate', 'order-entry', 'order-management', 'self-purchase'],
});
expect(result.modules).toContain('order-management');
expect(result.modules).not.toContain('order-entry');
});
it('does not send 自采多少条 to order-management', () => {
const result = routeModules({
text: '昨天自采多少条',
visibleModuleIds: ['navigate', 'order-entry', 'order-management', 'self-purchase'],
});
expect(result.modules).toContain('self-purchase');
expect(result.modules).not.toContain('order-management');
expect(result.modules).not.toContain('order-entry');
});
it('prefers order-management when editing an existing order code', () => {
const byCode = routeModules({
text: '改 ORD_WEB_1',
visibleModuleIds: ['navigate', 'order-entry', 'order-management'],
});
expect(byCode.modules).toContain('order-management');
expect(byCode.modules).not.toContain('order-entry');
const byPhrase = routeModules({
text: '我想修改这个订单',
visibleModuleIds: ['navigate', 'order-entry', 'order-management'],
});
expect(byPhrase.modules).toContain('order-management');
expect(byPhrase.modules).not.toContain('order-entry');
});
it('routes 打开备货表 to supplier-prep and navigate', () => {
const result = routeModules({
text: '打开备货表',
visibleModuleIds: ['navigate', 'order-entry', 'self-purchase', 'supplier-prep'],
});
expect(result.modules).toContain('supplier-prep');
expect(result.modules).toContain('navigate');
expect(result.modules).not.toContain('order-entry');
});
});
describe('toToolSchema', () => {
it('strips confirm from properties', () => {
const schema = toToolSchema({
name: 'x',
description: 'd',
inputSchema: { type: 'object', properties: { confirm: { type: 'boolean' }, a: { type: 'string' } } },
permissions: [],
effect: 'write',
surfaces: ['api'],
module: 'order-entry',
handler: async () => ({}),
});
expect((schema.inputSchema.properties as Record<string, unknown>).confirm).toBeUndefined();
});
it('infers create update delete grades without treating reject as delete', () => {
expect(inferWriteActionType('create_after_sale')).toBe('create');
expect(inferWriteActionType('complete_preparation')).toBe('update');
expect(inferWriteActionType('reject_prep_amend')).toBe('update');
expect(inferWriteActionType('delete_order')).toBe('delete');
expect(inferWriteActionType('void_inbound')).toBe('delete');
});
});
describe('listCapableModuleIds', () => {
it('supplier only has navigate(外加对其自身会话可用的 memory)', () => {
// 2026-09-22:新增 read_conversation_history(module=memory)——它只读**自己的会话**,
// 无权限门槛,因此任何登录账号都会多出 memory 模块(业务模块仍只有 navigate)。
expect(listCapableModuleIds({ ctx: supplier, surface: 'web' })).toEqual(['memory', 'navigate']);
});
it('exposes the read-only current time tool without permissions', () => {
const tools = listCapabilityToolSchemas({ ctx: supplier, surface: 'web', modules: ['navigate'] });
const currentTime = tools.find((tool) => tool.name === 'get_current_time');
expect(currentTime).toBeDefined();
expect(currentTime?.description).toMatch(/中国标准时间/);
expect(currentTime?.inputSchema.required).toBeUndefined();
});
it('hides self-purchase without purchase_manage', () => {
const clerk: TenantContext = {
userId: 'c1',
roles: ['operator'],
permissions: ['order_entry'],
branchCode: 'BR001',
supplierCode: null,
purchaserCode: null,
isSuperAdmin: false,
isBranchAdmin: false,
isInternalStaff: true,
isSupplierAccount: false,
};
expect(listCapableModuleIds({ ctx: clerk, surface: 'web' })).not.toContain('self-purchase');
const names = listCapabilityToolSchemas({ ctx: clerk, surface: 'web', modules: ['self-purchase', 'navigate'] }).map(
(t) => t.name
);
expect(names).not.toContain('open_self_purchase');
});
it('exposes open_self_purchase on web with purchase_manage and no purchase writes', () => {
const purchaser: TenantContext = {
userId: 'p1',
roles: ['purchaser'],
permissions: ['purchase_manage'],
branchCode: 'BR001',
supplierCode: null,
purchaserCode: 'PUR1',
isSuperAdmin: false,
isBranchAdmin: false,
isInternalStaff: true,
isSupplierAccount: false,
};
expect(listCapableModuleIds({ ctx: purchaser, surface: 'web' })).toContain('self-purchase');
const names = listCapabilityToolSchemas({
ctx: purchaser,
surface: 'web',
modules: ['self-purchase', 'navigate'],
}).map((t) => t.name);
expect(names).toContain('open_self_purchase');
expect(names).toContain('list_self_purchases');
const tools = listCapabilityToolSchemas({
ctx: purchaser,
surface: 'web',
modules: ['self-purchase', 'navigate'],
});
const listPages = tools.find((t) => t.name === 'list_pages');
expect(listPages?.description).toMatch(/在哪/);
const listSelf = tools.find((t) => t.name === 'list_self_purchases');
expect(listSelf?.inputSchema.required).toEqual(expect.arrayContaining(['date_from']));
expect(JSON.stringify(listSelf?.inputSchema)).not.toMatch(/yesterday/);
expect((listSelf?.inputSchema.properties as Record<string, unknown>)?.day).toBeUndefined();
expect(names).not.toContain('submit_order');
expect(names.join(',')).not.toMatch(/complete_purchase|amend_actual|assign_purchase/i);
const mpNames = listCapabilityToolSchemas({ ctx: purchaser, surface: 'miniprogram' }).map((t) => t.name);
expect(mpNames).not.toContain('open_self_purchase');
});
it('hides supplier-prep without preparation_manage', () => {
const clerk: TenantContext = {
userId: 'c1',
roles: ['operator'],
permissions: ['order_entry', 'purchase_manage'],
branchCode: 'BR001',
supplierCode: null,
purchaserCode: null,
isSuperAdmin: false,
isBranchAdmin: false,
isInternalStaff: true,
isSupplierAccount: false,
};
expect(listCapableModuleIds({ ctx: clerk, surface: 'web' })).not.toContain('supplier-prep');
const names = listCapabilityToolSchemas({
ctx: clerk,
surface: 'web',
modules: ['supplier-prep', 'navigate'],
}).map((t) => t.name);
expect(names).not.toContain('open_supplier_prep');
expect(names).not.toContain('list_preparations');
});
it('exposes supplier-prep tools on web with preparation_manage', () => {
const prepAdmin: TenantContext = {
userId: 'p1',
roles: ['admin'],
permissions: ['preparation_manage'],
branchCode: 'BR001',
supplierCode: null,
purchaserCode: null,
isSuperAdmin: false,
isBranchAdmin: false,
isInternalStaff: true,
isSupplierAccount: false,
};
expect(listCapableModuleIds({ ctx: prepAdmin, surface: 'web' })).toContain('supplier-prep');
const tools = listCapabilityToolSchemas({
ctx: prepAdmin,
surface: 'web',
modules: ['supplier-prep', 'navigate'],
});
const names = tools.map((t) => t.name);
expect(names).toContain('open_supplier_prep');
expect(names).toContain('list_preparations');
expect(names).toContain('list_prep_amend_pending');
expect(names).toContain('complete_preparation');
expect(names).toContain('transfer_prep_stockout');
expect(names).toContain('update_prep_purchase_price');
expect(names).toContain('confirm_prep_amend');
expect(names).toContain('reject_prep_amend');
const listPrep = tools.find((t) => t.name === 'list_preparations');
expect(listPrep?.inputSchema.required).toEqual(expect.arrayContaining(['date_from']));
expect(JSON.stringify(listPrep?.inputSchema)).not.toMatch(/yesterday/);
const complete = tools.find((t) => t.name === 'complete_preparation');
expect((complete?.inputSchema.properties as Record<string, unknown>)?.confirm).toBeUndefined();
const mpNames = listCapabilityToolSchemas({ ctx: prepAdmin, surface: 'miniprogram' }).map((t) => t.name);
expect(mpNames).not.toContain('open_supplier_prep');
expect(mpNames).not.toContain('list_preparations');
});
});
describe('open_self_purchase', () => {
it('returns navigate ui for /purchase when the page is visible', async () => {
const result = await executeCapability('open_self_purchase', {
userId: 'u1',
ctx: superAdmin,
args: {},
surface: 'web',
visiblePages: [{ path: '/purchase', label: '自采管理' }],
});
expect(result.ok).toBe(true);
if (result.ok) {
const data = result.data as { ui: { type: string; web?: { path: string } } };
expect(data.ui.type).toBe('navigate');
expect(data.ui.web?.path).toBe('/purchase');
}
});
});
describe('open_supplier_prep', () => {
it('returns navigate ui for /purchase/preparations when the page is visible', async () => {
const result = await executeCapability('open_supplier_prep', {
userId: 'u1',
ctx: superAdmin,
args: {},
surface: 'web',
visiblePages: [{ path: '/purchase/preparations', label: '供应商备货表' }],
});
expect(result.ok).toBe(true);
if (result.ok) {
const data = result.data as { ui: { type: string; web?: { path: string } } };
expect(data.ui.type).toBe('navigate');
expect(data.ui.web?.path).toBe('/purchase/preparations');
}
});
it('order_entry-only clerk has no order-management tools', () => {
const clerk: TenantContext = {
userId: 'c1',
roles: ['operator'],
permissions: ['order_entry'],
branchCode: 'BR001',
supplierCode: null,
purchaserCode: null,
isSuperAdmin: false,
isBranchAdmin: false,
isInternalStaff: true,
isSupplierAccount: false,
};
expect(listCapableModuleIds({ ctx: clerk, surface: 'web' })).not.toContain('order-management');
const names = listCapabilityToolSchemas({
ctx: clerk,
surface: 'web',
modules: ['order-management', 'order-entry'],
}).map((t) => t.name);
expect(names).not.toContain('list_orders');
expect(names).not.toContain('get_order_detail');
expect(names).not.toContain('prepare_order_edit');
});
it('order_view unlocks list; order_edit unlocks prepare_order_edit', () => {
const viewer: TenantContext = {
userId: 'v1',
roles: ['operator'],
permissions: ['order_entry', 'order_view'],
branchCode: 'BR001',
supplierCode: null,
purchaserCode: null,
isSuperAdmin: false,
isBranchAdmin: false,
isInternalStaff: true,
isSupplierAccount: false,
};
expect(listCapableModuleIds({ ctx: viewer, surface: 'web' })).toContain('order-management');
const viewNames = listCapabilityToolSchemas({
ctx: viewer,
surface: 'web',
modules: ['order-management'],
}).map((t) => t.name);
expect(viewNames).toContain('list_orders');
expect(viewNames).not.toContain('prepare_order_edit');
const editor: TenantContext = {
...viewer,
userId: 'e1',
permissions: ['order_entry', 'order_view', 'order_edit'],
};
const editNames = listCapabilityToolSchemas({
ctx: editor,
surface: 'web',
modules: ['order-management'],
}).map((t) => t.name);
expect(editNames).toContain('prepare_order_edit');
});
});
describe('OPEN_PAGE_BY_TOOL', () => {
it('maps existing shortcuts and open_after_sales still navigates', async () => {
expect(OPEN_PAGE_BY_TOOL.open_self_purchase).toBe('/purchase');
expect(OPEN_PAGE_BY_TOOL.open_after_sales).toBe('/ops');
const result = await executeCapability('open_after_sales', {
userId: 'u1',
ctx: superAdmin,
args: {},
surface: 'web',
visiblePages: [{ path: '/ops', label: '售后与预警管理' }],
});
expect(result.ok).toBe(true);
if (result.ok) {
const data = result.data as { ui: { type: string; web?: { path: string } } };
expect(data.ui.web?.path).toBe('/ops');
}
});
});