Files
accounted/lib/bokslut/ixbrl/validate/rules.ts
T
Jakob Wennberg 16fbcefbbc feat(invariants): shared format contracts + upgrade-path CI (#1364)
* feat(invariants): centralise shared format contracts, reconcile the org-number paths

The same format rules were written out independently across the codebase, and
where they disagreed the disagreement was invisible until a filing failed.

Worst case, now fixed: four Skatteverket- and Bolagsverket-bound export paths
each had their own idea of a valid organisationsnummer.

  lib/skatteverket/format.ts      strip '-' only      threw on any input with a space
  lib/salary/ku/ku10-generator.ts replace('-', '')    first hyphen only, spaces survived
  lib/salary/agi/xml-generator.ts strip non-digits    stray letters passed the length check
  lib/bokslut/ixbrl/validate      /^\d{6}-?\d{4}$/    rejected the 12-digit form, no Luhn

A company stored with a space or in 12-digit form could file AGI all year and
then fail at the arsredovisning deadline with a message that did not say why.

lib/invariants/ now owns account number, ISO date, four-digit fiscal year and
org number, each with the rationale recorded next to the rule. normalizeOrgNumber
moves here from lib/company-lookup/ and isSaneDateString from lib/utils.ts; both
old paths re-export, so no caller changes. lib/api/schemas.ts builds its
primitives on the module, so ~100 schemas inherit any correction.

The arsredovisning check-digit verdict is a warn, not an error: a wrong Luhn
digit is almost certainly a typo worth surfacing, but whether every org number
Bolagsverket accepts satisfies Luhn is a Swedish domain question we have not
verified against a primary source, and an error there blocks Skicka in. We do
not block a statutory filing on an unverified assumption.

KU10 still passes a 12-digit stored org number through unfolded. That is
pre-existing, and whether the KU10 schema wants 10 or 12 digits is not covered
by the swedish-payroll skill, so it is pinned by a test rather than changed
silently.

Guard 8 (hand-rolled-invariant) tracks the remaining 114 inline copies as a
ratchet that may only go down, same mechanism as the roundOre guard.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(ci): add an upgrade-path job that applies new migrations against real data

The pg-real job applies all 548 migrations to an EMPTY database. Empty means
zero rows, so a migration that adds a NOT NULL, adds a CHECK, creates a unique
index or backfills passes trivially in CI and can still fail on production,
where the rows exist. CI proved that a fresh install works; nothing proved that
an existing install upgrades.

The new pg-upgrade job: apply the schema as it stands at the merge base, seed a
small real company (three posted verifikat, balanced lines, one ore-level
amount), then apply ONLY the migrations this PR adds, then assert the data
survived (entries still posted, lines intact, ledger still balances, ore
unchanged, voucher numbers sequential). A PR with no migration no-ops.

Verified locally against supabase/postgres:15.8.1.060 rather than assumed, with
three deliberately bad migrations:

  rescale money on posted lines   empty: would pass   seeded: ERROR (immutability trigger)
  CHECK violating the ore row     empty: exit 0       seeded: exit 3
  NOT NULL on a populated column  empty: exit 0       seeded: exit 3

Base migrations are read out of the merge-base git tree, not the working tree,
so a PR that edits an already-shipped migration still gets the original applied
and the edit surfaces as a failure here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs: record the invariants and upgrade-CI decisions

Two entries covering what this PR changes and, more importantly, the calls that
are not obvious from the diff: why the arsredovisning check-digit verdict is a
warning rather than an error, why KU10's 12-digit passthrough is pinned instead
of fixed, and why the ROT/RUT brf org-number schemas stay on their own rule.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(test): mark the upgrade fixture as CI-only, never a production template

The fixture writes posted journal_entries and their lines directly, bypassing
the engine and the atomic commit RPC. That is the only way to hand a migration
pre-existing posted rows to break, and it is safe against a throwaway CI
database, but it reads like a sanctioned pattern to anyone who finds it later.

Says so explicitly, with the reason it is confined here (no voucher sequence to
keep gapless, no retention obligation on a database destroyed with the job) and
a pointer back to Hard Rule 2 for anything touching a real database.

Raised by the Swedish compliance review bot on #1364.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 16:30:14 +02:00

263 lines
11 KiB
TypeScript

/**
* Pre-flight validation of an iXBRL årsredovisning: local mirror of the
* Bolagsverket `kontrollera` service (GUIDE.md Appendix E codes).
*
* Runs on the assembled IxbrlArsredovisningInput BEFORE generation/upload so
* the wizard can surface actionable issues without an API round-trip, and so
* self-hosted installs without Bolagsverket credentials still get the checks.
*
* Severity:
* - 'error' → Bolagsverket would reject or föreläggande is near-certain;
* the wizard blocks Skicka in.
* - 'warn' → kontrollera warn-level utfall; filing is allowed
* (GUIDE §4.2.2) but the user should review.
*/
import type { IxbrlArsredovisningInput } from '../types'
import { isOrgNumberShaped, hasInvalidOrgNumberCheckDigit } from '@/lib/invariants/org-number'
export interface PreflightIssue {
/** Bolagsverket kontrollera code where one exists, else our own ACC-xxx. */
code: string
severity: 'error' | 'warn'
message: string
}
export interface PreflightResult {
issues: PreflightIssue[]
errors: PreflightIssue[]
warnings: PreflightIssue[]
ok: boolean
}
type Rule = (input: IxbrlArsredovisningInput, today: string) => PreflightIssue | null
const issue = (code: string, severity: 'error' | 'warn', message: string): PreflightIssue => ({
code,
severity,
message,
})
function monthsBetween(startIso: string, endIso: string): number {
const start = new Date(`${startIso}T00:00:00Z`)
const end = new Date(`${endIso}T00:00:00Z`)
return (
(end.getUTCFullYear() - start.getUTCFullYear()) * 12 +
(end.getUTCMonth() - start.getUTCMonth()) +
(end.getUTCDate() >= start.getUTCDate() ? 0 : -1)
)
}
const RULES: Rule[] = [
// ---- completeness -------------------------------------------------------
(input) =>
input.company.name.trim().length === 0
? issue('1020', 'error', 'Företagsnamnet saknas i årsredovisningen.')
: null,
// Shared rule (lib/invariants/org-number.ts), so this validator agrees with
// the AGI, KU10 and SRU export paths about what a valid org number is. The
// previous local regex rejected the 12-digit form outright and skipped the
// check digit, so a company stored in 12-digit form could file AGI all year
// and then fail here with a message that did not say why.
(input) => {
const orgNumber = input.company.orgNumber.trim()
if (!isOrgNumberShaped(orgNumber)) {
return issue(
'1035',
'error',
`Organisationsnumret "${input.company.orgNumber}" är inte giltigt (förväntat format NNNNNN-NNNN).`,
)
}
// Warn, not error, deliberately. A wrong check digit is almost certainly a
// typo and Bolagsverket will reject it, so the user should see it. But
// whether every org number Bolagsverket accepts satisfies Luhn is a Swedish
// domain question we have not verified against a primary source, and an
// 'error' here blocks Skicka in. We do not block a statutory filing on an
// unverified assumption: surface it and let the user judge.
if (hasInvalidOrgNumberCheckDigit(orgNumber)) {
return issue(
'1035',
'warn',
`Organisationsnumret "${input.company.orgNumber}" har fel kontrollsiffra. Kontrollera sista siffran.`,
)
}
return null
},
(input) =>
input.forvaltningsberattelse.allmantOmVerksamheten.trim().length === 0
? issue('1051', 'error', 'Förvaltningsberättelsen saknas (Allmänt om verksamheten är tom).')
: null,
(input) => {
const hasRr =
Object.values(input.rr).some((a) => a.current !== 0) ||
input.totals.aretsResultat.current !== 0
return hasRr
? null
: issue('1060', 'warn', 'Resultaträkningen verkar sakna belopp: kontrollera att räkenskapsåret innehåller bokförda transaktioner.')
},
(input) => {
const hasBr = input.totals.tillgangar.current !== 0
return hasBr
? null
: issue('1064', 'warn', 'Balansräkningen verkar sakna belopp (Summa tillgångar är 0).')
},
(input) =>
input.underskrifter.signers.length === 0
? issue('1107', 'error', 'Underskrifter saknas: årsredovisningen måste skrivas under av styrelsen (och ev. VD).')
: null,
(input) =>
input.underskrifter.signers.some(
(signer) => !signer.firstName.trim() || !signer.lastName.trim(),
)
? issue('1201', 'error', 'Det saknas för- eller efternamn på den eller de som skrivit under årsredovisningen.')
: null,
(input) =>
input.underskrifter.signers.some((signer) => !signer.signedDate)
? issue('1214', 'error', 'Datum för underskrifter saknas: alla underskrifter måste ha ett datum.')
: null,
(input) =>
!input.faststallelseintyg.signerFirstName.trim() ||
!input.faststallelseintyg.signerLastName.trim()
? issue('1169', 'error', 'Namnförtydligandet saknas i fastställelseintyget (välj undertecknare).')
: null,
(input) =>
input.faststallelseintyg.arsstammaDatum
? null
: issue('1103', 'error', 'Datum för årsstämman saknas i fastställelseintyget.'),
(input) =>
input.faststallelseintyg.resultatdispositionOutcome
? null
: issue('ACC-AGM-DISP', 'error', 'Årsstämmans beslut om resultatdisposition saknas.'),
(input) =>
input.faststallelseintyg.resultatdispositionOutcome === 'alternative_decision' &&
!input.faststallelseintyg.resultatdispositionDecision?.trim()
? issue(
'ACC-AGM-DISP-TEXT',
'error',
'Årsstämmans alternativa resultatdisposition saknar beslutstext.',
)
: null,
// ---- date ordering ------------------------------------------------------
(input, today) =>
input.period.end >= today
? issue('1015', 'error', `Räkenskapsårets sista dag (${input.period.end}) har inte passerats ännu.`)
: null,
(input) =>
monthsBetween(input.period.start, input.period.end) >= 18
? issue('1046', 'error', `Räkenskapsåret ${input.period.start}: ${input.period.end} är längre än 18 månader.`)
: null,
(input) =>
input.faststallelseintyg.arsstammaDatum &&
input.faststallelseintyg.arsstammaDatum <= input.period.end
? issue('1101', 'error', `Datum för årsstämman (${input.faststallelseintyg.arsstammaDatum}) får inte vara tidigare än eller samma som räkenskapsårets sista dag (${input.period.end}).`)
: null,
(input, today) =>
input.faststallelseintyg.arsstammaDatum !== null &&
input.faststallelseintyg.arsstammaDatum > today
? issue('1178', 'error', `Datum för årsstämman (${input.faststallelseintyg.arsstammaDatum}) får inte vara senare än dagens datum: håll årsstämman innan inlämning.`)
: null,
(input) => {
const bad = input.underskrifter.signers.find(
(signer) => signer.signedDate && signer.signedDate <= input.period.end,
)
return bad
? issue('1114', 'error', `Datum för underskrift (${bad.signedDate}) får inte vara tidigare än eller samma som räkenskapsårets sista dag (${input.period.end}).`)
: null
},
(input) => {
const agm = input.faststallelseintyg.arsstammaDatum
if (!agm) return null
const late = input.underskrifter.signers.find(
(signer) => signer.signedDate && signer.signedDate > agm,
)
return late
? issue('1183', 'error', `Datum för årsstämman (${agm}) är tidigare än styrelsens underskrift (${late.signedDate}).`)
: null
},
(input) => {
const datering = input.underskrifter.dateringsdatum
if (!datering) return null
const earliest = input.underskrifter.signers.reduce<string | null>(
(min, signer) =>
signer.signedDate !== null && (min === null || signer.signedDate < min)
? signer.signedDate
: min,
null,
)
return earliest && datering > earliest
? issue('1232', 'warn', `Datum för årsredovisningen (${datering}) är senare än styrelsens tidigaste underskrift (${earliest}).`)
: null
},
(input) =>
input.faststallelseintyg.arsstammaDatum &&
input.faststallelseintyg.genereratDatum < input.faststallelseintyg.arsstammaDatum
? issue('1165', 'warn', 'Datum för underskrift av fastställelseintyget sätts till genereringsdagen, som ligger före årsstämman: Bolagsverket skriver över datumet vid signering.')
: null,
// ---- balance checks -----------------------------------------------------
// Exact comparisons: Bolagsverket compares the tagged totals exactly, and
// the mapper already absorbs legitimate ±1 kr rounding residuals.
(input) => {
const assets = input.totals.tillgangar.current
const eqLiab = input.totals.egetKapitalSkulder.current
return assets !== eqLiab
? issue('3005', 'error', `"Summa tillgångar" (${assets} kr) och "Summa eget kapital och skulder" (${eqLiab} kr) stämmer inte överens.`)
: null
},
(input) => {
if (input.isFirstFiscalYear) return null
const prev = input.totals.tillgangar.previous
return prev === null
? issue('3006', 'error', 'Jämförelsesiffror saknas i balansräkningen. De behövs om det inte är företagets första räkenskapsår.')
: null
},
(input) => {
if (input.isFirstFiscalYear) return null
const prev = input.totals.aretsResultat.previous
return prev === null
? issue('3007', 'error', 'Jämförelsesiffror saknas i resultaträkningen. De behövs om det inte är företagets första räkenskapsår.')
: null
},
(input) => {
const rrResult = input.totals.aretsResultat.current
const brResult = input.br['AretsResultatEgetKapital']?.current ?? 0
return rrResult !== brResult
? issue('ACC-2099', 'error', `Årets resultat enligt resultaträkningen (${rrResult} kr) stämmer inte med eget kapital-posten Årets resultat (${brResult} kr): kör bokslutet (resultatdisposition) innan inlämning.`)
: null
},
// ---- resultatdisposition ------------------------------------------------
(input) => {
const rd = input.forvaltningsberattelse.resultatdisposition
return Math.abs(rd.utdelning + rd.balanserasINyRakning - rd.summa) > 1
? issue('ACC-DISP', 'error', `Resultatdispositionen går inte ihop: utdelning (${rd.utdelning}) + balanseras (${rd.balanserasINyRakning}) ≠ summa (${rd.summa}).`)
: null
},
(input) => {
const rd = input.forvaltningsberattelse.resultatdisposition
return rd.summa < 0 && rd.utdelning > 0
? issue('ACC-UTD', 'error', 'Utdelning kan inte föreslås när fritt eget kapital är negativt.')
: null
},
]
export function runPreflightChecks(
input: IxbrlArsredovisningInput,
todayIso?: string,
): PreflightResult {
const today = todayIso ?? new Date().toISOString().slice(0, 10)
const issues: PreflightIssue[] = []
for (const rule of RULES) {
const result = rule(input, today)
if (result) issues.push(result)
}
// Mapper warnings (unmapped accounts, reclassifications) ride along as warn.
for (const warning of input.warnings) {
issues.push(issue('ACC-WARN', 'warn', warning))
}
const errors = issues.filter((item) => item.severity === 'error')
const warnings = issues.filter((item) => item.severity === 'warn')
return { issues, errors, warnings, ok: errors.length === 0 }
}