* feat(salary): recurring payroll lines per employee (#2042) A standing per-employee payslip row derived into every salary run inside its validity window, e.g. a benefit-bike bruttolöneavdrag of -670 kr/month. Mirrors the employee_benefits pattern end to end: - employee_recurring_lines table with RLS, audit + updated_at triggers, and a salary_line_items.source_recurring_line_id back-link; amount sign and account format enforced by CHECKs - run-calculation step 8d3 derives rows with flags computed from the item type (gross deductions reduce tax + AGA bases, net deductions post-tax); derived rows are excluded from the manual-line set like benefit rows - CRUD routes under /api/salary/employees/[id]/recurring-lines with the same 401/403/404/400 contract as the benefits routes - EmployeeRecurringLinesPanel on the employee page, sv/en strings - registered in the BFL full-archive export Closes #2042 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): address #2044 review: feed recurring rows to the engine, guard deletes - Derived recurring rows are now appended to the calculateSalary lineItems set: they were inserted into salary_line_items but excluded from the in-memory calculation, so a recurring deduction never affected the payslip math (CodeRabbit, major). - DELETE deactivates a line that has derived rows instead of hard-deleting: ON DELETE SET NULL would turn a draft run's derived row into an apparent manual row that recalculation keeps forever; deactivation preserves the provenance link and lets the next recalculation drop the draft rows (CodeRabbit, major). The panel hides inactive lines. - POST employee lookup uses maybeSingle and answers 500 on lookup failure, 404 only on zero rows. - Panel: try/finally releases loading/submitting on network failure, and a request sequence guard stops a stale load from overwriting a newer list. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): move employee_recurring_lines off 20260830140000, which upstream now occupies Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): bind employee_id to company_id with a composite FK (review) The dimensions pattern: UNIQUE (id, company_id) on employees plus a composite FK, so RLS company scoping cannot be sidestepped by pointing a recurring line at another company's employee (IDOR, CWE-639). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): address review: deductions only, race-free delete, engine and pg tests Review round on #2044: - Blocker: recurring 'other' additions removed from the whitelist, the migration CHECK and the panel. calculateSalary only treats ADDITION_TYPES as additions, so a recurring taxable addition rendered on the payslip without entering gross, tax, AGA or AGI. Re-add only together with engine support (recorded in DECISIONS.md). - Delete race: salary_line_items.source_recurring_line_id is now NO ACTION instead of SET NULL; the DELETE route deletes first and falls back to deactivation on 23503, so a deletion racing a concurrent derivation can never orphan a derived row into an apparent manual row. NO ACTION defers to statement end, so company-deletion cascades are unaffected. - Correction runs copy source_benefit_id / source_recurring_line_id, so recalculating a correction no longer derives the copied rows a second time (pre-existing for benefits, now pinned). - Engine tests: gross_deduction_other through calculateSalary asserts gross, taxable income and avgifterBasis drop while the semester base stays; net_deduction_union only moves the paid-out net. - pg-real tests for the new table: RLS membership, composite FK cross-company refusal, deduction-only CHECKs, and the NO ACTION back-link blocking deletes of derived-into lines. - Nice-to-haves: POST rounds the stored amount to ore, the redundant single-column employees FK is dropped (composite carries the cascade), the schemas.ts comment references the real migration version, and the panel explains the validity-window semantics (payment date, bounds inclusive, no proration). - Rebased onto main; the phantom-columns ceiling re-measured at 395 on the merged tree. - DECISIONS.md records the vacation-basis judgment call (semester base not reduced by recurring gross deductions). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): gate recurring-line writes on the writer role, 404 unmatched deletes Two findings from the 2026-09-02 review round: - Superagent P1: the write policies were membership-only, so a read-only viewer could write recurring payroll deductions straight through PostgREST, bypassing the route's requireWrite. The table now carries aa_enforce_company_writer_role, the same gate 20260902093000 attaches to every company-scoped table (it also fires inside SECURITY DEFINER bodies, where RLS does not apply). The migration is re-versioned to 20260902140000 so the function exists when a fresh database replays the folder in order. - CodeRabbit: a filtered DELETE reports no error when nothing matches, so an unknown or cross-company line answered 200 deleted: true. The delete now selects the removed row and answers 404 when it is null. Tests: pg-real asserts a viewer is refused insert, update and delete with 42501 while the row survives unchanged, plus a non-member case; the route tests pin the 404. 896 salary tests green, rebased on main. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(salary): pin the recurring-line payload column sets Answers the phantom-column ceiling finding with scoped assertions rather than a bare ceiling raise: the PATCH route test now asserts the exact writable column set, and the comment records that the pg-real test covers the derived-row shape against the real table. Making the PATCH payload a literal would turn a partial update into last-write-wins, which is why the shape stays unresolved. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(salary): round recurring line amounts with roundOre check:guards naive-ore-round ratchet: the derived recurring row used Math.round(x * 100) / 100 (baseline 615, +1); roundOre is already imported in run-calculation.ts. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(migrations): guard the employees unique-key add against #2145 merge order #2145 (expense claims) also adds employees_id_company_id_key. Wrap this migration's ADD CONSTRAINT in an idempotent DO block so whichever of the two PRs merges second does not fail on a duplicate constraint. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
300 lines
11 KiB
TypeScript
300 lines
11 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useRef, useState } from 'react'
|
|
import { useTranslations } from 'next-intl'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Label } from '@/components/ui/label'
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from '@/components/ui/dialog'
|
|
import { DetailSection } from '@/components/ui/detail-section'
|
|
import { HelpPopover } from '@/components/ui/help-popover'
|
|
import { Skeleton } from '@/components/ui/skeleton'
|
|
import { Loader2 } from 'lucide-react'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { formatCurrency, formatDate } from '@/lib/utils'
|
|
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
|
|
|
type RecurringLineType =
|
|
| 'gross_deduction_pension'
|
|
| 'gross_deduction_other'
|
|
| 'net_deduction_union'
|
|
| 'net_deduction_benefit_payment'
|
|
| 'net_deduction_other'
|
|
|
|
interface EmployeeRecurringLine {
|
|
id: string
|
|
item_type: RecurringLineType
|
|
description: string
|
|
amount: number
|
|
account_number: string | null
|
|
valid_from: string
|
|
valid_to: string | null
|
|
metadata: Record<string, unknown>
|
|
is_active: boolean
|
|
}
|
|
|
|
// Swedish defaults written to the DB when the description is left empty:
|
|
// stored data stays Swedish regardless of the viewer's UI locale.
|
|
const LINE_LABELS: Record<RecurringLineType, string> = {
|
|
gross_deduction_pension: 'Bruttolöneavdrag pension (löneväxling)',
|
|
gross_deduction_other: 'Bruttolöneavdrag',
|
|
net_deduction_union: 'Fackavgift',
|
|
net_deduction_benefit_payment: 'Nettolöneavdrag förmån',
|
|
net_deduction_other: 'Nettolöneavdrag',
|
|
}
|
|
|
|
// In-row text action: same idiom as EmployeeBenefitsPanel.
|
|
const ROW_ACTION_CLASS =
|
|
'text-xs text-muted-foreground underline decoration-border underline-offset-4 transition-colors duration-150 hover:text-foreground hover:decoration-foreground disabled:opacity-50'
|
|
|
|
export function EmployeeRecurringLinesPanel({ employeeId, canWrite }: { employeeId: string; canWrite: boolean }) {
|
|
const t = useTranslations('salary_employee')
|
|
const { toast } = useToast()
|
|
const [lines, setLines] = useState<EmployeeRecurringLine[]>([])
|
|
const [loading, setLoading] = useState(true)
|
|
const [adding, setAdding] = useState(false)
|
|
const [submitting, setSubmitting] = useState(false)
|
|
// Monotonic request id: a reload issued after a create/delete must not be
|
|
// overwritten by an earlier, slower in-flight load resolving late.
|
|
const loadSeq = useRef(0)
|
|
|
|
const [type, setType] = useState<RecurringLineType>('gross_deduction_other')
|
|
const [description, setDescription] = useState('')
|
|
const [amount, setAmount] = useState('')
|
|
const [validFrom, setValidFrom] = useState(() => new Date().toISOString().slice(0, 10))
|
|
const [validTo, setValidTo] = useState('')
|
|
|
|
|
|
async function load() {
|
|
const seq = ++loadSeq.current
|
|
setLoading(true)
|
|
try {
|
|
const res = await fetch(`/api/salary/employees/${employeeId}/recurring-lines`)
|
|
if (res.ok) {
|
|
const { data } = await res.json()
|
|
if (seq === loadSeq.current) setLines(data || [])
|
|
}
|
|
} catch {
|
|
// Network failure: keep whatever is shown; the empty/stale list plus
|
|
// the still-enabled actions let the user retry.
|
|
} finally {
|
|
if (seq === loadSeq.current) setLoading(false)
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
load()
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [employeeId])
|
|
|
|
function reset() {
|
|
setType('gross_deduction_other')
|
|
setDescription('')
|
|
setAmount('')
|
|
setValidFrom(new Date().toISOString().slice(0, 10))
|
|
setValidTo('')
|
|
setAdding(false)
|
|
}
|
|
|
|
async function handleAdd() {
|
|
setSubmitting(true)
|
|
try {
|
|
// The field takes a positive number; every recurring line is a
|
|
// deduction and is stored negative so the payslip math reads the sign
|
|
// from the row.
|
|
const magnitude = Math.abs(parseFloat(amount) || 0)
|
|
const body: Record<string, unknown> = {
|
|
item_type: type,
|
|
description: description || LINE_LABELS[type],
|
|
amount: -magnitude,
|
|
valid_from: validFrom,
|
|
}
|
|
if (validTo) body.valid_to = validTo
|
|
|
|
const res = await fetch(`/api/salary/employees/${employeeId}/recurring-lines`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
})
|
|
|
|
if (res.ok) {
|
|
toast({ title: t('recurring_added') })
|
|
reset()
|
|
await load()
|
|
} else {
|
|
const result = await res.json()
|
|
toast({
|
|
title: t('recurring_save_failed'),
|
|
description: getErrorMessage(result, { statusCode: res.status }),
|
|
variant: 'destructive',
|
|
})
|
|
}
|
|
} catch {
|
|
toast({ title: t('recurring_save_failed'), variant: 'destructive' })
|
|
} finally {
|
|
setSubmitting(false)
|
|
}
|
|
}
|
|
|
|
async function handleDelete(id: string) {
|
|
try {
|
|
const res = await fetch(`/api/salary/employees/${employeeId}/recurring-lines/${id}`, { method: 'DELETE' })
|
|
if (res.ok) {
|
|
toast({ title: t('recurring_removed') })
|
|
await load()
|
|
} else {
|
|
toast({ title: t('recurring_remove_failed'), variant: 'destructive' })
|
|
}
|
|
} catch {
|
|
toast({ title: t('recurring_remove_failed'), variant: 'destructive' })
|
|
}
|
|
}
|
|
|
|
return (
|
|
<DetailSection
|
|
kicker={t('recurring_title')}
|
|
help={<HelpPopover>{t('recurring_help')}</HelpPopover>}
|
|
aside={
|
|
canWrite ? (
|
|
<Button type="button" size="sm" variant="outline" className="-my-1" onClick={() => setAdding(true)}>
|
|
{t('recurring_add')}
|
|
</Button>
|
|
) : undefined
|
|
}
|
|
>
|
|
{loading ? (
|
|
<div className="space-y-3">
|
|
<Skeleton className="h-4 w-full" />
|
|
<Skeleton className="h-4 w-2/3" />
|
|
</div>
|
|
) : lines.filter((l) => l.is_active).length === 0 ? (
|
|
<p className="text-sm text-muted-foreground">{t('recurring_empty')}</p>
|
|
) : (
|
|
<ul className="divide-y divide-border text-sm">
|
|
{/* Deactivated lines are hidden: "Ta bort" soft-deactivates a line
|
|
that has already been derived into a run, and showing it again
|
|
would read as the delete having failed. */}
|
|
{lines.filter((l) => l.is_active).map((l) => {
|
|
const typeLabel = t(`recurring_type_${l.item_type}`)
|
|
// The description defaults to the Swedish type label when left
|
|
// empty on creation; repeating it next to the type says nothing.
|
|
const showDescription =
|
|
!!l.description &&
|
|
l.description !== typeLabel &&
|
|
l.description !== LINE_LABELS[l.item_type]
|
|
return (
|
|
<li key={l.id} className="flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1 py-2">
|
|
<span className="min-w-0 truncate">
|
|
{typeLabel}
|
|
{showDescription && (
|
|
<span className="text-muted-foreground">{' · '}{l.description}</span>
|
|
)}
|
|
</span>
|
|
<span className="text-xs tabular-nums text-muted-foreground">
|
|
{formatDate(l.valid_from)} → {l.valid_to ? formatDate(l.valid_to) : t('recurring_ongoing')}
|
|
</span>
|
|
<span className="ml-auto tabular-nums">
|
|
{formatCurrency(l.amount)}
|
|
<span className="text-muted-foreground">{t('recurring_per_month')}</span>
|
|
</span>
|
|
{canWrite && (
|
|
<button type="button" onClick={() => handleDelete(l.id)} className={ROW_ACTION_CLASS}>
|
|
{t('recurring_remove')}
|
|
</button>
|
|
)}
|
|
</li>
|
|
)
|
|
})}
|
|
</ul>
|
|
)}
|
|
|
|
{/* Add dialog (convention 13: centered modal for create). Closing by
|
|
Escape or backdrop is the same as Avbryt; both are held while a
|
|
save is in flight. */}
|
|
<Dialog
|
|
open={adding}
|
|
onOpenChange={(open) => {
|
|
if (!open && !submitting) reset()
|
|
}}
|
|
>
|
|
<DialogContent className="sm:max-w-lg">
|
|
<DialogHeader>
|
|
<DialogTitle>{t('recurring_add')}</DialogTitle>
|
|
<DialogDescription>{t('recurring_help')}</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<div className="space-y-4">
|
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="recurring_type">{t('recurring_type')}</Label>
|
|
<Select value={type} onValueChange={(v) => setType(v as RecurringLineType)}>
|
|
<SelectTrigger id="recurring_type">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{(Object.keys(LINE_LABELS) as RecurringLineType[]).map(k => (
|
|
<SelectItem key={k} value={k}>{t(`recurring_type_${k}`)}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="recurring_description">{t('recurring_description')}</Label>
|
|
<Input
|
|
id="recurring_description"
|
|
value={description}
|
|
onChange={e => setDescription(e.target.value)}
|
|
placeholder={t(`recurring_type_${type}`)}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="recurring_amount">{t('recurring_amount_deduction')}</Label>
|
|
<Input
|
|
id="recurring_amount"
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
value={amount}
|
|
onChange={e => setAmount(e.target.value)}
|
|
placeholder={t('recurring_amount_placeholder')}
|
|
className="max-w-xs"
|
|
/>
|
|
<p className="text-xs text-muted-foreground">{t('recurring_deduction_hint')}</p>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="recurring_valid_from">{t('recurring_valid_from')}</Label>
|
|
<Input id="recurring_valid_from" type="date" value={validFrom} onChange={e => setValidFrom(e.target.value)} />
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="recurring_valid_to">{t('recurring_valid_to')}</Label>
|
|
<Input id="recurring_valid_to" type="date" value={validTo} onChange={e => setValidTo(e.target.value)} />
|
|
</div>
|
|
</div>
|
|
<p className="text-xs text-muted-foreground">{t('recurring_window_hint')}</p>
|
|
</div>
|
|
|
|
<DialogFooter>
|
|
<Button type="button" variant="outline" onClick={reset} disabled={submitting}>{t('form_cancel')}</Button>
|
|
<Button type="button" onClick={handleAdd} disabled={submitting}>
|
|
{submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
|
{t('form_save')}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
</DetailSection>
|
|
)
|
|
}
|