* 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>
219 lines
11 KiB
TypeScript
219 lines
11 KiB
TypeScript
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)
|
|
})
|
|
})
|