chore: MCP intent-tools, BankID enrichment table, multi-tenant fixes (#402)
* chore: MCP intent-tools, BankID enrichment table, multi-tenant fixes MCP server gains six intent-shaped tools that collapse multi-call agent flows into one: vat_close_check, query_journal, auto_match_period, create_supplier_invoice_from_inbox, audit_package, year_end_readiness. Tools wired into TOOL_SCOPE_MAP and OPERATION_RISK_TIERS as appropriate (create_supplier_invoice_from_inbox at medium tier — reversible until approve, but stages a leverantörsskuld). BankID enrichment now persists to a dedicated bankid_enrichment table keyed by user_id. extension_data has been company-scoped (NOT NULL company_id) since the multi-tenant refactor, so every BankID signup has silently been failing the enrichment upsert. Select-company picker reads from the new table. delete_last_voucher (BFNAR 2013:2) needs to clear document_attachments.journal_entry_id before deleting the entry, but the new document immutability trigger blocks that UPDATE. Added the same gnubok.allow_delete transaction-scoped bypass pattern used by the journal-entry/line/retention triggers. pg-real tests cover the happy path, the unauthorized direct UPDATE, and the swap-to-different-entry attempt under the bypass flag. fiscal_periods.no_overlapping_fiscal_periods exclusion was scoped to user_id from before multi-tenant — rebound to company_id so the same user can have overlapping fiscal years across companies they own/are member of. Also adds scripts/seed-demo-account.ts for end-to-end demo seeding (two companies, full FY2025, active FY2026 with mixed state). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(pr-402): address review feedback Migrations - Drop 20260506140000_document_journal_entry_immutability_delete_bypass.sql: redundant with 20260506140000_document_journal_entry_immutability_bypass.sql that landed on main while this branch was open. Both share the same gnubok.allow_delete pattern; main's version is what the DB actually has. - Rename 20260506150000_bankid_enrichment_table.sql → 20260506160000_bankid_enrichment_table.sql to clear the timestamp clash with 20260506150000_protect_document_journal_link.sql on main (Supabase branch preview was failing on schema_migrations PK collision). Tests - Drop the swap-under-flag test from delete-last-voucher.pg.test.ts: main's bypass returns NEW unconditionally when gnubok.allow_delete='true', so the swap is permitted. Drop the duplicate happy-path test (already covered by 'clears journal_entry_id on attached documents and deletes the voucher'). Keep the unauthorized-direct-UPDATE test. - Add bankid-enrichment.pg.test.ts covering the SELECT RLS policy: user reads own row, cannot read another user's row, INSERT denied for authenticated. gnubok_query_journal - amount_min/amount_max is applied post-fetch (PostgREST can't OR abs(debit) and abs(credit) cleanly), but PostgREST's count is computed pre-filter. Reporting that as total_lines mislead agents into paginating a tail that was already filtered out. When the amount filter is applied, anchor total_lines and truncated to the filtered set and surface db_matched_pre_amount_filter + amount_filter_applied_post_fetch separately. - Escape `_` in the free-text LIKE filter so a search for "2_441" doesn't match "2X441". VAT close check - Reverse-charge blocker no longer fires on ruta 30 (seller-side domestic omvänd skattskyldighet) — the seller books no VAT, the buyer does, so missing ruta 48 is expected. Now scoped to ruta 31/32 (EU acquisition) where the buyer must book both calculated output (2615) and matching ingående moms (2645). - High-value receipt threshold no longer reads journal_entries.total_amount (column doesn't exist; check silently never fired). Sums debits across the entry's lines, which equals the gross for ordinary purchase entries — comparing a gross figure against the BFL/ML 4 000 SEK threshold per ML 17 kap 26–28 §. seed-demo-account.ts - Require an explicit email argument; refuse to run with the previously hardcoded fallback that would silently target a real user. Ensure email is non-undefined for downstream typing. - Type the supabase fiscal_periods insert result locally so tsc no longer reports 'fp implicitly any' from the loose untyped client. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(test): adjust fiscal-period-start-day pg test for per-company overlap The pg-real failure on PR #402 was a latent bug surfaced by this branch's fiscal_periods exclusion constraint flip from user_id to company_id (migration 20260506140100). The test was inserting periods that overlapped seedCompany's default 2026-01-01..2026-12-31 period; the previous constraint slipped past it because the test's INSERT didn't set user_id (NULL escapes the WITH = match), so two same-company overlapping periods silently coexisted. Now that the constraint correctly fires per company, pick years that don't overlap with the seeded 2026 period. The trigger's behavior under test (allow mid-month start when no earlier period exists, allow back-dated SIE imports, reject mid-month start when an earlier period exists) is unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(vat-close-check): correct reverse-charge/import blocker rutor Rutor 30/31/32 are the buyer's calculated utgående moms on reverse- charge purchases (domestic byggtjänster/electronics → 2614 → ruta 30; EU goods → 2624 → ruta 31; EU services → 2634 → ruta 32). The buyer must also book matching ingående moms (2647 inhemskt / 2645 utlandet → ruta 48). The previous fix removed ruta 30 on the basis that it was seller-side; that's incorrect — domestic-RC sellers book no VAT at all (they report only beskattningsunderlag on ruta 41), so 2614 only sees buyer-side entries. Restore ruta 30. Also extend the check to import rutor 60/61/62 (non-EU import VAT declared via momsdeklaration since 2015 — 2615/2625/2635). Same mechanic: importer books output VAT on these rutor and deducts the input side via ruta 48. SaaS-from-AWS / OpenAI / Vercel companies hit this path; without including 60/61/62 the blocker would silently miss their misbookings. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(mcp): expose ruta 60/61/62 (import VAT) on the local VatReportResult The vat-close-check fix referenced vatReport.rutor.ruta60/61/62 but the MCP server's local VatReportResult type only carries ruta 05-49. Build broke on tsc. Extend the MCP server's slim VAT report to also project import VAT — 2615 → ruta 60 (25%), 2625 → ruta 61 (12%), 2635 → ruta 62 (6%) — and fold those into ruta 49 (att betala/återfå). Mirrors the BAS-to-Ruta mapping in lib/reports/vat-declaration.ts. Output schema and required list updated accordingly. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -92,18 +92,18 @@ export default async function SelectCompanyPage() {
|
||||
.single()
|
||||
const firstName = profile?.full_name?.split(' ')[0] ?? null
|
||||
|
||||
// TIC enrichment (SPAR + CompanyRoles).
|
||||
// BankID enrichment (CompanyRoles from Bolagsverket via TIC). Stored
|
||||
// user-keyed in `bankid_enrichment` because it lands before company
|
||||
// selection — see fetchAndStoreEnrichment in the tic extension.
|
||||
const { data: enrichmentRow } = await supabase
|
||||
.from('extension_data')
|
||||
.select('value, created_at, updated_at')
|
||||
.from('bankid_enrichment')
|
||||
.select('company_roles, created_at, updated_at')
|
||||
.eq('user_id', user.id)
|
||||
.eq('extension_id', 'tic')
|
||||
.eq('key', 'bankid_enrichment')
|
||||
.maybeSingle()
|
||||
|
||||
const enrichmentValue = enrichmentRow?.value as {
|
||||
companyRoles?: EnrichmentCompanyRole[]
|
||||
} | null
|
||||
const enrichmentValue = enrichmentRow
|
||||
? { companyRoles: enrichmentRow.company_roles as EnrichmentCompanyRole[] }
|
||||
: null
|
||||
|
||||
// "Currently a director" = no position end date. We deliberately do NOT
|
||||
// also require companyStatus === 'Aktivt': real TIC payloads have been
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Unit tests for gnubok_audit_package.
|
||||
*
|
||||
* Verifies registration, scope mapping, the estimate-only path, and the
|
||||
* size-limit guard. The full archive generation is exercised by
|
||||
* lib/reports/full-archive-export tests.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { tools } from '../server'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
|
||||
vi.mock('@/lib/reports/full-archive-export', () => ({
|
||||
generateFullArchive: vi.fn(),
|
||||
estimateArchiveSize: vi.fn(),
|
||||
}))
|
||||
|
||||
import {
|
||||
generateFullArchive,
|
||||
estimateArchiveSize,
|
||||
} from '@/lib/reports/full-archive-export'
|
||||
|
||||
describe('gnubok_audit_package — registration', () => {
|
||||
it('is registered', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_audit_package')
|
||||
expect(tool).toBeDefined()
|
||||
expect(tool?.annotations.idempotentHint).toBe(true)
|
||||
})
|
||||
|
||||
it('requires fiscal_period_id', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_audit_package')!
|
||||
const schema = tool.inputSchema as { required?: string[] }
|
||||
expect(schema.required).toContain('fiscal_period_id')
|
||||
})
|
||||
|
||||
it('is mapped to reports:read scope', () => {
|
||||
expect(TOOL_SCOPE_MAP.gnubok_audit_package).toBe('reports:read')
|
||||
})
|
||||
})
|
||||
|
||||
function makePeriodMock(period: Record<string, unknown> | null) {
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
single: vi.fn().mockResolvedValue({
|
||||
data: period,
|
||||
error: period ? null : { message: 'not found' },
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
storage: {
|
||||
from: vi.fn(),
|
||||
},
|
||||
} as never
|
||||
}
|
||||
|
||||
describe('gnubok_audit_package — execute', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('estimate_only=true returns size estimate without uploading', async () => {
|
||||
vi.mocked(estimateArchiveSize).mockResolvedValue({
|
||||
total_bytes: 5 * 1024 * 1024,
|
||||
breakdown: {} as never,
|
||||
} as never)
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_audit_package')!
|
||||
const supabase = makePeriodMock({
|
||||
id: 'p1', name: '2026',
|
||||
period_start: '2026-01-01', period_end: '2026-12-31',
|
||||
})
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ fiscal_period_id: 'p1', estimate_only: true },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase,
|
||||
)) as {
|
||||
estimate_only: boolean
|
||||
download_url: string | null
|
||||
size_bytes: number
|
||||
within_limit: boolean
|
||||
}
|
||||
|
||||
expect(result.estimate_only).toBe(true)
|
||||
expect(result.download_url).toBeNull()
|
||||
expect(result.size_bytes).toBe(5 * 1024 * 1024)
|
||||
expect(result.within_limit).toBe(true)
|
||||
expect(generateFullArchive).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('throws when archive would exceed size limit and include_documents=true', async () => {
|
||||
vi.mocked(estimateArchiveSize).mockResolvedValue({
|
||||
total_bytes: 100 * 1024 * 1024, // > 80 MB limit
|
||||
breakdown: {} as never,
|
||||
} as never)
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_audit_package')!
|
||||
const supabase = makePeriodMock({
|
||||
id: 'p1', name: '2026',
|
||||
period_start: '2026-01-01', period_end: '2026-12-31',
|
||||
})
|
||||
|
||||
await expect(
|
||||
tool.execute(
|
||||
{ fiscal_period_id: 'p1' },
|
||||
'company-1', 'user-1', supabase,
|
||||
),
|
||||
).rejects.toThrow(/exceed.*MB/)
|
||||
})
|
||||
|
||||
it('throws when fiscal period is not found', async () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_audit_package')!
|
||||
const supabase = makePeriodMock(null)
|
||||
|
||||
await expect(
|
||||
tool.execute(
|
||||
{ fiscal_period_id: 'nonexistent' },
|
||||
'company-1', 'user-1', supabase,
|
||||
),
|
||||
).rejects.toThrow(/Fiscal period not found/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Unit tests for gnubok_auto_match_period.
|
||||
*
|
||||
* Verifies registration, dry-run preview shape, confidence threshold filtering,
|
||||
* and the no-match counters. Per-item staging fault isolation is covered by
|
||||
* the existing stagePendingOperation tests.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { tools } from '../server'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
|
||||
vi.mock('@/lib/invoices/invoice-matching', () => ({
|
||||
findMatchingInvoices: vi.fn(),
|
||||
}))
|
||||
|
||||
import { findMatchingInvoices } from '@/lib/invoices/invoice-matching'
|
||||
|
||||
describe('gnubok_auto_match_period — registration', () => {
|
||||
it('is registered', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_auto_match_period')
|
||||
expect(tool).toBeDefined()
|
||||
// Stages writes when dry_run=false, so not read-only
|
||||
expect(tool?.annotations.readOnlyHint).toBe(false)
|
||||
expect(tool?.annotations.destructiveHint).toBe(false)
|
||||
})
|
||||
|
||||
it('requires date_from and date_to', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_auto_match_period')!
|
||||
const schema = tool.inputSchema as { required?: string[] }
|
||||
expect(schema.required).toContain('date_from')
|
||||
expect(schema.required).toContain('date_to')
|
||||
})
|
||||
|
||||
it('is mapped to transactions:write scope', () => {
|
||||
expect(TOOL_SCOPE_MAP.gnubok_auto_match_period).toBe('transactions:write')
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Build a mock that returns a fixed transactions array on the
|
||||
* .from('transactions').select(...).eq(...).gte(...).lte(...).gt(...).is(...).is(...).order(...).limit(...)
|
||||
* call chain.
|
||||
*/
|
||||
function makeTxMock(transactions: unknown[]) {
|
||||
const result = { data: transactions, error: null }
|
||||
const buildChain = (): unknown =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => resolve(result)
|
||||
}
|
||||
return () => buildChain()
|
||||
},
|
||||
},
|
||||
)
|
||||
return {
|
||||
from: vi.fn().mockImplementation(() => buildChain()),
|
||||
} as never
|
||||
}
|
||||
|
||||
describe('gnubok_auto_match_period — dry run', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns proposals at and above the confidence threshold, classifies the rest', async () => {
|
||||
const txs = [
|
||||
{ id: 't1', date: '2026-03-01', amount: 1000, currency: 'SEK', description: 'Pay 1', merchant_name: null, reference: null, journal_entry_id: null, invoice_id: null },
|
||||
{ id: 't2', date: '2026-03-02', amount: 500, currency: 'SEK', description: 'Pay 2', merchant_name: null, reference: null, journal_entry_id: null, invoice_id: null },
|
||||
{ id: 't3', date: '2026-03-03', amount: 200, currency: 'SEK', description: 'Pay 3', merchant_name: null, reference: null, journal_entry_id: null, invoice_id: null },
|
||||
]
|
||||
const supabase = makeTxMock(txs)
|
||||
|
||||
vi.mocked(findMatchingInvoices)
|
||||
// t1: high confidence — should propose
|
||||
.mockResolvedValueOnce([
|
||||
{ invoice: { id: 'i1', invoice_number: 'INV-1', total: 1000, customer: { name: 'Acme' } } as never, confidence: 0.95, matchReason: 'Exakt belopp + kund' },
|
||||
])
|
||||
// t2: below threshold (0.7 < 0.9)
|
||||
.mockResolvedValueOnce([
|
||||
{ invoice: { id: 'i2', invoice_number: 'INV-2', total: 500, customer: { name: 'Foo' } } as never, confidence: 0.7, matchReason: 'Belopp matchar' },
|
||||
])
|
||||
// t3: no match
|
||||
.mockResolvedValueOnce([])
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_auto_match_period')!
|
||||
const result = (await tool.execute(
|
||||
{
|
||||
date_from: '2026-03-01',
|
||||
date_to: '2026-03-31',
|
||||
confidence_threshold: 0.9,
|
||||
dry_run: true,
|
||||
},
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase,
|
||||
)) as {
|
||||
dry_run: boolean
|
||||
scanned_transactions: number
|
||||
proposed_matches: number
|
||||
below_threshold: number
|
||||
no_match_found: number
|
||||
staged_count: number
|
||||
proposals: { decision: string; transaction_id: string; confidence: number }[]
|
||||
}
|
||||
|
||||
expect(result.dry_run).toBe(true)
|
||||
expect(result.scanned_transactions).toBe(3)
|
||||
expect(result.proposed_matches).toBe(1)
|
||||
expect(result.below_threshold).toBe(1)
|
||||
expect(result.no_match_found).toBe(1)
|
||||
expect(result.staged_count).toBe(0)
|
||||
|
||||
const decisions = result.proposals.map((p) => p.decision)
|
||||
expect(decisions).toContain('propose')
|
||||
expect(decisions).toContain('below_threshold')
|
||||
})
|
||||
|
||||
it('truncates when more transactions match than max_transactions', async () => {
|
||||
// Return 3 transactions when max_transactions=2 → truncated should be true.
|
||||
// The tool fetches max_transactions+1 to detect truncation.
|
||||
const txs = [
|
||||
{ id: 't1', date: '2026-03-01', amount: 100, currency: 'SEK', description: '', merchant_name: null, reference: null, journal_entry_id: null, invoice_id: null },
|
||||
{ id: 't2', date: '2026-03-02', amount: 100, currency: 'SEK', description: '', merchant_name: null, reference: null, journal_entry_id: null, invoice_id: null },
|
||||
{ id: 't3', date: '2026-03-03', amount: 100, currency: 'SEK', description: '', merchant_name: null, reference: null, journal_entry_id: null, invoice_id: null },
|
||||
]
|
||||
const supabase = makeTxMock(txs)
|
||||
vi.mocked(findMatchingInvoices).mockResolvedValue([])
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_auto_match_period')!
|
||||
const result = (await tool.execute(
|
||||
{
|
||||
date_from: '2026-03-01',
|
||||
date_to: '2026-03-31',
|
||||
max_transactions: 2,
|
||||
dry_run: true,
|
||||
},
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase,
|
||||
)) as { truncated: boolean; scanned_transactions: number }
|
||||
|
||||
expect(result.truncated).toBe(true)
|
||||
expect(result.scanned_transactions).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* Unit tests for gnubok_create_supplier_invoice_from_inbox.
|
||||
*
|
||||
* Verifies registration, scope, supplier-resolution branches, dry_run preview,
|
||||
* already-converted guard, and the missing-extraction error.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { tools } from '../server'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
import { OPERATION_RISK_TIERS } from '@/lib/pending-operations/risk-tiers'
|
||||
|
||||
vi.mock('@/lib/currency/riksbanken', () => ({
|
||||
fetchExchangeRate: vi.fn().mockResolvedValue(11.5),
|
||||
convertToSEK: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('gnubok_create_supplier_invoice_from_inbox — registration', () => {
|
||||
it('is registered with idempotent + non-read-only annotations', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_create_supplier_invoice_from_inbox')
|
||||
expect(tool).toBeDefined()
|
||||
expect(tool?.annotations.readOnlyHint).toBe(false)
|
||||
expect(tool?.annotations.idempotentHint).toBe(true)
|
||||
expect(tool?.annotations.destructiveHint).toBe(false)
|
||||
})
|
||||
|
||||
it('requires inbox_item_id', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_create_supplier_invoice_from_inbox')!
|
||||
const schema = tool.inputSchema as { required?: string[] }
|
||||
expect(schema.required).toContain('inbox_item_id')
|
||||
})
|
||||
|
||||
it('is mapped to suppliers:write scope', () => {
|
||||
expect(TOOL_SCOPE_MAP.gnubok_create_supplier_invoice_from_inbox).toBe('suppliers:write')
|
||||
})
|
||||
|
||||
it('is classified as medium risk', () => {
|
||||
expect(OPERATION_RISK_TIERS.create_supplier_invoice_from_inbox).toBe('medium')
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Build a supabase mock that:
|
||||
* - returns the given inbox row from .from('invoice_inbox_items').select(...).eq(...).eq(...).single()
|
||||
* - returns the given supplier row from .from('suppliers') lookups
|
||||
* - resolves the pending_operations insert
|
||||
*/
|
||||
function makeMock(opts: {
|
||||
inbox?: Record<string, unknown> | null
|
||||
supplierByOrg?: Record<string, unknown> | null
|
||||
supplierByName?: Record<string, unknown> | null
|
||||
pendingInsert?: Record<string, unknown>
|
||||
}) {
|
||||
const inboxResult = { data: opts.inbox ?? null, error: opts.inbox ? null : { message: 'not found' } }
|
||||
const supplierByOrgResult = { data: opts.supplierByOrg ?? null, error: null }
|
||||
const supplierByNameResult = { data: opts.supplierByName ?? null, error: null }
|
||||
const insertResult = { data: opts.pendingInsert ?? { id: 'op-1' }, error: null }
|
||||
|
||||
// suppliers lookups distinguish by query method: org_number → .eq() chain ending in maybeSingle()
|
||||
// name → .ilike() chain ending in maybeSingle().
|
||||
// We stub by tracking the most recent .eq vs .ilike call. Simpler: return
|
||||
// org-result first, name-result second (the tool falls through).
|
||||
let supplierLookupCall = 0
|
||||
const supplierChain = (): unknown =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'maybeSingle') {
|
||||
return () => {
|
||||
supplierLookupCall++
|
||||
return Promise.resolve(supplierLookupCall === 1 ? supplierByOrgResult : supplierByNameResult)
|
||||
}
|
||||
}
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => resolve(supplierByOrgResult)
|
||||
}
|
||||
return () => supplierChain()
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const inboxChain = (): unknown =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'single') return () => Promise.resolve(inboxResult)
|
||||
if (prop === 'then') return (resolve: (v: unknown) => void) => resolve(inboxResult)
|
||||
return () => inboxChain()
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const pendingChain = (): unknown =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'single') return () => Promise.resolve(insertResult)
|
||||
if (prop === 'then') return (resolve: (v: unknown) => void) => resolve(insertResult)
|
||||
return () => pendingChain()
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
return {
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'invoice_inbox_items') return inboxChain()
|
||||
if (table === 'suppliers') return supplierChain()
|
||||
if (table === 'pending_operations') return pendingChain()
|
||||
return inboxChain()
|
||||
}),
|
||||
} as never
|
||||
}
|
||||
|
||||
const baseExtracted = {
|
||||
supplier: { name: 'Acme AB', organizationNumber: '5566778899' },
|
||||
invoice: { invoiceNumber: 'INV-100', invoiceDate: '2026-03-15', dueDate: '2026-04-14', currency: 'SEK' },
|
||||
totals: { subtotal: 1000, vat: 250, total: 1250 },
|
||||
lineItems: [
|
||||
{ description: 'Konsulttimmar', quantity: 10, unit_price: 100, line_total: 1000, vat_rate: 25, vat_amount: 250 },
|
||||
],
|
||||
}
|
||||
|
||||
describe('gnubok_create_supplier_invoice_from_inbox — execute', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('dry_run returns preview without inserting pending_operations', async () => {
|
||||
const supabase = makeMock({
|
||||
inbox: {
|
||||
id: 'inbox-1',
|
||||
status: 'received',
|
||||
extracted_data: baseExtracted,
|
||||
matched_supplier_id: 'supplier-1',
|
||||
created_supplier_invoice_id: null,
|
||||
document_id: 'doc-1',
|
||||
},
|
||||
})
|
||||
const tool = tools.find((t) => t.name === 'gnubok_create_supplier_invoice_from_inbox')!
|
||||
const result = (await tool.execute(
|
||||
{ inbox_item_id: 'inbox-1', dry_run: true },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase,
|
||||
)) as { dry_run?: boolean; staged: boolean; preview: Record<string, unknown> }
|
||||
|
||||
expect(result.dry_run).toBe(true)
|
||||
expect(result.staged).toBe(false)
|
||||
expect(result.preview.supplier_id).toBe('supplier-1')
|
||||
expect(result.preview.supplier_resolution).toBe('matched')
|
||||
expect(result.preview.total).toBe(1250)
|
||||
})
|
||||
|
||||
it('falls through to org_number lookup when no matched supplier', async () => {
|
||||
const supabase = makeMock({
|
||||
inbox: {
|
||||
id: 'inbox-2',
|
||||
status: 'received',
|
||||
extracted_data: baseExtracted,
|
||||
matched_supplier_id: null,
|
||||
created_supplier_invoice_id: null,
|
||||
document_id: 'doc-2',
|
||||
},
|
||||
supplierByOrg: { id: 'supplier-org-lookup' },
|
||||
})
|
||||
const tool = tools.find((t) => t.name === 'gnubok_create_supplier_invoice_from_inbox')!
|
||||
const result = (await tool.execute(
|
||||
{ inbox_item_id: 'inbox-2', dry_run: true },
|
||||
'company-1', 'user-1', supabase,
|
||||
)) as { preview: { supplier_resolution: string; supplier_id: string } }
|
||||
|
||||
expect(result.preview.supplier_id).toBe('supplier-org-lookup')
|
||||
expect(result.preview.supplier_resolution).toBe('lookup_org_number')
|
||||
})
|
||||
|
||||
it('throws when inbox item already converted', async () => {
|
||||
const supabase = makeMock({
|
||||
inbox: {
|
||||
id: 'inbox-3',
|
||||
status: 'received',
|
||||
extracted_data: baseExtracted,
|
||||
matched_supplier_id: 'supplier-1',
|
||||
created_supplier_invoice_id: 'si-existing',
|
||||
document_id: 'doc-3',
|
||||
},
|
||||
})
|
||||
const tool = tools.find((t) => t.name === 'gnubok_create_supplier_invoice_from_inbox')!
|
||||
await expect(
|
||||
tool.execute({ inbox_item_id: 'inbox-3' }, 'company-1', 'user-1', supabase),
|
||||
).rejects.toThrow(/already converted/)
|
||||
})
|
||||
|
||||
it('throws when supplier cannot be resolved', async () => {
|
||||
const supabase = makeMock({
|
||||
inbox: {
|
||||
id: 'inbox-4',
|
||||
status: 'received',
|
||||
extracted_data: baseExtracted,
|
||||
matched_supplier_id: null,
|
||||
created_supplier_invoice_id: null,
|
||||
document_id: 'doc-4',
|
||||
},
|
||||
supplierByOrg: null,
|
||||
supplierByName: null,
|
||||
})
|
||||
const tool = tools.find((t) => t.name === 'gnubok_create_supplier_invoice_from_inbox')!
|
||||
await expect(
|
||||
tool.execute({ inbox_item_id: 'inbox-4', dry_run: true }, 'company-1', 'user-1', supabase),
|
||||
).rejects.toThrow(/Cannot resolve supplier/)
|
||||
})
|
||||
|
||||
it('throws when extracted_data is missing', async () => {
|
||||
const supabase = makeMock({
|
||||
inbox: {
|
||||
id: 'inbox-5',
|
||||
status: 'received',
|
||||
extracted_data: null,
|
||||
matched_supplier_id: 'supplier-1',
|
||||
created_supplier_invoice_id: null,
|
||||
document_id: null,
|
||||
},
|
||||
})
|
||||
const tool = tools.find((t) => t.name === 'gnubok_create_supplier_invoice_from_inbox')!
|
||||
await expect(
|
||||
tool.execute({ inbox_item_id: 'inbox-5' }, 'company-1', 'user-1', supabase),
|
||||
).rejects.toThrow(/no extracted_data/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Unit tests for gnubok_query_journal.
|
||||
*
|
||||
* Verifies tool registration and the post-fetch amount filter + totals
|
||||
* computation. The supabase query-builder chain is exercised by the live
|
||||
* MCP smoke test; here we just check the result-shape pipeline.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { tools } from '../server'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
|
||||
describe('gnubok_query_journal — registration', () => {
|
||||
it('is registered and read-only', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_query_journal')
|
||||
expect(tool).toBeDefined()
|
||||
expect(tool?.annotations.readOnlyHint).toBe(true)
|
||||
expect(tool?.annotations.destructiveHint).toBe(false)
|
||||
})
|
||||
|
||||
it('declares the expected output fields', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_query_journal')!
|
||||
const schema = tool.outputSchema as { required?: string[] }
|
||||
expect(schema.required).toContain('lines')
|
||||
expect(schema.required).toContain('totals')
|
||||
expect(schema.required).toContain('total_lines')
|
||||
})
|
||||
|
||||
it('is mapped to reports:read scope', () => {
|
||||
expect(TOOL_SCOPE_MAP.gnubok_query_journal).toBe('reports:read')
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Build a minimal supabase mock that returns a fixed line set when the chain
|
||||
* is awaited. Uses a chainable proxy whose every method returns itself, with
|
||||
* the terminal awaitable resolving to { data, error, count }.
|
||||
*/
|
||||
function makeChainMock(lines: unknown[], count: number) {
|
||||
const result = { data: lines, error: null, count }
|
||||
const buildChain = (): unknown => {
|
||||
return new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => resolve(result)
|
||||
}
|
||||
return () => buildChain()
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
return {
|
||||
from: vi.fn().mockImplementation(() => buildChain()),
|
||||
} as never
|
||||
}
|
||||
|
||||
describe('gnubok_query_journal — execute', () => {
|
||||
it('applies amount_min filter and computes totals on the filtered set', async () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_query_journal')!
|
||||
const lines = [
|
||||
// Line 1: large debit — should pass amount_min: 1000
|
||||
{
|
||||
id: 'l1', account_number: '4010',
|
||||
debit_amount: 5000, credit_amount: 0,
|
||||
currency: 'SEK', line_description: 'Hyra', project: null, cost_center: null, sort_order: 0,
|
||||
journal_entries: {
|
||||
id: 'e1', voucher_number: 1, voucher_series: 'A',
|
||||
entry_date: '2026-03-15', description: 'Marshyra',
|
||||
source_type: 'supplier_invoice', status: 'posted',
|
||||
},
|
||||
},
|
||||
// Line 2: small debit — should fail amount_min: 1000
|
||||
{
|
||||
id: 'l2', account_number: '4010',
|
||||
debit_amount: 50, credit_amount: 0,
|
||||
currency: 'SEK', line_description: 'Småinköp', project: null, cost_center: null, sort_order: 0,
|
||||
journal_entries: {
|
||||
id: 'e2', voucher_number: 2, voucher_series: 'A',
|
||||
entry_date: '2026-03-16', description: 'Reseutlägg',
|
||||
source_type: 'bank_transaction', status: 'posted',
|
||||
},
|
||||
},
|
||||
]
|
||||
const supabase = makeChainMock(lines, 2)
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ account_from: '4000', account_to: '4999', amount_min: 1000, limit: 100 },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase,
|
||||
)) as {
|
||||
lines: { line_id: string }[]
|
||||
totals: { debit: number; credit: number; net: number }
|
||||
truncated: boolean
|
||||
total_lines: number
|
||||
returned_lines: number
|
||||
}
|
||||
|
||||
// amount_min: 1000 should filter out the 50-line
|
||||
expect(result.returned_lines).toBe(1)
|
||||
expect(result.lines[0].line_id).toBe('l1')
|
||||
expect(result.totals.debit).toBe(5000)
|
||||
expect(result.totals.credit).toBe(0)
|
||||
expect(result.totals.net).toBe(5000)
|
||||
})
|
||||
|
||||
it('caps accounts list at 50', async () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_query_journal')!
|
||||
const supabase = makeChainMock([], 0)
|
||||
const accounts = Array.from({ length: 51 }, (_, i) => String(1000 + i))
|
||||
|
||||
await expect(
|
||||
tool.execute({ accounts }, 'company-1', 'user-1', supabase),
|
||||
).rejects.toThrow(/capped at 50/)
|
||||
})
|
||||
|
||||
it('marks truncated=true when count exceeds returned', async () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_query_journal')!
|
||||
const lines = [
|
||||
{
|
||||
id: 'l1', account_number: '1930',
|
||||
debit_amount: 100, credit_amount: 0,
|
||||
currency: 'SEK', line_description: null, project: null, cost_center: null, sort_order: 0,
|
||||
journal_entries: {
|
||||
id: 'e1', voucher_number: 1, voucher_series: 'A',
|
||||
entry_date: '2026-01-01', description: 'Inbetalning',
|
||||
source_type: 'bank_transaction', status: 'posted',
|
||||
},
|
||||
},
|
||||
]
|
||||
// count=999 simulates "many more matched than were returned"
|
||||
const supabase = makeChainMock(lines, 999)
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ accounts: ['1930'], limit: 1 },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase,
|
||||
)) as { truncated: boolean; total_lines: number; returned_lines: number }
|
||||
|
||||
expect(result.truncated).toBe(true)
|
||||
expect(result.total_lines).toBe(999)
|
||||
expect(result.returned_lines).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Unit tests for gnubok_vat_close_check.
|
||||
*
|
||||
* Covers tool registration, scope mapping, the pure Skatteverket deadline math,
|
||||
* and the basic output shape. The full multi-query integration is tested via
|
||||
* the manual MCP smoke test described in the plan; mocking every chained
|
||||
* supabase call here would couple tests to internal query order.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { tools, computeMomsDeadline } from '../server'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
|
||||
describe('gnubok_vat_close_check', () => {
|
||||
it('is registered in the tools array', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_vat_close_check')
|
||||
expect(tool).toBeDefined()
|
||||
expect(tool?.annotations.readOnlyHint).toBe(true)
|
||||
expect(tool?.annotations.idempotentHint).toBe(true)
|
||||
expect(tool?.annotations.destructiveHint).toBe(false)
|
||||
})
|
||||
|
||||
it('has the required input schema', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_vat_close_check')!
|
||||
const schema = tool.inputSchema as { required?: string[]; properties?: Record<string, unknown> }
|
||||
expect(schema.required).toEqual(['period_type', 'year', 'period'])
|
||||
expect(schema.properties).toHaveProperty('period_type')
|
||||
expect(schema.properties).toHaveProperty('year')
|
||||
expect(schema.properties).toHaveProperty('period')
|
||||
})
|
||||
|
||||
it('declares an output schema with all the intent fields', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_vat_close_check')!
|
||||
const schema = tool.outputSchema as { required?: string[] }
|
||||
expect(schema.required).toContain('rutor')
|
||||
expect(schema.required).toContain('payment')
|
||||
expect(schema.required).toContain('blockers')
|
||||
expect(schema.required).toContain('sanity')
|
||||
expect(schema.required).toContain('ready_to_close')
|
||||
expect(schema.required).toContain('summary')
|
||||
})
|
||||
|
||||
it('is mapped to reports:read scope', () => {
|
||||
expect(TOOL_SCOPE_MAP.gnubok_vat_close_check).toBe('reports:read')
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeMomsDeadline', () => {
|
||||
it('monthly: March 2026 → 12 April 2026', () => {
|
||||
const d = computeMomsDeadline('monthly', 2026, 3)
|
||||
expect(d?.date).toBe('2026-04-12')
|
||||
expect(d?.label).toBe('12 april 2026')
|
||||
})
|
||||
|
||||
it('monthly: December rolls into next year', () => {
|
||||
const d = computeMomsDeadline('monthly', 2026, 12)
|
||||
expect(d?.date).toBe('2027-01-12')
|
||||
})
|
||||
|
||||
it('quarterly: Q1 2026 → 26 April 2026', () => {
|
||||
const d = computeMomsDeadline('quarterly', 2026, 1)
|
||||
expect(d?.date).toBe('2026-04-26')
|
||||
})
|
||||
|
||||
it('quarterly: Q4 2026 → 26 January 2027', () => {
|
||||
const d = computeMomsDeadline('quarterly', 2026, 4)
|
||||
expect(d?.date).toBe('2027-01-26')
|
||||
})
|
||||
|
||||
it('yearly: 2026 → 26 February 2027', () => {
|
||||
const d = computeMomsDeadline('yearly', 2026, 1)
|
||||
expect(d?.date).toBe('2027-02-26')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Unit tests for gnubok_year_end_readiness.
|
||||
*
|
||||
* Covers tool registration, scope mapping, and the blocker-kind classification
|
||||
* heuristic that turns the lib's flat error strings into structured agent-
|
||||
* friendly entries. Full integration with validateYearEndReadiness is covered
|
||||
* by lib/core/bookkeeping tests + the manual MCP smoke test.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { tools } from '../server'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
|
||||
vi.mock('@/lib/core/bookkeeping/year-end-service', () => ({
|
||||
validateYearEndReadiness: vi.fn(),
|
||||
previewYearEndClosing: vi.fn(),
|
||||
}))
|
||||
|
||||
import {
|
||||
validateYearEndReadiness,
|
||||
previewYearEndClosing,
|
||||
} from '@/lib/core/bookkeeping/year-end-service'
|
||||
|
||||
describe('gnubok_year_end_readiness — registration', () => {
|
||||
it('is registered in the tools array', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_year_end_readiness')
|
||||
expect(tool).toBeDefined()
|
||||
expect(tool?.annotations.readOnlyHint).toBe(true)
|
||||
expect(tool?.annotations.destructiveHint).toBe(false)
|
||||
expect(tool?.annotations.idempotentHint).toBe(true)
|
||||
})
|
||||
|
||||
it('requires fiscal_period_id', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_year_end_readiness')!
|
||||
const schema = tool.inputSchema as { required?: string[] }
|
||||
expect(schema.required).toContain('fiscal_period_id')
|
||||
})
|
||||
|
||||
it('declares output schema with intent fields', () => {
|
||||
const tool = tools.find((t) => t.name === 'gnubok_year_end_readiness')!
|
||||
const schema = tool.outputSchema as { required?: string[] }
|
||||
expect(schema.required).toContain('ready')
|
||||
expect(schema.required).toContain('blockers')
|
||||
expect(schema.required).toContain('warnings')
|
||||
expect(schema.required).toContain('summary')
|
||||
})
|
||||
|
||||
it('is mapped to reports:read scope', () => {
|
||||
expect(TOOL_SCOPE_MAP.gnubok_year_end_readiness).toBe('reports:read')
|
||||
})
|
||||
})
|
||||
|
||||
function makeMockSupabase(period: Record<string, unknown> | null) {
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
single: vi.fn().mockResolvedValue({ data: period, error: null }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
} as never
|
||||
}
|
||||
|
||||
describe('gnubok_year_end_readiness — execute', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('classifies common error strings into structured kinds', async () => {
|
||||
vi.mocked(validateYearEndReadiness).mockResolvedValue({
|
||||
ready: false,
|
||||
errors: [
|
||||
'3 draft journal entries must be posted or deleted before closing',
|
||||
'Unexplained voucher gap in series A: 5-7',
|
||||
'Trial balance is not balanced: debit=100, credit=200',
|
||||
'Sequence counter integrity error in series A: counter=3 but max voucher=5',
|
||||
],
|
||||
warnings: ['No posted journal entries in this period'],
|
||||
draftCount: 3,
|
||||
voucherGaps: [{ series: 'A', gap_start: 5, gap_end: 7 }],
|
||||
unexplainedGaps: [{ series: 'A', gap_start: 5, gap_end: 7 }],
|
||||
sequenceMismatches: [{ series: 'A', sequenceCounter: 3, actualMax: 5 }],
|
||||
trialBalanceBalanced: false,
|
||||
})
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_year_end_readiness')!
|
||||
const supabase = makeMockSupabase({
|
||||
id: 'period-1',
|
||||
name: '2026',
|
||||
period_start: '2026-01-01',
|
||||
period_end: '2026-12-31',
|
||||
is_closed: false,
|
||||
locked_at: null,
|
||||
closing_entry_id: null,
|
||||
continuity_verified: true,
|
||||
})
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ fiscal_period_id: 'period-1' },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase,
|
||||
)) as { ready: boolean; blockers: { kind: string }[]; summary: string }
|
||||
|
||||
expect(result.ready).toBe(false)
|
||||
const kinds = result.blockers.map((b) => b.kind)
|
||||
expect(kinds).toContain('draft_entries')
|
||||
expect(kinds).toContain('unexplained_voucher_gap')
|
||||
expect(kinds).toContain('sequence_mismatch')
|
||||
expect(kinds).toContain('trial_balance_unbalanced')
|
||||
expect(result.summary).toMatch(/Inte klart/)
|
||||
})
|
||||
|
||||
it('skips preview when not requested even if ready', async () => {
|
||||
vi.mocked(validateYearEndReadiness).mockResolvedValue({
|
||||
ready: true,
|
||||
errors: [],
|
||||
warnings: [],
|
||||
draftCount: 0,
|
||||
voucherGaps: [],
|
||||
unexplainedGaps: [],
|
||||
sequenceMismatches: [],
|
||||
trialBalanceBalanced: true,
|
||||
})
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_year_end_readiness')!
|
||||
const supabase = makeMockSupabase({
|
||||
id: 'period-1', name: '2026',
|
||||
period_start: '2026-01-01', period_end: '2026-12-31',
|
||||
is_closed: false, locked_at: null, closing_entry_id: null, continuity_verified: true,
|
||||
})
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ fiscal_period_id: 'period-1' },
|
||||
'company-1', 'user-1', supabase,
|
||||
)) as { ready: boolean; preview: unknown; summary: string }
|
||||
|
||||
expect(result.ready).toBe(true)
|
||||
expect(result.preview).toBeNull()
|
||||
expect(vi.mocked(previewYearEndClosing)).not.toHaveBeenCalled()
|
||||
expect(result.summary).toMatch(/Klart för bokslut/)
|
||||
})
|
||||
|
||||
it('returns the preview when include_preview=true and ready', async () => {
|
||||
vi.mocked(validateYearEndReadiness).mockResolvedValue({
|
||||
ready: true,
|
||||
errors: [],
|
||||
warnings: [],
|
||||
draftCount: 0,
|
||||
voucherGaps: [],
|
||||
unexplainedGaps: [],
|
||||
sequenceMismatches: [],
|
||||
trialBalanceBalanced: true,
|
||||
})
|
||||
vi.mocked(previewYearEndClosing).mockResolvedValue({
|
||||
net_result: 12345,
|
||||
closing_account: '2099',
|
||||
lines: [],
|
||||
} as never)
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_year_end_readiness')!
|
||||
const supabase = makeMockSupabase({
|
||||
id: 'period-1', name: '2026',
|
||||
period_start: '2026-01-01', period_end: '2026-12-31',
|
||||
is_closed: false, locked_at: null, closing_entry_id: null, continuity_verified: true,
|
||||
})
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ fiscal_period_id: 'period-1', include_preview: true },
|
||||
'company-1', 'user-1', supabase,
|
||||
)) as { preview: { net_result?: number } | null }
|
||||
|
||||
expect(result.preview).not.toBeNull()
|
||||
expect(result.preview?.net_result).toBe(12345)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -209,7 +209,7 @@ describe('POST /bankid/complete', () => {
|
||||
})
|
||||
|
||||
describe('enrichment — SPAR + CompanyRoles', () => {
|
||||
it('requests both SPAR and CompanyRoles, fetches data, and persists only companyRoles (no PII) to extension_data', async () => {
|
||||
it('requests both SPAR and CompanyRoles, fetches data, and persists only companyRoles (no PII) to bankid_enrichment', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
vi.mocked(requestEnrichment).mockResolvedValueOnce({
|
||||
enrichmentId: 'enr-1',
|
||||
@@ -257,14 +257,14 @@ describe('POST /bankid/complete', () => {
|
||||
{ error: null }, // bankid_identities insert OK
|
||||
])
|
||||
|
||||
// Intercept the extension_data upsert so we can assert the persisted shape
|
||||
// Intercept the bankid_enrichment upsert so we can assert the persisted shape
|
||||
// contains no SPAR / personnummer / name. Other tables fall through to the
|
||||
// queued chain.
|
||||
const upsertSpy = vi.fn().mockResolvedValue({ error: null })
|
||||
const origFrom = client.from as unknown as ReturnType<typeof vi.fn>
|
||||
const queuedFrom = origFrom.getMockImplementation() as (table: string) => unknown
|
||||
origFrom.mockImplementation((table: string) => {
|
||||
if (table === 'extension_data') {
|
||||
if (table === 'bankid_enrichment') {
|
||||
return { upsert: upsertSpy }
|
||||
}
|
||||
return queuedFrom(table)
|
||||
@@ -286,21 +286,19 @@ describe('POST /bankid/complete', () => {
|
||||
)
|
||||
expect(vi.mocked(fetchEnrichmentData)).toHaveBeenCalledWith('/api/v1/enrichment/data/abc')
|
||||
|
||||
// Persisted blob must contain companyRoles + enrichedAtUtc only.
|
||||
// Persisted row must contain company_roles + enriched_at_utc only.
|
||||
// SPAR (personnummer / name / address / birth date) must NOT be stored,
|
||||
// even when TIC returns it — those fields live in bankid_identities (encrypted).
|
||||
expect(upsertSpy).toHaveBeenCalledTimes(1)
|
||||
const [persistedRow] = upsertSpy.mock.calls[0] as [
|
||||
{ key: string; value: Record<string, unknown> },
|
||||
]
|
||||
expect(persistedRow.key).toBe('bankid_enrichment')
|
||||
expect(persistedRow.value).toEqual({
|
||||
companyRoles: expect.any(Array),
|
||||
enrichedAtUtc: '2026-05-06T11:30:00Z',
|
||||
const [persistedRow] = upsertSpy.mock.calls[0] as [Record<string, unknown>]
|
||||
expect(persistedRow).toEqual({
|
||||
user_id: expect.any(String),
|
||||
company_roles: expect.any(Array),
|
||||
enriched_at_utc: '2026-05-06T11:30:00Z',
|
||||
})
|
||||
expect(persistedRow.value).not.toHaveProperty('spar')
|
||||
expect(persistedRow.value).not.toHaveProperty('personalNumber')
|
||||
expect(persistedRow.value).not.toHaveProperty('name')
|
||||
expect(persistedRow).not.toHaveProperty('spar')
|
||||
expect(persistedRow).not.toHaveProperty('personalNumber')
|
||||
expect(persistedRow).not.toHaveProperty('name')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool, withUserContext } from '@/tests/pg/setup'
|
||||
import { insertAuthUser } from '@/tests/pg/fixtures'
|
||||
|
||||
// RLS coverage for `bankid_enrichment` (migration 20260506160000). The table
|
||||
// holds CompanyRoles fetched via TIC right after BankID auth and is keyed by
|
||||
// user_id. Reads must be scoped to auth.uid(); writes are service-role only
|
||||
// (no INSERT/UPDATE policy → RLS denies for authenticated).
|
||||
|
||||
async function seedEnrichment(userId: string, roles: unknown[]): Promise<void> {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.bankid_enrichment (user_id, company_roles, enriched_at_utc)
|
||||
VALUES ($1, $2::jsonb, now())`,
|
||||
[userId, JSON.stringify(roles)],
|
||||
)
|
||||
}
|
||||
|
||||
describe('bankid_enrichment RLS', () => {
|
||||
it("lets a user read their own enrichment row", async () => {
|
||||
const userA = await insertAuthUser()
|
||||
await seedEnrichment(userA, [{ orgNumber: '5560000001', position: 'VD' }])
|
||||
|
||||
await withUserContext(userA, async (client) => {
|
||||
const { rows } = await client.query<{ user_id: string }>(
|
||||
'SELECT user_id FROM public.bankid_enrichment WHERE user_id = $1',
|
||||
[userA],
|
||||
)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0]!.user_id).toBe(userA)
|
||||
})
|
||||
})
|
||||
|
||||
it("hides another user's enrichment row", async () => {
|
||||
const userA = await insertAuthUser()
|
||||
const userB = await insertAuthUser()
|
||||
await seedEnrichment(userA, [{ orgNumber: '5560000001' }])
|
||||
await seedEnrichment(userB, [{ orgNumber: '5560000002' }])
|
||||
|
||||
// Querying as userA must not see userB's row even with an explicit filter.
|
||||
await withUserContext(userA, async (client) => {
|
||||
const { rows } = await client.query(
|
||||
'SELECT user_id FROM public.bankid_enrichment WHERE user_id = $1',
|
||||
[userB],
|
||||
)
|
||||
expect(rows).toHaveLength(0)
|
||||
|
||||
// Unfiltered SELECT must return only userA's row.
|
||||
const all = await client.query<{ user_id: string }>(
|
||||
'SELECT user_id FROM public.bankid_enrichment',
|
||||
)
|
||||
const seen = new Set(all.rows.map((r) => r.user_id))
|
||||
expect(seen.has(userA)).toBe(true)
|
||||
expect(seen.has(userB)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
it('denies INSERT from authenticated role (service-role only)', async () => {
|
||||
const userA = await insertAuthUser()
|
||||
|
||||
// The migration grants only SELECT to authenticated; writes go through
|
||||
// the service role inside the TIC extension's BankID complete handler.
|
||||
await withUserContext(userA, async (client) => {
|
||||
await expect(
|
||||
client.query(
|
||||
`INSERT INTO public.bankid_enrichment (user_id, company_roles)
|
||||
VALUES ($1, '[]'::jsonb)`,
|
||||
[userA],
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -31,16 +31,21 @@ const log = createLogger('tic/bankid')
|
||||
|
||||
/**
|
||||
* Request SPAR + CompanyRoles enrichment for a completed BankID session and
|
||||
* cache the CompanyRoles slice in `extension_data` for the
|
||||
* cache the CompanyRoles slice in `bankid_enrichment` for the
|
||||
* /select-company picker.
|
||||
*
|
||||
* Stored in `bankid_enrichment` (user-keyed) rather than `extension_data`
|
||||
* because enrichment runs before the user has a company; `extension_data`
|
||||
* has been company-scoped (NOT NULL company_id) since the multi-tenant
|
||||
* refactor.
|
||||
*
|
||||
* SPAR (personnummer, address, name, birth date) is requested so TIC will
|
||||
* complete the enrichment, but is intentionally NOT persisted: personnummer
|
||||
* is already hashed + encrypted in `bankid_identities`, names live there too,
|
||||
* and no UI currently consumes the address. Storing the SPAR blob in
|
||||
* `extension_data.value` (a plain JSON column) would expose national-ID-level
|
||||
* PII to anyone with read access. If/when address pre-fill is built, encrypt
|
||||
* the relevant fields the same way `encryptPersonalNumber` does for pnr.
|
||||
* and no UI currently consumes the address. Storing the SPAR blob alongside
|
||||
* company roles would expose national-ID-level PII. If/when address pre-fill
|
||||
* is built, encrypt the relevant fields the same way `encryptPersonalNumber`
|
||||
* does for pnr.
|
||||
*
|
||||
* Non-blocking: any failure is logged and swallowed — BankID auth must still
|
||||
* succeed even if enrichment is down.
|
||||
@@ -125,19 +130,26 @@ async function fetchAndStoreEnrichment(
|
||||
|
||||
// Persist only what consumers actually read. See block comment on
|
||||
// fetchAndStoreEnrichment for why SPAR + personnummer + name are excluded.
|
||||
const persistedValue = {
|
||||
companyRoles: enrichmentData.companyRoles ?? [],
|
||||
enrichedAtUtc: enrichmentData.enrichedAtUtc,
|
||||
}
|
||||
|
||||
await supabase
|
||||
.from('extension_data')
|
||||
const { error: upsertError } = await supabase
|
||||
.from('bankid_enrichment')
|
||||
.upsert({
|
||||
user_id: userId,
|
||||
extension_id: 'tic',
|
||||
key: 'bankid_enrichment',
|
||||
value: persistedValue,
|
||||
}, { onConflict: 'user_id,extension_id,key' })
|
||||
company_roles: enrichmentData.companyRoles ?? [],
|
||||
enriched_at_utc: enrichmentData.enrichedAtUtc ?? null,
|
||||
}, { onConflict: 'user_id' })
|
||||
|
||||
if (upsertError) {
|
||||
log.warn('enrichment upsert failed (non-blocking)', {
|
||||
message: upsertError.message,
|
||||
code: upsertError.code,
|
||||
details: upsertError.details,
|
||||
hint: upsertError.hint,
|
||||
})
|
||||
} else {
|
||||
log.info('enrichment persisted to bankid_enrichment', {
|
||||
roleCount: enrichmentData.companyRoles?.length ?? 0,
|
||||
})
|
||||
}
|
||||
} catch (enrichError) {
|
||||
log.warn('enrichment failed (non-blocking)', enrichError)
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_get_counterparty_templates: 'transactions:read',
|
||||
gnubok_suggest_categories: 'transactions:read',
|
||||
gnubok_match_transaction_to_invoice: 'transactions:write',
|
||||
gnubok_auto_match_period: 'transactions:write',
|
||||
// Customers
|
||||
gnubok_list_customers: 'customers:read',
|
||||
gnubok_create_customer: 'customers:write',
|
||||
@@ -71,11 +72,13 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_get_trial_balance: 'reports:read',
|
||||
gnubok_get_vat_report: 'reports:read',
|
||||
gnubok_vat_review_widget: 'reports:read',
|
||||
gnubok_vat_close_check: 'reports:read',
|
||||
gnubok_get_kpi_report: 'reports:read',
|
||||
gnubok_get_income_statement: 'reports:read',
|
||||
gnubok_list_accounts: 'reports:read',
|
||||
gnubok_get_balance_sheet: 'reports:read',
|
||||
gnubok_get_general_ledger: 'reports:read',
|
||||
gnubok_query_journal: 'reports:read',
|
||||
gnubok_get_ar_ledger: 'reports:read',
|
||||
gnubok_get_supplier_ledger: 'reports:read',
|
||||
gnubok_list_fiscal_periods: 'reports:read',
|
||||
@@ -99,6 +102,7 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_lock_period: 'bookkeeping:write',
|
||||
gnubok_unlock_period: 'bookkeeping:write',
|
||||
gnubok_run_year_end: 'bookkeeping:write',
|
||||
gnubok_year_end_readiness: 'reports:read',
|
||||
gnubok_set_opening_balances: 'bookkeeping:write',
|
||||
gnubok_run_currency_revaluation: 'bookkeeping:write',
|
||||
gnubok_explain_voucher_gap: 'bookkeeping:write',
|
||||
@@ -107,10 +111,12 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_uncategorize_transaction: 'transactions:write',
|
||||
// SIE export (read-only) + import (write)
|
||||
gnubok_export_sie: 'reports:read',
|
||||
gnubok_audit_package: 'reports:read',
|
||||
gnubok_import_sie: 'bookkeeping:write',
|
||||
// Supplier invoice lifecycle
|
||||
gnubok_approve_supplier_invoice: 'suppliers:write',
|
||||
gnubok_credit_supplier_invoice: 'suppliers:write',
|
||||
gnubok_create_supplier_invoice_from_inbox: 'suppliers:write',
|
||||
// Invoice conversion + crediting
|
||||
gnubok_convert_invoice: 'invoices:write',
|
||||
gnubok_credit_invoice: 'invoices:write',
|
||||
|
||||
@@ -41,6 +41,33 @@ async function insertPostedEntryWithLines(params: {
|
||||
return id
|
||||
}
|
||||
|
||||
// Insert a document_attachment row already linked to a journal entry, so
|
||||
// tests can exercise the bidirectional immutability trigger on the
|
||||
// journal_entry_id column.
|
||||
async function insertDocumentLinkedToEntry(params: {
|
||||
userId: string
|
||||
companyId: string
|
||||
journalEntryId: string
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.document_attachments
|
||||
(id, user_id, company_id, storage_path, file_name, sha256_hash,
|
||||
journal_entry_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
`test/${id}.pdf`,
|
||||
'receipt.pdf',
|
||||
'a'.repeat(64),
|
||||
params.journalEntryId,
|
||||
],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
describe('delete_last_voucher.pg — RPC + immutability trigger interaction', () => {
|
||||
it('deletes the last posted voucher in a series', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
@@ -190,4 +217,24 @@ describe('delete_last_voucher.pg — RPC + immutability trigger interaction', ()
|
||||
),
|
||||
).rejects.toThrow(/Cannot modify a reversed journal entry/i)
|
||||
})
|
||||
|
||||
// The bypass must remain narrow: an unauthorized direct UPDATE that clears
|
||||
// journal_entry_id outside delete_last_voucher (no gnubok.allow_delete
|
||||
// transaction-local flag) must still raise BFL_DOCUMENT_IMMUTABILITY.
|
||||
it('blocks direct UPDATE that nulls journal_entry_id without the bypass flag', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertPostedEntryWithLines({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const documentId = await insertDocumentLinkedToEntry({
|
||||
userId, companyId, journalEntryId: entryId,
|
||||
})
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
|
||||
[documentId],
|
||||
),
|
||||
).rejects.toThrow(/BFL_DOCUMENT_IMMUTABILITY/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,11 @@ import { seedCompany } from '@/tests/pg/fixtures'
|
||||
// strictly earlier period exists — so importing a company's chronologically
|
||||
// first fiscal year (förlängt första räkenskapsår) via SIE must succeed even
|
||||
// after a later period was created during onboarding.
|
||||
//
|
||||
// seedCompany() creates a default 2026-01-01..2026-12-31 fiscal period; the
|
||||
// no_overlapping_fiscal_periods exclusion constraint (per-company since
|
||||
// migration 20260506140100) means every period inserted here must avoid
|
||||
// overlapping that year. The years below are chosen accordingly.
|
||||
describe('fiscal_periods: subsequent-period start-day trigger', () => {
|
||||
async function insertPeriod(
|
||||
companyId: string,
|
||||
@@ -26,11 +31,14 @@ describe('fiscal_periods: subsequent-period start-day trigger', () => {
|
||||
it('allows a mid-month start when no earlier period exists', async () => {
|
||||
const { companyId } = await seedCompany()
|
||||
|
||||
// The seeded 2026 period is later than this one, so this insert is the
|
||||
// chronologically earliest period for the company → trigger must permit
|
||||
// a mid-month start (förlängt första räkenskapsår path).
|
||||
const { rows } = await insertPeriod(
|
||||
companyId,
|
||||
'Räkenskapsår 2025',
|
||||
'2025-06-15',
|
||||
'2026-06-30',
|
||||
'Räkenskapsår 2024/2025',
|
||||
'2024-06-15',
|
||||
'2025-12-31',
|
||||
)
|
||||
expect(rows[0]!.id).toBeTruthy()
|
||||
})
|
||||
@@ -38,7 +46,7 @@ describe('fiscal_periods: subsequent-period start-day trigger', () => {
|
||||
it('allows importing an earlier mid-month period after a later day-1 period exists', async () => {
|
||||
const { companyId } = await seedCompany()
|
||||
|
||||
// Onboarding-created period (day 1, year N).
|
||||
// Onboarding-created period (day 1, year N) — sits before the seeded 2026.
|
||||
await insertPeriod(companyId, 'Räkenskapsår 2025', '2025-01-01', '2025-12-31')
|
||||
|
||||
// SIE import of förlängt första räkenskapsår — earlier in time,
|
||||
@@ -57,8 +65,10 @@ describe('fiscal_periods: subsequent-period start-day trigger', () => {
|
||||
|
||||
await insertPeriod(companyId, 'Räkenskapsår 2024', '2024-01-01', '2024-12-31')
|
||||
|
||||
// Mid-month start in 2025 — strictly later than 2024 and not overlapping
|
||||
// with the seeded 2026 period → only the start-day trigger should fire.
|
||||
await expect(
|
||||
insertPeriod(companyId, 'Räkenskapsår 2025 (bad)', '2025-06-15', '2026-06-30'),
|
||||
insertPeriod(companyId, 'Räkenskapsår 2025 (bad)', '2025-06-15', '2025-12-31'),
|
||||
).rejects.toThrow(/Non-first fiscal period must start on the 1st of a month/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -50,6 +50,11 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
uncategorize_transaction: 'medium',
|
||||
approve_supplier_invoice: 'high',
|
||||
credit_supplier_invoice: 'high',
|
||||
// Create supplier invoice from inbox: stages a `registered` supplier invoice
|
||||
// + its line items + document attachment. Reversible until approved (the
|
||||
// approval is a separate high-risk op) but creates a leverantörsskuld row,
|
||||
// so we route it through human review at medium tier.
|
||||
create_supplier_invoice_from_inbox: 'medium',
|
||||
credit_invoice: 'high',
|
||||
convert_invoice: 'medium',
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
-- Fix multi-tenant gap in fiscal_periods.no_overlapping_fiscal_periods
|
||||
--
|
||||
-- The exclusion constraint was created before multi-tenant and scopes
|
||||
-- overlap detection by user_id. After the multi-tenant refactor a single
|
||||
-- user can own/be a member of multiple companies, which legitimately
|
||||
-- have their own (overlapping) fiscal years. Rebind the exclusion to
|
||||
-- company_id so the constraint reflects per-tenant uniqueness.
|
||||
|
||||
ALTER TABLE public.fiscal_periods
|
||||
DROP CONSTRAINT IF EXISTS no_overlapping_fiscal_periods;
|
||||
|
||||
ALTER TABLE public.fiscal_periods
|
||||
ADD CONSTRAINT no_overlapping_fiscal_periods
|
||||
EXCLUDE USING gist (
|
||||
company_id WITH =,
|
||||
daterange(period_start, period_end, '[]') WITH &&
|
||||
);
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,28 @@
|
||||
-- BankID enrichment is user-level data fetched immediately after BankID auth,
|
||||
-- before the user has selected or created a company. It cannot live in
|
||||
-- extension_data, which migration 20260330130000 made company-scoped
|
||||
-- (company_id NOT NULL). Every BankID signup since that refactor has silently
|
||||
-- failed to persist enrichment because of the NOT NULL violation.
|
||||
|
||||
CREATE TABLE public.bankid_enrichment (
|
||||
user_id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||
company_roles JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
enriched_at_utc TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE public.bankid_enrichment ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "Users read own enrichment" ON public.bankid_enrichment
|
||||
FOR SELECT USING (auth.uid() = user_id);
|
||||
|
||||
-- Writes happen only via service role (createServiceClient) inside the
|
||||
-- TIC extension's BankID complete handler, so no user-facing INSERT/UPDATE
|
||||
-- policy is needed. Service role bypasses RLS.
|
||||
|
||||
CREATE TRIGGER set_updated_at_bankid_enrichment
|
||||
BEFORE UPDATE ON public.bankid_enrichment
|
||||
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
Reference in New Issue
Block a user