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:
Jakob Wennberg
2026-09-03 20:16:59 +02:00
committed by GitHub
co-authored by Claude Fable 5.1 Jakob Wennberg
parent 47c73206e1
commit 22b98e0a3b
24 changed files with 1935 additions and 48 deletions
@@ -0,0 +1,204 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
import { eventBus } from '@/lib/events'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({ createClient: () => Promise.resolve(mockSupabase) }))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({ requireWritePermission: vi.fn().mockResolvedValue({ ok: true }) }))
const lookupByOrgNumber = vi.fn()
const searchByName = vi.fn()
vi.mock('@/lib/parties/scb/client', () => ({ createScbClient: () => ({ lookupByOrgNumber, searchByName }) }))
const configured = { value: true }
vi.mock('@/lib/parties/scb/config', () => ({
isScbConfigured: () => configured.value,
scbConfigFromEnv: () => ({ baseUrl: 'https://scb.test', pfx: Buffer.from('x'), passphrase: 'p', timeoutMs: 1 }),
}))
import { POST } from '../route'
import { GET as candidatesGet } from '../candidates/route'
const user = { id: 'user-1', email: 'test@test.se' }
const PARTY = '11111111-1111-4111-8111-111111111111'
const OTHER = '22222222-2222-4222-8222-222222222222'
const call = (id = PARTY) => POST(createMockRequest(`/api/parties/${id}/enrich`, { method: 'POST' }), { params: Promise.resolve({ id }) })
const callWith = (body: unknown, id = PARTY) => {
const req = createMockRequest(`/api/parties/${id}/enrich`, { method: 'POST', body })
return POST(req, { params: Promise.resolve({ id }) })
}
const candidates = (q?: string, id = PARTY) => candidatesGet(createMockRequest(`/api/parties/${id}/enrich/candidates${q ? `?q=${encodeURIComponent(q)}` : ''}`), { params: Promise.resolve({ id }) })
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
configured.value = true
mockSupabase.auth.getUser.mockResolvedValue({ data: { user } })
})
describe('POST /api/parties/[id]/enrich', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
expect((await parseJsonResponse(await call())).status).toBe(401)
})
it('returns 503 when SCB is not configured, before touching the database', async () => {
configured.value = false
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await call())
expect(status).toBe(503)
expect(body.error.code).toBe('SCB_NOT_CONFIGURED')
expect(mockSupabase.from).not.toHaveBeenCalled()
})
it('returns 404 for a party outside the company', async () => {
enqueue({ data: null })
expect((await parseJsonResponse(await call())).status).toBe(404)
expect(lookupByOrgNumber).not.toHaveBeenCalled()
})
it('refuses a sole trader with 400 and never calls SCB', async () => {
enqueue({ data: { id: PARTY, org_number: '8001011234', legal_name: null } })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await call())
expect(status).toBe(400)
expect(body.error.code).toBe('SCB_NOT_A_LEGAL_PERSON')
expect(lookupByOrgNumber).not.toHaveBeenCalled()
})
it('maps an SCB failure to 502', async () => {
enqueue({ data: { id: PARTY, org_number: '5560125790', legal_name: null } })
lookupByOrgNumber.mockRejectedValue(new Error('boom'))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await call())
expect(status).toBe(502)
expect(body.error.code).toBe('SCB_LOOKUP_FAILED')
})
it('reports not found without writing anything', async () => {
enqueue({ data: { id: PARTY, org_number: '5560125790', legal_name: null } })
lookupByOrgNumber.mockResolvedValue({ found: false, peOrgNr: '165560125790', row: null, facts: [], fetchedAt: '2026-09-03T10:00:00Z' })
const { status, body } = await parseJsonResponse<{ data: { found: boolean; orgNumber: string } }>(await call())
expect(status).toBe(200)
expect(body.data).toMatchObject({ found: false, orgNumber: '5560125790' })
expect(mockSupabase.rpc).not.toHaveBeenCalled()
})
it('records the facts with provenance and fills an empty legal name', async () => {
enqueue({ data: { id: PARTY, org_number: '5560125790', legal_name: null } })
lookupByOrgNumber.mockResolvedValue({
found: true,
peOrgNr: '165560125790',
row: {},
facts: [
{ field: 'legal_name', value: 'Beijer Byggmaterial AB' },
{ field: 'f_tax', value: { code: '1', label: 'Godkänd för F-skatt' } },
],
fetchedAt: '2026-09-03T10:00:00Z',
})
enqueue({ data: { inserted: 2, superseded: 0, refreshed: 0 } })
enqueue({ data: null, count: 0 }) // no user-entered legal name
enqueue({ data: null }) // parties.update
const { status, body } = await parseJsonResponse<{ data: { found: boolean; inserted: number; facts: unknown[] } }>(await call())
expect(status).toBe(200)
expect(body.data).toMatchObject({ found: true, inserted: 2 })
expect(body.data.facts).toHaveLength(2)
expect(mockSupabase.rpc).toHaveBeenCalledWith('record_party_facts', {
p_company_id: 'company-1',
p_user_id: 'user-1',
p_party_id: PARTY,
p_source: 'registry_scb',
p_facts: [
{ field: 'legal_name', value: 'Beijer Byggmaterial AB', reference: { layout: 'Je', pe_org_nr: '165560125790' } },
{ field: 'f_tax', value: { code: '1', label: 'Godkänd för F-skatt' }, reference: { layout: 'Je', pe_org_nr: '165560125790' } },
],
p_fetched_at: '2026-09-03T10:00:00Z',
})
expect(lookupByOrgNumber).toHaveBeenCalledWith('5560125790')
})
})
describe('POST /api/parties/[id]/enrich, legal name survivorship', () => {
it('replaces a document-sourced legal name with the registry name, but never one a person entered', async () => {
enqueue({ data: { id: PARTY, org_number: '5560125790', legal_name: 'Beijer Bygg' } })
lookupByOrgNumber.mockResolvedValue({ found: true, peOrgNr: '165560125790', row: {}, facts: [{ field: 'legal_name', value: 'AKTIEBOLAGET VOLVO' }], fetchedAt: '2026-09-03T10:00:00Z' })
enqueue({ data: { inserted: 1, superseded: 0, refreshed: 0 } })
enqueue({ data: null, count: 1 }) // a user-entered legal name exists
const { status } = await parseJsonResponse(await call())
expect(status).toBe(200)
const updates = mockSupabase.from.mock.calls.filter((c) => c[0] === 'parties').length
// one lookup, no update
expect(updates).toBe(1)
})
})
describe('GET /api/parties/[id]/enrich/candidates', () => {
it('returns 503 when SCB is not configured and 404 for a foreign party', async () => {
configured.value = false
expect((await parseJsonResponse(await candidates())).status).toBe(503)
configured.value = true
enqueue({ data: null })
expect((await parseJsonResponse(await candidates())).status).toBe(404)
expect(searchByName).not.toHaveBeenCalled()
})
it('searches on the party name by default and on q when given', async () => {
const result = { query: 'Adobe Systems Software', mode: 'starts_with', total: 2, truncated: false, candidates: [] }
enqueue({ data: { id: PARTY, display_name: 'Adobe Systems Software', legal_name: null } })
searchByName.mockResolvedValue(result)
const a = await parseJsonResponse<{ data: typeof result }>(await candidates())
expect(a.status).toBe(200)
expect(a.body.data).toEqual(result)
expect(searchByName).toHaveBeenLastCalledWith('Adobe Systems Software')
enqueue({ data: { id: PARTY, display_name: 'Adobe Systems Software', legal_name: null } })
await candidates('Adobe Nordic')
expect(searchByName).toHaveBeenLastCalledWith('Adobe Nordic')
})
it('maps an SCB failure to 502', async () => {
enqueue({ data: { id: PARTY, display_name: 'Adobe', legal_name: null } })
searchByName.mockRejectedValue(new Error('boom'))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await candidates())
expect(status).toBe(502)
expect(body.error.code).toBe('SCB_LOOKUP_FAILED')
})
})
describe('POST /api/parties/[id]/enrich with a picked org number', () => {
it('rejects a malformed number, a sole trader, and a party that already has one', async () => {
expect((await parseJsonResponse(await callWith({ orgNumber: '12' }))).status).toBe(400)
enqueue({ data: { id: PARTY, org_number: null, legal_name: null, vat_number: null } })
expect((await parseJsonResponse(await callWith({ orgNumber: '8001011234' }))).status).toBe(400)
enqueue({ data: { id: PARTY, org_number: '5564300142', legal_name: null, vat_number: null } })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await callWith({ orgNumber: '5564082161' }))
expect(status).toBe(409)
expect(body.error.code).toBe('CONFLICT')
expect(lookupByOrgNumber).not.toHaveBeenCalled()
})
it('refuses a number another live party already holds, naming it', async () => {
enqueue({ data: { id: PARTY, org_number: null, legal_name: null, vat_number: null } })
enqueue({ data: { id: OTHER, display_name: 'Adobe Systems Nordic AB' } })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: { reason: string; displayName: string } } }>(await callWith({ orgNumber: '5564082161' }))
expect(status).toBe(409)
expect(body.error.details).toMatchObject({ reason: 'org_number_taken', displayName: 'Adobe Systems Nordic AB' })
expect(lookupByOrgNumber).not.toHaveBeenCalled()
})
it('sets the number as a user fact, then fetches by number', async () => {
enqueue({ data: { id: PARTY, org_number: null, legal_name: null, vat_number: null } })
enqueue({ data: null }) // no holder
enqueue({ data: null }) // parties.update org_number
enqueue({ data: { inserted: 1, superseded: 0, refreshed: 0 } }) // record_party_facts (user)
lookupByOrgNumber.mockResolvedValue({ found: true, peOrgNr: '165564082161', row: {}, facts: [{ field: 'legal_name', value: 'Adobe Systems Nordic Aktiebolag' }], fetchedAt: '2026-09-03T10:00:00Z' })
enqueue({ data: { inserted: 1, superseded: 0, refreshed: 0 } }) // record_party_facts (registry)
enqueue({ data: null, count: 0 }) // no user legal name
enqueue({ data: null }) // parties.update legal_name
const { status, body } = await parseJsonResponse<{ data: { found: boolean; orgNumber: string } }>(await callWith({ orgNumber: '556408-2161' }))
expect(status).toBe(200)
expect(body.data).toMatchObject({ found: true, orgNumber: '5564082161' })
expect(mockSupabase.rpc).toHaveBeenNthCalledWith(1, 'record_party_facts', expect.objectContaining({ p_source: 'user', p_facts: [{ field: 'org_number', value: '5564082161', reference: { picked_from: 'scb_search' } }] }))
expect(lookupByOrgNumber).toHaveBeenCalledWith('5564082161')
})
})
@@ -0,0 +1,44 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateQuery } from '@/lib/api/validate'
import { PartySearchRegistryQuerySchema } from '@/lib/api/schemas'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { createScbClient } from '@/lib/parties/scb/client'
import { isScbConfigured, scbConfigFromEnv } from '@/lib/parties/scb/config'
import { ScbApiError } from '@/lib/parties/scb/transport'
/**
* GET /api/parties/[id]/enrich/candidates?q=: SCB companies whose name
* matches, for the picker shown when a party has no org number. Never
* chooses; the user does, and the choice lands through POST .../enrich.
*/
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'parties.enrich.candidates',
async (request, { supabase, companyId, log, requestId }, { params }) => {
const { id } = await params
if (!/^[0-9a-f-]{36}$/i.test(id)) return errorResponseFromCode('NOT_FOUND', log, { requestId })
const validated = validateQuery(request, PartySearchRegistryQuerySchema, { log, operation: 'parties.enrich.candidates' })
if (!validated.success) return validated.response
if (!isScbConfigured()) return errorResponseFromCode('SCB_NOT_CONFIGURED', log, { requestId })
const { data: party, error } = await supabase
.from('parties')
.select('id, display_name, legal_name')
.eq('company_id', companyId)
.eq('id', id)
.is('merged_into', null)
.maybeSingle()
if (error) throw new Error(`parties lookup failed: ${error.message}`)
if (!party) return errorResponseFromCode('NOT_FOUND', log, { requestId })
const p = party as { id: string; display_name: string; legal_name: string | null }
const query = validated.data.q?.trim() || p.legal_name || p.display_name
try {
const result = await createScbClient(scbConfigFromEnv()).searchByName(query)
return NextResponse.json({ data: result })
} catch (err) {
log.warn('scb search failed', { partyId: id, status: err instanceof ScbApiError ? err.status : undefined, message: err instanceof Error ? err.message : String(err) })
return errorResponseFromCode('SCB_LOOKUP_FAILED', log, { requestId })
}
},
)
+136
View File
@@ -0,0 +1,136 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { PartyEnrichSchema } from '@/lib/api/schemas'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { createScbClient } from '@/lib/parties/scb/client'
import { isScbConfigured, scbConfigFromEnv } from '@/lib/parties/scb/config'
import { isLegalPersonOrgNumber } from '@/lib/parties/scb/org-number'
import { ScbApiError } from '@/lib/parties/scb/transport'
/**
* POST /api/parties/[id]/enrich: fetch the party's registry facts from SCB
* and record them with provenance (source registry_scb, fetched_at). Legal
* persons only: a sole trader's org number is a personnummer and stays out
* of registry lookups in this phase.
*
* Body { orgNumber } is the picker's answer for a party that had none: the
* choice is recorded as a fact with source 'user' and set on the party
* before the fetch, so every later fetch is by number. A number already
* held by another live party is refused (merge them instead).
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'parties.enrich',
async (request, { supabase, companyId, user, log, requestId }, { params }) => {
const { id } = await params
if (!/^[0-9a-f-]{36}$/i.test(id)) return errorResponseFromCode('NOT_FOUND', log, { requestId })
if (!isScbConfigured()) return errorResponseFromCode('SCB_NOT_CONFIGURED', log, { requestId })
// A body is optional (the plain button sends none); when present it is
// the picker's answer. Read as text first: fetch sets no content-length.
let chosen: string | undefined
const raw = (await request.text()).trim()
if (raw) {
let parsed: unknown
try {
parsed = JSON.parse(raw)
} catch {
return errorResponseFromCode('VALIDATION_ERROR', log, { requestId, details: { reason: 'invalid_json' } })
}
const validation = PartyEnrichSchema.safeParse(parsed)
if (!validation.success) return errorResponseFromCode('VALIDATION_ERROR', log, { requestId, details: validation.error.flatten() })
chosen = validation.data.orgNumber
}
const { data: party, error } = await supabase
.from('parties')
.select('id, org_number, legal_name, vat_number')
.eq('company_id', companyId)
.eq('id', id)
.is('merged_into', null)
.maybeSingle()
if (error) throw new Error(`parties lookup failed: ${error.message}`)
if (!party) return errorResponseFromCode('NOT_FOUND', log, { requestId })
const p = party as { id: string; org_number: string | null; legal_name: string | null; vat_number: string | null }
if (chosen && chosen !== p.org_number) {
if (!isLegalPersonOrgNumber(chosen)) return errorResponseFromCode('SCB_NOT_A_LEGAL_PERSON', log, { requestId })
if (p.org_number) return errorResponseFromCode('CONFLICT', log, { requestId, details: { reason: 'party_has_org_number', orgNumber: p.org_number } })
const { data: holder } = await supabase
.from('parties')
.select('id, display_name')
.eq('company_id', companyId)
.eq('org_number', chosen)
.is('merged_into', null)
.limit(1)
.maybeSingle()
if (holder) {
return errorResponseFromCode('CONFLICT', log, { requestId, details: { reason: 'org_number_taken', partyId: (holder as { id: string }).id, displayName: (holder as { display_name: string }).display_name } })
}
const { error: setError } = await supabase.from('parties').update({ org_number: chosen }).eq('company_id', companyId).eq('id', id)
if (setError) throw new Error(`parties update failed: ${setError.message}`)
const { error: factError } = await supabase.rpc('record_party_facts', {
p_company_id: companyId,
p_user_id: user.id,
p_party_id: id,
p_source: 'user',
p_facts: [{ field: 'org_number', value: chosen, reference: { picked_from: 'scb_search' } }],
p_fetched_at: new Date().toISOString(),
})
if (factError) throw new Error(`record_party_facts failed: ${factError.message}`)
p.org_number = chosen
}
if (!isLegalPersonOrgNumber(p.org_number)) return errorResponseFromCode('SCB_NOT_A_LEGAL_PERSON', log, { requestId })
let lookup
try {
lookup = await createScbClient(scbConfigFromEnv()).lookupByOrgNumber(p.org_number!)
} catch (err) {
log.warn('scb lookup failed', { partyId: id, status: err instanceof ScbApiError ? err.status : undefined, message: err instanceof Error ? err.message : String(err) })
return errorResponseFromCode('SCB_LOOKUP_FAILED', log, { requestId })
}
if (!lookup.found) {
return NextResponse.json({ data: { found: false, orgNumber: p.org_number, inserted: 0, superseded: 0, refreshed: 0 } })
}
const { data: summary, error: recordError } = await supabase.rpc('record_party_facts', {
p_company_id: companyId,
p_user_id: user.id,
p_party_id: id,
p_source: 'registry_scb',
p_facts: lookup.facts.map((f) => ({ ...f, reference: { ...(f.reference ?? {}), layout: 'Je', pe_org_nr: lookup.peOrgNr } })),
p_fetched_at: lookup.fetchedAt,
})
if (recordError) throw new Error(`record_party_facts failed: ${recordError.message}`)
// Survivorship (plan section 05): user > registry > document. The
// registry's legal name replaces one read from documents or none at all,
// but never one a person entered (a legal_name fact with source 'user').
const legal = lookup.facts.find((f) => f.field === 'legal_name')?.value
if (typeof legal === 'string' && legal && legal !== p.legal_name) {
const { count } = await supabase
.from('party_facts')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.eq('party_id', id)
.eq('field', 'legal_name')
.eq('source', 'user')
.is('superseded_at', null)
if (!count) {
await supabase.from('parties').update({ legal_name: legal }).eq('company_id', companyId).eq('id', id)
}
}
// The VAT number has one valid form, so it fills an empty field outright.
const vat = lookup.facts.find((f) => f.field === 'vat_number')?.value
if (!p.vat_number && typeof vat === 'string' && vat) {
await supabase.from('parties').update({ vat_number: vat }).eq('company_id', companyId).eq('id', id)
}
const r = (summary ?? {}) as Partial<Record<'inserted' | 'superseded' | 'refreshed', number>>
return NextResponse.json({
data: { found: true, orgNumber: p.org_number, inserted: r.inserted ?? 0, superseded: r.superseded ?? 0, refreshed: r.refreshed ?? 0, facts: lookup.facts },
})
},
{ requireWrite: true },
)