fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,123 @@
'use client'
import { useTranslations } from 'next-intl'
import Link from 'next/link'
import { Pin, ArrowUpRight } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { SettingsGroup, SettingsRow } from '@/components/settings/SettingsRows'
import type { AgentCompetence, AtomTier, FactKind, FactSource } from '@/lib/agent-context/agent-competence'
/**
* Read-only views of the agent's competence (domain-knowledge atoms) and top
* learned facts, for the "Vad din agent vet" overview. Each renders as a flat
* settings group (Fönster language) with its description behind the group
* "?" help. Full editable management lives in /settings/assistant; each
* links there.
*/
const TIER_ORDER: AtomTier[] = ['horizontal', 'vertical', 'modifier']
export function CompetenceCard({ competence }: { competence: AgentCompetence }) {
const t = useTranslations('agentKnowledge')
const { atoms } = competence
const activeAtoms = atoms.filter((a) => a.active).length
const tierLabel = (tier: AtomTier) =>
tier === 'horizontal' ? t('tier_horizontal') : tier === 'vertical' ? t('tier_vertical') : t('tier_modifier')
return (
<SettingsGroup label={t('comp_title')} help={t('comp_desc')}>
{atoms.length === 0 ? (
<p className="px-1 py-3 text-sm text-muted-foreground">{t('comp_empty')}</p>
) : (
<>
{/* One row per tier: micro-label left, atom chips right. Dormant
atoms are the exception the outline chip variant marks. */}
{TIER_ORDER.map((tier) => {
const items = atoms.filter((a) => a.tier === tier)
if (items.length === 0) return null
return (
<SettingsRow key={tier} label={tierLabel(tier)} align="baseline">
<div className="flex flex-wrap gap-2">
{items.map((a) => (
<Badge
key={a.id}
variant={a.active ? 'secondary' : 'outline'}
className={a.active ? '' : 'text-muted-foreground'}
title={a.description}
>
{a.title}
{!a.active && tier !== 'horizontal' && (
<span className="ml-1.5 opacity-70">· {t('badge_dormant')}</span>
)}
</Badge>
))}
</div>
</SettingsRow>
)
})}
<div className="flex items-center justify-between gap-4 px-1 pt-3 text-xs text-muted-foreground">
<span className="tabular-nums">{t('comp_count', { total: atoms.length, active: activeAtoms })}</span>
<ManageLink href="/settings/assistant?view=skills" label={t('comp_manage')} />
</div>
</>
)}
</SettingsGroup>
)
}
export function FactsCard({ competence }: { competence: AgentCompetence }) {
const t = useTranslations('agentKnowledge')
const { facts, factsActiveTotal } = competence
const kindLabel = (k: FactKind) =>
k === 'fact' ? t('kind_fact') : k === 'preference' ? t('kind_preference') : k === 'pattern' ? t('kind_pattern') : t('kind_correction')
const sourceLabel = (s: FactSource) =>
s === 'composer' ? t('source_composer') : s === 'user_taught' ? t('source_user_taught') : s === 'agent_learned' ? t('source_agent_learned') : t('source_derived')
return (
<SettingsGroup label={t('facts_title')} help={t('facts_desc')}>
{facts.length === 0 ? (
<p className="px-1 py-3 text-sm text-muted-foreground">{t('facts_empty')}</p>
) : (
<>
{/* Flat hairline rows: fact content with its kind/source flowing
inline as muted text; the pin marks the exception. */}
<ul>
{facts.map((f) => (
<li key={f.id} className="flex items-start gap-2 border-b border-border px-1 py-3">
{f.is_pinned ? (
<Pin role="img" className="mt-1 h-3.5 w-3.5 shrink-0 fill-current text-muted-foreground" aria-label={t('facts_pinned')} />
) : (
<span className="mt-1 h-3.5 w-3.5 shrink-0" aria-hidden />
)}
<div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-1">
<span className="text-sm text-foreground">{f.content}</span>
<span className="text-[11px] text-muted-foreground">
{kindLabel(f.kind)} · {sourceLabel(f.source)}
</span>
</div>
</li>
))}
</ul>
<div className="flex items-center justify-between gap-4 px-1 pt-3 text-xs text-muted-foreground">
<span className="tabular-nums">
{factsActiveTotal > facts.length ? t('facts_more', { n: factsActiveTotal - facts.length }) : ''}
</span>
<ManageLink href="/settings/assistant?view=memory" label={t('facts_manage')} />
</div>
</>
)}
</SettingsGroup>
)
}
function ManageLink({ href, label }: { href: string; label: string }) {
return (
<Button asChild variant="outline" size="sm">
<Link href={href}>
{label}
<ArrowUpRight className="ml-1 h-3 w-3" />
</Link>
</Button>
)
}
@@ -0,0 +1,86 @@
'use client'
import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Skeleton } from '@/components/ui/skeleton'
import { EmptyState } from '@/components/ui/empty-state'
import { Brain } from 'lucide-react'
import type { LedgerContext } from '@/lib/agent-context/ledger-context'
import type { DeepLedgerContext } from '@/lib/agent-context/ledger-deep'
import type { AgentCompetence } from '@/lib/agent-context/agent-competence'
import { AgentKnowledgeView } from './AgentKnowledgeView'
interface KnowledgePayload {
context: LedgerContext
deep: DeepLedgerContext
competence: AgentCompetence
companyName: string
}
/**
* Client wrapper for the "Vad din agent vet" view inside the assistant
* settings hub. Fetches the ledger context from /api/agent/knowledge on mount
* (lazy: this panel only renders when the Kunskap tab is opened, since Radix
* unmounts inactive tabs). Fetching client-side rather than via a server prop
* is deliberate: the settings sections mount as propless components in BOTH
* the full-page rail and the routed settings modal, so a server fetch wouldn't
* reach the modal.
*/
export function AgentKnowledgePanel() {
const t = useTranslations('agentKnowledge')
const [payload, setPayload] = useState<KnowledgePayload | null>(null)
const [error, setError] = useState(false)
useEffect(() => {
let cancelled = false
fetch('/api/agent/knowledge')
.then((res) => {
if (!res.ok) throw new Error(`knowledge fetch failed: ${res.status}`)
return res.json()
})
.then((json) => {
if (!cancelled) setPayload(json.data as KnowledgePayload)
})
.catch(() => {
if (!cancelled) setError(true)
})
return () => {
cancelled = true
}
}, [])
if (error) {
return (
<EmptyState
icon={Brain}
title={t('load_error_title')}
description={t('load_error_description')}
/>
)
}
if (!payload) {
// Mirrors the loaded layout: graph hero, section header, two profile cards.
return (
<div className="space-y-8">
<Skeleton className="h-96 w-full rounded-lg" />
<div className="space-y-4">
<Skeleton className="h-4 w-40" />
<div className="grid gap-4 md:grid-cols-2">
<Skeleton className="h-48 w-full rounded-lg" />
<Skeleton className="h-48 w-full rounded-lg" />
</div>
</div>
</div>
)
}
return (
<AgentKnowledgeView
context={payload.context}
deep={payload.deep}
competence={payload.competence}
companyName={payload.companyName}
/>
)
}
@@ -0,0 +1,182 @@
'use client'
import { useTranslations } from 'next-intl'
import { Brain } from 'lucide-react'
import {
SettingsGroup,
SettingsRow,
SettingsSectionHeader,
} from '@/components/settings/SettingsRows'
import { AccountNumber } from '@/components/ui/account-number'
import { EmptyState } from '@/components/ui/empty-state'
import { formatDateLong } from '@/lib/utils'
import type { LedgerContext } from '@/lib/agent-context/ledger-context'
import type { DeepLedgerContext } from '@/lib/agent-context/ledger-deep'
import type { AgentCompetence } from '@/lib/agent-context/agent-competence'
import { LedgerGraph } from './LedgerGraph'
import { CompetenceCard, FactsCard } from './AgentCompetenceSections'
// Swedish VAT (moms) treatment codes stay Swedish in both locales, like BAS
// account names and momsdeklaration labels (.claude/rules/i18n.md).
const VAT_LABELS: Record<string, string> = {
standard_25: 'Moms 25%',
standard_12: 'Moms 12%',
standard_6: 'Moms 6%',
reduced_12: 'Moms 12%',
reduced_6: 'Moms 6%',
reverse_charge: 'Omvänd moms',
reverse_charge_eu: 'Omvänd moms (EU)',
reverse_charge_services: 'Omvänd moms (tjänster)',
eu_reverse_charge_services: 'Omvänd moms (EU-tjänster)',
eu_goods: 'EU-varor',
export: 'Export',
exempt: 'Momsfri',
no_vat: 'Ingen moms',
}
function vatLabel(code: string | null): string | null {
if (!code) return null
return VAT_LABELS[code] ?? code
}
export function AgentKnowledgeView({
context,
deep,
competence,
companyName,
}: {
context: LedgerContext
deep: DeepLedgerContext
competence: AgentCompetence
companyName: string
}) {
const t = useTranslations('agentKnowledge')
const { meta, explicit_rules, vat_profile, conventions } = context
const entities = [...deep.counterparty_entities, ...deep.supplier_entities]
const isEmpty = meta.coverage.posted_entries_window === 0 && entities.length === 0 && explicit_rules.length === 0
if (isEmpty) {
// No bookings yet, but the agent still ships with competence and may
// already remember facts: show those rather than a dead end.
return (
<div className="space-y-8">
<EmptyState
icon={Brain}
title={t('empty_title')}
description={t('empty_description')}
actionLabel={t('empty_action')}
actionHref="/transactions"
/>
<div>
<CompetenceCard competence={competence} />
<FactsCard competence={competence} />
</div>
</div>
)
}
const methodLabel =
conventions.accounting_method === 'accrual'
? t('method_accrual')
: conventions.accounting_method === 'cash'
? t('method_cash')
: t('method_unknown')
const periodLabel =
vat_profile.moms_period === 'monthly'
? t('period_monthly')
: vat_profile.moms_period === 'quarterly'
? t('period_quarterly')
: vat_profile.moms_period === 'yearly'
? t('period_yearly')
: (vat_profile.moms_period ?? t('unknown'))
return (
<div className="space-y-8">
{/* The cinematic hero: a self-contained dark panel with its own header */}
<LedgerGraph deep={deep} companyName={companyName} />
{/* "Regler & profil": user-authored rules + observed VAT + conventions,
in the flat settings language (groups under eyebrow labels, static
descriptions behind the group "?"). Minne and Kompetens have their
own top-level views, so no second tab row here. */}
<section>
<SettingsSectionHeader title={t('tab_config')} />
{explicit_rules.length > 0 && (
<SettingsGroup label={t('rules_title')} help={t('rules_description')}>
{explicit_rules.map((r, i) => {
const vat = vatLabel(r.vat_treatment)
return (
<div
key={r.rule_name + r.match + i}
className="flex flex-wrap items-baseline gap-x-3 gap-y-1 border-b border-border px-1 py-3"
>
<span className="text-sm">{r.rule_name}</span>
<span className="min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground">
{r.match}
</span>
<span className="flex shrink-0 flex-wrap items-baseline gap-x-2 text-xs text-muted-foreground">
{r.account_number ? (
<AccountNumber number={r.account_number} showName size="sm" />
) : (
<span>-</span>
)}
{vat && <span>· {vat}</span>}
<span>· {t('src_rule')}</span>
</span>
</div>
)
})}
</SettingsGroup>
)}
<SettingsGroup label={t('vat_title')} help={t('vat_description')}>
<SettingsRow label={t('vat_registered_label')}>
<span>{vat_profile.registered ? t('yes') : t('no')}</span>
</SettingsRow>
<SettingsRow label={t('vat_period_label')}>
<span>{periodLabel}</span>
</SettingsRow>
<SettingsRow label={t('vat_treatments_label')}>
{vat_profile.treatments_used_12m.length === 0 ? (
<span className="text-muted-foreground">{t('vat_no_treatments')}</span>
) : (
<span>{vat_profile.treatments_used_12m.map((code) => vatLabel(code)).join(' · ')}</span>
)}
</SettingsRow>
</SettingsGroup>
<SettingsGroup label={t('conv_title')} help={t('conv_description')}>
<SettingsRow label={t('conv_method_label')}>
<span>{methodLabel}</span>
</SettingsRow>
<SettingsRow label={t('conv_series_label')}>
{conventions.voucher_series_in_use.length === 0 ? (
<span className="text-muted-foreground">-</span>
) : (
<span className="font-mono text-xs">{conventions.voucher_series_in_use.join(', ')}</span>
)}
</SettingsRow>
<SettingsRow label={t('conv_salary_label')}>
<span>{conventions.salary_run_active ? t('yes') : t('no')}</span>
</SettingsRow>
{conventions.typical_booking_lag_days !== null && (
<SettingsRow label={t('conv_lag_label')}>
<span className="tabular-nums">
{t('meta_lag_value', { days: conventions.typical_booking_lag_days })}
</span>
</SettingsRow>
)}
</SettingsGroup>
</section>
<p className="text-right text-xs text-muted-foreground">
{t('footer_basis', { entries: meta.coverage.posted_entries_window, date: formatDateLong(meta.computed_at) })}
</p>
</div>
)
}
+842
View File
@@ -0,0 +1,842 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { motion, AnimatePresence, useReducedMotion, animate } from 'framer-motion'
import { RotateCw } from 'lucide-react'
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
import { useBasReference } from '@/lib/bookkeeping/use-bas-reference'
import { useTranslations } from 'next-intl'
import { formatAmount, formatCurrency } from '@/lib/utils'
import type { DeepEntity, DeepLedgerContext } from '@/lib/agent-context/ledger-deep'
import { entityMagnitude, selectAccountRing, type RingBasis } from './ledger-graph-magnitude'
/**
* "Reconciliation Aurora" - the cinematic hero of the "Vad din agent vet" page.
*
* A self-contained dark SVG panel. The company is a luminous hub; the BAS
* accounts it books to form an inner ring of wedges (each wedge sized by the
* money that flows through it); the counterparties/suppliers live in the outer
* band, each constrained to its dominant account's angular slice so threads can
* never cross between accounts (the anti-hairball guarantee).
*
* Four orthogonal channels, so no two compete:
* - node AREA = magnitude (radius = k·√x), see ledger-graph-magnitude.ts
* - node COLOUR = booking cadence (weekly / monthly / irregular) - the one
* semantic axis; everything else stays achromatic
* - node SHAPE = kind (supplier = filled, counterparty = open ring)
* - node FOCUS = the agent's confidence in the account mapping, rendered as
* optical depth of field (sure = crisp/forward, unsure = soft)
*
* On mount it performs the signature act: for the most-merged payees, the raw
* bank descriptors ("CLAUDE.AI", "Anthropic PBC", "claude.ai*sub") fly in as
* ghost chips and magnetically collapse into one named node with a "×N" badge -
* the agent resolving chaos into knowledge, live, in front of the customer.
*
* Deterministic (seeded jitter, fixed input order) so the demo looks identical
* on every load. Motion is CSS-driven (single-clock idle, GPU dash pulses) with
* framer only orchestrating the entrance, the merge and the hover card. Fully
* keyboard-navigable; a visually-hidden table carries the payload for readers;
* honours prefers-reduced-motion (jumps straight to the settled state).
*/
const W = 1000
const H = 1000
const CX = W / 2
const CY = H / 2
const R_HUB = 34
const R_ACCOUNT = 178
const R_PAYEE_MIN = 258
const R_PAYEE_MAX = 432
const WEDGE_GAP = 0.07 // radians of padding between account wedges
// This panel is its own dark world regardless of the app theme, so the depth of
// field, the glow and the cadence hues all read. Achromatic chrome; colour only
// ever means cadence.
const INK = '#0a0a0c'
const PAPER = '#ecebe6'
const HAIR = 'rgba(236,235,230,0.13)'
const HAIR_STRONG = 'rgba(236,235,230,0.30)'
const MUTED = 'rgba(236,235,230,0.52)'
const CAD: Record<Cadence, string> = {
weekly: '#e0895f', // terracotta - fast, recurring
monthly: '#d7a648', // ochre - monthly
irregular: '#83a98d', // sage - one-off / irregular
}
// Depth-of-field buckets: stdDeviation in viewBox units (~0.64× on screen).
const DOF = [0, 1.7, 3.4, 5.2]
type Cadence = 'weekly' | 'monthly' | 'irregular'
interface Payee {
id: string
entity: DeepEntity
accountNumber: string
x: number
y: number
r: number
cadence: Cadence
bucket: number // depth-of-field bucket index into DOF
thread: string // svg path from hub to node, bowed through the account anchor
labelRight: boolean
revealDelay: number
merge: boolean // show the ghost-descriptor collapse on mount
chips: string[]
}
interface Account {
number: string
name: string | null
x: number
y: number
midAngle: number
arc: string
revealDelay: number
}
interface Model {
accounts: Account[]
payees: Payee[]
truncated: boolean
/** What the wedge widths and node areas actually measure. See the legend. */
basis: RingBasis
totals: { tx: number; payees: number; accounts: number }
}
function polar(cx: number, cy: number, r: number, a: number) {
return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) }
}
function arcPath(cx: number, cy: number, r: number, a0: number, a1: number) {
const s = polar(cx, cy, r, a0)
const e = polar(cx, cy, r, a1)
const large = a1 - a0 > Math.PI ? 1 : 0
return `M ${s.x.toFixed(2)} ${s.y.toFixed(2)} A ${r} ${r} 0 ${large} 1 ${e.x.toFixed(2)} ${e.y.toFixed(2)}`
}
function lerp(a: number, b: number, t: number) {
return a + (b - a) * t
}
// Deterministic [0,1) hash of a string (xmur3 → mulberry32), so seeded jitter is
// byte-identical on every render: the live demo never reshuffles.
function rand01(seed: string): number {
let h = 1779033703 ^ seed.length
for (let i = 0; i < seed.length; i++) {
h = Math.imul(h ^ seed.charCodeAt(i), 3432918353)
h = (h << 13) | (h >>> 19)
}
h = Math.imul(h ^ (h >>> 16), 2246822507)
h = Math.imul(h ^ (h >>> 13), 3266489909)
h ^= h >>> 16
return (h >>> 0) / 4294967296
}
function cadenceOf(e: DeepEntity): Cadence {
const cd = e.cadence_days
if (cd === null || e.occurrences < 3) return 'irregular'
if (cd >= 4 && cd <= 10) return 'weekly'
if (cd > 10 && cd <= 45) return 'monthly'
return 'irregular'
}
function bucketOf(share: number | null): number {
if (share === null) return 3
if (share >= 0.85) return 0
if (share >= 0.7) return 1
if (share >= 0.5) return 2
return 3
}
// Center-out slot order: biggest spender sits at the wedge's angular centre.
function centerOut(n: number): number[] {
const mid = (n - 1) / 2
return Array.from({ length: n }, (_, i) => i).sort(
(a, b) => Math.abs(a - mid) - Math.abs(b - mid),
)
}
function buildModel(deep: DeepLedgerContext): Model {
const all: DeepEntity[] = [
...(deep?.counterparty_entities ?? []),
...(deep?.supplier_entities ?? []),
].filter((e) => e.dominant_account_number)
const totalTx = all.reduce((s, e) => s + e.occurrences, 0)
// Grouping, weighting, ranking and truncation of the account ring live in
// ledger-graph-magnitude.ts so they can be unit tested. The one rule that
// matters here: every wedge weight below is expressed in the SAME unit
// (`ring.basis`), so the shared denominator never adds kronor to booking
// counts and no account is squeezed to an invisible sliver, or truncated
// away entirely, just for being measured differently.
const ring = selectAccountRing(all)
const { basis, groups, truncated } = ring
// The most name-merged payees earn the on-mount "descriptors collapse" moment.
const mergeIds = new Set(
all
.filter((e) => e.variant_count >= 3)
.sort((a, b) => b.variant_count - a.variant_count)
.slice(0, 5)
.map((e) => `${e.dominant_account_number}:${e.key}`),
)
const accounts: Account[] = []
const payees: Payee[] = []
const spans = 2 * Math.PI - WEDGE_GAP * groups.length
let angle = -Math.PI / 2 + WEDGE_GAP / 2
groups.forEach((g, gi) => {
const width = spans * (g.weight / ring.totalWeight)
const mid = angle + width / 2
const anchor = polar(CX, CY, R_ACCOUNT, mid)
accounts.push({
number: g.number,
name: getAccountDescription(g.number)?.name ?? null,
x: anchor.x,
y: anchor.y,
midAngle: mid,
arc: arcPath(CX, CY, R_ACCOUNT, angle + width * 0.04, angle + width * 0.96),
revealDelay: 0.2 + gi * 0.06,
})
const n = g.items.length
const inner = width * 0.16
const order = centerOut(n) // order[rank] = slot for that rank (rank 0 = biggest → centre)
g.items.forEach((e, rank) => {
const slot = order[rank]
const t = n === 1 ? 0.5 : slot / (n - 1)
const pa = angle + inner + t * (width - 2 * inner)
// Same unit as the wedge it sits in, so a node is never sized against a
// maximum measured in something else.
const sizeFrac = Math.sqrt(entityMagnitude(e, basis) / ring.maxMagnitude)
const radius = lerp(R_PAYEE_MIN, R_PAYEE_MAX, rand01(e.key)) + sizeFrac * 14
const pos = polar(CX, CY, Math.min(radius, R_PAYEE_MAX + 10), pa)
const id = `${g.number}:${e.key}`
payees.push({
id,
entity: e,
accountNumber: g.number,
x: pos.x,
y: pos.y,
r: 7 + 19 * sizeFrac,
cadence: cadenceOf(e),
bucket: bucketOf(e.dominant_account_share),
thread: `M ${CX} ${CY} Q ${anchor.x.toFixed(2)} ${anchor.y.toFixed(2)} ${pos.x.toFixed(2)} ${pos.y.toFixed(2)}`,
labelRight: Math.cos(pa) >= 0,
revealDelay: 0.55 + gi * 0.05 + rank * 0.045,
merge: mergeIds.has(id),
chips: e.variants.slice(0, 6),
})
angle += 0
})
angle += width + WEDGE_GAP
})
return {
accounts,
payees,
truncated,
basis,
totals: { tx: totalTx, payees: payees.length, accounts: accounts.length },
}
}
// Weekly beats faster than monthly; irregular drifts slow. Seconds per pulse.
const PULSE_DUR: Record<Cadence, number> = { weekly: 1.15, monthly: 2.7, irregular: 4.3 }
export function LedgerGraph({ deep, companyName }: { deep: DeepLedgerContext; companyName: string }) {
const t = useTranslations('agentKnowledge')
// Loads the BAS chart chunk after mount and re-renders once names and
// descriptions for non-hardcoded accounts are available.
useBasReference()
const reduce = useReducedMotion() ?? false
const model = useMemo(() => buildModel(deep), [deep])
const [hover, setHover] = useState<string | null>(null)
const [runKey, setRunKey] = useState(0)
// Track which run has finished its intro rather than a bare boolean, so a
// replay (runKey++) resets to "unresolved" by derivation, without a
// setState-in-effect. Chips fly in, then collapse into their node.
const [resolvedRun, setResolvedRun] = useState(-1)
useEffect(() => {
const id = setTimeout(() => setResolvedRun(runKey), reduce ? 0 : 1300)
return () => clearTimeout(id)
}, [runKey, reduce])
const resolved = reduce || resolvedRun === runKey
const payeeById = useMemo(() => new Map(model.payees.map((p) => [p.id, p])), [model])
function payeeCaption(p: Payee): string {
const e = p.entity
const nm = getAccountDescription(e.dominant_account_number ?? '')?.name
return [
e.name,
t('cap_bookings', { n: e.occurrences }),
e.variant_count > 1 ? t('cap_variants', { n: e.variant_count }) : null,
t(`cadence_${p.cadence}`),
formatCurrency(e.total_amount),
`${e.dominant_account_number}${nm ? ` ${nm}` : ''}${
e.dominant_account_share !== null ? ` · ${Math.round(e.dominant_account_share * 100)}%` : ''
}`,
]
.filter(Boolean)
.join(' · ')
}
if (model.payees.length === 0) {
return (
<div
className="rounded-lg border border-border p-16 text-center text-sm"
style={{ background: INK, borderColor: HAIR, color: MUTED }}
>
{t('none_cp')}
</div>
)
}
// Which ids are "lit" given the current hover (a payee lights its account and
// the reverse); everything else recedes into the depth of field.
const active = new Set<string>()
if (hover) {
active.add(hover)
if (hover.startsWith('acc:')) {
const num = hover.slice(4)
model.payees.forEach((p) => p.accountNumber === num && active.add(p.id))
} else {
const p = payeeById.get(hover)
if (p) active.add(`acc:${p.accountNumber}`)
}
}
const lit = (id: string) => !hover || active.has(id)
const hoveredPayee = hover && !hover.startsWith('acc:') ? payeeById.get(hover) ?? null : null
return (
<div
className="relative overflow-hidden rounded-lg border border-border"
style={{
borderColor: HAIR_STRONG,
background: `radial-gradient(120% 120% at 50% 42%, #17171b 0%, ${INK} 62%)`,
}}
>
<style>{keyframes}</style>
{/* header */}
<div className="flex items-start justify-between gap-4 px-5 pt-5 md:px-7 md:pt-6">
<div>
<h2
className="font-display text-lg tracking-tight md:text-xl"
style={{ color: PAPER }}
>
{t('graph_title')}
</h2>
<p className="mt-1 max-w-md text-sm leading-relaxed" style={{ color: MUTED }}>
{t('graph_description')}
</p>
</div>
{!reduce && (
<button
type="button"
onClick={() => setRunKey((k) => k + 1)}
className="inline-flex shrink-0 items-center gap-2 rounded-full border px-3 py-1.5 text-xs transition-colors"
style={{ borderColor: HAIR_STRONG, color: MUTED }}
>
<RotateCw className="h-3.5 w-3.5" />
{t('graph_replay')}
</button>
)}
</div>
{/* stage */}
<div className="relative mx-auto aspect-square w-full max-w-[680px]">
<svg
viewBox={`0 0 ${W} ${H}`}
className="block h-full w-full"
role="img"
aria-label={t('graph_aria', { payees: model.payees.length, accounts: model.accounts.length })}
>
<defs>
{DOF.map((sd, i) => (
<filter key={i} id={`dof-${i}`} x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation={sd} />
</filter>
))}
<radialGradient id="aurora-hub" cx="50%" cy="50%" r="50%">
<stop offset="0%" stopColor={PAPER} stopOpacity="0.22" />
<stop offset="100%" stopColor={PAPER} stopOpacity="0" />
</radialGradient>
</defs>
<g key={runKey}>
{/* account wedge arcs (the spine) */}
{model.accounts.map((a) => (
<g key={`acc:${a.number}`} opacity={lit(`acc:${a.number}`) ? 1 : 0.14}>
<motion.path
d={a.arc}
fill="none"
stroke={HAIR_STRONG}
strokeWidth={1.4}
strokeLinecap="round"
initial={reduce ? false : { pathLength: 0, opacity: 0 }}
animate={{ pathLength: 1, opacity: 1 }}
transition={{ duration: 0.7, delay: a.revealDelay, ease: 'easeInOut' }}
/>
<AccountHit account={a} caption={accountCaption(a)} onHover={setHover} lit={lit(`acc:${a.number}`)} />
</g>
))}
{/* threads: base vein + travelling cadence pulse */}
{model.payees.map((p) => (
<g key={`thread:${p.id}`} opacity={lit(p.id) ? 1 : 0.08}>
<motion.path
d={p.thread}
fill="none"
stroke={PAPER}
strokeOpacity={0.16}
strokeWidth={0.9 + 1.1 * (p.entity.dominant_account_share ?? 0.6)}
initial={reduce ? false : { pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.6, delay: p.revealDelay, ease: 'easeOut' }}
/>
<path
d={p.thread}
fill="none"
stroke={CAD[p.cadence]}
strokeWidth={2.4}
strokeLinecap="round"
pathLength={1}
className={reduce ? undefined : 'aurora-pulse'}
style={{
strokeDasharray: '0.035 1',
opacity: resolved && lit(p.id) ? 0.9 : 0,
transition: 'opacity .6s ease',
animationDuration: `${PULSE_DUR[p.cadence]}s`,
animationDelay: `${rand01(p.id + 'd') * -PULSE_DUR[p.cadence]}s`,
}}
/>
</g>
))}
{/* payee nodes, blurry buckets first so the confident ones sit on top */}
{[...model.payees]
.sort((a, b) => b.bucket - a.bucket)
.map((p) => (
<PayeeGlyph
key={p.id}
p={p}
reduce={reduce}
resolved={resolved}
lit={lit(p.id)}
focused={hover === p.id}
caption={payeeCaption(p)}
onHover={setHover}
/>
))}
{/* company hub */}
<g>
<circle cx={CX} cy={CY} r={R_HUB * 2.6} fill="url(#aurora-hub)" />
<circle
cx={CX}
cy={CY}
r={R_HUB}
fill={PAPER}
className={reduce ? undefined : 'aurora-breathe'}
style={{ transformOrigin: `${CX}px ${CY}px` }}
/>
<text
x={CX}
y={CY}
fill={INK}
fontSize={20}
fontWeight={600}
textAnchor="middle"
dominantBaseline="central"
>
{initialsOf(companyName)}
</text>
</g>
</g>
</svg>
{/* tally: the "understood" count-up */}
<div
className="pointer-events-none absolute bottom-3 left-4 text-xs tabular-nums md:bottom-4 md:left-6"
style={{ color: MUTED }}
>
<span style={{ color: PAPER }}>
<CountUp target={model.totals.tx} run={runKey} reduce={reduce} />
</span>{' '}
{t('graph_tally', {
payees: model.totals.payees,
accounts: model.totals.accounts,
})}
</div>
{/* hover detail card, anchored to the node */}
<AnimatePresence>
{hoveredPayee && (
<DetailCard key={hoveredPayee.id} p={hoveredPayee} t={t} />
)}
</AnimatePresence>
</div>
{/* legend */}
<div
className="flex flex-wrap items-center gap-x-5 gap-y-2 border-t px-5 py-3 text-xs md:px-7"
style={{ borderColor: HAIR, color: MUTED }}
>
<span className="inline-flex items-center gap-2">
<Dot fill={CAD.weekly} /> {t('cadence_weekly')}
</span>
<span className="inline-flex items-center gap-2">
<Dot fill={CAD.monthly} /> {t('cadence_monthly')}
</span>
<span className="inline-flex items-center gap-2">
<Dot fill={CAD.irregular} /> {t('cadence_irregular')}
</span>
{/* Says what the sizes actually measure. The ring drops to booking
volume whenever any account lacks a usable amount, and claiming
"Storlek = belopp" there would describe a unit nothing is drawn in. */}
<span className="opacity-70">
{model.basis === 'amount' ? t('legend_size') : t('legend_size_volume')}
</span>
<span className="opacity-70">{t('legend_focus')}</span>
{model.truncated && <span className="italic opacity-70">{t('graph_truncated')}</span>}
</div>
{/* screen-reader alternative: the full payload as a plain list */}
<ul className="sr-only">
{model.payees.map((p) => (
<li key={`sr:${p.id}`}>{payeeCaption(p)}</li>
))}
</ul>
</div>
)
}
function accountCaption(a: Account): string {
return `${a.number}${a.name ? ` · ${a.name}` : ''}`
}
// Enlarged invisible hit target + keyboard focus for an account arc.
function AccountHit({
account,
caption,
onHover,
lit,
}: {
account: Account
caption: string
onHover: (id: string | null) => void
lit: boolean
}) {
const id = `acc:${account.number}`
const inside = polar(CX, CY, R_ACCOUNT - 20, account.midAngle)
return (
<g
tabIndex={0}
role="button"
aria-label={caption}
onMouseEnter={() => onHover(id)}
onMouseLeave={() => onHover(null)}
onFocus={() => onHover(id)}
onBlur={() => onHover(null)}
className="cursor-pointer outline-none [&:focus-visible>circle]:opacity-100"
>
<title>{caption}</title>
<circle cx={account.x} cy={account.y} r={22} fill="transparent" />
<circle cx={account.x} cy={account.y} r={26} fill="none" stroke={PAPER} strokeWidth={1.25} opacity={0} />
<text
x={inside.x}
y={inside.y}
fill={lit ? PAPER : MUTED}
fontSize={13}
fontWeight={500}
textAnchor="middle"
dominantBaseline="central"
style={{ fontFamily: 'var(--font-geist-mono, ui-monospace, monospace)' }}
>
{account.number}
</text>
</g>
)
}
function PayeeGlyph({
p,
reduce,
resolved,
lit,
focused,
caption,
onHover,
}: {
p: Payee
reduce: boolean
resolved: boolean
lit: boolean
focused: boolean
caption: string
onHover: (id: string | null) => void
}) {
const colour = CAD[p.cadence]
const showChips = !reduce && p.merge && !resolved
// The depth-of-field blur only attaches once the entrance spring settles, so
// feGaussianBlur never re-rasterizes per frame while the node is moving (and
// the blur "racking in" as the node comes to rest is the intended focus pull).
const [settled, setSettled] = useState(reduce)
// Only the biggest spenders keep a resting label; the rest reveal on focus.
const bigLabel = p.r >= 14
const label = p.entity.name.length > 16 ? p.entity.name.slice(0, 15) + '…' : p.entity.name
const lx = p.labelRight ? p.r + 8 : -(p.r + 8)
return (
// Positioning lives on a plain <g> (SVG transform attribute) so it can never
// be clobbered by framer's CSS transform on the scaling child below. Hover
// "racks focus" onto a node by dropping it to the crisp filter bucket.
<g
transform={`translate(${p.x} ${p.y})`}
filter={`url(#dof-${focused || !settled ? 0 : p.bucket})`}
tabIndex={0}
role="button"
aria-label={caption}
onMouseEnter={() => onHover(p.id)}
onMouseLeave={() => onHover(null)}
onFocus={() => onHover(p.id)}
onBlur={() => onHover(null)}
className="cursor-pointer outline-none"
>
<title>{caption}</title>
{/* always-full-size transparent hit target */}
<circle cx={0} cy={0} r={Math.max(p.r + 8, 16)} fill="transparent" />
{/* opacity layer: entrance fade + hover dimming. Animates opacity only, so
framer never sets a CSS transform that would fight the attribute. */}
<motion.g
initial={reduce ? false : { opacity: 0 }}
animate={{ opacity: lit ? 1 : 0.12 }}
transition={{ duration: reduce ? 0.2 : 0.4, delay: reduce ? 0 : p.merge ? 0.1 : p.revealDelay }}
>
{/* the money shot: raw bank descriptors that collapse inward. Kept OUT
of the scaling group so they show at full size during the scatter. */}
<AnimatePresence>
{showChips &&
p.chips.map((chip, i) => {
const ang = rand01(p.id + chip) * Math.PI * 2
const rad = 34 + rand01(chip + String(i)) * 52
const ox = Math.cos(ang) * rad
const oy = Math.sin(ang) * rad
return (
<motion.text
key={chip + i}
fontSize={12}
fill={MUTED}
textAnchor="middle"
dominantBaseline="central"
initial={{ opacity: 0, x: ox * 1.55, y: oy * 1.55 }}
animate={{ opacity: 0.7, x: ox, y: oy }}
exit={{ opacity: 0, x: 0, y: 0, scale: 0.4 }}
transition={{ duration: 0.5, delay: 0.1 + i * 0.05, ease: 'easeOut' }}
>
{chip.length > 18 ? chip.slice(0, 17) + '…' : chip}
</motion.text>
)
})}
</AnimatePresence>
{/* scale layer: the node grows in around its centre (fill-box) */}
<motion.g
initial={reduce ? false : { scale: 0 }}
animate={{ scale: 1 }}
onAnimationComplete={() => setSettled(true)}
transition={
reduce
? { duration: 0 }
: { type: 'spring', stiffness: 150, damping: 17, delay: p.merge ? 1.32 : p.revealDelay }
}
style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
>
{/* variant echo ring: faint concentric hint that this node is a merge */}
{p.entity.variant_count > 2 && (
<circle cx={0} cy={0} r={p.r + 5} fill="none" stroke={colour} strokeWidth={0.75} strokeOpacity={0.35} />
)}
{focused && <circle cx={0} cy={0} r={p.r + 6} fill="none" stroke={PAPER} strokeWidth={1.5} />}
{/* the glyph: supplier = filled, counterparty = open */}
<circle
cx={0}
cy={0}
r={p.r}
fill={p.entity.kind === 'supplier' ? colour : INK}
fillOpacity={p.entity.kind === 'supplier' ? 0.85 : 1}
stroke={colour}
strokeWidth={2}
/>
{/* "×N" merge badge */}
{p.entity.variant_count > 1 && (resolved || reduce) && (
<g transform={`translate(${p.r * 0.72} ${-p.r * 0.72})`}>
<circle r={8.5} fill={INK} stroke={colour} strokeWidth={1} />
<text fill={PAPER} fontSize={9} fontWeight={600} textAnchor="middle" dominantBaseline="central">
{p.merge ? (
<CountUp target={p.entity.variant_count} run={resolved ? 1 : 0} reduce={reduce} prefix="×" duration={0.5} />
) : (
`×${p.entity.variant_count}`
)}
</text>
</g>
)}
</motion.g>
{bigLabel && (
<text
x={lx}
y={0}
fill={lit ? PAPER : MUTED}
fontSize={12}
dominantBaseline="central"
textAnchor={p.labelRight ? 'start' : 'end'}
>
{label}
</text>
)}
</motion.g>
</g>
)
}
function DetailCard({ p, t }: { p: Payee; t: ReturnType<typeof useTranslations> }) {
const e = p.entity
const nm = getAccountDescription(e.dominant_account_number ?? '')?.name
const share = e.dominant_account_share !== null ? Math.round(e.dominant_account_share * 100) : null
// Anchor to the node: viewBox coords → % of the square stage. Flip sides so it
// never spills off the edge.
const left = (p.x / W) * 100
const top = (p.y / H) * 100
const right = p.x < CX
return (
<motion.div
className="pointer-events-none absolute z-10 w-60 rounded-lg border p-3 backdrop-blur-sm"
style={{
left: `${left}%`,
top: `${top}%`,
transform: `translate(${right ? '14px' : 'calc(-100% - 14px)'}, -50%)`,
background: 'rgba(14,14,17,0.92)',
borderColor: HAIR_STRONG,
color: PAPER,
}}
initial={{ opacity: 0, scale: 0.94 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.96 }}
transition={{ type: 'spring', stiffness: 320, damping: 26 }}
>
<div className="flex items-center gap-2">
<span className="inline-block h-2.5 w-2.5 shrink-0 rounded-full" style={{ background: CAD[p.cadence] }} />
<span className="truncate font-medium">{e.name}</span>
</div>
<div className="mt-2 space-y-1.5 text-xs" style={{ color: MUTED }}>
<div className="flex justify-between gap-3">
<span>{t('cap_bookings', { n: e.occurrences })}</span>
<span style={{ color: PAPER }}>{t(`cadence_${p.cadence}`)}</span>
</div>
{e.variant_count > 1 && (
<div className="flex justify-between gap-3">
<span>{t('card_variants')}</span>
<span style={{ color: PAPER }}>×{e.variant_count}</span>
</div>
)}
{/* Its own label: `legend_size` now describes whichever unit the ring
settled on, which is not always the amount. Rendered as a plain
number with NO currency suffix: total_amount is the RAW FOREIGN
amount when no SEK equivalent exists (ledger-graph-magnitude.ts),
so labelling it "kr" would show a 500 EUR supplier as "500 kr".
Proper per-currency display is deferred to the RPC fix documented
in that module. */}
<div className="flex justify-between gap-3">
<span>{t('card_amount')}</span>
<span className="tabular-nums" style={{ color: PAPER }}>
{formatAmount(e.total_amount)}
</span>
</div>
<div className="mt-2 border-t pt-2" style={{ borderColor: HAIR }}>
<div className="flex items-center justify-between gap-3">
<span className="font-mono" style={{ color: PAPER }}>
{e.dominant_account_number}
{nm ? ` ${nm}` : ''}
</span>
{share !== null && <span className="tabular-nums">{t('card_confidence', { share })}</span>}
</div>
{share !== null && (
<div className="mt-1.5 h-1 overflow-hidden rounded-full" style={{ background: HAIR }}>
<div className="h-full rounded-full" style={{ width: `${share}%`, background: CAD[p.cadence] }} />
</div>
)}
{e.dominant_account_count != null && e.dominant_account_total != null && (
<div className="mt-1 tabular-nums opacity-80">
{t('card_evidence', { k: e.dominant_account_count, n: e.dominant_account_total })}
</div>
)}
</div>
{e.variants.length > 1 && (
<div className="pt-1 leading-relaxed opacity-80">
{e.variants.slice(0, 4).join(' · ')}
{e.variant_count > 4 ? ' …' : ''}
</div>
)}
</div>
</motion.div>
)
}
function CountUp({
target,
run,
reduce,
prefix = '',
duration = 1,
}: {
target: number
run: number
reduce: boolean
prefix?: string
duration?: number
}) {
const [v, setV] = useState(0)
// Re-run whenever `run` bumps (mount / replay / resolve). No ref-guard: it
// would early-return on React StrictMode's second effect setup in dev and
// freeze the number at 0 (the cleanup already stops any prior animation).
useEffect(() => {
if (reduce) return
const controls = animate(0, target, {
duration,
ease: 'easeOut',
onUpdate: (x) => setV(Math.round(x)),
})
return () => controls.stop()
}, [target, run, reduce, duration])
const shown = reduce ? target : v
return <>{prefix}{shown.toLocaleString('sv-SE')}</>
}
function Dot({ fill }: { fill: string }) {
return <span className="inline-block h-2.5 w-2.5 rounded-full" style={{ background: fill }} />
}
function initialsOf(name: string): string {
return (
name
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((w) => w[0]?.toUpperCase() ?? '')
.join('') || '•'
)
}
// One clock for all continuous life: GPU-friendly CSS keyframes, frozen for
// prefers-reduced-motion users.
const keyframes = `
@keyframes aurora-pulse { to { stroke-dashoffset: -1; } }
@keyframes aurora-breathe { 0%,100% { transform: scale(1); } 50% { transform: scale(1.03); } }
.aurora-pulse { animation-name: aurora-pulse; animation-timing-function: linear; animation-iteration-count: infinite; }
.aurora-breathe { animation: aurora-breathe 5.5s ease-in-out infinite; }
@media (prefers-reduced-motion: reduce) {
.aurora-pulse, .aurora-breathe { animation: none !important; }
}
`
@@ -0,0 +1,163 @@
import { describe, it, expect } from 'vitest'
import {
entityMagnitude,
selectAccountRing,
MAX_ACCOUNTS,
} from '@/components/agent-knowledge/ledger-graph-magnitude'
import type { DeepEntity } from '@/lib/agent-context/ledger-deep'
function entity(overrides: Partial<DeepEntity> & { key: string }): DeepEntity {
return {
name: overrides.key,
variants: [overrides.key],
variant_count: 1,
occurrences: 1,
total_amount: 0,
first_seen: '2026-01-01',
last_seen: '2026-06-01',
cadence_days: null,
dominant_account_number: '5420',
dominant_account_share: 0.8,
dominant_account_count: 4,
dominant_account_total: 5,
kind: 'counterparty',
...overrides,
}
}
/** Share of the ring an account gets, ignoring the fixed inter-wedge padding. */
function share(weight: number, totalWeight: number): number {
return weight / totalWeight
}
describe('selectAccountRing', () => {
it('weighs a SEK-only company by amount, exactly as before', () => {
const ring = selectAccountRing([
entity({ key: 'a', dominant_account_number: '5420', total_amount: 24000, occurrences: 12 }),
entity({ key: 'b', dominant_account_number: '5420', total_amount: 6000, occurrences: 3 }),
entity({ key: 'c', dominant_account_number: '6540', total_amount: 10000, occurrences: 2 }),
])
expect(ring.basis).toBe('amount')
expect(ring.groups.map((g) => g.number)).toEqual(['5420', '6540'])
expect(ring.groups.map((g) => g.weight)).toEqual([30000, 10000])
expect(ring.totalWeight).toBe(40000)
expect(ring.maxMagnitude).toBe(24000)
expect(ring.truncated).toBe(false)
// Biggest spender first inside the wedge: it lands at the angular centre.
expect(ring.groups[0].items.map((e) => e.key)).toEqual(['a', 'b'])
})
it('never puts kronor and booking counts in the same denominator', () => {
// 6570 is booked 4 times but carries no usable amount: on the counterparty
// side that is a spend of 0, and it used to fall back to its booking count
// while 5420 stayed in kronor.
const entities = [
entity({ key: 'big', dominant_account_number: '5420', total_amount: 250000, occurrences: 6 }),
entity({ key: 'nil', dominant_account_number: '6570', total_amount: 0, occurrences: 4 }),
]
const ring = selectAccountRing(entities)
expect(ring.basis).toBe('volume')
expect(ring.groups.map((g) => [g.number, g.weight])).toEqual([
['5420', 6],
['6570', 4],
])
expect(ring.totalWeight).toBe(10)
// No weight is a kronor figure, so nothing can be summed across units.
expect(ring.groups.every((g) => g.weight < 1000)).toBe(true)
// The pre-fix mix: 250 000 kr against 4 bookings in one denominator gave
// 6570 a wedge of 0.0016% of the circle, an invisible sliver. Now it is a
// legible tenth of the ring.
const mixedShare = share(4, 250000 + 4)
expect(mixedShare).toBeLessThan(0.0001)
expect(share(ring.groups[1].weight, ring.totalWeight)).toBeCloseTo(0.4, 10)
})
it('keeps an account with no usable amount inside the truncation cap', () => {
// Ten accounts, cap is nine. The amount-less one is the most-booked account
// the company has, so dropping it is the worst possible choice.
const entities: DeepEntity[] = [
entity({ key: 'unpriced', dominant_account_number: '4000', total_amount: 0, occurrences: 40 }),
]
for (let i = 0; i < 9; i++) {
entities.push(
entity({
key: `priced-${i}`,
dominant_account_number: `55${10 + i}`,
total_amount: 100000 + i,
occurrences: 2,
}),
)
}
const ring = selectAccountRing(entities)
expect(ring.groups).toHaveLength(MAX_ACCOUNTS)
expect(ring.truncated).toBe(true)
expect(ring.groups.map((g) => g.number)).toContain('4000')
// It is the largest wedge, not a survivor by luck.
const unpriced = ring.groups.find((g) => g.number === '4000')
expect(unpriced?.weight).toBe(40)
expect(Math.max(...ring.groups.map((g) => g.weight))).toBe(40)
})
it('sizes nodes against a maximum measured in the same unit', () => {
const ring = selectAccountRing([
entity({ key: 'a', dominant_account_number: '5420', total_amount: 0, occurrences: 9 }),
entity({ key: 'b', dominant_account_number: '6540', total_amount: 500, occurrences: 3 }),
])
expect(ring.basis).toBe('volume')
expect(ring.maxMagnitude).toBe(9)
// The 500 is not compared against 9: under a volume ring it is not read.
expect(entityMagnitude(ring.groups[1].items[0], ring.basis)).toBe(3)
})
it('truncates payees per wedge without changing what the wedge weighs', () => {
const items = Array.from({ length: 8 }, (_, i) =>
entity({ key: `e${i}`, dominant_account_number: '5420', total_amount: 1000, occurrences: 1 }),
)
const ring = selectAccountRing(items, { maxPerAccount: 6 })
expect(ring.truncated).toBe(true)
expect(ring.groups[0].items).toHaveLength(6)
expect(ring.groups[0].weight).toBe(8000)
})
it('drops entities with no dominant account and survives an empty ledger', () => {
const ring = selectAccountRing([
entity({ key: 'orphan', dominant_account_number: null, total_amount: 900, occurrences: 2 }),
])
expect(ring.groups).toEqual([])
expect(ring.basis).toBe('volume')
// Safe divisors: the layout divides by both.
expect(ring.totalWeight).toBe(1)
expect(ring.maxMagnitude).toBe(1)
})
it('is deterministic when weights tie', () => {
const build = (order: string[]) =>
selectAccountRing(
order.map((number) =>
entity({ key: number, dominant_account_number: number, total_amount: 5000, occurrences: 1 }),
),
{ maxAccounts: 2 },
)
expect(build(['6000', '5000', '7000']).groups.map((g) => g.number)).toEqual(['5000', '6000'])
expect(build(['7000', '6000', '5000']).groups.map((g) => g.number)).toEqual(['5000', '6000'])
})
})
describe('entityMagnitude', () => {
it('clamps a negative amount rather than subtracting it from a sibling', () => {
const e = entity({ key: 'credit', total_amount: -4000, occurrences: 2 })
expect(entityMagnitude(e, 'amount')).toBe(0)
expect(entityMagnitude(e, 'volume')).toBe(2)
})
})
@@ -0,0 +1,176 @@
/**
* Pure account-ring selection and weighting for `LedgerGraph`.
*
* Lives outside the component (which is `'use client'` and pure JSX) so the
* rule below can be unit tested: this repo runs Vitest in the `node`
* environment and never renders components, so logic embedded in a component
* is unverifiable by construction. Same arrangement as
* `components/transactions/invoice-candidate-ranking.ts`.
*
* # Why this exists
*
* The ring weighted each account wedge with:
*
* const spend = items.reduce((s, i) => s + Math.max(i.total_amount, 0), 0)
* return spend > 0 ? spend : items.reduce((s, i) => s + i.occurrences, 0)
*
* The fallback is per group, but the weights are then summed into one
* denominator (`shownWeight`) and ranked against each other. So an account
* whose entities carry no usable amount contributed a booking COUNT (say 4)
* into a denominator otherwise made of kronor (say 250 000), and:
*
* - its wedge came out ~0.002% of the circle, i.e. an invisible sliver whose
* payee nodes all collapse onto one angle, and
* - it sorted below every money-weighted account, so it was the first thing
* dropped by the top-`maxAccounts` truncation.
*
* An account the agent genuinely books to therefore vanished from the map for
* no reason other than its magnitude being expressed in a different unit.
* Silent exclusion, which is exactly what this surface must not do.
*
* The rule here: the whole ring is measured in ONE unit. Amount if every
* account has a usable amount, booking volume otherwise. Never a mix. The unit
* is decided over every account, not just the nine that end up shown, because
* the unit is what ranks them: deciding it from the survivors would be circular
* and would reintroduce the truncation bug it exists to prevent. The chosen
* unit is returned as `basis` so the legend can say which one the sizes
* actually mean instead of always claiming "Storlek = belopp".
*
* # What this does NOT fix
*
* `DeepEntity.total_amount` arrives from `get_ledger_deep_context` already
* summed to a single scalar per entity, built as
* `abs(coalesce(t.amount_sek, t.amount))` on the counterparty side and
* `coalesce(si.total_sek, si.total, 0)` on the supplier side. That is SEK when
* a SEK equivalent was recorded and the RAW FOREIGN AMOUNT otherwise, and the
* RPC projects neither `currency` nor a per-row breakdown. A 500 EUR supplier
* invoice with no stored exchange rate therefore reaches this file as the
* number 500, indistinguishable from 500 kr.
*
* Nothing here can undo that: by the time the payload exists the currencies
* have already been added together upstream, and no field survives that would
* let us split them, convert them or even count them. Forming a per-currency
* total on this side would mean inventing one. The fix belongs in the RPC
* (project `total_amount_sek` + per-currency totals + a count of rows with no
* SEK equivalent, and drop the raw-foreign fallback); this file is written so
* that the moment those fields exist, `entityMagnitude` is the single place
* that has to learn about them.
*/
import type { DeepEntity } from '@/lib/agent-context/ledger-deep'
/** How many account wedges the ring shows before it truncates. */
export const MAX_ACCOUNTS = 9
/** How many payee nodes one wedge shows before it truncates. */
export const MAX_PER_ACCOUNT = 6
/**
* The unit the whole ring is measured in.
*
* - `amount`: `total_amount` as delivered by the RPC (kronor, with the caveat
* in the file header). Only chosen when every account has one.
* - `volume`: number of bookings. Currency-free, so it is always available and
* is what the ring falls back to rather than mixing units.
*/
export type RingBasis = 'amount' | 'volume'
export interface RingGroup {
/** BAS account number. Strings, never numbers (CLAUDE.md). */
number: string
/** Entities booked to this account, biggest magnitude first. */
items: DeepEntity[]
/**
* Wedge weight, in `basis` units. Computed over ALL the account's entities,
* including the ones `items` truncated away, so the wedge keeps the size the
* account actually earned.
*/
weight: number
}
export interface RingSelection {
basis: RingBasis
/** Shown accounts, ordered by account number so wedges never swap places. */
groups: RingGroup[]
/** True when accounts or payees were dropped by the display caps. */
truncated: boolean
/** Sum of the shown weights, floored at 1 so it is always a safe divisor. */
totalWeight: number
/** Largest single-entity magnitude among the shown groups, floored at 1. */
maxMagnitude: number
}
/**
* One entity's magnitude in the ring's unit.
*
* `total_amount` is whole kronor (`round(...)::bigint` in the RPC), so summing
* these is exact integer arithmetic and needs no öre rounding. Negative totals
* are clamped to 0 rather than subtracted from a sibling: this drives geometry,
* and a negative radius is not a thing.
*/
export function entityMagnitude(entity: DeepEntity, basis: RingBasis): number {
if (basis === 'volume') return Math.max(entity.occurrences, 0)
return Math.max(entity.total_amount, 0)
}
function sumMagnitude(items: DeepEntity[], basis: RingBasis): number {
return items.reduce((sum, item) => sum + entityMagnitude(item, basis), 0)
}
/**
* Groups entities by their dominant account and picks what the ring shows.
*
* Deterministic end to end: ties break on account number rather than on input
* order, so the demo lays out identically on every load.
*/
export function selectAccountRing(
entities: DeepEntity[],
options: { maxAccounts?: number; maxPerAccount?: number } = {},
): RingSelection {
const maxAccounts = options.maxAccounts ?? MAX_ACCOUNTS
const maxPerAccount = options.maxPerAccount ?? MAX_PER_ACCOUNT
const byAccount = new Map<string, DeepEntity[]>()
for (const entity of entities) {
const account = entity.dominant_account_number
if (!account) continue
const bucket = byAccount.get(account)
if (bucket) bucket.push(entity)
else byAccount.set(account, [entity])
}
const buckets = [...byAccount.entries()]
// The unit decision, made once for the whole ring. An account with no usable
// amount would otherwise be weighted in bookings while its siblings are
// weighted in kronor, and the two get summed into one denominator below.
const basis: RingBasis =
buckets.length > 0 && buckets.every(([, items]) => sumMagnitude(items, 'amount') > 0)
? 'amount'
: 'volume'
let groups: RingGroup[] = buckets.map(([number, items]) => ({
number,
items: [...items].sort((a, b) => entityMagnitude(b, basis) - entityMagnitude(a, basis)),
weight: sumMagnitude(items, basis),
}))
// Rank to decide what to show, then lay out in account-number order.
groups.sort((a, b) => b.weight - a.weight || a.number.localeCompare(b.number))
const accountCount = groups.length
groups = groups.slice(0, maxAccounts)
let truncated = accountCount > groups.length
for (const group of groups) {
if (group.items.length > maxPerAccount) {
truncated = true
group.items = group.items.slice(0, maxPerAccount)
}
}
groups.sort((a, b) => a.number.localeCompare(b.number))
const totalWeight = groups.reduce((sum, group) => sum + group.weight, 0) || 1
const maxMagnitude = Math.max(
...groups.flatMap((group) => group.items.map((item) => entityMagnitude(item, basis))),
1,
)
return { basis, groups, truncated, totalWeight, maxMagnitude }
}