Files
accounted/supabase/migrations/20260904000200_record_party_facts.sql
T
22b98e0a3b 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>
2026-09-03 20:16:59 +02:00

90 lines
4.1 KiB
PL/PgSQL

-- Parties, phase 3 start: one way to write facts from a registry.
--
-- record_party_facts(company, user, party, source, facts, fetched_at)
-- facts: [{field, value, reference?, valid_from?, valid_to?}]
--
-- Facts are statements with provenance and time (plan section 05). A new
-- statement for the same field from the same source supersedes the old one
-- only when the value changed: an unchanged value just refreshes fetched_at,
-- so "SCB · 2026-09-03" on the dossier means "checked then", not "changed
-- then". Facts from other sources (document, user) are never touched: the
-- dossier shows every source side by side and the survivorship chain
-- (user > registry > document > bank > ledger > model) decides what leads.
CREATE OR REPLACE FUNCTION public.record_party_facts(
p_company_id uuid,
p_user_id uuid,
p_party_id uuid,
p_source text,
p_facts jsonb,
p_fetched_at timestamptz DEFAULT now()
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path TO 'public'
AS $$
DECLARE
v_fact jsonb;
v_field text;
v_existing_id uuid;
v_existing_value jsonb;
v_inserted integer := 0;
v_superseded integer := 0;
v_refreshed integer := 0;
BEGIN
IF auth.uid() IS NOT NULL AND auth.uid() <> p_user_id THEN
RAISE EXCEPTION 'record_party_facts: p_user_id must be the caller' USING ERRCODE = '42501';
END IF;
IF p_source NOT IN ('user', 'registry_scb', 'registry_tic', 'vies', 'peppol', 'document', 'bank', 'ledger', 'model') THEN
RAISE EXCEPTION 'record_party_facts: unknown source %', p_source USING ERRCODE = '22023';
END IF;
IF p_facts IS NULL OR jsonb_typeof(p_facts) <> 'array' THEN
RAISE EXCEPTION 'record_party_facts: p_facts must be a JSON array' USING ERRCODE = '22023';
END IF;
IF NOT EXISTS (SELECT 1 FROM public.parties p WHERE p.id = p_party_id AND p.company_id = p_company_id AND p.merged_into IS NULL) THEN
RAISE EXCEPTION 'record_party_facts: party % is not a live party of this company', p_party_id USING ERRCODE = '23503';
END IF;
FOR v_fact IN SELECT * FROM jsonb_array_elements(p_facts) LOOP
v_field := nullif(btrim(coalesce(v_fact->>'field', '')), '');
IF v_field IS NULL OR length(v_field) > 64 THEN
RAISE EXCEPTION 'record_party_facts: every fact needs a field of at most 64 characters' USING ERRCODE = '22023';
END IF;
SELECT f.id, f.value INTO v_existing_id, v_existing_value
FROM public.party_facts f
WHERE f.party_id = p_party_id AND f.company_id = p_company_id AND f.field = v_field AND f.source = p_source AND f.superseded_at IS NULL
ORDER BY f.recorded_at DESC LIMIT 1;
IF v_existing_id IS NOT NULL AND v_existing_value = v_fact->'value' THEN
UPDATE public.party_facts SET fetched_at = p_fetched_at, reference = coalesce(v_fact->'reference', reference)
WHERE id = v_existing_id;
v_refreshed := v_refreshed + 1;
CONTINUE;
END IF;
IF v_existing_id IS NOT NULL THEN
UPDATE public.party_facts SET superseded_at = p_fetched_at WHERE id = v_existing_id;
v_superseded := v_superseded + 1;
END IF;
INSERT INTO public.party_facts (party_id, company_id, user_id, field, value, source, reference, fetched_at, valid_from, valid_to, recorded_at)
VALUES (
p_party_id, p_company_id, p_user_id, v_field, v_fact->'value', p_source, v_fact->'reference', p_fetched_at,
(v_fact->>'valid_from')::date, (v_fact->>'valid_to')::date, p_fetched_at
);
v_inserted := v_inserted + 1;
END LOOP;
RETURN jsonb_build_object('inserted', v_inserted, 'superseded', v_superseded, 'refreshed', v_refreshed);
END;
$$;
REVOKE ALL ON FUNCTION public.record_party_facts(uuid, uuid, uuid, text, jsonb, timestamptz) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.record_party_facts(uuid, uuid, uuid, text, jsonb, timestamptz) TO authenticated, service_role;
COMMENT ON FUNCTION public.record_party_facts(uuid, uuid, uuid, text, jsonb, timestamptz) IS
'Records facts from one source for one party: unchanged values refresh fetched_at, changed values supersede the previous statement and insert a new one. Other sources are never touched.';
NOTIFY pgrst, 'reload schema';