Files
accounted/tests/pg/party-role-link-trigger.pg.test.ts
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

111 lines
6.1 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany } from './fixtures'
const ORG = '5564300142'
async function party(id: string) {
const { rows } = await getPool().query<{ id: string; display_name: string; org_number: string | null; kind: string; status: string }>(
`SELECT id, display_name, org_number, kind, status FROM public.parties WHERE id = $1`,
[id],
)
return rows[0] ?? null
}
describe('link_party_on_role_write (pg)', () => {
it('gives a new supplier a confirmed party keyed on its org number, and reuses it for a customer with the same org', async () => {
const c = await seedCompany()
const s = await getPool().query<{ party_id: string }>(
`INSERT INTO public.suppliers (company_id, user_id, name, org_number) VALUES ($1, $2, 'Beijer Byggmaterial AB', '556430-0142') RETURNING party_id`,
[c.companyId, c.userId],
)
expect(s.rows[0]!.party_id).toBeTruthy()
const p = await party(s.rows[0]!.party_id)
expect(p).toMatchObject({ display_name: 'Beijer Byggmaterial AB', org_number: ORG, kind: 'company', status: 'confirmed' })
const k = await getPool().query<{ party_id: string }>(
`INSERT INTO public.customers (company_id, user_id, name, org_number, customer_type) VALUES ($1, $2, 'Beijer Bygg', $3, 'swedish_business') RETURNING party_id`,
[c.companyId, c.userId, ORG],
)
expect(k.rows[0]!.party_id).toBe(s.rows[0]!.party_id)
const n = await getPool().query<{ n: string }>(`SELECT count(*)::text AS n FROM public.parties WHERE company_id = $1`, [c.companyId])
expect(n.rows[0]!.n).toBe('1')
})
it('never merges on name: two suppliers without org numbers become two parties', async () => {
const c = await seedCompany()
await getPool().query(`INSERT INTO public.suppliers (company_id, user_id, name) VALUES ($1, $2, 'Fortnox')`, [c.companyId, c.userId])
await getPool().query(`INSERT INTO public.suppliers (company_id, user_id, name) VALUES ($1, $2, 'Fortnox')`, [c.companyId, c.userId])
const n = await getPool().query<{ n: string }>(`SELECT count(*)::text AS n FROM public.parties WHERE company_id = $1`, [c.companyId])
expect(n.rows[0]!.n).toBe('2')
})
it('creates a person party without any number for a private customer', async () => {
const c = await seedCompany()
const k = await getPool().query<{ party_id: string }>(
`INSERT INTO public.customers (company_id, user_id, name, customer_type, personal_number, org_number)
VALUES ($1, $2, 'Anna Andersson', 'individual', repeat('ab', 40), '19800101-1234') RETURNING party_id`,
[c.companyId, c.userId],
)
const p = await party(k.rows[0]!.party_id)
expect(p).toMatchObject({ display_name: 'Anna Andersson', org_number: null, kind: 'person' })
const leak = await getPool().query<{ n: string }>(
`SELECT count(*)::text AS n FROM public.parties WHERE company_id = $1 AND (org_number IS NOT NULL OR display_name ~ '[0-9]{6}')`,
[c.companyId],
)
expect(leak.rows[0]!.n).toBe('0')
})
it('re-keys when the org number changes to another live party, and teaches a party its org number', async () => {
const c = await seedCompany()
const a = await getPool().query<{ id: string; party_id: string }>(
`INSERT INTO public.suppliers (company_id, user_id, name) VALUES ($1, $2, 'Loopia') RETURNING id, party_id`,
[c.companyId, c.userId],
)
expect((await party(a.rows[0]!.party_id))!.org_number).toBeNull()
// The party learns the org number.
await getPool().query(`UPDATE public.suppliers SET org_number = '556666-1012' WHERE id = $1`, [a.rows[0]!.id])
const after = await getPool().query<{ party_id: string }>(`SELECT party_id FROM public.suppliers WHERE id = $1`, [a.rows[0]!.id])
expect(after.rows[0]!.party_id).toBe(a.rows[0]!.party_id)
expect((await party(a.rows[0]!.party_id))!.org_number).toBe('5566661012')
// A different org number that belongs to another live party moves the link.
const b = await getPool().query<{ party_id: string }>(
`INSERT INTO public.suppliers (company_id, user_id, name, org_number) VALUES ($1, $2, 'Beijer', $3) RETURNING party_id`,
[c.companyId, c.userId, ORG],
)
await getPool().query(`UPDATE public.suppliers SET org_number = $2 WHERE id = $1`, [a.rows[0]!.id, ORG])
const moved = await getPool().query<{ party_id: string }>(`SELECT party_id FROM public.suppliers WHERE id = $1`, [a.rows[0]!.id])
expect(moved.rows[0]!.party_id).toBe(b.rows[0]!.party_id)
})
it('leaves a nameless row unlinked and relinks a row whose party_id was cleared', async () => {
const c = await seedCompany()
const s = await getPool().query<{ id: string; party_id: string | null }>(
`INSERT INTO public.suppliers (company_id, user_id, name) VALUES ($1, $2, '') RETURNING id, party_id`,
[c.companyId, c.userId],
)
expect(s.rows[0]!.party_id).toBeNull()
const t = await getPool().query<{ id: string; party_id: string }>(
`INSERT INTO public.suppliers (company_id, user_id, name) VALUES ($1, $2, 'Telia') RETURNING id, party_id`,
[c.companyId, c.userId],
)
await getPool().query(`UPDATE public.suppliers SET party_id = NULL WHERE id = $1`, [t.rows[0]!.id])
const relinked = await getPool().query<{ party_id: string | null }>(`SELECT party_id FROM public.suppliers WHERE id = $1`, [t.rows[0]!.id])
expect(relinked.rows[0]!.party_id).toBeTruthy()
})
it('works for an authenticated member writing a supplier owned by a colleague', async () => {
const c = await seedCompany()
const { rows } = await getPool().query<{ id: string }>(`SELECT id FROM auth.users WHERE id <> $1 LIMIT 1`, [c.userId])
const colleague = rows[0]?.id ?? c.userId
const inserted = await withUserContext(c.userId, async (client) => {
const r = await client.query<{ party_id: string | null }>(
`INSERT INTO public.suppliers (company_id, user_id, name, org_number) VALUES ($1, $2, 'Skellefteå Plåt AB', $3) RETURNING party_id`,
[c.companyId, colleague, ORG],
)
return r.rows[0]!.party_id
})
expect(inserted).toBeTruthy()
})
})