Files
accounted/components/dashboard/DashboardContent.tsx
T
Jakob WennbergandClaude Opus 4.8 076bb169f8 feat(dashboard): unified "Att göra" worklist section on Hem (#674)
* feat(dashboard): unified "Att göra" worklist section on Hem

The pilot's core complaint: pending work was scattered across
Transaktioner, Underlag and Ny verifikation with no single starting
point. Hem now carries one flat Att göra ledger — three bands by
session intent (Bokför / Granska & komplettera / Bevaka), every count
read from lib/worklist (the same source as the sidebar badges, so the
numbers can never disagree), and an "Allt klart!" empty state.

Suggested transaction↔invoice matches render inline with one-click
Bekräfta posting to the existing match endpoints; rows fade out
optimistically and counts re-sync from /api/worklist/counts.

Replaces the "Att hantera" alert-card grid — whose warning/destructive
chrome borders violated the design system — with neutral hairline rows;
urgency is now carried by Badge variants only. The "Att göra" KPI tile
switches to the worklist total, and the home page drops eight inline
pending-work queries (incl. the legacy receipts queue, superseded by
the inbox category) in favour of getWorklistCounts().

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

* fix(dashboard): address PR #674 review — count/visibility consistency

greptile found two real contradictions in the Att göra section:
- Expiring bank connections rendered a Bevaka row without counting
  toward the header total — a user with only an expiring consent read
  "0 kvar" next to a visible action row. The section header and the
  KPI tile now both show worklist.total + expiring connections.
- deadline_action counted toward the total but had no row, so
  deadline-only users saw "Allt klart!" under a non-zero tile. Bevaka
  gains a "Moms- och skattedeadlines" row linking to /deadlines.

Invariant after this commit: every count that feeds a displayed total
has a visible row, and the tile and section header always agree.

Also per compliance review: a failed counts refetch after a confirmed
match now logs via console.error (Sentry-observable) instead of being
silently swallowed.

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-05 10:44:16 +02:00

380 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'
import { getBranding } from '@/lib/branding/service'
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)
const slim = getBranding().navDensity === 'slim'
// 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>
) : slim ? (
/* Next best action — single hero card */
<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>
) : null}
{/* 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 font-medium 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 font-medium 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 font-medium 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 font-medium tabular-nums leading-tight text-warning-foreground">
{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 font-medium 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/30 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 font-medium 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/30 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>
)
}