commit e29da874ee80bd4b8cc4224b0be9d01bd660bccc Author: Joao Carreira Date: Mon Oct 5 22:36:27 2026 +0100 feat: initial implementation diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..bc63248 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +.git +.venv +__pycache__ +.pytest_cache +.env +data/*.db +data/*.sqlite3 +*.pyc diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..efcb65f --- /dev/null +++ b/.env.example @@ -0,0 +1,25 @@ +APP_NAME=CRR Bar Rota +SECRET_KEY=replace-with-a-long-random-value +DATABASE_URL=sqlite:///./data/bar_rota.db +BASE_URL=http://localhost:8000 + +# Initial admin is created only if no users exist. +INITIAL_ADMIN_NAME=Administrator +INITIAL_ADMIN_USERNAME=admin +INITIAL_ADMIN_EMAIL=admin@example.com +INITIAL_ADMIN_PASSWORD=change-me-now + +# SMTP is optional. If SMTP_HOST is blank, notifications are recorded in the DB +# but no email is sent. +SMTP_HOST= +SMTP_PORT=587 +SMTP_USERNAME= +SMTP_PASSWORD= +SMTP_FROM=bar-rota@example.com +SMTP_STARTTLS=true + +# Reminder command looks this many days ahead. +REMINDER_DAYS_AHEAD=1 + +# Set true when the app is served only over HTTPS. +SESSION_HTTPS_ONLY=false diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..425c6f0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.venv/ +.env +*.db +*.sqlite3 +data/* +!data/.gitkeep diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..f857381 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,76 @@ +# AGENTS.md + +## Mission + +Maintain a deliberately small, self-hosted rota application for a non-profit bar/club. Prefer clarity and operational simplicity over enterprise HR features. + +## Domain invariants + +1. **Assignments are the source of truth.** Recurrence/rotation rules only create assignments that do not already exist. +2. There are three seeded schedules: + - `night`: fixed/manual, every day of the month. + - `saturday-lunch`: rotating, Saturdays only. + - `sunday-lunch`: rotating, Sundays only. +3. Saturday and Sunday rotations are independent. +4. Never silently rewrite an existing assignment when rotation membership/order changes. +5. A swap/change request only applies if the requester still owns the assignment when it is accepted/approved. +6. `email` and `phone` are optional. `username` is required and unique for authentication. +7. Email failure must never roll back or block a rota change. Log failures in `notification_logs`. +8. Past assignments cannot be offered for change through the member UI. + +## Stack + +- Python 3.12+ +- FastAPI + server-rendered Jinja2 +- SQLAlchemy 2.x +- SQLite by default +- No frontend build step or JavaScript framework +- Docker Compose for self-hosting + +## Important files + +- `app/models.py` — database schema. +- `app/scheduling.py` — recurrence and assignment generation. Treat changes here as high-risk. +- `app/web.py` — HTTP routes and workflows. +- `app/notifications.py` — SMTP delivery; should fail soft. +- `app/bootstrap.py` — initial admin + three default schedules. +- `app/cli.py` — database/demo/reminder commands. +- `docs/DOMAIN.md` — expected business behavior. + +## Working rules for agents + +- Read `docs/DOMAIN.md` before changing scheduling behavior. +- Add/update tests for every scheduling or swap-state change. +- Keep existing generated/published assignments stable unless an admin explicitly edits them. +- Do not add payroll, time clocks, attendance, leave management, or HR modules unless requested. +- 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. + +## Validation before handoff + +Run: + +```bash +python -m compileall -q app +pytest -q +``` + +For route/UI changes also start the app and verify `/health`, `/login`, the rota, admin month editor, and swap workflow. + +## Security notes + +- Passwords use PBKDF2-SHA256 from Python stdlib. +- State-changing forms use a session CSRF token. +- Admin routes must call `_require_admin`. +- Treat names, email addresses, phone numbers and schedules as private member data. +- Change the default `SECRET_KEY` and initial admin password before deployment. + +## Branding and UI + +- The CRR logo is the user-supplied asset at `app/static/logo-crr.png`. Keep its aspect ratio and do not redraw, recolor, crop, or replace it unless explicitly requested. +- CRR brand red is `#ED1C24` and is exposed as `--brand` in `app/static/app.css`. +- For controls with white text, use the darker accessible red `--brand-deep` (`#C81018`), not the exact brand red. The exact brand red is used for borders, focus states, highlights, and other identity accents. +- Keep branding usable on mobile and preserve visible keyboard focus states. +- Default application name is `CRR Bar Rota`; deployments can still override it with `APP_NAME`. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..2133091 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt +COPY . . +RUN mkdir -p /app/data +EXPOSE 8000 +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e3bcc11 --- /dev/null +++ b/Makefile @@ -0,0 +1,16 @@ +.PHONY: dev test init-db seed-demo reminders + +dev: + uvicorn app.main:app --reload + +test: + pytest -q + +init-db: + python -m app.cli init-db + +seed-demo: + python -m app.cli seed-demo + +reminders: + python -m app.cli send-reminders diff --git a/README.md b/README.md new file mode 100644 index 0000000..b277d47 --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +# Bar Rota + +Small self-hosted rota application for a non-profit bar/club. + +## What it does + +- One **Night** assignment for every calendar day. +- Independent rotating **Saturday Lunch** and **Sunday Lunch** schedules. +- Admins can override any generated assignment. +- Members can request that another person (or anyone available) takes an assignment. +- Optional manager approval before a change becomes final. +- Optional email and phone on each user; username is used for login. +- SMTP email notifications and a notification log. +- Daily reminder command suitable for cron. +- SQLite by default, packaged for Docker. + +## Quick start with Docker + +```bash +cp .env.example .env +# Edit SECRET_KEY and INITIAL_ADMIN_PASSWORD before first start. +docker compose up -d --build +``` + +Open `http://localhost:8000` and sign in with the values in `.env`. + +**Important:** the initial admin is only created when the database has no users. Changing `INITIAL_ADMIN_PASSWORD` later does not reset that account; reset it from the People screen. + +## Local development + +```bash +python -m venv .venv +. .venv/bin/activate +pip install -r requirements-dev.txt +cp .env.example .env +python -m app.cli init-db +uvicorn app.main:app --reload +``` + +Demo data: + +```bash +python -m app.cli seed-demo +``` + +Demo member password: `demo-password`. + +## Email + +Set `SMTP_HOST`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `SMTP_FROM` and `SMTP_STARTTLS` in `.env`. If SMTP is not configured, email attempts are safely recorded as `skipped` in **Email log**. + +To send reminders from cron: + +```bash +python -m app.cli send-reminders +``` + +Example cron entry at 09:00 every day: + +```cron +0 9 * * * cd /path/to/bar-rota && docker compose exec -T bar-rota python -m app.cli send-reminders +``` + +## Tests + +```bash +pytest -q +``` + +## Project documentation + +- `AGENTS.md` — instructions and guardrails for coding agents/LLMs. +- `docs/DOMAIN.md` — scheduling rules and terminology. +- `docs/ARCHITECTURE.md` — implementation overview. +- `docs/ROADMAP.md` — intentionally deferred work. diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..1462d13 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +"""Bar Rota application package.""" diff --git a/app/bootstrap.py b/app/bootstrap.py new file mode 100644 index 0000000..2b37f7c --- /dev/null +++ b/app/bootstrap.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from datetime import date + +from sqlalchemy import select +from sqlalchemy.orm import Session + +from .config import settings +from .models import Schedule, User +from .security import hash_password + + +def ensure_initial_data(db: Session) -> None: + user_count = db.scalar(select(User.id).limit(1)) + if user_count is None: + db.add( + User( + name=settings.initial_admin_name, + username=settings.initial_admin_username, + email=settings.initial_admin_email or None, + phone=None, + password_hash=hash_password(settings.initial_admin_password), + is_admin=True, + is_active=True, + ) + ) + db.commit() + + defaults = [ + { + "name": "Night", + "slug": "night", + "schedule_type": "fixed", + "weekdays": "0,1,2,3,4,5,6", + "label_time": "Night", + "rotation_anchor_date": None, + }, + { + "name": "Saturday Lunch", + "slug": "saturday-lunch", + "schedule_type": "rotation", + "weekdays": "5", + "label_time": "Lunch", + "rotation_anchor_date": date(2024, 1, 6), + }, + { + "name": "Sunday Lunch", + "slug": "sunday-lunch", + "schedule_type": "rotation", + "weekdays": "6", + "label_time": "Lunch", + "rotation_anchor_date": date(2024, 1, 7), + }, + ] + + for item in defaults: + exists = db.scalar(select(Schedule.id).where(Schedule.slug == item["slug"])) + if exists is None: + db.add(Schedule(**item, requires_manager_approval=True, is_active=True)) + db.commit() diff --git a/app/cli.py b/app/cli.py new file mode 100644 index 0000000..196120a --- /dev/null +++ b/app/cli.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import sys +from datetime import date, timedelta + +from sqlalchemy import select +from sqlalchemy.orm import selectinload + +from .bootstrap import ensure_initial_data +from .config import settings +from .database import Base, SessionLocal, engine +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 + + +def init_db() -> None: + Base.metadata.create_all(bind=engine) + with SessionLocal() as db: + ensure_initial_data(db) + print("Database initialized.") + + +def seed_demo() -> None: + init_db() + demo_people = [ + ("Alice", "alice", "alice@example.com"), + ("Bruno", "bruno", "bruno@example.com"), + ("Carla", "carla", None), + ("Diogo", "diogo", "diogo@example.com"), + ] + with SessionLocal() as db: + for name, username, email in demo_people: + if not db.scalar(select(User.id).where(User.username == username)): + db.add( + User( + name=name, + username=username, + email=email, + phone=None, + password_hash=hash_password("demo-password"), + is_active=True, + is_admin=False, + notify_email=True, + ) + ) + db.commit() + people = db.scalars(select(User).where(User.username.in_([x[1] for x in demo_people])).order_by(User.name)).all() + schedules = db.scalars(select(Schedule).where(Schedule.schedule_type == "rotation").order_by(Schedule.id)).all() + for schedule in schedules: + if not db.scalar(select(RotationMember.id).where(RotationMember.schedule_id == schedule.id)): + for pos, person in enumerate(people, start=1): + db.add(RotationMember(schedule_id=schedule.id, user_id=person.id, position=pos)) + db.commit() + + today = date.today() + assignments = ensure_month_assignments(db, today.year, today.month) + night_people = people or [] + if night_people: + idx = 0 + for assignment in assignments: + if assignment.schedule.slug == "night" and assignment.user_id is None: + assignment.user_id = night_people[idx % len(night_people)].id + assignment.source = "manual" + idx += 1 + db.commit() + print("Demo data seeded. Demo member password: demo-password") + + +def send_reminders() -> None: + Base.metadata.create_all(bind=engine) + target = date.today() + timedelta(days=settings.reminder_days_ahead) + with SessionLocal() as db: + ensure_initial_data(db) + ensure_month_assignments(db, target.year, target.month) + assignments = db.scalars( + select(Assignment) + .where(Assignment.date == target, Assignment.user_id.is_not(None)) + .options(selectinload(Assignment.user), selectinload(Assignment.schedule)) + ).all() + count = 0 + for assignment in assignments: + if not assignment.user: + continue + subject = f"Rota reminder: {assignment.schedule.name} on {assignment.date:%d %b}" + already_sent = db.scalar( + select(NotificationLog.id).where( + NotificationLog.user_id == assignment.user.id, + NotificationLog.event_type == "shift_reminder", + NotificationLog.subject == subject, + NotificationLog.status == "sent", + ) + ) + if already_sent: + continue + send_email_notification( + db, + assignment.user, + "shift_reminder", + subject, + f"Reminder: you are assigned to {assignment.schedule.name} on " + f"{assignment.date:%A, %d %B %Y}.\n\nView the rota: {settings.normalized_base_url}/", + ) + count += 1 + print(f"Processed {count} reminder(s) for {target.isoformat()}.") + + +def main() -> None: + command = sys.argv[1] if len(sys.argv) > 1 else "" + commands = { + "init-db": init_db, + "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]") + raise SystemExit(2) + commands[command]() + + +if __name__ == "__main__": + main() diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..3360400 --- /dev/null +++ b/app/config.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + app_name: str = "CRR Bar Rota" + secret_key: str = "dev-only-change-me" + database_url: str = "sqlite:///./data/bar_rota.db" + base_url: str = "http://localhost:8000" + + initial_admin_name: str = "Administrator" + initial_admin_username: str = "admin" + initial_admin_email: str = "admin@example.com" + initial_admin_password: str = "change-me-now" + + smtp_host: str = "" + smtp_port: int = 587 + smtp_username: str = "" + smtp_password: str = "" + smtp_from: str = "bar-rota@example.com" + smtp_starttls: bool = True + reminder_days_ahead: int = 1 + session_https_only: bool = False + + model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore") + + @property + def normalized_base_url(self) -> str: + return self.base_url.rstrip("/") + + +settings = Settings() diff --git a/app/database.py b/app/database.py new file mode 100644 index 0000000..e474798 --- /dev/null +++ b/app/database.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from collections.abc import Generator + +from sqlalchemy import create_engine +from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker + +from .config import settings + + +class Base(DeclarativeBase): + pass + + +connect_args = {"check_same_thread": False} if settings.database_url.startswith("sqlite") else {} +engine = create_engine(settings.database_url, connect_args=connect_args, future=True) +SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False, class_=Session) + + +def get_db() -> Generator[Session, None, None]: + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..7e8ddbf --- /dev/null +++ b/app/main.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from contextlib import asynccontextmanager +from pathlib import Path + +from fastapi import FastAPI +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates +from starlette.middleware.sessions import SessionMiddleware + +from .bootstrap import ensure_initial_data +from .config import settings +from .database import Base, SessionLocal, engine +from .web import router + +BASE_DIR = Path(__file__).resolve().parent + + +@asynccontextmanager +async def lifespan(app: FastAPI): + Base.metadata.create_all(bind=engine) + with SessionLocal() as db: + ensure_initial_data(db) + yield + + +app = FastAPI(title=settings.app_name, lifespan=lifespan) +app.add_middleware( + SessionMiddleware, + secret_key=settings.secret_key, + same_site="lax", + https_only=settings.session_https_only, + max_age=60 * 60 * 24 * 30, +) +app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static") +app.state.templates = Jinja2Templates(directory=BASE_DIR / "templates") +app.include_router(router) diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..bce09e3 --- /dev/null +++ b/app/models.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +from datetime import date, datetime + +from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from .database import Base + + +class User(Base): + __tablename__ = "users" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(120), nullable=False) + username: Mapped[str] = mapped_column(String(80), unique=True, nullable=False) + email: Mapped[str | None] = mapped_column(String(254), unique=True, nullable=True) + phone: Mapped[str | None] = mapped_column(String(40), nullable=True) + password_hash: Mapped[str] = mapped_column(String(300), nullable=False) + is_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) + is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) + notify_email: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class Schedule(Base): + __tablename__ = "schedules" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(120), unique=True, nullable=False) + slug: Mapped[str] = mapped_column(String(80), unique=True, nullable=False) + schedule_type: Mapped[str] = mapped_column(String(20), nullable=False) # fixed | rotation + weekdays: Mapped[str] = mapped_column(String(30), nullable=False) # comma-separated 0..6 + label_time: Mapped[str] = mapped_column(String(80), default="", nullable=False) + requires_manager_approval: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) + is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) + rotation_anchor_date: Mapped[date | None] = mapped_column(Date, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + rotation_members: Mapped[list[RotationMember]] = relationship( + back_populates="schedule", cascade="all, delete-orphan", order_by="RotationMember.position" + ) + + @property + def weekday_set(self) -> set[int]: + return {int(v) for v in self.weekdays.split(",") if v.strip()} + + +class RotationMember(Base): + __tablename__ = "rotation_members" + __table_args__ = ( + UniqueConstraint("schedule_id", "user_id", name="uq_rotation_schedule_user"), + UniqueConstraint("schedule_id", "position", name="uq_rotation_schedule_position"), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + schedule_id: Mapped[int] = mapped_column(ForeignKey("schedules.id", ondelete="CASCADE"), nullable=False) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + position: Mapped[int] = mapped_column(Integer, nullable=False) + + schedule: Mapped[Schedule] = relationship(back_populates="rotation_members") + user: Mapped[User] = relationship() + + +class Assignment(Base): + __tablename__ = "assignments" + __table_args__ = (UniqueConstraint("schedule_id", "date", name="uq_assignment_schedule_date"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + schedule_id: Mapped[int] = mapped_column(ForeignKey("schedules.id", ondelete="CASCADE"), nullable=False) + date: Mapped[date] = mapped_column(Date, nullable=False, index=True) + user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True) + source: Mapped[str] = mapped_column(String(20), default="generated", nullable=False) # generated | manual | swap + note: Mapped[str | None] = mapped_column(String(500), nullable=True) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + schedule: Mapped[Schedule] = relationship() + user: Mapped[User | None] = relationship() + + +class SwapRequest(Base): + __tablename__ = "swap_requests" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + assignment_id: Mapped[int] = mapped_column(ForeignKey("assignments.id", ondelete="CASCADE"), nullable=False) + requester_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + target_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True) + accepted_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True) + status: Mapped[str] = mapped_column(String(30), default="open", nullable=False) + message: Mapped[str | None] = mapped_column(String(500), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + assignment: Mapped[Assignment] = relationship() + requester: Mapped[User] = relationship(foreign_keys=[requester_id]) + target_user: Mapped[User | None] = relationship(foreign_keys=[target_user_id]) + accepted_by: Mapped[User | None] = relationship(foreign_keys=[accepted_by_id]) + + +class NotificationLog(Base): + __tablename__ = "notification_logs" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True) + event_type: Mapped[str] = mapped_column(String(60), nullable=False) + channel: Mapped[str] = mapped_column(String(20), default="email", nullable=False) + recipient: Mapped[str | None] = mapped_column(String(254), nullable=True) + subject: Mapped[str] = mapped_column(String(250), nullable=False) + body: Mapped[str] = mapped_column(Text, nullable=False) + status: Mapped[str] = mapped_column(String(20), nullable=False) # sent | skipped | failed + error: Mapped[str | None] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True) + + user: Mapped[User | None] = relationship() diff --git a/app/notifications.py b/app/notifications.py new file mode 100644 index 0000000..11d36f0 --- /dev/null +++ b/app/notifications.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import smtplib +from datetime import datetime +from email.message import EmailMessage + +from sqlalchemy.orm import Session + +from .config import settings +from .models import NotificationLog, User + + +def send_email_notification( + db: Session, + user: User, + event_type: str, + subject: str, + body: str, +) -> NotificationLog: + recipient = user.email + log = NotificationLog( + user_id=user.id, + event_type=event_type, + channel="email", + recipient=recipient, + subject=subject, + body=body, + status="skipped", + ) + + if not user.notify_email or not recipient: + log.error = "Email notifications disabled or no email address" + db.add(log) + db.commit() + return log + + if not settings.smtp_host: + log.error = "SMTP_HOST is not configured" + db.add(log) + db.commit() + return log + + msg = EmailMessage() + msg["From"] = settings.smtp_from + msg["To"] = recipient + msg["Subject"] = subject + msg.set_content(body) + + try: + with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=15) as smtp: + if settings.smtp_starttls: + smtp.starttls() + if settings.smtp_username: + smtp.login(settings.smtp_username, settings.smtp_password) + smtp.send_message(msg) + log.status = "sent" + log.sent_at = datetime.utcnow() + except Exception as exc: # keep scheduling operations usable if email is unavailable + log.status = "failed" + log.error = str(exc) + + db.add(log) + db.commit() + return log + + +def send_many( + db: Session, + users: list[User], + event_type: str, + subject: str, + body: str, +) -> None: + seen: set[int] = set() + for user in users: + if user.id in seen: + continue + seen.add(user.id) + send_email_notification(db, user, event_type, subject, body) diff --git a/app/scheduling.py b/app/scheduling.py new file mode 100644 index 0000000..993b7a9 --- /dev/null +++ b/app/scheduling.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import calendar +from collections import defaultdict +from datetime import date, timedelta + +from sqlalchemy import select +from sqlalchemy.orm import Session, selectinload + +from .models import Assignment, RotationMember, Schedule, User + + +def month_bounds(year: int, month: int) -> tuple[date, date]: + last_day = calendar.monthrange(year, month)[1] + return date(year, month, 1), date(year, month, last_day) + + +def iter_month_dates(year: int, month: int): + first, last = month_bounds(year, month) + current = first + while current <= last: + yield current + current += timedelta(days=1) + + +def _rotation_occurrence_index(schedule: Schedule, target: date) -> int: + """Return zero-based matching-day occurrence index from the schedule anchor.""" + if schedule.rotation_anchor_date is None: + raise ValueError("Rotation schedule is missing an anchor date") + + anchor = schedule.rotation_anchor_date + weekdays = schedule.weekday_set + step = 1 if target >= anchor else -1 + current = anchor + count = 0 + + if step == 1: + while current < target: + if current.weekday() in weekdays: + count += 1 + current += timedelta(days=1) + return count + + while current > target: + current -= timedelta(days=1) + if current.weekday() in weekdays: + count -= 1 + return count + + +def rotation_user_for_date(db: Session, schedule: Schedule, target: date) -> User | None: + if schedule.schedule_type != "rotation" or target.weekday() not in schedule.weekday_set: + return None + + members = db.scalars( + select(RotationMember) + .join(User, RotationMember.user_id == User.id) + .where(RotationMember.schedule_id == schedule.id, User.is_active.is_(True)) + .order_by(RotationMember.position) + .options(selectinload(RotationMember.user)) + ).all() + if not members: + return None + + idx = _rotation_occurrence_index(schedule, target) % len(members) + return members[idx].user + + +def ensure_month_assignments(db: Session, year: int, month: int) -> list[Assignment]: + schedules = db.scalars(select(Schedule).where(Schedule.is_active.is_(True))).all() + first, last = month_bounds(year, month) + existing = db.scalars( + select(Assignment).where(Assignment.date >= first, Assignment.date <= last) + ).all() + existing_keys = {(a.schedule_id, a.date) for a in existing} + + changed = False + for schedule in schedules: + for day in iter_month_dates(year, month): + if day.weekday() not in schedule.weekday_set: + continue + key = (schedule.id, day) + if key in existing_keys: + continue + + user_id = None + if schedule.schedule_type == "rotation": + user = rotation_user_for_date(db, schedule, day) + user_id = user.id if user else None + + db.add( + Assignment( + schedule_id=schedule.id, + date=day, + user_id=user_id, + source="generated", + ) + ) + changed = True + + if changed: + db.commit() + + return db.scalars( + select(Assignment) + .where(Assignment.date >= first, Assignment.date <= last) + .options(selectinload(Assignment.user), selectinload(Assignment.schedule)) + .order_by(Assignment.date, Assignment.schedule_id) + ).all() + + +def assignments_by_date(assignments: list[Assignment]) -> dict[date, list[Assignment]]: + result: dict[date, list[Assignment]] = defaultdict(list) + for assignment in assignments: + result[assignment.date].append(assignment) + return dict(result) diff --git a/app/security.py b/app/security.py new file mode 100644 index 0000000..ad6bb5b --- /dev/null +++ b/app/security.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import hashlib +import hmac +import os +import secrets + +ITERATIONS = 310_000 + + +def hash_password(password: str) -> str: + if len(password) < 8: + raise ValueError("Password must be at least 8 characters") + salt = os.urandom(16) + digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, ITERATIONS) + return f"pbkdf2_sha256${ITERATIONS}${salt.hex()}${digest.hex()}" + + +def verify_password(password: str, encoded: str) -> bool: + try: + scheme, iterations, salt_hex, digest_hex = encoded.split("$", 3) + if scheme != "pbkdf2_sha256": + return False + digest = hashlib.pbkdf2_hmac( + "sha256", password.encode(), bytes.fromhex(salt_hex), int(iterations) + ) + return hmac.compare_digest(digest.hex(), digest_hex) + except (ValueError, TypeError): + return False + + +def new_csrf_token() -> str: + return secrets.token_urlsafe(32) diff --git a/app/static/app.css b/app/static/app.css new file mode 100644 index 0000000..88e542b --- /dev/null +++ b/app/static/app.css @@ -0,0 +1,114 @@ +:root{ + --bg:#f8f6f6; + --card:#fff; + --text:#282122; + --muted:#6f6567; + --line:#e7dddd; + --brand:#ed1c24; + --brand-deep:#c81018; + --brand-dark:#8f0e14; + --brand-soft:#fff0f1; + --accent:var(--brand-deep); + --accent2:var(--brand-soft); + --danger:#a21f25; + --warn:#8a6100; +} +*{box-sizing:border-box} +body{margin:0;background:var(--bg);color:var(--text);font:16px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif} +.container{width:min(1100px,calc(100% - 28px));margin:auto} +.topbar{background:#fff;border-top:4px solid var(--brand);border-bottom:1px solid var(--line);margin-bottom:28px} +.topbar-inner{min-height:68px;display:flex;align-items:center;gap:20px;flex-wrap:wrap} +.brand{display:inline-flex;align-items:center;gap:10px;font-weight:800;color:var(--text);text-decoration:none;font-size:1.12rem;min-width:0} +.brand-logo{display:block;width:46px;height:41px;object-fit:contain;flex:0 0 auto} +.brand-name{white-space:nowrap} +.nav{display:flex;gap:14px;flex:1;flex-wrap:wrap} +.nav a,.link-button{color:var(--muted);text-decoration:none;background:none;border:0;padding:0;font:inherit;cursor:pointer} +.nav a:hover,.link-button:hover{color:var(--brand-dark)} +.account{display:flex;gap:10px;align-items:center;font-size:.9rem} +.page-head{display:flex;justify-content:space-between;gap:20px;align-items:end;flex-wrap:wrap;margin-bottom:20px} +h1,h2,h3{line-height:1.2} +h1{margin:0 0 6px;font-size:1.8rem} +h2{font-size:1.15rem;margin:0 0 8px} +a{color:var(--brand-dark)} +.muted{color:var(--muted)} +.panel,.auth-card,.day-card{background:var(--card);border:1px solid var(--line);border-radius:12px} +.panel{padding:18px} +.auth-card{max-width:430px;margin:56px auto 70px;padding:28px} +.auth-brand{display:flex;justify-content:center;margin:-2px 0 18px} +.auth-brand img{display:block;width:126px;max-width:42%;height:auto} +.stack{display:flex;flex-direction:column} +.stack:not(.gap-lg){gap:14px} +.gap-lg{gap:14px} +.top-space{margin-top:18px} +.row{display:flex;align-items:center} +.between{justify-content:space-between} +.wrap{flex-wrap:wrap} +.gap{gap:14px} +.month-nav,.actions,.inline-form{display:flex;gap:8px;align-items:center;flex-wrap:wrap} +.button,button{border-radius:8px;border:1px solid transparent;padding:9px 12px;font:inherit;cursor:pointer;text-decoration:none;display:inline-block;font-weight:600} +.primary{background:var(--accent);color:#fff} +.primary:hover{background:var(--brand-dark)} +.secondary{background:#fff;color:var(--text);border-color:var(--line)} +.secondary:hover{border-color:#cfbabc;background:#fffafa} +.danger{background:#fff;color:var(--danger);border-color:#e7c3c3} +.small{padding:5px 9px;font-size:.88rem} +.compact{gap:4px} +.link-button{padding:0;font-weight:400} +.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px} +.form-grid label,.stack label,.swap-form label{display:flex;flex-direction:column;gap:5px;font-weight:600;font-size:.9rem} +input,select{width:100%;border:1px solid #cfc4c5;border-radius:8px;padding:9px 10px;background:#fff;color:var(--text);font:inherit} +input:focus,select:focus,button:focus-visible,a:focus-visible,summary:focus-visible{outline:3px solid rgba(237,28,36,.24);outline-offset:2px;border-color:var(--brand)} +.check{flex-direction:row!important;align-items:center!important;font-weight:500!important} +.check input{width:auto;accent-color:var(--brand-deep)} +.flash{padding:12px 14px;border-radius:9px;margin-bottom:18px;background:var(--brand-soft);border-left:4px solid var(--brand)} +.flash.error{background:#f8e8e8;color:#7d2525;border-left-color:var(--danger)} +.calendar-list{display:flex;flex-direction:column;gap:8px;padding-bottom:35px} +.day-card{display:grid;grid-template-columns:74px 1fr;overflow:hidden} +.day-card.today{outline:2px solid var(--brand);outline-offset:1px} +.day-label{padding:14px;text-align:center;border-right:1px solid var(--line);display:flex;flex-direction:column;background:#fffafa} +.day-label span{font-size:1.55rem;font-weight:800} +.day-assignments{display:flex;flex-direction:column} +.assignment{padding:12px 14px;display:flex;justify-content:space-between;gap:15px;align-items:center} +.assignment+.assignment{border-top:1px solid var(--line)} +.assignment.mine{background:var(--accent2);box-shadow:inset 4px 0 0 var(--brand)} +.assignment-title{font-size:.82rem;text-transform:uppercase;letter-spacing:.04em;color:var(--muted)} +.assignment-person{font-weight:700} +.unassigned{color:var(--danger)} +details summary{cursor:pointer;color:var(--brand-dark);font-weight:600} +.swap-form{margin-top:10px;min-width:min(360px,75vw);display:grid;gap:8px} +.badge,.status{display:inline-block;border-radius:999px;padding:4px 8px;font-size:.78rem;background:#f2eeee;color:#5a5052} +.status-approved,.status-sent{background:#e5f4eb;color:#286141} +.status-open,.status-pending_approval{background:#fff3d9;color:#735000} +.status-rejected,.status-failed{background:#fae5e5;color:#842e2e} +.quote{border-left:3px solid var(--brand);padding-left:10px;color:var(--muted)} +.eyebrow{text-transform:uppercase;letter-spacing:.04em;font-size:.75rem;color:var(--muted)} +.empty{padding:30px;text-align:center;color:var(--muted)} +.rotation-list{max-width:620px;padding-left:24px} +.rotation-list li{padding:8px 0;border-bottom:1px solid var(--line);display:list-item} +.rotation-list li>span{display:inline-block;min-width:220px} +.table-wrap{overflow-x:auto;background:#fff;border:1px solid var(--line);border-radius:12px} +table{width:100%;border-collapse:collapse;min-width:650px} +th,td{text-align:left;padding:10px 12px;border-bottom:1px solid var(--line)} +th{font-size:.8rem;text-transform:uppercase;color:var(--muted);background:#fff7f7} +.sticky-actions{position:sticky;bottom:10px;padding:15px 0;text-align:right} +.inline-form select{width:auto;min-width:190px} +@media(max-width:700px){ + .topbar-inner{padding:8px 0} + .brand-logo{width:40px;height:36px} + .nav{order:3;width:100%;padding-bottom:4px} + .account{margin-left:auto} + .form-grid{grid-template-columns:1fr} + .day-card{grid-template-columns:58px 1fr} + .day-label{padding:10px 7px} + .assignment{align-items:flex-start;flex-direction:column} + .assignment-action{width:100%} + .swap-form{min-width:0;width:100%} + .month-nav{width:100%} + .month-nav .button{flex:1;text-align:center} + .panel{padding:14px} + .auth-card{margin-top:36px;padding:22px} +} +@media(max-width:430px){ + .brand-name{font-size:1rem} + .account span{display:none} +} diff --git a/app/static/logo-crr.png b/app/static/logo-crr.png new file mode 100644 index 0000000..d621299 Binary files /dev/null and b/app/static/logo-crr.png differ diff --git a/app/templates/admin_month.html b/app/templates/admin_month.html new file mode 100644 index 0000000..733f2e6 --- /dev/null +++ b/app/templates/admin_month.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} +{% block content %} +
+

Manage {{ month_name }} {{ year }}

Night rows are manually assigned. Lunch rows are prefilled from their rotations and can be overridden.

+ +
+
+ + +
+ {% for assignment in assignments %} + + {% endfor %} +
DateSchedulePersonSource
{{ assignment.date.strftime('%a %d %b') }}{{ assignment.schedule.name }}{{ assignment.source }}
+
+
+{% endblock %} diff --git a/app/templates/admin_notifications.html b/app/templates/admin_notifications.html new file mode 100644 index 0000000..169c902 --- /dev/null +++ b/app/templates/admin_notifications.html @@ -0,0 +1,7 @@ +{% extends "base.html" %} +{% block content %} +

Email log

Skipped means the user has no email, disabled email notifications, or SMTP is not configured.

+
+{% for log in logs %}{% else %}{% endfor %} +
TimeEventPersonRecipientStatusSubject
{{ log.created_at.strftime('%Y-%m-%d %H:%M') }}{{ log.event_type }}{{ log.user.name if log.user else '—' }}{{ log.recipient or '—' }}{{ log.status }}{{ log.subject }}
No notifications yet.
+{% endblock %} diff --git a/app/templates/admin_schedules.html b/app/templates/admin_schedules.html new file mode 100644 index 0000000..de11371 --- /dev/null +++ b/app/templates/admin_schedules.html @@ -0,0 +1,39 @@ +{% extends "base.html" %} +{% block content %} +

Schedules

Saturday lunch and Sunday lunch rotate independently. Existing generated assignments are not rewritten when the rotation changes.

+
+{% for schedule in schedules %} +
+
+

{{ schedule.name }}

{{ schedule.schedule_type }} · weekdays {{ schedule.weekdays }} · {{ schedule.label_time }}

+
+ + + + +
+
+ {% if schedule.schedule_type == 'rotation' %} +

Rotation order

+
    + {% for member in schedule.rotation_members %} +
  1. + {{ member.user.name }} +
    +
    +
    +
    +
    +
  2. + {% else %}
  3. No members yet.
  4. {% endfor %} +
+
+ + + +
+ {% endif %} +
+{% endfor %} +
+{% endblock %} diff --git a/app/templates/admin_users.html b/app/templates/admin_users.html new file mode 100644 index 0000000..e549f3e --- /dev/null +++ b/app/templates/admin_users.html @@ -0,0 +1,36 @@ +{% extends "base.html" %} +{% block content %} +

People

Email and phone are optional. Username is used to sign in.

+
+

Add person

+
+ + + + + + + + +
+
+
+
+{% for person in users %} +
+ {{ person.name }} @{{ person.username }}{% if not person.is_active %} · inactive{% endif %} +
+ + + + + + + + +
+
+
+{% endfor %} +
+{% endblock %} diff --git a/app/templates/base.html b/app/templates/base.html new file mode 100644 index 0000000..448900b --- /dev/null +++ b/app/templates/base.html @@ -0,0 +1,46 @@ + + + + + + + {% block title %}{{ settings.app_name }}{% endblock %} + + + + +
+
+ + + {{ settings.app_name }} + + {% if current_user %} + + + {% endif %} +
+
+
+ {% if flash %} +
{{ flash.message }}
+ {% endif %} + {% block content %}{% endblock %} +
+ + diff --git a/app/templates/dashboard.html b/app/templates/dashboard.html new file mode 100644 index 0000000..c28e61b --- /dev/null +++ b/app/templates/dashboard.html @@ -0,0 +1,62 @@ +{% extends "base.html" %} +{% block content %} +
+
+

{{ month_name }} {{ year }}

+

Night duty every day, plus separate Saturday and Sunday lunch rotas.

+
+ +
+ +
+{% for day, assignments in month_days %} +
+
+ {{ day.strftime('%a') }} + {{ day.day }} +
+
+ {% for assignment in assignments %} +
+
+
{{ assignment.schedule.name }}
+
+ {% if assignment.user %}{{ assignment.user.name }}{% else %}Unassigned{% endif %} +
+
+ {% if assignment.id in my_assignment_ids and day >= today %} +
+ {% if assignment.id in open_swap_assignment_ids %} + Change requested + {% else %} +
+ Request change +
+ + + + +
+
+ {% endif %} +
+ {% endif %} +
+ {% endfor %} +
+
+{% endfor %} +
+{% endblock %} diff --git a/app/templates/login.html b/app/templates/login.html new file mode 100644 index 0000000..c98fcc4 --- /dev/null +++ b/app/templates/login.html @@ -0,0 +1,21 @@ +{% extends "base.html" %} +{% block title %}Sign in · {{ settings.app_name }}{% endblock %} +{% block content %} +
+ +

Sign in

+

Use your rota username and password.

+
+ + + + +
+
+{% endblock %} diff --git a/app/templates/swaps.html b/app/templates/swaps.html new file mode 100644 index 0000000..ede5bae --- /dev/null +++ b/app/templates/swaps.html @@ -0,0 +1,56 @@ +{% extends "base.html" %} +{% block content %} +
+

Change requests

People can volunteer for an open assignment or accept a request sent directly to them.

+
+ +
+{% for swap in swaps %} +
+
+
+
{{ swap.assignment.date.strftime('%A, %d %B %Y') }}
+

{{ swap.assignment.schedule.name }}

+

{{ swap.requester.name }} requested a change{% if swap.target_user %} with {{ swap.target_user.name }}{% else %} and opened it to anyone{% endif %}.

+ {% if swap.message %}

{{ swap.message }}

{% endif %} + {% if swap.accepted_by %}

Accepted by {{ swap.accepted_by.name }}.

{% endif %} +
+ {{ swap.status.replace('_', ' ') }} +
+ +
+ {% if swap.status == 'open' and swap.requester_id != current_user.id and (swap.target_user_id is none or swap.target_user_id == current_user.id) %} +
+ + +
+ {% endif %} + {% if swap.status == 'open' and swap.target_user_id == current_user.id %} +
+ + +
+ {% endif %} + {% if swap.requester_id == current_user.id and swap.status in ['open', 'pending_approval'] %} +
+ + +
+ {% endif %} + {% if current_user.is_admin and swap.status == 'pending_approval' %} +
+ + +
+
+ + +
+ {% endif %} +
+
+{% else %} +
No change requests yet.
+{% endfor %} +
+{% endblock %} diff --git a/app/web.py b/app/web.py new file mode 100644 index 0000000..2a43fdc --- /dev/null +++ b/app/web.py @@ -0,0 +1,783 @@ +from __future__ import annotations + +import calendar +from datetime import date, datetime + +from fastapi import APIRouter, Depends, Form, HTTPException, Request +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlalchemy import delete, func, select +from sqlalchemy.orm import Session, selectinload + +from .config import settings +from .database import get_db +from .models import Assignment, NotificationLog, RotationMember, Schedule, SwapRequest, User +from .notifications import send_email_notification, send_many +from .scheduling import assignments_by_date, ensure_month_assignments, month_bounds +from .security import hash_password, new_csrf_token, verify_password + +router = APIRouter() + + +def _redirect(path: str, status_code: int = 303) -> RedirectResponse: + return RedirectResponse(path, status_code=status_code) + + +def _current_user(request: Request, db: Session) -> User | None: + user_id = request.session.get("user_id") + if not user_id: + return None + return db.get(User, int(user_id)) + + +def _require_user(request: Request, db: Session) -> User: + user = _current_user(request, db) + if not user or not user.is_active: + raise HTTPException(status_code=401, detail="Login required") + return user + + +def _require_admin(request: Request, db: Session) -> User: + user = _require_user(request, db) + if not user.is_admin: + raise HTTPException(status_code=403, detail="Administrator access required") + return user + + +def _csrf(request: Request) -> str: + token = request.session.get("csrf") + if not token: + token = new_csrf_token() + request.session["csrf"] = token + return token + + +def _check_csrf(request: Request, token: str) -> None: + expected = request.session.get("csrf") + if not expected or token != expected: + raise HTTPException(status_code=400, detail="Invalid CSRF token") + + +def _flash(request: Request, message: str, level: str = "info") -> None: + request.session["flash"] = {"message": message, "level": level} + + +def _context(request: Request, db: Session, **extra): + return { + "request": request, + "settings": settings, + "current_user": _current_user(request, db), + "csrf_token": _csrf(request), + "flash": request.session.pop("flash", None), + **extra, + } + + +def _parse_month(year: int | None, month: int | None) -> tuple[int, int]: + today = date.today() + y = year or today.year + m = month or today.month + if m < 1 or m > 12 or y < 2000 or y > 2100: + raise HTTPException(status_code=400, detail="Invalid month") + return y, m + + +def _month_nav(year: int, month: int) -> tuple[tuple[int, int], tuple[int, int]]: + if month == 1: + prev = (year - 1, 12) + else: + prev = (year, month - 1) + if month == 12: + nxt = (year + 1, 1) + else: + nxt = (year, month + 1) + return prev, nxt + + +@router.get("/health") +def health(): + return {"status": "ok"} + + +@router.get("/login", response_class=HTMLResponse) +def login_page(request: Request, db: Session = Depends(get_db)): + if _current_user(request, db): + return _redirect("/") + return request.app.state.templates.TemplateResponse( + request=request, + name="login.html", + context=_context(request, db), + ) + + +@router.post("/login") +def login( + request: Request, + username: str = Form(...), + password: str = Form(...), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + user = db.scalar(select(User).where(func.lower(User.username) == username.strip().lower())) + if not user or not user.is_active or not verify_password(password, user.password_hash): + _flash(request, "Invalid username or password.", "error") + return _redirect("/login") + request.session["user_id"] = user.id + _flash(request, f"Welcome, {user.name}.") + return _redirect("/") + + +@router.post("/logout") +def logout(request: Request, csrf_token: str = Form(...)): + _check_csrf(request, csrf_token) + request.session.clear() + return _redirect("/login") + + +@router.get("/", response_class=HTMLResponse) +def dashboard( + request: Request, + year: int | None = None, + month: int | None = None, + db: Session = Depends(get_db), +): + user = _require_user(request, db) + year, month = _parse_month(year, month) + assignments = ensure_month_assignments(db, year, month) + grouped = assignments_by_date(assignments) + prev, nxt = _month_nav(year, month) + + my_assignment_ids = {a.id for a in assignments if a.user_id == user.id} + open_swap_assignment_ids = set( + db.scalars( + select(SwapRequest.assignment_id).where( + SwapRequest.requester_id == user.id, + SwapRequest.status.in_(["open", "pending_approval"]), + ) + ).all() + ) + + return request.app.state.templates.TemplateResponse( + request=request, + name="dashboard.html", + context=_context( + request, + db, + year=year, + month=month, + month_name=calendar.month_name[month], + month_days=[(date(year, month, d), grouped.get(date(year, month, d), [])) for d in range(1, calendar.monthrange(year, month)[1] + 1)], + grouped=grouped, + my_assignment_ids=my_assignment_ids, + open_swap_assignment_ids=open_swap_assignment_ids, + prev=prev, + nxt=nxt, + active_users=db.scalars(select(User).where(User.is_active.is_(True)).order_by(User.name)).all(), + today=date.today(), + ), + ) + + +@router.get("/swaps", response_class=HTMLResponse) +def swaps_page(request: Request, db: Session = Depends(get_db)): + user = _require_user(request, db) + query = ( + select(SwapRequest) + .options( + selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.requester), + selectinload(SwapRequest.target_user), + selectinload(SwapRequest.accepted_by), + ) + .order_by(SwapRequest.created_at.desc()) + ) + if not user.is_admin: + query = query.where( + (SwapRequest.requester_id == user.id) + | (SwapRequest.target_user_id == user.id) + | ((SwapRequest.target_user_id.is_(None)) & (SwapRequest.status == "open")) + | (SwapRequest.accepted_by_id == user.id) + ) + swaps = db.scalars(query).all() + return request.app.state.templates.TemplateResponse( + request=request, + name="swaps.html", + context=_context(request, db, swaps=swaps, today=date.today()), + ) + + +@router.post("/assignments/{assignment_id}/swap") +def create_swap( + assignment_id: int, + request: Request, + target_user_id: str = Form(""), + message: str = Form(""), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + user = _require_user(request, db) + assignment = db.scalar( + select(Assignment) + .where(Assignment.id == assignment_id) + .options(selectinload(Assignment.schedule), selectinload(Assignment.user)) + ) + if not assignment or assignment.user_id != user.id: + raise HTTPException(status_code=403, detail="You can only offer your own assignment") + if assignment.date < date.today(): + raise HTTPException(status_code=400, detail="Past assignments cannot be changed") + + existing = db.scalar( + select(SwapRequest.id).where( + SwapRequest.assignment_id == assignment.id, + SwapRequest.status.in_(["open", "pending_approval"]), + ) + ) + if existing: + _flash(request, "There is already an active change request for this assignment.", "error") + return _redirect("/swaps") + + target = None + if target_user_id.strip(): + target = db.get(User, int(target_user_id)) + if not target or not target.is_active or target.id == user.id: + raise HTTPException(status_code=400, detail="Invalid target user") + + swap = SwapRequest( + assignment_id=assignment.id, + requester_id=user.id, + target_user_id=target.id if target else None, + status="open", + message=message.strip() or None, + ) + db.add(swap) + db.commit() + + subject = f"Bar rota change request: {assignment.date:%d %b} – {assignment.schedule.name}" + body = ( + f"{user.name} is asking for someone to take their {assignment.schedule.name} assignment " + f"on {assignment.date:%A, %d %B %Y}.\n\n" + f"{message.strip()}\n\n" + f"Open the rota: {settings.normalized_base_url}/swaps" + ) + if target: + send_email_notification(db, target, "swap_requested", subject, body) + else: + candidates = db.scalars( + select(User).where(User.is_active.is_(True), User.id != user.id).order_by(User.name) + ).all() + send_many(db, candidates, "swap_requested", subject, body) + + _flash(request, "Change request created.") + return _redirect("/swaps") + + +@router.post("/swaps/{swap_id}/accept") +def accept_swap( + swap_id: int, + request: Request, + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + user = _require_user(request, db) + swap = db.scalar( + select(SwapRequest) + .where(SwapRequest.id == swap_id) + .options(selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), selectinload(SwapRequest.requester)) + ) + if not swap or swap.status != "open": + raise HTTPException(status_code=400, detail="This request is no longer open") + if swap.requester_id == user.id: + raise HTTPException(status_code=400, detail="You cannot accept your own request") + if swap.target_user_id is not None and swap.target_user_id != user.id: + raise HTTPException(status_code=403, detail="This request is for another user") + if swap.assignment.user_id != swap.requester_id: + swap.status = "cancelled" + db.commit() + raise HTTPException(status_code=409, detail="The assignment has already changed") + + swap.accepted_by_id = user.id + if swap.assignment.schedule.requires_manager_approval: + swap.status = "pending_approval" + db.commit() + admins = db.scalars(select(User).where(User.is_admin.is_(True), User.is_active.is_(True))).all() + send_many( + db, + admins, + "swap_needs_approval", + "Bar rota change needs approval", + f"{user.name} accepted {swap.requester.name}'s {swap.assignment.schedule.name} assignment " + f"for {swap.assignment.date:%d %B %Y}. Approve it at {settings.normalized_base_url}/swaps", + ) + send_email_notification( + db, + swap.requester, + "swap_accepted", + "Your rota change was accepted", + f"{user.name} accepted your request. It is now waiting for manager approval.", + ) + _flash(request, "Accepted. Waiting for manager approval.") + else: + swap.assignment.user_id = user.id + swap.assignment.source = "swap" + swap.status = "approved" + db.commit() + send_email_notification( + db, + swap.requester, + "swap_approved", + "Your rota change is confirmed", + f"{user.name} will take {swap.assignment.schedule.name} on {swap.assignment.date:%d %B %Y}.", + ) + send_email_notification( + db, + user, + "swap_approved", + "Rota assignment confirmed", + f"You are now assigned to {swap.assignment.schedule.name} on {swap.assignment.date:%d %B %Y}.", + ) + _flash(request, "Assignment transferred to you.") + return _redirect("/swaps") + + +@router.post("/swaps/{swap_id}/reject") +def reject_swap( + swap_id: int, + request: Request, + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + user = _require_user(request, db) + swap = db.scalar( + select(SwapRequest) + .where(SwapRequest.id == swap_id) + .options(selectinload(SwapRequest.requester)) + ) + if not swap or swap.status != "open": + raise HTTPException(status_code=400, detail="This request is no longer open") + if swap.target_user_id != user.id: + raise HTTPException(status_code=403, detail="Only the requested user can reject this request") + swap.status = "rejected" + db.commit() + send_email_notification( + db, + swap.requester, + "swap_rejected", + "Rota change request declined", + f"{user.name} declined your rota change request.", + ) + _flash(request, "Request declined.") + return _redirect("/swaps") + + +@router.post("/swaps/{swap_id}/cancel") +def cancel_swap( + swap_id: int, + request: Request, + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + user = _require_user(request, db) + swap = db.get(SwapRequest, swap_id) + if not swap or swap.requester_id != user.id or swap.status not in {"open", "pending_approval"}: + raise HTTPException(status_code=403, detail="Cannot cancel this request") + swap.status = "cancelled" + db.commit() + _flash(request, "Request cancelled.") + return _redirect("/swaps") + + +@router.post("/swaps/{swap_id}/approve") +def approve_swap( + swap_id: int, + request: Request, + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + _require_admin(request, db) + swap = db.scalar( + select(SwapRequest) + .where(SwapRequest.id == swap_id) + .options( + selectinload(SwapRequest.assignment).selectinload(Assignment.schedule), + selectinload(SwapRequest.requester), + selectinload(SwapRequest.accepted_by), + ) + ) + if not swap or swap.status != "pending_approval" or not swap.accepted_by: + raise HTTPException(status_code=400, detail="Request is not ready for approval") + if swap.assignment.user_id != swap.requester_id: + swap.status = "cancelled" + db.commit() + raise HTTPException(status_code=409, detail="The assignment has already changed") + + swap.assignment.user_id = swap.accepted_by_id + swap.assignment.source = "swap" + swap.status = "approved" + db.commit() + subject = "Rota change approved" + body = ( + f"The change for {swap.assignment.schedule.name} on {swap.assignment.date:%d %B %Y} was approved. " + f"{swap.accepted_by.name} is now assigned." + ) + send_many(db, [swap.requester, swap.accepted_by], "swap_approved", subject, body) + _flash(request, "Change approved and schedule updated.") + return _redirect("/swaps") + + +@router.post("/swaps/{swap_id}/admin-reject") +def admin_reject_swap( + swap_id: int, + request: Request, + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + _require_admin(request, db) + swap = db.scalar( + select(SwapRequest) + .where(SwapRequest.id == swap_id) + .options(selectinload(SwapRequest.requester), selectinload(SwapRequest.accepted_by)) + ) + if not swap or swap.status != "pending_approval": + raise HTTPException(status_code=400, detail="Request is not awaiting approval") + swap.status = "rejected" + db.commit() + users = [u for u in [swap.requester, swap.accepted_by] if u] + send_many(db, users, "swap_rejected", "Rota change not approved", "The manager did not approve the requested rota change.") + _flash(request, "Change rejected.") + return _redirect("/swaps") + + +@router.get("/admin/users", response_class=HTMLResponse) +def admin_users(request: Request, db: Session = Depends(get_db)): + _require_admin(request, db) + users = db.scalars(select(User).order_by(User.name)).all() + return request.app.state.templates.TemplateResponse( + request=request, + name="admin_users.html", + context=_context(request, db, users=users), + ) + + +@router.post("/admin/users") +def admin_create_user( + request: Request, + name: str = Form(...), + username: str = Form(...), + email: str = Form(""), + phone: str = Form(""), + password: str = Form(...), + is_admin: str = Form(""), + notify_email: str = Form(""), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + _require_admin(request, db) + username = username.strip().lower() + email_value = email.strip().lower() or None + if db.scalar(select(User.id).where(User.username == username)): + _flash(request, "Username already exists.", "error") + return _redirect("/admin/users") + if email_value and db.scalar(select(User.id).where(User.email == email_value)): + _flash(request, "Email address already exists.", "error") + return _redirect("/admin/users") + try: + password_hash = hash_password(password) + except ValueError as exc: + _flash(request, str(exc), "error") + return _redirect("/admin/users") + db.add( + User( + name=name.strip(), + username=username, + email=email_value, + phone=phone.strip() or None, + password_hash=password_hash, + is_admin=bool(is_admin), + is_active=True, + notify_email=bool(notify_email), + ) + ) + db.commit() + _flash(request, "User created.") + return _redirect("/admin/users") + + +@router.post("/admin/users/{user_id}/update") +def admin_update_user( + user_id: int, + request: Request, + name: str = Form(...), + email: str = Form(""), + phone: str = Form(""), + is_admin: str = Form(""), + is_active: str = Form(""), + notify_email: str = Form(""), + new_password: str = Form(""), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + admin = _require_admin(request, db) + user = db.get(User, user_id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + email_value = email.strip().lower() or None + duplicate = db.scalar(select(User.id).where(User.email == email_value, User.id != user.id)) if email_value else None + if duplicate: + _flash(request, "That email address is already in use.", "error") + return _redirect("/admin/users") + user.name = name.strip() + user.email = email_value + user.phone = phone.strip() or None + user.notify_email = bool(notify_email) + if user.id != admin.id: + user.is_active = bool(is_active) + else: + user.is_active = True + if user.id != admin.id: + user.is_admin = bool(is_admin) + if new_password.strip(): + try: + user.password_hash = hash_password(new_password.strip()) + except ValueError as exc: + _flash(request, str(exc), "error") + return _redirect("/admin/users") + db.commit() + _flash(request, "User updated.") + return _redirect("/admin/users") + + +@router.get("/admin/schedules", response_class=HTMLResponse) +def admin_schedules(request: Request, db: Session = Depends(get_db)): + _require_admin(request, db) + schedules = db.scalars( + select(Schedule) + .options(selectinload(Schedule.rotation_members).selectinload(RotationMember.user)) + .order_by(Schedule.id) + ).all() + users = db.scalars(select(User).where(User.is_active.is_(True)).order_by(User.name)).all() + return request.app.state.templates.TemplateResponse( + request=request, + name="admin_schedules.html", + context=_context(request, db, schedules=schedules, users=users), + ) + + +@router.post("/admin/schedules/{schedule_id}/settings") +def admin_schedule_settings( + schedule_id: int, + request: Request, + requires_manager_approval: str = Form(""), + is_active: str = Form(""), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + _require_admin(request, db) + schedule = db.get(Schedule, schedule_id) + if not schedule: + raise HTTPException(status_code=404, detail="Schedule not found") + schedule.requires_manager_approval = bool(requires_manager_approval) + schedule.is_active = bool(is_active) + db.commit() + _flash(request, "Schedule settings saved.") + return _redirect("/admin/schedules") + + +@router.post("/admin/schedules/{schedule_id}/rotation") +def admin_rotation_add( + schedule_id: int, + request: Request, + user_id: int = Form(...), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + _require_admin(request, db) + schedule = db.get(Schedule, schedule_id) + user = db.get(User, user_id) + if not schedule or schedule.schedule_type != "rotation" or not user or not user.is_active: + raise HTTPException(status_code=400, detail="Invalid rotation member") + exists = db.scalar( + select(RotationMember.id).where( + RotationMember.schedule_id == schedule.id, + RotationMember.user_id == user.id, + ) + ) + if exists: + _flash(request, "That person is already in this rotation.", "error") + return _redirect("/admin/schedules") + max_position = db.scalar( + select(func.max(RotationMember.position)).where(RotationMember.schedule_id == schedule.id) + ) or 0 + db.add(RotationMember(schedule_id=schedule.id, user_id=user.id, position=max_position + 1)) + db.commit() + _flash(request, "Rotation member added.") + return _redirect("/admin/schedules") + + +@router.post("/admin/rotation/{member_id}/remove") +def admin_rotation_remove( + member_id: int, + request: Request, + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + _require_admin(request, db) + member = db.get(RotationMember, member_id) + if not member: + raise HTTPException(status_code=404, detail="Rotation member not found") + schedule_id = member.schedule_id + db.delete(member) + db.commit() + members = db.scalars( + select(RotationMember).where(RotationMember.schedule_id == schedule_id).order_by(RotationMember.position) + ).all() + for idx, row in enumerate(members, start=1): + row.position = idx + db.commit() + _flash(request, "Rotation member removed.") + return _redirect("/admin/schedules") + + +@router.post("/admin/rotation/{member_id}/move") +def admin_rotation_move( + member_id: int, + request: Request, + direction: str = Form(...), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + _check_csrf(request, csrf_token) + _require_admin(request, db) + member = db.get(RotationMember, member_id) + if not member or direction not in {"up", "down"}: + raise HTTPException(status_code=400, detail="Invalid move") + target_position = member.position - 1 if direction == "up" else member.position + 1 + other = db.scalar( + select(RotationMember).where( + RotationMember.schedule_id == member.schedule_id, + RotationMember.position == target_position, + ) + ) + if other: + temporary = 1000000 + member.id + member.position = temporary + db.flush() + other.position = target_position + 1 if direction == "up" else target_position - 1 + db.flush() + member.position = target_position + db.commit() + return _redirect("/admin/schedules") + + +@router.get("/admin/month", response_class=HTMLResponse) +def admin_month( + request: Request, + year: int | None = None, + month: int | None = None, + db: Session = Depends(get_db), +): + _require_admin(request, db) + year, month = _parse_month(year, month) + assignments = ensure_month_assignments(db, year, month) + users = db.scalars(select(User).where(User.is_active.is_(True)).order_by(User.name)).all() + schedules = db.scalars(select(Schedule).where(Schedule.is_active.is_(True)).order_by(Schedule.id)).all() + prev, nxt = _month_nav(year, month) + return request.app.state.templates.TemplateResponse( + request=request, + name="admin_month.html", + context=_context( + request, + db, + year=year, + month=month, + month_name=calendar.month_name[month], + assignments=assignments, + users=users, + schedules=schedules, + prev=prev, + nxt=nxt, + ), + ) + + +@router.post("/admin/month/save") +async def admin_month_save( + request: Request, + db: Session = Depends(get_db), +): + _require_admin(request, db) + form = await request.form() + _check_csrf(request, str(form.get("csrf_token", ""))) + year = int(form.get("year", date.today().year)) + month = int(form.get("month", date.today().month)) + first, last = month_bounds(year, month) + assignments = db.scalars( + select(Assignment) + .where(Assignment.date >= first, Assignment.date <= last) + .options(selectinload(Assignment.user), selectinload(Assignment.schedule)) + ).all() + users_by_id = {u.id: u for u in db.scalars(select(User).where(User.is_active.is_(True))).all()} + + changed: list[tuple[Assignment, User | None, User | None]] = [] + for assignment in assignments: + raw = str(form.get(f"assignment_{assignment.id}", "")).strip() + new_user_id = int(raw) if raw else None + if new_user_id is not None and new_user_id not in users_by_id: + continue + if assignment.user_id != new_user_id: + old_user = assignment.user + new_user = users_by_id.get(new_user_id) if new_user_id else None + assignment.user_id = new_user_id + assignment.source = "manual" + changed.append((assignment, old_user, new_user)) + db.commit() + + for assignment, old_user, new_user in changed: + subject = f"Bar rota updated: {assignment.date:%d %b} – {assignment.schedule.name}" + if new_user: + send_email_notification( + db, + new_user, + "assignment_updated", + subject, + f"You are assigned to {assignment.schedule.name} on {assignment.date:%A, %d %B %Y}.\n\n" + f"View the rota: {settings.normalized_base_url}/", + ) + if old_user and (not new_user or old_user.id != new_user.id): + send_email_notification( + db, + old_user, + "assignment_changed", + subject, + f"You are no longer assigned to {assignment.schedule.name} on {assignment.date:%A, %d %B %Y}.\n\n" + f"View the rota: {settings.normalized_base_url}/", + ) + + _flash(request, f"Saved {len(changed)} assignment change(s).") + return _redirect(f"/admin/month?year={year}&month={month}") + + +@router.get("/admin/notifications", response_class=HTMLResponse) +def admin_notifications(request: Request, db: Session = Depends(get_db)): + _require_admin(request, db) + logs = db.scalars( + select(NotificationLog) + .options(selectinload(NotificationLog.user)) + .order_by(NotificationLog.created_at.desc()) + .limit(200) + ).all() + return request.app.state.templates.TemplateResponse( + request=request, + name="admin_notifications.html", + context=_context(request, db, logs=logs), + ) diff --git a/data/.gitkeep b/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..5ce78b0 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,11 @@ +services: + bar-rota: + build: . + container_name: bar-rota + restart: unless-stopped + env_file: + - .env + ports: + - "8000:8000" + volumes: + - ./data:/app/data diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..3b3b3a0 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,28 @@ +# Architecture + +## Runtime + +Single FastAPI process with server-rendered HTML and a SQLite database volume. This keeps deployment suitable for a small VPS, NAS or home server. + +## Layers + +- `models.py`: persistence schema. +- `scheduling.py`: deterministic month/rotation generation. +- `web.py`: authentication, admin editing and change-request orchestration. +- `notifications.py`: synchronous SMTP adapter + durable send log. +- `cli.py`: maintenance commands that can be run manually or by cron. + +## Data lifecycle + +1. Visiting a month calls `ensure_month_assignments`. +2. Missing Night rows are created unassigned. +3. Missing lunch rows are created from each independent rotation. +4. Admin assigns/overrides rows through the month editor. +5. Member change requests operate on concrete assignment IDs. +6. Email is attempted after the database action commits. + +## Deployment + +`docker-compose.yml` mounts `./data` at `/app/data`, so the SQLite DB persists across image rebuilds. + +For larger installations, the SQLAlchemy configuration can point to PostgreSQL, but the project intentionally ships only the SQLite deployment path today. diff --git a/docs/DOMAIN.md b/docs/DOMAIN.md new file mode 100644 index 0000000..ceaa7f4 --- /dev/null +++ b/docs/DOMAIN.md @@ -0,0 +1,66 @@ +# Domain model + +## Schedules vs assignments + +A **schedule** describes when a duty exists and how its initial assignee is chosen. An **assignment** is the actual duty on a concrete date. Once an assignment exists, it is not recalculated from the schedule. + +This distinction is intentional: editing a rotation must not retroactively change an already published month. + +## Seeded schedules + +### Night + +- Exists every day (`Monday` through `Sunday`). +- Type: `fixed`. +- Generation creates an unassigned row for every date. +- An administrator assigns a person for each date in **Manage month**. +- Once assigned, it remains fixed until explicitly edited or transferred through an approved change request. + +### Saturday Lunch + +- Saturdays only. +- Type: `rotation`. +- Has its own ordered member list. +- Uses an anchor date to continue the rotation across month boundaries. + +### Sunday Lunch + +- Sundays only. +- Type: `rotation`. +- Has its own ordered member list, independent of Saturday. + +The data model supports a schedule matching multiple weekdays even though the seeded lunch schedules each use one day. + +## Rotation generation + +For a rotation schedule, the member is chosen from the ordered active rotation members using the number of matching schedule days from the anchor date to the target date modulo member count. + +Only missing assignments are generated. Existing rows are never rewritten. + +## Change request state machine + +`open` → `pending_approval` → `approved` + +Other terminal states: `rejected`, `cancelled`. + +- A member can offer one of their future/current assignments to a specific active member or to anyone. +- The requester cannot accept their own request. +- A targeted request can only be accepted/rejected by that target. +- An open request can be accepted by any other active member. +- If the schedule requires manager approval, acceptance moves to `pending_approval`. +- Approval transfers the assignment and sets its source to `swap`. +- If the requester no longer owns the assignment, the request must not be applied. + +## Notifications + +Email is optional per user and per installation. + +Events include: +- assignment updated/removed by admin; +- change requested; +- change accepted; +- manager approval required; +- change approved/rejected; +- shift reminder. + +An email error is logged but must not undo a scheduling action. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..ff6cbf3 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,15 @@ +# Roadmap / intentionally deferred + +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. +- Holiday/special-event exceptions. +- Optional schedule eligibility groups. +- Audit log for every admin assignment edit. +- PostgreSQL deployment profile and automated backups. +- Localization (Portuguese/English). + +Not planned unless specifically requested: payroll, attendance/time clock, HR records, leave accrual, performance management. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..9d5f155 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,4 @@ +[tool.pytest.ini_options] +pythonpath = ["."] +testpaths = ["tests"] +addopts = "-ra" diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..7267c3b --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest>=8,<9 +httpx>=0.27,<1 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..669638a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +fastapi>=0.115,<1 +uvicorn[standard]>=0.30,<1 +SQLAlchemy>=2.0,<3 +Jinja2>=3.1,<4 +python-multipart>=0.0.12,<1 +itsdangerous>=2.2,<3 +email-validator>=2.2,<3 +pydantic-settings>=2.5,<3 diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py new file mode 100644 index 0000000..410e728 --- /dev/null +++ b/tests/test_bootstrap.py @@ -0,0 +1,16 @@ +from sqlalchemy import create_engine, select +from sqlalchemy.orm import Session +from sqlalchemy.pool import StaticPool + +from app.database import Base +from app.bootstrap import ensure_initial_data +from app.models import Schedule + + +def test_bootstrap_creates_three_expected_schedules(monkeypatch): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool) + Base.metadata.create_all(engine) + with Session(engine) as db: + ensure_initial_data(db) + slugs = set(db.scalars(select(Schedule.slug)).all()) + assert {"night", "saturday-lunch", "sunday-lunch"}.issubset(slugs) diff --git a/tests/test_scheduling.py b/tests/test_scheduling.py new file mode 100644 index 0000000..c3dc12a --- /dev/null +++ b/tests/test_scheduling.py @@ -0,0 +1,126 @@ +from datetime import date + +from sqlalchemy import create_engine, select +from sqlalchemy.orm import Session +from sqlalchemy.pool import StaticPool + +from app.database import Base +from app.models import Assignment, RotationMember, Schedule, User +from app.scheduling import ensure_month_assignments +from app.security import hash_password + + +def make_db() -> Session: + engine = create_engine( + "sqlite://", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + Base.metadata.create_all(engine) + return Session(engine) + + +def add_user(db: Session, name: str, pos: int) -> User: + user = User( + name=name, + username=name.lower(), + email=None, + phone=None, + password_hash=hash_password("password-123"), + is_active=True, + is_admin=False, + notify_email=False, + ) + db.add(user) + db.flush() + return user + + +def seed_schedules(db: Session): + night = Schedule( + name="Night", + slug="night", + schedule_type="fixed", + weekdays="0,1,2,3,4,5,6", + label_time="Night", + requires_manager_approval=True, + is_active=True, + ) + sat = Schedule( + name="Saturday Lunch", + slug="sat", + schedule_type="rotation", + weekdays="5", + label_time="Lunch", + requires_manager_approval=True, + is_active=True, + rotation_anchor_date=date(2026, 1, 3), + ) + sun = Schedule( + name="Sunday Lunch", + slug="sun", + schedule_type="rotation", + weekdays="6", + label_time="Lunch", + requires_manager_approval=True, + is_active=True, + rotation_anchor_date=date(2026, 1, 4), + ) + db.add_all([night, sat, sun]) + db.flush() + return night, sat, sun + + +def test_month_generation_has_daily_nights_and_independent_lunch_rotations(): + db = make_db() + users = [add_user(db, name, i) for i, name in enumerate(["Alice", "Bruno", "Carla"], 1)] + night, sat, sun = seed_schedules(db) + for schedule in [sat, sun]: + for pos, user in enumerate(users, 1): + db.add(RotationMember(schedule_id=schedule.id, user_id=user.id, position=pos)) + db.commit() + + assignments = ensure_month_assignments(db, 2026, 5) + nights = [a for a in assignments if a.schedule_id == night.id] + sats = [a for a in assignments if a.schedule_id == sat.id] + suns = [a for a in assignments if a.schedule_id == sun.id] + + assert len(nights) == 31 + assert all(a.user_id is None for a in nights) + assert all(a.date.weekday() == 5 for a in sats) + assert all(a.date.weekday() == 6 for a in suns) + assert [a.user_id for a in sats] != [] + assert [a.user_id for a in suns] != [] + + +def test_existing_assignment_is_not_rewritten_when_rotation_changes(): + db = make_db() + alice = add_user(db, "Alice", 1) + bruno = add_user(db, "Bruno", 2) + _, sat, _ = seed_schedules(db) + db.add_all([ + RotationMember(schedule_id=sat.id, user_id=alice.id, position=1), + RotationMember(schedule_id=sat.id, user_id=bruno.id, position=2), + ]) + db.commit() + + ensure_month_assignments(db, 2026, 5) + first_sat = db.scalar( + select(Assignment).where(Assignment.schedule_id == sat.id).order_by(Assignment.date).limit(1) + ) + assert first_sat is not None + original_user = first_sat.user_id + + members = db.scalars( + select(RotationMember).where(RotationMember.schedule_id == sat.id).order_by(RotationMember.position) + ).all() + members[0].position = 999 + db.flush() + members[1].position = 1 + db.flush() + members[0].position = 2 + db.commit() + + ensure_month_assignments(db, 2026, 5) + refreshed = db.get(Assignment, first_sat.id) + assert refreshed.user_id == original_user diff --git a/tests/test_security.py b/tests/test_security.py new file mode 100644 index 0000000..6ed38a1 --- /dev/null +++ b/tests/test_security.py @@ -0,0 +1,8 @@ +from app.security import hash_password, verify_password + + +def test_password_hash_roundtrip(): + encoded = hash_password("a-secure-password") + assert encoded != "a-secure-password" + assert verify_password("a-secure-password", encoded) + assert not verify_password("wrong-password", encoded)