* 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>
130 lines
5.9 KiB
SQL
130 lines
5.9 KiB
SQL
-- Recurring payroll lines per employee (issue #2042).
|
|
--
|
|
-- A standard Swedish payroll setup is a benefit bike paid via bruttolöneavdrag:
|
|
-- the payslip carries the same signed line every month (e.g. "Förmånscykel
|
|
-- bruttolöneavdrag -670,17 kr"). employee_benefits only derives positive
|
|
-- taxable benefit rows, so recurring deductions had to be re-added by hand on
|
|
-- every run: easy to forget and silently wrong (overstated gross, tax, AGA).
|
|
--
|
|
-- This table mirrors the employee_benefits pattern: an active row inside its
|
|
-- validity window is derived into salary_line_items on every calculation,
|
|
-- marked with source_recurring_line_id so recalculation replaces derived rows
|
|
-- without touching manual ones.
|
|
|
|
-- Same-company integrity by construction (the dimensions pattern): the
|
|
-- composite FK below binds employee_id to the row's company_id, so an
|
|
-- RLS-authorized member of one company can never point a recurring line at
|
|
-- another company's employee (IDOR guard, CWE-639).
|
|
-- Idempotent: #2145 (expense claims) adds the same key, so whichever PR
|
|
-- merges second must not collide.
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM pg_constraint
|
|
WHERE conname = 'employees_id_company_id_key'
|
|
AND conrelid = 'public.employees'::regclass
|
|
) THEN
|
|
ALTER TABLE public.employees ADD CONSTRAINT employees_id_company_id_key UNIQUE (id, company_id);
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE TABLE public.employee_recurring_lines (
|
|
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
|
-- No single-column employees FK: the composite FK below carries both the
|
|
-- integrity and the cascade (the dimensions-tables convention).
|
|
employee_id uuid NOT NULL,
|
|
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
|
FOREIGN KEY (employee_id, company_id)
|
|
REFERENCES public.employees(id, company_id) ON DELETE CASCADE,
|
|
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
|
|
|
-- Reuses existing salary_line_items item types; no CHECK expansion needed
|
|
-- there. Only deductions: the engine does not treat a generic 'other'
|
|
-- addition as pay, so recurring additions are excluded until it does.
|
|
item_type text NOT NULL CHECK (item_type IN (
|
|
'gross_deduction_pension',
|
|
'gross_deduction_other',
|
|
'net_deduction_union',
|
|
'net_deduction_benefit_payment',
|
|
'net_deduction_other'
|
|
)),
|
|
description text NOT NULL,
|
|
amount numeric NOT NULL,
|
|
-- Optional BAS account override; NULL falls back to the engine's
|
|
-- LINE_ITEM_ACCOUNTS mapping for the item type.
|
|
account_number text,
|
|
|
|
valid_from date NOT NULL,
|
|
valid_to date,
|
|
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
|
is_active boolean NOT NULL DEFAULT true,
|
|
created_at timestamptz NOT NULL DEFAULT now(),
|
|
updated_at timestamptz NOT NULL DEFAULT now(),
|
|
|
|
CHECK (valid_to IS NULL OR valid_to >= valid_from),
|
|
CONSTRAINT employee_recurring_lines_amount_sign CHECK (amount < 0),
|
|
CONSTRAINT employee_recurring_lines_account_format CHECK (
|
|
account_number IS NULL OR account_number ~ '^[0-9]{4}$'
|
|
)
|
|
);
|
|
|
|
ALTER TABLE public.employee_recurring_lines ENABLE ROW LEVEL SECURITY;
|
|
|
|
CREATE POLICY "view own-company employee_recurring_lines"
|
|
ON public.employee_recurring_lines FOR SELECT
|
|
USING (company_id IN (SELECT user_company_ids()));
|
|
-- Membership predicates like every sibling table; the read-only viewer is
|
|
-- kept out by the aa_enforce_company_writer_role trigger below, which is the
|
|
-- gate 20260902093000 put on every company-scoped table (it also fires
|
|
-- inside SECURITY DEFINER bodies, where RLS does not apply).
|
|
CREATE POLICY "insert own-company employee_recurring_lines"
|
|
ON public.employee_recurring_lines FOR INSERT
|
|
WITH CHECK (company_id IN (SELECT user_company_ids()));
|
|
CREATE POLICY "update own-company employee_recurring_lines"
|
|
ON public.employee_recurring_lines FOR UPDATE
|
|
USING (company_id IN (SELECT user_company_ids()));
|
|
CREATE POLICY "delete own-company employee_recurring_lines"
|
|
ON public.employee_recurring_lines FOR DELETE
|
|
USING (company_id IN (SELECT user_company_ids()));
|
|
|
|
CREATE INDEX idx_employee_recurring_lines_company
|
|
ON public.employee_recurring_lines (company_id);
|
|
CREATE INDEX idx_employee_recurring_lines_employee
|
|
ON public.employee_recurring_lines (employee_id);
|
|
CREATE INDEX idx_employee_recurring_lines_active
|
|
ON public.employee_recurring_lines (employee_id, valid_from, valid_to)
|
|
WHERE is_active = true;
|
|
|
|
-- The table-level writer guard 20260902093000 attaches to every
|
|
-- company-scoped table: it also fires inside SECURITY DEFINER bodies, where
|
|
-- RLS does not apply. This migration is versioned after that one so the
|
|
-- function exists when a fresh database replays the folder in order.
|
|
CREATE TRIGGER aa_enforce_company_writer_role
|
|
BEFORE INSERT OR UPDATE OR DELETE ON public.employee_recurring_lines
|
|
FOR EACH ROW EXECUTE FUNCTION public.enforce_company_writer_role();
|
|
|
|
CREATE TRIGGER set_updated_at_employee_recurring_lines
|
|
BEFORE UPDATE ON public.employee_recurring_lines
|
|
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
|
|
|
|
CREATE TRIGGER audit_employee_recurring_lines
|
|
AFTER INSERT OR UPDATE OR DELETE ON public.employee_recurring_lines
|
|
FOR EACH ROW EXECUTE FUNCTION public.write_audit_log();
|
|
|
|
-- Back-link so the calculation can replace derived rows idempotently,
|
|
-- mirroring salary_line_items.source_benefit_id but with NO ACTION instead
|
|
-- of SET NULL: a deletion racing a concurrent derivation must fail (23503)
|
|
-- rather than silently orphan the derived row into an apparent manual row.
|
|
-- The DELETE route catches 23503 and falls back to deactivating the line.
|
|
-- Company deletion still cascades cleanly: NO ACTION defers the check to
|
|
-- statement end, by which time the same cascade removed both sides.
|
|
ALTER TABLE public.salary_line_items
|
|
ADD COLUMN source_recurring_line_id uuid
|
|
REFERENCES public.employee_recurring_lines(id);
|
|
|
|
CREATE INDEX idx_salary_line_items_source_recurring_line
|
|
ON public.salary_line_items (source_recurring_line_id)
|
|
WHERE source_recurring_line_id IS NOT NULL;
|
|
|
|
NOTIFY pgrst, 'reload schema';
|