* 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>
264 lines
12 KiB
TypeScript
264 lines
12 KiB
TypeScript
/**
|
|
* /api/parties: the Kontakter register and its write actions. The read model
|
|
* and the pipeline are unit-tested in lib/parties; here the routes are
|
|
* checked for auth, validation and the shape they hand the page.
|
|
*/
|
|
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 getRegister = vi.fn()
|
|
const getDossier = vi.fn()
|
|
vi.mock('@/lib/parties/register', () => ({
|
|
getRegister: (...args: unknown[]) => getRegister(...args),
|
|
getDossier: (...args: unknown[]) => getDossier(...args),
|
|
}))
|
|
const suggestPartiesForCompany = vi.fn()
|
|
vi.mock('@/lib/parties/suggest', () => ({
|
|
suggestPartiesForCompany: (...args: unknown[]) => suggestPartiesForCompany(...args),
|
|
}))
|
|
|
|
import { GET as listGet } from '../route'
|
|
import { GET as dossierGet } from '../[id]/route'
|
|
import { POST as suggestPost } from '../suggest/route'
|
|
import { POST as decidePost } from '../decide/route'
|
|
import { POST as undoDecidePost } from '../decide/undo/route'
|
|
import { POST as mergePost } from '../merge/route'
|
|
import { POST as undoMergePost } from '../merge/undo/route'
|
|
import { POST as promotePost } from '../promote/route'
|
|
import { POST as undoPromotePost } from '../promote/undo/route'
|
|
|
|
const user = { id: 'user-1', email: 'test@test.se' }
|
|
const noParams = { params: Promise.resolve({}) }
|
|
const PARTY = '11111111-1111-4111-8111-111111111111'
|
|
const OTHER = '22222222-2222-4222-8222-222222222222'
|
|
const DECISION = '33333333-3333-4333-8333-333333333333'
|
|
|
|
function json(url: string, body: unknown) {
|
|
return createMockRequest(url, { method: 'POST', body })
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
reset()
|
|
eventBus.clear()
|
|
mockSupabase.auth.getUser.mockResolvedValue({ data: { user } })
|
|
})
|
|
|
|
describe('GET /api/parties', () => {
|
|
it('returns 401 when not authenticated', async () => {
|
|
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
|
const { status } = await parseJsonResponse(await listGet(createMockRequest('/api/parties'), noParams))
|
|
expect(status).toBe(401)
|
|
})
|
|
|
|
it('rejects an unknown view with 400', async () => {
|
|
const { status } = await parseJsonResponse(await listGet(createMockRequest('/api/parties?view=nope'), noParams))
|
|
expect(status).toBe(400)
|
|
expect(getRegister).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('passes view, query and period to the read model for the active company', async () => {
|
|
const register = { counts: { suggested: 1, suggestedSuppliers: 1, suggestedCustomers: 0, observed: 0, confirmed: 3 }, rows: [], observed: [], generic: { count: 0, expenseSek: 0, examples: [] }, period: 'all' }
|
|
getRegister.mockResolvedValue(register)
|
|
const { status, body } = await parseJsonResponse<{ data: typeof register }>(
|
|
await listGet(createMockRequest('/api/parties?view=observed&q=beijer&period=all'), noParams),
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual(register)
|
|
expect(getRegister).toHaveBeenCalledWith(mockSupabase, 'company-1', { view: 'observed', q: 'beijer', period: 'all' })
|
|
})
|
|
|
|
it('no longer accepts the register views that moved to Leverantörer and Kunder', async () => {
|
|
const { status } = await parseJsonResponse(await listGet(createMockRequest('/api/parties?view=suppliers'), noParams))
|
|
expect(status).toBe(400)
|
|
})
|
|
})
|
|
|
|
describe('GET /api/parties/[id]', () => {
|
|
it('returns 404 for a party that is not in the company', async () => {
|
|
getDossier.mockResolvedValue(null)
|
|
const { status } = await parseJsonResponse(
|
|
await dossierGet(createMockRequest(`/api/parties/${PARTY}`), { params: Promise.resolve({ id: PARTY }) }),
|
|
)
|
|
expect(status).toBe(404)
|
|
})
|
|
|
|
it('returns 404 for a malformed id without touching the database', async () => {
|
|
const { status } = await parseJsonResponse(
|
|
await dossierGet(createMockRequest('/api/parties/not-a-uuid'), { params: Promise.resolve({ id: 'not-a-uuid' }) }),
|
|
)
|
|
expect(status).toBe(404)
|
|
expect(getDossier).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('returns the dossier', async () => {
|
|
const dossier = { party: { id: PARTY, displayName: 'Loopia AB' }, facts: [], identities: [], decisions: [], vouchers: [], similar: [] }
|
|
getDossier.mockResolvedValue(dossier)
|
|
const { status, body } = await parseJsonResponse<{ data: typeof dossier }>(
|
|
await dossierGet(createMockRequest(`/api/parties/${PARTY}`), { params: Promise.resolve({ id: PARTY }) }),
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data.party.displayName).toBe('Loopia AB')
|
|
expect(getDossier).toHaveBeenCalledWith(mockSupabase, 'company-1', PARTY)
|
|
})
|
|
})
|
|
|
|
describe('POST /api/parties/suggest', () => {
|
|
it('runs the pipeline for the caller and company', async () => {
|
|
const summary = { observed: 10, suggested: 4, skipped: 6, created: 3, attached: 1, identities: 2, facts: 5 }
|
|
suggestPartiesForCompany.mockResolvedValue(summary)
|
|
const { status, body } = await parseJsonResponse<{ data: typeof summary }>(await suggestPost(createMockRequest('/api/parties/suggest', { method: 'POST' }), noParams))
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual(summary)
|
|
expect(suggestPartiesForCompany).toHaveBeenCalledWith(mockSupabase, 'company-1', 'user-1')
|
|
})
|
|
})
|
|
|
|
describe('POST /api/parties/decide', () => {
|
|
it('rejects an empty id list and an unknown kind', async () => {
|
|
const a = await parseJsonResponse(await decidePost(json('/api/parties/decide', { partyIds: [], kind: 'confirm' }), noParams))
|
|
expect(a.status).toBe(400)
|
|
const b = await parseJsonResponse(await decidePost(json('/api/parties/decide', { partyIds: [PARTY], kind: 'merge' }), noParams))
|
|
expect(b.status).toBe(400)
|
|
})
|
|
|
|
it('calls decide_parties with the caller identity and returns the count', async () => {
|
|
enqueue({ data: 2 })
|
|
const { status, body } = await parseJsonResponse<{ data: { count: number; kind: string } }>(
|
|
await decidePost(json('/api/parties/decide', { partyIds: [PARTY, OTHER], kind: 'confirm', note: 'from queue' }), noParams),
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual({ count: 2, kind: 'confirm' })
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith('decide_parties', {
|
|
p_company_id: 'company-1',
|
|
p_user_id: 'user-1',
|
|
p_party_ids: [PARTY, OTHER],
|
|
p_kind: 'confirm',
|
|
p_note: 'from queue',
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('POST /api/parties/decide/undo', () => {
|
|
it('reverses the latest decisions for the given parties', async () => {
|
|
enqueue({ data: 1 })
|
|
const { status, body } = await parseJsonResponse<{ data: { count: number } }>(
|
|
await undoDecidePost(json('/api/parties/decide/undo', { partyIds: [PARTY] }), noParams),
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual({ count: 1 })
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith('undo_party_decisions', { p_company_id: 'company-1', p_user_id: 'user-1', p_party_ids: [PARTY] })
|
|
})
|
|
})
|
|
|
|
describe('POST /api/parties/merge', () => {
|
|
it('rejects a survivor listed among the merged ids', async () => {
|
|
const { status } = await parseJsonResponse(await mergePost(json('/api/parties/merge', { survivorId: PARTY, mergedIds: [PARTY] }), noParams))
|
|
expect(status).toBe(400)
|
|
expect(mockSupabase.rpc).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('maps a foreign or merged party to 404', async () => {
|
|
enqueue({ data: null, error: { code: '23503', message: 'survivor is not a live party of this company' } })
|
|
const { status } = await parseJsonResponse(await mergePost(json('/api/parties/merge', { survivorId: PARTY, mergedIds: [OTHER] }), noParams))
|
|
expect(status).toBe(404)
|
|
})
|
|
|
|
it('returns the decision id for undo', async () => {
|
|
enqueue({ data: DECISION })
|
|
const { status, body } = await parseJsonResponse<{ data: { decisionId: string; survivorId: string; mergedIds: string[] } }>(
|
|
await mergePost(json('/api/parties/merge', { survivorId: PARTY, mergedIds: [OTHER], note: 'same supplier' }), noParams),
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual({ decisionId: DECISION, survivorId: PARTY, mergedIds: [OTHER] })
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith('merge_parties', {
|
|
p_company_id: 'company-1',
|
|
p_user_id: 'user-1',
|
|
p_survivor: PARTY,
|
|
p_merged: [OTHER],
|
|
p_note: 'same supplier',
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('POST /api/parties/merge/undo', () => {
|
|
it('validates the decision id', async () => {
|
|
const { status } = await parseJsonResponse(await undoMergePost(json('/api/parties/merge/undo', { decisionId: 'x' }), noParams))
|
|
expect(status).toBe(400)
|
|
})
|
|
|
|
it('restores the merged parties', async () => {
|
|
enqueue({ data: 2 })
|
|
const { status, body } = await parseJsonResponse<{ data: { restored: number } }>(
|
|
await undoMergePost(json('/api/parties/merge/undo', { decisionId: DECISION }), noParams),
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual({ restored: 2 })
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith('undo_party_merge', { p_company_id: 'company-1', p_user_id: 'user-1', p_decision_id: DECISION })
|
|
})
|
|
})
|
|
|
|
describe('POST /api/parties/promote', () => {
|
|
it('rejects an item without roles', async () => {
|
|
const { status } = await parseJsonResponse(await promotePost(json('/api/parties/promote', { items: [{ partyId: PARTY, roles: [] }] }), noParams))
|
|
expect(status).toBe(400)
|
|
expect(mockSupabase.rpc).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('maps a foreign or archived party to 404', async () => {
|
|
enqueue({ data: null, error: { code: '23503', message: 'not a live party' } })
|
|
const { status } = await parseJsonResponse(await promotePost(json('/api/parties/promote', { items: [{ partyId: PARTY, roles: ['supplier'] }] }), noParams))
|
|
expect(status).toBe(404)
|
|
})
|
|
|
|
it('calls promote_parties with snake_case items and returns the counts', async () => {
|
|
enqueue({ data: { parties: 2, suppliers: 1, customers: 1 } })
|
|
const { status, body } = await parseJsonResponse<{ data: { parties: number; suppliers: number; customers: number } }>(
|
|
await promotePost(
|
|
json('/api/parties/promote', {
|
|
items: [
|
|
{ partyId: PARTY, roles: ['supplier'] },
|
|
{ partyId: OTHER, roles: ['customer'] },
|
|
],
|
|
}),
|
|
noParams,
|
|
),
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual({ parties: 2, suppliers: 1, customers: 1 })
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith('promote_parties', {
|
|
p_company_id: 'company-1',
|
|
p_user_id: 'user-1',
|
|
p_items: [
|
|
{ party_id: PARTY, roles: ['supplier'] },
|
|
{ party_id: OTHER, roles: ['customer'] },
|
|
],
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('POST /api/parties/promote/undo', () => {
|
|
it('reverses promotions for the given parties', async () => {
|
|
enqueue({ data: 2 })
|
|
const { status, body } = await parseJsonResponse<{ data: { count: number } }>(
|
|
await undoPromotePost(json('/api/parties/promote/undo', { partyIds: [PARTY, OTHER] }), noParams),
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual({ count: 2 })
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith('undo_party_promotions', { p_company_id: 'company-1', p_user_id: 'user-1', p_party_ids: [PARTY, OTHER] })
|
|
})
|
|
})
|