f24b26a139
* fix(security): gate replace_sie_import behind owner/admin membership The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no company_members lookup, no auth.uid() reference and no unauthorized raise, while setting gnubok.allow_delete to disarm the BFL immutability and retention triggers. Any caller holding a company_id and an import id could hard delete another tenant's verifikationer. Confirmed live in production. Applies the same fail closed owner/admin guard that undo_sie_import already carries (migration 20260624120000), resolving the actor from COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then revokes EXECUTE from PUBLIC and anon. search_path and the raised statement_timeout are restated, since CREATE OR REPLACE drops settings that are not repeated. userId is a required parameter on replaceSIEImport: the service client has a NULL auth.uid(), so a caller without an explicit actor now fails to compile rather than hitting the closed gate at runtime. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): validate arcim OAuth callback state server side The callback route is skipAuth and decoded the state parameter as plain base64url JSON, trusting consentId and provider from it. A one time code was minted at flow start and never read. An unauthenticated attacker who learned a consent id could run an OAuth flow on their own provider account and post the callback with a forged state, landing their tokens on another tenant's consent, so the victim's next migration imported the attacker's ledger. State is now an opaque randomBytes(32) pointer to a provider_otc row, consumed by a single atomic UPDATE guarded on used_at IS NULL and expires_at, so a replay loses the row lock race and updates nothing. provider is read from provider_consents rather than trusted from the client. provider_otc already existed for exactly this purpose and was never wired up. Also scopes getConsent to an owning company, closing a cross tenant status oracle where the preview and migrate paths echoed a consent's status before the scoped check ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): scope documents storage to company_id (phase A) The documents bucket policies matched on auth.uid(), and upload keys were documents/{userId}/..., so company membership was never consulted. Removing a member revoked nothing: their session still authenticated and they kept direct Storage read access to every receipt, supplier invoice and bank statement they had uploaded. The same bug was fixed for sie-files in 20260416120000; this bucket was left behind. Phase A is additive. Company scoped policies are added alongside the uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and reads accept either layout so nothing breaks mid migration. Phase C, which drops the old policies, is gated on the backfill reporting zero remaining legacy prefix objects. The policy compares the company segment as text rather than casting to uuid the way sie-files does: this bucket holds keys whose second segment is not a uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix qual runs before the cast, so a planner reordering would raise 22P02 and fail the whole query instead of filtering the row out. deleteDocument now removes both candidate keys. Removing only the stored pointer would leave a readable orphan copy of a document the user asked to erase. The backfill script is included but has never been run. It defaults to dry run, refuses .env.local by name, and verifies each copy is readable and SHA-256 identical before repointing the row. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): enforce events:read scope and membership on /api/events This was the only one of the three validateApiKey call sites with no downstream guard: v1 and the MCP server both check scope and re-verify company membership, this route did neither. An events:read scope existed and was documented as gating the endpoint but was never called, so a legacy key falling back to DEFAULT_SCOPES read the full log. The bound company id went straight from the api_keys row into a service role query, so a key whose user had been removed from the company kept reading. Adds the scope check before any database access, re-verifies company_members with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead of ignoring it, applies minimisePayload so the pull surface can never return a wider payload than the push surface, and replaces the three flat error strings with the canonical envelope. Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is gated on mutations in with-api-v1, so a read gets the same treatment as every other v1 read endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf(bookkeeping): sweep remaining journal_entries!inner embeds A previous refactor removed this pattern from lib/reports and introduced fetchEntryLines, but the class was never swept. Seventeen sites remained and had become the top application consumer of production database time: measured across the resulting query shapes, 32,694 calls and 25,848 seconds of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at 7,962ms against the 8s statement_timeout, which surfaced to users as 500s on the booking path. PostgREST compiles an embed with filters on the embedded side into a correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops Postgres reordering the join, so each query walked the whole journal_entry_lines table across all tenants. Driving from the entries side instead turns that into two indexed round trips. Converted sites keep their existing shape: the helper reattaches the parent entry under the same key the embed produced. Several conversions also remove a latent silent truncation where an unpaginated query was capped at PostgREST's 1000 row ceiling. Two deliberate exceptions. The free text ilike legs of the MCP display query stay on the embed, because each is capped at legLimit and that cap drives the truncation contract the tool reports, while the helper is unbounded. The accounts route moves to the existing get_account_usage_counts RPC instead, since its embed was a head count and the helper returns rows. commitEntry's write path is untouched: the change there is confined to the read query of the pre-commit dimension rule check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): anchor v1 list cursors on created_at Page two returned page one, forever, while still advertising a fresh next_cursor. The three routes sorted by and encoded a Postgres date column, which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor timestamp as full ISO-8601 and returned null, so the keyset filter was never applied and has_more never went false. An integrator syncing verifikat looped on the newest rows indefinitely. The transactions route already solved this and its comment names the trap; the fix was never ported. All three now order and encode on created_at with an id tie break, matching the transactions keyset predicate exactly. ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change sort semantics on the route that currently works. Default ordering therefore moves from business date to insert order. Every business date is still on the row, and the invoices list gains date_from and date_to filters so a date range is still reachable; the other two already had them. The tests use an in-memory PostgREST that actually evaluates the filters, because the repo's pass-through mock cannot catch this class of bug: the bug is that the filter is never sent. They walk to exhaustion with a hard iteration cap, so an unterminated walk fails instead of hanging. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): separate dry run from commit in the idempotency hash The request hash was built from url.pathname, which excludes the query string, so a dry run and its commit hashed identically. Following the flow documented in dry-run.ts, re-issuing the request with the same Idempotency-Key returned the cached preview with Idempotent-Replayed set and wrote nothing, while reporting 200. An agent or integrator saw success for a write that never happened. dry_run is folded into the hash only when true, not as an unconditional boolean. Including it as false would change the hash of every ordinary write, and with a 24h idempotency TTL any key in flight across the deploy would fail the request_hash comparison and 409 on a legitimate retry. Both hash call sites now go through one shared helper so they cannot drift into a permanent cache miss, and dry run responses are no longer stored at all. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: install the Bedrock SDK out of tree in the compliance review The Swedish accounting compliance gate had failed ten consecutive runs and so was posting nothing. With --no-package-lock npm discarded the lockfile and re-resolved the whole tree from package.json, floating @hookform/resolvers to 5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0. Installing into the parent of the checkout resolves only that one package, so an unrelated peer conflict can never take the gate down again. Node still finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH would not have worked, as it is CommonJS only. --legacy-peer-deps was rejected because it masks future genuine peer conflicts and still reifies the full tree. The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that package.json and check:guards enforce after the streaming outage. That drift went unnoticed because the pin guard only inspects package.json and the lockfile, never workflow files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * build(docker): generate crontabs from vercel.json vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were byte identical to each other. Self hosted deployments therefore never sent recurring invoices, never dispatched webhooks and never cleaned up idempotency keys. tax-deadlines also ran once a year on 2 January instead of daily, and documents/verify weekly instead of daily. Extension crons are included rather than excluded. The Dockerfile copies the whole tree before building, so every extension cron route is compiled into the image regardless of the enabled preset, and each returns 200 when its extension is unconfigured, so curl -sf logs no failure. Two such entries were already present in the crontab for extensions absent from the preset, which settles the intent. documents/verify is treated as drift rather than a self hosted concession: the weekly cadence was present in the hosted crontab too, and the run is capped at 200 documents walking a nulls-first queue, so weekly drains the integrity queue seven times slower on a check that exists for BFL retention. webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day on self hosted. A gentler tick would silently stretch the first retry, since the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line place to change that. A parity test asserts the path sets match minus a documented exclusion list, and ratchets three cron routes that are currently scheduled nowhere so they are named rather than silently rotting. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(observability): add a provider agnostic error sink There is no error tracking in this codebase: logs go to console and Vercel retention and nowhere else, nothing alerts on the 16 cron jobs, and seven code comments across lib, app, components and extensions asserted that Sentry captures errors when Sentry is not a dependency. The two most recent bug fixes on this repo were both discovered by customer email. This adds the sink, not a vendor. No dependency is taken: the interface has a no-op default and a registration point, so behaviour is unchanged until an adapter is registered. Releases are tagged from the build id already inlined by next.config.ts. Redaction moved out of lib/logger.ts into a leaf module that both the logger and the sink import, so there is one denylist and no path from application data to a third party can skip the personnummer regex, including direct sink calls that bypass the logger. That matters here because these logs carry personnummer and financial data. verifyCronSecret now reports its own 401s, which covers all 16 jobs without touching a route file and catches the case where CRON_SECRET is rotated without updating the scheduler and every job silently 401s forever. The threshold is one failure rather than the backup alert's three: suppressing the first occurrence is precisely how an outage stays invisible. The seven misleading comments are corrected to describe what the code actually does, including the two cases that still are not covered: the client side one, since the sink is server side, and a warn level call that is not forwarded. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: remediate the 2026-07-26 similar-sweep findings across all surfaces Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with one agent per finding; every behavioural fix carries a regression test proven to fail at HEAD. Full status, corrections to the sweep, refusals and open decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md. Structural roots closed: - resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking 1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING - ledger-line-amount.ts: journal_entry_lines.currency labels the document, not the amount; SQL pre-filter decoy proven and fixed - sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the exploitable salary payslip-line PATCH and KPI preferences sinks fixed - tests/schema: migration-replay phantom-column guard (13k+ refs, closed CHECK sets, onConflict targets); found 28 real defects, all fixed, all four baselines now empty - three new ratchet guards: sek-labelled-amount, cross-extension-import, ungated-extension-route Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap), RC input VAT mismatch wired on web + both MCP callers, missing-underlag resource delegates to the shared RPC predicate, push-notifications consent polarity fail-closed, deadlines undo honours requested state, silent-failure and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/ Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites with isSwedishUserMessage extended. Also includes the parallel session's MCP invoice tools (update_invoice, recurring schedules, invoice deliveries) which share files with the sweep work and are verified green together. 13 new migrations are NOT applied anywhere; they apply via branch merge. 20260726120000 backfills 1247 supplier-invoice rows. pg tests for new DDL are written but unrun (no local Postgres). Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0 errors, check:guards passing, MCP payload 57475/57500. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): rename replace_sie_import migration off main's 20260726090000 version origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping our replace_sie_import migration on the same version would abort the Supabase apply with a schema_migrations_pkey duplicate at merge time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate pre-publish deep-review findings across all slices A 13-agent review of the full branch diff surfaced 1 critical, 5 high and ~45 further findings; this commit resolves them in one pass: - replace_sie_import / undo_sie_import: p_user_id honored only for service_role callers; any other caller is pinned to auth.uid() (impersonation gate bypass), authz raise errcode 42501 mapped to a Swedish 403 in the route, new caller-guard migration for undo - bulk_book_transactions refuses homogeneous non-SEK batches instead of writing foreign magnitudes into SEK ledger columns - credit-note cap trigger: company-match on credited_invoice_id, no cross-tenant figures in exception text - link_voucher RPCs resolve NULL invoice currency as SEK end to end - personal-number ciphertext CHECK split into NOT VALID + VALIDATE - same-currency foreign settlements clear 1510 at booking rate and book realized diff to 3960/7960; rate-less foreign write paths refuse - receivables revaluation covers partially_paid and outstanding amounts - period lock guard paginates candidates past the PostgREST 1000 cap - documents: service-client storage removals after authz, dual-layout reads in integrity cron and archive export, backfill delete-source sweep actually deletes with hash verification and shared-key grouping - invoice matching normalizes NULL/lowercase currencies (regression), duplicate candidates stop claiming amount matches they never ran - match-invoice aborts on any booking failure (no paid-without-verifikat) - refresh-exchange-rate reverts on concurrent booking (TOCTOU window) - KPI preferences upsert arbiter aligned to the company-scoped constraint - personnummer_last4 stripped from all salary responses incl. MCP tools - worked-hours batch restores destroyed rows on conflict and error paths - MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit on tag_journal_lines overflow, auto_send schedules stage as high risk - observability sink redacts emails/IBANs/API keys and keeps redacted stacks in prod; assorted small guards (safe-return-to /@, dry_run=True, cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings call removed) Full dispositions, deferred items and hand-verified accounting numbers are documented in the PR body and DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(personnummer): implement masking and encryption for personal numbers with tests * fix(review): address CI and compliance-bot findings for PR #1215 pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role GUC, so both service-role simulations (runAsServiceRole and the invoice-delivery test's local helper) never satisfied auth.role() = 'service_role' and every legitimate p_user_id path failed closed; the shared helper now sets both GUC shapes plus SET LOCAL ROLE with a fail-loud sanity check, and the delivery test reuses it. The link-voucher migration had recreated both RPCs from pre-rewrite file text, reintroducing the NULL-unsafe membership pattern the null-safe-tenant-guards ratchet bans; both guards now use public.caller_is_company_member() with all currency changes preserved. Compliance bots: the customers export now emits the standard masked form instead of raw AES-256-GCM ciphertext in the Org-/personnummer column, and maskCustomerRow returns a non-round-trippable placeholder on decrypt failure instead of 500ing the list. MCP parity: gnubok_lock_period's staging pre-check now runs the exact countUnbookedInPeriod the commit path enforces (exported from period-service; local mirror deleted), and gnubok_agi_status resolves AGI state run-scoped so a correction run no longer renders as already filed. Declined with evidence: PR-Agent's opening-balances null-zeroing concern (all mergeable columns are NOT NULL with defaults per 20260713101000). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): address codex review findings on PR #1215 - restore 20260726140000 to its preview-recorded content and restate the NULL-safe tenant guard under 20260727130000: a recorded migration version never re-runs, so the in-place edit could not reach the preview branch - replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap warning texts and update the pinned test expectations - drop the em dash in the fiscal-periods route comment - strip trailing whitespace in import-existing.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): raise timeout on real PDF render tests renderToBuffer does real @react-pdf layout work and exceeds the 5s default when the full suite saturates the CPU; tests pass in isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
839 lines
30 KiB
TypeScript
839 lines
30 KiB
TypeScript
'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 { useTranslations } from 'next-intl'
|
||
import { 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')
|
||
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-xl 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-xl 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-md 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 }}>
|
||
{e.total_amount.toLocaleString('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
||
</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; }
|
||
}
|
||
`
|