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
+24
View File
@@ -7306,6 +7306,30 @@
"benefits_monthly_value": "Monthly benefit value (SEK)",
"benefits_valid_from": "Valid from",
"benefits_valid_to": "Valid to (optional)",
"recurring_title": "Recurring payroll lines",
"recurring_help": "Active lines are added automatically to every salary run, e.g. a benefit-bike gross salary deduction.",
"recurring_add": "Add line",
"recurring_empty": "No recurring payroll lines.",
"recurring_ongoing": "ongoing",
"recurring_per_month": "/mo",
"recurring_remove": "Remove",
"recurring_added": "Line added",
"recurring_save_failed": "Could not save the line",
"recurring_removed": "Line removed",
"recurring_remove_failed": "Could not remove the line",
"recurring_type": "Type",
"recurring_type_gross_deduction_pension": "Gross deduction, pension (salary exchange)",
"recurring_type_gross_deduction_other": "Gross salary deduction",
"recurring_type_net_deduction_union": "Union fee",
"recurring_type_net_deduction_benefit_payment": "Net deduction, benefit co-payment",
"recurring_type_net_deduction_other": "Net salary deduction",
"recurring_description": "Description",
"recurring_amount_deduction": "Deduction per month (SEK)",
"recurring_amount_placeholder": "e.g. 670.17",
"recurring_deduction_hint": "Enter as a positive amount; it is deducted from every month's pay. Gross deductions reduce the tax and employer-fee bases; net deductions come out after tax.",
"recurring_window_hint": "The line is included in salary runs whose payment date falls inside the period (bounds inclusive). No proration for partial months.",
"recurring_valid_from": "Valid from",
"recurring_valid_to": "Valid to (optional)",
"kommun_search_placeholder": "Search municipality…",
"kommun_table_number": "Table {number}",
"kommun_load_failed": "Could not fetch the municipality list — type the municipality name and enter the tax table (skattetabell) manually.",
+24
View File
@@ -7306,6 +7306,30 @@
"benefits_monthly_value": "Månatligt förmånsvärde (SEK)",
"benefits_valid_from": "Gäller från",
"benefits_valid_to": "Gäller till (valfritt)",
"recurring_title": "Återkommande lönerader",
"recurring_help": "Aktiva rader läggs till automatiskt vid varje lönekörning, t.ex. ett bruttolöneavdrag för förmånscykel.",
"recurring_add": "Lägg till rad",
"recurring_empty": "Inga återkommande lönerader.",
"recurring_ongoing": "tills vidare",
"recurring_per_month": "/mån",
"recurring_remove": "Ta bort",
"recurring_added": "Rad tillagd",
"recurring_save_failed": "Kunde inte spara raden",
"recurring_removed": "Rad borttagen",
"recurring_remove_failed": "Kunde inte ta bort raden",
"recurring_type": "Typ",
"recurring_type_gross_deduction_pension": "Bruttolöneavdrag pension (löneväxling)",
"recurring_type_gross_deduction_other": "Bruttolöneavdrag",
"recurring_type_net_deduction_union": "Fackavgift",
"recurring_type_net_deduction_benefit_payment": "Nettolöneavdrag förmån",
"recurring_type_net_deduction_other": "Nettolöneavdrag",
"recurring_description": "Beskrivning",
"recurring_amount_deduction": "Avdrag per månad (SEK)",
"recurring_amount_placeholder": "t.ex. 670,17",
"recurring_deduction_hint": "Anges som positivt belopp och dras från lönen varje månad. Bruttolöneavdrag sänker skatte- och avgiftsunderlaget; nettolöneavdrag dras efter skatt.",
"recurring_window_hint": "Raden tas med i lönekörningar vars utbetalningsdatum ligger inom perioden (inklusive gränsdagarna). Ingen proportionering görs för delmånader.",
"recurring_valid_from": "Gäller från",
"recurring_valid_to": "Gäller till (valfritt)",
"kommun_search_placeholder": "Sök kommun…",
"kommun_table_number": "Tabell {number}",
"kommun_load_failed": "Kunde inte hämta kommunlistan — skriv kommunnamnet och ange skattetabellen manuellt.",