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
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user