import { readFileSync } from 'node:fs'; import path from 'node:path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { TenantContext } from '../src/services/tenantScope'; vi.mock('../src/services/orderManagementQueryService', () => ({ listOrdersForManagement: vi.fn(async (_ctx: TenantContext, branchCode: string | null) => ({ rows: [{ order_code: 'ORD1', customer_code: 'C1', company_name: '张记', delivery_date: '2026-09-23', order_status: 20, total_amount: 1 }], total: 1, totalAmount: 1, stats: {}, _branch: branchCode, })), })); vi.mock('../src/services/preparationListQueryService', () => ({ listPreparationsForManagement: vi.fn(async (input: { branchCode?: string | null }) => ({ rows: [{ id: 'prep-1', item_name: '土豆', supplier_name: '张记', prepare_qty: 1, unit: '斤', prepare_status: 10, order_code: 'ORD1', delivery_date: '2026-09-23' }], stats: { total: 1 }, _branch: input.branchCode, })), })); vi.mock('../src/services/purchaseOrderQueryService', () => ({ listPurchaseOrdersForManagement: vi.fn(async (_ctx: TenantContext, branchCode: string | null) => ({ rows: [], total: 0, stats: {}, _branch: branchCode, })), })); vi.mock('../src/services/aftersaleOps', () => ({ listAfterSalesForManagement: vi.fn(async () => ({ rows: [], total: 0 })), createAfterSalesWithValidation: vi.fn(async () => ({ aftersale_code: 'AR9' })), acceptAfterSale: vi.fn(async () => ({})), rejectAfterSale: vi.fn(async () => ({})), handleAfterSalesWithValidation: vi.fn(async () => ({})), getAfterSaleOrderContext: vi.fn(async () => ({ order_code: 'ORD1', customer_code: 'C001', items: [] })), })); 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: [], orderCodes: [] })), })); import { listOrdersForManagement } from '../src/services/orderManagementQueryService'; import { listPreparationsForManagement } from '../src/services/preparationListQueryService'; import { listPurchaseOrdersForManagement } from '../src/services/purchaseOrderQueryService'; import { createAfterSalesWithValidation } from '../src/services/aftersaleOps'; import { updateSupplierPreparationStatus } from '../src/services/supplierPreparationStatusService'; import { executeCapability, listCapabilityToolSchemas } from '../src/capabilities/registry'; import * as capabilityRegistry from '../src/capabilities/registry'; import { registerBuiltinCapabilities } from '../src/capabilities/registerBuiltins'; import { filterAssistantVisiblePages, isAssistantPageAllowed } from '../src/mcp/assistantVisiblePages'; import { sanitizeAssistantSnapshot } from '../src/mcp/assistantSnapshot'; import { matchAssistantL0Intent, tryAssistantL0 } from '../src/mcp/assistantL0'; import { TOOL_HANDLERS } from '../src/mcp/tools'; import { runOrderEntryAgentConfirm } from '../src/mcp/orderEntryAgentHost'; import { resetAssistantSessionsForTests, writeAssistantSession, } from '../src/services/assistantSessionStore'; 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 staff: TenantContext = { userId: 'staff1', roles: ['operator'], permissions: ['order_entry'], branchCode: 'BR002', supplierCode: null, purchaserCode: null, isSuperAdmin: false, isBranchAdmin: false, isInternalStaff: true, isSupplierAccount: false, }; describe('assistant optimize P2c', () => { beforeEach(() => { vi.mocked(createAfterSalesWithValidation).mockClear(); vi.mocked(updateSupplierPreparationStatus).mockClear(); vi.mocked(listOrdersForManagement).mockClear(); vi.mocked(listPreparationsForManagement).mockClear(); vi.mocked(listPurchaseOrdersForManagement).mockClear(); resetAssistantSessionsForTests(); }); it('create_after_sale preview includes 金额 and does not write without confirm', async () => { const result = await executeCapability('create_after_sale', { userId: 'u1', ctx: superAdmin, args: { order_code: 'ORD1', customer_code: 'C001', description: '少货', amount: 12.5 }, surface: 'web', }); expect(result.ok).toBe(false); if (!result.ok) { expect(result.code).toBe('need_confirm'); expect(result.preview?.diff.some((row) => row.field === '金额' && row.after === 12.5)).toBe(true); } expect(createAfterSalesWithValidation).not.toHaveBeenCalled(); }); it('create_after_sale handler without confirm does not write', async () => { let thrown: { code?: string } | null = null; try { await TOOL_HANDLERS.create_after_sale({ userId: 'u1', ctx: superAdmin, name: 'create_after_sale', args: { order_code: 'ORD1', customer_code: 'C001', description: '少货' }, extra: {}, pages: [], }); } catch (error) { thrown = error as { code?: string }; } expect(thrown?.code).toBe('need_confirm'); expect(createAfterSalesWithValidation).not.toHaveBeenCalled(); }); it('complete_preparation without confirm does not write; confirm passes ctx.branchCode', async () => { const pending = await executeCapability('complete_preparation', { userId: 'u1', ctx: { ...superAdmin, branchCode: 'BR002' }, args: { ids: ['prep-1'] }, surface: 'web', }); expect(pending.ok).toBe(false); expect(updateSupplierPreparationStatus).not.toHaveBeenCalled(); const done = await executeCapability('complete_preparation', { userId: 'u1', ctx: { ...superAdmin, branchCode: 'BR002' }, args: { ids: ['prep-1'] }, surface: 'web', confirmedActionId: 'complete_preparation', }); expect(done.ok).toBe(true); expect(updateSupplierPreparationStatus).toHaveBeenCalledWith( expect.anything(), expect.objectContaining({ branchCode: 'BR002' }) ); }); it('write capabilities are forbidden without prep/after_sale permission', async () => { const prep = await executeCapability('complete_preparation', { userId: staff.userId, ctx: staff, args: { ids: ['prep-1'] }, surface: 'web', }); expect(prep).toMatchObject({ ok: false, code: 'forbidden' }); const after = await executeCapability('create_after_sale', { userId: staff.userId, ctx: staff, args: { order_code: 'ORD1', customer_code: 'C1', description: 'x' }, surface: 'web', }); expect(after).toMatchObject({ ok: false, code: 'forbidden' }); expect(createAfterSalesWithValidation).not.toHaveBeenCalled(); }); it('forged /ops is not allowed without aftersales capability', () => { expect(isAssistantPageAllowed('/ops', staff, 'web')).toBe(false); const filtered = filterAssistantVisiblePages( [ { path: '/ops', label: '售后与预警管理' }, { path: '/customer-order', label: '录单' }, ], staff, 'web' ); expect(filtered.map((row) => row.path)).toEqual(['/customer-order']); }); it('open_page to after-sales is 403 when the account cannot use after-sales', async () => { await expect( executeCapability('open_page', { userId: staff.userId, ctx: staff, args: { path: '/ops' }, surface: 'web', visiblePages: [{ path: '/ops', label: '售后与预警管理' }], }) ).rejects.toMatchObject({ status: 403, code: 'forbidden' }); }); it('account B cannot confirm account A pending write', async () => { await writeAssistantSession('u1', 's1', { lastModule: 'after-sales', lastUser: '建售后', lastReply: '请确认', traces: [], pendingWrite: { capability: 'create_after_sale', args: { order_code: 'ORD1', customer_code: 'C001', description: '少货' }, }, }); await expect( runOrderEntryAgentConfirm({ userId: 'u2', ctx: superAdmin, sessionId: 's1', confirmedActionId: 'create_after_sale', client: 'web', }) ).rejects.toMatchObject({ code: 'confirm_mismatch' }); expect(createAfterSalesWithValidation).not.toHaveBeenCalled(); }); it('snapshot sanitizer drops price fields', () => { const out = sanitizeAssistantSnapshot({ pageId: 'order-management', path: '/orders', values: { selected_order_code: 'ORD1', unit_cost: '9.9', sale_price: '12', search: '土豆' }, }); expect(out?.values).toEqual({ selected_order_code: 'ORD1', search: '土豆' }); }); it('L0 matches thin edit / stockout / after-sale and skips complex edit', () => { expect(matchAssistantL0Intent('改单 ORD88 数量 2')?.kind).toBe('prepare_order_edit'); expect(matchAssistantL0Intent('把 prep 转自采 11111111-1111-4111-8111-111111111111')?.kind).toBe( 'transfer_prep_stockout' ); expect(matchAssistantL0Intent('给订单 ORD88 建售后 少货 金额 10')?.kind).toBe('create_after_sale'); expect(matchAssistantL0Intent('改单 ORD88 派供应商')).toBeNull(); }); it('L0 write path never passes confirmedActionId and still returns preview', async () => { const spy = vi.spyOn(capabilityRegistry, 'executeCapability').mockImplementation(async (name, input) => { expect('confirmedActionId' in input).toBe(false); if (name === 'get_order_detail') { return { ok: true, data: { order: { order_code: 'ORD88' }, items: [] } }; } if (name === 'prepare_order_edit') { return { ok: false, code: 'need_confirm', message: '请确认', action_id: 'prepare_order_edit', preview: { action_type: 'update', capability: 'prepare_order_edit', target_type: 'order', summary: '改单', diff: [], }, }; } return { ok: false, code: 'forbidden', message: 'no' }; }); const hit = await tryAssistantL0({ userId: 'u1', userText: '改单 ORD88 数量 2', ctx: superAdmin, surface: 'web', }); expect(hit?.pendingWrite?.capability).toBe('prepare_order_edit'); expect(hit?.ui_actions[0]?.type).toBe('preview_change'); expect(spy.mock.calls.every((call) => !('confirmedActionId' in call[1]))).toBe(true); spy.mockRestore(); }); it('get_order_bundle / get_supply_today reuse list ctx branchCode; old list tools remain', async () => { const names = listCapabilityToolSchemas({ ctx: superAdmin, surface: 'web' }).map((row) => row.name); expect(names).toEqual(expect.arrayContaining(['list_orders', 'list_preparations', 'list_self_purchases', 'list_after_sales'])); expect(names).toEqual(expect.arrayContaining(['get_order_bundle', 'get_supply_today', 'get_after_sale_bundle'])); const bundle = await executeCapability('get_order_bundle', { userId: 'u1', ctx: { ...staff, permissions: ['order_manage'] }, args: { date_from: '2026-09-23' }, surface: 'web', }); expect(bundle.ok).toBe(true); expect(listOrdersForManagement).toHaveBeenCalledWith( expect.objectContaining({ branchCode: 'BR002' }), 'BR002', expect.anything() ); const supply = await executeCapability('get_supply_today', { userId: 'u1', ctx: { ...superAdmin, branchCode: 'BR003' }, args: { date_from: '2026-09-23' }, surface: 'web', }); expect(supply.ok).toBe(true); expect(listPreparationsForManagement).toHaveBeenCalledWith( expect.objectContaining({ branchCode: 'BR003' }) ); expect(listPurchaseOrdersForManagement).toHaveBeenCalledWith( expect.objectContaining({ branchCode: 'BR003' }), 'BR003', expect.anything() ); }); it('chat host L0 and chat loop never pass confirmedActionId; order detail is branch-scoped', () => { const host = readFileSync(path.join(__dirname, '../src/mcp/orderEntryAgentHost.ts'), 'utf8'); const chat = host.slice( host.indexOf('export async function runOrderEntryAgentChat'), host.indexOf('export async function runOrderEntryAgentConfirm') ); expect(chat).not.toMatch(/confirmedActionId/); const l0 = readFileSync(path.join(__dirname, '../src/mcp/assistantL0.ts'), 'utf8'); expect(l0).not.toMatch(/confirmedActionId\s*:/); const orders = readFileSync(path.join(__dirname, '../src/mcp/tools/orders.ts'), 'utf8'); expect(orders).toContain('ctx.isSuperAdmin ? null : ctx.branchCode'); expect(orders).toContain('assertOrderCodeAccess(orderCode, run.ctx)'); const prep = readFileSync(path.join(__dirname, '../src/mcp/tools/supplierPrep.ts'), 'utf8'); expect(prep).toContain('branchCode: run.ctx.branchCode'); expect(prep).not.toContain('branchCode: null'); }); });