fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
+146
View File
@@ -0,0 +1,146 @@
/**
* Swedish translation of CONNECT_CLAUDE_MD (lib/docs/content/connect-claude.ts).
*
* The docs site has no locale routing, so the two languages live at two URLs
* and cross-link to each other. Keep them in sync: an edit to one is only half
* an edit.
*/
export const ANSLUT_CLAUDE_MD = `# Anslut Claude
> Prata med din bokföring. Koppla Accounted till Claude (claude.ai, Claude Desktop eller Claude Code) och ställ frågor, kontera transaktioner och förbered momsdeklarationen i vanligt språk. Varje skrivning stannar för ditt godkännande först.
_This page in English: [Connect with Claude](/docs/api/connect-claude)._
Accounted har en [MCP](https://modelcontextprotocol.io)-server som exponerar hela bokföringsmotorn (150+ verktyg) för vilken MCP-klient som helst. Adressen är:
\`\`\`
https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted
\`\`\`
Det finns tre vägar in, beroende på vilken klient du använder. Alla tre når samma verktyg och samma godkännandemodell: läsverktyg svarar direkt, medan skrivverktyg (kontera, markera betald, skapa verifikat, bokslut) **lägger upp en pending operation** som du bekräftar i chatten eller i webbgränssnittet under **/pending** innan något bokförs.
## Väg A: claude.ai eller Claude Desktop (ett klick)
**[→ Anslut Accounted till Claude](https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=Accounted&connectorUrl=https%3A%2F%2Fapp.accounted.se%2Fapi%2Fextensions%2Fext%2Fmcp-server%2Fmcp%3Ftool_namespace%3Daccounted%26client%3Dclaude-connector%26auth%3Drequired)**
Länken öppnar claude.ai med namn och adress ifyllda. Du granskar värdena och godkänner; länken fyller bara i formuläret och ger ingenting i sig. Ingen API-nyckel att hålla reda på.
**Du behöver inget Accounted-konto ännu.** Inloggningen öppnas direkt när du lägger till anslutningen, och där skapar du som ny kontot på plats (BankID eller e-post + 2FA).
**Alla behörigheter förvalda, varje skrivning stannar ändå.** Godkännandesidan ger hela behörighetslistan med ett klick. Fäll ut **Behörigheter** och välj **Endast läs** för en läsande anslutning (lista fakturor, läsa rapporter, räkna moms): så kan en granskare ansluta läsande medan du själv har en anslutning med skrivrättigheter för det dagliga arbetet. Oavsett behörigheter lägger skrivverktygen (skapa faktura, kontera, bokföra verifikat, köra bokslut) bara upp en pending operation som du bekräftar innan något bokförs, och åtkomsten går att återkalla under Inställningar → API & MCP.
#### Vad som händer efter klicket
Resten av inställningarna görs på Claudes sida, i den här ordningen:
1. **Connector-dialogen.** claude.ai öppnar **Add custom connector** med namn och adress ifyllda. Kontrollera adressen och gå vidare: dialogen känner av att servern kräver inloggning (**Always required**) och att Claude kan registrera sig själv automatiskt. Behåll de valen och klicka **Add**. Claude Desktop visar samma dialog under Inställningar → Connectors.
2. **Inloggningen öppnas.** claude.ai ber dig ansluta och öppnar Accounteds inloggning (BankID eller e-post + 2FA) följd av godkännandesidan. Den visar bolaget som just nu är aktivt i appen (byt bolag i appen först om du har flera) med alla behörigheter förvalda; fäll ut **Behörigheter** och välj **Endast läs** för en läsande anslutning. Godkänn, så visas anslutningen som ansluten med Accounteds verktyg listade.
3. **Ställ din första fråga.** Till exempel *"Vilket bolag är jag ansluten till?"*. Härifrån går varje fråga mot det bolaget, och skrivningar stannar under **/pending** tills du bekräftar.
Inloggad, men Claude säger fortfarande att servern inte går att nå? Fråga igen i samma chatt först. Hjälper inte det: öppna Inställningar → Connectors, ta bort anslutningen och lägg till den igen via länken ovan, med autentisering kvar på **Always required**.
#### Lägga till manuellt i stället
I **claude.ai** (Inställningar → Connectors) eller **Claude Desktop** (Inställningar → Connectors → Add custom connector), välj **Add custom connector** och klistra in:
\`\`\`
https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted&client=claude-connector&auth=required
\`\`\`
Behåll alla tre parametrarna. \`tool_namespace=accounted\` väljer verktygsnamnen som guiden utgår från. \`auth=required\` gör att dialogen känner av inloggningen (**Always required**): utan den accepterar servern en anonym handskakning, dialogen föreslår **None**, och en anslutning som läggs till med det förvalet öppnar aldrig inloggningen. Lägger du ändå till adressen utan parametern, välj **Required when the server asks** själv. \`client=claude-connector\` är bara statistik.
## Väg B: Claude Code (plugin)
Bäst i terminalen. Pluginet installerar både anslutningen och sju färdiga arbetsflöden som följer den svenska bokföringsrytmen.
\`\`\`text
/plugin marketplace add erp-mafia/accounted
/plugin install accounted@accounted
\`\`\`
Kör sedan \`/mcp\` och logga in med Accounted (samma OAuth-ruta som i väg A). Börja med \`/accounted:start\`.
| Kommando | Vad det gör |
|---|---|
| \`/accounted:start\` | Ansluter, orienterar och visar vad som behöver göras |
| \`/accounted:bookkeep\` | Betar av obokförda banktransaktioner och kvitton |
| \`/accounted:check\` | Läsande hälsokoll med prioriterad åtgärdslista |
| \`/accounted:month-close\` | Stänger månaden mot produktens checklista |
| \`/accounted:vat\` | Förbereder och stämmer av momsdeklarationen |
| \`/accounted:payroll\` | Månadens lönekörning och underlag för AGI |
| \`/accounted:year-end\` | Bokslut, spärrat mot readiness-kontrollen |
Vill du bara ha anslutningen utan arbetsflödena kopplar \`claude mcp add\` in samma server i Claude Code:
\`\`\`bash
claude mcp add --transport http accounted \\
"https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted&client=claude-code"
\`\`\`
**Cursor** har inget pluginformat och läser inte \`claude mcp add\`. Lägg i stället till servern i \`~/.cursor/mcp.json\` (globalt) eller \`.cursor/mcp.json\` (per projekt):
\`\`\`json
{
"mcpServers": {
"accounted": {
"url": "https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted&client=cursor"
}
}
}
\`\`\`
## Väg C: \`npx accounted-mcp\` med API-nyckel
Bäst när du hellre använder en långlivad API-nyckel än OAuth-flödet, eller när du skriptar.
1. Skapa en API-nyckel i Accounted under **Inställningar → API & MCP**. Använd en \`gnubok_sk_test_*\`-nyckel mot sandlådan medan du utvärderar och byt till \`gnubok_sk_live_*\` för skarp data.
2. Lägg till bryggan i din \`claude_desktop_config.json\`:
\`\`\`json
{
"mcpServers": {
"accounted": {
"command": "npx",
"args": ["-y", "accounted-mcp"],
"env": {
"ACCOUNTED_API_KEY": "gnubok_sk_test_...",
"ACCOUNTED_CLIENT": "claude-desktop"
}
}
}
}
\`\`\`
Kör du Accounted i egen drift pekar du om bryggan med \`ACCOUNTED_URL\`.
3. Starta om Claude Desktop. Bryggan skickar vidare stdio-JSON-RPC till den hostade MCP-servern över HTTPS, och nyckeln bär de rättigheter du gav den när den skapades.
Nyckelns rättigheter styr exakt vilka verktyg som går att kalla: en nyckel utan skrivrättigheter kan läsa rapporter och reskontror men inte lägga upp en bokföring.
Nyckelvärdet börjar fortfarande med \`gnubok_sk_\`. Det är ett stabilt kreditformat, inte namnet på integrationen. Befintliga \`gnubok-mcp\`-konfigurationer fortsätter att fungera oförändrade.
## Testa med de här frågorna
Alla tre går mot den deterministiska sandlådan (använd en \`gnubok_sk_test_*\`-nyckel, eller gör sandlådebolaget aktivt i appen innan du loggar in från Claude). De går igenom hela läsvägen utan att bokföra något.
1. **"Visa mina okonterade banktransaktioner och föreslå konteringar."**
Claude kallar \`accounted_list_uncategorized_transactions\` och sedan \`accounted_suggest_categories\` och går igenom förslagen med dig. Godkänner du ett förslag läggs en \`accounted_categorize_transaction\` upp som pending operation. Ingenting bokförs förrän du bekräftar.
2. **"Vilka fakturor är förfallna?"**
Claude kallar \`accounted_get_ar_ledger\` (kundreskontra) och listar utestående kundfakturor med åldersfördelning.
3. **"Räkna fram momsen för det här kvartalet och säg om jag kan stänga."**
Claude kallar \`accounted_get_vat_report\` för momsdeklarationens rutor och sedan \`accounted_vat_close_check\` som letar efter stopp (okonterade rader, ej godkända leverantörsfakturor, saknade kvitton på utgifter över 4 000 kr, vilket är verktygets tröskel för väsentliga belopp; BFL kräver underlag för varje affärshändelse oavsett belopp) och rapporterar \`ready_to_close\`.
## Tiominuterstestet
En snabb genomgång som visar att anslutningen fungerar innan du släpper in den på skarp data. Kör stegen i ordning. Varje steg säger vad du gör och vad du ska se.
1. **Anslut.** Väg A med **Endast läs** valt på godkännandesidan, väg B, eller väg C med en \`gnubok_sk_test_*\`-nyckel. → Claude listar Accounteds verktyg (rubriker som *List Uncategorized Transactions* och *VAT Declaration (Momsdeklaration)*).
2. **Kontrollera bolaget.** Fråga *"Vilket bolag är jag ansluten till?"* → Claude namnger sandlådebolaget (till exempel **Sandlådan Konsult**).
3. **Kör fråga 1** (okonterade och konteringsförslag). → En lista med okonterade rader plus förslag. Ingen bokföring sker.
4. **Kör fråga 2** (förfallna fakturor). → Minst en förfallen kundfaktura med åldersfördelning.
5. **Kör fråga 3** (moms och kan jag stänga). → Momsdeklarationens rutor plus en **icke-tom lista med stopp** från \`accounted_vat_close_check\` (okonterade transaktioner, en ej godkänd leverantörsfaktura och en större utgift utan kvitto).
6. **Testa en skrivning.** Be Claude kontera en transaktion. → Claude lägger upp en pending operation och ber dig bekräfta. Bokföringen sker **inte** förrän du godkänner i chatten eller på **/pending**.
Stämmer varje steg är anslutningen rätt kopplad och godkännandemodellen på plats.
## Support
Fastnar du, eller ser ett stopp du inte förstår? Använd supportformuläret i appen under **/help**. Det går direkt till produktteamet med ditt bolag som kontext. Skriv med vilken klient du använder (claude.ai, Desktop eller Code), vilken väg du tog (A, B eller C) och verktygsnamnet från eventuellt felmeddelande.
`
+90
View File
@@ -0,0 +1,90 @@
import { API_V1_VERSION } from '@/lib/api/v1/version'
export const CHANGELOG_MD = `# Changelog
> Reverse-chronological release notes for the Accounted REST API. Versions follow Stripe's dated format (\`YYYY-MM-DD\`). The current version is **\`${API_V1_VERSION}\`**.
---
## ${API_V1_VERSION} *(current)*
The first stable release of the public REST API. Six phases of development covering the full agent-native surface: authentication + discovery, invoicing vertical, transactions vertical, bookkeeping engine + suppliers + compliance check, payroll + reports + import, webhooks.
### Authentication + discovery (Phase 1)
- API key auth via \`Authorization: Bearer gnubok_sk_<random>\` (live keys) / \`gnubok_sk_test_<random>\` (test keys). 100 RPM rate limit per key.
- \`gnubok_sk_test_*\` keys bound to deterministic sandbox companies.
- Scope-based authorisation per endpoint (\`invoices:read\`, \`payroll:write\`, \`webhooks:manage\`, ...).
- Discovery: \`GET /llms.txt\`, \`GET /api/v1/openapi.json\`, \`GET /.well-known/skills/index.json\`.
- Health: \`GET /api/v1/health\`.
- Response envelope: \`{ data, meta: { request_id, api_version, audit, next_cursor } }\`.
- \`X-Request-Id\` on every response; idempotency on every write.
### Invoices vertical (Phase 2)
- **Customers**: GET list + detail, POST create + bulk-create, PATCH, DELETE.
- **Invoices**: GET list + detail, POST create, PATCH, lifecycle verbs \`/mark-sent\`, \`/mark-paid\`, \`/credit\`, \`/send\`, \`/bulk-create\`. PDF download at \`/{id}/pdf\`.
- VIES validation runs on commit for EU-business customers with a VAT number.
- Mixed-rate invoices supported: per-item \`vat_rate\` overrides the header rate.
- ROT/RUT-avdrag flow and supplier-invoice fakturamodellen on the AP side.
### Transactions vertical (Phase 3)
- **Transactions**: cursor-paginated GET list + detail. Single-tx verbs \`/categorize\`, \`/uncategorize\`, \`/match-invoice\`, \`/match-supplier-invoice\`. Bulk \`/ingest\` (up to 500), \`/batch-categorize\` (up to 100).
- **Reconciliation**: \`POST /reconciliation/bank/run\`, \`GET /reconciliation/bank/status\`.
- **Reads**: \`GET /accounts\`, \`GET /fiscal-periods\`.
- All write surfaces honour strict-mode (commit fully or error with no side effects).
### Reconciliation, account-keyed (2026-08)
- **Accounts**: \`GET /reconciliation/accounts\` lists every account with an outside truth (bank accounts as \`bank:<cash_account_id>\`, the skattekonto as \`skattekonto\`) with status; \`GET .../accounts/{accountKey}\` is the bridge (outside balance, ledger, difference, unexplained, explanatory lines, counts, latest sign-off); \`GET .../accounts/{accountKey}/items\` the rows behind it, bucketed (proposed, unmatched_external, unmatched_ledger, matched, ignored, upcoming).
- **Links**: \`POST .../accounts/{accountKey}/links\` (pairs or \`use_proposals\`), \`DELETE .../links/{linkId}\`, \`POST .../items/{itemId}/ignore\`. Links never touch the ledger.
- **Sign-off**: \`POST .../accounts/{accountKey}/signoff\` ("avstämt t.o.m." a date; refused with an unexplained difference unless forced with a note), \`GET .../signoff\` history, \`POST .../signoff/{signoffId}/reopen\`.
- New scopes \`reconciliation:read\`, \`reconciliation:write\`, \`reconciliation:signoff\`. The legacy \`/reconciliation/bank/*\` endpoints and their \`transactions:*\` scopes are unchanged.
- **Webhooks**: new event types \`reconciliation.matched\`, \`reconciliation.unmatched\`, \`reconciliation.signed_off\`, \`reconciliation.reopened\`. Additive: existing subscriptions are unaffected and the API version date is unchanged.
### Reports, companies, Skatteverket, customers, transactions (2026-08, additive)
Backfilled 2026-08-26 from merged PRs. Every item is additive (new endpoints, optional fields, optional filters): the API version date stays \`${API_V1_VERSION}\`.
- **Custom date ranges on reports** (#1909, 2026-08-25): \`GET /reports/income-statement\` and \`GET /reports/balance-sheet\` accept optional \`from_date\` / \`to_date\` (\`YYYY-MM-DD\`, both inside the fiscal period named by \`period_id\`, \`from_date <= to_date\`); the balance sheet also takes \`as_of\` as an alias for \`to_date\`. Omit both for the whole period, as before. These routes now reject unknown query parameters with \`400 VALIDATION_ERROR\` (\`unknown_params\` + \`allowed_params\` in details) instead of silently returning a full-period report.
- **Report PDFs** (#1909): \`GET /reports/balance-sheet/pdf\` and \`GET /reports/income-statement/pdf\` return \`application/pdf\`, byte-equivalent to the dashboard export, with the same \`period_id\` and range parameters. Scope \`reports:read\`.
- **Company creation** (#1864, 2026-08-25): \`POST /api/v1/companies\` (scope \`companies:write\`) creates a company and sets it up in one call: owner membership, BAS chart of accounts for the company form, compliance settings, the first fiscal period and the automatic tax deadlines. A VAT-registered company must send \`moms_period\`. Not idempotent, and \`Idempotency-Key\` is not honoured on this company-less route: list \`GET /api/v1/companies\` before retrying.
- **Filed VAT declarations** (#1773, 2026-08-21): \`GET /skatteverket/vat-declarations?period_type=&year=&period=\` (scope \`compliance:read\`) reads one period's momsdeklaration as Skatteverket has it on file: \`submitted\` (SKV inlämnat) and \`decided\` (SKV beslutat), each \`null\` when nothing is on file. Live read, requires an active Skatteverket connection on the company.
- **Company settings write** (#1405, 2026-08-04): \`PATCH /companies/{companyId}/settings\` (scope \`companies:write\`, risk medium, dry-run supported) updates bank details (\`bank_name\`, \`clearing_number\`, \`account_number\`, \`bankgiro\`, \`plusgiro\`, \`swish\`, \`iban\`, \`bic\`), \`contact_person\`, \`email\`, \`phone\`, \`website\` and \`invoice_email_texts\`, with the same validation as the MCP tool.
- **Customer \`personal_number\`** (#1724 2026-08-20, #1788 2026-08-21): \`personal_number\` on customer create, bulk-create, detail, PATCH and list. Accepted only for \`customer_type=individual\`, stored encrypted, always returned masked (\`********-1234\`); sending the masked form on PATCH means "leave unchanged", \`null\` clears it. A personnummer-shaped \`org_number\` on a business customer type is refused (\`400 CUSTOMER_ORG_NUMBER_IS_PERSONAL\`); on an individual it is moved into \`personal_number\` and \`org_number\` is cleared, or refused with \`400 CUSTOMER_PERSONAL_NUMBER_CONFLICT\` when it differs from a \`personal_number\` in the same body.
- **Ignore a transaction** (#1661, 2026-08-29): \`POST /transactions/{id}/ignore\` (scope \`transactions:write\`, risk low, idempotent, dry-run supported) marks an unbooked bank transaction as ignored without writing a verifikat, so it is allowed in a locked or closed period: the path for rows that are not business events (PSD2 ghost rows, duplicates, transfers that never executed). \`DELETE\` on the same path restores the row. A booked transaction (directly, via a payment allocation, or via a voucher link) is refused with \`409 TX_IGNORE_ALREADY_BOOKED\`. In the same change, \`/categorize\` and \`/batch-categorize\` answer \`is_business: false\` in a locked period with \`400 TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED\` (\`details.suggested_action: "ignore"\`) instead of a bare \`PERIOD_LOCKED\`: a private marking is a real eget uttag / insättning booking, so the lock still applies to it.
- **Transactions by bank account** (#1809, 2026-08-23): transaction list and detail carry \`cash_account_id\`; \`GET /transactions?cash_account_id=<uuid>\` filters to one bank account.
### Bookkeeping primitives + AP + compliance (Phase 4)
- **Suppliers + supplier-invoices** vertical (mirror of Phase 2 invoices on the AP side).
- **Journal entries** primitives: \`POST /journal-entries\` (draft+commit), \`/{id}/commit\`, \`/{id}/reverse\` (storno) and \`/{id}/correct\` (rättelse): both satisfy BFL 5 kap 5 § (storno is the canonical method of rättelse), \`/batch-create\`.
- **Voucher gap explanations**: \`POST /voucher-gap-explanations\` per BFNAR 2013:2.
- **Fiscal-periods ops**: \`/lock\`, \`/close\` and \`/opening-balances\` are synchronous and return 200 with the updated period; \`/year-end\` and \`/currency-revaluation\` are async and return 202 with operation_id (poll at \`GET /api/v1/operations/{id}\`).
- **Compliance check**: \`GET /compliance/check?type={year_end_readiness|voucher_gaps}\`: pre-flight findings before submission.
- **Documents**: \`POST /documents\` (multipart upload, magic-number-checked), \`GET /{id}/download\` (15-min signed URL), \`POST /{id}/link\` (attach to journal entry).
### Payroll + reports + import (Phase 5)
- **Employees**: full CRUD with personnummer masking on list/create per GDPR Art.5(1)(c). Soft-delete via \`is_active\`.
- **Salary runs**: CRUD + lifecycle verbs \`/calculate\`, \`/approve\`, \`/mark-paid\`, \`/book\`, \`/generate-agi\`. State machine: draft → review → approved → paid → booked. \`/generate-agi\` produces and persists the arbetsgivardeklaration XML: the response carries it as \`data.xml\` for the integrator to upload to Skatteverket Mina Sidor (or via the optional \`skatteverket\` extension). Accounted does NOT auto-submit; the AGI deadline: **the 12th of the following month for every reporting period EXCEPT January and August, where companies with annual turnover ≤ 40 MSEK get the 17th**: is the integrator's responsibility.
- **JSON reports** (13): trial-balance, balance-sheet, income-statement, general-ledger, journal-register, vat-declaration, monthly-breakdown, ar-ledger, supplier-ledger, continuity-check, salary-journal, avgifter-basis, vacation-liability.
- **Binary report**: \`GET /reports/sie-export\` (text/plain SIE4 file). Note: a SIE4 export alone does NOT satisfy BFL 7 kap archiving obligations: SIE captures account-level positions and verifikationer but lacks system documentation and behandlingshistorik. Treat SIE as a portability format (Fortnox/Visma/Bokio migration), not as a complete archive.
- **Async imports**: \`POST /imports/sie\` (multipart, 50 MB), \`POST /imports/bank\` (multipart, 10 MB, auto-format detection across 12 bank formats). Both async via \`operations\` substrate. **Post-SIE-import warning:** SIE files do NOT carry VAT codes or tax-rate-to-account mappings, AND they do NOT transfer behandlingshistorik (the source system's processing log required by BFNAR 2013:2 kap 8 §) or systemdokumentation. After importing from Fortnox / Visma / BL / SpeedLedger / Bokio you MUST manually reconfigure VAT codes (typically via \`/settings/tax-codes\`) before the first momsdeklaration; skipping this step is the most common source of incorrect VAT submissions in migrated bookkeeping. The behandlingshistorik gap must be preserved separately: under BFNAR 2013:2 kap 8 § the obligation attaches to the entire räkenskapsår, not from the import date forward. Best practice for a mid-year migration: export the source system's behandlingshistorik for the full fiscal year and archive it alongside the SIE file. Accounted starts a fresh behandlingshistorik from the import date forward; the pre-import portion of the year remains the source system's record.
### 2026-05-15: Webhooks (Phase 6 PR-1)
- **Subscriptions**: \`POST /webhooks\` (HMAC secret returned exactly once), GET list + detail, PATCH, DELETE. Per-event-type elevated scope check (\`salary_run.*\` and \`agi.generated\` require \`payroll:read\`).
- **Delivery substrate**: dispatched immediately after the event is enqueued, with a per-minute Vercel cron at \`/api/webhooks/dispatch/cron\` as the retry and sweep path. Due rows are claimed atomically via the \`claim_due_webhook_deliveries\` SQL function (\`FOR UPDATE SKIP LOCKED\`), with \`*.pg.test.ts\` coverage for the claim path and the webhook DB triggers. Exponential backoff \`1m / 5m / 30m / 2h / 12h / 24h / 48h\` (7 retries, ~87h total). HTTP 410 from receiver auto-disables the webhook.
- **Signature**: \`X-Gnubok-Signature: t=<unix>,v1=<hex-HMAC-SHA256>\`. Stripe-format. Sample receivers in [Node + Python](/docs/api/webhooks#verifying-signatures).
- **SSRF protection**: webhook_url must be HTTPS; resolved IPs in private/loopback/link-local/CGNAT/cloud-metadata ranges are rejected at create AND dispatch time. Dispatch pins the validated IP through a DNS-rebinding-safe \`node:https.request\` agent (\`lib/webhooks/pinned-fetch.ts\`); redirects are refused on every outbound POST (any 3xx is treated as a blocked redirect).
- **Audit + retention**: webhook delivery rows are *behandlingshistorik* per BFNAR 2013:2 kap 8 §: immutable once terminal so the audit trail of what an integration was notified of stays intact. Delivery rows are NOT räkenskapsinformation themselves; the 7-year statutory retention under BFL 7 kap 1 § applies only to the underlying verifikation / faktura / AGI XML in its own table, NOT to the delivery envelope. Accounted keeps accounting-event delivery rows for 7 years as a voluntary operational policy (the duration aligns with BFL 7 kap on the underlying records but is not itself a statutory obligation on delivery rows). Webhook DELETE preserves the delivery audit trail (\`ON DELETE SET NULL\` on \`webhook_id\`). Webhook lifecycle events (create / update / delete, plus dispatcher auto-disable) each write a V16 \`audit_log\` entry.
- **Verbs**: \`POST /webhooks/{id}/test\` enqueues a synthetic event; \`POST /webhook-deliveries/{id}/retry\` re-enqueues a dead/delivered delivery.
### Coming soon (Phase 6 PR-2 hardening)
- 90-day TTL cleanup cron for non-accounting webhook deliveries
- Per-route rate limits on \`:test\`, \`:retry\`, and webhook \`:create\`
- Populated \`previous_attributes\` for update-style webhook events
`
+141
View File
@@ -0,0 +1,141 @@
export const CONNECT_CLAUDE_MD = `# Connect with Claude
> Talk to your bookkeeping. Connect Accounted to Claude (claude.ai, Claude Desktop, or Claude Code) and ask questions, categorise transactions, and prepare a momsdeklaration in plain language: every write still stages for your approval first.
_Den här sidan på svenska: [Anslut Claude](/docs/api/anslut-claude)._
Accounted ships an [MCP](https://modelcontextprotocol.io) server that exposes the full bookkeeping engine (150+ tools) to any MCP client. The endpoint is:
\`\`\`
https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted
\`\`\`
There are three ways to connect, depending on your client. All three reach the same tools and the same approval model: read tools answer immediately, write tools (categorise, mark paid, create voucher, year-end) **stage a pending operation** that you confirm in chat or in the **/pending** web UI before anything is booked.
## Path A: claude.ai or Claude Desktop (one click)
**[→ Connect Accounted to Claude](https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=Accounted&connectorUrl=https%3A%2F%2Fapp.accounted.se%2Fapi%2Fextensions%2Fext%2Fmcp-server%2Fmcp%3Ftool_namespace%3Daccounted%26client%3Dclaude-connector%26auth%3Drequired)**
The link opens claude.ai with the connector name and URL already filled in. You review the values and confirm; the link only prefills the dialog, it grants nothing on its own. No API key to manage.
**You do not need an Accounted account yet.** Adding the connector opens the Accounted sign-in straight away, and a new user creates the account right there (BankID or e-mail + 2FA).
**All permissions pre-selected, every write still staged.** The consent page grants the full scope set with one click. Expand **Behörigheter** and choose **Endast läs** to connect read-only (list invoices, read reports, compute VAT): a reviewer can do that while you keep a write-enabled connection for daily work. Whatever the scopes, write tools (create invoice, categorise, book vouchers, run year-end) only stage a pending operation that you confirm before anything is booked, and the grant can be revoked under Settings → API & MCP.
#### What happens after you click
The rest of the setup happens on Claude's side, in this order:
1. **The connector dialog.** claude.ai opens **Add custom connector** with the name and URL filled in. Check the URL and continue: the dialog detects that the server requires a sign-in (**Always required**) and that Claude can register itself automatically. Keep those and click **Add**. Claude Desktop shows the same dialog under Settings → Connectors.
2. **The sign-in opens.** claude.ai asks you to connect and opens the Accounted sign-in (BankID or e-mail + 2FA), followed by the consent page. It shows the company that is currently active in the app (switch company in the app first if you have several) with every permission pre-selected; expand **Behörigheter** and choose **Endast läs** for a read-only connection. Approve, and the connector shows as connected with the Accounted tools listed.
3. **Ask your first question.** For example *"Which company am I connected to?"*. From here every question runs against that company; writes stage at **/pending** until you confirm.
Signed in, but Claude still says it cannot reach the server? Ask again in the same chat first. If that does not help, open Settings → Connectors, remove the connector, and add it again from the link above, with authentication left on **Always required**.
#### Adding it by hand instead
In **claude.ai** (Settings → Connectors) or **Claude Desktop** (Settings → Connectors → Add custom connector), choose **Add custom connector** and paste:
\`\`\`
https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted&client=claude-connector&auth=required
\`\`\`
Keep all three parameters. \`tool_namespace=accounted\` selects the tool names this guide uses. \`auth=required\` makes the dialog detect the sign-in (**Always required**): without it the server accepts an anonymous handshake, the dialog suggests **None**, and a connector added with that default never opens the sign-in. If you do add the bare URL, choose **Required when the server asks** by hand. \`client=claude-connector\` is telemetry-only.
## Path B: Claude Code (plugin)
Best in the terminal. The plugin installs the connection *and* seven workflow commands that follow the Swedish bookkeeping rhythm.
\`\`\`text
/plugin marketplace add erp-mafia/accounted
/plugin install accounted@accounted
\`\`\`
Then run \`/mcp\` and sign in with Accounted (the same OAuth consent screen as Path A). Start with \`/accounted:start\`.
| Command | What it does |
|---|---|
| \`/accounted:start\` | Connect, orient, and surface what needs attention |
| \`/accounted:bookkeep\` | Clear unbooked bank transactions and receipts |
| \`/accounted:check\` | Read-only health check with a prioritized fix list |
| \`/accounted:month-close\` | Close the month against the product's checklist |
| \`/accounted:vat\` | Prepare and reconcile the momsdeklaration |
| \`/accounted:payroll\` | Monthly salary run and AGI underlag |
| \`/accounted:year-end\` | Bokslut, readiness-gated |
Prefer plain MCP without the workflow commands? \`claude mcp add\` wires the same connection into Claude Code:
\`\`\`bash
claude mcp add --transport http accounted \\
"https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted&client=claude-code"
\`\`\`
**Cursor** has no plugin format and does not read \`claude mcp add\`. Add the server to \`~/.cursor/mcp.json\` (global) or \`.cursor/mcp.json\` (per project) instead:
\`\`\`json
{
"mcpServers": {
"accounted": {
"url": "https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted&client=cursor"
}
}
}
\`\`\`
## Path C: \`npx accounted-mcp\` with an API key (stdio bridge)
Best for Claude Desktop on a machine where you'd rather use a long-lived API key than the OAuth flow, or for scripting.
1. Mint an API key in the Accounted dashboard under **Settings → API & MCP** (\`/settings/api\`). Use a \`gnubok_sk_test_*\` key against the sandbox while you evaluate; switch to \`gnubok_sk_live_*\` for real data.
2. Add the stdio bridge to your \`claude_desktop_config.json\`:
\`\`\`json
{
"mcpServers": {
"accounted": {
"command": "npx",
"args": ["-y", "accounted-mcp"],
"env": {
"ACCOUNTED_API_KEY": "gnubok_sk_test_...",
"ACCOUNTED_CLIENT": "claude-desktop"
}
}
}
}
\`\`\`
Running Accounted yourself? Point the bridge at your own host with \`ACCOUNTED_URL\`.
3. Restart Claude Desktop. The bridge proxies stdio JSON-RPC to the hosted MCP endpoint over HTTPS; the key carries the scopes you granted it at mint time.
The key's scopes gate exactly which tools are callable: a key without write scopes can read reports and ledgers but cannot stage a booking.
The API-key value still begins with \`gnubok_sk_\`. That is a stable credential
format, not the MCP integration name. Existing \`gnubok-mcp\` configurations
continue to work without changes.
## Try these prompts
All three run against the deterministic sandbox seed (use a \`gnubok_sk_test_*\` key, or make the sandbox company the active company in the app before you sign in from Claude). They exercise the read path end-to-end without booking anything.
1. **"Show my uncategorized bank transactions and suggest categories."**
Claude calls \`accounted_list_uncategorized_transactions\` then \`accounted_suggest_categories\` and walks you through the proposals. Approving one stages an \`accounted_categorize_transaction\` pending operation: nothing is booked until you confirm.
2. **"Which invoices are overdue?"**
Claude calls \`accounted_get_ar_ledger\` (kundreskontra) and lists outstanding customer invoices with aging.
3. **"Compute my VAT report for this quarter and tell me if I can close it."**
Claude calls \`accounted_get_vat_report\` for the momsdeklaration rutor, then \`accounted_vat_close_check\` to scan for blockers (uncategorised rows, unapproved supplier invoices, missing receipts on expenses ≥ 4 000 kr: the tool's high-value heuristic; BFL requires underlag for every affärshändelse regardless of amount) and reports \`ready_to_close\`.
## 10-minute reviewer test
A quick end-to-end pass to confirm the connection works before you trust it with real data. Run the steps in order; each lists what you do and what you should see.
1. **Connect.** Use Path A (choose **Endast läs** on the consent page), Path B, or Path C with a \`gnubok_sk_test_*\` key. → Claude lists the Accounted tools (titles like *List Uncategorized Transactions*, *VAT Declaration (Momsdeklaration)*).
2. **Confirm the company.** Ask *"Which company am I connected to?"* → Claude names the sandbox company (e.g. **Sandlådan Konsult**).
3. **Run prompt 1** (*uncategorized + suggest categories*). → A list of uncategorised rows plus category suggestions; no booking happens.
4. **Run prompt 2** (*overdue invoices*). → At least one overdue customer invoice with aging.
5. **Run prompt 3** (*VAT report + can I close*). → Momsdeklaration rutor returned; \`accounted_vat_close_check\` reports a **non-empty blocker list** (uncategorised transactions, an unapproved leverantörsfaktura, and a high-value business expense without a receipt).
6. **Stage a write.** Ask Claude to categorise one transaction. → Claude stages a pending operation and asks you to confirm: the booking does **not** post until you approve in chat or at **/pending**.
If every step matches, the connector is wired correctly and the approval model is enforced.
## Support
Stuck connecting, or seeing an unexpected blocker? Use the in-app support form at **/help**: it routes straight to the product team with your company context attached. Include the client (claude.ai / Desktop / Code), the path you used (A, B, or C), and the tool name from any error message.
`
@@ -0,0 +1,154 @@
export const COOKBOOK_VAT_DECLARATION_MD = `# Cookbook: compute and review a VAT declaration
> Compute the Swedish momsdeklaration rutor 05-62 from your posted general-ledger entries and prepare the numbers for manual submission to Skatteverket.
This is the operational companion to the [Reports reference](/docs/api/reference/reports). v1 does NOT submit the declaration to Skatteverket directly: that path exists via the BankID-gated Skatteverket extension, not the public REST API. v1 produces the numbers and the receipt-quality JSON for manual submission via Skatteverket Mina Sidor.
## What you'll need
- A test API key with \`reports:read\` scope.
- All transactions for the period categorised and posted (see [ingest-bank-transactions cookbook](/docs/api/cookbook/ingest-bank-transactions)).
- The company's \`moms_redovisning\` cycle configured: monthly (kvartalsvis is supported for small companies with omsättning ≤ 1M SEK; the API doesn't dictate cadence, your bookkeeping does).
## 1. Compute the declaration
\`GET /reports/vat-declaration\` returns all the rutor plus supporting counts and a per-source breakdown. The period is selected with three **required** params — \`period_type\` (monthly|quarterly|yearly), \`year\`, and \`period\` (monthly 1-12, quarterly 1-4, yearly 1) — plus an optional \`accounting_method\` (accrual|cash, default accrual):
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/reports/vat-declaration?period_type=monthly&year=2026&period=4" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
Response (abbreviated):
\`\`\`json
{
"data": {
"period": { "type": "monthly", "year": 2026, "period": 4, "start": "2026-04-01", "end": "2026-04-30" },
"rutor": {
"ruta05": 133300.00,
"ruta06": 0.00,
"ruta10": 31075.00,
"ruta11": 720.00,
"ruta12": 180.00,
"ruta20": 0.00,
"ruta21": 20800.00,
"ruta22": 0.00,
"ruta23": 0.00,
"ruta24": 0.00,
"ruta30": 5200.00,
"ruta31": 0.00,
"ruta32": 0.00,
"ruta39": 3450.00,
"ruta40": 0.00,
"ruta48": 17547.00,
"ruta50": 0.00,
"ruta60": 0.00,
"ruta61": 0.00,
"ruta62": 0.00,
"ruta49": 19628.00
},
"invoiceCount": 42,
"transactionCount": 15,
"breakdown": {
"invoices": {
"ruta05": 133300.00, "ruta06": 0.00, "ruta07": 0.00,
"ruta10": 31075.00, "ruta11": 720.00, "ruta12": 180.00,
"ruta39": 3450.00, "ruta40": 0.00,
"base25": 124300.00, "base12": 6000.00, "base6": 3000.00
},
"transactions": { "ruta48": 17547.00 },
"receipts": { "ruta48": 0.00 },
"reverseCharge": {
"ruta20": 0.00, "ruta21": 20800.00, "ruta22": 0.00, "ruta23": 0.00, "ruta24": 0.00,
"ruta30": 5200.00, "ruta31": 0.00, "ruta32": 0.00
}
}
},
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
Ruta 49 = (utgående moms 10+11+12 + omvänd skattskyldighet 30+31+32 + utgående moms vid import 60+61+62) − ingående moms (ruta 48). Positive → moms att betala. Negative → moms att återfå.
## 2. Trace the numbers back to the ledger
The declaration is a **pure projection of the general ledger**: every ruta is the aggregated balance of its BAS accounts over the period. There is no separate reconciliation object in the response — the rutor *are* the ledger balances. The account → ruta mapping (SKV 4700) is:
- \`2611\`: Utgående moms 25% → ruta 10
- \`2614\`: Utgående moms vid omvänd skattskyldighet → ruta 30
- \`2615\`: Utgående moms vid import → ruta 60
- \`2621\`: Utgående moms 12% → ruta 11
- \`2631\`: Utgående moms 6% → ruta 12
- \`2641\`: Ingående moms → ruta 48
- \`2645\`: Ingående moms på utländska förvärv → ruta 48
To sanity-check the figures, use the supporting fields the response already returns:
- \`invoiceCount\` / \`transactionCount\`: how many posted entries fed the period.
- \`breakdown.invoices\`: the sales-side rutor (05/06/07/10/11/12/39/40) plus per-rate bases (\`base25\`/\`base12\`/\`base6\`).
- \`breakdown.transactions.ruta48\` / \`breakdown.receipts.ruta48\`: where the input VAT in ruta 48 came from (\`breakdown.transactions.ruta48\` mirrors the full \`rutor.ruta48\`).
- \`breakdown.reverseCharge\`: the reverse-charge purchase bases (ruta 20-24) and the self-assessed output VAT (ruta 30-32).
For a byte-level tie-out against raw account balances, pull the [general ledger report](/docs/api/reference/reports) filtered to the 26xx accounts and compare each account against the mapping above.
## 3. The 2026-04-01 livsmedel rate change
**Important compliance moment in April 2026.** The VAT rate on livsmedel (groceries) drops from 12% → 6% effective 2026-04-01 (Prop. 2025/26:55). The decisive date under ML (2023:200) is the *tidpunkt för skattskyldighetens inträde*, whose timing rules live in **7 kap. 3–13 §§**. The general rule for goods is the **supply date** (delivery), not the invoice date — **but** a *förskott* (advance payment) received before delivery triggers the VAT point, and pins the rate, at the time of that payment for the amount paid. So a food förskott paid in March for an April delivery is taxed at 12%, even though delivery is after the cutover. Drive the treatment off the taxable event (delivery, or earlier advance payment), not the delivery date alone.
- **Choose the VAT treatment from the supply date, and record \`delivery_date\` when it differs from \`invoice_date\`.** You set the rate per line via \`vat_treatment\`: \`reduced_6\` books to \`2631\` (6%) and \`reduced_12\` books to \`2621\` (12%). The engine does **not** infer the rate from \`delivery_date\` — it books to the account implied by the treatment you send — so for food supplied ≥ 2026-04-01 send \`reduced_6\`, and \`reduced_12\` for food supplied before the cutover, regardless of when the invoice was issued. For continuous or subscription food supplies (e.g. a weekly grocery box), the trigger point is the date when each individual delivery's skattskyldighet inträder: confirm against ML 1 kap 3 § rather than assuming the rule equals a single delivery date.
- The classic edge case: food delivered in March, invoiced in April. The supply date (March) governs, so the line must be booked at 12% (\`reduced_12\`) even though the invoice is dated April. Drive the treatment off the supply date — not the invoice date — and record \`delivery_date\` on the invoice for the audit trail. **Do this for every food-line item in March-April 2026 invoices**: the cost of explicit data is zero; the cost of a mis-booked verifikation is a manual rectification + a momsdeklaration adjustment.
- If you omit \`delivery_date\`, the invoice carries no explicit supply date and you are implicitly treating the invoice date as the supply date — fine for **one-off** service supplies where delivery and invoice coincide. Long-running service contracts (subscriptions, ongoing maintenance) have per-delprestation skattskyldighet under ML 1 kap 3 § and need an explicit \`delivery_date\` per billing cycle. Goods that straddle the cutover always need an explicit \`delivery_date\`.
The VAT declaration for April 2026 onwards will show split balances on rutor 11/12: pre-2026-04-01 food sales remain on ruta 11 (12%), post-cutover food sales appear on ruta 12 (6%). The \`breakdown.invoices\` per-rate bases (\`base12\` / \`base6\`) let you see the split, so you can catch any post-cutover line still booked at 12% before you submit.
## 4. Pre-flight: voucher gaps
BFNAR 2013:2 kap 6-7 §§ requires every voucher gap to have a documented explanation. Skatteverket may ask why \`F-2026-0042\` exists when no \`F-2026-0041\` is on the books. Check before declaring:
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/compliance/check?type=voucher_gaps&fiscal_period_id=$FISCAL_PERIOD_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
The check takes the period's UUID as \`fiscal_period_id\` (not a \`YYYY-MM\` string); get it from \`GET /fiscal-periods\`. Supported \`type\` values are \`voucher_gaps\` and \`year_end_readiness\`. If gaps exist, file an explanation via \`POST /voucher-gap-explanations\` BEFORE submitting the declaration: gaps without explanations are a compliance audit finding.
## 5. Pre-flight: locked period
The declaration is computed from posted entries in the period. If the period is still open and you have draft entries that should be in this declaration, commit them before declaring. After declaring, lock the period:
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/fiscal-periods/$PERIOD_ID/lock" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
Locking is reversible until you close the period, but the unlock endpoint is not exposed in v1: reverse a lock from the dashboard. Closing the period is irreversible per BFL 5 kap 8 §; only close after the declaration is submitted AND any audit-period grace window has passed.
## 6. Manual submission to Skatteverket
v1 does not submit the declaration. The receipt-quality JSON above is what you transcribe into Skatteverket Mina Sidor (or feed into your own Skatteverket-integration tooling, gated by BankID: handled by the optional \`skatteverket\` extension, not the public REST API).
For audit-trail completeness, capture the submission confirmation number from Skatteverket. v1 does not expose a field for a Skatteverket submission reference on the fiscal period, so record it in your own system of record (or your integration's audit log) alongside the period it belongs to.
## EU and reverse-charge handling
Sales of services to other EU businesses (\`vat_treatment: 'reverse_charge'\`) book to account 3308 and appear on ruta 39, bypassing the output-moms accounts (no entry on 26xx). The customer accounts for moms in their own country. (Use \`export\` instead — account 3305, ruta 40 — for services sold outside the EU.)
Purchases of services from other EU businesses (supplier_invoice with \`vat_treatment: 'reverse_charge'\`) put the **purchase base** on ruta 21 (tjänster från EU). The engine books a calculated 25% reverse-charge output on account 2614 (→ ruta 30) AND an input-moms entry on 2645 (→ ruta 48): net zero impact on cash flow when full avdragsrätt applies, full traceability on the declaration. **For blandad verksamhet (mixed-activity companies with partial avdragsrätt per HFD 2023 ref. 45),** the deductible portion of the \`2645\` leg must be restricted at booking time (e.g. by splitting the non-deductible share onto account 2649, blandad verksamhet) — there is no company-level deduction-percent setting that does this for you; otherwise the full input-moms reaches ruta 48 and over-declares the deduction.
Imports from outside EU book through a customs-clearance flow — there is no \`import\` \`vat_treatment\` value; the customs (Tullverket) invoice is what posts the moms, not the supplier invoice itself. The beskattningsunderlag lands on ruta 50 and the calculated import output VAT on rutor 60/61/62 (25/12/6%). Coverage of this is in the [Supplier invoices reference](/docs/api/reference/supplier-invoices).
## Common pitfalls
- **Decimals vs hela kronor: truncate öre, do not round.** The API returns rutor as decimal numbers (öre preserved). Skatteverket Mina Sidor and SRU filings accept only hela kronor; the rule per SFL 22 kap 1 § is **truncation** (drop öre), NOT half-up rounding. Use \`Math.floor\` for positive amounts when transcribing. Truncate at the rendering / submission boundary, not in storage.
- **Don't compute mid-month.** The figures are only meaningful for a complete month; calling with \`period_type=monthly&year=2026&period=4\` mid-April returns the partial state. The endpoint doesn't refuse partial periods, so this is on the integrator.
- **Mixed-rate invoices.** A single invoice with both 25% and 12% items lands on both \`2611\` and \`2621\`. The declaration handles this correctly because the per-line VAT rate is preserved in the engine; integrations that flatten to a single header rate will mis-declare.
- **Reverse-charge invoices in the wrong ruta.** A B2B sale to an EU customer with a missing/unvalidated VAT number does NOT qualify for reverse charge: those go to ruta 05 with normal 25% moms. Validate the customer's VAT number against VIES before issuing the invoice — note that VAT-number validation is a dashboard feature and is **not** exposed as a public v1 endpoint, so do the VIES check in your own flow.
## Next steps
- **[Year-end closing](/docs/api/cookbook/year-end-closing)**: once all 12 monthly declarations are filed, close the fiscal year.
- **[Run payroll](/docs/api/cookbook/run-payroll-and-agi)**: moms and AGI are independent; both need to be filed monthly.
- **[Reports reference](/docs/api/reference/reports)**: every report, every parameter.
`
+109
View File
@@ -0,0 +1,109 @@
/**
* Cookbook recipe registry. All six recipes ship live as of Phase 6 PR-3:
* - quickstart: send your first invoice (high-leverage onboarding path)
* - webhooks: end-to-end webhook setup with sig verification + retry handling
* - ingest-bank-transactions: bank file → categorised + invoice-matched
* - file-vat-declaration: compute rutor 05-62, reconcile against GL,
* manual submission to Skatteverket (includes 2026-04-01 livsmedel
* 12% → 6% rate-change transition)
* - run-payroll-and-agi: draft → calculate → approve → mark-paid →
* book → generate-agi state machine
* - year-end-closing: IB/UB continuity per BFL 5 kap, year-end procedures,
* irreversible close per BFL 5 kap 8 §
*/
import { QUICKSTART_MD } from './quickstart'
import { COOKBOOK_WEBHOOKS_MD } from './webhooks'
import { COOKBOOK_INGEST_BANK_MD } from './ingest-bank-transactions'
import { COOKBOOK_VAT_DECLARATION_MD } from './file-vat-declaration'
import { COOKBOOK_PAYROLL_AGI_MD } from './run-payroll-and-agi'
import { COOKBOOK_YEAR_END_MD } from './year-end-closing'
interface CookbookEntry {
slug: string
title: string
/** Full markdown content, OR null if the recipe is a placeholder. */
markdown: string | null
/** Where the placeholder points the reader if markdown is null. */
referenceLink?: { href: string; label: string }
description: string
}
export const COOKBOOK: CookbookEntry[] = [
{
slug: 'quickstart',
title: 'Quickstart: send your first invoice',
markdown: QUICKSTART_MD,
description: 'Five minutes from a fresh sandbox to an emailed invoice.',
},
{
slug: 'send-first-invoice',
title: 'Send your first invoice',
markdown: QUICKSTART_MD, // alias of quickstart for now
description: 'Create a customer, draft an invoice, send it, mark it paid.',
},
{
slug: 'webhooks',
title: 'Set up webhooks and verify signatures',
markdown: COOKBOOK_WEBHOOKS_MD,
description: 'Subscribe to events, verify HMAC, handle retries idempotently.',
},
{
slug: 'set-up-webhooks-and-verify-signatures',
title: 'Set up webhooks and verify signatures',
markdown: COOKBOOK_WEBHOOKS_MD, // alias matching docs nav
description: 'Subscribe to events, verify HMAC, handle retries idempotently.',
},
{
slug: 'ingest-bank-transactions',
title: 'Ingest and categorise bank transactions',
markdown: COOKBOOK_INGEST_BANK_MD,
description: 'Push CSV/CAMT into the engine, get AI suggestions, commit, match payments.',
},
{
slug: 'file-vat-declaration',
title: 'Compute and review a VAT declaration',
markdown: COOKBOOK_VAT_DECLARATION_MD,
description: 'Compute momsdeklaration rutor 05-62 and reconcile against the GL before manual submission to Skatteverket. Includes the 2026-04-01 livsmedel 12% → 6% rate-change transition.',
},
{
slug: 'run-payroll-and-agi',
title: 'Run payroll and generate the AGI XML',
markdown: COOKBOOK_PAYROLL_AGI_MD,
description: 'Calculate, approve, mark paid, book, generate the AGI XML for manual submission to Skatteverket Mina Sidor.',
},
{
slug: 'year-end-closing',
title: 'Year-end closing',
markdown: COOKBOOK_YEAR_END_MD,
description: 'Lock periods, run year-end procedures, set opening balances. IB/UB continuity per BFL 5 kap.',
},
]
export function findRecipe(slug: string): CookbookEntry | undefined {
return COOKBOOK.find((c) => c.slug === slug)
}
export const COOKBOOK_SLUGS = COOKBOOK.map((c) => c.slug)
export function buildPlaceholderMd(entry: CookbookEntry): string {
const link = entry.referenceLink
return [
`# ${entry.title}`,
'',
`> ${entry.description}`,
'',
'## Coming soon',
'',
`This narrative cookbook recipe is in the queue alongside the Phase 6 PR-3 hardening work. The endpoints are live and documented: start from the [reference page](${link?.href ?? '/docs/api/reference'}) below and the [quickstart](/docs/api/cookbook/quickstart) for the auth + idempotency + dry-run patterns; the recipe will be a guided narrative on top.`,
'',
link
? `**Reference:** [${link.label}](${link.href})`
: '**Reference:** [API reference](/docs/api/reference)',
'',
'**Related cookbooks already shipped:**',
'',
'- [Quickstart: send your first invoice](/docs/api/cookbook/quickstart)',
'- [Set up webhooks and verify signatures](/docs/api/cookbook/webhooks)',
].join('\n')
}
@@ -0,0 +1,227 @@
export const COOKBOOK_INGEST_BANK_MD = `# Cookbook: ingest and categorise bank transactions
> Push a bank statement file into Accounted, get AI-assisted category suggestions, commit the categorisations, and match payments against open invoices. End-to-end transaction-to-booking pipeline.
This is the operational companion to the [Transactions reference](/docs/api/reference/transactions) and the [Imports reference](/docs/api/reference/imports). Use it for the first integration where transactions enter the system from a bank source.
## What you'll need
- A test API key with \`transactions:write\`, \`transactions:read\`, and \`operations:read\` scopes. (There is no \`imports:write\` scope: the bank import runs under \`transactions:write\`, and polling the operation needs \`operations:read\`.)
- A bank statement file in one of the supported formats: CSV (SEB / Swedbank / Handelsbanken / Nordea / Nordea Business / Länsförsäkringar / ICA Banken / Skandia / Lunar / Northmill / generic CSV auto-detected), CAMT.053 XML, or a generic account-statement CSV with at minimum date + amount + description columns.
- The settlement account for the bank: typically \`1930\` for an SEK business account (check via \`GET /accounts\`). \`/imports/bank\` resolves the settlement account automatically; \`settlement_account\` is an explicit parameter of \`POST /transactions/ingest\`, not of the file upload.
## 1. Upload the bank file
\`POST /imports/bank\` accepts multipart upload. Format detection is automatic; the detected format is reported in the polled operation result (\`result.format\`), not in the upload response. The endpoint kicks off an async operation: you'll poll for the result.
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/imports/bank" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-F "file=@statement-2026-04.csv"
\`\`\`
Response is a 202 with the operation handle:
\`\`\`json
{
"data": {
"operation_id": "3f2a9c8e-...",
"type": "import.bank",
"status": "queued",
"poll_url": "/api/v1/operations/3f2a9c8e-...",
"webhook_event": "operation.completed"
},
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
## 2. Poll until the import completes
Polling is currently the way to detect import completion. \`operation.completed\` is named in the response as the intended push signal but is not yet a deliverable webhook event, so poll for now; the categorisation events (\`transaction.categorized\` / \`transaction.reconciled\`) that fire later in this flow are subscribable today ([cookbook](/docs/api/cookbook/webhooks)). The operation lifecycle is \`queued → running → succeeded | failed | cancelled\`.
\`\`\`bash
curl "https://app.gnubok.se/api/v1/operations/$OPERATION_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
On \`succeeded\`:
\`\`\`json
{
"data": {
"operation_id": "3f2a9c8e-...",
"type": "import.bank",
"status": "succeeded",
"progress": { "current": 187, "total": 187, "phase": "complete" },
"result": {
"format": "seb",
"file_hash": "e3b0c44298fc...",
"transactions_imported": 165,
"transactions_duplicates": 22,
"transactions_reconciled": 0,
"transactions_auto_categorized": 0,
"transactions_errors": 0,
"date_from": "2026-04-01",
"date_to": "2026-04-30"
},
"started_at": "2026-05-01T08:00:00Z",
"completed_at": "2026-05-01T08:00:04Z"
}
}
\`\`\`
Note the dedup: each row gets a stable \`external_id\` (composed from date + amount + counterparty) as the primary dedup key, and a secondary content match on \`(date, amount, description)\` against already-booked rows also skips duplicates. Re-uploading the same file is safe.
## 3. List uncategorised transactions
After ingest the rows are in \`transactions\` but unbooked (\`journal_entry_id: null\`, \`category: null\`). The list \`status\` filter takes \`booked\` | \`unbooked\` (\`unbooked\` filters on \`journal_entry_id IS NULL\`), and date filtering uses \`date_from\` / \`date_to\` (there is no \`period\` param). List them:
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/transactions?status=unbooked&date_from=2026-04-01&date_to=2026-04-30&limit=50" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
Response (cursor-paginated, newest-imported first — ordered by \`created_at\` DESC):
\`\`\`json
{
"data": [
{
"id": "tx_...",
"date": "2026-04-03",
"description": "SEB CARD - SJ 25-...",
"amount": -487.00,
"currency": "SEK",
"reference": null,
"merchant_name": "SJ",
"journal_entry_id": null,
"invoice_id": null,
"supplier_invoice_id": null,
"is_business": null,
"category": null,
"import_source": "bank_file",
"created_at": "2026-05-01T08:00:04Z"
},
...
],
"meta": { "request_id": "req_...", "next_cursor": "eyJ0cyI6Ij..." }
}
\`\`\`
## 4. Decide the category
There is no category-suggestion endpoint in the v1 REST API. Ranked suggestions (from the description, counterparty history, and your booking-template library) are surfaced by the dashboard and by the MCP tool \`accounted_suggest_categories\`: not over REST.
In a REST integration you supply the category yourself: choose a \`category\`, or pass an explicit \`account_override\` / \`template_id\` / \`counterparty_template_id\`, based on your own mapping logic. When categorising interactively, use the dry-run in the next step to preview the resolved verifikation before you commit.
## 5. Commit the categorisation
\`POST /transactions/{id}/categorize\` books the transaction (creates the verifikation directly — it is not staged for approval). \`is_business\` is required. Then supply a mapping: a \`template_id\` or \`counterparty_template_id\` (these take precedence), or a \`category\` for the default mapping. \`account_override\` is an optional posting-account override that **combines with \`category\`** — it applies only when neither \`template_id\` nor \`counterparty_template_id\` is present (as in the example below). Dry-run first to preview the resolved mapping:
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/transactions/$TX_ID/categorize?dry_run=true" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{
"is_business": true,
"category": "expense_travel",
"account_override": "5800",
"vat_treatment": "standard_25"
}'
\`\`\`
The dry-run returns the resolved mapping (debit / credit accounts + VAT lines) under \`{ dry_run: true, preview }\` — not a full posted journal, and no voucher number is burned:
\`\`\`json
{
"data": {
"dry_run": true,
"preview": {
"category": "expense_travel",
"mapping": {
"debit_account": "5800",
"credit_account": "1930",
"vat_lines": [
{ "account_number": "2641", "debit_amount": 97.40, "credit_amount": 0, "description": "Ingående moms 25%" }
],
"all_lines_complete": false
},
"would_create_journal_entry": true,
"already_had_journal_entry": false
}
},
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
Drop \`?dry_run=true\` and reuse the same \`Idempotency-Key\` to commit. The commit response returns \`journal_entry_id\` (plus \`journal_entry_created\` and \`category\`); it does not include a voucher number or audit block — fetch the voucher via the journal entry if you need it.
## 6. Batch categorise
For a backlog, use \`POST /transactions/batch-categorize\` (up to 100 transactions per call, dry-runnable, partial-success on commit):
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/transactions/batch-categorize" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{
"items": [
{ "transaction_id": "tx_1", "categorization": { "is_business": true, "category": "expense_travel", "account_override": "5800", "vat_treatment": "standard_25" } },
{ "transaction_id": "tx_2", "categorization": { "is_business": true, "category": "income_services", "account_override": "3001", "vat_treatment": "standard_25" } },
...
]
}'
\`\`\`
Response shape: every item carries its own \`ok\` flag and \`transaction_id\`:
\`\`\`json
{
"data": {
"results": [
{ "ok": true, "request_index": 0, "transaction_id": "tx_1", "data": { "journal_entry_created": true, "journal_entry_id": "je_...", "category": "expense_travel" } },
{ "ok": false, "request_index": 1, "transaction_id": "tx_2", "error": { "code": "PERIOD_LOCKED", "message": "Period is locked or closed; cannot post journal entry." } }
],
"summary": { "total": 2, "succeeded": 1, "failed": 1 }
}
}
\`\`\`
## 7. Match a payment against an invoice
When a transaction is a customer payment, match it to the open invoice via \`POST /transactions/{id}/match-invoice\` instead of \`categorize\`. The engine posts the payment voucher (debit 1930, credit 1510) AND marks the invoice paid in a single transaction.
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/transactions/$TX_ID/match-invoice" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{ "invoice_id": "inv_..." }'
\`\`\`
There is no \`payment_date\` field: the payment date is taken from the transaction's own \`date\`. For supplier-invoice payments use \`POST /transactions/{id}/match-supplier-invoice\` — same shape, but the body field is \`supplier_invoice_id\` and the transaction must be negative (expense).
## Multicurrency
Bank statements that include non-SEK transactions are imported with the foreign amount preserved in \`amount\` + \`currency\`; the booked SEK value is stored in \`amount_sek\`. When you categorise, the engine looks up the Riksbanken FX rate for the transaction date and books the SEK equivalent on the GL side. The FX delta (rate at booking vs rate at month-end revaluation) is later picked up by the currency-revaluation job.
The ledger is SEK-denominated; foreign amounts are converted to SEK automatically from the cached daily Riksbanken snapshot. There is no public FX-rate endpoint — rates are applied by the engine at categorisation time. (For cross-currency invoice settlement where no rate is published for a date, \`match-invoice\` accepts a \`manual_exchange_rate\`.)
## Common pitfalls
- **Re-running the same file is safe; date-only overlap is also safe.** Dedup is primarily by a stable \`external_id\` (date + amount + counterparty); a secondary content match on \`(date, amount, description)\` against already-booked rows also skips, so partial overlap of two statements doesn't double-import.
- **Settlement account selection matters.** The wrong settlement account silently breaks bank reconciliation later. \`1930\` (företagskonto) is the SEK default; a foreign-currency bank account uses its own asset account (e.g. \`1932\` for USD). \`/imports/bank\` resolves the settlement account automatically — to set it explicitly, ingest via \`POST /transactions/ingest\` with \`settlement_account\`.
- **Cash-method companies and partial payments don't mix.** If \`company_settings.accounting_method = 'cash'\` and you try to match a partial payment, the response is \`VALIDATION_ERROR\` rather than booking accrual entries: cash-method cannot model the per-installment moms event correctly (bokslutsmetoden reports moms at payment, per installment). Either book the partial payment as a separate categorisation or switch to accrual.
- **Batch-categorize is partial-success by default.** If one item hits a locked period, the others still commit. The summary block tells you the totals; check per-item \`ok\` flags.
- **Private is a booking; ignore is not.** \`is_business: false\` books eget uttag / insättning, so in a locked or closed period it returns \`TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED\`. A row that is not a business event at all (a PSD2 ghost row, a duplicate from a reconnect, a transfer that never executed) should be ignored instead: \`POST /transactions/{id}/ignore\` writes no verifikat and is allowed in a locked period; \`DELETE\` on the same path restores the row. Real purchases and owner withdrawals still need the period unlocked.
## Next steps
- **[Set up webhooks](/docs/api/cookbook/webhooks)**: get notified of \`transaction.categorized\` events without polling.
- **[File a VAT declaration](/docs/api/cookbook/file-vat-declaration)**: compute the rutor 05-62 from your now-categorised transactions.
- **[Transactions reference](/docs/api/reference/transactions)**: every parameter, every filter.
- **[Imports reference](/docs/api/reference/imports)**: full bank-file format coverage.
`
+181
View File
@@ -0,0 +1,181 @@
export const QUICKSTART_MD = `# Quickstart: send your first invoice
> Five minutes from a fresh sandbox to an emailed invoice. Demonstrates the auth, dry-run, and idempotency patterns you'll use everywhere.
## What you'll need
- A **live** API key (\`gnubok_sk_*\`, no \`test_\` infix) from the Accounted dashboard at **/settings/api**. Run the whole walkthrough with this one key: the create→send→pay sequence chains on real IDs (the customer's \`id\`, then the invoice's \`id\`) that only committed writes return. A **test** key (\`gnubok_sk_test_*\`) is useful to validate request *shapes* first — it's bound to a deterministic sandbox company and the wrapper forces every write into dry-run — but because a forced dry-run never persists (\`id: null\`, no emails), it can't complete the stateful flow, and its sandbox \`companyId\` differs from your live one. So: **use one key throughout.** If you validate with a test key first, re-run step 1 with your live key before step 3 so \`COMPANY_ID\` matches the company you're actually writing to.
- \`curl\` or any HTTP client.
## 1. List the companies the key can access
This call confirms your key works and returns the \`companyId\` you'll use throughout. Run it with the **same key you'll use for the committing steps** so the \`companyId\` matches — a live key resolves to the real companies it can access; a test key resolves to its sandbox company.
\`\`\`bash
curl https://app.gnubok.se/api/v1/companies \\
-H "Authorization: Bearer gnubok_sk_..."
\`\`\`
Response (truncated):
\`\`\`json
{
"data": [{ "id": "00000000-0000-0000-0000-000000000001", "name": "Sandbox AB", "org_number": "556677-8899", ... }],
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
Save the \`id\` as \`COMPANY_ID\` for the next steps.
## 2. Create a customer (dry-run first)
Most writes support \`?dry_run=true\`: the response shows the would-be record without committing. (Bank/SIE imports are the exception: they run for real or not at all.) Use it in agent test loops to validate inputs before paying the side-effect cost.
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/customers?dry_run=true" \\
-H "Authorization: Bearer gnubok_sk_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{
"name": "Acme AB",
"customer_type": "swedish_business",
"email": "ap@acme.test",
"org_number": "556677-8899",
"default_payment_terms": 30
}'
\`\`\`
Response (\`X-Dry-Run: true\` header, no row written). The would-be record is nested under \`data.preview\`, with \`data.dry_run: true\` so agents can branch on it without reading headers:
\`\`\`json
{
"data": {
"dry_run": true,
"preview": {
"id": null,
"name": "Acme AB",
"customer_type": "swedish_business",
"vat_number_validated": false,
"default_payment_terms": 30,
"created_at": null,
...
}
},
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
With a **live** key, dropping \`?dry_run=true\` commits the row: the response drops the \`dry_run\`/\`preview\` wrapper and returns the record directly under \`data\` with a real \`id\` and \`created_at\`. Save that committed \`data.id\` as \`CUSTOMER_ID\` for the next step. With a **test** key the write is forced to dry-run either way, so you keep getting this preview (\`id\`/\`created_at\` stay \`null\`) — which is why the create→send→pay steps below need a live key to produce IDs to chain on.
## 3. Draft an invoice
Invoices are typed (B2B, EU-business, individual) and support mixed-rate VAT (per-item \`vat_rate\` overrides). The minimum body:
\`\`\`bash
INVOICE_IDEMP=$(uuidgen)
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/invoices" \\
-H "Authorization: Bearer gnubok_sk_..." \\
-H "Idempotency-Key: $INVOICE_IDEMP" \\
-H "Content-Type: application/json" \\
-d '{
"customer_id": "'$CUSTOMER_ID'",
"invoice_date": "2026-05-15",
"due_date": "2026-06-14",
"delivery_date": "2026-05-15",
"currency": "SEK",
"items": [
{ "description": "Konsultation, maj 2026", "quantity": 8, "unit": "tim", "unit_price": 1200, "vat_rate": 25 }
]
}'
\`\`\`
A fresh draft has \`invoice_number: null\`: the F-series löpnummer is allocated atomically on the first \`/send\`, not at create time (ML 17 kap 24§ p.2 requires an unbroken series covering only issued invoices, so abandoned drafts must not burn a number). The response carries the computed VAT lines and totals; there is no audit block, because the verifikation hasn't been posted yet (drafts are not yet räkenskapsinformation):
\`\`\`json
{
"data": {
"id": "...",
"invoice_number": null,
"status": "draft",
"subtotal": 9600.00,
"vat_amount": 2400.00,
"total": 12000.00,
"items": [...]
},
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
(With a test key this call returns the dry-run preview shape instead: \`data: { "dry_run": true, "preview": { ... } }\`. The committed shape above is what a live key returns.)
## 4. Send it
\`POST /invoices/{id}/send\` runs a sequential pipeline: preflight PDF render (validates rendering before a number is burned) → allocate the F-series number atomically → final PDF render → email the customer via Resend (PDF attached, copy to the company). Any hard failure up to and including the email rolls nothing forward. Once the email is delivered the pipeline hits a **point of no return**: the status flip to \`sent\`, the journal entry (accrual + real invoices), PDF archival as underlag, and the \`invoice.sent\` event are best-effort, and any of their failures surface as \`warnings\` on the response rather than unwinding the send. It is not a single atomic transaction.
\`\`\`bash
# Generate the key ONCE and reuse it on every retry of this same send, so a
# timeout-then-retry replays the original result instead of sending twice.
SEND_IDEMP=$(uuidgen)
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/invoices/$INVOICE_ID/send" \\
-H "Authorization: Bearer gnubok_sk_..." \\
-H "Idempotency-Key: $SEND_IDEMP"
\`\`\`
Response carries the allocated invoice number and the id of the posted journal entry (there is no \`meta.audit\` block on this endpoint: use \`data.journal_entry_id\` and \`data.invoice_number\` as the posting reference):
\`\`\`json
{
"data": {
"id": "...",
"invoice_number": "2026-0042",
"status": "sent",
"total": 12000.00,
"message_id": "re_abc123",
"sent_to": "ap@acme.test",
"cc": "billing@gnubok-user.test",
"journal_entry_id": "7b3a..."
},
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
If any post-email step degraded, \`data.warnings\` is present (e.g. \`JOURNAL_ENTRY_NOT_POSTED\`); the invoice is marked \`sent\` regardless.
## 5. Mark it paid
When the customer pays, mark the invoice paid. The engine generates the payment voucher (debit 1930 bank, credit 1510 AR) and links it to the invoice. There is no \`payment_amount\` field: the default books the full remaining amount (\`remaining_amount\`). For a partial payment, pass a custom \`lines\` array (at least two balanced rows).
\`\`\`bash
# One key per logical payment; reuse it across retries of this mark-paid.
PAY_IDEMP=$(uuidgen)
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/invoices/$INVOICE_ID/mark-paid" \\
-H "Authorization: Bearer gnubok_sk_..." \\
-H "Idempotency-Key: $PAY_IDEMP" \\
-H "Content-Type: application/json" \\
-d '{ "payment_date": "2026-05-22" }'
\`\`\`
## What just happened
This flow creates a customer, drafts a single-line invoice, posts the verifikation on \`/send\`, emails the PDF, and records the payment. That's **five committing calls** — list companies, create customer, create invoice, send, mark-paid — plus the optional \`?dry_run=true\` preview in step 2 if you run it. The engine handles BAS account selection, voucher numbering, period-lock checks, audit-trail entries, and PDF rendering. Run the committing calls with a live key; a test key can validate request shapes via dry-run first but never persists, so it can't chain the real IDs each step needs.
The rendered PDF that the customer received contains every field required by ML 17 kap 24 § (the Swedish faktura mandate): including \`beskattningsunderlag per skattesats\` (taxable amount per VAT rate; one line per distinct rate on multi-rate invoices), the supplier's organisationsnummer, sequential invoice number, per-line VAT rate, and the supply date. **Pass \`delivery_date\` explicitly** when goods or services are delivered on a different date than the invoice date: ML 17 kap 24 § field 7 requires the supply date and the API does NOT default it to \`invoice_date\`; a faktura with no supply date is non-compliant.
The "Godkänd för F-skatt" note is a **legal requirement** on every faktura issued by a Swedish momsregistrerad seller that holds F-skatt registration. The buyer uses this note to determine whether they must withhold preliminary tax (A-skatt): omitting it can shift liability onto the buyer and triggers a FATAL Peppol BIS 3.0 validation failure (SE-R-005) on B2G invoices. The requirement applies equally to PDF/paper and Peppol/e-invoice formats; B2G is just where the validation is automated. The PDF includes it automatically when \`company_settings.has_f_skatt\` is true. **The integrator is responsible for keeping \`has_f_skatt\` in sync with the company's live Skatteverket registration status.** Keep it in sync from the settings page in the dashboard (there is no v1 settings endpoint today): a flag that's false while the company is actually F-skatt-registered produces non-compliant invoices, not merely a missing optional note.
The summary fields in the JSON response (\`subtotal\`, \`vat_amount\`, \`total\`) are convenience aggregates for the integration; the binding faktura content is the PDF itself.
## Next steps
- **[Subscribe to invoice events](/docs/api/cookbook/webhooks)**: get notified when invoices are paid via webhooks instead of polling.
- **[Ingest bank transactions](/docs/api/cookbook/ingest-bank-transactions)**: push CAMT/CSV into the engine and auto-categorise.
- **[Run a VAT declaration](/docs/api/cookbook/file-vat-declaration)**: compute momsdeklaration rutor and submit to Skatteverket.
- **[Full Invoices reference](/docs/api/reference/invoices)**: every endpoint, all the optional fields.
## Common pitfalls
- **Use one idempotency key per logical action.** The key is treated as an opaque string (UUIDs are recommended, but any unique value works). Generate one per logical action and reuse it across retries of that same action: never on a fresh attempt. Reusing a key with a different request body is rejected with \`IDEMPOTENCY_KEY_REUSE\`.
- **Test keys never send or post.** \`gnubok_sk_test_*\` keys are simulation-only: every write is forced to dry-run, so \`/send\` never emails the customer, never allocates an F-series number, and never posts a voucher. On top of that the sandbox company they're bound to blocks outbound email outright (403 \`sandbox_blocked\`). Use a live key on a real company to actually deliver an invoice.
- **Period locks block writes.** If you try to invoice into a closed period (\`invoice_date\` falls inside a locked fiscal period), the response is \`PERIOD_LOCKED\` (400). Use \`GET /fiscal-periods\` to check before backdating.
- **VIES VAT validation runs on commit only.** It only fires when you create an \`eu_business\` customer with a \`vat_number\` (Swedish customers like the one above never trigger it). Dry-run skips the external VIES call; the real commit blocks on slow VIES responses (we time out after 10s, but that's still up to 10s added to the request). There is no v1 pre-validation endpoint today: rely on dry-run to check the rest of the payload first.
`
@@ -0,0 +1,221 @@
export const COOKBOOK_PAYROLL_AGI_MD = `# Cookbook: run payroll and generate the AGI XML
> Drive a Swedish salary run from draft to booked, then generate the arbetsgivardeklaration på individnivå (AGI) XML for manual submission to Skatteverket. Five-step lifecycle, every state transition idempotent and dry-runnable (generate-agi is idempotent but not dry-runnable).
This is the operational companion to the [Salary-runs reference](/docs/api/reference/salary-runs). The whole lifecycle is API-callable end-to-end: create the run, attach employees (\`POST /salary-runs/{id}/employees\`), add manual payslip lines if needed, calculate, approve, mark paid, book, generate AGI. Per-employee results are readable via \`GET /salary-runs/{id}/employees\` (list) and \`GET /salary-runs/{id}/employees/{employeeId}\` (payslip detail incl. line items and the step-by-step calculation breakdown); the rendered payslip PDF is at \`GET /salary-runs/{id}/payslips/{employeeId}/pdf\`.
## What you'll need
- A test API key with \`payroll:read\` AND \`payroll:write\` scopes. \`payroll:write\` is required for every state transition; \`payroll:read\` covers the read paths plus the elevated-scope gate on the webhook \`salary_run.*\` subscription.
- At least one employee on file with the payroll fields set (\`monthly_salary\` or \`hourly_rate\`, \`tax_table_number\`, \`tax_column\`, \`f_skatt_status\`). \`GET /employees\` masks personnummer to \`ÅÅÅÅMMDDXXXX\`; \`GET /employees/{id}\` returns the full value (deliberate drill-in, GDPR Art.5(1)(c)).
- An open fiscal period covering the salary date.
## 1. Create a salary run (draft)
\`POST /salary-runs\` opens an **empty** run in \`draft\` status: it takes only the period + payment metadata (\`period_year\`, \`period_month\`, \`payment_date\`, optional \`voucher_series\` and \`notes\`). Attach each employee with \`POST /salary-runs/{id}/employees\` (body \`{ "employee_id": "..." }\`, plus \`hours_worked\` for hourly staff) before you \`:calculate\`. The attach snapshots the employee's pay config onto the run and seeds the base salary line; one-off components (bonus, deduction, reimbursement) go through \`POST /salary-runs/{id}/employees/{employeeId}/lines\` while the run is still a draft. Line edits never recompute tax: always \`:calculate\` afterwards.
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/salary-runs" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{
"period_year": 2026,
"period_month": 5,
"payment_date": "2026-05-25",
"voucher_series": "L"
}'
\`\`\`
Response:
\`\`\`json
{
"data": {
"id": "run_...",
"status": "draft",
"period_year": 2026,
"period_month": 5,
"payment_date": "2026-05-25",
"voucher_series": "L",
"total_gross": 0,
"total_tax": 0,
"total_net": 0,
"total_avgifter": 0,
"total_employer_cost": 0
}
}
\`\`\`
Totals are 0 until you calculate.
## 2. Calculate (math + draft → review)
\`POST /salary-runs/{id}/calculate\` runs the full Swedish tax engine: skattetabell lookup per employee, sociala avgifter at the current rate (31.42% for 2026), age-adjusted reductions per Prop. 2025/26:66 (the youth-reduction band is **18-22 years old at the start of 2026**: i.e. employees **born 2003-2007** for the 2026 income year, NOT a blanket "under-25"; the elder reduction applies at **67+ from 2026**, not 66+), förmånsbeskattning, semesterlöneskuld, OB-tillägg, traktamente.
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/salary-runs/$SR_ID/calculate" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
Response transitions \`draft → review\`:
\`\`\`json
{
"data": {
"id": "run_...",
"status": "review",
"period_year": 2026,
"period_month": 5,
"total_gross": 80000.00,
"total_tax": 24300.00,
"total_net": 55700.00,
"total_avgifter": 25136.00,
"total_employer_cost": 105136.00,
"warnings": []
}
}
\`\`\`
The \`warnings\` array surfaces non-blocking issues (Skatteverket tax-table fallback, läkarintyg day-8 / Försäkringskassan day-15 transitions, F-skatt \`not_verified\` employees); the run still advances to \`review\`. Per-employee figures are not returned inline: read them from the run detail or the salary-journal report.
The \`review\` status is a soft hold: the math is done but no journal entries are posted yet. Treat this as the human-review step.
## 3. Approve (review → approved)
\`POST /salary-runs/{id}/approve\` validates and locks the run for payment. \`PATCH\` on a salary run is **draft-only** (\`SALARY_RUN_PATCH_NOT_DRAFT\`): once a run leaves \`draft\` it can no longer be edited, and there is no \`:unapprove\`. Correcting a booked run is done via the forthcoming \`:correct\` verb (storno-then-rebook).
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/salary-runs/$SR_ID/approve" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
Response shows \`status: 'approved'\` plus a \`warnings\` array. The endpoint validates every employee on the run and returns **all** problems at once (not just the first):
- Bank details present: \`clearing_number\` AND \`bank_account_number\` (required for the transfer)
- \`calculation_breakdown\` populated (proves \`:calculate\` has run)
Missing email is a **non-blocking warning** (lönebesked can't be sent automatically) and does not fail approval. Validation failures return \`SALARY_RUN_APPROVE_VALIDATION_FAILED\` with the full \`issues\` list (and any \`warnings\`) in \`details\`. A non-\`review\` run returns \`SALARY_RUN_APPROVE_NOT_REVIEW\`.
## 4. Mark paid (approved → paid)
After the bank transfer settles (or you mark it on the same day for cash-method shops), tell Accounted:
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/salary-runs/$SR_ID/mark-paid" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
This step records the payment event but does NOT post the journal entry yet: that's step 5. The split is deliberate: the \`mark-paid\` step gives integrators a hook to confirm the bank-side leg landed before locking the GL side. It is a **bodyless POST**: \`paid_at\` is stamped server-side to the current UTC timestamp (the API does not accept a body-supplied date, to keep the BFL audit trail clean).
## 5. Book (paid → booked)
\`POST /salary-runs/{id}/book\` is the engine-touching step. It posts **2-4 verifikationer** atomically — always the salary and avgifter entries, plus a semesterlöneskuld-accrual entry and/or a löneväxling-pension entry when those apply:
- Verifikation 1: Bruttolön: debit → 7210 / 7220 / 7240 (Löner tjänstemän / företagsledare / styrelsearvoden, by \`employment_type\`), credit → 2710 (Personalskatt, avdragen skatt) + 1930 (utbetalning)
- Verifikation 2: Arbetsgivaravgifter: debit → 7510 (Lagstadgade sociala avgifter, exact öre), credit → 2731 (Avräkning sociala avgifter: whole kronor, the amount Skatteverket computes from the declared underlag and draws) + 3740 (Öres- och kronutjämning: the remainder, when the exact cost differs)
- Verifikation 3 (if semesterlöneskuld): debit → 7290 (Förändring semesterlöneskuld) + 7519 (sociala avgifter på semester), credit → 2920 (Upplupna semesterlöner) + 2940 (Upplupna sociala avgifter)
- Verifikation 4 (if löneväxling): debit → 7410 (Pensionsförsäkringspremier) + 7533 (Särskild löneskatt på pensionskostnader), credit → 2740 (Skuld pensionsförsäkringar) + 2514 (Beräknad särskild löneskatt); pension = löneväxling × 1.058
The 2731 series is the **employer-contributions-payable** liability per BAS 2026: not to be confused with 2615 (utgående moms vid import, unrelated to payroll). The arbetsgivardeklaration cycle posts the payable on book day and clears it via 1930 when the bank transfer to Skatteverket settles.
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/salary-runs/$SR_ID/book" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
Response:
\`\`\`json
{
"data": {
"id": "run_...",
"status": "booked",
"booked_at": "2026-05-26T09:15:00Z",
"booked_by": "user_...",
"salary_entry_id": "je_salary...",
"avgifter_entry_id": "je_avg...",
"vacation_entry_id": "je_vac...",
"pension_entry_id": null,
"entry_ids": ["je_salary...", "je_avg...", "je_vac..."]
},
"meta": {
"request_id": "req_...",
"api_version": "2026-05-12",
"audit": {
"voucher_number": "L2026-0023",
"voucher_url": "/api/v1/companies/.../journal-entries/je_salary...",
"immutable_at": "2026-05-26T09:15:00Z"
}
}
}
\`\`\`
If \`book\` fails partway (e.g. period locked while waiting for the bank-side confirmation), the route is strict-mode v1: no partial commits. The state stays at \`paid\` and the response carries the \`PERIOD_LOCKED\` error code with the offending period.
## 6. Generate the AGI XML
\`POST /salary-runs/{id}/generate-agi\` produces the arbetsgivardeklaration på individnivå XML for the period. Skatteverket requires AGI monthly; the XML is embedded in the JSON response: no separate file endpoint.
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/salary-runs/$SR_ID/generate-agi" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
Response:
\`\`\`json
{
"data": {
"agi_declaration_id": "agi_...",
"period_year": 2026,
"period_month": 5,
"employee_count": 2,
"is_correction": false,
"totals": {
"totalTax": 24300.00,
"totalAvgifterBasis": 80000.00,
"totalAvgifterAmount": 25136.00,
"totalSjuklonekostnad": 0,
"avgifterByCategory": { "standard": { "basis": 80000.00, "amount": 25136.00 } }
},
"xml": "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><Skatteverket omrade=\\"Arbetsgivardeklaration\\">…</Skatteverket>",
"xml_filename": "AGI_5566778899_202605.xml"
}
}
\`\`\`
Save the XML to disk and upload it to **Skatteverket Mina Sidor → Tjänster → Arbetsgivardeklaration**. Mina Sidor accepts the file directly; no manual transcription needed. (Direct API submission requires BankID and goes through the \`skatteverket\` extension, not the public REST API.)
Generating the XML stamps \`agi_generated_at\` on the salary run and emits an \`agi.generated\` event. There is no public endpoint to store a Skatteverket confirmation number back on the run: track the submission reference in your own system.
## State machine summary
\`\`\`
draft ──calculate──► review ──approve──► approved ──mark-paid──► paid ──book──► booked ──generate-agi──► (AGI XML)
\`\`\`
Each transition is idempotent on \`Idempotency-Key\`. Retrying a transition that has already completed returns the same response with \`Idempotent-Replayed: true\`. Failed transitions don't advance the state: fix and retry.
## Förmånsbeskattning
When an employee has bilförmån / fri kost / friskvård, the förmånsvärde is configured on the employee's benefit records: it is **not** passed on the run-creation request (\`POST /salary-runs\` takes only period + payment metadata). When you \`:calculate\`, the engine adds the förmånsvärde to bruttolön for the avgifts-basis (2731) and produces a separate förmåner line on the AGI. \`bilförmån_värde\` follows Skatteverkets schablon for 2026; supply the figure directly: the API does not compute it from car make / model / year.
## Common pitfalls
- **\`PATCH\`/\`DELETE\` are draft-only.** Both require \`draft\` status (\`SALARY_RUN_PATCH_NOT_DRAFT\` / \`SALARY_RUN_DELETE_NOT_DRAFT\`). There is no revert-to-draft and no \`:unapprove\`; a booked run is corrected via the forthcoming \`:correct\` verb (storno-then-rebook), not by editing or deleting.
- **AGI period vs run period.** The AGI declaration covers \`(period_year, period_month)\`: the same period as the run, not the payment date. A run paid on 2026-06-02 for May still files as the May AGI.
- **F-skatt verification is the integrator's job.** The API trusts \`employee.f_skatt_status\` (\`a_skatt\` | \`f_skatt\` | \`fa_skatt\` | \`not_verified\`) to be in sync with the employee's live Skatteverket registration. A wrong status produces a non-compliant AGI; check the F-skattsedel before payroll runs. \`not_verified\` employees are surfaced as a non-blocking warning on \`:calculate\` (30% skatteavdrag and full avgifter are applied until verified).
- **Sociala avgifter age reduction.** Per Prop. 2025/26:66, employees who are **18-22 years old at the start of the 2026 income year (born 2003-2007)** AND employees who **have turned 67 at the start of the income year (1 January 2026)** get reduced satser. The "at the start of" boundary matters: a 66-year-old whose 67th birthday falls in February 2026 does NOT qualify for the elder reduction in 2026. The engine derives age from the employee's personnummer (the leading birthdate digits: there is no separate \`birthdate\` field) and applies the correct sats automatically: don't override unless you've consulted [Skatteverkets table](https://www.skatteverket.se/foretagochorganisationer/skatter/arbetsgivareochinkomstuppgifter/arbetsgivaravgifteroch_skatteavdrag.4.18e1b10334ebe8bc80003392.html). The old "under 26" rule from 2024 does NOT apply for 2026 and later.
- **Bruttolöneavdrag vs nettolöneavdrag order.** Bruttolöneavdrag reduces both lön och avgifter; nettolöneavdrag only affects the employee's payout. Pass either explicitly in the run; don't mix them.
## Next steps
- **[Set up webhooks](/docs/api/cookbook/webhooks)**: subscribe to \`salary_run.booked\` and \`agi.generated\` events to drive downstream payroll integrations.
- **[Year-end closing](/docs/api/cookbook/year-end-closing)**: payroll's annual cap is the kontrolluppgift season (january of the following year).
- **[Salary-runs reference](/docs/api/reference/salary-runs)**: every parameter, every error code.
`
+188
View File
@@ -0,0 +1,188 @@
export const COOKBOOK_WEBHOOKS_MD = `# Cookbook: set up webhooks and verify signatures end-to-end
> Subscribe a receiver to invoice events, verify HMAC signatures correctly, handle the at-least-once retry semantics, and build idempotency around the delivery id.
This is the operational companion to the [Webhooks concept page](/docs/api/webhooks): that page explains *what* webhooks are; this one walks through *how* to wire one up correctly the first time.
## What you'll need
- A test API key with \`webhooks:manage\` scope (and \`payroll:read\` if you intend to subscribe to payroll events).
- A receiver URL that Accounted can POST to. For local development use [smee.io](https://smee.io) or \`ngrok\`: Accounted refuses webhook URLs that resolve to private IPs (SSRF protection), so localhost won't work directly.
- HTTPS only: \`http://\` URLs are rejected at registration.
## 1. Register the webhook
The response includes the HMAC signing secret **exactly once**. Capture it immediately and store it on the receiver side as an environment variable.
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/webhooks" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{
"event_type": "invoice.paid",
"webhook_url": "https://my-receiver.example.com/gnubok",
"name": "CRM sync: invoice paid"
}'
\`\`\`
Response:
\`\`\`json
{
"data": {
"id": "a8f1e4c2-3b5d-4e6f-8a90-1b2c3d4e5f60",
"name": "CRM sync: invoice paid",
"event_type": "invoice.paid",
"webhook_url": "https://my-receiver.example.com/gnubok",
"active": true,
"api_version_pinned": "2026-05-12",
"secret": "whsec_b3a7c9e2...",
"created_at": "2026-05-15T12:00:00Z"
},
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
> ⚠️ The \`secret\` field is returned only on creation. Subsequent GETs never include it. If you lose it, mint a fresh one with \`POST /api/v1/companies/{companyId}/webhooks/{id}/rotate-secret\`: it re-issues the signing secret in place (returned exactly once, like creation) without deleting the webhook or its delivery history. Rotation invalidates the old secret immediately — there is no grace period — so stage the new value on the receiver first (or \`PATCH active=false\` to pause delivery while you swap), then re-deploy the receiver with the new value.
**Store the secret in a secrets manager** (AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault, Doppler, 1Password Connect, ...) rather than a plaintext \`.env\` file or a config commit. The secret is signing material: anyone who reads it can forge events that will pass your signature check. Treat it with the same care as a database password.
## 2. Implement signature verification
Use the [Node](https://app.gnubok.se/docs/api/webhooks#nodejs) or [Python](https://app.gnubok.se/docs/api/webhooks#python) sample on the concept page. The critical detail: capture the **raw request body** before any framework JSON-parses it. Re-serialising the body produces different bytes and the signature won't match.
For an Express handler, that means \`express.raw({ type: 'application/json' })\`: NOT the default \`express.json()\` middleware. For FastAPI / Flask use \`request.get_data()\`. For Cloudflare Workers use \`await request.text()\` BEFORE \`request.json()\`.
## 3. Send a test event
The \`:test\` verb enqueues a synthetic \`webhook.test\` delivery without driving real state. The dispatcher sends it on the next per-minute cron tick.
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/webhooks/$WEBHOOK_ID/test" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
Response:
\`\`\`json
{
"data": { "webhook_delivery_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "status": "pending" },
"meta": { "request_id": "req_...", "api_version": "2026-05-12" }
}
\`\`\`
Wait up to 60s, then check the receiver logs. The delivery should arrive with:
\`\`\`
POST /gnubok HTTP/1.1
Content-Type: application/json
X-Gnubok-Signature: t=1778846400,v1=2f5c...
X-Gnubok-Event: webhook.test
X-Gnubok-Delivery: f47ac10b-58cc-4372-a567-0e02b2c3d479
X-Gnubok-Api-Version: 2026-05-12
{"id":"f47ac10b-58cc-4372-a567-0e02b2c3d479","type":"webhook.test","api_version":"2026-05-12","created":1778846400,"data":{"object":{"hello":"from Accounted","tested_at":"2026-05-15T12:00:00Z"}},"previous_attributes":null}
\`\`\`
If your receiver returns 2xx, the delivery moves to \`delivered\`. If it returns 4xx (other than 410) or 5xx, it goes to \`failed\` and retries on the schedule \`1m / 5m / 30m / 2h / 12h / 24h / 48h\`.
## 4. Inspect the delivery
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/webhooks/$WEBHOOK_ID/deliveries?delivery_id=$DELIVERY_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
Response carries the captured response status and body (truncated to 4 KB), which is invaluable when debugging a 4xx from the receiver:
\`\`\`json
{
"data": [{
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"event_type": "webhook.test",
"status": "delivered",
"attempts": 1,
"next_attempt_at": "2026-05-15T12:00:00Z",
"response_status": 200,
"response_body": "ok",
"error": null,
"request_id": "req_...",
"created_at": "2026-05-15T12:00:00Z",
"delivered_at": "2026-05-15T12:00:01Z"
}]
}
\`\`\`
## 5. Drive a real event
Now mark a real invoice paid (or use any of the [event-emitting endpoints](/docs/api/webhooks#event-types)). The webhook handler picks up the emission and enqueues a delivery within the same request cycle.
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/invoices/$INVOICE_ID/mark-paid" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{ "payment_date": "2026-05-22" }'
\`\`\`
The next dispatcher tick (within 60s) delivers an \`invoice.paid\` event to your receiver carrying the full invoice payload + payment details.
## Idempotency on the receiver side
Deliveries are at-least-once. The same \`X-Gnubok-Delivery\` may arrive twice when the network drops a 200 response or your receiver times out after processing. Build idempotency around that header:
\`\`\`javascript
// Pseudo-code: adapt to your storage layer.
async function handleEvent(event) {
const inserted = await db.processedDeliveries.insertIfMissing({
delivery_id: event.id,
event_type: event.type,
received_at: new Date(),
})
if (!inserted) {
console.log('duplicate delivery, skipping', event.id)
return
}
await processBusinessLogic(event)
}
\`\`\`
This pattern: a unique constraint on \`delivery_id\`, an INSERT-on-conflict-do-nothing, and short-circuit when nothing was inserted. Every Accounted delivery passes through that gate at most once even if the dispatcher retries.
## Replaying a dead delivery
When a delivery exhausts its retries it's marked \`dead\`. After fixing the receiver, replay individual deliveries with:
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/webhook-deliveries/$DELIVERY_ID/retry" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
The retry creates a fresh delivery row pointing at the same payload: the original audit row stays in place. Receivers see a new \`X-Gnubok-Delivery\` (the new row's id, not the original's), so the idempotency table needs no special handling.
## Auto-disable
After:
- HTTP 410 Gone from your receiver, OR
- HTTP 3xx redirect (refused to follow: SSRF policy), OR
- The webhook URL resolves to a private/loopback/link-local/cloud-metadata IP at dispatch time
…the webhook is automatically disabled (\`active=false\`, \`disabled_reason\` set). Re-enable with:
\`\`\`bash
curl -X PATCH "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/webhooks/$WEBHOOK_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Content-Type: application/json" \\
-d '{ "active": true }'
\`\`\`
This clears \`disabled_at\` and \`disabled_reason\` but does NOT replay the deliveries that died while disabled: replay them individually with the retry endpoint.
## Common pitfalls
- **Re-serialising the body.** \`JSON.parse(rawBody); JSON.stringify(parsed)\` produces different bytes than Accounted sent. Always sign-check against the raw bytes.
- **Forgetting the timestamp window.** Without a \`t\` check, an attacker who captured one signed payload can replay it forever. 5 minutes is the recommended tolerance.
- **Returning 5xx for application errors.** A 5xx triggers the full retry schedule (~87h, roughly 3.6 days). If a payload is malformed-but-stable, return 200 and queue for internal investigation.
- **Treating \`failed\` as terminal.** \`failed\` rows will retry; only \`delivered\` and \`dead\` are terminal. Don't alert on \`failed\`: alert when retries exhaust to \`dead\`.
`
@@ -0,0 +1,235 @@
export const COOKBOOK_YEAR_END_MD = `# Cookbook: year-end closing (bokslut)
> Run the year-end procedures for a Swedish fiscal year — the engine locks and closes it and sets the opening balances for the new year. Built around BFL 5 kap and 7 kap requirements (verifikationskedja, balanskontinuitet, 7-year retention).
This is the operational companion to the [Fiscal-periods reference](/docs/api/reference/fiscal-periods). Year-end is the single most consequential lifecycle event in a Swedish bookkeeping system: closing is irreversible per BFL 5 kap 8 §. Treat the steps below as a checklist, not a script to copy-paste.
## What you'll need
- A test API key with \`bookkeeping:write\`, \`bookkeeping:read\`, \`reports:read\`, \`compliance:read\`, \`documents:write\`, and \`operations:read\` scopes.
- All transactions for the year posted (no drafts).
- All VAT declarations for the year filed (12 monthly, 4 quarterly, or 1 annual: see the [VAT cookbook](/docs/api/cookbook/file-vat-declaration)).
- All AGI declarations for the year filed. (Employment income reported through monthly AGI is **not** re-reported on an annual kontrolluppgift — KU remains only for the specific payment types AGI doesn't cover, e.g. certain ränta/utdelning; it is not a blanket year-end step.)
- The bokslut date: usually 31 december for calendar-year companies (kalenderår), or the last day of the räkenskapsår for off-calendar (brutet räkenskapsår).
## 1. Pre-flight: continuity check (IB/UB per BFL 5 kap)
Before you run year-end, verify the period's continuity. BFL 5 kap (with the SIE4 invariant) requires that a period's opening balance (IB) equals the previous period's closing balance (UB) on every BAS 1xxx, 2xxx account. The check takes the fiscal-period UUID and compares that period's IB against its predecessor's UB.
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/reports/continuity-check?period_id=$PERIOD_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
Response (a passing check returns \`valid: true\` with an empty \`discrepancies\` array):
\`\`\`json
{
"data": {
"valid": true,
"period_name": "FY 2025",
"previous_period_name": "FY 2024",
"discrepancies": [],
"checked_accounts": 42
}
}
\`\`\`
When a mismatch exists \`valid\` is \`false\` and each offending account appears in \`discrepancies\`:
\`\`\`json
{
"account_number": "1930",
"account_name": "Företagskonto",
"previous_ub_net": 156432.00,
"current_ib_net": 156430.00,
"difference": 2.00
}
\`\`\`
\`valid: false\` is a BFL violation: the previous period's closing balance (UB) was not carried into this period as the opening balance (IB). This is always a carry-forward problem — a missing/incorrect opening-balance entry, or a post-close mutation of the prior period — not a missed bank reconciliation or a VAT-vs-GL disagreement. Investigate the opening-balance entry for the flagged account before proceeding.
## 2. Pre-flight: voucher gaps (BFNAR 2013:2)
BFNAR 2013:2 kap 6-7 §§ requires explanations for missing voucher numbers. Run the check:
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/compliance/check?type=voucher_gaps&fiscal_period_id=$PERIOD_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
The check returns a \`findings\` array; each unexplained gap is a \`blocker\` (code \`VOUCHER_GAP_UNEXPLAINED\`). For every gap, file an explanation via \`POST /voucher-gap-explanations\` before the year is closed. Skatteverket can ask for these years later under the 7-year retention rule.
## 3. Pre-flight: missing documents on posted entries
For aktiebolag, BFL 7 kap requires every verifikation to have its underlag (receipt, faktura, kontrakt) attached. The v1 \`compliance/check\` endpoint does **not** gate on documents — its only supported types are \`year_end_readiness\` and \`voucher_gaps\` — so surface missing underlag through the MCP tools instead:
\`\`\`
accounted_list_verifikat_without_documents
accounted_list_transactions_without_documents
\`\`\`
Attach an already-uploaded document to its verifikation via \`POST /documents/{id}/link\`, passing the target entry in the body:
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/documents/$DOCUMENT_ID/link" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{ "journal_entry_id": "a8f1c2d3-..." }'
\`\`\`
The first link to a verifikation is allowed even after the period is locked (it completes the audit trail rather than modifying the entry). Re-linking a document that is already attached to a *posted* entry is refused with \`CONFLICT\` (\`document_already_linked_to_posted_entry\`) per BFL 5 kap 5 §.
## 4. Locking is handled by year-end (do NOT pre-lock)
The year-end run in step 5 locks the fiscal year itself as part of its flow. **Do not call \`/lock\` on the year you are about to close first**: \`executeYearEndClosing\` locks the period internally, and a period that is already locked makes the run fail with \`Period is already locked\`.
The standalone \`POST /fiscal-periods/{id}/lock\` endpoint (synchronous, returns \`200\` with the updated period) is for *interim* locking, e.g. freezing a finished month you are not year-end-closing. It refuses if uncategorised affärstransaktioner remain in the period (\`PERIOD_HAS_UNBOOKED_TRANSACTIONS\`).
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/fiscal-periods/$PERIOD_ID/lock" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
Unlocking a locked period is not exposed in v1 (dashboard only). A closed period can never be unlocked: closing is irreversible per BFL 5 kap 8 §.
## 5. Run year-end
\`POST /fiscal-periods/{id}/year-end\` is the single engine-touching step. It takes **no request body** (only the mandatory \`Idempotency-Key\` header); the next fiscal period is resolved automatically — an existing next period is reused, otherwise one is created. In order, \`executeYearEndClosing\`:
1. Re-validates readiness (no drafts, no unexplained voucher gaps, trial balance balanced). Preview it first with \`GET /compliance/check?type=year_end_readiness&fiscal_period_id=$PERIOD_ID\`.
2. Runs currency revaluation, posting FX gains/losses to \`3960\`/\`7960\` **before** the closing entry so they get swept into the result.
3. Posts one closing entry (\`source_type=year_end\`, series A, "Årsbokslut …"): it zeros every result account in BAS class 3-8 and books the net result **directly** onto \`2099\` "Årets resultat" (aktiebolag) — or \`2010\` "Eget kapital" for enskild firma. There is no \`8910\` intermediate step.
4. Locks, then closes the period (irreversible per BFL 5 kap 8 §).
5. Generates the opening-balance verifikat in the next period: every BAS class 1-2 account's UB becomes its IB, as a single balanced entry.
6. Re-validates IB/UB continuity (rolling back on failure), then — for aktiebolag — omför föregående års resultat from \`2099\` to \`2098\` in the new period as a separate verifikat.
The engine does **not** compute or post income tax (bolagsskatt), periodiseringsfond, or överavskrivningar. Book any bokslutsdispositioner and the tax entry yourself as ordinary verifikationer **before** running year-end — the tax entry debits \`8910\` against \`2512\`; a periodiseringsfond avsättning debits \`8811\` against an obeskattad reserv in \`21xx\` — so the closing entry sweeps their class-8 legs into the result.
This is an async operation. It takes no body:
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/fiscal-periods/$PERIOD_ID/year-end" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
Response is a \`202\` with an operation handle (operation ids are UUIDs):
\`\`\`json
{
"data": {
"operation_id": "0e9c1f2a-8b3d-4f6a-9c21-1a2b3c4d5e6f",
"type": "fiscal_periods.year_end",
"status": "queued",
"poll_url": "/api/v1/operations/0e9c1f2a-8b3d-4f6a-9c21-1a2b3c4d5e6f",
"webhook_event": "operation.completed"
}
}
\`\`\`
Poll \`GET /operations/{id}\`; on \`succeeded\` the \`result\` block carries the ids of the entries the engine posted and the next period it opened:
\`\`\`json
{
"data": {
"operation_id": "0e9c1f2a-8b3d-4f6a-9c21-1a2b3c4d5e6f",
"type": "fiscal_periods.year_end",
"status": "succeeded",
"result": {
"closing_entry_id": "a8f1c2d3-...",
"revaluation_entry_id": "b7e2d3c4-...",
"opening_balance_entry_id": "c6d3e4f5-...",
"next_period_id": "d5c4b3a2-..."
},
"error": null,
"poll_url": "/api/v1/operations/0e9c1f2a-8b3d-4f6a-9c21-1a2b3c4d5e6f",
"webhook_event": "operation.completed"
}
}
\`\`\`
(\`revaluation_entry_id\` is \`null\` when there were no open foreign-currency items to revalue.)
## 6. Verify opening balances on the new year
After year-end runs, the new period (\`next_period_id\` from the operation result) has IB on every balance-sheet account matching the prior period's UB. Pass that period's UUID as \`period_id\`:
\`\`\`bash
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/reports/trial-balance?period_id=$NEXT_PERIOD_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
The \`opening_balance\` column on every 1xxx/2xxx row should equal the \`closing_balance\` on the same row for the closed year. \`3xxx-8xxx\` accounts have zero opening balance: the year-end procedure cleared them into \`2099\`.
You normally never touch \`POST /fiscal-periods/{id}/opening-balances\`: year-end already generates the IB, and this endpoint returns \`CONFLICT\` (\`opening_balance_already_posted\`) once an IB entry exists in the target period. It exists only to generate the IB in isolation — its body is \`{ "next_period_id": "<uuid>" }\` and it computes balances from the closed period's UB (no explicit values are accepted). To correct a wrong IB, post a storno/manual entry instead.
## 7. The period is already closed (\`/close\` is recovery-only)
Step 5 already locked **and** closed the period — \`executeYearEndClosing\` runs \`closePeriod\` as its final bookkeeping step. **BFL 5 kap 8 §: closing is irreversible.** No code path can re-open a closed period, so in the normal flow you never call \`/close\` yourself.
\`POST /fiscal-periods/{id}/close\` exists only as a recovery path: it finalizes a year-end that posted its closing entry and locked the period but did not reach the close step (a rare mid-flow failure). It reads **no body** — only the mandatory \`Idempotency-Key\` header:
\`\`\`bash
curl -X POST "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/fiscal-periods/$PERIOD_ID/close" \\
-H "Authorization: Bearer gnubok_sk_test_..." \\
-H "Idempotency-Key: $(uuidgen)"
\`\`\`
It returns \`CONFLICT\` (\`already_closed\`) if the period is already closed, \`PERIOD_NOT_LOCKED\` if it was never locked, and \`CONFLICT\` (\`year_end_not_executed\`) if no closing entry exists yet.
## 8. Assemble the årsredovisning (aktiebolag only)
For an AB, the annual report (årsredovisning) is filed with Bolagsverket within 7 months of the fiscal-year end. A single \`/reports/annual-report\` endpoint is **not yet exposed in v1**: assemble the K2/K3 source figures from the report endpoints that do exist, then typeset and submit via Bolagsverket Mina Sidor.
\`\`\`bash
# Resultaträkning
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/reports/income-statement?period_id=$PERIOD_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..."
# Balansräkning
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/reports/balance-sheet?period_id=$PERIOD_ID" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
The resultaträkning and balansräkning come from those two reports; the noter and förvaltningsberättelse are assembled from the GL on your side. The signing flow (every styrelseledamot must sign) is outside the API surface.
## 9. Generate INK2 / NE for the tax declaration
The tax declaration (INK2 for AB, NE-bilaga for enskild firma) is due in March/May depending on entity type and fiscal-year shape. The endpoints:
\`\`\`bash
# Aktiebolag: INK2
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/reports/ink2?year=2025" \\
-H "Authorization: Bearer gnubok_sk_test_..."
# Enskild firma: NE-bilaga
curl "https://app.gnubok.se/api/v1/companies/$COMPANY_ID/reports/ne-bilaga?year=2025" \\
-H "Authorization: Bearer gnubok_sk_test_..."
\`\`\`
These produce **two files**: \`INFO.SRU\` (metadata header) plus \`BLANKETTER.SRU\` (the declaration body), uploaded together as a single submission to Skatteverket. **The SRU format is plain text encoded in ISO 8859-1 (NOT XML)**: a tagged record-line shape per Skatteverket's SRU specification. A single-file upload is rejected by Skatteverket's validation. This is a separate artefact from Bolagsverket's digital årsredovisning filing, which uses **iXBRL** (an XML-based standard). SRU goes to Skatteverket for INK2/INK2R/INK2S declarations; iXBRL goes to Bolagsverket for the public annual report. Don't conflate them.
> **Note:** \`/reports/ink2\` and \`/reports/ne-bilaga\` are not part of the v1 report surface yet: see the API changelog for current availability. Until they ship, generate the inputs via \`/reports/trial-balance?period_id=<uuid>\` and feed your tax-software of choice.
## Brutet räkenskapsår (off-calendar year)
For a company on a non-calendar fiscal year (e.g. 2024-07-01 → 2025-06-30), the entire flow is identical: substitute the actual period dates everywhere. The IB/UB continuity check, the year-end procedure, and the lock/close lifecycle all operate on the period regardless of its alignment with the calendar.
The one exception: the VAT declaration cadence is monthly/kvartalsvis/årlig regardless of the räkenskapsår shape, so a brutet räkenskapsår company files moms on calendar months while closing books on its own fiscal calendar.
## Common pitfalls
- **Don't year-end before the last month's moms is declared.** The year-end procedure expects every moms-account balance to reconcile. A pending declaration leaves dangling balances on 2611-2641.
- **Periodiseringsfond is your entry, not the engine's.** \`/year-end\` does not accept a set-aside amount and does not post the reserve; it only revalues currency, posts the closing entry (class 3-8 → \`2099\`), and generates the IB. If you set aside a periodiseringsfond, book it yourself as an obeskattad reserv (\`21xx\`, against \`8811\`) **before** running year-end. For sizing it: per IL 30 kap 5 § and 30 kap 6 a §, an AB can set aside max 25% of the **taxable profit AFTER schablonintäkt has been added back and BEFORE the periodiseringsfond deduction itself**. The schablonintäkt is **(SLR + 1%) × outstanding prior-year periodiseringsfonder balance**, where SLR is Skatteverket's statslåneränta as published on 30 November of the preceding income year: for 2026 SLR is 2.55%, so the rate is **3.55%**. Under BFL/BFNAR 2016:10 (materiellt samband for AB), the periodiseringsfond is BOOKED as an obeskattad reserv, not just declared on INK2.
- **Don't unlock a period after the AB's annual report is filed.** The signed annual report is a public document at Bolagsverket; unlocking and changing the books afterwards creates a discrepancy with the filed report (which is itself an audit finding). Use storno (\`POST /journal-entries/{id}/reverse\`) to correct in the current open period instead. (Unlocking is dashboard-only; it is not in v1.)
- **Year-end is async.** Don't block your request loop on it: poll \`GET /operations/{id}\` with reasonable backoff (every 5-10s). If you prefer webhooks, subscribe to \`period.year_closed\` — that is the event the engine emits on completion. (\`operation.completed\`, shown in the operation envelope, is the polling contract, not a separately deliverable subscription event.)
## Next steps
- **[VAT declaration cookbook](/docs/api/cookbook/file-vat-declaration)**: covers each monthly cycle within the year.
- **[Payroll cookbook](/docs/api/cookbook/run-payroll-and-agi)**: the monthly AGI cycle, plus any exception-based kontrolluppgifter (the KU types AGI doesn't cover) filed in January of year N+1.
- **[Fiscal-periods reference](/docs/api/reference/fiscal-periods)**: every parameter, every state transition.
`
+138
View File
@@ -0,0 +1,138 @@
/**
* /docs/api/errors content: generated from the STRUCTURED_ERRORS registry.
*
* The registry lives in lib/errors/structured-errors.ts; we re-import it here
* and build a Stripe-style catalogue page where every code is anchorable
* (the docs_url field on every error envelope already points at this page).
*
* Adding a new error code in the registry automatically surfaces here on the
* next build: no manual edits to keep in sync.
*/
import { listErrorCodes, getErrorEntry } from '@/lib/errors/structured-errors'
interface DomainGroup {
label: string
description: string
/** Code prefix matchers: first match wins; codes without a match fall to 'Other'. */
prefixes: string[]
}
const DOMAINS: DomainGroup[] = [
{ label: 'Generic', description: 'Cross-cutting codes returned by any endpoint.', prefixes: ['UNKNOWN_', 'INTERNAL_', 'VALIDATION_', 'UNAUTHORIZED', 'MFA_', 'FORBIDDEN', 'NOT_FOUND', 'CONFLICT', 'RATE_LIMITED', 'NOT_IMPLEMENTED', 'COMPANY_CONTEXT_', 'IDEMPOTENCY_', 'INSUFFICIENT_SCOPE'] },
{ label: 'Bookkeeping engine', description: 'Errors from the journal-entry lifecycle (create, commit, reverse, correct).', prefixes: ['BOOKKEEPING_', 'JOURNAL_', 'VOUCHER_'] },
{ label: 'Periods + year-end', description: 'Fiscal period locking, year-end closing, opening balances, FX revaluation.', prefixes: ['PERIOD_', 'YEAR_END_', 'OPENING_BALANCE_', 'FX_'] },
{ label: 'Invoices', description: 'Customer invoice lifecycle: draft, send, mark paid, credit.', prefixes: ['INVOICE_', 'CREDIT_NOTE_', 'CUSTOMER_'] },
{ label: 'Supplier invoices', description: 'AP lifecycle: register, approve, mark paid, credit.', prefixes: ['SUPPLIER_INVOICE_', 'SUPPLIER_'] },
{ label: 'Transactions', description: 'Bank transaction ingest, categorisation, matching.', prefixes: ['TRANSACTION_', 'MATCH_INVOICE_', 'MATCH_SI_', 'MATCH_'] },
{ label: 'Reports', description: 'Report generation: VAT declaration, periodisk sammanställning, SIE export, INK2.', prefixes: ['REPORT_', 'VAT_', 'PS_', 'SIE_EXPORT_', 'TAX_DECL_'] },
{ label: 'Imports', description: 'SIE import, bank file import, opening-balance import, provider migration.', prefixes: ['SIE_IMPORT_', 'BANK_FILE_', 'OPENING_BALANCE_IMPORT_', 'REGISTER_IMPORT_', 'PROVIDER_MIGRATION_'] },
{ label: 'Documents', description: 'Document upload, link, signed-URL download, retention.', prefixes: ['DOCUMENT_'] },
{ label: 'Salary + AGI', description: 'Payroll lifecycle, AGI generation, KU declarations.', prefixes: ['SALARY_', 'AGI_', 'KU_', 'EMPLOYEE_'] },
{ label: 'Company + API keys', description: 'Multi-tenant + auth lifecycle.', prefixes: ['COMPANY_', 'API_KEY_'] },
{ label: 'Provider connections', description: 'External provider OAuth, sync, consent.', prefixes: ['PROVIDER_'] },
]
function classify(code: string): string {
for (const group of DOMAINS) {
for (const prefix of group.prefixes) {
if (code.startsWith(prefix)) return group.label
}
}
return 'Other'
}
function statusLabel(status: number): string {
switch (status) {
case 400: return 'Bad request'
case 401: return 'Unauthorized'
case 403: return 'Forbidden'
case 404: return 'Not found'
case 409: return 'Conflict'
case 422: return 'Unprocessable'
case 429: return 'Rate limited'
case 500: return 'Server error'
case 501: return 'Not implemented'
default: return ''
}
}
export function buildErrorReferenceMd(): string {
const codes = listErrorCodes().sort()
const grouped = new Map<string, string[]>()
for (const code of codes) {
const domain = classify(code)
if (!grouped.has(domain)) grouped.set(domain, [])
grouped.get(domain)!.push(code)
}
// Render groups in the order DOMAINS declares, with Other last.
const orderedLabels = [...DOMAINS.map((d) => d.label), 'Other']
const lines: string[] = []
lines.push('# Errors')
lines.push('')
lines.push(`> Every error returned by the Accounted REST API uses a stable code from this catalogue. Codes never change once shipped: agents can pattern-match on them safely. The \`docs_url\` field on every error envelope points at the catalogue entry for that specific code.`)
lines.push('')
lines.push('## Envelope shape')
lines.push('')
lines.push('```json')
lines.push('{')
lines.push(' "error": {')
lines.push(' "code": "PERIOD_LOCKED",')
lines.push(' "message": "Den valda perioden är låst.",')
lines.push(' "message_en": "The selected period is locked.",')
lines.push(' "details": { "fiscal_period_id": "..." },')
lines.push(' "recovery_hint": "Unlock via /fiscal-periods/{id}/unlock or pick an open period.",')
lines.push(' "docs_url": "https://app.gnubok.se/docs/api/errors/PERIOD_LOCKED",')
lines.push(' "request_id": "req_..."')
lines.push(' }')
lines.push('}')
lines.push('```')
lines.push('')
lines.push(`The \`message\` field is Swedish (matches the dashboard); \`message_en\` is English (for agent and developer logs). \`recovery_hint\` (when present) is a one-line description of the canonical fix. \`request_id\` echoes the request for support and log correlation — note it lives inside \`error\` on failures (there is no top-level \`meta\` block on an error response, unlike the success envelope). \`docs_url\` is built from the code (\`…/docs/api/errors/<CODE>\`).`)
lines.push('')
for (const label of orderedLabels) {
const codes = grouped.get(label)
if (!codes || codes.length === 0) continue
const desc = DOMAINS.find((d) => d.label === label)?.description ?? ''
lines.push(`## ${label}`)
lines.push('')
if (desc) {
lines.push(`*${desc}*`)
lines.push('')
}
for (const code of codes) {
const entry = getErrorEntry(code)
if (!entry) continue
const status = entry.httpStatus
const statusName = statusLabel(status)
lines.push(`### ${code}`)
lines.push('')
lines.push(`**HTTP \`${status}\`**${statusName ? `: ${statusName}` : ''}`)
lines.push('')
lines.push(`${entry.message_en}`)
lines.push('')
if (entry.message_sv) {
lines.push(`**Swedish:** ${entry.message_sv}`)
lines.push('')
}
if (entry.remediation) {
lines.push(`**Remediation:** ${entry.remediation.description}`)
if (entry.remediation.tool) {
lines.push(`Related tool: \`${entry.remediation.tool}\``)
}
if (entry.remediation.resource) {
lines.push(`Related resource: \`${entry.remediation.resource}\``)
}
lines.push('')
}
}
}
return lines.join('\n')
}
+110
View File
@@ -0,0 +1,110 @@
import { API_V1_VERSION } from '@/lib/api/v1/version'
export const LANDING_MD = `# accounted API
> Swedish double-entry bookkeeping as a public REST API for agents and integrations. API version \`${API_V1_VERSION}\`.
The accounted API covers the financial workflows an integration needs: create invoices, ingest bank transactions, file VAT declarations, run payroll, and subscribe to webhooks for state changes. Every endpoint is designed for autonomous agents first: machine-readable schemas, dry-run previews, idempotent retries, and inline audit blocks on every write. (A few dashboard-only steps remain, e.g. generating salary payment files and sending payslips, and each cookbook calls out where one applies.)
If you've used [Stripe's API](https://docs.stripe.com/api), the shape will feel familiar: bearer-token auth, dated API versions, webhook signature verification, idempotency keys. The accounting concepts are Swedish (BAS chart, BFL retention, K2/K3, momsdeklaration) but the surface is built for the same kind of integrator.
## Authentication
All requests authenticate with a bearer token in the \`Authorization\` header:
\`\`\`bash
curl https://app.gnubok.se/api/v1/companies \\
-H "Authorization: Bearer gnubok_sk_live_..."
\`\`\`
Create keys in the accounted dashboard at **/settings/api**. Two key prefixes are available:
- \`gnubok_sk_live_*\`: hits real customer data. Use in production.
- \`gnubok_sk_test_*\`: reads real company data, but every write is forced into dry-run and nothing persists (responses carry \`X-Gnubok-Mode: test\`). Safe for evals, demos, and agent learning. Same surface, different blast radius.
Each key carries one or more **scopes** (\`invoices:read\`, \`invoices:write\`, \`payroll:write\`, \`webhooks:manage\`, ...) that gate which endpoints it can call. Scopes are listed on every endpoint reference page.
Rate limit: 100 requests per minute per key.
## Base URL
\`\`\`
https://app.gnubok.se/api/v1
\`\`\`
URLs include the company id explicitly:
\`\`\`
GET /api/v1/companies/{companyId}/invoices
POST /api/v1/companies/{companyId}/invoices
\`\`\`
A multi-company key can act on any company the underlying user is a member of: the URL is the source of truth, not a default. List the companies a key can access with:
\`\`\`bash
curl https://app.gnubok.se/api/v1/companies \\
-H "Authorization: Bearer gnubok_sk_live_..."
\`\`\`
## Core principles
These four invariants hold across the entire surface: once you've internalised them you can predict the shape of any endpoint without reading the reference.
**Dry-run on every write.** Append \`?dry_run=true\` (or send \`X-Dry-Run: true\`) to any POST/PATCH/DELETE to preview the effect: the response shows the journal lines, voucher number, account deltas, and any validation errors that would surface, but commits nothing. Use this in agent test-loops to validate inputs before paying the side-effect cost.
**Idempotency-Key on every write.** Pass a UUID in the \`Idempotency-Key\` header. Replays of the same key+body return the original response with \`Idempotent-Replayed: true\` (24h cache). Replays with a different body return \`409 IDEMPOTENCY_KEY_REUSE\`.
**Strict-mode write semantics.** A v1 mutation either commits fully or returns a structured error code with no side effects. The dashboard soft-fails on partial writes (a human is there to retry); the v1 surface aborts. This means you never see "the invoice was sent but the email failed": either both happened or neither did.
**Inline audit on every write.** Every successful write response includes an \`audit\` block in \`meta\` with the voucher number, audit-trail URL, and immutability timestamp. No second round-trip needed to confirm what happened.
## Response envelope
Every response has the same shape:
\`\`\`json
{
"data": { ... },
"meta": {
"request_id": "req_...",
"api_version": "${API_V1_VERSION}",
"next_cursor": "...",
"audit": { "voucher_number": "A-2026-042", "voucher_url": "..." }
}
}
\`\`\`
Errors return an \`error\` object instead of \`data\` (and carry no \`meta\` block — the \`request_id\` moves inside \`error\`):
\`\`\`json
{
"error": {
"code": "PERIOD_LOCKED",
"message": "Den valda perioden är låst.",
"message_en": "The selected period is locked.",
"details": { "fiscal_period_id": "..." },
"recovery_hint": "Unlock via /fiscal-periods/{id}/unlock or pick an open period.",
"docs_url": "https://app.gnubok.se/docs/api/errors/PERIOD_LOCKED",
"request_id": "req_..."
}
}
\`\`\`
Every error code is documented in the [error reference](/docs/api/errors).
## Where to go next
- **[Quickstart cookbook](/docs/api/cookbook/quickstart)**: send your first invoice in five minutes.
- **[API reference](/docs/api/reference)**: every endpoint, grouped by resource.
- **[Webhooks](/docs/api/webhooks)**: subscribe to events with HMAC-signed delivery.
- **[Errors](/docs/api/errors)**: every stable error code with remediation.
- **[Versioning](/docs/api/versioning)**: how API versions are pinned and upgraded.
- **[Changelog](/docs/api/changelog)**: what shipped when.
For LLM-based agents:
- **Agent skill for integrators**: \`npx skills add erp-mafia/accounted --skill accounted-api\` teaches your coding agent (Claude Code, Cursor, Codex, ...) this entire API: auth, conventions, and every endpoint with request/response schemas. Generated from the same registry that serves this spec, so it cannot drift.
- **[\`/llms.txt\`](/llms.txt)**: concise agent-discovery index.
- **[\`/llms-full.txt\`](/llms-full.txt)**: full docs concatenated for ingestion.
- **[\`/api/v1/openapi.json\`](/api/v1/openapi.json)**: machine-readable OpenAPI 3.1 spec.
- **[\`/.well-known/skills/index.json\`](/.well-known/skills/index.json)**: accounted-specific skill catalogue.
`
+207
View File
@@ -0,0 +1,207 @@
/**
* Auto-generated API reference pages.
*
* Iterates lib/api/v1/registry.ts ENDPOINTS, groups by resource (derived
* from the URL path), and renders one Markdown page per resource. Stripe-
* style: each endpoint section has the description, useWhen, doNotUseFor,
* pitfalls, scope, idempotent/reversible/dryRun flags, and a worked example.
*
* To make this work, every v1 route file needs to import-side-effect call
* registerEndpoint(): which they all do at module load time. The doc
* builder triggers that load via lib/api/v1/load-routes.ts.
*
* Adding a new endpoint means editing the route file's registerEndpoint
* call; the docs then surface it on the next build with no manual sync.
*/
import { listEndpoints, type EndpointDefinition, type HttpMethod } from '@/lib/api/v1/registry'
// Side-effect import: every v1 route file's top-level registerEndpoint()
// call runs as a result of loading this module, populating the shared
// ENDPOINTS map that listEndpoints() reads from.
import '@/lib/api/v1/load-routes'
interface ResourceGroup {
/** URL slug, used in /docs/api/reference/{slug}. */
slug: string
/** Display label for headings + nav. */
label: string
/** One-line description for the resource landing card. */
description: string
/** URL pattern segment that identifies endpoints belonging to this resource. */
matcher: (path: string) => boolean
}
const RESOURCES: ResourceGroup[] = [
{ slug: 'companies', label: 'Companies', description: 'List and read companies the API key can access.', matcher: (p) => /\/companies(?:\/:companyId)?$/.test(p) },
{ slug: 'customers', label: 'Customers', description: 'CRM-side: who you invoice. Business and individual (sole-trader) customers with VIES validation.', matcher: (p) => /\/customers(\/|$)/.test(p) },
{ slug: 'invoices', label: 'Invoices', description: 'Outbound invoicing: draft, send, mark paid, credit, PDF download. Mixed-rate VAT supported.', matcher: (p) => /\/invoices(\/|$)/.test(p) },
{ slug: 'articles', label: 'Articles', description: 'Read the article/product catalogue used to build invoice line items.', matcher: (p) => /\/articles(\/|$)/.test(p) },
{ slug: 'suppliers', label: 'Suppliers', description: 'AP-side counterparties. Mirrors customers on the supplier vertical.', matcher: (p) => /\/suppliers(\/|$)/.test(p) },
{ slug: 'supplier-invoices', label: 'Supplier invoices', description: 'AP lifecycle: register, approve, mark paid, credit. With ROT/RUT and reverse-charge support.', matcher: (p) => /\/supplier-invoices(\/|$)/.test(p) },
{ slug: 'transactions', label: 'Transactions', description: 'Bank transactions: ingest, categorise, match to invoices, reconcile.', matcher: (p) => /\/transactions(\/|$)/.test(p) },
{ slug: 'reconciliation', label: 'Reconciliation', description: 'Run bank-to-ledger reconciliation and read the current matching status.', matcher: (p) => /\/reconciliation(\/|$)/.test(p) },
{ slug: 'journal-entries', label: 'Journal entries', description: 'The bookkeeping engine surface: verifikation lifecycle (draft, commit, reverse, correct).', matcher: (p) => /\/journal-entries(\/|$)/.test(p) },
{ slug: 'voucher-gap-explanations', label: 'Voucher gap explanations', description: 'Documented explanations for gaps in the voucher series, per BFNAR 2013:2.', matcher: (p) => /\/voucher-gap/.test(p) },
{ slug: 'fiscal-periods', label: 'Fiscal periods', description: 'Period lifecycle: lock, close, year-end, opening balances, FX revaluation. Async via the operations substrate.', matcher: (p) => /\/fiscal-periods(\/|$)/.test(p) },
{ slug: 'accounts', label: 'Accounts', description: 'Read the chart of accounts (BAS).', matcher: (p) => /\/accounts(\/|$)/.test(p) },
{ slug: 'documents', label: 'Documents', description: 'Multipart upload, signed-URL download (15-min TTL), link to journal entries.', matcher: (p) => /\/documents(\/|$)/.test(p) },
{ slug: 'inbox-items', label: 'Inbox items', description: 'Stamp incoming documents in the inbox to turn them into supplier invoices or transactions.', matcher: (p) => /\/inbox-items(\/|$)/.test(p) },
{ slug: 'dimensions', label: 'Dimensions', description: 'Cost-centre / project dimensions and their values for tagging journal lines.', matcher: (p) => /\/dimensions(\/|$)/.test(p) },
{ slug: 'employees', label: 'Employees', description: 'Payroll roster: CRUD with personnummer masking on list endpoints.', matcher: (p) => /\/employees(\/|$)/.test(p) },
{ slug: 'salary-runs', label: 'Salary runs', description: 'Payroll lifecycle: create, calculate, approve, mark paid, book, generate AGI XML.', matcher: (p) => /\/salary-runs(\/|$)/.test(p) },
{ slug: 'reports', label: 'Reports', description: 'Read-only reports: trial balance, P&L, balance sheet, GL, VAT, salary journal, SIE export, +9 more.', matcher: (p) => /\/reports(\/|$)/.test(p) },
{ slug: 'imports', label: 'Imports', description: 'Bulk async ingest: SIE files (Fortnox/Visma/BL/SpeedLedger/Bokio migrations) and bank statements (12 formats).', matcher: (p) => /\/imports(\/|$)/.test(p) },
{ slug: 'compliance', label: 'Compliance check', description: 'Pre-flight verification: voucher gaps, year-end readiness, before submitting to Skatteverket.', matcher: (p) => /\/compliance(\/|$)/.test(p) },
{ slug: 'webhooks', label: 'Webhooks', description: 'Subscribe to events with HMAC-signed delivery, exponential retries, and dead-letter replay.', matcher: (p) => /\/webhooks|\/webhook-deliveries/.test(p) },
{ slug: 'operations', label: 'Operations', description: 'Poll long-running async operations (year-end closing, imports, currency revaluation).', matcher: (p) => /\/operations(\/|$)/.test(p) },
]
/** Discover the resource a given endpoint path belongs to. Returns null if it doesn't fit any. */
function classifyEndpoint(path: string): ResourceGroup | null {
for (const r of RESOURCES) {
if (r.matcher(path)) return r
}
return null
}
export interface BuiltResourcePage {
slug: string
label: string
description: string
endpoints: EndpointDefinition[]
markdown: string
}
const METHOD_ORDER: Record<HttpMethod, number> = { GET: 0, POST: 1, PATCH: 2, PUT: 3, DELETE: 4 }
function endpointAnchor(ep: EndpointDefinition): string {
return `${ep.method.toLowerCase()}-${ep.operation.replace(/\./g, '-')}`
}
function renderEndpoint(ep: EndpointDefinition): string {
const lines: string[] = []
const methodBadge = ep.method
lines.push(`### \`${methodBadge}\` ${ep.path} {#${endpointAnchor(ep)}}`)
lines.push('')
lines.push(`**\`${ep.operation}\`**${ep.scope ? ` · scope \`${ep.scope}\`` : ' · public'}`)
lines.push('')
lines.push(ep.summary)
lines.push('')
lines.push(ep.description)
lines.push('')
lines.push(`**Use when:** ${ep.useWhen}`)
lines.push('')
lines.push(`**Don't use for:** ${ep.doNotUseFor}`)
lines.push('')
if (ep.pitfalls.length > 0) {
lines.push('**Pitfalls**')
for (const p of ep.pitfalls) lines.push(`- ${p}`)
lines.push('')
}
const flags: string[] = []
flags.push(`**Risk:** ${ep.risk}`)
flags.push(`**Idempotent:** ${ep.idempotent ? 'yes' : 'no'}`)
flags.push(`**Reversible:** ${ep.reversible ? 'yes' : 'no'}`)
flags.push(`**Dry-run supported:** ${ep.dryRunSupported ? 'yes' : 'no'}`)
lines.push(flags.join(' · '))
lines.push('')
if (ep.example.request) {
lines.push('**Example request**')
lines.push('')
lines.push('```json')
lines.push(JSON.stringify(ep.example.request, null, 2))
lines.push('```')
lines.push('')
}
lines.push('**Example response**')
lines.push('')
lines.push('```json')
lines.push(JSON.stringify(ep.example.response, null, 2))
lines.push('```')
lines.push('')
return lines.join('\n')
}
// Module-level memoisation. The endpoint registry is populated once at
// module load (via the side-effect import of load-routes) and is then
// immutable for the process lifetime. The Markdown serialisation is
// pure derivation: reusing a single result avoids repeated work on the
// .md route handlers (which Next.js doesn't statically pre-render) AND
// halves the cost on each generateMetadata + page render pair on the
// HTML routes. (Greptile P2, round 1.)
let cachedPages: BuiltResourcePage[] | null = null
export function buildResourcePages(): BuiltResourcePage[] {
if (cachedPages) return cachedPages
const all = listEndpoints()
const byResource = new Map<string, EndpointDefinition[]>()
for (const ep of all) {
const r = classifyEndpoint(ep.path)
if (!r) continue
if (!byResource.has(r.slug)) byResource.set(r.slug, [])
byResource.get(r.slug)!.push(ep)
}
const pages = RESOURCES.map((r) => {
const endpoints = (byResource.get(r.slug) ?? []).sort((a, b) => {
const m = METHOD_ORDER[a.method] - METHOD_ORDER[b.method]
if (m !== 0) return m
return a.path.localeCompare(b.path)
})
const lines: string[] = []
lines.push(`# ${r.label}`)
lines.push('')
lines.push(`> ${r.description}`)
lines.push('')
if (endpoints.length === 0) {
lines.push('*No endpoints registered yet for this resource.*')
} else {
lines.push('## Endpoints')
lines.push('')
for (const ep of endpoints) {
lines.push(`- [\`${ep.method}\` \`${ep.path}\`](#${endpointAnchor(ep)}): ${ep.summary}`)
}
lines.push('')
lines.push('---')
lines.push('')
for (const ep of endpoints) {
lines.push(renderEndpoint(ep))
lines.push('---')
lines.push('')
}
}
return {
slug: r.slug,
label: r.label,
description: r.description,
endpoints,
markdown: lines.join('\n'),
}
})
cachedPages = pages
return pages
}
export function buildReferenceOverviewMd(): string {
const lines: string[] = []
lines.push('# API reference')
lines.push('')
lines.push(`> Every endpoint exposed by the Accounted REST API, grouped by resource. Auto-generated from the same Zod registry that powers the [OpenAPI 3.1 spec](/api/v1/openapi.json), the MCP tool surface, and runtime validators: there is no separate doc-source to keep in sync.`)
lines.push('')
lines.push('## Resources')
lines.push('')
for (const r of RESOURCES) {
lines.push(`### [${r.label}](/docs/api/reference/${r.slug})`)
lines.push('')
lines.push(r.description)
lines.push('')
}
return lines.join('\n')
}
export const RESOURCE_SLUGS = RESOURCES.map((r) => r.slug)
+161
View File
@@ -0,0 +1,161 @@
import { API_V1_VERSION } from '@/lib/api/v1/version'
export const VERSIONING_MD = `# Versioning + idempotency + dry-run
> Three guarantees that hold across the entire v1 surface: stable response shapes pinned per request, safe retries on every write, and previewable side effects on every mutation. Once you've internalised them you can predict the shape of any new endpoint without reading its reference.
## Versioning
The major version is encoded in the URL: \`/api/v1/\`. Within v1, the response shape is dated and pinned. The current version is **\`${API_V1_VERSION}\`**.
Every response carries the active version in headers and the \`meta\` envelope:
\`\`\`
Gnubok-Version: ${API_V1_VERSION}
\`\`\`
\`\`\`json
{ "data": {...}, "meta": { "request_id": "...", "api_version": "${API_V1_VERSION}" } }
\`\`\`
### Pinning
Webhooks are pinned to the API version active at creation time (the \`api_version_pinned\` column on the \`webhooks\` row). Payload shapes for *your* webhook will not change until you explicitly upgrade: even if we ship a new dated version that breaks the shape for newly-created webhooks.
API requests pin per-request via the \`Gnubok-Version\` request header (planned for v1.x; today every request gets the current version):
\`\`\`bash
curl https://app.gnubok.se/api/v1/companies \\
-H "Authorization: Bearer ..." \\
-H "Gnubok-Version: ${API_V1_VERSION}"
\`\`\`
### Deprecation policy
When we ship a new dated version that breaks an existing shape:
1. The new version is dated forward (e.g. \`2026-08-01\`) and made the default for newly-created keys + webhooks.
2. The previous version stays available for at least **6 months** after the new version ships.
3. Deprecation appears in the [changelog](/docs/api/changelog) with the retirement date and a migration guide.
4. Three months before retirement, responses from the deprecated version will carry a \`Gnubok-Deprecation: <ISO date>\` header. Planned alongside request pinning: no version has been deprecated yet and nothing emits the header today.
5. Calls to a retired version receive HTTP 410 with code \`API_VERSION_RETIRED\`.
We will not break a shape inside an active dated version. Additive changes (new optional response fields, new request fields with defaults, new endpoints) ship as patch updates and are always backwards-compatible.
### What counts as a breaking change
- Removing a response field
- Renaming a response field
- Changing the type of a response field
- Removing an endpoint
- Removing or narrowing a stable error code
- Tightening request validation in a way that rejects previously-accepted input
- Changing the URL of an existing endpoint
What does NOT count as a breaking change:
- Adding a new optional response field
- Adding a new optional request field with a default
- Adding a new endpoint
- Adding a new error code (we expand the catalogue freely; existing codes stay stable)
- Loosening request validation
- Performance improvements that don't change observable behaviour
---
## Idempotency
Every state-changing endpoint (POST, PATCH, DELETE) accepts an \`Idempotency-Key\` header. The key is treated as an opaque string (a UUID is recommended, but any unique value works); the server caches the response keyed by \`(user_id, company_id, idempotency_key)\` for 24 hours. The canonical hash of the request body is stored alongside and compared on replay: same key + same body returns the cached response, same key + different body returns \`409 IDEMPOTENCY_KEY_REUSE\`.
### How it works
- **First call with a fresh key** → executes normally; response is cached.
- **Replay with the same key + same body** → returns the cached response with \`Idempotent-Replayed: true\` header. The original side effects are NOT re-executed.
- **Replay with the same key + different body** → returns \`409 IDEMPOTENCY_KEY_REUSE\`. This indicates the key was reused incorrectly.
- **Two concurrent requests with the same key** → the cache lookup takes no lock, so both may execute; the response write is best-effort (the first writer wins, the loser hits the unique-index conflict and skips). Idempotency de-duplicates *sequential* retries reliably; serialise concurrent retries of the same action on your side.
### Required vs supported
Most write endpoints **require** an Idempotency-Key: not only the obvious creates (invoices, customers, supplier-invoices, webhooks) but also journal-entry and salary-run creation, invoice \`send\`, period \`lock\`/\`close\`/\`year-end\`, bank reconciliation runs, dimension-value creation, PATCH/DELETE on customers, and more. Each endpoint's reference page states whether the key is required. Calls that omit a required key return \`400 VALIDATION_ERROR\` with field \`Idempotency-Key\`.
Other endpoints **support** but don't require it. Sending one is always safe.
### Pattern
\`\`\`bash
curl https://app.gnubok.se/api/v1/companies/{cid}/invoices \\
-H "Authorization: Bearer ..." \\
-H "Idempotency-Key: $(uuidgen)" \\
-H "Content-Type: application/json" \\
-d '{ "customer_id": "...", "items": [...] }'
\`\`\`
In an agent loop, generate the key once at the *start* of an attempt and reuse it across every retry of that single logical action: never on a fresh attempt with new inputs.
---
## Dry-run
Every state-changing endpoint that supports dry-run (\`x-dry-run-supported: true\` in the OpenAPI spec) accepts \`?dry_run=true\` query param **or** \`X-Dry-Run: true\` header. The endpoint executes its full validation pipeline (Zod, business rules, period-lock checks, VAT-rate compatibility, cross-tenant guards, ...) but does NOT commit. A dry-run always returns **HTTP 200** with the \`X-Dry-Run: true\` response header, never the resource's normal success status (201, 204). The body wraps a preview, not the resource itself:
- All **local** \`validation_error\` shapes that a real commit would produce surface here (Zod, business rules, period locks, cross-tenant guards). Failures that depend on external providers do **not** surface: dry-run skips them (see below), so a VIES/BankID/Skatteverket rejection only appears on the real commit.
- \`data.preview\` holds the would-be record (same shape as the success response).
- For **financial** writes (invoices, journal entries, period ops, salary) the preview also carries \`staged_operation_id\`, the \`journal_lines\` that would be posted, \`account_deltas\`, and \`voucher_number_assigned_on_commit\` (a projection: the committed number can differ by one or two if another writer takes the next number first).
\`\`\`json
{
"data": {
"dry_run": true,
"preview": { ... },
"staged_operation_id": "po_...",
"journal_lines": [{ "account": "1510", "debit": 12500, "credit": 0 }],
"voucher_number_assigned_on_commit": "A-2026-043"
},
"meta": { "request_id": "req_...", "api_version": "${API_V1_VERSION}" }
}
\`\`\`
Use dry-run to:
- **Validate input shape** before paying the side-effect cost (especially in agent test loops).
- **Preview voucher lines** the engine would generate for a given invoice + VAT mix before committing.
- **Probe period-lock** on a date before scheduling work.
Dry-run **does not** call external providers (VIES VAT validation, BankID, Skatteverket submission). Those run only on commit.
---
## Strict-mode write semantics
A v1 mutation either commits fully or returns a structured error code with no side effects. The dashboard soft-fails on partial writes (a human is there to retry); the v1 surface aborts. This means you never see "the invoice was sent but the email failed" or "the journal entry posted but the payment row didn't": either both happened or neither did.
When a multi-step write fails:
- **Pre-engine failure** (validation, missing FK, period locked) → no rows written, structured error returned.
- **Post-engine failure** (engine call succeeded, follow-up step failed) → the engine's writes are reversed via \`reverseEntry()\` (storno), the failure surfaces with code matching the failed step (e.g. \`MATCH_INVOICE_LINK_TX_FAILED\`).
Storno reversals are themselves immutable journal entries: the original audit trail remains visible per BFL 5 kap 5 §. \`reversed_by_id\` on the original row points at the storno; the storno carries \`reverses_id\` back to the original.
---
## Inline audit on every write
Every successful write response carries an \`audit\` block in \`meta\`:
\`\`\`json
{
"data": {...},
"meta": {
"request_id": "req_...",
"api_version": "${API_V1_VERSION}",
"audit": {
"voucher_number": "A-2026-042",
"voucher_url": "https://app.gnubok.se/bookkeeping/...",
"audit_trail_url": "https://app.gnubok.se/audit/req_...",
"immutable_at": "2026-05-15T12:00:00Z"
}
}
}
\`\`\`
No second round-trip needed to confirm what happened: agents can chain follow-up work directly on the returned voucher number.
`
+222
View File
@@ -0,0 +1,222 @@
import {
PUBLIC_WEBHOOK_EVENT_GROUPS,
type PublicWebhookEventGroup,
} from '@/lib/webhooks/public-events'
/**
* The "Event types" section, rendered from the same catalogue the fan-out
* handler subscribes to and the v1 create schema validates against.
*/
function renderEventTypes(): string {
return PUBLIC_WEBHOOK_EVENT_GROUPS.map((group: PublicWebhookEventGroup) => {
const heading = group.note ? `**${group.title}** *(${group.note})*` : `**${group.title}**`
const lines = group.events.map((event) =>
event.description ? `- \`${event.type}\`: ${event.description}` : `- \`${event.type}\``,
)
return [heading, ...lines].join('\n')
}).join('\n\n')
}
export const WEBHOOKS_MD = `# Webhooks
> Receive HMAC-signed POST notifications when state changes in Accounted: invoices paid, journal entries committed, periods locked, salary runs booked, AGI files generated. At-least-once delivery with exponential backoff over ~87 hours (about 3.6 days).
If you've used [Stripe webhooks](https://docs.stripe.com/webhooks), the model is identical: subscribe a URL to an event type, Accounted POSTs each event with a signed JSON body, your receiver returns 2xx to acknowledge. The signature header format and retry policy are the same. The event types are gnubok-specific.
## Lifecycle
1. **Register a receiver** with [\`POST /api/v1/companies/{companyId}/webhooks\`](/docs/api/reference/webhooks#post-webhooks-create). The response includes an HMAC signing secret returned **exactly once**: store it on the receiver side immediately. If you lose it, rotate it with [\`POST /api/v1/companies/{companyId}/webhooks/{webhookId}/rotate-secret\`](/docs/api/reference/webhooks#post-webhooks-rotate_secret): a fresh secret is issued in place and the old one is invalidated immediately, with no change to the webhook's id or delivery history.
2. **Accounted emits events** internally (e.g. an invoice is marked paid via the dashboard or another API call). The webhook handler enqueues a delivery row.
3. **The dispatcher runs immediately after the event**, signs the payload with HMAC-SHA256, and POSTs to your URL with a 10-second timeout. A cron sweep every minute picks up anything the immediate pass did not get to, so first-attempt latency is normally a second or two but is never guaranteed to be: treat delivery as prompt, not synchronous.
4. **Your receiver verifies the signature**, processes the event idempotently, and returns 2xx.
5. **Failed deliveries retry** at \`1m / 5m / 30m / 2h / 12h / 24h / 48h\` (7 retries, ~87 hours total, about 3.6 days). After all attempts the delivery is marked \`dead\`. HTTP 410 from your receiver short-circuits to \`dead\` immediately and **auto-disables** the webhook.
## Event types
The following event types are deliverable as webhooks. Subscribing to a type that requires elevated scope (\`salary_run.*\` and \`agi.*\` need \`payroll:read\`) returns \`INSUFFICIENT_SCOPE\` at registration time.
${renderEventTypes()}
## Payload shape
Every delivery wraps the event in a Stripe-style envelope:
\`\`\`json
{
"id": "d290f1ee-6c54-4b01-90e6-d701748f0851",
"type": "invoice.paid",
"api_version": "2026-05-12",
"created": 1778846400,
"data": {
"object": {
"invoice": { "id": "...", "invoice_number": "2026-0042", "total": 12500.00, ... },
"paymentAmount": 12500.00,
"paymentDate": "2026-05-15",
"companyId": "..."
}
},
"previous_attributes": null
}
\`\`\`
- \`id\` matches the \`webhook_delivery_id\` you can poll at [\`GET /api/v1/companies/{companyId}/webhooks/{webhookId}/deliveries\`](/docs/api/reference/webhooks#get-webhooks-deliveries-list).
- \`api_version\` is the version pinned to your webhook at creation time. Payload shapes for *your* webhook will not change until you explicitly upgrade.
- \`previous_attributes\` is reserved for a future field-diff feature and is currently always \`null\` for every event type.
## Request headers
Every outbound POST carries:
\`\`\`
POST /your-receiver-url HTTP/1.1
Content-Type: application/json
User-Agent: gnubok-webhook/1
X-Gnubok-Signature: t=1778846400,v1=2f5c...
X-Gnubok-Event: invoice.paid
X-Gnubok-Delivery: d290f1ee-6c54-4b01-90e6-d701748f0851
X-Gnubok-Api-Version: 2026-05-12
X-Request-Id: whdel_d290f1ee-6c54-4b01-90e6-d701748f0851
\`\`\`
The \`X-Gnubok-Delivery\` header is the canonical correlation id: log it on receipt and use it to deduplicate retries (deliveries are at-least-once, so the same delivery id may arrive more than once after a network blip).
## Verifying signatures
The signature header has the format \`t=<unix-seconds>,v1=<hex-HMAC-SHA256>\`. The signed payload is \`\${t}.\${rawBody}\`: the timestamp is included so receivers can implement a replay window (we recommend rejecting deliveries with \`t\` more than 5 minutes old).
You **must** verify the signature on every delivery before processing it. Without verification, anyone who learns your URL can forge events.
### Node.js
\`\`\`javascript
import crypto from 'node:crypto'
import express from 'express'
const app = express()
const SECRET = process.env.GNUBOK_WEBHOOK_SECRET // whsec_...
// Important: capture the RAW body before any JSON parsing: the signature
// is computed against the exact bytes Accounted sent, not a re-serialised JSON.
app.post(
'/webhook',
express.raw({ type: 'application/json' }),
(req, res) => {
const sigHeader = req.header('x-gnubok-signature') ?? ''
const rawBody = req.body.toString('utf8')
if (!verifySignature(rawBody, sigHeader, SECRET)) {
return res.status(400).send('invalid signature')
}
const event = JSON.parse(rawBody)
// Idempotency: process the delivery id once.
if (alreadyProcessed(event.id)) return res.status(200).send('ok')
handleEvent(event)
return res.status(200).send('ok')
},
)
function verifySignature(body, header, secret) {
const parts = Object.fromEntries(
header.split(',').map((p) => p.split('=', 2)),
)
const t = Number.parseInt(parts.t, 10)
const v1 = parts.v1
if (!t || !v1) return false
// Reject deliveries older than 5 minutes: replay protection.
const ageSec = Math.floor(Date.now() / 1000) - t
if (Math.abs(ageSec) > 300) return false
const expected = crypto
.createHmac('sha256', secret)
.update(\`\${t}.\${body}\`)
.digest('hex')
// Constant-time comparison.
const expectedBuf = Buffer.from(expected, 'hex')
const actualBuf = Buffer.from(v1, 'hex')
if (expectedBuf.length !== actualBuf.length) return false
return crypto.timingSafeEqual(expectedBuf, actualBuf)
}
\`\`\`
### Python
\`\`\`python
import hmac
import hashlib
import json
import os
import time
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = os.environ["GNUBOK_WEBHOOK_SECRET"].encode("utf-8") # whsec_...
@app.post("/webhook")
def webhook():
raw_body = request.get_data() # bytes: must be the raw request body
sig_header = request.headers.get("X-Gnubok-Signature", "")
if not verify_signature(raw_body, sig_header, SECRET):
abort(400, "invalid signature")
event = json.loads(raw_body)
if already_processed(event["id"]):
return "", 200
handle_event(event)
return "", 200
def verify_signature(body: bytes, header: str, secret: bytes) -> bool:
parts = dict(p.split("=", 1) for p in header.split(","))
try:
t = int(parts["t"])
v1 = parts["v1"]
except (KeyError, ValueError):
return False
# Replay protection: 5-minute window.
if abs(int(time.time()) - t) > 300:
return False
signed = f"{t}.".encode("utf-8") + body
expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1)
\`\`\`
### Common pitfalls
- **Using parsed JSON instead of raw bytes.** Re-serialising the body (\`JSON.stringify(req.body)\`) produces different bytes than Accounted sent: the signature won't match. Capture the raw body before any framework parses it.
- **Forgetting the timestamp window.** Without checking \`t\`, an attacker who captured one signed payload can replay it forever. 5 minutes is our recommended window; tighten if your clock skew is small.
- **Treating retries as duplicates of failure.** Retries arrive when *we* didn't get a 2xx. A 200 response that arrives slowly may not reach us in time and we'll retry: your receiver sees the same \`X-Gnubok-Delivery\` twice. Idempotency is on you.
- **Returning 5xx for application errors.** A 5xx triggers the full retry policy (~87h of attempts). If your handler hit an application bug that won't resolve on retry, return 200 and queue the failure for internal investigation; only return 5xx for genuinely transient problems.
- **Missing \`redirect: 'error'\`-style refusal at receiver level.** If your receiver follows redirects, an attacker who can MITM the response could redirect re-tries to a malicious URL. Modern HTTP clients refuse redirects by default for POST; verify yours does.
## Delivery debugging
Use [\`GET /api/v1/companies/{companyId}/webhooks/{webhookId}/deliveries\`](/docs/api/reference/webhooks#get-webhooks-deliveries-list) to list the recent delivery history for a webhook: every row has the response status, response body (truncated to 4 KB, only \`text/plain\` and \`application/json\` content types persisted), error message, and current state (\`pending\` / \`in_flight\` / \`delivered\` / \`failed\` / \`dead\`).
To replay a \`dead\` or \`delivered\` delivery, call [\`POST /api/v1/webhook-deliveries/{deliveryId}/retry\`](/docs/api/reference/webhooks#post-webhook_deliveries-retry). The retry creates a fresh delivery row pointing at the same payload: the original audit row stays in place. Receivers must be idempotent on the \`X-Gnubok-Delivery\` header.
To send a synthetic test event without driving real state, call [\`POST /api/v1/companies/{companyId}/webhooks/{webhookId}/test\`](/docs/api/reference/webhooks#post-webhooks-test). The dispatcher delivers a \`webhook.test\` event with a static payload immediately, so the outcome is normally visible within a second or two.
## Auto-disable behaviour
The dispatcher disables a webhook (sets \`active=false\` + \`disabled_reason\`) and stops attempting delivery when:
- The receiver returns **HTTP 410 Gone**: explicit "stop sending"
- The receiver returns **HTTP 3xx redirect**: refusing to follow redirects to internal IPs is a security policy; a stable receiver should not return 3xx
- The webhook URL **resolves to a private/loopback/link-local/cloud-metadata IP** at dispatch time (DNS rebinding refusal)
Re-enable with [\`PATCH /api/v1/companies/{companyId}/webhooks/{webhookId}\`](/docs/api/reference/webhooks#patch-webhooks-update) setting \`active: true\`. This clears \`disabled_at\` + \`disabled_reason\` but does NOT replay the deliveries that died while disabled: replay them individually with the retry endpoint.
## Audit + retention
Webhook delivery rows are *behandlingshistorik* (a system-event log) per BFNAR 2013:2 kap 8 §: they are immutable once they reach a terminal state (\`delivered\` or \`dead\`) so the audit trail of who-was-notified-when stays intact. The underlying *räkenskapsinformation* (the verifikation, the faktura, the AGI XML itself) lives in its own table with its own BFL 7 kap retention: webhook delivery rows are NOT räkenskapsinformation and the 7-year retention applies to the underlying record, not to the delivery envelope.
For accounting-event delivery rows (\`journal_entry.*\`, \`period.*\`, \`salary_run.booked\`, \`agi.generated\`, \`invoice.paid\`, \`supplier_invoice.paid\`), Accounted keeps the delivery rows for 7 years. **This is a voluntary operational audit-trail policy Accounted chose because the duration aligns conveniently with BFL 7 kap retention on the underlying records: it is NOT itself a statutory obligation.** The 7-year statutory retention under BFL 7 kap 1 § applies to the underlying verifikation / faktura / AGI XML in its own table, not to the delivery envelope. The integrator's own retention obligations likewise attach to the underlying records you receive (and any local copies you persist), not to the delivery-row metadata.
Deleting a webhook does not delete its delivery history; the FK is \`ON DELETE SET NULL\` so the audit trail survives.
`
+114
View File
@@ -0,0 +1,114 @@
/**
* Shared Markdown renderer for the /docs/api surface.
*
* Two modes:
* - <DocsMarkdown> renders Markdown source as styled JSX inside a docs page.
* - getMarkdownSource() returns the raw string for the sibling .md route handlers.
*
* Stripe-inspired typography rules baked in:
* - Hedvig serif headlines (font-display)
* - Tabular nums on code, monospaced via Geist Mono
* - Hairline horizontal rules between top-level sections
* - Code blocks: paper-white surface, single-pixel border, no shadow
* - Tables: only used by the auto-generated reference; flat hairline rows
*/
import ReactMarkdown from 'react-markdown'
import { cn } from '@/lib/utils'
interface DocsMarkdownProps {
source: string
className?: string
}
export function DocsMarkdown({ source, className }: DocsMarkdownProps) {
return (
<div className={cn('docs-prose', className)}>
<ReactMarkdown
components={{
h1: ({ children }) => (
<h1 className="font-display text-4xl tracking-tight mb-6 mt-2">{children}</h1>
),
h2: ({ children }) => (
<h2 className="font-display text-2xl tracking-tight mt-12 mb-4 pb-2 border-b border-border">
{children}
</h2>
),
h3: ({ children }) => (
<h3 className="font-display text-xl tracking-tight mt-8 mb-3">{children}</h3>
),
h4: ({ children }) => (
<h4 className="text-sm font-medium uppercase tracking-wider text-muted-foreground mt-6 mb-2">
{children}
</h4>
),
p: ({ children }) => (
<p className="text-[15px] leading-7 text-foreground/90 my-4">{children}</p>
),
a: ({ href, children }) => (
<a
href={href}
className="text-foreground underline decoration-muted-foreground/40 underline-offset-4 hover:decoration-foreground transition-colors"
>
{children}
</a>
),
ul: ({ children }) => (
<ul className="my-4 space-y-2 list-disc pl-6 text-[15px] leading-7 text-foreground/90 marker:text-muted-foreground">
{children}
</ul>
),
ol: ({ children }) => (
<ol className="my-4 space-y-2 list-decimal pl-6 text-[15px] leading-7 text-foreground/90 marker:text-muted-foreground">
{children}
</ol>
),
li: ({ children }) => <li className="pl-1">{children}</li>,
code: ({ className: codeClassName, children, ...props }) => {
const isBlock = (codeClassName ?? '').startsWith('language-')
if (isBlock) {
return (
<code className={cn('font-mono text-[13px] leading-6 block', codeClassName)} {...props}>
{children}
</code>
)
}
return (
<code className="font-mono text-[13px] bg-secondary/60 px-1.5 py-0.5 rounded border border-border/60">
{children}
</code>
)
},
pre: ({ children }) => (
<pre className="my-5 p-4 bg-secondary/40 border border-border rounded-lg overflow-x-auto text-[13px] leading-6 font-mono">
{children}
</pre>
),
hr: () => <hr className="my-12 border-border" />,
blockquote: ({ children }) => (
<blockquote className="my-5 pl-4 border-l-2 border-border text-foreground/80 italic">
{children}
</blockquote>
),
strong: ({ children }) => <strong className="font-semibold text-foreground">{children}</strong>,
table: ({ children }) => (
<div className="my-6 overflow-x-auto">
<table className="w-full text-[14px]">{children}</table>
</div>
),
thead: ({ children }) => (
<thead className="border-b border-border">{children}</thead>
),
th: ({ children }) => (
<th className="text-left px-3 py-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
{children}
</th>
),
td: ({ children }) => <td className="px-3 py-2 align-top border-b border-border">{children}</td>,
}}
>
{source}
</ReactMarkdown>
</div>
)
}
+92
View File
@@ -0,0 +1,92 @@
/**
* Single source of truth for the /docs/api sidebar navigation.
*
* Stripe-pattern grouping: top-level sections (Getting started, Cookbooks,
* API reference, Concepts, Errors, Changelog) with nested links. Used by
* the DocsLayout sidebar AND by the landing page resource grid AND by the
* /llms-full.txt aggregator so additions land in every surface from one
* edit.
*/
export interface DocsNavLink {
label: string
href: string
/** Optional one-line summary shown on landing-page cards. */
summary?: string
}
export interface DocsNavSection {
label: string
links: DocsNavLink[]
}
export const DOCS_NAV: DocsNavSection[] = [
{
label: 'Getting started',
links: [
{ label: 'Introduction', href: '/docs/api', summary: 'What the Accounted REST API is and how to authenticate.' },
{ label: 'Quickstart', href: '/docs/api/cookbook/quickstart', summary: 'Send your first invoice in five minutes.' },
{ label: 'Authentication', href: '/docs/api#authentication', summary: 'API keys, scopes, test mode.' },
{ label: 'Connect with Claude', href: '/docs/api/connect-claude', summary: 'Connect Claude via the MCP server: OAuth connector, Claude Code plugin, or npx accounted-mcp bridge.' },
{ label: 'Anslut Claude (svenska)', href: '/docs/api/anslut-claude', summary: 'Samma guide på svenska: OAuth-connector, Claude Code-plugin eller npx accounted-mcp.' },
],
},
{
label: 'Cookbooks',
links: [
{ label: 'Send your first invoice', href: '/docs/api/cookbook/send-first-invoice', summary: 'Create a customer, draft an invoice, send it, mark it paid.' },
{ label: 'Ingest and categorise bank transactions', href: '/docs/api/cookbook/ingest-bank-transactions', summary: 'Push CSV/CAMT into the engine, get AI suggestions, commit.' },
{ label: 'Compute and review a VAT declaration', href: '/docs/api/cookbook/file-vat-declaration', summary: 'Compute momsdeklaration rutor 05-62 and reconcile before manual Skatteverket submission.' },
{ label: 'Run payroll and generate AGI', href: '/docs/api/cookbook/run-payroll-and-agi', summary: 'Calculate, approve, mark paid, book, generate AGI XML for manual Skatteverket upload.' },
{ label: 'Set up webhooks and verify signatures', href: '/docs/api/cookbook/webhooks', summary: 'Subscribe to events, verify HMAC, handle retries idempotently.' },
{ label: 'Year-end closing', href: '/docs/api/cookbook/year-end-closing', summary: 'Lock periods, run year-end, set opening balances.' },
],
},
{
label: 'Concepts',
links: [
{ label: 'Webhooks', href: '/docs/api/webhooks', summary: 'Event types, delivery model, retries, signature verification.' },
{ label: 'Versioning', href: '/docs/api/versioning', summary: 'How API versions are pinned, upgraded, and deprecated.' },
{ label: 'Idempotency', href: '/docs/api/versioning#idempotency', summary: 'Safe retries on every write via Idempotency-Key.' },
{ label: 'Dry-run', href: '/docs/api/versioning#dry-run', summary: 'Preview every write before committing.' },
],
},
{
label: 'API reference',
links: [
{ label: 'Overview', href: '/docs/api/reference', summary: 'All resources, grouped by domain.' },
{ label: 'Companies', href: '/docs/api/reference/companies' },
{ label: 'Customers', href: '/docs/api/reference/customers' },
{ label: 'Invoices', href: '/docs/api/reference/invoices' },
{ label: 'Articles', href: '/docs/api/reference/articles' },
{ label: 'Suppliers', href: '/docs/api/reference/suppliers' },
{ label: 'Supplier invoices', href: '/docs/api/reference/supplier-invoices' },
{ label: 'Transactions', href: '/docs/api/reference/transactions' },
{ label: 'Journal entries', href: '/docs/api/reference/journal-entries' },
{ label: 'Fiscal periods', href: '/docs/api/reference/fiscal-periods' },
{ label: 'Accounts', href: '/docs/api/reference/accounts' },
{ label: 'Documents', href: '/docs/api/reference/documents' },
{ label: 'Inbox items', href: '/docs/api/reference/inbox-items' },
{ label: 'Dimensions', href: '/docs/api/reference/dimensions' },
{ label: 'Employees', href: '/docs/api/reference/employees' },
{ label: 'Salary runs', href: '/docs/api/reference/salary-runs' },
{ label: 'Reports', href: '/docs/api/reference/reports' },
{ label: 'Imports', href: '/docs/api/reference/imports' },
{ label: 'Compliance check', href: '/docs/api/reference/compliance' },
{ label: 'Reconciliation', href: '/docs/api/reference/reconciliation' },
{ label: 'Webhooks', href: '/docs/api/reference/webhooks' },
{ label: 'Operations', href: '/docs/api/reference/operations' },
{ label: 'Voucher gap explanations', href: '/docs/api/reference/voucher-gap-explanations' },
],
},
{
label: 'Reference',
links: [
{ label: 'Errors', href: '/docs/api/errors', summary: 'Every stable error code, status, and remediation.' },
{ label: 'Changelog', href: '/docs/api/changelog', summary: 'Per-version release notes.' },
{ label: 'OpenAPI 3.1 spec', href: '/api/v1/openapi.json', summary: 'Machine-readable spec for client generation.' },
{ label: 'llms.txt', href: '/llms.txt', summary: 'Agent-discoverable index.' },
{ label: 'llms-full.txt', href: '/llms-full.txt', summary: 'Full docs concatenated for LLM ingestion.' },
],
},
]