feat(parties): Förslag från bokföringen, confirmed straight into Leverantörer and Kunder (#2206)

* 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>

* 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>

---------

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 19:49:25 +02:00
committed by GitHub
co-authored by Claude Fable 5.1 Jakob Wennberg
parent e2d38b0ab3
commit b996da60ee
40 changed files with 3568 additions and 12 deletions
@@ -0,0 +1,141 @@
-- Parties, phase 1e: the queue's confirm and dismiss are undoable for 30 days.
--
-- decide_parties now snapshots the suggested_reason it clears, so a confirm
-- can be reversed without losing why the row was suggested. A new decision
-- kind 'undo' records the reversal; merges keep their own 'split' record
-- (undo_party_merge, 20260902210000).
ALTER TABLE public.party_decisions DROP CONSTRAINT IF EXISTS party_decisions_kind_check;
ALTER TABLE public.party_decisions ADD CONSTRAINT party_decisions_kind_check
CHECK (kind IN ('confirm', 'merge', 'split', 'rename', 'role', 'dismiss', 'pin', 'ignore', 'label', 'undo'));
CREATE OR REPLACE FUNCTION public.decide_parties(
p_company_id uuid,
p_user_id uuid,
p_party_ids uuid[],
p_kind text,
p_note text DEFAULT NULL
)
RETURNS integer
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path TO 'public'
AS $$
DECLARE
v_count integer := 0;
BEGIN
IF auth.uid() IS NOT NULL AND auth.uid() <> p_user_id THEN
RAISE EXCEPTION 'decide_parties: p_user_id must be the caller' USING ERRCODE = '42501';
END IF;
IF p_kind NOT IN ('confirm', 'dismiss') THEN
RAISE EXCEPTION 'decide_parties: kind must be confirm or dismiss, got %', p_kind USING ERRCODE = '22023';
END IF;
IF p_kind = 'confirm' THEN
WITH target AS (
SELECT p.id, p.suggested_reason
FROM public.parties p
WHERE p.company_id = p_company_id AND p.id = ANY(p_party_ids) AND p.merged_into IS NULL
AND (p.status <> 'confirmed' OR p.archived_at IS NOT NULL)
FOR UPDATE
), changed AS (
UPDATE public.parties p
SET status = 'confirmed', suggested_reason = NULL, archived_at = NULL
FROM target t
WHERE p.id = t.id
RETURNING p.id, t.suggested_reason AS old_reason
), logged AS (
INSERT INTO public.party_decisions (party_id, company_id, user_id, kind, before, after, note)
SELECT c.id, p_company_id, p_user_id, 'confirm',
jsonb_build_object('status', 'suggested', 'suggested_reason', c.old_reason),
jsonb_build_object('status', 'confirmed'), p_note
FROM changed c
RETURNING 1
)
SELECT count(*) INTO v_count FROM logged;
ELSE
-- Dismiss is the queue's "not a party" answer: it only touches suggested
-- rows. A confirmed party is archived through its own action later.
WITH changed AS (
UPDATE public.parties p
SET archived_at = now()
WHERE p.company_id = p_company_id AND p.id = ANY(p_party_ids) AND p.merged_into IS NULL
AND p.status = 'suggested' AND p.archived_at IS NULL
RETURNING p.id, p.status
), logged AS (
INSERT INTO public.party_decisions (party_id, company_id, user_id, kind, before, after, note)
SELECT c.id, p_company_id, p_user_id, 'dismiss',
jsonb_build_object('status', c.status, 'archived', false), jsonb_build_object('status', c.status, 'archived', true), p_note
FROM changed c
RETURNING 1
)
SELECT count(*) INTO v_count FROM logged;
END IF;
RETURN v_count;
END;
$$;
COMMENT ON FUNCTION public.decide_parties(uuid, uuid, uuid[], text, text) IS
'Bulk confirm (suggested -> confirmed, reason snapshotted in the decision) or dismiss (archive a suggested party), one party_decisions row each. Reversible for 30 days through undo_party_decisions.';
-- ── Undo the latest confirm or dismiss per party ────────────────────────────
CREATE OR REPLACE FUNCTION public.undo_party_decisions(
p_company_id uuid,
p_user_id uuid,
p_party_ids uuid[]
)
RETURNS integer
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path TO 'public'
AS $$
DECLARE
v_count integer := 0;
BEGIN
IF auth.uid() IS NOT NULL AND auth.uid() <> p_user_id THEN
RAISE EXCEPTION 'undo_party_decisions: p_user_id must be the caller' USING ERRCODE = '42501';
END IF;
-- The latest confirm/dismiss per party, unless a later decision of any
-- kind already followed it: undo only ever reverses the most recent step.
WITH latest AS (
SELECT DISTINCT ON (d.party_id) d.id, d.party_id, d.kind, d.before, d.created_at
FROM public.party_decisions d
WHERE d.company_id = p_company_id AND d.party_id = ANY(p_party_ids)
ORDER BY d.party_id, d.created_at DESC, d.id DESC
),
eligible AS (
SELECT l.* FROM latest l
WHERE l.kind IN ('confirm', 'dismiss') AND l.created_at >= now() - interval '30 days'
),
reverted AS (
UPDATE public.parties p
SET status = CASE WHEN e.kind = 'confirm' THEN 'suggested' ELSE p.status END,
suggested_reason = CASE WHEN e.kind = 'confirm' THEN e.before->'suggested_reason' ELSE p.suggested_reason END,
archived_at = CASE WHEN e.kind = 'dismiss' THEN NULL ELSE p.archived_at END
FROM eligible e
WHERE p.id = e.party_id AND p.company_id = p_company_id AND p.merged_into IS NULL
RETURNING p.id, e.id AS decision_id, e.kind
),
logged AS (
INSERT INTO public.party_decisions (party_id, company_id, user_id, kind, before, after, note)
SELECT r.id, p_company_id, p_user_id, 'undo',
jsonb_build_object('decision_id', r.decision_id, 'kind', r.kind),
jsonb_build_object('status', 'suggested', 'archived', false),
'undo ' || r.kind
FROM reverted r
RETURNING 1
)
SELECT count(*) INTO v_count FROM logged;
RETURN v_count;
END;
$$;
REVOKE ALL ON FUNCTION public.undo_party_decisions(uuid, uuid, uuid[]) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.undo_party_decisions(uuid, uuid, uuid[]) TO authenticated, service_role;
COMMENT ON FUNCTION public.undo_party_decisions(uuid, uuid, uuid[]) IS
'Reverses the latest confirm or dismiss per party within 30 days (confirm -> suggested with its reason restored; dismiss -> unarchived). Logs an undo decision. Returns the number of parties reverted.';
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,92 @@
-- get_ledger_key_evidence: a company without an org number lost every hard
-- key. (d.org = own.org) is NULL when own.org is NULL, NOT NULL is NULL, and
-- the row fell out of the useful set, so orgs, names, bankgiro and plusgiro
-- came back empty while docs still counted. Sole traders and every company
-- that has not filled in its org number were affected. The comparison is now
-- coalesced to false: with no own org number nothing can be self-extracted.
-- Same body as 20260902200000 otherwise.
-- pg-test: covered-by tests/pg/party-suggestions.pg.test.ts
CREATE OR REPLACE FUNCTION public.get_ledger_key_evidence(p_company_id uuid)
RETURNS jsonb
LANGUAGE sql
STABLE
SECURITY INVOKER
SET search_path TO 'public'
AS $$
WITH own AS (
SELECT public.normalize_org_number(c.org_number) AS org
FROM public.companies c WHERE c.id = p_company_id
),
entries AS (
SELECT je.id, je.entry_date, public.ledger_key(je.description) AS k
FROM public.journal_entries je
WHERE je.company_id = p_company_id
AND je.status = 'posted'
AND je.source_type NOT IN ('storno', 'opening_balance', 'year_end', 'vat_settlement')
AND je.description IS NOT NULL
AND btrim(je.description) <> ''
AND NOT EXISTS (
SELECT 1 FROM public.transactions t
WHERE t.journal_entry_id = je.id
AND t.merchant_name IS NOT NULL
AND btrim(t.merchant_name) <> ''
)
),
docs AS (
SELECT e.k, e.entry_date, d.id AS document_id,
public.normalize_org_number(d.extracted_data->'supplier'->>'orgNumber') AS org,
nullif(upper(regexp_replace(coalesce(d.extracted_data->'supplier'->>'vatNumber', ''), '[^0-9A-Za-z]', '', 'g')), '') AS vat,
nullif(regexp_replace(coalesce(d.extracted_data->'supplier'->>'bankgiro', ''), '[^0-9]', '', 'g'), '') AS bankgiro,
nullif(regexp_replace(coalesce(d.extracted_data->'supplier'->>'plusgiro', ''), '[^0-9]', '', 'g'), '') AS plusgiro,
nullif(btrim(d.extracted_data->'supplier'->>'name'), '') AS name
FROM entries e
JOIN public.document_attachments d
ON d.journal_entry_id = e.id
AND d.company_id = p_company_id
AND d.is_current_version
AND jsonb_typeof(d.extracted_data->'supplier') = 'object'
WHERE e.k <> ''
),
classified AS (
SELECT d.*, coalesce(d.org IS NOT NULL AND d.org = own.org, false) AS is_self
FROM docs d CROSS JOIN own
),
useful AS (SELECT * FROM classified WHERE NOT is_self),
orgs AS (
SELECT k, org, count(*) AS n FROM useful WHERE org IS NOT NULL GROUP BY k, org
),
vats AS (
SELECT k, vat, count(*) AS n FROM useful WHERE vat IS NOT NULL GROUP BY k, vat
),
names AS (
SELECT k, name, count(*) AS n FROM useful WHERE name IS NOT NULL GROUP BY k, name
),
bg AS (
SELECT k, bankgiro AS value, count(*) AS n, min(entry_date) AS first_seen, max(entry_date) AS last_seen
FROM useful WHERE bankgiro IS NOT NULL AND length(bankgiro) BETWEEN 7 AND 8 GROUP BY k, bankgiro
),
pg AS (
SELECT k, plusgiro AS value, count(*) AS n, min(entry_date) AS first_seen, max(entry_date) AS last_seen
FROM useful WHERE plusgiro IS NOT NULL AND length(plusgiro) BETWEEN 5 AND 8 GROUP BY k, plusgiro
),
per_key AS (
SELECT c.k,
count(*) AS docs,
count(*) FILTER (WHERE c.is_self) AS self_docs
FROM classified c GROUP BY c.k
)
SELECT coalesce(jsonb_agg(jsonb_build_object(
'key', p.k,
'docs', p.docs,
'self_docs', p.self_docs,
'orgs', coalesce((SELECT jsonb_agg(jsonb_build_object('org', o.org, 'n', o.n) ORDER BY o.n DESC, o.org) FROM orgs o WHERE o.k = p.k), '[]'::jsonb),
'vat_numbers', coalesce((SELECT jsonb_agg(jsonb_build_object('vat', v.vat, 'n', v.n) ORDER BY v.n DESC, v.vat) FROM vats v WHERE v.k = p.k), '[]'::jsonb),
'names', coalesce((SELECT jsonb_agg(jsonb_build_object('name', x.name, 'n', x.n) ORDER BY x.n DESC, x.name) FROM names x WHERE x.k = p.k), '[]'::jsonb),
'bankgiro', coalesce((SELECT jsonb_agg(jsonb_build_object('value', b.value, 'n', b.n, 'first_seen', b.first_seen, 'last_seen', b.last_seen) ORDER BY b.n DESC, b.value) FROM bg b WHERE b.k = p.k), '[]'::jsonb),
'plusgiro', coalesce((SELECT jsonb_agg(jsonb_build_object('value', g.value, 'n', g.n, 'first_seen', g.first_seen, 'last_seen', g.last_seen) ORDER BY g.n DESC, g.value) FROM pg g WHERE g.k = p.k), '[]'::jsonb)
) ORDER BY p.docs DESC, p.k), '[]'::jsonb)
FROM per_key p;
$$;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,182 @@
-- Parties, phase 1f: every supplier and customer gets a party on write.
--
-- The backfill in 20260902160000 linked the rows that existed on that day;
-- rows created since (108 on prod within a day) had no party and never
-- reached the Kontakter register. A trigger closes every write path at
-- once: the dialogs, the v1 API, MCP tools, imports and provider
-- migrations. It runs BEFORE INSERT and BEFORE UPDATE OF party_id, name,
-- org_number, customer_type on customers (supplier_type on suppliers), so
-- a row whose party was cleared, or whose org number arrived later, is
-- linked or re-keyed too.
--
-- Rules, all inherited from ensure_party:
-- * find-or-create by org number inside the company; never by name;
-- * a private customer (customer_type = 'individual') carries a person's
-- identity, and a personal number is not an org number: the party is
-- created without org_number, kind = 'person', so nothing of the
-- personnummer lands in parties (customers keeps its own masked field);
-- * an empty name gets no party (ensure_party refuses one);
-- * rows in a company archived by a migration reset are immutable and
-- the trigger never fires on them (the archive is not written to).
-- Origin is 'manual' for interactive writes and 'import' when the row
-- arrives inside a migration or import: the row does not know, so the
-- trigger records 'manual' and the pipeline attaches evidence later.
CREATE OR REPLACE FUNCTION public.link_party_on_role_write()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
v_is_person boolean := false;
v_org text;
v_kind text;
v_party_org text;
v_merged uuid;
BEGIN
IF NEW.company_id IS NULL OR nullif(btrim(coalesce(NEW.name, '')), '') IS NULL THEN
RETURN NEW;
END IF;
-- The party was deleted and the foreign key cleared the link (ON DELETE
-- SET NULL arrives here as an UPDATE): keep it cleared.
IF TG_OP = 'UPDATE' AND NEW.party_id IS NULL AND OLD.party_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM public.parties p WHERE p.id = OLD.party_id) THEN
RETURN NEW;
END IF;
IF TG_TABLE_NAME = 'customers' THEN
v_is_person := (NEW.customer_type = 'individual');
END IF;
v_org := CASE WHEN v_is_person THEN NULL ELSE public.normalize_org_number(NEW.org_number) END;
v_kind := CASE WHEN v_is_person THEN 'person' ELSE 'company' END;
-- Already linked: keep the link unless the org number now points at a
-- different live party (the user corrected it). A party without an org
-- number simply learns it.
IF NEW.party_id IS NOT NULL THEN
SELECT p.org_number, p.merged_into INTO v_party_org, v_merged
FROM public.parties p
WHERE p.id = NEW.party_id AND p.company_id = NEW.company_id;
IF NOT FOUND THEN
-- A party of another company: the composite foreign key would refuse
-- it too; refusing here keeps the error the same on every path.
RAISE EXCEPTION 'party % is not a party of this company', NEW.party_id USING ERRCODE = '23503';
END IF;
IF v_merged IS NOT NULL THEN
-- Linked to a merged party: follow the chain to the survivor.
NEW.party_id := public.canonical_party_id(NEW.party_id);
SELECT p.org_number INTO v_party_org FROM public.parties p WHERE p.id = NEW.party_id;
END IF;
IF v_org IS NOT NULL AND v_party_org IS NULL THEN
UPDATE public.parties p SET org_number = v_org
WHERE p.id = NEW.party_id
AND NOT EXISTS (SELECT 1 FROM public.parties q WHERE q.company_id = NEW.company_id AND q.org_number = v_org AND q.merged_into IS NULL AND q.id <> NEW.party_id);
RETURN NEW;
ELSIF v_org IS NOT NULL AND v_party_org <> v_org THEN
NEW.party_id := NULL;
ELSE
RETURN NEW;
END IF;
END IF;
NEW.party_id := public.ensure_party(NEW.company_id, NEW.user_id, NEW.name, v_org, v_kind, 'manual');
RETURN NEW;
END;
$$;
REVOKE ALL ON FUNCTION public.link_party_on_role_write() FROM PUBLIC, anon;
-- SECURITY DEFINER because ensure_party checks auth.uid() against p_user_id
-- and a supplier may be created for a company by a colleague: the row's
-- user_id is the owner of record, the caller is whoever is writing. Inside
-- a trigger the write itself is already authorised by RLS on the role table.
DROP TRIGGER IF EXISTS customers_link_party ON public.customers;
CREATE TRIGGER customers_link_party
BEFORE INSERT OR UPDATE OF party_id, name, org_number, customer_type ON public.customers
FOR EACH ROW EXECUTE FUNCTION public.link_party_on_role_write();
DROP TRIGGER IF EXISTS suppliers_link_party ON public.suppliers;
CREATE TRIGGER suppliers_link_party
BEFORE INSERT OR UPDATE OF party_id, name, org_number, supplier_type ON public.suppliers
FOR EACH ROW EXECUTE FUNCTION public.link_party_on_role_write();
-- ensure_party runs under the definer here, where auth.uid() is still the
-- caller's; relax its identity check for trigger context by letting the
-- definer pass. The RPC path (auth.uid() = caller) is unchanged.
CREATE OR REPLACE FUNCTION public.ensure_party(
p_company_id uuid,
p_user_id uuid,
p_name text,
p_org_number text DEFAULT NULL,
p_kind text DEFAULT 'company',
p_origin text DEFAULT 'manual'
)
RETURNS uuid
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path TO 'public'
AS $$
DECLARE
v_org text := public.normalize_org_number(p_org_number);
v_name text := btrim(coalesce(p_name, ''));
v_id uuid;
BEGIN
-- Authenticated callers write under their own identity; the service role
-- (auth.uid() NULL) and the role-link trigger (pg_trigger_depth() > 0,
-- the row's owner is the recorded user) may act for another user.
IF pg_trigger_depth() = 0 AND auth.uid() IS NOT NULL AND auth.uid() <> p_user_id THEN
RAISE EXCEPTION 'ensure_party: p_user_id must be the caller' USING ERRCODE = '42501';
END IF;
IF v_name = '' THEN
RAISE EXCEPTION 'ensure_party: name is required';
END IF;
IF v_org IS NOT NULL THEN
SELECT id INTO v_id FROM public.parties
WHERE company_id = p_company_id AND org_number = v_org AND merged_into IS NULL
LIMIT 1;
IF v_id IS NOT NULL THEN RETURN v_id; END IF;
END IF;
INSERT INTO public.parties (company_id, user_id, display_name, org_number, kind, origin)
VALUES (p_company_id, p_user_id, v_name, v_org, p_kind, p_origin)
ON CONFLICT DO NOTHING
RETURNING id INTO v_id;
IF v_id IS NULL THEN
-- Lost a race on the live org-number index: return the winner.
SELECT id INTO v_id FROM public.parties
WHERE company_id = p_company_id AND org_number = v_org AND merged_into IS NULL
LIMIT 1;
END IF;
RETURN v_id;
END;
$$;
-- Catch-up for the rows created between the backfill and this trigger.
-- Same skip rules as the backfill: nameless rows and archived companies.
DO $$
DECLARE
r record;
BEGIN
FOR r IN
SELECT id FROM public.suppliers
WHERE party_id IS NULL AND company_id IS NOT NULL
AND nullif(btrim(name), '') IS NOT NULL
AND company_id NOT IN (SELECT source_company_id FROM public.company_migration_resets)
ORDER BY created_at, id
LOOP
UPDATE public.suppliers SET party_id = NULL WHERE id = r.id;
END LOOP;
FOR r IN
SELECT id FROM public.customers
WHERE party_id IS NULL AND company_id IS NOT NULL
AND nullif(btrim(name), '') IS NOT NULL
AND company_id NOT IN (SELECT source_company_id FROM public.company_migration_resets)
ORDER BY created_at, id
LOOP
UPDATE public.customers SET party_id = NULL WHERE id = r.id;
END LOOP;
END $$;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,200 @@
-- Parties, phase 1g: a suggestion is confirmed INTO a role.
--
-- Founder decision 2026-09-03: users know two words, kund and leverantör,
-- and a "kontakt" with no role is a state nobody has seen in Fortnox or
-- Bokio. Confirming a suggestion therefore creates the supplier and/or
-- customer row straight away, filled from what the documents said (org
-- number, VAT number, bankgiro, plusgiro). The party model stays underneath
-- unchanged: the role rows link to the party through party_id and the
-- role-link trigger; the register the user sees is Leverantörer and Kunder.
--
-- promote_parties(company, user, items) items: [{party_id, roles: [...]}]
-- undo_party_promotions(company, user, party_ids) within 30 days
--
-- Undo archives the role rows the promotion created (archived_at, and
-- is_active = false on suppliers, the same state the v1 API's archive
-- leaves) and puts the party back in the queue. Rows the promotion did not
-- create are left alone.
CREATE OR REPLACE FUNCTION public.promote_parties(
p_company_id uuid,
p_user_id uuid,
p_items jsonb
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path TO 'public'
AS $$
DECLARE
v_item jsonb;
v_party public.parties%ROWTYPE;
v_roles text[];
v_supplier_id uuid;
v_customer_id uuid;
v_created text[];
v_bankgiro text;
v_plusgiro text;
v_suppliers integer := 0;
v_customers integer := 0;
v_parties integer := 0;
v_supplier_type text;
v_customer_type text;
BEGIN
IF auth.uid() IS NOT NULL AND auth.uid() <> p_user_id THEN
RAISE EXCEPTION 'promote_parties: p_user_id must be the caller' USING ERRCODE = '42501';
END IF;
IF p_items IS NULL OR jsonb_typeof(p_items) <> 'array' THEN
RAISE EXCEPTION 'promote_parties: p_items must be a JSON array' USING ERRCODE = '22023';
END IF;
FOR v_item IN SELECT * FROM jsonb_array_elements(p_items) LOOP
v_roles := ARRAY(SELECT DISTINCT r FROM jsonb_array_elements_text(coalesce(v_item->'roles', '[]'::jsonb)) AS r WHERE r IN ('supplier', 'customer'));
IF coalesce(array_length(v_roles, 1), 0) = 0 THEN
RAISE EXCEPTION 'promote_parties: every item needs at least one of supplier, customer' USING ERRCODE = '22023';
END IF;
SELECT * INTO v_party FROM public.parties
WHERE id = (v_item->>'party_id')::uuid AND company_id = p_company_id AND merged_into IS NULL AND archived_at IS NULL
FOR UPDATE;
IF v_party.id IS NULL THEN
RAISE EXCEPTION 'promote_parties: party % is not a live party of this company', v_item->>'party_id' USING ERRCODE = '23503';
END IF;
v_created := '{}';
SELECT s.id INTO v_supplier_id FROM public.suppliers s
WHERE s.company_id = p_company_id AND s.party_id = v_party.id AND s.archived_at IS NULL
ORDER BY s.created_at LIMIT 1;
SELECT c.id INTO v_customer_id FROM public.customers c
WHERE c.company_id = p_company_id AND c.party_id = v_party.id AND c.archived_at IS NULL
ORDER BY c.created_at LIMIT 1;
-- Identities are stored as digits; the supplier form writes them the way
-- they are printed (5317-0900, 12 34 56-7 style plusgiro as 123456-7).
SELECT CASE WHEN length(i.value) IN (7, 8) THEN left(i.value, length(i.value) - 4) || '-' || right(i.value, 4) ELSE i.value END
INTO v_bankgiro FROM public.party_identities i
WHERE i.party_id = v_party.id AND i.scheme = 'bankgiro' ORDER BY i.seen_count DESC, i.last_seen DESC NULLS LAST LIMIT 1;
SELECT CASE WHEN length(i.value) >= 2 THEN left(i.value, length(i.value) - 1) || '-' || right(i.value, 1) ELSE i.value END
INTO v_plusgiro FROM public.party_identities i
WHERE i.party_id = v_party.id AND i.scheme = 'plusgiro' ORDER BY i.seen_count DESC, i.last_seen DESC NULLS LAST LIMIT 1;
-- Type from the numbers we hold: a Swedish org number means a Swedish
-- business; an EU VAT number without one means an EU business; nothing
-- means we do not know, and swedish_business is the form's own default.
v_supplier_type := CASE
WHEN v_party.org_number IS NOT NULL THEN 'swedish_business'
WHEN v_party.vat_number IS NOT NULL AND v_party.vat_number !~* '^SE' THEN 'eu_business'
ELSE 'swedish_business' END;
v_customer_type := CASE
WHEN v_party.kind = 'person' THEN 'individual'
ELSE v_supplier_type END;
IF 'supplier' = ANY(v_roles) AND v_supplier_id IS NULL THEN
INSERT INTO public.suppliers (company_id, user_id, name, supplier_type, org_number, vat_number, bankgiro, plusgiro, party_id)
VALUES (p_company_id, p_user_id, v_party.display_name, v_supplier_type, v_party.org_number, v_party.vat_number, v_bankgiro, v_plusgiro, v_party.id)
RETURNING id INTO v_supplier_id;
v_created := array_append(v_created, 'supplier');
v_suppliers := v_suppliers + 1;
END IF;
IF 'customer' = ANY(v_roles) AND v_customer_id IS NULL THEN
INSERT INTO public.customers (company_id, user_id, name, customer_type, org_number, vat_number, party_id)
VALUES (p_company_id, p_user_id, v_party.display_name, v_customer_type, v_party.org_number, v_party.vat_number, v_party.id)
RETURNING id INTO v_customer_id;
v_created := array_append(v_created, 'customer');
v_customers := v_customers + 1;
END IF;
UPDATE public.parties SET status = 'confirmed', suggested_reason = NULL WHERE id = v_party.id;
v_parties := v_parties + 1;
INSERT INTO public.party_decisions (party_id, company_id, user_id, kind, before, after, note)
VALUES (v_party.id, p_company_id, p_user_id, 'role',
jsonb_build_object('status', v_party.status, 'suggested_reason', v_party.suggested_reason),
jsonb_build_object('status', 'confirmed', 'roles', to_jsonb(v_roles), 'created', to_jsonb(v_created),
'supplier_id', v_supplier_id, 'customer_id', v_customer_id),
NULL);
END LOOP;
RETURN jsonb_build_object('parties', v_parties, 'suppliers', v_suppliers, 'customers', v_customers);
END;
$$;
REVOKE ALL ON FUNCTION public.promote_parties(uuid, uuid, jsonb) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.promote_parties(uuid, uuid, jsonb) TO authenticated, service_role;
COMMENT ON FUNCTION public.promote_parties(uuid, uuid, jsonb) IS
'Confirms suggested parties into roles: creates the supplier and/or customer row from the party''s facts (no duplicate when a live role row already points at the party), sets status confirmed, logs a role decision. Undo through undo_party_promotions within 30 days.';
CREATE OR REPLACE FUNCTION public.undo_party_promotions(
p_company_id uuid,
p_user_id uuid,
p_party_ids uuid[]
)
RETURNS integer
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path TO 'public'
AS $$
DECLARE
v_count integer := 0;
BEGIN
IF auth.uid() IS NOT NULL AND auth.uid() <> p_user_id THEN
RAISE EXCEPTION 'undo_party_promotions: p_user_id must be the caller' USING ERRCODE = '42501';
END IF;
WITH latest AS (
SELECT DISTINCT ON (d.party_id) d.id, d.party_id, d.kind, d.before, d.after, d.created_at
FROM public.party_decisions d
WHERE d.company_id = p_company_id AND d.party_id = ANY(p_party_ids)
ORDER BY d.party_id, d.created_at DESC, d.id DESC
),
eligible AS (
SELECT l.* FROM latest l WHERE l.kind = 'role' AND l.created_at >= now() - interval '30 days'
),
archived_suppliers AS (
UPDATE public.suppliers s
SET archived_at = now(), is_active = false
FROM eligible e
WHERE s.company_id = p_company_id AND s.id = (e.after->>'supplier_id')::uuid
AND e.after->'created' ? 'supplier' AND s.archived_at IS NULL
AND NOT EXISTS (SELECT 1 FROM public.supplier_invoices si WHERE si.supplier_id = s.id)
RETURNING s.id
),
archived_customers AS (
UPDATE public.customers c
SET archived_at = now()
FROM eligible e
WHERE c.company_id = p_company_id AND c.id = (e.after->>'customer_id')::uuid
AND e.after->'created' ? 'customer' AND c.archived_at IS NULL
AND NOT EXISTS (SELECT 1 FROM public.invoices i WHERE i.customer_id = c.id)
RETURNING c.id
),
reverted AS (
UPDATE public.parties p
SET status = 'suggested', suggested_reason = e.before->'suggested_reason'
FROM eligible e
WHERE p.id = e.party_id AND p.company_id = p_company_id AND p.merged_into IS NULL
RETURNING p.id, e.id AS decision_id
),
logged AS (
INSERT INTO public.party_decisions (party_id, company_id, user_id, kind, before, after, note)
SELECT r.id, p_company_id, p_user_id, 'undo',
jsonb_build_object('decision_id', r.decision_id, 'kind', 'role'),
jsonb_build_object('status', 'suggested',
'archived_suppliers', (SELECT count(*) FROM archived_suppliers),
'archived_customers', (SELECT count(*) FROM archived_customers)),
'undo role'
FROM reverted r
RETURNING 1
)
SELECT count(*) INTO v_count FROM logged;
RETURN v_count;
END;
$$;
REVOKE ALL ON FUNCTION public.undo_party_promotions(uuid, uuid, uuid[]) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.undo_party_promotions(uuid, uuid, uuid[]) TO authenticated, service_role;
COMMENT ON FUNCTION public.undo_party_promotions(uuid, uuid, uuid[]) IS
'Reverses the latest promotion per party within 30 days: archives the supplier/customer rows that promotion created (unless invoices already point at them), returns the party to the queue with its reason, logs an undo decision.';
NOTIFY pgrst, 'reload schema';