Rework balances around per-parent days left and deduce the partner from FK

Manual entry now takes one parent's sjukpenningnivå, lägstanivå and
dubbeldagar left (plus optional reserved days) and derives the rest in
build_snapshot, shared with the scraper. The scraper also reads the
family panel and exposes a partner deduction; with two parents it is
saved as a 'deduced' snapshot (migration 002). Parent count is the single
source of entitlement: one member gets 480 days and 96 savable at age 4,
two get 240 and 48 each. Workspaces are capped at two parents.

Also lands the in-flight squash of migrations 002–011 into the initial
schema and the removal of planning_mode.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
2026-09-19 12:27:29 +02:00
parent 375bc64f2f
commit e4719cb9ae
71 changed files with 5705 additions and 1859 deletions
+104 -11
View File
@@ -1,8 +1,16 @@
"""Initial schema — all nine tables for the full application.
"""Initial schema — full application schema, collapsed from the prior 13-migration chain.
Migrations 001-013 are collapsed into this single one now that the chain has
never shipped to a production database (dev-only so far). This file must stay
byte-for-byte equivalent, schema-wise, to `_FULL_SCHEMA` in
`app/db/connection.py` — `tests/integration/test_schema_parity.py` asserts
exactly that by building a database from each and diffing tables, columns,
CHECKs, foreign keys and indexes. The CREATE TABLE / CREATE INDEX statements
below are copied verbatim from `_FULL_SCHEMA` so the two can never drift.
Revision ID: 001
Revises: None
Create Date: 2026-05-31
Create Date: 2026-09-18
"""
from __future__ import annotations
@@ -14,13 +22,12 @@ down_revision: str | None = None
branch_labels: str | None = None
depends_on: str | None = None
# Tables are created in FK-dependency order (workspace first).
# Tables in FK-dependency order (workspace first); indexes last. Kept in sync
# with `_FULL_SCHEMA` in `app/db/connection.py` — see module docstring.
_UPGRADE_SQL = """
CREATE TABLE IF NOT EXISTS workspace (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
planning_goal TEXT NOT NULL DEFAULT 'balanced'
CHECK (planning_goal IN ('max_time','max_money','balanced')),
created_at TIMESTAMP NOT NULL
);
@@ -32,6 +39,8 @@ CREATE TABLE IF NOT EXISTS personal_data (
CHECK (salary_type IN ('monthly','hourly')),
employment_status TEXT NOT NULL DEFAULT 'employed'
CHECK (employment_status IN ('employed','jobseeking','none')),
min_vacation_days_per_year INTEGER NOT NULL DEFAULT 20
CHECK (min_vacation_days_per_year >= 0 AND min_vacation_days_per_year <= 60),
personnummer_enc TEXT,
created_at TIMESTAMP NOT NULL,
deleted_at TIMESTAMP,
@@ -44,6 +53,7 @@ CREATE TABLE IF NOT EXISTS "user" (
email TEXT NOT NULL UNIQUE,
hashed_password TEXT NOT NULL,
created_at TIMESTAMP NOT NULL,
is_active INTEGER NOT NULL DEFAULT 1,
FOREIGN KEY (personal_data_uuid) REFERENCES personal_data(uuid) ON DELETE CASCADE
);
@@ -66,20 +76,44 @@ CREATE TABLE IF NOT EXISTS child (
name TEXT NOT NULL,
birth_date DATE NOT NULL,
preschool_start_date DATE,
preschool_planning_days_per_year INTEGER NOT NULL DEFAULT 6
CHECK (preschool_planning_days_per_year >= 0 AND preschool_planning_days_per_year <= 30),
created_at TIMESTAMP NOT NULL,
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS break_period (
CREATE TABLE IF NOT EXISTS leave_wish (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
child_id TEXT,
name TEXT NOT NULL,
start_date DATE NOT NULL,
end_date DATE NOT NULL,
name_message_key TEXT,
window_start_month INTEGER NOT NULL DEFAULT 1
CHECK (window_start_month >= 1 AND window_start_month <= 12),
window_start_day INTEGER NOT NULL DEFAULT 1
CHECK (window_start_day >= 1 AND window_start_day <= 31),
window_end_month INTEGER NOT NULL DEFAULT 1
CHECK (window_end_month >= 1 AND window_end_month <= 12),
window_end_day INTEGER NOT NULL DEFAULT 1
CHECK (window_end_day >= 1 AND window_end_day <= 31),
target_weeks INTEGER NOT NULL,
target_days INTEGER,
recurrence TEXT NOT NULL DEFAULT 'once'
CHECK (recurrence IN ('yearly','once')),
first_year INTEGER NOT NULL DEFAULT 2026,
last_year INTEGER,
priority INTEGER NOT NULL DEFAULT 1 CHECK (priority >= 1),
parent_mode TEXT NOT NULL DEFAULT 'either'
CHECK (parent_mode IN ('either','both','specific')),
parent_personal_data_uuid TEXT,
window_mode TEXT NOT NULL DEFAULT 'fixed'
CHECK (window_mode IN ('fixed','flexible')),
wants_dubbeldag INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE,
FOREIGN KEY (child_id) REFERENCES child(id) ON DELETE CASCADE,
FOREIGN KEY (parent_personal_data_uuid) REFERENCES personal_data(uuid) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS parental_leave_fetch (
@@ -126,20 +160,79 @@ CREATE TABLE IF NOT EXISTS planned_leave_day (
date DATE NOT NULL,
day_type TEXT NOT NULL CHECK (day_type IN ('sjukpenning','lagsta','vacation')),
is_dubbeldag INTEGER NOT NULL DEFAULT 0,
wish_id TEXT,
is_pinned INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
UNIQUE(workspace_id, child_id, date, parent_personal_data_uuid),
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE,
FOREIGN KEY (child_id) REFERENCES child(id) ON DELETE CASCADE,
FOREIGN KEY (parent_personal_data_uuid) REFERENCES personal_data(uuid) ON DELETE CASCADE
FOREIGN KEY (parent_personal_data_uuid) REFERENCES personal_data(uuid) ON DELETE CASCADE,
FOREIGN KEY (wish_id) REFERENCES leave_wish(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS day_override (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
date DATE NOT NULL,
is_working_day INTEGER NOT NULL,
note TEXT,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
UNIQUE(workspace_id, date),
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS tip_dismissal (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
tip_id TEXT NOT NULL,
data_hash TEXT NOT NULL,
dismissed_at TIMESTAMP NOT NULL,
UNIQUE(workspace_id, tip_id),
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_pld_parent_child_type_date
ON planned_leave_day (parent_personal_data_uuid, child_id, day_type, date);
CREATE INDEX IF NOT EXISTS idx_pld_child_dubbeldag_date
ON planned_leave_day (child_id, is_dubbeldag, date);
CREATE INDEX IF NOT EXISTS idx_pld_wish
ON planned_leave_day (wish_id);
CREATE INDEX IF NOT EXISTS idx_plf_parent_child_fetched
ON parental_leave_fetch (personal_data_uuid, child_id, fetched_at);
CREATE INDEX IF NOT EXISTS idx_plf_workspace
ON parental_leave_fetch (workspace_id);
CREATE INDEX IF NOT EXISTS idx_plf_child
ON parental_leave_fetch (child_id);
CREATE INDEX IF NOT EXISTS idx_leave_wish_workspace
ON leave_wish (workspace_id);
CREATE INDEX IF NOT EXISTS idx_leave_wish_child
ON leave_wish (child_id);
CREATE INDEX IF NOT EXISTS idx_leave_wish_parent
ON leave_wish (parent_personal_data_uuid);
CREATE INDEX IF NOT EXISTS idx_child_workspace_birth
ON child (workspace_id, birth_date);
CREATE INDEX IF NOT EXISTS idx_personal_data_workspace_deleted
ON personal_data (workspace_id, deleted_at);
CREATE INDEX IF NOT EXISTS idx_invitation_workspace_status_created
ON workspace_invitation (workspace_id, status, created_at);
CREATE INDEX IF NOT EXISTS idx_invitation_invited_by
ON workspace_invitation (invited_by_user_id);
CREATE INDEX IF NOT EXISTS idx_vacation_days_workspace
ON vacation_days (workspace_id);
"""
# Reverse FK-dependency order: drop dependents before their targets. Dropping
# a table also drops its own indexes, so no separate DROP INDEX statements
# are needed.
_DOWNGRADE_SQL = """
DROP TABLE IF EXISTS tip_dismissal;
DROP TABLE IF EXISTS day_override;
DROP TABLE IF EXISTS planned_leave_day;
DROP TABLE IF EXISTS vacation_days;
DROP TABLE IF EXISTS parental_leave_fetch;
DROP TABLE IF EXISTS break_period;
DROP TABLE IF EXISTS leave_wish;
DROP TABLE IF EXISTS child;
DROP TABLE IF EXISTS workspace_invitation;
DROP TABLE IF EXISTS "user";
@@ -0,0 +1,134 @@
"""Add 'deduced' to parental_leave_fetch.source's CHECK constraint.
`source` gains a third value alongside 'scraped'/'manual': 'deduced', for a
snapshot the app derived on the user's behalf (e.g. defaulting an unentered
total) rather than one FK reported or the user typed in directly. SQLite has
no `ALTER TABLE ... DROP/ADD CONSTRAINT`, so the table is recreated with the
new CHECK and its rows copied across — the standard SQLite migration dance
(see e.g. https://sqlite.org/lang_altertable.html#otheralter). Recreating the
table also drops its indexes, so they're recreated afterwards.
Must stay byte-for-byte equivalent, CHECK-constraint-wise, to
`parental_leave_fetch` in `app/db/connection.py`'s `_FULL_SCHEMA` —
`tests/integration/test_schema_parity.py` asserts exactly that.
Revision ID: 002
Revises: 001
Create Date: 2026-09-19
"""
from __future__ import annotations
from alembic import op
revision: str = "002"
down_revision: str | None = "001"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
CREATE TABLE parental_leave_fetch_new (
id TEXT PRIMARY KEY,
personal_data_uuid TEXT NOT NULL,
workspace_id TEXT NOT NULL,
child_id TEXT NOT NULL,
source TEXT NOT NULL CHECK (source IN ('scraped','manual','deduced')),
fetched_at TIMESTAMP NOT NULL,
total_days INTEGER NOT NULL,
days_used INTEGER NOT NULL,
days_left INTEGER NOT NULL,
reserved_days_total INTEGER NOT NULL DEFAULT 90,
reserved_days_left INTEGER NOT NULL,
transferable_days_left INTEGER NOT NULL,
dubbeldagar_left INTEGER NOT NULL,
tier_data TEXT NOT NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
FOREIGN KEY (personal_data_uuid) REFERENCES personal_data(uuid) ON DELETE CASCADE,
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE,
FOREIGN KEY (child_id) REFERENCES child(id) ON DELETE CASCADE
);
INSERT INTO parental_leave_fetch_new (
id, personal_data_uuid, workspace_id, child_id, source, fetched_at,
total_days, days_used, days_left, reserved_days_total, reserved_days_left,
transferable_days_left, dubbeldagar_left, tier_data, created_at, updated_at
)
SELECT
id, personal_data_uuid, workspace_id, child_id, source, fetched_at,
total_days, days_used, days_left, reserved_days_total, reserved_days_left,
transferable_days_left, dubbeldagar_left, tier_data, created_at, updated_at
FROM parental_leave_fetch;
DROP TABLE parental_leave_fetch;
ALTER TABLE parental_leave_fetch_new RENAME TO parental_leave_fetch;
CREATE INDEX IF NOT EXISTS idx_plf_parent_child_fetched
ON parental_leave_fetch (personal_data_uuid, child_id, fetched_at);
CREATE INDEX IF NOT EXISTS idx_plf_workspace
ON parental_leave_fetch (workspace_id);
CREATE INDEX IF NOT EXISTS idx_plf_child
ON parental_leave_fetch (child_id);
"""
_DOWNGRADE_SQL = """
CREATE TABLE parental_leave_fetch_old (
id TEXT PRIMARY KEY,
personal_data_uuid TEXT NOT NULL,
workspace_id TEXT NOT NULL,
child_id TEXT NOT NULL,
source TEXT NOT NULL CHECK (source IN ('scraped','manual')),
fetched_at TIMESTAMP NOT NULL,
total_days INTEGER NOT NULL,
days_used INTEGER NOT NULL,
days_left INTEGER NOT NULL,
reserved_days_total INTEGER NOT NULL DEFAULT 90,
reserved_days_left INTEGER NOT NULL,
transferable_days_left INTEGER NOT NULL,
dubbeldagar_left INTEGER NOT NULL,
tier_data TEXT NOT NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
FOREIGN KEY (personal_data_uuid) REFERENCES personal_data(uuid) ON DELETE CASCADE,
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE,
FOREIGN KEY (child_id) REFERENCES child(id) ON DELETE CASCADE
);
INSERT INTO parental_leave_fetch_old (
id, personal_data_uuid, workspace_id, child_id, source, fetched_at,
total_days, days_used, days_left, reserved_days_total, reserved_days_left,
transferable_days_left, dubbeldagar_left, tier_data, created_at, updated_at
)
SELECT
id, personal_data_uuid, workspace_id, child_id, source, fetched_at,
total_days, days_used, days_left, reserved_days_total, reserved_days_left,
transferable_days_left, dubbeldagar_left, tier_data, created_at, updated_at
FROM parental_leave_fetch
WHERE source != 'deduced';
DROP TABLE parental_leave_fetch;
ALTER TABLE parental_leave_fetch_old RENAME TO parental_leave_fetch;
CREATE INDEX IF NOT EXISTS idx_plf_parent_child_fetched
ON parental_leave_fetch (personal_data_uuid, child_id, fetched_at);
CREATE INDEX IF NOT EXISTS idx_plf_workspace
ON parental_leave_fetch (workspace_id);
CREATE INDEX IF NOT EXISTS idx_plf_child
ON parental_leave_fetch (child_id);
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,42 +0,0 @@
"""Add workspace.planning_mode and child.preschool_planning_days_per_year.
Revision ID: 002
Revises: 001
Create Date: 2026-09-12
"""
from __future__ import annotations
from alembic import op
revision: str = "002"
down_revision: str | None = "001"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
ALTER TABLE workspace ADD COLUMN planning_mode TEXT NOT NULL DEFAULT 'solo'
CHECK (planning_mode IN ('solo','couple'));
ALTER TABLE child ADD COLUMN preschool_planning_days_per_year INTEGER NOT NULL DEFAULT 6
CHECK (preschool_planning_days_per_year >= 0 AND preschool_planning_days_per_year <= 30);
"""
_DOWNGRADE_SQL = """
ALTER TABLE child DROP COLUMN preschool_planning_days_per_year;
ALTER TABLE workspace DROP COLUMN planning_mode;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,134 +0,0 @@
"""Rename break_period -> leave_wish and add recurrence/priority/parent fields.
`break_period` modeled "N weeks home together in this window" — single-year,
no recurrence, no priority, no notion of which parent. The planning engine
(PLANNING_ENGINE_SPEC.md §2.1) needs all three, so the table is renamed and
extended rather than adding a parallel concept. Safe to do now: the table has
zero rows in production.
The recurring window is stored as month/day integers (not dates) so it can
repeat yearly without a custom SQLite type; old `start_date`/`end_date` rows
are backfilled into `window_*` columns and the date columns are then dropped.
Revision ID: 003
Revises: 002
Create Date: 2026-09-12
"""
from __future__ import annotations
from alembic import op
revision: str = "003"
down_revision: str | None = "002"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
ALTER TABLE break_period RENAME TO leave_wish;
ALTER TABLE leave_wish ADD COLUMN child_id TEXT
REFERENCES child(id) ON DELETE CASCADE;
ALTER TABLE leave_wish ADD COLUMN window_start_month INTEGER NOT NULL DEFAULT 1
CHECK (window_start_month >= 1 AND window_start_month <= 12);
ALTER TABLE leave_wish ADD COLUMN window_start_day INTEGER NOT NULL DEFAULT 1
CHECK (window_start_day >= 1 AND window_start_day <= 31);
ALTER TABLE leave_wish ADD COLUMN window_end_month INTEGER NOT NULL DEFAULT 1
CHECK (window_end_month >= 1 AND window_end_month <= 12);
ALTER TABLE leave_wish ADD COLUMN window_end_day INTEGER NOT NULL DEFAULT 1
CHECK (window_end_day >= 1 AND window_end_day <= 31);
ALTER TABLE leave_wish ADD COLUMN recurrence TEXT NOT NULL DEFAULT 'once'
CHECK (recurrence IN ('yearly','once'));
ALTER TABLE leave_wish ADD COLUMN first_year INTEGER NOT NULL DEFAULT 2026;
ALTER TABLE leave_wish ADD COLUMN last_year INTEGER;
ALTER TABLE leave_wish ADD COLUMN priority INTEGER NOT NULL DEFAULT 1
CHECK (priority >= 1);
ALTER TABLE leave_wish ADD COLUMN parent_mode TEXT NOT NULL DEFAULT 'either'
CHECK (parent_mode IN ('either','both','specific'));
ALTER TABLE leave_wish ADD COLUMN parent_personal_data_uuid TEXT
REFERENCES personal_data(uuid) ON DELETE CASCADE;
ALTER TABLE leave_wish ADD COLUMN goal_override TEXT
CHECK (goal_override IS NULL OR goal_override IN ('max_time','max_money','balanced'));
UPDATE leave_wish SET
recurrence = 'once',
priority = 1,
parent_mode = 'either',
first_year = CAST(strftime('%Y', start_date) AS INTEGER),
last_year = CAST(strftime('%Y', start_date) AS INTEGER),
window_start_month = CAST(strftime('%m', start_date) AS INTEGER),
window_start_day = CAST(strftime('%d', start_date) AS INTEGER),
window_end_month = CAST(strftime('%m', end_date) AS INTEGER),
window_end_day = CAST(strftime('%d', end_date) AS INTEGER);
ALTER TABLE leave_wish DROP COLUMN start_date;
ALTER TABLE leave_wish DROP COLUMN end_date;
"""
_DOWNGRADE_SQL = """
ALTER TABLE leave_wish ADD COLUMN start_date DATE;
ALTER TABLE leave_wish ADD COLUMN end_date DATE;
UPDATE leave_wish SET
start_date = printf('%04d-%02d-%02d', first_year, window_start_month, window_start_day),
end_date = printf(
'%04d-%02d-%02d',
CASE WHEN (window_end_month, window_end_day) < (window_start_month, window_start_day)
THEN first_year + 1 ELSE first_year END,
window_end_month,
window_end_day
);
ALTER TABLE leave_wish DROP COLUMN goal_override;
ALTER TABLE leave_wish DROP COLUMN parent_personal_data_uuid;
ALTER TABLE leave_wish DROP COLUMN parent_mode;
ALTER TABLE leave_wish DROP COLUMN priority;
ALTER TABLE leave_wish DROP COLUMN last_year;
ALTER TABLE leave_wish DROP COLUMN first_year;
ALTER TABLE leave_wish DROP COLUMN recurrence;
ALTER TABLE leave_wish DROP COLUMN window_end_day;
ALTER TABLE leave_wish DROP COLUMN window_end_month;
ALTER TABLE leave_wish DROP COLUMN window_start_day;
ALTER TABLE leave_wish DROP COLUMN window_start_month;
ALTER TABLE leave_wish DROP COLUMN child_id;
ALTER TABLE leave_wish RENAME TO break_period;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,54 +0,0 @@
"""Add day_override table.
Lets a workspace correct the calendar cache (`app/data/swedish_calendar.json`)
in either direction on a per-date basis: `is_working_day=false` means the
workspace is off that day even though the calendar calls it a working day
(e.g. a klämdag their employer gives off); `is_working_day=true` means the
workspace must work despite the calendar (e.g. julafton is a normal workday
there). See PLANNING_ENGINE task notes / app.services.allocation_service.
Revision ID: 004
Revises: 003
Create Date: 2026-09-13
"""
from __future__ import annotations
from alembic import op
revision: str = "004"
down_revision: str | None = "003"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
CREATE TABLE IF NOT EXISTS day_override (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
date DATE NOT NULL,
is_working_day INTEGER NOT NULL,
note TEXT,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
UNIQUE(workspace_id, date),
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE
);
"""
_DOWNGRADE_SQL = """
DROP TABLE IF EXISTS day_override;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,44 +0,0 @@
"""Add personal_data.min_vacation_days_per_year.
Semesterlagen requires a minimum number of vacation days to be *taken* each
year (statutory 20); only days above that minimum may be saved, for up to 5
years. Employers may set a higher floor, and entitlements differ per parent,
so this is modelled per PersonalData row rather than as a single global
constant. See PLANNING_ENGINE_SPEC.md §9.2.
Revision ID: 005
Revises: 004
Create Date: 2026-09-13
"""
from __future__ import annotations
from alembic import op
revision: str = "005"
down_revision: str | None = "004"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
ALTER TABLE personal_data ADD COLUMN min_vacation_days_per_year INTEGER NOT NULL DEFAULT 20
CHECK (min_vacation_days_per_year >= 0 AND min_vacation_days_per_year <= 60);
"""
_DOWNGRADE_SQL = """
ALTER TABLE personal_data DROP COLUMN min_vacation_days_per_year;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,45 +0,0 @@
"""Add leave_wish.window_mode ('fixed' | 'flexible').
PLANNING_ENGINE_SPEC.md §10.1 — "när det passar bäst" flexible wishes. For a
'flexible' wish the EXISTING window_start_*/window_end_* columns are
reinterpreted as the bounding range the allocator searches within, rather
than the exact placement; no new columns are needed for the bound itself.
Defaults to 'fixed' so every existing row (and every existing construction
site) keeps its current, unchanged meaning.
Revision ID: 006
Revises: 005
Create Date: 2026-09-13
"""
from __future__ import annotations
from alembic import op
revision: str = "006"
down_revision: str | None = "005"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
ALTER TABLE leave_wish ADD COLUMN window_mode TEXT NOT NULL DEFAULT 'fixed'
CHECK (window_mode IN ('fixed','flexible'));
"""
_DOWNGRADE_SQL = """
ALTER TABLE leave_wish DROP COLUMN window_mode;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,51 +0,0 @@
"""Add leave_wish.name_message_key (nullable i18n key for preset names).
Bug: `WishEditor.tsx` created preset wishes (Sommar/Jullov/Höstlov/...) with
`name` set to the already-translated string (e.g. "Jul"), persisted as-is.
Switching the UI language afterwards could never fix a wish's name, because
the Swedish (or English) text was the data, not a rendering choice.
Fix: `name_message_key` stores the i18n key that produced `name` at creation
time (e.g. "wishEditor.seasonJul"), alongside the translated `name` so
anything reading `name` directly (backend, exports, ...) still gets a sane
value. The frontend re-translates via the key when present and falls back to
the literal `name` otherwise. Nullable and no default: every existing row
(and any row created by a free-typed custom name) has no key and must keep
showing its stored `name` unchanged — see `LeaveWishService.update`, which
also force-clears the key the moment a user edits `name`.
Revision ID: 007
Revises: 006
Create Date: 2026-09-14
"""
from __future__ import annotations
from alembic import op
revision: str = "007"
down_revision: str | None = "006"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
ALTER TABLE leave_wish ADD COLUMN name_message_key TEXT;
"""
_DOWNGRADE_SQL = """
ALTER TABLE leave_wish DROP COLUMN name_message_key;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,68 +0,0 @@
"""Link planned_leave_day back to the wish that produced it; add pin + day-granular target.
Persisted leave days currently have no link back to the `leave_wish` that
produced them: the allocator's `ProposedDay` carries `wish_id`, but it was
deliberately stripped at persist time. That makes it impossible for the UI to
click a multi-day band on a calendar and edit it as one period — the entire
point of the UX rework this migration is the keystone for.
Three additive, independently-nullable/defaulted changes (no backfill
possible or needed — every existing row predates this link):
1. `planned_leave_day.wish_id` — which wish produced this day. NULL = ad-hoc
/ legacy / unattributable (e.g. a day added by hand, or persisted before
this column existed). `ON DELETE SET NULL` so deleting a wish later never
cascades into deleting the days it already funded — it only orphans them
back to "ad-hoc", matching the nullable semantics.
2. `planned_leave_day.is_pinned` — marks a day the user hand-edited so a
later allocator pass knows not to retype it. This migration only adds the
column and carries it through the read/write path; the allocator itself
does not yet honor it (a follow-up task wires that up).
3. `leave_wish.target_days` — a calendar-drawn period is not a whole number
of weeks. NULL (the default for every existing row) falls back to
`target_weeks * 7` via `LeaveWish.target_span_days()`.
Revision ID: 008
Revises: 007
Create Date: 2026-09-15
"""
from __future__ import annotations
from alembic import op
revision: str = "008"
down_revision: str | None = "007"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
ALTER TABLE planned_leave_day ADD COLUMN wish_id TEXT
REFERENCES leave_wish(id) ON DELETE SET NULL;
ALTER TABLE planned_leave_day ADD COLUMN is_pinned INTEGER NOT NULL DEFAULT 0;
ALTER TABLE leave_wish ADD COLUMN target_days INTEGER;
"""
_DOWNGRADE_SQL = """
ALTER TABLE leave_wish DROP COLUMN target_days;
ALTER TABLE planned_leave_day DROP COLUMN is_pinned;
ALTER TABLE planned_leave_day DROP COLUMN wish_id;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,50 +0,0 @@
"""Drop workspace.planning_goal and leave_wish.goal_override.
Product decision: there is only one sensible allocation objective — maximise
the value extracted from parental-leave days plus vacation days. Exposing
`max_time` / `max_money` / `balanced` as a user-facing setting made the
planner's behaviour unpredictable without making it more useful. The engine
now always applies what used to be the `max_money` policy; the `goal`
concept (and the ability to override it per-wish) is removed entirely.
Revision ID: 009
Revises: 008
Create Date: 2026-09-15
"""
from __future__ import annotations
from alembic import op
revision: str = "009"
down_revision: str | None = "008"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
ALTER TABLE workspace DROP COLUMN planning_goal;
ALTER TABLE leave_wish DROP COLUMN goal_override;
"""
_DOWNGRADE_SQL = """
ALTER TABLE workspace ADD COLUMN planning_goal TEXT NOT NULL DEFAULT 'balanced'
CHECK (planning_goal IN ('max_time','max_money','balanced'));
ALTER TABLE leave_wish ADD COLUMN goal_override TEXT
CHECK (goal_override IS NULL OR goal_override IN ('max_time','max_money','balanced'));
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,59 +0,0 @@
"""Add tip_dismissal table for persisting tip dismissals.
`useOptimizationTips` only kept dismissed tip ids in a local `Set` — they came
back on every reload. This adds a workspace-scoped dismissal record keyed by
`(workspace_id, tip_id)` so a dismissed tip stays dismissed across reloads,
until the underlying situation changes materially.
`data_hash` is a fingerprint of the tip's `data` payload at dismiss time
(see `app.utils.tip_predicates.hash_tip_data`). `TipsService` only honors a
dismissal while the rule's current output still hashes the same; once the
numbers move (e.g. more days now projected to expire at age 4), the
dismissal is stale and the tip resurfaces automatically. A dismissal that
never expired could permanently silence a safety-relevant warning such as
`preserve_for_age_4` — that would be worse than not persisting dismissals at
all, so expiry-on-change is not optional here.
Revision ID: 010
Revises: 009
Create Date: 2026-09-17
"""
from __future__ import annotations
from alembic import op
revision: str = "010"
down_revision: str | None = "009"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
CREATE TABLE tip_dismissal (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
tip_id TEXT NOT NULL,
data_hash TEXT NOT NULL,
dismissed_at TIMESTAMP NOT NULL,
UNIQUE(workspace_id, tip_id),
FOREIGN KEY (workspace_id) REFERENCES workspace(id) ON DELETE CASCADE
);
"""
_DOWNGRADE_SQL = """
DROP TABLE tip_dismissal;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
@@ -1,99 +0,0 @@
"""Add indexes on hot filter/FK-cascade columns, and user.is_active.
Backend-perf audit (`scratchpad/audit/backend-perf.md` §4, M1): every
migration to date created zero indexes; `EXPLAIN QUERY PLAN` against the full
schema shows several hot paths doing a full table SCAN once the DB carries
more than a handful of rows per table (multi-workspace deployment, years of
FK-fetch history) — `planned_leave_day.count_by_parent_type` (2x per
parent+child in analytics and plan/apply), `count_dubbeldagar`,
`parental_leave_fetch.get_latest_by_parent`, and every FK-cascade column that
`ON DELETE CASCADE` walks on a GDPR delete. These 14 indexes cover exactly
those columns; see the audit for the full per-index rationale. Every
`CREATE INDEX` below is mirrored verbatim (same columns, same order, no
partial indexes) in `_FULL_SCHEMA` (`app/db/connection.py`) so
`tests/integration/test_schema_parity.py` — which compares index sets between
the Alembic chain and that hand-maintained DDL — stays green.
Also adds `user.is_active` (default 1): `AuthService.login` and
`get_user_from_token` already check `User.is_active` (account
deactivation), but the column never existed — every account was
unconditionally treated as active. This migration adds it and
`SQLiteUserRepository` now reads/writes it.
Revision ID: 011
Revises: 010
Create Date: 2026-09-18
"""
from __future__ import annotations
from alembic import op
revision: str = "011"
down_revision: str | None = "010"
branch_labels: str | None = None
depends_on: str | None = None
_UPGRADE_SQL = """
ALTER TABLE "user" ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1;
CREATE INDEX idx_pld_parent_child_type_date
ON planned_leave_day (parent_personal_data_uuid, child_id, day_type, date);
CREATE INDEX idx_pld_child_dubbeldag_date
ON planned_leave_day (child_id, is_dubbeldag, date);
CREATE INDEX idx_pld_wish
ON planned_leave_day (wish_id);
CREATE INDEX idx_plf_parent_child_fetched
ON parental_leave_fetch (personal_data_uuid, child_id, fetched_at);
CREATE INDEX idx_plf_workspace
ON parental_leave_fetch (workspace_id);
CREATE INDEX idx_plf_child
ON parental_leave_fetch (child_id);
CREATE INDEX idx_leave_wish_workspace
ON leave_wish (workspace_id);
CREATE INDEX idx_leave_wish_child
ON leave_wish (child_id);
CREATE INDEX idx_leave_wish_parent
ON leave_wish (parent_personal_data_uuid);
CREATE INDEX idx_child_workspace_birth
ON child (workspace_id, birth_date);
CREATE INDEX idx_personal_data_workspace_deleted
ON personal_data (workspace_id, deleted_at);
CREATE INDEX idx_invitation_workspace_status_created
ON workspace_invitation (workspace_id, status, created_at);
CREATE INDEX idx_invitation_invited_by
ON workspace_invitation (invited_by_user_id);
CREATE INDEX idx_vacation_days_workspace
ON vacation_days (workspace_id);
"""
_DOWNGRADE_SQL = """
DROP INDEX idx_vacation_days_workspace;
DROP INDEX idx_invitation_invited_by;
DROP INDEX idx_invitation_workspace_status_created;
DROP INDEX idx_personal_data_workspace_deleted;
DROP INDEX idx_child_workspace_birth;
DROP INDEX idx_leave_wish_parent;
DROP INDEX idx_leave_wish_child;
DROP INDEX idx_leave_wish_workspace;
DROP INDEX idx_plf_child;
DROP INDEX idx_plf_workspace;
DROP INDEX idx_plf_parent_child_fetched;
DROP INDEX idx_pld_wish;
DROP INDEX idx_pld_child_dubbeldag_date;
DROP INDEX idx_pld_parent_child_type_date;
ALTER TABLE "user" DROP COLUMN is_active;
"""
def upgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _UPGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))
def downgrade() -> None:
from sqlalchemy import text
for stmt in [s.strip() for s in _DOWNGRADE_SQL.split(";") if s.strip()]:
op.execute(text(stmt))