* fix(mcp): surface BFL 5 kap 6 § underlag requirements in voucher and transaction tooling Addresses a user report that the MCP surface treats document anchoring as optional convenience while the law treats it as mandatory: - create_voucher: description and inbox_item_id reframed as the compliant path for received handlingar; staging without a document now carries an advisory compliance_warning in the preview and a WARNING in the message (never blocks: IB/migration vouchers legitimately lack a kvitto). - High-risk approval guidance now tells the agent to surface any preview compliance_warning alongside the 5 kap 5 § irreversibility. - Approval-flow copy is scope-aware: staging responses and list_pending_operations explain that keys without pending_operations:approve (SoD) approve at /pending instead of hunting for a tool their catalog hides. - categorize/create/bulk_book transactions: state that a transaction models a cash-account movement and point cashless events (privat utlagg) at create_voucher instead of silently fabricating a bank line. - link_document_to_voucher: signposts the pre-posting inbox path. - /pending VoucherPreview shows an attn line when document_attached=false. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mcp): entity-neutral utlagg hint, coherent no-document envelope, real attn styling Addresses the skeptic refutations on da811a58f: - categorize_transaction: drop the 6540/2893 example; 2893 is AB-only (EF books egen insattning 2013/2018 per category-mapping.ts) and a static description cannot know the entity type. - create_voucher: when inbox_item_id is supplied but the item has no stored document (document_id NULL, ON DELETE SET NULL), the will-text no longer claims an OCR attach and the compliance warning gets an inbox variant instead of a dead-end 'restage with inbox_item_id'. Pinned by a new test. - /pending VoucherPreview: use the AttnLine component (the bare 'attn' class does not exist) and conditional wording so IB/internal vouchers are not falsely flagged under BFL 5 kap 6 \u00a7. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mcp): exempt IB vouchers from the underlag warning; UI mirrors the staged warning Swedish accounting review round 2: the warning keyed off document_attached alone, so migrated IB entries (and the /pending card for any old no-document row) were falsely flagged under BFL 5 kap 6 \u00a7. Staging now skips the complianceNote when is_opening_balance=true, and VoucherPreview gates on the staged compliance_warning instead of overloading document_attached, so the server owns the policy in one place. Pinned by a new IB test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mcp): trim two descriptions to fit the tools/list payload ceiling after merging main PR #1846 spent the 59,950 headroom; the merged state crossed by 7 tokens. Dropped the redundant filter enumeration from list_pending_operations (the schema documents the filters) and the dims-bags aside from bulk_book_transactions (the lines schema documents the bags). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
1077 lines
36 KiB
TypeScript
1077 lines
36 KiB
TypeScript
/**
|
|
* Staging-time gate tests for gnubok_create_voucher.
|
|
*
|
|
* The executor-level gates (period lock, balance, status === 'posted' for
|
|
* correct_entry) are tested in lib/pending-operations/__tests__/. This file
|
|
* covers the pre-staging gates added to the MCP tool layer for UX: explicit
|
|
* fiscal_period_id validation, inactive/missing account rejection, and the
|
|
* source_type-not-staged invariant.
|
|
*/
|
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { createQueuedMockSupabase } from '@/tests/helpers'
|
|
|
|
vi.mock('@/lib/bookkeeping/engine', async () => {
|
|
const actual = await vi.importActual<typeof import('@/lib/bookkeeping/engine')>(
|
|
'@/lib/bookkeeping/engine'
|
|
)
|
|
return {
|
|
...actual,
|
|
findFiscalPeriod: vi.fn(),
|
|
}
|
|
})
|
|
|
|
import { tools } from '../server'
|
|
import { findFiscalPeriod } from '@/lib/bookkeeping/engine'
|
|
|
|
const createVoucher = tools.find((t) => t.name === 'gnubok_create_voucher')!
|
|
const correctEntry = tools.find((t) => t.name === 'gnubok_correct_entry')!
|
|
const reverseEntry = tools.find((t) => t.name === 'gnubok_reverse_journal_entry')!
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
const balancedLines = [
|
|
{ account_number: '1010', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
|
|
]
|
|
|
|
describe('gnubok_create_voucher: staging gates', () => {
|
|
it('is registered and mapped to bookkeeping:write scope', async () => {
|
|
const { TOOL_SCOPE_MAP } = await import('@/lib/auth/api-keys')
|
|
expect(createVoucher).toBeDefined()
|
|
expect(createVoucher.annotations.readOnlyHint).toBe(false)
|
|
expect(TOOL_SCOPE_MAP.gnubok_create_voucher).toBe('bookkeeping:write')
|
|
})
|
|
|
|
it('rejects unbalanced lines before staging', async () => {
|
|
const { supabase } = createQueuedMockSupabase()
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'unbalanced',
|
|
fiscal_period_id: 'fp-1',
|
|
lines: [
|
|
{ account_number: '1010', debit_amount: 100, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 80 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/not balanced/i)
|
|
})
|
|
|
|
it('rejects when an explicit fiscal_period_id is closed', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
// fiscal_periods fetch returns a closed period
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-closed',
|
|
is_closed: true,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-03-31',
|
|
name: 'Q1 2026',
|
|
},
|
|
error: null,
|
|
})
|
|
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-02-15',
|
|
description: 'attempt to post in closed Q1',
|
|
fiscal_period_id: 'fp-closed',
|
|
lines: balancedLines,
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/låst/i)
|
|
// findFiscalPeriod must NOT be called when an explicit ID was supplied.
|
|
expect(findFiscalPeriod).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('rejects when an explicit fiscal_period_id does not exist', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: null, error: null }) // fiscal_periods fetch: not found
|
|
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'unknown period uuid',
|
|
fiscal_period_id: 'fp-nonexistent',
|
|
lines: balancedLines,
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/not found/i)
|
|
})
|
|
|
|
it('rejects when entry_date is outside the supplied period', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-03-31',
|
|
name: 'Q1 2026',
|
|
},
|
|
error: null,
|
|
})
|
|
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'date outside Q1',
|
|
fiscal_period_id: 'fp-1',
|
|
lines: balancedLines,
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/utanför/i)
|
|
})
|
|
|
|
it('rejects an account that is neither in the chart nor in BAS 2026', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
// chart_of_accounts knows only 1930: 4020 is a custom number the company
|
|
// never created, and it is absent from the BAS 2026 catalog, so the
|
|
// engine could not seed it either.
|
|
enqueue({
|
|
data: [{ account_number: '1930', account_name: 'Företagskonto', is_active: true }],
|
|
error: null,
|
|
})
|
|
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'custom account never created',
|
|
fiscal_period_id: 'fp-1',
|
|
lines: [
|
|
{ account_number: '4020', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/saknas i kontoplanen och finns inte i BAS 2026: 4020/i)
|
|
})
|
|
|
|
it('stages when a BAS 2026 account is merely absent from the chart (engine seeds it)', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
// 7690 (Övriga personalkostnader) is in BAS 2026 but not in this chart:
|
|
// the old gate rejected it even though createDraftEntry backfills it.
|
|
enqueue({
|
|
data: [{ account_number: '1930', account_name: 'Företagskonto', is_active: true }],
|
|
error: null,
|
|
})
|
|
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 1
|
|
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 2
|
|
enqueue({ data: { id: 'op-seedable' }, error: null }) // pending_operations insert
|
|
|
|
const result = (await createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'Friskvård badhus',
|
|
fiscal_period_id: 'fp-1',
|
|
lines: [
|
|
{ account_number: '7690', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
)) as {
|
|
staged: boolean
|
|
preview: {
|
|
will_activate_accounts?: string[]
|
|
lines: Array<{ account_number: string; account_name: string | null }>
|
|
}
|
|
}
|
|
|
|
expect(result.staged).toBe(true)
|
|
// The approver must see the activation side-effect and a named line
|
|
// (name from the BAS catalog, not a bare number).
|
|
expect(result.preview.will_activate_accounts).toEqual(['7690'])
|
|
const line7690 = result.preview.lines.find((l) => l.account_number === '7690')
|
|
expect(line7690?.account_name).toMatch(/personalkostnader/i)
|
|
})
|
|
|
|
it('rejects when a referenced account exists but is inactive', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1010', account_name: 'Balanserade utgifter', is_active: false },
|
|
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
|
|
],
|
|
error: null,
|
|
})
|
|
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'inactive account',
|
|
fiscal_period_id: 'fp-1',
|
|
lines: balancedLines,
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/inaktiv/i)
|
|
})
|
|
|
|
it('happy path: stages with no source_type in params (executor hardcodes it)', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1010', account_name: 'Balanserade utgifter', is_active: true },
|
|
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
|
|
],
|
|
error: null,
|
|
})
|
|
// resolvePeriodStatusForDate: layer 1 (company_settings) + layer 2 (fiscal_periods).
|
|
enqueue({ data: null, error: null })
|
|
enqueue({ data: null, error: null })
|
|
enqueue({ data: { id: 'op-staged' }, error: null }) // pending_operations insert
|
|
|
|
const result = (await createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'Capitalize Cursor',
|
|
fiscal_period_id: 'fp-1',
|
|
lines: balancedLines,
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
)) as { staged: boolean; operation_id?: string; message: string; preview: Record<string, unknown> }
|
|
|
|
expect(result.staged).toBe(true)
|
|
expect(result.operation_id).toBe('op-staged')
|
|
expect(result.preview.total_debit).toBe(250)
|
|
expect(result.preview.total_credit).toBe(250)
|
|
|
|
// No document attached: the advisory BFL 5 kap 6§ warning must reach both
|
|
// the agent (message) and the /pending approval card (preview) without
|
|
// blocking the staging itself.
|
|
expect(result.preview.document_attached).toBe(false)
|
|
expect(result.preview.compliance_warning).toMatch(/BFL 5 kap 6§/)
|
|
expect(result.preview.compliance_warning).toMatch(/underlag/i)
|
|
expect(result.message).toMatch(/WARNING:.*underlag/i)
|
|
|
|
// Critical: the staged pending_operations row must NOT carry source_type.
|
|
// The executor always hardcodes 'manual'. Look at the insert call.
|
|
const insertCalls = (supabase.from as ReturnType<typeof vi.fn>).mock.calls
|
|
expect(insertCalls.some((args) => args[0] === 'pending_operations')).toBe(true)
|
|
})
|
|
|
|
it('exposes inbox_item_id as an optional input', () => {
|
|
const schema = createVoucher.inputSchema as {
|
|
properties: { inbox_item_id?: { type: string; description?: string } }
|
|
required?: string[]
|
|
}
|
|
expect(schema.properties.inbox_item_id).toBeDefined()
|
|
expect(schema.properties.inbox_item_id?.type).toBe('string')
|
|
// Must NOT be required: voucher creation works standalone too.
|
|
expect(schema.required ?? []).not.toContain('inbox_item_id')
|
|
})
|
|
|
|
it('happy path with inbox_item_id: stages the op with inbox_item_id + document_id in params', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
|
|
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
|
|
],
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: {
|
|
id: 'inbox-1',
|
|
document_id: 'doc-1',
|
|
created_journal_entry_id: null,
|
|
created_supplier_invoice_id: null,
|
|
},
|
|
error: null,
|
|
}) // invoice_inbox_items lookup
|
|
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 1
|
|
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 2
|
|
enqueue({ data: { id: 'op-inbox' }, error: null }) // pending_operations insert
|
|
|
|
const result = (await createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'Kvitto från Clas Ohlson: adapter',
|
|
fiscal_period_id: 'fp-1',
|
|
inbox_item_id: 'inbox-1',
|
|
lines: [
|
|
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
)) as { staged: boolean; operation_id?: string; preview: Record<string, unknown> }
|
|
|
|
expect(result.staged).toBe(true)
|
|
expect(result.preview.inbox_item_id).toBe('inbox-1')
|
|
expect(result.preview.document_attached).toBe(true)
|
|
expect(result.preview.will).toMatch(/link the inbox item/i)
|
|
// Document attached: the missing-underlag warning must NOT appear.
|
|
expect(result.preview.compliance_warning).toBeUndefined()
|
|
})
|
|
|
|
it('inbox item without a stored document: no attach claim, inbox-variant warning', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
|
|
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
|
|
],
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: {
|
|
id: 'inbox-nodoc',
|
|
document_id: null, // ingested without attachment, or ON DELETE SET NULL
|
|
created_journal_entry_id: null,
|
|
created_supplier_invoice_id: null,
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 1
|
|
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 2
|
|
enqueue({ data: { id: 'op-nodoc' }, error: null }) // pending_operations insert
|
|
|
|
const result = (await createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'Inbox item utan dokument',
|
|
fiscal_period_id: 'fp-1',
|
|
inbox_item_id: 'inbox-nodoc',
|
|
lines: [
|
|
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
)) as { staged: boolean; preview: Record<string, unknown> }
|
|
|
|
expect(result.staged).toBe(true)
|
|
expect(result.preview.document_attached).toBe(false)
|
|
// The envelope must not contradict itself: no "attach the OCR document"
|
|
// claim, and the warning must not tell the agent to restage with the
|
|
// inbox_item_id it already supplied.
|
|
expect(result.preview.will).toMatch(/link the inbox item/i)
|
|
expect(result.preview.will).not.toMatch(/attach the OCR document/i)
|
|
expect(result.preview.compliance_warning).toMatch(/no stored document/i)
|
|
expect(result.preview.compliance_warning).not.toMatch(/restage with inbox_item_id/i)
|
|
})
|
|
|
|
it('is_opening_balance: no underlag warning (IB legitimately lacks a kvitto)', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
|
|
{ account_number: '2081', account_name: 'Aktiekapital', is_active: true },
|
|
],
|
|
error: null,
|
|
})
|
|
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 1
|
|
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 2
|
|
enqueue({ data: { id: 'op-ib' }, error: null }) // pending_operations insert
|
|
|
|
const result = (await createVoucher.execute(
|
|
{
|
|
entry_date: '2026-01-01',
|
|
description: 'Ingående balans',
|
|
fiscal_period_id: 'fp-1',
|
|
is_opening_balance: true,
|
|
lines: [
|
|
{ account_number: '1930', debit_amount: 25000, credit_amount: 0 },
|
|
{ account_number: '2081', debit_amount: 0, credit_amount: 25000 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
)) as { staged: boolean; message: string; preview: Record<string, unknown> }
|
|
|
|
expect(result.staged).toBe(true)
|
|
expect(result.preview.document_attached).toBe(false)
|
|
expect(result.preview.compliance_warning).toBeUndefined()
|
|
expect(result.message).not.toMatch(/WARNING/)
|
|
})
|
|
|
|
it('rejects when inbox_item_id is already booked as a journal entry', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
|
|
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
|
|
],
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: {
|
|
id: 'inbox-1',
|
|
document_id: 'doc-1',
|
|
created_journal_entry_id: 'je-existing',
|
|
created_supplier_invoice_id: null,
|
|
},
|
|
error: null,
|
|
})
|
|
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'duplicate book attempt',
|
|
fiscal_period_id: 'fp-1',
|
|
inbox_item_id: 'inbox-1',
|
|
lines: [
|
|
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/already booked/i)
|
|
})
|
|
|
|
it('rejects when inbox_item_id is already converted to a supplier invoice', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
|
|
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
|
|
],
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: {
|
|
id: 'inbox-1',
|
|
document_id: 'doc-1',
|
|
created_journal_entry_id: null,
|
|
created_supplier_invoice_id: 'si-existing',
|
|
},
|
|
error: null,
|
|
})
|
|
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'voucher attempt on AP-converted inbox',
|
|
fiscal_period_id: 'fp-1',
|
|
inbox_item_id: 'inbox-1',
|
|
lines: [
|
|
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/already converted/i)
|
|
})
|
|
|
|
it('rejects when inbox_item_id does not exist for the company', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: 'fp-1',
|
|
is_closed: false,
|
|
period_start: '2026-01-01',
|
|
period_end: '2026-12-31',
|
|
name: '2026',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
|
|
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
|
|
],
|
|
error: null,
|
|
})
|
|
enqueue({ data: null, error: { message: 'not found' } })
|
|
|
|
await expect(
|
|
createVoucher.execute(
|
|
{
|
|
entry_date: '2026-05-12',
|
|
description: 'unknown inbox uuid',
|
|
fiscal_period_id: 'fp-1',
|
|
inbox_item_id: 'inbox-missing',
|
|
lines: [
|
|
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/inbox item .* not found/i)
|
|
})
|
|
})
|
|
|
|
describe('gnubok_correct_entry: registration', () => {
|
|
it('is registered with bookkeeping:write scope and is not read-only', async () => {
|
|
const { TOOL_SCOPE_MAP } = await import('@/lib/auth/api-keys')
|
|
expect(correctEntry).toBeDefined()
|
|
expect(correctEntry.annotations.readOnlyHint).toBe(false)
|
|
expect(TOOL_SCOPE_MAP.gnubok_correct_entry).toBe('bookkeeping:write')
|
|
})
|
|
|
|
it('rejects unbalanced replacement lines before staging', async () => {
|
|
const { supabase } = createQueuedMockSupabase()
|
|
await expect(
|
|
correctEntry.execute(
|
|
{
|
|
entry_id: 'je-1',
|
|
lines: [
|
|
{ account_number: '2645', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '2614', debit_amount: 0, credit_amount: 200 },
|
|
],
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/not balanced/i)
|
|
})
|
|
|
|
it('shows preserved currency, tax, and dimension metadata in the correction preview', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { dimensions_enabled: false }, error: null })
|
|
enqueue({
|
|
data: {
|
|
id: '11111111-1111-4111-8111-111111111111',
|
|
status: 'posted',
|
|
entry_date: '2026-05-12',
|
|
description: 'Foreign purchase',
|
|
voucher_number: 12,
|
|
voucher_series: 'A',
|
|
fiscal_period_id: 'fp-1',
|
|
fiscal_periods: { name: '2026', is_closed: false, locked_at: null },
|
|
lines: [
|
|
{
|
|
account_number: '5420',
|
|
debit_amount: 1000,
|
|
credit_amount: 0,
|
|
line_description: 'Software',
|
|
currency: 'EUR',
|
|
amount_in_currency: 90,
|
|
exchange_rate: 11.111111,
|
|
tax_code: 'EU_SERVICE',
|
|
dimensions: { '6': 'P001' },
|
|
cost_center: null,
|
|
project: 'P001',
|
|
},
|
|
{
|
|
account_number: '1930',
|
|
debit_amount: 0,
|
|
credit_amount: 1000,
|
|
line_description: 'Settlement',
|
|
currency: 'EUR',
|
|
amount_in_currency: 90,
|
|
exchange_rate: 11.111111,
|
|
tax_code: null,
|
|
dimensions: {},
|
|
cost_center: null,
|
|
project: null,
|
|
},
|
|
],
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({ data: { bookkeeping_locked_through: null }, error: null })
|
|
enqueue({ data: { id: 'fp-1', is_closed: false, locked_at: null }, error: null })
|
|
enqueue({ data: { id: 'op-correct-1' }, error: null })
|
|
|
|
const replacementLines = [
|
|
{
|
|
account_number: '5420',
|
|
debit_amount: 1000,
|
|
credit_amount: 0,
|
|
line_description: 'Software',
|
|
currency: 'EUR',
|
|
amount_in_currency: 90,
|
|
exchange_rate: 11.111111,
|
|
tax_code: 'EU_SERVICE',
|
|
dimensions: { '6': 'P001' },
|
|
},
|
|
{
|
|
account_number: '1931',
|
|
debit_amount: 0,
|
|
credit_amount: 1000,
|
|
line_description: 'Settlement',
|
|
currency: 'EUR',
|
|
amount_in_currency: 90,
|
|
exchange_rate: 11.111111,
|
|
dimensions: {},
|
|
},
|
|
]
|
|
|
|
const result = (await correctEntry.execute(
|
|
{
|
|
entry_id: '11111111-1111-4111-8111-111111111111',
|
|
lines: replacementLines,
|
|
},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
)) as {
|
|
preview: {
|
|
original: { lines: Array<Record<string, unknown>> }
|
|
correction: { lines: Array<Record<string, unknown>> }
|
|
}
|
|
}
|
|
|
|
expect(result.preview.original.lines[0]).toMatchObject({
|
|
currency: 'EUR',
|
|
amount_in_currency: 90,
|
|
exchange_rate: 11.111111,
|
|
tax_code: 'EU_SERVICE',
|
|
dimensions: { '6': 'P001' },
|
|
project: 'P001',
|
|
})
|
|
expect(result.preview.correction.lines[0]).toMatchObject({
|
|
currency: 'EUR',
|
|
amount_in_currency: 90,
|
|
exchange_rate: 11.111111,
|
|
tax_code: 'EU_SERVICE',
|
|
dimensions: { '6': 'P001' },
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('gnubok_correct_entry / gnubok_reverse_journal_entry: chain-depth guard', () => {
|
|
// Base row for a posted correction that already sits 3 links deep:
|
|
// c3 → c2 → c1 → orig-0 (root, voucher A7).
|
|
const deepTarget = {
|
|
id: '22222222-2222-4222-8222-222222222222',
|
|
status: 'posted',
|
|
entry_date: '2026-05-12',
|
|
description: 'Rättelse: Rättelse: Rättelse: Köp',
|
|
voucher_number: 15,
|
|
voucher_series: 'A',
|
|
fiscal_period_id: 'fp-1',
|
|
correction_of_id: 'c2',
|
|
reverses_id: null,
|
|
fiscal_periods: { name: '2026', is_closed: false, locked_at: null },
|
|
lines: [
|
|
{ account_number: '5420', debit_amount: 1000, credit_amount: 0, line_description: null, currency: null, amount_in_currency: null, exchange_rate: null, tax_code: null, dimensions: null, cost_center: null, project: null },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 1000, line_description: null, currency: null, amount_in_currency: null, exchange_rate: null, tax_code: null, dimensions: null, cost_center: null, project: null },
|
|
],
|
|
}
|
|
const walkerRows = [
|
|
{ data: { id: 'c2', correction_of_id: 'c1', reverses_id: null, voucher_series: 'A', voucher_number: 12 }, error: null },
|
|
{ data: { id: 'c1', correction_of_id: 'orig-0', reverses_id: null, voucher_series: 'A', voucher_number: 9 }, error: null },
|
|
{ data: { id: 'orig-0', correction_of_id: null, reverses_id: null, voucher_series: 'A', voucher_number: 7 }, error: null },
|
|
]
|
|
|
|
const replacementLines = [
|
|
{ account_number: '5410', debit_amount: 1000, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 1000 },
|
|
]
|
|
|
|
it('refuses to stage a correction on a chain 3 levels deep with an agent-actionable error', async () => {
|
|
const { supabase, enqueue, enqueueMany } = createQueuedMockSupabase()
|
|
// Lines carry no dimensions, so no dimension-registry query precedes the
|
|
// entry fetch.
|
|
enqueue({ data: deepTarget, error: null })
|
|
enqueueMany(walkerRows)
|
|
|
|
await expect(
|
|
correctEntry.execute(
|
|
{ entry_id: deepTarget.id, lines: replacementLines },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toMatchObject({
|
|
code: 'CORRECTION_CHAIN_TOO_DEEP',
|
|
depth: 3,
|
|
chainRootVoucher: 'A7',
|
|
})
|
|
})
|
|
|
|
it('stages when allow_deep_chain=true and forwards the flag to the executor params', async () => {
|
|
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
|
|
enqueue({ data: deepTarget, error: null })
|
|
// No walker queries: the guard is skipped entirely on explicit override.
|
|
enqueue({ data: { bookkeeping_locked_through: null }, error: null })
|
|
enqueue({ data: { id: 'fp-1', is_closed: false, locked_at: null }, error: null })
|
|
enqueue({ data: { id: 'op-deep-1' }, error: null })
|
|
|
|
await correctEntry.execute(
|
|
{ entry_id: deepTarget.id, lines: replacementLines, allow_deep_chain: true },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
)
|
|
|
|
const insertArgs = findCall('pending_operations', 'insert')
|
|
expect(insertArgs).toBeDefined()
|
|
const payload = (insertArgs as unknown[])[0] as { params?: { allow_deep_chain?: boolean } }
|
|
expect(payload.params?.allow_deep_chain).toBe(true)
|
|
})
|
|
|
|
it('refuses to stage a storno on a chain 3 levels deep', async () => {
|
|
const { supabase, enqueue, enqueueMany } = createQueuedMockSupabase()
|
|
enqueue({ data: deepTarget, error: null })
|
|
enqueueMany(walkerRows)
|
|
|
|
await expect(
|
|
reverseEntry.execute(
|
|
{ entry_id: deepTarget.id },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toMatchObject({ code: 'CORRECTION_CHAIN_TOO_DEEP', depth: 3 })
|
|
})
|
|
})
|
|
|
|
describe('gnubok_reverse_journal_entry: staging gates', () => {
|
|
it('is registered with bookkeeping:write scope and is not read-only', async () => {
|
|
const { TOOL_SCOPE_MAP } = await import('@/lib/auth/api-keys')
|
|
expect(reverseEntry).toBeDefined()
|
|
expect(reverseEntry.annotations.readOnlyHint).toBe(false)
|
|
expect(TOOL_SCOPE_MAP.gnubok_reverse_journal_entry).toBe('bookkeeping:write')
|
|
})
|
|
|
|
it('rejects when entry_id is missing', async () => {
|
|
const { supabase } = createQueuedMockSupabase()
|
|
await expect(
|
|
reverseEntry.execute({}, 'company-1', 'user-1', supabase as never),
|
|
).rejects.toThrow(/entry_id is required/i)
|
|
})
|
|
|
|
it('rejects a reason over 500 characters with a VALIDATION_ERROR code and a Swedish message', async () => {
|
|
// Customer report: the envelope said "Något gick fel. Försök igen." in
|
|
// Swedish while the cause was only in the English field.
|
|
const { supabase } = createQueuedMockSupabase()
|
|
const { getStructuredError } = await import('@/lib/errors/get-structured-error')
|
|
let thrown: unknown
|
|
try {
|
|
await reverseEntry.execute(
|
|
{ entry_id: '11111111-1111-1111-1111-111111111111', reason: 'x'.repeat(501) },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
)
|
|
} catch (err) {
|
|
thrown = err
|
|
}
|
|
expect(thrown).toBeInstanceOf(Error)
|
|
const envelope = getStructuredError(thrown)
|
|
expect(envelope.code).toBe('VALIDATION_ERROR')
|
|
expect(envelope.message_sv).toBe('Motiveringen får vara högst 500 tecken.')
|
|
expect(envelope.message_en).toMatch(/500 characters or fewer/)
|
|
})
|
|
|
|
it('rejects when the original entry is not posted', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: '11111111-1111-1111-1111-111111111111',
|
|
status: 'draft',
|
|
entry_date: '2026-05-12',
|
|
description: 'Test',
|
|
voucher_number: 1,
|
|
voucher_series: 'A',
|
|
fiscal_period_id: 'fp-1',
|
|
fiscal_periods: { name: '2026', is_closed: false },
|
|
lines: [],
|
|
},
|
|
error: null,
|
|
})
|
|
await expect(
|
|
reverseEntry.execute(
|
|
{ entry_id: '11111111-1111-1111-1111-111111111111' },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/posted entries can be reversed/i)
|
|
})
|
|
|
|
it('rejects when the original entry is in a closed period', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: {
|
|
id: '22222222-2222-2222-2222-222222222222',
|
|
status: 'posted',
|
|
entry_date: '2025-12-31',
|
|
description: 'Test',
|
|
voucher_number: 42,
|
|
voucher_series: 'A',
|
|
fiscal_period_id: 'fp-closed',
|
|
fiscal_periods: { name: '2025', is_closed: true },
|
|
lines: [],
|
|
},
|
|
error: null,
|
|
})
|
|
await expect(
|
|
reverseEntry.execute(
|
|
{ entry_id: '22222222-2222-2222-2222-222222222222' },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/closed/i)
|
|
})
|
|
})
|
|
|
|
describe('entry_id resolution: voucher refs and hallucinated UUIDs', () => {
|
|
// These tests cover the resolveJournalEntryRef helper as exercised through
|
|
// gnubok_correct_entry. The same resolution path is wired into
|
|
// gnubok_reverse_journal_entry, so one tool is enough to lock the behaviour.
|
|
|
|
const balancedCorrection = [
|
|
{ account_number: '2645', debit_amount: 250, credit_amount: 0 },
|
|
{ account_number: '2614', debit_amount: 0, credit_amount: 250 },
|
|
]
|
|
|
|
it('resolves a voucher ref like "A-113" to its UUID before the lookup', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const resolvedId = '33333333-3333-3333-3333-333333333333'
|
|
|
|
// 1) resolveJournalEntryRef -> single match by (series, number)
|
|
enqueue({
|
|
data: [{ id: resolvedId, entry_date: '2026-03-06', description: 'Cursor 2' }],
|
|
error: null,
|
|
})
|
|
// 2) original journal_entries lookup, but the period is closed so we
|
|
// short-circuit before staging. That's enough to confirm the helper
|
|
// resolved the ref and passed the UUID through to the next query.
|
|
enqueue({
|
|
data: {
|
|
id: resolvedId,
|
|
status: 'posted',
|
|
entry_date: '2026-03-06',
|
|
description: 'Cursor 2',
|
|
voucher_number: 113,
|
|
voucher_series: 'A',
|
|
fiscal_period_id: 'fp-closed',
|
|
fiscal_periods: { name: '2026', is_closed: true, locked_at: null },
|
|
lines: [],
|
|
},
|
|
error: null,
|
|
})
|
|
|
|
await expect(
|
|
correctEntry.execute(
|
|
{ entry_id: 'A-113', lines: balancedCorrection },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/locked or closed/i)
|
|
})
|
|
|
|
it('errors when a voucher ref matches multiple entries across fiscal periods', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({
|
|
data: [
|
|
{ id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', entry_date: '2026-03-06', description: 'Cursor 2' },
|
|
{ id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', entry_date: '2025-03-06', description: 'Cursor 1' },
|
|
],
|
|
error: null,
|
|
})
|
|
await expect(
|
|
correctEntry.execute(
|
|
{ entry_id: 'A-113', lines: balancedCorrection },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/matches multiple entries/i)
|
|
})
|
|
|
|
it('errors when a voucher ref matches nothing', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [], error: null })
|
|
await expect(
|
|
correctEntry.execute(
|
|
{ entry_id: 'Z-999', lines: balancedCorrection },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/no journal entry found for voucher "z-999"/i)
|
|
})
|
|
|
|
it('errors with a parse hint when the ref is neither a UUID nor a voucher format', async () => {
|
|
const { supabase } = createQueuedMockSupabase()
|
|
await expect(
|
|
correctEntry.execute(
|
|
{ entry_id: 'not-an-id-at-all', lines: balancedCorrection },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(/could not parse entry reference/i)
|
|
})
|
|
|
|
it('surfaces the supplied UUID in not-found errors so hallucinated IDs are debuggable', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const hallucinated = 'a71a11ae-b8e2-450f-aaa6-a227d03b0c94'
|
|
// UUID passes through resolution unchanged → straight to the original
|
|
// lookup, which returns no row.
|
|
enqueue({ data: null, error: null })
|
|
await expect(
|
|
correctEntry.execute(
|
|
{ entry_id: hallucinated, lines: balancedCorrection },
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
),
|
|
).rejects.toThrow(new RegExp(`id=${hallucinated}`))
|
|
})
|
|
})
|
|
|
|
describe('agent memory tools: agent:write scope gate', () => {
|
|
const rememberFact = tools.find((t) => t.name === 'gnubok_remember_fact')
|
|
const forgetFact = tools.find((t) => t.name === 'gnubok_forget_fact')
|
|
|
|
it('registers the memory write tools mapped to agent:write', async () => {
|
|
const { TOOL_SCOPE_MAP } = await import('@/lib/auth/api-keys')
|
|
expect(rememberFact).toBeDefined()
|
|
expect(forgetFact).toBeDefined()
|
|
expect(TOOL_SCOPE_MAP.gnubok_remember_fact).toBe('agent:write')
|
|
expect(TOOL_SCOPE_MAP.gnubok_forget_fact).toBe('agent:write')
|
|
})
|
|
|
|
// Mirror the server's enforcement: a tool is blocked when it has a required
|
|
// scope the key does not hold (server.ts: `requiredScope && !hasScope(...)`).
|
|
it('denies a key without agent:write and allows one with it', async () => {
|
|
const { TOOL_SCOPE_MAP, hasScope } = await import('@/lib/auth/api-keys')
|
|
const required = TOOL_SCOPE_MAP.gnubok_remember_fact
|
|
|
|
const without = ['agent:read', 'reports:read'] as never[]
|
|
const isDenied = !!required && !hasScope(without, required)
|
|
expect(isDenied).toBe(true)
|
|
|
|
const withWrite = ['agent:read', 'agent:write'] as never[]
|
|
const isAllowed = !required || hasScope(withWrite, required)
|
|
expect(isAllowed).toBe(true)
|
|
})
|
|
})
|