Files
accounted/components/parties/SuggestionQueue.tsx
T
c6ca119e73 feat(parties): one suggestion per legal person, rename on rebuild, review list for SCB matches, model reading for memos (#2274)
* fix(parties): one suggestion per legal person, and a later run may rename an untouched one

Found while walking the queue end to end: two voucher keys naming the same
company ("TIC identity · … The Intelligence Company AB (publ)" and
"Utbetalning leverantörsfaktura …, The Intelligence Company AB (publ)")
became two suggestions and, after Lägg upp, two suppliers; and a suggestion
made before the legal-form anchoring kept its sentence-long name for good,
because apply_party_suggestions never touched a name.

- Suggestions whose display name is anchored on a legal form read out of
  the voucher text (name_anchored) are grouped: one item, both keys as
  aliases, stats summed. Such a name also attaches to an existing party
  called exactly that, legal form included, unless an org number on either
  side says otherwise. Registered company names are unique in Sweden; a
  bank memo never groups or attaches by name.
- Migration 20260904030000: apply_party_suggestions renames a suggestion
  nobody has touched (no decision, no user or registry fact) to an anchored
  name from a later run, and reports 'renamed'. Confirmed and decided
  parties keep their names.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(parties): read legal_name for exact-name attach; say a row is foreign instead of offering SCB

next build: ExistingParty had no legal_name, so the exact-legal-name index
did not compile. The query now selects it.

Queue rows whose voucher text places the company abroad show
"Utländskt bolag (Nederländerna), finns inte i SCB" instead of a search
that cannot succeed; the promote dialog counts them separately from rows
that merely lack an org number; the dossier shows the country.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(parties): carry country on the dossier row

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(parties): one review list for SCB matches, a model reading for bank memos, refresh demoted

- Review list ("Hitta org.nr (n)" in the queue toolbar): every suggestion
  SCB could hold but that lacks an org number is asked for, one row at a
  time under SCB's rate limit; rows with exactly one active match are
  shown ticked and approved in one click, the rest keep the per-row
  picker. Nothing is written before the click.
- Model reading (lib/parties/ai-name.ts, through getAiService): when the
  rules find no legal form or country in the texts, one call reads the
  counterpart out of the bank memo; kept as a 'model' fact, shown as
  "Läst ur verifikatet", used as the query, never as a hard key. On
  demand only, never when the queue builds.
- "Uppdatera förslag" moves from the page header to a ghost button in the
  toolbar: the queue builds itself now.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(parties): review list passes the dialog overflow guard; plural for match counts

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(parties): gate the model reading on the company's AI capability

Same gate as every other model call on company data: the capability the
company holds by plan and can switch off. No call, no fact, no reading
without it.

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-04 17:01:10 +02:00

196 lines
8.6 KiB
TypeScript

'use client'
import { useLocale, 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.
*/
/** A party the voucher text places abroad: SCB cannot hold it, so no search is offered. */
export function isForeign(row: { country: string | null }): boolean {
return !!row.country && row.country !== 'SE'
}
export function regionName(code: string, locale: string): string {
try {
return new Intl.DisplayNames([locale], { type: 'region' }).of(code) ?? code
} catch {
return code
}
}
export function SuggestionQueue({
rows,
selected,
roles,
canWrite,
busy,
onToggle,
onSelectAll,
onClear,
onRoles,
onConfirmSelected,
onDismiss,
onOpen,
onFind,
}: {
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
/** Open the SCB picker for a row without an org number; undefined hides the link. */
onFind?: (row: RegisterRow) => void
}) {
const t = useTranslations('parties')
const locale = useLocale()
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} max-w-[22rem]`}>
<button
type="button"
className="block max-w-full truncate 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 })}
title={row.displayName}
>
{row.displayName}
</button>
{isDuplicateCandidate(row) ? (
<Badge variant="warning" className="ml-2">
{t('chip_duplicate')}
</Badge>
) : null}
</td>
<td className={`${TD_CLASS} min-w-[16rem] max-w-[28rem] text-muted-foreground`}>
{reasonText(t, row.reason, row.stats?.rhythm ?? null, row.orgNumber)}
{isForeign(row) ? (
<>
{' · '}
<span className="text-foreground">{t('row_foreign', { country: regionName(row.country as string, locale) })}</span>
</>
) : onFind && !row.orgNumber && row.kind !== 'person' ? (
<>
{' · '}
<button
type="button"
className="text-foreground underline underline-offset-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onFind(row)}
disabled={!canWrite}
>
{t('pick_registry')}
</button>
</>
) : 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>
)
}