feat(skatteverket): expose skattekonto row booking via MCP staged operations (#2039)
* feat(skatteverket): expose skattekonto row booking via MCP staged operations Skattekonto READ and RECONCILE were already MCP tools, but BOOKING rows existed only behind the cookie-session extension routes. This closes the flow on API-key surfaces: - New staged MCP write tools gnubok_book_skattekonto_row and gnubok_book_skattekonto_rows (batch, 1-200 ids), catalogVisibility 'search', STAGED_OPERATION_SCHEMA, stage-time bookability gates and rule-matched counter-account preview. Staging never books. - New pending-operation types book_skattekonto_row / book_skattekonto_rows (CHECK constraint migration pair, risk tier medium, sv/en labels). - Commit executor reaches the skatteverket extension through the registry-resolved services channel (core never imports @/extensions): new commitBookSkattekontoRows service wraps the SAME bokforSkattekontoTransactionsBatch helper the HTTP bokfor-batch route uses (draft + commit per row via the bookkeeping engine, requireSettled), with the approving user id passed explicitly (auth.uid() is NULL on the service client). No booking math or account mapping changed: auth-surface exposure only. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018zGah8Yy49esAwpnKGxiGy * chore(migrations): move book_skattekonto constraint pair after main's newest version origin/main gained 20260830101500 while this branch was in flight; keep the new pending_operations constraint migrations sorted after it so they apply in order. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018zGah8Yy49esAwpnKGxiGy * fix(skatteverket): resolve CI and review findings for skattekonto booking tools - Inline the skattekonto_transactions select strings at both stage-time call sites so the no-phantom-columns scanner can resolve them (the shared const pushed the unresolvable-expression count past the ceiling and failed Unit tests 3/4). - Return a fixed public message from the commitBookSkattekontoRows batch-level catch instead of the raw exception text; the raw error stays in the server log (Superagent P2). - Add verifikat_description to the staged previews so the reviewer sees the exact ledger text the booking helper writes, Skatteverket motpart included (Swedish accounting review). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018zGah8Yy49esAwpnKGxiGy --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
3cf2e10740
commit
8f68421fef
@@ -236,6 +236,10 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_bulk_book_transactions: 'transactions:write',
|
||||
gnubok_bulk_book_inbox_items: 'transactions:write',
|
||||
gnubok_auto_match_period: 'transactions:write',
|
||||
// Skattekonto row booking writes a verifikat from an outside (SKV) row:
|
||||
// same scope family as reconcile_residual / bulk_book above.
|
||||
gnubok_book_skattekonto_row: 'transactions:write',
|
||||
gnubok_book_skattekonto_rows: 'transactions:write',
|
||||
// Customers
|
||||
gnubok_list_customers: 'customers:read',
|
||||
gnubok_create_customer: 'customers:write',
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* Unit tests for commitBookSkattekontoRows (op types book_skattekonto_row /
|
||||
* book_skattekonto_rows), driven through the public commitPendingOperation
|
||||
* dispatcher.
|
||||
*
|
||||
* The MCP staging tools never book; the approved op's executor resolves the
|
||||
* skatteverket extension's commitBookSkattekontoRows service via the registry
|
||||
* (core cannot import @/extensions) and translates its result into the op
|
||||
* lifecycle:
|
||||
* - ok with >= 1 booked row → committed (per-row results in result_data)
|
||||
* - ok with 0 booked rows → rejected (409, reasons in result_data)
|
||||
* - recoverable failure → released back to 'pending'
|
||||
* - non-recoverable failure → rejected
|
||||
*
|
||||
* A FAKE extension is registered so no real booking code runs: this isolates
|
||||
* the core wiring (registry resolution + lifecycle), same pattern as
|
||||
* skatteverket-executors.test.ts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import type { Extension } from '@/lib/extensions/types'
|
||||
import type { SkattekontoBookCommitResult } from '@/lib/pending-operations/skatteverket-commit'
|
||||
import type { PendingOperation } from '@/types'
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
return {
|
||||
id: 'op-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
operation_type: 'book_skattekonto_rows',
|
||||
status: 'pending',
|
||||
title: 'test',
|
||||
params: {},
|
||||
preview_data: {},
|
||||
result_data: null,
|
||||
actor_type: 'user',
|
||||
actor_id: null,
|
||||
actor_label: null,
|
||||
risk_level: 'medium',
|
||||
created_at: '2026-08-01T00:00:00Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-08-01T00:00:00Z',
|
||||
...overrides,
|
||||
} as PendingOperation
|
||||
}
|
||||
|
||||
function registerFakeSkatteverket(
|
||||
services: Record<string, (...a: unknown[]) => Promise<SkattekontoBookCommitResult>>,
|
||||
): void {
|
||||
extensionRegistry.register({
|
||||
id: 'skatteverket',
|
||||
name: 'fake-skatteverket',
|
||||
version: '0.0.0',
|
||||
services,
|
||||
} as unknown as Extension)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
afterEach(() => {
|
||||
extensionRegistry.clear()
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: book_skattekonto_row(s)', () => {
|
||||
it('happy batch path: committed with per-row results, actor userId passed through', async () => {
|
||||
const book = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
results: [
|
||||
{ id: 'skv-1', ok: true, journal_entry_id: 'je-1', voucher_number: 41, voucher_series: 'A' },
|
||||
{ id: 'skv-2', ok: true, journal_entry_id: 'je-2', voucher_number: 42, voucher_series: 'A' },
|
||||
],
|
||||
summary: { total: 2, succeeded: 2, failed: 0 },
|
||||
})
|
||||
registerFakeSkatteverket({ commitBookSkattekontoRows: book })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: null, error: null }) // dispatcher commit update
|
||||
|
||||
const op = makePendingOp({ params: { ids: ['skv-1', 'skv-2'] } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ summary: { total: 2, succeeded: 2, failed: 0 } })
|
||||
// The approving human is the actor: userId is threaded explicitly because
|
||||
// the service-role client nulls auth.uid().
|
||||
expect(book).toHaveBeenCalledWith(expect.anything(), 'user-1', 'company-1', {
|
||||
ids: ['skv-1', 'skv-2'],
|
||||
})
|
||||
})
|
||||
|
||||
it('single-row op shape { transaction_id } is normalised to an id list', async () => {
|
||||
const book = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
results: [{ id: 'skv-1', ok: true, journal_entry_id: 'je-1', voucher_number: 7, voucher_series: 'A' }],
|
||||
summary: { total: 1, succeeded: 1, failed: 0 },
|
||||
})
|
||||
registerFakeSkatteverket({ commitBookSkattekontoRows: book })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null })
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const op = makePendingOp({
|
||||
operation_type: 'book_skattekonto_row',
|
||||
params: { transaction_id: 'skv-1' },
|
||||
})
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(book).toHaveBeenCalledWith(expect.anything(), 'user-1', 'company-1', { ids: ['skv-1'] })
|
||||
})
|
||||
|
||||
it('partial batch still commits, with the failed rows in result_data', async () => {
|
||||
const book = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
results: [
|
||||
{ id: 'skv-1', ok: true, journal_entry_id: 'je-1', voucher_number: 41, voucher_series: 'A' },
|
||||
{ id: 'skv-2', ok: false, error_code: 'PERIOD_LOCKED', error_message: 'låst period' },
|
||||
],
|
||||
summary: { total: 2, succeeded: 1, failed: 1 },
|
||||
})
|
||||
registerFakeSkatteverket({ commitBookSkattekontoRows: book })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null })
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const op = makePendingOp({ params: { ids: ['skv-1', 'skv-2'] } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ summary: { total: 2, succeeded: 1, failed: 1 } })
|
||||
})
|
||||
|
||||
it('zero booked rows → rejected 409 with per-row reasons, never silently committed', async () => {
|
||||
const book = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
results: [
|
||||
{ id: 'skv-1', ok: false, error_code: 'ALREADY_BOOKED', error_message: 'Transaktionen är redan bokförd.' },
|
||||
],
|
||||
summary: { total: 1, succeeded: 0, failed: 1 },
|
||||
})
|
||||
registerFakeSkatteverket({ commitBookSkattekontoRows: book })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null })
|
||||
enqueue({ data: null, error: null }) // reject update
|
||||
|
||||
const op = makePendingOp({ params: { ids: ['skv-1'] } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(409)
|
||||
expect(result.error).toMatch(/redan bokförd/)
|
||||
})
|
||||
|
||||
it('no service registered → failed EXTENSION_DISABLED, op released to pending', async () => {
|
||||
// registry is empty (afterEach cleared it; nothing registered here)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: null, error: null }) // release-to-pending update
|
||||
|
||||
const op = makePendingOp({ params: { ids: ['skv-1'] } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.code).toBe('EXTENSION_DISABLED')
|
||||
expect(result.http_status).toBe(503)
|
||||
})
|
||||
|
||||
it('recoverable service result → released to pending with the structured code', async () => {
|
||||
const book = vi.fn().mockResolvedValue({
|
||||
ok: false, code: 'EXTENSION_DISABLED', http_status: 503, recoverable: true,
|
||||
error: 'Skatteverket-integrationen är inte aktiverad i denna miljö.',
|
||||
})
|
||||
registerFakeSkatteverket({ commitBookSkattekontoRows: book })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null })
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const op = makePendingOp({ params: { ids: ['skv-1'] } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.code).toBe('EXTENSION_DISABLED')
|
||||
expect(result.http_status).toBe(503)
|
||||
})
|
||||
|
||||
it('non-recoverable service result → op rejected (consumed)', async () => {
|
||||
const book = vi.fn().mockResolvedValue({
|
||||
ok: false, code: 'SKATTEKONTO_BOOKING_FAILED', http_status: 500, recoverable: false,
|
||||
error: 'rule context load failed',
|
||||
})
|
||||
registerFakeSkatteverket({ commitBookSkattekontoRows: book })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null })
|
||||
enqueue({ data: null, error: null }) // reject update
|
||||
|
||||
const op = makePendingOp({ params: { ids: ['skv-1'] } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(500)
|
||||
expect(result.error).toMatch(/rule context/)
|
||||
})
|
||||
|
||||
it('missing ids → 400 without resolving the extension service', async () => {
|
||||
const book = vi.fn()
|
||||
registerFakeSkatteverket({ commitBookSkattekontoRows: book })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null })
|
||||
enqueue({ data: null, error: null }) // reject update
|
||||
|
||||
const op = makePendingOp({ params: {} })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(400)
|
||||
expect(book).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -106,6 +106,7 @@ import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import {
|
||||
SkatteverketRecoverableError,
|
||||
type SkatteverketCommitServices,
|
||||
type SkattekontoBookingCommitService,
|
||||
type SkvSubmitResult,
|
||||
} from '@/lib/pending-operations/skatteverket-commit'
|
||||
import { PartialCommitError } from '@/lib/pending-operations/errors'
|
||||
@@ -5899,6 +5900,80 @@ async function commitSubmitAgi(
|
||||
return handleSkvSubmitResult(result)
|
||||
}
|
||||
|
||||
// ── Skattekonto row booking commit handler ────────────────────────
|
||||
//
|
||||
// Commit side of the staged book_skattekonto_row / book_skattekonto_rows MCP
|
||||
// ops. The booking logic lives in the skatteverket extension
|
||||
// (lib/skattekonto-booking.ts, same helper the HTTP bokfor-batch route uses),
|
||||
// so this reaches it through the registry-resolved `services` channel exactly
|
||||
// like the filing handlers above. Separate getter: the booking service must
|
||||
// work (or fail recoverable) independently of the SKV filing services.
|
||||
|
||||
function getSkattekontoBookingService(): SkattekontoBookingCommitService {
|
||||
const services = extensionRegistry.get('skatteverket')?.services as
|
||||
| Partial<SkattekontoBookingCommitService>
|
||||
| undefined
|
||||
if (!services?.commitBookSkattekontoRows) {
|
||||
// Extension absent or not wired. Recoverable: leave the op pending so a
|
||||
// re-enable + re-approve works without re-staging.
|
||||
throw new SkatteverketRecoverableError(
|
||||
'Skatteverket-integrationen är inte tillgänglig.',
|
||||
'EXTENSION_DISABLED',
|
||||
503,
|
||||
)
|
||||
}
|
||||
return services as SkattekontoBookingCommitService
|
||||
}
|
||||
|
||||
async function commitBookSkattekontoRows(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>,
|
||||
): Promise<ExecutorResult> {
|
||||
// Accept both staged shapes: the single-row op stores { transaction_id },
|
||||
// the batch op stores { ids }. Normalised to one id list for the service.
|
||||
const ids = Array.isArray(params.ids)
|
||||
? params.ids.filter((v): v is string => typeof v === 'string' && v.length > 0)
|
||||
: typeof params.transaction_id === 'string' && params.transaction_id.length > 0
|
||||
? [params.transaction_id]
|
||||
: []
|
||||
if (ids.length === 0) {
|
||||
return { error: 'ids (eller transaction_id) krävs', status: 400 }
|
||||
}
|
||||
|
||||
const services = getSkattekontoBookingService()
|
||||
const result = await services.commitBookSkattekontoRows(supabase, userId, companyId, { ids })
|
||||
if (!result.ok) {
|
||||
if (result.recoverable) {
|
||||
throw new SkatteverketRecoverableError(result.error, result.code, result.http_status)
|
||||
}
|
||||
return { error: result.error, status: result.http_status, errorCode: result.code }
|
||||
}
|
||||
|
||||
if (result.summary.succeeded === 0) {
|
||||
// Nothing was booked: reject (consume) the op with the per-row reasons in
|
||||
// result_data so the user fixes the rows (unignore, unlock period, add a
|
||||
// rule) and re-stages. 409: the dominant causes are state conflicts
|
||||
// (already booked / ignored / unsettled).
|
||||
const firstError = result.results.find((r) => !r.ok)
|
||||
return {
|
||||
error: firstError?.error_message ?? 'Ingen skattekontorad kunde bokföras.',
|
||||
status: 409,
|
||||
data: { results: result.results, summary: result.summary },
|
||||
}
|
||||
}
|
||||
|
||||
log.info('book_skattekonto_rows committed', {
|
||||
companyId,
|
||||
operationType: 'book_skattekonto_rows',
|
||||
total: result.summary.total,
|
||||
succeeded: result.summary.succeeded,
|
||||
failed: result.summary.failed,
|
||||
})
|
||||
return { data: { results: result.results, summary: result.summary } }
|
||||
}
|
||||
|
||||
// ── Multi-tx commit handlers (PRs #603/#606/#608/#610) ────────────
|
||||
//
|
||||
// Both wrap their SQL RPC. The RPCs do all the heavy lifting (locking,
|
||||
@@ -6626,6 +6701,10 @@ async function commitPendingOperationInner(
|
||||
case 'reconciliation_residual':
|
||||
result = await commitReconciliationResidual(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'book_skattekonto_row':
|
||||
case 'book_skattekonto_rows':
|
||||
result = await commitBookSkattekontoRows(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'submit_vat_declaration':
|
||||
result = await commitSubmitVatDeclaration(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -218,6 +218,13 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// links the selection: a typed, bounded booking like categorize_transaction,
|
||||
// undone by storno + unmatch, so 'medium' rather than create_voucher's 'high'.
|
||||
reconciliation_residual: 'medium',
|
||||
// Book synced skattekonto rows as posted verifikat: 1630 against the
|
||||
// skattekonto_rules-matched counter account, amounts straight from the
|
||||
// synced Skatteverket data. No caller-supplied lines (the agent passes only
|
||||
// row ids), reversible via storno: same bounded-booking tier as
|
||||
// book_mileage_period, not create_voucher's arbitrary-line 'high'.
|
||||
book_skattekonto_row: 'medium',
|
||||
book_skattekonto_rows: 'medium',
|
||||
|
||||
// ── Körjournal (mileage) ───────────────────────────────────────────
|
||||
// A trip row is pure travel documentation: no booking impact until a
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
* contract without core ever importing the extension.
|
||||
*/
|
||||
|
||||
import type { SkattekontoBatchResult } from '@/types/skatteverket'
|
||||
|
||||
/** Result returned by the extension's commitSubmitVatDeclaration / commitSubmitAgi. */
|
||||
export type SkvSubmitResult =
|
||||
| ({
|
||||
@@ -48,6 +50,39 @@ export interface SkatteverketCommitServices {
|
||||
) => Promise<SkvSubmitResult>
|
||||
}
|
||||
|
||||
/**
|
||||
* Result returned by the extension's commitBookSkattekontoRows service.
|
||||
* On ok the shape is the same per-row list + summary the HTTP bokfor-batch
|
||||
* endpoint returns (types/skatteverket.ts): row failures are data, never a
|
||||
* thrown error, so a partially successful batch still commits the op with
|
||||
* the failed rows listed in result_data.
|
||||
*/
|
||||
export type SkattekontoBookCommitResult =
|
||||
| ({ ok: true } & SkattekontoBatchResult)
|
||||
| {
|
||||
ok: false
|
||||
code: string
|
||||
http_status: number
|
||||
/** Same semantics as SkvSubmitResult: true releases the op back to pending. */
|
||||
recoverable: boolean
|
||||
error: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Booking service a fully-wired skatteverket extension exposes on `services`.
|
||||
* Separate from SkatteverketCommitServices so the skattekonto booking path
|
||||
* (local bookkeeping over already-synced rows) does not depend on the SKV
|
||||
* filing services being wired, and vice versa.
|
||||
*/
|
||||
export interface SkattekontoBookingCommitService {
|
||||
commitBookSkattekontoRows: (
|
||||
supabase: unknown,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>,
|
||||
) => Promise<SkattekontoBookCommitResult>
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown by a commit executor when the failure is recoverable (extension
|
||||
* disabled, no SKV connection, rate-limited). The dispatcher catches it,
|
||||
|
||||
Reference in New Issue
Block a user