feat(parties): fetch registry facts from SCB into the dossier, with a picker for parties without an org number (#2258)
* 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> * feat(parties): fetch registry facts from SCB into the dossier SCB granted API access today (certificate + password, layouts Je and Ae). This adds the first registry enricher of phase 3: - lib/parties/scb: config from env (SCB_API_CERT_PFX_BASE64, SCB_API_CERT_PASSWORD), an mTLS transport on node:https, the mapping of every documented Je variable to a labelled fact, and a client whose wire format sits in one file because SCB replaces the API this month. Legal persons only: a sole trader's org number is a personnummer. - Migration 20260903150000: record_party_facts(company, user, party, source, facts, fetched_at) refreshes unchanged values, supersedes changed ones, never touches other sources. pg test. - POST /api/parties/[id]/enrich: 503 when not configured, 400 for a sole trader, 502 when SCB fails, fills an empty legal name. 7 tests. - Dossier: 'Hämta uppgifter' button (gated on configuration) and the registry rows with 'SCB · datum' as their source line. - scripts/scb/discover.ts prints the live variable list, code tables and one lookup so the request shape is checked against the real API. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): SCB client on the live wire format, mapper on the real Je row Verified against the API on 2026-09-03: an identity lookup is one filter (Variabel 'OrgNr (10 siffror)', Operator ArLikaMed) without status keys, and the row carries '<name>, kod' beside SCB's own text. The mapper now reads those columns, prefers SCB's text, and adds turnover band, seat names and Skatteverket registration. The AB Volvo row is the fixture. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): registry legal name outranks the document one, never a person's Survivorship from the plan: user > registry > document. The dossier's legal-name row now carries 'SCB · datum' when the registry is the source. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): VAT number from the moms flag, one primary action, one source line Founder review of the SCB dossier: - A Swedish company registered for moms has VAT number SE + org number + 01 by construction, so the registry's moms flag yields the number; it fills an empty vat_number on the party and shows in the Momsnr row instead of 'Saknas'. - The 'Registrerad hos Skatteverket' row said nothing (true for every legal person) and is gone. - Five buttons became one primary (the role the ledger suggests) and a menu with the rest; the per-row 'SCB · datum' notes became one group line 'Från SCB · hämtat datum'. - A postal-code-only address (large companies) is labelled as such. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): do not repeat the county when it equals the municipality Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): SCB picker for parties without an org number 'Hitta i företagsregistret' in the dossier menu opens a picker: SCB is searched on the party's name (prefix first, contains as fallback, counts before rows, capped at 25, natural persons and estates excluded, active companies first). The user chooses; the org number is recorded as a fact with source 'user' and set on the party, then the normal fetch runs, so every later fetch is by number. A number another live party holds is refused with a pointer to it. One match is still shown, never auto-picked. The transport retries once on a dropped connection (seen live). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): a picked org number shows in the queue's reason and counts as a hard key Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): SCB search tightened after a batch of real supplier names Twenty-five prod supplier names and twenty org numbers across every legal form went through the search and the lookup: - total is what the picker can offer, not SCB's raw count (Eismann counted one row and offered none, a natural person); - foreign legal forms stay in the query: they are part of the registered name and dropping them floods (Schmidt GmbH became 167 Schmidts); - a fusion or delning in progress is no longer a warning (Fortnox AB and Avanza Bank trade normally under 'Fusion pågår'); distress and disappearance codes still are. 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> * chore(parties): move record_party_facts after the queue migrations Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move record_party_facts to a version after tonight's collisions 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:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
47c73206e1
commit
22b98e0a3b
@@ -1,8 +1,11 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { isLegalPersonOrgNumber } from '@/lib/parties/scb/org-number'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { MoreHorizontal } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { VTD_CLASS, VTH_CLASS } from '@/components/ui/dry-table'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { SlideOver, SlideOverBody, SlideOverContent, SlideOverHeader } from '@/components/ui/slide-over'
|
||||
@@ -16,6 +19,58 @@ function SectionTitle({ children }: { children: React.ReactNode }) {
|
||||
return <h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">{children}</h2>
|
||||
}
|
||||
|
||||
const REGISTRY_FIELDS = [
|
||||
'f_tax',
|
||||
'vat_registration',
|
||||
'employer_registration',
|
||||
'company_status',
|
||||
'legal_form',
|
||||
'bolagsverket_status',
|
||||
'employees_band',
|
||||
'turnover_band',
|
||||
'industry',
|
||||
'postal_address',
|
||||
'seat',
|
||||
'registered_at',
|
||||
'active_since',
|
||||
'active_until',
|
||||
'phone',
|
||||
'email',
|
||||
'workplaces',
|
||||
'trade_name',
|
||||
] as const
|
||||
|
||||
/** Live registry facts, in the order the dossier shows them; the VAT number sits in its own row above. */
|
||||
function registryFacts(facts: Dossier['facts']): Dossier['facts'] {
|
||||
const scb = facts.filter((f) => f.source === 'registry_scb')
|
||||
return REGISTRY_FIELDS.flatMap((field) => scb.filter((f) => f.field === field))
|
||||
}
|
||||
|
||||
function registryLabel(t: (k: string) => string, field: string): string {
|
||||
return REGISTRY_FIELDS.includes(field as (typeof REGISTRY_FIELDS)[number]) ? t(`fact_${field}`) : field
|
||||
}
|
||||
|
||||
/** Coded facts show their label; address and seat compose; the rest print. */
|
||||
function registryValue(value: unknown): React.ReactNode {
|
||||
if (value === null || value === undefined) return '·'
|
||||
if (typeof value === 'string' || typeof value === 'number') return String(value)
|
||||
const v = value as Record<string, unknown>
|
||||
if (typeof v.label === 'string') {
|
||||
const label = typeof v.year === 'string' && v.year ? `${v.label} (${v.year})` : v.label
|
||||
return v.warning ? <span className="text-warning">{label}</span> : label
|
||||
}
|
||||
if ('street' in v || 'city' in v) {
|
||||
return [v.co, v.street, [v.postal_code, v.city].filter(Boolean).join(' ')].filter(Boolean).join(', ')
|
||||
}
|
||||
if ('municipality' in v || 'municipality_code' in v) {
|
||||
const parts = [v.municipality ?? v.municipality_code, v.county ?? v.county_code].filter(Boolean) as string[]
|
||||
// "Stockholm, Stockholm": the county adds nothing when it repeats the municipality.
|
||||
return parts.filter((x, i) => i === 0 || x !== parts[0]).join(', ')
|
||||
}
|
||||
if ('code' in v) return String(v.code)
|
||||
return JSON.stringify(v)
|
||||
}
|
||||
|
||||
function Row({ label, value, note }: { label: string; value: React.ReactNode; note?: React.ReactNode }) {
|
||||
return (
|
||||
<tr>
|
||||
@@ -42,6 +97,9 @@ export function PartyDossier({
|
||||
onPromote,
|
||||
onDismiss,
|
||||
onMerge,
|
||||
onFetchRegistry,
|
||||
onPickRegistry,
|
||||
fetching = false,
|
||||
reloadKey,
|
||||
}: {
|
||||
partyId: string | null
|
||||
@@ -52,6 +110,11 @@ export function PartyDossier({
|
||||
onPromote: (id: string, roles: PartyRole[]) => void
|
||||
onDismiss: (id: string) => void
|
||||
onMerge: (subject: MergeCandidate, suggested: MergeCandidate[]) => void
|
||||
/** Fetch registry facts from SCB for this party; undefined hides the item. */
|
||||
onFetchRegistry?: (id: string) => void
|
||||
/** Open the SCB picker for a party without an org number. */
|
||||
onPickRegistry?: (id: string, name: string) => void
|
||||
fetching?: boolean
|
||||
reloadKey: number
|
||||
}) {
|
||||
const t = useTranslations('parties')
|
||||
@@ -99,10 +162,19 @@ export function PartyDossier({
|
||||
const orgFact = dossier?.facts.find((f) => f.field === 'org_number')
|
||||
const docsFor = (field: string) => {
|
||||
const f = dossier?.facts.find((x) => x.field === field)
|
||||
const n = (f?.reference as { docs?: number } | null)?.docs
|
||||
return n ? t('fact_from_documents', { count: n }) : f?.source === 'ledger' ? t('fact_from_ledger') : f?.source === 'user' ? t('fact_from_user') : ''
|
||||
if (!f) return ''
|
||||
if (f.source === 'registry_scb') return t('source_scb')
|
||||
const n = (f.reference as { docs?: number } | null)?.docs
|
||||
return n ? t('fact_from_documents', { count: n }) : f.source === 'ledger' ? t('fact_from_ledger') : f.source === 'user' ? t('fact_from_user') : ''
|
||||
}
|
||||
const dominant = dossier?.facts.find((f) => f.field === 'dominant_account')?.value as { account?: string; count?: number } | undefined
|
||||
const registryVat = dossier?.facts.find((f) => f.field === 'vat_number' && f.source === 'registry_scb')?.value
|
||||
// One primary action: the role the ledger suggests and the party does not
|
||||
// have yet. The other role and everything else live behind the menu.
|
||||
const missingRoles: PartyRole[] = p ? (['supplier', 'customer'] as PartyRole[]).filter((r) => (r === 'supplier' ? !p.roles.supplierId : !p.roles.customerId)) : []
|
||||
const primaryRole: PartyRole | null = p ? (missingRoles.find((r) => p.defaultRoles.includes(r)) ?? missingRoles[0] ?? null) : null
|
||||
const secondaryRole: PartyRole | null = missingRoles.find((r) => r !== primaryRole) ?? null
|
||||
const scbFetchedAt = dossier?.facts.filter((f) => f.source === 'registry_scb').map((f) => f.fetchedAt ?? f.recordedAt).sort().at(-1) ?? null
|
||||
|
||||
return (
|
||||
<SlideOver open={Boolean(partyId)} onOpenChange={(open) => (!open ? onClose() : undefined)}>
|
||||
@@ -121,48 +193,46 @@ export function PartyDossier({
|
||||
<div className="space-y-8">
|
||||
<div className="space-y-3">
|
||||
{subtitle ? <p className="text-[13px] text-muted-foreground">{subtitle}</p> : null}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{suggested || !p.roles.supplierId ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={p.defaultRoles.includes('supplier') ? 'default' : 'outline'}
|
||||
onClick={() => onPromote(p.id, ['supplier'])}
|
||||
disabled={!canWrite || busy}
|
||||
>
|
||||
{t('promote_supplier')}
|
||||
</Button>
|
||||
) : null}
|
||||
{suggested || !p.roles.customerId ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={p.defaultRoles.includes('customer') && !p.defaultRoles.includes('supplier') ? 'default' : 'outline'}
|
||||
onClick={() => onPromote(p.id, ['customer'])}
|
||||
disabled={!canWrite || busy}
|
||||
>
|
||||
{t('promote_customer')}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={!canWrite || busy}
|
||||
onClick={() =>
|
||||
onMerge(
|
||||
{ id: p.id, displayName: p.displayName, orgNumber: p.orgNumber, status: p.status },
|
||||
dossier.similar.map((s) => ({ id: s.id, displayName: s.displayName, orgNumber: s.orgNumber, status: s.status })),
|
||||
)
|
||||
}
|
||||
>
|
||||
{t('merge')}
|
||||
</Button>
|
||||
{suggested ? (
|
||||
<Button type="button" size="sm" variant="ghost" onClick={() => onDismiss(p.id)} disabled={!canWrite || busy}>
|
||||
{t('dismiss')}
|
||||
<div className="flex items-center gap-2">
|
||||
{primaryRole ? (
|
||||
<Button type="button" size="sm" onClick={() => onPromote(p.id, [primaryRole])} disabled={!canWrite || busy}>
|
||||
{primaryRole === 'supplier' ? t('promote_supplier') : t('promote_customer')}
|
||||
</Button>
|
||||
) : null}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" size="sm" variant="outline" aria-label={t('more_actions')} disabled={!canWrite || busy}>
|
||||
<MoreHorizontal className="h-4 w-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start">
|
||||
{secondaryRole ? (
|
||||
<DropdownMenuItem onSelect={() => onPromote(p.id, [secondaryRole])}>
|
||||
{secondaryRole === 'supplier' ? t('promote_supplier') : t('promote_customer')}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{onFetchRegistry && isLegalPersonOrgNumber(p.orgNumber) ? (
|
||||
<DropdownMenuItem onSelect={() => onFetchRegistry(p.id)} disabled={fetching}>
|
||||
{fetching ? t('fetching_registry') : t('fetch_registry')}
|
||||
</DropdownMenuItem>
|
||||
) : onPickRegistry && !p.orgNumber && p.kind !== 'person' ? (
|
||||
<DropdownMenuItem onSelect={() => onPickRegistry(p.id, p.legalName ?? p.displayName)} disabled={fetching}>
|
||||
{t('pick_registry')}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
<DropdownMenuItem
|
||||
onSelect={() =>
|
||||
onMerge(
|
||||
{ id: p.id, displayName: p.displayName, orgNumber: p.orgNumber, status: p.status },
|
||||
dossier.similar.map((s) => ({ id: s.id, displayName: s.displayName, orgNumber: s.orgNumber, status: s.status })),
|
||||
)
|
||||
}
|
||||
>
|
||||
{t('merge')}
|
||||
</DropdownMenuItem>
|
||||
{suggested ? <DropdownMenuItem onSelect={() => onDismiss(p.id)}>{t('dismiss')}</DropdownMenuItem> : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -226,7 +296,11 @@ export function PartyDossier({
|
||||
value={p.orgNumber ? formatOrgNumber(p.orgNumber) : <span className="text-muted-foreground">{t('fact_missing')}</span>}
|
||||
note={p.orgNumber && orgFact ? docsFor('org_number') : undefined}
|
||||
/>
|
||||
<Row label={t('fact_vat')} value={p.vatNumber ?? <span className="text-muted-foreground">{t('fact_missing')}</span>} />
|
||||
<Row
|
||||
label={t('fact_vat')}
|
||||
value={p.vatNumber ?? (registryVat ? String(registryVat) : <span className="text-muted-foreground">{t('fact_missing')}</span>)}
|
||||
note={p.vatNumber ? docsFor('vat_number') || undefined : registryVat ? docsFor('vat_number') : undefined}
|
||||
/>
|
||||
{dossier.identities.map((i) => (
|
||||
<Row
|
||||
key={i.id}
|
||||
@@ -235,6 +309,20 @@ export function PartyDossier({
|
||||
note={`${t('fact_from_documents', { count: i.seenCount })} · ${i.status === 'known' ? t('identity_known') : t('identity_unverified')}`}
|
||||
/>
|
||||
))}
|
||||
{scbFetchedAt && registryFacts(dossier.facts).length > 0 ? (
|
||||
<tr>
|
||||
<td colSpan={2} className="pt-4 pb-1 text-[11px] uppercase tracking-wider text-muted-foreground">
|
||||
{t('registry_group', { date: formatDate(scbFetchedAt) })}
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{registryFacts(dossier.facts).map((f) => (
|
||||
<Row
|
||||
key={f.id}
|
||||
label={f.field === 'postal_address' && !(f.value as { street?: string | null })?.street ? t('fact_postal_code_city') : registryLabel(t, f.field)}
|
||||
value={registryValue(f.value)}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import type { ScbCandidate, ScbSearchResult } from '@/lib/parties/scb/client'
|
||||
import { formatOrgNumber } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* "SCB hittar två företag som liknar Adobe Systems Software, vilket menar
|
||||
* du?" The picker for a party without an org number: the user chooses,
|
||||
* the org number lands on the party, and every later fetch is by number.
|
||||
* One match is still shown, never auto-picked.
|
||||
*/
|
||||
export function ScbPickerDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
partyId,
|
||||
partyName,
|
||||
busy,
|
||||
onPick,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
partyId: string
|
||||
partyName: string
|
||||
busy: boolean
|
||||
onPick: (candidate: ScbCandidate) => Promise<void>
|
||||
}) {
|
||||
const t = useTranslations('parties')
|
||||
const tCommon = useTranslations('common')
|
||||
const [query, setQuery] = useState('')
|
||||
const [loaded, setLoaded] = useState<{ key: string; result: ScbSearchResult | null; failed: boolean } | null>(null)
|
||||
const [selected, setSelected] = useState<string | null>(null)
|
||||
|
||||
const key = `${partyId}:${query.trim()}`
|
||||
const current = loaded && loaded.key === key ? loaded : null
|
||||
const loading = open && current === null
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
let cancelled = false
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const params = query.trim() ? `?q=${encodeURIComponent(query.trim())}` : ''
|
||||
const res = await fetch(`/api/parties/${partyId}/enrich/candidates${params}`, { signal: ctrl.signal })
|
||||
const json = (await res.json()) as { data?: ScbSearchResult }
|
||||
if (!cancelled) setLoaded({ key, result: res.ok ? (json.data ?? null) : null, failed: !res.ok })
|
||||
} catch {
|
||||
if (!cancelled) setLoaded({ key, result: null, failed: true })
|
||||
}
|
||||
}, query.trim() ? 300 : 0)
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearTimeout(timer)
|
||||
ctrl.abort()
|
||||
}
|
||||
}, [open, partyId, query, key])
|
||||
|
||||
const result = current?.result ?? null
|
||||
const candidates = result?.candidates ?? []
|
||||
const chosen = candidates.find((c) => c.orgNumber === selected) ?? null
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('picker_title')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{result && !current?.failed
|
||||
? result.truncated
|
||||
? t('picker_too_many', { count: result.total, query: result.query })
|
||||
: candidates.length === 0
|
||||
? t('picker_none', { query: result.query })
|
||||
: t('picker_found', { count: candidates.length, query: result.query })
|
||||
: t('picker_body', { name: partyName })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value)
|
||||
setSelected(null)
|
||||
}}
|
||||
placeholder={t('picker_search_placeholder')}
|
||||
aria-label={t('picker_search_placeholder')}
|
||||
/>
|
||||
{loading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
) : current?.failed ? (
|
||||
<p className="text-sm text-muted-foreground">{t('registry_unavailable_title')}</p>
|
||||
) : candidates.length > 0 ? (
|
||||
<ul className="max-h-80 divide-y divide-border overflow-y-auto rounded-lg border border-border" role="listbox" aria-label={t('picker_title')}>
|
||||
{candidates.map((c) => {
|
||||
const isSelected = selected === c.orgNumber
|
||||
return (
|
||||
<li key={c.orgNumber}>
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
onClick={() => setSelected(c.orgNumber)}
|
||||
className={`flex w-full items-start gap-3 px-4 py-3 text-left text-[13px] transition-colors duration-150 hover:bg-secondary/35 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${isSelected ? 'bg-secondary/60' : ''}`}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate font-medium">{c.name}</span>
|
||||
{!c.active ? <Badge variant="warning">{c.status ?? t('picker_inactive')}</Badge> : null}
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted-foreground tabular-nums">
|
||||
{[formatOrgNumber(c.orgNumber), c.city, c.industry].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>
|
||||
{tCommon('cancel')}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => (chosen ? void onPick(chosen) : undefined)} disabled={busy || !chosen}>
|
||||
{chosen ? t('picker_confirm', { name: chosen.name }) : t('picker_confirm_empty')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -107,7 +107,7 @@ export function SuggestionQueue({
|
||||
</Badge>
|
||||
) : null}
|
||||
</td>
|
||||
<td className={`${TD_CLASS} text-muted-foreground`}>{reasonText(t, row.reason, row.stats?.rhythm ?? null)}</td>
|
||||
<td className={`${TD_CLASS} text-muted-foreground`}>{reasonText(t, row.reason, row.stats?.rhythm ?? null, row.orgNumber)}</td>
|
||||
<td className={`${TD_CLASS} whitespace-nowrap`}>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
|
||||
@@ -25,16 +25,20 @@ export function rolesLabel(t: Translate, roles: PartyRole[]): string {
|
||||
}
|
||||
|
||||
/** "Org.nr 556354-5185 i 3 underlag · 12 verifikat · varje månad": why a row is in the queue. */
|
||||
export function reasonText(t: Translate, reason: SuggestionReason | null, rhythm: LedgerStats['rhythm']): string {
|
||||
export function reasonText(t: Translate, reason: SuggestionReason | null, rhythm: LedgerStats['rhythm'], orgNumber: string | null = null): string {
|
||||
if (!reason) return ''
|
||||
const parts: string[] = []
|
||||
const docs = Math.max(0, (reason.docs ?? 0) - (reason.self_docs ?? 0))
|
||||
// An org number the person picked from the register (no document carries
|
||||
// it) is stated as such; the stored reason predates the pick.
|
||||
const picked = Boolean(orgNumber) && !reason.org_number
|
||||
if (reason.org_number) parts.push(t('reason_org', { org: formatOrgNumber(reason.org_number), docs }))
|
||||
else if (picked) parts.push(t('reason_org_picked', { org: formatOrgNumber(orgNumber!) }))
|
||||
else if (reason.ambiguous_orgs?.length) parts.push(t('reason_ambiguous'))
|
||||
else if (docs > 0) parts.push(t('reason_docs', { docs }))
|
||||
parts.push(t('reason_vouchers', { count: reason.occurrences ?? 0 }))
|
||||
if (rhythm && rhythm !== 'irregular') parts.push(rhythmLabel(t, rhythm))
|
||||
if (!reason.org_number && !reason.ambiguous_orgs?.length && docs === 0) parts.push(t('reason_ledger_only'))
|
||||
if (!reason.org_number && !picked && !reason.ambiguous_orgs?.length && docs === 0) parts.push(t('reason_ledger_only'))
|
||||
if (reason.similar_to?.length) parts.push(t('reason_similar', { name: reason.similar_to[0]!.display_name }))
|
||||
return parts.join(' · ')
|
||||
}
|
||||
@@ -52,5 +56,5 @@ export function isDuplicateCandidate(row: RegisterRow): boolean {
|
||||
}
|
||||
|
||||
export function hasHardKey(row: RegisterRow): boolean {
|
||||
return Boolean(row.reason?.org_number)
|
||||
return Boolean(row.reason?.org_number || row.orgNumber)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user