diff --git a/AGENTS.md b/AGENTS.md index dae84b2..fb3fd9e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,9 +14,10 @@ Maintain a deliberately small, self-hosted rota application for a non-profit bar 3. Saturday and Sunday rotations are independent, each with its own configuration page (`/admin/schedules/`); the night schedule is fixed and repeats every month with a single configuration. `/admin/schedules` is the hub: it shows every schedule (kind, hours, next dates, rotation order or night pattern) and links to its configuration page. There is no public schedule page: `/`, the rota, is the only page open to signed-out visitors. 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. Signing in belongs to a `login_accounts` row (username, password, admin flag) that several people can share; a person with no login account is rota-only. A username is unique across accounts, not across people. The session stores the login account, and everything a member sees and controls is scoped to the people on it. -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. +6. A **team** (`teams`) is who works a shift; a **user** (`users`) is the login that signs in for it. Several teams can share one user, and a team without a user is rota-only. A username is unique across users. The session stores the user, and everything a member sees and controls is scoped to the teams assigned to it. +7. `/admin/teams` only selects which user signs in for each team; `/admin/users` creates the users and assigns them to teams. Neither page creates the other's records. +8. Email failure must never roll back or block a rota change. Log failures in `notification_logs`. +9. Past assignments cannot be offered for change through the member UI. ## Stack @@ -30,11 +31,11 @@ Maintain a deliberately small, self-hosted rota application for a non-profit bar ## Important files -- `app/models.py` — database schema: people (`users`) and the login accounts they share (`login_accounts`). +- `app/models.py` — database schema: the teams who work the rota (`teams`) and the users that sign in for them (`users`). - `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 login account + person + three default schedules. +- `app/bootstrap.py` — initial admin user + team + three default schedules. - `app/cli.py` — database/demo/reminder commands. - `docs/DOMAIN.md` — expected business behavior. @@ -48,6 +49,7 @@ Maintain a deliberately small, self-hosted rota application for a non-profit bar - 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. - 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. +- The history is squashed into the single baseline revision `0001_initial`, so a new database is created in one step and an existing one is adopted with `alembic stamp head` instead of being upgraded. Add new revisions on top of the baseline; do not re-introduce per-change migrations for a test environment. ## Validation before handoff diff --git a/Makefile b/Makefile index 64c2c8a..07752b2 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ dev-setup: setup # Host run with auto-reload, for fast debugging. dev: setup @test -x $(PYTHON) || (echo "Run 'make dev-setup' first." && exit 1) - $(PYTHON) -m uvicorn app.main:app --reload --port $(PORT) --proxy-headers --forwarded-allow-ips '*' + $(PYTHON) -m uvicorn app.main:app --reload --port $(PORT) --proxy-headers --forwarded-allow-ips '*' --reload-exclude 'data/*' --reload-exclude 'backups/*' --reload-exclude '.git/*' # Full app in Docker with bind mounts and auto-reload. dev-up: setup diff --git a/README.md b/README.md index 083237b..e836d5b 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ Small self-hosted rota application for a non-profit bar/club. - 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. +- Members can request that another team (or any available one) takes an assignment. - Optional manager approval before a change becomes final. -- Optional email and phone on each user; username is used for login. +- Optional email and phone on each team; users sign in with a username. - SMTP email notifications and a notification log. - Daily reminder command suitable for cron. - SQLite by default, packaged for Docker. @@ -20,7 +20,7 @@ Requirements: Python **3.12+**, `make`, and Docker Compose **2.24+** for checks. ```bash make dev-setup # creates .env if missing, .venv, and installs dependencies -make seed-demo # optional: populate example people and schedules before opening the app +make seed-demo # optional: populate example teams, users and schedules before opening the app make dev # auto-reload on http://localhost:8000 ``` @@ -30,18 +30,19 @@ Open `http://localhost:8000`. With the example configuration, the administrator To fill your own data, skip `seed-demo`, sign in as administrator, and: -1. Open **People** (`/admin/users`) and add members. Contact details are optional; credentials are optional as a pair. -2. Open **Gerir escalas** (`/admin/schedules`) to see every schedule, then configure each one: Night's repeating day-of-month pattern, Saturday's rotation, and Sunday's independent rotation. -3. View the rota (`/`) and use each schedule's configuration page to edit assignments. -4. Sign in as a member to request a change, as another member to accept it, then as admin to approve it. +1. Open **Equipas** (`/admin/teams`) and add who works the rota: one team per person, or per group of people. Contact details are optional. +2. Open **Utilizadores** (`/admin/users`) and create the logins, assigning each to the teams it signs in for. One user can cover several teams, so a team can share a single username. +3. Open **Gerir escalas** (`/admin/schedules`) to see every schedule, then configure each one: Night's repeating day-of-month pattern, Saturday's rotation, and Sunday's independent rotation. +4. View the rota (`/`) and use each schedule's configuration page to edit assignments. +5. Sign in as a member to request a change, as another member to accept it, then as admin to approve it. On either lunch schedule page, **Apply rotation** updates the displayed month's automatic shifts from the current rotation order, keeping manual assignments and completed swaps. Every row has **Regenerate** to explicitly auto-assign that date again, including manual assignments and completed swaps. **Generate after date** creates missing shifts and updates automatic assignments strictly after the chosen date through an inclusive end date, across as many months as you select; it preserves manual assignments and completed swaps. If the rotation has no active members, automatic shifts become unassigned. Ownership changes cancel any open/pending change request for that shift. -Rotation uses the previous assigned person in that same schedule as its reference, then selects the next active person in the order, wrapping to the start. This continues across months and respects manual assignments and completed swaps as references. For example, with Alice → Bruno → Carla, a previous shift assigned to Bruno means the next automatic shift goes to Carla. If no usable previous assignee exists, the schedule's anchor date supplies the starting position. +Rotation uses the previously assigned team in that same schedule as its reference, then selects the next active team in the order, wrapping to the start. This continues across months and respects manual assignments and completed swaps as references. For example, with Alice → Bruno → Carla, a previous shift assigned to Bruno means the next automatic shift goes to Carla. If no usable previous assignee exists, the schedule's anchor date supplies the starting position. -Demo seeding creates the logins **alice** and **bruno**, plus a shared **sabado** login that both **carla** and **diogo** sign in through, all with password **demo-password** for newly created accounts, together with both lunch rotations and all 31 days of the repeating Night pattern. It generates this month and next so there are future shifts available for testing changes. Re-running it preserves existing accounts, configured schedules, and assignments, including intentionally unassigned shifts. If you already opened a month before seeding, its existing rows stay as they were; use the next month or edit them in the admin UI. +Demo seeding creates the users **alice** and **bruno**, plus a shared **sabado** user that both the **carla** and the **diogo** teams sign in through, all with password **demo-password** for newly created accounts, together with both lunch rotations and all 31 days of the repeating Night pattern. It generates this month and next so there are future shifts available for testing changes. Re-running it preserves existing accounts, configured schedules, and assignments, including intentionally unassigned shifts. If you already opened a month before seeding, its existing rows stay as they were; use the next month or edit them in the admin UI. -**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. +**Important:** the initial admin is only created when the database has no teams. Changing `INITIAL_ADMIN_PASSWORD` later does not reset that account; reset it from the Utilizadores screen. ## Develop in Docker @@ -118,9 +119,10 @@ make db-shell RUNTIME=docker A console session exposes `db`, `select`, `models`, and all model classes: ```python -people = db.scalars(select(User).order_by(User.name)).all() -[(person.id, person.name) for person in people] -db.add(User(name="New member", is_active=True)) # rota-only person +teams = db.scalars(select(Team).order_by(Team.name)).all() +[(team.id, team.name, team.user.username if team.user else None) for team in teams] +db.add(Team(name="New team", is_active=True)) # nobody signs in for it +db.add(User(name="Equipa de sábado", username="sabado", password_hash=hash_password("..."))) db.commit() # explicitly save edits # db.rollback() # discard uncommitted edits ``` @@ -129,7 +131,7 @@ Exit with Ctrl-D. Use the admin UI for normal rota edits and swaps so workflow v The SQLite file can also be opened with a SQLite database editor. With the default configuration it is `data/bar_rota.db`; use Alembic for schema edits so code and database stay in sync. -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. +The migration history is squashed into a single `0001_initial` revision that creates the whole schema, so a new database is built in one step. An existing database is adopted with `alembic stamp head` (`python -m app.cli stamp`, or `make migrate` after the stamp): its tables are already the baseline schema, so nothing is rebuilt and no data is touched. A database with no version stamp at all is stamped at the baseline and upgraded from there. `tests/test_migrations.py` fails if the models and the migrations drift apart. ## Tests @@ -143,7 +145,7 @@ docker compose -f docker-compose.dev.yml --profile check run --rm checks `make check` runs `python -m compileall -q app && pytest -ra` against the working tree. -Keep `make dev` or `make dev-up` running in one terminal and run `make check` in another. You can keep adding people and editing the rota while checks run: the checks container does **not** load `.env` or mount your `data/` directory. Its database is disposable, and individual tests use temporary/in-memory databases. Stopping or rebuilding the development app does not delete your populated database. +Keep `make dev` or `make dev-up` running in one terminal and run `make check` in another. You can keep adding teams and editing the rota while checks run: the checks container does **not** load `.env` or mount your `data/` directory. Its database is disposable, and individual tests use temporary/in-memory databases. Stopping or rebuilding the development app does not delete your populated database. ## Project documentation diff --git a/app/bootstrap.py b/app/bootstrap.py index 747b822..fc91d39 100644 --- a/app/bootstrap.py +++ b/app/bootstrap.py @@ -6,19 +6,19 @@ from sqlalchemy import select from sqlalchemy.orm import Session from .config import settings -from .models import LoginAccount, Schedule, User +from .models import Schedule, Team, 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: + team_count = db.scalar(select(Team.id).limit(1)) + if team_count is None: db.add( - User( + Team( name=settings.initial_admin_name, email=settings.initial_admin_email or None, phone=None, - login=LoginAccount( + user=User( name=settings.initial_admin_name, username=settings.initial_admin_username, password_hash=hash_password(settings.initial_admin_password), diff --git a/app/calendar.py b/app/calendar.py index ff716a8..91e9c21 100644 --- a/app/calendar.py +++ b/app/calendar.py @@ -15,7 +15,7 @@ from sqlalchemy.orm import Session, selectinload from .config import settings from .i18n import day_long, day_numeric_long, window_label -from .models import Assignment, Schedule, User +from .models import Assignment, Schedule, Team # How much of the rota the feed publishes: recent history and the next months. MONTHS_BACK = 1 @@ -92,21 +92,21 @@ def _escape(value: str) -> str: ) -def _event(assignment: Assignment, person: User | None, tzid: str) -> list[str]: +def _event(assignment: Assignment, team: Team | None, tzid: str) -> list[str]: schedule = assignment.schedule start = datetime.combine(assignment.date, schedule.start_time) end = datetime.combine(assignment.date, schedule.end_time) if end <= start: # a shift that runs past midnight end += timedelta(days=1) - # The person's name is part of the event title, so a list of shifts reads at a glance. - summary = f"{person.name} · {schedule.name} · {window_label(schedule.start_time, schedule.end_time)}" \ - if person is not None else f"{schedule.name} · {window_label(schedule.start_time, schedule.end_time)}" + # The team's name is part of the event title, so a list of shifts reads at a glance. + summary = f"{team.name} · {schedule.name} · {window_label(schedule.start_time, schedule.end_time)}" \ + if team is not None else f"{schedule.name} · {window_label(schedule.start_time, schedule.end_time)}" description = [ day_long(assignment.date), f"{schedule.start_time:%H:%M}–{schedule.end_time:%H:%M}", ] - if person is not None: - description.append(f"Pessoa: {person.name}") + if team is not None: + description.append(f"Equipa: {team.name}") description.append(settings.app_name) return [ "BEGIN:VEVENT", @@ -126,8 +126,8 @@ def _host() -> str: return (settings.base_url.split("//")[-1] or "localhost").split("/")[0] -def build_feed(db: Session, person: User | None, name: str) -> str: - """The whole rota, or only the shifts of one person.""" +def build_feed(db: Session, team: Team | None, name: str) -> str: + """The whole rota, or only the shifts of one team.""" today = date.today() first = (today.replace(day=1) - timedelta(days=31 * MONTHS_BACK)).replace(day=1) last = (today.replace(day=1) + timedelta(days=32 * MONTHS_FORWARD)).replace(day=1) - timedelta(days=1) @@ -140,11 +140,11 @@ def build_feed(db: Session, person: User | None, name: str) -> str: Assignment.date <= last, Assignment.schedule_id.in_([s.id for s in schedules]), ) - .options(selectinload(Assignment.schedule), selectinload(Assignment.user)) + .options(selectinload(Assignment.schedule), selectinload(Assignment.team)) .order_by(Assignment.date) ).all() - if person is not None: - assignments = [a for a in assignments if a.user_id == person.id] + if team is not None: + assignments = [a for a in assignments if a.team_id == team.id] tzid = feed_timezone() lines = [ @@ -161,7 +161,7 @@ def build_feed(db: Session, person: User | None, name: str) -> str: ] lines.extend(_timezone_block(tzid)) for assignment in assignments: - lines.extend(_event(assignment, assignment.user, tzid)) + lines.extend(_event(assignment, assignment.team, tzid)) lines.append("END:VCALENDAR") folded: list[str] = [] for line in lines: diff --git a/app/cli.py b/app/cli.py index d70dab3..a3b890d 100644 --- a/app/cli.py +++ b/app/cli.py @@ -19,12 +19,12 @@ from .database import ( from . import models from .models import ( Assignment, - LoginAccount, + User, MonthlyPattern, NotificationLog, RotationMember, Schedule, - User, + Team, ) from .i18n import day_long, day_numeric from .notifications import send_email_notification @@ -51,32 +51,32 @@ def init_db() -> None: def seed_demo() -> None: init_db() - # The last two share one login, the way a team would in real life. - demo_people = [ + # Carla and Diogo are two teams covered by the same user, as a real team would be. + demo_teams = [ ("Alice", "alice", "alice@example.com"), ("Bruno", "bruno", "bruno@example.com"), ("Carla", "sabado", None), ("Diogo", "sabado", "diogo@example.com"), ] with SessionLocal() as db: - for name, username, email in demo_people: - if db.scalar(select(User.id).where(User.name == name)): - continue # this person is already there, whoever they sign in with - account = db.scalar(select(LoginAccount).where(LoginAccount.username == username)) - if account is None: - account = LoginAccount( - name=name, + for name, username, email in demo_teams: + if db.scalar(select(Team.id).where(Team.name == name)): + continue # this team is already there, whoever signs in for it + user = db.scalar(select(User).where(User.username == username)) + if user is None: + user = User( + name=username.capitalize(), username=username, password_hash=hash_password("demo-password"), is_admin=False, is_active=True, ) - db.add(account) + db.add(user) db.flush() db.add( - User( + Team( name=name, - login=account, + user=user, email=email, phone=None, is_active=True, @@ -84,19 +84,19 @@ def seed_demo() -> None: ) ) db.commit() - people = db.scalars( - select(User) - .join(LoginAccount) - .where(LoginAccount.username.in_([x[1] for x in demo_people])) - .order_by(User.name) + teams = db.scalars( + select(Team) + .join(User) + .where(User.username.in_([x[1] for x in demo_teams])) + .order_by(Team.name) ).all() schedules = db.scalars( select(Schedule).where(Schedule.slug.in_(["saturday-lunch", "sunday-lunch"])).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)) + for pos, team in enumerate(teams, start=1): + db.add(RotationMember(schedule_id=schedule.id, team_id=team.id, position=pos)) night = db.scalar(select(Schedule).where(Schedule.slug == "night")) if night is not None and not db.scalar( @@ -106,7 +106,7 @@ def seed_demo() -> None: db.add(MonthlyPattern( schedule_id=night.id, day_of_month=day, - user_id=people[(day - 1) % len(people)].id, + team_id=teams[(day - 1) % len(teams)].id, )) db.commit() @@ -115,7 +115,7 @@ def seed_demo() -> None: for month in (today, next_month): ensure_month_assignments(db, month.year, month.month) print("Demo data seeded for this month and next. Existing assignments and configuration preserved.") - print("Demo logins: alice, bruno, sabado (Carla e Diogo entram com a mesma conta). " + print("Demo users: alice, bruno, sabado (Carla e Diogo entram com o mesmo utilizador). " "Password: demo-password (new accounts only).") @@ -125,11 +125,11 @@ def db_shell() -> None: with SessionLocal() as db: namespace = {"db": db, "select": select, "models": models} namespace.update({name: getattr(models, name) for name in ( - "User", "LoginAccount", "Schedule", "MonthlyPattern", "RotationMember", "Assignment", "SwapRequest", "NotificationLog" + "Team", "User", "Schedule", "MonthlyPattern", "RotationMember", "Assignment", "SwapRequest", "NotificationLog" )}) code.interact( banner="Database console: db, select, models and model classes are available.\n" - "Example: db.scalars(select(User)).all()\n" + "Example: db.scalars(select(Team)).all()\n" "Use db.commit() to save edits, db.rollback() to discard them; Ctrl-D to exit.", local=namespace, ) @@ -143,17 +143,17 @@ def send_reminders() -> None: 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)) + .where(Assignment.date == target, Assignment.team_id.is_not(None)) + .options(selectinload(Assignment.team), selectinload(Assignment.schedule)) ).all() count = 0 for assignment in assignments: - if not assignment.user: + if not assignment.team: continue subject = f"Lembrete de turno: {assignment.schedule.name} a {day_numeric(assignment.date)}" already_sent = db.scalar( select(NotificationLog.id).where( - NotificationLog.user_id == assignment.user.id, + NotificationLog.team_id == assignment.team.id, NotificationLog.event_type == "shift_reminder", NotificationLog.subject == subject, NotificationLog.status == "sent", @@ -163,7 +163,7 @@ def send_reminders() -> None: continue send_email_notification( db, - assignment.user, + assignment.team, "shift_reminder", subject, f"Lembrete: está atribuído ao turno de {assignment.schedule.name} a " diff --git a/app/models.py b/app/models.py index f08bcbc..cadaa31 100644 --- a/app/models.py +++ b/app/models.py @@ -19,10 +19,11 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from .database import Base -class LoginAccount(Base): - """A login several people share, so a team signs in with one username.""" +class User(Base): + """A login: a username, a password and the administrator flag. Several teams can be + assigned to it, so one person can sign in once and control the shifts of all of them.""" - __tablename__ = "login_accounts" + __tablename__ = "users" id: Mapped[int] = mapped_column(Integer, primary_key=True) name: Mapped[str] = mapped_column(String(120), nullable=False) @@ -32,21 +33,26 @@ class LoginAccount(Base): is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - people: Mapped[list[User]] = relationship(back_populates="login") + teams: Mapped[list[Team]] = relationship(back_populates="user") @property def can_login(self) -> bool: return bool(self.username and self.password_hash) + @property + def label(self) -> str: + return self.name or self.username -class User(Base): - __tablename__ = "users" + +class Team(Base): + """Who works a shift: one person, or the people who cover it together. Every rota + row, rotation position, pattern day and change request names a team.""" + + __tablename__ = "teams" id: Mapped[int] = mapped_column(Integer, primary_key=True) name: Mapped[str] = mapped_column(String(120), nullable=False) - login_id: Mapped[int | None] = mapped_column( - ForeignKey("login_accounts.id", ondelete="SET NULL"), nullable=True - ) + user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True) email: Mapped[str | None] = mapped_column(String(254), unique=True, nullable=True) phone: Mapped[str | None] = mapped_column(String(40), nullable=True) calendar_token: Mapped[str | None] = mapped_column(String(64), unique=True, nullable=True) @@ -54,21 +60,21 @@ class User(Base): notify_email: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - login: Mapped[LoginAccount | None] = relationship(back_populates="people") + user: Mapped[User | None] = relationship(back_populates="teams") @property def can_login(self) -> bool: - """Whether this person signs in at all, through a shared login or their own.""" - return self.login is not None + """Whether anyone signs in for this team.""" + return self.user is not None @property def is_admin(self) -> bool: - """Administrator rights belong to the login, so every person sharing it has them.""" - return bool(self.login and self.login.is_admin) + """Administrator rights belong to the user, so every team it covers has them.""" + return bool(self.user and self.user.is_admin) @property def username(self) -> str | None: - return self.login.username if self.login else None + return self.user.username if self.user else None class Schedule(Base): @@ -100,7 +106,7 @@ class Schedule(Base): class MonthlyPattern(Base): - """One person per calendar day of the month, repeating every month.""" + """One team per calendar day of the month, repeating every month.""" __tablename__ = "monthly_patterns" __table_args__ = ( @@ -111,26 +117,26 @@ class MonthlyPattern(Base): id: Mapped[int] = mapped_column(Integer, primary_key=True) schedule_id: Mapped[int] = mapped_column(ForeignKey("schedules.id", ondelete="CASCADE"), nullable=False) day_of_month: Mapped[int] = mapped_column(Integer, nullable=False) - user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True) + team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.id", ondelete="SET NULL"), nullable=True) schedule: Mapped[Schedule] = relationship(back_populates="pattern_days") - user: Mapped[User | None] = relationship() + team: Mapped[Team | None] = relationship() class RotationMember(Base): __tablename__ = "rotation_members" __table_args__ = ( - UniqueConstraint("schedule_id", "user_id", name="uq_rotation_schedule_user"), + UniqueConstraint("schedule_id", "team_id", name="uq_rotation_schedule_team"), 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) + team_id: Mapped[int] = mapped_column(ForeignKey("teams.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() + team: Mapped[Team] = relationship() class Assignment(Base): @@ -140,13 +146,13 @@ class Assignment(Base): 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) + team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.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() + team: Mapped[Team | None] = relationship() class SwapRequest(Base): @@ -160,9 +166,9 @@ class SwapRequest(Base): target_assignment_id: Mapped[int | None] = mapped_column( ForeignKey("assignments.id", ondelete="SET NULL"), nullable=True ) - 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) + requester_id: Mapped[int] = mapped_column(ForeignKey("teams.id", ondelete="CASCADE"), nullable=False) + target_team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.id", ondelete="SET NULL"), nullable=True) + accepted_team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.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) @@ -170,16 +176,16 @@ class SwapRequest(Base): assignment: Mapped[Assignment] = relationship(foreign_keys=[assignment_id]) target_assignment: Mapped[Assignment | None] = relationship(foreign_keys=[target_assignment_id]) - 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]) + requester: Mapped[Team] = relationship(foreign_keys=[requester_id]) + target_team: Mapped[Team | None] = relationship(foreign_keys=[target_team_id]) + accepted_by: Mapped[Team | None] = relationship(foreign_keys=[accepted_team_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) + team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.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) @@ -190,4 +196,4 @@ class NotificationLog(Base): 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() + team: Mapped[Team | None] = relationship() diff --git a/app/notifications.py b/app/notifications.py index bce224d..10076a3 100644 --- a/app/notifications.py +++ b/app/notifications.py @@ -7,19 +7,19 @@ from email.message import EmailMessage from sqlalchemy.orm import Session from .config import settings -from .models import NotificationLog, User +from .models import NotificationLog, Team def send_email_notification( db: Session, - user: User, + team: Team, event_type: str, subject: str, body: str, ) -> NotificationLog: - recipient = user.email + recipient = team.email log = NotificationLog( - user_id=user.id, + team_id=team.id, event_type=event_type, channel="email", recipient=recipient, @@ -28,7 +28,7 @@ def send_email_notification( status="skipped", ) - if not user.notify_email or not recipient: + if not team.notify_email or not recipient: log.error = "Notificações por e-mail desativadas ou sem endereço de e-mail" db.add(log) db.commit() @@ -66,14 +66,14 @@ def send_email_notification( def send_many( db: Session, - users: list[User], + teams: list[Team], event_type: str, subject: str, body: str, ) -> None: seen: set[int] = set() - for user in users: - if user.id in seen: + for team in teams: + if team.id in seen: continue - seen.add(user.id) - send_email_notification(db, user, event_type, subject, body) + seen.add(team.id) + send_email_notification(db, team, event_type, subject, body) diff --git a/app/scheduling.py b/app/scheduling.py index 1ef0451..12e1c78 100644 --- a/app/scheduling.py +++ b/app/scheduling.py @@ -7,7 +7,7 @@ from datetime import date, timedelta from sqlalchemy import select from sqlalchemy.orm import Session, selectinload -from .models import Assignment, MonthlyPattern, RotationMember, Schedule, User +from .models import Assignment, MonthlyPattern, RotationMember, Schedule, Team def month_bounds(year: int, month: int) -> tuple[date, date]: @@ -48,64 +48,64 @@ def _rotation_occurrence_index(schedule: Schedule, target: date) -> int: return count -def rotation_user_for_date(db: Session, schedule: Schedule, target: date) -> User | None: +def rotation_team_for_date(db: Session, schedule: Schedule, target: date) -> Team | None: """Continue after the last actual assignee in this schedule, with anchor fallback.""" 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) + .join(Team, RotationMember.team_id == Team.id) .where(RotationMember.schedule_id == schedule.id) .order_by(RotationMember.position) - .options(selectinload(RotationMember.user)) + .options(selectinload(RotationMember.team)) ).all() - active_members = [member for member in members if member.user.is_active] + active_members = [member for member in members if member.team.is_active] if not active_members: return None - previous_user_id = db.scalar( - select(Assignment.user_id) + previous_team_id = db.scalar( + select(Assignment.team_id) .where( Assignment.schedule_id == schedule.id, Assignment.date < target, - Assignment.user_id.is_not(None), + Assignment.team_id.is_not(None), ) .order_by(Assignment.date.desc()) .limit(1) ) for idx, member in enumerate(members): - if member.user_id == previous_user_id: + if member.team_id == previous_team_id: for offset in range(1, len(members) + 1): next_member = members[(idx + offset) % len(members)] - if next_member.user.is_active: - return next_member.user + if next_member.team.is_active: + return next_member.team # No usable reference yet (or the last assignee left the rotation). idx = _rotation_occurrence_index(schedule, target) % len(active_members) - return active_members[idx].user + return active_members[idx].team -def pattern_user_for_date(db: Session, schedule: Schedule, target: date) -> User | None: - """The person configured for this calendar day of the month, if any.""" +def pattern_team_for_date(db: Session, schedule: Schedule, target: date) -> Team | None: + """The team configured for this calendar day of the month, if any.""" row = db.scalar( select(MonthlyPattern) .where(MonthlyPattern.schedule_id == schedule.id, MonthlyPattern.day_of_month == target.day) - .options(selectinload(MonthlyPattern.user)) + .options(selectinload(MonthlyPattern.team)) ) - if row is None or row.user is None or not row.user.is_active: + if row is None or row.team is None or not row.team.is_active: return None - return row.user + return row.team -def pattern_users(db: Session, schedule: Schedule) -> dict[int, int]: - """Active person per calendar day of the month, for a `fixed` schedule.""" +def pattern_teams(db: Session, schedule: Schedule) -> dict[int, int]: + """Active team per calendar day of the month, for a `fixed` schedule.""" rows = db.scalars( select(MonthlyPattern) .where(MonthlyPattern.schedule_id == schedule.id) - .options(selectinload(MonthlyPattern.user)) + .options(selectinload(MonthlyPattern.team)) ).all() - return {row.day_of_month: row.user.id for row in rows if row.user is not None and row.user.is_active} + return {row.day_of_month: row.team.id for row in rows if row.team is not None and row.team.is_active} def ensure_month_assignments(db: Session, year: int, month: int) -> list[Assignment]: @@ -118,7 +118,7 @@ def ensure_month_assignments(db: Session, year: int, month: int) -> list[Assignm changed = False for schedule in schedules: - patterns = pattern_users(db, schedule) if schedule.schedule_type == "fixed" else {} + patterns = pattern_teams(db, schedule) if schedule.schedule_type == "fixed" else {} for day in iter_month_dates(year, month): if day.weekday() not in schedule.weekday_set: continue @@ -126,18 +126,18 @@ def ensure_month_assignments(db: Session, year: int, month: int) -> list[Assignm if key in existing_keys: continue - user_id = None + team_id = None if schedule.schedule_type == "rotation": - user = rotation_user_for_date(db, schedule, day) - user_id = user.id if user else None + team = rotation_team_for_date(db, schedule, day) + team_id = team.id if team else None else: - user_id = patterns.get(day.day) + team_id = patterns.get(day.day) db.add( Assignment( schedule_id=schedule.id, date=day, - user_id=user_id, + team_id=team_id, source="generated", ) ) @@ -152,7 +152,7 @@ def ensure_month_assignments(db: Session, year: int, month: int) -> list[Assignm db.scalars( select(Assignment) .where(Assignment.date >= first, Assignment.date <= last) - .options(selectinload(Assignment.user), selectinload(Assignment.schedule)) + .options(selectinload(Assignment.team), selectinload(Assignment.schedule)) .order_by(Assignment.date, Assignment.schedule_id) ).all() ) diff --git a/app/static/app.css b/app/static/app.css index 5d5162a..683250d 100644 --- a/app/static/app.css +++ b/app/static/app.css @@ -79,7 +79,7 @@ input:focus,select:focus,button:focus-visible,a:focus-visible,summary:focus-visi .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} +.assignment-team{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} diff --git a/app/templates/account.html b/app/templates/account.html index 2a94e70..0e1d40e 100644 --- a/app/templates/account.html +++ b/app/templates/account.html @@ -5,9 +5,9 @@

Rota

A minha conta

-

{{ current_login.name or current_login.username }} · @{{ current_login.username }}

- {% if current_people %} -

Esta conta entra em nome de {{ current_people|length }} pessoa(s): {{ current_people|map(attribute='name')|join(', ') }}. Vê e controla os turnos de todas.

+

{{ current_user.name or current_user.username }} · @{{ current_user.username }}

+ {% if current_teams %} +

Este utilizador entra em nome de {{ current_teams|length }} equipa(s): {{ current_teams|map(attribute='name')|join(', ') }}. Vê e controla os turnos de todas.

{% endif %}
diff --git a/app/templates/admin_assign.html b/app/templates/admin_assign.html index ade5026..98b59ee 100644 --- a/app/templates/admin_assign.html +++ b/app/templates/admin_assign.html @@ -5,7 +5,7 @@

Escalas

Atribuição por dia

-

Escolha o dia e a pessoa que fica com cada turno. É uma atribuição direta, não uma troca.

+

Escolha o dia e a equipa que fica com cada turno. É uma atribuição direta, não uma troca.

@@ -29,19 +29,19 @@ {{ row.schedule.name }} · {{ row.schedule|horario }}
- {% if row.assignment.user %} - Agora: {{ row.assignment.user.name }} ({{ row.assignment.source|origem }}) + {% if row.assignment.team %} + Agora: {{ row.assignment.team.name }} ({{ row.assignment.source|origem }}) {% else %} Agora: sem atribuição {% endif %}
- - - {% for person in users %} - + + {% for team in teams %} + {% endfor %} @@ -51,7 +51,7 @@
Este dia não tem turnos.
{% endfor %} -

Atribuir aqui fecha qualquer pedido de troca em aberto sobre esse turno e avisa a nova pessoa e a anterior.

-

«Automático» repõe a pessoa que a escala dá a este dia — a ordem da rotação ou o padrão de noites — e volta a marcar o turno como automático.

+

Atribuir aqui fecha qualquer pedido de troca em aberto sobre esse turno e avisa a nova equipa e a anterior.

+

«Automático» repõe a equipa que a escala dá a este dia — a ordem da rotação ou o padrão de noites — e volta a marcar o turno como automático.

{% endblock %} \ No newline at end of file diff --git a/app/templates/admin_logins.html b/app/templates/admin_logins.html deleted file mode 100644 index a3bc8dc..0000000 --- a/app/templates/admin_logins.html +++ /dev/null @@ -1,47 +0,0 @@ -{% extends "base.html" %} -{% block content %} -
-
-

Contas de acesso

-

Uma conta tem utilizador e palavra-passe e pode ser partilhada por várias pessoas. Quem entra por uma conta vê e controla os turnos de todas as pessoas que a usam, e a administração é da conta, não da pessoa.

-
-
-
-
-

Adicionar conta

- -
- - - - - - - -

Depois de criada, atribua as pessoas a esta conta em Pessoas.

-
-
-{% for account in logins %} -
- @{{ account.username }} {{ account.name }}{% if account.is_admin %} · administrador{% endif %}{% if not account.is_active %} · inativa{% endif %} · {{ account.people|length }} pessoa(s) -
- - - - - - -
- {% if account.id in removable_ids %} -
- {% endif %} -
- {% if account.people %} -

Pessoas: {% for person in account.people %}{{ person.name }}{% if not person.is_active %} (inativa){% endif %}{% if not loop.last %}, {% endif %}{% endfor %}

- {% else %} -

Ainda sem pessoas.

- {% endif %} -
-{% endfor %} -
-{% endblock %} \ No newline at end of file diff --git a/app/templates/admin_notifications.html b/app/templates/admin_notifications.html index 2444bb9..2706c90 100644 --- a/app/templates/admin_notifications.html +++ b/app/templates/admin_notifications.html @@ -1,8 +1,8 @@ {% extends "base.html" %} {% block title %}Registo de e-mails · {{ settings.app_name }}{% endblock %} {% block content %} -

Registo de e-mails

«ignorado» significa que a pessoa não tem e-mail, que tem as notificações desligadas ou que o SMTP não está configurado.

-
-{% for log in logs %}{% else %}{% endfor %} +

Registo de e-mails

«ignorado» significa que a equipa não tem e-mail, que tem as notificações desligadas ou que o SMTP não está configurado.

+
Data e horaEventoPessoaDestinatárioEstadoAssunto
{{ log.created_at|momento }}{{ log.event_type|evento }}{{ log.user.name if log.user else '—' }}{{ log.recipient or '—' }}{{ log.status|estado_email }}{{ log.subject }}
Ainda não há notificações.
+{% for log in logs %}{% else %}{% endfor %}
Data e horaEventoEquipaDestinatárioEstadoAssunto
{{ log.created_at|momento }}{{ log.event_type|evento }}{{ log.team.name if log.team else '—' }}{{ log.recipient or '—' }}{{ log.status|estado_email }}{{ log.subject }}
Ainda não há notificações.
{% endblock %} diff --git a/app/templates/admin_schedule.html b/app/templates/admin_schedule.html index 7aa5f92..90a350a 100644 --- a/app/templates/admin_schedule.html +++ b/app/templates/admin_schedule.html @@ -44,9 +44,9 @@
-
+
DataPessoaOrigemAção
{% for assignment in assignments %} - + {% endfor %}
DataEquipaOrigemAção
{{ assignment.date|dia }}{{ assignment.source|origem }}
{{ assignment.date|dia }}{{ assignment.source|origem }}
@@ -67,10 +67,10 @@
    {% for member in schedule.rotation_members %}
  1. - {{ member.user.name }} + {{ member.team.name }}
    - -
    +
    +
  2. @@ -78,7 +78,7 @@
- +
@@ -92,7 +92,7 @@ {% endfor %} @@ -107,13 +107,13 @@ -

Atualiza os turnos automáticos já existentes do mês e ano escolhidos e de todos os seguintes, para refletirem o padrão guardado acima. As atribuições manuais e as trocas concluídas são mantidas, os dias sem pessoa no padrão ficam como estão e nenhum turno é criado.

+

Atualiza os turnos automáticos já existentes do mês e ano escolhidos e de todos os seguintes, para refletirem o padrão guardado acima. As atribuições manuais e as trocas concluídas são mantidas, os dias sem equipa no padrão ficam como estão e nenhum turno é criado.

{% endif %}

Pedidos de troca

-

Um administrador pode atribuir o turno a outra pessoa, mesmo que essa pessoa não entre na aplicação. Só se aplica se quem pediu a troca continuar a ser o titular do turno.

+

Um administrador pode atribuir o turno a outra equipa, mesmo que nenhuma pessoa entre na aplicação por ela. Só se aplica se quem pediu a troca continuar a ser o titular do turno.