From 2c3e038161925ec50117e4b84eecd3dbe207b5b5 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 6 Oct 2026 01:44:50 +0100 Subject: [PATCH] fix: update schedule --- AGENTS.md | 2 +- Makefile | 10 +- README.md | 11 ++ alembic.ini | 149 ++++++++++++++++++++ app/cli.py | 25 +++- app/database.py | 39 ++++- app/main.py | 14 +- app/templates/admin_schedule.html | 2 +- app/web.py | 35 ++++- docs/ARCHITECTURE.md | 1 + docs/ROADMAP.md | 1 - migrations/README | 1 + migrations/env.py | 58 ++++++++ migrations/script.py.mako | 28 ++++ migrations/versions/0001_initial.py | 129 +++++++++++++++++ migrations/versions/0002_monthly_pattern.py | 37 +++++ requirements.txt | 1 + tests/test_admin_schedule_assignments.py | 64 +++++++-- tests/test_migrations.py | 43 ++++++ 19 files changed, 623 insertions(+), 27 deletions(-) create mode 100644 alembic.ini create mode 100644 migrations/README create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/0001_initial.py create mode 100644 migrations/versions/0002_monthly_pattern.py create mode 100644 tests/test_migrations.py diff --git a/AGENTS.md b/AGENTS.md index bcb26c9..3f0e23e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,7 +47,7 @@ Maintain a deliberately small, self-hosted rota application for a non-profit bar - Keep phone as data-only until SMS/WhatsApp is explicitly implemented. - Do not commit `.env`, database files, credentials, or real member data. - Do not introduce a frontend package manager unless the UI requirements truly need it. -- Prefer migrations before making schema changes in a deployed installation. This MVP currently uses `create_all`; adding Alembic is a roadmap item. +- Schema changes go through Alembic. Edit `app/models.py`, then `make revision m="short description"`, review the generated file in `migrations/versions/`, and never rely on `create_all` (the app runs `alembic upgrade head` on start). `make check` fails if the migrations and the models drift apart. ## Validation before handoff diff --git a/Makefile b/Makefile index f2869b3..4975887 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ COMPOSE_DEV = $(COMPOSE) -f docker-compose.dev.yml PYTHON ?= .venv/bin/python PORT ?= 8000 -.PHONY: dev-setup dev dev-up dev-down dev-logs check test-docker init-db seed-demo reminders +.PHONY: dev-setup dev dev-up dev-down dev-logs check test-docker migrate revision init-db seed-demo reminders # Host virtualenv, used for local debugging only. Checks always run in Docker. dev-setup: @@ -35,6 +35,14 @@ check: test-docker: $(MAKE) check +# Apply database migrations (also runs automatically on app start). +migrate: + $(PYTHON) -m app.cli migrate + +# Autogenerate a migration: make revision m="add something" +revision: + $(PYTHON) -m alembic revision --autogenerate -m "$(m)" + init-db: $(PYTHON) -m app.cli init-db diff --git a/README.md b/README.md index 055a6cd..1e2ac69 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,17 @@ Example cron entry at 09:00 every day: 0 9 * * * cd /path/to/bar-rota && docker compose exec -T bar-rota python -m app.cli send-reminders ``` +## Database + +The schema is managed with Alembic. The app runs `alembic upgrade head` on start, so starting it is enough to apply pending migrations. + +```bash +make migrate # apply pending migrations +make revision m="add phone field" # generate a revision after editing app/models.py +``` + +A database created before Alembic existed has no version stamp; it is adopted at the baseline revision `0001_initial` and upgraded from there. `tests/test_migrations.py` fails if the models and the migrations drift apart. + ## Tests Checks run in a container, so the host Python environment does not matter: diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..08f1d9f --- /dev/null +++ b/alembic.ini @@ -0,0 +1,149 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/app/cli.py b/app/cli.py index 196120a..bd3149d 100644 --- a/app/cli.py +++ b/app/cli.py @@ -8,15 +8,31 @@ from sqlalchemy.orm import selectinload from .bootstrap import ensure_initial_data from .config import settings -from .database import Base, SessionLocal, engine +from .database import ( + SessionLocal, + current_revision, + has_tables, + run_migrations, + stamp, +) from .models import Assignment, NotificationLog, RotationMember, Schedule, User from .notifications import send_email_notification from .scheduling import ensure_month_assignments from .security import hash_password +BASELINE_REVISION = "0001_initial" + + +def migrate() -> None: + if has_tables() and current_revision() is None: + stamp(BASELINE_REVISION) + print(f"Existing database stamped at {BASELINE_REVISION}.") + run_migrations() + print(f"Database at revision {current_revision()}.") + def init_db() -> None: - Base.metadata.create_all(bind=engine) + migrate() with SessionLocal() as db: ensure_initial_data(db) print("Database initialized.") @@ -69,7 +85,7 @@ def seed_demo() -> None: def send_reminders() -> None: - Base.metadata.create_all(bind=engine) + migrate() target = date.today() + timedelta(days=settings.reminder_days_ahead) with SessionLocal() as db: ensure_initial_data(db) @@ -110,11 +126,12 @@ def main() -> None: command = sys.argv[1] if len(sys.argv) > 1 else "" commands = { "init-db": init_db, + "migrate": migrate, "seed-demo": seed_demo, "send-reminders": send_reminders, } if command not in commands: - print("Usage: python -m app.cli [init-db|seed-demo|send-reminders]") + print("Usage: python -m app.cli [init-db|migrate|seed-demo|send-reminders]") raise SystemExit(2) commands[command]() diff --git a/app/database.py b/app/database.py index e474798..c27fd5d 100644 --- a/app/database.py +++ b/app/database.py @@ -1,12 +1,19 @@ from __future__ import annotations from collections.abc import Generator +from pathlib import Path -from sqlalchemy import create_engine +from alembic import command +from alembic.config import Config +from alembic.runtime.migration import MigrationContext +from alembic.script import ScriptDirectory +from sqlalchemy import create_engine, inspect from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker from .config import settings +MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations" + class Base(DeclarativeBase): pass @@ -17,6 +24,36 @@ engine = create_engine(settings.database_url, connect_args=connect_args, future= SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False, class_=Session) +def alembic_config() -> Config: + config = Config(str(MIGRATIONS_DIR.parent / "alembic.ini")) + config.set_main_option("script_location", str(MIGRATIONS_DIR)) + config.set_main_option("sqlalchemy.url", settings.database_url) + return config + + +def run_migrations() -> None: + """Bring the database up to the latest revision. Safe to call on every start.""" + command.upgrade(alembic_config(), "head") + + +def current_revision() -> str | None: + with engine.connect() as connection: + return MigrationContext.configure(connection).get_current_revision() + + +def has_tables() -> bool: + """True when the database already holds the pre-Alembic schema.""" + return bool(set(inspect(engine).get_table_names()) - {"alembic_version"}) + + +def head_revision() -> str: + return ScriptDirectory.from_config(alembic_config()).get_current_head() or "" + + +def stamp(revision: str) -> None: + command.stamp(alembic_config(), revision) + + def get_db() -> Generator[Session, None, None]: db = SessionLocal() try: diff --git a/app/main.py b/app/main.py index 7e8ddbf..da502bd 100644 --- a/app/main.py +++ b/app/main.py @@ -10,7 +10,13 @@ from starlette.middleware.sessions import SessionMiddleware from .bootstrap import ensure_initial_data from .config import settings -from .database import Base, SessionLocal, engine +from .database import ( + SessionLocal, + current_revision, + has_tables, + run_migrations, + stamp, +) from .web import router BASE_DIR = Path(__file__).resolve().parent @@ -18,7 +24,11 @@ BASE_DIR = Path(__file__).resolve().parent @asynccontextmanager async def lifespan(app: FastAPI): - Base.metadata.create_all(bind=engine) + # Databases created before Alembic existed have no version stamp: adopt them + # at the baseline revision so the migrations can continue from there. + if has_tables() and current_revision() is None: + stamp("0001_initial") + run_migrations() with SessionLocal() as db: ensure_initial_data(db) yield diff --git a/app/templates/admin_schedule.html b/app/templates/admin_schedule.html index 7709f2c..16354ac 100644 --- a/app/templates/admin_schedule.html +++ b/app/templates/admin_schedule.html @@ -63,7 +63,7 @@ {% else %}

