Files
accounted/components/salary/TaxPaymentPanel.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

198 lines
6.7 KiB
TypeScript

'use client'
import { useCallback, useEffect, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Download, Loader2, CheckCircle2, ExternalLink } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { formatCurrency } from '@/lib/utils'
interface TaxPaymentPanelProps {
/** YYYY-MM */
period: string
totalTax: number
totalAvgifter: number
paymentFileGeneratedAt: string | null
taxPaidAt: string | null
readOnly?: boolean
onChange?: () => void
}
/**
* Generates a Bankgirot LB-fil for paying skatt + arbetsgivaravgifter for an
* AGI period to Skatteverket Bankgiro 5050-1055 with the company's
* Skattekontot OCR.
*/
export function TaxPaymentPanel({
period,
totalTax,
totalAvgifter,
paymentFileGeneratedAt,
taxPaidAt,
readOnly,
onChange,
}: TaxPaymentPanelProps) {
const { toast } = useToast()
const [downloading, setDownloading] = useState(false)
const [marking, setMarking] = useState(false)
const [paymentDeadline, setPaymentDeadline] = useState<string>('')
useEffect(() => {
const m = /^(\d{4})-(\d{2})$/.exec(period)
if (!m) return
const year = parseInt(m[1], 10)
const month = parseInt(m[2], 10)
const dlMonth = month === 12 ? 1 : month + 1
const dlYear = month === 12 ? year + 1 : year
setPaymentDeadline(`${dlYear}-${String(dlMonth).padStart(2, '0')}-12`)
}, [period])
const totalAmount = Math.round((totalTax + totalAvgifter) * 100) / 100
const handleDownload = useCallback(async () => {
setDownloading(true)
try {
const res = await fetch(`/api/skatteverket/tax-payments/${period}/payment-file`)
if (!res.ok) {
const result = await res.json().catch(() => ({ error: 'Kunde inte generera betalfil' }))
toast({
title: 'Betalfil kunde inte genereras',
description: getErrorMessage(result, { context: 'salary', statusCode: res.status }),
variant: 'destructive',
})
return
}
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `bg_lb_skatt_${period}.txt`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
toast({ title: 'Betalfil för skatt nedladdad' })
onChange?.()
} finally {
setDownloading(false)
}
}, [period, toast, onChange])
const handleMarkPaid = useCallback(async () => {
setMarking(true)
try {
const res = await fetch(`/api/skatteverket/tax-payments/${period}/mark-paid`, {
method: 'POST',
})
if (!res.ok) {
const result = await res.json().catch(() => ({ error: 'Kunde inte markera som betald' }))
toast({
title: 'Kunde inte markera som betald',
description: getErrorMessage(result, { context: 'salary', statusCode: res.status }),
variant: 'destructive',
})
return
}
toast({ title: 'Markerad som betald' })
onChange?.()
} finally {
setMarking(false)
}
}, [period, toast, onChange])
if (totalAmount <= 0) return null
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Inbetalning till Skattekontot</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 sm:grid-cols-3 gap-4 text-sm">
<div>
<p className="text-xs text-muted-foreground">Skatt</p>
<p className="font-semibold tabular-nums">{formatCurrency(totalTax)}</p>
</div>
<div>
<p className="text-xs text-muted-foreground">Arbetsgivaravgifter</p>
<p className="font-semibold tabular-nums">{formatCurrency(totalAvgifter)}</p>
</div>
<div>
<p className="text-xs text-muted-foreground">Totalt att betala</p>
<p className="font-semibold tabular-nums">{formatCurrency(totalAmount)}</p>
</div>
</div>
<div className="text-sm text-muted-foreground space-y-1">
<p>
Mottagare: <span className="text-foreground">Skatteverket Bankgiro 5050-1055</span>
</p>
<p>
Förfallodag: <span className="text-foreground tabular-nums">{paymentDeadline}</span>
</p>
<p className="text-xs">
Betalfil använder ditt Skattekonto-OCR (org-nummer + Luhn-kontrollsiffra). Skatteverket
applicerar betalningen på det belopp du deklarerat i AGI för perioden.
</p>
</div>
{paymentFileGeneratedAt && (
<div className="flex items-start gap-2 text-sm text-muted-foreground">
<CheckCircle2 className="h-4 w-4 mt-0.5 text-emerald-600 dark:text-emerald-400" />
<div>
Betalfil senast genererad{' '}
<span className="text-foreground">
{new Date(paymentFileGeneratedAt).toLocaleString('sv-SE')}
</span>
</div>
</div>
)}
{taxPaidAt && (
<div className="flex items-start gap-2 text-sm text-emerald-700 dark:text-emerald-400">
<CheckCircle2 className="h-4 w-4 mt-0.5" />
<div>
Markerad som betald{' '}
<span className="font-medium">{new Date(taxPaidAt).toLocaleString('sv-SE')}</span>
</div>
</div>
)}
{!readOnly && (
<div className="flex flex-wrap justify-end gap-2">
<Button variant="outline" size="sm" asChild>
<a
href="https://www.skatteverket.se/foretag/skatterochavdrag/skattekonto.4.18e1b10334ebe8bc80004481.html"
target="_blank"
rel="noopener noreferrer"
>
<ExternalLink className="mr-2 h-4 w-4" />
Skattekontot
</a>
</Button>
<Button onClick={handleDownload} disabled={downloading || marking}>
{downloading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Download className="mr-2 h-4 w-4" />
)}
Ladda ner betalfil
</Button>
{!taxPaidAt && (
<Button
variant="outline"
onClick={handleMarkPaid}
disabled={downloading || marking}
>
{marking ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <CheckCircle2 className="mr-2 h-4 w-4" />}
Markera som betald
</Button>
)}
</div>
)}
</CardContent>
</Card>
)
}