4b51af3d80
* feat(agent): 'Vad din agent vet' page rendering the ledger context (P2) The human-facing surface for the openwiki ledger-context: a read-only page that renders the exact payload the AI agent reads (Accounted://ledger/context + the briefing digest) as a legible profile of how this company books. - Route app/(dashboard)/agent-knowledge (server component) calls the shared buildLedgerContext(supabase, companyId) directly: one payload, two renderers, no new API or data path. - Sections mirror the payload 1:1: coverage/freshness strip, counterparty patterns (monochrome confidence bars + seen/agree evidence), supplier patterns, explicit rules shown as authoritative instructions distinct from observed patterns, account usage, VAT profile, conventions. - Nav entry in the Analys group (icon Brain), ungated so it doubles as an upsell; flip requiredCapability to paywall. - Design per .claude/rules/design.md (PageHeader, Card, Table, Badge, AccountNumber BAS tooltips); sv + en strings (agentKnowledge namespace). VAT/BAS labels stay Swedish in both locales per i18n rules. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(agent): deep entity-resolved analysis + radial graph for the knowledge page Reworks the 'Vad din agent vet' page from tables into a radial-hub graph driven by a new full-history deep analysis, per founder feedback. - fix(rpc): median_booking_lag_days now measures real posting promptness via committed_at, not entry_date (which the bank flow sets to the transaction date, giving a ~0 tautology: 151/152 on prod). migration 20260708120000. - feat(rpc): get_ledger_deep_context (migration 20260708130000): full-history, deterministic, read-side. Merges counterparties by normalize_counterparty_key (e.g. Claude = 14 bookings across 12 name variants, weekly, 9 710 kr, always 5420), mines booked verifikat for SEK spend (coalesce amount_sek), detects recurrence cadence, dominant account + share, plus supplier entities. Storno excluded, corrections kept; 19xx/26xx excluded from the dominant contra. - LedgerGraph: radial SVG (company center, accounts inner ring, payees outer ring), hover/focus reveals variants + spend + cadence + account. Keyboard focusable nodes with per-node accessible names + a screen-reader data table. - Page fetches the deep context alongside the light context; coverage strip gains tracked-payee / recurring / tracked-spend stats. sv + en strings. - 14 pg tests (light + deep) green; both RPCs applied to prod + version-matched. Reviewed by an adversarial multi-lens pass (accounting/SQL, frontend/a11y, prod-fact verification); all four verified findings fixed (SEK currency, storno-lag guard, keyboard a11y, spacing tokens). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(agent): gentle mount fade-in for the radial map (reduced-motion safe) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(agent): render the page for a rules-only company (empty-state edge case) isEmpty ignored explicit_rules, so a company with configured mapping rules but no posted transactions hit the 'hasn't learned anything' empty state and lost its rules section. Rules are independent of bookings. (CodeRabbit) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(agent): show Kompetens (skills) + Fakta (memory) on the knowledge page The 'Vad din agent vet' page now shows the full picture of what the agent knows: alongside the booking map, a compact read-only view of its Kompetens (the Swedish accounting/tax knowledge atoms it ships with, grouped by tier as chips with active/dormant state) and the Fakta it remembers (top learned facts with kind + source), each linking to /settings/assistant for full management. Server-rendered via a new buildAgentCompetence() that mirrors GET /api/agent/skills + /api/agent/memory. Also renders in the no-bookings case so a new company still sees its agent's competence. sv + en strings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(agent): restructure knowledge page - hero graph + tabbed detail Declutters the page per feedback: the booking map is the always-visible hero, and the supporting detail (Kompetens · Minne · Regler & profil) moves into tabs so only one view shows at a time instead of a long card stack. Split AgentCompetenceSections into standalone CompetenceCard + FactsCard for the tabs; removed the top stat row on request. sv + en. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(agent): Reconciliation Aurora rewrite of the ledger knowledge graph Full rewrite of LedgerGraph: node area = sqrt(spend), colour = cadence, shape = supplier/counterparty, confidence = depth-of-field; on-mount descriptor-collapse animation with xN badge; cadence pulse veins; deterministic seeded layout; framer-motion only (no new deps); keyboard navigation, reduced-motion and sr-only support. Build-verified; 3-lens adversarial review findings fixed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(agent): sample-size-honest confidence in the ledger knowledge graph dominant_account_share was raw cnt/total, so a counterparty with a single booking rendered as '100% säkerhet': fake certainty by construction (the data_quality_master Item-C / P3 finding). New migration replaces get_ledger_deep_context with a Laplace-smoothed share (cnt+1)/(total+2) (1/1 -> 0.67, 3/3 -> 0.80) and exposes the raw evidence as dominant_account_count / dominant_account_total. The detail card now shows 'Bokförd hit i k av n fall' under the confidence bar; the existing focus buckets, stroke widths and percent labels inherit the honest value unchanged. pg-real test updated to guard the n=1 case. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
248 lines
8.8 KiB
TypeScript
248 lines
8.8 KiB
TypeScript
import { getTranslations } from 'next-intl/server'
|
|
import { Brain } from 'lucide-react'
|
|
import {
|
|
Card,
|
|
CardHeader,
|
|
CardTitle,
|
|
CardDescription,
|
|
CardContent,
|
|
} from '@/components/ui/card'
|
|
import { Badge } from '@/components/ui/badge'
|
|
import {
|
|
Table,
|
|
TableHeader,
|
|
TableBody,
|
|
TableHead,
|
|
TableRow,
|
|
TableCell,
|
|
} from '@/components/ui/table'
|
|
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'
|
|
import { KnowledgeTabs } from './KnowledgeTabs'
|
|
|
|
// 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 async function AgentKnowledgeView({
|
|
context,
|
|
deep,
|
|
competence,
|
|
companyName,
|
|
}: {
|
|
context: LedgerContext
|
|
deep: DeepLedgerContext
|
|
competence: AgentCompetence
|
|
companyName: string
|
|
}) {
|
|
const t = await getTranslations('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 (
|
|
<>
|
|
<Card>
|
|
<CardContent className="p-0">
|
|
<EmptyState
|
|
icon={Brain}
|
|
title={t('empty_title')}
|
|
description={t('empty_description')}
|
|
actionLabel={t('empty_action')}
|
|
actionHref="/transactions"
|
|
/>
|
|
</CardContent>
|
|
</Card>
|
|
<div className="grid gap-4 lg:grid-cols-2">
|
|
<CompetenceCard competence={competence} />
|
|
<FactsCard competence={competence} />
|
|
</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'))
|
|
|
|
// "Regler & profil" tab: user-authored rules + observed VAT + conventions.
|
|
const configContent = (
|
|
<>
|
|
{explicit_rules.length > 0 && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">{t('rules_title')}</CardTitle>
|
|
<CardDescription>{t('rules_description')}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="p-0">
|
|
<Table>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<TableHead>{t('col_rule')}</TableHead>
|
|
<TableHead>{t('col_match')}</TableHead>
|
|
<TableHead>{t('col_account')}</TableHead>
|
|
<TableHead>{t('col_vat')}</TableHead>
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{explicit_rules.map((r, i) => (
|
|
<TableRow key={r.rule_name + r.match + i}>
|
|
<TableCell>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<span className="font-medium">{r.rule_name}</span>
|
|
<Badge variant="default">{t('src_rule')}</Badge>
|
|
</div>
|
|
</TableCell>
|
|
<TableCell className="font-mono text-xs text-muted-foreground">{r.match}</TableCell>
|
|
<TableCell>
|
|
{r.account_number
|
|
? <AccountNumber number={r.account_number} showName size="sm" />
|
|
: <span className="text-muted-foreground">-</span>}
|
|
</TableCell>
|
|
<TableCell className="text-muted-foreground">{vatLabel(r.vat_treatment) ?? '-'}</TableCell>
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
<div className="grid gap-4 md:grid-cols-2">
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">{t('vat_title')}</CardTitle>
|
|
<CardDescription>{t('vat_description')}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4 pt-0">
|
|
<Row label={t('vat_registered_label')}>
|
|
<Badge variant={vat_profile.registered ? 'success' : 'outline'}>
|
|
{vat_profile.registered ? t('yes') : t('no')}
|
|
</Badge>
|
|
</Row>
|
|
<Row label={t('vat_period_label')}>
|
|
<span className="text-sm">{periodLabel}</span>
|
|
</Row>
|
|
<Row label={t('vat_treatments_label')}>
|
|
{vat_profile.treatments_used_12m.length === 0 ? (
|
|
<span className="text-sm text-muted-foreground">{t('vat_no_treatments')}</span>
|
|
) : (
|
|
<div className="flex flex-wrap justify-end gap-2">
|
|
{vat_profile.treatments_used_12m.map((code) => (
|
|
<Badge key={code} variant="outline">{vatLabel(code)}</Badge>
|
|
))}
|
|
</div>
|
|
)}
|
|
</Row>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">{t('conv_title')}</CardTitle>
|
|
<CardDescription>{t('conv_description')}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4 pt-0">
|
|
<Row label={t('conv_method_label')}>
|
|
<span className="text-sm">{methodLabel}</span>
|
|
</Row>
|
|
<Row label={t('conv_series_label')}>
|
|
{conventions.voucher_series_in_use.length === 0 ? (
|
|
<span className="text-sm text-muted-foreground">-</span>
|
|
) : (
|
|
<div className="flex flex-wrap justify-end gap-2">
|
|
{conventions.voucher_series_in_use.map((s) => (
|
|
<Badge key={s} variant="secondary" className="font-mono">{s}</Badge>
|
|
))}
|
|
</div>
|
|
)}
|
|
</Row>
|
|
<Row label={t('conv_salary_label')}>
|
|
<Badge variant={conventions.salary_run_active ? 'success' : 'outline'}>
|
|
{conventions.salary_run_active ? t('yes') : t('no')}
|
|
</Badge>
|
|
</Row>
|
|
{conventions.typical_booking_lag_days !== null && (
|
|
<Row label={t('conv_lag_label')}>
|
|
<span className="text-sm tabular-nums">{t('meta_lag_value', { days: conventions.typical_booking_lag_days })}</span>
|
|
</Row>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
</>
|
|
)
|
|
|
|
const tabs = [
|
|
{ value: 'competence', label: t('tab_competence'), content: <CompetenceCard competence={competence} /> },
|
|
{ value: 'memory', label: t('tab_memory'), content: <FactsCard competence={competence} /> },
|
|
{ value: 'config', label: t('tab_config'), content: configContent },
|
|
]
|
|
|
|
return (
|
|
<>
|
|
{/* The cinematic hero: a self-contained dark panel with its own header */}
|
|
<LedgerGraph deep={deep} companyName={companyName} />
|
|
|
|
{/* Supporting detail, tabbed so it doesn't stack into a long scroll */}
|
|
<KnowledgeTabs tabs={tabs} />
|
|
|
|
<p className="text-right text-xs text-muted-foreground">
|
|
{t('footer_basis', { entries: meta.coverage.posted_entries_window, date: formatDateLong(meta.computed_at) })}
|
|
</p>
|
|
</>
|
|
)
|
|
}
|
|
|
|
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
|
return (
|
|
<div className="flex items-center justify-between gap-4">
|
|
<span className="text-sm text-muted-foreground">{label}</span>
|
|
<div>{children}</div>
|
|
</div>
|
|
)
|
|
}
|