* fix(salary): declare, book and pay AGI in whole kronor (SKV per-sats computation) A user's first lönekörning surfaced öre amounts in the AGI payable while Skatteverket deals in whole kronor. Three connected defects: - the AGI XML rounded amounts (Math.round); öretal bortfaller (SFF 2011:1261 22 kap. 1 §) requires truncation, and FK487 must be Skatteverket's own per-sats computation on the whole-krona underlag sums (IK587, kontroll B_006), not a truncation of the öre-exact engine sum - the salary booking credited 2731 with exact öre, leaving a residual after the whole-krona skattekonto draw; 2731 now carries the declared amount with the remainder on 3740 (Öres- och kronutjämning) - the LB payment file and TaxPaymentPanel paid/showed öre; they now use the declared whole-krona totals stored on agi_declarations (which also lets skattekonto auto-settlement match the draw); legacy öre rows keep paying öre-exact so pre-deploy bookings still clear 2731 New lib/salary/declared-avgifter.ts implements the SKV computation (per-IU whole-krona underlag, per-sats sums, youth/växa cap splits, exact integer math) shared by the AGI generator, the booking split and the preview. Review overrides route all legs through the same per-category truncation; basis overrides are inert on money totals (they never reach the filed IUs); the v1 book route gains override parity with book-run; F-skatt rows ignore avgifter overrides on every surface. Booked runs show their posted verifikat instead of a recomputed projection. tax_withheld_override requires whole kronor. Adversarially verified over three /skeptic rounds. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: merge origin/main and re-ratchet the öre-round baseline The merge brought #1609 (net-pay öresavrundning) whose two new Math.round(x*100)/100 occurrences are counted against the baseline this branch had tightened from 637 to 629; 631 keeps the net -6 improvement without policing already-merged code. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): address PR review (hybrid override computation, legacy youth cap, robustness) CodeRabbit round on #1611, all findings in one pass: - computeDeclaredAvgifterWithOverrides: one shared hybrid for the AGI generator AND the booking split. Overridden rows contribute their manual amounts per category; colleagues keep the SKV-exact per-sats underlag computation (a FoU override on one employee no longer costs the rest of the roster kronor of declared accuracy) - youth cap keys on the RESOLVED category so legacy null-category rows classified as youth by the rate heuristic still get the 25k split - F-skatt rows zero their avgifter_basis on both booking surfaces and in the preview, matching the AGI's isFSkattRow invariant - preview route: posted-voucher lookup errors return 500 instead of masquerading as a booked run with no vouchers; 400/500 tests added - run page clears stale AGI totals when the tax-payment fetch fails - SalaryOverridePanel truncates the tax override to whole kronor so the schema's .int() cannot bounce a decimal input with a 400 - v1 book route override parity pinned by a lifecycle test - DECISIONS.md format fixes + superseded entry marked; exempt category mapped explicitly; unified truncation-drift band with rationale Declined (recorded): dating the decision entries 2026-08-13 (bot assumed UTC; the decisions were made after midnight local time). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): round-2 review nits (shared F-skatt helper, test hygiene) - isFSkattStatus in declared-avgifter.ts: single source for the F-skatt exclusion, consumed by book-run, the v1 book route, the preview route and the AGI generator, per the Swedish review's drift-risk finding - declared-avgifter test suite gets the standard beforeEach cleanup Declined (recorded for the summary): auto-generated correction voucher for regenerated legacy periods (data-repair follow-up needing Emil's go); SFF 22 kap. 1 par. citation doubt (verified against lagen.nu and already shipped in tax-tables.ts); 3740 scope doubt (BAS generic utjamning account, Visma praxis, matches the user's reference voucher). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
221 lines
7.9 KiB
TypeScript
221 lines
7.9 KiB
TypeScript
'use client'
|
|
|
|
import { useCallback, useEffect, useState } from 'react'
|
|
import { useLocale, useTranslations } from 'next-intl'
|
|
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 { downloadFile } from '@/lib/browser/download-file'
|
|
import { postAction } from '@/lib/browser/post-action'
|
|
import { failureDescription } from '@/lib/browser/action-failure'
|
|
import type { ErrorLocale } from '@/lib/errors/get-error-message'
|
|
import { formatCurrency } from '@/lib/utils'
|
|
import { roundOre } from '@/lib/money'
|
|
|
|
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 t = useTranslations('salary_payments')
|
|
const locale = useLocale() as ErrorLocale
|
|
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])
|
|
|
|
// The page passes the AGI declaration's stored totals when the AGI exists
|
|
// (whole kronor for declarations generated since the whole-krona change:
|
|
// exactly what the payment file pays and Skatteverket draws), falling back
|
|
// to run totals. Display what will actually be paid: no reformatting here,
|
|
// so legacy öre declarations still show the öre-exact amount their
|
|
// payment file pays.
|
|
const totalAmount = roundOre(totalTax + totalAvgifter)
|
|
|
|
const handleDownload = useCallback(async () => {
|
|
// Both buttons are disabled while either is in flight; this guard closes the
|
|
// double-click race before React has re-rendered them. A second file for the
|
|
// same period is a second payable instruction to Skattekontot.
|
|
if (downloading || marking) return
|
|
setDownloading(true)
|
|
try {
|
|
// Bounded, and no file is written unless the server answered 2xx with a
|
|
// complete body: an error envelope saved as bg_lb_skatt_2026-04.txt is a
|
|
// file the user would upload to the bank before discovering it pays no tax.
|
|
const result = await downloadFile({
|
|
url: `/api/skatteverket/tax-payments/${period}/payment-file`,
|
|
filename: `bg_lb_skatt_${period}.txt`,
|
|
locale,
|
|
})
|
|
// Exactly one toast per outcome: TOAST_LIMIT is 1.
|
|
if (!result.ok) {
|
|
toast({
|
|
title: t('tax_download_failed_title'),
|
|
description: failureDescription(result, {
|
|
timeout: t('download_timeout'),
|
|
network: t('download_network'),
|
|
}),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
toast({ title: t('tax_downloaded') })
|
|
onChange?.()
|
|
} finally {
|
|
setDownloading(false)
|
|
}
|
|
}, [period, toast, onChange, t, locale, downloading, marking])
|
|
|
|
const handleMarkPaid = useCallback(async () => {
|
|
if (downloading || marking) return
|
|
setMarking(true)
|
|
try {
|
|
const result = await postAction({
|
|
url: `/api/skatteverket/tax-payments/${period}/mark-paid`,
|
|
locale,
|
|
})
|
|
if (!result.ok) {
|
|
toast({
|
|
title: t('tax_mark_paid_failed_title'),
|
|
description: failureDescription(result, {
|
|
// A timeout on a write is genuinely ambiguous: the update may have
|
|
// landed. Say that instead of claiming it failed.
|
|
timeout: t('tax_mark_paid_timeout'),
|
|
network: t('tax_mark_paid_network'),
|
|
}),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
toast({ title: t('tax_marked_paid') })
|
|
onChange?.()
|
|
} finally {
|
|
setMarking(false)
|
|
}
|
|
}, [period, toast, onChange, t, locale, downloading, marking])
|
|
|
|
if (totalAmount <= 0) return null
|
|
|
|
return (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">{t('tax_title')}</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">{t('tax_label_tax')}</p>
|
|
<p className="font-semibold tabular-nums">{formatCurrency(totalTax)}</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-xs text-muted-foreground">{t('tax_label_avgifter')}</p>
|
|
<p className="font-semibold tabular-nums">{formatCurrency(totalAvgifter)}</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-xs text-muted-foreground">{t('tax_label_total')}</p>
|
|
<p className="font-semibold tabular-nums">{formatCurrency(totalAmount)}</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="text-sm text-muted-foreground space-y-1">
|
|
<p>
|
|
{t('tax_recipient')} <span className="text-foreground">{t('tax_recipient_value')}</span>
|
|
</p>
|
|
<p>
|
|
{t('tax_due_date')} <span className="text-foreground tabular-nums">{paymentDeadline}</span>
|
|
</p>
|
|
<p className="text-xs">
|
|
{t('tax_ocr_note')}
|
|
</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-success" />
|
|
<div>
|
|
{t('tax_file_generated')}{' '}
|
|
<span className="text-foreground">
|
|
{new Date(paymentFileGeneratedAt).toLocaleString('sv-SE')}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{taxPaidAt && (
|
|
<div className="flex items-start gap-2 text-sm text-success">
|
|
<CheckCircle2 className="h-4 w-4 mt-0.5" />
|
|
<div>
|
|
{t('tax_marked_paid')}{' '}
|
|
<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" />
|
|
{t('tax_skattekonto_button')}
|
|
</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" />
|
|
)}
|
|
{t('tax_download_button')}
|
|
</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" />}
|
|
{t('tax_mark_paid_button')}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
)
|
|
}
|