Files
accounted/components/parties/SuggestionQueue.tsx
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

158 lines
7.0 KiB
TypeScript

'use client'
import { useTranslations } from 'next-intl'
import { Check, ChevronDown } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { HOVER_REVEAL_CLASS, TD_CLASS, TH_CLASS } from '@/components/ui/dry-table'
import type { PartyRole, RegisterRow } from '@/lib/parties/register'
import { formatCurrency } from '@/lib/utils'
import { AccountNub } from './AccountNub'
import { isDuplicateCandidate, reasonText, rolesLabel } from './format'
/**
* The queue in front of Leverantörer and Kunder. Every row states why it is
* here and what it becomes; only rows with a hard key arrive pre-ticked;
* bulk confirm opens one dialog that says what happens.
*/
export function SuggestionQueue({
rows,
selected,
roles,
canWrite,
busy,
onToggle,
onSelectAll,
onClear,
onRoles,
onConfirmSelected,
onDismiss,
onOpen,
}: {
rows: RegisterRow[]
selected: Set<string>
roles: (row: RegisterRow) => PartyRole[]
canWrite: boolean
busy: boolean
onToggle: (id: string) => void
onSelectAll: () => void
onClear: () => void
onRoles: (id: string, roles: PartyRole[]) => void
onConfirmSelected: () => void
onDismiss: (row: RegisterRow) => void
onOpen: (id: string) => void
}) {
const t = useTranslations('parties')
const count = selected.size
const allSelected = rows.length > 0 && rows.every((r) => selected.has(r.id))
function toggleRole(row: RegisterRow, role: PartyRole) {
const current = roles(row)
const next = current.includes(role) ? current.filter((r) => r !== role) : [...current, role]
if (next.length === 0) return
onRoles(row.id, next)
}
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3 text-[13px]">
<span className="tabular-nums text-muted-foreground">{t('selected_n', { count })}</span>
<span className="text-muted-foreground">{t('selected_hint')}</span>
<div className="ml-auto flex items-center gap-2">
<Button type="button" variant="outline" size="sm" onClick={allSelected ? onClear : onSelectAll} disabled={rows.length === 0}>
{allSelected ? t('deselect') : t('select_all')}
</Button>
<Button type="button" size="sm" onClick={onConfirmSelected} disabled={!canWrite || busy || count === 0}>
{t('promote_n', { count })}
</Button>
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={`${TH_CLASS} w-8`} />
<th className={TH_CLASS}>{t('th_name')}</th>
<th className={TH_CLASS}>{t('th_why')}</th>
<th className={TH_CLASS}>{t('th_becomes')}</th>
<th className={TH_CLASS}>{t('th_account')}</th>
<th className={`${TH_CLASS} text-right`}>{t('th_revenue')}</th>
<th className={`${TH_CLASS} text-right`}>{t('th_expense')}</th>
<th className={`${TH_CLASS} w-16`} />
</tr>
</thead>
<tbody className="stagger-enter">
{rows.map((row) => {
const checked = selected.has(row.id)
const current = roles(row)
return (
<tr key={row.id} className="group transition-colors duration-150 hover:bg-secondary/35">
<td className={`${TD_CLASS} w-8`}>
<Checkbox checked={checked} onCheckedChange={() => onToggle(row.id)} aria-label={row.displayName} disabled={!canWrite} />
</td>
<td className={`${TD_CLASS} whitespace-nowrap`}>
<button
type="button"
className="text-left font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onOpen(row.id)}
aria-label={t('open_dossier', { name: row.displayName })}
>
{row.displayName}
</button>
{isDuplicateCandidate(row) ? (
<Badge variant="warning" className="ml-2">
{t('chip_duplicate')}
</Badge>
) : null}
</td>
<td className={`${TD_CLASS} text-muted-foreground`}>{reasonText(t, row.reason, row.stats?.rhythm ?? null)}</td>
<td className={`${TD_CLASS} whitespace-nowrap`}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="inline-flex items-center gap-1 text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:text-muted-foreground"
disabled={!canWrite}
aria-label={t('becomes_aria', { name: row.displayName })}
>
{rolesLabel(t, current)}
<ChevronDown className="h-3 w-3 text-muted-foreground" aria-hidden="true" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
{(['supplier', 'customer'] as const).map((role) => (
<DropdownMenuItem key={role} onSelect={(e) => { e.preventDefault(); toggleRole(row, role) }} className="gap-2">
<Check className={`h-3.5 w-3.5 ${current.includes(role) ? '' : 'invisible'}`} aria-hidden="true" />
{role === 'supplier' ? t('role_supplier') : t('role_customer')}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</td>
<td className={TD_CLASS}>
<AccountNub account={row.stats?.dominantAccount ?? null} />
</td>
<td className={`${TD_CLASS} text-right tabular-nums`}>{row.stats?.revenueSek ? formatCurrency(row.stats.revenueSek) : ''}</td>
<td className={`${TD_CLASS} text-right tabular-nums`}>{row.stats?.expenseSek ? formatCurrency(row.stats.expenseSek) : ''}</td>
<td className={`${TD_CLASS} text-right`}>
<button
type="button"
className={`${HOVER_REVEAL_CLASS} text-xs text-muted-foreground underline-offset-2 hover:underline`}
onClick={() => onDismiss(row)}
disabled={!canWrite || busy}
>
{t('dismiss')}
</button>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
)
}