docs(api): correct /docs/api against the v1 implementation (#999)
Audited every endpoint, param, header, request/response field, error code, and webhook event in the public API docs against the v1 implementation and fixed the drift; addressed two rounds of CodeRabbit review. - Error envelope, idempotency, dry-run, and reversal-field corrections. - Registered the missing articles/dimensions/inbox-items reference resources. - Cookbook fixes: removed nonexistent endpoints, corrected params/fields, fixed the test-key vs live-key quickstart flow and the year-end lock/close sequence. - Webhooks/changelog: retry window ~87h (incl. route metadata), shipped-vs- coming-soon, counts, API-key format, previous_attributes. - export-docs-to-website.mts absolutises app-served links for the website. The gnubok-website side is on branch docs/api-correctness (already deployed). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
This commit is contained in:
@@ -32,7 +32,7 @@ registerEndpoint({
|
||||
doNotUseFor:
|
||||
'Smoke-testing the dispatcher itself (use a real event). Replaying a failed delivery (use POST /webhook-deliveries/{id}/retry).',
|
||||
pitfalls: [
|
||||
'Test deliveries follow the same retry policy as real events: a 500 from your receiver will retry 7 times over ~72h. Use a 2xx ack-only handler if you want a clean signal.',
|
||||
'Test deliveries follow the same retry policy as real events: a 500 from your receiver will retry 7 times over ~87h (about 3.6 days). Use a 2xx ack-only handler if you want a clean signal.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
|
||||
@@ -46,7 +46,7 @@ registerEndpoint({
|
||||
description:
|
||||
'Returns the current snapshot of a v1 async operation: status (queued / running / succeeded / failed / cancelled), progress (jsonb, free-form), result (on success), and error (on failure). The operation_id is returned by the POST endpoints that initiate async work (period close, year-end, currency revaluation, SIE import).',
|
||||
useWhen:
|
||||
'You started an async operation and need to know whether it has finished. Poll every 5-30 seconds; switch to the `operation.completed` webhook for production integrations.',
|
||||
'You started an async operation and need to know whether it has finished. Poll every 5-30 seconds until a terminal status. (The 202 response advertises `operation.completed` as the eventual push signal, but that webhook event is not deliverable yet — polling is the only supported completion signal today.)',
|
||||
doNotUseFor:
|
||||
'Fetching the resource the operation produced: once status=succeeded, read the result field or call the resource-specific GET endpoint. Cancelling a running operation (no cancel endpoint exists in v1).',
|
||||
pitfalls: [
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -73,7 +73,7 @@ export function buildErrorReferenceMd(): string {
|
||||
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 anchor for that specific code.`)
|
||||
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('')
|
||||
@@ -83,18 +83,15 @@ export function buildErrorReferenceMd(): string {
|
||||
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(' "remediation": {')
|
||||
lines.push(' "description": "Unlock via /fiscal-periods/{id}/unlock or pick an open period.",')
|
||||
lines.push(' "tool": "fiscal_periods.unlock"')
|
||||
lines.push(' },')
|
||||
lines.push(' "details": { "fiscal_period_id": "..." },')
|
||||
lines.push(' "docs_url": "https://app.gnubok.se/docs/api/errors#period_locked"')
|
||||
lines.push(' },')
|
||||
lines.push(' "meta": { "request_id": "req_...", "api_version": "..." }')
|
||||
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); \`remediation\` (when present) hints at the canonical fix and may include a \`tool\` reference into the MCP surface.`)
|
||||
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) {
|
||||
|
||||
@@ -4,7 +4,7 @@ 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 lets you do anything the dashboard can do: 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.
|
||||
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. attaching employees to a salary run — 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.
|
||||
|
||||
@@ -24,7 +24,7 @@ Create keys in the accounted dashboard at **/settings/api**. Two key prefixes ar
|
||||
|
||||
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, returned in \`X-RateLimit-*\` headers.
|
||||
Rate limit: 100 requests per minute per key.
|
||||
|
||||
## Base URL
|
||||
|
||||
@@ -74,7 +74,7 @@ Every response has the same shape:
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
Errors swap \`data\` for \`error\`:
|
||||
Errors return an \`error\` object instead of \`data\` (and carry no \`meta\` block — the \`request_id\` moves inside \`error\`):
|
||||
|
||||
\`\`\`json
|
||||
{
|
||||
@@ -82,11 +82,11 @@ Errors swap \`data\` for \`error\`:
|
||||
"code": "PERIOD_LOCKED",
|
||||
"message": "Den valda perioden är låst.",
|
||||
"message_en": "The selected period is locked.",
|
||||
"remediation": { "description": "Unlock via /fiscal-periods/{id}/unlock or pick an open period.", "tool": "fiscal_periods.unlock" },
|
||||
"details": { "fiscal_period_id": "..." },
|
||||
"docs_url": "https://app.gnubok.se/docs/api/errors#period_locked"
|
||||
},
|
||||
"meta": { "request_id": "req_...", "api_version": "${API_V1_VERSION}" }
|
||||
"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_..."
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ 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) },
|
||||
@@ -44,10 +45,12 @@ const RESOURCES: ResourceGroup[] = [
|
||||
{ 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 (11 formats).', matcher: (p) => /\/imports(\/|$)/.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) },
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -57,6 +57,7 @@ export const DOCS_NAV: DocsNavSection[] = [
|
||||
{ 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' },
|
||||
@@ -64,6 +65,8 @@ export const DOCS_NAV: DocsNavSection[] = [
|
||||
{ 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' },
|
||||
|
||||
@@ -28,7 +28,7 @@ import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('webhooks/dispatcher')
|
||||
|
||||
/** 7 retries over ~72h. Index = attempts BEFORE this one. */
|
||||
/** 7 retries over ~87h (≈3.6 days). Index = attempts BEFORE this one. */
|
||||
const RETRY_BACKOFF_SECONDS: ReadonlyArray<number> = [
|
||||
60, // 1m: first retry
|
||||
5 * 60, // 5m
|
||||
|
||||
@@ -28,6 +28,18 @@ if (!buildErrorReferenceMd || !buildResourcePages || !buildReferenceOverviewMd)
|
||||
|
||||
const WEBSITE = resolve('/Users/jakobwennberg/gnubok-website')
|
||||
|
||||
/**
|
||||
* The website is served from www.accounted.se while the API (and everything
|
||||
* under /api/v1 and /.well-known) lives on app.gnubok.se — root-relative links
|
||||
* to app-served resources would 404 on the website, so absolutise them.
|
||||
*/
|
||||
const APP_ORIGIN = 'https://app.gnubok.se'
|
||||
function adaptForWebsite(md: string): string {
|
||||
return md
|
||||
.replaceAll('](/api/v1/', `](${APP_ORIGIN}/api/v1/`)
|
||||
.replaceAll('](/.well-known/', `](${APP_ORIGIN}/.well-known/`)
|
||||
}
|
||||
|
||||
function write(rel: string, content: string) {
|
||||
const out = resolve(WEBSITE, rel)
|
||||
mkdirSync(dirname(out), { recursive: true })
|
||||
@@ -35,13 +47,13 @@ function write(rel: string, content: string) {
|
||||
console.log(`wrote ${out} (${content.length} chars)`)
|
||||
}
|
||||
|
||||
const errorsMd = buildErrorReferenceMd()
|
||||
const errorsMd = adaptForWebsite(buildErrorReferenceMd())
|
||||
write(
|
||||
'lib/docs/content/errors.generated.ts',
|
||||
`// AUTO-GENERATED from erp-base: do not hand-edit.\n// Regenerate via \`npx tsx scripts/export-docs-to-website.mts\` in erp-base.\nexport const ERRORS_MD = ${JSON.stringify(errorsMd)}\n`,
|
||||
)
|
||||
|
||||
const refOverview = buildReferenceOverviewMd()
|
||||
const refOverview = adaptForWebsite(buildReferenceOverviewMd())
|
||||
const refPages = buildResourcePages()
|
||||
const slugs = refPages.map((p: { slug: string }) => p.slug)
|
||||
|
||||
@@ -49,7 +61,7 @@ const pagesPayload = refPages.map((p: { slug: string; label: string; description
|
||||
slug: p.slug,
|
||||
label: p.label,
|
||||
description: p.description,
|
||||
markdown: p.markdown,
|
||||
markdown: adaptForWebsite(p.markdown),
|
||||
}))
|
||||
|
||||
write(
|
||||
@@ -59,7 +71,7 @@ write(
|
||||
)} as const\n\nexport const RESOURCE_PAGES: ResourcePage[] = ${JSON.stringify(pagesPayload, null, 2)}\n\nexport function findResourcePage(slug: string): ResourcePage | undefined {\n return RESOURCE_PAGES.find((p) => p.slug === slug)\n}\n`,
|
||||
)
|
||||
|
||||
const connectClaudeMd = connectClaude.CONNECT_CLAUDE_MD
|
||||
const connectClaudeMd = connectClaude.CONNECT_CLAUDE_MD && adaptForWebsite(connectClaude.CONNECT_CLAUDE_MD)
|
||||
if (!connectClaudeMd) {
|
||||
console.error('Missing CONNECT_CLAUDE_MD export. Inspect:', { connectClaudeKeys: Object.keys(connectClaude) })
|
||||
process.exit(1)
|
||||
|
||||
Reference in New Issue
Block a user