* feat: separate AR/AP/accounting into distinct nav groups (#92) Split the flat "Finans" sidebar group into three visually distinct sections — Försäljning (AR), Inköp (AP), and Redovisning — so users coming from Fortnox immediately find customer invoicing and supplier invoices as top-level concepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: journal entry detail view, correction chain, and account name display - Add journal entry detail page at /bookkeeping/[id] with full entry view - Add correction chain API and component showing storno relationships - Add JournalEntryStatusBadge component for entry status display - Show debit/credit account names in template picker and review dialogs - Expand client-side BAS account name mapping with additional accounts - Show account codes on transaction inbox suggestion buttons Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address review feedback — N+1 query, duplicate name, nav dedup - Batch reverse-lookup into single query per BFS iteration (was N+1) - Differentiate account 2393 from 2893 in display names - Extract shared loop for desktop/mobile nav group rendering Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: counterparty templates, Skatteverket extension, VAT form completeness, and UI cleanup - Add counterparty-based categorization templates (learned from user approvals and auto-ingestion) with fuzzy matching in the mapping engine - Add Skatteverket extension for direct VAT declaration submission via API - Complete VAT declaration form with all 30 SKV 4700 boxes (ruta 08, 35-42, 50, 60-62) - Fix ruta 49 formula to include import VAT (ruta 60+61+62) - Simplify dashboard UI: remove redundant icons from stat cards, customer cards, invoice list, supplier invoices; use Badge variants consistently - Add SkatteverketPanel component to reports page - Add categorization_templates and skatteverket_tokens migrations - Update tests and helpers for new types Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address PR review feedback — VAT detection, migration timestamps, dedup - Fix detectVatTreatment to derive actual rate (12%/6%) from VAT line description instead of hardcoding standard_25 - Rename skatteverket_tokens migration to 20260324120001 to avoid duplicate timestamp with categorization_templates (fixes Supabase deployment failure) - Make refreshAccessToken accept previousRefreshCount param to enforce refresh limit contract at the type level - Fix rate limiter TOCTOU by claiming slot before await - Extract formatRedovisare/formatRedovisningsperiod to shared lib/skatteverket/format.ts — eliminates duplication between mappers.ts and SkatteverketPanel.tsx Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
135 lines
3.7 KiB
TypeScript
135 lines
3.7 KiB
TypeScript
import type { SkatteverketTokens } from '../types'
|
|
|
|
/**
|
|
* Skatteverket OAuth2 helpers for the `per` (BankID) flow.
|
|
*
|
|
* Endpoints:
|
|
* Authorize: GET {base}/authorize
|
|
* Token: POST {base}/token
|
|
*
|
|
* The `per` flow is user-facing BankID authentication.
|
|
* No mTLS required (unlike the `org` flow).
|
|
*/
|
|
|
|
const DEFAULT_OAUTH_BASE_URL = 'https://peroauth2.test.skatteverket.se/oauth2/v1/per'
|
|
const DEFAULT_SCOPES = 'momsdeklaration inkforetag ska skahmst'
|
|
|
|
function getOAuthBaseUrl(): string {
|
|
return process.env.SKATTEVERKET_OAUTH_BASE_URL || DEFAULT_OAUTH_BASE_URL
|
|
}
|
|
|
|
function getClientId(): string {
|
|
const id = process.env.SKATTEVERKET_OAUTH2_CLIENT_ID
|
|
if (!id) throw new Error('SKATTEVERKET_OAUTH2_CLIENT_ID is required')
|
|
return id
|
|
}
|
|
|
|
function getClientSecret(): string {
|
|
const secret = process.env.SKATTEVERKET_OAUTH2_CLIENT_SECRET
|
|
if (!secret) throw new Error('SKATTEVERKET_OAUTH2_CLIENT_SECRET is required')
|
|
return secret
|
|
}
|
|
|
|
/**
|
|
* Build the Skatteverket OAuth2 authorization URL.
|
|
* User is redirected here to authenticate with BankID.
|
|
*/
|
|
export function buildAuthorizeUrl(
|
|
redirectUri: string,
|
|
state: string,
|
|
scope?: string
|
|
): string {
|
|
const base = getOAuthBaseUrl()
|
|
const params = new URLSearchParams({
|
|
client_id: getClientId(),
|
|
response_type: 'code',
|
|
state,
|
|
redirect_uri: redirectUri,
|
|
scope: scope || DEFAULT_SCOPES,
|
|
})
|
|
return `${base}/authorize?${params.toString()}`
|
|
}
|
|
|
|
/**
|
|
* Exchange an authorization code for tokens.
|
|
* Must be called immediately upon receiving the callback — code expires in 5 minutes.
|
|
*/
|
|
export async function exchangeCodeForTokens(
|
|
code: string,
|
|
redirectUri: string
|
|
): Promise<SkatteverketTokens> {
|
|
const base = getOAuthBaseUrl()
|
|
|
|
const body = new URLSearchParams({
|
|
grant_type: 'authorization_code',
|
|
client_id: getClientId(),
|
|
client_secret: getClientSecret(),
|
|
redirect_uri: redirectUri,
|
|
code,
|
|
})
|
|
|
|
const response = await fetch(`${base}/token`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
|
|
body: body.toString(),
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text()
|
|
throw new Error(`Skatteverket token exchange failed (${response.status}): ${text}`)
|
|
}
|
|
|
|
const data = await response.json()
|
|
|
|
return {
|
|
access_token: data.access_token,
|
|
refresh_token: data.refresh_token ?? null,
|
|
expires_at: Date.now() + (data.expires_in ?? 3600) * 1000,
|
|
refresh_count: 0,
|
|
scope: data.scope ?? DEFAULT_SCOPES,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Refresh an access token using a stored refresh token.
|
|
*
|
|
* The `per` flow supports up to 10 refreshes per session.
|
|
* Each refresh returns a NEW refresh_token that must be stored.
|
|
* Refresh tokens are valid for 65 minutes.
|
|
*/
|
|
export async function refreshAccessToken(
|
|
refreshToken: string,
|
|
previousRefreshCount: number
|
|
): Promise<SkatteverketTokens> {
|
|
const base = getOAuthBaseUrl()
|
|
|
|
const body = new URLSearchParams({
|
|
grant_type: 'refresh_token',
|
|
client_id: getClientId(),
|
|
client_secret: getClientSecret(),
|
|
refresh_token: refreshToken,
|
|
})
|
|
|
|
const response = await fetch(`${base}/token`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
|
|
body: body.toString(),
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text()
|
|
throw new Error(`Skatteverket token refresh failed (${response.status}): ${text}`)
|
|
}
|
|
|
|
const data = await response.json()
|
|
|
|
return {
|
|
access_token: data.access_token,
|
|
// Each refresh returns a new refresh_token — must be stored
|
|
refresh_token: data.refresh_token ?? null,
|
|
expires_at: Date.now() + (data.expires_in ?? 3600) * 1000,
|
|
refresh_count: previousRefreshCount + 1,
|
|
scope: data.scope ?? '',
|
|
}
|
|
}
|