feat: monorepo migration phase 3
App checks / changes (push) Canceled after 0s
App checks / tournament (push) Canceled after 0s
App checks / shifts (push) Canceled after 0s
App checks / changes (push) Canceled after 0s
App checks / tournament (push) Canceled after 0s
App checks / shifts (push) Canceled after 0s
This commit is contained in:
1 parent
e92ae5064c
commit
561b6a2da9
79 files changed
+4514
-1541
No files matched your search
@@ -25,6 +25,10 @@ jobs:
|
|||||||
filters: |
|
filters: |
|
||||||
tournament:
|
tournament:
|
||||||
- 'apps/tournament/**'
|
- 'apps/tournament/**'
|
||||||
|
- 'migration/contracts/**'
|
||||||
|
- 'migration/python_*'
|
||||||
|
- 'migration/fixtures/**'
|
||||||
|
- 'tools/check_tournament_compat.py'
|
||||||
- 'packages/crr-brand/**'
|
- 'packages/crr-brand/**'
|
||||||
- 'packages/crr-python/**'
|
- 'packages/crr-python/**'
|
||||||
- 'pyproject.toml'
|
- 'pyproject.toml'
|
||||||
@@ -56,6 +60,10 @@ jobs:
|
|||||||
node-version: '22'
|
node-version: '22'
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: apps/tournament/package-lock.json
|
cache-dependency-path: apps/tournament/package-lock.json
|
||||||
|
- uses: astral-sh/setup-uv@v6
|
||||||
|
with:
|
||||||
|
version: '0.11.31'
|
||||||
|
enable-cache: true
|
||||||
- run: make tournament-install tournament-test tournament-build
|
- run: make tournament-install tournament-test tournament-build
|
||||||
- run: docker compose config --quiet
|
- run: docker compose config --quiet
|
||||||
- run: docker build -f apps/tournament/Dockerfile -t crr-tournament .
|
- run: docker build -f apps/tournament/Dockerfile -t crr-tournament .
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ UV ?= uv
|
|||||||
PYTHON ?= python3
|
PYTHON ?= python3
|
||||||
.DEFAULT_GOAL := test
|
.DEFAULT_GOAL := test
|
||||||
|
|
||||||
.PHONY: baseline-test baseline-fixtures baseline-screenshots baseline-preserve migration-visual-check branding-visual-check images-smoke-test tournament-install tournament-backend-dev tournament-frontend-dev tournament-test tournament-build shifts-dev shifts-test shifts-build test
|
.PHONY: baseline-test baseline-fixtures baseline-screenshots baseline-preserve migration-visual-check branding-visual-check images-smoke-test tournament-install tournament-backend-dev tournament-frontend-dev tournament-test tournament-compat-test tournament-build shifts-dev shifts-test shifts-build test
|
||||||
|
|
||||||
baseline-test:
|
baseline-test:
|
||||||
$(PYTHON) tools/migration_baseline.py all
|
$(PYTHON) tools/migration_baseline.py all
|
||||||
@@ -32,14 +32,20 @@ tournament-install:
|
|||||||
npm --prefix apps/tournament ci
|
npm --prefix apps/tournament ci
|
||||||
|
|
||||||
tournament-backend-dev:
|
tournament-backend-dev:
|
||||||
npm --prefix apps/tournament run dev:server
|
DATABASE_PATH=$(abspath apps/tournament/tournament.sqlite) $(UV) run --directory apps/tournament/backend --package crr-tournament --locked uvicorn app.main:create_app --factory --reload --host 127.0.0.1 --port 8080 --no-proxy-headers
|
||||||
|
|
||||||
tournament-frontend-dev:
|
tournament-frontend-dev:
|
||||||
npm --prefix apps/tournament run dev:client
|
npm --prefix apps/tournament run dev:client
|
||||||
|
|
||||||
tournament-test:
|
tournament-test:
|
||||||
|
$(UV) run --directory apps/tournament/backend --package crr-tournament --locked pytest
|
||||||
npm --prefix apps/tournament test
|
npm --prefix apps/tournament test
|
||||||
npm --prefix apps/tournament run typecheck
|
npm --prefix apps/tournament run typecheck
|
||||||
|
$(PYTHON) tools/check_tournament_compat.py
|
||||||
|
|
||||||
|
tournament-compat-test:
|
||||||
|
$(UV) sync --package crr-tournament --locked
|
||||||
|
$(PYTHON) tools/check_tournament_compat.py
|
||||||
|
|
||||||
tournament-build:
|
tournament-build:
|
||||||
npm --prefix apps/tournament run build
|
npm --prefix apps/tournament run build
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Two independently runnable applications migrating into one monorepo:
|
Two independently runnable applications migrating into one monorepo:
|
||||||
|
|
||||||
- [Tournament](apps/tournament/README.md): Vue 3 and the temporary legacy Node backend.
|
- [Tournament](apps/tournament/README.md): Vue 3 and FastAPI on Python 3.13.
|
||||||
- [Shifts](apps/shifts/README.md): FastAPI, Jinja, SQLAlchemy and Alembic on Python 3.13.
|
- [Shifts](apps/shifts/README.md): FastAPI, Jinja, SQLAlchemy and Alembic on Python 3.13.
|
||||||
- [CRR brand](packages/crr-brand/README.md): shared logo, favicon and CSS primitives.
|
- [CRR brand](packages/crr-brand/README.md): shared logo, favicon and CSS primitives.
|
||||||
|
|
||||||
@@ -20,8 +20,9 @@ make shifts-test
|
|||||||
make test
|
make test
|
||||||
```
|
```
|
||||||
|
|
||||||
`uv` resolves Shifts dependencies using the single root `uv.lock` and creates the
|
`uv` resolves both backend projects using the single root `uv.lock` and creates
|
||||||
root `.venv`. Tournament joins that workspace when the FastAPI backend is ported.
|
the root `.venv`. Each backend runs from its own directory and owns its database,
|
||||||
|
models, authentication and migration history.
|
||||||
Run `make tournament-backend-dev` and `make tournament-frontend-dev` in separate
|
Run `make tournament-backend-dev` and `make tournament-frontend-dev` in separate
|
||||||
terminals, or `make shifts-dev` for Shifts. App-specific environment setup is
|
terminals, or `make shifts-dev` for Shifts. App-specific environment setup is
|
||||||
documented in each application's README.
|
documented in each application's README.
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 UV_PROJECT_ENVIRONMENT=/opt/ven
|
|||||||
WORKDIR /workspace
|
WORKDIR /workspace
|
||||||
COPY pyproject.toml uv.lock ./
|
COPY pyproject.toml uv.lock ./
|
||||||
COPY apps/shifts/backend/pyproject.toml apps/shifts/backend/pyproject.toml
|
COPY apps/shifts/backend/pyproject.toml apps/shifts/backend/pyproject.toml
|
||||||
|
COPY apps/tournament/backend/pyproject.toml apps/tournament/backend/pyproject.toml
|
||||||
RUN uv sync --frozen --package crr-shifts --no-dev --no-editable
|
RUN uv sync --frozen --package crr-shifts --no-dev --no-editable
|
||||||
COPY apps/shifts/backend/ apps/shifts/backend/
|
COPY apps/shifts/backend/ apps/shifts/backend/
|
||||||
COPY packages/crr-brand/ packages/crr-brand/
|
COPY packages/crr-brand/ packages/crr-brand/
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
ADMIN_PASSWORD=replace-with-an-admin-password
|
||||||
ADMIN_PASSWORD=<pass>
|
SESSION_SECRET=replace-with-a-long-random-session-secret
|
||||||
SESSION_SECRET=<secret>
|
TRUST_PROXY=false
|
||||||
TRUST_PROXY=true
|
APP_BASE_PATH=/jogo/
|
||||||
DEPLOYMENT_BASE_PATH=/jogo/
|
VITE_BASE_PATH=/jogo/
|
||||||
@@ -1,9 +1,15 @@
|
|||||||
# Tournament
|
# Tournament
|
||||||
|
|
||||||
- Follow the root migration plan and record checks in `migration/README.md`.
|
- Follow the root migration plan and record checks in `migration/README.md`.
|
||||||
- Phase 1 temporarily retains the Vue/Fastify source layout and Node backend.
|
- The FastAPI backend is under `backend/app`; Vue stays under `src/client` until
|
||||||
|
final layout cleanup. Backend commands must run from `backend/` to isolate its
|
||||||
|
`app` package from Shifts.
|
||||||
|
- Alembic owns the schema. Validate legacy databases before stamping the baseline;
|
||||||
|
preserve SQLite rows, constraints, indexes, FKs and existing container UID 1000.
|
||||||
- Preserve `/api/...`, camelCase payloads, Portuguese errors, session cookies,
|
- Preserve `/api/...`, camelCase payloads, Portuguese errors, session cookies,
|
||||||
HMAC tokens, login limiting, SSE, and sub-path deployment during the Python port.
|
HMAC tokens, login limiting, SSE, and sub-path deployment during the Python port.
|
||||||
- Keep deterministic calendar, standings, seeding, and bracket rules testable.
|
- Keep deterministic calendar, standings, seeding, and bracket rules testable.
|
||||||
- Run `make tournament-test` and `make tournament-build` from the repository root.
|
- Run `make tournament-test` and `make tournament-build` from the repository root.
|
||||||
|
- The compatibility command reuses preserved legacy assertions against real Python
|
||||||
|
services and HTTP servers; production code must not import the legacy backend.
|
||||||
- Version and release this application independently using `tournament-v...` tags.
|
- Version and release this application independently using `tournament-v...` tags.
|
||||||
+17
-13
@@ -1,22 +1,26 @@
|
|||||||
# Phase 1 retains the legacy Node runtime until the FastAPI compatibility exit.
|
FROM node:22-alpine AS frontend
|
||||||
FROM node:22-alpine AS build
|
|
||||||
WORKDIR /workspace/apps/tournament
|
WORKDIR /workspace/apps/tournament
|
||||||
RUN apk add --no-cache python3 make g++
|
|
||||||
COPY apps/tournament/package.json apps/tournament/package-lock.json ./
|
COPY apps/tournament/package.json apps/tournament/package-lock.json ./
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
COPY apps/tournament/ ./
|
COPY apps/tournament/ ./
|
||||||
COPY packages/crr-brand/ /workspace/packages/crr-brand/
|
COPY packages/crr-brand/ /workspace/packages/crr-brand/
|
||||||
ARG VITE_BASE_PATH=/jogo/
|
ARG VITE_BASE_PATH=/jogo/
|
||||||
ENV VITE_BASE_PATH=${VITE_BASE_PATH}
|
ENV VITE_BASE_PATH=${VITE_BASE_PATH}
|
||||||
RUN npm run build && npm prune --omit=dev
|
RUN npm run build
|
||||||
|
|
||||||
FROM node:22-alpine AS runtime
|
FROM ghcr.io/astral-sh/uv:0.11.31 AS uv
|
||||||
ENV NODE_ENV=production DATABASE_PATH=/data/tournament.sqlite CLIENT_DIST_PATH=/app/dist/client APP_BASE_PATH=/jogo/
|
FROM python:3.13-slim AS runtime
|
||||||
WORKDIR /app
|
COPY --from=uv /uv /uvx /bin/
|
||||||
COPY --from=build --chown=node:node /workspace/apps/tournament/package.json ./
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 UV_PROJECT_ENVIRONMENT=/opt/venv PATH="/opt/venv/bin:$PATH" DATABASE_PATH=/data/tournament.sqlite APP_BASE_PATH=/jogo/
|
||||||
COPY --from=build --chown=node:node /workspace/apps/tournament/node_modules ./node_modules
|
WORKDIR /workspace
|
||||||
COPY --from=build --chown=node:node /workspace/apps/tournament/dist ./dist
|
COPY pyproject.toml uv.lock ./
|
||||||
RUN mkdir /data && chown node:node /data
|
COPY apps/tournament/backend/pyproject.toml apps/tournament/backend/pyproject.toml
|
||||||
USER node
|
COPY apps/shifts/backend/pyproject.toml apps/shifts/backend/pyproject.toml
|
||||||
|
RUN uv sync --frozen --package crr-tournament --no-dev --no-editable
|
||||||
|
COPY apps/tournament/backend/ apps/tournament/backend/
|
||||||
|
COPY --from=frontend /workspace/apps/tournament/dist/client apps/tournament/dist/client/
|
||||||
|
RUN groupadd --gid 1000 tournament && useradd --uid 1000 --gid 1000 --no-create-home tournament && mkdir /data && chown tournament /data
|
||||||
|
WORKDIR /workspace/apps/tournament/backend
|
||||||
|
USER tournament
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
CMD ["node", "dist/server/main.js"]
|
CMD ["uvicorn", "app.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8080", "--no-proxy-headers"]
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
# Tournament
|
# Tournament
|
||||||
|
|
||||||
Phase 1 retains the legacy Vue/Fastify application under `src/client`, `src/server`
|
The FastAPI backend lives in `backend/app`, with app-specific SQLAlchemy models,
|
||||||
and `src/shared`. The planned `frontend/` and Python `backend/` split follows the
|
Alembic history, Pydantic schemas, domain services and routers. Vue continues to
|
||||||
API compatibility port; the current backend remains independently runnable.
|
use `src/client` and `src/shared` with its existing `/api/...` contract. The final
|
||||||
|
frontend directory move and removal of retired TypeScript server sources are
|
||||||
|
tracked as cleanup work in the migration plan.
|
||||||
|
|
||||||
Shared CRR assets and CSS come from `packages/crr-brand` through Vite's
|
Shared CRR assets and CSS come from `packages/crr-brand` through Vite's
|
||||||
`@crr-brand` alias. Tokens/base/components load before `src/client/styles.css`;
|
`@crr-brand` alias. Tokens/base/components load before `src/client/styles.css`;
|
||||||
@@ -21,7 +23,7 @@ make tournament-frontend-dev
|
|||||||
```
|
```
|
||||||
|
|
||||||
Copy `apps/tournament/.env.example` to `apps/tournament/.env` and configure
|
Copy `apps/tournament/.env.example` to `apps/tournament/.env` and configure
|
||||||
`ADMIN_PASSWORD` and `SESSION_SECRET`. The backend listens on port 8080 and Vite
|
`ADMIN_PASSWORD` and `SESSION_SECRET`. Uvicorn listens on port 8080 and Vite
|
||||||
on 5173. Development data is stored in `apps/tournament/tournament.sqlite`.
|
on 5173. Development data is stored in `apps/tournament/tournament.sqlite`.
|
||||||
Use consistent `APP_BASE_PATH` and `VITE_BASE_PATH`; `/jogo/` remains the example
|
Use consistent `APP_BASE_PATH` and `VITE_BASE_PATH`; `/jogo/` remains the example
|
||||||
deployment prefix, while both support `/`.
|
deployment prefix, while both support `/`.
|
||||||
@@ -33,9 +35,27 @@ docker compose up --build tournament
|
|||||||
Compose loads `apps/tournament/.env`; `TOURNAMENT_BASE_PATH` in the root shell
|
Compose loads `apps/tournament/.env`; `TOURNAMENT_BASE_PATH` in the root shell
|
||||||
controls both the frontend build path and backend path (default `/jogo/`). The
|
controls both the frontend build path and backend path (default `/jogo/`). The
|
||||||
`tournament-data` volume contains `/data/tournament.sqlite`. The image is
|
`tournament-data` volume contains `/data/tournament.sqlite`. The image is
|
||||||
`crr-tournament`; the current app version remains `1.0.0` in `package.json`.
|
`crr-tournament`; app version `1.0.0` is recorded in the frontend package and
|
||||||
|
backend project metadata. The image builds Vue with Node 22 and runs Python 3.13
|
||||||
|
as UID/GID 1000, matching the old container's database ownership.
|
||||||
|
|
||||||
Run checks with Node 22+; the CI/container target is Node 22. The legacy package
|
Tests require Node 22+ and uv. `make tournament-test` runs backend pytest,
|
||||||
has no lint script. Its tests cover HTTP/auth/SSE/sub-path behavior and the
|
frontend/shared tests, Vue typechecking and the preserved legacy compatibility
|
||||||
deterministic tournament services. Python migration fixtures live in
|
assertions against actual Python services and HTTP/SSE servers. Those assertions
|
||||||
`migration/fixtures/` at the repository root.
|
live in `migration/contracts`; their transports are generated only in ignored
|
||||||
|
`.migration/` staging. CI uses Node 22/Python 3.13 and does not execute snapshots.
|
||||||
|
Node backend dependencies (Fastify, better-sqlite3 and Zod) have been removed.
|
||||||
|
|
||||||
|
## Existing SQLite data
|
||||||
|
|
||||||
|
Startup upgrades empty databases with Alembic. Pre-Alembic databases are validated
|
||||||
|
against all nine legacy tables, columns, defaults, checks, unique/index definitions
|
||||||
|
and foreign keys before being stamped at `0001_baseline`. Adoption preserves
|
||||||
|
their schema and rows; there is no export/import. An incompatible schema stops
|
||||||
|
startup before stamping. SQLite foreign keys, WAL and a 5000 ms busy timeout are
|
||||||
|
configured on every connection. Migration/stamp operations are transactional.
|
||||||
|
|
||||||
|
Keep `SESSION_SECRET` unchanged during cut-over so existing HMAC/base64url admin
|
||||||
|
sessions remain valid. Cookie name/path, HttpOnly, Strict SameSite, HTTPS behavior
|
||||||
|
and seven-day lifetime are preserved. `TRUST_PROXY` controls forwarded headers.
|
||||||
|
Deployments under `/jogo/` retain the legacy proxy-prefix stripping behavior.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = %(here)s/migrations
|
||||||
|
prepend_sys_path = %(here)s
|
||||||
|
path_separator = os
|
||||||
Whitespace-only changes.
@@ -0,0 +1,23 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from pydantic import Field, field_validator
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
admin_password: str = Field(min_length=1)
|
||||||
|
session_secret: str = Field(min_length=1)
|
||||||
|
database_path: str = "/data/tournament.sqlite"
|
||||||
|
app_base_path: str = "/"
|
||||||
|
client_dist_path: Path = Path(__file__).resolve().parents[2] / "dist/client"
|
||||||
|
trust_proxy: bool = False
|
||||||
|
session_lifetime_ms: int = 7 * 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
model_config = SettingsConfigDict(env_file=Path(__file__).resolve().parents[2] / ".env", extra="ignore")
|
||||||
|
|
||||||
|
@field_validator("app_base_path")
|
||||||
|
@classmethod
|
||||||
|
def normalize_base(cls, value: str) -> str:
|
||||||
|
if not value.startswith("/"):
|
||||||
|
raise ValueError('APP_BASE_PATH tem de começar por "/".')
|
||||||
|
return value if value.endswith("/") else value + "/"
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from alembic import command
|
||||||
|
from alembic.config import Config
|
||||||
|
from sqlalchemy import CheckConstraint, DefaultClause, UniqueConstraint, URL, create_engine, event, inspect
|
||||||
|
from sqlalchemy.engine import Connection, Engine
|
||||||
|
from sqlalchemy.pool import StaticPool
|
||||||
|
|
||||||
|
from .models import Base
|
||||||
|
|
||||||
|
BACKEND = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def create_database_engine(path: str) -> Engine:
|
||||||
|
if path != ":memory:":
|
||||||
|
Path(path).resolve().parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
options = {"poolclass": StaticPool} if path == ":memory:" else {}
|
||||||
|
engine = create_engine(URL.create("sqlite", database=path),
|
||||||
|
connect_args={"check_same_thread": False}, **options)
|
||||||
|
|
||||||
|
@event.listens_for(engine, "connect")
|
||||||
|
def pragmas(connection, _record):
|
||||||
|
cursor = connection.cursor()
|
||||||
|
cursor.execute("PRAGMA foreign_keys=ON")
|
||||||
|
cursor.execute("PRAGMA journal_mode=WAL")
|
||||||
|
cursor.execute("PRAGMA busy_timeout=5000")
|
||||||
|
cursor.close()
|
||||||
|
|
||||||
|
return engine
|
||||||
|
|
||||||
|
|
||||||
|
def normalized(value: object) -> str:
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
return re.sub(r"\s+", "", str(value)).lower()
|
||||||
|
|
||||||
|
|
||||||
|
def validate_legacy_schema(connection: Connection) -> None:
|
||||||
|
inspector = inspect(connection)
|
||||||
|
if set(inspector.get_table_names()) - {"alembic_version"} != set(Base.metadata.tables):
|
||||||
|
raise RuntimeError("Tournament database does not match the legacy table set; adoption refused.")
|
||||||
|
for name, table in Base.metadata.tables.items():
|
||||||
|
actual = inspector.get_columns(name)
|
||||||
|
if [column["name"] for column in actual] != list(table.columns.keys()):
|
||||||
|
raise RuntimeError(f"Legacy columns differ: {name}; adoption refused.")
|
||||||
|
for column in actual:
|
||||||
|
expected = table.columns[column["name"]]
|
||||||
|
# SQLite reflects an INTEGER PRIMARY KEY as nullable, despite its implicit NOT NULL.
|
||||||
|
if (str(column["type"]) != str(expected.type).split(" COLLATE")[0] or
|
||||||
|
(not (expected.primary_key and len(table.primary_key.columns) == 1) and column["nullable"] != expected.nullable)):
|
||||||
|
raise RuntimeError(f"Legacy column type/nullability differs: {name}.{expected.name}")
|
||||||
|
default = column["default"]
|
||||||
|
expected_default = str(expected.server_default.arg) if isinstance(expected.server_default, DefaultClause) else None
|
||||||
|
if str(default).strip("'") != str(expected_default).strip("'"):
|
||||||
|
raise RuntimeError(f"Legacy default differs: {name}.{expected.name}")
|
||||||
|
if inspector.get_pk_constraint(name)["constrained_columns"] != [c.name for c in table.primary_key.columns]:
|
||||||
|
raise RuntimeError(f"Legacy primary key differs: {name}")
|
||||||
|
checks = {normalized(item["sqltext"]) for item in inspector.get_check_constraints(name)}
|
||||||
|
expected_checks = {normalized(item.sqltext) for item in table.constraints if isinstance(item, CheckConstraint)}
|
||||||
|
if checks != expected_checks:
|
||||||
|
raise RuntimeError(f"Legacy checks differ: {name}")
|
||||||
|
uniques = {tuple(item["column_names"]) for item in inspector.get_unique_constraints(name)}
|
||||||
|
expected_uniques = {tuple(c.name for c in item.columns) for item in table.constraints if isinstance(item, UniqueConstraint)}
|
||||||
|
if uniques != expected_uniques:
|
||||||
|
raise RuntimeError(f"Legacy unique constraints differ: {name}")
|
||||||
|
foreign = {(tuple(item["constrained_columns"]), item["referred_table"], tuple(item["referred_columns"]),
|
||||||
|
item.get("options", {}).get("ondelete")) for item in inspector.get_foreign_keys(name)}
|
||||||
|
expected_foreign = {(tuple(c.parent.name for c in item.elements), item.referred_table.name,
|
||||||
|
tuple(c.column.name for c in item.elements), item.ondelete) for item in table.foreign_key_constraints}
|
||||||
|
if foreign != expected_foreign:
|
||||||
|
raise RuntimeError(f"Legacy foreign keys differ: {name}")
|
||||||
|
indexes = {(item["name"], tuple(item["column_names"]), bool(item["unique"]),
|
||||||
|
normalized(item.get("dialect_options", {}).get("sqlite_where", "")))
|
||||||
|
for item in inspector.get_indexes(name)}
|
||||||
|
expected_indexes = {(item.name, tuple(c.name for c in item.columns), item.unique,
|
||||||
|
normalized(item.dialect_options["sqlite"].get("where"))) for item in table.indexes}
|
||||||
|
if indexes != expected_indexes:
|
||||||
|
raise RuntimeError(f"Legacy indexes differ: {name}")
|
||||||
|
ddl = connection.exec_driver_sql("SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (name,)).scalar_one()
|
||||||
|
if bool(table.dialect_options["sqlite"].get("autoincrement")) != ("autoincrement" in ddl.lower()):
|
||||||
|
raise RuntimeError(f"Legacy autoincrement differs: {name}")
|
||||||
|
if name == "league_groups" and not re.search(r"\bname\s+TEXT\b[^,]*\bCOLLATE\s+NOCASE\b", ddl, re.IGNORECASE):
|
||||||
|
raise RuntimeError("Legacy group collation differs")
|
||||||
|
if connection.exec_driver_sql("PRAGMA foreign_key_check").fetchall():
|
||||||
|
raise RuntimeError("Legacy foreign key violations; adoption refused.")
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations(engine: Engine) -> None:
|
||||||
|
with engine.begin() as connection:
|
||||||
|
# SQLite's legacy driver transaction mode does not begin on DDL.
|
||||||
|
# Explicitly enclose validation, stamping and upgrade in one real transaction.
|
||||||
|
connection.exec_driver_sql("BEGIN IMMEDIATE")
|
||||||
|
config = Config(str(BACKEND / "alembic.ini"))
|
||||||
|
config.attributes["connection"] = connection
|
||||||
|
tables = set(inspect(connection).get_table_names())
|
||||||
|
if tables and "alembic_version" not in tables:
|
||||||
|
validate_legacy_schema(connection)
|
||||||
|
command.stamp(config, "0001_baseline")
|
||||||
|
command.upgrade(config, "head")
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from starlette.exceptions import HTTPException
|
||||||
|
|
||||||
|
|
||||||
|
class AppError(Exception):
|
||||||
|
def __init__(self, status: int, message: str):
|
||||||
|
self.status = status
|
||||||
|
self.message = message
|
||||||
|
|
||||||
|
|
||||||
|
def install_errors(app: FastAPI) -> None:
|
||||||
|
@app.exception_handler(Exception)
|
||||||
|
async def unexpected_error(_request: Request, error: Exception):
|
||||||
|
logging.getLogger("tournament").error("Unexpected Tournament error", exc_info=error)
|
||||||
|
return JSONResponse({"error": "Ocorreu um erro inesperado. Tente novamente."}, status_code=500)
|
||||||
|
|
||||||
|
@app.exception_handler(AppError)
|
||||||
|
async def domain_error(_request: Request, error: AppError):
|
||||||
|
return JSONResponse({"error": error.message}, status_code=error.status)
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation_error(_request: Request, _error: RequestValidationError):
|
||||||
|
if any(item["type"] == "json_invalid" for item in _error.errors()):
|
||||||
|
# The legacy Fastify error handler treats malformed JSON as an unexpected error.
|
||||||
|
return JSONResponse({"error": "Ocorreu um erro inesperado. Tente novamente."}, status_code=500)
|
||||||
|
return JSONResponse({"error": "Os dados enviados não são válidos."}, status_code=400)
|
||||||
|
|
||||||
|
@app.exception_handler(HTTPException)
|
||||||
|
async def http_error(_request: Request, error: HTTPException):
|
||||||
|
return JSONResponse({"error": "O recurso pedido não existe."}, status_code=404 if error.status_code in (404, 405) else error.status_code)
|
||||||
|
|
||||||
|
@app.exception_handler(IntegrityError)
|
||||||
|
async def integrity_error(_request: Request, error: IntegrityError):
|
||||||
|
message = str(error.orig)
|
||||||
|
if "UNIQUE constraint failed: league_groups.name" in message:
|
||||||
|
return JSONResponse({"error": "Já existe um grupo com esse nome."}, status_code=409)
|
||||||
|
if "UNIQUE constraint failed: teams.number" in message:
|
||||||
|
return JSONResponse({"error": "Já existe uma equipa com esse número."}, status_code=409)
|
||||||
|
return JSONResponse({"error": "Ocorreu um erro inesperado. Tente novamente."}, status_code=500)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import asyncio
|
||||||
|
from threading import Lock
|
||||||
|
|
||||||
|
STATE_CHANGED = 'event: state-changed\ndata: {"type":"state-changed"}\n\n'
|
||||||
|
|
||||||
|
|
||||||
|
class StateChangeEvents:
|
||||||
|
def __init__(self, heartbeat_seconds: float = 25):
|
||||||
|
self.heartbeat_seconds = heartbeat_seconds
|
||||||
|
self.clients = {}
|
||||||
|
self.lock = Lock()
|
||||||
|
|
||||||
|
def broadcast(self) -> None:
|
||||||
|
with self.lock:
|
||||||
|
for queue, loop in self.clients.items():
|
||||||
|
loop.call_soon_threadsafe(queue.put_nowait, STATE_CHANGED)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
with self.lock:
|
||||||
|
for queue, loop in self.clients.items():
|
||||||
|
loop.call_soon_threadsafe(queue.put_nowait, None)
|
||||||
|
|
||||||
|
async def stream(self):
|
||||||
|
queue = asyncio.Queue()
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
with self.lock:
|
||||||
|
self.clients[queue] = loop
|
||||||
|
next_heartbeat = loop.time() + self.heartbeat_seconds
|
||||||
|
try:
|
||||||
|
yield "retry: 3000\n\n"
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
message = await asyncio.wait_for(queue.get(), max(0, next_heartbeat - loop.time()))
|
||||||
|
if message is None:
|
||||||
|
return
|
||||||
|
yield message
|
||||||
|
except TimeoutError:
|
||||||
|
yield ": heartbeat\n\n"
|
||||||
|
next_heartbeat = loop.time() + self.heartbeat_seconds
|
||||||
|
finally:
|
||||||
|
with self.lock:
|
||||||
|
self.clients.pop(queue, None)
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import asyncio
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
|
||||||
|
|
||||||
|
from .config import Settings
|
||||||
|
from .database import create_database_engine, run_migrations
|
||||||
|
from .errors import AppError, install_errors
|
||||||
|
from .events import StateChangeEvents
|
||||||
|
from .routers import auth, public
|
||||||
|
from .routers.admin import calendar, display, final_stage, groups, matches, settings as settings_router, teams
|
||||||
|
from .security.rate_limit import LoginRateLimiter
|
||||||
|
|
||||||
|
|
||||||
|
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||||
|
settings = settings or Settings()
|
||||||
|
engine = create_database_engine(settings.database_path)
|
||||||
|
events = StateChangeEvents()
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app):
|
||||||
|
try:
|
||||||
|
run_migrations(engine)
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
events.close()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None, redirect_slashes=False)
|
||||||
|
app.state.settings = settings
|
||||||
|
app.state.engine = engine
|
||||||
|
app.state.sessions = sessionmaker(engine, expire_on_commit=False)
|
||||||
|
app.state.database_lock = asyncio.Lock()
|
||||||
|
app.state.events = events
|
||||||
|
app.state.limiter = LoginRateLimiter()
|
||||||
|
if settings.trust_proxy:
|
||||||
|
app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")
|
||||||
|
install_errors(app)
|
||||||
|
for router in [auth.router, public.router, settings_router.router, display.router, groups.router,
|
||||||
|
teams.router, calendar.router, matches.router, final_stage.router]:
|
||||||
|
app.include_router(router)
|
||||||
|
|
||||||
|
@app.api_route("/{path:path}", methods=["GET", "HEAD"], include_in_schema=False)
|
||||||
|
def client(path: str):
|
||||||
|
root = settings.client_dist_path.resolve()
|
||||||
|
file = (root / path).resolve()
|
||||||
|
if not file.is_relative_to(root):
|
||||||
|
raise AppError(404, "O recurso pedido não existe.")
|
||||||
|
if path in ("", "results", "display", "display/", "admin") or path.startswith("admin/"):
|
||||||
|
file = root / "index.html"
|
||||||
|
if not file.is_file():
|
||||||
|
raise AppError(404, "O recurso pedido não existe.")
|
||||||
|
return FileResponse(file)
|
||||||
|
|
||||||
|
return app
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
from .base import Base
|
||||||
|
from .final_stage import FinalResult, FinalSeed
|
||||||
|
from .matches import LeagueMatch, LeagueRound
|
||||||
|
from .settings import DisplaySettings, TournamentSettings
|
||||||
|
from .teams import Group, Player, Team
|
||||||
|
|
||||||
|
__all__ = ["Base", "FinalResult", "FinalSeed", "LeagueMatch", "LeagueRound",
|
||||||
|
"DisplaySettings", "TournamentSettings", "Group", "Player", "Team"]
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
from sqlalchemy import CheckConstraint, ForeignKey, Index, Integer, text
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from .base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class FinalSeed(Base):
|
||||||
|
__tablename__ = "final_seeds"
|
||||||
|
__table_args__ = (CheckConstraint("slot_index >= 1"),
|
||||||
|
Index("idx_final_seeds_unique_team", "team_id", unique=True, sqlite_where=text("team_id IS NOT NULL")))
|
||||||
|
slot_index: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.id"))
|
||||||
|
|
||||||
|
|
||||||
|
class FinalResult(Base):
|
||||||
|
__tablename__ = "final_match_results"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("round_index >= 1"), CheckConstraint("match_index >= 1"),
|
||||||
|
CheckConstraint("(score_a IS NULL AND score_b IS NULL) OR (score_a IS NOT NULL AND score_b IS NOT NULL AND score_a >= 0 AND score_b >= 0)"),
|
||||||
|
)
|
||||||
|
round_index: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
match_index: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
score_a: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
score_b: Mapped[int | None] = mapped_column(Integer)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
from sqlalchemy import CheckConstraint, ForeignKey, Index, Integer
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from .base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class LeagueMatch(Base):
|
||||||
|
__tablename__ = "league_matches"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("order_index >= 1"), CheckConstraint("round_index >= 1"),
|
||||||
|
CheckConstraint("team_a_id <> team_b_id"),
|
||||||
|
CheckConstraint("(score_a IS NULL AND score_b IS NULL) OR (score_a IS NOT NULL AND score_b IS NOT NULL AND score_a >= 0 AND score_b >= 0)"),
|
||||||
|
Index("idx_league_matches_order", "order_index"), {"sqlite_autoincrement": True},
|
||||||
|
)
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
order_index: Mapped[int] = mapped_column(Integer, unique=True)
|
||||||
|
round_index: Mapped[int] = mapped_column(Integer)
|
||||||
|
team_a_id: Mapped[int] = mapped_column(ForeignKey("teams.id"))
|
||||||
|
team_b_id: Mapped[int] = mapped_column(ForeignKey("teams.id"))
|
||||||
|
score_a: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
score_b: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
|
||||||
|
|
||||||
|
class LeagueRound(Base):
|
||||||
|
__tablename__ = "league_rounds"
|
||||||
|
__table_args__ = (CheckConstraint("round_index >= 1"), CheckConstraint("counts_toward_standings IN (0, 1)"))
|
||||||
|
round_index: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
counts_toward_standings: Mapped[int] = mapped_column(Integer, server_default="0")
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from sqlalchemy import CheckConstraint, Integer, Text, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from .base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class TournamentSettings(Base):
|
||||||
|
__tablename__ = "tournament_settings"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("id = 1"), CheckConstraint("length(trim(name)) > 0"),
|
||||||
|
CheckConstraint("final_round_count IS NULL OR (final_round_count BETWEEN 1 AND 8)"),
|
||||||
|
CheckConstraint("third_place_enabled IN (0, 1)"),
|
||||||
|
CheckConstraint("classification_mode IN ('standard', 'total-points')"),
|
||||||
|
)
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
name: Mapped[str] = mapped_column(Text)
|
||||||
|
final_round_count: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
created_at: Mapped[str] = mapped_column(Text, default=func.current_timestamp())
|
||||||
|
updated_at: Mapped[str] = mapped_column(Text, default=func.current_timestamp())
|
||||||
|
third_place_enabled: Mapped[int] = mapped_column(Integer, server_default="0")
|
||||||
|
classification_mode: Mapped[str] = mapped_column(Text, server_default="standard")
|
||||||
|
|
||||||
|
|
||||||
|
class DisplaySettings(Base):
|
||||||
|
__tablename__ = "display_settings"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("id = 1"), CheckConstraint("length(trim(active_panel)) > 0"),
|
||||||
|
CheckConstraint("zoom_percent BETWEEN 50 AND 400"),
|
||||||
|
)
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
active_panel: Mapped[str] = mapped_column(Text)
|
||||||
|
zoom_percent: Mapped[int] = mapped_column(Integer, server_default="100")
|
||||||
|
created_at: Mapped[str] = mapped_column(Text, default=func.current_timestamp())
|
||||||
|
updated_at: Mapped[str] = mapped_column(Text, default=func.current_timestamp())
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
from sqlalchemy import CheckConstraint, ForeignKey, Index, Integer, Text, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from .base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Group(Base):
|
||||||
|
__tablename__ = "league_groups"
|
||||||
|
__table_args__ = (CheckConstraint("length(trim(name)) > 0"), CheckConstraint("sort_order >= 0"),
|
||||||
|
{"sqlite_autoincrement": True})
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
name: Mapped[str] = mapped_column(Text(collation="NOCASE"), unique=True)
|
||||||
|
sort_order: Mapped[int] = mapped_column(Integer, unique=True)
|
||||||
|
created_at: Mapped[str] = mapped_column(Text, default=func.current_timestamp())
|
||||||
|
updated_at: Mapped[str] = mapped_column(Text, default=func.current_timestamp())
|
||||||
|
|
||||||
|
|
||||||
|
class Team(Base):
|
||||||
|
__tablename__ = "teams"
|
||||||
|
__table_args__ = (CheckConstraint("number > 0"), CheckConstraint("length(trim(name)) > 0"),
|
||||||
|
Index("idx_teams_group", "group_id"), {"sqlite_autoincrement": True})
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
number: Mapped[int] = mapped_column(Integer, unique=True)
|
||||||
|
name: Mapped[str] = mapped_column(Text)
|
||||||
|
group_id: Mapped[int] = mapped_column(ForeignKey("league_groups.id"))
|
||||||
|
created_at: Mapped[str] = mapped_column(Text, default=func.current_timestamp())
|
||||||
|
updated_at: Mapped[str] = mapped_column(Text, default=func.current_timestamp())
|
||||||
|
|
||||||
|
|
||||||
|
class Player(Base):
|
||||||
|
__tablename__ = "players"
|
||||||
|
__table_args__ = (CheckConstraint("length(trim(name)) > 0"), CheckConstraint("sort_order >= 0"),
|
||||||
|
Index("idx_players_team_order", "team_id", "sort_order"), {"sqlite_autoincrement": True})
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
team_id: Mapped[int] = mapped_column(ForeignKey("teams.id", ondelete="CASCADE"))
|
||||||
|
name: Mapped[str] = mapped_column(Text)
|
||||||
|
sort_order: Mapped[int] = mapped_column(Integer)
|
||||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,38 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Request
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from ...models import LeagueMatch
|
||||||
|
from ...schemas.base import Confirmation
|
||||||
|
from ...schemas.calendar import GenerationInput, PreviewInput
|
||||||
|
from ...services import calendar_store
|
||||||
|
from ...services.state import get_matches
|
||||||
|
from ..dependencies import DB, changed, confirm, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin/calendar", dependencies=[Depends(require_admin)])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
@router.head("", include_in_schema=False)
|
||||||
|
def read_calendar(db: DB):
|
||||||
|
return calendar_store.summary(get_matches(db))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate-preview")
|
||||||
|
def preview(body: PreviewInput, db: DB):
|
||||||
|
return calendar_store.generate_preview(db, body.legs)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate")
|
||||||
|
def generate(body: GenerationInput, db: DB, request: Request):
|
||||||
|
result = calendar_store.save_calendar(db, body)
|
||||||
|
changed(db, request)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("")
|
||||||
|
def clear(db: DB, request: Request, body: Confirmation | None = None):
|
||||||
|
if db.scalar(select(LeagueMatch.id).limit(1)) is not None:
|
||||||
|
confirm(body is not None and body.confirm, "Confirme que pretende limpar o calendário e todos os seus resultados.")
|
||||||
|
calendar_store.clear_calendar(db)
|
||||||
|
changed(db, request)
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Request
|
||||||
|
from sqlalchemy import func
|
||||||
|
|
||||||
|
from ...models import DisplaySettings as DisplayRow
|
||||||
|
from ...schemas.settings import DisplayInput
|
||||||
|
from ...services.state import get_display
|
||||||
|
from ..dependencies import DB, changed, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin/display", dependencies=[Depends(require_admin)])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
@router.head("", include_in_schema=False)
|
||||||
|
def read_display(db: DB):
|
||||||
|
return get_display(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("")
|
||||||
|
def update_display(body: DisplayInput, db: DB, request: Request):
|
||||||
|
row = db.get(DisplayRow, 1)
|
||||||
|
row.active_panel, row.zoom_percent, row.updated_at = body.active_panel, body.zoom_percent, func.current_timestamp()
|
||||||
|
changed(db, request)
|
||||||
|
return get_display(db)
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, Depends, Request
|
||||||
|
|
||||||
|
from ...schemas.base import Confirmation, PositiveId
|
||||||
|
from ...schemas.calendar import ResultInput
|
||||||
|
from ...schemas.final_stage import ConfigInput, OverallInput, PerGroupInput, SeedsInput
|
||||||
|
from ...services import final_stage
|
||||||
|
from ...services.state import get_final_stage, get_settings
|
||||||
|
from ..dependencies import DB, changed, confirm, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin/final-stage", dependencies=[Depends(require_admin)])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
@router.head("", include_in_schema=False)
|
||||||
|
def read_stage(db: DB):
|
||||||
|
return get_final_stage(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/config")
|
||||||
|
def configure(body: ConfigInput, db: DB, request: Request):
|
||||||
|
if final_stage.configure(db, body):
|
||||||
|
changed(db, request)
|
||||||
|
return get_final_stage(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/config")
|
||||||
|
def clear_config(db: DB, request: Request, body: Confirmation | None = None):
|
||||||
|
if get_settings(db).final_round_count is not None:
|
||||||
|
confirm(body is not None and body.confirm, "Confirme que pretende limpar a configuração e todos os resultados da fase final.")
|
||||||
|
final_stage.clear(db)
|
||||||
|
changed(db, request)
|
||||||
|
return get_final_stage(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/auto-seed-preview")
|
||||||
|
def preview(body: Annotated[PerGroupInput | OverallInput, Body(discriminator="mode")], db: DB):
|
||||||
|
return final_stage.seed_preview(db, body)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/seeds")
|
||||||
|
def seeds(body: SeedsInput, db: DB, request: Request):
|
||||||
|
if final_stage.save_seeds(db, body):
|
||||||
|
changed(db, request)
|
||||||
|
return get_final_stage(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/matches/{round}/{match}/result")
|
||||||
|
def save_result(round: PositiveId, match: PositiveId, body: ResultInput, db: DB, request: Request):
|
||||||
|
final_stage.save_result(db, round, match, body.score_a, body.score_b)
|
||||||
|
changed(db, request)
|
||||||
|
return get_final_stage(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/matches/{round}/{match}/result")
|
||||||
|
def clear_result(round: PositiveId, match: PositiveId, db: DB, request: Request):
|
||||||
|
final_stage.clear_result(db, round, match)
|
||||||
|
changed(db, request)
|
||||||
|
return get_final_stage(db)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Request
|
||||||
|
|
||||||
|
from ...schemas.base import PositiveId
|
||||||
|
from ...schemas.teams import NameInput
|
||||||
|
from ...services import teams
|
||||||
|
from ...services.state import get_groups
|
||||||
|
from ..dependencies import DB, changed, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin/groups", dependencies=[Depends(require_admin)])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
@router.head("", include_in_schema=False)
|
||||||
|
def read_groups(db: DB):
|
||||||
|
return get_groups(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", status_code=201)
|
||||||
|
def create_group(body: NameInput, db: DB, request: Request):
|
||||||
|
result = teams.create_group(db, body.name)
|
||||||
|
changed(db, request)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{id}")
|
||||||
|
def update_group(id: PositiveId, body: NameInput, db: DB, request: Request):
|
||||||
|
result = teams.update_group(db, id, body.name)
|
||||||
|
changed(db, request)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{id}")
|
||||||
|
def delete_group(id: PositiveId, db: DB, request: Request):
|
||||||
|
teams.delete_group(db, id)
|
||||||
|
changed(db, request)
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Request
|
||||||
|
|
||||||
|
from ...errors import AppError
|
||||||
|
from ...models import LeagueMatch, LeagueRound
|
||||||
|
from ...schemas.base import PositiveId
|
||||||
|
from ...schemas.calendar import ResultInput, StandingsInput
|
||||||
|
from ...services.state import get_matches
|
||||||
|
from ..dependencies import DB, changed, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin", dependencies=[Depends(require_admin)])
|
||||||
|
|
||||||
|
|
||||||
|
def existing_match(db, identifier):
|
||||||
|
row = db.get(LeagueMatch, identifier)
|
||||||
|
if row is None:
|
||||||
|
raise AppError(404, "O jogo não existe.")
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/matches/{id}/result")
|
||||||
|
def save_result(id: PositiveId, body: ResultInput, db: DB, request: Request):
|
||||||
|
row = existing_match(db, id)
|
||||||
|
row.score_a, row.score_b = body.score_a, body.score_b
|
||||||
|
changed(db, request)
|
||||||
|
return next(match for match in get_matches(db) if match.id == id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/matches/{id}/result")
|
||||||
|
def clear_result(id: PositiveId, db: DB, request: Request):
|
||||||
|
row = existing_match(db, id)
|
||||||
|
row.score_a = row.score_b = None
|
||||||
|
changed(db, request)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/rounds/{round}/standings")
|
||||||
|
def save_standings(round: PositiveId, body: StandingsInput, db: DB, request: Request):
|
||||||
|
row = db.get(LeagueRound, round)
|
||||||
|
if row is None:
|
||||||
|
raise AppError(404, "A jornada não existe.")
|
||||||
|
row.counts_toward_standings = int(body.counts_toward_standings)
|
||||||
|
changed(db, request)
|
||||||
|
return {"roundNumber": round, "countsTowardStandings": body.counts_toward_standings}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Request
|
||||||
|
from sqlalchemy import func
|
||||||
|
|
||||||
|
from ...models import TournamentSettings
|
||||||
|
from ...schemas.settings import SettingsInput
|
||||||
|
from ...services.state import get_settings
|
||||||
|
from ..dependencies import DB, changed, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin/settings", dependencies=[Depends(require_admin)])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
@router.head("", include_in_schema=False)
|
||||||
|
def read_settings(db: DB):
|
||||||
|
return get_settings(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("")
|
||||||
|
def update_settings(body: SettingsInput, db: DB, request: Request):
|
||||||
|
row = db.get(TournamentSettings, 1)
|
||||||
|
row.name, row.classification_mode, row.updated_at = body.name, body.classification_mode, func.current_timestamp()
|
||||||
|
changed(db, request)
|
||||||
|
return get_settings(db)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Request
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
|
||||||
|
from ...models import Player
|
||||||
|
from ...errors import AppError
|
||||||
|
from ...schemas.base import Confirmation, PositiveId
|
||||||
|
from ...schemas.teams import NameInput, TeamCreate, TeamInput
|
||||||
|
from ...services import teams
|
||||||
|
from ...services.state import get_admin_teams, player_from_row
|
||||||
|
from ..dependencies import DB, changed, confirm, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin", dependencies=[Depends(require_admin)])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/teams")
|
||||||
|
@router.head("/teams", include_in_schema=False)
|
||||||
|
def read_teams(db: DB):
|
||||||
|
return get_admin_teams(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/teams/randomize")
|
||||||
|
def randomize(db: DB, request: Request, body: Confirmation | None = None):
|
||||||
|
confirm(body is not None and body.confirm, "Confirme que pretende randomizar os números e os grupos das equipas.")
|
||||||
|
result = teams.randomize_teams(db)
|
||||||
|
changed(db, request)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/teams", status_code=201)
|
||||||
|
def create_team(body: TeamCreate, db: DB, request: Request):
|
||||||
|
result = teams.create_team(db, body)
|
||||||
|
changed(db, request)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/teams/{id}")
|
||||||
|
def update_team(id: PositiveId, body: TeamInput, db: DB, request: Request):
|
||||||
|
result = teams.update_team(db, id, body)
|
||||||
|
changed(db, request)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/teams/{id}")
|
||||||
|
def delete_team(id: PositiveId, db: DB, request: Request):
|
||||||
|
teams.delete_team(db, id)
|
||||||
|
changed(db, request)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/teams/{teamId}/players", status_code=201)
|
||||||
|
def create_player(teamId: PositiveId, body: NameInput, db: DB, request: Request):
|
||||||
|
teams.existing_team(db, teamId)
|
||||||
|
order = db.scalar(select(func.max(Player.sort_order)).where(Player.team_id == teamId))
|
||||||
|
row = Player(team_id=teamId, name=body.name, sort_order=0 if order is None else order + 1)
|
||||||
|
db.add(row)
|
||||||
|
db.flush()
|
||||||
|
result = player_from_row(row)
|
||||||
|
changed(db, request)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def existing_player(db, identifier):
|
||||||
|
row = db.get(Player, identifier)
|
||||||
|
if row is None:
|
||||||
|
raise AppError(404, "O jogador não existe.")
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/players/{id}")
|
||||||
|
def update_player(id: PositiveId, body: NameInput, db: DB, request: Request):
|
||||||
|
row = existing_player(db, id)
|
||||||
|
row.name = body.name
|
||||||
|
result = player_from_row(row)
|
||||||
|
changed(db, request)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/players/{id}")
|
||||||
|
def delete_player(id: PositiveId, db: DB, request: Request):
|
||||||
|
db.delete(existing_player(db, id))
|
||||||
|
changed(db, request)
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
from fastapi import APIRouter, Request, Response
|
||||||
|
from pydantic import Field, field_validator
|
||||||
|
|
||||||
|
from ..errors import AppError
|
||||||
|
from ..schemas.base import RequestSchema
|
||||||
|
from ..security.session import COOKIE_NAME, create_token, password_matches, valid_token
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/auth")
|
||||||
|
|
||||||
|
|
||||||
|
class LoginInput(RequestSchema):
|
||||||
|
password: str = Field(strict=True, min_length=1, max_length=1000)
|
||||||
|
|
||||||
|
@field_validator("password")
|
||||||
|
@classmethod
|
||||||
|
def password_length(cls, value):
|
||||||
|
if len(value.encode("utf-16-le", errors="surrogatepass")) // 2 > 1000:
|
||||||
|
raise ValueError("Invalid password length")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login")
|
||||||
|
def login(body: LoginInput, request: Request, response: Response):
|
||||||
|
# Checking, recording and resetting attempts must be atomic across ASGI workers.
|
||||||
|
with request.app.state.limiter.lock:
|
||||||
|
return finish_login(body, request, response)
|
||||||
|
|
||||||
|
|
||||||
|
def finish_login(body: LoginInput, request: Request, response: Response):
|
||||||
|
settings, limiter = request.app.state.settings, request.app.state.limiter
|
||||||
|
key = request.client.host if request.client else ""
|
||||||
|
if limiter.limited(key):
|
||||||
|
raise AppError(429, "Foram feitas demasiadas tentativas. Tente novamente mais tarde.")
|
||||||
|
if not password_matches(body.password, settings.admin_password):
|
||||||
|
limiter.failure(key)
|
||||||
|
raise AppError(401, "A palavra-passe está incorreta.")
|
||||||
|
limiter.clear(key)
|
||||||
|
response.set_cookie(COOKIE_NAME, create_token(settings), path=settings.app_base_path,
|
||||||
|
httponly=True, samesite="strict", secure=request.url.scheme == "https",
|
||||||
|
max_age=settings.session_lifetime_ms // 1000)
|
||||||
|
return {"authenticated": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/logout")
|
||||||
|
def logout(request: Request, response: Response):
|
||||||
|
response.delete_cookie(COOKIE_NAME, path=request.app.state.settings.app_base_path,
|
||||||
|
httponly=True, samesite="strict", secure=request.url.scheme == "https")
|
||||||
|
return {"authenticated": False}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/session")
|
||||||
|
@router.head("/session", include_in_schema=False)
|
||||||
|
def session(request: Request):
|
||||||
|
return {"authenticated": valid_token(request.cookies.get(COOKIE_NAME), request.app.state.settings)}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import Depends, Request
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..errors import AppError
|
||||||
|
from ..security.session import COOKIE_NAME, valid_token
|
||||||
|
|
||||||
|
|
||||||
|
async def get_db(request: Request):
|
||||||
|
# The Node backend executed each synchronous SQLite operation serially.
|
||||||
|
# Preserve that behavior for read/modify/write operations such as automatic numbering.
|
||||||
|
async with request.app.state.database_lock:
|
||||||
|
with request.app.state.sessions() as db:
|
||||||
|
yield db
|
||||||
|
|
||||||
|
|
||||||
|
DB = Annotated[Session, Depends(get_db)]
|
||||||
|
|
||||||
|
|
||||||
|
def require_admin(request: Request) -> None:
|
||||||
|
if not valid_token(request.cookies.get(COOKIE_NAME), request.app.state.settings):
|
||||||
|
raise AppError(401, "É necessário iniciar sessão para aceder à administração.")
|
||||||
|
|
||||||
|
|
||||||
|
def changed(db: Session, request: Request) -> None:
|
||||||
|
db.commit()
|
||||||
|
request.app.state.events.broadcast()
|
||||||
|
|
||||||
|
|
||||||
|
def confirm(value: bool, message: str) -> None:
|
||||||
|
if not value:
|
||||||
|
raise AppError(409, message)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
from fastapi import APIRouter, Request
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
|
|
||||||
|
from ..services.state import get_public_state
|
||||||
|
from .dependencies import DB
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/public")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/state")
|
||||||
|
@router.head("/state", include_in_schema=False)
|
||||||
|
def state(db: DB):
|
||||||
|
return get_public_state(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/events")
|
||||||
|
@router.head("/events", include_in_schema=False)
|
||||||
|
async def events(request: Request):
|
||||||
|
return StreamingResponse(request.app.state.events.stream(), media_type="text/event-stream",
|
||||||
|
headers={"Cache-Control": "no-cache, no-transform", "Connection": "keep-alive", "X-Accel-Buffering": "no"})
|
||||||
Whitespace-only changes.
@@ -0,0 +1,64 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, StringConstraints
|
||||||
|
from pydantic.alias_generators import to_camel
|
||||||
|
|
||||||
|
MAX_SAFE_INTEGER = 9007199254740991
|
||||||
|
|
||||||
|
|
||||||
|
class Schema(BaseModel):
|
||||||
|
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra="ignore")
|
||||||
|
|
||||||
|
|
||||||
|
class RequestSchema(Schema):
|
||||||
|
model_config = ConfigDict(populate_by_name=False, validate_by_name=False, validate_by_alias=True)
|
||||||
|
|
||||||
|
|
||||||
|
def number(value):
|
||||||
|
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||||
|
raise ValueError("Expected a JSON number")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def identifier(value):
|
||||||
|
# Zod's coerce.number() is used for URL IDs and team group IDs in the legacy app.
|
||||||
|
try:
|
||||||
|
if isinstance(value, str):
|
||||||
|
value = value.strip()
|
||||||
|
if value.lower().startswith(("0x", "0b", "0o")):
|
||||||
|
return int(value, 0)
|
||||||
|
return float(value or "0")
|
||||||
|
return int(value) if isinstance(value, bool) else value
|
||||||
|
except (ValueError, OverflowError):
|
||||||
|
raise ValueError("Invalid identifier") from None
|
||||||
|
|
||||||
|
|
||||||
|
PositiveInt = Annotated[int, BeforeValidator(number), Field(ge=1, le=MAX_SAFE_INTEGER)]
|
||||||
|
PositiveId = Annotated[int, BeforeValidator(identifier), Field(ge=1, le=MAX_SAFE_INTEGER)]
|
||||||
|
Score = Annotated[int, BeforeValidator(number), Field(ge=0, le=MAX_SAFE_INTEGER)]
|
||||||
|
JS_WHITESPACE = "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
|
||||||
|
|
||||||
|
|
||||||
|
def name(value):
|
||||||
|
if not isinstance(value, str):
|
||||||
|
raise ValueError("Expected a string")
|
||||||
|
value = value.strip(JS_WHITESPACE)
|
||||||
|
if not 1 <= len(value.encode("utf-16-le", errors="surrogatepass")) // 2 <= 200:
|
||||||
|
raise ValueError("Invalid name length")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
Name = Annotated[str, BeforeValidator(name), StringConstraints(strict=True, min_length=1, max_length=200)]
|
||||||
|
|
||||||
|
|
||||||
|
def confirmed(value):
|
||||||
|
if value is not True:
|
||||||
|
raise ValueError("Confirmation must be true")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
Confirmed = Annotated[bool, BeforeValidator(confirmed)]
|
||||||
|
|
||||||
|
|
||||||
|
class Confirmation(RequestSchema):
|
||||||
|
confirm: Confirmed = False
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
from typing import Annotated, Literal
|
||||||
|
|
||||||
|
from pydantic import BeforeValidator, Field
|
||||||
|
|
||||||
|
from .base import Confirmed, PositiveId, RequestSchema, Schema, Score, number
|
||||||
|
from .teams import Group, TeamSummary
|
||||||
|
|
||||||
|
Legs = Annotated[Literal[1, 2], BeforeValidator(number)]
|
||||||
|
|
||||||
|
|
||||||
|
class GenerationTeam(RequestSchema):
|
||||||
|
team_id: PositiveId
|
||||||
|
group_id: PositiveId
|
||||||
|
|
||||||
|
|
||||||
|
class Generation(RequestSchema):
|
||||||
|
legs: Legs
|
||||||
|
team_order: list[GenerationTeam]
|
||||||
|
|
||||||
|
|
||||||
|
class GenerationInput(RequestSchema):
|
||||||
|
generation: Generation
|
||||||
|
confirm_replace: Confirmed = False
|
||||||
|
|
||||||
|
|
||||||
|
class PreviewInput(RequestSchema):
|
||||||
|
legs: Legs
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarMatch(Schema):
|
||||||
|
game_number: int
|
||||||
|
round_number: int
|
||||||
|
group: Group | None
|
||||||
|
team_a: TeamSummary
|
||||||
|
team_b: TeamSummary
|
||||||
|
|
||||||
|
|
||||||
|
class LeagueMatch(CalendarMatch):
|
||||||
|
id: int
|
||||||
|
counts_toward_standings: bool
|
||||||
|
score_a: int | None
|
||||||
|
score_b: int | None
|
||||||
|
|
||||||
|
|
||||||
|
class ResultInput(RequestSchema):
|
||||||
|
score_a: Score
|
||||||
|
score_b: Score
|
||||||
|
|
||||||
|
|
||||||
|
class StandingsInput(RequestSchema):
|
||||||
|
counts_toward_standings: Annotated[bool, Field(strict=True)]
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
from typing import Annotated, Literal
|
||||||
|
|
||||||
|
from pydantic import Field
|
||||||
|
|
||||||
|
from .base import Confirmed, PositiveInt, RequestSchema, Schema
|
||||||
|
from .teams import TeamSummary
|
||||||
|
|
||||||
|
|
||||||
|
class Participant(Schema):
|
||||||
|
team: TeamSummary | None
|
||||||
|
pending: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class BracketMatch(Schema):
|
||||||
|
match_index: int
|
||||||
|
team_a: Participant
|
||||||
|
team_b: Participant
|
||||||
|
score_a: int | None = None
|
||||||
|
score_b: int | None = None
|
||||||
|
winner: TeamSummary | None = None
|
||||||
|
is_bye: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class BracketRound(Schema):
|
||||||
|
round_index: int
|
||||||
|
name: str
|
||||||
|
matches: list[BracketMatch]
|
||||||
|
|
||||||
|
|
||||||
|
class FinalStage(Schema):
|
||||||
|
round_count: int | None
|
||||||
|
third_place_enabled: bool = False
|
||||||
|
rounds: list[BracketRound] = Field(default_factory=list)
|
||||||
|
third_place_match: BracketMatch | None = None
|
||||||
|
champion: TeamSummary | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigInput(RequestSchema):
|
||||||
|
round_count: Annotated[PositiveInt, Field(le=8)]
|
||||||
|
third_place_enabled: Annotated[bool, Field(strict=True)] = False
|
||||||
|
confirm_clear_results: Confirmed = False
|
||||||
|
|
||||||
|
|
||||||
|
class Seed(Schema):
|
||||||
|
slot_index: PositiveInt
|
||||||
|
team_id: PositiveInt | None
|
||||||
|
|
||||||
|
|
||||||
|
class SeedInput(Seed, RequestSchema):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class SeedsInput(RequestSchema):
|
||||||
|
seeds: list[SeedInput]
|
||||||
|
confirm_clear_results: Confirmed = False
|
||||||
|
|
||||||
|
|
||||||
|
class PerGroupInput(RequestSchema):
|
||||||
|
mode: Literal["per-group"]
|
||||||
|
qualifiers_per_group: PositiveInt
|
||||||
|
|
||||||
|
|
||||||
|
class OverallInput(RequestSchema):
|
||||||
|
mode: Literal["overall"]
|
||||||
|
qualifier_count: PositiveInt
|
||||||
|
|
||||||
|
|
||||||
|
class QualifiedTeam(Schema):
|
||||||
|
seed_number: int
|
||||||
|
group_position: int
|
||||||
|
team: TeamSummary
|
||||||
|
|
||||||
|
|
||||||
|
class SeedPreview(Schema):
|
||||||
|
mode: Literal["per-group", "overall"]
|
||||||
|
qualifiers_per_group: int | None
|
||||||
|
qualifier_count: int
|
||||||
|
qualifiers: list[QualifiedTeam]
|
||||||
|
seeds: list[Seed]
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from typing import Annotated, Literal
|
||||||
|
|
||||||
|
from pydantic import BeforeValidator, ConfigDict, Field
|
||||||
|
|
||||||
|
from .base import Name, RequestSchema, Schema, number
|
||||||
|
|
||||||
|
ClassificationMode = Literal["standard", "total-points"]
|
||||||
|
DisplayPanel = Literal["next-match", "latest-results", "classification"]
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsInput(RequestSchema):
|
||||||
|
name: Name
|
||||||
|
classification_mode: ClassificationMode
|
||||||
|
|
||||||
|
|
||||||
|
class TournamentSettings(Schema):
|
||||||
|
name: str
|
||||||
|
classification_mode: ClassificationMode
|
||||||
|
final_round_count: int | None
|
||||||
|
third_place_enabled: bool
|
||||||
|
|
||||||
|
|
||||||
|
class DisplaySettings(Schema):
|
||||||
|
active_panel: DisplayPanel
|
||||||
|
zoom_percent: Annotated[int, BeforeValidator(number), Field(ge=50, le=400)]
|
||||||
|
|
||||||
|
|
||||||
|
class DisplayInput(DisplaySettings):
|
||||||
|
model_config = ConfigDict(populate_by_name=False, validate_by_name=False, validate_by_alias=True)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
from .base import Schema
|
||||||
|
from .calendar import LeagueMatch
|
||||||
|
from .final_stage import FinalStage
|
||||||
|
from .settings import DisplaySettings, TournamentSettings
|
||||||
|
from .teams import Group, TeamSummary
|
||||||
|
|
||||||
|
|
||||||
|
class ClassificationRow(Schema):
|
||||||
|
position: int = 0
|
||||||
|
team: TeamSummary
|
||||||
|
played: int = 0
|
||||||
|
wins: int = 0
|
||||||
|
draws: int = 0
|
||||||
|
losses: int = 0
|
||||||
|
goals_for: int = 0
|
||||||
|
goals_against: int = 0
|
||||||
|
goal_difference: int = 0
|
||||||
|
points: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
class GroupStanding(Schema):
|
||||||
|
group: Group
|
||||||
|
rows: list[ClassificationRow]
|
||||||
|
|
||||||
|
|
||||||
|
class PublicState(Schema):
|
||||||
|
tournament: TournamentSettings
|
||||||
|
display: DisplaySettings
|
||||||
|
groups: list[Group]
|
||||||
|
matches: list[LeagueMatch]
|
||||||
|
group_standings: list[GroupStanding]
|
||||||
|
final_stage: FinalStage
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
from pydantic import Field, field_validator
|
||||||
|
|
||||||
|
from .base import Name, PositiveId, PositiveInt, RequestSchema, Schema
|
||||||
|
|
||||||
|
|
||||||
|
class Group(Schema):
|
||||||
|
id: int
|
||||||
|
name: str
|
||||||
|
sort_order: int
|
||||||
|
|
||||||
|
|
||||||
|
class TeamSummary(Schema):
|
||||||
|
id: int
|
||||||
|
number: int
|
||||||
|
name: str
|
||||||
|
group: Group
|
||||||
|
|
||||||
|
|
||||||
|
class Player(Schema):
|
||||||
|
id: int
|
||||||
|
team_id: int
|
||||||
|
name: str
|
||||||
|
sort_order: int
|
||||||
|
|
||||||
|
|
||||||
|
class Team(TeamSummary):
|
||||||
|
players: list[Player] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class NameInput(RequestSchema):
|
||||||
|
name: Name
|
||||||
|
|
||||||
|
|
||||||
|
class TeamInput(NameInput):
|
||||||
|
number: PositiveInt
|
||||||
|
group_id: PositiveId
|
||||||
|
|
||||||
|
|
||||||
|
class TeamCreate(NameInput):
|
||||||
|
number: PositiveInt | None = None
|
||||||
|
group_id: PositiveId
|
||||||
|
|
||||||
|
@field_validator("number", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def reject_explicit_null(cls, value):
|
||||||
|
if value is None:
|
||||||
|
raise ValueError("number must be omitted or positive")
|
||||||
|
return value
|
||||||
Whitespace-only changes.
@@ -0,0 +1,30 @@
|
|||||||
|
from threading import RLock
|
||||||
|
|
||||||
|
from .session import timestamp_ms
|
||||||
|
|
||||||
|
|
||||||
|
class LoginRateLimiter:
|
||||||
|
def __init__(self, maximum_failures: int = 5, window_ms: int = 15 * 60 * 1000):
|
||||||
|
self.maximum_failures = maximum_failures
|
||||||
|
self.window_ms = window_ms
|
||||||
|
self.attempts: dict[str, tuple[int, int]] = {}
|
||||||
|
self.lock = RLock()
|
||||||
|
|
||||||
|
def limited(self, key: str, now: int | None = None) -> bool:
|
||||||
|
now = timestamp_ms() if now is None else now
|
||||||
|
with self.lock:
|
||||||
|
for expired in [key for key, (_, reset) in self.attempts.items() if reset <= now]:
|
||||||
|
del self.attempts[expired]
|
||||||
|
return self.attempts.get(key, (0, 0))[0] >= self.maximum_failures
|
||||||
|
|
||||||
|
def failure(self, key: str, now: int | None = None) -> None:
|
||||||
|
now = timestamp_ms() if now is None else now
|
||||||
|
with self.lock:
|
||||||
|
count, reset = self.attempts.get(key, (0, now + self.window_ms))
|
||||||
|
if reset <= now:
|
||||||
|
count, reset = 0, now + self.window_ms
|
||||||
|
self.attempts[key] = (count + 1, reset)
|
||||||
|
|
||||||
|
def clear(self, key: str) -> None:
|
||||||
|
with self.lock:
|
||||||
|
self.attempts.pop(key, None)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import time
|
||||||
|
|
||||||
|
from ..config import Settings
|
||||||
|
|
||||||
|
COOKIE_NAME = "tournament_admin_session"
|
||||||
|
|
||||||
|
|
||||||
|
def timestamp_ms() -> int:
|
||||||
|
return int(time.time() * 1000)
|
||||||
|
|
||||||
|
|
||||||
|
def encode(data: bytes) -> str:
|
||||||
|
return base64.urlsafe_b64encode(data).decode().rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def sign(payload: str, secret: str) -> str:
|
||||||
|
return encode(hmac.new(secret.encode(), payload.encode(), hashlib.sha256).digest())
|
||||||
|
|
||||||
|
|
||||||
|
def create_token(settings: Settings, now: int | None = None) -> str:
|
||||||
|
expiry = (timestamp_ms() if now is None else now) + settings.session_lifetime_ms
|
||||||
|
payload = encode(json.dumps({"expiresAt": expiry}, separators=(",", ":")).encode())
|
||||||
|
return payload + "." + sign(payload, settings.session_secret)
|
||||||
|
|
||||||
|
|
||||||
|
def valid_token(token: str | None, settings: Settings, now: int | None = None) -> bool:
|
||||||
|
if not token or token.count(".") != 1:
|
||||||
|
return False
|
||||||
|
payload, signature = token.split(".")
|
||||||
|
if not payload or not hmac.compare_digest(signature.encode(), sign(payload, settings.session_secret).encode()):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
value = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
|
||||||
|
expiry = value.get("expiresAt")
|
||||||
|
return type(expiry) in (int, float) and math.isfinite(expiry) and expiry > (timestamp_ms() if now is None else now)
|
||||||
|
except (ValueError, TypeError, AttributeError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def password_matches(actual: str, expected: str) -> bool:
|
||||||
|
return hmac.compare_digest(actual.encode(), expected.encode())
|
||||||
Whitespace-only changes.
@@ -0,0 +1,70 @@
|
|||||||
|
from ..schemas.final_stage import BracketMatch, BracketRound, FinalStage, Participant
|
||||||
|
from ..schemas.teams import TeamSummary
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_bracket(round_count: int | None, seeds: dict[int, TeamSummary | None],
|
||||||
|
results: dict[tuple[int, int], tuple[int | None, int | None]],
|
||||||
|
third_place_enabled: bool = False) -> FinalStage:
|
||||||
|
if round_count is None:
|
||||||
|
return FinalStage(round_count=None)
|
||||||
|
if type(round_count) is not int or not 1 <= round_count <= 8:
|
||||||
|
raise ValueError("O número de rondas tem de estar entre 1 e 8.")
|
||||||
|
rounds = []
|
||||||
|
can_produce = {}
|
||||||
|
for index in range(1, round_count + 1):
|
||||||
|
matches = []
|
||||||
|
for number in range(1, 2 ** (round_count - index) + 1):
|
||||||
|
if index == 1:
|
||||||
|
a, b = Participant(team=seeds.get(number * 2 - 1)), Participant(team=seeds.get(number * 2))
|
||||||
|
else:
|
||||||
|
previous = rounds[-1].matches
|
||||||
|
a = Participant(team=previous[number * 2 - 2].winner,
|
||||||
|
pending=previous[number * 2 - 2].winner is None and can_produce[index - 1, number * 2 - 1])
|
||||||
|
b = Participant(team=previous[number * 2 - 1].winner,
|
||||||
|
pending=previous[number * 2 - 1].winner is None and can_produce[index - 1, number * 2])
|
||||||
|
both = a.team is not None and b.team is not None
|
||||||
|
bye = not a.pending and not b.pending and ((a.team is None) != (b.team is None))
|
||||||
|
empty = not a.pending and not b.pending and a.team is None and b.team is None
|
||||||
|
score_a, score_b = results.get((index, number), (None, None)) if both else (None, None)
|
||||||
|
winner = a.team or b.team if bye else None
|
||||||
|
if both and score_a is not None and score_b is not None and score_a != score_b:
|
||||||
|
winner = a.team if score_a > score_b else b.team
|
||||||
|
match = BracketMatch(match_index=number, team_a=a, team_b=b, score_a=score_a,
|
||||||
|
score_b=score_b, winner=winner, is_bye=bye)
|
||||||
|
matches.append(match)
|
||||||
|
can_produce[index, number] = not empty and (winner is not None or a.pending or b.pending or both)
|
||||||
|
count = 2 ** (round_count - index + 1)
|
||||||
|
name = {2: "Final", 4: "Meias-finais", 8: "Quartos de final", 16: "Oitavos de final"}.get(count, f"Ronda de {count}")
|
||||||
|
rounds.append(BracketRound(round_index=index, name=name, matches=matches))
|
||||||
|
third = None
|
||||||
|
if third_place_enabled and round_count >= 2:
|
||||||
|
def loser(match):
|
||||||
|
if match.team_a.pending or match.team_b.pending:
|
||||||
|
return Participant(team=None, pending=True)
|
||||||
|
if match.team_a.team is None or match.team_b.team is None or match.winner is None:
|
||||||
|
return Participant(team=None, pending=match.team_a.team is not None and match.team_b.team is not None)
|
||||||
|
return Participant(team=match.team_b.team if match.winner.id == match.team_a.team.id else match.team_a.team)
|
||||||
|
a, b = [loser(match) for match in rounds[-2].matches]
|
||||||
|
score_a, score_b = results.get((round_count, 2), (None, None)) if a.team is not None and b.team is not None else (None, None)
|
||||||
|
winner = None
|
||||||
|
if score_a is not None and score_b is not None and score_a != score_b:
|
||||||
|
winner = a.team if score_a > score_b else b.team
|
||||||
|
third = BracketMatch(match_index=2, team_a=a, team_b=b, score_a=score_a, score_b=score_b, winner=winner)
|
||||||
|
return FinalStage(round_count=round_count, third_place_enabled=third_place_enabled,
|
||||||
|
rounds=rounds, third_place_match=third, champion=rounds[-1].matches[0].winner)
|
||||||
|
|
||||||
|
|
||||||
|
def get_bracket_match(stage: FinalStage, round_index: int, match_index: int) -> BracketMatch | None:
|
||||||
|
if stage.third_place_match is not None and round_index == stage.round_count and match_index == 2:
|
||||||
|
return stage.third_place_match
|
||||||
|
if 1 <= round_index <= len(stage.rounds) and 1 <= match_index <= len(stage.rounds[round_index - 1].matches):
|
||||||
|
return stage.rounds[round_index - 1].matches[match_index - 1]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def downstream_matches(round_count: int, round_index: int, match_index: int) -> list[tuple[int, int]]:
|
||||||
|
downstream = []
|
||||||
|
for index in range(round_index + 1, round_count + 1):
|
||||||
|
match_index = (match_index + 1) // 2
|
||||||
|
downstream.append((index, match_index))
|
||||||
|
return downstream
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
from ..schemas.calendar import CalendarMatch
|
||||||
|
from ..schemas.teams import TeamSummary
|
||||||
|
|
||||||
|
|
||||||
|
def group_rounds(teams: list[TeamSummary]) -> list[list[tuple[TeamSummary, TeamSummary]]]:
|
||||||
|
if len(teams) < 2:
|
||||||
|
return []
|
||||||
|
rotation = list(teams)
|
||||||
|
if len(rotation) % 2:
|
||||||
|
rotation.append(None)
|
||||||
|
rounds = []
|
||||||
|
for round_index in range(len(rotation) - 1):
|
||||||
|
pairs = []
|
||||||
|
for index in range(len(rotation) // 2):
|
||||||
|
a, b = rotation[index], rotation[-index - 1]
|
||||||
|
if a is not None and b is not None:
|
||||||
|
pairs.append((b, a) if round_index % 2 and index == 0 else (a, b))
|
||||||
|
rounds.append(pairs)
|
||||||
|
rotation.insert(1, rotation.pop())
|
||||||
|
return rounds
|
||||||
|
|
||||||
|
|
||||||
|
def generate_calendar(teams: list[TeamSummary], legs: int) -> list[CalendarMatch]:
|
||||||
|
if type(legs) is not int or legs not in (1, 2):
|
||||||
|
raise ValueError("O número de voltas tem de ser 1 ou 2.")
|
||||||
|
groups = {team.group.id: team.group for team in teams}
|
||||||
|
rounds = [(group, group_rounds([team for team in teams if team.group.id == group.id]))
|
||||||
|
for group in sorted(groups.values(), key=lambda group: (group.sort_order, group.id))]
|
||||||
|
round_count = max((len(items) for _, items in rounds), default=0)
|
||||||
|
matches = []
|
||||||
|
for index in range(round_count):
|
||||||
|
for group, items in rounds:
|
||||||
|
for a, b in items[index] if index < len(items) else []:
|
||||||
|
matches.append(CalendarMatch(game_number=len(matches) + 1, round_number=index + 1,
|
||||||
|
group=group, team_a=a, team_b=b))
|
||||||
|
if legs == 2:
|
||||||
|
matches += [CalendarMatch(game_number=len(matches) + index + 1,
|
||||||
|
round_number=match.round_number + round_count,
|
||||||
|
group=match.group, team_a=match.team_b, team_b=match.team_a)
|
||||||
|
for index, match in enumerate(matches)]
|
||||||
|
return matches
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
from random import SystemRandom
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from .. import models as m
|
||||||
|
from ..errors import AppError
|
||||||
|
from ..schemas.calendar import Generation, GenerationInput, GenerationTeam
|
||||||
|
from .calendar import generate_calendar
|
||||||
|
from .state import get_groups, get_matches, get_teams
|
||||||
|
|
||||||
|
|
||||||
|
def summary(matches):
|
||||||
|
return {"matches": matches, "matchCount": len(matches), "roundCount": max((match.round_number for match in matches), default=0)}
|
||||||
|
|
||||||
|
|
||||||
|
def ordered_teams(db: Session, generation: Generation):
|
||||||
|
teams = get_teams(db)
|
||||||
|
if len(generation.team_order) != len(teams):
|
||||||
|
raise AppError(409, "As equipas foram alteradas. Sorteie novamente o calendário.")
|
||||||
|
by_id, seen, ordered = {team.id: team for team in teams}, set(), []
|
||||||
|
for entry in generation.team_order:
|
||||||
|
team = by_id.get(entry.team_id)
|
||||||
|
if team is None or team.group.id != entry.group_id or entry.team_id in seen:
|
||||||
|
raise AppError(409, "As equipas ou os grupos foram alterados. Sorteie novamente o calendário.")
|
||||||
|
seen.add(entry.team_id)
|
||||||
|
ordered.append(team)
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
|
def matches_for_generation(db: Session, generation: Generation):
|
||||||
|
matches = generate_calendar(ordered_teams(db, generation), generation.legs)
|
||||||
|
if not matches:
|
||||||
|
raise AppError(409, "São necessárias pelo menos duas equipas no mesmo grupo para gerar o calendário.")
|
||||||
|
return matches
|
||||||
|
|
||||||
|
|
||||||
|
def generate_preview(db: Session, legs: int):
|
||||||
|
teams = get_teams(db)
|
||||||
|
order = []
|
||||||
|
for group in get_groups(db):
|
||||||
|
members = [team for team in teams if team.group.id == group.id]
|
||||||
|
SystemRandom().shuffle(members)
|
||||||
|
order += [GenerationTeam.model_validate({"teamId": team.id, "groupId": group.id}) for team in members]
|
||||||
|
generation = Generation.model_validate({"legs": legs, "teamOrder": order})
|
||||||
|
return {"generation": generation, **summary(matches_for_generation(db, generation))}
|
||||||
|
|
||||||
|
|
||||||
|
def save_calendar(db: Session, body: GenerationInput):
|
||||||
|
matches = matches_for_generation(db, body.generation)
|
||||||
|
has_scores = db.scalar(select(m.LeagueMatch.id).where(m.LeagueMatch.score_a.is_not(None)).limit(1)) is not None
|
||||||
|
if has_scores and not body.confirm_replace:
|
||||||
|
raise AppError(409, "Já existem resultados registados. Confirme a substituição do calendário para eliminar esses resultados.")
|
||||||
|
clear_calendar(db)
|
||||||
|
for round_number in sorted({match.round_number for match in matches}):
|
||||||
|
db.add(m.LeagueRound(round_index=round_number))
|
||||||
|
for match in matches:
|
||||||
|
db.add(m.LeagueMatch(order_index=match.game_number, round_index=match.round_number,
|
||||||
|
team_a_id=match.team_a.id, team_b_id=match.team_b.id))
|
||||||
|
db.flush()
|
||||||
|
return summary(get_matches(db))
|
||||||
|
|
||||||
|
|
||||||
|
def clear_calendar(db: Session):
|
||||||
|
db.execute(delete(m.LeagueMatch))
|
||||||
|
db.execute(delete(m.LeagueRound))
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
from itertools import groupby
|
||||||
|
|
||||||
|
from ..schemas.calendar import LeagueMatch
|
||||||
|
from ..schemas.state import ClassificationRow
|
||||||
|
from ..schemas.teams import TeamSummary
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_classification(teams: list[TeamSummary], matches: list[LeagueMatch], mode: str = "standard") -> list[ClassificationRow]:
|
||||||
|
statistics = {team.id: ClassificationRow(team=team) for team in teams}
|
||||||
|
completed = [match for match in matches if match.score_a is not None and match.score_b is not None]
|
||||||
|
for match in completed:
|
||||||
|
a, b = statistics.get(match.team_a.id), statistics.get(match.team_b.id)
|
||||||
|
if a is None or b is None:
|
||||||
|
continue
|
||||||
|
a.played += 1
|
||||||
|
b.played += 1
|
||||||
|
a.goals_for += match.score_a
|
||||||
|
a.goals_against += match.score_b
|
||||||
|
b.goals_for += match.score_b
|
||||||
|
b.goals_against += match.score_a
|
||||||
|
if mode == "total-points":
|
||||||
|
a.points += match.score_a
|
||||||
|
b.points += match.score_b
|
||||||
|
if match.score_a > match.score_b:
|
||||||
|
a.wins += 1
|
||||||
|
b.losses += 1
|
||||||
|
if mode == "standard":
|
||||||
|
a.points += 3
|
||||||
|
elif match.score_b > match.score_a:
|
||||||
|
b.wins += 1
|
||||||
|
a.losses += 1
|
||||||
|
if mode == "standard":
|
||||||
|
b.points += 3
|
||||||
|
else:
|
||||||
|
a.draws += 1
|
||||||
|
b.draws += 1
|
||||||
|
if mode == "standard":
|
||||||
|
a.points += 1
|
||||||
|
b.points += 1
|
||||||
|
for row in statistics.values():
|
||||||
|
row.goal_difference = row.goals_for - row.goals_against
|
||||||
|
|
||||||
|
def primary(row):
|
||||||
|
return (-row.points,) if mode == "total-points" else (-row.points, -row.goal_difference, -row.goals_for)
|
||||||
|
|
||||||
|
ordered = []
|
||||||
|
for _, group in groupby(sorted(statistics.values(), key=primary), key=primary):
|
||||||
|
tied = list(group)
|
||||||
|
head = {row.team.id: [0, 0, 0] for row in tied}
|
||||||
|
for match in completed:
|
||||||
|
if match.team_a.id not in head or match.team_b.id not in head:
|
||||||
|
continue
|
||||||
|
a, b = head[match.team_a.id], head[match.team_b.id]
|
||||||
|
a[1] += match.score_a
|
||||||
|
a[2] += match.score_b
|
||||||
|
b[1] += match.score_b
|
||||||
|
b[2] += match.score_a
|
||||||
|
a[0] += 3 if match.score_a > match.score_b else 1 if match.score_a == match.score_b else 0
|
||||||
|
b[0] += 3 if match.score_b > match.score_a else 1 if match.score_a == match.score_b else 0
|
||||||
|
tied.sort(key=lambda row: (-head[row.team.id][0], -(head[row.team.id][1] - head[row.team.id][2]),
|
||||||
|
-head[row.team.id][1], row.team.number))
|
||||||
|
ordered.extend(tied)
|
||||||
|
for position, row in enumerate(ordered, 1):
|
||||||
|
row.position = position
|
||||||
|
return ordered
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
from sqlalchemy import delete, func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from .. import models as m
|
||||||
|
from ..errors import AppError
|
||||||
|
from ..schemas.final_stage import ConfigInput, OverallInput, PerGroupInput, SeedsInput
|
||||||
|
from .bracket import downstream_matches, get_bracket_match
|
||||||
|
from .seeding import group_qualification, overall_qualification
|
||||||
|
from .state import get_final_stage, get_public_state, get_settings
|
||||||
|
from .teams import existing_team
|
||||||
|
|
||||||
|
|
||||||
|
def configure(db: Session, body: ConfigInput) -> bool:
|
||||||
|
if body.third_place_enabled and body.round_count < 2:
|
||||||
|
raise AppError(400, "O jogo do 3.º lugar requer pelo menos duas rondas.")
|
||||||
|
current = get_settings(db)
|
||||||
|
changed = current.final_round_count != body.round_count or current.third_place_enabled != body.third_place_enabled
|
||||||
|
if changed and current.final_round_count is not None and not body.confirm_clear_results:
|
||||||
|
raise AppError(409, "Alterar a configuração elimina as equipas e os resultados da fase final. Confirme esta alteração.")
|
||||||
|
if changed:
|
||||||
|
row = db.get(m.TournamentSettings, 1)
|
||||||
|
row.final_round_count, row.third_place_enabled, row.updated_at = body.round_count, int(body.third_place_enabled), func.current_timestamp()
|
||||||
|
db.execute(delete(m.FinalSeed))
|
||||||
|
db.execute(delete(m.FinalResult))
|
||||||
|
db.flush()
|
||||||
|
return changed
|
||||||
|
|
||||||
|
|
||||||
|
def clear(db: Session):
|
||||||
|
row = db.get(m.TournamentSettings, 1)
|
||||||
|
row.final_round_count, row.third_place_enabled, row.updated_at = None, 0, func.current_timestamp()
|
||||||
|
db.execute(delete(m.FinalSeed))
|
||||||
|
db.execute(delete(m.FinalResult))
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def seed_preview(db: Session, body: PerGroupInput | OverallInput):
|
||||||
|
state = get_public_state(db)
|
||||||
|
if state.tournament.final_round_count is None:
|
||||||
|
raise AppError(409, "Configure primeiro o número de rondas da fase final.")
|
||||||
|
standings = [standing for standing in state.group_standings if standing.rows]
|
||||||
|
if not standings:
|
||||||
|
raise AppError(409, "Ainda não existem equipas classificadas para preencher a fase final.")
|
||||||
|
if not any(row.played > 0 for standing in standings for row in standing.rows):
|
||||||
|
raise AppError(409, "Ainda não existem resultados contabilizados na classificação.")
|
||||||
|
if any(match.counts_toward_standings and (match.score_a is None or match.score_b is None) for match in state.matches):
|
||||||
|
raise AppError(409, "Conclua primeiro todos os jogos que contam para a classificação.")
|
||||||
|
slots = 2 ** state.tournament.final_round_count
|
||||||
|
if isinstance(body, PerGroupInput):
|
||||||
|
for standing in standings:
|
||||||
|
if len(standing.rows) < body.qualifiers_per_group:
|
||||||
|
raise AppError(400, f"{standing.group.name} não tem {body.qualifiers_per_group} equipas para apurar.")
|
||||||
|
if len(standings) * body.qualifiers_per_group > slots:
|
||||||
|
raise AppError(400, f"A fase final só tem {slots} lugares. Reduza o número de apurados por grupo.")
|
||||||
|
return group_qualification(standings, body.qualifiers_per_group, slots)
|
||||||
|
count = sum(len(standing.rows) for standing in standings)
|
||||||
|
if body.qualifier_count > slots:
|
||||||
|
raise AppError(400, f"A fase final só tem {slots} lugares. Reduza o número total de apurados.")
|
||||||
|
if body.qualifier_count > count:
|
||||||
|
raise AppError(400, f"Só existem {count} equipas classificadas.")
|
||||||
|
return overall_qualification(standings, body.qualifier_count, slots, state.tournament.classification_mode)
|
||||||
|
|
||||||
|
|
||||||
|
def save_seeds(db: Session, body: SeedsInput) -> bool:
|
||||||
|
settings = get_settings(db)
|
||||||
|
if settings.final_round_count is None:
|
||||||
|
raise AppError(409, "Configure primeiro o número de rondas da fase final.")
|
||||||
|
slots = 2 ** settings.final_round_count
|
||||||
|
if len(body.seeds) != slots or {seed.slot_index for seed in body.seeds} != set(range(1, slots + 1)):
|
||||||
|
raise AppError(400, f"Indique exatamente as {slots} posições iniciais da fase final.")
|
||||||
|
assigned = [seed.team_id for seed in body.seeds if seed.team_id is not None]
|
||||||
|
if len(set(assigned)) != len(assigned):
|
||||||
|
raise AppError(400, "A mesma equipa não pode ser atribuída a mais do que uma posição.")
|
||||||
|
for identifier in assigned:
|
||||||
|
existing_team(db, identifier)
|
||||||
|
current = {row.slot_index: row.team_id for row in db.scalars(select(m.FinalSeed))}
|
||||||
|
changed = len(current) != len(body.seeds) or any(current.get(seed.slot_index) != seed.team_id for seed in body.seeds)
|
||||||
|
if changed and db.scalar(select(m.FinalResult.round_index).limit(1)) is not None and not body.confirm_clear_results:
|
||||||
|
raise AppError(409, "Alterar as equipas iniciais elimina todos os resultados da fase final. Confirme esta alteração.")
|
||||||
|
if changed:
|
||||||
|
db.execute(delete(m.FinalSeed))
|
||||||
|
db.execute(delete(m.FinalResult))
|
||||||
|
db.add_all([m.FinalSeed(slot_index=seed.slot_index, team_id=seed.team_id) for seed in body.seeds])
|
||||||
|
db.flush()
|
||||||
|
return changed
|
||||||
|
|
||||||
|
|
||||||
|
def match_for_result(db: Session, round_index: int, match_index: int, require_teams: bool):
|
||||||
|
stage = get_final_stage(db)
|
||||||
|
if stage.round_count is None:
|
||||||
|
raise AppError(409, "A fase final ainda não está configurada.")
|
||||||
|
match = get_bracket_match(stage, round_index, match_index)
|
||||||
|
if match is None:
|
||||||
|
raise AppError(404, "O jogo da fase final não existe.")
|
||||||
|
if require_teams and (match.team_a.team is None or match.team_b.team is None or match.team_a.pending or match.team_b.pending):
|
||||||
|
raise AppError(409, "Só pode registar um resultado quando as duas equipas estiverem apuradas.")
|
||||||
|
return stage, match
|
||||||
|
|
||||||
|
|
||||||
|
def invalidate_results(db: Session, stage, round_index: int, match_index: int, previous_winner: int | None):
|
||||||
|
db.flush()
|
||||||
|
match = get_bracket_match(get_final_stage(db), round_index, match_index)
|
||||||
|
next_winner = match.winner.id if match.winner else None
|
||||||
|
if previous_winner == next_winner:
|
||||||
|
return
|
||||||
|
downstream = downstream_matches(stage.round_count, round_index, match_index)
|
||||||
|
if stage.third_place_enabled and round_index == stage.round_count - 1 and match_index <= 2:
|
||||||
|
downstream.append((stage.round_count, 2))
|
||||||
|
for index, number in downstream:
|
||||||
|
db.execute(delete(m.FinalResult).where(m.FinalResult.round_index == index, m.FinalResult.match_index == number))
|
||||||
|
|
||||||
|
|
||||||
|
def save_result(db: Session, round_index: int, match_index: int, score_a: int, score_b: int):
|
||||||
|
if score_a == score_b:
|
||||||
|
raise AppError(400, "Os jogos da fase final não podem terminar empatados.")
|
||||||
|
stage, match = match_for_result(db, round_index, match_index, True)
|
||||||
|
previous = match.winner.id if match.winner else None
|
||||||
|
row = db.get(m.FinalResult, (round_index, match_index))
|
||||||
|
if row is None:
|
||||||
|
row = m.FinalResult(round_index=round_index, match_index=match_index)
|
||||||
|
db.add(row)
|
||||||
|
row.score_a, row.score_b = score_a, score_b
|
||||||
|
invalidate_results(db, stage, round_index, match_index, previous)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_result(db: Session, round_index: int, match_index: int):
|
||||||
|
stage, match = match_for_result(db, round_index, match_index, False)
|
||||||
|
previous = match.winner.id if match.winner else None
|
||||||
|
db.execute(delete(m.FinalResult).where(m.FinalResult.round_index == round_index, m.FinalResult.match_index == match_index))
|
||||||
|
invalidate_results(db, stage, round_index, match_index, previous)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
from ..schemas.final_stage import QualifiedTeam, Seed, SeedPreview
|
||||||
|
from ..schemas.state import GroupStanding
|
||||||
|
|
||||||
|
|
||||||
|
def seed_order(slot_count: int) -> list[int]:
|
||||||
|
if type(slot_count) is not int or slot_count < 1 or slot_count & (slot_count - 1):
|
||||||
|
raise ValueError("O número de lugares da fase final tem de ser uma potência de dois.")
|
||||||
|
if slot_count == 1:
|
||||||
|
return [1]
|
||||||
|
order, size = [1, 2], 4
|
||||||
|
while size <= slot_count:
|
||||||
|
order = [value for seed in order for value in (seed, size + 1 - seed)]
|
||||||
|
size *= 2
|
||||||
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
def preview(qualifiers: list[QualifiedTeam], slot_count: int, mode: str, per_group: int | None) -> SeedPreview:
|
||||||
|
if len(qualifiers) > slot_count:
|
||||||
|
raise ValueError("Existem mais equipas apuradas do que lugares na fase final.")
|
||||||
|
by_seed = {item.seed_number: item.team.id for item in qualifiers}
|
||||||
|
return SeedPreview(mode=mode, qualifiers_per_group=per_group, qualifier_count=len(qualifiers),
|
||||||
|
qualifiers=qualifiers, seeds=[Seed(slot_index=index, team_id=by_seed.get(seed))
|
||||||
|
for index, seed in enumerate(seed_order(slot_count), 1)])
|
||||||
|
|
||||||
|
|
||||||
|
def group_qualification(standings: list[GroupStanding], per_group: int, slot_count: int) -> SeedPreview:
|
||||||
|
if type(per_group) is not int or per_group < 1:
|
||||||
|
raise ValueError("O número de apurados por grupo tem de ser positivo.")
|
||||||
|
standings = sorted((item for item in standings if item.rows), key=lambda item: (item.group.sort_order, item.group.id))
|
||||||
|
qualifiers = []
|
||||||
|
for position in range(1, per_group + 1):
|
||||||
|
for standing in standings:
|
||||||
|
if len(standing.rows) >= position:
|
||||||
|
qualifiers.append(QualifiedTeam(seed_number=len(qualifiers) + 1, group_position=position,
|
||||||
|
team=standing.rows[position - 1].team))
|
||||||
|
return preview(qualifiers, slot_count, "per-group", per_group)
|
||||||
|
|
||||||
|
|
||||||
|
def overall_qualification(standings: list[GroupStanding], count: int, slot_count: int, mode: str) -> SeedPreview:
|
||||||
|
if type(count) is not int or count < 1:
|
||||||
|
raise ValueError("O número total de apurados tem de ser positivo.")
|
||||||
|
def key(row):
|
||||||
|
return (-row.points, row.team.number) if mode == "total-points" else (-row.points, -row.goal_difference, -row.goals_for, row.team.number)
|
||||||
|
rows = sorted((row for standing in standings for row in standing.rows), key=key)
|
||||||
|
if count > len(rows):
|
||||||
|
raise ValueError("Não existem equipas suficientes para esse número de apurados.")
|
||||||
|
qualifiers = [QualifiedTeam(seed_number=index, group_position=row.position, team=row.team)
|
||||||
|
for index, row in enumerate(rows[:count], 1)]
|
||||||
|
return preview(qualifiers, slot_count, "overall", None)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from .. import models as m
|
||||||
|
from ..schemas.calendar import LeagueMatch
|
||||||
|
from ..schemas.settings import DisplaySettings, TournamentSettings
|
||||||
|
from ..schemas.state import GroupStanding, PublicState
|
||||||
|
from ..schemas.teams import Group, Player, Team, TeamSummary
|
||||||
|
from .bracket import calculate_bracket
|
||||||
|
from .classification import calculate_classification
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings(db: Session) -> TournamentSettings:
|
||||||
|
row = db.get(m.TournamentSettings, 1)
|
||||||
|
if row is None:
|
||||||
|
raise RuntimeError("As definições do torneio não foram inicializadas.")
|
||||||
|
return TournamentSettings(name=row.name, classification_mode=row.classification_mode,
|
||||||
|
final_round_count=row.final_round_count, third_place_enabled=bool(row.third_place_enabled))
|
||||||
|
|
||||||
|
|
||||||
|
def get_display(db: Session) -> DisplaySettings:
|
||||||
|
row = db.get(m.DisplaySettings, 1)
|
||||||
|
if row is None:
|
||||||
|
raise RuntimeError("As definições do ecrã não foram inicializadas.")
|
||||||
|
return DisplaySettings(active_panel=row.active_panel if row.active_panel in ("next-match", "latest-results", "classification") else "latest-results",
|
||||||
|
zoom_percent=row.zoom_percent if type(row.zoom_percent) is int and 50 <= row.zoom_percent <= 400 else 100)
|
||||||
|
|
||||||
|
|
||||||
|
def group_from_row(row: m.Group) -> Group:
|
||||||
|
return Group(id=row.id, name=row.name, sort_order=row.sort_order)
|
||||||
|
|
||||||
|
|
||||||
|
def get_groups(db: Session) -> list[Group]:
|
||||||
|
return [group_from_row(row) for row in db.scalars(select(m.Group).order_by(m.Group.sort_order, m.Group.id))]
|
||||||
|
|
||||||
|
|
||||||
|
def get_teams(db: Session) -> list[TeamSummary]:
|
||||||
|
return [TeamSummary(id=team.id, number=team.number, name=team.name, group=group_from_row(group))
|
||||||
|
for team, group in db.execute(select(m.Team, m.Group).join(m.Group, m.Team.group_id == m.Group.id).order_by(m.Team.number))]
|
||||||
|
|
||||||
|
|
||||||
|
def player_from_row(row: m.Player) -> Player:
|
||||||
|
return Player(id=row.id, team_id=row.team_id, name=row.name, sort_order=row.sort_order)
|
||||||
|
|
||||||
|
|
||||||
|
def get_admin_teams(db: Session) -> list[Team]:
|
||||||
|
teams = [Team(**team.model_dump()) for team in get_teams(db)]
|
||||||
|
by_id = {team.id: team for team in teams}
|
||||||
|
for player in db.scalars(select(m.Player).order_by(m.Player.team_id, m.Player.sort_order, m.Player.id)):
|
||||||
|
if player.team_id in by_id:
|
||||||
|
by_id[player.team_id].players.append(player_from_row(player))
|
||||||
|
return teams
|
||||||
|
|
||||||
|
|
||||||
|
def get_matches(db: Session) -> list[LeagueMatch]:
|
||||||
|
teams = {team.id: team for team in get_teams(db)}
|
||||||
|
result = []
|
||||||
|
for row, round_row in db.execute(select(m.LeagueMatch, m.LeagueRound).join(m.LeagueRound, m.LeagueRound.round_index == m.LeagueMatch.round_index).order_by(m.LeagueMatch.order_index)):
|
||||||
|
a, b = teams[row.team_a_id], teams[row.team_b_id]
|
||||||
|
result.append(LeagueMatch(id=row.id, game_number=row.order_index, round_number=row.round_index,
|
||||||
|
counts_toward_standings=bool(round_row.counts_toward_standings),
|
||||||
|
group=a.group if a.group.id == b.group.id else None,
|
||||||
|
team_a=a, team_b=b, score_a=row.score_a, score_b=row.score_b))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def get_final_stage(db: Session):
|
||||||
|
settings = get_settings(db)
|
||||||
|
teams = {team.id: team for team in get_teams(db)}
|
||||||
|
seeds = {row.slot_index: teams.get(row.team_id) for row in db.scalars(select(m.FinalSeed))}
|
||||||
|
results = {(row.round_index, row.match_index): (row.score_a, row.score_b) for row in db.scalars(select(m.FinalResult))}
|
||||||
|
return calculate_bracket(settings.final_round_count, seeds, results, settings.third_place_enabled)
|
||||||
|
|
||||||
|
|
||||||
|
def get_public_state(db: Session) -> PublicState:
|
||||||
|
settings, groups, teams, matches = get_settings(db), get_groups(db), get_teams(db), get_matches(db)
|
||||||
|
standings = [GroupStanding(group=group, rows=calculate_classification(
|
||||||
|
[team for team in teams if team.group.id == group.id],
|
||||||
|
[match for match in matches if match.counts_toward_standings and match.team_a.group.id == group.id and match.team_b.group.id == group.id],
|
||||||
|
settings.classification_mode)) for group in groups]
|
||||||
|
return PublicState(tournament=settings, display=get_display(db), groups=groups, matches=matches,
|
||||||
|
group_standings=standings, final_stage=get_final_stage(db))
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
from random import SystemRandom
|
||||||
|
|
||||||
|
from sqlalchemy import delete, func, or_, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from .. import models as m
|
||||||
|
from ..errors import AppError
|
||||||
|
from ..schemas.base import MAX_SAFE_INTEGER
|
||||||
|
from ..schemas.teams import TeamCreate, TeamInput
|
||||||
|
from .state import get_admin_teams, get_groups, group_from_row
|
||||||
|
|
||||||
|
|
||||||
|
def existing_group(db: Session, identifier: int):
|
||||||
|
row = db.get(m.Group, identifier)
|
||||||
|
if row is None:
|
||||||
|
raise AppError(404, "O grupo não existe.")
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def existing_team(db: Session, identifier: int):
|
||||||
|
row = db.get(m.Team, identifier)
|
||||||
|
if row is None:
|
||||||
|
raise AppError(404, "A equipa não existe.")
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def available_group_name(db: Session, name: str, except_id: int | None = None):
|
||||||
|
query = select(m.Group).where(m.Group.name == name)
|
||||||
|
if except_id is not None:
|
||||||
|
query = query.where(m.Group.id != except_id)
|
||||||
|
if db.scalar(query) is not None:
|
||||||
|
raise AppError(409, "Já existe um grupo com esse nome.")
|
||||||
|
|
||||||
|
|
||||||
|
def create_group(db: Session, name: str):
|
||||||
|
available_group_name(db, name)
|
||||||
|
order = db.scalar(select(func.max(m.Group.sort_order)))
|
||||||
|
row = m.Group(name=name, sort_order=0 if order is None else order + 1)
|
||||||
|
db.add(row)
|
||||||
|
db.flush()
|
||||||
|
return group_from_row(row)
|
||||||
|
|
||||||
|
|
||||||
|
def update_group(db: Session, identifier: int, name: str):
|
||||||
|
row = existing_group(db, identifier)
|
||||||
|
available_group_name(db, name, identifier)
|
||||||
|
row.name, row.updated_at = name, func.current_timestamp()
|
||||||
|
db.flush()
|
||||||
|
return group_from_row(row)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_group(db: Session, identifier: int):
|
||||||
|
row = existing_group(db, identifier)
|
||||||
|
if db.scalar(select(m.Team.id).where(m.Team.group_id == identifier).limit(1)) is not None:
|
||||||
|
raise AppError(409, "Não é possível eliminar um grupo com equipas.")
|
||||||
|
if db.scalar(select(func.count()).select_from(m.Group)) <= 1:
|
||||||
|
raise AppError(409, "Não é possível eliminar o último grupo.")
|
||||||
|
db.delete(row)
|
||||||
|
|
||||||
|
|
||||||
|
def used_in_calendar(db: Session, identifier: int) -> bool:
|
||||||
|
return db.scalar(select(m.LeagueMatch.id).where(or_(m.LeagueMatch.team_a_id == identifier,
|
||||||
|
m.LeagueMatch.team_b_id == identifier)).limit(1)) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def create_team(db: Session, body: TeamCreate):
|
||||||
|
existing_group(db, body.group_id)
|
||||||
|
number = body.number
|
||||||
|
if number is None:
|
||||||
|
maximum = db.scalar(select(func.max(m.Team.number))) or 0
|
||||||
|
if maximum >= MAX_SAFE_INTEGER:
|
||||||
|
raise AppError(409, "Não é possível atribuir outro número de equipa.")
|
||||||
|
number = maximum + 1
|
||||||
|
row = m.Team(number=number, name=body.name, group_id=body.group_id)
|
||||||
|
db.add(row)
|
||||||
|
db.flush()
|
||||||
|
return next(team for team in get_admin_teams(db) if team.id == row.id)
|
||||||
|
|
||||||
|
|
||||||
|
def update_team(db: Session, identifier: int, body: TeamInput):
|
||||||
|
row = existing_team(db, identifier)
|
||||||
|
existing_group(db, body.group_id)
|
||||||
|
if row.group_id != body.group_id and used_in_calendar(db, identifier):
|
||||||
|
raise AppError(409, "Não é possível alterar o grupo de uma equipa utilizada no calendário. Limpe ou substitua o calendário primeiro.")
|
||||||
|
row.number, row.name, row.group_id, row.updated_at = body.number, body.name, body.group_id, func.current_timestamp()
|
||||||
|
db.flush()
|
||||||
|
return next(team for team in get_admin_teams(db) if team.id == identifier)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_team(db: Session, identifier: int):
|
||||||
|
row = existing_team(db, identifier)
|
||||||
|
if used_in_calendar(db, identifier):
|
||||||
|
raise AppError(409, "Não é possível eliminar esta equipa porque está a ser utilizada no calendário.")
|
||||||
|
if db.scalar(select(m.FinalSeed.slot_index).where(m.FinalSeed.team_id == identifier).limit(1)) is not None:
|
||||||
|
raise AppError(409, "Não é possível eliminar esta equipa porque está a ser utilizada na fase final.")
|
||||||
|
db.delete(row)
|
||||||
|
|
||||||
|
|
||||||
|
def randomize_teams(db: Session):
|
||||||
|
teams = list(db.scalars(select(m.Team).order_by(m.Team.number)))
|
||||||
|
groups = get_groups(db)
|
||||||
|
has_calendar = db.scalar(select(m.LeagueMatch.id).limit(1)) is not None
|
||||||
|
if has_calendar:
|
||||||
|
db.execute(delete(m.LeagueMatch))
|
||||||
|
db.execute(delete(m.LeagueRound))
|
||||||
|
maximum = max((row.number for row in teams), default=0)
|
||||||
|
numbers, shuffled_groups = [row.number for row in teams], list(groups)
|
||||||
|
SystemRandom().shuffle(numbers)
|
||||||
|
SystemRandom().shuffle(shuffled_groups)
|
||||||
|
for index, row in enumerate(teams, 1):
|
||||||
|
row.number = maximum + index
|
||||||
|
db.flush()
|
||||||
|
for index, row in enumerate(teams):
|
||||||
|
row.number, row.group_id, row.updated_at = numbers[index], shuffled_groups[index % len(groups)].id, func.current_timestamp()
|
||||||
|
db.flush()
|
||||||
|
return {"teams": get_admin_teams(db), "calendarCleared": has_calendar}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
from alembic import context
|
||||||
|
from sqlalchemy import engine_from_config, pool
|
||||||
|
|
||||||
|
from app.models import Base
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
|
||||||
|
def migrate(connection):
|
||||||
|
context.configure(connection=connection, target_metadata=Base.metadata)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
context.configure(url=config.get_main_option("sqlalchemy.url"), target_metadata=Base.metadata,
|
||||||
|
literal_binds=True, dialect_opts={"paramstyle": "named"})
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
elif config.attributes.get("connection") is not None:
|
||||||
|
migrate(config.attributes["connection"])
|
||||||
|
else:
|
||||||
|
from app.config import Settings
|
||||||
|
from app.database import create_database_engine
|
||||||
|
engine = create_database_engine(Settings().database_path)
|
||||||
|
with engine.connect() as connection:
|
||||||
|
migrate(connection)
|
||||||
|
engine.dispose()
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""Exact baseline of the Node SQLite schema; adopted databases are stamped only."""
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0001_baseline"
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
# Frozen SQL belongs to this migration, never application startup or runtime models.
|
||||||
|
SCHEMA = """
|
||||||
|
CREATE TABLE tournament_settings (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
name TEXT NOT NULL CHECK (length(trim(name)) > 0),
|
||||||
|
final_round_count INTEGER CHECK (final_round_count IS NULL OR (final_round_count BETWEEN 1 AND 8)),
|
||||||
|
created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||||
|
third_place_enabled INTEGER NOT NULL DEFAULT 0 CHECK (third_place_enabled IN (0, 1)),
|
||||||
|
classification_mode TEXT NOT NULL DEFAULT 'standard' CHECK (classification_mode IN ('standard', 'total-points'))
|
||||||
|
);
|
||||||
|
CREATE TABLE display_settings (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
active_panel TEXT NOT NULL CHECK (length(trim(active_panel)) > 0),
|
||||||
|
zoom_percent INTEGER NOT NULL DEFAULT 100 CHECK (zoom_percent BETWEEN 50 AND 400),
|
||||||
|
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE league_groups (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL COLLATE NOCASE UNIQUE CHECK (length(trim(name)) > 0),
|
||||||
|
sort_order INTEGER NOT NULL UNIQUE CHECK (sort_order >= 0),
|
||||||
|
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE teams (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
number INTEGER NOT NULL UNIQUE CHECK (number > 0),
|
||||||
|
name TEXT NOT NULL CHECK (length(trim(name)) > 0),
|
||||||
|
group_id INTEGER NOT NULL REFERENCES league_groups(id),
|
||||||
|
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE players (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
team_id INTEGER NOT NULL,
|
||||||
|
name TEXT NOT NULL CHECK (length(trim(name)) > 0),
|
||||||
|
sort_order INTEGER NOT NULL CHECK (sort_order >= 0),
|
||||||
|
FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE TABLE league_matches (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
order_index INTEGER NOT NULL UNIQUE CHECK (order_index >= 1),
|
||||||
|
round_index INTEGER NOT NULL CHECK (round_index >= 1),
|
||||||
|
team_a_id INTEGER NOT NULL, team_b_id INTEGER NOT NULL, score_a INTEGER, score_b INTEGER,
|
||||||
|
CHECK (team_a_id <> team_b_id),
|
||||||
|
CHECK ((score_a IS NULL AND score_b IS NULL) OR (score_a IS NOT NULL AND score_b IS NOT NULL AND score_a >= 0 AND score_b >= 0)),
|
||||||
|
FOREIGN KEY (team_a_id) REFERENCES teams(id), FOREIGN KEY (team_b_id) REFERENCES teams(id)
|
||||||
|
);
|
||||||
|
CREATE TABLE final_seeds (
|
||||||
|
slot_index INTEGER PRIMARY KEY CHECK (slot_index >= 1),
|
||||||
|
team_id INTEGER, FOREIGN KEY (team_id) REFERENCES teams(id)
|
||||||
|
);
|
||||||
|
CREATE TABLE final_match_results (
|
||||||
|
round_index INTEGER NOT NULL CHECK (round_index >= 1),
|
||||||
|
match_index INTEGER NOT NULL CHECK (match_index >= 1), score_a INTEGER, score_b INTEGER,
|
||||||
|
PRIMARY KEY (round_index, match_index),
|
||||||
|
CHECK ((score_a IS NULL AND score_b IS NULL) OR (score_a IS NOT NULL AND score_b IS NOT NULL AND score_a >= 0 AND score_b >= 0))
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX idx_final_seeds_unique_team ON final_seeds(team_id) WHERE team_id IS NOT NULL;
|
||||||
|
CREATE INDEX idx_teams_group ON teams(group_id);
|
||||||
|
CREATE INDEX idx_players_team_order ON players(team_id, sort_order);
|
||||||
|
CREATE INDEX idx_league_matches_order ON league_matches(order_index);
|
||||||
|
CREATE TABLE league_rounds (
|
||||||
|
round_index INTEGER PRIMARY KEY CHECK (round_index >= 1),
|
||||||
|
counts_toward_standings INTEGER NOT NULL DEFAULT 0 CHECK (counts_toward_standings IN (0, 1))
|
||||||
|
);
|
||||||
|
INSERT INTO tournament_settings (id, name, created_at, updated_at) VALUES (1, 'Torneio', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
|
||||||
|
INSERT INTO display_settings (id, active_panel, created_at, updated_at) VALUES (1, 'latest-results', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
|
||||||
|
INSERT INTO league_groups (id, name, sort_order, created_at, updated_at) VALUES (1, 'Grupo A', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for statement in SCHEMA.split(";"):
|
||||||
|
if statement.strip():
|
||||||
|
op.execute(statement)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table in ["final_match_results", "final_seeds", "players", "league_matches", "league_rounds",
|
||||||
|
"teams", "league_groups", "display_settings", "tournament_settings"]:
|
||||||
|
op.drop_table(table)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
[project]
|
||||||
|
name = "crr-tournament"
|
||||||
|
version = "1.0.0"
|
||||||
|
description = "CRR Tournament FastAPI backend"
|
||||||
|
requires-python = ">=3.13,<3.14"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115,<1",
|
||||||
|
"uvicorn[standard]>=0.30,<1",
|
||||||
|
"SQLAlchemy>=2.0,<3",
|
||||||
|
"alembic>=1.13,<2",
|
||||||
|
"pydantic-settings>=2.5,<3",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependency-groups]
|
||||||
|
dev = ["pytest>=8,<9", "httpx>=0.27,<1"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
pythonpath = ["."]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
addopts = "-ra"
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.config import Settings
|
||||||
|
from app.main import create_app
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def settings(tmp_path):
|
||||||
|
return Settings(admin_password="migration-fixture-password", session_secret="migration-fixture-secret-not-for-production",
|
||||||
|
database_path=str(tmp_path / "tournament.sqlite"), app_base_path="/jogo/")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(settings):
|
||||||
|
with TestClient(create_app(settings)) as client:
|
||||||
|
yield client
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def admin(client):
|
||||||
|
response = client.post("/api/auth/login", json={"password": "migration-fixture-password"})
|
||||||
|
assert response.status_code == 200
|
||||||
|
client.headers["cookie"] = f"tournament_admin_session={response.cookies['tournament_admin_session']}"
|
||||||
|
return client
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.main import create_app
|
||||||
|
|
||||||
|
FIXTURES = Path(__file__).resolve().parents[4] / "migration/fixtures"
|
||||||
|
|
||||||
|
|
||||||
|
def test_replays_saved_node_workflow_statuses_and_json(client):
|
||||||
|
token = None
|
||||||
|
for observation in json.loads((FIXTURES / "tournament-api.json").read_text()):
|
||||||
|
request, expected = observation["request"], observation["response"]
|
||||||
|
headers = {"cookie": token} if request["authorized"] and token else {}
|
||||||
|
response = client.request(request["method"], request["url"], json=request.get("payload"), headers=headers)
|
||||||
|
assert response.status_code == expected["status"], (request, response.text)
|
||||||
|
assert response.json() == expected["body"], request
|
||||||
|
if request["url"] == "/api/auth/login" and response.status_code == 200:
|
||||||
|
token = f"tournament_admin_session={response.cookies['tournament_admin_session']}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_python_startup_adopts_node_database_and_preserves_public_state(settings):
|
||||||
|
shutil.copyfile(FIXTURES / "tournament.sqlite", settings.database_path)
|
||||||
|
with TestClient(create_app(settings)) as client:
|
||||||
|
response = client.get("/api/public/state")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == json.loads((FIXTURES / "tournament-state.json").read_text())
|
||||||
|
# The Node-era rows remain unchanged, including timestamps and sequence-backed IDs.
|
||||||
|
import sqlite3
|
||||||
|
with sqlite3.connect(settings.database_path) as db:
|
||||||
|
db.row_factory = sqlite3.Row
|
||||||
|
for table, rows in json.loads((FIXTURES / "tournament-rows.json").read_text()).items():
|
||||||
|
assert [dict(row) for row in db.execute(f'SELECT * FROM "{table}" ORDER BY rowid')] == rows
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("payload", [None, {}, {"password": ""}, {"password": 123}])
|
||||||
|
def test_login_validation_error_shape(client, payload):
|
||||||
|
response = client.post("/api/auth/login", json=payload)
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json() == {"error": "Os dados enviados não são válidos."}
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_limiter_cookie_and_logout(client):
|
||||||
|
for _ in range(5):
|
||||||
|
assert client.post("/api/auth/login", json={"password": "wrong"}).status_code == 401
|
||||||
|
assert client.post("/api/auth/login", json={"password": "migration-fixture-password"}).status_code == 429
|
||||||
|
response = client.post("/api/auth/logout")
|
||||||
|
assert response.json() == {"authenticated": False}
|
||||||
|
assert "Path=/jogo/" in response.headers["set-cookie"]
|
||||||
|
assert "HttpOnly" in response.headers["set-cookie"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_head_and_malformed_json_follow_legacy_contract(client):
|
||||||
|
response = client.head("/api/public/state")
|
||||||
|
assert response.status_code == 200 and response.content == b""
|
||||||
|
response = client.post("/api/auth/login", content="{", headers={"content-type": "application/json"})
|
||||||
|
assert response.status_code == 500
|
||||||
|
assert response.json() == {"error": "Ocorreu um erro inesperado. Tente novamente."}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("payload", [
|
||||||
|
{"name": " ", "groupId": 1}, {"name": "T", "groupId": 1, "number": "1"},
|
||||||
|
{"name": "T", "groupId": 1, "number": True}, {"name": "T", "groupId": 1, "number": 1.5},
|
||||||
|
])
|
||||||
|
def test_rejects_invalid_team_payloads(admin, payload):
|
||||||
|
response = admin.post("/api/admin/teams", json=payload)
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_all_saved_api_routes_exist_with_matching_methods(settings):
|
||||||
|
app = create_app(settings)
|
||||||
|
routes = {(method.upper(), path) for path, operations in app.openapi()["paths"].items() for method in operations}
|
||||||
|
for expected in json.loads((FIXTURES / "tournament-routes.json").read_text()):
|
||||||
|
import re
|
||||||
|
path = re.sub(r":(\w+)", r"{\1}", expected["path"])
|
||||||
|
assert (expected["method"], path) in routes
|
||||||
|
app.state.engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_aliases_and_unicode_name_limits_follow_zod(admin):
|
||||||
|
assert admin.put("/api/admin/display", json={"active_panel": "classification", "zoom_percent": 100}).status_code == 400
|
||||||
|
assert admin.post("/api/admin/teams", json={"name": "T", "group_id": 1}).status_code == 400
|
||||||
|
assert admin.post("/api/admin/teams", json={"name": "T", "groupId": 1, "number": None}).status_code == 400
|
||||||
|
assert admin.post("/api/admin/teams", json={"name": "\U0001f600" * 101, "groupId": 1}).status_code == 400
|
||||||
|
response = admin.post("/api/admin/teams", json={"name": "\ufeff Equipa \ufeff", "groupId": "0x1"})
|
||||||
|
assert response.status_code == 201
|
||||||
|
assert response.json()["name"] == "Equipa"
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrent_automatic_team_numbers_are_unique_and_contiguous(admin):
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
def create(index):
|
||||||
|
response = admin.post("/api/admin/teams", json={"name": f"Equipa {index}", "groupId": 1})
|
||||||
|
assert response.status_code == 201
|
||||||
|
return response.json()["number"]
|
||||||
|
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||||
|
assert sorted(pool.map(create, range(4))) == [1, 2, 3, 4]
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_display_fallback_for_unknown_panel_and_fractional_sqlite_zoom(client):
|
||||||
|
# SQLite INTEGER affinity permits fractional values within the legacy BETWEEN check.
|
||||||
|
with client.app.state.engine.begin() as connection:
|
||||||
|
connection.exec_driver_sql("UPDATE display_settings SET active_panel='old-panel', zoom_percent=100.5")
|
||||||
|
response = client.get("/api/public/state")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["display"] == {"activePanel": "latest-results", "zoomPercent": 100}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import inspect
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
|
||||||
|
from app.database import create_database_engine, normalized, run_migrations, validate_legacy_schema
|
||||||
|
|
||||||
|
FIXTURES = Path(__file__).resolve().parents[4] / "migration/fixtures"
|
||||||
|
|
||||||
|
|
||||||
|
def test_fresh_database_matches_node_schema_and_defaults(tmp_path):
|
||||||
|
engine = create_database_engine(str(tmp_path / "new.sqlite"))
|
||||||
|
try:
|
||||||
|
run_migrations(engine)
|
||||||
|
with engine.connect() as connection:
|
||||||
|
validate_legacy_schema(connection)
|
||||||
|
expected = json.loads((FIXTURES / "tournament-schema.json").read_text())
|
||||||
|
for item in expected:
|
||||||
|
actual = connection.exec_driver_sql("SELECT sql FROM sqlite_master WHERE name=?", (item["name"],)).scalar_one()
|
||||||
|
assert normalized(actual) == normalized(item["sql"]), item["name"]
|
||||||
|
assert connection.exec_driver_sql("SELECT name FROM tournament_settings").scalar_one() == "Torneio"
|
||||||
|
assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar_one() == 1
|
||||||
|
assert connection.exec_driver_sql("PRAGMA journal_mode").scalar_one() == "wal"
|
||||||
|
assert connection.exec_driver_sql("PRAGMA busy_timeout").scalar_one() == 5000
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_adopts_populated_node_database_without_modifying_rows_or_schema(tmp_path):
|
||||||
|
path = tmp_path / "legacy.sqlite"
|
||||||
|
shutil.copyfile(FIXTURES / "tournament.sqlite", path)
|
||||||
|
engine = create_database_engine(str(path))
|
||||||
|
try:
|
||||||
|
run_migrations(engine)
|
||||||
|
run_migrations(engine)
|
||||||
|
with engine.connect() as connection:
|
||||||
|
for name, rows in json.loads((FIXTURES / "tournament-rows.json").read_text()).items():
|
||||||
|
assert [dict(row) for row in connection.exec_driver_sql(f'SELECT * FROM "{name}" ORDER BY rowid').mappings()] == rows
|
||||||
|
assert connection.exec_driver_sql("SELECT version_num FROM alembic_version").scalar_one() == "0001_baseline"
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("damage", ["DROP TABLE players", "ALTER TABLE teams ADD COLUMN unexpected TEXT", "DROP INDEX idx_teams_group"])
|
||||||
|
def test_refuses_incompatible_legacy_database_without_stamping(tmp_path, damage):
|
||||||
|
path = tmp_path / "bad.sqlite"
|
||||||
|
shutil.copyfile(FIXTURES / "tournament.sqlite", path)
|
||||||
|
engine = create_database_engine(str(path))
|
||||||
|
try:
|
||||||
|
with engine.begin() as connection:
|
||||||
|
connection.exec_driver_sql(damage)
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
run_migrations(engine)
|
||||||
|
assert "alembic_version" not in inspect(engine).get_table_names()
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_database_constraints_and_player_cascade(tmp_path):
|
||||||
|
engine = create_database_engine(str(tmp_path / "constraints.sqlite"))
|
||||||
|
try:
|
||||||
|
run_migrations(engine)
|
||||||
|
with engine.begin() as connection:
|
||||||
|
connection.exec_driver_sql("INSERT INTO teams(number,name,group_id,created_at,updated_at) VALUES(1,'Equipa',1,'t','t')")
|
||||||
|
connection.exec_driver_sql("INSERT INTO players(team_id,name,sort_order) VALUES(1,'Jogador',0)")
|
||||||
|
connection.exec_driver_sql("DELETE FROM teams WHERE id=1")
|
||||||
|
assert connection.exec_driver_sql("SELECT count(*) FROM players").scalar_one() == 0
|
||||||
|
with pytest.raises(IntegrityError), engine.begin() as connection:
|
||||||
|
connection.exec_driver_sql("INSERT INTO league_groups(name,sort_order,created_at,updated_at) VALUES('grupo a',1,'t','t')")
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_upgrade_rolls_back_schema_creation(tmp_path, monkeypatch):
|
||||||
|
from app import database
|
||||||
|
engine = create_database_engine(str(tmp_path / "failed.sqlite"))
|
||||||
|
def fail(config, revision):
|
||||||
|
config.attributes["connection"].exec_driver_sql("CREATE TABLE incomplete(id INTEGER)")
|
||||||
|
raise RuntimeError("migration failed")
|
||||||
|
monkeypatch.setattr(database.command, "upgrade", fail)
|
||||||
|
try:
|
||||||
|
with pytest.raises(RuntimeError, match="migration failed"):
|
||||||
|
run_migrations(engine)
|
||||||
|
assert not inspect(engine).get_table_names()
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import asyncio
|
||||||
|
|
||||||
|
from app.events import StateChangeEvents
|
||||||
|
|
||||||
|
|
||||||
|
def test_notification_only_sse_retry_heartbeat_broadcast_and_cleanup():
|
||||||
|
async def scenario():
|
||||||
|
broker = StateChangeEvents(heartbeat_seconds=0.02)
|
||||||
|
stream = broker.stream()
|
||||||
|
assert await anext(stream) == "retry: 3000\n\n"
|
||||||
|
broker.broadcast()
|
||||||
|
assert await anext(stream) == 'event: state-changed\ndata: {"type":"state-changed"}\n\n'
|
||||||
|
assert await anext(stream) == ": heartbeat\n\n"
|
||||||
|
await stream.aclose()
|
||||||
|
assert not broker.clients
|
||||||
|
asyncio.run(scenario())
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.main import create_app
|
||||||
|
from app.security.rate_limit import LoginRateLimiter
|
||||||
|
from app.security.session import create_token, valid_token
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_matches_node_wire_format_and_rejects_expired_or_tampered_tokens(settings):
|
||||||
|
# Produced by the frozen Node createSessionToken implementation at now=2000.
|
||||||
|
token = "eyJleHBpcmVzQXQiOjYwNDgwMjAwMH0.MbES4fCzzaBuj5tLh_9osvDnYNwSKDYBlSYPpF-iJQo"
|
||||||
|
assert create_token(settings, now=2000) == token
|
||||||
|
assert valid_token(token, settings, now=2000)
|
||||||
|
assert not valid_token(token, settings, now=604802000)
|
||||||
|
assert not valid_token(token + "x", settings, now=2000)
|
||||||
|
assert not valid_token(token + ".extra", settings)
|
||||||
|
assert not valid_token("malformed", settings)
|
||||||
|
|
||||||
|
|
||||||
|
def test_limiter_expiry_ip_isolation_and_successful_login_reset(client):
|
||||||
|
limiter = LoginRateLimiter()
|
||||||
|
for _ in range(5):
|
||||||
|
limiter.failure("a", now=1000)
|
||||||
|
assert limiter.limited("a", now=1000)
|
||||||
|
assert not limiter.limited("b", now=1000)
|
||||||
|
assert not limiter.limited("a", now=901000)
|
||||||
|
assert not limiter.attempts
|
||||||
|
for _ in range(4):
|
||||||
|
assert client.post("/api/auth/login", json={"password": "wrong"}).status_code == 401
|
||||||
|
assert client.post("/api/auth/login", json={"password": "migration-fixture-password"}).status_code == 200
|
||||||
|
for _ in range(5):
|
||||||
|
assert client.post("/api/auth/login", json={"password": "wrong"}).status_code == 401
|
||||||
|
assert client.post("/api/auth/login", json={"password": "wrong"}).status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
def test_cookie_https_and_proxy_trust(settings):
|
||||||
|
for trust, secure in [(False, False), (True, True)]:
|
||||||
|
with TestClient(create_app(settings.model_copy(update={"trust_proxy": trust}))) as client:
|
||||||
|
response = client.post("/api/auth/login", json={"password": "migration-fixture-password"},
|
||||||
|
headers={"x-forwarded-proto": "https"})
|
||||||
|
cookie = response.headers["set-cookie"]
|
||||||
|
assert ("; Secure" in cookie) is secure
|
||||||
|
assert "HttpOnly" in cookie and "SameSite=strict" in cookie
|
||||||
|
assert "Max-Age=604800" in cookie and "Path=/jogo/" in cookie
|
||||||
|
with TestClient(create_app(settings), base_url="https://testserver") as client:
|
||||||
|
response = client.post("/api/auth/login", json={"password": "migration-fixture-password"})
|
||||||
|
assert "; Secure" in response.headers["set-cookie"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_parallel_failed_logins_do_not_bypass_five_attempt_limit(client):
|
||||||
|
from collections import Counter
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
def attempt(_index):
|
||||||
|
return client.post("/api/auth/login", json={"password": "wrong"}).status_code
|
||||||
|
with ThreadPoolExecutor(max_workers=6) as pool:
|
||||||
|
assert Counter(pool.map(attempt, range(6))) == {401: 5, 429: 1}
|
||||||
Generated
+1
-1482
File diff suppressed because it is too large.
Load diff
@@ -8,30 +8,19 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev:client": "vite",
|
"dev:client": "vite",
|
||||||
"dev:server": "DATABASE_PATH=./tournament.sqlite node --watch --env-file-if-exists=.env --import tsx src/server/main.ts",
|
"build": "vite build",
|
||||||
"build": "npm run build:client && npm run build:server",
|
"typecheck": "vue-tsc --noEmit --project tsconfig.client.json",
|
||||||
"build:client": "vite build",
|
"test": "vitest run src/client src/shared",
|
||||||
"build:server": "tsc --project tsconfig.server.json",
|
"test:watch": "vitest src/client src/shared"
|
||||||
"start": "node dist/server/main.js",
|
|
||||||
"typecheck": "vue-tsc --noEmit --project tsconfig.client.json && tsc --noEmit --project tsconfig.server.json",
|
|
||||||
"test": "vitest run",
|
|
||||||
"test:watch": "vitest"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fastify/cookie": "^11.0.2",
|
|
||||||
"@fastify/static": "^10.1.3",
|
|
||||||
"better-sqlite3": "^13.0.3",
|
|
||||||
"fastify": "^5.2.1",
|
|
||||||
"vue": "^3.5.13",
|
"vue": "^3.5.13",
|
||||||
"vue-router": "^4.5.0",
|
"vue-router": "^4.5.0"
|
||||||
"zod": "^3.24.1"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/better-sqlite3": "^7.6.12",
|
|
||||||
"@types/node": "^22.10.5",
|
"@types/node": "^22.10.5",
|
||||||
"@vitejs/plugin-vue": "^5.2.1",
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
"typescript": "^5.7.2",
|
"typescript": "^5.7.2",
|
||||||
"tsx": "^4.19.2",
|
|
||||||
"vite": "^6.0.7",
|
"vite": "^6.0.7",
|
||||||
"vitest": "^2.1.8",
|
"vitest": "^2.1.8",
|
||||||
"vue-tsc": "^2.2.0"
|
"vue-tsc": "^2.2.0"
|
||||||
|
|||||||
+65
-3
@@ -166,12 +166,74 @@ reference. Both require the Phase 0 staging/Playwright setup described above.
|
|||||||
Container smoke checks emulate the existing Tournament proxy's `/jogo` prefix
|
Container smoke checks emulate the existing Tournament proxy's `/jogo` prefix
|
||||||
stripping when fetching its built asset URLs. Remote CI remains unverified.
|
stripping when fetching its built asset URLs. Remote CI remains unverified.
|
||||||
|
|
||||||
|
## Phase 3 — Tournament FastAPI replacement: locally verified complete
|
||||||
|
|
||||||
|
- Added the independent `crr-tournament` Python 3.13 workspace member, version
|
||||||
|
1.0.0, with FastAPI, SQLAlchemy 2, Alembic and Pydantic Settings.
|
||||||
|
- Modeled the nine existing SQLite tables with typed `Mapped` columns. The frozen
|
||||||
|
Alembic baseline creates the exact Node schema and defaults. Existing databases
|
||||||
|
are validated before stamping, including column types/nullability, defaults,
|
||||||
|
primary/unique keys, checks, indexes, foreign keys, autoincrement and group
|
||||||
|
collation. Validation/stamping/upgrades use an explicit SQLite transaction;
|
||||||
|
failed upgrades roll back schema creation. Foreign keys/WAL/5000 ms timeout
|
||||||
|
apply to every connection.
|
||||||
|
- Ported calendar generation, standard/total-points standings and head-to-head
|
||||||
|
tie breakers, brackets/byes/third-place advancement, seeding and state assembly.
|
||||||
|
- Added domain-grouped request/response schemas and separate auth/public/admin
|
||||||
|
routers. CamelCase payloads, status/error shapes, Portuguese messages, HTTP
|
||||||
|
methods and confirmation rules are preserved. Request validation also covers
|
||||||
|
JavaScript-style ID coercion, name trimming and UTF-16 length limits.
|
||||||
|
- Reproduced the Node HMAC-SHA256/base64url session format and cookie semantics;
|
||||||
|
verified a token produced by the actual Node implementation. Preserved the
|
||||||
|
five-failure/15-minute login window and successful-login reset. Synchronization
|
||||||
|
preserves serial numbering and atomic login limiting under ASGI concurrency.
|
||||||
|
- Ported notification-only SSE with retry 3000, 25-second heartbeat, exact
|
||||||
|
state-change frames and subscriber cleanup. FastAPI serves the existing Vue
|
||||||
|
build, including the legacy sub-path proxy deployment behavior.
|
||||||
|
- Switched development and production runtime to Uvicorn/Python. The image builds
|
||||||
|
Vue with Node 22 and preserves UID/GID 1000 for existing SQLite volumes. Removed
|
||||||
|
Fastify, better-sqlite3, Zod, tsx and backend-only type packages/scripts from
|
||||||
|
the frontend dependency graph after compatibility checks passed.
|
||||||
|
- Updated Makefile/CI to check both Python and frontend code. Preserved all 44
|
||||||
|
legacy HTTP/service assertions under `contracts/` and execute them unchanged
|
||||||
|
using migration-only Python transports. This compatibility command uses owned
|
||||||
|
contracts and app tooling; CI never reads/builds/runs `originals/`.
|
||||||
|
|
||||||
|
| Check | Result |
|
||||||
|
| --- | --- |
|
||||||
|
| Backend pytest | 28 passed |
|
||||||
|
| Preserved legacy assertions against Python | 44 passed: 19 HTTP/SSE, 25 deterministic services |
|
||||||
|
| Frontend/shared tests | 13 passed |
|
||||||
|
| Vue typecheck and build | Passed |
|
||||||
|
| Fresh database schema/defaults vs Node | Exact normalized SQLite DDL match |
|
||||||
|
| Python startup with populated Node fixture | All nine table contents and public state preserved |
|
||||||
|
| Incompatible schemas / migration failure | Refused without stamping; failed DDL rolled back |
|
||||||
|
| Token compatibility / cookies / limiter | Node-produced token and HTTPS/proxy/window/reset/concurrency checks passed |
|
||||||
|
| `make migration-visual-check` | All 14 screenshots match Phase 2 byte-for-byte |
|
||||||
|
| Both Docker builds | Passed |
|
||||||
|
| Container smoke checks | Fresh Tournament, adopted Node fixture and Shifts passed; referenced resources served |
|
||||||
|
| Shifts regression suite | 16 passed |
|
||||||
|
|
||||||
|
`phase3/compatibility.json` preserves passing legacy test names and contract
|
||||||
|
checksums; raw test reports remain in `.migration/port-compat/`. Database tests
|
||||||
|
copy the Node fixture before adoption; container adoption checks likewise use a
|
||||||
|
read-only fixture mount copied into tmpfs. No production database was used.
|
||||||
|
|
||||||
|
The TypeScript server source/config files are retired reference material pending
|
||||||
|
Phase 6 cleanup; production images contain only the Python backend and built
|
||||||
|
Vue assets. The Vue source directory move is also deferred to that cleanup.
|
||||||
|
Compatibility transport scaffolding remains until the corresponding cleanup
|
||||||
|
exit criteria are verified. Remote GitHub Actions execution is still unverified.
|
||||||
|
|
||||||
|
On this machine, the pyenv override described above also applies to Tournament
|
||||||
|
Makefile commands; uv still executes the applications on Python 3.13.
|
||||||
|
|
||||||
## Next work
|
## Next work
|
||||||
|
|
||||||
1. Verify the new CI jobs on Node 22/Python 3.13 after publishing the changes.
|
1. Verify the new CI jobs on Node 22/Python 3.13 after publishing the changes.
|
||||||
2. Phase 3: Tournament SQLAlchemy/Alembic adoption of the saved SQLite fixture,
|
2. Phase 4: Shifts service/model/security extraction and router split, preserving
|
||||||
then deterministic services, state, auth, routers and SSE compatibility.
|
routes, templates, forms, authentication, SQLite data and migration history.
|
||||||
|
|
||||||
Phases 3–6 are not complete. No shared Python package has been extracted yet.
|
Phases 4–6 are not complete. No shared Python package has been extracted yet.
|
||||||
Independent tag-triggered release workflows and final dependency cleanup belong
|
Independent tag-triggered release workflows and final dependency cleanup belong
|
||||||
to later phases.
|
to later phases.
|
||||||
@@ -53,6 +53,10 @@ def main(migrated: bool = False, branding: bool = False, reference: Path | None
|
|||||||
"INITIAL_ADMIN_PASSWORD": "migration-fixture-password",
|
"INITIAL_ADMIN_PASSWORD": "migration-fixture-password",
|
||||||
"SMTP_HOST": "", "ROOT_PATH": "", "SESSION_HTTPS_ONLY": "false",
|
"SMTP_HOST": "", "ROOT_PATH": "", "SESSION_HTTPS_ONLY": "false",
|
||||||
"PYTHONDONTWRITEBYTECODE": "1",
|
"PYTHONDONTWRITEBYTECODE": "1",
|
||||||
|
"ADMIN_PASSWORD": "migration-fixture-password",
|
||||||
|
"SESSION_SECRET": "migration-fixture-secret-not-for-production",
|
||||||
|
"APP_BASE_PATH": "/", "DATABASE_PATH": str(tournament_db),
|
||||||
|
"CLIENT_DIST_PATH": str(tournament_source / "dist/client"),
|
||||||
}
|
}
|
||||||
python = str(ROOT / ".venv/bin/python" if migrated else WORK / "shifts/.venv/bin/python")
|
python = str(ROOT / ".venv/bin/python" if migrated else WORK / "shifts/.venv/bin/python")
|
||||||
subprocess.run([python, "-m", "app.cli", "seed-demo"], cwd=shifts_source, env=env, check=True)
|
subprocess.run([python, "-m", "app.cli", "seed-demo"], cwd=shifts_source, env=env, check=True)
|
||||||
@@ -60,8 +64,10 @@ def main(migrated: bool = False, branding: bool = False, reference: Path | None
|
|||||||
logs = []
|
logs = []
|
||||||
try:
|
try:
|
||||||
for name, command, cwd in [
|
for name, command, cwd in [
|
||||||
("tournament", ["node", "--import", str(tournament_source / "node_modules/tsx/dist/loader.mjs"),
|
("tournament", [python, "-m", "uvicorn", "app.main:create_app", "--factory", "--host", "127.0.0.1",
|
||||||
"migration/capture_tournament.mjs", "--serve"], ROOT),
|
"--port", "18080", "--no-proxy-headers"] if migrated else
|
||||||
|
["node", "--import", str(tournament_source / "node_modules/tsx/dist/loader.mjs"),
|
||||||
|
"migration/capture_tournament.mjs", "--serve"], ROOT / "apps/tournament/backend" if migrated else ROOT),
|
||||||
("shifts", [python, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1",
|
("shifts", [python, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1",
|
||||||
"--port", "18081"], shifts_source),
|
"--port", "18081"], shifts_source),
|
||||||
]:
|
]:
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# Preserved Tournament assertions
|
||||||
|
|
||||||
|
These five test files are byte-for-byte copies of the legacy HTTP and deterministic
|
||||||
|
service tests, preserved before retiring Node backend dependencies. Their source
|
||||||
|
checksums match the Phase 0 Tournament manifest.
|
||||||
|
|
||||||
|
`tools/check_tournament_compat.py` generates isolated test copies that replace
|
||||||
|
only implementation imports with migration transport adapters. All assertions
|
||||||
|
and scenarios run unchanged: 19 tests use actual FastAPI HTTP/SSE servers, and 25
|
||||||
|
invoke the real Python calendar, classification, bracket and seeding services.
|
||||||
|
The adapters depend on frontend Vitest tooling and the Python backend, with no
|
||||||
|
Fastify/better-sqlite3/Zod runtime dependency and no imports from `originals/`.
|
||||||
|
|
||||||
|
Run `make tournament-compat-test` after `make tournament-install`, or run the full
|
||||||
|
`make tournament-test`. The `--freeze` option was used once; do not overwrite
|
||||||
|
these snapshots during later refactors. Native pytest supplies database adoption,
|
||||||
|
HTTP fixture replay, authentication, validation, concurrency and SSE checks.
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { Group, TeamSummary } from '../../shared/types/tournament.js';
|
||||||
|
import { calculateBracket, downstreamMatches } from './bracket.js';
|
||||||
|
|
||||||
|
const group: Group = { id: 1, name: 'Grupo A', sortOrder: 0 };
|
||||||
|
const team = (id: number): TeamSummary => ({ id, number: id, name: `Equipa ${id}`, group });
|
||||||
|
const seeds = [1, 2, 3, 4].map((slotIndex) => ({ slotIndex, team: team(slotIndex) }));
|
||||||
|
|
||||||
|
describe('calculateBracket', () => {
|
||||||
|
it('faz avançar vencedores entre várias rondas e determina o campeão', () => {
|
||||||
|
const bracket = calculateBracket(2, seeds, [
|
||||||
|
{ roundIndex: 1, matchIndex: 1, scoreA: 5, scoreB: 2 },
|
||||||
|
{ roundIndex: 1, matchIndex: 2, scoreA: 1, scoreB: 3 },
|
||||||
|
{ roundIndex: 2, matchIndex: 1, scoreA: 4, scoreB: 2 },
|
||||||
|
]);
|
||||||
|
expect(bracket.rounds[1].matches[0].teamA.team?.id).toBe(1);
|
||||||
|
expect(bracket.rounds[1].matches[0].teamB.team?.id).toBe(4);
|
||||||
|
expect(bracket.champion?.id).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('não faz avançar um empate que a API deve rejeitar', () => {
|
||||||
|
const bracket = calculateBracket(1, seeds.slice(0, 2), [
|
||||||
|
{ roundIndex: 1, matchIndex: 1, scoreA: 3, scoreB: 3 },
|
||||||
|
]);
|
||||||
|
expect(bracket.rounds[0].matches[0].winner).toBeNull();
|
||||||
|
expect(bracket.champion).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('faz avançar uma equipa automaticamente num bye e deixa jogos vazios por apurar', () => {
|
||||||
|
const bracket = calculateBracket(2, [
|
||||||
|
{ slotIndex: 1, team: team(1) },
|
||||||
|
{ slotIndex: 2, team: null },
|
||||||
|
{ slotIndex: 3, team: null },
|
||||||
|
{ slotIndex: 4, team: null },
|
||||||
|
], []);
|
||||||
|
expect(bracket.rounds[0].matches[0]).toMatchObject({ isBye: true, winner: team(1) });
|
||||||
|
expect(bracket.rounds[0].matches[1].winner).toBeNull();
|
||||||
|
expect(bracket.rounds[1].matches[0].teamA.team?.id).toBe(1);
|
||||||
|
expect(bracket.rounds[1].matches[0].teamB.pending).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cria o jogo do 3.º lugar com os derrotados das meias-finais', () => {
|
||||||
|
const bracket = calculateBracket(2, seeds, [
|
||||||
|
{ roundIndex: 1, matchIndex: 1, scoreA: 5, scoreB: 2 },
|
||||||
|
{ roundIndex: 1, matchIndex: 2, scoreA: 1, scoreB: 3 },
|
||||||
|
{ roundIndex: 2, matchIndex: 2, scoreA: 2, scoreB: 4 },
|
||||||
|
], true);
|
||||||
|
expect(bracket.thirdPlaceEnabled).toBe(true);
|
||||||
|
expect(bracket.thirdPlaceMatch).toMatchObject({
|
||||||
|
matchIndex: 2,
|
||||||
|
teamA: { team: { id: 2 } },
|
||||||
|
teamB: { team: { id: 3 } },
|
||||||
|
scoreA: 2,
|
||||||
|
scoreB: 4,
|
||||||
|
winner: { id: 3 },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('identifica todos os resultados a invalidar após mudar um jogo a montante', () => {
|
||||||
|
expect(downstreamMatches(4, 1, 3)).toEqual([
|
||||||
|
{ roundIndex: 2, matchIndex: 2 },
|
||||||
|
{ roundIndex: 3, matchIndex: 1 },
|
||||||
|
{ roundIndex: 4, matchIndex: 1 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { Group, TeamSummary } from '../../shared/types/tournament.js';
|
||||||
|
import { generateRoundRobinSchedule } from './calendar.js';
|
||||||
|
|
||||||
|
const team = (id: number, group: Group): TeamSummary => ({
|
||||||
|
id,
|
||||||
|
number: id,
|
||||||
|
name: `Equipa ${id}`,
|
||||||
|
group,
|
||||||
|
});
|
||||||
|
|
||||||
|
function pairCounts(schedule: ReturnType<typeof generateRoundRobinSchedule>): Map<string, number> {
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
for (const game of schedule) {
|
||||||
|
const key = [game.teamA.id, game.teamB.id].sort((a, b) => a - b).join('-');
|
||||||
|
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('generateRoundRobinSchedule', () => {
|
||||||
|
it('gera as três jornadas de um grupo par com quatro equipas', () => {
|
||||||
|
const group: Group = { id: 1, name: 'Grupo A', sortOrder: 0 };
|
||||||
|
const teams = [1, 2, 3, 4].map((id) => team(id, group));
|
||||||
|
|
||||||
|
const schedule = generateRoundRobinSchedule(teams, 1);
|
||||||
|
|
||||||
|
expect(schedule.map((game) => ({
|
||||||
|
gameNumber: game.gameNumber,
|
||||||
|
roundNumber: game.roundNumber,
|
||||||
|
groupId: game.group.id,
|
||||||
|
teams: [game.teamA.id, game.teamB.id],
|
||||||
|
}))).toEqual([
|
||||||
|
{ gameNumber: 1, roundNumber: 1, groupId: 1, teams: [1, 4] },
|
||||||
|
{ gameNumber: 2, roundNumber: 1, groupId: 1, teams: [2, 3] },
|
||||||
|
{ gameNumber: 3, roundNumber: 2, groupId: 1, teams: [3, 1] },
|
||||||
|
{ gameNumber: 4, roundNumber: 2, groupId: 1, teams: [4, 2] },
|
||||||
|
{ gameNumber: 5, roundNumber: 3, groupId: 1, teams: [1, 2] },
|
||||||
|
{ gameNumber: 6, roundNumber: 3, groupId: 1, teams: [3, 4] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('suporta um grupo ímpar através de uma folga por jornada', () => {
|
||||||
|
const group: Group = { id: 1, name: 'Grupo A', sortOrder: 0 };
|
||||||
|
const teams = [1, 2, 3].map((id) => team(id, group));
|
||||||
|
|
||||||
|
const schedule = generateRoundRobinSchedule(teams, 1);
|
||||||
|
|
||||||
|
expect(schedule.map((game) => [game.roundNumber, game.teamA.id, game.teamB.id])).toEqual([
|
||||||
|
[1, 2, 3],
|
||||||
|
[2, 3, 1],
|
||||||
|
[3, 1, 2],
|
||||||
|
]);
|
||||||
|
expect(schedule.map((game) => game.roundNumber)).toEqual([1, 2, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('combina grupos ordenados nas mesmas jornadas sem cruzar nem repetir equipas', () => {
|
||||||
|
const group2: Group = { id: 2, name: 'Grupo 2', sortOrder: 0 };
|
||||||
|
const group1: Group = { id: 1, name: 'Grupo 1', sortOrder: 0 };
|
||||||
|
const group3: Group = { id: 3, name: 'Grupo 3', sortOrder: 1 };
|
||||||
|
const teams = [
|
||||||
|
team(21, group2),
|
||||||
|
team(11, group1),
|
||||||
|
team(31, group3),
|
||||||
|
team(22, group2),
|
||||||
|
team(12, group1),
|
||||||
|
team(32, group3),
|
||||||
|
team(23, group2),
|
||||||
|
team(13, group1),
|
||||||
|
team(14, group1),
|
||||||
|
];
|
||||||
|
|
||||||
|
const schedule = generateRoundRobinSchedule(teams, 1);
|
||||||
|
|
||||||
|
expect(schedule.map((game) => [game.roundNumber, game.group.id])).toEqual([
|
||||||
|
[1, 1], [1, 1], [1, 2], [1, 3],
|
||||||
|
[2, 1], [2, 1], [2, 2],
|
||||||
|
[3, 1], [3, 1], [3, 2],
|
||||||
|
]);
|
||||||
|
expect(schedule.every((game) => (
|
||||||
|
game.teamA.group.id === game.group.id && game.teamB.group.id === game.group.id
|
||||||
|
))).toBe(true);
|
||||||
|
|
||||||
|
for (const roundNumber of [1, 2, 3]) {
|
||||||
|
const participants = schedule
|
||||||
|
.filter((game) => game.roundNumber === roundNumber)
|
||||||
|
.flatMap((game) => [game.teamA.id, game.teamB.id]);
|
||||||
|
expect(new Set(participants).size).toBe(participants.length);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('anexa uma segunda volta que espelha exatamente a primeira', () => {
|
||||||
|
const group: Group = { id: 1, name: 'Grupo A', sortOrder: 0 };
|
||||||
|
const teams = [1, 2, 3, 4].map((id) => team(id, group));
|
||||||
|
const firstLeg = generateRoundRobinSchedule(teams, 1);
|
||||||
|
|
||||||
|
const schedule = generateRoundRobinSchedule(teams, 2);
|
||||||
|
|
||||||
|
expect(schedule.slice(0, firstLeg.length)).toEqual(firstLeg);
|
||||||
|
expect(schedule.slice(firstLeg.length)).toEqual(firstLeg.map((game, index) => ({
|
||||||
|
gameNumber: firstLeg.length + index + 1,
|
||||||
|
roundNumber: game.roundNumber + 3,
|
||||||
|
group: game.group,
|
||||||
|
teamA: game.teamB,
|
||||||
|
teamB: game.teamA,
|
||||||
|
})));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('agenda todos os pares uma vez por volta', () => {
|
||||||
|
const group: Group = { id: 1, name: 'Grupo A', sortOrder: 0 };
|
||||||
|
const teams = [1, 2, 3, 4].map((id) => team(id, group));
|
||||||
|
const expectedPairs = ['1-2', '1-3', '1-4', '2-3', '2-4', '3-4'];
|
||||||
|
|
||||||
|
expect(pairCounts(generateRoundRobinSchedule(teams, 1))).toEqual(
|
||||||
|
new Map(expectedPairs.map((pair) => [pair, 1])),
|
||||||
|
);
|
||||||
|
expect(pairCounts(generateRoundRobinSchedule(teams, 2))).toEqual(
|
||||||
|
new Map(expectedPairs.map((pair) => [pair, 2])),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('não altera a lista nem a ordem recebidas', () => {
|
||||||
|
const groupA: Group = { id: 1, name: 'Grupo A', sortOrder: 1 };
|
||||||
|
const groupB: Group = { id: 2, name: 'Grupo B', sortOrder: 0 };
|
||||||
|
const teams = [team(1, groupA), team(4, groupB), team(3, groupA), team(2, groupB)];
|
||||||
|
const snapshot = structuredClone(teams);
|
||||||
|
|
||||||
|
generateRoundRobinSchedule(teams, 2);
|
||||||
|
|
||||||
|
expect(teams).toEqual(snapshot);
|
||||||
|
expect(teams.map(({ id }) => id)).toEqual([1, 4, 3, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejeita um número de voltas inválido mesmo quando o tipo é contornado', () => {
|
||||||
|
expect(() => generateRoundRobinSchedule([], 3 as 1 | 2)).toThrowError(RangeError);
|
||||||
|
expect(() => generateRoundRobinSchedule([], 3 as 1 | 2)).toThrow('1 ou 2');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { Group, TeamSummary } from '../../shared/types/tournament.js';
|
||||||
|
import { calculateClassification, type ClassificationMatch } from './classification.js';
|
||||||
|
|
||||||
|
const group: Group = { id: 1, name: 'Grupo A', sortOrder: 0 };
|
||||||
|
const team = (id: number, number = id): TeamSummary => ({ id, number, name: `Equipa ${number}`, group });
|
||||||
|
const teams = [team(1), team(2), team(3), team(4)];
|
||||||
|
const match = (teamA: TeamSummary, teamB: TeamSummary, scoreA: number | null, scoreB: number | null): ClassificationMatch => ({
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA,
|
||||||
|
scoreB,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('calculateClassification', () => {
|
||||||
|
it('mantém a classificação standard como modo predefinido', () => {
|
||||||
|
const matches = [
|
||||||
|
match(teams[0], teams[1], 2, 0),
|
||||||
|
match(teams[2], teams[1], 4, 1),
|
||||||
|
];
|
||||||
|
|
||||||
|
const standard = calculateClassification(teams.slice(0, 3), matches, 'standard');
|
||||||
|
expect(calculateClassification(teams.slice(0, 3), matches)).toEqual(standard);
|
||||||
|
expect(standard.map((row) => ({ id: row.team.id, points: row.points }))).toEqual([
|
||||||
|
{ id: 3, points: 3 },
|
||||||
|
{ id: 1, points: 3 },
|
||||||
|
{ id: 2, points: 0 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calcula vitórias, empates, derrotas e ignora resultados incompletos', () => {
|
||||||
|
const table = calculateClassification(teams.slice(0, 3), [
|
||||||
|
match(teams[0], teams[1], 3, 1),
|
||||||
|
match(teams[0], teams[2], 2, 2),
|
||||||
|
match(teams[1], teams[2], null, null),
|
||||||
|
]);
|
||||||
|
expect(table[0]).toMatchObject({ team: teams[0], played: 2, wins: 1, draws: 1, losses: 0, goalsFor: 5, goalsAgainst: 3, goalDifference: 2, points: 4 });
|
||||||
|
expect(table.find((row) => row.team.id === 2)).toMatchObject({ played: 1, losses: 1, points: 0 });
|
||||||
|
expect(table.find((row) => row.team.id === 3)).toMatchObject({ played: 1, draws: 1, points: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ordena por pontos, diferença de golos e golos marcados', () => {
|
||||||
|
const table = calculateClassification(teams.slice(0, 3), [
|
||||||
|
match(teams[0], teams[1], 2, 0),
|
||||||
|
match(teams[2], teams[1], 4, 1),
|
||||||
|
]);
|
||||||
|
expect(table.map((row) => row.team.id)).toEqual([3, 1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('usa confronto direto para equipas empatadas nos critérios principais', () => {
|
||||||
|
const table = calculateClassification(teams, [
|
||||||
|
match(teams[0], teams[1], 1, 0),
|
||||||
|
match(teams[0], teams[2], 0, 1),
|
||||||
|
match(teams[1], teams[3], 1, 0),
|
||||||
|
]);
|
||||||
|
const teamOnePosition = table.findIndex((row) => row.team.id === 1);
|
||||||
|
const teamTwoPosition = table.findIndex((row) => row.team.id === 2);
|
||||||
|
expect(teamOnePosition).toBeLessThan(teamTwoPosition);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('usa o número da equipa como último critério determinístico', () => {
|
||||||
|
const reversed = [team(10, 9), team(11, 2)];
|
||||||
|
expect(calculateClassification(reversed, []).map((row) => row.team.number)).toEqual([2, 9]);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('total-points', () => {
|
||||||
|
it('soma os resultados marcados por cada equipa nos pontos', () => {
|
||||||
|
const table = calculateClassification(teams.slice(0, 3), [
|
||||||
|
match(teams[0], teams[1], 8, 5),
|
||||||
|
match(teams[0], teams[2], 3, 4),
|
||||||
|
match(teams[1], teams[2], 7, 6),
|
||||||
|
], 'total-points');
|
||||||
|
|
||||||
|
expect(table.map((row) => ({ id: row.team.id, points: row.points }))).toEqual([
|
||||||
|
{ id: 2, points: 12 },
|
||||||
|
{ id: 1, points: 11 },
|
||||||
|
{ id: 3, points: 10 },
|
||||||
|
]);
|
||||||
|
expect(table.find((row) => row.team.id === 1)).toMatchObject({
|
||||||
|
played: 2,
|
||||||
|
wins: 1,
|
||||||
|
draws: 0,
|
||||||
|
losses: 1,
|
||||||
|
goalsFor: 11,
|
||||||
|
goalsAgainst: 9,
|
||||||
|
goalDifference: 2,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolve totais empatados pelo confronto direto, não pela diferença global', () => {
|
||||||
|
const table = calculateClassification(teams, [
|
||||||
|
match(teams[0], teams[1], 0, 1),
|
||||||
|
match(teams[0], teams[2], 5, 0),
|
||||||
|
match(teams[1], teams[3], 4, 10),
|
||||||
|
], 'total-points');
|
||||||
|
|
||||||
|
expect(table.map((row) => row.team.id)).toEqual([4, 2, 1, 3]);
|
||||||
|
expect(table.find((row) => row.team.id === 1)).toMatchObject({ points: 5, goalDifference: 4 });
|
||||||
|
expect(table.find((row) => row.team.id === 2)).toMatchObject({ points: 5, goalDifference: -5 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('usa o número da equipa como fallback determinístico', () => {
|
||||||
|
const reversed = [team(10, 9), team(11, 2), team(12, 5)];
|
||||||
|
|
||||||
|
expect(calculateClassification(reversed, [], 'total-points').map((row) => row.team.number))
|
||||||
|
.toEqual([2, 5, 9]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignora jogos incompletos sem acumular resultados ou estatísticas', () => {
|
||||||
|
const table = calculateClassification(teams.slice(0, 3), [
|
||||||
|
match(teams[0], teams[1], 7, 3),
|
||||||
|
match(teams[0], teams[2], 9, null),
|
||||||
|
match(teams[1], teams[2], null, 8),
|
||||||
|
], 'total-points');
|
||||||
|
|
||||||
|
expect(table.find((row) => row.team.id === 1)).toMatchObject({ played: 1, points: 7, goalsFor: 7 });
|
||||||
|
expect(table.find((row) => row.team.id === 2)).toMatchObject({ played: 1, points: 3, goalsFor: 3 });
|
||||||
|
expect(table.find((row) => row.team.id === 3)).toMatchObject({ played: 0, points: 0, goalsFor: 0 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { GroupStanding, TeamSummary } from './types/tournament';
|
||||||
|
import { buildGroupQualificationPreview, buildOverallQualificationPreview, standardBracketSeedOrder } from './finalSeeding';
|
||||||
|
|
||||||
|
function team(id: number, number: number, name: string, groupId: number, groupName: string): TeamSummary {
|
||||||
|
return { id, number, name, group: { id: groupId, name: groupName, sortOrder: groupId - 1 } };
|
||||||
|
}
|
||||||
|
|
||||||
|
function standing(groupId: number, groupName: string, teams: TeamSummary[]): GroupStanding {
|
||||||
|
return {
|
||||||
|
group: { id: groupId, name: groupName, sortOrder: groupId - 1 },
|
||||||
|
rows: teams.map((entry, index) => ({
|
||||||
|
position: index + 1,
|
||||||
|
team: entry,
|
||||||
|
played: 1,
|
||||||
|
wins: index === 0 ? 1 : 0,
|
||||||
|
draws: 0,
|
||||||
|
losses: index === 0 ? 0 : 1,
|
||||||
|
goalsFor: index === 0 ? 3 : 1,
|
||||||
|
goalsAgainst: index === 0 ? 1 : 3,
|
||||||
|
goalDifference: index === 0 ? 2 : -2,
|
||||||
|
points: index === 0 ? 3 : 0,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('final seeding', () => {
|
||||||
|
it('uses standard bracket seed placement', () => {
|
||||||
|
expect(standardBracketSeedOrder(2)).toEqual([1, 2]);
|
||||||
|
expect(standardBracketSeedOrder(4)).toEqual([1, 4, 2, 3]);
|
||||||
|
expect(standardBracketSeedOrder(8)).toEqual([1, 8, 4, 5, 2, 7, 3, 6]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('crosses the top two teams from two groups in the semi-finals', () => {
|
||||||
|
const a1 = team(1, 1, 'A1', 1, 'Grupo A');
|
||||||
|
const a2 = team(2, 2, 'A2', 1, 'Grupo A');
|
||||||
|
const b1 = team(3, 3, 'B1', 2, 'Grupo B');
|
||||||
|
const b2 = team(4, 4, 'B2', 2, 'Grupo B');
|
||||||
|
|
||||||
|
const preview = buildGroupQualificationPreview([
|
||||||
|
standing(1, 'Grupo A', [a1, a2]),
|
||||||
|
standing(2, 'Grupo B', [b1, b2]),
|
||||||
|
], 2, 4);
|
||||||
|
|
||||||
|
expect(preview).toMatchObject({ mode: 'per-group', qualifiersPerGroup: 2, qualifierCount: 4 });
|
||||||
|
expect(preview.qualifiers.map((qualifier) => qualifier.team.id)).toEqual([a1.id, b1.id, a2.id, b2.id]);
|
||||||
|
expect(preview.seeds).toEqual([
|
||||||
|
{ slotIndex: 1, teamId: a1.id },
|
||||||
|
{ slotIndex: 2, teamId: b2.id },
|
||||||
|
{ slotIndex: 3, teamId: b1.id },
|
||||||
|
{ slotIndex: 4, teamId: a2.id },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves lower seeds empty when the bracket has extra slots', () => {
|
||||||
|
const a1 = team(1, 1, 'A1', 1, 'Grupo A');
|
||||||
|
const b1 = team(2, 2, 'B1', 2, 'Grupo B');
|
||||||
|
|
||||||
|
const preview = buildGroupQualificationPreview([
|
||||||
|
standing(1, 'Grupo A', [a1]),
|
||||||
|
standing(2, 'Grupo B', [b1]),
|
||||||
|
], 1, 4);
|
||||||
|
|
||||||
|
expect(preview.seeds).toEqual([
|
||||||
|
{ slotIndex: 1, teamId: a1.id },
|
||||||
|
{ slotIndex: 2, teamId: null },
|
||||||
|
{ slotIndex: 3, teamId: b1.id },
|
||||||
|
{ slotIndex: 4, teamId: null },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('can select the best teams across all groups', () => {
|
||||||
|
const a1 = team(1, 1, 'A1', 1, 'Grupo A');
|
||||||
|
const a2 = team(2, 2, 'A2', 1, 'Grupo A');
|
||||||
|
const b1 = team(3, 3, 'B1', 2, 'Grupo B');
|
||||||
|
const b2 = team(4, 4, 'B2', 2, 'Grupo B');
|
||||||
|
const groupA = standing(1, 'Grupo A', [a1, a2]);
|
||||||
|
const groupB = standing(2, 'Grupo B', [b1, b2]);
|
||||||
|
groupB.rows[0].points = 6;
|
||||||
|
groupB.rows[0].goalDifference = 4;
|
||||||
|
|
||||||
|
const preview = buildOverallQualificationPreview([groupA, groupB], 2, 4, 'standard');
|
||||||
|
|
||||||
|
expect(preview).toMatchObject({ mode: 'overall', qualifiersPerGroup: null, qualifierCount: 2 });
|
||||||
|
expect(preview.qualifiers.map((qualifier) => qualifier.team.id)).toEqual([b1.id, a1.id]);
|
||||||
|
expect(preview.seeds).toEqual([
|
||||||
|
{ slotIndex: 1, teamId: b1.id },
|
||||||
|
{ slotIndex: 2, teamId: null },
|
||||||
|
{ slotIndex: 3, teamId: a1.id },
|
||||||
|
{ slotIndex: 4, teamId: null },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
{
|
||||||
|
"passed": 44,
|
||||||
|
"tests": [
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API rejects unauthenticated administration and accepts only the configured login password",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API scopes the administration session cookie to the deployment path",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API publishes the admin-selected panel and zoom to the public display state",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API notifies connected displays when the selected panel changes",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API creates teams in Grupo A and rejects globally duplicated team numbers",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API assigns the next team number when creating a team without one",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API manages groups and prevents deleting nonempty or final groups",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API previews and saves the exact one-leg schedule for four teams",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API rejects generation when no group can produce a match",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API keeps a round out of the standings until an administrator enables it",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API ranks total game points and resolves equal totals by the direct match",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API generates only intra-group games with persisted rounds and aligned public classifications",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API previews a second leg that exactly mirrors the first with reversed venues",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API rejects tampered and stale calendar generation descriptors",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API requires confirmation to replace a scored calendar and clears scores when confirmed",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API randomizes existing team numbers and group assignments after confirmation",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API configures and advances a final stage that is exposed through public state",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API accepts the next-match display panel",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "tournament manager HTTP API previews automatic final-stage qualification from group standings",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "final seeding uses standard bracket seed placement",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "final seeding crosses the top two teams from two groups in the semi-finals",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "final seeding leaves lower seeds empty when the bracket has extra slots",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "final seeding can select the best teams across all groups",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateBracket faz avan\u00e7ar vencedores entre v\u00e1rias rondas e determina o campe\u00e3o",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateBracket n\u00e3o faz avan\u00e7ar um empate que a API deve rejeitar",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateBracket faz avan\u00e7ar uma equipa automaticamente num bye e deixa jogos vazios por apurar",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateBracket cria o jogo do 3.\u00ba lugar com os derrotados das meias-finais",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateBracket identifica todos os resultados a invalidar ap\u00f3s mudar um jogo a montante",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "generateRoundRobinSchedule gera as tr\u00eas jornadas de um grupo par com quatro equipas",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "generateRoundRobinSchedule suporta um grupo \u00edmpar atrav\u00e9s de uma folga por jornada",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "generateRoundRobinSchedule combina grupos ordenados nas mesmas jornadas sem cruzar nem repetir equipas",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "generateRoundRobinSchedule anexa uma segunda volta que espelha exatamente a primeira",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "generateRoundRobinSchedule agenda todos os pares uma vez por volta",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "generateRoundRobinSchedule n\u00e3o altera a lista nem a ordem recebidas",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "generateRoundRobinSchedule rejeita um n\u00famero de voltas inv\u00e1lido mesmo quando o tipo \u00e9 contornado",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification mant\u00e9m a classifica\u00e7\u00e3o standard como modo predefinido",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification calcula vit\u00f3rias, empates, derrotas e ignora resultados incompletos",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification ordena por pontos, diferen\u00e7a de golos e golos marcados",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification usa confronto direto para equipas empatadas nos crit\u00e9rios principais",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification usa o n\u00famero da equipa como \u00faltimo crit\u00e9rio determin\u00edstico",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification total-points soma os resultados marcados por cada equipa nos pontos",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification total-points resolve totais empatados pelo confronto direto, n\u00e3o pela diferen\u00e7a global",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification total-points usa o n\u00famero da equipa como fallback determin\u00edstico",
|
||||||
|
"status": "passed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculateClassification total-points ignora jogos incompletos sem acumular resultados ou estat\u00edsticas",
|
||||||
|
"status": "passed"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"contract_sha256": {
|
||||||
|
"src/server/app.integration.test.ts": "a8d16cedbfbfcacc33f234c4fe60e09078dac117953a3254106d0a701865488c",
|
||||||
|
"src/server/services/calendar.test.ts": "3ed80358e56a2447242f0d5e8907ac558cde9983149ed618e63cfc530c189248",
|
||||||
|
"src/server/services/classification.test.ts": "83eddf6ee8b6f1779d0c5488cbf34ed3e6e4f4777172ad37cee42fc060d62e91",
|
||||||
|
"src/server/services/bracket.test.ts": "9a930d995b020751609bc70658e5a3514cbc0feb559fb51e0ed6dbd2d9a9dbc6",
|
||||||
|
"src/shared/finalSeeding.test.ts": "5e4a3ea66324d0b488a29109263495c0d5ee5c831a149e659b2e5dfd9b23a99b"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
|
||||||
|
function call(name, args) {
|
||||||
|
const result = spawnSync(process.env.TOURNAMENT_PYTHON, [process.env.TOURNAMENT_BRIDGE], {
|
||||||
|
input: JSON.stringify({ name, args }), encoding: 'utf8', env: process.env,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) throw new Error(result.stderr || 'Python bridge failed');
|
||||||
|
const value = JSON.parse(result.stdout);
|
||||||
|
if (value.error) throw new RangeError(value.error);
|
||||||
|
return value.result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const generateRoundRobinSchedule = (...args) => call('calendar', args);
|
||||||
|
export const calculateClassification = (...args) => call('classification', args);
|
||||||
|
export const calculateBracket = (...args) => call('bracket', args);
|
||||||
|
export const downstreamMatches = (...args) => call('downstream', args);
|
||||||
|
export const standardBracketSeedOrder = (...args) => call('seed-order', args);
|
||||||
|
export const buildGroupQualificationPreview = (...args) => call('group-qualification', args);
|
||||||
|
export const buildOverallQualificationPreview = (...args) => call('overall-qualification', args);
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Execute actual Python services for the legacy deterministic-service assertions."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.environ["TOURNAMENT_BACKEND"])
|
||||||
|
|
||||||
|
from app.schemas.base import Schema
|
||||||
|
from app.schemas.state import GroupStanding
|
||||||
|
from app.schemas.teams import TeamSummary
|
||||||
|
from app.services.bracket import calculate_bracket, downstream_matches
|
||||||
|
from app.services.calendar import generate_calendar
|
||||||
|
from app.services.classification import calculate_classification
|
||||||
|
from app.services.seeding import group_qualification, overall_qualification, seed_order
|
||||||
|
|
||||||
|
|
||||||
|
class MatchScores(Schema):
|
||||||
|
team_a: TeamSummary
|
||||||
|
team_b: TeamSummary
|
||||||
|
score_a: int | None
|
||||||
|
score_b: int | None
|
||||||
|
|
||||||
|
|
||||||
|
def serialize(value):
|
||||||
|
if isinstance(value, Schema):
|
||||||
|
return value.model_dump(by_alias=True)
|
||||||
|
if isinstance(value, list):
|
||||||
|
return [serialize(item) for item in value]
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def execute(name, args):
|
||||||
|
if name == "calendar":
|
||||||
|
return generate_calendar([TeamSummary.model_validate(item) for item in args[0]], args[1])
|
||||||
|
if name == "classification":
|
||||||
|
return calculate_classification([TeamSummary.model_validate(item) for item in args[0]],
|
||||||
|
[MatchScores.model_validate(item) for item in args[1]],
|
||||||
|
args[2] if len(args) > 2 else "standard")
|
||||||
|
if name == "bracket":
|
||||||
|
seeds = {item["slotIndex"]: TeamSummary.model_validate(item["team"]) if item["team"] else None for item in args[1]}
|
||||||
|
results = {(item["roundIndex"], item["matchIndex"]): (item["scoreA"], item["scoreB"]) for item in args[2]}
|
||||||
|
return calculate_bracket(args[0], seeds, results, args[3] if len(args) > 3 else False)
|
||||||
|
if name == "downstream":
|
||||||
|
return [{"roundIndex": index, "matchIndex": number} for index, number in downstream_matches(*args)]
|
||||||
|
if name == "seed-order":
|
||||||
|
return seed_order(args[0])
|
||||||
|
standings = [GroupStanding.model_validate(item) for item in args[0]]
|
||||||
|
if name == "group-qualification":
|
||||||
|
return group_qualification(standings, args[1], args[2])
|
||||||
|
if name == "overall-qualification":
|
||||||
|
return overall_qualification(standings, args[1], args[2], args[3])
|
||||||
|
raise ValueError(f"Unknown service: {name}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
request = json.load(sys.stdin)
|
||||||
|
try:
|
||||||
|
response = {"result": serialize(execute(request["name"], request["args"]))}
|
||||||
|
except ValueError as error:
|
||||||
|
response = {"error": str(error)}
|
||||||
|
print(json.dumps(response, ensure_ascii=False))
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
// Migration-only transport adapter: runs the unchanged legacy HTTP assertions on FastAPI.
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import net from 'node:net';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
export const SESSION_COOKIE_NAME = 'tournament_admin_session';
|
||||||
|
|
||||||
|
export async function createApp(options) {
|
||||||
|
const temporary = mkdtempSync(join(process.env.TOURNAMENT_WORK, 'api-'));
|
||||||
|
const socket = net.createServer();
|
||||||
|
await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve));
|
||||||
|
const port = socket.address().port;
|
||||||
|
await new Promise(resolve => socket.close(resolve));
|
||||||
|
const processHandle = spawn(process.env.TOURNAMENT_PYTHON, [
|
||||||
|
'-m', 'uvicorn', 'app.main:create_app', '--factory', '--host', '127.0.0.1',
|
||||||
|
'--port', String(port), '--no-proxy-headers',
|
||||||
|
], { cwd: process.env.TOURNAMENT_BACKEND, env: {
|
||||||
|
...process.env, ADMIN_PASSWORD: options.authentication.adminPassword,
|
||||||
|
SESSION_SECRET: options.authentication.sessionSecret,
|
||||||
|
DATABASE_PATH: join(temporary, 'tournament.sqlite'), APP_BASE_PATH: options.basePath,
|
||||||
|
TRUST_PROXY: 'false', PYTHONDONTWRITEBYTECODE: '1',
|
||||||
|
}, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||||
|
let logs = '';
|
||||||
|
processHandle.stdout.on('data', chunk => { logs += chunk; });
|
||||||
|
processHandle.stderr.on('data', chunk => { logs += chunk; });
|
||||||
|
const base = `http://127.0.0.1:${port}`;
|
||||||
|
async function close() {
|
||||||
|
if (processHandle.exitCode === null) {
|
||||||
|
processHandle.kill('SIGTERM');
|
||||||
|
const timer = setTimeout(() => processHandle.kill('SIGKILL'), 3000);
|
||||||
|
await new Promise(resolve => processHandle.once('exit', resolve));
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
rmSync(temporary, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
let ready = false;
|
||||||
|
for (let count = 0; count < 100; count++) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(base + '/api/auth/session');
|
||||||
|
if (response.ok) { ready = true; break; }
|
||||||
|
} catch { /* Wait for Uvicorn to bind its socket. */ }
|
||||||
|
if (processHandle.exitCode !== null) throw new Error(logs);
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 50));
|
||||||
|
}
|
||||||
|
if (!ready) throw new Error('FastAPI startup timed out: ' + logs);
|
||||||
|
} catch (error) {
|
||||||
|
await close();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ready: async () => {}, listen: async () => {}, server: { address: () => ({ port }) }, close,
|
||||||
|
async inject(input) {
|
||||||
|
const headers = { ...input.headers };
|
||||||
|
if (input.payload !== undefined) headers['content-type'] = 'application/json';
|
||||||
|
const response = await fetch(base + input.url, {
|
||||||
|
method: input.method, headers,
|
||||||
|
body: input.payload === undefined ? undefined : JSON.stringify(input.payload),
|
||||||
|
});
|
||||||
|
const body = await response.text();
|
||||||
|
return {
|
||||||
|
statusCode: response.status, headers: Object.fromEntries(response.headers), body,
|
||||||
|
json: () => JSON.parse(body),
|
||||||
|
cookies: response.headers.getSetCookie().map(cookie => {
|
||||||
|
const [pair] = cookie.split(';');
|
||||||
|
const separator = pair.indexOf('=');
|
||||||
|
return { name: pair.slice(0, separator), value: pair.slice(separator + 1) };
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
+1
-2
@@ -1,5 +1,4 @@
|
|||||||
[tool.uv.workspace]
|
[tool.uv.workspace]
|
||||||
members = ["apps/shifts/backend"]
|
members = ["apps/shifts/backend", "apps/tournament/backend"]
|
||||||
|
|
||||||
# Tournament joins the Python workspace when its FastAPI backend is created.
|
|
||||||
# Shared Python infrastructure is introduced only after proven duplication.
|
# Shared Python infrastructure is introduced only after proven duplication.
|
||||||
+5
-1
@@ -1,5 +1,9 @@
|
|||||||
{
|
{
|
||||||
"include": ["apps/shifts/backend/app", "apps/shifts/backend/tests"],
|
"include": ["apps/shifts/backend/app", "apps/shifts/backend/tests", "apps/tournament/backend/app", "apps/tournament/backend/tests"],
|
||||||
|
"executionEnvironments": [
|
||||||
|
{"root": "apps/shifts/backend"},
|
||||||
|
{"root": "apps/tournament/backend"}
|
||||||
|
],
|
||||||
"exclude": ["originals", ".migration", "**/node_modules", "**/__pycache__"],
|
"exclude": ["originals", ".migration", "**/node_modules", "**/__pycache__"],
|
||||||
"venvPath": ".",
|
"venvPath": ".",
|
||||||
"venv": ".venv",
|
"venv": ".venv",
|
||||||
|
|||||||
+18
-2
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
from html.parser import HTMLParser
|
from html.parser import HTMLParser
|
||||||
|
from pathlib import Path
|
||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
from urllib.request import urlopen
|
from urllib.request import urlopen
|
||||||
@@ -22,13 +23,18 @@ class PageResources(HTMLParser):
|
|||||||
self.urls.append(attributes.get("href") or "")
|
self.urls.append(attributes.get("href") or "")
|
||||||
|
|
||||||
|
|
||||||
def check(image: str, port: int, environment: dict[str, str], routes: list[str], proxy_prefix: str = "") -> None:
|
def check(image: str, port: int, environment: dict[str, str], routes: list[str], proxy_prefix: str = "",
|
||||||
|
legacy_fixture: Path | None = None, expected_state: dict | None = None) -> None:
|
||||||
name = f"crr-migration-{uuid4().hex[:12]}"
|
name = f"crr-migration-{uuid4().hex[:12]}"
|
||||||
command = ["docker", "run", "--rm", "--detach", "--name", name,
|
command = ["docker", "run", "--rm", "--detach", "--name", name,
|
||||||
"--tmpfs", "/data:mode=1777", "--publish", f"127.0.0.1::{port}"]
|
"--tmpfs", "/data:mode=1777", "--publish", f"127.0.0.1::{port}"]
|
||||||
for key, value in environment.items():
|
for key, value in environment.items():
|
||||||
command.extend(["--env", f"{key}={value}"])
|
command.extend(["--env", f"{key}={value}"])
|
||||||
|
if legacy_fixture is not None:
|
||||||
|
command.extend(["--mount", f"type=bind,source={legacy_fixture},target=/legacy.sqlite,readonly"])
|
||||||
command.append(image)
|
command.append(image)
|
||||||
|
if legacy_fixture is not None:
|
||||||
|
command.extend(["sh", "-c", "cp /legacy.sqlite /data/tournament.sqlite && exec uvicorn app.main:create_app --factory --host 0.0.0.0 --port 8080 --no-proxy-headers"])
|
||||||
subprocess.run(command, check=True, capture_output=True, text=True)
|
subprocess.run(command, check=True, capture_output=True, text=True)
|
||||||
try:
|
try:
|
||||||
binding = subprocess.check_output(["docker", "port", name, str(port)], text=True).strip()
|
binding = subprocess.check_output(["docker", "port", name, str(port)], text=True).strip()
|
||||||
@@ -48,7 +54,10 @@ def check(image: str, port: int, environment: dict[str, str], routes: list[str],
|
|||||||
assert response.status == 200, route
|
assert response.status == 200, route
|
||||||
body = response.read()
|
body = response.read()
|
||||||
if route == "/api/public/state":
|
if route == "/api/public/state":
|
||||||
assert json.loads(body)["tournament"]["name"] == "Torneio"
|
if expected_state is not None:
|
||||||
|
assert json.loads(body) == expected_state
|
||||||
|
else:
|
||||||
|
assert json.loads(body)["tournament"]["name"] == "Torneio"
|
||||||
elif route in {"/results", "/login"}:
|
elif route in {"/results", "/login"}:
|
||||||
assert b"<html" in body.lower(), route
|
assert b"<html" in body.lower(), route
|
||||||
resources = PageResources()
|
resources = PageResources()
|
||||||
@@ -73,6 +82,13 @@ if __name__ == "__main__":
|
|||||||
"ADMIN_PASSWORD": "migration-smoke-only-password",
|
"ADMIN_PASSWORD": "migration-smoke-only-password",
|
||||||
"SESSION_SECRET": "migration-smoke-only-secret",
|
"SESSION_SECRET": "migration-smoke-only-secret",
|
||||||
}, ["/api/public/state", "/results"], proxy_prefix="/jogo")
|
}, ["/api/public/state", "/results"], proxy_prefix="/jogo")
|
||||||
|
fixtures = Path(__file__).resolve().parents[1] / "migration/fixtures"
|
||||||
|
check("crr-tournament", 8080, {
|
||||||
|
"ADMIN_PASSWORD": "migration-smoke-only-password",
|
||||||
|
"SESSION_SECRET": "migration-smoke-only-secret",
|
||||||
|
}, ["/api/public/state", "/results"], proxy_prefix="/jogo",
|
||||||
|
legacy_fixture=fixtures / "tournament.sqlite",
|
||||||
|
expected_state=json.loads((fixtures / "tournament-state.json").read_text()))
|
||||||
check("crr-shifts", 8000, {
|
check("crr-shifts", 8000, {
|
||||||
"DATABASE_URL": "sqlite:////data/smoke.db",
|
"DATABASE_URL": "sqlite:////data/smoke.db",
|
||||||
"SECRET_KEY": "migration-smoke-only-secret",
|
"SECRET_KEY": "migration-smoke-only-secret",
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"""Run legacy assertions unchanged, replacing only their backend/service transports."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
CONTRACTS = ROOT / "migration/contracts"
|
||||||
|
TEST_FILES = ["src/server/app.integration.test.ts", "src/server/services/calendar.test.ts",
|
||||||
|
"src/server/services/classification.test.ts", "src/server/services/bracket.test.ts",
|
||||||
|
"src/shared/finalSeeding.test.ts"]
|
||||||
|
|
||||||
|
|
||||||
|
def main(freeze: bool = False):
|
||||||
|
if freeze:
|
||||||
|
for name in TEST_FILES:
|
||||||
|
destination = CONTRACTS / name
|
||||||
|
if destination.exists():
|
||||||
|
raise FileExistsError(f"Refusing to overwrite {destination}")
|
||||||
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copyfile(ROOT / "apps/tournament" / name, destination)
|
||||||
|
print("Preserved legacy assertions under migration/contracts without modifying source snapshots.")
|
||||||
|
return
|
||||||
|
modules = ROOT / "apps/tournament/node_modules"
|
||||||
|
if not modules.is_dir():
|
||||||
|
raise RuntimeError("Run make tournament-install first.")
|
||||||
|
work = ROOT / ".migration/port-compat"
|
||||||
|
work.mkdir(parents=True, exist_ok=True)
|
||||||
|
staging = work / "tests"
|
||||||
|
staging.mkdir(parents=True, exist_ok=True)
|
||||||
|
if not (staging / "node_modules").exists():
|
||||||
|
(staging / "node_modules").symlink_to(modules, target_is_directory=True)
|
||||||
|
(staging / "package.json").write_text('{"private":true,"type":"module"}\n')
|
||||||
|
(staging / "vitest.config.mjs").write_text("export default {test:{include:['src/**/python.*.test.ts']}};\n")
|
||||||
|
for name in TEST_FILES:
|
||||||
|
destination = staging / name
|
||||||
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copyfile(CONTRACTS / name, destination)
|
||||||
|
STAGING = staging
|
||||||
|
server = STAGING / "src/server"
|
||||||
|
shutil.copyfile(ROOT / "migration/python_fastify_adapter.mjs", server / "python_fastify_adapter.mjs")
|
||||||
|
shutil.copyfile(ROOT / "migration/python_domain_adapter.mjs", server / "python_domain_adapter.mjs")
|
||||||
|
files = []
|
||||||
|
for source, module, replacement in [
|
||||||
|
(server / "app.integration.test.ts", "./app.js", "./python_fastify_adapter.mjs"),
|
||||||
|
(server / "services/calendar.test.ts", "./calendar.js", "../python_domain_adapter.mjs"),
|
||||||
|
(server / "services/classification.test.ts", "./classification.js", "../python_domain_adapter.mjs"),
|
||||||
|
(server / "services/bracket.test.ts", "./bracket.js", "../python_domain_adapter.mjs"),
|
||||||
|
(STAGING / "src/shared/finalSeeding.test.ts", "./finalSeeding", "../server/python_domain_adapter.mjs"),
|
||||||
|
]:
|
||||||
|
text = source.read_text()
|
||||||
|
original = f"from '{module}'"
|
||||||
|
assert text.count(original) == 1, source
|
||||||
|
destination = source.with_name("python." + source.name)
|
||||||
|
text = text.replace(original, f"from '{replacement}'")
|
||||||
|
if "from './auth.js'" in text:
|
||||||
|
text = text.replace("from './auth.js'", "from './python_fastify_adapter.mjs'")
|
||||||
|
destination.write_text(text)
|
||||||
|
files.append(str(destination.relative_to(STAGING)))
|
||||||
|
env = os.environ | {
|
||||||
|
"TOURNAMENT_BACKEND": str(ROOT / "apps/tournament/backend"),
|
||||||
|
"TOURNAMENT_PYTHON": str(ROOT / ".venv/bin/python"),
|
||||||
|
"TOURNAMENT_WORK": str(work),
|
||||||
|
"TOURNAMENT_BRIDGE": str(ROOT / "migration/python_domain_bridge.py"),
|
||||||
|
"PYTHONDONTWRITEBYTECODE": "1",
|
||||||
|
}
|
||||||
|
result = subprocess.run(["node", str(STAGING / "node_modules/vitest/vitest.mjs"), "run", *files,
|
||||||
|
"--reporter=default", "--reporter=json", f"--outputFile={work / 'tests.json'}"],
|
||||||
|
cwd=STAGING, env=env)
|
||||||
|
if result.returncode == 0:
|
||||||
|
raw = json.loads((work / "tests.json").read_text())
|
||||||
|
report = {
|
||||||
|
"passed": raw["numPassedTests"],
|
||||||
|
"tests": [{"name": test["fullName"], "status": test["status"]}
|
||||||
|
for suite in raw["testResults"] for test in suite["assertionResults"]],
|
||||||
|
"contract_sha256": {name: hashlib.sha256((CONTRACTS / name).read_bytes()).hexdigest()
|
||||||
|
for name in TEST_FILES},
|
||||||
|
}
|
||||||
|
output = ROOT / "migration/phase3"
|
||||||
|
output.mkdir(parents=True, exist_ok=True)
|
||||||
|
(output / "compatibility.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||||
|
raise SystemExit(result.returncode)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--freeze", action="store_true", help="One-time preservation of the unchanged legacy assertions")
|
||||||
|
main(parser.parse_args().freeze)
|
||||||
@@ -5,6 +5,7 @@ requires-python = "==3.13.*"
|
|||||||
[manifest]
|
[manifest]
|
||||||
members = [
|
members = [
|
||||||
"crr-shifts",
|
"crr-shifts",
|
||||||
|
"crr-tournament",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -170,6 +171,39 @@ dev = [
|
|||||||
{ name = "pytest", specifier = ">=8,<9" },
|
{ name = "pytest", specifier = ">=8,<9" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crr-tournament"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = { virtual = "apps/tournament/backend" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "alembic" },
|
||||||
|
{ name = "fastapi" },
|
||||||
|
{ name = "pydantic-settings" },
|
||||||
|
{ name = "sqlalchemy" },
|
||||||
|
{ name = "uvicorn", extra = ["standard"] },
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.dev-dependencies]
|
||||||
|
dev = [
|
||||||
|
{ name = "httpx" },
|
||||||
|
{ name = "pytest" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.metadata]
|
||||||
|
requires-dist = [
|
||||||
|
{ name = "alembic", specifier = ">=1.13,<2" },
|
||||||
|
{ name = "fastapi", specifier = ">=0.115,<1" },
|
||||||
|
{ name = "pydantic-settings", specifier = ">=2.5,<3" },
|
||||||
|
{ name = "sqlalchemy", specifier = ">=2.0,<3" },
|
||||||
|
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.30,<1" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.metadata.requires-dev]
|
||||||
|
dev = [
|
||||||
|
{ name = "httpx", specifier = ">=0.27,<1" },
|
||||||
|
{ name = "pytest", specifier = ">=8,<9" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dnspython"
|
name = "dnspython"
|
||||||
version = "2.8.0"
|
version = "2.8.0"
|
||||||
|
|||||||
Reference in new issue
Block a user