Files
accounted/supabase/migrations/20260903180000_party_decision_undo.sql
T
b996da60ee 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>
2026-09-03 19:49:25 +02:00

142 lines
5.7 KiB
PL/PgSQL

-- 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';