fix: remove tests and documentation to prepare for reset

This commit is contained in:
jfmcarreira committed 2026-10-06 22:23:57 +01:00
1 parent 1b5fd41eb2
commit bca7150c9e
23 files changed
+10 -4091

No files matched your search

-93
View File
@@ -1,93 +0,0 @@
# 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, each with its own configuration page (`/admin/schedules/<id>`); 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. 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
- 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
- Docker Compose `test` profile for running tests independently of the host Python environment
## Important files
- `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 user + team + 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.
- 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
All checks run inside Docker, never on the host:
```bash
make check
```
That is `python -m compileall -q app && pytest -ra` in the `checks` service of `docker-compose.dev.yml`, which bind-mounts `app/`, `tests/` and `pyproject.toml` so it always validates the working tree.
`make dev` (host uvicorn with auto-reload, using `./.venv`) exists for interactive debugging. Running `pytest`, `python -m compileall` or `python -m app.cli` directly against the host interpreter is not a valid check.
The `dev` target of the `Dockerfile` installs `requirements-dev.txt` on top of the app image; the `checks` service supplies throwaway settings (`SECRET_KEY`, `DATABASE_URL`, `INITIAL_ADMIN_PASSWORD`), keeps `data/` inside the container, and does not read `.env`, so it is safe on a fresh clone.
`docker-compose.yml` is the service stack only. Anything development-related (auto-reload, bind mounts, test runner) belongs in `docker-compose.dev.yml`.
For route/UI changes also start the app and verify `/health`, `/login`, the rota, each schedule's configuration page, and the 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 `Contínuos CRR`; deployments can still override it with `APP_NAME`.
## Language
- Everything a member reads is European Portuguese: templates, flash messages, e-mail subjects and bodies, the seeded schedule names, and the `lang="pt-PT"` document attribute.
- Weekday and month names, and every rendered date, come from `app/i18n.py`. Never use `calendar.month_name`, `date.strftime("%a"/"%b"/"%A"/"%B")` or `calendar.day_name` for user-facing text; the container locale is not Portuguese.
- Stored enum values (`assignment.source`, `swap.status`, `notification_log.status`/`event_type`) stay English in the database and are translated for display by the Jinja filters registered in `app/main.py`.
- Code, comments, tests names and `docs/` stay in English; only rendered strings are Portuguese.
-80
View File
@@ -1,80 +0,0 @@
COMPOSE ?= docker compose
COMPOSE_DEV = PORT=$(PORT) $(COMPOSE) -f docker-compose.dev.yml
PYTHON ?= .venv/bin/python
PORT ?= 8000
RUNTIME ?= local
ifeq ($(RUNTIME),docker)
RUN_PYTHON = $(COMPOSE_DEV) run --rm --build app python
else ifeq ($(RUNTIME),local)
RUN_PYTHON = $(PYTHON)
else
$(error RUNTIME must be local or docker)
endif
.DEFAULT_GOAL := help
.PHONY: help setup dev-setup dev dev-up dev-down dev-logs check test-docker migrate revision init-db seed-demo db-shell reminders
help:
@echo "Local: make dev-setup && make seed-demo && make dev"
@echo "Docker: make seed-demo RUNTIME=docker && make dev-up"
@echo "Checks: make check (isolated from your development database)"
@echo "Data: make db-shell; make migrate; make revision m='description'"
@echo " Add RUNTIME=docker to run database commands in Docker."
@echo "Port: make dev PORT=8080 or make dev-up PORT=8080"
# Preserve an existing configuration and any populated database.
setup:
@test -f .env || cp .env.example .env
@mkdir -p data
# Host virtualenv, used for local debugging only. Checks always run in Docker.
dev-setup: setup
@python3 -c 'import sys; sys.exit("Python 3.12+ is required; use Docker or install a newer Python.") if sys.version_info < (3, 12) else None'
python3 -m venv .venv
$(PYTHON) -m pip install --upgrade pip
$(PYTHON) -m pip install -r requirements-dev.txt
# 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 '*' --reload-exclude 'data/*' --reload-exclude 'backups/*' --reload-exclude '.git/*'
# Full app in Docker with bind mounts and auto-reload.
dev-up: setup
$(COMPOSE_DEV) up --build
dev-down:
$(COMPOSE_DEV) down
dev-logs:
$(COMPOSE_DEV) logs -f app
# Compile check plus the test suite, inside Docker.
check:
$(COMPOSE_DEV) --profile check run --rm --build checks
test-docker:
$(MAKE) check
# Apply database migrations (also runs automatically on app start).
migrate: setup
$(RUN_PYTHON) -m app.cli migrate
# Autogenerate a migration: make revision m="add something"
revision: setup
@test -n "$(m)" || (echo 'Use make revision m="short description"' && exit 1)
$(RUN_PYTHON) -m alembic revision --autogenerate -m "$(m)"
init-db: setup
$(RUN_PYTHON) -m app.cli init-db
seed-demo: setup
$(RUN_PYTHON) -m app.cli seed-demo
db-shell: setup
$(RUN_PYTHON) -m app.cli db-shell
reminders: setup
$(RUN_PYTHON) -m app.cli send-reminders
-155
View File
@@ -1,155 +0,0 @@
# Contínuos CRR
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 team (or any available one) takes an assignment.
- Optional manager approval before a change becomes final.
- 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.
## Start locally and fill data
Requirements: Python **3.12+**, `make`, and Docker Compose **2.24+** for checks. Run commands from the project root.
```bash
make dev-setup # creates .env if missing, .venv, and installs dependencies
make seed-demo # optional: populate example teams, users and schedules before opening the app
make dev # auto-reload on http://localhost:8000
```
No virtualenv activation is needed. `make setup` preserves an existing `.env` and database. Run `make` to see the main commands; use `make dev PORT=8080` for another port.
Open `http://localhost:8000`. With the example configuration, the administrator login is **admin / change-me-now**. Existing installations use their existing credentials.
To fill your own data, skip `seed-demo`, sign in as administrator, and:
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 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 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 teams. Changing `INITIAL_ADMIN_PASSWORD` later does not reset that account; reset it from the Utilizadores screen.
## Develop in Docker
Requirements: Docker with Compose **2.24+** and `make`; host Python is optional.
```bash
make seed-demo RUNTIME=docker # optional; initializes and seeds the persistent database
make dev-up # builds and starts the app with auto-reload
```
Open `http://localhost:8000` with the same logins as local development. App code, templates, static files, and migration files are bind-mounted; Python changes reload automatically. Refresh the browser after template or CSS edits. Dependency changes need an image rebuild: stop with Ctrl-C and run `make dev-up` again.
```bash
make dev-up PORT=8080 # use another host port
make dev-logs # follow app logs from another terminal
make dev-down # remove containers; database files are kept
```
`docker-compose.dev.yml` contains the development app and isolated checks service. Database commands support `RUNTIME=docker` and work even when the app is stopped.
## Move to Docker deployment
The default host and Docker configurations both use **`data/bar_rota.db`**. Stop the local app (or development container), then start the deployment stack. On the same machine, your populated database is reused without an import or conversion.
```bash
make setup
# Set SECRET_KEY and INITIAL_ADMIN_PASSWORD for deployment in .env.
# Set BASE_URL to the deployed URL; PORT defaults to 8000.
docker compose up -d --build
docker compose ps # includes the HTTP healthcheck status
```
`docker-compose.yml` explicitly builds the production image, with persistent data and a restart policy. It runs without auto-reload. Rebuild after code changes with `docker compose up -d --build`.
To move to another machine, stop the app, copy the **entire `data/` directory** and your `.env` configuration to the new project checkout, then run the deployment command there. Keep these private files out of Git and Docker images. Stopping the app before copying also avoids copying an active SQLite database mid-write.
Behind a reverse proxy, set `BASE_URL` to the public address (used in e-mail links), `ROOT_PATH` to the prefix the app is served under when it is not at the domain root (for example `/crr` for `https://host/crr/`), and `SESSION_HTTPS_ONLY=true` when the proxy terminates TLS. Uvicorn runs with `--proxy-headers --forwarded-allow-ips '*'`, so `X-Forwarded-Proto`/`X-Forwarded-Host` set the scheme and host used in generated URLs and cookies; the proxy must forward them and keep the prefix it advertises.
On every start the application writes a copy of the SQLite file to `backups/` beside the database (override with `BACKUP_DIR`), named `rota-<timestamp>.db` and never overwriting an older copy. Nothing is deleted, so the folder grows by one file per start; prune it yourself if that becomes too much.
`DATA_DIR` changes the Docker host directory mounted at `/app/data`. Keep `DATABASE_URL=sqlite:///./data/bar_rota.db` in Docker: this path is relative to `/app` inside the container. For seamless switching between host and Docker, use the default `DATA_DIR=./data`; a custom directory requires a matching host `DATABASE_URL` when running locally. The port for Make development commands is selected with `PORT=...`; direct Compose commands use `.env`'s `PORT`. Update `BASE_URL` when changing the URL used in notification links.
## 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
```
## Database
The schema is managed with Alembic. The app runs `alembic upgrade head` on start, so starting it is enough to apply pending migrations.
```bash
make migrate # apply pending migrations
make revision m="add phone field" # generate a revision after editing app/models.py
make db-shell # inspect/edit data with SQLAlchemy
# The same commands without host Python:
make migrate RUNTIME=docker
make revision RUNTIME=docker m="add phone field"
make db-shell RUNTIME=docker
```
A console session exposes `db`, `select`, `models`, and all model classes:
```python
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
```
Exit with Ctrl-D. Use the admin UI for normal rota edits and swaps so workflow validation and notifications run. For schema changes, edit `app/models.py`, generate and review an Alembic revision, then run `make migrate` and `make check`. Docker-generated revisions appear directly in `migrations/versions/` through the bind mount. Migrate while the app is stopped, then restart it.
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.
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
Checks run in a container, so the host Python environment does not matter:
```bash
make check
# or
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 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
- `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.
-149
View File
@@ -1,149 +0,0 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
View File
Whitespace-only changes.
-40
View File
@@ -1,40 +0,0 @@
# Development stack: code is bind-mounted, reload is on, no restart policy.
# Run standalone: docker compose -f docker-compose.dev.yml up --build
# Checks: make check
services:
app:
build:
context: .
target: dev
env_file:
- path: .env
required: false
ports:
- "${PORT:-8000}:8000"
volumes:
- ./app:/app/app
- ./tests:/app/tests
- ./migrations:/app/migrations
- ./alembic.ini:/app/alembic.ini:ro
- ${DATA_DIR:-./data}:/app/data
command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload", "--reload-dir", "app", "--reload-dir", "migrations", "--proxy-headers", "--forwarded-allow-ips", "*"]
checks:
build:
context: .
target: dev
profiles:
- check
environment:
SECRET_KEY: test-only-secret-key
DATABASE_URL: sqlite:///./data/test.db
INITIAL_ADMIN_PASSWORD: test-only-password
SMTP_HOST: ""
PYTHONPATH: /app
volumes:
- ./app:/app/app
- ./tests:/app/tests
- ./pyproject.toml:/app/pyproject.toml:ro
- ./migrations:/app/migrations:ro
- ./alembic.ini:/app/alembic.ini:ro
command: ["sh", "-c", "python -m compileall -q app && pytest -ra"]
-20
View File
@@ -1,20 +0,0 @@
services:
bar-rota:
build:
context: .
target: production
container_name: bar-rota
restart: unless-stopped
env_file:
- path: .env
required: false
ports:
- "${PORT:-8000}:8000"
volumes:
- ${DATA_DIR:-./data}:/app/data
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=5)"]
interval: 30s
timeout: 10s
start_period: 10s
retries: 3
-14
View File
@@ -1,14 +0,0 @@
# Roadmap / intentionally deferred
Good next additions if the association needs them:
- 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.
+1 -1
View File
@@ -55,4 +55,4 @@ def run_migrations_online() -> None:
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
run_migrations_online()
+1 -1
View File
@@ -1,4 +1,4 @@
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
testpaths = []
addopts = "-ra"
+8 -2
View File
@@ -1,8 +1,14 @@
{
"venvPath": ".",
"venv": ".venv",
"include": ["app", "tests"],
"exclude": ["**/__pycache__", ".venv", "data"],
"include": [
"app"
],
"exclude": [
"**/__pycache__",
".venv",
"data"
],
"typeCheckingMode": "basic",
"reportMissingImports": true,
"reportMissingTypeStubs": false,
-69
View File
@@ -1,69 +0,0 @@
"""Test helpers: teams that work the rota, and the users that sign in for them."""
from __future__ import annotations
from sqlalchemy.orm import Session
from app.models import Team, User
from app.security import hash_password
def make_user(
db: Session,
username: str,
*,
name: str | None = None,
password: str = "login-password",
is_admin: bool = False,
is_active: bool = True,
) -> User:
account = User(
name=name or username.capitalize(),
username=username,
password_hash=hash_password(password),
is_admin=is_admin,
is_active=is_active,
)
db.add(account)
db.commit()
return account
def make_team(
db: Session,
name: str,
*,
user: User | None = None,
is_active: bool = True,
notify_email: bool = False,
**fields,
) -> Team:
"""One team on the rota. Without a `user` it can never be signed in for."""
team = Team(name=name, user=user, is_active=is_active, notify_email=notify_email, **fields)
db.add(team)
db.commit()
return team
def make_member(
db: Session,
name: str,
username: str,
*,
password: str = "member-password",
is_admin: bool = False,
**fields,
) -> Team:
"""A team with a user of its own, the usual single-login case."""
return make_team(
db,
name,
user=make_user(db, username, password=password, is_admin=is_admin),
**fields,
)
def make_shared_user(db: Session, username: str, *names: str, password: str = "team-password"):
"""One user assigned to several teams, the way a real team signs in."""
user = make_user(db, username, password=password)
return user, [make_team(db, name, user=user) for name in names]
File diff suppressed because it is too large. Load diff
-82
View File
@@ -1,82 +0,0 @@
import sqlite3
from datetime import datetime
from app.database import backup_database, database_file
def _touch(path, rows: int = 1) -> None:
with sqlite3.connect(path) as connection:
for index in range(rows):
connection.execute("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)")
connection.execute("INSERT INTO notes (body) VALUES (?)", (f"{index}",))
connection.commit()
def test_a_backup_is_written_beside_the_database(tmp_path, monkeypatch):
db_file = tmp_path / "rota.db"
_touch(db_file, 2)
monkeypatch.setattr("app.config.settings.database_url", f"sqlite:///{db_file}")
backup = backup_database()
assert backup is not None
assert backup.parent == tmp_path / "backups"
assert backup.name.startswith("rota-")
assert backup.name.endswith(".db")
with sqlite3.connect(backup) as connection:
assert connection.execute("SELECT count(*) FROM notes").fetchone()[0] == 2
def test_backups_never_overwrite_each_other(tmp_path, monkeypatch):
db_file = tmp_path / "rota.db"
_touch(db_file)
monkeypatch.setattr("app.config.settings.database_url", f"sqlite:///{db_file}")
first = backup_database()
second = backup_database()
assert first != second
assert first.exists() and second.exists()
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
assert first.stem.startswith(f"rota-{stamp}")
# same second: the name is incremented rather than reused
assert second.name in {f"rota-{stamp}-1.db", f"rota-{stamp}-2.db"}
def test_the_backup_directory_can_be_chosen(tmp_path, monkeypatch):
db_file = tmp_path / "rota.db"
_touch(db_file)
target = tmp_path / "copias"
monkeypatch.setattr("app.config.settings.database_url", f"sqlite:///{db_file}")
backup = backup_database(target)
assert backup.parent == target
def test_nothing_is_copied_without_a_database_file(tmp_path, monkeypatch):
monkeypatch.setattr("app.config.settings.database_url", f"sqlite:///{tmp_path}/nao-existe.db")
assert backup_database() is None
assert database_file() == tmp_path / "nao-existe.db"
assert not (tmp_path / "backups").exists()
monkeypatch.setattr("app.config.settings.database_url", "sqlite:///:memory:")
assert database_file() is None
assert backup_database() is None
monkeypatch.setattr("app.config.settings.database_url", "postgresql://localhost/rota")
assert database_file() is None
assert backup_database() is None
def test_the_copy_keeps_the_data_of_that_moment(tmp_path, monkeypatch):
db_file = tmp_path / "rota.db"
_touch(db_file, 1)
monkeypatch.setattr("app.config.settings.database_url", f"sqlite:///{db_file}")
backup = backup_database()
assert backup is not None
_touch(db_file, 3) # the app carries on being written to
with sqlite3.connect(backup) as connection:
assert connection.execute("SELECT count(*) FROM notes").fetchone()[0] == 1
-63
View File
@@ -1,63 +0,0 @@
from datetime import time
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, Team, User
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)
def test_seeded_schedules_are_named_in_portuguese(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)
names = {
slug: name
for slug, name in db.execute(select(Schedule.slug, Schedule.name)).all()
}
assert names["night"] == "Noite"
assert names["saturday-lunch"] == "Almoço - Sábados"
assert names["sunday-lunch"] == "Almoço - Domingo"
def test_seeded_schedules_run_at_the_bar_hours(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)
windows = {
slug: (start, end)
for slug, start, end in db.execute(
select(Schedule.slug, Schedule.start_time, Schedule.end_time)
).all()
}
assert windows == {
"night": (time(20, 30), time(0, 0)),
"saturday-lunch": (time(13, 0), time(16, 0)),
"sunday-lunch": (time(13, 0), time(16, 0)),
}
def test_bootstrap_creates_an_admin_team_with_its_user(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)
team = db.scalar(select(Team))
user = db.scalar(select(User))
assert team.name == user.name
assert team.user_id == user.id
assert user.is_admin is True
assert user.can_login is True
-230
View File
@@ -1,230 +0,0 @@
from datetime import date, time, timedelta
from sqlalchemy import select
from app.calendar import build_feed
from app.config import settings
from app.models import Assignment, Schedule, Team
# the fixtures live next door and are shared by importing them here
from app.security import hash_password
from test_admin_schedule_assignments import ( # noqa: F401
CSRF_RE,
client,
db,
login_account,
seed,
sign_in,
)
def unfold(feed: str) -> str:
"""Undo RFC 5545 line folding so assertions can read whole lines."""
return feed.replace("\r\n ", "")
def _hours(db, schedule: Schedule, start: str, end: str) -> Schedule:
schedule.start_time = time.fromisoformat(start)
schedule.end_time = time.fromisoformat(end)
db.commit()
return schedule
def _shift(db, schedule: Schedule, day: date, team: Team) -> Assignment:
assignment = Assignment(schedule_id=schedule.id, date=day, team_id=team.id, source="manual")
db.add(assignment)
db.commit()
db.refresh(assignment)
return assignment
def test_the_team_feed_only_carries_that_team_shifts(client, db):
night, sat, sun, ana, bruno, admin = seed(db)
_hours(db, night, "20:30", "00:00")
_hours(db, sat, "13:00", "16:00")
today = date.today()
_shift(db, night, today, ana)
_shift(db, sat, today, bruno)
feed = build_feed(db, ana, "Rota — Ana")
flat = unfold(feed)
assert "BEGIN:VCALENDAR" in feed and feed.endswith("END:VCALENDAR\r\n")
assert "SUMMARY:Ana · Noite · 20:30–00:00" in flat
assert "SUMMARY:Ana · Almoço - Sábados" not in flat # Bruno's shift
assert "Equipa: Ana" in flat
assert "Bruno" not in flat
assert f"DTSTART;TZID=Europe/Lisbon:{today:%Y%m%d}T203000" in flat
# 20:30–00:00 ends after midnight, so the night ends the next morning
assert f"DTEND;TZID=Europe/Lisbon:{(today + timedelta(days=1)):%Y%m%d}T000000" in flat
def test_a_shift_past_midnight_ends_on_the_next_day(client, db):
night, _, _, ana, _, _ = seed(db)
night.start_time = time(20, 30)
night.end_time = time(0, 0)
db.commit()
_shift(db, night, date(2026, 11, 7), ana)
feed = unfold(build_feed(db, ana, "Rota — Ana"))
assert "DTSTART;TZID=Europe/Lisbon:20261107T203000" in feed
assert "DTEND;TZID=Europe/Lisbon:20261108T000000" in feed
def test_the_feed_reaches_the_right_team_by_token(client, db):
night, _, _, ana, bruno, admin = seed(db)
_shift(db, night, date.today(), ana)
ana.calendar_token = "ana-token"
db.commit()
sign_in(client)
page = client.get("/calendar").text
assert f"/calendar/{admin.calendar_token}.ics" in page
mine = unfold(client.get("/calendar/ana-token.ics").text)
assert client.get("/calendar/ana-token.ics").headers["content-type"].startswith("text/calendar")
assert "Equipa: Ana" in mine
assert "X-WR-CALNAME:Contínuos CRR — Ana" in mine
assert client.get("/calendar/nao-existe.ics").status_code == 404
def test_admins_share_one_feed_with_the_whole_rota(client, db):
from app.config import settings
night, sat, _, ana, bruno, admin = seed(db)
_shift(db, night, date.today(), ana)
_shift(db, sat, date.today(), bruno)
sign_in(client)
hub = client.get("/admin/schedules").text
assert "/calendar/" in hub
token = settings.calendar_token
assert token, "the team token is created on first use"
response = client.get(f"/calendar/{token}.ics")
feed = unfold(response.text)
assert response.status_code == 200
assert "Equipa: Ana" in feed
assert "Equipa: Bruno" in feed
assert "X-WR-CALNAME:Contínuos CRR" in feed
assert settings.calendar_token == token # stable between visits
def test_inactive_teams_lose_their_feed(client, db):
_, _, _, ana, _, _ = seed(db)
ana.calendar_token = "ana-token"
ana.is_active = False
db.commit()
assert client.get("/calendar/ana-token.ics").status_code == 404
def test_the_calendar_page_holds_the_links_and_the_rota_only_links_to_it(client, db):
night, sat, _, ana, bruno, admin = seed(db)
sign_in(client)
rota = client.get("/").text
assert 'href="/calendar">Calendário</a>' in rota
assert "O meu calendário" not in rota # the links live on their own page
page = client.get("/calendar").text
assert "Turnos de Admin" in page # one feed per team the signed-in user covers
assert "Rota completa" in page # admins also get the team feed
assert "/calendar/" in page
assert 'data-copy="http://testserver/calendar/' in page
assert ">Copiar</button>" in page
assert "webcal://testserver/calendar/" in page
# members only get their own feed
client.post("/logout", data={"csrf_token": CSRF_RE.search(client.get("/").text).group(1)})
ana.user = login_account("ana", "ana-password")
db.commit()
token = CSRF_RE.search(client.get("/login").text).group(1)
client.post("/login", data={"username": "ana", "password": "ana-password", "csrf_token": token})
member_page = client.get("/calendar").text
assert "Turnos de Ana" in member_page
assert "Rota completa" not in member_page
def test_the_calendar_page_needs_a_signed_in_user(client, db):
seed(db)
assert client.get("/calendar", follow_redirects=False).status_code == 401
def test_long_lines_with_accents_are_folded_without_breaking_characters(client, db):
"""Names with accents must survive the 75 octet folding of RFC 5545."""
from app.calendar import _fold
night, _, _, ana, _, _ = seed(db)
long_name = "Afonso Vieira e Julinha Conceição da Conceição e Silva"
night.name = long_name
db.commit()
_shift(db, night, date.today(), ana)
feed = build_feed(db, ana, "Rota — Ana")
raw_lines = feed.split("\r\n")
assert unfold(feed).count(long_name) == 1
assert all(len(line.encode("utf-8")) <= 75 for line in raw_lines)
assert "DESCRIPTION:" + long_name not in raw_lines # it was folded
# unfolding the continuations gives the original lines back
assert unfold(feed) == feed.replace("\r\n ", "").replace("\r\n", "\r\n")
assert any(line.startswith(" ") for line in raw_lines)
assert _fold("ç" * 60)[1].startswith(" ")
def test_the_feed_declares_the_bar_timezone(client, db):
"""Times are local to the bar, with the European summer-time rules attached."""
from app.calendar import feed_timezone
night, _, _, ana, _, _ = seed(db)
_shift(db, night, date.today(), ana)
feed = unfold(build_feed(db, ana, "Rota — Ana"))
assert feed_timezone() == "Europe/Lisbon"
assert "X-WR-TIMEZONE:Europe/Lisbon" in feed
assert "BEGIN:VTIMEZONE" in feed and "END:VTIMEZONE" in feed
assert "TZID:Europe/Lisbon" in feed
assert "TZNAME:WEST" in feed and "TZNAME:WET" in feed
assert "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU" in feed
assert "RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU" in feed
# the block comes before the events
assert feed.index("END:VTIMEZONE") < feed.index("BEGIN:VEVENT")
def test_an_unknown_timezone_falls_back_to_lisbon(client, db, monkeypatch):
from app.calendar import feed_timezone
monkeypatch.setattr("app.config.settings.timezone", "Marte/Phobos")
assert feed_timezone() == "Europe/Lisbon"
def test_an_unassigned_shift_still_has_an_event(client, db):
night, _, _, ana, _, _ = seed(db)
_hours(db, night, "20:30", "00:00")
assignment = Assignment(schedule_id=night.id, date=date.today(), team_id=None, source="generated")
db.add(assignment)
db.commit()
night_row = db.get(Assignment, assignment.id)
feed = unfold(build_feed(db, None, "Rota completa"))
assert "SUMMARY:Noite · 20:30–00:00" in feed # nobody to name
assert "SUMMARY:Noite · 20:30–00:00 ·" not in feed
def test_both_feeds_publish_the_same_timezone(client, db):
"""A team's own feed and the shared one must not drift apart on the timezone."""
night, sat, _, ana, bruno, admin = seed(db)
_hours(db, night, "20:30", "00:00")
_shift(db, night, date.today(), ana)
own_feed = unfold(build_feed(db, ana, "Rota — Ana"))
shared = unfold(build_feed(db, None, settings.app_name))
for feed in (own_feed, shared):
assert "X-WR-TIMEZONE:Europe/Lisbon" in feed
assert "TZID:Europe/Lisbon" in feed
assert "BEGIN:VTIMEZONE" in feed and "END:VTIMEZONE" in feed
assert f"DTSTART;TZID=Europe/Lisbon:{date.today():%Y%m%d}T203000" in feed
-92
View File
@@ -1,92 +0,0 @@
from datetime import date, timedelta
import pytest
from sqlalchemy import create_engine, select
from sqlalchemy.orm import sessionmaker
from app import cli, database
from app.models import Assignment, MonthlyPattern, RotationMember, Schedule, Team, User
from app.security import verify_password
@pytest.fixture()
def sessions(tmp_path, monkeypatch):
url = f"sqlite:///{tmp_path / 'demo.db'}"
engine = create_engine(url)
factory = sessionmaker(bind=engine, expire_on_commit=False)
monkeypatch.setattr(database.settings, "database_url", url)
monkeypatch.setattr(database, "engine", engine)
monkeypatch.setattr(cli, "SessionLocal", factory)
yield factory
engine.dispose()
def test_demo_seeds_repeating_schedules_and_is_repeatable(sessions):
cli.seed_demo()
today = date.today()
next_month = (today.replace(day=28) + timedelta(days=4)).replace(day=1)
with sessions() as db:
accounts = db.scalars(
select(User).where(User.username.in_(["alice", "bruno", "sabado"]))
).all()
assert len(accounts) == 3 # Carla and Diogo are covered by the same user
assert all(verify_password("demo-password", account.password_hash) for account in accounts)
teams = db.scalars(select(Team).join(User).where(
User.username.in_(["alice", "bruno", "sabado"])
)).all()
assert len(teams) == 4
assert len(db.scalars(select(MonthlyPattern)).all()) == 31
assert len(db.scalars(select(RotationMember)).all()) == 8
assignments = db.scalars(select(Assignment)).all()
assert all(row.team_id is not None for row in assignments)
assert {row.date.replace(day=1) for row in assignments} == {today.replace(day=1), next_month}
original = [(row.id, row.date, row.team_id, row.source) for row in assignments]
cli.seed_demo()
with sessions() as db:
assert len(db.scalars(select(Team)).all()) == 5
assert len(db.scalars(select(MonthlyPattern)).all()) == 31
assert len(db.scalars(select(RotationMember)).all()) == 8
assert [(row.id, row.date, row.team_id, row.source) for row in db.scalars(select(Assignment)).all()] == original
def test_demo_preserves_existing_teams_configuration_and_assignments(sessions):
cli.init_db()
today = date.today()
assigned_day = today.replace(day=1) if today.day != 1 else today + timedelta(days=1)
with sessions() as db:
night = db.scalar(select(Schedule).where(Schedule.slug == "night"))
saturday = db.scalar(select(Schedule).where(Schedule.slug == "saturday-lunch"))
alice = Team(
name="My Alice",
user=User(
name="My Alice",
username="alice",
password_hash="keep-this-password",
is_admin=False,
is_active=True,
),
is_active=True,
)
db.add(alice)
db.flush()
db.add_all([
MonthlyPattern(schedule_id=night.id, day_of_month=1, team_id=alice.id),
RotationMember(schedule_id=saturday.id, position=10, team_id=alice.id),
Assignment(schedule_id=night.id, date=today, team_id=None, source="manual", note="Keep unassigned"),
Assignment(schedule_id=night.id, date=assigned_day, team_id=alice.id, source="swap"),
])
db.commit()
original = [(row.id, row.team_id, row.source, row.note) for row in db.scalars(select(Assignment)).all()]
cli.seed_demo()
with sessions() as db:
alice = db.scalar(select(Team).join(User).where(User.username == "alice"))
assert (alice.name, alice.user.password_hash) == ("My Alice", "keep-this-password")
pattern = db.scalars(select(MonthlyPattern).where(MonthlyPattern.schedule_id == night.id)).all()
assert [(row.day_of_month, row.team_id) for row in pattern] == [(1, alice.id)]
rotation = db.scalars(select(RotationMember).where(RotationMember.schedule_id == saturday.id)).all()
assert [(row.position, row.team_id) for row in rotation] == [(10, alice.id)]
for assignment_id, team_id, source, note in original:
row = db.get(Assignment, assignment_id)
assert (row.team_id, row.source, row.note) == (team_id, source, note)
-49
View File
@@ -1,49 +0,0 @@
from datetime import date, datetime
from app.i18n import (
MONTHS,
day_long,
day_numeric,
day_numeric_long,
day_short,
event_type_label,
moment,
month_name,
notification_status_label,
source_label,
swap_status_label,
weekday_name,
weekday_names,
)
def test_month_and_weekday_names_are_european_portuguese():
assert month_name(1) == "Janeiro"
assert month_name(8) == "Agosto"
assert MONTHS[0] == "Janeiro"
assert weekday_name(5) == "Sábado"
assert weekday_name(0) == "Segunda-feira"
assert weekday_name(5, short=True) == "Sáb"
assert weekday_names({5, 6}) == "Sábado e Domingo"
assert weekday_names({0, 1, 2, 3, 4, 5, 6}) == (
"Segunda-feira, Terça-feira, Quarta-feira, Quinta-feira, Sexta-feira, Sábado e Domingo"
)
def test_dates_are_formatted_the_portuguese_way():
saturday = date(2026, 1, 3)
assert day_short(saturday) == "sáb 03 jan"
assert day_long(saturday) == "Sábado, 3 de janeiro de 2026"
assert day_numeric(saturday) == "03/01/2026"
assert day_numeric_long(saturday) == "3 de janeiro de 2026"
assert moment(datetime(2026, 1, 3, 21, 45)) == "03/01/2026 21:45"
def test_stored_enum_values_are_translated_for_display():
assert source_label("generated") == "automático"
assert source_label("manual") == "manual"
assert source_label("swap") == "troca"
assert source_label("something-new") == "something-new"
assert swap_status_label("pending_approval") == "aguarda aprovação"
assert notification_status_label("skipped") == "ignorado"
assert event_type_label("shift_reminder") == "Lembrete de turno"
-100
View File
@@ -1,100 +0,0 @@
from sqlalchemy import create_engine, inspect, text
from app.database import Base
from app import models # noqa: F401 (registers the tables on Base.metadata)
def migrated_database(tmp_path, monkeypatch):
"""An empty database upgraded to head, plus the URL it lives at."""
from alembic import command
from app.database import alembic_config
db_path = tmp_path / "rota.db"
url = f"sqlite:///{db_path}"
monkeypatch.setenv("DATABASE_URL", url)
monkeypatch.setattr("app.config.settings.database_url", url)
config = alembic_config()
command.upgrade(config, "head")
return url
def test_migrations_produce_the_model_schema(tmp_path, monkeypatch):
"""`alembic upgrade head` must match app/models.py, no drift in either direction."""
url = migrated_database(tmp_path, monkeypatch)
engine = create_engine(url)
migrated = set(inspect(engine).get_table_names()) - {"alembic_version"}
assert migrated == set(Base.metadata.tables)
with engine.connect() as connection:
head = connection.execute(text("select version_num from alembic_version")).scalar_one()
assert head == "0001_initial"
def test_the_whole_schema_lands_in_one_revision(tmp_path, monkeypatch):
"""The history is squashed: one revision creates everything and one drops it."""
from alembic import command
from app.database import alembic_config
url = migrated_database(tmp_path, monkeypatch)
engine = create_engine(url)
with engine.connect() as connection:
users = {row[1] for row in connection.execute(text("PRAGMA table_info(users)"))}
teams = {row[1] for row in connection.execute(text("PRAGMA table_info(teams)"))}
assert "username" in users
assert {"user_id", "name", "email", "phone"} <= teams
assert "login_id" not in teams
command.downgrade(alembic_config(), "base")
with create_engine(url).connect() as connection:
assert connection.execute(text("select version_num from alembic_version")).scalar() is None
left = set(inspect(create_engine(url)).get_table_names()) - {"alembic_version"}
assert not left
def test_an_existing_database_is_claimed_by_the_baseline(tmp_path, monkeypatch):
"""What the squash means in practice: a populated database is stamped, not rebuilt."""
from alembic import command
from app.database import alembic_config
url = migrated_database(tmp_path, monkeypatch)
engine = create_engine(url)
with engine.begin() as connection:
connection.execute(text(
"INSERT INTO teams (name, email, is_active, notify_email, created_at) "
"VALUES ('Carla', 'carla@example.com', 1, 1, '2026-01-01 00:00:00')"
))
connection.execute(text(
"INSERT INTO users (name, username, password_hash, is_admin, is_active, created_at) "
"VALUES ('Equipa de sábado', 'sabado', 'hash', 0, 1, '2026-01-01 00:00:00')"
))
user_id = connection.execute(text("select id from users")).scalar_one()
connection.execute(text("UPDATE teams SET user_id = :user"), {"user": user_id})
# An install that predates the squash: its tables are already the baseline schema.
config = alembic_config()
command.stamp(config, "base")
command.stamp(config, "head")
command.upgrade(config, "head")
command.check(config)
with engine.connect() as connection:
assert connection.execute(text("select version_num from alembic_version")).scalar() == "0001_initial"
rows = connection.execute(text(
"SELECT teams.name, users.username FROM teams JOIN users ON users.id = teams.user_id"
)).all()
assert rows == [("Carla", "sabado")]
def test_a_new_column_gets_a_revision(monkeypatch, tmp_path):
"""Autogenerate must report no pending operations once head is applied."""
from alembic import command
from app.database import alembic_config
migrated_database(tmp_path, monkeypatch)
command.check(alembic_config())
-386
View File
@@ -1,386 +0,0 @@
import re
from datetime import date, time, timedelta
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, select
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database import Base, get_db
from app.main import app
from app.i18n import day_short, month_name, weekday_name
from app.models import RotationMember, Schedule, Team
from factories import make_member, make_user
CSRF_RE = re.compile(r'name="csrf_token" value="([^"]+)"')
@pytest.fixture()
def db():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine, expire_on_commit=False)()
try:
yield session
finally:
session.close()
@pytest.fixture()
def client(db):
def override_get_db():
yield db
app.dependency_overrides[get_db] = override_get_db
try:
yield TestClient(app)
finally:
app.dependency_overrides.pop(get_db, None)
def add_team(db, name: str) -> Team:
team = Team(
name=name,
is_active=True,
notify_email=False,
)
db.add(team)
db.flush()
return team
def add_schedule(db, **fields) -> Schedule:
defaults = {
"schedule_type": "rotation",
"weekdays": "5",
"start_time": time(13, 0),
"end_time": time(16, 0),
"requires_manager_approval": True,
"is_active": True,
"rotation_anchor_date": date(2026, 1, 3),
}
defaults.update(fields)
schedule = Schedule(**defaults)
db.add(schedule)
db.flush()
return schedule
def add_rotation_member(db, schedule: Schedule, team: Team, position: int) -> RotationMember:
member = RotationMember(schedule_id=schedule.id, team_id=team.id, position=position)
db.add(member)
db.flush()
return member
def login(client: TestClient, username: str, password: str) -> str:
match = CSRF_RE.search(client.get("/login").text)
assert match, "no csrf token on /login"
return client.post(
"/login",
data={"username": username, "password": password, "csrf_token": match.group(1)},
follow_redirects=True,
).text
def seed_schedules(db):
night = add_schedule(db, name="Noite", slug="night", schedule_type="fixed", weekdays="0,1,2,3,4,5,6")
sat = add_schedule(db, name="Almoço - Sábados", slug="sat")
sun = add_schedule(db, name="Almoço - Domingo", slug="sun", weekdays="6")
ana = add_team(db, "Ana")
bruno = add_team(db, "Bruno")
add_rotation_member(db, sat, ana, 0)
add_rotation_member(db, sat, bruno, 1)
add_rotation_member(db, sun, bruno, 0)
db.commit()
return night, sat, sun
def test_the_schedule_hub_needs_an_administrator(client, db):
seed_schedules(db)
response = client.get("/admin/schedules", follow_redirects=False)
assert response.status_code == 401
def test_rota_is_the_landing_page_for_signed_out_visitors(client, db):
seed_schedules(db)
page = client.get("/", follow_redirects=False).text
assert month_name(date.today().month) in page
assert '<a class="brand" href="/"' in page
assert "Almoço - Sábados" in page
assert "Entrar" in page
assert "Pedir troca" not in page
assert "/swap" not in page
assert 'class="assignment mine"' not in page
def test_signed_in_rota_shows_change_actions_for_own_shifts(client, db):
_, sat, _ = seed_schedules(db)
ana = db.scalar(select(Team).where(Team.name == "Ana"))
ana.user = make_user(db, "ana", password="a-secure-password")
db.commit()
login(client, "ana", "a-secure-password")
page = client.get("/", follow_redirects=False).text
assert "Pedir troca" in page
assert "/swap" in page
assert f"{sat.id}" in page
def test_the_admin_hub_shows_the_rotation_order_and_the_night_pattern(client, db):
seed_schedules(db)
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
hub = client.get("/admin/schedules").text
assert "Noite" in hub
assert "Almoço - Sábados" in hub
assert "Ana" in hub
assert "Bruno" in hub
assert "Todos os dias" in hub
def test_fixed_schedule_is_described_as_repeating_every_month(client, db):
seed_schedules(db)
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
page = client.get("/admin/schedules").text
assert "repete todos os meses" in page
assert "Todos os dias" in page
def test_raw_weekday_numbers_are_never_shown(client, db):
night, sat, _ = seed_schedules(db)
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
for path in ("/admin/schedules", f"/admin/schedules/{night.id}", f"/admin/schedules/{sat.id}"):
page = client.get(path).text
assert "0,1,2,3,4,5,6" not in page
assert "weekdays" not in page
def test_each_schedule_has_its_own_configuration_page(client, db):
night, sat, sun = seed_schedules(db)
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
hub = client.get("/admin/schedules").text
for schedule in (night, sat, sun):
assert f'href="/admin/schedules/{schedule.id}"' in hub
assert "Rotação · Sábado" in hub
assert "Rotação · Domingo" in hub
def test_an_inactive_schedule_is_listed_as_inactive(client, db):
add_schedule(db, name="Retired Shift", slug="retired", is_active=False)
db.commit()
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
hub = client.get("/admin/schedules").text
assert "Retired Shift" in hub
assert "inativa" in hub
def test_rotations_show_upcoming_dates_instead_of_weekdays(client, db):
seed_schedules(db)
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
page = client.get("/admin/schedules").text
first_saturday = date.today()
while first_saturday.weekday() != 5:
first_saturday += timedelta(days=1)
expected = day_short(first_saturday)
assert expected in page
def test_the_admin_hub_shows_a_placeholder_when_no_schedules_exist(client, db):
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
page = client.get("/admin/schedules").text
assert "Ainda não há escalas." in page
def test_signed_out_visitors_are_not_offered_the_admin_pages(client, db):
seed_schedules(db)
page = client.get("/login").text
assert 'href="/schedules"' not in page
assert 'href="/admin/schedules"' not in page
def test_a_member_cannot_read_the_schedule_hub(client, db):
seed_schedules(db)
make_member(db, "Member", "member", password="member-password")
db.commit()
assert "Entrar" not in login(client, "member", "member-password")
assert client.get("/admin/schedules", follow_redirects=False).status_code == 403
def test_rota_is_read_only_for_signed_out_visitors(client, db):
seed_schedules(db)
page = client.get("/", follow_redirects=False).text
assert month_name(date.today().month) in page
assert "Pedir troca" not in page
assert "/swap" not in page
assert client.get("/swaps", follow_redirects=False).status_code == 401
def test_pages_are_served_in_european_portuguese(client, db):
seed_schedules(db)
today = date.today()
page = client.get(f"/?year={today.year}&month={today.month}").text
assert '<html lang="pt-PT">' in page
assert month_name(today.month) in page
assert day_short(today) not in page # the rota shows the weekday, not the full date
assert f'<strong>{weekday_name(today.weekday(), short=True)}</strong>' in page
assert "Sem atribuição" in page
def test_admin_schedules_page_separates_the_three_schedule_types(client, db):
night, sat, sun = seed_schedules(db)
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
hub = client.get("/admin/schedules").text
for schedule in (night, sat, sun):
assert f'href="/admin/schedules/{schedule.id}"' in hub
assert "weekdays" not in hub
assert "Ordem da rotação" not in client.get(f"/admin/schedules/{night.id}").text
assert "Ordem da rotação" in client.get(f"/admin/schedules/{sat.id}").text
assert "Ordem da rotação" in client.get(f"/admin/schedules/{sun.id}").text
def test_rotation_edits_return_to_the_schedule_page(client, db):
_, sat, _ = seed_schedules(db)
admin = make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
login(client, "admin", "admin-password")
token = CSRF_RE.search(client.get(f"/admin/schedules/{sat.id}").text).group(1)
member = sat.rotation_members[0]
response = client.post(
f"/admin/rotation/{member.id}/remove",
data={"csrf_token": token},
follow_redirects=False,
)
assert response.headers["location"] == f"/admin/schedules/{sat.id}"
def test_adding_a_rotation_member_returns_to_the_rotation_order_anchor(client, db):
_, sat, _ = seed_schedules(db)
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
newcomer = add_team(db, "Carla")
db.commit()
login(client, "admin", "admin-password")
page = client.get(f"/admin/schedules/{sat.id}").text
assert 'id="rotation-order"' in page
token = CSRF_RE.search(page).group(1)
response = client.post(
f"/admin/schedules/{sat.id}/rotation",
data={"csrf_token": token, "team_id": newcomer.id},
follow_redirects=False,
)
assert response.headers["location"] == f"/admin/schedules/{sat.id}#rotation-order"
db.refresh(sat)
assert newcomer.id in {member.team_id for member in sat.rotation_members}
def test_pages_and_static_files_survive_a_sub_path_deployment(client, db):
"""Behind a proxy serving /crr/, every link, form and asset keeps the prefix."""
_, sat, _ = seed_schedules(db)
make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
db.commit()
monkey = pytest.MonkeyPatch()
monkey.setattr("app.config.settings.root_path", "/crr")
proxied = TestClient(app, root_path="/crr")
try:
proxied.post(
"/login",
data={
"username": "admin",
"password": "admin-password",
"csrf_token": CSRF_RE.search(proxied.get("/login").text).group(1),
},
)
page = proxied.get("/admin/schedules").text
finally:
monkey.undo()
# static assets are built with url_for, which already honours the prefix
assert 'href="http://testserver/crr/static/app.css"' in page
assert 'src="http://testserver/crr/static/logo-crr.png"' in page
# every hand written link goes through app_path
assert 'href="/crr/"' in page
assert f'href="/crr/admin/schedules/{sat.id}"' in page
assert 'href="/crr/admin/users"' in page
assert "http://testserver/crr/admin/schedules/1" not in page
def test_redirects_keep_the_prefix_behind_a_sub_path_deployment(client, db):
seed_schedules(db)
monkey = pytest.MonkeyPatch()
monkey.setattr("app.config.settings.root_path", "/crr")
try:
response = client.post(
"/login",
data={
"username": "x",
"password": "y",
"csrf_token": CSRF_RE.search(client.get("/login").text).group(1),
},
follow_redirects=False,
)
finally:
monkey.undo()
assert response.status_code == 303
assert response.headers["location"].startswith("/crr/login")
def test_settings_url_only_prefixes_real_paths():
from app.config import Settings
plain = Settings(root_path="")
assert plain.prefix == ""
assert plain.url("/swaps") == "/swaps"
proxied = Settings(root_path="/crr/")
assert proxied.prefix == "/crr"
assert proxied.url("/swaps") == "/crr/swaps"
assert proxied.url("/?year=2026") == "/crr/?year=2026"
assert proxied.url("/admin/assign#rotation") == "/crr/admin/assign#rotation"
assert proxied.url("https://example.com/x") == "https://example.com/x"
-204
View File
@@ -1,204 +0,0 @@
from datetime import date
import pytest
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, Team
from app.scheduling import ensure_month_assignments, rotation_team_for_date
def make_db() -> Session:
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
Base.metadata.create_all(engine)
return Session(engine, autoflush=False)
def add_team(db: Session, name: str, pos: int) -> Team:
team = Team(
name=name,
email=None,
phone=None,
is_active=True,
notify_email=False,
)
db.add(team)
db.flush()
return team
def seed_schedules(db: Session):
night = Schedule(
name="Night",
slug="night",
schedule_type="fixed",
weekdays="0,1,2,3,4,5,6",
requires_manager_approval=True,
is_active=True,
)
sat = Schedule(
name="Saturday Lunch",
slug="sat",
schedule_type="rotation",
weekdays="5",
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",
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()
teams = [add_team(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, team in enumerate(teams, 1):
db.add(RotationMember(schedule_id=schedule.id, team_id=team.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.team_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.team_id for a in sats] != []
assert [a.team_id for a in suns] != []
def test_existing_assignment_is_not_rewritten_when_rotation_changes():
db = make_db()
alice = add_team(db, "Alice", 1)
bruno = add_team(db, "Bruno", 2)
_, sat, _ = seed_schedules(db)
db.add_all([
RotationMember(schedule_id=sat.id, team_id=alice.id, position=1),
RotationMember(schedule_id=sat.id, team_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.team_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.team_id == original_user
def test_generation_continues_from_previous_people_across_months_independently():
with make_db() as db:
alice, bruno, carla = [add_team(db, name, pos) for pos, name in enumerate(["Alice", "Bruno", "Carla"], 1)]
_, sat, sun = seed_schedules(db)
for schedule in (sat, sun):
for pos, member in enumerate((alice, bruno, carla), 1):
db.add(RotationMember(schedule_id=schedule.id, team_id=member.id, position=pos))
db.add_all([
Assignment(schedule_id=sat.id, date=date(2026, 9, 26), team_id=bruno.id, source="manual"),
Assignment(schedule_id=sun.id, date=date(2026, 9, 27), team_id=carla.id, source="swap"),
])
db.commit()
assignments = ensure_month_assignments(db, 2026, 10)
assert [row.team_id for row in assignments if row.schedule_id == sat.id] == [
carla.id, alice.id, bruno.id, carla.id, alice.id,
]
assert [row.team_id for row in assignments if row.schedule_id == sun.id] == [
alice.id, bruno.id, carla.id, alice.id,
]
november = ensure_month_assignments(db, 2026, 11)
assert next(row for row in november if row.schedule_id == sat.id).team_id == bruno.id
assert next(row for row in november if row.schedule_id == sun.id).team_id == bruno.id
def test_generation_uses_preserved_manual_and_swapped_shifts_as_references():
with make_db() as db:
alice, bruno, carla = [add_team(db, name, pos) for pos, name in enumerate(["Alice", "Bruno", "Carla"], 1)]
_, sat, _ = seed_schedules(db)
for pos, member in enumerate((alice, bruno, carla), 1):
db.add(RotationMember(schedule_id=sat.id, team_id=member.id, position=pos))
manual = Assignment(schedule_id=sat.id, date=date(2026, 10, 10), team_id=bruno.id, source="manual")
swapped = Assignment(schedule_id=sat.id, date=date(2026, 10, 24), team_id=alice.id, source="swap")
db.add_all([manual, swapped])
db.commit()
original_ids = manual.id, swapped.id
rows = ensure_month_assignments(db, 2026, 10)
assert [row.team_id for row in rows if row.schedule_id == sat.id] == [
alice.id, bruno.id, carla.id, alice.id, bruno.id,
]
assert (manual.id, swapped.id) == original_ids
assert (manual.source, swapped.source) == ("manual", "swap")
snapshot = [(row.id, row.team_id, row.source) for row in rows]
assert [(row.id, row.team_id, row.source) for row in ensure_month_assignments(db, 2026, 10)] == snapshot
@pytest.mark.parametrize("previous, inactive, expected", [
("Alice", ["Alice"], "Bruno"), # inactive reference still has its position
("Alice", ["Bruno"], "Carla"), # skip the inactive next team
("Carla", [], "Alice"), # wrap at the end
("Alice", ["Alice", "Bruno", "Carla"], None),
("Outside", [], "Alice"), # removed team: fallback to the anchor
])
def test_reference_selection_handles_inactive_members_wraparound_and_missing_members(previous, inactive, expected):
with make_db() as db:
teams = {name: add_team(db, name, pos) for pos, name in enumerate(["Alice", "Bruno", "Carla", "Outside"], 1)}
_, sat, _ = seed_schedules(db)
for pos, name in enumerate(("Alice", "Bruno", "Carla"), 1):
teams[name].is_active = name not in inactive
db.add(RotationMember(schedule_id=sat.id, team_id=teams[name].id, position=pos))
db.add(Assignment(schedule_id=sat.id, date=date(2026, 9, 26), team_id=teams[previous].id, source="manual"))
db.commit()
selected = rotation_team_for_date(db, sat, date(2026, 10, 3))
assert (selected.name if selected else None) == expected
def test_reference_ignores_unassigned_dates_current_date_and_future_shifts():
with make_db() as db:
alice, bruno, carla = [add_team(db, name, pos) for pos, name in enumerate(["Alice", "Bruno", "Carla"], 1)]
_, sat, sun = seed_schedules(db)
for pos, member in enumerate((alice, bruno, carla), 1):
db.add(RotationMember(schedule_id=sat.id, team_id=member.id, position=pos))
db.add_all([
Assignment(schedule_id=sat.id, date=date(2026, 9, 19), team_id=bruno.id, source="manual"),
Assignment(schedule_id=sat.id, date=date(2026, 9, 26), team_id=None, source="manual"),
Assignment(schedule_id=sun.id, date=date(2026, 9, 27), team_id=carla.id, source="manual"),
Assignment(schedule_id=sat.id, date=date(2026, 10, 3), team_id=alice.id, source="manual"),
Assignment(schedule_id=sat.id, date=date(2026, 10, 10), team_id=carla.id, source="manual"),
])
db.commit()
assert rotation_team_for_date(db, sat, date(2026, 10, 3)).id == carla.id
-8
View File
@@ -1,8 +0,0 @@
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)
-552
View File
@@ -1,552 +0,0 @@
import re
from datetime import date
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, select
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database import Base, get_db
from app.main import app
from app.models import Assignment, SwapRequest, Team, User
from app.security import verify_password
from factories import make_member, make_shared_user, make_team, make_user
CSRF_RE = re.compile(r'name="csrf_token" value="([^"]+)"')
@pytest.fixture()
def db():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine, expire_on_commit=False)()
try:
yield session
finally:
session.close()
@pytest.fixture()
def client(db):
def override_get_db():
yield db
app.dependency_overrides[get_db] = override_get_db
try:
yield TestClient(app)
finally:
app.dependency_overrides.pop(get_db, None)
@pytest.fixture()
def admin(db):
"""The administrator: a team on the rota with its own administrator user."""
return make_member(db, "Admin", "admin", password="admin-password", is_admin=True)
def csrf(client: TestClient, path: str) -> str:
match = CSRF_RE.search(client.get(path).text)
assert match, f"no csrf token on {path}"
return match.group(1)
def login(client: TestClient, username: str, password: str) -> str:
token = csrf(client, "/login")
return client.post(
"/login",
data={"username": username, "password": password, "csrf_token": token},
follow_redirects=True,
).text
def add_team(client: TestClient, **fields) -> str:
data = {"name": "Equipa", "csrf_token": csrf(client, "/admin/teams")}
data.update(fields)
return client.post("/admin/teams", data=data, follow_redirects=True).text
def update_team(client: TestClient, team_id: int, **fields) -> str:
data = {
"name": "Equipa",
"is_active": "on",
"notify_email": "on",
"csrf_token": csrf(client, "/admin/teams"),
}
data.update(fields)
return client.post(f"/admin/teams/{team_id}/update", data=data, follow_redirects=True).text
def add_user(client: TestClient, **fields) -> str:
data = {"name": "Gestão", "csrf_token": csrf(client, "/admin/users")}
data.update(fields)
return client.post("/admin/users", data=data, follow_redirects=True).text
def update_user(client: TestClient, user_id: int, **fields) -> str:
data = {
"name": "Gestão",
"is_active": "on",
"csrf_token": csrf(client, "/admin/users"),
}
data.update(fields)
return client.post(f"/admin/users/{user_id}/update", data=data, follow_redirects=True).text
def usernames(db) -> list[str | None]:
return [team.username for team in db.scalars(select(Team).order_by(Team.name)).all()]
def team_named(db, name: str) -> Team:
return db.scalar(select(Team).where(Team.name == name))
def user_named(db, username: str) -> User:
return db.scalar(select(User).where(User.username == username))
def night_schedule(db):
"""A night schedule that needs no manager approval, so a swap completes at once."""
from app.models import Schedule
schedule = Schedule(
name="Noite",
slug="night",
schedule_type="fixed",
weekdays="0,1,2,3,4,5,6",
requires_manager_approval=False,
is_active=True,
)
db.add(schedule)
db.commit()
return schedule
def shift_on(db, schedule, team: Team, day: date):
from app.models import Assignment
shift = Assignment(schedule_id=schedule.id, date=day, team_id=team.id, source="manual")
db.add(shift)
db.commit()
return shift
def test_a_team_is_created_without_any_access(client, db, admin):
login(client, "admin", "admin-password")
page = add_team(client, name="Rota Only")
assert "Equipa criada." in page
assert "Rota Only" in page
assert "sem utilizador" in page
assert usernames(db) == ["admin", None]
assert team_named(db, "Rota Only").can_login is False
def test_the_two_pages_keep_the_two_jobs_apart(client, db, admin):
login(client, "admin", "admin-password")
teams_page = client.get("/admin/teams").text
users_page = client.get("/admin/users").text
# Users are not created on the teams page...
assert 'name="username"' not in teams_page
assert 'name="password"' not in teams_page
assert 'name="team_ids"' not in teams_page
# ...and the users page only picks from teams, it never asks for a new one.
assert 'name="phone"' not in users_page
assert 'action="/admin/teams"' not in users_page
assert 'name="assigned_user_id"' in teams_page
assert 'name="team_ids"' in users_page
def test_a_user_is_created_on_its_own_page_and_assigned_to_teams(client, db, admin):
login(client, "admin", "admin-password")
add_team(client, name="Carla")
add_team(client, name="Diogo")
carla = team_named(db, "Carla")
diogo = team_named(db, "Diogo")
page = add_user(
client,
name="Equipa de sábado",
username="sabado",
password="abcd",
team_ids=[str(carla.id), str(diogo.id)],
)
assert "Utilizador criado." in page
user = user_named(db, "sabado")
assert user.name == "Equipa de sábado"
assert {team.name for team in user.teams} == {"Carla", "Diogo"}
assert verify_password("abcd", user.password_hash)
def test_a_team_only_picks_which_user_signs_in_for_it(client, db, admin):
login(client, "admin", "admin-password")
add_team(client, name="Carla")
carla = team_named(db, "Carla")
sabado = make_user(db, "sabado", name="Equipa de sábado")
page = update_team(client, carla.id, name="Carla", assigned_user_id=str(sabado.id))
assert "Equipa atualizada." in page
db.refresh(carla)
assert carla.user_id == sabado.id
assert "partilhada com" not in page # only this team so far
assert "@sabado" in page
def test_the_same_user_can_be_picked_by_several_teams(client, db, admin):
login(client, "admin", "admin-password")
sabado = make_user(db, "sabado", name="Equipa de sábado")
add_team(client, name="Carla", assigned_user_id=str(sabado.id))
add_team(client, name="Diogo", assigned_user_id=str(sabado.id))
db.refresh(sabado)
assert {team.name for team in sabado.teams} == {"Carla", "Diogo"}
page = client.get("/admin/teams").text
assert page.count("partilhada com 1") == 2
def test_assigning_a_user_from_the_teams_page_replaces_the_previous_one(client, db, admin):
login(client, "admin", "admin-password")
add_team(client, name="Carla", assigned_user_id=str(user_named(db, "admin").id))
carla = team_named(db, "Carla")
sabado = make_user(db, "sabado")
update_team(client, carla.id, name="Carla", assigned_user_id=str(sabado.id))
db.refresh(carla)
assert carla.user_id == sabado.id
assert [team.name for team in sabado.teams] == ["Carla"]
# The administrator keeps only the team it signs in through.
assert [team.name for team in user_named(db, "admin").teams] == ["Admin"]
def test_a_team_with_nobody_signing_in_cannot_be_reached(client, db, admin):
make_team(db, "Rota Only")
assert "Nome de utilizador ou palavra-passe inválidos" in login(client, " ", "abcd")
assert client.get("/swaps", follow_redirects=False).status_code == 401
def test_an_inactive_user_cannot_sign_in(client, db, admin):
make_user(db, "folga", is_active=False)
assert "Nome de utilizador ou palavra-passe inválidos" in login(client, "folga", "login-password")
assert client.get("/swaps", follow_redirects=False).status_code == 401
def test_a_username_stays_unique(client, db, admin):
login(client, "admin", "admin-password")
page = add_user(client, username="admin", password="abcd")
assert "Esse nome de utilizador já existe." in page
assert len(db.scalars(select(User).where(User.username == "admin")).all()) == 1
def test_a_user_is_removed_only_once_no_team_uses_it(client, db, admin):
login(client, "admin", "admin-password")
spare = make_user(db, "sabado", name="Equipa de sábado")
add_team(client, name="Carla", assigned_user_id=str(spare.id))
carla = team_named(db, "Carla")
page = client.get("/admin/users").text
assert "@sabado" in page and "Carla" in page
assert f"/admin/users/{spare.id}/delete" not in page
client.post(
f"/admin/users/{spare.id}/delete",
data={"csrf_token": csrf(client, "/admin/users")},
follow_redirects=True,
)
assert db.get(User, spare.id) is not None
update_team(client, carla.id, name="Carla")
db.refresh(carla)
assert carla.user_id is None
client.post(
f"/admin/users/{spare.id}/delete",
data={"csrf_token": csrf(client, "/admin/users")},
follow_redirects=True,
)
assert db.get(User, spare.id) is None
assert db.get(Team, carla.id) is not None
def test_the_administrator_cannot_lock_themselves_out(client, db, admin):
login(client, "admin", "admin-password")
own_user = user_named(db, "admin")
page = update_user(client, own_user.id, name="Admin", username="admin", is_admin="on", is_active="")
assert "Não pode desativar o acesso com que está ligado." in page
assert db.get(User, own_user.id).is_active is True
page = update_user(client, own_user.id, name="Admin", username="admin", is_active="on", is_admin="")
assert "Não pode tirar a administração ao último utilizador que a tem." in page
assert db.get(User, own_user.id).is_admin is True
client.post(
f"/admin/users/{own_user.id}/delete",
data={"csrf_token": csrf(client, "/admin/users")},
follow_redirects=True,
)
assert db.get(User, own_user.id) is not None
def test_an_administrator_user_covers_every_team_assigned_to_it(client, db, admin):
login(client, "admin", "admin-password")
management = make_user(db, "gestao", name="Gestão", is_admin=True)
add_team(client, name="Rota Only", assigned_user_id=str(management.id), notify_email="on")
team = team_named(db, "Rota Only")
assert team.is_admin is True
client.post("/logout", data={"csrf_token": csrf(client, "/admin/teams")})
login(client, "gestao", "login-password")
assert "Gerir escalas" in client.get("/").text
assert client.get("/admin/teams").status_code == 200
def test_removing_a_team_clears_every_reference(client, db, admin):
from app.models import MonthlyPattern, NotificationLog, RotationMember, Schedule
login(client, "admin", "admin-password")
page = add_team(client, name="Rota Only")
assert f'href="/admin/teams/{db.scalar(select(Team.id).where(Team.name == "Rota Only"))}/delete"' in page
team = team_named(db, "Rota Only")
schedule = Schedule(
name="Almoço - Sábados",
slug="saturday-lunch",
schedule_type="rotation",
weekdays="5",
requires_manager_approval=True,
is_active=True,
rotation_anchor_date=date(2026, 1, 3),
)
db.add(schedule)
db.flush()
shift = Assignment(schedule_id=schedule.id, date=date(2026, 10, 3), team_id=team.id)
pattern = MonthlyPattern(schedule_id=schedule.id, day_of_month=1, team_id=team.id)
member = RotationMember(schedule_id=schedule.id, team_id=team.id, position=0)
log = NotificationLog(team_id=team.id, event_type="swap_requested", subject="x", body="x", status="skipped")
db.add_all([shift, pattern, member, log])
db.flush()
swap = SwapRequest(assignment_id=shift.id, requester_id=team.id, status="open")
db.add(swap)
db.commit()
# Someone who still holds a shift cannot be removed, not even from the past.
token = csrf(client, "/admin/teams")
assert client.get(f"/admin/teams/{team.id}/delete").status_code == 400
assert client.post(
f"/admin/teams/{team.id}/delete", data={"csrf_token": token}
).status_code == 400
assert db.get(Team, team.id) is not None
assert db.get(Assignment, shift.id).team_id == team.id
assert f'href="/admin/teams/{team.id}/delete"' not in client.get("/admin/teams").text
# Freeing the shift makes the removal possible again.
shift.team_id = None
db.commit()
assert f'href="/admin/teams/{team.id}/delete"' in client.get("/admin/teams").text
confirm = client.get(f"/admin/teams/{team.id}/delete").text
assert "Remover definitivamente" in confirm
assert "1 posição(ões) saem das rotações" in confirm
assert "1 dia(s) do padrão" in confirm
assert "1 pedido(s) de troca em aberto" in confirm
client.post(
f"/admin/teams/{team.id}/delete",
data={"csrf_token": csrf(client, "/admin/teams")},
follow_redirects=True,
)
assert db.get(Team, team.id) is None
db.refresh(log)
assert log.team_id is None
assert db.get(MonthlyPattern, pattern.id).team_id is None
assert db.get(RotationMember, member.id) is None
assert db.scalars(
select(SwapRequest).where(SwapRequest.requester_id == team.id)
).all() == []
def test_a_team_cannot_be_removed_by_a_member_or_without_the_right_token(client, db, admin):
login(client, "admin", "admin-password")
add_team(client, name="Rota Only")
team = team_named(db, "Rota Only")
url = f"/admin/teams/{team.id}/delete"
token = csrf(client, "/admin/teams")
assert client.post(url, data={"csrf_token": "invalid"}).status_code == 400
add_user(client, name="Member", username="member", password="member-password")
client.post("/logout", data={"csrf_token": csrf(client, "/admin/teams")})
login(client, "member", "member-password")
token = csrf(client, "/")
assert client.get(url).status_code == 403
assert client.post(url, data={"csrf_token": token}).status_code == 403
client.post("/logout", data={"csrf_token": token})
assert client.get(url).status_code == 401
assert client.post(url, data={"csrf_token": "invalid"}).status_code == 401
assert db.get(Team, team.id) is not None
def test_the_administrator_cannot_remove_their_own_team(client, db, admin):
login(client, "admin", "admin-password")
token = csrf(client, "/admin/teams")
assert client.get(f"/admin/teams/{admin.id}/delete").status_code == 400
assert client.post(
f"/admin/teams/{admin.id}/delete", data={"csrf_token": token}
).status_code == 400
assert f'href="/admin/teams/{admin.id}/delete"' not in client.get("/admin/teams").text
def test_a_user_sees_and_controls_every_team_assigned_to_it(client, db, admin):
login(client, "admin", "admin-password")
_, (carla, diogo) = make_shared_user(db, "sabado", "Carla", "Diogo")
bruno = make_member(db, "Bruno", "bruno")
schedule = night_schedule(db)
shift_on(db, schedule, carla, date(2026, 10, 3))
shift_on(db, schedule, diogo, date(2026, 10, 4))
bruno_shift = shift_on(db, schedule, bruno, date(2026, 10, 12))
diogo_next = shift_on(db, schedule, diogo, date(2026, 10, 11))
client.post("/logout", data={"csrf_token": csrf(client, "/")})
rota = login(client, "sabado", "team-password")
# Three of the month's shifts belong to the two teams this user covers.
assert rota.count('class="assignment mine"') == 3
client.post("/logout", data={"csrf_token": csrf(client, "/")})
login(client, "bruno", "member-password")
client.post(
"/swaps/new",
data={
"csrf_token": csrf(client, "/swaps/new"),
"assignment_id": bruno_shift.id,
"target_assignment_id": diogo_next.id,
},
follow_redirects=True,
)
swap = db.scalar(select(SwapRequest).where(SwapRequest.requester_id == bruno.id))
assert swap is not None and swap.target_team_id == diogo.id
client.post("/logout", data={"csrf_token": csrf(client, "/swaps")})
login(client, "sabado", "team-password")
assert swap.requester.name in client.get("/swaps").text
client.post(
f"/swaps/{swap.id}/accept",
data={"csrf_token": csrf(client, "/swaps")},
follow_redirects=True,
)
# The shift goes to the team the request named, not to the session.
db.refresh(swap)
assert swap.status == "approved"
assert swap.accepted_team_id == diogo.id
assert bruno_shift.team_id == diogo.id
assert swap.target_assignment.team_id == bruno.id
def test_a_user_cannot_answer_a_request_from_its_own_team(client, db, admin):
login(client, "admin", "admin-password")
_, (carla, diogo) = make_shared_user(db, "sabado", "Carla", "Diogo")
bruno = make_member(db, "Bruno", "bruno")
schedule = night_schedule(db)
carla_shift = shift_on(db, schedule, carla, date(2026, 10, 3))
bruno_shift = shift_on(db, schedule, bruno, date(2026, 10, 12))
swap = SwapRequest(
assignment_id=carla_shift.id,
target_assignment_id=bruno_shift.id,
requester_id=carla.id,
target_team_id=bruno.id,
status="open",
)
db.add(swap)
db.commit()
client.post("/logout", data={"csrf_token": csrf(client, "/")})
login(client, "sabado", "team-password")
assert client.post(
f"/swaps/{swap.id}/accept", data={"csrf_token": csrf(client, "/swaps")}
).status_code == 400
assert bruno_shift.team_id == bruno.id
def test_a_user_changes_its_own_password(client, db, admin):
login(client, "admin", "admin-password")
add_user(client, name="Member", username="member", password="abcd")
user = user_named(db, "member")
# the username in the bar is the button that opens the password editor
assert '<a class="account-link" href="/account"' in client.get("/").text
client.post("/logout", data={"csrf_token": csrf(client, "/")})
login(client, "member", "abcd")
rota = client.get("/").text
assert '<a class="account-link" href="/account"' in rota
assert "@member" in rota
page = client.get("/account").text
assert "Alterar palavra-passe" in page
assert 'name="new_password"' in page
assert 'name="current_password"' not in page # one field is enough
assert 'name="confirm_password"' not in page
client.post("/logout", data={"csrf_token": csrf(client, "/")})
login(client, "member", "abcd")
changed = client.post(
"/account",
data={"csrf_token": csrf(client, "/account"), "new_password": "wxyz"},
follow_redirects=True,
)
assert "Palavra-passe alterada." in changed.text
assert verify_password("wxyz", db.get(User, user.id).password_hash)
client.post("/logout", data={"csrf_token": csrf(client, "/")})
assert "Bem-vindo(a)" in login(client, "member", "wxyz")
assert "Nome de utilizador ou palavra-passe inválidos." in login(client, "member", "abcd")
def test_the_new_password_is_checked_before_it_is_saved(client, db, admin):
login(client, "admin", "admin-password")
token = csrf(client, "/account")
def post(new_password):
return client.post(
"/account",
data={"csrf_token": token, "new_password": new_password},
follow_redirects=True,
).text
assert "A palavra-passe tem de ter pelo menos 4 caracteres" in post("abc")
assert "A nova palavra-passe é igual à atual." in post("admin-password")
assert verify_password("admin-password", user_named(db, "admin").password_hash)
assert "Palavra-passe alterada." in post("outra1")
assert verify_password("outra1", user_named(db, "admin").password_hash)
def test_the_password_editor_needs_a_session_and_a_token(client, db, admin):
assert client.get("/account", follow_redirects=False).status_code == 401
assert client.post("/account", data={"new_password": "wxyz"}).status_code == 422 # no CSRF token
assert "account-link" not in client.get("/").text # signed out: no button at all
login(client, "admin", "admin-password")
assert client.post(
"/account", data={"csrf_token": "invalid", "new_password": "wxyz"}
).status_code == 400
def test_signed_in_home_is_the_rota_and_nav_has_no_rota_link(client, db, admin):
landing = login(client, "admin", "admin-password")
assert '<a class="brand" href="/"' in landing
nav = client.get("/admin/teams").text
assert '<a href="/">Rota</a>' not in nav
assert '<a href="/swaps">Trocas</a>' in nav
assert '<a href="/admin/teams">Equipas</a>' in nav
assert '<a href="/admin/users">Utilizadores</a>' in nav
assert 'href="/"' in nav # the brand stays the home link for signed-in members