Files
accounted/extensions/general/skatteverket/lib/agi-client.ts
T
MattssonandClaude Fable 5 98d0c7f2d0 Add/stripe skv (#1004)
* fix(salary): align pain.001 salary file with the Swedish domestic bank dialect

Verified against the Swedish Common Interpretation of ISO 20022
(Bankforeningen, Common Payment Types in Sweden, Appendix 1 Example 4:
Salaries) and Nordea Corporate Access pain.001 examples v2.6 (2026-06-22),
and XSD-validated against the official pain.001.001.03 schema:

- drop SvcLvl SEPA (SEPA credit transfers are EUR-only; omitting SvcLvl
  gets the domestic NURG default)
- drop RmtInf (not allowed for SALA salary payments; the beneficiary
  statement text comes from the Dataclearing LON code)
- address employees domestically: clearing as CdtrAgt ClrSysMmbId SESBA,
  account WITHOUT clearing as CdtrAcct Othr with SchmeNm BBAN
- share the clearing/account split (Swedbank 5-digit shift, Nordea
  personkonto prefix dedup) between the LB and pain.001 generators via
  splitDomesticBankAccount, fixing pain.001 duplicating the personkonto
  clearing
- clamp MsgId/PmtInfId/InstrId/EndToEndId to Max35Text with the per-tx
  counter surviving truncation; carry the org number on Dbtr
- return 400 from the pain001 route on an invalid clearing instead of
  emitting a broken file

Also includes two unrelated decision-log lines from the parallel
revisor-review session (DECISIONS.md is a shared append-only log).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(nav): surface the year-end chain in the sidebar

Add Periodiseringar, Arsredovisning (aktiebolag only) and
Inkomstdeklaration (INK2 for AB, NE-bilaga for EF) to the Skatt &
bokslut group, in workflow order. Entity gating via a new entityOnly
flag on NavItem; isActive carve-outs extended so exactly one row
lights up for the new routes. Driven by an external revisor review
that concluded these features did not exist because none of them
were reachable from the nav.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(stripe): Stripe Connect integration behind config gate

Connect OAuth per company (only the acct_ id is stored), automatic
single-use Payment Links on invoice send, deterministic payment
settlement against 1686 (BAS moved acquirer receivables 1580 -> 1686),
payout booking with reverse-charge fees (6570 + 4535/4598 + 2645/2614),
and a 15-minute sync cron. Non-deterministic events land as
needs_review, never guessed at.

Fully dark without STRIPE_CONNECT_CLIENT_ID: connect returns 503, the
send hook and cron no-op, and the settings page shows 'Kommer snart'
(hosted) until the Connect platform is verified. Self-hosted keeps the
honest not-configured message.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(deadlines): add shared completeTaxDeadline and fix dead AGI deadline auto-complete

generate-declaration.ts has updated non-existent columns (type/period/
status) since inception, so the arbetsgivardeklaration deadline was
never auto-completed. Replace with a shared helper targeting the real
schema (tax_deadline_type/tax_period/is_completed), also used by the
kvittens crons and moms handlers in the follow-up commit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(rot-rut): import Skatteverket beslutsfil and record decisions on payout requests

Parse the beslutsfil JSON from Skatteverkets rot/rut e-tjanst and record
godkant belopp on the matching begaran: matched by stored
skv_referensnummer first, then exact name among active undecided
requests; arenden by fakturanummer then personnummer, exactly-one or the
beslut errors (all-or-nothing). Never auto-settles: recording the beslut
and booking the payout are separate acts. Exposed as an API route and
the gnubok_import_rot_rut_beslut MCP tool.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(skatteverket): system auth for background reads, one-click VAT submit, kvittens notifications

Hybrid auth program: system CCG (org certificate) for background reads
while personal BankID stays for interactive submissions, since SKV
per-flow refresh tokens live 65 min and crons structurally cannot run
on them. All system-auth code sits behind SKATTEVERKET_SYSTEM_AUTH_MODE
(default off) with a stub transport until the Expisoft cert and CCG
avtal land; auth resolution is centralized in resolve-auth.ts.

Also in this change:
- One-click VAT submit chaining kontrollera -> utkast -> las
  server-side with a stage discriminator; step-by-step buttons demoted
  to the overflow menu.
- Kvittens crons (AGI + new VAT schedule) with email-only
  notifications, deduped in notification_log under the new
  skv_kvittens type.
- Ombud grant probe + verification UI in the connect panel, and a
  dashboard promo card for unconnected companies.
- skatteverket_company_connections table with pg-real coverage.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(salary): auto-settle AGI tax payment from skattekonto and surface SKV reconnect on the tax card

The "Skatt att betala" card only cleared via the manual mark-paid button
on the run detail page; the promised automatic flip from the Skattekonto
sync was never implemented, so paid periods stayed red.

- settleAgiTaxPayments: during every skattekonto sync, a booked
  "Arbetsgivardeklaration YYYYMM" debit row settles the matching
  agi_declarations.tax_paid_at, but only when the amount equals the
  declared total to the ore and the account is not in deficit
  (deterministic; drift or deficit falls back to manual).
- Salary overview card: reconnect hint when the SKV token needs
  re-consent (link to /settings/tax, silent when the extension is off),
  plus an inline "Markera som betald" button reusing the existing
  endpoint and salary_payments strings.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add cloud backup scheduling and alerting features

- Implement unit tests for scheduling logic in `schedule.test.ts`, covering various scenarios for determining if a backup schedule is due.
- Create a new module `backup-alert.ts` to handle failure alerts for cloud backup auto-sync, including email notifications for reauthentication and repeated failures.
- Introduce `schedule.ts` to manage scheduling logic, including handling local time zones and converting between local and UTC hours.
- Add CSV report generation functions in `archive-csv.ts` for trial balance, income statement, balance sheet, and general ledger, ensuring compatibility with Swedish Excel formats.
- Create a README generator for the archive structure in `archive-readme.ts`, providing clear documentation for users accessing backup files.
- Implement tests for CSV report generation in `archive-csv.test.ts`, ensuring correct formatting and content.
- Establish a full-archive coverage contract test in `full-archive-coverage.pg.test.ts` to ensure all company-scoped tables are properly classified for backup.

* fix(stripe): correct invoice clearing reference and improve type safety in sync logic

* fix(invoices): narrow accountingMethod before resolveInvoicePaymentSourceType

settleInvoicePayment takes accountingMethod as a raw settings string, but
resolveInvoicePaymentSourceType requires the 'accrual' | 'cash' union.
Normalize at the call site (anything but 'cash' books as accrual), matching
the existing useCashEntry semantics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: address CodeRabbit review findings and nitpicks on PR #1004

Review findings:
- backup settings redirect: always force view=export over incoming params
- AGI/VAT kvittens crons: isolate best-effort post-submit calls, check the
  signed-state persist error, guard recovery calls in catch blocks so one
  company cannot abort the rest; surface grant_revoked in the run summary
- kvittens notifications: atomic claim-first dedup with a partial unique
  index; map non-uuid reference keys to deterministic uuids
- grant probe: record the actual 2xx status; mTLS transport: handle
  response-stream errors
- stripe: amount-aware idempotency keys for payment links; emit
  stripe.disconnected on upstream revocations
- ROT/RUT beslut import: mutate in-memory request state after apply, move
  item + header writes into an atomic apply_rot_rut_beslut RPC, add
  rot_rut_payout to JournalEntrySourceTypeSchema
- migrations: use NOT VALID + VALIDATE CONSTRAINT for CHECK constraints on
  journal_entries, notification_log and rot_rut_payout_requests
- cloud backup: hour_utc-only schedule updates clear stale hour_local

Nitpicks:
- stripe sync: enforce the cron time budget inside per-connection event
  processing with idempotent cursor progress; maybeSingle for settings;
  honest partial-customer DTO shared with the settlement boundary
- shared applyPaymentLinkToInvoice helper for both invoice send routes,
  v1 docblock documents step 6b and PAYMENT_LINK_FAILED
- settings panel: drop redundant decodeURIComponent
- cloud backup: document worst-case archive memory headroom

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 19:14:12 +02:00

423 lines
14 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { skvRequest, skvRequestWithAuth, type SkvAuth } from './api-client'
import type {
SkatteverketAGIErrorBody,
SkatteverketAGIGranskningsunderlagResponse,
SkatteverketAGIKontrollresultat,
SkatteverketAGIKontrollsvar,
SkatteverketAGIKvittenserResponse,
SkatteverketAGIUnderlagResponse,
} from '../types'
/**
* Skatteverket AGI (Arbetsgivardeklaration) client.
*
* Two RAMLs back this surface:
* • inlamning v1.7.7 : XML ingest + JSON status reads
* base: /arbetsgivardeklaration/inlamning/v1
* • hanteraredovisningsperiod v1.2.8: period lock + receipts
* base: /arbetsgivardeklaration/hanteraredovisningsperiod/v1
*
* Filing flow:
* 1. POST /underlag (XML body, returns inlamningId)
* 2. GET /underlag/{inlamningId}/kontrollresultat (poll until status != PROCESSING)
* 3a. POST /underlag/{inlamningId}/spara (move into Eget utrymme)
* 3b. DELETE /underlag/{inlamningId} (abort if user wants to retry)
* 4. POST /arbetsgivare/{x}/redovisningsperioder/{y}/skapaGranskningsunderlag?lasPeriod=true
* → returns Mina Sidor deep-link for BankID signing
* 5. GET /arbetsgivare/{x}/redovisningsperioder/{y}/kvittenser (after user signs)
*
* Optional period management on the hantera API:
* POST /arbetsgivare/{x}/redovisningsperioder/{y}/las (lock)
* POST /arbetsgivare/{x}/redovisningsperioder/{y}/lasUpp (unlock)
*
* Cleanup paths (both on the inlämning API, NOT hantera):
* DELETE /underlag/{inlamningId}:
* abort an unsaved underlag (use agiAvbrytUnderlag)
* DELETE /arbetsgivare/{x}/redovisningsperioder/{y}/inlamningar/{inlamningId}:
* remove a SAVED underlag from Eget utrymme (use agiTaBortSparadInlamning)
*
* Note: skvRequest already maps 401/403/429 to SkatteverketAuthError. AGI
* 400/404/409 carry the SkatteverketAGIErrorBody envelope, which we surface
* via Result.error so callers can render meddelandeTillAnvandare verbatim.
*/
const DEFAULT_INLAMNING_BASE_URL =
'https://api.test.skatteverket.se/arbetsgivardeklaration/inlamning/v1'
const DEFAULT_HANTERA_BASE_URL =
'https://api.test.skatteverket.se/arbetsgivardeklaration/hanteraredovisningsperiod/v1'
function getInlamningBaseUrl(): string {
return process.env.SKATTEVERKET_AGD_INLAMNING_API_BASE_URL || DEFAULT_INLAMNING_BASE_URL
}
function getHanteraBaseUrl(): string {
return process.env.SKATTEVERKET_AGD_PERIOD_API_BASE_URL || DEFAULT_HANTERA_BASE_URL
}
function periodPath(arbetsgivare: string, period: string): string {
return `/arbetsgivare/${arbetsgivare}/redovisningsperioder/${period}`
}
interface Ok<T> { ok: true; status: number; data: T }
interface Err { ok: false; status: number; error: string; body?: SkatteverketAGIErrorBody }
type Result<T> = Ok<T> | Err
async function readErrorBody(response: Response): Promise<{ error: string; body?: SkatteverketAGIErrorBody }> {
try {
const body = (await response.json()) as SkatteverketAGIErrorBody
if (body && typeof body.meddelandeTillAnvandare === 'string') {
return { error: body.meddelandeTillAnvandare, body }
}
return { error: JSON.stringify(body) }
} catch {
return { error: `Skatteverket svarade med ${response.status}` }
}
}
/**
* POST /underlag: XML body, returns the new inlämningsId.
*
* The xml is whatever generateAGIXml() produced. We don't validate it
* locally; Skatteverket replies 415 if the schema fails parsing, or 400
* with felkod 38 if required fields are missing.
*/
export async function agiPostUnderlag(
supabase: SupabaseClient,
userId: string,
xml: string,
): Promise<Result<SkatteverketAGIUnderlagResponse>> {
const response = await skvRequest(
supabase,
userId,
'POST',
'/underlag',
xml,
{
baseUrl: getInlamningBaseUrl(),
contentType: 'application/xml',
},
)
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = (await response.json()) as SkatteverketAGIUnderlagResponse
return { ok: true, status: response.status, data }
}
/**
* GET /underlag/{inlamningId}/kontrollresultat.
*
* Returns immediately with the current status. Callers should poll while
* status === 'PROCESSING' (Skatteverket's typical processing time is sub-
* second but the spec doesn't guarantee it).
*/
export async function agiGetKontrollresultat(
supabase: SupabaseClient,
userId: string,
inlamningId: number,
): Promise<Result<SkatteverketAGIKontrollresultat>> {
const response = await skvRequest(
supabase,
userId,
'GET',
`/underlag/${inlamningId}/kontrollresultat`,
undefined,
{ baseUrl: getInlamningBaseUrl() },
)
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = (await response.json()) as SkatteverketAGIKontrollresultat
return { ok: true, status: response.status, data }
}
/**
* POST /underlag/{inlamningId}/spara: commit the underlag to Eget utrymme.
*
* Allowed even when kontrollresultat reports DONE_REJECTED: SKV will keep
* the rejected underlag in Eget utrymme as a record. Mina Sidor does NOT
* expose in-place editing of saved underlag; correcting a rejected AGI
* means generating new XML (with the same FK570 specifikationsnummer per
* employee) and resubmitting it as a rättelse via the same /underlag flow.
* The current AGIPanel doesn't auto-spara on rejection; it surfaces the
* findings and leaves recovery (re-generate + re-submit) to the user.
*
* Returns 400 felkod 20 if the underlag was already saved or had no
* errors to fix.
*/
export async function agiSparaUnderlag(
supabase: SupabaseClient,
userId: string,
inlamningId: number,
): Promise<Result<unknown>> {
const response = await skvRequest(
supabase,
userId,
'POST',
`/underlag/${inlamningId}/spara`,
undefined,
{ baseUrl: getInlamningBaseUrl() },
)
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = await response.json().catch(() => ({}))
return { ok: true, status: response.status, data }
}
/**
* DELETE /underlag/{inlamningId}: avbryt en inlämning som ännu inte sparats.
*
* Use this to discard an underlag whose kontrollresultat showed errors
* before the user has clicked "spara". For *saved* underlag use
* agiTaBortSparadInlamning() below.
*/
export async function agiAvbrytUnderlag(
supabase: SupabaseClient,
userId: string,
inlamningId: number,
): Promise<Result<unknown>> {
const response = await skvRequest(
supabase,
userId,
'DELETE',
`/underlag/${inlamningId}`,
undefined,
{ baseUrl: getInlamningBaseUrl() },
)
if (response.status === 204) return { ok: true, status: 204, data: {} }
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = await response.json().catch(() => ({}))
return { ok: true, status: response.status, data }
}
/**
* DELETE a saved underlag for an arbetsgivare + period. Distinct from
* agiAvbrytUnderlag: this targets the saved copy in Eget utrymme.
*/
export async function agiTaBortSparadInlamning(
supabase: SupabaseClient,
userId: string,
arbetsgivare: string,
period: string,
inlamningId: number,
): Promise<Result<unknown>> {
const response = await skvRequest(
supabase,
userId,
'DELETE',
`${periodPath(arbetsgivare, period)}/inlamningar/${inlamningId}`,
undefined,
{ baseUrl: getInlamningBaseUrl() },
)
if (response.status === 204) return { ok: true, status: 204, data: {} }
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
return { ok: true, status: response.status, data: {} }
}
/**
* POST /arbetsgivare/{x}/redovisningsperioder/{y}/skapaGranskningsunderlag.
*
* Returns a Mina Sidor deep-link the user opens in a new tab to sign with
* BankID. `lasPeriod=true` locks the period for changes during signing:
* recommended for the happy path. Caller can later POST .../las or .../lasUpp
* on the hantera API to flip the lock without regenerating the granskning.
*/
export async function agiSkapaGranskningsunderlag(
supabase: SupabaseClient,
userId: string,
arbetsgivare: string,
period: string,
options: { lasPeriod?: boolean } = {},
): Promise<Result<SkatteverketAGIGranskningsunderlagResponse>> {
const qs = options.lasPeriod ? '?lasPeriod=true' : ''
const response = await skvRequest(
supabase,
userId,
'POST',
`${periodPath(arbetsgivare, period)}/skapaGranskningsunderlag${qs}`,
undefined,
{ baseUrl: getInlamningBaseUrl() },
)
// 409 INCORRECT_DATA returns the same shape as 200 (with a felrapport
// link): surface it as data rather than an error so the UI can route the
// user to fix the rejected underlag.
if (response.status === 409) {
const data = (await response.json()) as SkatteverketAGIGranskningsunderlagResponse
return { ok: true, status: 409, data }
}
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = (await response.json()) as SkatteverketAGIGranskningsunderlagResponse
return { ok: true, status: response.status, data }
}
/**
* GET /arbetsgivare/{x}/redovisningsperioder/{y}/kvittenser
* (hanteraredovisningsperiod API).
*
* Returns an empty kvittenser array until the user has signed in Mina Sidor.
* Once signed, each receipt carries uuidKvittens + signeradAv + signeradTid.
*
* Takes SkvAuth (not supabase+userId): kvittens polling is a background
* read, so the crons can run it on system credentials when the company has
* granted the lasombud behorighet.
*/
export async function agiGetKvittenser(
auth: SkvAuth,
arbetsgivare: string,
period: string,
): Promise<Result<SkatteverketAGIKvittenserResponse>> {
const response = await skvRequestWithAuth(
auth,
'GET',
`${periodPath(arbetsgivare, period)}/kvittenser`,
undefined,
{ baseUrl: getHanteraBaseUrl() },
)
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = (await response.json()) as SkatteverketAGIKvittenserResponse
return { ok: true, status: response.status, data }
}
/**
* POST /arbetsgivare/{x}/redovisningsperioder/{y}/las (hantera API).
* Locks the period for changes: typically called automatically by
* skapaGranskningsunderlag with lasPeriod=true.
*/
export async function agiLasPeriod(
supabase: SupabaseClient,
userId: string,
arbetsgivare: string,
period: string,
): Promise<Result<unknown>> {
const response = await skvRequest(
supabase,
userId,
'POST',
`${periodPath(arbetsgivare, period)}/las`,
undefined,
{ baseUrl: getHanteraBaseUrl() },
)
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = await response.json().catch(() => ({}))
return { ok: true, status: response.status, data }
}
/** POST /arbetsgivare/{x}/redovisningsperioder/{y}/lasUpp (hantera API). */
export async function agiLasUppPeriod(
supabase: SupabaseClient,
userId: string,
arbetsgivare: string,
period: string,
): Promise<Result<unknown>> {
const response = await skvRequest(
supabase,
userId,
'POST',
`${periodPath(arbetsgivare, period)}/lasUpp`,
undefined,
{ baseUrl: getHanteraBaseUrl() },
)
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = await response.json().catch(() => ({}))
return { ok: true, status: response.status, data }
}
/**
* POST /underlag/huvuduppgift/kontrollera: pre-flight validation of a single
* HU as JSON without saving anything. Returns the kontrollsvar (OK / INFO /
* ARENDE / STOPP / AVVISANDE) and a list of any fel that fired.
*
* Use this to surface validation errors per HU to the user before they
* generate and submit a full XML underlag. The JSON property names follow
* the v1.7 spec §7: see lib/salary/agi/huvuduppgift-json.ts for the typed
* builder.
*/
export async function agiKontrolleraHU(
supabase: SupabaseClient,
userId: string,
hu: Record<string, unknown>,
): Promise<Result<SkatteverketAGIKontrollsvar>> {
const response = await skvRequest(
supabase,
userId,
'POST',
'/underlag/huvuduppgift/kontrollera',
hu,
{ baseUrl: getInlamningBaseUrl() },
)
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = (await response.json()) as SkatteverketAGIKontrollsvar
return { ok: true, status: response.status, data }
}
/**
* POST /underlag/individuppgift/kontrollera: pre-flight validation of a
* single IU as JSON without saving anything. JSON property names follow
* the v1.7 spec §8: see lib/salary/agi/individuppgift-json.ts for the
* typed builder.
*/
export async function agiKontrolleraIU(
supabase: SupabaseClient,
userId: string,
iu: Record<string, unknown>,
): Promise<Result<SkatteverketAGIKontrollsvar>> {
const response = await skvRequest(
supabase,
userId,
'POST',
'/underlag/individuppgift/kontrollera',
iu,
{ baseUrl: getInlamningBaseUrl() },
)
if (!response.ok) {
const { error, body } = await readErrorBody(response)
return { ok: false, status: response.status, error, body }
}
const data = (await response.json()) as SkatteverketAGIKontrollsvar
return { ok: true, status: response.status, data }
}