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>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
e2d38b0ab3
commit
b996da60ee
@@ -0,0 +1,4 @@
|
||||
export function AccountNub({ account }: { account: string | null }) {
|
||||
if (!account) return <span className="text-muted-foreground">·</span>
|
||||
return <span className="rounded-sm bg-secondary px-1 py-px font-mono text-[12px] tabular-nums">{account}</span>
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import type { Register, RegisterRow } from '@/lib/parties/register'
|
||||
import { formatOrgNumber } from '@/lib/utils'
|
||||
|
||||
export interface MergeCandidate {
|
||||
id: string
|
||||
displayName: string
|
||||
orgNumber: string | null
|
||||
status: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge with a visible survivor that can be swapped. Everything merged keeps
|
||||
* its rows; the survivor gains the aliases. Undo lives on the toast.
|
||||
*/
|
||||
export function MergeDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
subject,
|
||||
suggested,
|
||||
busy,
|
||||
onMerge,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
subject: MergeCandidate
|
||||
suggested: MergeCandidate[]
|
||||
busy: boolean
|
||||
onMerge: (survivorId: string, mergedIds: string[]) => Promise<void>
|
||||
}) {
|
||||
const t = useTranslations('parties')
|
||||
const tCommon = useTranslations('common')
|
||||
const [picked, setPicked] = useState<Set<string>>(new Set(suggested.map((s) => s.id)))
|
||||
const [survivor, setSurvivor] = useState<string>(subject.id)
|
||||
const [query, setQuery] = useState('')
|
||||
const [found, setFound] = useState<MergeCandidate[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const q = query.trim()
|
||||
if (q.length < 2) return
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/parties?view=all&q=${encodeURIComponent(q)}`, { signal: ctrl.signal })
|
||||
if (!res.ok) return
|
||||
const json = (await res.json()) as { data: Register }
|
||||
setFound(
|
||||
json.data.rows
|
||||
.filter((r: RegisterRow) => r.id !== subject.id)
|
||||
.slice(0, 8)
|
||||
.map((r: RegisterRow) => ({ id: r.id, displayName: r.displayName, orgNumber: r.orgNumber, status: r.status })),
|
||||
)
|
||||
} catch {
|
||||
// aborted or offline: the list simply does not update
|
||||
}
|
||||
}, 250)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
ctrl.abort()
|
||||
}
|
||||
}, [query, subject.id])
|
||||
|
||||
const candidates = useMemo(() => {
|
||||
const seen = new Set<string>()
|
||||
const out: MergeCandidate[] = []
|
||||
const searched = query.trim().length >= 2 ? found : []
|
||||
for (const c of [...suggested, ...searched]) {
|
||||
if (seen.has(c.id) || c.id === subject.id) continue
|
||||
seen.add(c.id)
|
||||
out.push(c)
|
||||
}
|
||||
return out
|
||||
}, [suggested, found, query, subject.id])
|
||||
|
||||
const members = [subject, ...candidates.filter((c) => picked.has(c.id))]
|
||||
const mergedIds = members.filter((m) => m.id !== survivor).map((m) => m.id)
|
||||
|
||||
function toggle(id: string) {
|
||||
setPicked((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) {
|
||||
next.delete(id)
|
||||
if (survivor === id) setSurvivor(subject.id)
|
||||
} else next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('merge_dialog_title')}</DialogTitle>
|
||||
<DialogDescription>{t('merge_body')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<ul className="divide-y divide-border rounded-lg border border-border">
|
||||
{[subject, ...candidates].map((c) => {
|
||||
const isSubject = c.id === subject.id
|
||||
const included = isSubject || picked.has(c.id)
|
||||
return (
|
||||
<li key={c.id} className="flex items-center gap-3 px-4 py-3 text-[13px]">
|
||||
<Checkbox
|
||||
checked={included}
|
||||
disabled={isSubject}
|
||||
onCheckedChange={() => toggle(c.id)}
|
||||
aria-label={c.displayName}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate font-medium">{c.displayName}</div>
|
||||
<div className="text-xs text-muted-foreground tabular-nums">
|
||||
{c.orgNumber ? formatOrgNumber(c.orgNumber) : ''}
|
||||
{c.status === 'suggested' ? (c.orgNumber ? ' · ' : '') + t('view_suggested') : ''}
|
||||
</div>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<input
|
||||
type="radio"
|
||||
name="party-survivor"
|
||||
className="h-4 w-4 accent-foreground"
|
||||
checked={survivor === c.id}
|
||||
disabled={!included}
|
||||
onChange={() => setSurvivor(c.id)}
|
||||
/>
|
||||
{survivor === c.id ? t('merge_kept') : t('merge_keep')}
|
||||
</label>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t('merge_search_placeholder')}
|
||||
aria-label={t('merge_search_placeholder')}
|
||||
/>
|
||||
{candidates.length === 0 && query.trim().length >= 2 ? (
|
||||
<p className="text-xs text-muted-foreground">{t('merge_none')}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>
|
||||
{tCommon('cancel')}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => void onMerge(survivor, mergedIds)} disabled={busy || mergedIds.length === 0}>
|
||||
{t('merge_confirm', { count: mergedIds.length })}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { TD_CLASS, TH_CLASS } from '@/components/ui/dry-table'
|
||||
import type { ObservedRow, Register } from '@/lib/parties/register'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { AccountNub } from './AccountNub'
|
||||
import { rhythmLabel } from './format'
|
||||
|
||||
function money(n: number): string {
|
||||
return n ? formatCurrency(n) : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* "Bara i bokföringen": counterparts the ledger names that no party claims.
|
||||
* Computed, never stored; the generic band keeps unattributed spend visible
|
||||
* without inventing a supplier for "Inköp av varor".
|
||||
*/
|
||||
export function ObservedTable({ rows, generic }: { rows: ObservedRow[]; generic: Register['generic'] }) {
|
||||
const t = useTranslations('parties')
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={TH_CLASS}>{t('th_name')}</th>
|
||||
<th className={TH_CLASS}>{t('th_rhythm')}</th>
|
||||
<th className={TH_CLASS}>{t('th_vouchers')}</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>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="stagger-enter">
|
||||
{rows.map((row) => (
|
||||
<tr key={row.key} className="transition-colors duration-150 hover:bg-secondary/35">
|
||||
<td className={`${TD_CLASS} whitespace-nowrap`}>
|
||||
<span className="text-foreground">{row.name}</span>
|
||||
{row.label === 'unsure' ? <span className="ml-2 text-xs text-muted-foreground">{t('uncertain_name')}</span> : null}
|
||||
</td>
|
||||
<td className={`${TD_CLASS} whitespace-nowrap text-muted-foreground`}>{rhythmLabel(t, row.stats.rhythm)}</td>
|
||||
<td className={`${TD_CLASS} whitespace-nowrap text-muted-foreground tabular-nums`}>{t('vouchers_count', { count: row.stats.occurrences })}</td>
|
||||
<td className={TD_CLASS}>
|
||||
<AccountNub account={row.stats.dominantAccount} />
|
||||
</td>
|
||||
<td className={`${TD_CLASS} text-right tabular-nums`}>{money(row.stats.revenueSek)}</td>
|
||||
<td className={`${TD_CLASS} text-right tabular-nums`}>{money(row.stats.expenseSek)}</td>
|
||||
</tr>
|
||||
))}
|
||||
{generic.count > 0 ? (
|
||||
<tr className="bg-muted/30">
|
||||
<td colSpan={5} className="px-4 py-2 text-[12px] text-muted-foreground">
|
||||
<span className="font-semibold">{t('generic_band', { count: generic.count })}</span>
|
||||
<span className="ml-2">{t('generic_band_description', { examples: generic.examples.join(' · ') })}</span>
|
||||
</td>
|
||||
<td className="px-4 py-2 text-right text-[12px] text-muted-foreground tabular-nums">{money(generic.expenseSek)}</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
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'
|
||||
import type { Dossier, PartyRole, RegisterPeriod } from '@/lib/parties/register'
|
||||
import { formatCurrency, formatDate, formatOrgNumber } from '@/lib/utils'
|
||||
import { AccountNub } from './AccountNub'
|
||||
import { formatPaymentIdentity, rhythmLabel, roleLabel } from './format'
|
||||
import type { MergeCandidate } from './MergeDialog'
|
||||
|
||||
function SectionTitle({ children }: { children: React.ReactNode }) {
|
||||
return <h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">{children}</h2>
|
||||
}
|
||||
|
||||
function Row({ label, value, note }: { label: string; value: React.ReactNode; note?: React.ReactNode }) {
|
||||
return (
|
||||
<tr>
|
||||
<th className={`${VTH_CLASS} w-36`}>{label}</th>
|
||||
<td className={VTD_CLASS}>
|
||||
<div className="tabular-nums">{value}</div>
|
||||
{note ? <div className="text-xs text-muted-foreground">{note}</div> : null}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Moment 3: the dossier. Money and booking knowledge come from the ledger;
|
||||
* "Vad Accounted vet" lists every fact with its source; promotion and
|
||||
* merge are one action each and always confirm up front.
|
||||
*/
|
||||
export function PartyDossier({
|
||||
partyId,
|
||||
period,
|
||||
canWrite,
|
||||
busy,
|
||||
onClose,
|
||||
onPromote,
|
||||
onDismiss,
|
||||
onMerge,
|
||||
reloadKey,
|
||||
}: {
|
||||
partyId: string | null
|
||||
period: RegisterPeriod
|
||||
canWrite: boolean
|
||||
busy: boolean
|
||||
onClose: () => void
|
||||
onPromote: (id: string, roles: PartyRole[]) => void
|
||||
onDismiss: (id: string) => void
|
||||
onMerge: (subject: MergeCandidate, suggested: MergeCandidate[]) => void
|
||||
reloadKey: number
|
||||
}) {
|
||||
const t = useTranslations('parties')
|
||||
// { partyId, reloadKey } stamps the loaded dossier, so "loading" and
|
||||
// "failed" are derived instead of set from inside the effect.
|
||||
const [loaded, setLoaded] = useState<{ partyId: string; reloadKey: number; dossier: Dossier | null } | null>(null)
|
||||
const current = loaded && loaded.partyId === partyId && loaded.reloadKey === reloadKey ? loaded : null
|
||||
const dossier = partyId ? (current?.dossier ?? (loaded?.partyId === partyId ? loaded.dossier : null)) : null
|
||||
const loading = Boolean(partyId) && current === null
|
||||
const failed = Boolean(partyId) && current !== null && current.dossier === null
|
||||
|
||||
useEffect(() => {
|
||||
if (!partyId) return
|
||||
let cancelled = false
|
||||
const key = reloadKey
|
||||
fetch(`/api/parties/${partyId}`)
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw new Error(String(res.status))
|
||||
const json = (await res.json()) as { data: Dossier }
|
||||
if (!cancelled) setLoaded({ partyId, reloadKey: key, dossier: json.data })
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoaded({ partyId, reloadKey: key, dossier: null })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [partyId, reloadKey])
|
||||
|
||||
const p = dossier?.party
|
||||
const stats = p?.stats ?? null
|
||||
const suggested = p?.status === 'suggested'
|
||||
const kicker = p ? (suggested ? t('dossier_kicker_suggested') : roleLabel(t, p.roles)) : ''
|
||||
const subtitle = stats
|
||||
? [
|
||||
t('dossier_seen', { count: stats.occurrences }),
|
||||
rhythmLabel(t, stats.rhythm),
|
||||
stats.lastSeen ? t('dossier_last', { date: formatDate(stats.lastSeen) }) : '',
|
||||
stats.variants.length > 1 ? t('dossier_variants', { count: stats.variants.length }) : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
: ''
|
||||
const legalName = p?.legalName ?? (dossier?.facts.find((f) => f.field === 'legal_name')?.value as string | undefined) ?? null
|
||||
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') : ''
|
||||
}
|
||||
const dominant = dossier?.facts.find((f) => f.field === 'dominant_account')?.value as { account?: string; count?: number } | undefined
|
||||
|
||||
return (
|
||||
<SlideOver open={Boolean(partyId)} onOpenChange={(open) => (!open ? onClose() : undefined)}>
|
||||
<SlideOverContent>
|
||||
<SlideOverHeader kicker={kicker} title={p?.displayName ?? (loading ? '…' : '')} />
|
||||
<SlideOverBody>
|
||||
{loading && !dossier ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
<Skeleton className="h-24 w-full" />
|
||||
</div>
|
||||
) : failed || !dossier || !p ? (
|
||||
<p className="text-sm text-muted-foreground">{t('load_failed')}</p>
|
||||
) : (
|
||||
<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')}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="space-y-3">
|
||||
<SectionTitle>{t('section_money')}</SectionTitle>
|
||||
<table className="w-full text-[13px]">
|
||||
<tbody>
|
||||
{stats?.expenseSek || !stats?.revenueSek ? (
|
||||
<Row
|
||||
label={t('money_expense')}
|
||||
value={formatCurrency(stats?.expenseSek ?? 0)}
|
||||
note={period === '12m' ? t('money_period_12m') : t('money_period_all')}
|
||||
/>
|
||||
) : null}
|
||||
{stats?.revenueSek ? (
|
||||
<Row
|
||||
label={t('money_revenue')}
|
||||
value={formatCurrency(stats.revenueSek)}
|
||||
note={period === '12m' ? t('money_period_12m') : t('money_period_all')}
|
||||
/>
|
||||
) : null}
|
||||
{stats?.firstSeen ? <Row label={t('money_first')} value={formatDate(stats.firstSeen)} /> : null}
|
||||
{stats?.lastSeen ? <Row label={t('money_last')} value={formatDate(stats.lastSeen)} /> : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<SectionTitle>{t('section_bookkeeping')}</SectionTitle>
|
||||
<table className="w-full text-[13px]">
|
||||
<tbody>
|
||||
<Row
|
||||
label={t('bk_account')}
|
||||
value={<AccountNub account={stats?.dominantAccount ?? dominant?.account ?? null} />}
|
||||
note={
|
||||
stats?.dominantAccount && stats.occurrences
|
||||
? t('bk_account_share', {
|
||||
count: Math.round((stats.dominantShare ?? 0) * (stats.occurrences + 2) - 1) || dominant?.count || 0,
|
||||
total: stats.occurrences,
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<Row label={t('bk_when')} value={t('bk_when_value')} />
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<SectionTitle>{t('section_facts')}</SectionTitle>
|
||||
<table className="w-full text-[13px]">
|
||||
<tbody>
|
||||
<Row
|
||||
label={t('fact_name')}
|
||||
value={p.displayName}
|
||||
note={stats && stats.variants.length > 1 ? stats.variants.slice(0, 3).join(', ') : undefined}
|
||||
/>
|
||||
<Row label={t('fact_legal_name')} value={legalName ?? <span className="text-muted-foreground">{t('fact_missing')}</span>} note={legalName ? docsFor('legal_name') : undefined} />
|
||||
<Row
|
||||
label={t('fact_org')}
|
||||
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>} />
|
||||
{dossier.identities.map((i) => (
|
||||
<Row
|
||||
key={i.id}
|
||||
label={i.scheme === 'bankgiro' ? t('fact_bankgiro') : i.scheme === 'plusgiro' ? t('fact_plusgiro') : i.scheme}
|
||||
value={formatPaymentIdentity(i.scheme, i.value)}
|
||||
note={`${t('fact_from_documents', { count: i.seenCount })} · ${i.status === 'known' ? t('identity_known') : t('identity_unverified')}`}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<SectionTitle>{t('section_vouchers')}</SectionTitle>
|
||||
{dossier.vouchers.length === 0 ? (
|
||||
<p className="text-[13px] text-muted-foreground">{t('vouchers_none')}</p>
|
||||
) : (
|
||||
<table className="w-full text-[13px]">
|
||||
<tbody>
|
||||
{dossier.vouchers.map((v) => (
|
||||
<tr key={v.id}>
|
||||
<td className={`${VTD_CLASS} w-24 whitespace-nowrap text-muted-foreground tabular-nums`}>{formatDate(v.entryDate)}</td>
|
||||
<td className={`${VTD_CLASS} truncate`}>
|
||||
{v.voucher ? <span className="text-muted-foreground">{v.voucher} · </span> : null}
|
||||
{v.description}
|
||||
</td>
|
||||
<td className={`${VTD_CLASS} text-right tabular-nums`}>{v.amount ? formatCurrency(v.amount) : ''}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{dossier.decisions.length > 0 ? (
|
||||
<section className="space-y-3">
|
||||
<SectionTitle>{t('section_history')}</SectionTitle>
|
||||
<table className="w-full text-[13px]">
|
||||
<tbody>
|
||||
{dossier.decisions.map((d) => (
|
||||
<tr key={d.id}>
|
||||
<td className={`${VTD_CLASS} w-24 whitespace-nowrap text-muted-foreground tabular-nums`}>{formatDate(d.createdAt)}</td>
|
||||
<td className={VTD_CLASS}>
|
||||
{['confirm', 'dismiss', 'merge', 'split', 'undo'].includes(d.kind) ? t(`decision_${d.kind}`) : d.kind}
|
||||
{d.note ? <span className="text-muted-foreground"> · {d.note}</span> : null}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</SlideOverBody>
|
||||
</SlideOverContent>
|
||||
</SlideOver>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
'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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import type { RegisterCounts } from '@/lib/parties/register'
|
||||
|
||||
/**
|
||||
* The one line on Leverantörer and Kunder that leads to the queue: how many
|
||||
* suggestions from the books are waiting for this side. Renders nothing
|
||||
* when there is nothing to do, so the pages stay as they were.
|
||||
*/
|
||||
export function SuggestionsAttn({ side }: { side: 'supplier' | 'customer' }) {
|
||||
const t = useTranslations('parties')
|
||||
const router = useRouter()
|
||||
const [counts, setCounts] = useState<RegisterCounts | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch('/api/parties?view=suggested')
|
||||
.then(async (res) => {
|
||||
if (!res.ok) return
|
||||
const json = (await res.json()) as { data: { counts: RegisterCounts } }
|
||||
if (!cancelled) setCounts(json.data.counts)
|
||||
})
|
||||
.catch(() => {
|
||||
// The line is a convenience; a failed count shows nothing.
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!counts) return null
|
||||
const n = side === 'supplier' ? counts.suggestedSuppliers : counts.suggestedCustomers
|
||||
if (n > 0) {
|
||||
return (
|
||||
<AttnLine action={{ label: t('attn_review'), onClick: () => router.push('/parties') }}>
|
||||
{side === 'supplier' ? t('attn_suppliers', { count: n }) : t('attn_customers', { count: n })}
|
||||
</AttnLine>
|
||||
)
|
||||
}
|
||||
if (side === 'supplier' && counts.suggested === 0 && counts.observed > 0) {
|
||||
return (
|
||||
<AttnLine action={{ label: t('attn_fetch'), onClick: () => router.push('/parties?view=observed') }}>
|
||||
{t('attn_observed', { count: counts.observed })}
|
||||
</AttnLine>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { LedgerStats, PartyRole, RegisterRow } from '@/lib/parties/register'
|
||||
import type { SuggestionReason } from '@/lib/parties/suggest'
|
||||
import { formatOrgNumber } from '@/lib/utils'
|
||||
|
||||
/** next-intl translator shape the register components accept. */
|
||||
export type Translate = (key: string, values?: Record<string, string | number>) => string
|
||||
|
||||
export function rhythmLabel(t: Translate, rhythm: LedgerStats['rhythm']): string {
|
||||
return rhythm ? t(`rhythm_${rhythm}`) : ''
|
||||
}
|
||||
|
||||
export function roleLabel(t: Translate, roles: RegisterRow['roles']): string {
|
||||
const parts: string[] = []
|
||||
if (roles.supplierId) parts.push(t('role_supplier'))
|
||||
if (roles.customerId) parts.push(t('role_customer'))
|
||||
return parts.length ? parts.join(' · ') : t('role_none')
|
||||
}
|
||||
|
||||
/** "Leverantör", "Kund" or "Leverantör · Kund": what a suggestion becomes. */
|
||||
export function rolesLabel(t: Translate, roles: PartyRole[]): string {
|
||||
const parts: string[] = []
|
||||
if (roles.includes('supplier')) parts.push(t('role_supplier'))
|
||||
if (roles.includes('customer')) parts.push(t('role_customer'))
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/** "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 {
|
||||
if (!reason) return ''
|
||||
const parts: string[] = []
|
||||
const docs = Math.max(0, (reason.docs ?? 0) - (reason.self_docs ?? 0))
|
||||
if (reason.org_number) parts.push(t('reason_org', { org: formatOrgNumber(reason.org_number), docs }))
|
||||
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.similar_to?.length) parts.push(t('reason_similar', { name: reason.similar_to[0]!.display_name }))
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/** 53170900 reads 5317-0900; 7-digit bankgiro 531-7090; plusgiro keeps its check digit after the hyphen. */
|
||||
export function formatPaymentIdentity(scheme: string, value: string): string {
|
||||
const d = value.replace(/[^0-9]/g, '')
|
||||
if (scheme === 'bankgiro' && (d.length === 7 || d.length === 8)) return `${d.slice(0, d.length - 4)}-${d.slice(-4)}`
|
||||
if (scheme === 'plusgiro' && d.length >= 2) return `${d.slice(0, -1)}-${d.slice(-1)}`
|
||||
return value
|
||||
}
|
||||
|
||||
export function isDuplicateCandidate(row: RegisterRow): boolean {
|
||||
return row.similar.length > 0 || Boolean(row.reason?.similar_to?.length)
|
||||
}
|
||||
|
||||
export function hasHardKey(row: RegisterRow): boolean {
|
||||
return Boolean(row.reason?.org_number)
|
||||
}
|
||||
Reference in New Issue
Block a user