Files
accounted/lib/skatteverket/skattekonto-ocr.ts
T
MattssonandClaude Fable 5.1 26e29f47bc feat(company): ideell förening as a third legal form, behind a flag (#2072 step 1) (#2423)
* feat(company): ideell förening as a third legal form, behind a flag (#2072 step 1)

Why the problem occurred: the legal form was modelled as a binary flag in
~300 files. `EntityType` was a two-member union, but nothing dispatched on it
exhaustively: 28 sites defaulted `?? 'enskild_firma'` (invoice, categorize,
match, stripe, invoice-inbox) or `?? 'aktiebolag'` (year-end, bokslut,
MCP), and every form-dependent choice was an `=== 'aktiebolag' ? A : B`
ternary. Widening the union compiled everywhere and changed nothing, so a
förening would have booked as an enskild firma in the app and as an
aktiebolag in bokslut and MCP, with no error anywhere. The lookup refused
föreningar at the door (mapEntityType returned null), which is what the
tester hit.

What was removed or simplified: the silent defaults. One module,
lib/company/entity-type.ts, now holds the list (ENTITY_TYPES), the parser
(never defaults), the resolver (settings hint, then companies.entity_type,
then throw) and `byEntityType`, whose Record arms make the compiler refuse
the next widening until each site has an answer. The form-dependent facts
(closing account, owner settlement account, calendar-year lock, default
method, K1/K2 label, personnummer vs 16-prefix) live there once instead of
in the ternaries. On the SQL side supported_entity_types() replaces four
copies of the literal list in the create RPCs.

Why this shape and not the proposed one: the tracker asked for the enum
widening plus a chart; that alone was the dangerous version (compiles, books
wrong). Bundling stiftelse was considered and dropped: identical plumbing but
no chart block. Creation sits behind NEXT_PUBLIC_IDEELL_FORENING_ENABLED so
the CHECK, RPCs and seed can ship now and the first partner is switched on
without a migration; the flag goes when Phase 2 (packs, INK3, årsbokslut,
Swish) lands on the tracker.

Domain choices (DECISIONS.md 2026-09-08, verify with an accountant before
Phase 2): result closes to 2069 with 2068 as prior-year carry; no owner
accounts, member settlement on 2890; accrual default; brutet räkenskapsår
allowed; K1 label for the 5 000 kr accrual threshold (BFNAR 2010:1); org
number gets the 16 prefix.

Migration 20260908110835 widens the three CHECK constraints, adds
supported_entity_types(), re-creates the three create RPCs with the widened
guard and adds the förening block to seed_chart_of_accounts. Applied to
staging and covered by ideell-forening-entity-type.pg.test.ts.

Part of #2072

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh

* fix(company): close the förening paths the skeptic refuted (#2072)

Five refutations from the /skeptic pass on 7a05c54d2, each fixed at the
shared definition rather than the reported site:

1. Privately paid supplier invoices and the utlägg dialog resolved the owner
   account in lib/expenses/payer.ts with its own AB/EF ternary, so a förening
   member's invoice was built on 2893 and then refused by the expense-claim
   service (which already said 2890), burning an ankomstnummer. The helper now
   uses ownerSettlementAccount.
2. Booking templates substitute their `_ab` accounts only for an aktiebolag;
   the `private_expense` template kept its base 2013 for a förening. Template
   accounts now resolve through templateAccountForForm: EF base, AB override,
   förening base with owner accounts translated to 2890 (booking-templates.ts
   and proposal-lines.ts share it).
3. A VAT-registered förening with helårsmoms got no momsdeklaration deadline:
   the annual VAT rule bailed on anything but AB/EF. A förening is a juridisk
   person and follows the räkenskapsår schedule (SFL 26 kap 33 §), so the rule
   now keys on fiscalYearLockedToCalendar instead of the two literals; same in
   the MCP VAT report.
4. 2069 would have accumulated across years: the year-open omföring was
   AB-only with 2099/2098 hard-coded. planResultAppropriation now takes the
   pair from resultClosingAccounts (AB 2099 -> 2098, förening 2069 -> 2068)
   and skips forms with no carry (EF).
5. With the flag off, a registry lookup that returned "Ideell förening" was
   prefilled into the onboarding journey, the form picker was skipped and the
   create step answered "Ogiltig företagsform" with no way back. The
   journey, the BankID picker, the onboarding page and the MCP lookup now use
   mapSetupEntityType, which maps only creatable forms, so a flagged-off form
   falls through to the picker as before.

Also: form picker keeps its AB-first order; tests for each fix.

Part of #2072

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh

* chore(migrations): move ideell förening migration after main's latest version (20260908143051)

Two migrations landed on main after the branch forked; a lower version
would be skipped by the merge-time apply. Staging history row renamed to
match.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh

* chore(skills): regenerate accounted-api reference for the widened entity_type enum

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 14:47:50 +02:00

110 lines
4.2 KiB
TypeScript

/**
* OCR-nummer for Skatteverket Skattekonto payments.
*
* Companies pay tax (skatt + arbetsgivaravgifter + F-skatt + slutlig skatt etc.)
* to Bankgiro 5050-1055 with an OCR reference. The reference identifies which
* Skattekonto receives the credit; Skatteverket applies it to the most recent
* declared liability.
*
* Format (per Skatteverket "Referensnummer (OCR) för inbetalning till
* skattekonto"):
* - The person-, samordnings- or organisationsnummer in its TWELVE-digit
* form: an organisationsnummer carries the "16" prefix (5595470021 →
* 165595470021), a personnummer its century (880225-1234 → 198802251234)
* - Followed by a single Luhn check digit
* - Total: 13 digits
*
* Example: 559547-0021 → "165595470021" + check digit "7" = "1655954700217"
*
* The twelve-digit form is the same "redovisare" identity the AGI and moms
* APIs take, so it is built with the shared `toRedovisare12` converter rather
* than a second local rule: the payment reference and the declaration it pays
* must never disagree about who the taxpayer is.
*
* Reference: https://www.skatteverket.se/privat/etjansterochblanketter/allaetjanster/tjanster/ocrberakning
*/
import type { SupabaseClient } from '@supabase/supabase-js'
import type { EntityType } from '@/types'
import { luhnCheckDigit, luhnValidate } from '@/lib/bankgiro/luhn'
import { toRedovisare12 } from '@/lib/invariants/org-number'
/** Bankgiro number for all payments to Skattekontot. */
export const SKATTEKONTO_BANKGIRO = '5050-1055'
/**
* The skattekonto extension caches Skatteverket's own saldo response here
* (same shape the reconciliation engine reads). Core reads the row directly
* rather than importing the extension: core must never import `@/extensions/*`.
*/
const SKATTEVERKET_EXTENSION_ID = 'skatteverket'
const BALANCE_SNAPSHOT_KEY = 'skattekonto_balance_snapshot'
/**
* Compute the Skattekontot OCR reference for a company.
*
* Accepts org_number/personnummer in any common Swedish format
* ("556012-3456", "5560123456", "19880225-1234", "198802251234"); a value
* already in twelve-digit form passes through the century step untouched.
*
* @throws when the input is not 10 or 12 digits after separators are stripped.
*/
export function generateSkattekontoOcr(
orgOrPersonnummer: string,
entityType: EntityType,
): string {
const redovisare = toRedovisare12(orgOrPersonnummer, entityType)
return redovisare + luhnCheckDigit(redovisare).toString()
}
/**
* The OCR to print on a payment file, preferring the one Skatteverket itself
* reported over the one we derive.
*
* `saldo.ocrNummer` comes straight out of the skattekonto API and is the
* authoritative reference for the account we actually sync, which the derived
* value can only approximate: it also covers identities our converter has no
* rule for (samordningsnummer, GD-nummer) and companies whose stored
* org_number has drifted from the skattekonto they are connected to.
*
* Falls back to {@link generateSkattekontoOcr} when no snapshot exists (the
* Skatteverket extension is off or never synced) or the cached value fails a
* Luhn check.
*/
export async function resolveSkattekontoOcr(
supabase: SupabaseClient,
companyId: string,
orgOrPersonnummer: string,
entityType: EntityType,
): Promise<string> {
const reported = await readReportedOcr(supabase, companyId)
return reported ?? generateSkattekontoOcr(orgOrPersonnummer, entityType)
}
async function readReportedOcr(
supabase: SupabaseClient,
companyId: string,
): Promise<string | null> {
const { data, error } = await supabase
.from('extension_data')
.select('value')
.eq('company_id', companyId)
.eq('extension_id', SKATTEVERKET_EXTENSION_ID)
.eq('key', BALANCE_SNAPSHOT_KEY)
.maybeSingle()
if (error || !data?.value) return null
const value = data.value as { saldo?: { ocrNummer?: unknown } }
const raw = value.saldo?.ocrNummer
if (typeof raw !== 'string') return null
// Bankgirot accepts 2-25 digit OCR references; anything else in the cache is
// not something we can put on a payment file, so fall back to the computed
// value rather than shipping it.
const digits = raw.replace(/\D/g, '')
if (digits.length < 2 || digits.length > 25) return null
return luhnValidate(digits) ? digits : null
}