feat(salary): recurring payroll lines per employee (#2042) (#2044)

* 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>
This commit is contained in:
Joakim Hansson
2026-09-04 16:44:45 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 50b6299699
commit 4eb1626129
19 changed files with 1741 additions and 3 deletions
+77
View File
@@ -3327,6 +3327,83 @@ export const UpdateEmployeeBenefitSchema = z.object({
}
})
export const RecurringLineItemTypeSchema = z.enum([
'gross_deduction_pension',
'gross_deduction_other',
'net_deduction_union',
'net_deduction_benefit_payment',
'net_deduction_other',
])
/** Same inclusive-bound semantics as BENEFIT_PERIOD_ORDER_MESSAGE, for
* employee_recurring_lines (migration 20260902140000). */
export const RECURRING_LINE_PERIOD_ORDER_MESSAGE =
'"Gäller till" måste vara samma dag som eller efter "Gäller från". Lämna fältet tomt för en löpande rad.'
const recurringLineAmountIssue = (
data: { item_type?: string; amount?: number },
ctx: z.RefinementCtx,
) => {
// Mirrors the employee_recurring_lines_amount_sign CHECK: every supported
// type is a deduction and must be negative. Kept in the schema so the
// violation is a field-level 400 instead of a Postgres 23514.
if (data.amount === undefined || data.item_type === undefined) return
const bad = data.amount >= 0
if (bad) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Avdragsrader måste ha negativt belopp och tilläggsrader positivt belopp.',
path: ['amount'],
})
}
}
export const CreateEmployeeRecurringLineSchema = z.object({
item_type: RecurringLineItemTypeSchema,
description: z.string().min(1).max(200),
amount: z.number(),
account_number: accountNumberSchema.optional(),
valid_from: isoDate,
valid_to: isoDate.optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
is_active: z.boolean().optional(),
}).superRefine((data, ctx) => {
recurringLineAmountIssue(data, ctx)
if (data.valid_to !== undefined && data.valid_to < data.valid_from) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: RECURRING_LINE_PERIOD_ORDER_MESSAGE,
path: ['valid_to'],
})
}
})
/** item_type is not patchable (like benefit_type): the sign rule and derived
* flags key off it, so changing kind means delete + recreate. The route
* re-checks the amount sign and merged date pair against the stored row. */
export const UpdateEmployeeRecurringLineSchema = z.object({
description: z.string().min(1).max(200).optional(),
amount: z.number().optional(),
account_number: accountNumberSchema.nullable().optional(),
valid_from: isoDate.optional(),
valid_to: isoDate.nullable().optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
is_active: z.boolean().optional(),
}).superRefine((data, ctx) => {
if (
data.valid_from !== undefined &&
data.valid_to !== undefined &&
data.valid_to !== null &&
data.valid_to < data.valid_from
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: RECURRING_LINE_PERIOD_ORDER_MESSAGE,
path: ['valid_to'],
})
}
})
export const CreateSalaryRunSchema = z.object({
period_year: z.number().int().min(2020).max(2100),
period_month: z.number().int().min(1).max(12),
+1
View File
@@ -1089,6 +1089,7 @@ export const MASTER_DATA_DUMP_TABLES: MasterDataTableSpec[] = [
// Salary (räkenskapsinformation with 7-year retention)
{ name: 'employees', file: 'employees.json', orderBy: 'created_at' },
{ name: 'employee_benefits', file: 'employee_benefits.json', orderBy: 'created_at' },
{ name: 'employee_recurring_lines', file: 'employee_recurring_lines.json', orderBy: 'created_at' },
{ name: 'salary_runs', file: 'salary_runs.json', orderBy: 'created_at' },
{ name: 'salary_run_employees', file: 'salary_run_employees.json', orderBy: 'created_at' },
{ name: 'salary_line_items', file: 'salary_line_items.json', orderBy: 'created_at' },
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi } from 'vitest'
import {
calculateSalary,
calculateKarensavdrag,
@@ -8,6 +8,7 @@ import {
prorateBaseSalaryForPeriod,
} from '../calculation-engine'
import { calculateVacationPay } from '../absence-calculator'
import { recurringLineFlags } from '../recurring-lines'
import type { PayrollConfig } from '../payroll-config'
import type { TaxTableRate } from '../tax-tables'
@@ -1493,3 +1494,66 @@ describe('öresavrundning (roundNetToWholeKrona)', () => {
)
})
})
describe('recurring line flags through the engine', () => {
// Pins the payroll math for derived recurring rows: the flags produced by
// recurringLineFlags must actually move gross, the tax base and the AGA
// base when run through calculateSalary (regression guard for #2044).
it('a recurring gross deduction reduces gross, tax base and AGA base, not the semester base', () => {
const flags = recurringLineFlags('gross_deduction_other')
const base = calculateSalary(makeBasicInput(), config2026, emptyTaxRates)
const withDeduction = calculateSalary(
makeBasicInput({
lineItems: [
{
itemType: 'gross_deduction_other' as const,
amount: -500,
isTaxable: flags.is_taxable,
isAvgiftBasis: flags.is_avgift_basis,
isVacationBasis: flags.is_vacation_basis,
isGrossDeduction: flags.is_gross_deduction,
isNetDeduction: flags.is_net_deduction,
},
],
}),
config2026,
emptyTaxRates,
)
expect(withDeduction.grossDeductions).toBe(500)
expect(withDeduction.grossSalary).toBe(base.grossSalary - 500)
expect(withDeduction.taxableIncome).toBe(base.taxableIncome - 500)
expect(withDeduction.avgifterBasis).toBe(base.avgifterBasis - 500)
expect(withDeduction.avgifterAmount).toBeLessThan(base.avgifterAmount)
// The DECISIONS.md judgment call: the semester base stays untouched.
expect(withDeduction.vacationAccrual).toBe(base.vacationAccrual)
})
it('a recurring net deduction reduces only the paid-out net', () => {
const flags = recurringLineFlags('net_deduction_union')
const base = calculateSalary(makeBasicInput(), config2026, emptyTaxRates)
const withDeduction = calculateSalary(
makeBasicInput({
lineItems: [
{
itemType: 'net_deduction_union' as const,
amount: -300,
isTaxable: flags.is_taxable,
isAvgiftBasis: flags.is_avgift_basis,
isVacationBasis: flags.is_vacation_basis,
isGrossDeduction: flags.is_gross_deduction,
isNetDeduction: flags.is_net_deduction,
},
],
}),
config2026,
emptyTaxRates,
)
expect(withDeduction.grossSalary).toBe(base.grossSalary)
expect(withDeduction.taxableIncome).toBe(base.taxableIncome)
expect(withDeduction.avgifterBasis).toBe(base.avgifterBasis)
expect(withDeduction.netDeductions).toBe(300)
expect(withDeduction.netSalary).toBe(base.netSalary - 300)
})
})
@@ -0,0 +1,73 @@
import { describe, it, expect } from 'vitest'
import {
RECURRING_LINE_ITEM_TYPES,
RECURRING_LINE_AMOUNT_SIGN_MESSAGE,
recurringLineFlags,
validateRecurringLineAmount,
} from '../recurring-lines'
describe('recurringLineFlags', () => {
it('marks gross deductions as taxable, avgift-basis gross deductions', () => {
for (const t of ['gross_deduction_pension', 'gross_deduction_other'] as const) {
expect(recurringLineFlags(t)).toEqual({
is_taxable: true,
is_avgift_basis: true,
is_vacation_basis: false,
is_gross_deduction: true,
is_net_deduction: false,
})
}
})
it('marks net deductions as after-tax only', () => {
for (const t of [
'net_deduction_union',
'net_deduction_benefit_payment',
'net_deduction_other',
] as const) {
expect(recurringLineFlags(t)).toEqual({
is_taxable: false,
is_avgift_basis: false,
is_vacation_basis: false,
is_gross_deduction: false,
is_net_deduction: true,
})
}
})
it('every supported type is a deduction with exactly one deduction flag set', () => {
// 'other' (recurring addition) is deliberately absent: the engine does
// not treat generic taxable rows as additions, see recurring-lines.ts.
expect(RECURRING_LINE_ITEM_TYPES).not.toContain('other')
for (const t of RECURRING_LINE_ITEM_TYPES) {
const flags = recurringLineFlags(t)
expect(flags.is_gross_deduction && flags.is_net_deduction).toBe(false)
expect(flags.is_gross_deduction || flags.is_net_deduction).toBe(true)
}
})
})
describe('validateRecurringLineAmount', () => {
it('requires deductions to be negative', () => {
expect(validateRecurringLineAmount('gross_deduction_other', -670.17)).toBeNull()
expect(validateRecurringLineAmount('gross_deduction_other', 670.17)).toBe(
RECURRING_LINE_AMOUNT_SIGN_MESSAGE,
)
expect(validateRecurringLineAmount('net_deduction_union', -100)).toBeNull()
expect(validateRecurringLineAmount('net_deduction_union', 100)).toBe(
RECURRING_LINE_AMOUNT_SIGN_MESSAGE,
)
})
it('never accepts zero, positive or non-finite amounts', () => {
expect(validateRecurringLineAmount('gross_deduction_other', 0)).toBe(
RECURRING_LINE_AMOUNT_SIGN_MESSAGE,
)
expect(validateRecurringLineAmount('net_deduction_other', Number.NaN)).toBe(
RECURRING_LINE_AMOUNT_SIGN_MESSAGE,
)
expect(validateRecurringLineAmount('gross_deduction_pension', Number.POSITIVE_INFINITY)).toBe(
RECURRING_LINE_AMOUNT_SIGN_MESSAGE,
)
})
})
+85
View File
@@ -0,0 +1,85 @@
import type { SalaryLineItemType } from '@/types'
/**
* Recurring payroll lines (issue #2042): standing per-employee payslip rows
* derived into every salary run inside their validity window, e.g. a benefit
* bike bruttolöneavdrag of -670,17 kr/month.
*
* This module is pure: item-type whitelist, flag derivation and amount-sign
* validation. The DB derivation lives in run-calculation.ts (step 8d3) and
* mirrors the employee_benefits step 8d lifecycle via
* salary_line_items.source_recurring_line_id.
*/
/** Item types a recurring line may use. Mirrors the table CHECK constraint. */
export const RECURRING_LINE_ITEM_TYPES = [
'gross_deduction_pension',
'gross_deduction_other',
'net_deduction_union',
'net_deduction_benefit_payment',
'net_deduction_other',
] as const satisfies readonly SalaryLineItemType[]
export type RecurringLineItemType = (typeof RECURRING_LINE_ITEM_TYPES)[number]
export interface RecurringLineFlags {
is_taxable: boolean
is_avgift_basis: boolean
is_vacation_basis: boolean
is_gross_deduction: boolean
is_net_deduction: boolean
}
/**
* Derive the salary_line_items flags from the item type instead of storing
* them: a gross deduction that is not tax-reducing (or a net deduction that
* is) cannot be expressed, so the payslip math stays consistent by
* construction.
*
* Gross deductions carry the sick-karens convention: negative amount with
* is_taxable + is_avgift_basis true, so they reduce both the tax base and the
* arbetsgivaravgift base. Net deductions only move money after tax. Neither
* touches the semester base (is_vacation_basis false on the deduction row:
* the loneväxling-style choice recorded in DECISIONS.md).
*
* Recurring ADDITIONS ('other') are deliberately not supported: the engine's
* calculateSalary only treats ADDITION_TYPES as additions and never reads a
* generic taxable row into gross/tax/AGA, so a recurring 'other' would show
* on the payslip without being paid or declared. Teach the engine first.
*/
export function recurringLineFlags(itemType: RecurringLineItemType): RecurringLineFlags {
if (itemType === 'gross_deduction_pension' || itemType === 'gross_deduction_other') {
return {
is_taxable: true,
is_avgift_basis: true,
is_vacation_basis: false,
is_gross_deduction: true,
is_net_deduction: false,
}
}
return {
is_taxable: false,
is_avgift_basis: false,
is_vacation_basis: false,
is_gross_deduction: false,
is_net_deduction: true,
}
}
/** Shared 400 copy: schema, route backstop and UI hint say the same thing. */
export const RECURRING_LINE_AMOUNT_SIGN_MESSAGE =
'Återkommande rader är avdrag och måste ha negativt belopp.'
/**
* Validate the amount sign for an item type. Returns an error message or
* null. Mirrors the employee_recurring_lines_amount_sign CHECK so bad input
* is a 400 with field-level feedback rather than a Postgres 23514.
*/
export function validateRecurringLineAmount(
itemType: RecurringLineItemType,
amount: number,
): string | null {
void itemType // every supported type is a deduction; kept for call-site shape
if (!Number.isFinite(amount) || amount >= 0) return RECURRING_LINE_AMOUNT_SIGN_MESSAGE
return null
}
+78 -1
View File
@@ -31,6 +31,7 @@ import { loadPayrollConfig, serializePayrollConfig } from './payroll-config'
import { fetchAllTaxTableRatesForRun, TaxTableUnavailableError } from './tax-tables'
import { loadAndDeriveAbsence } from './derive-absence-line-items'
import { getLineItemAccount } from './account-mapping'
import { recurringLineFlags, type RecurringLineItemType } from './recurring-lines'
import { computePremiumLines } from './shift-premium-engine'
import { roundOre } from '@/lib/money'
import { computePriorYtd, loadOpeningBalances } from './ytd'
@@ -502,6 +503,66 @@ export async function runSalaryCalculation(
}
}
// 8d3. Derive recurring line items from employee_recurring_lines: same
// lifecycle as the benefit rows (delete by back-link, re-derive for
// rows whose validity window covers the payment date). Flags come
// from the item type so a stored row can never contradict the
// payslip math.
// valid_to is filtered in JS rather than with a dynamic .or() so the
// phantom-column scanner can resolve every expression in this query.
const { data: recurringRows, error: recurringErr } = await supabase
.from('employee_recurring_lines')
.select('id, item_type, description, amount, account_number, valid_to')
.eq('employee_id', emp.id)
.eq('company_id', companyId)
.eq('is_active', true)
.lte('valid_from', run.payment_date)
if (recurringErr) {
return { ok: false, code: 'DATABASE_ERROR', details: recurringErr }
}
const activeRecurring = (recurringRows ?? []).filter(
(r) => !r.valid_to || r.valid_to >= run.payment_date,
)
const { error: delRecurringErr } = await supabase
.from('salary_line_items')
.delete()
.eq('salary_run_employee_id', sre.id)
.not('source_recurring_line_id', 'is', null)
if (delRecurringErr) {
return { ok: false, code: 'DATABASE_ERROR', details: delRecurringErr }
}
const derivedRecurringRows = activeRecurring.map((r, idx) => {
const itemType = r.item_type as RecurringLineItemType
const flags = recurringLineFlags(itemType)
return {
salary_run_employee_id: sre.id,
company_id: companyId,
item_type: itemType,
description: r.description,
quantity: 1,
amount: roundOre(r.amount),
is_taxable: flags.is_taxable,
is_avgift_basis: flags.is_avgift_basis,
is_vacation_basis: flags.is_vacation_basis,
is_gross_deduction: flags.is_gross_deduction,
is_net_deduction: flags.is_net_deduction,
account_number: r.account_number || getLineItemAccount(itemType, emp.employment_type),
sort_order: 250 + idx,
source_recurring_line_id: r.id,
}
})
if (derivedRecurringRows.length > 0) {
const { error: insRecurringErr } = await supabase
.from('salary_line_items')
.insert(derivedRecurringRows)
if (insRecurringErr) {
return { ok: false, code: 'DATABASE_ERROR', details: insRecurringErr }
}
}
if (absenceResult.lineItems.length > 0) {
const rows = absenceResult.lineItems.map((li, idx) => ({
salary_run_employee_id: sre.id,
@@ -606,6 +667,7 @@ export async function runSalaryCalculation(
if (DERIVED_ABSENCE_TYPES.includes(li.item_type as SalaryLineItemType)) return false
if (DERIVED_PREMIUM_TYPES.includes(li.item_type as ShiftPremiumItemType)) return false
if (li.source_benefit_id) return false
if (li.source_recurring_line_id) return false
if (li.item_type === 'semesterersattning') return false
if (li.item_type === 'oresavrundning') return false
return true
@@ -646,7 +708,22 @@ export async function runSalaryCalculation(
isGrossDeduction: false,
isNetDeduction: false,
}))
const lineItems = [...manualLineItems, ...derivedLineItems, ...derivedBenefitLineItems, ...derivedPremiumLineItems]
const derivedRecurringLineItems = derivedRecurringRows.map((row) => ({
itemType: row.item_type as SalaryLineItemType,
amount: row.amount,
isTaxable: row.is_taxable,
isAvgiftBasis: row.is_avgift_basis,
isVacationBasis: row.is_vacation_basis,
isGrossDeduction: row.is_gross_deduction,
isNetDeduction: row.is_net_deduction,
}))
const lineItems = [
...manualLineItems,
...derivedLineItems,
...derivedBenefitLineItems,
...derivedPremiumLineItems,
...derivedRecurringLineItems,
]
// 8f. Run the engine for this employee.
const result = calculateSalary(