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:
co-authored by
Claude Opus 4.7
parent
ce3af4d17e
commit
4131db2894
@@ -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',
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user