From f4dade9eec8396cd04f395539d9896b3fdd0c166 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 6 Oct 2026 18:17:18 +0100 Subject: [PATCH] feat: account share --- AGENTS.md | 6 +- app/bootstrap.py | 12 +- app/cli.py | 61 +- app/models.py | 40 +- app/templates/account.html | 9 +- app/templates/admin_logins.html | 47 ++ app/templates/admin_schedules.html | 8 + app/templates/admin_user_delete.html | 2 +- app/templates/admin_users.html | 43 +- app/templates/base.html | 15 +- app/templates/dashboard.html | 4 +- app/templates/schedule.html | 2 +- app/templates/schedules.html | 2 +- app/templates/swaps.html | 14 +- app/web.py | 539 ++++++++++++++---- docs/DOMAIN.md | 24 +- .../c3f8a1d05b7e_shared_login_accounts.py | 94 +++ tests/factories.py | 69 +++ tests/test_admin_schedule_assignments.py | 65 ++- tests/test_calendar.py | 16 +- tests/test_cli.py | 28 +- tests/test_migrations.py | 44 +- tests/test_public_schedules.py | 45 +- tests/test_scheduling.py | 4 - tests/test_users.py | 323 +++++++++-- 25 files changed, 1185 insertions(+), 331 deletions(-) create mode 100644 app/templates/admin_logins.html create mode 100644 migrations/versions/c3f8a1d05b7e_shared_login_accounts.py create mode 100644 tests/factories.py diff --git a/AGENTS.md b/AGENTS.md index 8539660..80e5c7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ 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. The `/admin/schedules` and `/schedules` pages are hubs that link to one page per schedule. 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`/`password` are optional as a pair: a person either signs in or is rota-only. A `username`, when set, is unique. +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. @@ -30,11 +30,11 @@ Maintain a deliberately small, self-hosted rota application for a non-profit bar ## Important files -- `app/models.py` — database schema. +- `app/models.py` — database schema: people (`users`) and the login accounts they share (`login_accounts`). - `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/bootstrap.py` — initial admin login account + person + three default schedules. - `app/cli.py` — database/demo/reminder commands. - `docs/DOMAIN.md` — expected business behavior. diff --git a/app/bootstrap.py b/app/bootstrap.py index c4bd792..747b822 100644 --- a/app/bootstrap.py +++ b/app/bootstrap.py @@ -6,7 +6,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session from .config import settings -from .models import Schedule, User +from .models import LoginAccount, Schedule, User from .security import hash_password @@ -16,11 +16,15 @@ def ensure_initial_data(db: Session) -> 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, + login=LoginAccount( + name=settings.initial_admin_name, + username=settings.initial_admin_username, + password_hash=hash_password(settings.initial_admin_password), + is_admin=True, + is_active=True, + ), is_active=True, ) ) diff --git a/app/cli.py b/app/cli.py index c88a26c..d70dab3 100644 --- a/app/cli.py +++ b/app/cli.py @@ -17,7 +17,15 @@ from .database import ( stamp, ) from . import models -from .models import Assignment, MonthlyPattern, NotificationLog, RotationMember, Schedule, User +from .models import ( + Assignment, + LoginAccount, + MonthlyPattern, + NotificationLog, + RotationMember, + Schedule, + User, +) from .i18n import day_long, day_numeric from .notifications import send_email_notification from .scheduling import ensure_month_assignments @@ -43,29 +51,45 @@ 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 = [ ("Alice", "alice", "alice@example.com"), ("Bruno", "bruno", "bruno@example.com"), - ("Carla", "carla", None), - ("Diogo", "diogo", "diogo@example.com"), + ("Carla", "sabado", None), + ("Diogo", "sabado", "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, - ) + 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, + username=username, + password_hash=hash_password("demo-password"), + is_admin=False, + is_active=True, ) + db.add(account) + db.flush() + db.add( + User( + name=name, + login=account, + email=email, + phone=None, + is_active=True, + 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() + people = db.scalars( + select(User) + .join(LoginAccount) + .where(LoginAccount.username.in_([x[1] for x in demo_people])) + .order_by(User.name) + ).all() schedules = db.scalars( select(Schedule).where(Schedule.slug.in_(["saturday-lunch", "sunday-lunch"])).order_by(Schedule.id) ).all() @@ -91,7 +115,8 @@ 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, carla, diogo. Password: demo-password (new accounts only).") + print("Demo logins: alice, bruno, sabado (Carla e Diogo entram com a mesma conta). " + "Password: demo-password (new accounts only).") def db_shell() -> None: @@ -100,7 +125,7 @@ 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", "Schedule", "MonthlyPattern", "RotationMember", "Assignment", "SwapRequest", "NotificationLog" + "User", "LoginAccount", "Schedule", "MonthlyPattern", "RotationMember", "Assignment", "SwapRequest", "NotificationLog" )}) code.interact( banner="Database console: db, select, models and model classes are available.\n" diff --git a/app/models.py b/app/models.py index 0cb6f36..f08bcbc 100644 --- a/app/models.py +++ b/app/models.py @@ -19,24 +19,56 @@ 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.""" + + __tablename__ = "login_accounts" + + 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) + 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) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + people: Mapped[list[User]] = relationship(back_populates="login") + + @property + def can_login(self) -> bool: + return bool(self.username and self.password_hash) + + 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 | None] = mapped_column(String(80), unique=True, nullable=True) + login_id: Mapped[int | None] = mapped_column( + ForeignKey("login_accounts.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) - password_hash: Mapped[str | None] = mapped_column(String(300), nullable=True) calendar_token: Mapped[str | None] = mapped_column(String(64), unique=True, nullable=True) - 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) + login: Mapped[LoginAccount | None] = relationship(back_populates="people") + @property def can_login(self) -> bool: - return bool(self.username and self.password_hash) + """Whether this person signs in at all, through a shared login or their own.""" + return self.login 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) + + @property + def username(self) -> str | None: + return self.login.username if self.login else None class Schedule(Base): diff --git a/app/templates/account.html b/app/templates/account.html index 8b171c7..2a94e70 100644 --- a/app/templates/account.html +++ b/app/templates/account.html @@ -5,20 +5,19 @@

Rota

A minha conta

-

{{ current_user.name }}{% if current_user.username %} · @{{ current_user.username }}{% endif %}

+

{{ 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.

+ {% endif %}

Alterar palavra-passe

- {% if current_user.can_login %}
- {% else %} -

A sua conta ainda não tem palavra-passe. Peça a um administrador que a defina para poder entrar.

- {% endif %}
{% endblock %} diff --git a/app/templates/admin_logins.html b/app/templates/admin_logins.html new file mode 100644 index 0000000..a3bc8dc --- /dev/null +++ b/app/templates/admin_logins.html @@ -0,0 +1,47 @@ +{% 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_schedules.html b/app/templates/admin_schedules.html index 7458f78..40f2f46 100644 --- a/app/templates/admin_schedules.html +++ b/app/templates/admin_schedules.html @@ -28,4 +28,12 @@
Ainda não há escalas. Execute python -m app.cli init-db para criar as predefinidas.
{% endfor %} +
+

Calendário da equipa

+

Um único endereço com a rota completa, para qualquer calendário.

+
+ + +
+
{% endblock %} diff --git a/app/templates/admin_user_delete.html b/app/templates/admin_user_delete.html index e684d4d..cc9c036 100644 --- a/app/templates/admin_user_delete.html +++ b/app/templates/admin_user_delete.html @@ -10,7 +10,7 @@

{{ person.name }}

-

{% if person.can_login %}@{{ person.username }}{% else %}Sem login, apenas aparece na escala.{% endif %}

+

{% if person.login %}@{{ person.login.username }} · {{ person.login.name }}{% if person.login.people|length > 1 %} (partilhada com {{ person.login.people|length - 1 }} pessoa(s)){% endif %}{% else %}Sem login, apenas aparece na escala.{% endif %}

Só é possível remover quem ainda não tem turnos atribuídos. Primeiro transfira os turnos desta pessoa para outras; assim o registo de quem trabalhou cada data mantém-se.

Ao remover, acontece o seguinte: