* 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>
246 lines
8.2 KiB
TypeScript
246 lines
8.2 KiB
TypeScript
'use client'
|
|
|
|
import { useState } from 'react'
|
|
import { useTranslations } from 'next-intl'
|
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Label } from '@/components/ui/label'
|
|
import { Textarea } from '@/components/ui/textarea'
|
|
import { Badge } from '@/components/ui/badge'
|
|
import { Settings2, Loader2 } from 'lucide-react'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { formatCurrency } from '@/lib/utils'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
|
|
interface SalaryOverridePanelProps {
|
|
runId: string
|
|
employeeId: string
|
|
taxWithheld: number
|
|
taxOverride: number | null
|
|
avgifterAmount: number
|
|
avgifterOverride: number | null
|
|
avgifterBasis: number
|
|
avgifterBasisOverride: number | null
|
|
reason: string | null
|
|
onSaved: () => void
|
|
disabled?: boolean
|
|
}
|
|
|
|
function num(v: string): number | null {
|
|
const trimmed = v.trim()
|
|
if (!trimmed) return null
|
|
const n = Number(trimmed.replace(',', '.'))
|
|
return Number.isFinite(n) ? n : null
|
|
}
|
|
|
|
export function SalaryOverridePanel(props: SalaryOverridePanelProps) {
|
|
const t = useTranslations('salary_override')
|
|
const { toast } = useToast()
|
|
const [expanded, setExpanded] = useState(
|
|
props.taxOverride !== null ||
|
|
props.avgifterOverride !== null ||
|
|
props.avgifterBasisOverride !== null,
|
|
)
|
|
const [taxStr, setTaxStr] = useState(props.taxOverride !== null ? String(props.taxOverride) : '')
|
|
const [avgStr, setAvgStr] = useState(
|
|
props.avgifterOverride !== null ? String(props.avgifterOverride) : '',
|
|
)
|
|
const [basisStr, setBasisStr] = useState(
|
|
props.avgifterBasisOverride !== null ? String(props.avgifterBasisOverride) : '',
|
|
)
|
|
const [reason, setReason] = useState(props.reason ?? '')
|
|
const [saving, setSaving] = useState(false)
|
|
|
|
const hasOverride =
|
|
props.taxOverride !== null ||
|
|
props.avgifterOverride !== null ||
|
|
props.avgifterBasisOverride !== null
|
|
|
|
async function handleSave() {
|
|
setSaving(true)
|
|
try {
|
|
// Skatteavdrag is stated in whole kronor (öretal bortfaller): the
|
|
// schema rejects öre, so drop them here instead of bouncing the save
|
|
// with a 400 when someone types a decimal.
|
|
const taxOverride = num(taxStr)
|
|
const body = {
|
|
tax_withheld_override: taxOverride === null ? null : Math.trunc(taxOverride),
|
|
avgifter_amount_override: num(avgStr),
|
|
avgifter_basis_override: num(basisStr),
|
|
reason: reason.trim() || null,
|
|
}
|
|
const res = await fetch(`/api/salary/runs/${props.runId}/employees/${props.employeeId}`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
})
|
|
const data = await res.json()
|
|
if (!res.ok) {
|
|
toast({
|
|
title: t('save_failed'),
|
|
description: typeof data?.error === 'string' ? data.error : t('unknown_error'),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
toast({ title: t('saved') })
|
|
props.onSaved()
|
|
} catch (err) {
|
|
toast({
|
|
title: t('save_failed'),
|
|
description: err instanceof Error ? getUserErrorMessage(err) : t('unknown_error'),
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setSaving(false)
|
|
}
|
|
}
|
|
|
|
async function handleClear() {
|
|
setSaving(true)
|
|
try {
|
|
const res = await fetch(`/api/salary/runs/${props.runId}/employees/${props.employeeId}`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
tax_withheld_override: null,
|
|
avgifter_amount_override: null,
|
|
avgifter_basis_override: null,
|
|
reason: null,
|
|
}),
|
|
})
|
|
if (!res.ok) {
|
|
const data = await res.json()
|
|
toast({
|
|
title: t('clear_failed'),
|
|
description: typeof data?.error === 'string' ? data.error : t('unknown_error'),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
setTaxStr('')
|
|
setAvgStr('')
|
|
setBasisStr('')
|
|
setReason('')
|
|
toast({ title: t('cleared') })
|
|
props.onSaved()
|
|
} finally {
|
|
setSaving(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Card>
|
|
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
|
<div className="flex items-center gap-2">
|
|
<CardTitle className="text-base">{t('title')}</CardTitle>
|
|
{hasOverride && <Badge variant="warning">{t('adjusted_badge')}</Badge>}
|
|
</div>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => setExpanded((v) => !v)}
|
|
disabled={props.disabled}
|
|
>
|
|
<Settings2 className="mr-1.5 h-3.5 w-3.5" />
|
|
{expanded ? t('hide') : t('show')}
|
|
</Button>
|
|
</CardHeader>
|
|
{expanded && (
|
|
<CardContent className="space-y-4">
|
|
<p className="text-xs text-muted-foreground">
|
|
{t('description')}
|
|
</p>
|
|
|
|
<div className="grid gap-4 sm:grid-cols-3">
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="tax_override" className="text-xs">
|
|
{t('tax_label')}
|
|
</Label>
|
|
<Input
|
|
id="tax_override"
|
|
inputMode="decimal"
|
|
placeholder={String(props.taxWithheld)}
|
|
value={taxStr}
|
|
onChange={(e) => setTaxStr(e.target.value)}
|
|
disabled={props.disabled || saving}
|
|
className="tabular-nums"
|
|
/>
|
|
<p className="text-[11px] text-muted-foreground">
|
|
{t('calculated')} <span className="tabular-nums">{formatCurrency(props.taxWithheld)}</span>
|
|
</p>
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="avgifter_override" className="text-xs">
|
|
{t('avgifter_label')}
|
|
</Label>
|
|
<Input
|
|
id="avgifter_override"
|
|
inputMode="decimal"
|
|
placeholder={String(props.avgifterAmount)}
|
|
value={avgStr}
|
|
onChange={(e) => setAvgStr(e.target.value)}
|
|
disabled={props.disabled || saving}
|
|
className="tabular-nums"
|
|
/>
|
|
<p className="text-[11px] text-muted-foreground">
|
|
{t('calculated')} <span className="tabular-nums">{formatCurrency(props.avgifterAmount)}</span>
|
|
</p>
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="avgifter_basis_override" className="text-xs">
|
|
{t('basis_label')}
|
|
</Label>
|
|
<Input
|
|
id="avgifter_basis_override"
|
|
inputMode="decimal"
|
|
placeholder={String(props.avgifterBasis)}
|
|
value={basisStr}
|
|
onChange={(e) => setBasisStr(e.target.value)}
|
|
disabled={props.disabled || saving}
|
|
className="tabular-nums"
|
|
/>
|
|
<p className="text-[11px] text-muted-foreground">
|
|
{t('calculated')} <span className="tabular-nums">{formatCurrency(props.avgifterBasis)}</span>
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="override_reason" className="text-xs">
|
|
{t('reason_label')}
|
|
</Label>
|
|
<Textarea
|
|
id="override_reason"
|
|
rows={2}
|
|
placeholder={t('reason_placeholder')}
|
|
value={reason}
|
|
onChange={(e) => setReason(e.target.value)}
|
|
disabled={props.disabled || saving}
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button onClick={handleSave} disabled={props.disabled || saving}>
|
|
{saving && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
|
{t('save')}
|
|
</Button>
|
|
{hasOverride && (
|
|
<Button
|
|
variant="outline"
|
|
onClick={handleClear}
|
|
disabled={props.disabled || saving}
|
|
>
|
|
{t('clear')}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</CardContent>
|
|
)}
|
|
</Card>
|
|
)
|
|
}
|