Files
accounted/components/dashboard/DashboardContent.tsx
T
Jakob WennbergandClaude Opus 4.8 36e3f6ceb0 Design critique: normalize daily-operator flows + UX improvements (#741)
* style(design): normalize daily-operator flows to locked design system

Sweep the dashboard, transactions, reconciliation, invoicing and supplier
flows for design-system violations (.claude/rules/design.md):

- font-medium removed from Hedvig display headings/numerals
- font-mono -> tabular-nums on monetary values (voucher ids stay mono)
- raw Tailwind status colors -> Badge variants / muted-alert pattern
- semantic colors removed from chrome backgrounds (deadline widgets, icon halos)
- hand-rolled skeletons/empty-states -> Skeleton / EmptyState primitives
- opacity-suffixed borders, the invisible warning-foreground count color, and
  shadow-sm/rounded-xl on non-overlay surfaces normalized

The four files that also received UX changes carry their token fixes in the
following commit.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(ux): clearer dashboard CTA, match confidence, AI provenance, invoice actions

Four high-impact UX fixes from the design critique (these files also carry their
design-system token normalization):

- Dashboard: render the next-best-action hero for every agent-built company, not
  only 'slim' nav density, so there is always one obvious next step instead of
  four equal-weight metric tiles.
- Reconciliation: surface the match engine's 0-1 confidence as a graded strength
  badge (Stark / Trolig / Svag traff) in the shared verifikat picker rows and
  selected chip; drop the uninformative binary "Foreslagen traff" badge from the
  match dialog.
- Supplier inbox: show AI-filled provenance per extracted field (a success dot
  that clears once the user verifies/edits the value) so misparsed amounts/dates
  get proofread before they post to an immutable verifikat.
- Invoice detail: keep each status's primary action only in the header row; the
  sidebar "Status actions" card now holds secondary/reversible actions only
  (makulera, ta bort, skapa kreditnota, manual-send alternative), removing the
  duplicated CTAs and closing a viewer-permission gap on the old sidebar buttons.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(ux): Tier-B medium design-critique fixes across daily-operator flows

- Reconciliation: standardise the match-confirm verb on "Matcha" (was "Koppla"
  in MatchVoucherDialog) and replace the hand-rolled date <input>s in the bank
  reconciliation view with the Input primitive.
- Supplier inbox: fold the two alternative bookings (Skapa leverantorsfaktura /
  Bokfor som verifikat) behind a single "Andra satt att bokfora" dropdown so the
  default path (Matcha mot transaktion) stays the lone primary action.
- Duplicate-payment guard: demote the "Skapa ny verifikation anda" escape hatch
  to a ghost button so the safe "Koppla till befintlig" path dominates.
- Onboarding: raise the "start fresh" escape hatch from a muted text link to a
  visible secondary button; normalise the checklist's off-scale spacing.
- Supplier flows: finish the font-mono -> tabular-nums sweep on monetary values
  in the supplier-invoice detail / create / review surfaces (ids stay mono).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(deadlines): keep overdue rows visually distinct (destructive chrome is allowed)

The Tier-A normalization stripped all semantic-color row tints from the deadline
widgets, but design.md exempts --destructive ("only --destructive survives in
chrome"). Restore a subtle bg-destructive/5 on OVERDUE rows so missed tax/AGI
deadlines (-> skattetillagg) stay noticeable in a list scan; action-needed
(warning) rows stay clean since warning is data-only. Surfaced by the Swedish
compliance review on #741.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(reconciliation): hide match-strength badge on already-matched verifikat

Per the Swedish compliance review on #741: a green "Stark traff" confidence badge
rendered alongside "Redan matchad" could visually nudge an accidental double-match
of a posted verifikat (a BFL 5 kap audit-trail concern). Suppress the strength
badge when linked_transaction_count > 0 so "Redan matchad" is the lone signal
there; N:1 matching stays an explicit opt-in.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 14:23:33 +02:00

378 lines
16 KiB
TypeScript

'use client'
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { cn, formatCurrency } from '@/lib/utils'
import { UpcomingDeadlinesWidget } from '@/components/deadlines/UpcomingDeadlinesWidget'
import { TaxTodoWidget } from '@/components/deadlines/TaxTodoWidget'
import NewUserChecklist from '@/components/onboarding/NewUserChecklist'
import AttGoraSection from '@/components/dashboard/AttGoraSection'
import {
Receipt,
ArrowLeftRight,
ChevronRight,
CheckCircle2,
Clock,
ArrowRight,
MessageCircle,
} from 'lucide-react'
import type { Deadline, OnboardingProgress } from '@/types'
import type { SuggestedMatch, WorklistCounts } from '@/lib/worklist/types'
const setupFreshStartKey = (companyId: string) => `erp_setup_fresh_start:${companyId}`
interface DashboardContentProps {
companyId: string
summary: {
ytd: { income: number; expenses: number; net: number }
mtd: { income: number; expenses: number; net: number }
unpaidInvoicesCount: number
unpaidInvoicesTotal: number
unpaidVatTotal: number
overdueInvoicesCount: number
bankBalance: number | null
expiringBankConnections?: { id: string; bank_name: string; days_left: number }[]
deadlines: Deadline[]
staleUncategorizedCount: number
}
/** Unified pending-work counts from lib/worklist — same source as the sidebar badges. */
worklist: WorklistCounts
/** High-confidence transaction↔invoice matches for inline one-click confirm. */
suggestedMatches: SuggestedMatch[]
onboardingProgress?: OnboardingProgress
/**
* False until the company has a verified agent_profile. When false the hero
* slot shows a build-assistant prompt instead of the next-best-action card,
* so existing/migrated users are nudged to build the assistant without a
* full-screen onboarding takeover.
*/
agentBuilt?: boolean
}
export default function DashboardContent({ companyId, summary, worklist, suggestedMatches, onboardingProgress, agentBuilt = true }: DashboardContentProps) {
const t = useTranslations('dashboard')
// The setup gate exists to nudge brand-new users into a data-import step
// before they hit the dashboard. Once the assistant is built we treat the
// user as past that phase — they've already committed to using the tool —
// and let the dashboard render normally. This also keeps the sandbox
// (which ships with a pre-built assistant + seeded data but no bank
// connection / SIE import) from showing a checklist that re-links to
// /onboarding/agent.
const needsSetup =
!agentBuilt &&
onboardingProgress &&
!onboardingProgress.hasBankConnected &&
!onboardingProgress.hasSIEImport
const [setupGateActive, setSetupGateActive] = useState(!!needsSetup)
useEffect(() => {
if (!needsSetup) {
setSetupGateActive(false)
return
}
const scopedKey = setupFreshStartKey(companyId)
const freshStart = localStorage.getItem(scopedKey) === 'true'
const legacyFreshStart = localStorage.getItem('erp_setup_fresh_start') === 'true'
const legacyDismissed = localStorage.getItem('erp_checklist_dismissed') === 'true'
if (freshStart || legacyFreshStart || legacyDismissed) {
if (!freshStart) {
localStorage.setItem(scopedKey, 'true')
}
setSetupGateActive(false)
}
}, [needsSetup, companyId])
if (setupGateActive) {
return (
<NewUserChecklist
hasBookkeepingImported={!!onboardingProgress?.hasSIEImport}
hasBankConnected={!!onboardingProgress?.hasBankConnected}
hasSkatteverketConnected={!!onboardingProgress?.hasSkatteverketConnected}
hasAgentBuilt={agentBuilt}
onFreshStart={() => {
localStorage.setItem(setupFreshStartKey(companyId), 'true')
setSetupGateActive(false)
}}
/>
)
}
const formatLargeNumber = (amount: number) => {
return new Intl.NumberFormat('sv-SE', {
style: 'decimal',
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(amount)
}
// One number, one source: the worklist total plus expiring bank connections
// (dashboard-only, not a lib/worklist category). Must match AttGoraSection's
// header so the tile and the section never disagree.
const todoCount = worklist.total + (summary.expiringBankConnections?.length ?? 0)
// Pick the single most-urgent next action so the launchpad surfaces one
// unambiguous CTA. Order matches the friction we actually want to remove
// first: stale → overdue → uncategorized → unpaid → all clear.
const nextBestAction = (() => {
if (summary.staleUncategorizedCount > 0) {
return {
href: '/transactions',
title: 'Gamla transaktioner väntar',
body: `${summary.staleUncategorizedCount} transaktion${summary.staleUncategorizedCount === 1 ? '' : 'er'} äldre än 14 dagar saknar bokföring.`,
cta: 'Bokför nu',
tone: 'destructive' as const,
icon: Clock,
}
}
if (summary.overdueInvoicesCount > 0) {
return {
href: '/invoices?status=unpaid',
title: 'Förfallna fakturor',
body: `${summary.overdueInvoicesCount} st · ${formatCurrency(summary.unpaidInvoicesTotal)}`,
cta: 'Gå till fakturor',
tone: 'destructive' as const,
icon: Receipt,
}
}
if (worklist.counts.book_transaction > 0) {
const n = worklist.counts.book_transaction
return {
href: '/transactions',
title: 'Transaktioner att bokföra',
body: `${n} obokförd${n === 1 ? '' : 'a'} transaktion${n === 1 ? '' : 'er'}.`,
cta: 'Bokför nu',
tone: 'primary' as const,
icon: ArrowLeftRight,
}
}
if (summary.unpaidInvoicesCount > 0) {
return {
href: '/invoices?status=unpaid',
title: 'Obetalda fakturor',
body: `${summary.unpaidInvoicesCount} st · ${formatCurrency(summary.unpaidInvoicesTotal)}`,
cta: 'Visa fakturor',
tone: 'primary' as const,
icon: Receipt,
}
}
return {
href: '/invoices/new',
title: 'Allt är ikapp',
body: 'Inga obokförda transaktioner och inga obetalda fakturor. Skicka nästa faktura?',
cta: 'Skapa faktura',
tone: 'neutral' as const,
icon: CheckCircle2,
}
})()
return (
<div className="stagger-enter space-y-8">
{!agentBuilt ? (
/* Build-assistant hero — shown until the company has a verified
agent_profile. Takes the hero slot so existing/migrated users get a
clear prompt instead of a full-screen onboarding takeover. */
<section>
<Link href="/onboarding/agent" className="block group">
<Card className="transition-colors hover:border-primary/50">
<CardContent className="p-6 flex items-center gap-5">
<div className="flex-shrink-0 h-10 w-10 rounded-lg flex items-center justify-center bg-foreground text-background">
<MessageCircle className="h-5 w-5" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-display text-xl leading-tight">Bygg din bokföringsassistent</p>
<Badge variant="secondary" className="uppercase tracking-wider">Beta</Badge>
</div>
<p className="text-sm text-muted-foreground mt-1">
Några frågor om din verksamhet kalibrerar en assistent som föreslår bokföring åt dig.
</p>
</div>
<div className="hidden sm:flex items-center gap-1.5 text-sm font-medium text-foreground group-hover:translate-x-0.5 transition-transform">
<span>Kom igång</span>
<ArrowRight className="h-4 w-4" />
</div>
</CardContent>
</Card>
</Link>
</section>
) : (
/* Next best action — single hero card, shown for every agent-built
company regardless of nav density so there is always one clear CTA */
<section>
<Link href={nextBestAction.href} className="block group">
<Card className={cn(
'transition-colors',
nextBestAction.tone === 'destructive' && 'border-destructive/30 hover:bg-destructive/[0.03]',
nextBestAction.tone === 'primary' && 'hover:border-primary/50',
nextBestAction.tone === 'neutral' && 'hover:border-primary/30',
)}>
<CardContent className="p-6 flex items-center gap-5">
<div className={cn(
'flex-shrink-0 h-10 w-10 rounded-lg flex items-center justify-center',
nextBestAction.tone === 'destructive' && 'bg-destructive/10 text-destructive',
nextBestAction.tone === 'primary' && 'bg-secondary text-foreground',
nextBestAction.tone === 'neutral' && 'bg-secondary text-foreground',
)}>
<nextBestAction.icon className="h-5 w-5" />
</div>
<div className="flex-1 min-w-0">
<p className="font-display text-xl leading-tight">{nextBestAction.title}</p>
<p className="text-sm text-muted-foreground mt-1">{nextBestAction.body}</p>
</div>
<div className="flex items-center gap-1.5 text-sm font-medium text-foreground group-hover:translate-x-0.5 transition-transform">
<span>{nextBestAction.cta}</span>
<ArrowRight className="h-4 w-4" />
</div>
</CardContent>
</Card>
</Link>
</section>
)}
{/* Key metrics — 4 compact cards */}
<section>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<Card>
<CardContent className="p-4">
<p className="text-xs text-muted-foreground mb-2">{t('result')}</p>
<p className={cn(
'font-display text-xl tabular-nums leading-tight',
summary.mtd.net >= 0 ? 'text-success' : 'text-destructive'
)}>
{formatLargeNumber(summary.mtd.net)}
<span className="text-sm ml-0.5 text-muted-foreground font-normal">kr</span>
</p>
<p className="text-xs text-muted-foreground mt-1">
{formatCurrency(summary.ytd.net)} {t('this_year_short')}
</p>
</CardContent>
</Card>
<Link href="/invoices?status=unpaid">
<Card className="h-full hover:border-primary/50 transition-colors cursor-pointer">
<CardContent className="p-4">
<div className="flex items-start justify-between">
<p className="text-xs text-muted-foreground mb-2">{t('to_be_paid')}</p>
<ChevronRight className="h-3.5 w-3.5 text-muted-foreground/50" />
</div>
<p className="font-display text-xl tabular-nums leading-tight">
{summary.unpaidInvoicesCount}
{t('units') && <span className="text-sm ml-0.5 text-muted-foreground font-normal">{t('units')}</span>}
</p>
<p className="text-xs text-muted-foreground mt-1">
{formatCurrency(summary.unpaidInvoicesTotal)}
</p>
</CardContent>
</Card>
</Link>
{summary.bankBalance !== null ? (
<Card>
<CardContent className="p-4">
<p className="text-xs text-muted-foreground mb-2">{t('bank_balance')}</p>
<p className="font-display text-xl tabular-nums leading-tight">
{formatLargeNumber(summary.bankBalance)}
<span className="text-sm ml-0.5 text-muted-foreground font-normal">kr</span>
</p>
</CardContent>
</Card>
) : (
<Link href="/import">
<Card className="h-full hover:border-primary/50 transition-colors cursor-pointer">
<CardContent className="p-4">
<div className="flex items-start justify-between">
<p className="text-xs text-muted-foreground mb-2">{t('bank_balance')}</p>
<ChevronRight className="h-3.5 w-3.5 text-muted-foreground/50" />
</div>
<p className="text-sm font-medium text-primary">{t('connect_bank')}</p>
</CardContent>
</Card>
</Link>
)}
<Card>
<CardContent className="p-4">
<p className="text-xs text-muted-foreground mb-2">{t('todo')}</p>
<div role="status" aria-live="polite">
{todoCount > 0 ? (
<p className="font-display text-xl tabular-nums leading-tight">
{todoCount}
{t('units') && <span className="text-sm ml-0.5 text-muted-foreground font-normal">{t('units')}</span>}
</p>
) : (
<div className="flex items-center gap-1.5">
<CheckCircle2 className="h-4 w-4 text-success" />
<p className="text-sm font-medium text-success">{t('all_done')}</p>
</div>
)}
</div>
</CardContent>
</Card>
</div>
</section>
{/* Att göra — the unified worklist. One section, every actionable item,
same counts as the sidebar badges (lib/worklist). */}
<AttGoraSection
worklist={worklist}
suggestedMatches={suggestedMatches}
expiringBankConnections={summary.expiringBankConnections}
staleUncategorizedCount={summary.staleUncategorizedCount}
/>
{/* Result — revenue / expenses (always visible) */}
<section>
<div className="grid md:grid-cols-2 gap-4">
<Card>
<CardContent className="p-6">
<p className="text-sm text-muted-foreground mb-3">{t('revenue')}</p>
<p className="font-display text-2xl tabular-nums leading-tight">
{formatLargeNumber(summary.mtd.income)}
<span className="text-base ml-1 text-muted-foreground font-normal">kr</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">{t('this_month')}</p>
<div className="mt-4 pt-3 border-t border-border flex items-baseline justify-between">
<p className="text-xs text-muted-foreground">{t('this_year_block')}</p>
<p className="text-sm font-medium tabular-nums">{formatCurrency(summary.ytd.income)}</p>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<p className="text-sm text-muted-foreground mb-3">{t('expenses')}</p>
<p className="font-display text-2xl tabular-nums leading-tight">
{formatLargeNumber(summary.mtd.expenses)}
<span className="text-base ml-1 text-muted-foreground font-normal">kr</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">{t('this_month')}</p>
<div className="mt-4 pt-3 border-t border-border flex items-baseline justify-between">
<p className="text-xs text-muted-foreground">{t('this_year_block')}</p>
<p className="text-sm font-medium tabular-nums">{formatCurrency(summary.ytd.expenses)}</p>
</div>
</CardContent>
</Card>
</div>
</section>
{/* Upcoming deadlines */}
{summary.deadlines && summary.deadlines.length > 0 && (
<section>
<UpcomingDeadlinesWidget deadlines={summary.deadlines} maxItems={8} />
</section>
)}
{/* Tax todo */}
{summary.deadlines?.some(d => d.deadline_type === 'tax' && !d.is_completed) && (
<section>
<TaxTodoWidget deadlines={summary.deadlines} />
</section>
)}
</div>
)
}