Files
accounted/lib/errors/get-error-message.ts
T
Mattsson 87f0d5af48 fix: GH issues batch: deadlines opt-ins, SKV reconnect, narrative edit, payment-link gating (#1076)
* fix(errors): close remaining raw-message leaks after #1048 (#337)

Follow-up to PR #1048. No user-visible toast or response field can now
carry a raw engine or DB message; everything maps through getErrorMessage
or the structured-errors registry.

- get-error-message: only normalize a code-carrying Error instance into
  the structured path when the registry knows the code; unknown codes
  (Node system errors, stray third-party codes, Error-wrapped Postgres
  SQLSTATEs) fall through to pattern match, Swedish check, Postgres map
  and the status/context/generic fallbacks instead of returning the raw
  message. New Swedish-detection pattern for "ar last" phrases and a
  known-pattern row for "already has a journal entry".
- structured-errors: add CANNOT_EDIT_NON_DRAFT (409) and
  MANDATORY_DIMENSION_MISSING (400) rows, plus common Node network codes
  (ECONNREFUSED, ECONNRESET, ETIMEDOUT, ENOTFOUND, EAI_AGAIN, EPIPE) as
  retryable 503 transients with a Swedish message.
- pending-operations commit + bulk-commit routes: map executor error
  strings through getErrorMessage before responding (raw stays in logs);
  Swedish passes through, English falls to status-appropriate Swedish.
- pending page: toast via getErrorMessage, fixing raw English toasts and
  "[object Object]" for structured envelopes on commit/bulk/reject.
- transactions book + journal-entries routes: untyped catch and DB list
  errors no longer return err.message; mapped or static Swedish instead.
- invoice send + issue-credit-note: partial_failures reasons are now
  Swedish (raw provider/DB text logged, never returned).
- Tests: new unknown-code/Error-instance suite, registry rows asserted,
  route tests updated off the pinned raw-English expectations.

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

* fix(skatteverket): target the räkenskapsår for yearly VAT redovisningsperiod

A yearly filer with a broken fiscal year has a Skatteverket period ending
in its FY-end month, not December, and the panel's year state is never
maintained in yearly mode (the year picker is replaced by the
räkenskapsår selector), so calls targeted the wrong period even for
calendar-FY companies filing after year end. The selected fiscal period
now rides through the whole chain: panel query strings, draft/validate/
submit bodies, buildMomsuppgift (which resolves the FY bounds so the
period id and the figures describe the same räkenskapsår), and the
staged-commit path. MCP callers without a fiscal period keep the
calendar fallback.

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

* feat(deadlines): group same-day skattekonto deadlines into one card

Moms, AGI and preliminärskatt legally share the skattekonto date (den
12:e), so a small monthly-moms employer saw 2-3 near-identical rows per
month. Two or more pending system rows of the skattekonto family on the
same due date now render as one grouped card with the date block once
and each obligation as a sub-row keeping its own confirm-to-complete
flow. Presentation only: rows, statuses, ICS feed unchanged.

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

* feat(deadlines): KU + ROT/RUT + long-tail opt-in deadlines, rolling horizon

Follow-ups from the #1028 audit left out of the #1057-#1060 fix stack,
each with its own condition modeling:

- kontrolluppgifter (KU10/KU20/KU31), due 31 Jan (SFL 24 kap. 1 §):
  opt-in flag suggested from ledger signals (2898 utdelning, 2393/2893
  ägarlån; deliberately not 2091, see DECISIONS.md), AB only, mirroring
  the #1059 EU-sales suggest-and-confirm pattern.
- rot_rut_begaran, due 31 Jan after the payment year (Lag 2009:194
  8 §): rows generated only for years with actually PAID ROT/RUT
  invoices, resolved inside the generator; invoice-derived suggestion.
- Long tail, explicit opt-in ('Fler deadlines'): OSS quarterly and IOSS
  monthly with a skipBankingDayAdjustment config flag (EU-law dates
  stand on weekends), Intrastat (10th banking day of the following
  month), punktskatt (ordinary skattedeklaration schedule), and
  fyllnadsinbetalning (12th of 2nd month over 30k / 3rd of 5th month,
  SFL 62:8 + 65 kap.). Kvarskatt deferred: needs a slutskattebesked
  date the app does not hold.
- Rolling generation horizon: recurring types ~6 months ahead, annual
  12 months, mirrored in the backfill expectation keys so the nightly
  cron never thrashes; regeneration now preserves manual in_progress
  status; one-time cleanup migration removes existing far-future rows.

Migrations also applied to the staging branch, together with the
previously missing 20260717xxxxxx deadline migrations (staging had
drifted and lacked dismissed_at).

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

* fix(arsredovisning): keep narrative editable after year-end close

The narrative save endpoint refused writes whenever the fiscal period was
closed/locked, but Verkstall bokslut closes the period before the
arsredovisning text is ever written, so every legitimate save failed with
PERIOD_LOCKED and the PDF fell back to placeholder text.

The narrative is arsredovisning document text (ARL 6 kap.), not journal
rakenskapsinformation, so the bookkeeping period lock does not apply.
Saves are now refused only once a Bolagsverket submission for the period
is registrerad (ARSREDOVISNING_REGISTERED, 409); the filed artifact was
already frozen separately by the submissions immutability trigger.

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

* fix(skatteverket): surface dead SKV connections and nudge reconnect

Prod has ~70 companies that connected Skatteverket before the post-connect
sync fix (#1010) and silently never synced skattekonto: the only reconnect
prompt lived in the settings panel nobody revisits.

- transactions-page banner when the connection is needs_reconsent or
  expired without refresh, linking to /settings/tax
- pre-connect note in the connect panel: approve ALL behorigheter on
  Skatteverket's consent page (previously only shown after a failure)
- wire the inert skattekonto.connection.expired event to an email nudge
  to the token owner; one send per consent episode via claim-first dedup
  in notification_log (type skv_connection_expired, partial unique index
  in migration 20260720090000, applied to staging)

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

* fix(archive): per-year behandlingshistorik covers late-booked vouchers + Drive backup disclaimer

The per-fiscal-year archive filtered audit rows by created_at within the
period, dropping treatment history for bokslut entries, stornos and SIE
imports booked after year end (BFNAR 2013:2 kap 8). The year archive now
unions the date window with every audit row touching the period's journal
entries and lines, deduped by audit id; line rows (company_id NULL by
trigger design) are admitted via a scoped OR and reachable on the
service-role backup path. ARCHIVE_FORMAT_VERSION 2->3 forces a one-time
Drive re-upload so existing archives pick up the complete history. The
Drive card on /import Exportera and the LASMIG texts now state the Drive
copy is a convenience backup, not the BFL 7 kap legal archive.

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

* fix(decisions): clarify Arsredovisning narrative save behavior on submission status

* feat(invoices): gate payment links behind invoice settings opt-in

The payment-link section (manual URL field + Stripe auto-create toggle)
was visible on every invoice and auto-created Stripe links on send for
any connected company. It is now opt-in per company:

- new company_settings.invoice_payment_links_enabled, default false for
  everyone (no grandfathering of Stripe-connected companies)
- invoice editor hides the whole section unless enabled; a draft that
  already carries a link still shows it so old links stay clearable
- enforced server-side in maybeCreatePaymentLinkForInvoice (after the
  provider lookup, so the extension-free core build never queries), so
  dashboard, v1, MCP and recurring sends all obey it
- new toggle on Settings -> Invoicing, saves instantly; sv/en strings

Migration applied to the staging branch; prod gets it on merge.

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

* fix(tests): add invoice_payment_links_enabled to company settings fixture

The makeCompanySettings fixture missed the new required boolean, failing
the core-only build's type check of tests/helpers.ts. Default false,
matching the migration default.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Emil <emilmattsson14@gmail.com>

* fix(review): address CodeRabbit, compliance and Swedish review findings

Round 2 of PR #1076 review feedback, one change per accepted finding:

- pending page: res.json() safe fallback in both commit paths so a
  non-JSON proxy response cannot surface a raw parser error
- bulk-commit: map operation status enums to Swedish display labels in
  the 'Redan hanterad' skip message
- payment-link settings: disable the toggle while a save is in flight
  to prevent out-of-order PUT responses
- deadlines group card: route all UI strings through next-intl
  (deadlines namespace, sv + en)
- archive export: scope the period audit entry lookup to
  posted/reversed, matching the rest of the export
- error tests: assert the exact registry English message for
  ECONNREFUSED to lock the no-leakage contract
- signal routes: log.warn when best-effort lookups swallow a Supabase
  error (forensics), keep fail-closed behavior
- narrative route: document that 'avslutad' submissions deliberately
  stay editable (never registered at Bolagsverket)
- VAT: yearly declarations without an explicit fiscalPeriodId now
  resolve the räkenskapsår ending in the target year from
  fiscal_periods instead of assuming a calendar FY (SFL 26 kap
  10-11 §§); calendar fallback only when no fiscal period exists
- deadlines: IOSS deadline no longer requires vat_registered
  (Art. 369s has no Swedish VAT registration prerequisite)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Emil <emilmattsson14@gmail.com>

---------

Signed-off-by: Emil <emilmattsson14@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 13:38:14 +02:00

537 lines
23 KiB
TypeScript

/**
* Maps raw errors to user-friendly localized messages.
*
* Priority chain:
* 1. Zod validation field errors
* 2. Postgres error code map
* 3. HTTP status code map
* 4. Context-specific fallback
* 5. Generic fallback
*
* Callers can pass an explicit `locale` ('sv' | 'en'). Default 'sv' so existing
* server-side callers (cron, background jobs, logs) keep their current Swedish
* output. UI callers should pass the active locale from useLocale() / getLocale().
*
* Specific domain phrases (locked period, unbalanced voucher, etc.) remain
* Swedish for now: those refer to statutory accounting concepts and English
* users will still see them on Skatteverket-bound surfaces.
*/
import { formatCurrency } from '@/lib/utils'
// Pure module (no next/server): safe for the client bundles this file lives in.
import { formatDimensionValidationIssues } from '@/lib/bookkeeping/dimension-errors'
import { getErrorEntry, hasErrorEntry } from './structured-errors'
type ErrorContext =
| 'invoice'
| 'supplier_invoice'
| 'customer'
| 'article'
| 'supplier'
| 'transaction'
| 'journal_entry'
| 'settings'
| 'auth'
| 'salary'
export type ErrorLocale = 'sv' | 'en'
interface GetErrorMessageOptions {
context?: ErrorContext
statusCode?: number
locale?: ErrorLocale
}
type Bilingual = { sv: string; en: string }
function pick(b: Bilingual, locale: ErrorLocale): string {
return b[locale] ?? b.sv
}
// Postgres error codes -> localized messages
const POSTGRES_ERROR_MAP: Record<string, Bilingual> = {
'23505': { sv: 'En post med samma uppgifter finns redan.', en: 'A record with the same details already exists.' },
'23503': { sv: 'Posten kan inte ändras eftersom den refereras av annan data.', en: 'This record cannot be changed because other data refers to it.' },
'23502': { sv: 'Ett obligatoriskt fält saknas.', en: 'A required field is missing.' },
'42501': { sv: 'Du har inte behörighet att utföra denna åtgärd.', en: 'You do not have permission to perform this action.' },
'42P01': { sv: 'Resursen kunde inte hittas.', en: 'The resource could not be found.' },
'23514': { sv: 'Värdet uppfyller inte de tillåtna kraven.', en: 'The value does not meet the allowed constraints.' },
'40001': { sv: 'En annan ändring pågick samtidigt. Försök igen.', en: 'A concurrent change was in progress. Please try again.' },
'40P01': { sv: 'En konflikt uppstod. Försök igen.', en: 'A conflict occurred. Please try again.' },
'22P02': { sv: 'Ogiltigt värde angavs.', en: 'Invalid value supplied.' },
'22003': { sv: 'Värdet är utanför tillåtet intervall.', en: 'Value is out of allowed range.' },
}
// HTTP status codes -> localized messages
const HTTP_STATUS_MAP: Record<number, Bilingual> = {
400: { sv: 'Förfrågan innehåller ogiltiga uppgifter.', en: 'The request contains invalid data.' },
401: { sv: 'Din session har gått ut. Logga in igen.', en: 'Your session has expired. Please sign in again.' },
403: { sv: 'Du har inte behörighet att utföra denna åtgärd.', en: 'You do not have permission to perform this action.' },
404: { sv: 'Resursen kunde inte hittas.', en: 'The resource could not be found.' },
409: { sv: 'En konflikt uppstod. Ladda om sidan och försök igen.', en: 'A conflict occurred. Reload the page and try again.' },
422: { sv: 'Uppgifterna kunde inte bearbetas. Kontrollera fälten och försök igen.', en: 'The data could not be processed. Check the fields and try again.' },
429: { sv: 'För många förfrågningar. Vänta en stund och försök igen.', en: 'Too many requests. Wait a moment and try again.' },
500: { sv: 'Ett oväntat serverfel uppstod. Försök igen senare.', en: 'An unexpected server error occurred. Please try again later.' },
502: { sv: 'Servern är tillfälligt otillgänglig. Försök igen om en stund.', en: 'The server is temporarily unavailable. Please try again shortly.' },
503: { sv: 'Tjänsten är tillfälligt otillgänglig. Försök igen om en stund.', en: 'The service is temporarily unavailable. Please try again shortly.' },
}
// Context-specific fallbacks
const CONTEXT_FALLBACKS: Record<ErrorContext, Bilingual> = {
invoice: { sv: 'Kunde inte hantera fakturan. Försök igen.', en: 'Could not process the invoice. Please try again.' },
supplier_invoice: { sv: 'Kunde inte hantera leverantörsfakturan. Försök igen.', en: 'Could not process the supplier invoice. Please try again.' },
customer: { sv: 'Kunde inte hantera kunden. Försök igen.', en: 'Could not process the customer. Please try again.' },
article: { sv: 'Kunde inte hantera artikeln. Försök igen.', en: 'Could not process the article. Please try again.' },
supplier: { sv: 'Kunde inte hantera leverantören. Försök igen.', en: 'Could not process the supplier. Please try again.' },
transaction: { sv: 'Kunde inte hantera transaktionen. Försök igen.', en: 'Could not process the transaction. Please try again.' },
journal_entry: { sv: 'Kunde inte hantera verifikationen. Försök igen.', en: 'Could not process the journal entry. Please try again.' },
settings: { sv: 'Kunde inte spara inställningarna. Försök igen.', en: 'Could not save settings. Please try again.' },
auth: { sv: 'Ett fel uppstod vid inloggningen. Försök igen.', en: 'An error occurred while signing in. Please try again.' },
salary: { sv: 'Kunde inte hantera löneuppgifterna. Försök igen.', en: 'Could not process the payroll data. Please try again.' },
}
const GENERIC_FALLBACK: Bilingual = { sv: 'Något gick fel. Försök igen.', en: 'Something went wrong. Please try again.' }
// Known error patterns → user-friendly Swedish messages
const ERROR_PATTERN_MAP: [RegExp, string | null][] = [
[
/locked\/closed fiscal period/i,
'Perioden är låst. Verifikationen kan inte skapas i en stängd eller låst period.',
],
[
/Bokföringen är låst t\.o\.m\./,
null, // null = extract the Swedish message directly from the raw error text
],
[
/Cannot attach documents to entries in a locked/i,
'Kan inte bifoga dokument till verifikationer i en låst period.',
],
[
/Entry date .+ is outside fiscal period/i,
'Datumet ligger utanför det valda räkenskapsåret.',
],
[
/Only company owners and admins can delete vouchers/i,
'Endast ägare och administratörer kan radera verifikationer.',
],
[
/Journal entry not found/i,
'Verifikationen kunde inte hittas.',
],
[
/Only posted entries can be deleted/i,
'Endast bokförda verifikationer kan raderas.',
],
[
/Cannot delete voucher in a closed fiscal period/i,
'Verifikationen kan inte raderas: räkenskapsåret är stängt.',
],
[
/Cannot delete voucher in a locked fiscal period/i,
'Verifikationen kan inte raderas: perioden är låst.',
],
[
/Cannot delete: other entries reference this voucher/i,
'Verifikationen kan inte raderas eftersom andra verifikationer (t.ex. storno eller rättelse) refererar till den.',
],
[
/timed out after \d+m?s/i,
'Anslutningen mot tjänsten tog för lång tid. Försök igen.',
],
[
/already has a journal entry/i,
'Transaktionen är redan bokförd. Ångra kategoriseringen om du vill ändra den.',
],
]
/**
* Check if a message matches a known error pattern and return the Swedish translation.
* Returns null if no pattern matches.
*/
function tryMatchKnownError(message: string): string | null {
for (const [pattern, translation] of ERROR_PATTERN_MAP) {
if (pattern.test(message)) {
if (translation !== null) return translation
// Extract the Swedish part from the message
const match = message.match(/Bokföringen är låst t\.o\.m\. [^.]+\./)
return match ? match[0] : 'Bokföringen är låst för denna period.'
}
}
return null
}
/**
* Simple heuristic to detect already-translated Swedish messages.
* If the message contains common Swedish words/patterns, pass it through.
*/
function isSwedishUserMessage(message: string): boolean {
const swedishPatterns = [
/kunde inte/i,
/försök igen/i,
/ogiltigt?/i,
/saknas/i,
/saknar/i,
/krävs/i,
/måste/i,
/redan finns/i,
/gick fel/i,
/valideringsfel/i,
/korrigera/i,
/bankuppgifter/i,
/behörighet/i,
/session/i,
/förfrågan/i,
/obligatorisk/i,
/är låst/i,
/fält/i,
/värde/i,
/felaktig/i,
/för (lång|kort|stor|liten|många|få)/i,
/bankgiro/i,
/personnummer/i,
/kontonummer/i,
/clearingnummer/i,
/nummer är/i,
/tillgängligt/i,
]
return swedishPatterns.some((p) => p.test(message))
}
/**
* Extract a user-friendly message from a Zod validation error shape.
* Returns null if the error is not a Zod error.
*/
function tryParseZodErrors(error: unknown): string | null {
if (typeof error !== 'object' || error === null) return null
const obj = error as Record<string, unknown>
// Check for Zod-style field errors: { fieldName: ["message"] } or { issues: [...] }
if (Array.isArray(obj.issues)) {
const issues = obj.issues as Array<{ message?: string; path?: string[] }>
const messages = issues
.slice(0, 3)
.map((issue) => {
const field = issue.path?.join('.') || ''
const msg = issue.message || 'ogiltigt värde'
return field ? `${field}: ${msg}` : msg
})
if (messages.length > 0) return messages.join('. ')
}
// Check for { errors: [{ field, message, code }] } shape from validateBody
if (Array.isArray(obj.errors)) {
const items = obj.errors as Array<{ field?: string; message?: string }>
const messages = items
.slice(0, 3)
.map((it) => {
const field = it.field || ''
const msg = it.message || 'ogiltigt värde'
return field ? `${field}: ${msg}` : msg
})
.filter(Boolean)
if (messages.length > 0) return messages.join('. ')
}
// Check for { errors: { field: ["msg"] } } shape (legacy)
if (typeof obj.errors === 'object' && obj.errors !== null) {
const fieldErrors = obj.errors as Record<string, string[]>
const messages: string[] = []
for (const [field, msgs] of Object.entries(fieldErrors)) {
if (Array.isArray(msgs) && msgs.length > 0) {
messages.push(`${field}: ${msgs[0]}`)
}
if (messages.length >= 3) break
}
if (messages.length > 0) return messages.join('. ')
}
return null
}
/**
* Get a user-friendly Swedish error message from a raw error.
*
* @param error - The raw error. Can be an API response body (object), Error instance, string, or unknown.
* @param options - Optional context and HTTP status code.
*/
export function getErrorMessage(
error: unknown,
options: GetErrorMessageOptions = {}
): string {
const { context, statusCode, locale = 'sv' } = options
// 1. If it's a string, check if it's already Swedish or matches a known pattern
if (typeof error === 'string' && error.trim()) {
if (isSwedishUserMessage(error)) return error
const knownError = tryMatchKnownError(error)
if (knownError) return knownError
}
// 2. If it's an object, try various parsing strategies
if (typeof error === 'object' && error !== null) {
const obj = error as Record<string, unknown>
// Bare envelope inner-error shape: { code, message, message_en?, ... }.
// Happens when a caller forwards `result.error` (the inner object) instead
// of the whole `result`. Pick the English variant when the UI locale is
// English; otherwise fall back to the Swedish `message`.
if (typeof obj.code === 'string' && typeof obj.message === 'string' && obj.message.trim()) {
// Typed domain exceptions (lib/bookkeeping/errors.ts classes) also match
// this shape, but their `message` is raw English (often a DB constraint
// string) and must never reach the user verbatim. Normalize the instance
// into the structured envelope so the per-code branches below own the
// translation. Class fields are enumerable own props, so { ...obj }
// carries exactly the details those branches expect (totalDebit,
// lockDate, reason, issues, ...), while the non-enumerable Error.message
// stays out of details. Plain objects (forwarded inner envelopes,
// PostgrestError-shaped literals) keep the passthrough behavior.
if (error instanceof Error) {
// Only recurse when the registry knows the code: the structured
// branches then own the translation. An unknown code (a Node system
// error like ECONNREFUSED, a Postgres SQLSTATE on a wrapped Error, a
// stray third-party code) would fall out of the structured path with
// its raw English message, so instead fall through to the plain
// handling below: Postgres map, known patterns, Swedish check, and
// finally the status/context/generic fallbacks.
if (hasErrorEntry(obj.code)) {
return getErrorMessage(
{
error: {
code: obj.code,
message: obj.message,
account_numbers: (obj as { accountNumbers?: unknown }).accountNumbers,
details: { ...obj },
},
},
options
)
}
} else {
if (locale === 'en' && typeof obj.message_en === 'string' && obj.message_en.trim()) {
return obj.message_en
}
return obj.message
}
}
// Structured application error: { error: { code, message, message_en?, ... } }
if (typeof obj.error === 'object' && obj.error !== null) {
const structured = obj.error as {
code?: unknown
message?: unknown
message_en?: unknown
account_numbers?: unknown
details?: unknown
}
// For English UI, return the registry's English message for any known
// code instead of falling through to the Swedish branches below (which
// ignored locale: English users were shown Swedish prose). The Swedish
// path is left entirely unchanged; codes absent from the registry still
// fall through. The dynamic branches (amounts / lock date / reason) keep
// owning Swedish display.
if (locale === 'en' && typeof structured.code === 'string') {
const entry = getErrorEntry(structured.code)
if (entry?.message_en) return entry.message_en
}
if (structured.code === 'ACCOUNTS_NOT_IN_CHART' && Array.isArray(structured.account_numbers)) {
const numbers = structured.account_numbers as string[]
return `Följande konton behöver aktiveras: ${numbers.join(', ')}`
}
if (structured.code === 'JOURNAL_ENTRY_NOT_BALANCED') {
const details = structured.details as { totalDebit?: number; totalCredit?: number } | undefined
if (details && typeof details.totalDebit === 'number' && typeof details.totalCredit === 'number') {
return `Verifikationen balanserar inte (${formatCurrency(details.totalDebit)} debet vs ${formatCurrency(details.totalCredit)} kredit).`
}
return 'Verifikationen balanserar inte. Kontrollera att debet och kredit är lika stora.'
}
if (structured.code === 'FISCAL_PERIOD_NOT_FOUND') {
return 'Räkenskapsperioden kunde inte hittas.'
}
if (structured.code === 'ENTRY_DATE_OUTSIDE_FISCAL_PERIOD') {
return 'Datumet ligger utanför det valda räkenskapsåret.'
}
if (structured.code === 'JOURNAL_ENTRY_NOT_FOUND') {
return 'Verifikationen kunde inte hittas.'
}
if (structured.code === 'CANNOT_REVERSE_NON_POSTED') {
return 'Endast bokförda verifikationer kan stornas.'
}
if (structured.code === 'CANNOT_CORRECT_NON_POSTED') {
return 'Endast bokförda verifikationer kan rättas.'
}
if (structured.code === 'ENTRY_ALREADY_REVERSED') {
return 'Verifikationen har redan stornats av en annan användare. Ladda om sidan och försök igen.'
}
if (structured.code === 'CURRENCY_REVALUATION_ALREADY_EXISTS') {
return 'En valutaomvärdering finns redan för denna period.'
}
if (structured.code === 'INVALID_MAPPING_RESULT') {
return 'Kontering saknas för transaktionen. Kontrollera bokföringsreglerna.'
}
if (structured.code === 'DIMENSION_VALIDATION_FAILED') {
// Prefer reconstructing the per-code Swedish sentences from the
// machine-readable issue list (present on both the dashboard and the
// v1/registry error envelopes); fall back to the message, which the
// engine already emits in Swedish naming the offending codes.
const details = structured.details as { issues?: unknown } | undefined
const formatted = formatDimensionValidationIssues(details?.issues)
if (formatted) return formatted
if (typeof structured.message === 'string' && structured.message.trim()) {
return structured.message
}
return 'Ett angivet kostnadsställe/projekt finns inte i dimensionsregistret eller är arkiverat. Skapa värdet i registret först.'
}
if (structured.code === 'NO_OPEN_PERIOD_FOR_DATE') {
return 'Det finns ingen räkenskapsperiod som täcker det valda datumet. Skapa eller öppna räkenskapsåret först.'
}
if (structured.code === 'TARGET_PERIOD_CLOSED') {
return 'Räkenskapsåret för det valda datumet är stängt (bokslut) och kan inte återöppnas. Bokför rättelsen i innevarande period istället.'
}
if (structured.code === 'TARGET_PERIOD_LOCKED') {
const details = structured.details as { lockDate?: string } | undefined
return details?.lockDate
? `Räkenskapsperioden för det valda datumet är låst (t.o.m. ${details.lockDate}). Lås upp perioden för att flytta verifikationen dit.`
: 'Räkenskapsperioden för det valda datumet är låst. Lås upp perioden för att flytta verifikationen dit.'
}
if (structured.code === 'OB_COMPANY_LOCK_DATE') {
const details = structured.details as { lockDate?: string } | undefined
return details?.lockDate
? `Bokföringen är låst t.o.m. ${details.lockDate} och ingående balanser kan inte korrigeras. Ta bort eller flytta låsdatumet under Inställningar → Bokföring och försök igen.`
: 'Bokföringen är låst av företagets låsdatum och ingående balanser kan inte korrigeras. Ta bort eller flytta låsdatumet under Inställningar → Bokföring och försök igen.'
}
if (structured.code === 'MEANINGLESS_CORRECTION') {
const details = structured.details as { reason?: string } | undefined
if (details?.reason === 'no_date_change') {
return 'Det nya datumet är samma som det nuvarande: det finns inget att flytta.'
}
if (details?.reason === 'identical_to_original') {
return 'Rättelsen är identisk med originalverifikationen: inget har ändrats.'
}
return 'Rättelsen saknar ekonomisk innebörd: varje konto netto till noll. En rättelse måste beskriva en faktisk affärshändelse (BFL 5 kap. 5 §).'
}
if (structured.code === 'BOOKKEEPING_DATABASE_ERROR') {
// A DB-layer error may carry a user-relevant cause (e.g. period lock
// trigger). Try the known-pattern map before falling back to the
// generic "kunde inte sparas" message.
if (typeof structured.message === 'string') {
const matched = tryMatchKnownError(structured.message)
if (matched) return matched
}
return 'Verifikationen kunde inte sparas. Försök igen.'
}
if (locale === 'en' && typeof structured.message_en === 'string' && structured.message_en.trim()) {
return structured.message_en
}
if (typeof structured.message === 'string' && structured.message.trim()) {
// Known codes without a dynamic branch above (e.g. CANNOT_REVERSE_STORNO)
// carry raw English engine messages: prefer the registry's Swedish
// message so no typed code surfaces English in a Swedish UI.
if (locale === 'sv' && typeof structured.code === 'string' && !isSwedishUserMessage(structured.message)) {
const entry = getErrorEntry(structured.code)
if (entry?.message_sv) return entry.message_sv
}
return structured.message
}
}
// Accumulated per-item validation list from routes that collect several
// problems before responding, e.g. the salary approve route:
// { error: 'Valideringsfel …', details: ['Tomas Tysén: Bankuppgifter saknas …', …] }
// Surface the specific reasons: otherwise this shape falls all the way
// through to the generic HTTP-400 message and the user learns nothing.
if (
Array.isArray(obj.details) &&
obj.details.length > 0 &&
obj.details.every((d) => typeof d === 'string' && d.trim() !== '')
) {
const items = (obj.details as string[]).map((d) => d.trim())
const shown = items.slice(0, 5).join(' • ')
const more = items.length > 5 ? ` (+${items.length - 5} till)` : ''
const lead = typeof obj.error === 'string' && obj.error.trim() ? `${obj.error.trim()}: ` : ''
return `${lead}${shown}${more}`
}
// Try Zod validation errors
const zodMessage = tryParseZodErrors(obj)
if (zodMessage) return zodMessage
// Try Postgres error code
if (typeof obj.code === 'string' && POSTGRES_ERROR_MAP[obj.code]) {
return pick(POSTGRES_ERROR_MAP[obj.code], locale)
}
// Try known error patterns (e.g. locked period triggers)
for (const field of ['error', 'message'] as const) {
if (typeof obj[field] === 'string' && obj[field].trim()) {
const knownError = tryMatchKnownError(obj[field])
if (knownError) return knownError
}
}
// Try error.message if it's already a good Swedish message
if (typeof obj.error === 'string' && obj.error.trim()) {
if (isSwedishUserMessage(obj.error)) return obj.error
}
if (typeof obj.message === 'string' && obj.message.trim()) {
if (isSwedishUserMessage(obj.message)) return obj.message
}
}
// 3. Error instance
if (error instanceof Error && error.message.trim()) {
const knownError = tryMatchKnownError(error.message)
if (knownError) return knownError
if (isSwedishUserMessage(error.message)) return error.message
}
// 4. HTTP status code map
if (statusCode && HTTP_STATUS_MAP[statusCode]) {
return pick(HTTP_STATUS_MAP[statusCode], locale)
}
// 5. Context-specific fallback
if (context && CONTEXT_FALLBACKS[context]) {
return pick(CONTEXT_FALLBACKS[context], locale)
}
// 6. Generic fallback
return pick(GENERIC_FALLBACK, locale)
}
/**
* Helper that parses a Response body and returns a user-friendly error message.
*/
export async function getResponseErrorMessage(
response: Response,
context?: ErrorContext,
locale?: ErrorLocale,
): Promise<string> {
try {
const body = await response.json()
return getErrorMessage(body, { context, statusCode: response.status, locale })
} catch {
return getErrorMessage(null, { context, statusCode: response.status, locale })
}
}