fix(skatteverket): skattekonto-OCR is 13 digits, and the AGI panel stops guessing that you have not signed (#1888)

* fix(skatteverket): skattekonto-OCR is 13 digits, and the AGI panel stops guessing that you have not signed

Two reports from the same salary run (Fabian, Specific AI Sweden AB).

1. The payment file carried an OCR Skatteverket does not accept.
   generateSkattekontoOcr built the reference from the TEN-digit org number
   plus a Luhn check digit (11 digits). Skatteverket's reference is the
   TWELVE-digit identity plus a check digit: an organisationsnummer carries
   the "16" prefix, a personnummer its century. For 559547-0021 we emitted
   55954700211 where Skatteverket prints 1655954700217.

   The twelve-digit form is the same "redovisare" identity the AGI and moms
   APIs take, so it now goes through the shared toRedovisare12 converter
   instead of a second local rule: the payment file and the declaration it
   pays must not disagree about who the taxpayer is. That needs the entity
   type, which the route now reads alongside org_number.

   The route also prefers saldo.ocrNummer from the cached skattekonto
   snapshot over the derived value. It is Skatteverket's own answer for the
   account we actually sync, it covers identities the converter has no rule
   for (samordningsnummer, GD-nummer), and it covers the companies whose
   companies.org_number has drifted from company_settings.org_number.

2. AGI status stayed on "väntar på BankID-signatur i Mina Sidor" after the
   user had signed.
   Reading the kvittens needs a live Skatteverket session, and the personal
   token lives ~65 minutes, so by the time anyone signs in Mina Sidor the
   2-hourly kvittens cron finds a dead token and skips quietly. The panel
   kept asserting a state it could no longer observe.

   It now says so instead, and the reconnect action already on the panel is
   the fix: runPostConnectRefresh reconciles pending declarations on a fresh
   consent. sessionExpiredStatus also counts the needs_reconsent health flag,
   which a cron can set while the access token is still inside its hour;
   without it the panel reported a dead connection as healthy.

   Background reconciliation without a reconnect needs the läsombud grant,
   which is a registration decision and not part of this change.

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

* docs(skatteverket): say why the entity_type collapse in the payment-file route is total

companies.entity_type is NOT NULL with CHECK IN ('enskild_firma',
'aktiebolag'), so the ternary cannot silently mis-tag an enskild firma as
a legal entity and give a personnummer the "16" prefix. Two review bots
read it as an unguarded default; write down the constraint that makes it
safe instead of leaving the next reader to re-derive it.

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

* docs(decisions): record why the cached skattekonto OCR needs no freshness gate

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>
This commit is contained in:
Jakob Wennberg
2026-08-25 14:25:00 +02:00
committed by GitHub
parent cbfb2201ff
commit d80103a2f5
8 changed files with 229 additions and 61 deletions
+3
View File
@@ -1206,6 +1206,9 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
[2026-08-24] fiscal_periods.previous_period_id is adjacency-only: findNextPeriod ignores a chained period that does not start the day after the current one, and SIE import only wires predecessor/successor links between date-adjacent periods (before: nearest period across any gap). A non-adjacent link is what sent a company's opening balances two years forward (feedback seq 249297); 40 such links exist on prod across 39 companies and are neutralized by the read-side guard, not repaired in this change. A gap in the chain means a missing räkenskapsår (BFL 3 kap), which reports should show as missing rather than bridge silently.
[2026-08-24] Pending-operation authorization refusals (401/403 from an executor) release the claim back to 'pending' instead of consuming the op as 'rejected': the refusal happens before any side-effect and reflects the credential, not the booking, so the same op must survive for an authorized approver (/pending UI or a scoped key). Every CommitResult now carries operation_status so agents stop inferring "consumed" from status 'failed'. Deterministic content errors (400) still consume the op: re-staging is the only fix for those.
[2026-08-24] tools/call rejects unknown top-level parameters (VALIDATION_ERROR naming the valid keys) instead of ignoring them: hosts do not reliably enforce inputSchema, and a misspelled key silently widened gnubok_query_journal to the whole journal (feedback seq 261545). company_id stays tolerated on every tool because the routing layer owns it. Chose server-side enforcement over per-tool presence guards: every schema already declares additionalProperties:false, so the contract exists, it just was not enforced.
[2026-08-25] Skattekonto-OCR is the twelve-digit redovisare identity plus a Luhn check digit (13 digits), built with the shared toRedovisare12 rather than a second local rule: the previous ten-digit form (11 digits total) was never a reference Skatteverket accepts, and the payment file must not disagree with the AGI it pays about who the taxpayer is. The payment route prefers saldo.ocrNummer from the cached skattekonto snapshot over the derived value: it is Skatteverket's own answer for the account we actually sync, and it covers identities the converter has no rule for (samordningsnummer, GD-nummer) plus the 90 prod companies whose companies.org_number has drifted from company_settings.org_number.
[2026-08-25] The AGI panel stops claiming "väntar på BankID-signatur i Mina Sidor" when the Skatteverket session is dead: with a personal token that lives ~65 minutes and no ombud grant on prod (skatteverket_company_connections is empty), the kvittens cron can never reconcile, and 0 of 7 pending_signature declarations have ever reached submitted. Chose UI honesty plus the existing reconnect path (runPostConnectRefresh reconciles on consent) over building a new polling mechanism: background reconciliation needs the läsombud rollout, which is a registration decision, not a code change.
[2026-08-25] resolveSkattekontoOcr uses the cached saldo.ocrNummer without a freshness gate (review bot asked for one): a skattekontoreferens is a function of the taxpayer identity, not of a balance, so it cannot go stale the way a saldo does. In the one scenario where cached and computed disagree (org number corrected after the last sync), the cached value is the correct reference for the skattekonto the company is actually connected to, and recomputing would be the guess.
[2026-08-24] Agent-first onboarding (issue #1814) ships as shape B+ (signup inside the MCP OAuth popup, lazy auth, setup tools token-agnostic) and NOT as pre-identity provisional tenants first: bank and Skatteverket connects need a human browser anyway, so the claim-link shape buys little for a lot of TTL/abuse/RLS work; it stays a later auth swap.
[2026-08-24] Keys minted from the OAuth popup before the first company exists get company_id NULL and are bound lazily in validateApiKey (first validation after a company exists) instead of at company creation: creation happens in a Server Action that knows nothing about keys, and one chokepoint covers every creation path.
[2026-08-24] /api/mcp-oauth/authorize now forces TOTP enrollment (not just verification) for password accounts with no factor: the middleware skips enrollment for zero-company users, so a popup signup would otherwise mint an MFA-exempt key for an account with no second factor. BankID-linked accounts stay exempt.
@@ -45,7 +45,7 @@ vi.mock('@/lib/branding/service', () => ({
}))
vi.mock('@/lib/skatteverket/skattekonto-ocr', () => ({
generateSkattekontoOcr: vi.fn().mockReturnValue('1234567890'),
resolveSkattekontoOcr: vi.fn().mockResolvedValue('1655954700217'),
SKATTEKONTO_BANKGIRO: '5050-1055',
}))
@@ -107,7 +107,7 @@ describe('GET /api/skatteverket/tax-payments/[period]/payment-file', () => {
it('generates the LB file (happy path)', async () => {
enqueue({ data: { id: 'agi-1', total_tax: 1000, total_avgifter: 500 } }) // agi
enqueue({ data: { name: 'Test AB', org_number: '5566778899' } }) // companies
enqueue({ data: { name: 'Test AB', org_number: '5566778899', entity_type: 'aktiebolag' } }) // companies
enqueue({ data: { bankgiro: '123-4567' } }) // company_settings
enqueue({ data: null, error: null }) // update tax_payment_file_generated_at
@@ -129,7 +129,7 @@ describe('GET /api/skatteverket/tax-payments/[period]/payment-file', () => {
// the matching salary booking credited 2731 with the same number: the
// payment must be exactly their sum.
enqueue({ data: { id: 'agi-1', total_tax: 12268, total_avgifter: 16073 } }) // agi
enqueue({ data: { name: 'Test AB', org_number: '5566778899' } }) // companies
enqueue({ data: { name: 'Test AB', org_number: '5566778899', entity_type: 'aktiebolag' } }) // companies
enqueue({ data: { bankgiro: '123-4567' } }) // company_settings
enqueue({ data: null, error: null }) // update tax_payment_file_generated_at
@@ -148,7 +148,7 @@ describe('GET /api/skatteverket/tax-payments/[period]/payment-file', () => {
// (the öre parks as a small skattekonto överskott, the pre-existing
// equilibrium). Truncating here would strand the öre on 2731 instead.
enqueue({ data: { id: 'agi-1', total_tax: 12268, total_avgifter: 16073.84 } }) // agi
enqueue({ data: { name: 'Test AB', org_number: '5566778899' } }) // companies
enqueue({ data: { name: 'Test AB', org_number: '5566778899', entity_type: 'aktiebolag' } }) // companies
enqueue({ data: { bankgiro: '123-4567' } }) // company_settings
enqueue({ data: null, error: null }) // update tax_payment_file_generated_at
@@ -163,7 +163,7 @@ describe('GET /api/skatteverket/tax-payments/[period]/payment-file', () => {
it('generates a pain.001 file when format=pain001', async () => {
enqueue({ data: { id: 'agi-1', total_tax: 1000, total_avgifter: 500 } }) // agi
enqueue({ data: { name: 'Test AB', org_number: '5566778899' } }) // companies
enqueue({ data: { name: 'Test AB', org_number: '5566778899', entity_type: 'aktiebolag' } }) // companies
enqueue({ data: null, error: null }) // update tax_payment_file_generated_at
const response = await GET(
@@ -185,14 +185,14 @@ describe('GET /api/skatteverket/tax-payments/[period]/payment-file', () => {
payee: { type: 'bankgiro', bankgiro: '50501055' },
payeeName: 'Skatteverket',
amount: 1500,
reference: { type: 'ocr', value: '1234567890' },
reference: { type: 'ocr', value: '1655954700217' },
})
})
it('returns 400 when the pain.001 debtor is missing an IBAN', async () => {
mockResolveBatchDebtor.mockResolvedValue({ ok: false, missing: 'iban' })
enqueue({ data: { id: 'agi-1', total_tax: 1000, total_avgifter: 500 } }) // agi
enqueue({ data: { name: 'Test AB', org_number: '5566778899' } }) // companies
enqueue({ data: { name: 'Test AB', org_number: '5566778899', entity_type: 'aktiebolag' } }) // companies
const response = await GET(
createMockRequest('/api/skatteverket/tax-payments/2026-04/payment-file', {
@@ -5,7 +5,7 @@ import { getErrorMessage } from '@/lib/errors/get-error-message'
import { generateBankgiroPaymentBgLb } from '@/lib/salary/payment/bg-lb-generator'
import { generateSupplierPain001 } from '@/lib/payments/pain001-supplier'
import { resolveBatchDebtor } from '@/lib/payments/batch-service'
import { generateSkattekontoOcr, SKATTEKONTO_BANKGIRO } from '@/lib/skatteverket/skattekonto-ocr'
import { resolveSkattekontoOcr, SKATTEKONTO_BANKGIRO } from '@/lib/skatteverket/skattekonto-ocr'
import { validateBankgiroNumber } from '@/lib/bankgiro/luhn'
import { getBranding } from '@/lib/branding/service'
import { roundOre } from '@/lib/money'
@@ -86,7 +86,7 @@ export const GET = withRouteContext<{ params: Promise<{ period: string }> }>(
const { data: company } = await supabase
.from('companies')
.select('name, org_number')
.select('name, org_number, entity_type')
.eq('id', companyId)
.single()
@@ -97,9 +97,25 @@ export const GET = withRouteContext<{ params: Promise<{ period: string }> }>(
)
}
// The reference is the company's twelve-digit identity plus a Luhn check
// digit (13 digits), not the ten-digit form: Skatteverket rejects the short
// one. Skatteverket's own reported OCR wins when the skattekonto has been
// synced; the derived value is the fallback.
//
// The entity_type collapse below is total, not a guess at a default:
// companies.entity_type is NOT NULL with CHECK IN ('enskild_firma',
// 'aktiebolag'), so there is no third value and no null to mis-tag. It
// matters because it picks the prefix: a personnummer must keep its century
// where an organisationsnummer takes "16", and getting that wrong yields a
// Luhn-valid OCR for the wrong taxpayer.
let ocr: string
try {
ocr = generateSkattekontoOcr(company.org_number)
ocr = await resolveSkattekontoOcr(
supabase,
companyId,
company.org_number,
company.entity_type === 'enskild_firma' ? 'enskild_firma' : 'aktiebolag',
)
} catch (err) {
return NextResponse.json({ error: getErrorMessage(err) }, { status: 400 })
}
+15 -6
View File
@@ -63,6 +63,8 @@ interface ConnectionStatus {
connected: boolean
expired?: boolean
canRefresh?: boolean
/** Persisted health flag: a cron hit a terminal auth state on this token. */
needsReconsent?: boolean
scope?: string
expiresAt?: string
}
@@ -253,7 +255,8 @@ export function AGIPanel(props: AGIPanelProps) {
// place even though the token is now fresh. This wipes the error
// only when (a) there's currently an error and (b) the new status
// says we're healthy: never silently swallowing unrelated errors.
const isHealthy = next.connected && !next.expired && next.canRefresh !== false
const isHealthy =
next.connected && !next.expired && next.canRefresh !== false && !next.needsReconsent
if (isHealthy) {
setError(prev =>
prev && /sessionen har gått ut|logga in med bankid igen/i.test(prev)
@@ -917,10 +920,14 @@ export function AGIPanel(props: AGIPanelProps) {
grantedScopes !== null && !missingAgdScope && !grantedScopes.includes('agdredovisningperiod')
// Expired session: the token row exists (so status.connected is true) but
// the access token is past expiry and either has no refresh token or has
// burned through its 10-refresh budget. The only fix is a fresh BankID
// round-trip.
const sessionExpiredStatus = status?.expired === true || status?.canRefresh === false
// the access token is past expiry, has no refresh token or has burned
// through its 10-refresh budget, or a cron already parked it as
// needs_reconsent. The only fix is a fresh BankID round-trip. The
// needs_reconsent flag has to count on its own: it is set on terminal auth
// errors that can land while the access token is still inside its hour, and
// without it the panel reports a dead connection as healthy.
const sessionExpiredStatus =
status?.expired === true || status?.canRefresh === false || status?.needsReconsent === true
// One attention sentence per section (convention 6). The expired session
// outranks the missing inlämning scope: nothing can be filed until the
@@ -1089,7 +1096,9 @@ export function AGIPanel(props: AGIPanelProps) {
awaitingSigning
? draftIsStale
? t('pending_stale_draft')
: t('pending_awaiting_signature')
: sessionExpiredStatus
? t('pending_signature_unverifiable')
: t('pending_awaiting_signature')
: underlagSubmitted
? t('pending_underlag_submitted')
: t('pending_not_submitted')
@@ -1,32 +1,115 @@
import { describe, it, expect } from 'vitest'
import { generateSkattekontoOcr, SKATTEKONTO_BANKGIRO } from '../skattekonto-ocr'
import { describe, it, expect, vi } from 'vitest'
import {
generateSkattekontoOcr,
resolveSkattekontoOcr,
SKATTEKONTO_BANKGIRO,
} from '../skattekonto-ocr'
import { luhnValidate } from '@/lib/bankgiro/luhn'
describe('generateSkattekontoOcr', () => {
it('produces 11-digit OCR with valid Luhn check digit for AB org-number', () => {
const ocr = generateSkattekontoOcr('556012-3456')
expect(ocr).toHaveLength(11)
expect(ocr.startsWith('5560123456')).toBe(true)
// Ground truth from Skatteverket for org 559547-0021: the reference their
// e-service prints is the twelve-digit form plus a check digit, not the
// ten-digit one (which is what we used to emit, and banks/SKV rejected).
it('produces the 13-digit OCR Skatteverket prints for an AB', () => {
expect(generateSkattekontoOcr('559547-0021', 'aktiebolag')).toBe('1655954700217')
})
it('prefixes an organisationsnummer with 16 and appends a Luhn check digit', () => {
const ocr = generateSkattekontoOcr('556012-3456', 'aktiebolag')
expect(ocr).toHaveLength(13)
expect(ocr.startsWith('165560123456')).toBe(true)
expect(luhnValidate(ocr)).toBe(true)
})
it('accepts org-number without dash', () => {
expect(generateSkattekontoOcr('5560123456')).toBe(generateSkattekontoOcr('556012-3456'))
it('accepts org-number without dash and with spaces', () => {
const canonical = generateSkattekontoOcr('556012-3456', 'aktiebolag')
expect(generateSkattekontoOcr('5560123456', 'aktiebolag')).toBe(canonical)
expect(generateSkattekontoOcr('556012 3456', 'aktiebolag')).toBe(canonical)
})
it('accepts 12-digit personnummer by stripping century prefix', () => {
const ocr12 = generateSkattekontoOcr('198802251234')
const ocr10 = generateSkattekontoOcr('880225-1234')
expect(ocr12).toBe(ocr10)
it('keeps the century for an enskild firma personnummer', () => {
const ocr = generateSkattekontoOcr('19880225-1234', 'enskild_firma')
expect(ocr).toHaveLength(13)
expect(ocr.startsWith('198802251234')).toBe(true)
expect(luhnValidate(ocr)).toBe(true)
})
it('derives the century for a 10-digit personnummer', () => {
expect(generateSkattekontoOcr('880225-1234', 'enskild_firma')).toBe(
generateSkattekontoOcr('198802251234', 'enskild_firma'),
)
})
it('does not give an enskild firma the organisationsnummer prefix', () => {
const ef = generateSkattekontoOcr('880225-1234', 'enskild_firma')
const ab = generateSkattekontoOcr('880225-1234', 'aktiebolag')
expect(ef.startsWith('16')).toBe(false)
expect(ab.startsWith('16')).toBe(true)
expect(ef).not.toBe(ab)
})
it('rejects malformed numbers', () => {
expect(() => generateSkattekontoOcr('123')).toThrow(/Ogiltigt/)
expect(() => generateSkattekontoOcr('')).toThrow(/Ogiltigt/)
expect(() => generateSkattekontoOcr('abcdefghij')).toThrow(/Ogiltigt/)
expect(() => generateSkattekontoOcr('123', 'aktiebolag')).toThrow(/Ogiltigt/)
expect(() => generateSkattekontoOcr('', 'aktiebolag')).toThrow(/Ogiltigt/)
expect(() => generateSkattekontoOcr('abcdefghij', 'aktiebolag')).toThrow(/Ogiltigt/)
})
it('exports correct Bankgiro for Skattekontot', () => {
expect(SKATTEKONTO_BANKGIRO).toBe('5050-1055')
})
})
describe('resolveSkattekontoOcr', () => {
function snapshotClient(value: unknown, error: unknown = null) {
const maybeSingle = vi.fn().mockResolvedValue({ data: value === undefined ? null : { value }, error })
const eq = vi.fn()
const builder = { select: vi.fn(() => builder), eq, maybeSingle }
eq.mockImplementation(() => builder)
return {
client: { from: vi.fn(() => builder) } as never,
from: builder,
}
}
it('prefers the OCR Skatteverket reported on the skattekonto saldo', async () => {
const { client } = snapshotClient({ saldo: { ocrNummer: '1948040320946' }, fetchedAt: 1 })
await expect(
resolveSkattekontoOcr(client, 'company-1', '556012-3456', 'aktiebolag'),
).resolves.toBe('1948040320946')
})
it('strips separators from the reported OCR', async () => {
const { client } = snapshotClient({ saldo: { ocrNummer: '16 5595470021 7' } })
await expect(
resolveSkattekontoOcr(client, 'company-1', '556012-3456', 'aktiebolag'),
).resolves.toBe('1655954700217')
})
it('falls back to the computed OCR when no snapshot is cached', async () => {
const { client } = snapshotClient(undefined)
await expect(
resolveSkattekontoOcr(client, 'company-1', '559547-0021', 'aktiebolag'),
).resolves.toBe('1655954700217')
})
it('falls back when the cached OCR fails its Luhn check', async () => {
const { client } = snapshotClient({ saldo: { ocrNummer: '1655954700216' } })
await expect(
resolveSkattekontoOcr(client, 'company-1', '559547-0021', 'aktiebolag'),
).resolves.toBe('1655954700217')
})
it('falls back when the cached OCR is longer than Bankgirot accepts', async () => {
const { client } = snapshotClient({ saldo: { ocrNummer: '1'.repeat(26) } })
await expect(
resolveSkattekontoOcr(client, 'company-1', '559547-0021', 'aktiebolag'),
).resolves.toBe('1655954700217')
})
it('falls back when the snapshot read errors', async () => {
const { client } = snapshotClient(undefined, { message: 'boom' })
await expect(
resolveSkattekontoOcr(client, 'company-1', '559547-0021', 'aktiebolag'),
).resolves.toBe('1655954700217')
})
})
+85 -30
View File
@@ -6,48 +6,103 @@
* Skattekonto receives the credit; Skatteverket applies it to the most recent
* declared liability.
*
* Format (per Skatteverket "OCR-nummer för inbetalning till skattekontot"):
* - 10-digit organisationsnummer (AB) or 10-digit personnummer (EF)
* stripped of dashes/spaces
* 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: 11 digits
* - Total: 13 digits
*
* Examples:
* 556012-3456 → "5560123456" + check digit "6" = "55601234566"
* 880225-1234 → "8802251234" + check digit → 11 digits
* Example: 559547-0021 → "165595470021" + check digit "7" = "1655954700217"
*
* Reference: https://www.skatteverket.se/foretag/skatterochavdrag/skattekonto/betalainochavskattekonto/sabetalardupaskattekontot.4.18e1b10334ebe8bc80004499.html
* 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 { luhnCheckDigit } from '@/lib/bankgiro/luhn'
import type { SupabaseClient } from '@supabase/supabase-js'
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'
/**
* Generate the standard Skattekontot OCR reference for a company.
* 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").
* ("556012-3456", "5560123456", "19880225-1234", "198802251234"); a value
* already in twelve-digit form passes through the century step untouched.
*
* For 12-digit personnummer (with century prefix), the leading century digits
* are stripped: Skatteverket's Skattekonto-OCR uses the 10-digit form.
* @throws when the input is not 10 or 12 digits after separators are stripped.
*/
export function generateSkattekontoOcr(orgOrPersonnummer: string): string {
const digits = orgOrPersonnummer.replace(/\D/g, '')
let base: string
if (digits.length === 10) {
base = digits
} else if (digits.length === 12) {
// Strip century prefix (1900s = "19", 2000s = "20")
base = digits.slice(2)
} else {
throw new Error(
`Ogiltigt org/personnummer för Skattekonto-OCR: "${orgOrPersonnummer}" (förväntat 10 eller 12 siffror)`
)
}
const checkDigit = luhnCheckDigit(base)
return base + checkDigit.toString()
export function generateSkattekontoOcr(
orgOrPersonnummer: string,
entityType: 'enskild_firma' | 'aktiebolag',
): 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: 'enskild_firma' | 'aktiebolag',
): 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
}
+1
View File
@@ -7051,6 +7051,7 @@
"submitted": "Submitted",
"pending_stale_draft": "A signing draft exists at Skatteverket but is outdated — unlock and submit the underlag again.",
"pending_awaiting_signature": "Granskningsunderlag ready — waiting for BankID signature in Mina Sidor.",
"pending_signature_unverifiable": "Granskningsunderlag ready. If it has already been signed in Mina Sidor, that will not show here until the Skatteverket connection is renewed.",
"pending_underlag_submitted": "Underlag received by Skatteverket. Create a granskningsunderlag to proceed to signing.",
"pending_not_submitted": "Not submitted to Skatteverket yet. Deadline: the 12th of the month after payout (the 17th in January/August for employers whose total annual payroll is below SEK 40 million).",
"draft_locked_title": "The draft is locked and ready to be signed",
+1
View File
@@ -7051,6 +7051,7 @@
"submitted": "Skickad",
"pending_stale_draft": "Ett signeringsutkast finns hos Skatteverket men är inaktuellt — lås upp och skicka in underlaget på nytt.",
"pending_awaiting_signature": "Granskningsunderlag klart — väntar på BankID-signatur i Mina Sidor.",
"pending_signature_unverifiable": "Granskningsunderlag klart. Om det redan är signerat i Mina Sidor syns det inte här förrän anslutningen till Skatteverket förnyats.",
"pending_underlag_submitted": "Underlag inläst hos Skatteverket. Skapa granskningsunderlag för att gå vidare till signering.",
"pending_not_submitted": "Inte skickad till Skatteverket ännu. Deadline: 12:e i månaden efter utbetalning (17:e i januari/augusti för arbetsgivare vars sammanlagda lönesumma understiger 40 MSEK per år).",
"draft_locked_title": "Utkastet är låst och redo att signeras",