import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { TenantContext } from '../src/services/tenantScope'; vi.mock('../src/services/preparationListQueryService', () => ({ listPreparationsForManagement: vi.fn(async () => ({ rows: [ { id: 'prep-1', item_name: '土豆', supplier_name: '张记', prepare_qty: 10, unit: '斤', prepare_status: 10, order_code: 'ORD1', delivery_date: '2026-09-02', }, ], stats: { pending: 1, in_progress: 0, completed: 0, exception: 0, stockout: 0, transferred: 0, total: 1, }, })), })); vi.mock('../src/services/supplierPreparationStatusService', () => ({ updateSupplierPreparationStatus: vi.fn(async () => ({ updated: 1, needsCustomerPrice: false, })), updatePreparationPurchasePrice: vi.fn(async () => ({ updated: 1, needsCustomerPrice: false, })), })); vi.mock('../src/services/preparationStockoutService', () => ({ transferPreparationStockoutBatch: vi.fn(async () => ({ purchaseCodes: ['PO1'], orderCodes: ['ORD1'] })), })); vi.mock('../src/services/prepAmendRequestService', () => ({ listPendingPrepAmends: vi.fn(async () => []), confirmPrepAmend: vi.fn(async () => ({ request: { id: 'r1' }, closed_loop: {} })), rejectPrepAmend: vi.fn(async () => ({ id: 'r1', status: 30 })), })); import { listPreparationsForManagement } from '../src/services/preparationListQueryService'; import { updateSupplierPreparationStatus } from '../src/services/supplierPreparationStatusService'; import { executeCapability } from '../src/capabilities/registry'; import { registerBuiltinCapabilities } from '../src/capabilities/registerBuiltins'; import { uiActionsFromCapabilityResult, runOrderEntryAgentConfirm } from '../src/mcp/orderEntryAgentHost'; import { readAssistantSession, resetAssistantSessionsForTests, writeAssistantSession, } from '../src/services/assistantSessionStore'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; registerBuiltinCapabilities(); const superAdmin: TenantContext = { userId: 'u1', roles: ['super_admin'], permissions: [], branchCode: 'BR001', supplierCode: null, purchaserCode: null, isSuperAdmin: true, isBranchAdmin: false, isInternalStaff: true, isSupplierAccount: false, }; describe('list_preparations', () => { beforeEach(() => { vi.mocked(listPreparationsForManagement).mockClear(); }); it('asks for date_from instead of defaulting to today', async () => { const result = await executeCapability('list_preparations', { userId: 'u1', ctx: superAdmin, args: {}, surface: 'web', }); expect(result.ok).toBe(false); if (!result.ok) { expect(result.code).toBe('need_input'); expect(result.missing).toContain('date_from'); } expect(listPreparationsForManagement).not.toHaveBeenCalled(); }); it('passes explicit YYYY-MM-DD range to shared list', async () => { const result = await executeCapability('list_preparations', { userId: 'u1', ctx: superAdmin, args: { date_from: '2026-09-02' }, surface: 'web', }); expect(result.ok).toBe(true); if (result.ok) { const data = result.data as { count: number; items: Array<{ item_name: string }>; date_from: string }; expect(data.count).toBe(1); expect(data.items[0].item_name).toBe('土豆'); expect(data.date_from).toBe('2026-09-02'); } expect(listPreparationsForManagement).toHaveBeenCalledWith( expect.objectContaining({ dateFrom: '2026-09-02', dateTo: '2026-09-02', }) ); }); it('syncs web prep table filters including empty status and active→normal', async () => { const result = await executeCapability('list_preparations', { userId: 'u1', ctx: superAdmin, args: { date_from: '2026-09-02', stockout: 'active', sync_page: true }, surface: 'web', visiblePages: [{ path: '/purchase/preparations', label: '供应商备货表' }], }); expect(result.ok).toBe(true); if (!result.ok) return; const data = result.data as { ui: Array<{ type: string; patches?: Array<{ name: string; value: unknown }> }>; }; const setFields = data.ui.find((row) => row.type === 'set_fields'); expect(setFields?.patches).toEqual( expect.arrayContaining([ { name: 'date_from', value: '2026-09-02' }, { name: 'date_to', value: '2026-09-02' }, { name: 'stockout', value: 'normal' }, { name: 'status', value: '' }, ]) ); expect(data.ui.some((row) => row.type === 'navigate')).toBe(true); }); }); describe('complete_preparation confirm gate', () => { beforeEach(() => { vi.mocked(updateSupplierPreparationStatus).mockClear(); }); it('returns need_confirm without confirmed_action_id and does not write', async () => { const result = await executeCapability('complete_preparation', { userId: 'u1', ctx: superAdmin, args: { ids: ['prep-1'] }, surface: 'web', }); expect(result.ok).toBe(false); if (!result.ok) { expect(result.code).toBe('need_confirm'); expect(result.action_id).toBe('complete_preparation'); expect(result.preview).toMatchObject({ action_type: 'update', capability: 'complete_preparation', }); } expect(updateSupplierPreparationStatus).not.toHaveBeenCalled(); const actions = uiActionsFromCapabilityResult('complete_preparation', result); expect(actions[0]?.type).toBe('preview_change'); }); }); describe('confirm without LLM', () => { beforeEach(() => { resetAssistantSessionsForTests(); vi.mocked(updateSupplierPreparationStatus).mockClear(); }); it('executes pending write from session without calling chat', async () => { await writeAssistantSession('u1', 's1', { lastModule: 'supplier-prep', lastUser: '完成备货', lastReply: '请确认', traces: [], pendingWrite: { capability: 'complete_preparation', args: { ids: ['prep-1'] } }, }); const result = await runOrderEntryAgentConfirm({ userId: 'u1', ctx: superAdmin, sessionId: 's1', confirmedActionId: 'complete_preparation', client: 'web', }); expect(result.provider).toBe('confirm'); expect(result.tool_trace[0]?.ok).toBe(true); expect(updateSupplierPreparationStatus).toHaveBeenCalled(); const session = await readAssistantSession('u1', 's1'); expect(session?.pendingWrite).toBeNull(); }); it('rejects confirm when pending capability does not match', async () => { await writeAssistantSession('u1', 's1', { lastModule: 'supplier-prep', lastUser: '完成备货', lastReply: '请确认', traces: [], pendingWrite: { capability: 'complete_preparation', args: { ids: ['prep-1'] } }, }); await expect( runOrderEntryAgentConfirm({ userId: 'u1', ctx: superAdmin, sessionId: 's1', confirmedActionId: 'create_after_sale', client: 'web', }) ).rejects.toMatchObject({ code: 'confirm_mismatch' }); expect(updateSupplierPreparationStatus).not.toHaveBeenCalled(); }); }); describe('mobile preparations GET contract', () => { it('still calls shared list without assistant date_from gate', () => { const source = readFileSync(join(__dirname, '../src/routes/mobile/mobileAdminRoutes.ts'), 'utf8'); expect(source).toContain("router.get('/admin/preparations'"); expect(source).toContain('listPreparationsForManagement'); expect(source).not.toMatch(/need_input/); }); }); describe('web prep page contract', () => { it('registers only on admin table and maps list patches', () => { const page = readFileSync( join(__dirname, '../../src/pages/purchase/supplierPreparation/SupplierPreparationPage.tsx'), 'utf8' ); expect(page).toContain("pageId: 'purchase-preparations'"); expect(page).toContain('if (isSupplierScoped) return undefined'); expect(page).toContain('applyPrepCopilotFieldPatches'); const tools = readFileSync(join(__dirname, '../src/mcp/tools/supplierPrep.ts'), 'utf8'); expect(tools).toContain('buildPrepListPagePatches'); expect(tools).toContain('count: result.stats.total'); }); });