Files
accounted/lib/pending-operations/skatteverket-commit.ts
T
MattssonandClaude Fable 5 8f68421fef 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>
2026-08-30 16:38:30 +02:00

102 lines
3.5 KiB
TypeScript

/**
* Core ↔ Skatteverket-extension commit boundary.
*
* `lib/` cannot import from `@/extensions/` (CI guard, core-build.yml), so the
* commit-side executors reach the Skatteverket extension only through the
* registry-resolved `services` channel. This module defines the SHARED shape
* the extension's commit services return and the recoverable-error class the
* dispatcher uses to release an op back to `pending`: both live in core so the
* extension (which may import core freely) and `commit.ts` agree on the
* contract without core ever importing the extension.
*/
import type { SkattekontoBatchResult } from '@/types/skatteverket'
/** Result returned by the extension's commitSubmitVatDeclaration / commitSubmitAgi. */
export type SkvSubmitResult =
| ({
ok: true
/** BankID signing deep-link. The op is "sent for signing", not filed. */
signing_url: string
} & Record<string, unknown>)
| {
ok: false
/** Structured error code (see lib/errors/structured-errors.ts). */
code: string
http_status: number
/**
* true → the op is fine; the connection/flag/quota isn't. Release it back
* to `pending` so the user can fix and re-approve the SAME op.
* false → a wrong-data / SKV-business condition. Reject (consume) the op;
* the user must regenerate and re-stage.
*/
recoverable: boolean
error: string
}
/** The two functions a fully-wired skatteverket extension exposes on `services`. */
export interface SkatteverketCommitServices {
commitSubmitVatDeclaration: (
supabase: unknown,
userId: string,
companyId: string,
params: Record<string, unknown>,
) => Promise<SkvSubmitResult>
commitSubmitAgi: (
supabase: unknown,
userId: string,
companyId: string,
params: Record<string, unknown>,
) => 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,
* releases the atomic claim back to `pending`, and surfaces { error, code,
* http_status }: mirroring the AccountsNotInChartError release path.
*/
export class SkatteverketRecoverableError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly httpStatus: number,
) {
super(message)
this.name = 'SkatteverketRecoverableError'
}
}