feat(parties): fetch registry facts from SCB into the dossier, with a picker for parties without an org number (#2258)
* feat(parties): Kontakter register, suggestion queue, dossier and merge Phase 1's two surfaces on top of the parties substrate: - /parties page: one list with the five-way switch (Alla, Kunder, Leverantörer, Förslag, Bara i bokföringen), search, a 12-month/all period picker, and at most one attention line. Confirmed rows show roles as muted text, rhythm, underlag, dominant account and money. Observed rows are computed and never stored; a generic band keeps unattributed spend visible. - Suggestion queue: a reason per row, hard-key rows pre-ticked, bulk confirm behind one dialog, dismiss on hover, undo on the toast. - Dossier slide-over: Pengar, Bokföring, Vad Accounted vet (facts and identities with source and count), Underlag och verifikat, Historik. - Merge dialog with a visible, swappable survivor and undo. - API: GET /api/parties, GET /api/parties/[id], POST suggest, decide, decide/undo, merge, merge/undo (withRouteContext, Zod, 15 tests). - Migration 20260903090000: decide_parties snapshots the reason it clears; undo_party_decisions reverses confirm/dismiss within 30 days; decision kind 'undo'. - The pipeline runs after SIE import and provider migration (non-blocking) so a migrant's register is full on arrival. - Nav entry under Register; sv/en strings. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): pass explicit interpolation values to next-intl next build's type check rejects a typed interface where the translator wants an index-signature record. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): retry label on the load-failed state Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): hard keys for companies without org number, readable names, look-alikes at read time - get_ledger_key_evidence dropped every document for a company whose own org number is NULL (the self check compared against NULL). Replaced in 20260903100000 with a coalesced comparison; pg test covers it. - Display names come from the printed name on documents, otherwise from the voucher text with the AP/AR prefix and supplier number removed. - Look-alike parties (same core, or one core extending the other by whole words: Fortnox / Fortnox Finans) are detected when the register is read, never stored, and feed the Dubblett? chip and the merge dialog. - Queue shows Intäkt beside Kostnad; dossier hides zero money rows and formats bankgiro/plusgiro; merge dialog cancels with Avbryt; no synchronous setState inside effects. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): link every new supplier and customer to a party on write The backfill covered the rows that existed on 2026-09-02; 108 rows created since had no party and never reached the register. A BEFORE INSERT/UPDATE trigger on customers and suppliers now calls ensure_party on every write path at once: find-or-create by org number inside the company, never by name; a private customer gets a kind=person party without any number; a nameless row stays unlinked; a foreign party id is refused with the same error as the composite foreign key; a link to a merged party follows the chain to the survivor; the clear that ON DELETE SET NULL performs is kept. ensure_party lets the trigger act for the row's owner (pg_trigger_depth() > 0); the RPC path is unchanged. The migration also links the rows created since the backfill. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): dossier hides dismissed parties and follows merges to the survivor The register hid archived parties while the dossier still served them by id, and a merged party's dossier pointed at a dead row. Superagent P2 on #2206; three unit tests. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move the role-link migration past main's 20260903110000 Two files with one version would collide in schema_migrations. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): confirm suggestions into Leverantörer and Kunder, no third noun Founder decision after the walkthrough: users know two words. The page becomes the queue 'Förslag från bokföringen' with 'Bara i bokföringen' beside it; the Kontakter nav entry and the Alla/Kunder/Leverantörer views go. Each suggestion shows what it becomes (Blir), read from the ledger side and changeable per row; confirming calls promote_parties, which creates the supplier and/or customer row from the party's facts, never a duplicate, and is undoable for 30 days through undo_party_promotions (the created rows are archived, the party returns to the queue). Leverantörer and Kunder carry the one attention line that leads here. The dossier offers Lägg upp som leverantör / som kund. Migration 20260903130000, 5 pg tests, route and unit tests updated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): write bankgiro and plusgiro the way the supplier form does Identities are stored as digits; suppliers carry 5317-0900. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): fetch registry facts from SCB into the dossier SCB granted API access today (certificate + password, layouts Je and Ae). This adds the first registry enricher of phase 3: - lib/parties/scb: config from env (SCB_API_CERT_PFX_BASE64, SCB_API_CERT_PASSWORD), an mTLS transport on node:https, the mapping of every documented Je variable to a labelled fact, and a client whose wire format sits in one file because SCB replaces the API this month. Legal persons only: a sole trader's org number is a personnummer. - Migration 20260903150000: record_party_facts(company, user, party, source, facts, fetched_at) refreshes unchanged values, supersedes changed ones, never touches other sources. pg test. - POST /api/parties/[id]/enrich: 503 when not configured, 400 for a sole trader, 502 when SCB fails, fills an empty legal name. 7 tests. - Dossier: 'Hämta uppgifter' button (gated on configuration) and the registry rows with 'SCB · datum' as their source line. - scripts/scb/discover.ts prints the live variable list, code tables and one lookup so the request shape is checked against the real API. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): SCB client on the live wire format, mapper on the real Je row Verified against the API on 2026-09-03: an identity lookup is one filter (Variabel 'OrgNr (10 siffror)', Operator ArLikaMed) without status keys, and the row carries '<name>, kod' beside SCB's own text. The mapper now reads those columns, prefers SCB's text, and adds turnover band, seat names and Skatteverket registration. The AB Volvo row is the fixture. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): registry legal name outranks the document one, never a person's Survivorship from the plan: user > registry > document. The dossier's legal-name row now carries 'SCB · datum' when the registry is the source. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): VAT number from the moms flag, one primary action, one source line Founder review of the SCB dossier: - A Swedish company registered for moms has VAT number SE + org number + 01 by construction, so the registry's moms flag yields the number; it fills an empty vat_number on the party and shows in the Momsnr row instead of 'Saknas'. - The 'Registrerad hos Skatteverket' row said nothing (true for every legal person) and is gone. - Five buttons became one primary (the role the ledger suggests) and a menu with the rest; the per-row 'SCB · datum' notes became one group line 'Från SCB · hämtat datum'. - A postal-code-only address (large companies) is labelled as such. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): do not repeat the county when it equals the municipality Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): SCB picker for parties without an org number 'Hitta i företagsregistret' in the dossier menu opens a picker: SCB is searched on the party's name (prefix first, contains as fallback, counts before rows, capped at 25, natural persons and estates excluded, active companies first). The user chooses; the org number is recorded as a fact with source 'user' and set on the party, then the normal fetch runs, so every later fetch is by number. A number another live party holds is refused with a pointer to it. One match is still shown, never auto-picked. The transport retries once on a dropped connection (seen live). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): a picked org number shows in the queue's reason and counts as a hard key Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): SCB search tightened after a batch of real supplier names Twenty-five prod supplier names and twenty org numbers across every legal form went through the search and the lookup: - total is what the picker can offer, not SCB's raw count (Eismann counted one row and offered none, a natural person); - foreign legal forms stay in the query: they are part of the registered name and dropping them floods (Schmidt GmbH became 167 Schmidts); - a fusion or delning in progress is no longer a warning (Fortnox AB and Avanza Bank trade normally under 'Fusion pågår'); distress and disappearance codes still are. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move the four queue migrations past main's 20260903170000 Main merged 20260903120000_skattekonto_transactions_realtime_publication with the same version as the role-link trigger; the preview database refused the duplicate key. All four now sit after main's newest so the set applies in one ordered run on prod. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move record_party_facts after the queue migrations Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move record_party_facts to a version after tonight's collisions Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
47c73206e1
commit
22b98e0a3b
@@ -4030,6 +4030,19 @@ export const PartyMergeSchema = z.object({
|
||||
note: z.string().max(500).optional(),
|
||||
})
|
||||
|
||||
export const PartyEnrichSchema = z.object({
|
||||
/** Chosen from the SCB picker: sets the party's org number before the fetch. */
|
||||
orgNumber: z
|
||||
.string()
|
||||
.transform((v) => v.replace(/[^0-9]/g, ''))
|
||||
.pipe(z.string().regex(/^\d{10}$/))
|
||||
.optional(),
|
||||
})
|
||||
|
||||
export const PartySearchRegistryQuerySchema = z.object({
|
||||
q: z.string().max(120).optional(),
|
||||
})
|
||||
|
||||
export const PartyUndoMergeSchema = z.object({
|
||||
decisionId: uuid,
|
||||
})
|
||||
|
||||
@@ -1514,6 +1514,21 @@ const INVOICE: Record<string, StructuredErrorEntry> = {
|
||||
// POST /api/invoices/{id}/peppol/send. The Access Point is an environment
|
||||
// decision (PEPPOL_TRANSPORT_PROVIDER + adapter credentials); the product
|
||||
// never pretends to send when no adapter is switched on.
|
||||
SCB_NOT_CONFIGURED: {
|
||||
httpStatus: 503,
|
||||
message_sv: 'Uppslag mot SCB:s företagsregister är inte aktiverat i den här miljön.',
|
||||
message_en: 'Lookups against the SCB business register are not enabled in this environment.',
|
||||
},
|
||||
SCB_LOOKUP_FAILED: {
|
||||
httpStatus: 502,
|
||||
message_sv: 'SCB:s företagsregister svarade inte. Försök igen om en stund.',
|
||||
message_en: 'The SCB business register did not answer. Try again shortly.',
|
||||
},
|
||||
SCB_NOT_A_LEGAL_PERSON: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Uppgifter hämtas bara för juridiska personer, inte för enskilda firmor.',
|
||||
message_en: 'Details are fetched for legal persons only, not for sole traders.',
|
||||
},
|
||||
PEPPOL_TRANSPORT_UNAVAILABLE: {
|
||||
httpStatus: 503,
|
||||
message_sv: 'Peppol-utskick är inte aktiverat i den här miljön. En avtalad Peppol-operatör måste vara konfigurerad.',
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { coreKey } from './ledger-key'
|
||||
import { isScbConfigured } from './scb/config'
|
||||
import { getObservedParties, type ObservedParty } from './observed'
|
||||
import type { SuggestionReason } from './suggest'
|
||||
|
||||
@@ -80,6 +81,8 @@ export interface Register {
|
||||
/** Observed keys the pre-classifier calls a category: unattributed spend. */
|
||||
generic: { count: number; expenseSek: number; examples: string[] }
|
||||
period: RegisterPeriod
|
||||
/** Whether this environment can fetch registry facts from SCB (gates the dossier button). */
|
||||
scbConfigured: boolean
|
||||
}
|
||||
|
||||
interface PartyRecord {
|
||||
@@ -335,7 +338,7 @@ export async function getRegister(
|
||||
.sort((a, b) => b.stats.expenseSek + b.stats.revenueSek - (a.stats.expenseSek + a.stats.revenueSek))
|
||||
: []
|
||||
|
||||
return { counts, rows: selected, observed: observedSelected, generic, period }
|
||||
return { counts, rows: selected, observed: observedSelected, generic, period, scbConfigured: isScbConfigured() }
|
||||
}
|
||||
|
||||
// ── Dossier ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
{
|
||||
"PeOrgNr": "165560125790",
|
||||
"OrgNr": "5560125790",
|
||||
"Företagsnamn": "AKTIEBOLAGET VOLVO",
|
||||
"COAdress": "",
|
||||
"PostAdress": "",
|
||||
"PostNr": "405 08",
|
||||
"PostOrt": "GÖTEBORG",
|
||||
"Säteskommun, kod": "1480",
|
||||
"Säteskommun": "Göteborg",
|
||||
"Säteslän, kod": "14",
|
||||
"Säteslän": "Västra Götaland",
|
||||
"Aregion, kod": "33",
|
||||
"ARegion": "Göteborg",
|
||||
"Antal arbetsställen": "1 ",
|
||||
"Stkl, kod": "8 ",
|
||||
"Storleksklass": "200-499 anställda",
|
||||
"Företagsstatus, kod": "1",
|
||||
"Företagsstatus": "Är verksam",
|
||||
"Registrerad hos SKV, kod": "1",
|
||||
"Registrerad hos SKV": "Registrerad",
|
||||
"Juridisk form, kod": "49",
|
||||
"Juridisk form": "Övriga aktiebolag",
|
||||
"Reklam, kod": "11",
|
||||
"Reklam": "Tar emot reklam, ej telefonnummerspärrat",
|
||||
"Utskick, kod": "1",
|
||||
"Utskick": "Postadress är OK",
|
||||
"Startdatum": "1972-01-01",
|
||||
"Slutdatum": "",
|
||||
"Registreringsdatum": "1972-01-01",
|
||||
"Bransch_1, kod": "70100",
|
||||
"Bransch_1P, kod": "70.100",
|
||||
"Bransch_1": "Verksamheter som utövas av huvudkontor",
|
||||
"Avdelning_1, kod": "N",
|
||||
"Avdelning_1": "Verksamhet inom juridik, ekonomi, vetenskap och teknik",
|
||||
"Bransch_2, kod": " ",
|
||||
"Bransch_2P, kod": " ",
|
||||
"Bransch_2": "",
|
||||
"Avdelning_2, kod": " ",
|
||||
"Avdelning_2": "",
|
||||
"Bransch_3, kod": " ",
|
||||
"Bransch_3P, kod": " ",
|
||||
"Bransch_3": "",
|
||||
"Avdelning_3, kod": " ",
|
||||
"Avdelning_3": "",
|
||||
"Bransch_4, kod": " ",
|
||||
"Bransch_4P, kod": " ",
|
||||
"Bransch_4": "",
|
||||
"Avdelning_4, kod": " ",
|
||||
"Avdelning_4": "",
|
||||
"Bransch_5, kod": " ",
|
||||
"Bransch_5P, kod": " ",
|
||||
"Bransch_5": "",
|
||||
"Avdelning_5, kod": " ",
|
||||
"Avdelning_5": "",
|
||||
"Export/Importmarkering": "J",
|
||||
"Omsättning, år": "2025",
|
||||
"Stkl, oms, kod": "10",
|
||||
"Storleksklass, oms": "1 000 000 - 4 999 999 tkr",
|
||||
"Stkl Fin, oms, kod": "19",
|
||||
"Storleksklass Fin, oms": "1 000 000 - 4 999 999 tkr",
|
||||
"Ägarkategori, kod": "42",
|
||||
"Ägarkategori": "Privat svenskt med koncern",
|
||||
"Telefon": "031660000",
|
||||
"E-post": "",
|
||||
"Privat/Publikt, kod": "21",
|
||||
"Privat/Publikt": "Publikt, Stockholm Large Cap",
|
||||
"Arbetsgivarstatus, kod": "1",
|
||||
"Arbetsgivarstatus": "Är registrerad som vanlig arbetsgivare",
|
||||
"Momsstatus, kod": "1",
|
||||
"Momsstatus": "Är registrerad för moms",
|
||||
"Fskattstatus, kod": "1",
|
||||
"Fskattstatus": "Är registrerad för F-skatt",
|
||||
"Bolagsstatus, kod": "0 ",
|
||||
"Bolagsstatus": "Normalläge",
|
||||
"Antal firmor": "0 ",
|
||||
"Firma": "",
|
||||
"Sektor, kod": "111000",
|
||||
"Sektor": "Icke-finansiella bolag, utom statliga affärsverk, filialer i Sverige till icke-finansiella bolag i utlandet och icke-vinstdrivande organisationer som betjänar icke-finansiella bolag",
|
||||
"Stkl SME, kod": "4 ",
|
||||
"Storleksklass SME": "250-499 anställda",
|
||||
"Andel kvinna": "*",
|
||||
"Andel man": "*",
|
||||
"Ägarland, kod": "*",
|
||||
"Ägarland": "*",
|
||||
"Ägarnamn": "*",
|
||||
"Utländskt ägande, kod": "*",
|
||||
"Utländskt ägande": "*",
|
||||
"Stkl export, kod": "1",
|
||||
"Stkl export": "1-249 tkr",
|
||||
"Stkl import, kod": "2",
|
||||
"Stkl import": "250-999 tkr",
|
||||
"Norden": "Ingen export/import",
|
||||
"EU": "Import",
|
||||
"Övriga Europa": "Export",
|
||||
"Asien, ej Fjärran Östern": "Export",
|
||||
"Fjärran Östern": "Import",
|
||||
"Nord- och Centralamerika": "Export",
|
||||
"Sydamerika": "Ingen export/import",
|
||||
"Afrika": "Ingen export/import"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createScbClient, identityLookupBody, nameQuery, nameSearchBody, SCB_SEARCH_CAP } from '../client'
|
||||
import { isScbConfigured, scbConfigFromEnv } from '../config'
|
||||
import { factsFromScbCompany, BOLAGSVERKET_WARNING_CODES } from '../map'
|
||||
import { isLegalPersonOrgNumber, toPeOrgNr } from '../org-number'
|
||||
import { ScbApiError, scbJson } from '../transport'
|
||||
|
||||
/** One Je row exactly as the live API returned it on 2026-09-03 (AB Volvo, public registry data). */
|
||||
const volvo = JSON.parse(readFileSync(join(__dirname, 'fixtures', 'volvo-je.json'), 'utf8')) as Record<string, string>
|
||||
|
||||
describe('org numbers we send to SCB', () => {
|
||||
it('accepts legal persons (month slot 20 or more) and refuses personnummer-shaped numbers', () => {
|
||||
expect(isLegalPersonOrgNumber('556012-5790')).toBe(true)
|
||||
expect(isLegalPersonOrgNumber('5564300142')).toBe(true)
|
||||
expect(isLegalPersonOrgNumber('9696789012')).toBe(true)
|
||||
expect(isLegalPersonOrgNumber('19800101-1234')).toBe(false)
|
||||
expect(isLegalPersonOrgNumber('8001011234')).toBe(false)
|
||||
expect(isLegalPersonOrgNumber('')).toBe(false)
|
||||
expect(isLegalPersonOrgNumber(null)).toBe(false)
|
||||
})
|
||||
|
||||
it('builds PeOrgNr with the 16 prefix', () => {
|
||||
expect(toPeOrgNr('556012-5790')).toBe('165560125790')
|
||||
})
|
||||
})
|
||||
|
||||
describe('config', () => {
|
||||
it('is configured only when both the certificate and its password are set', () => {
|
||||
const env = (v: Record<string, string>) => v as unknown as NodeJS.ProcessEnv
|
||||
expect(isScbConfigured(env({}))).toBe(false)
|
||||
expect(isScbConfigured(env({ SCB_API_CERT_PFX_BASE64: 'AAAA' }))).toBe(false)
|
||||
expect(isScbConfigured(env({ SCB_API_CERT_PFX_BASE64: 'AAAA', SCB_API_CERT_PASSWORD: 'x' }))).toBe(true)
|
||||
const cfg = scbConfigFromEnv(env({ SCB_API_CERT_PFX_BASE64: Buffer.from('pfx').toString('base64'), SCB_API_CERT_PASSWORD: 'x', SCB_API_BASE_URL: 'https://example.test/base/' }))
|
||||
expect(cfg.baseUrl).toBe('https://example.test/base')
|
||||
expect(cfg.pfx.toString()).toBe('pfx')
|
||||
expect(() => scbConfigFromEnv(env({}))).toThrow(/SCB_API_CERT_PFX_BASE64/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('factsFromScbCompany on a live row', () => {
|
||||
it('maps the Volvo row with SCB codes and SCB text', () => {
|
||||
const facts = factsFromScbCompany(volvo)
|
||||
const by = Object.fromEntries(facts.map((f) => [f.field, f.value]))
|
||||
expect(by.legal_name).toBe('AKTIEBOLAGET VOLVO')
|
||||
expect(by.trade_name).toBeUndefined()
|
||||
expect(by.f_tax).toEqual({ code: '1', label: 'Är registrerad för F-skatt' })
|
||||
expect(by.vat_registration).toEqual({ code: '1', label: 'Är registrerad för moms' })
|
||||
expect(by.employer_registration).toEqual({ code: '1', label: 'Är registrerad som vanlig arbetsgivare' })
|
||||
expect(by.company_status).toEqual({ code: '1', label: 'Är verksam' })
|
||||
expect(by.legal_form).toEqual({ code: '49', label: 'Övriga aktiebolag' })
|
||||
expect(by.bolagsverket_status).toEqual({ code: '0', label: 'Normalläge', warning: false })
|
||||
expect(by.employees_band).toEqual({ code: '8', label: '200-499 anställda' })
|
||||
expect(by.registered_skv).toBeUndefined()
|
||||
expect(by.vat_number).toBe('SE556012579001')
|
||||
expect(by.industry).toEqual({ code: '70100', label: 'Verksamheter som utövas av huvudkontor' })
|
||||
expect(by.postal_address).toEqual({ street: null, co: null, postal_code: '405 08', city: 'GÖTEBORG' })
|
||||
expect(by.seat).toEqual({ municipality_code: '1480', county_code: '14', municipality: 'Göteborg', county: 'Västra Götaland' })
|
||||
expect(by.turnover_band).toEqual({ code: '10', label: '1 000 000 - 4 999 999 tkr', year: '2025' })
|
||||
expect(by.registered_at).toBe('1972-01-01')
|
||||
expect(by.active_since).toBe('1972-01-01')
|
||||
expect(by.active_until).toBeUndefined()
|
||||
expect(by.phone).toBe('031660000')
|
||||
expect(by.email).toBeUndefined()
|
||||
expect(by.workplaces).toBe(1)
|
||||
})
|
||||
|
||||
it('flags a company in konkurs, falls back to our labels without SCB text, and tolerates an empty row', () => {
|
||||
const facts = factsFromScbCompany({ Företagsnamn: 'Gone AB', 'Bolagsstatus, kod': '20', 'Fskattstatus, kod': '9 ' })
|
||||
const by = Object.fromEntries(facts.map((f) => [f.field, f.value]))
|
||||
expect(by.legal_name).toBe('Gone AB')
|
||||
expect(by.bolagsverket_status).toEqual({ code: '20', label: 'Konkurs inledd', warning: true })
|
||||
expect(by.f_tax).toEqual({ code: '9', label: 'Avregistrerad för F-skatt' })
|
||||
expect(by.vat_number).toBeUndefined()
|
||||
expect(factsFromScbCompany({ OrgNr: '5560125790', 'Momsstatus, kod': '9' }).find((f) => f.field === 'vat_number')).toBeUndefined()
|
||||
expect(BOLAGSVERKET_WARNING_CODES.has('0')).toBe(false)
|
||||
expect(BOLAGSVERKET_WARNING_CODES.has('49')).toBe(false) // fusion pågår
|
||||
expect(BOLAGSVERKET_WARNING_CODES.has('41')).toBe(true) // upplöst genom fusion
|
||||
expect(factsFromScbCompany({})).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('createScbClient', () => {
|
||||
const cfg = { baseUrl: 'https://scb.test', pfx: Buffer.from('x'), passphrase: 'p', timeoutMs: 1 }
|
||||
|
||||
it('sends the identity filter the live API accepts', () => {
|
||||
expect(identityLookupBody('5560125790')).toEqual({
|
||||
Variabler: [{ Variabel: 'OrgNr (10 siffror)', Operator: 'ArLikaMed', Varde1: '5560125790', Varde2: '' }],
|
||||
Kategorier: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a sole trader before any call is made', async () => {
|
||||
const json = async () => {
|
||||
throw new Error('should not be called')
|
||||
}
|
||||
const client = createScbClient(cfg, { json: json as never })
|
||||
await expect(client.lookupByOrgNumber('8001011234')).rejects.toThrow(/juridiska personer/)
|
||||
})
|
||||
|
||||
it('posts HamtaForetag and maps the returned row', async () => {
|
||||
const calls: Array<{ method: string; path: string; body: unknown }> = []
|
||||
const json = async (_c: unknown, method: string, path: string, body?: unknown) => {
|
||||
calls.push({ method, path, body })
|
||||
return [volvo]
|
||||
}
|
||||
const client = createScbClient(cfg, { json: json as never })
|
||||
const r = await client.lookupByOrgNumber('556012-5790')
|
||||
expect(calls[0]!.method).toBe('POST')
|
||||
expect(calls[0]!.path).toBe('/api/Je/HamtaForetag')
|
||||
expect(calls[0]!.body).toEqual(identityLookupBody('5560125790'))
|
||||
expect(r.found).toBe(true)
|
||||
expect(r.peOrgNr).toBe('165560125790')
|
||||
expect(r.facts.find((f) => f.field === 'legal_name')?.value).toBe('AKTIEBOLAGET VOLVO')
|
||||
})
|
||||
|
||||
it('reports not found when the list is empty', async () => {
|
||||
const json = async () => []
|
||||
const client = createScbClient(cfg, { json: json as never })
|
||||
const r = await client.lookupByOrgNumber('5564300142')
|
||||
expect(r.found).toBe(false)
|
||||
expect(r.facts).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('name search', () => {
|
||||
it('strips AP prefixes, numbers and legal forms from the query', () => {
|
||||
expect(nameQuery('Levfakt Telia Sverige AB (17)')).toBe('Telia Sverige')
|
||||
expect(nameQuery('Leverantörsfaktura från 18 Loopia')).toBe('Loopia')
|
||||
expect(nameQuery('Adobe Systems Software')).toBe('Adobe Systems Software')
|
||||
expect(nameQuery("O'Learys Sundsvall AB")).toBe('OLearys Sundsvall')
|
||||
// Foreign legal forms stay: they are part of the registered name and dropping them floods.
|
||||
expect(nameQuery('Schmidt GmbH')).toBe('Schmidt GmbH')
|
||||
expect(nameQuery('Google Cloud EMEA Limited')).toBe('Google Cloud EMEA Limited')
|
||||
expect(nameSearchBody('Telia', 'starts_with').Variabler[0]).toEqual({ Variabel: 'Namn', Operator: 'BorjarPa', Varde1: 'Telia', Varde2: '' })
|
||||
expect(nameSearchBody('Telia', 'contains').Variabler[0]!.Operator).toBe('Innehaller')
|
||||
})
|
||||
|
||||
const cfg = { baseUrl: 'https://scb.test', pfx: Buffer.from('x'), passphrase: 'p', timeoutMs: 1 }
|
||||
const row = (org: string, name: string, statusCode = '1', legalForm = '49', city = 'STOCKHOLM') => ({
|
||||
OrgNr: org,
|
||||
Företagsnamn: name,
|
||||
PostOrt: city,
|
||||
Bransch_1: 'Utgivning av annan programvara',
|
||||
'Företagsstatus, kod': statusCode,
|
||||
Företagsstatus: statusCode === '1' ? 'Är verksam' : 'Är ej längre verksam',
|
||||
'Juridisk form, kod': legalForm,
|
||||
'Juridisk form': 'Övriga aktiebolag',
|
||||
})
|
||||
|
||||
it('counts first, prefers a prefix match, sorts active companies first and drops natural persons', async () => {
|
||||
const calls: string[] = []
|
||||
const json = async (_c: unknown, _m: string, path: string, body: { Variabler: Array<{ Operator: string }> }) => {
|
||||
calls.push(`${path}:${body.Variabler[0]!.Operator}`)
|
||||
if (path.endsWith('RaknaForetag')) return 3
|
||||
return [row('5020594593', 'ADOBE SYSTEMS SOFTWARE IRELAND LTD', '9'), row('5564082161', 'Adobe Systems Nordic Aktiebolag'), row('8001011234', 'ADOBE, ANNA', '1', '10')]
|
||||
}
|
||||
const client = createScbClient(cfg, { json: json as never })
|
||||
const r = await client.searchByName('Levfakt Adobe Systems (2)')
|
||||
expect(calls).toEqual(['/api/Je/RaknaForetag:BorjarPa', '/api/Je/HamtaForetag:BorjarPa'])
|
||||
expect(r.mode).toBe('starts_with')
|
||||
expect(r.total).toBe(2)
|
||||
expect(r.candidates.map((c) => [c.name, c.active])).toEqual([
|
||||
['Adobe Systems Nordic Aktiebolag', true],
|
||||
['ADOBE SYSTEMS SOFTWARE IRELAND LTD', false],
|
||||
])
|
||||
})
|
||||
|
||||
it('falls back to a contains match when the prefix finds nothing, and refuses to pull a flood', async () => {
|
||||
const calls: string[] = []
|
||||
const json = async (_c: unknown, _m: string, path: string, body: { Variabler: Array<{ Operator: string; Varde1: string }> }) => {
|
||||
calls.push(`${path}:${body.Variabler[0]!.Operator}`)
|
||||
if (path.endsWith('RaknaForetag')) return body.Variabler[0]!.Operator === 'BorjarPa' ? 0 : 593
|
||||
throw new Error('should not fetch rows for a flood')
|
||||
}
|
||||
const client = createScbClient(cfg, { json: json as never })
|
||||
const r = await client.searchByName('UBER')
|
||||
expect(calls).toEqual(['/api/Je/RaknaForetag:BorjarPa', '/api/Je/RaknaForetag:Innehaller'])
|
||||
expect(r).toMatchObject({ mode: 'contains', total: 593, truncated: true, candidates: [] })
|
||||
expect(SCB_SEARCH_CAP).toBe(25)
|
||||
})
|
||||
|
||||
it('does not call SCB for a query shorter than two characters', async () => {
|
||||
const json = async () => {
|
||||
throw new Error('should not be called')
|
||||
}
|
||||
const r = await createScbClient(cfg, { json: json as never }).searchByName('Levfakt 17')
|
||||
expect(r.candidates).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('scbJson', () => {
|
||||
const cfg = { baseUrl: 'https://scb.test', pfx: Buffer.from('x'), passphrase: 'p', timeoutMs: 1 }
|
||||
|
||||
it('retries once on a dropped connection, then succeeds', async () => {
|
||||
let n = 0
|
||||
const request = async () => {
|
||||
n += 1
|
||||
if (n === 1) throw Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' })
|
||||
return { status: 200, body: '3' }
|
||||
}
|
||||
await expect(scbJson(cfg, 'POST', '/api/Je/RaknaForetag', {}, { request: request as never, delayMs: 0 })).resolves.toBe(3)
|
||||
expect(n).toBe(2)
|
||||
})
|
||||
|
||||
it('does not retry a non-transient error or a bad status', async () => {
|
||||
let n = 0
|
||||
const boom = async () => {
|
||||
n += 1
|
||||
throw new Error('certificate unknown')
|
||||
}
|
||||
await expect(scbJson(cfg, 'GET', '/x', undefined, { request: boom as never, delayMs: 0 })).rejects.toThrow(/certificate/)
|
||||
expect(n).toBe(1)
|
||||
const bad = async () => ({ status: 400, body: '{"Message":"Ogiltigt"}' })
|
||||
await expect(scbJson(cfg, 'GET', '/x', undefined, { request: bad as never })).rejects.toBeInstanceOf(ScbApiError)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
import type { ScbConfig } from './config'
|
||||
import { factsFromScbCompany, type ScbCompanyRow, type ScbFact } from './map'
|
||||
import { isLegalPersonOrgNumber, toPeOrgNr } from './org-number'
|
||||
import { scbJson } from './transport'
|
||||
|
||||
/**
|
||||
* The wire format of the current SokPaVar API, checked against the live
|
||||
* service on 2026-09-03 (scripts/scb/discover.ts, help page at
|
||||
* <base>/help). A search is a list of variable filters; an identity lookup
|
||||
* is one filter on "OrgNr (10 siffror)" with operator ArLikaMed, and
|
||||
* without Företagsstatus/Registreringsstatus so a deregistered company is
|
||||
* still returned (an empty string there is rejected with 400). The row
|
||||
* comes back with every purchased column, codes and texts side by side.
|
||||
*/
|
||||
export const SCB_ORG_VARIABLE = 'OrgNr (10 siffror)'
|
||||
|
||||
export interface ScbLookupResult {
|
||||
found: boolean
|
||||
peOrgNr: string
|
||||
row: ScbCompanyRow | null
|
||||
facts: ScbFact[]
|
||||
fetchedAt: string
|
||||
}
|
||||
|
||||
export interface ScbCandidate {
|
||||
orgNumber: string
|
||||
name: string
|
||||
city: string | null
|
||||
industry: string | null
|
||||
legalForm: string | null
|
||||
/** SCB's own status text; active is Företagsstatus code 1. */
|
||||
status: string | null
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export interface ScbSearchResult {
|
||||
query: string
|
||||
/** How SCB was asked: a prefix match first, a contains match as fallback. */
|
||||
mode: 'starts_with' | 'contains'
|
||||
/** Rows SCB counted before the cap; above the cap the list is cut and the user should refine. */
|
||||
total: number
|
||||
truncated: boolean
|
||||
candidates: ScbCandidate[]
|
||||
}
|
||||
|
||||
export interface ScbClient {
|
||||
variables(): Promise<unknown>
|
||||
categories(): Promise<unknown>
|
||||
lookupByOrgNumber(orgNumber: string): Promise<ScbLookupResult>
|
||||
searchByName(query: string): Promise<ScbSearchResult>
|
||||
}
|
||||
|
||||
/** Candidates shown per search; SCB can return thousands for a short word. */
|
||||
export const SCB_SEARCH_CAP = 25
|
||||
/** Legal forms never offered in the picker: natural persons and estates. */
|
||||
const NON_COMPANY_LEGAL_FORMS = new Set(['10', '91'])
|
||||
|
||||
/**
|
||||
* What we send SCB for a name: the AP prefix, supplier numbers and a
|
||||
* trailing legal form are noise ("Levfakt Telia Sverige AB (17)" becomes
|
||||
* "Telia Sverige"). SCB's name filter refuses an apostrophe.
|
||||
*/
|
||||
export function nameQuery(raw: string): string {
|
||||
return raw
|
||||
.replace(/^(levfakt|levfkt|lev\.?fakt\.?|leverantörsfaktura från\s*\d*|leverantörsfaktura|levbet\.?|kundbet\.?|kundfaktura|faktura från|faktura|kvitto|utgift|inköp)\s+/i, '')
|
||||
.replace(/[(),]/g, ' ')
|
||||
.replace(/\b\d{1,6}\b/g, ' ')
|
||||
.replace(/\s+(ab|aktiebolag|hb|kb|publ|\(publ\))\.?\s*$/i, '')
|
||||
.replace(/'/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
export function nameSearchBody(query: string, mode: 'starts_with' | 'contains') {
|
||||
return {
|
||||
Variabler: [{ Variabel: 'Namn', Operator: mode === 'starts_with' ? 'BorjarPa' : 'Innehaller', Varde1: query, Varde2: '' }],
|
||||
Kategorier: [],
|
||||
}
|
||||
}
|
||||
|
||||
function candidateFrom(row: ScbCompanyRow): ScbCandidate | null {
|
||||
const org = String(row.OrgNr ?? '').replace(/[^0-9]/g, '')
|
||||
const legalFormCode = String(row['Juridisk form, kod'] ?? '').trim()
|
||||
if (org.length !== 10 || NON_COMPANY_LEGAL_FORMS.has(legalFormCode)) return null
|
||||
const str = (k: string) => {
|
||||
const v = row[k]
|
||||
const t = v === null || v === undefined ? '' : String(v).trim()
|
||||
return t === '' ? null : t
|
||||
}
|
||||
return {
|
||||
orgNumber: org,
|
||||
name: str('Företagsnamn') ?? org,
|
||||
city: str('PostOrt'),
|
||||
industry: str('Bransch_1'),
|
||||
legalForm: str('Juridisk form'),
|
||||
status: str('Företagsstatus'),
|
||||
active: String(row['Företagsstatus, kod'] ?? '').trim() === '1',
|
||||
}
|
||||
}
|
||||
|
||||
export function identityLookupBody(orgNumber10: string) {
|
||||
return {
|
||||
Variabler: [{ Variabel: SCB_ORG_VARIABLE, Operator: 'ArLikaMed', Varde1: orgNumber10, Varde2: '' }],
|
||||
Kategorier: [],
|
||||
}
|
||||
}
|
||||
|
||||
export function createScbClient(config: ScbConfig, deps: { json?: typeof scbJson } = {}): ScbClient {
|
||||
const json = deps.json ?? scbJson
|
||||
return {
|
||||
variables: () => json(config, 'GET', '/api/Je/Variabler'),
|
||||
categories: () => json(config, 'GET', '/api/Je/KategorierMedKodtabeller'),
|
||||
async lookupByOrgNumber(orgNumber) {
|
||||
if (!isLegalPersonOrgNumber(orgNumber)) {
|
||||
throw new Error('SCB-uppslag görs bara på organisationsnummer för juridiska personer.')
|
||||
}
|
||||
const org10 = orgNumber.replace(/[^0-9]/g, '')
|
||||
const peOrgNr = toPeOrgNr(org10)
|
||||
const fetchedAt = new Date().toISOString()
|
||||
const rows = await json<ScbCompanyRow[]>(config, 'POST', '/api/Je/HamtaForetag', identityLookupBody(org10))
|
||||
const list = Array.isArray(rows) ? rows : []
|
||||
const row = list.find((r) => String(r.OrgNr ?? r.PeOrgNr ?? '').replace(/[^0-9]/g, '').endsWith(org10)) ?? null
|
||||
return { found: Boolean(row), peOrgNr, row, facts: row ? factsFromScbCompany(row) : [], fetchedAt }
|
||||
},
|
||||
async searchByName(raw) {
|
||||
const query = nameQuery(raw)
|
||||
if (query.length < 2) return { query, mode: 'starts_with', total: 0, truncated: false, candidates: [] }
|
||||
// Count first: a short word can match thousands and we never pull those.
|
||||
const run = async (mode: 'starts_with' | 'contains'): Promise<ScbSearchResult> => {
|
||||
const body = nameSearchBody(query, mode)
|
||||
const total = Number(await json<number | string>(config, 'POST', '/api/Je/RaknaForetag', body)) || 0
|
||||
if (total === 0) return { query, mode, total, truncated: false, candidates: [] }
|
||||
if (total > SCB_SEARCH_CAP * 4) return { query, mode, total, truncated: true, candidates: [] }
|
||||
const rows = await json<ScbCompanyRow[]>(config, 'POST', '/api/Je/HamtaForetag', body)
|
||||
const all = (Array.isArray(rows) ? rows : []).map(candidateFrom).filter((c): c is ScbCandidate => c !== null)
|
||||
// Active companies first, then by name; the cap keeps the picker a picker.
|
||||
all.sort((a, b) => Number(b.active) - Number(a.active) || a.name.localeCompare(b.name, 'sv'))
|
||||
// total is what the picker can offer: SCB's count minus the natural
|
||||
// persons and estates we never show ("Eismann" counted 1, offered 0).
|
||||
return { query, mode, total: all.length, truncated: all.length > SCB_SEARCH_CAP, candidates: all.slice(0, SCB_SEARCH_CAP) }
|
||||
}
|
||||
const first = await run('starts_with')
|
||||
if (first.total > 0 || first.truncated || query.length < 4) return first
|
||||
return run('contains')
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* SCB:s allmänna företagsregister, the free API (SokPaVar layout Je).
|
||||
*
|
||||
* Access is a client certificate SCB issues per user plus its password; both
|
||||
* live in env vars only, never in settings or the repository:
|
||||
* SCB_API_CERT_PFX_BASE64 the .pfx SCB mailed, base64-encoded
|
||||
* SCB_API_CERT_PASSWORD the password SCB mailed separately
|
||||
* SCB_API_BASE_URL optional override (default: the current API)
|
||||
*
|
||||
* SCB replaces this API with an API-key one from September 2026 and keeps
|
||||
* the current one for a transition period; everything that knows the wire
|
||||
* format sits in client.ts so the swap is one file.
|
||||
*/
|
||||
|
||||
export interface ScbConfig {
|
||||
baseUrl: string
|
||||
pfx: Buffer
|
||||
passphrase: string
|
||||
timeoutMs: number
|
||||
}
|
||||
|
||||
export const SCB_DEFAULT_BASE_URL = 'https://privateapi.scb.se/nv0101/v1/sokpavar'
|
||||
|
||||
/** True when the hosted environment carries SCB credentials: gates the button. */
|
||||
export function isScbConfigured(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
return Boolean(env.SCB_API_CERT_PFX_BASE64 && env.SCB_API_CERT_PASSWORD)
|
||||
}
|
||||
|
||||
export function scbConfigFromEnv(env: NodeJS.ProcessEnv = process.env): ScbConfig {
|
||||
const pfx = env.SCB_API_CERT_PFX_BASE64
|
||||
const passphrase = env.SCB_API_CERT_PASSWORD
|
||||
if (!pfx || !passphrase) {
|
||||
throw new Error('SCB är inte konfigurerat: SCB_API_CERT_PFX_BASE64 och SCB_API_CERT_PASSWORD saknas.')
|
||||
}
|
||||
return {
|
||||
baseUrl: (env.SCB_API_BASE_URL ?? SCB_DEFAULT_BASE_URL).replace(/\/+$/, ''),
|
||||
pfx: Buffer.from(pfx, 'base64'),
|
||||
passphrase,
|
||||
timeoutMs: 20_000,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* From SCB's Je layout to party facts. Codes come from "Variabelbeskrivning
|
||||
* API" (SCB:s allmänna företagsregister, 28 pages, saved in
|
||||
* dev_docs/scb_docs); labels are Swedish because the dossier shows them as
|
||||
* they are and the register is Swedish by nature.
|
||||
*/
|
||||
|
||||
export interface ScbFact {
|
||||
field: string
|
||||
value: unknown
|
||||
reference?: Record<string, unknown>
|
||||
valid_from?: string
|
||||
}
|
||||
|
||||
const F_SKATT: Record<string, string> = {
|
||||
'0': 'Har aldrig varit registrerat för F-skatt',
|
||||
'1': 'Godkänd för F-skatt',
|
||||
'9': 'Avregistrerad för F-skatt',
|
||||
}
|
||||
const MOMS: Record<string, string> = {
|
||||
'0': 'Har aldrig varit registrerat för moms',
|
||||
'1': 'Momsregistrerad',
|
||||
'3': 'Momsregistrerad via representant',
|
||||
'9': 'Avregistrerad för moms',
|
||||
}
|
||||
const ARBETSGIVARE: Record<string, string> = {
|
||||
'0': 'Har aldrig varit registrerad som arbetsgivare',
|
||||
'1': 'Registrerad som arbetsgivare',
|
||||
'2': 'Registrerad som privatarbetsgivare',
|
||||
'3': 'Registrerad som arbetsgivare via representant',
|
||||
'4': 'Registrerad som ambassad eller konsulat',
|
||||
'9': 'Avregistrerad som arbetsgivare',
|
||||
}
|
||||
const FORETAGSSTATUS: Record<string, string> = {
|
||||
'0': 'Har aldrig varit verksamt',
|
||||
'1': 'Verksamt',
|
||||
'9': 'Ej verksamt',
|
||||
}
|
||||
export const JURIDISK_FORM: Record<string, string> = {
|
||||
'10': 'Fysisk person',
|
||||
'21': 'Enkelt bolag',
|
||||
'22': 'Partrederi',
|
||||
'23': 'Värdepappersfond',
|
||||
'31': 'Handelsbolag eller kommanditbolag',
|
||||
'32': 'Gruvbolag',
|
||||
'41': 'Bankaktiebolag',
|
||||
'42': 'Försäkringsaktiebolag',
|
||||
'43': 'Europabolag',
|
||||
'49': 'Aktiebolag',
|
||||
'51': 'Ekonomisk förening',
|
||||
'53': 'Bostadsrättsförening',
|
||||
'54': 'Kooperativ hyresrättsförening',
|
||||
'55': 'Europakooperativ',
|
||||
'61': 'Ideell förening',
|
||||
'62': 'Samfällighet',
|
||||
'63': 'Registrerat trossamfund',
|
||||
'71': 'Familjestiftelse',
|
||||
'72': 'Stiftelse eller fond',
|
||||
'81': 'Statlig enhet',
|
||||
'82': 'Kommun',
|
||||
'83': 'Kommunalförbund',
|
||||
'84': 'Region',
|
||||
'85': 'Allmän försäkringskassa',
|
||||
'87': 'Offentlig korporation eller anstalt',
|
||||
'88': 'Hypoteksförening',
|
||||
'89': 'Regional statlig myndighet',
|
||||
'91': 'Oskiftat dödsbo',
|
||||
'92': 'Ömsesidigt försäkringsbolag',
|
||||
'93': 'Sparbank',
|
||||
'94': 'Understöds- eller försäkringsförening',
|
||||
'95': 'Arbetslöshetskassa',
|
||||
'96': 'Utländsk juridisk person',
|
||||
'98': 'Övrig svensk juridisk person',
|
||||
'99': 'Juridisk form ej utredd',
|
||||
}
|
||||
const BOLAGSVERKET_STATUS: Record<string, string> = {
|
||||
'0': 'Normalläge',
|
||||
'11': 'Ackordsförhandling inledd',
|
||||
'12': 'Ackordsförhandling upphör',
|
||||
'13': 'Ackordsförhandling upphävd av domstol',
|
||||
'20': 'Konkurs inledd',
|
||||
'21': 'Konkurs avslutad',
|
||||
'22': 'Konkurs avslutad med överskott',
|
||||
'24': 'Konkurs upphävd av rätt',
|
||||
'31': 'Likvidation avslutad',
|
||||
'32': 'Likvidation beslutad',
|
||||
'33': 'Likvidation fortsätter',
|
||||
'34': 'Likvidation upphör, verksamheten återupptas',
|
||||
'35': 'Likvidation upphävd av domstol',
|
||||
'36': 'Bolaget avfört enligt 13 kap 18 § ABL',
|
||||
'37': 'Bolaget är avfört',
|
||||
'40': 'Fusion inledd',
|
||||
'41': 'Upplöst genom fusion',
|
||||
'45': 'Fusion tillåten',
|
||||
'49': 'Fusion pågår',
|
||||
'50': 'Avförd enligt 17 § handelsregisterlagen',
|
||||
'51': 'Avförd',
|
||||
'52': 'Avregistrerad',
|
||||
'53': 'Avregistrerad på grund av ny innehavare',
|
||||
'54': 'Avförd på grund av fusion med utländskt företag',
|
||||
'60': 'Avförd på grund av utländskt företags likvidation eller konkurs',
|
||||
'61': 'Avförd, verksamheten har upphört',
|
||||
'62': 'Avförd, filialen saknar verkställande direktör',
|
||||
'63': 'Avförd enligt domstolsbeslut',
|
||||
'64': 'Avförd, årsredovisning saknas',
|
||||
'70': 'Bolaget avfört på egen begäran',
|
||||
'71': 'Bolaget avfört av Bolagsverket',
|
||||
'73': 'Avförd',
|
||||
'74': 'Avförd, omregistrerat till bankaktiebolag',
|
||||
'75': 'Beslut om ombildning',
|
||||
'76': 'Tillstånd till ombildning',
|
||||
'77': 'Avregistrerad på grund av ombildning',
|
||||
'78': 'Ombildning förfallen',
|
||||
'80': 'Företagsrekonstruktion inledd',
|
||||
'81': 'Företagsrekonstruktion upphörd',
|
||||
'82': 'Företagsrekonstruktion upphävd av domstol',
|
||||
'85': 'Resolution inledd',
|
||||
'86': 'Resolution avslutad',
|
||||
'87': 'Resolution upphävd',
|
||||
'90': 'Delning pågår',
|
||||
'91': 'Upplöst genom delning',
|
||||
'99': 'Övertagande av annat bolag pågår',
|
||||
}
|
||||
const STORLEKSKLASS: Record<string, string> = {
|
||||
'0': 'Uppgift saknas',
|
||||
'1': '0 anställda',
|
||||
'2': '1 till 4 anställda',
|
||||
'3': '5 till 9 anställda',
|
||||
'4': '10 till 19 anställda',
|
||||
'5': '20 till 49 anställda',
|
||||
'6': '50 till 99 anställda',
|
||||
'7': '100 till 199 anställda',
|
||||
'8': '200 till 499 anställda',
|
||||
'9': '500 till 999 anställda',
|
||||
'10': '1 000 till 1 499 anställda',
|
||||
'11': '1 500 till 1 999 anställda',
|
||||
'12': '2 000 till 2 999 anställda',
|
||||
'13': '3 000 till 3 999 anställda',
|
||||
'14': '4 000 till 4 999 anställda',
|
||||
'15': '5 000 till 9 999 anställda',
|
||||
'16': '10 000 anställda eller fler',
|
||||
}
|
||||
|
||||
/**
|
||||
* Which Bolagsverket statuses mean "do not treat this as a going concern":
|
||||
* distress (ackord, konkurs, likvidation, rekonstruktion, resolution) and
|
||||
* disappearance (avförd, avregistrerad, upplöst). A fusion or delning in
|
||||
* progress is not a warning: Fortnox AB and Avanza Bank carried "Fusion
|
||||
* pågår" on 2026-09-03 while trading normally.
|
||||
*/
|
||||
export const BOLAGSVERKET_WARNING_CODES = new Set(['11', '12', '13', '20', '32', '33', '36', '37', '41', '50', '51', '52', '53', '54', '60', '61', '62', '63', '64', '70', '71', '73', '77', '80', '85', '91'])
|
||||
|
||||
/**
|
||||
* A company row as the API returns it (fixture: __tests__/fixtures/
|
||||
* volvo-je.json, fetched live 2026-09-03). Codes come as "<name>, kod" and
|
||||
* SCB's own text as "<name>"; values are space-padded. Lookups are tolerant
|
||||
* of case, spacing and diacritics so a renamed column in the new API still
|
||||
* maps, and SCB's text wins over our label table when both exist.
|
||||
*/
|
||||
export type ScbCompanyRow = Record<string, unknown>
|
||||
|
||||
function pick(row: ScbCompanyRow, ...names: string[]): string | null {
|
||||
const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||
const wanted = new Set(names.map(norm))
|
||||
for (const [k, v] of Object.entries(row)) {
|
||||
if (wanted.has(norm(k))) {
|
||||
if (v === null || v === undefined) return null
|
||||
const s = String(v).trim()
|
||||
return s === '' ? null : s
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function coded(field: string, code: string | null, table: Record<string, string>, extra: Record<string, unknown> = {}, text: string | null = null): ScbFact | null {
|
||||
if (code === null) return null
|
||||
const c = code.replace(/^0+(?=\d)/, '') || '0'
|
||||
return { field, value: { code: c, label: text ?? table[c] ?? `Kod ${c}`, ...extra } }
|
||||
}
|
||||
|
||||
function isoDate(s: string | null): string | null {
|
||||
if (!s) return null
|
||||
const d = s.replace(/[^0-9]/g, '')
|
||||
if (d.length === 8) return `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`
|
||||
if (/^\d{4}-\d{2}-\d{2}/.test(s)) return s.slice(0, 10)
|
||||
return null
|
||||
}
|
||||
|
||||
/** Map one Je row to facts. Unknown or empty variables simply produce nothing. */
|
||||
export function factsFromScbCompany(row: ScbCompanyRow): ScbFact[] {
|
||||
const out: ScbFact[] = []
|
||||
const push = (f: ScbFact | null) => {
|
||||
if (f) out.push(f)
|
||||
}
|
||||
|
||||
const name = pick(row, 'Företagsnamn', 'Foretagsnamn', 'Namn')
|
||||
if (name) push({ field: 'legal_name', value: name })
|
||||
const firma = pick(row, 'Firma')
|
||||
if (firma && firma !== name) push({ field: 'trade_name', value: firma })
|
||||
|
||||
// "<name>, kod" carries the code, "<name>" SCB's text. A column without
|
||||
// the ", kod" twin (older layouts) is a bare code.
|
||||
const codeOf = (...names: string[]) => pick(row, ...names.map((n) => `${n}, kod`), ...names)
|
||||
const textOf = (...names: string[]) => {
|
||||
const t = pick(row, ...names)
|
||||
return t && !/^\d+$/.test(t) ? t : null
|
||||
}
|
||||
push(coded('f_tax', codeOf('Fskattstatus', 'F-skattstatus'), F_SKATT, {}, textOf('Fskattstatus', 'F-skattstatus')))
|
||||
push(coded('vat_registration', codeOf('Momsstatus'), MOMS, {}, textOf('Momsstatus')))
|
||||
push(coded('employer_registration', codeOf('Arbetsgivarstatus'), ARBETSGIVARE, {}, textOf('Arbetsgivarstatus')))
|
||||
push(coded('company_status', codeOf('Företagsstatus', 'Foretagsstatus'), FORETAGSSTATUS, {}, textOf('Företagsstatus', 'Foretagsstatus')))
|
||||
push(coded('legal_form', codeOf('Juridisk form'), JURIDISK_FORM, {}, textOf('Juridisk form')))
|
||||
const bv = codeOf('Bolagsstatus', 'Status hos Bolagsverket')
|
||||
push(coded('bolagsverket_status', bv, BOLAGSVERKET_STATUS, bv ? { warning: BOLAGSVERKET_WARNING_CODES.has(bv.replace(/^0+(?=\d)/, '') || '0') } : {}, textOf('Bolagsstatus', 'Status hos Bolagsverket')))
|
||||
push(coded('employees_band', codeOf('Stkl', 'Storleksklass Anställda'), STORLEKSKLASS, {}, textOf('Storleksklass', 'Storleksklass Anställda')))
|
||||
|
||||
// A Swedish company registered for moms has VAT number SE + org number + 01
|
||||
// by construction (Skatteverket assigns no other form), so the registry's
|
||||
// moms flag gives the number itself. Represented as a fact so the source
|
||||
// and date travel with it; the supplier row copies it on promotion.
|
||||
const momsCode = codeOf('Momsstatus')
|
||||
const org = pick(row, 'OrgNr')
|
||||
if ((momsCode === '1' || momsCode === '3') && org && /^\d{10}$/.test(org)) {
|
||||
push({ field: 'vat_number', value: `SE${org}01` })
|
||||
}
|
||||
|
||||
const sni = pick(row, 'Bransch_1, kod', 'Bransch_1', 'Bransch', 'SNI')
|
||||
const sniText = textOf('Bransch_1', 'Bransch_1, text', 'Bransch')
|
||||
if (sni && /^\d/.test(sni)) push({ field: 'industry', value: { code: sni, label: sniText } })
|
||||
|
||||
const street = pick(row, 'PostAdress', 'Postadress')
|
||||
const postal = pick(row, 'PostNr', 'Postnr', 'Postnummer')
|
||||
const city = pick(row, 'PostOrt', 'Postort')
|
||||
const co = pick(row, 'COAdress', 'COadress', 'C/O-adress')
|
||||
if (street || postal || city) push({ field: 'postal_address', value: { street, co, postal_code: postal, city } })
|
||||
|
||||
const municipality = pick(row, 'Säteskommun, kod', 'Sateskommun, kod')
|
||||
const county = pick(row, 'Säteslän, kod', 'Sateslan, kod')
|
||||
const municipalityName = textOf('Säteskommun', 'Sateskommun')
|
||||
const countyName = textOf('Säteslän', 'Sateslan')
|
||||
if (municipality || county || municipalityName) {
|
||||
push({ field: 'seat', value: { municipality_code: municipality, county_code: county, municipality: municipalityName, county: countyName } })
|
||||
}
|
||||
|
||||
const turnoverYear = pick(row, 'Omsättning, år', 'Omsattning, ar')
|
||||
const turnoverBand = textOf('Storleksklass, oms')
|
||||
const turnoverCode = codeOf('Stkl, oms')
|
||||
if (turnoverBand || turnoverCode) push({ field: 'turnover_band', value: { code: turnoverCode, label: turnoverBand, year: turnoverYear } })
|
||||
|
||||
const registered = isoDate(pick(row, 'Registreringsdatum'))
|
||||
if (registered) push({ field: 'registered_at', value: registered })
|
||||
const started = isoDate(pick(row, 'Startdatum'))
|
||||
if (started) push({ field: 'active_since', value: started })
|
||||
const ended = isoDate(pick(row, 'Slutdatum'))
|
||||
if (ended) push({ field: 'active_until', value: ended })
|
||||
|
||||
const phone = pick(row, 'Telefon')
|
||||
if (phone) push({ field: 'phone', value: phone })
|
||||
const email = pick(row, 'E-post', 'Epost', 'E-postadress')
|
||||
if (email) push({ field: 'email', value: email })
|
||||
const workplaces = pick(row, 'Antal arbetsställen', 'AntalArbetsstallen', 'Antal arbetsstallen')
|
||||
if (workplaces && /^\d+$/.test(workplaces)) push({ field: 'workplaces', value: Number(workplaces) })
|
||||
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Which numbers we send to SCB.
|
||||
*
|
||||
* A Swedish organisationsnummer for a juridisk person has 20 or more in
|
||||
* positions 3 and 4 (the "month" slot), which is how it is told apart from a
|
||||
* personnummer. A sole trader's org number IS a personnummer, so a lookup
|
||||
* would be personal-data processing with SCB as an independent controller;
|
||||
* the plan keeps sole traders out of registry enrichment in this phase (no
|
||||
* credit or registry facts on natural persons, GDPR Art. 14 notice first).
|
||||
*/
|
||||
export function isLegalPersonOrgNumber(orgNumber: string | null | undefined): boolean {
|
||||
const d = (orgNumber ?? '').replace(/[^0-9]/g, '')
|
||||
if (d.length !== 10) return false
|
||||
const month = Number(d.slice(2, 4))
|
||||
return month >= 20
|
||||
}
|
||||
|
||||
/** SCB's PeOrgNr: 16 + the ten-digit org number for legal persons. */
|
||||
export function toPeOrgNr(orgNumber: string): string {
|
||||
const d = orgNumber.replace(/[^0-9]/g, '')
|
||||
return d.length === 10 ? `16${d}` : d
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { request as httpsRequest, type RequestOptions } from 'node:https'
|
||||
import type { ScbConfig } from './config'
|
||||
|
||||
export class ScbApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number,
|
||||
public readonly body: string,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ScbApiError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface ScbHttpResponse {
|
||||
status: number
|
||||
body: string
|
||||
}
|
||||
|
||||
/**
|
||||
* One HTTPS request with the client certificate. node:https rather than
|
||||
* fetch: undici's fetch has no portable client-certificate option inside a
|
||||
* Next.js route (same reason the Bolagsverket client does this).
|
||||
*/
|
||||
export function scbRequest(config: ScbConfig, method: 'GET' | 'POST', path: string, jsonBody?: unknown): Promise<ScbHttpResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = new URL(config.baseUrl + path)
|
||||
const payload = jsonBody === undefined ? null : JSON.stringify(jsonBody)
|
||||
const options: RequestOptions = {
|
||||
method,
|
||||
hostname: url.hostname,
|
||||
path: url.pathname + url.search,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {}),
|
||||
},
|
||||
pfx: config.pfx,
|
||||
passphrase: config.passphrase,
|
||||
timeout: config.timeoutMs,
|
||||
}
|
||||
const req = httpsRequest(options, (res) => {
|
||||
const chunks: Buffer[] = []
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||
res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }))
|
||||
})
|
||||
req.on('timeout', () => req.destroy(new Error('SCB svarade inte i tid')))
|
||||
req.on('error', (err) => reject(err))
|
||||
if (payload) req.write(payload)
|
||||
req.end()
|
||||
})
|
||||
}
|
||||
|
||||
const RETRIABLE = new Set(['ECONNRESET', 'ETIMEDOUT', 'ECONNREFUSED', 'EPIPE', 'EAI_AGAIN'])
|
||||
|
||||
function isTransient(err: unknown): boolean {
|
||||
const e = err as { code?: string; message?: string } | null
|
||||
return Boolean(e && ((e.code && RETRIABLE.has(e.code)) || /svarade inte i tid|socket hang up/i.test(e.message ?? '')))
|
||||
}
|
||||
|
||||
/**
|
||||
* One JSON call with a single retry on a dropped connection: SCB resets
|
||||
* the TLS session now and then (seen live 2026-09-03), and every request
|
||||
* here is idempotent (counts, lists, lookups).
|
||||
*/
|
||||
export async function scbJson<T>(
|
||||
config: ScbConfig,
|
||||
method: 'GET' | 'POST',
|
||||
path: string,
|
||||
jsonBody?: unknown,
|
||||
deps: { request?: typeof scbRequest; delayMs?: number } = {},
|
||||
): Promise<T> {
|
||||
const request = deps.request ?? scbRequest
|
||||
let res: ScbHttpResponse
|
||||
try {
|
||||
res = await request(config, method, path, jsonBody)
|
||||
} catch (err) {
|
||||
if (!isTransient(err)) throw err
|
||||
await new Promise((r) => setTimeout(r, deps.delayMs ?? 400))
|
||||
res = await request(config, method, path, jsonBody)
|
||||
}
|
||||
if (res.status < 200 || res.status >= 300) {
|
||||
throw new ScbApiError(`SCB svarade ${res.status} på ${method} ${path}`, res.status, res.body.slice(0, 2000))
|
||||
}
|
||||
try {
|
||||
return JSON.parse(res.body) as T
|
||||
} catch {
|
||||
throw new ScbApiError(`SCB svarade med något annat än JSON på ${method} ${path}`, res.status, res.body.slice(0, 2000))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user