* 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>
266 lines
11 KiB
TypeScript
266 lines
11 KiB
TypeScript
/**
|
|
* 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
|
|
}
|