* fix(salary): align pain.001 salary file with the Swedish domestic bank dialect Verified against the Swedish Common Interpretation of ISO 20022 (Bankforeningen, Common Payment Types in Sweden, Appendix 1 Example 4: Salaries) and Nordea Corporate Access pain.001 examples v2.6 (2026-06-22), and XSD-validated against the official pain.001.001.03 schema: - drop SvcLvl SEPA (SEPA credit transfers are EUR-only; omitting SvcLvl gets the domestic NURG default) - drop RmtInf (not allowed for SALA salary payments; the beneficiary statement text comes from the Dataclearing LON code) - address employees domestically: clearing as CdtrAgt ClrSysMmbId SESBA, account WITHOUT clearing as CdtrAcct Othr with SchmeNm BBAN - share the clearing/account split (Swedbank 5-digit shift, Nordea personkonto prefix dedup) between the LB and pain.001 generators via splitDomesticBankAccount, fixing pain.001 duplicating the personkonto clearing - clamp MsgId/PmtInfId/InstrId/EndToEndId to Max35Text with the per-tx counter surviving truncation; carry the org number on Dbtr - return 400 from the pain001 route on an invalid clearing instead of emitting a broken file Also includes two unrelated decision-log lines from the parallel revisor-review session (DECISIONS.md is a shared append-only log). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(nav): surface the year-end chain in the sidebar Add Periodiseringar, Arsredovisning (aktiebolag only) and Inkomstdeklaration (INK2 for AB, NE-bilaga for EF) to the Skatt & bokslut group, in workflow order. Entity gating via a new entityOnly flag on NavItem; isActive carve-outs extended so exactly one row lights up for the new routes. Driven by an external revisor review that concluded these features did not exist because none of them were reachable from the nav. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(stripe): Stripe Connect integration behind config gate Connect OAuth per company (only the acct_ id is stored), automatic single-use Payment Links on invoice send, deterministic payment settlement against 1686 (BAS moved acquirer receivables 1580 -> 1686), payout booking with reverse-charge fees (6570 + 4535/4598 + 2645/2614), and a 15-minute sync cron. Non-deterministic events land as needs_review, never guessed at. Fully dark without STRIPE_CONNECT_CLIENT_ID: connect returns 503, the send hook and cron no-op, and the settings page shows 'Kommer snart' (hosted) until the Connect platform is verified. Self-hosted keeps the honest not-configured message. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(deadlines): add shared completeTaxDeadline and fix dead AGI deadline auto-complete generate-declaration.ts has updated non-existent columns (type/period/ status) since inception, so the arbetsgivardeklaration deadline was never auto-completed. Replace with a shared helper targeting the real schema (tax_deadline_type/tax_period/is_completed), also used by the kvittens crons and moms handlers in the follow-up commit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(rot-rut): import Skatteverket beslutsfil and record decisions on payout requests Parse the beslutsfil JSON from Skatteverkets rot/rut e-tjanst and record godkant belopp on the matching begaran: matched by stored skv_referensnummer first, then exact name among active undecided requests; arenden by fakturanummer then personnummer, exactly-one or the beslut errors (all-or-nothing). Never auto-settles: recording the beslut and booking the payout are separate acts. Exposed as an API route and the gnubok_import_rot_rut_beslut MCP tool. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(skatteverket): system auth for background reads, one-click VAT submit, kvittens notifications Hybrid auth program: system CCG (org certificate) for background reads while personal BankID stays for interactive submissions, since SKV per-flow refresh tokens live 65 min and crons structurally cannot run on them. All system-auth code sits behind SKATTEVERKET_SYSTEM_AUTH_MODE (default off) with a stub transport until the Expisoft cert and CCG avtal land; auth resolution is centralized in resolve-auth.ts. Also in this change: - One-click VAT submit chaining kontrollera -> utkast -> las server-side with a stage discriminator; step-by-step buttons demoted to the overflow menu. - Kvittens crons (AGI + new VAT schedule) with email-only notifications, deduped in notification_log under the new skv_kvittens type. - Ombud grant probe + verification UI in the connect panel, and a dashboard promo card for unconnected companies. - skatteverket_company_connections table with pg-real coverage. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(salary): auto-settle AGI tax payment from skattekonto and surface SKV reconnect on the tax card The "Skatt att betala" card only cleared via the manual mark-paid button on the run detail page; the promised automatic flip from the Skattekonto sync was never implemented, so paid periods stayed red. - settleAgiTaxPayments: during every skattekonto sync, a booked "Arbetsgivardeklaration YYYYMM" debit row settles the matching agi_declarations.tax_paid_at, but only when the amount equals the declared total to the ore and the account is not in deficit (deterministic; drift or deficit falls back to manual). - Salary overview card: reconnect hint when the SKV token needs re-consent (link to /settings/tax, silent when the extension is off), plus an inline "Markera som betald" button reusing the existing endpoint and salary_payments strings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add cloud backup scheduling and alerting features - Implement unit tests for scheduling logic in `schedule.test.ts`, covering various scenarios for determining if a backup schedule is due. - Create a new module `backup-alert.ts` to handle failure alerts for cloud backup auto-sync, including email notifications for reauthentication and repeated failures. - Introduce `schedule.ts` to manage scheduling logic, including handling local time zones and converting between local and UTC hours. - Add CSV report generation functions in `archive-csv.ts` for trial balance, income statement, balance sheet, and general ledger, ensuring compatibility with Swedish Excel formats. - Create a README generator for the archive structure in `archive-readme.ts`, providing clear documentation for users accessing backup files. - Implement tests for CSV report generation in `archive-csv.test.ts`, ensuring correct formatting and content. - Establish a full-archive coverage contract test in `full-archive-coverage.pg.test.ts` to ensure all company-scoped tables are properly classified for backup. * fix(stripe): correct invoice clearing reference and improve type safety in sync logic * fix(invoices): narrow accountingMethod before resolveInvoicePaymentSourceType settleInvoicePayment takes accountingMethod as a raw settings string, but resolveInvoicePaymentSourceType requires the 'accrual' | 'cash' union. Normalize at the call site (anything but 'cash' books as accrual), matching the existing useCashEntry semantics. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: address CodeRabbit review findings and nitpicks on PR #1004 Review findings: - backup settings redirect: always force view=export over incoming params - AGI/VAT kvittens crons: isolate best-effort post-submit calls, check the signed-state persist error, guard recovery calls in catch blocks so one company cannot abort the rest; surface grant_revoked in the run summary - kvittens notifications: atomic claim-first dedup with a partial unique index; map non-uuid reference keys to deterministic uuids - grant probe: record the actual 2xx status; mTLS transport: handle response-stream errors - stripe: amount-aware idempotency keys for payment links; emit stripe.disconnected on upstream revocations - ROT/RUT beslut import: mutate in-memory request state after apply, move item + header writes into an atomic apply_rot_rut_beslut RPC, add rot_rut_payout to JournalEntrySourceTypeSchema - migrations: use NOT VALID + VALIDATE CONSTRAINT for CHECK constraints on journal_entries, notification_log and rot_rut_payout_requests - cloud backup: hour_utc-only schedule updates clear stale hour_local Nitpicks: - stripe sync: enforce the cron time budget inside per-connection event processing with idempotent cursor progress; maybeSingle for settings; honest partial-customer DTO shared with the settlement boundary - shared applyPaymentLinkToInvoice helper for both invoice send routes, v1 docblock documents step 6b and PAYMENT_LINK_FAILED - settings panel: drop redundant decodeURIComponent - cloud backup: document worst-case archive memory headroom Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
558 lines
21 KiB
TypeScript
558 lines
21 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useCallback } from 'react'
|
|
import Link from 'next/link'
|
|
import { useRouter } from 'next/navigation'
|
|
import { useTranslations } from 'next-intl'
|
|
import { createClient } from '@/lib/supabase/client'
|
|
import { Badge } from '@/components/ui/badge'
|
|
import { Skeleton } from '@/components/ui/skeleton'
|
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
|
import { Button } from '@/components/ui/button'
|
|
import { EmptyState } from '@/components/ui/empty-state'
|
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
|
import { ArrowRight, CalendarClock, CheckCircle2, HandCoins, Loader2, Plus, UserX, Users } from 'lucide-react'
|
|
import { PageHeader } from '@/components/ui/page-header'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
|
import { useCompany } from '@/contexts/CompanyContext'
|
|
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { formatCurrency, formatDate } from '@/lib/utils'
|
|
import type { Employee, SalaryRun } from '@/types'
|
|
|
|
const supabase = createClient()
|
|
|
|
const STATUS_LABEL_KEYS: Record<string, string> = {
|
|
draft: 'status_draft',
|
|
review: 'status_review',
|
|
approved: 'status_approved',
|
|
paid: 'status_paid',
|
|
booked: 'status_booked',
|
|
corrected: 'status_corrected',
|
|
}
|
|
|
|
const STATUS_VARIANTS: Record<string, 'default' | 'secondary' | 'success' | 'warning' | 'destructive' | 'outline'> = {
|
|
draft: 'secondary',
|
|
review: 'warning',
|
|
approved: 'default',
|
|
paid: 'success',
|
|
booked: 'success',
|
|
corrected: 'outline',
|
|
}
|
|
|
|
interface TaxPaymentState {
|
|
tax_payment_file_generated_at: string | null
|
|
tax_paid_at: string | null
|
|
}
|
|
|
|
export default function SalaryPage() {
|
|
const [runs, setRuns] = useState<SalaryRun[]>([])
|
|
const [employees, setEmployees] = useState<Employee[]>([])
|
|
const [payDay, setPayDay] = useState(25)
|
|
const [agiDeadline, setAgiDeadline] = useState<{ due_date: string; title: string } | null>(null)
|
|
const [taxPayment, setTaxPayment] = useState<TaxPaymentState | null>(null)
|
|
// The Skatteverket connection previously worked but now needs re-consent:
|
|
// the skattekonto sync (which auto-settles the tax card) is paused.
|
|
const [skvNeedsReconsent, setSkvNeedsReconsent] = useState(false)
|
|
const [loading, setLoading] = useState(true)
|
|
const [starting, setStarting] = useState(false)
|
|
const [markingPaid, setMarkingPaid] = useState(false)
|
|
const { canWrite } = useCanWrite()
|
|
const { company } = useCompany()
|
|
const { toast } = useToast()
|
|
const router = useRouter()
|
|
const t = useTranslations('salary')
|
|
const tp = useTranslations('salary_payments')
|
|
|
|
const load = useCallback(async () => {
|
|
const [runsRes, empRes, settingsRes] = await Promise.all([
|
|
fetch('/api/salary/runs'),
|
|
fetch('/api/salary/employees'),
|
|
fetch('/api/settings'),
|
|
])
|
|
|
|
let loadedRuns: SalaryRun[] = []
|
|
if (runsRes.ok) {
|
|
const { data } = await runsRes.json()
|
|
loadedRuns = data || []
|
|
setRuns(loadedRuns)
|
|
}
|
|
if (empRes.ok) {
|
|
const { data } = await empRes.json()
|
|
setEmployees(data || [])
|
|
}
|
|
if (settingsRes.ok) {
|
|
const { data } = await settingsRes.json()
|
|
if (typeof data?.salary_pay_day === 'number') setPayDay(data.salary_pay_day)
|
|
}
|
|
|
|
// Latest booked run drives the "skatt att betala" card.
|
|
const latestBooked = loadedRuns.find(r => r.status === 'booked')
|
|
if (latestBooked) {
|
|
const period = `${latestBooked.period_year}-${String(latestBooked.period_month).padStart(2, '0')}`
|
|
const txRes = await fetch(`/api/skatteverket/tax-payments/${period}`)
|
|
if (txRes.ok) {
|
|
const tx = await txRes.json()
|
|
setTaxPayment(tx.data)
|
|
}
|
|
}
|
|
|
|
// Connection health for the tax card hint. Only needs_reconsent counts:
|
|
// the routine short-lived token expiry is normal and must not nag. Any
|
|
// failure (extension disabled → 503, network) silently means no hint.
|
|
try {
|
|
const statusRes = await fetch('/api/extensions/ext/skatteverket/status')
|
|
if (statusRes.ok) {
|
|
const status = await statusRes.json()
|
|
setSkvNeedsReconsent(status?.needsReconsent === true)
|
|
}
|
|
} catch {
|
|
// Extension unavailable: no hint.
|
|
}
|
|
|
|
setLoading(false)
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
load()
|
|
}, [load])
|
|
|
|
// Next open AGI deadline instance - generated by the tax-deadline engine
|
|
// when the company pays salaries; same source as the /deadlines page.
|
|
useEffect(() => {
|
|
if (!company) return
|
|
const today = new Date().toISOString().split('T')[0]
|
|
supabase
|
|
.from('deadlines')
|
|
.select('due_date, title')
|
|
.eq('company_id', company.id)
|
|
.eq('tax_deadline_type', 'arbetsgivardeklaration')
|
|
.eq('is_completed', false)
|
|
.gte('due_date', today)
|
|
.order('due_date')
|
|
.limit(1)
|
|
.maybeSingle()
|
|
.then(({ data }) => setAgiDeadline(data ?? null))
|
|
}, [company])
|
|
|
|
// One-click run creation: the API seeds all active employees, calculates,
|
|
// and resolves period/pay-date/series defaults from settings.
|
|
async function startRun() {
|
|
setStarting(true)
|
|
try {
|
|
const res = await fetch('/api/salary/runs', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: '{}',
|
|
})
|
|
const json = await res.json().catch(() => null)
|
|
if (res.status === 201 && json?.data?.id) {
|
|
router.push(`/salary/runs/${json.data.id}`)
|
|
return
|
|
}
|
|
const existingId = json?.error?.details?.existingId
|
|
if (res.status === 409 && existingId) {
|
|
toast({ title: t('run_exists_opening') })
|
|
router.push(`/salary/runs/${existingId}`)
|
|
return
|
|
}
|
|
toast({
|
|
title: t('start_run_failed'),
|
|
description: getErrorMessage(json, { context: 'salary', statusCode: res.status }),
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setStarting(false)
|
|
}
|
|
}
|
|
|
|
// Inline mark-paid on the tax card: same endpoint as TaxPaymentPanel on the
|
|
// run detail page, for users who paid Skatteverket outside the app.
|
|
async function markTaxPaid(period: string) {
|
|
setMarkingPaid(true)
|
|
try {
|
|
const res = await fetch(`/api/skatteverket/tax-payments/${period}/mark-paid`, {
|
|
method: 'POST',
|
|
})
|
|
if (!res.ok) {
|
|
const result = await res.json().catch(() => null)
|
|
toast({
|
|
title: tp('tax_mark_paid_failed_title'),
|
|
description: getErrorMessage(result, { context: 'salary', statusCode: res.status }),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
toast({ title: tp('tax_marked_paid') })
|
|
const txRes = await fetch(`/api/skatteverket/tax-payments/${period}`)
|
|
if (txRes.ok) {
|
|
const tx = await txRes.json()
|
|
setTaxPayment(tx.data)
|
|
}
|
|
} finally {
|
|
setMarkingPaid(false)
|
|
}
|
|
}
|
|
|
|
if (loading) {
|
|
// Real header renders immediately; only the data surfaces are skeletons.
|
|
return (
|
|
<div className="space-y-8">
|
|
<PageHeader
|
|
title={t('title')}
|
|
action={
|
|
<div className="flex gap-2">
|
|
<Button variant="outline" asChild>
|
|
<Link href="/salary/employees">
|
|
<Users className="mr-2 h-4 w-4" />
|
|
{t('employees')}
|
|
</Link>
|
|
</Button>
|
|
{canWrite && (
|
|
<Button disabled>
|
|
<Plus className="mr-2 h-4 w-4" />
|
|
{t('start_run')}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
}
|
|
/>
|
|
<Skeleton className="h-28 rounded-lg" />
|
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
|
{[1, 2, 3].map(i => (
|
|
<Skeleton key={i} className="h-24 rounded-lg" />
|
|
))}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// ── Hero state machine (first match wins) ────────────────────────────────
|
|
const activeRun = runs.find(r => r.status !== 'corrected')
|
|
const latestBooked = runs.find(r => r.status === 'booked')
|
|
const periodOf = (r: SalaryRun) => `${r.period_year}-${String(r.period_month).padStart(2, '0')}`
|
|
|
|
// Next period for the quiet state: month after the latest non-corrected run.
|
|
const nextPeriod = (() => {
|
|
if (!activeRun) {
|
|
const now = new Date()
|
|
return { year: now.getFullYear(), month: now.getMonth() + 1 }
|
|
}
|
|
return activeRun.period_month === 12
|
|
? { year: activeRun.period_year + 1, month: 1 }
|
|
: { year: activeRun.period_year, month: activeRun.period_month + 1 }
|
|
})()
|
|
const nextPayDate = `${nextPeriod.year}-${String(nextPeriod.month).padStart(2, '0')}-${String(payDay).padStart(2, '0')}`
|
|
|
|
type Hero =
|
|
| { kind: 'onboarding' }
|
|
| { kind: 'cta'; title: string; description: string; label: string; runId: string }
|
|
| { kind: 'quiet' }
|
|
|
|
const hero: Hero = (() => {
|
|
if (runs.length === 0 && employees.length === 0) return { kind: 'onboarding' }
|
|
if (activeRun && (activeRun.status === 'draft' || activeRun.status === 'review')) {
|
|
return {
|
|
kind: 'cta',
|
|
title: t('hero_review_title', { period: periodOf(activeRun) }),
|
|
description: t('hero_review_description', {
|
|
count: (activeRun as SalaryRun & { employees?: unknown[] }).employees?.length ?? employees.length,
|
|
net: formatCurrency(activeRun.total_net),
|
|
date: formatDate(activeRun.payment_date),
|
|
}),
|
|
label: t('hero_review_action'),
|
|
runId: activeRun.id,
|
|
}
|
|
}
|
|
if (activeRun && activeRun.status === 'approved') {
|
|
// A run that pays out nothing (nollkörning, or fully net-deducted) has no
|
|
// payment file to download - don't send the user to "pay". The real next
|
|
// step is to post it and file AGI, so shepherd them into the run instead.
|
|
const noPayout = Math.round((activeRun.total_net ?? 0) * 100) === 0
|
|
if (noPayout) {
|
|
return {
|
|
kind: 'cta',
|
|
title: t('hero_finish_title', { period: periodOf(activeRun) }),
|
|
description: t('hero_finish_description'),
|
|
label: t('hero_finish_action'),
|
|
runId: activeRun.id,
|
|
}
|
|
}
|
|
return {
|
|
kind: 'cta',
|
|
title: t('hero_pay_title', { period: periodOf(activeRun) }),
|
|
description: t('hero_pay_description', {
|
|
net: formatCurrency(activeRun.total_net),
|
|
date: formatDate(activeRun.payment_date),
|
|
}),
|
|
label: t('hero_pay_action'),
|
|
runId: activeRun.id,
|
|
}
|
|
}
|
|
if (activeRun && activeRun.status === 'paid') {
|
|
return {
|
|
kind: 'cta',
|
|
title: t('hero_book_title', { period: periodOf(activeRun) }),
|
|
description: t('hero_book_description'),
|
|
label: t('hero_book_action'),
|
|
runId: activeRun.id,
|
|
}
|
|
}
|
|
if (activeRun && activeRun.status === 'booked' && !activeRun.agi_submitted_at) {
|
|
return {
|
|
kind: 'cta',
|
|
title: t('hero_agi_title', { period: periodOf(activeRun) }),
|
|
description: t('hero_agi_description'),
|
|
label: t('hero_agi_action'),
|
|
runId: activeRun.id,
|
|
}
|
|
}
|
|
return { kind: 'quiet' }
|
|
})()
|
|
|
|
// ── Blockers: active employees missing what a run needs ──────────────────
|
|
const missingBank = employees.filter(e => !e.clearing_number || !e.bank_account_number).length
|
|
const missingEmail = employees.filter(e => !e.email).length
|
|
const blockerCount = missingBank + missingEmail
|
|
|
|
return (
|
|
<div className="space-y-8">
|
|
<PageHeader
|
|
title={t('title')}
|
|
action={
|
|
<div className="flex gap-2">
|
|
<Button variant="outline" asChild>
|
|
<Link href="/salary/employees">
|
|
<Users className="mr-2 h-4 w-4" />
|
|
{t('employees')}
|
|
</Link>
|
|
</Button>
|
|
{canWrite && (
|
|
<Button onClick={startRun} disabled={starting}>
|
|
{starting ? (
|
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
) : (
|
|
<Plus className="mr-2 h-4 w-4" />
|
|
)}
|
|
{t('start_run')}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
}
|
|
/>
|
|
|
|
{/* Hero - the one thing to do now */}
|
|
{hero.kind === 'onboarding' ? (
|
|
<Card>
|
|
<CardContent className="p-0">
|
|
<EmptyState
|
|
icon={Users}
|
|
title={t('onboarding_title')}
|
|
description={t('onboarding_description')}
|
|
actionLabel={canWrite ? t('onboarding_action') : undefined}
|
|
actionHref={canWrite ? '/salary/employees/new' : undefined}
|
|
/>
|
|
</CardContent>
|
|
</Card>
|
|
) : hero.kind === 'cta' ? (
|
|
<Card>
|
|
<CardContent className="p-6 flex flex-col md:flex-row md:items-center gap-4 justify-between">
|
|
<div className="space-y-1 min-w-0">
|
|
<h2 className="font-display text-xl md:text-2xl tracking-tight">{hero.title}</h2>
|
|
<p className="text-sm text-muted-foreground">{hero.description}</p>
|
|
</div>
|
|
<Button asChild className="shrink-0">
|
|
<Link href={`/salary/runs/${hero.runId}`}>
|
|
{hero.label}
|
|
<ArrowRight className="ml-2 h-4 w-4" />
|
|
</Link>
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
) : (
|
|
<Card>
|
|
<CardContent className="p-6 flex flex-col md:flex-row md:items-center gap-4 justify-between">
|
|
<div className="space-y-1 min-w-0">
|
|
<h2 className="font-display text-xl md:text-2xl tracking-tight">
|
|
{t('quiet_title', {
|
|
period: `${nextPeriod.year}-${String(nextPeriod.month).padStart(2, '0')}`,
|
|
})}
|
|
</h2>
|
|
<p className="text-sm text-muted-foreground">
|
|
{t('quiet_description', { date: formatDate(nextPayDate) })}
|
|
</p>
|
|
</div>
|
|
{canWrite && (
|
|
<Button variant="outline" onClick={startRun} disabled={starting} className="shrink-0">
|
|
{starting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
|
{t('quiet_action')}
|
|
</Button>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* Attention cards */}
|
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
|
<Card>
|
|
<CardContent className="p-4">
|
|
<div className="flex items-center gap-2 mb-2">
|
|
<CalendarClock className="h-4 w-4 text-muted-foreground" />
|
|
<p className="text-xs text-muted-foreground">{t('card_agi_title')}</p>
|
|
</div>
|
|
{agiDeadline ? (
|
|
<>
|
|
<p className="font-sans text-lg font-medium tabular-nums leading-tight">
|
|
{formatDate(agiDeadline.due_date)}
|
|
</p>
|
|
<Link
|
|
href="/deadlines"
|
|
className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-2"
|
|
>
|
|
{agiDeadline.title}
|
|
</Link>
|
|
</>
|
|
) : (
|
|
<p className="text-sm text-muted-foreground">{t('card_agi_none')}</p>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardContent className="p-4">
|
|
<div className="flex items-center gap-2 mb-2">
|
|
<HandCoins className="h-4 w-4 text-muted-foreground" />
|
|
<p className="text-xs text-muted-foreground">{t('card_tax_title')}</p>
|
|
</div>
|
|
{latestBooked ? (
|
|
<>
|
|
<p className="font-sans text-lg font-medium tabular-nums leading-tight">
|
|
{formatCurrency(latestBooked.total_tax + latestBooked.total_avgifter)}
|
|
</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
{taxPayment?.tax_paid_at
|
|
? t('card_tax_paid', { date: formatDate(taxPayment.tax_paid_at) })
|
|
: t('card_tax_unpaid', { period: periodOf(latestBooked) })}
|
|
</p>
|
|
{!taxPayment?.tax_paid_at && skvNeedsReconsent && (
|
|
<Link
|
|
href="/settings/tax"
|
|
className="mt-1 block text-xs text-muted-foreground hover:text-foreground underline underline-offset-2"
|
|
>
|
|
{t('card_tax_reconnect')}
|
|
</Link>
|
|
)}
|
|
{!taxPayment?.tax_paid_at && canWrite && (
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="mt-2"
|
|
onClick={() => markTaxPaid(periodOf(latestBooked))}
|
|
disabled={markingPaid}
|
|
>
|
|
{markingPaid ? (
|
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
) : (
|
|
<CheckCircle2 className="mr-2 h-4 w-4" />
|
|
)}
|
|
{tp('tax_mark_paid_button')}
|
|
</Button>
|
|
)}
|
|
</>
|
|
) : (
|
|
<p className="text-sm text-muted-foreground">{t('card_tax_none')}</p>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardContent className="p-4">
|
|
<div className="flex items-center gap-2 mb-2">
|
|
<UserX className="h-4 w-4 text-muted-foreground" />
|
|
<p className="text-xs text-muted-foreground">{t('card_blockers_title')}</p>
|
|
</div>
|
|
{blockerCount > 0 ? (
|
|
<>
|
|
<p className="font-sans text-lg font-medium tabular-nums leading-tight">
|
|
{blockerCount}
|
|
</p>
|
|
<Link
|
|
href="/salary/employees"
|
|
className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-2"
|
|
>
|
|
{t('card_blockers_detail', { bank: missingBank, email: missingEmail })}
|
|
</Link>
|
|
</>
|
|
) : (
|
|
<p className="text-sm text-muted-foreground">{t('card_blockers_none')}</p>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
|
|
{/* History */}
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">{t('runs_title')}</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="p-0">
|
|
{runs.length === 0 ? (
|
|
<EmptyState
|
|
icon={HandCoins}
|
|
title={t('empty_runs_title')}
|
|
description={t('empty_runs_description')}
|
|
actionLabel={canWrite ? t('start_run') : undefined}
|
|
onAction={canWrite ? startRun : undefined}
|
|
/>
|
|
) : (
|
|
<Table>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<TableHead>{t('th_period')}</TableHead>
|
|
<TableHead>{t('th_payday')}</TableHead>
|
|
<TableHead className="text-right">{t('th_gross')}</TableHead>
|
|
<TableHead className="text-right">{t('th_net')}</TableHead>
|
|
<TableHead className="text-right">{t('th_contributions')}</TableHead>
|
|
<TableHead>{t('th_status')}</TableHead>
|
|
<TableHead></TableHead>
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{runs.slice(0, 12).map(run => (
|
|
<TableRow key={run.id}>
|
|
<TableCell className="font-medium tabular-nums">
|
|
{periodOf(run)}
|
|
</TableCell>
|
|
<TableCell className="text-muted-foreground tabular-nums">
|
|
{formatDate(run.payment_date)}
|
|
</TableCell>
|
|
<TableCell className="text-right tabular-nums">
|
|
{formatCurrency(run.total_gross)}
|
|
</TableCell>
|
|
<TableCell className="text-right tabular-nums">
|
|
{formatCurrency(run.total_net)}
|
|
</TableCell>
|
|
<TableCell className="text-right tabular-nums">
|
|
{formatCurrency(run.total_avgifter)}
|
|
</TableCell>
|
|
<TableCell>
|
|
<Badge variant={STATUS_VARIANTS[run.status] || 'secondary'}>
|
|
{STATUS_LABEL_KEYS[run.status] ? t(STATUS_LABEL_KEYS[run.status]) : run.status}
|
|
</Badge>
|
|
</TableCell>
|
|
<TableCell className="text-right">
|
|
<Link href={`/salary/runs/${run.id}`} className="text-muted-foreground hover:text-foreground">
|
|
<ArrowRight className="h-4 w-4" />
|
|
</Link>
|
|
</TableCell>
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
)
|
|
}
|