Files
accounted/supabase/migrations/20260526120900_ob_overtime_premiums.sql
Mattsson 32d9978f1b Fix/chrome pdf preview csp (#572)
* feat: add option to exclude year-end closing entries in SIE export and related reports

* delete docs

* fix: allow Chrome's PDF viewer in verifikat document preview

The /api/documents/:id/inline route shipped with
`object-src 'none'` in its CSP, which blocked Chrome's built-in PDF
viewer (it renders inline PDFs via an internal <embed>). Users on
Chrome saw "Det här innehållet har blockerats" when expanding a PDF
attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own
viewer) were unaffected, and JPGs worked because <img> isn't subject
to object-src.

Drops the CSP for this route to the minimum needed for embeddability:
`frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the
fixed Content-Type from the handler already block MIME confusion;
X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(auth): add webmail deep link to email confirmation screens

Mirrors Stripe's signup UX: after asking the user to verify their email,
detect their webmail provider from the domain and show a button that
opens the inbox in a new tab. Gmail gets a from:<sender> search
pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly.
Unknown / custom domains fall back to the existing copy.

Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM
(default noreply@gnubok.se) so white-label installs can match their
Supabase Auth SMTP config.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(auth): unblock first-time password set for BankID users with MFA

Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session
is required" whenever a TOTP factor is enrolled. BankID magic-link logins
produce AAL1, and middleware skips MFA enforcement for bankid_linked users,
so they had no path to AAL2 — leaving them unable to set a backup password
or disable MFA without going through the email-recovery escape hatch.

- /api/account/password: branch on app_metadata.has_password. First-time set
  writes via service.auth.admin.updateUserById (no existing credential to
  protect, AAL2 guard does not apply). Change-password keeps the user-session
  updateUser so AAL2 still fires for credential rotation.
- /mfa/verify: accept a safeReturnTo query param and route there after
  successful verify, so step-up flows can land back where they came from.
- SecuritySettings: detect the AAL2 error from both change-password and
  mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account
  instead of toasting a dead-end error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Add tests and rounding utility for öre precision in bokslut calculations

- Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations.
- Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries.
- Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency.
- Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies.
- Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios.

* fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility

* fix: enhance security by rejecting data URIs in safeReturnTo function tests

* fix: improve rounding logic in roundOre function and add customer_type migration

* fix: add customer_type column to customers and enforce CHECK constraint

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 22:29:41 +02:00

117 lines
5.8 KiB
SQL
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- =============================================================================
-- OB-tillägg & övertid: shift-premium automation
-- =============================================================================
--
-- Adds:
-- 1. New salary_line_items.item_type values for shift premiums (OB) and
-- tiered overtime (övertid 50 %/100 %).
-- 2. Optional start_time / end_time columns on salary_worked_days so the
-- calculator can match per-shift windows against premium rules. Legacy
-- rows (NULL times) fall back to a default-shift assumption inside the
-- engine (08:0017:00) — pure-night/weekend rules will not trigger for
-- hours-only days, which mirrors how those rows were intended to behave
-- before this migration.
-- 3. shift_premium_rules — per-company configuration of when and how much
-- to top up the base hourly rate. Either applies to all employees or a
-- filtered list. Multiple rules may match a shift; the engine prefers
-- higher priority and tie-breaks on higher premium_percent. ISO weekday
-- encoding (1 = Monday … 7 = Sunday) matches PostgreSQL's
-- extract(isodow from date), so server-side queries can filter natively.
--
-- CHECK migration note: the new item_type CHECK preserves every existing
-- value (including gross_deduction_*, net_deduction_advance/benefit_payment,
-- semesterersattning, benefit_bike). Adding values without listing the
-- originals would drop rows on commit.
ALTER TABLE public.salary_line_items DROP CONSTRAINT IF EXISTS salary_line_items_item_type_check;
ALTER TABLE public.salary_line_items
ADD CONSTRAINT salary_line_items_item_type_check
CHECK (item_type IN (
'monthly_salary', 'hourly_salary',
'overtime', 'overtime_50', 'overtime_100',
'ob_weekday_evening', 'ob_weekend', 'ob_night', 'ob_holiday',
'bonus', 'commission',
'gross_deduction_pension', 'gross_deduction_other',
'benefit_car', 'benefit_housing', 'benefit_meals', 'benefit_wellness', 'benefit_bike', 'benefit_other',
'sick_karens', 'sick_day2_14', 'sick_day15_plus',
'vab', 'parental_leave', 'vacation', 'semesterersattning',
'traktamente_taxfree', 'traktamente_taxable',
'mileage_taxfree', 'mileage_taxable',
'net_deduction_advance', 'net_deduction_union', 'net_deduction_benefit_payment', 'net_deduction_other',
'correction', 'other'
));
-- --------------------------------------------------------------------------
-- Per-shift time columns on salary_worked_days
-- --------------------------------------------------------------------------
-- Nullable so existing hours-only rows continue to work. When both times are
-- set the engine uses the explicit overlap with the rule window; when either
-- is NULL the engine falls back to a default-shift assumption.
ALTER TABLE public.salary_worked_days
ADD COLUMN IF NOT EXISTS start_time TIME NULL,
ADD COLUMN IF NOT EXISTS end_time TIME NULL;
-- --------------------------------------------------------------------------
-- shift_premium_rules
-- --------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.shift_premium_rules (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
company_id UUID NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
name TEXT NOT NULL,
applies_to_all_employees BOOLEAN NOT NULL DEFAULT TRUE,
applies_to_employee_ids UUID[] NOT NULL DEFAULT '{}',
-- ISO weekday array: 1 = Monday … 7 = Sunday. Matches extract(isodow from x).
day_of_week INT[] NOT NULL,
start_time TIME NOT NULL,
end_time TIME NOT NULL,
premium_percent NUMERIC(5, 2) NOT NULL
CHECK (premium_percent >= 0 AND premium_percent <= 500),
item_type TEXT NOT NULL,
priority INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
created_by UUID REFERENCES auth.users(id),
-- Only allow the dedicated premium types here. 'overtime' (untyped) is
-- excluded because manually-flagged overtime line items do not need a rule;
-- premium rules are exclusively for the new tiered + OB families.
CONSTRAINT shift_premium_rules_item_type_check CHECK (item_type IN (
'overtime_50', 'overtime_100',
'ob_weekday_evening', 'ob_weekend', 'ob_night', 'ob_holiday'
)),
-- Day-of-week array must contain at least one ISO day in [1, 7].
CONSTRAINT shift_premium_rules_day_of_week_check CHECK (
array_length(day_of_week, 1) >= 1
AND array_length(day_of_week, 1) <= 7
AND day_of_week <@ ARRAY[1, 2, 3, 4, 5, 6, 7]
)
);
CREATE INDEX IF NOT EXISTS idx_shift_premium_rules_company
ON public.shift_premium_rules (company_id)
WHERE is_active = TRUE;
ALTER TABLE public.shift_premium_rules ENABLE ROW LEVEL SECURITY;
CREATE POLICY "shift_premium_rules_select" ON public.shift_premium_rules
FOR SELECT USING (company_id IN (SELECT public.user_company_ids()));
CREATE POLICY "shift_premium_rules_insert" ON public.shift_premium_rules
FOR INSERT WITH CHECK (company_id IN (SELECT public.user_company_ids()));
CREATE POLICY "shift_premium_rules_update" ON public.shift_premium_rules
FOR UPDATE USING (company_id IN (SELECT public.user_company_ids()))
WITH CHECK (company_id IN (SELECT public.user_company_ids()));
CREATE POLICY "shift_premium_rules_delete" ON public.shift_premium_rules
FOR DELETE USING (company_id IN (SELECT public.user_company_ids()));
CREATE TRIGGER shift_premium_rules_updated_at
BEFORE UPDATE ON public.shift_premium_rules
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
NOTIFY pgrst, 'reload schema';