Repeating every month

-

One person for each day of the month, the same every month. Days 29 to 31 only apply to months that have them. Existing dates are never rewritten.

+

One person for each day of the month, the same every month. Days 29 to 31 only apply to months that have them. Saving fills the nights that nobody has been given yet; nights already assigned keep their person.

diff --git a/app/web.py b/app/web.py index 8334f36..f2cf5ca 100644 --- a/app/web.py +++ b/app/web.py @@ -787,10 +787,43 @@ async def admin_schedule_pattern( row.user_id = user_id saved += 1 db.commit() - _flash(request, f"Saved the repeating night pattern ({saved} change(s)).") + touched = _apply_pattern_to_open_rows(db, schedule) + _flash( + request, + f"Saved the repeating night pattern ({saved} change(s)). " + f"Updated {touched} unassigned night(s) in this month and the next; nights already assigned were left alone.", + ) return _redirect(f"/admin/schedules/{schedule.id}") +def _apply_pattern_to_open_rows(db: Session, schedule: Schedule) -> int: + """Fill empty generated nights from the pattern; never touch existing assignees.""" + patterns = _pattern_map(db, schedule) + if not patterns: + return 0 + today = date.today() + last_month = (today.month % 12) + 1 + last_year = today.year + (1 if today.month == 12 else 0) + rows = db.scalars( + select(Assignment).where( + Assignment.schedule_id == schedule.id, + Assignment.user_id.is_(None), + Assignment.source == "generated", + Assignment.date >= today.replace(day=1), + Assignment.date <= date(last_year, last_month, calendar.monthrange(last_year, last_month)[1]), + ) + ).all() + touched = 0 + for row in rows: + user_id = patterns.get(row.date.day) + if user_id and row.user_id != user_id: + row.user_id = user_id + touched += 1 + if touched: + db.commit() + return touched + + @router.post("/admin/schedules/{schedule_id}/settings") def admin_schedule_settings( schedule_id: int, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a9d5785..b6cc338 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -7,6 +7,7 @@ Single FastAPI process with server-rendered HTML and a SQLite database volume. T ## Layers - `models.py`: persistence schema. +- `migrations/`: Alembic revisions. The app upgrades to `head` on start; a database created before Alembic existed is stamped at the baseline revision and then upgraded. - `scheduling.py`: deterministic month/rotation generation. - `web.py`: authentication, admin editing and change-request orchestration. - `notifications.py`: synchronous SMTP adapter + durable send log. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index ff6cbf3..0c20e13 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2,7 +2,6 @@ Good next additions if the association needs them: -- Alembic migrations before production schema evolution. - Password self-service and forgot-password flow. - Phone notifications via an explicit SMS/WhatsApp provider. - iCalendar (`.ics`) export / personal calendar subscription. diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..a176106 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,58 @@ +"""Alembic environment for the rota database. + +The URL always comes from app settings (`DATABASE_URL`), so migrations run +against the same database as the application, on the host and in Docker alike. +""" + +from __future__ import annotations + +from logging.config import fileConfig + +from alembic import context +from sqlalchemy import engine_from_config, pool + +from app.config import settings +from app.database import Base +from app import models # noqa: F401 (imported for its side effect: metadata) + +config = context.config +config.set_main_option("sqlalchemy.url", settings.database_url) + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def run_migrations_offline() -> None: + context.configure( + url=settings.database_url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + render_as_batch=settings.database_url.startswith("sqlite"), + ) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=settings.database_url.startswith("sqlite"), + ) + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() \ No newline at end of file diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1101630 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,28 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/0001_initial.py b/migrations/versions/0001_initial.py new file mode 100644 index 0000000..91f29b9 --- /dev/null +++ b/migrations/versions/0001_initial.py @@ -0,0 +1,129 @@ +"""initial schema (everything up to the monthly night pattern) + +Revision ID: 0001_initial +Revises: +Create Date: 2026-10-06 + +Existing installations created before Alembic was introduced already have this +schema: stamp them with `alembic stamp 0001_initial` before upgrading. +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '0001_initial' +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('schedules', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=120), nullable=False), + sa.Column('slug', sa.String(length=80), nullable=False), + sa.Column('schedule_type', sa.String(length=20), nullable=False), + sa.Column('weekdays', sa.String(length=30), nullable=False), + sa.Column('label_time', sa.String(length=80), nullable=False), + sa.Column('requires_manager_approval', sa.Boolean(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('rotation_anchor_date', sa.Date(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('name'), + sa.UniqueConstraint('slug') + ) + op.create_table('users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=120), nullable=False), + sa.Column('username', sa.String(length=80), nullable=True), + sa.Column('email', sa.String(length=254), nullable=True), + sa.Column('phone', sa.String(length=40), nullable=True), + sa.Column('password_hash', sa.String(length=300), nullable=True), + sa.Column('is_admin', sa.Boolean(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('notify_email', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('email'), + sa.UniqueConstraint('username') + ) + op.create_table('assignments', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('schedule_id', sa.Integer(), nullable=False), + sa.Column('date', sa.Date(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('source', sa.String(length=20), nullable=False), + sa.Column('note', sa.String(length=500), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['schedule_id'], ['schedules.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='SET NULL'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('schedule_id', 'date', name='uq_assignment_schedule_date') + ) + with op.batch_alter_table('assignments', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_assignments_date'), ['date'], unique=False) + + op.create_table('notification_logs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('event_type', sa.String(length=60), nullable=False), + sa.Column('channel', sa.String(length=20), nullable=False), + sa.Column('recipient', sa.String(length=254), nullable=True), + sa.Column('subject', sa.String(length=250), nullable=False), + sa.Column('body', sa.Text(), nullable=False), + sa.Column('status', sa.String(length=20), nullable=False), + sa.Column('error', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('sent_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='SET NULL'), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('rotation_members', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('schedule_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('position', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['schedule_id'], ['schedules.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('schedule_id', 'position', name='uq_rotation_schedule_position'), + sa.UniqueConstraint('schedule_id', 'user_id', name='uq_rotation_schedule_user') + ) + op.create_table('swap_requests', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('assignment_id', sa.Integer(), nullable=False), + sa.Column('requester_id', sa.Integer(), nullable=False), + sa.Column('target_user_id', sa.Integer(), nullable=True), + sa.Column('accepted_by_id', sa.Integer(), nullable=True), + sa.Column('status', sa.String(length=30), nullable=False), + sa.Column('message', sa.String(length=500), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['accepted_by_id'], ['users.id'], ondelete='SET NULL'), + sa.ForeignKeyConstraint(['assignment_id'], ['assignments.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['requester_id'], ['users.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['target_user_id'], ['users.id'], ondelete='SET NULL'), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('swap_requests') + op.drop_table('rotation_members') + op.drop_table('notification_logs') + with op.batch_alter_table('assignments', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_assignments_date')) + + op.drop_table('assignments') + op.drop_table('users') + op.drop_table('schedules') + # ### end Alembic commands ### diff --git a/migrations/versions/0002_monthly_pattern.py b/migrations/versions/0002_monthly_pattern.py new file mode 100644 index 0000000..2e495ff --- /dev/null +++ b/migrations/versions/0002_monthly_pattern.py @@ -0,0 +1,37 @@ +"""add monthly night pattern + +Revision ID: 0002_monthly_pattern +Revises: 0001_initial +Create Date: 2026-10-06 + +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision: str = "0002_monthly_pattern" +down_revision: Union[str, Sequence[str], None] = "0001_initial" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.create_table( + "monthly_patterns", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("schedule_id", sa.Integer(), nullable=False), + sa.Column("day_of_month", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=True), + sa.CheckConstraint("day_of_month BETWEEN 1 AND 31", name="ck_pattern_day_of_month"), + sa.ForeignKeyConstraint(["schedule_id"], ["schedules.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="SET NULL"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("schedule_id", "day_of_month", name="uq_pattern_schedule_day"), + ) + + +def downgrade() -> None: + op.drop_table("monthly_patterns") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 669638a..0de609c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,3 +6,4 @@ python-multipart>=0.0.12,<1 itsdangerous>=2.2,<3 email-validator>=2.2,<3 pydantic-settings>=2.5,<3 +alembic>=1.13,<2 diff --git a/tests/test_admin_schedule_assignments.py b/tests/test_admin_schedule_assignments.py index a01003b..31f9b70 100644 --- a/tests/test_admin_schedule_assignments.py +++ b/tests/test_admin_schedule_assignments.py @@ -155,27 +155,22 @@ def test_saving_the_pattern_fills_every_month(client, db): def test_changing_the_pattern_never_rewrites_existing_assignments(client, db): - night, _, _, ana, bruno, _ = seed(db) - ensure_month_assignments(db, YEAR, MONTH) + night, _, _, ana, _, _ = seed(db) + ensure_month_assignments(db, 2026, 11) db.expire_all() - existing = assignment_on(db, night, date(YEAR, MONTH, 1)) - assert existing.user_id is None + assert assignment_on(db, night, date(2026, 11, 1)).user_id is None + + # Pattern added after the rows already exist. db.add(MonthlyPattern(schedule_id=night.id, day_of_month=1, user_id=ana.id)) db.commit() - token = sign_in(client) - - client.post( - f"/admin/schedules/{night.id}/pattern", - data={"csrf_token": token, "day_1": ana.id}, - follow_redirects=False, - ) - ensure_month_assignments(db, YEAR, MONTH) + ensure_month_assignments(db, 2026, 11) db.expire_all() + assert assignment_on(db, night, date(2026, 11, 1)).user_id is None - assert assignment_on(db, night, date(YEAR, MONTH, 1)).user_id is None - ensure_month_assignments(db, YEAR, MONTH + 1) + # A month that did not exist yet picks the pattern up. + ensure_month_assignments(db, 2026, 12) db.expire_all() - assert assignment_on(db, night, date(YEAR, MONTH + 1, 1)).user_id == ana.id + assert assignment_on(db, night, date(2026, 12, 1)).user_id == ana.id def test_assigning_on_the_saturday_page_saves_only_saturday_rows(client, db): @@ -208,6 +203,45 @@ def test_assigning_on_the_saturday_page_saves_only_saturday_rows(client, db): assert assignment_on(db, sun, date(2026, 10, 4)).user_id == bruno.id +def test_saving_the_pattern_fills_unassigned_nights_of_this_month(client, db): + night, _, _, ana, _, _ = seed(db) + sign_in(client) # signing in renders the rota, which generates this month + ensure_month_assignments(db, date.today().year, date.today().month) + db.expire_all() + today_row = assignment_on(db, night, date.today()) + assert today_row.user_id is None + token = CSRF_RE.search(client.get(f"/admin/schedules/{night.id}").text).group(1) + + client.post( + f"/admin/schedules/{night.id}/pattern", + data={"csrf_token": token, f"day_{date.today().day}": ana.id}, + follow_redirects=False, + ) + db.expire_all() + + assert assignment_on(db, night, date.today()).user_id == ana.id + + +def test_saving_the_pattern_leaves_assigned_nights_alone(client, db): + night, _, _, ana, bruno, _ = seed(db) + sign_in(client) + ensure_month_assignments(db, date.today().year, date.today().month) + today_row = assignment_on(db, night, date.today()) + today_row.user_id = bruno.id + today_row.source = "manual" + db.commit() + token = CSRF_RE.search(client.get(f"/admin/schedules/{night.id}").text).group(1) + + client.post( + f"/admin/schedules/{night.id}/pattern", + data={"csrf_token": token, f"day_{date.today().day}": ana.id}, + follow_redirects=False, + ) + db.expire_all() + + assert assignment_on(db, night, date.today()).user_id == bruno.id + + def test_saturday_page_only_shows_saturdays(client, db): _, sat, _, _, _, _ = seed(db) sign_in(client) diff --git a/tests/test_migrations.py b/tests/test_migrations.py new file mode 100644 index 0000000..b30faeb --- /dev/null +++ b/tests/test_migrations.py @@ -0,0 +1,43 @@ +from sqlalchemy import create_engine, inspect, text + +from app.database import Base +from app import models # noqa: F401 (registers the tables on Base.metadata) + + +def test_migrations_produce_the_model_schema(tmp_path, monkeypatch): + """`alembic upgrade head` must match app/models.py, no drift in either direction.""" + from alembic import command + + from app.database import alembic_config + + db_path = tmp_path / "migrate.db" + url = f"sqlite:///{db_path}" + monkeypatch.setenv("DATABASE_URL", url) + monkeypatch.setattr("app.config.settings.database_url", url) + + config = alembic_config() + command.upgrade(config, "head") + + engine = create_engine(url) + migrated = set(inspect(engine).get_table_names()) - {"alembic_version"} + assert migrated == set(Base.metadata.tables) + + with engine.connect() as connection: + head = connection.execute(text("select version_num from alembic_version")).scalar_one() + assert head == "0002_monthly_pattern" + + +def test_a_new_column_gets_a_revision(monkeypatch, tmp_path): + """Autogenerate must report no pending operations once head is applied.""" + from alembic import command + + from app.database import alembic_config + + db_path = tmp_path / "drift.db" + url = f"sqlite:///{db_path}" + monkeypatch.setenv("DATABASE_URL", url) + monkeypatch.setattr("app.config.settings.database_url", url) + + config = alembic_config() + command.upgrade(config, "head") + command.check(config) \ No newline at end of file