Files
accounted/components/transactions/TransactionInboxCard.tsx
T
Jakob WennbergandClaude Opus 4.7 d0fbc2b616 refactor(ui): app-wide UI/UX consistency pass (#436)
* refactor(ui): app-wide UI/UX consistency pass

Net: +1,159 / −1,373 LOC across 77 files. No new features, no behavior
changes. Locks in a uniform design system across every dashboard surface.

What changed:

- **Foundation**: sidebar width 232→256px (md:w-64), spacing scale locked
  (Tailwind 1/2/3/4/6/8/10/12; 2.5/5 forbidden), card padding p-6 default
  (p-4 for compact metric cards), space-y-8 between page sections.

- **Tables unified**: all 33 thead blocks now share the Resultatrapport
  pattern via shadcn Table primitive (text-[11px] font-medium uppercase
  tracking-wider text-muted-foreground). Hand-rolled <table> instances
  converted where they were data tables; form/edit grids kept distinct.

- **Status badges unified**: every status indicator routes through
  shadcn <Badge variant>. Eliminated raw Tailwind colors
  (bg-amber-100, bg-emerald-500/10, bg-blue-100, bg-purple-100, etc.)
  in favor of the gnubok semantic palette (success=sage, warning=ochre,
  destructive=terracotta).

- **Empty states unified**: list pages migrated from hand-rolled
  "flex flex-col items-center py-12" divs to the EmptyState primitive.

- **Loading skeletons unified**: hand-rolled bg-muted rounded animate-pulse
  divs replaced with shadcn <Skeleton> across 15 files.

- **Touch targets**: 6 back-buttons + edit-pencil + inbox delete bumped
  from 24/32/36px to shadcn's 40px icon default. Added aria-labels on
  9 icon-only navigation buttons.

- **Date formatting**: formatDate() for accounting data (ISO yyyy-MM-dd,
  table-friendly) vs formatDateLong() for metadata (Swedish long form).
  Raw {x.invoice_date} renderings routed through formatDate() in 18 sites.

- **Toast titles**: eliminated 33 generic "Fel" titles. Each toast title
  now carries the action ("Kunde inte skapa lönekörning" etc.) with
  description carrying the error detail.

- **Page-level cleanups**:
  - Dashboard: dropped greeting hero + Snabbåtgärder/Att hantera nav
    duplicates + Visa detaljer collapsible.
  - Reports: 5-col mega-menu replaced with left-rail layout
    (new ReportsNav component).
  - Bookkeeping: fixed layout jump between Verifikationer/Ny verifikation
    tabs (moved FiscalYearSelector inside journal tab).
  - Bookkeeping: added voucher sort (A1 first / latest first) alongside
    existing date sort. Required matching API param sort_by.
  - KPI page: FiscalYearSelector instead of raw <select>; InfoTooltip
    instead of inline info-button toggle; bigger numbers.
  - Salary section: enum values translated to Swedish labels, mobile
    table collapses to Anställd+Netto on <md, KPI typography aligned
    with dashboard.
  - Invoice forms: styled RequiredMark + aria-required, tabular-nums
    on amount inputs.

- **CLAUDE.md**: new "Design System Tokens" subsection documents the
  locked spacing scale, primitives table, typography rules, date helpers,
  and forbidden patterns so future contributors don't drift.

Tests: 2,906 passing (unchanged). Lint: unchanged from main baseline.

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

* fix: address PR review feedback (Greptile + compliance bot)

- **formatDate / formatDateLong timezone fix**: switch from new Date() to
  parseISO. Bare yyyy-MM-dd strings are now parsed as local midnight rather
  than UTC midnight, eliminating the off-by-one display in west-of-UTC
  timezones flagged by Greptile.

- **DashboardContentProps cleanup**: removed unused firstName and settings
  fields from the interface, and the corresponding fetch (profiles table)
  + computation in app/(dashboard)/page.tsx. The greeting was dropped in
  the dashboard cleanup; these props were dead weight.

- **Voucher sort behavior documented**: extended the comment in the journal
  entries API route to explain why voucher sort intentionally uses strict
  fiscal_period_id filtering (BFL 5 kap 6–7 §§ — voucher numbers are
  series-scoped within a fiscal year). The row-count delta between date
  sort and voucher sort is now a documented design choice.

- **delete_last_voucher migration + draft-delete test included**: the UI
  already shipped the "Radera utkast" path in the previous commit; this
  pulls in the backing RPC migration that allows draft deletes (with the
  full safety logic — drafts skip series/period checks since they have
  voucher_number=0, posted entries go through the existing unchanged
  path). This was originally meant for a separate PR but the UI shipped
  half the feature without it.

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

* chore(migration): rename to match applied version

The function delete_last_voucher is already applied to the production DB
under version 20260509103736 (verified via pg_get_functiondef — exact
byte-for-byte match to file content). The previous file timestamp
20260509120000 would cause a fresh `supabase db push` to attempt re-applying
under a different version row. Renaming the file aligns local tracking
with what the database actually has.

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

* fix: address compliance bot findings (payroll label + VAT visibility)

- sick_karens label: drop "(första sjukdagen)" qualifier. Per sjuklönelagen
  6 §, karensavdrag is a single calculated amount (20% of one week's
  sjuklön) deducted from the first sick day's pay — not bounded to the
  first day. The qualifier could mislead users when the first sick day
  and return-to-work span a weekend. Swedish-payroll bot recommendation.

- Omvänd skattskyldighet badge: variant outline → warning. The reverse-
  charge indicator is compliance-critical (ML 16 kap) — missing it leads
  to incorrect input VAT deduction. Outline was too subtle; warning's
  ochre fill matches its semantic weight.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:34:07 +02:00

264 lines
11 KiB
TypeScript

'use client'
import { motion } from 'framer-motion'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import { ArrowUpRight, ArrowDownRight, FileText, Loader2, Trash2 } from 'lucide-react'
import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from '@/components/ui/info-tooltip'
import { getAccountName, formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
import { getTemplateById } from '@/lib/bookkeeping/booking-templates'
import { isCounterpartyTemplateId } from '@/lib/bookkeeping/counterparty-templates'
import type { TransactionWithInvoice, CategorizeHandler } from './transaction-types'
import type { SuggestedCategory, SuggestedTemplate } from '@/lib/transactions/category-suggestions'
interface TransactionInboxCardProps {
transaction: TransactionWithInvoice
suggestions?: SuggestedCategory[]
templateSuggestions?: SuggestedTemplate[]
processingId: string | null
isBatchMode: boolean
isSelected: boolean
entityType?: string
onCategorize: CategorizeHandler
onMarkPrivate: (id: string) => void
onOpenMatchDialog: (transaction: TransactionWithInvoice) => void
onOpenCategoryDialog: (transaction: TransactionWithInvoice) => void
onDelete?: (id: string) => void
onOpenQuickReview?: (transaction: TransactionWithInvoice, suggestion: SuggestedCategory) => void
onOpenTemplateReview?: (transaction: TransactionWithInvoice, templateId: string) => void
onToggleSelect: (id: string) => void
onAnimationComplete?: (id: string) => void
}
export default function TransactionInboxCard({
transaction,
suggestions,
templateSuggestions,
processingId,
isBatchMode,
isSelected,
entityType = 'enskild_firma',
onCategorize,
onMarkPrivate,
onOpenMatchDialog,
onOpenCategoryDialog,
onDelete,
onOpenQuickReview,
onOpenTemplateReview,
onToggleSelect,
onAnimationComplete,
}: TransactionInboxCardProps) {
const isProcessing = processingId === transaction.id
const isDisabled = processingId !== null && processingId !== transaction.id
const isIncome = transaction.amount > 0
const hasInvoiceMatch = !!transaction.potential_invoice && !transaction.invoice_id
const hasSupplierInvoiceMatch = !!transaction.potential_supplier_invoice && !transaction.supplier_invoice_id
const topSuggestion = suggestions?.[0]
const isUncategorized = transaction.is_business === null && !transaction.journal_entry_id
const showCheckbox = isBatchMode && isUncategorized
const isDeletable = !transaction.journal_entry_id
function handleSuggestionClick(suggestion: SuggestedCategory) {
if (onOpenQuickReview) {
onOpenQuickReview(transaction, suggestion)
} else {
onCategorize(transaction.id, true, suggestion.category)
}
}
return (
<motion.div
layout
initial={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95, x: -16 }}
transition={{ duration: 0.25, ease: [0.25, 0.46, 0.45, 0.94] }}
onAnimationComplete={(definition) => {
// Only call on exit animation
if (typeof definition === 'object' && 'opacity' in definition && definition.opacity === 0) {
onAnimationComplete?.(transaction.id)
}
}}
>
<Card
className={cn(
'transition-colors',
hasInvoiceMatch || hasSupplierInvoiceMatch ? 'border-primary/50' : 'border-warning/50',
isSelected && 'border-primary bg-primary/[0.02]',
isDisabled && 'opacity-50'
)}
onClick={showCheckbox ? () => onToggleSelect(transaction.id) : undefined}
>
<CardContent className="py-4">
<div className="flex items-start justify-between gap-4">
{/* Left: checkbox + icon + info */}
<div className="flex items-start gap-3 min-w-0 flex-1">
{showCheckbox && (
<Checkbox
checked={isSelected}
onCheckedChange={() => onToggleSelect(transaction.id)}
onClick={(e) => e.stopPropagation()}
className="mt-1"
/>
)}
<div
className={`h-9 w-9 rounded-full flex items-center justify-center flex-shrink-0 ${isIncome ? 'bg-success/10 text-success' : 'bg-destructive/10 text-destructive'}`}
aria-hidden="true"
>
{isIncome ? (
<ArrowUpRight className="h-5 w-5" />
) : (
<ArrowDownRight className="h-5 w-5" />
)}
</div>
<div className="min-w-0">
<p className="font-medium truncate">{transaction.description}</p>
<p className="text-sm text-muted-foreground">{formatDate(transaction.date)}</p>
</div>
</div>
{/* Right: amount */}
<div className="text-right flex-shrink-0">
<p className={cn('font-medium tabular-nums', isIncome && 'text-success')}>
{isIncome ? '+' : ''}
{formatCurrency(transaction.amount, transaction.currency)}
</p>
{transaction.currency !== 'SEK' && transaction.amount_sek && (
<p className="text-sm text-muted-foreground">
{formatCurrency(transaction.amount_sek)}
</p>
)}
</div>
</div>
{/* Inline action buttons - only shown when not in batch mode */}
{!isBatchMode && (
<div className="flex flex-wrap items-center gap-2 mt-3 pt-3 border-t">
{/* Primary action: invoice match or top suggestion */}
{hasInvoiceMatch ? (
<Button
size="sm"
variant="default"
className="h-9 text-xs max-w-full truncate"
onClick={() => onOpenMatchDialog(transaction)}
disabled={isProcessing || isDisabled}
>
{isProcessing ? (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin flex-shrink-0" />
) : (
<FileText className="mr-1.5 h-3 w-3 flex-shrink-0" />
)}
Matcha Faktura {transaction.potential_invoice!.invoice_number}
</Button>
) : hasSupplierInvoiceMatch ? (
<Button
size="sm"
variant="default"
className="h-9 text-xs max-w-full truncate"
onClick={() => onOpenMatchDialog(transaction)}
disabled={isProcessing || isDisabled}
>
{isProcessing ? (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin flex-shrink-0" />
) : (
<FileText className="mr-1.5 h-3 w-3 flex-shrink-0" />
)}
Matcha Leverantörsfaktura {transaction.potential_supplier_invoice!.supplier_invoice_number}
</Button>
) : templateSuggestions && templateSuggestions.length > 0 ? (
<>
{templateSuggestions.slice(0, 2).map((ts, idx) => {
const isCounterparty = isCounterpartyTemplateId(ts.template_id)
const tmpl = isCounterparty ? null : getTemplateById(ts.template_id)
return (
<Button
key={ts.template_id}
size="sm"
variant={idx === 0 ? 'default' : 'outline'}
className="h-auto py-1.5 text-xs"
onClick={() => {
if (onOpenTemplateReview && (isCounterparty || tmpl)) {
onOpenTemplateReview(transaction, ts.template_id)
} else if (topSuggestion) {
handleSuggestionClick(topSuggestion)
}
}}
disabled={isProcessing || isDisabled}
>
<div className="flex flex-col items-start">
<div className="flex items-center">
{isProcessing && idx === 0 ? (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
) : null}
{ts.name_sv}
</div>
<span className="opacity-70 font-normal text-[10px]">
{isCounterparty
? `${ts.description_sv}`
: getAccountName(tmpl?.debit_account || ts.debit_account)
}
</span>
</div>
</Button>
)
})}
</>
) : topSuggestion ? (
<Button
size="sm"
variant="default"
className="h-9 text-xs"
onClick={() => handleSuggestionClick(topSuggestion)}
disabled={isProcessing || isDisabled}
>
{isProcessing ? (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
) : null}
{topSuggestion.label}
{topSuggestion.account && (
<span className="ml-1 opacity-70 font-normal">
({formatAccountWithName(topSuggestion.account)})
</span>
)}
{topSuggestion.confidence >= 0.8 && (
<Badge variant="secondary" className="ml-1.5 text-[10px] px-1 py-0">
{Math.round(topSuggestion.confidence * 100)}%
</Badge>
)}
</Button>
) : null}
{/* Open category dialog / template picker */}
<Button
size="sm"
variant={!hasInvoiceMatch && !hasSupplierInvoiceMatch && !topSuggestion && (!templateSuggestions || templateSuggestions.length === 0) ? 'default' : 'outline'}
className="h-9 text-xs"
onClick={() => onOpenCategoryDialog(transaction)}
disabled={isProcessing || isDisabled}
>
Välj mall...
</Button>
{/* Delete button — available for all unbooked transactions */}
{isDeletable && onDelete && (
<Button
variant="ghost"
size="icon"
className="ml-auto text-muted-foreground hover:text-destructive"
onClick={() => onDelete(transaction.id)}
disabled={isProcessing || isDisabled}
aria-label="Ta bort transaktion"
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
)}
</CardContent>
</Card>
</motion.div>
)
}