diff --git a/.env.example b/.env.example index f8b7f4e..fbf8e57 100644 --- a/.env.example +++ b/.env.example @@ -9,3 +9,8 @@ DB_USER=root DB_PASSWORD= DB_HOST=127.0.0.1 DB_PORT=3306 + +# Sähköposti ja linkit +SITE_URL=http://127.0.0.1:8000 +EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend +DEFAULT_FROM_EMAIL=toiminnanohjaus@localhost diff --git a/.gitignore b/.gitignore index 53aacd8..7adfb91 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,10 @@ media/ *.sqlite3 .idea/ .vscode/ +node_modules/ +static/dist/ +*.mo +test-results/ +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ diff --git a/CLAUDE.md b/CLAUDE.md index 62a8eb9..99002e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ Toiminnanohjaus is an ERP for a small (5–10 people) Finnish media and marketin - Stack: Django 5.2 LTS, Python 3.14, MariaDB 10.11 (XAMPP in development), HTMX, Alpine.js, Tailwind CSS 4 and daisyUI 5. - Language: code (identifiers, tables, columns, enum keys) is in English. Specs, UI texts, docs and commit messages are in Finnish. -**Current state:** only the project skeleton exists (the `config/` package, MariaDB settings, `.env`). Nothing under `apps/` has been built yet, and the frontend build (`package.json`), pytest, ruff, mypy and import-linter are not set up. `docs/architecture.md` describes the target design. Follow it when you add code, and set up each tool the first time it is needed. +**Current state:** phase 1 item 1 is done: the `shared` module and the `users` module (custom user model, login, password links, user management). It is the reference implementation of the architecture; copy its patterns for new modules. Other modules described in `docs/architecture.md` are not built yet. ## Source of truth @@ -20,32 +20,36 @@ Toiminnanohjaus is an ERP for a small (5–10 people) Finnish media and marketin ```powershell .venv\Scripts\python manage.py runserver # dev server http://127.0.0.1:8000 (start MySQL in XAMPP Control Panel first) -.venv\Scripts\python manage.py check -.venv\Scripts\python manage.py makemigrations -.venv\Scripts\python manage.py migrate -.venv\Scripts\python -m pip install -r requirements.txt -``` +npm run build # vendor htmx/alpine + Tailwind/daisyUI -> static/dist (npm run dev = watch) +.venv\Scripts\python manage.py makemigrations ; .venv\Scripts\python manage.py migrate +.venv\Scripts\python manage.py create_admin "Name" email # prints a password link (email goes to console in dev) -Planned tooling, per `docs/architecture.md` (not set up yet): - -```powershell -.venv\Scripts\pytest apps # all tests -.venv\Scripts\pytest apps/customers/tests/domain/test_x.py::test_name # single test -.venv\Scripts\pytest apps -m "not django_db" # fast tests that don't touch the DB -.venv\Scripts\lint-imports # layer/module dependency rules +.venv\Scripts\pytest apps # unit + integration tests (MariaDB test DB) +.venv\Scripts\pytest apps/users/tests/domain/test_user_account.py::TestCanLogIn::test_inactive_user_cannot_log_in +.venv\Scripts\pytest apps -m "not django_db" # fast tests without DB +.venv\Scripts\pytest tests/browser -m browser # Playwright + axe, light/dark, 1920/320 px; needs npm run build +.venv\Scripts\lint-imports # layer contracts in pyproject.toml .venv\Scripts\mypy apps .venv\Scripts\ruff check . ; .venv\Scripts\ruff format . -npm run dev / npm run build # Tailwind + daisyUI -> static/dist/app.css ``` +Translations: source strings are English; Finnish is in `locale/fi/LC_MESSAGES/django.po`. GNU gettext lives in `%LOCALAPPDATA%\Programs\gettext-iconv\bin` (prepend it to `PATH` if `makemessages` cannot find it). Run `makemessages -l fi --ignore=.venv --ignore=node_modules --ignore=static`, fill every new `msgstr`, then `compilemessages -l fi --ignore=.venv`. Tests assert Finnish texts, so stale `.mo` files make them fail. + ## Configuration - `config/settings.py` reads `.env` via python-dotenv. Variables: `DJANGO_SECRET_KEY` (required), `DJANGO_DEBUG`, `DJANGO_ALLOWED_HOSTS`, `DB_NAME` (default `django-toiminnanohjaus`), `DB_USER`, `DB_PASSWORD`, `DB_HOST`, `DB_PORT`. `.env` is gitignored; `.env.example` is the template. - The database engine is `django.db.backends.mysql` (mysqlclient), with utf8mb4 and `STRICT_TRANS_TABLES`. The database name contains a hyphen, so backtick-quote it in raw SQL. - Settings use `LANGUAGE_CODE = "fi"` and `TIME_ZONE = "Europe/Helsinki"`. Templates go in `templates/` plus app templates, static files in `static/`, and `STATIC_ROOT` is `staticfiles/`. -- **The custom user model `users.User` (`AUTH_USER_MODEL`) does not exist yet.** The database was already migrated with Django's default `auth.User`. Before creating the users app, drop and recreate the (still empty) database, then rerun migrations. +- `AUTH_USER_MODEL = "users.User"` (`apps/users/infrastructure/orm.py`): email login, a role field, no `PermissionsMixin` and no Django admin. Permissions are role-based: `apps/users/domain/permissions.py` (`role_has`), `PermissionRequiredMixin`, and the template filter `{% if request.user|can:"users.manage" %}` (`{% load users_tags %}`). +- `LoginRequiredMiddleware` is on, so mark public views with `login_not_required`. `EnsureAccountIsUsable` logs out deactivated users and interns past their end date on every request. +- The cache is `DatabaseCache` (login throttling), so run `createcachetable` on new databases. +- **Templates and tags:** + - Each module's templates live in `apps//presentation/templates` and are added to `TEMPLATES['DIRS']` by a glob in settings. + - Template tag libraries live in `presentation/templatetags` and must be registered in `TEMPLATES['OPTIONS']['libraries']`. + - Shared layouts and components are in the project `templates/` folder (`base.html`, `layouts/auth.html`, `components/`). +- **Forms:** `FORM_RENDERER` (`apps/shared/presentation/forms.py`) renders every field with `components/field.html`. Forms should mix in `DaisyFormMixin`, which adds the daisyUI classes and `aria-describedby`/`aria-invalid` on errors and provides `add_domain_error(error, ERROR_MESSAGES)`. -## Architecture (target, see `docs/architecture.md`) +## Architecture (see `docs/architecture.md`) The project is a modular monolith. Each business area is a Django app under `apps//` (planned: `shared`, `users`, `customers`, `jobs`, `tasks`, `time_tracking`, `expenses`, `catalog`, `sales`, `billing`, later `inventory`, `machines`). Each app has Clean Architecture layers: @@ -53,7 +57,8 @@ The project is a modular monolith. Each business area is a Django app under `app - `application/` holds use cases (one class, one `execute()`, with dependencies injected through the constructor), frozen dataclass DTOs and query `Protocol`s. Query protocols are the module's public read API. This layer has no `django` imports. - `infrastructure/` holds the Django models (named `…Model`, in `orm.py` and re-exported from the app's `models.py`; set `Meta.db_table` to the table names in spec section 14), the repository implementations and the query implementations, which return DTOs straight from the ORM. - `presentation/` holds thin views, Django Forms and templates. Forms validate input shape and build DTOs. Domain errors are turned into field errors with `form.add_error()`. HTMX requests get partial templates. -- `container.py` is the composition root, with factory functions that wire the use cases. There is no DI framework. +- `container.py` is the composition root, with factory functions that wire the use cases. There is no DI framework. Presentation reaches infrastructure only through the container (import-linter enforces this; add every new module to the contracts in `pyproject.toml`). +- Tests live in `apps//tests/{domain,application,integration}`. Application tests use in-memory fakes (`apps/users/tests/fakes.py` shows the pattern) and need no DB. Cross-cutting rules: @@ -72,6 +77,7 @@ WCAG 2.2 AA / EN 301 549 is the contract's acceptance criterion for the whole UI - After an HTMX swap, move focus deliberately and announce the change in an `aria-live` / `role="status"` region. - Dialogs use `` (the daisyUI modal). - **Layout:** no horizontal page scrolling from 320 px up to FullHD. The machine console needs touch targets of at least 44 × 44 px. -- **Implementation:** use daisyUI classes, with shared partials in `apps/shared/presentation/templates/components/`. Alpine.js is for local UI state only, never for business logic. +- **Implementation:** use daisyUI classes and the shared partials in `templates/components/`. Alpine.js is for local UI state only, never for business logic. +- **Colours:** daisyUI's default text colours fail WCAG contrast in places. `static/src/app.css` overrides soft alerts and badges, `.menu-title`, and the light theme's error and success colours. Use `link` rather than `link-primary` for text links. The browser tests (axe) catch regressions. - **Assets:** no CDN in production; build the assets with npm. - **Texts:** all UI text goes through `gettext` / `{% translate %}`. diff --git a/README.md b/README.md index 8181a0d..a687443 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,12 @@ # Toiminnanohjaus (Django 5.2 LTS) +Määrittely: `docs/maarittely.md`, arkkitehtuuri: `docs/architecture.md`. + ## Vaatimukset - Python 3.14 +- Node.js (Tailwind CSS 4 + daisyUI 5 -build) - XAMPP (vain MariaDB/MySQL käytössä – Apachea tai htdocs-kansiota ei tarvita) +- GNU gettext käännösten kääntämiseen: `winget install mlocati.GetText` ## Käyttöönotto 1. Käynnistä **MySQL** XAMPP Control Panelista. @@ -10,16 +14,41 @@ ```powershell C:\xampp\mysql\bin\mysql.exe -u root -e "CREATE DATABASE IF NOT EXISTS ``django-toiminnanohjaus`` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" ``` -3. Kopioi `.env.example` → `.env` ja täytä arvot (jos ei vielä ole). -4. Asenna riippuvuudet ja aja migraatiot: +3. Kopioi `.env.example` → `.env` ja täytä arvot (`DJANGO_SECRET_KEY` vähintään). +4. Asenna riippuvuudet, rakenna käyttöliittymä ja käännökset, aja migraatiot: ```powershell py -3.14 -m venv .venv - .venv\Scripts\python -m pip install -r requirements.txt + .venv\Scripts\python -m pip install -r requirements-dev.txt + npm install + npm run build + .venv\Scripts\python manage.py compilemessages -l fi --ignore=.venv .venv\Scripts\python manage.py migrate - .venv\Scripts\python manage.py createsuperuser + .venv\Scripts\python manage.py createcachetable ``` -5. Käynnistä kehityspalvelin: +5. Luo ensimmäinen pääkäyttäjä. Salasanan asetuslinkki tulostuu konsoliin (kehityksessä sähköposti tulostuu konsoliin): + ```powershell + .venv\Scripts\python manage.py create_admin "Nimi" osoite@example.fi + ``` +6. Käynnistä kehityspalvelin ja avaa http://127.0.0.1:8000/: ```powershell .venv\Scripts\python manage.py runserver ``` - Avaa http://127.0.0.1:8000/ ja ylläpito http://127.0.0.1:8000/admin/ + Tyylejä muokatessa `npm run dev` rakentaa CSS:n automaattisesti uudelleen. + +## Testit ja tarkistukset +```powershell +.venv\Scripts\pytest apps # domain-, application- ja integraatiotestit +.venv\Scripts\pytest apps -m "not django_db" # nopeat testit ilman tietokantaa +.venv\Scripts\python -m playwright install chromium # kerran +.venv\Scripts\pytest tests/browser -m browser # saavutettavuus (axe) selaimessa, vaatii npm run build +.venv\Scripts\lint-imports # kerrossäännöt +.venv\Scripts\mypy apps +.venv\Scripts\ruff check . ; .venv\Scripts\ruff format . +``` + +## Käännökset +Lähdetekstit ovat englanniksi, suomenkieliset käännökset tiedostossa `locale/fi/LC_MESSAGES/django.po`. +```powershell +.venv\Scripts\python manage.py makemessages -l fi --ignore=.venv --ignore=node_modules --ignore=static +.venv\Scripts\python manage.py compilemessages -l fi --ignore=.venv +``` diff --git a/apps/__init__.py b/apps/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/shared/__init__.py b/apps/shared/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/shared/application/__init__.py b/apps/shared/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/shared/application/ports.py b/apps/shared/application/ports.py new file mode 100644 index 0000000..4281793 --- /dev/null +++ b/apps/shared/application/ports.py @@ -0,0 +1,34 @@ +"""Ports that application layers of all modules depend on.""" + +from collections.abc import Callable +from contextlib import AbstractContextManager +from datetime import date +from types import TracebackType +from typing import Protocol + + +class UnitOfWork(Protocol): + """Transaction boundary of a use case: ``with uow: ...``.""" + + def __enter__(self) -> object: ... + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> bool | None: ... + + +class EventPublisher(Protocol): + def publish(self, event: object) -> None: ... + + +class Clock(Protocol): + def today(self) -> date: + """Current date in the business time zone.""" + ... + + +EventHandler = Callable[[object], None] +TransactionFactory = Callable[[], AbstractContextManager[object]] diff --git a/apps/shared/apps.py b/apps/shared/apps.py new file mode 100644 index 0000000..cd019e4 --- /dev/null +++ b/apps/shared/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class SharedConfig(AppConfig): + name = "apps.shared" + label = "shared" + default_auto_field = "django.db.models.BigAutoField" diff --git a/apps/shared/domain/__init__.py b/apps/shared/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/shared/domain/exceptions.py b/apps/shared/domain/exceptions.py new file mode 100644 index 0000000..02e7f82 --- /dev/null +++ b/apps/shared/domain/exceptions.py @@ -0,0 +1,23 @@ +"""Base class for business rule violations.""" + +from typing import Any + + +class DomainError(Exception): + """A business rule was violated. + + ``code`` identifies the rule; presentation maps it to a translated message. + ``field`` optionally names the input field the error belongs to. + """ + + code: str = "domain_error" + field: str | None = None + + def __init__(self, **params: Any) -> None: + self.params = params + super().__init__(self.code) + + +class InvalidEmailAddress(DomainError): + code = "invalid_email" + field = "email" diff --git a/apps/shared/domain/value_objects.py b/apps/shared/domain/value_objects.py new file mode 100644 index 0000000..b59c117 --- /dev/null +++ b/apps/shared/domain/value_objects.py @@ -0,0 +1,22 @@ +"""Value objects shared by several modules.""" + +import re +from dataclasses import dataclass + +from apps.shared.domain.exceptions import InvalidEmailAddress + +_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") + + +@dataclass(frozen=True, slots=True) +class EmailAddress: + value: str + + def __post_init__(self) -> None: + normalized = self.value.strip().lower() + if len(normalized) > 254 or not _EMAIL_RE.match(normalized): + raise InvalidEmailAddress() + object.__setattr__(self, "value", normalized) + + def __str__(self) -> str: + return self.value diff --git a/apps/shared/infrastructure/__init__.py b/apps/shared/infrastructure/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/shared/infrastructure/clock.py b/apps/shared/infrastructure/clock.py new file mode 100644 index 0000000..facedb7 --- /dev/null +++ b/apps/shared/infrastructure/clock.py @@ -0,0 +1,9 @@ +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from django.conf import settings + + +class DjangoClock: + def today(self) -> date: + return datetime.now(ZoneInfo(settings.BUSINESS_TIME_ZONE)).date() diff --git a/apps/shared/infrastructure/events.py b/apps/shared/infrastructure/events.py new file mode 100644 index 0000000..9042938 --- /dev/null +++ b/apps/shared/infrastructure/events.py @@ -0,0 +1,25 @@ +"""In-process domain event bus. Events are delivered after the transaction commits.""" + +from collections import defaultdict +from collections.abc import Callable +from typing import Any + +from django.db import transaction + +_handlers: dict[type, list[Callable[[Any], None]]] = defaultdict(list) + + +def subscribe(event_type: type, handler: Callable[[Any], None]) -> None: + """Register a handler; call from ``AppConfig.ready()``.""" + if handler not in _handlers[event_type]: + _handlers[event_type].append(handler) + + +def _dispatch(event: object) -> None: + for handler in list(_handlers[type(event)]): + handler(event) + + +class DjangoEventPublisher: + def publish(self, event: object) -> None: + transaction.on_commit(lambda: _dispatch(event)) diff --git a/apps/shared/infrastructure/models.py b/apps/shared/infrastructure/models.py new file mode 100644 index 0000000..6b2e70e --- /dev/null +++ b/apps/shared/infrastructure/models.py @@ -0,0 +1,9 @@ +from django.db import models + + +class TimestampedModel(models.Model): + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + abstract = True diff --git a/apps/shared/infrastructure/unit_of_work.py b/apps/shared/infrastructure/unit_of_work.py new file mode 100644 index 0000000..b76feac --- /dev/null +++ b/apps/shared/infrastructure/unit_of_work.py @@ -0,0 +1,25 @@ +from types import TracebackType + +from django.db import transaction + + +class DjangoUnitOfWork: + """Wraps a use case in ``transaction.atomic``.""" + + def __init__(self) -> None: + self._atomic: transaction.Atomic | None = None + + def __enter__(self) -> DjangoUnitOfWork: + self._atomic = transaction.atomic() + self._atomic.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + assert self._atomic is not None + self._atomic.__exit__(exc_type, exc, tb) + self._atomic = None diff --git a/apps/shared/models.py b/apps/shared/models.py new file mode 100644 index 0000000..277f9ad --- /dev/null +++ b/apps/shared/models.py @@ -0,0 +1 @@ +# The shared app has no concrete models; TimestampedModel is abstract. diff --git a/apps/shared/presentation/__init__.py b/apps/shared/presentation/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/shared/presentation/forms.py b/apps/shared/presentation/forms.py new file mode 100644 index 0000000..94d87b6 --- /dev/null +++ b/apps/shared/presentation/forms.py @@ -0,0 +1,64 @@ +"""Form helpers that give every form the same daisyUI styling and ARIA wiring.""" + +from collections.abc import Mapping +from typing import Any + +from django import forms +from django.forms.renderers import TemplatesSetting +from django.forms.widgets import Input + +from apps.shared.domain.exceptions import DomainError + + +class DaisyFormRenderer(TemplatesSetting): + """Renders ``{{ field.as_field_group }}`` / ``{{ form }}`` with ``components/field.html``.""" + + form_template_name = "components/form.html" + field_template_name = "components/field.html" + + +_WIDGET_CLASSES: list[tuple[type[forms.Widget], str]] = [ + (forms.CheckboxInput, "checkbox"), + (forms.RadioSelect, "radio"), + (forms.CheckboxSelectMultiple, "checkbox"), + (forms.Select, "select w-full"), + (forms.Textarea, "textarea w-full"), + (Input, "input w-full"), +] + + +class DaisyFormMixin: + """Adds daisyUI classes to widgets and links field errors with ``aria-describedby``.""" + + fields: dict[str, forms.Field] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + for field in self.fields.values(): + widget = field.widget + for widget_type, css in _WIDGET_CLASSES: + if isinstance(widget, widget_type): + existing = widget.attrs.get("class", "") + widget.attrs["class"] = f"{css} {existing}".strip() + break + + def full_clean(self) -> None: + super().full_clean() # type: ignore[misc] + form: Any = self + for name in form.errors: + if name not in self.fields: + continue + bound = form[name] + widget = self.fields[name].widget + error_id = f"{bound.auto_id}_error" + described = widget.attrs.get("aria-describedby", "") + if error_id not in described.split(): + widget.attrs["aria-describedby"] = f"{described} {error_id}".strip() + widget.attrs["aria-invalid"] = "true" + + def add_domain_error(self, error: DomainError, messages: Mapping[str, object]) -> None: + """Show a domain rule violation as a field (or non-field) error.""" + form: Any = self + message = str(messages.get(error.code, messages.get("*", error.code))) + field = error.field if error.field in self.fields else None + form.add_error(field, message) diff --git a/apps/shared/presentation/templatetags/__init__.py b/apps/shared/presentation/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/shared/presentation/views.py b/apps/shared/presentation/views.py new file mode 100644 index 0000000..9ddc148 --- /dev/null +++ b/apps/shared/presentation/views.py @@ -0,0 +1,6 @@ +from django.http import HttpRequest, HttpResponse +from django.shortcuts import render + + +def home(request: HttpRequest) -> HttpResponse: + return render(request, "home.html") diff --git a/apps/shared/tests/__init__.py b/apps/shared/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/__init__.py b/apps/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/application/__init__.py b/apps/users/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/application/dto.py b/apps/users/application/dto.py new file mode 100644 index 0000000..20cea16 --- /dev/null +++ b/apps/users/application/dto.py @@ -0,0 +1,63 @@ +from dataclasses import dataclass +from datetime import date, datetime +from enum import StrEnum +from typing import Any, Self + +from apps.users.domain.enums import Role + + +class PasswordLinkPurpose(StrEnum): + SETUP = "setup" # created by an admin: new user or new link, valid 72 h + RESET = "reset" # "forgot password", valid 60 min + + +@dataclass(frozen=True, slots=True) +class UserDetailsData: + name: str + email: str + role: Role + is_active: bool = True + employment_ends_on: date | None = None + supervisor_id: int | None = None + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> Self: + supervisor = data.get("supervisor_id") + return cls( + name=str(data.get("name", "")), + email=str(data.get("email", "")), + role=Role(data["role"]), + is_active=bool(data.get("is_active", True)), + employment_ends_on=data.get("employment_ends_on") or None, + supervisor_id=int(supervisor) if supervisor else None, + ) + + +@dataclass(frozen=True, slots=True) +class UserSummary: + id: int + name: str + email: str + role: Role + is_active: bool + employment_ends_on: date | None + supervisor_name: str | None + + +@dataclass(frozen=True, slots=True) +class SupervisorChoice: + id: int + name: str + + +@dataclass(frozen=True, slots=True) +class PasswordLink: + url: str + expires_at: datetime + emailed: bool = False + + +@dataclass(frozen=True, slots=True) +class CreatedUser: + user_id: int + password_link: PasswordLink diff --git a/apps/users/application/ports.py b/apps/users/application/ports.py new file mode 100644 index 0000000..0c9483d --- /dev/null +++ b/apps/users/application/ports.py @@ -0,0 +1,14 @@ +from typing import Protocol + +from apps.users.application.dto import PasswordLink, PasswordLinkPurpose +from apps.users.domain.entities import UserAccount + + +class PasswordLinkService(Protocol): + def issue(self, user_id: int, purpose: PasswordLinkPurpose) -> PasswordLink: + """Create a single-use link; any earlier link of the user stops working.""" + ... + + def send(self, user: UserAccount, link: PasswordLink, purpose: PasswordLinkPurpose) -> bool: + """Email the link. Returns False (and logs) if sending fails.""" + ... diff --git a/apps/users/application/queries.py b/apps/users/application/queries.py new file mode 100644 index 0000000..fdd84a8 --- /dev/null +++ b/apps/users/application/queries.py @@ -0,0 +1,19 @@ +from collections.abc import Sequence +from typing import Protocol + +from apps.users.application.dto import SupervisorChoice, UserDetailsData, UserSummary +from apps.users.domain.enums import Role + + +class UserQueries(Protocol): + def list_users( + self, *, search: str = "", role: Role | None = None, is_active: bool | None = None + ) -> Sequence[UserSummary]: ... + + def get_details(self, user_id: int) -> UserDetailsData | None: ... + + def get_summary(self, user_id: int) -> UserSummary | None: ... + + def supervisor_choices(self, *, exclude_id: int | None = None) -> Sequence[SupervisorChoice]: + """Active management and employee users.""" + ... diff --git a/apps/users/application/use_cases.py b/apps/users/application/use_cases.py new file mode 100644 index 0000000..f2a503a --- /dev/null +++ b/apps/users/application/use_cases.py @@ -0,0 +1,150 @@ +from dataclasses import replace + +from apps.shared.application.ports import Clock, UnitOfWork +from apps.shared.domain.exceptions import InvalidEmailAddress +from apps.shared.domain.value_objects import EmailAddress +from apps.users.application.dto import ( + CreatedUser, + PasswordLink, + PasswordLinkPurpose, + UserDetailsData, +) +from apps.users.application.ports import PasswordLinkService +from apps.users.domain.entities import UserAccount +from apps.users.domain.exceptions import ( + EmailAlreadyTaken, + InvalidSupervisor, + LastActiveAdmin, + SupervisorHasInterns, + UserNotFound, +) +from apps.users.domain.repositories import UserRepository +from apps.users.domain.value_objects import PersonName + + +def _check_supervisor(repo: UserRepository, user: UserAccount) -> None: + if user.supervisor_id is None: + return + supervisor = repo.get_by_id(user.supervisor_id) + if supervisor is None or not supervisor.can_supervise or supervisor.id == user.id: + raise InvalidSupervisor() + + +class CreateUser: + """An admin creates a user; the user sets the password with a 72 h link.""" + + def __init__(self, repo: UserRepository, uow: UnitOfWork, links: PasswordLinkService) -> None: + self.repo = repo + self.uow = uow + self.links = links + + def execute(self, data: UserDetailsData) -> CreatedUser: + name = PersonName(data.name) + email = EmailAddress(data.email) + with self.uow: + if self.repo.is_email_taken(email): + raise EmailAlreadyTaken() + user = UserAccount.register( + name=name, + email=email, + role=data.role, + employment_ends_on=data.employment_ends_on, + supervisor_id=data.supervisor_id, + ) + _check_supervisor(self.repo, user) + user = self.repo.save(user) + assert user.id is not None + link = self.links.issue(user.id, PasswordLinkPurpose.SETUP) + # Email is sent outside the transaction: a mail failure must not undo the user. + emailed = self.links.send(user, link, PasswordLinkPurpose.SETUP) + return CreatedUser(user_id=user.id, password_link=replace(link, emailed=emailed)) + + +class UpdateUser: + def __init__(self, repo: UserRepository, uow: UnitOfWork) -> None: + self.repo = repo + self.uow = uow + + def execute(self, user_id: int, data: UserDetailsData) -> None: + name = PersonName(data.name) + email = EmailAddress(data.email) + with self.uow: + current = self.repo.get_by_id(user_id) + if current is None: + raise UserNotFound() + if self.repo.is_email_taken(email, exclude_id=user_id): + raise EmailAlreadyTaken() + updated = current.update_details( + name=name, + email=email, + role=data.role, + is_active=data.is_active, + employment_ends_on=data.employment_ends_on, + supervisor_id=data.supervisor_id, + ) + _check_supervisor(self.repo, updated) + # The count locks the admin rows, so two concurrent changes cannot remove the last one. + if ( + current.is_active_admin + and not updated.is_active_admin + and self.repo.lock_active_admin_count() <= 1 + ): + raise LastActiveAdmin() + if ( + current.can_supervise + and not updated.can_supervise + and self.repo.has_active_interns(user_id) + ): + raise SupervisorHasInterns() + self.repo.save(updated) + + +class IssuePasswordLink: + """An admin creates a new 72 h link for an existing user (shown and emailed).""" + + def __init__(self, repo: UserRepository, links: PasswordLinkService) -> None: + self.repo = repo + self.links = links + + def execute(self, user_id: int) -> PasswordLink: + user = self.repo.get_by_id(user_id) + if user is None: + raise UserNotFound() + link = self.links.issue(user_id, PasswordLinkPurpose.SETUP) + emailed = self.links.send(user, link, PasswordLinkPurpose.SETUP) + return replace(link, emailed=emailed) + + +class RequestPasswordReset: + """Forgot password: emails a 60 min link only to users allowed to log in today. + + The caller always shows the same message, so the page does not reveal which emails exist. + """ + + def __init__(self, repo: UserRepository, links: PasswordLinkService, clock: Clock) -> None: + self.repo = repo + self.links = links + self.clock = clock + + def execute(self, email: str) -> None: + try: + address = EmailAddress(email) + except InvalidEmailAddress: + return + user = self.repo.get_by_email(address) + if user is None or user.id is None or not user.can_log_in(self.clock.today()): + return + link = self.links.issue(user.id, PasswordLinkPurpose.RESET) + self.links.send(user, link, PasswordLinkPurpose.RESET) + + +class CheckLoginAllowed: + """A user may log in (and keep a session) while active and, for interns, until the end date.""" + + def __init__(self, repo: UserRepository, clock: Clock) -> None: + self.repo = repo + self.clock = clock + + def execute(self, user_id: int) -> bool: + user = self.repo.get_by_id(user_id) + return user is not None and user.can_log_in(self.clock.today()) diff --git a/apps/users/apps.py b/apps/users/apps.py new file mode 100644 index 0000000..3574c16 --- /dev/null +++ b/apps/users/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + name = "apps.users" + label = "users" + default_auto_field = "django.db.models.BigAutoField" diff --git a/apps/users/container.py b/apps/users/container.py new file mode 100644 index 0000000..fdd5460 --- /dev/null +++ b/apps/users/container.py @@ -0,0 +1,55 @@ +"""Composition root of the users module: wires use cases to their implementations.""" + +from apps.shared.infrastructure.clock import DjangoClock +from apps.shared.infrastructure.unit_of_work import DjangoUnitOfWork +from apps.users.application.dto import PasswordLinkPurpose +from apps.users.application.queries import UserQueries +from apps.users.application.use_cases import ( + CheckLoginAllowed, + CreateUser, + IssuePasswordLink, + RequestPasswordReset, + UpdateUser, +) +from apps.users.infrastructure.orm import User +from apps.users.infrastructure.password_links import DjangoPasswordLinkService +from apps.users.infrastructure.queries import DjangoUserQueries +from apps.users.infrastructure.repositories import DjangoUserRepository +from apps.users.infrastructure.throttle import LoginThrottle +from apps.users.infrastructure.tokens import token_generator + + +def create_user() -> CreateUser: + return CreateUser(DjangoUserRepository(), DjangoUnitOfWork(), DjangoPasswordLinkService()) + + +def update_user() -> UpdateUser: + return UpdateUser(DjangoUserRepository(), DjangoUnitOfWork()) + + +def issue_password_link() -> IssuePasswordLink: + return IssuePasswordLink(DjangoUserRepository(), DjangoPasswordLinkService()) + + +def request_password_reset() -> RequestPasswordReset: + return RequestPasswordReset(DjangoUserRepository(), DjangoPasswordLinkService(), DjangoClock()) + + +def check_login_allowed() -> CheckLoginAllowed: + return CheckLoginAllowed(DjangoUserRepository(), DjangoClock()) + + +def user_queries() -> UserQueries: + return DjangoUserQueries() + + +def login_throttle() -> LoginThrottle: + return LoginThrottle() + + +def user_for_password_link(user_id: int, purpose: PasswordLinkPurpose, token: str) -> User | None: + """The auth user a valid password link belongs to (Django's SetPasswordForm needs it).""" + user = User.objects.filter(pk=user_id).first() + if user is None or not token_generator(purpose).check_token(user, token): + return None + return user diff --git a/apps/users/domain/__init__.py b/apps/users/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/domain/entities.py b/apps/users/domain/entities.py new file mode 100644 index 0000000..ae88f01 --- /dev/null +++ b/apps/users/domain/entities.py @@ -0,0 +1,125 @@ +from dataclasses import dataclass, replace +from datetime import date +from typing import Self + +from apps.shared.domain.value_objects import EmailAddress +from apps.users.domain.enums import Role +from apps.users.domain.exceptions import ( + InternRequiresEndDate, + InternRequiresSupervisor, + InvalidSupervisor, +) +from apps.users.domain.value_objects import PersonName + + +@dataclass(frozen=True, slots=True) +class UserAccount: + """Business view of a user (specification 2.1, 2.2). + + Invariant: an intern always has an end date and a supervisor; other roles never have them. + """ + + id: int | None + name: PersonName + email: EmailAddress + role: Role + is_active: bool + employment_ends_on: date | None + supervisor_id: int | None + + @classmethod + def register( + cls, + *, + name: PersonName, + email: EmailAddress, + role: Role, + employment_ends_on: date | None = None, + supervisor_id: int | None = None, + ) -> Self: + return cls._validated( + id=None, + name=name, + email=email, + role=role, + is_active=True, + employment_ends_on=employment_ends_on, + supervisor_id=supervisor_id, + ) + + @classmethod + def reconstitute( + cls, + *, + id: int, + name: PersonName, + email: EmailAddress, + role: Role, + is_active: bool, + employment_ends_on: date | None, + supervisor_id: int | None, + ) -> Self: + """Rebuild a stored user without checking rules, so a bad row cannot break login.""" + return cls(id, name, email, role, is_active, employment_ends_on, supervisor_id) + + def update_details( + self, + *, + name: PersonName, + email: EmailAddress, + role: Role, + is_active: bool, + employment_ends_on: date | None, + supervisor_id: int | None, + ) -> Self: + return self._validated( + id=self.id, + name=name, + email=email, + role=role, + is_active=is_active, + employment_ends_on=employment_ends_on, + supervisor_id=supervisor_id, + ) + + def with_id(self, id: int) -> Self: + return replace(self, id=id) + + def can_log_in(self, today: date) -> bool: + if not self.is_active: + return False + if self.role is Role.INTERN: + return self.employment_ends_on is not None and self.employment_ends_on >= today + return True + + @property + def is_active_admin(self) -> bool: + return self.is_active and self.role is Role.ADMIN + + @property + def can_supervise(self) -> bool: + return self.is_active and self.role.can_supervise_interns + + @classmethod + def _validated( + cls, + *, + id: int | None, + name: PersonName, + email: EmailAddress, + role: Role, + is_active: bool, + employment_ends_on: date | None, + supervisor_id: int | None, + ) -> Self: + if role is Role.INTERN: + if employment_ends_on is None: + raise InternRequiresEndDate() + if supervisor_id is None: + raise InternRequiresSupervisor() + if id is not None and supervisor_id == id: + raise InvalidSupervisor() + else: + employment_ends_on = None + supervisor_id = None + return cls(id, name, email, role, is_active, employment_ends_on, supervisor_id) diff --git a/apps/users/domain/enums.py b/apps/users/domain/enums.py new file mode 100644 index 0000000..6060d0a --- /dev/null +++ b/apps/users/domain/enums.py @@ -0,0 +1,20 @@ +from enum import StrEnum + + +class Role(StrEnum): + """User roles (specification 2.2). Public: other modules may use it for authorization.""" + + ADMIN = "admin" + MANAGEMENT = "management" + EMPLOYEE = "employee" + INTERN = "intern" + SUBCONTRACTOR = "subcontractor" + + @property + def can_supervise_interns(self) -> bool: + return self in (Role.MANAGEMENT, Role.EMPLOYEE) + + +class Permission(StrEnum): + USERS_MANAGE = "users.manage" + CUSTOMERS_USE = "customers.use" diff --git a/apps/users/domain/exceptions.py b/apps/users/domain/exceptions.py new file mode 100644 index 0000000..841f784 --- /dev/null +++ b/apps/users/domain/exceptions.py @@ -0,0 +1,44 @@ +from apps.shared.domain.exceptions import DomainError + + +class InvalidPersonName(DomainError): + code = "invalid_name" + field = "name" + + +class InternRequiresEndDate(DomainError): + code = "intern_requires_end_date" + field = "employment_ends_on" + + +class InternRequiresSupervisor(DomainError): + code = "intern_requires_supervisor" + field = "supervisor_id" + + +class InvalidSupervisor(DomainError): + """The supervisor must be an active management or employee user, not the user itself.""" + + code = "invalid_supervisor" + field = "supervisor_id" + + +class EmailAlreadyTaken(DomainError): + code = "email_taken" + field = "email" + + +class LastActiveAdmin(DomainError): + """The last active admin cannot be deactivated or moved to another role.""" + + code = "last_active_admin" + + +class SupervisorHasInterns(DomainError): + """A supervisor of active interns cannot be deactivated or moved to a non-supervising role.""" + + code = "supervisor_has_interns" + + +class UserNotFound(DomainError): + code = "user_not_found" diff --git a/apps/users/domain/permissions.py b/apps/users/domain/permissions.py new file mode 100644 index 0000000..29f82ea --- /dev/null +++ b/apps/users/domain/permissions.py @@ -0,0 +1,14 @@ +"""Role based permissions (specification 2.4). Extended module by module.""" + +from apps.users.domain.enums import Permission, Role + +_ALL_EXCEPT_SUBCONTRACTOR = frozenset({Role.ADMIN, Role.MANAGEMENT, Role.EMPLOYEE, Role.INTERN}) + +_PERMISSIONS: dict[Permission, frozenset[Role]] = { + Permission.USERS_MANAGE: frozenset({Role.ADMIN}), + Permission.CUSTOMERS_USE: _ALL_EXCEPT_SUBCONTRACTOR, +} + + +def role_has(role: Role, permission: Permission) -> bool: + return role in _PERMISSIONS.get(permission, frozenset()) diff --git a/apps/users/domain/repositories.py b/apps/users/domain/repositories.py new file mode 100644 index 0000000..f2b8808 --- /dev/null +++ b/apps/users/domain/repositories.py @@ -0,0 +1,22 @@ +from typing import Protocol + +from apps.shared.domain.value_objects import EmailAddress +from apps.users.domain.entities import UserAccount + + +class UserRepository(Protocol): + def get_by_id(self, user_id: int) -> UserAccount | None: ... + + def get_by_email(self, email: EmailAddress) -> UserAccount | None: ... + + def save(self, user: UserAccount) -> UserAccount: + """Insert or update; a new user gets its id here.""" + ... + + def is_email_taken(self, email: EmailAddress, *, exclude_id: int | None = None) -> bool: ... + + def lock_active_admin_count(self) -> int: + """Lock the active admin rows for the transaction and return their number.""" + ... + + def has_active_interns(self, supervisor_id: int) -> bool: ... diff --git a/apps/users/domain/value_objects.py b/apps/users/domain/value_objects.py new file mode 100644 index 0000000..75d60a5 --- /dev/null +++ b/apps/users/domain/value_objects.py @@ -0,0 +1,17 @@ +from dataclasses import dataclass + +from apps.users.domain.exceptions import InvalidPersonName + + +@dataclass(frozen=True, slots=True) +class PersonName: + value: str + + def __post_init__(self) -> None: + normalized = " ".join(self.value.split()) + if not normalized or len(normalized) > 150: + raise InvalidPersonName() + object.__setattr__(self, "value", normalized) + + def __str__(self) -> str: + return self.value diff --git a/apps/users/infrastructure/__init__.py b/apps/users/infrastructure/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/infrastructure/auth.py b/apps/users/infrastructure/auth.py new file mode 100644 index 0000000..f8bbcae --- /dev/null +++ b/apps/users/infrastructure/auth.py @@ -0,0 +1,39 @@ +from typing import Any + +from django.contrib.auth.backends import BaseBackend +from django.http import HttpRequest + +from apps.shared.infrastructure.clock import DjangoClock +from apps.users.application.use_cases import CheckLoginAllowed +from apps.users.infrastructure.orm import User +from apps.users.infrastructure.repositories import DjangoUserRepository + + +class EmailBackend(BaseBackend): + """Email + password login; the user must be allowed to log in today (CheckLoginAllowed).""" + + def authenticate( + self, + request: HttpRequest | None, + username: str | None = None, + password: str | None = None, + email: str | None = None, + **kwargs: Any, + ) -> User | None: + address = (email or username or "").strip().lower() + if not address or password is None: + return None + user = User.objects.filter(email__iexact=address).first() + if user is None: + # Run the hasher anyway so response time does not reveal unknown emails. + User().set_password(password) + return None + if user.check_password(password) and self.user_can_authenticate(user): + return user + return None + + def user_can_authenticate(self, user: User) -> bool: + return CheckLoginAllowed(DjangoUserRepository(), DjangoClock()).execute(user.pk) + + def get_user(self, user_id: int) -> User | None: + return User.objects.filter(pk=user_id).first() diff --git a/apps/users/infrastructure/orm.py b/apps/users/infrastructure/orm.py new file mode 100644 index 0000000..b699a36 --- /dev/null +++ b/apps/users/infrastructure/orm.py @@ -0,0 +1,76 @@ +from typing import Any + +from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager +from django.db import models + +from apps.shared.infrastructure.models import TimestampedModel +from apps.users.domain.enums import Role + + +class UserManager(BaseUserManager["User"]): + use_in_migrations = True + + def create_user(self, email: str, name: str, password: str | None = None, **extra: Any) -> User: + user = self.model(email=self.normalize_email(email).lower(), name=name, **extra) + if password: + user.set_password(password) + else: + user.set_unusable_password() + user.save(using=self._db) + return user + + def create_superuser( + self, email: str, name: str, password: str | None = None, **extra: Any + ) -> User: + extra.setdefault("role", Role.ADMIN.value) + return self.create_user(email, name, password, **extra) + + +class User(AbstractBaseUser, TimestampedModel): + """Persistence model of users.UserAccount and Django's AUTH_USER_MODEL. + + Business rules live in the domain entity; change users through the use cases. + """ + + email = models.EmailField(unique=True, max_length=254) + name = models.CharField(max_length=150) + role = models.CharField(max_length=20, default=Role.EMPLOYEE.value) + is_active = models.BooleanField(default=True) + employment_ends_on = models.DateField(null=True, blank=True) + supervisor = models.ForeignKey( + "self", null=True, blank=True, on_delete=models.PROTECT, related_name="interns" + ) + # Incremented whenever a password link is issued; earlier links then stop working. + password_link_nonce = models.PositiveIntegerField(default=0) + + objects = UserManager() + + USERNAME_FIELD = "email" + EMAIL_FIELD = "email" + REQUIRED_FIELDS = ["name"] + + class Meta: + db_table = "users" + ordering = ["name"] + + def __str__(self) -> str: + return self.name + + @property + def role_enum(self) -> Role: + return Role(self.role) + + # Django admin is not used; these keep third-party code that asks happy. + @property + def is_staff(self) -> bool: + return False + + @property + def is_superuser(self) -> bool: + return False + + def has_perm(self, perm: str, obj: object = None) -> bool: + return False + + def has_module_perms(self, app_label: str) -> bool: + return False diff --git a/apps/users/infrastructure/password.py b/apps/users/infrastructure/password.py new file mode 100644 index 0000000..0f33b94 --- /dev/null +++ b/apps/users/infrastructure/password.py @@ -0,0 +1,50 @@ +from django.core.exceptions import ValidationError +from django.utils.translation import gettext as _ + + +class ComplexityValidator: + """At least 12 characters with upper and lower case letters, a digit and a special character.""" + + min_length = 12 + + def validate(self, password: str, user: object = None) -> None: + errors: list[ValidationError] = [] + if len(password) < self.min_length: + errors.append( + ValidationError( + _("The password must be at least %(min)d characters long.") + % {"min": self.min_length}, + code="password_too_short", + ) + ) + checks = [ + ( + any(c.isupper() for c in password), + _("The password must contain an upper case letter."), + "password_no_upper", + ), + ( + any(c.islower() for c in password), + _("The password must contain a lower case letter."), + "password_no_lower", + ), + ( + any(c.isdigit() for c in password), + _("The password must contain a digit."), + "password_no_digit", + ), + ( + any(not c.isalnum() and not c.isspace() for c in password), + _("The password must contain a special character."), + "password_no_special", + ), + ] + errors += [ValidationError(message, code=code) for ok, message, code in checks if not ok] + if errors: + raise ValidationError(errors) + + def get_help_text(self) -> str: + return _( + "At least %(min)d characters, including upper and lower case letters, " + "a digit and a special character." + ) % {"min": self.min_length} diff --git a/apps/users/infrastructure/password_links.py b/apps/users/infrastructure/password_links.py new file mode 100644 index 0000000..e57bb41 --- /dev/null +++ b/apps/users/infrastructure/password_links.py @@ -0,0 +1,53 @@ +import logging +from datetime import timedelta + +from django.conf import settings +from django.core.mail import send_mail +from django.db.models import F +from django.template.loader import render_to_string +from django.urls import reverse +from django.utils import timezone +from django.utils.encoding import force_bytes +from django.utils.http import urlsafe_base64_encode + +from apps.users.application.dto import PasswordLink, PasswordLinkPurpose +from apps.users.domain.entities import UserAccount +from apps.users.infrastructure.orm import User +from apps.users.infrastructure.tokens import token_generator + +logger = logging.getLogger(__name__) + + +class DjangoPasswordLinkService: + def issue(self, user_id: int, purpose: PasswordLinkPurpose) -> PasswordLink: + User.objects.filter(pk=user_id).update(password_link_nonce=F("password_link_nonce") + 1) + user = User.objects.get(pk=user_id) + generator = token_generator(purpose) + path = reverse( + "users:set_password", + kwargs={ + "purpose": purpose.value, + "uidb64": urlsafe_base64_encode(force_bytes(user.pk)), + "token": generator.make_token(user), + }, + ) + return PasswordLink( + url=f"{settings.SITE_URL.rstrip('/')}{path}", + expires_at=timezone.now() + timedelta(seconds=generator.timeout_seconds), + ) + + def send(self, user: UserAccount, link: PasswordLink, purpose: PasswordLinkPurpose) -> bool: + context = { + "name": user.name.value, + "url": link.url, + "expires_at": link.expires_at, + "purpose": purpose.value, + } + subject = render_to_string("users/email/password_link_subject.txt", context).strip() + body = render_to_string("users/email/password_link.txt", context) + try: + send_mail(subject, body, None, [user.email.value]) + except Exception: + logger.exception("Sending the password link to user %s failed", user.id) + return False + return True diff --git a/apps/users/infrastructure/queries.py b/apps/users/infrastructure/queries.py new file mode 100644 index 0000000..3bdfdf9 --- /dev/null +++ b/apps/users/infrastructure/queries.py @@ -0,0 +1,58 @@ +from collections.abc import Sequence + +from django.db.models import Q + +from apps.users.application.dto import SupervisorChoice, UserDetailsData, UserSummary +from apps.users.domain.enums import Role +from apps.users.infrastructure.orm import User + + +def _summary(user: User) -> UserSummary: + return UserSummary( + id=user.pk, + name=user.name, + email=user.email, + role=Role(user.role), + is_active=user.is_active, + employment_ends_on=user.employment_ends_on, + supervisor_name=user.supervisor.name if user.supervisor else None, + ) + + +class DjangoUserQueries: + def list_users( + self, *, search: str = "", role: Role | None = None, is_active: bool | None = None + ) -> Sequence[UserSummary]: + qs = User.objects.select_related("supervisor").order_by("name", "pk") + if search: + qs = qs.filter(Q(name__icontains=search) | Q(email__icontains=search)) + if role is not None: + qs = qs.filter(role=role.value) + if is_active is not None: + qs = qs.filter(is_active=is_active) + return [_summary(u) for u in qs] + + def get_details(self, user_id: int) -> UserDetailsData | None: + user = User.objects.filter(pk=user_id).first() + if user is None: + return None + return UserDetailsData( + name=user.name, + email=user.email, + role=Role(user.role), + is_active=user.is_active, + employment_ends_on=user.employment_ends_on, + supervisor_id=user.supervisor_id, + ) + + def get_summary(self, user_id: int) -> UserSummary | None: + user = User.objects.select_related("supervisor").filter(pk=user_id).first() + return _summary(user) if user else None + + def supervisor_choices(self, *, exclude_id: int | None = None) -> Sequence[SupervisorChoice]: + qs = User.objects.filter( + is_active=True, role__in=[Role.MANAGEMENT.value, Role.EMPLOYEE.value] + ).order_by("name") + if exclude_id is not None: + qs = qs.exclude(pk=exclude_id) + return [SupervisorChoice(id=u.pk, name=u.name) for u in qs] diff --git a/apps/users/infrastructure/repositories.py b/apps/users/infrastructure/repositories.py new file mode 100644 index 0000000..457b2c4 --- /dev/null +++ b/apps/users/infrastructure/repositories.py @@ -0,0 +1,57 @@ +from apps.shared.domain.value_objects import EmailAddress +from apps.users.domain.entities import UserAccount +from apps.users.domain.enums import Role +from apps.users.domain.value_objects import PersonName +from apps.users.infrastructure.orm import User + + +def to_entity(model: User) -> UserAccount: + return UserAccount.reconstitute( + id=model.pk, + name=PersonName(model.name), + email=EmailAddress(model.email), + role=Role(model.role), + is_active=model.is_active, + employment_ends_on=model.employment_ends_on, + supervisor_id=model.supervisor_id, + ) + + +class DjangoUserRepository: + def get_by_id(self, user_id: int) -> UserAccount | None: + model = User.objects.filter(pk=user_id).first() + return to_entity(model) if model else None + + def get_by_email(self, email: EmailAddress) -> UserAccount | None: + model = User.objects.filter(email__iexact=email.value).first() + return to_entity(model) if model else None + + def save(self, user: UserAccount) -> UserAccount: + if user.id is None: + model = User(password="") + model.set_unusable_password() + else: + model = User.objects.get(pk=user.id) + model.name = user.name.value + model.email = user.email.value + model.role = user.role.value + model.is_active = user.is_active + model.employment_ends_on = user.employment_ends_on + model.supervisor_id = user.supervisor_id + model.save() + return user.with_id(model.pk) + + def is_email_taken(self, email: EmailAddress, *, exclude_id: int | None = None) -> bool: + qs = User.objects.filter(email__iexact=email.value) + if exclude_id is not None: + qs = qs.exclude(pk=exclude_id) + return qs.exists() + + def lock_active_admin_count(self) -> int: + rows = User.objects.select_for_update().filter(is_active=True, role=Role.ADMIN.value) + return len(list(rows.values_list("pk", flat=True))) + + def has_active_interns(self, supervisor_id: int) -> bool: + return User.objects.filter( + supervisor_id=supervisor_id, is_active=True, role=Role.INTERN.value + ).exists() diff --git a/apps/users/infrastructure/throttle.py b/apps/users/infrastructure/throttle.py new file mode 100644 index 0000000..7dd74d5 --- /dev/null +++ b/apps/users/infrastructure/throttle.py @@ -0,0 +1,28 @@ +"""Login attempt limit: 5 failed attempts per email + IP within 5 minutes.""" + +import hashlib + +from django.core.cache import cache + +MAX_ATTEMPTS = 5 +WINDOW_SECONDS = 5 * 60 + + +class LoginThrottle: + def _key(self, email: str, ip: str) -> str: + digest = hashlib.sha256(f"{email.strip().lower()}|{ip}".encode()).hexdigest() + return f"login-attempts:{digest}" + + def is_blocked(self, email: str, ip: str) -> bool: + return int(cache.get(self._key(email, ip), 0)) >= MAX_ATTEMPTS + + def register_failure(self, email: str, ip: str) -> None: + key = self._key(email, ip) + if not cache.add(key, 1, WINDOW_SECONDS): + try: + cache.incr(key) + except ValueError: + cache.set(key, 1, WINDOW_SECONDS) + + def reset(self, email: str, ip: str) -> None: + cache.delete(self._key(email, ip)) diff --git a/apps/users/infrastructure/tokens.py b/apps/users/infrastructure/tokens.py new file mode 100644 index 0000000..a2dc03f --- /dev/null +++ b/apps/users/infrastructure/tokens.py @@ -0,0 +1,51 @@ +"""Single-use password links with per-purpose lifetimes (specification 3).""" + +from typing import Any + +from django.conf import settings +from django.contrib.auth.tokens import PasswordResetTokenGenerator +from django.utils.crypto import constant_time_compare +from django.utils.http import base36_to_int + +from apps.users.application.dto import PasswordLinkPurpose + + +class PasswordLinkTokenGenerator(PasswordResetTokenGenerator): + """Token that stops working when the password is set or a newer link is issued. + + The hash covers the password hash (changes when the password is set: single use) + and ``password_link_nonce`` (incremented for every new link: older links die). + """ + + def __init__(self, purpose: PasswordLinkPurpose, timeout_seconds: int) -> None: + super().__init__() + self.purpose = purpose + self.timeout_seconds = timeout_seconds + self.key_salt = f"apps.users.password_link.{purpose.value}" + + def _make_hash_value(self, user: Any, timestamp: int) -> str: + return f"{user.pk}{user.password}{user.password_link_nonce}{timestamp}{user.email}" + + def check_token(self, user: Any, token: str | None) -> bool: + if not (user and token): + return False + try: + ts_b36, _ = token.split("-") + ts = base36_to_int(ts_b36) + except ValueError: + return False + for secret in [self.secret, *self.secret_fallbacks]: + if constant_time_compare(self._make_token_with_timestamp(user, ts, secret), token): + break + else: + return False + return (self._num_seconds(self._now()) - ts) <= self.timeout_seconds + + +def token_generator(purpose: PasswordLinkPurpose) -> PasswordLinkTokenGenerator: + timeout = ( + settings.PASSWORD_LINK_SETUP_TIMEOUT + if purpose is PasswordLinkPurpose.SETUP + else settings.PASSWORD_RESET_TIMEOUT + ) + return PasswordLinkTokenGenerator(purpose, timeout) diff --git a/apps/users/management/__init__.py b/apps/users/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/management/commands/__init__.py b/apps/users/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/management/commands/create_admin.py b/apps/users/management/commands/create_admin.py new file mode 100644 index 0000000..4b52470 --- /dev/null +++ b/apps/users/management/commands/create_admin.py @@ -0,0 +1,31 @@ +from typing import Any + +from django.core.management.base import BaseCommand, CommandError, CommandParser + +from apps.shared.domain.exceptions import DomainError +from apps.users.application.dto import UserDetailsData +from apps.users.container import create_user +from apps.users.domain.enums import Role + + +class Command(BaseCommand): + help = 'Creates an admin user and prints a password link: create_admin "Name" email' + + def add_arguments(self, parser: CommandParser) -> None: + parser.add_argument("name") + parser.add_argument("email") + + def handle(self, *args: Any, **options: Any) -> None: + data = UserDetailsData(name=options["name"], email=options["email"], role=Role.ADMIN) + try: + created = create_user().execute(data) + except DomainError as error: + raise CommandError(f"Could not create the admin: {error.code}") from error + link = created.password_link + self.stdout.write(self.style.SUCCESS(f"Admin created (id {created.user_id}).")) + self.stdout.write(f"Password link (valid until {link.expires_at:%Y-%m-%d %H:%M} UTC):") + self.stdout.write(link.url) + if not link.emailed: + self.stdout.write( + self.style.WARNING("Sending the email failed; deliver the link yourself.") + ) diff --git a/apps/users/migrations/0001_initial.py b/apps/users/migrations/0001_initial.py new file mode 100644 index 0000000..f07a1b8 --- /dev/null +++ b/apps/users/migrations/0001_initial.py @@ -0,0 +1,41 @@ +# Generated by Django 5.2.19 on 2026-11-29 10:10 + +import apps.users.infrastructure.orm +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('email', models.EmailField(max_length=254, unique=True)), + ('name', models.CharField(max_length=150)), + ('role', models.CharField(default='employee', max_length=20)), + ('is_active', models.BooleanField(default=True)), + ('employment_ends_on', models.DateField(blank=True, null=True)), + ('password_link_nonce', models.PositiveIntegerField(default=0)), + ('supervisor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='interns', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'db_table': 'users', + 'ordering': ['name'], + }, + managers=[ + ('objects', apps.users.infrastructure.orm.UserManager()), + ], + ), + ] diff --git a/apps/users/migrations/__init__.py b/apps/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/models.py b/apps/users/models.py new file mode 100644 index 0000000..51297b4 --- /dev/null +++ b/apps/users/models.py @@ -0,0 +1,4 @@ +# Django discovers the module's ORM models through this file. +from apps.users.infrastructure.orm import User + +__all__ = ["User"] diff --git a/apps/users/presentation/__init__.py b/apps/users/presentation/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/presentation/forms.py b/apps/users/presentation/forms.py new file mode 100644 index 0000000..e8dd4dd --- /dev/null +++ b/apps/users/presentation/forms.py @@ -0,0 +1,121 @@ +from collections.abc import Sequence +from typing import Any + +from django import forms +from django.contrib.auth import password_validation +from django.contrib.auth.forms import AuthenticationForm, SetPasswordForm +from django.utils.translation import gettext_lazy as _ + +from apps.shared.presentation.forms import DaisyFormMixin +from apps.users.application.dto import SupervisorChoice, UserDetailsData +from apps.users.container import login_throttle +from apps.users.domain.enums import Role +from apps.users.presentation.labels import ROLE_CHOICES + + +def client_ip(request: Any) -> str: + return str(request.META.get("REMOTE_ADDR", "")) if request is not None else "" + + +class LoginForm(DaisyFormMixin, AuthenticationForm): + username = forms.EmailField( + label=_("Email"), + widget=forms.EmailInput(attrs={"autocomplete": "email", "autofocus": True}), + ) + remember_me = forms.BooleanField(label=_("Remember me"), required=False) + + error_messages = { + # Same message for a wrong password and a deactivated account. + "invalid_login": _("The email address or password is incorrect."), + "inactive": _("The email address or password is incorrect."), + "throttled": _("Too many login attempts. Try again in a few minutes."), + } + + def clean(self) -> dict[str, Any]: + email = self.cleaned_data.get("username") or "" + ip = client_ip(self.request) + throttle = login_throttle() + if email and throttle.is_blocked(email, ip): + raise forms.ValidationError(self.error_messages["throttled"], code="throttled") + try: + cleaned = super().clean() + except forms.ValidationError: + if email: + throttle.register_failure(email, ip) + raise + throttle.reset(email, ip) + return cleaned + + +class ForgotPasswordForm(DaisyFormMixin, forms.Form): + email = forms.EmailField( + label=_("Email"), + widget=forms.EmailInput(attrs={"autocomplete": "email", "autofocus": True}), + ) + + +class PasswordSetForm(DaisyFormMixin, SetPasswordForm): # type: ignore[type-arg] + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + complexity = [ + v.get_help_text() + for v in password_validation.get_default_password_validators() + if type(v).__name__ == "ComplexityValidator" + ] + self.fields["new_password1"].help_text = complexity[0] if complexity else "" + self.fields["new_password1"].widget.attrs["autofocus"] = True + + +class UserForm(DaisyFormMixin, forms.Form): + name = forms.CharField(label=_("Name"), max_length=150) + email = forms.EmailField(label=_("Email"), max_length=254) + role = forms.ChoiceField(label=_("Role"), choices=ROLE_CHOICES) + is_active = forms.BooleanField(label=_("Active"), required=False, initial=True) + employment_ends_on = forms.DateField( + label=_("Last day"), + required=False, + widget=forms.DateInput(attrs={"type": "date"}, format="%Y-%m-%d"), + help_text=_("The intern cannot log in after this day."), + ) + supervisor_id = forms.TypedChoiceField( + label=_("Supervisor"), required=False, coerce=int, empty_value=None + ) + + def __init__( + self, + *args: Any, + supervisors: Sequence[SupervisorChoice] = (), + is_new: bool = True, + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + self.fields["supervisor_id"].choices = [("", _("Choose a supervisor"))] + [ # type: ignore[attr-defined] + (s.id, s.name) for s in supervisors + ] + self.fields["role"].widget.attrs["x-model"] = "role" + if is_new: + del self.fields["is_active"] + + def to_dto(self) -> UserDetailsData: + data = self.cleaned_data + is_intern = data["role"] == Role.INTERN.value + return UserDetailsData( + name=data["name"], + email=data["email"], + role=Role(data["role"]), + is_active=data.get("is_active", True), + employment_ends_on=data.get("employment_ends_on") if is_intern else None, + supervisor_id=data.get("supervisor_id") if is_intern else None, + ) + + +class UserFilterForm(DaisyFormMixin, forms.Form): + q = forms.CharField(label=_("Search"), required=False) + role = forms.ChoiceField( + label=_("Role"), required=False, choices=[("", _("All roles")), *ROLE_CHOICES] + ) + active = forms.ChoiceField( + label=_("Status"), + required=False, + choices=[("", _("All")), ("1", _("Active")), ("0", _("Inactive"))], + ) diff --git a/apps/users/presentation/labels.py b/apps/users/presentation/labels.py new file mode 100644 index 0000000..9b75280 --- /dev/null +++ b/apps/users/presentation/labels.py @@ -0,0 +1,32 @@ +"""Translated display names and error messages of the users module.""" + +from django.utils.translation import gettext_lazy as _ + +from apps.users.domain.enums import Role + +ROLE_LABELS = { + Role.ADMIN: _("Admin"), + Role.MANAGEMENT: _("Management"), + Role.EMPLOYEE: _("Employee"), + Role.INTERN: _("Intern"), + Role.SUBCONTRACTOR: _("Subcontractor"), +} + +ROLE_CHOICES = [(role.value, label) for role, label in ROLE_LABELS.items()] + +ERROR_MESSAGES = { + "invalid_name": _("Enter a name (at most 150 characters)."), + "invalid_email": _("Enter a valid email address."), + "email_taken": _("A user with this email address already exists."), + "intern_requires_end_date": _("An intern must have an end date."), + "intern_requires_supervisor": _("An intern must have a supervisor."), + "invalid_supervisor": _("The supervisor must be an active management or employee user."), + "last_active_admin": _( + "This is the last active admin. It cannot be deactivated or moved to another role." + ), + "supervisor_has_interns": _( + "This user supervises active interns. Change their supervisor first." + ), + "user_not_found": _("The user was not found."), + "*": _("The change could not be saved."), +} diff --git a/apps/users/presentation/middleware.py b/apps/users/presentation/middleware.py new file mode 100644 index 0000000..1ffbc9d --- /dev/null +++ b/apps/users/presentation/middleware.py @@ -0,0 +1,30 @@ +from collections.abc import Callable + +from django.contrib.auth import logout +from django.http import HttpRequest, HttpResponse +from django.shortcuts import redirect +from django.urls import reverse + +from apps.users.container import check_login_allowed + + +class EnsureAccountIsUsable: + """Ends the session at once when the user is deactivated or the internship has ended. + + The reason travels in the URL (``?access=ended``) so the login page can explain it. + """ + + def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None: + self.get_response = get_response + + def __call__(self, request: HttpRequest) -> HttpResponse: + user = request.user + if user.is_authenticated and not check_login_allowed().execute(user.pk): + logout(request) + url = f"{reverse('users:login')}?access=ended" + if request.headers.get("HX-Request") == "true": + response = HttpResponse(status=204) + response["HX-Redirect"] = url + return response + return redirect(url) + return self.get_response(request) diff --git a/apps/users/presentation/mixins.py b/apps/users/presentation/mixins.py new file mode 100644 index 0000000..004b4fa --- /dev/null +++ b/apps/users/presentation/mixins.py @@ -0,0 +1,25 @@ +from typing import Any + +from django.core.exceptions import PermissionDenied +from django.http import HttpRequest, HttpResponseBase + +from apps.users.domain.enums import Permission, Role +from apps.users.domain.permissions import role_has + + +def user_has(user: Any, permission: Permission | str) -> bool: + if not getattr(user, "is_authenticated", False): + return False + return role_has(Role(user.role), Permission(permission)) + + +class PermissionRequiredMixin: + """Requires a role based permission (specification 2.4); otherwise 403.""" + + permission: Permission + + def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase: + if not user_has(request.user, self.permission): + raise PermissionDenied + response: HttpResponseBase = super().dispatch(request, *args, **kwargs) # type: ignore[misc] + return response diff --git a/apps/users/presentation/templates/users/email/password_link.txt b/apps/users/presentation/templates/users/email/password_link.txt new file mode 100644 index 0000000..153e917 --- /dev/null +++ b/apps/users/presentation/templates/users/email/password_link.txt @@ -0,0 +1,10 @@ +{% autoescape off %}{% blocktranslate %}Hello {{ name }},{% endblocktranslate %} + +{% if purpose == "reset" %}{% translate "You asked for a link for setting a new password." %}{% else %}{% translate "An account has been created or a new password link has been requested for you." %}{% endif %} +{% translate "Set your password with this link:" %} + +{{ url }} + +{% blocktranslate with expires=expires_at|date:"j.n.Y H:i" %}The link can be used once and it is valid until {{ expires }}.{% endblocktranslate %} +{% translate "If you did not expect this message, you can ignore it." %} +{% endautoescape %} diff --git a/apps/users/presentation/templates/users/email/password_link_subject.txt b/apps/users/presentation/templates/users/email/password_link_subject.txt new file mode 100644 index 0000000..acdabca --- /dev/null +++ b/apps/users/presentation/templates/users/email/password_link_subject.txt @@ -0,0 +1 @@ +{% if purpose == "reset" %}{% translate "Set a new password" %}{% else %}{% translate "Set your password" %}{% endif %} – Toiminnanohjaus diff --git a/apps/users/presentation/templates/users/forgot_password.html b/apps/users/presentation/templates/users/forgot_password.html new file mode 100644 index 0000000..6b2e71a --- /dev/null +++ b/apps/users/presentation/templates/users/forgot_password.html @@ -0,0 +1,12 @@ +{% extends "layouts/auth.html" %} +{% block title %}{% translate "Forgot your password?" %}{% endblock %} +{% block content %} +

{% translate "Forgot your password?" %}

+

{% translate "Enter your email address. We will send you a link for setting a new password." %}

+
+ {% csrf_token %} + {{ form }} + +
+ {% translate "Back to login" %} +{% endblock %} diff --git a/apps/users/presentation/templates/users/form.html b/apps/users/presentation/templates/users/form.html new file mode 100644 index 0000000..e036e27 --- /dev/null +++ b/apps/users/presentation/templates/users/form.html @@ -0,0 +1,48 @@ +{% extends "base.html" %} +{% block title %}{% if user_id %}{% translate "Edit user" %}{% else %}{% translate "New user" %}{% endif %}{% endblock %} +{% block content %} + +

{% if user_id %}{% translate "Edit user" %}{% else %}{% translate "New user" %}{% endif %}

+ +
+
+ {% csrf_token %} +
+ {% include "components/non_field_errors.html" %} + {{ form.name.as_field_group }} + {{ form.email.as_field_group }} + {{ form.role.as_field_group }} +
+

{% translate "An intern must have a last day and a supervisor." %}

+ {{ form.employment_ends_on.as_field_group }} + {{ form.supervisor_id.as_field_group }} +
+ {% if form.is_active %}{{ form.is_active.as_field_group }}{% endif %} +
+ {% translate "Cancel" %} + +
+
+
+ + {% if user_id %} +
+
+ +

{% translate "Creates a new link for setting the password. The link is emailed to the user and shown here for copying. Earlier links stop working." %}

+ + +
+
+ {% url 'users:password_link' user_id as link_url %} + {% translate "Create a new password link?" as dialog_title %} + {% translate "Earlier links of this user stop working." as dialog_body %} + {% translate "Create link" as dialog_confirm %} + {% include "components/confirm_dialog.html" with id="confirm-password-link" title=dialog_title body=dialog_body action_url=link_url confirm_label=dialog_confirm hx_target="#password-link-result" %} + {% endif %} +
+{% endblock %} diff --git a/apps/users/presentation/templates/users/list.html b/apps/users/presentation/templates/users/list.html new file mode 100644 index 0000000..6b137c2 --- /dev/null +++ b/apps/users/presentation/templates/users/list.html @@ -0,0 +1,24 @@ +{% extends "base.html" %} +{% block title %}{% translate "Users" %}{% endblock %} +{% block content %} +
+

{% translate "Users" %}

+ {% translate "New user" %} +
+ + + +
+ {% include "users/partials/user_table.html" %} +
+{% endblock %} diff --git a/apps/users/presentation/templates/users/login.html b/apps/users/presentation/templates/users/login.html new file mode 100644 index 0000000..b04183c --- /dev/null +++ b/apps/users/presentation/templates/users/login.html @@ -0,0 +1,17 @@ +{% extends "layouts/auth.html" %} +{% block title %}{% translate "Log in" %}{% endblock %} +{% block content %} +

{% translate "Log in" %}

+ {% if access_ended %} + + {% endif %} +
+ {% csrf_token %} + {{ form }} + + +
+ {% translate "Forgot your password?" %} +{% endblock %} diff --git a/apps/users/presentation/templates/users/partials/password_link.html b/apps/users/presentation/templates/users/partials/password_link.html new file mode 100644 index 0000000..34eb1e0 --- /dev/null +++ b/apps/users/presentation/templates/users/partials/password_link.html @@ -0,0 +1,20 @@ + diff --git a/apps/users/presentation/templates/users/partials/user_table.html b/apps/users/presentation/templates/users/partials/user_table.html new file mode 100644 index 0000000..412227d --- /dev/null +++ b/apps/users/presentation/templates/users/partials/user_table.html @@ -0,0 +1,47 @@ +{% load users_tags %} +

{% blocktranslate count counter=page.paginator.count %}{{ counter }} user found{% plural %}{{ counter }} users found{% endblocktranslate %}

+
+ + + + + + + + + + + + + + {% for u in page.object_list %} + + + + + + + + + {% empty %} + + {% endfor %} + +
{% translate "Users" %}
{% translate "Name" %}{% translate "Email" %}{% translate "Role" %}{% translate "Status" %}{% translate "Last day" %}{% translate "Supervisor" %}
{{ u.name }}{{ u.email }}{{ u.role|role_label }} + {% if u.is_active %}{% translate "Active" %} + {% else %}{% translate "Inactive" %}{% endif %} + {{ u.employment_ends_on|date:"j.n.Y"|default:"–" }}{{ u.supervisor_name|default:"–" }}
{% translate "No users match the filters." %}
+
+{% if page.paginator.num_pages > 1 %} + +{% endif %} diff --git a/apps/users/presentation/templates/users/password_link_page.html b/apps/users/presentation/templates/users/password_link_page.html new file mode 100644 index 0000000..a3e3b15 --- /dev/null +++ b/apps/users/presentation/templates/users/password_link_page.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} +{% block title %}{% translate "Password link" %}{% endblock %} +{% block content %} +

{% blocktranslate with name=user_summary.name %}Password link for {{ name }}{% endblocktranslate %}

+
+
+ {% include "users/partials/password_link.html" %} + +
+
+{% endblock %} diff --git a/apps/users/presentation/templates/users/set_password.html b/apps/users/presentation/templates/users/set_password.html new file mode 100644 index 0000000..39b74f9 --- /dev/null +++ b/apps/users/presentation/templates/users/set_password.html @@ -0,0 +1,10 @@ +{% extends "layouts/auth.html" %} +{% block title %}{% translate "Set password" %}{% endblock %} +{% block content %} +

{% translate "Set password" %}

+
+ {% csrf_token %} + {{ form }} + +
+{% endblock %} diff --git a/apps/users/presentation/templates/users/set_password_invalid.html b/apps/users/presentation/templates/users/set_password_invalid.html new file mode 100644 index 0000000..678751f --- /dev/null +++ b/apps/users/presentation/templates/users/set_password_invalid.html @@ -0,0 +1,7 @@ +{% extends "layouts/auth.html" %} +{% block title %}{% translate "The link is not valid" %}{% endblock %} +{% block content %} +

{% translate "The link is not valid" %}

+

{% translate "The link has expired, it has already been used, or a newer link has been created. Request a new link or ask the admin to create one." %}

+ {% translate "Request a new link" %} +{% endblock %} diff --git a/apps/users/presentation/templatetags/__init__.py b/apps/users/presentation/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/presentation/templatetags/users_tags.py b/apps/users/presentation/templatetags/users_tags.py new file mode 100644 index 0000000..714b3f5 --- /dev/null +++ b/apps/users/presentation/templatetags/users_tags.py @@ -0,0 +1,20 @@ +from typing import Any + +from django import template + +from apps.users.domain.enums import Role +from apps.users.presentation.labels import ROLE_LABELS +from apps.users.presentation.mixins import user_has + +register = template.Library() + + +@register.filter +def can(user: Any, permission: str) -> bool: + """``{% if request.user|can:"users.manage" %}``""" + return user_has(user, permission) + + +@register.filter +def role_label(role: Any) -> str: + return str(ROLE_LABELS.get(Role(role), role)) diff --git a/apps/users/presentation/urls.py b/apps/users/presentation/urls.py new file mode 100644 index 0000000..5ec6653 --- /dev/null +++ b/apps/users/presentation/urls.py @@ -0,0 +1,21 @@ +from django.contrib.auth import views as auth_views +from django.urls import path + +from apps.users.presentation import views + +app_name = "users" + +urlpatterns = [ + path("login/", views.LoginView.as_view(), name="login"), + path("logout/", auth_views.LogoutView.as_view(), name="logout"), + path("password/forgot/", views.ForgotPasswordView.as_view(), name="forgot_password"), + path( + "password/set////", + views.SetPasswordView.as_view(), + name="set_password", + ), + path("users/", views.UserListView.as_view(), name="list"), + path("users/new/", views.UserCreateView.as_view(), name="create"), + path("users//edit/", views.UserUpdateView.as_view(), name="edit"), + path("users//password-link/", views.PasswordLinkView.as_view(), name="password_link"), +] diff --git a/apps/users/presentation/views.py b/apps/users/presentation/views.py new file mode 100644 index 0000000..8bcecea --- /dev/null +++ b/apps/users/presentation/views.py @@ -0,0 +1,219 @@ +from typing import Any + +from django.contrib import messages +from django.contrib.auth import views as auth_views +from django.contrib.auth.decorators import login_not_required +from django.core.paginator import Paginator +from django.http import Http404, HttpRequest, HttpResponse +from django.shortcuts import redirect, render +from django.utils.decorators import method_decorator +from django.utils.encoding import force_str +from django.utils.http import urlsafe_base64_decode +from django.utils.translation import gettext as _ +from django.views import View +from django.views.generic import FormView, TemplateView + +from apps.shared.domain.exceptions import DomainError +from apps.users import container +from apps.users.application.dto import PasswordLinkPurpose +from apps.users.domain.enums import Permission, Role +from apps.users.presentation.forms import ( + ForgotPasswordForm, + LoginForm, + PasswordSetForm, + UserFilterForm, + UserForm, +) +from apps.users.presentation.labels import ERROR_MESSAGES +from apps.users.presentation.mixins import PermissionRequiredMixin + + +class LoginView(auth_views.LoginView): + form_class = LoginForm + template_name = "users/login.html" + redirect_authenticated_user = True + + def form_valid(self, form: LoginForm) -> HttpResponse: # type: ignore[override] + if not form.cleaned_data.get("remember_me"): + self.request.session.set_expiry(0) # ends when the browser is closed + return super().form_valid(form) + + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: + context = super().get_context_data(**kwargs) + context["access_ended"] = self.request.GET.get("access") == "ended" + return context + + +@method_decorator(login_not_required, name="dispatch") +class ForgotPasswordView(FormView): # type: ignore[type-arg] + form_class = ForgotPasswordForm + template_name = "users/forgot_password.html" + + def form_valid(self, form: ForgotPasswordForm) -> HttpResponse: + container.request_password_reset().execute(form.cleaned_data["email"]) + # Same answer for every address: the page must not reveal which emails exist. + messages.info( + self.request, + _( + "If the address belongs to a user who may log in, a link for setting " + "the password has been sent to it. The link is valid for 60 minutes." + ), + ) + return redirect("users:login") + + +@method_decorator(login_not_required, name="dispatch") +class SetPasswordView(View): + template_name = "users/set_password.html" + + def _get_user(self, purpose: str, uidb64: str, token: str) -> Any: + try: + link_purpose = PasswordLinkPurpose(purpose) + user_id = int(force_str(urlsafe_base64_decode(uidb64))) + except ValueError: + return None + user = container.user_for_password_link(user_id, link_purpose, token) + if user is None or not container.check_login_allowed().execute(user.pk): + return None + return user + + def get(self, request: HttpRequest, purpose: str, uidb64: str, token: str) -> HttpResponse: + user = self._get_user(purpose, uidb64, token) + if user is None: + return render(request, "users/set_password_invalid.html", status=400) + return render(request, self.template_name, {"form": PasswordSetForm(user)}) + + def post(self, request: HttpRequest, purpose: str, uidb64: str, token: str) -> HttpResponse: + user = self._get_user(purpose, uidb64, token) + if user is None: + return render(request, "users/set_password_invalid.html", status=400) + form = PasswordSetForm(user, request.POST) + if not form.is_valid(): + return render(request, self.template_name, {"form": form}, status=422) + # Saving changes the password hash: the link stops working and other sessions end. + form.save() + messages.success(request, _("Your password has been set. You can now log in.")) + return redirect("users:login") + + +class UserListView(PermissionRequiredMixin, TemplateView): + permission = Permission.USERS_MANAGE + template_name = "users/list.html" + page_size = 25 + + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: + context = super().get_context_data(**kwargs) + filters = UserFilterForm(self.request.GET or None) + search, role, active = "", None, None + if filters.is_valid(): + search = filters.cleaned_data["q"].strip() + role = Role(filters.cleaned_data["role"]) if filters.cleaned_data["role"] else None + if filters.cleaned_data["active"] in ("0", "1"): + active = filters.cleaned_data["active"] == "1" + users = container.user_queries().list_users(search=search, role=role, is_active=active) + page = Paginator(users, self.page_size).get_page(self.request.GET.get("page")) + query = self.request.GET.copy() + query.pop("page", None) + context.update(filters=filters, page=page, query=query.urlencode()) + return context + + def get_template_names(self) -> list[str]: + if getattr(self.request, "htmx", False): + return ["users/partials/user_table.html"] + return [self.template_name] + + +class UserCreateView(PermissionRequiredMixin, FormView): # type: ignore[type-arg] + permission = Permission.USERS_MANAGE + form_class = UserForm + template_name = "users/form.html" + + def get_form_kwargs(self) -> dict[str, Any]: + kwargs = super().get_form_kwargs() + kwargs["supervisors"] = container.user_queries().supervisor_choices() + kwargs["is_new"] = True + return kwargs + + def form_valid(self, form: UserForm) -> HttpResponse: + try: + created = container.create_user().execute(form.to_dto()) + except DomainError as error: + form.add_domain_error(error, ERROR_MESSAGES) + return self.render_to_response(self.get_context_data(form=form), status=422) + user = container.user_queries().get_summary(created.user_id) + messages.success(self.request, _("User created.")) + return render( + self.request, + "users/password_link_page.html", + {"link": created.password_link, "user_summary": user}, + ) + + def form_invalid(self, form: UserForm) -> HttpResponse: + return self.render_to_response(self.get_context_data(form=form), status=422) + + +class UserUpdateView(PermissionRequiredMixin, FormView): # type: ignore[type-arg] + permission = Permission.USERS_MANAGE + form_class = UserForm + template_name = "users/form.html" + + def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Any: + self.details = container.user_queries().get_details(kwargs["pk"]) + if self.details is None: + raise Http404 + return super().dispatch(request, *args, **kwargs) + + def get_initial(self) -> dict[str, Any]: + d = self.details + assert d is not None + return { + "name": d.name, + "email": d.email, + "role": d.role.value, + "is_active": d.is_active, + "employment_ends_on": d.employment_ends_on, + "supervisor_id": d.supervisor_id, + } + + def get_form_kwargs(self) -> dict[str, Any]: + kwargs = super().get_form_kwargs() + kwargs["supervisors"] = container.user_queries().supervisor_choices( + exclude_id=self.kwargs["pk"] + ) + kwargs["is_new"] = False + return kwargs + + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: + context = super().get_context_data(**kwargs) + context["user_id"] = self.kwargs["pk"] + context["user_name"] = self.details.name if self.details else "" + return context + + def form_valid(self, form: UserForm) -> HttpResponse: + try: + container.update_user().execute(self.kwargs["pk"], form.to_dto()) + except DomainError as error: + form.add_domain_error(error, ERROR_MESSAGES) + return self.form_invalid(form) + messages.success(self.request, _("Changes saved.")) + return redirect("users:list") + + def form_invalid(self, form: UserForm) -> HttpResponse: + return self.render_to_response(self.get_context_data(form=form), status=422) + + +class PasswordLinkView(PermissionRequiredMixin, View): + """Creates a new 72 h link for a user and shows it for copying (POST only).""" + + permission = Permission.USERS_MANAGE + + def post(self, request: HttpRequest, pk: int) -> HttpResponse: + try: + link = container.issue_password_link().execute(pk) + except DomainError: + raise Http404 from None + user = container.user_queries().get_summary(pk) + context = {"link": link, "user_summary": user} + if getattr(request, "htmx", False): + return render(request, "users/partials/password_link.html", context) + return render(request, "users/password_link_page.html", context) diff --git a/apps/users/tests/__init__.py b/apps/users/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/tests/application/__init__.py b/apps/users/tests/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/tests/application/test_use_cases.py b/apps/users/tests/application/test_use_cases.py new file mode 100644 index 0000000..ee281c8 --- /dev/null +++ b/apps/users/tests/application/test_use_cases.py @@ -0,0 +1,179 @@ +from datetime import date + +import pytest + +from apps.shared.domain.value_objects import EmailAddress +from apps.users.application.dto import PasswordLinkPurpose, UserDetailsData +from apps.users.application.use_cases import ( + CheckLoginAllowed, + CreateUser, + IssuePasswordLink, + RequestPasswordReset, + UpdateUser, +) +from apps.users.domain.enums import Role +from apps.users.domain.exceptions import ( + EmailAlreadyTaken, + InvalidSupervisor, + LastActiveAdmin, + SupervisorHasInterns, + UserNotFound, +) +from apps.users.tests.fakes import ( + FakePasswordLinkService, + FakeUnitOfWork, + FixedClock, + InMemoryUserRepository, + account, +) + +TODAY = date(2026, 3, 1) + + +@pytest.fixture +def repo() -> InMemoryUserRepository: + return InMemoryUserRepository() + + +@pytest.fixture +def links() -> FakePasswordLinkService: + return FakePasswordLinkService() + + +def details(**overrides: object) -> UserDetailsData: + base: dict[str, object] = { + "name": "Eeva Employee", + "email": "eeva@example.test", + "role": Role.EMPLOYEE, + } + return UserDetailsData(**{**base, **overrides}) # type: ignore[arg-type] + + +class TestCreateUser: + def test_creates_user_and_emails_setup_link( + self, repo: InMemoryUserRepository, links: FakePasswordLinkService + ) -> None: + created = CreateUser(repo, FakeUnitOfWork(), links).execute(details()) + + assert repo.get_by_id(created.user_id) is not None + assert links.issued == [(created.user_id, PasswordLinkPurpose.SETUP)] + assert links.sent == [("eeva@example.test", PasswordLinkPurpose.SETUP)] + assert created.password_link.emailed + + def test_email_must_be_unique( + self, repo: InMemoryUserRepository, links: FakePasswordLinkService + ) -> None: + repo.save(account(email=EmailAddress("eeva@example.test"))) + with pytest.raises(EmailAlreadyTaken): + CreateUser(repo, FakeUnitOfWork(), links).execute(details(email="EEVA@example.test")) + + def test_failed_email_still_creates_user(self, repo: InMemoryUserRepository) -> None: + links = FakePasswordLinkService(send_ok=False) + created = CreateUser(repo, FakeUnitOfWork(), links).execute(details()) + + assert repo.get_by_id(created.user_id) is not None + assert not created.password_link.emailed + + def test_intern_supervisor_must_be_active_employee_or_management( + self, repo: InMemoryUserRepository, links: FakePasswordLinkService + ) -> None: + sub = repo.save(account(email=EmailAddress("sub@example.test"), role=Role.SUBCONTRACTOR)) + with pytest.raises(InvalidSupervisor): + CreateUser(repo, FakeUnitOfWork(), links).execute( + details( + role=Role.INTERN, employment_ends_on=date(2026, 6, 30), supervisor_id=sub.id + ) + ) + + +class TestUpdateUser: + def test_last_active_admin_cannot_be_deactivated(self, repo: InMemoryUserRepository) -> None: + admin = repo.save(account(role=Role.ADMIN)) + with pytest.raises(LastActiveAdmin): + UpdateUser(repo, FakeUnitOfWork()).execute( + admin.id, # type: ignore[arg-type] + details(name="Admin", email="user@example.test", role=Role.ADMIN, is_active=False), + ) + assert repo.locked + + def test_last_active_admin_cannot_change_role(self, repo: InMemoryUserRepository) -> None: + admin = repo.save(account(role=Role.ADMIN)) + with pytest.raises(LastActiveAdmin): + UpdateUser(repo, FakeUnitOfWork()).execute( + admin.id, # type: ignore[arg-type] + details(email="user@example.test", role=Role.MANAGEMENT), + ) + + def test_admin_can_be_deactivated_when_another_exists( + self, repo: InMemoryUserRepository + ) -> None: + admin = repo.save(account(role=Role.ADMIN)) + repo.save(account(role=Role.ADMIN, email=EmailAddress("other@example.test"))) + UpdateUser(repo, FakeUnitOfWork()).execute( + admin.id, # type: ignore[arg-type] + details(email="user@example.test", role=Role.ADMIN, is_active=False), + ) + assert not repo.get_by_id(admin.id).is_active # type: ignore[arg-type, union-attr] + + def test_supervisor_with_active_interns_cannot_be_deactivated( + self, repo: InMemoryUserRepository + ) -> None: + boss = repo.save(account(role=Role.EMPLOYEE)) + repo.save( + account( + email=EmailAddress("intern@example.test"), + role=Role.INTERN, + employment_ends_on=date(2026, 6, 30), + supervisor_id=boss.id, + ) + ) + with pytest.raises(SupervisorHasInterns): + UpdateUser(repo, FakeUnitOfWork()).execute( + boss.id, # type: ignore[arg-type] + details(email="user@example.test", is_active=False), + ) + + def test_unknown_user(self, repo: InMemoryUserRepository) -> None: + with pytest.raises(UserNotFound): + UpdateUser(repo, FakeUnitOfWork()).execute(99, details()) + + +class TestPasswordLinks: + def test_issue_link_for_existing_user( + self, repo: InMemoryUserRepository, links: FakePasswordLinkService + ) -> None: + user = repo.save(account()) + link = IssuePasswordLink(repo, links).execute(user.id) # type: ignore[arg-type] + assert link.emailed + assert links.issued == [(user.id, PasswordLinkPurpose.SETUP)] + + def test_reset_is_sent_to_user_who_may_log_in( + self, repo: InMemoryUserRepository, links: FakePasswordLinkService + ) -> None: + repo.save(account()) + RequestPasswordReset(repo, links, FixedClock(TODAY)).execute("USER@example.test") + assert links.sent == [("user@example.test", PasswordLinkPurpose.RESET)] + + @pytest.mark.parametrize("email", ["unknown@example.test", "not an email", ""]) + def test_reset_does_nothing_for_unknown_address( + self, repo: InMemoryUserRepository, links: FakePasswordLinkService, email: str + ) -> None: + RequestPasswordReset(repo, links, FixedClock(TODAY)).execute(email) + assert links.issued == [] + + def test_reset_is_not_sent_to_ended_intern( + self, repo: InMemoryUserRepository, links: FakePasswordLinkService + ) -> None: + repo.save(account(role=Role.INTERN, employment_ends_on=date(2026, 2, 28), supervisor_id=9)) + RequestPasswordReset(repo, links, FixedClock(TODAY)).execute("user@example.test") + assert links.issued == [] + + +class TestCheckLoginAllowed: + def test_allowed_and_denied(self, repo: InMemoryUserRepository) -> None: + active = repo.save(account()) + inactive = repo.save(account(email=EmailAddress("x@example.test"), is_active=False)) + check = CheckLoginAllowed(repo, FixedClock(TODAY)) + assert check.execute(active.id) # type: ignore[arg-type] + assert not check.execute(inactive.id) # type: ignore[arg-type] + assert not check.execute(12345) diff --git a/apps/users/tests/conftest.py b/apps/users/tests/conftest.py new file mode 100644 index 0000000..50ecfe1 --- /dev/null +++ b/apps/users/tests/conftest.py @@ -0,0 +1,43 @@ +from collections.abc import Callable +from typing import Any + +import pytest +from django.core.cache import cache + +from apps.users.infrastructure.orm import User + +PASSWORD = "Vahva-Salasana-2026" + + +@pytest.fixture(autouse=True) +def _clear_cache(request: pytest.FixtureRequest) -> None: + # The cache (login throttle) lives in the database; only DB tests can touch it. + if request.node.get_closest_marker("django_db"): + request.getfixturevalue("db") + cache.clear() + + +@pytest.fixture +def make_user(db: Any) -> Callable[..., User]: + counter = iter(range(1, 10_000)) + + def factory(**fields: Any) -> User: + n = next(counter) + fields.setdefault("email", f"user{n}@example.test") + fields.setdefault("name", f"User {n}") + fields.setdefault("role", "employee") + password = fields.pop("password", PASSWORD) + return User.objects.create_user(password=password, **fields) + + return factory + + +@pytest.fixture +def admin(make_user: Callable[..., User]) -> User: + return make_user(email="admin@example.test", name="Admin", role="admin") + + +@pytest.fixture +def admin_client(client: Any, admin: User) -> Any: + client.force_login(admin) + return client diff --git a/apps/users/tests/domain/__init__.py b/apps/users/tests/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/tests/domain/test_user_account.py b/apps/users/tests/domain/test_user_account.py new file mode 100644 index 0000000..4a5b62c --- /dev/null +++ b/apps/users/tests/domain/test_user_account.py @@ -0,0 +1,96 @@ +from datetime import date + +import pytest + +from apps.shared.domain.exceptions import InvalidEmailAddress +from apps.shared.domain.value_objects import EmailAddress +from apps.users.domain.entities import UserAccount +from apps.users.domain.enums import Permission, Role +from apps.users.domain.exceptions import ( + InternRequiresEndDate, + InternRequiresSupervisor, + InvalidPersonName, + InvalidSupervisor, +) +from apps.users.domain.permissions import role_has +from apps.users.domain.value_objects import PersonName +from apps.users.tests.fakes import account + + +def register(**kwargs: object) -> UserAccount: + defaults: dict[str, object] = { + "name": PersonName("Iida Intern"), + "email": EmailAddress("iida@example.test"), + "role": Role.EMPLOYEE, + } + return UserAccount.register(**{**defaults, **kwargs}) # type: ignore[arg-type] + + +class TestValueObjects: + def test_email_is_normalized(self) -> None: + assert EmailAddress(" Iida@Example.TEST ").value == "iida@example.test" + + @pytest.mark.parametrize("value", ["", "no-at-sign", "a@b", "a b@c.fi"]) + def test_invalid_email(self, value: str) -> None: + with pytest.raises(InvalidEmailAddress): + EmailAddress(value) + + def test_name_whitespace_is_collapsed(self) -> None: + assert PersonName(" Iida Intern ").value == "Iida Intern" + + @pytest.mark.parametrize("value", ["", " ", "x" * 151]) + def test_invalid_name(self, value: str) -> None: + with pytest.raises(InvalidPersonName): + PersonName(value) + + +class TestInternRules: + def test_intern_requires_end_date(self) -> None: + with pytest.raises(InternRequiresEndDate): + register(role=Role.INTERN, supervisor_id=1) + + def test_intern_requires_supervisor(self) -> None: + with pytest.raises(InternRequiresSupervisor): + register(role=Role.INTERN, employment_ends_on=date(2026, 6, 30)) + + def test_intern_cannot_supervise_self(self) -> None: + user = account(id=5, role=Role.EMPLOYEE) + with pytest.raises(InvalidSupervisor): + user.update_details( + name=user.name, + email=user.email, + role=Role.INTERN, + is_active=True, + employment_ends_on=date(2026, 6, 30), + supervisor_id=5, + ) + + def test_other_roles_clear_intern_fields(self) -> None: + user = register(role=Role.EMPLOYEE, employment_ends_on=date(2026, 6, 30), supervisor_id=2) + assert user.employment_ends_on is None + assert user.supervisor_id is None + + +class TestCanLogIn: + def test_inactive_user_cannot_log_in(self) -> None: + assert not account(is_active=False).can_log_in(date(2026, 1, 1)) + + def test_intern_can_log_in_until_end_date(self) -> None: + intern = account(role=Role.INTERN, employment_ends_on=date(2026, 6, 30), supervisor_id=1) + assert intern.can_log_in(date(2026, 6, 30)) + assert not intern.can_log_in(date(2026, 7, 1)) + + def test_intern_without_end_date_cannot_log_in(self) -> None: + # A bad stored row must not crash login; it just denies access. + assert not account(role=Role.INTERN).can_log_in(date(2026, 1, 1)) + + +class TestPermissions: + def test_only_admin_manages_users(self) -> None: + assert role_has(Role.ADMIN, Permission.USERS_MANAGE) + for role in (Role.MANAGEMENT, Role.EMPLOYEE, Role.INTERN, Role.SUBCONTRACTOR): + assert not role_has(role, Permission.USERS_MANAGE) + + def test_subcontractor_does_not_use_customers(self) -> None: + assert not role_has(Role.SUBCONTRACTOR, Permission.CUSTOMERS_USE) + assert role_has(Role.INTERN, Permission.CUSTOMERS_USE) diff --git a/apps/users/tests/fakes.py b/apps/users/tests/fakes.py new file mode 100644 index 0000000..4053d1c --- /dev/null +++ b/apps/users/tests/fakes.py @@ -0,0 +1,100 @@ +"""In-memory test doubles for the users application layer (no database).""" + +from dataclasses import replace +from datetime import UTC, date, datetime + +from apps.shared.domain.value_objects import EmailAddress +from apps.users.application.dto import PasswordLink, PasswordLinkPurpose +from apps.users.domain.entities import UserAccount +from apps.users.domain.enums import Role + + +class InMemoryUserRepository: + def __init__(self) -> None: + self.users: dict[int, UserAccount] = {} + self.locked = False + self._next_id = 1 + + def get_by_id(self, user_id: int) -> UserAccount | None: + return self.users.get(user_id) + + def get_by_email(self, email: EmailAddress) -> UserAccount | None: + return next((u for u in self.users.values() if u.email == email), None) + + def save(self, user: UserAccount) -> UserAccount: + if user.id is None: + user = user.with_id(self._next_id) + self._next_id += 1 + self.users[user.id] = user # type: ignore[index] + return user + + def is_email_taken(self, email: EmailAddress, *, exclude_id: int | None = None) -> bool: + return any(u.email == email and u.id != exclude_id for u in self.users.values()) + + def lock_active_admin_count(self) -> int: + self.locked = True + return sum(1 for u in self.users.values() if u.is_active_admin) + + def has_active_interns(self, supervisor_id: int) -> bool: + return any( + u.is_active and u.role is Role.INTERN and u.supervisor_id == supervisor_id + for u in self.users.values() + ) + + +class FakeUnitOfWork: + def __init__(self) -> None: + self.entered = 0 + + def __enter__(self) -> FakeUnitOfWork: + self.entered += 1 + return self + + def __exit__(self, *exc: object) -> None: + return None + + +class FakePasswordLinkService: + def __init__(self, *, send_ok: bool = True) -> None: + self.send_ok = send_ok + self.issued: list[tuple[int, PasswordLinkPurpose]] = [] + self.sent: list[tuple[str, PasswordLinkPurpose]] = [] + + def issue(self, user_id: int, purpose: PasswordLinkPurpose) -> PasswordLink: + self.issued.append((user_id, purpose)) + return PasswordLink( + url=f"http://test/password/{purpose.value}/{user_id}/", + expires_at=datetime(2026, 1, 1, tzinfo=UTC), + ) + + def send(self, user: UserAccount, link: PasswordLink, purpose: PasswordLinkPurpose) -> bool: + if self.send_ok: + self.sent.append((user.email.value, purpose)) + return self.send_ok + + +class FixedClock: + def __init__(self, today: date) -> None: + self._today = today + + def today(self) -> date: + return self._today + + def set(self, today: date) -> None: + self._today = today + + +def account(**overrides: object) -> UserAccount: + """A stored user without rule checks, for arranging test state.""" + from apps.users.domain.value_objects import PersonName + + base = UserAccount.reconstitute( + id=None, # type: ignore[arg-type] + name=PersonName("Test User"), + email=EmailAddress("user@example.test"), + role=Role.EMPLOYEE, + is_active=True, + employment_ends_on=None, + supervisor_id=None, + ) + return replace(base, **overrides) # type: ignore[arg-type] diff --git a/apps/users/tests/integration/__init__.py b/apps/users/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/tests/integration/test_auth.py b/apps/users/tests/integration/test_auth.py new file mode 100644 index 0000000..ec3ff11 --- /dev/null +++ b/apps/users/tests/integration/test_auth.py @@ -0,0 +1,180 @@ +from collections.abc import Callable +from datetime import date, timedelta +from typing import Any + +import pytest +from django.core import mail +from django.test import Client +from django.urls import reverse + +from apps.users.application.dto import PasswordLinkPurpose +from apps.users.infrastructure.orm import User +from apps.users.infrastructure.password_links import DjangoPasswordLinkService +from apps.users.tests.conftest import PASSWORD + +pytestmark = pytest.mark.django_db + +LOGIN = "/login/" + + +def login(client: Client, email: str, password: str = PASSWORD, **extra: str) -> Any: + return client.post(LOGIN, {"username": email, "password": password, **extra}) + + +class TestLogin: + def test_login_page_is_public_and_other_pages_are_not(self, client: Client) -> None: + assert client.get(LOGIN).status_code == 200 + response = client.get("/") + assert response.status_code == 302 + assert response["Location"].startswith(LOGIN) + + def test_successful_login(self, client: Client, make_user: Callable[..., User]) -> None: + make_user(email="eeva@example.test") + response = login(client, "EEVA@example.test") + assert response.status_code == 302 + assert client.get("/").status_code == 200 + + def test_session_ends_with_browser_unless_remember_me( + self, client: Client, make_user: Callable[..., User] + ) -> None: + make_user(email="eeva@example.test") + login(client, "eeva@example.test") + assert client.session.get_expire_at_browser_close() + client.logout() + login(client, "eeva@example.test", remember_me="on") + assert not client.session.get_expire_at_browser_close() + + def test_wrong_password_and_inactive_user_get_same_message( + self, client: Client, make_user: Callable[..., User] + ) -> None: + make_user(email="eeva@example.test") + make_user(email="old@example.test", is_active=False) + wrong = login(client, "eeva@example.test", "Wrong-Password-1") + inactive = login(client, "old@example.test") + message = "Sähköpostiosoite tai salasana on väärin." + assert message in wrong.content.decode() + assert message in inactive.content.decode() + + def test_ended_intern_cannot_log_in( + self, client: Client, make_user: Callable[..., User] + ) -> None: + boss = make_user() + make_user( + email="intern@example.test", + role="intern", + supervisor=boss, + employment_ends_on=date.today() - timedelta(days=2), + ) + response = login(client, "intern@example.test") + assert response.status_code == 200 + assert "_auth_user_id" not in client.session + + def test_login_is_throttled_after_five_failures( + self, client: Client, make_user: Callable[..., User] + ) -> None: + make_user(email="eeva@example.test") + for _ in range(5): + login(client, "eeva@example.test", "Wrong-Password-1") + response = login(client, "eeva@example.test") # correct password, still blocked + assert "Liian monta kirjautumisyritystä" in response.content.decode() + assert "_auth_user_id" not in client.session + + +class TestSessionEnds: + def test_deactivated_user_is_logged_out_on_next_request( + self, client: Client, make_user: Callable[..., User] + ) -> None: + user = make_user() + client.force_login(user) + User.objects.filter(pk=user.pk).update(is_active=False) + response = client.get("/") + assert response.status_code == 302 + assert response["Location"] == f"{LOGIN}?access=ended" + assert "_auth_user_id" not in client.session + + def test_htmx_request_gets_hx_redirect( + self, client: Client, make_user: Callable[..., User] + ) -> None: + user = make_user() + client.force_login(user) + User.objects.filter(pk=user.pk).update(is_active=False) + response = client.get("/", headers={"HX-Request": "true"}) + assert response["HX-Redirect"] == f"{LOGIN}?access=ended" + + def test_access_ended_message_is_shown(self, client: Client) -> None: + assert ( + "Käyttöoikeutesi on päättynyt" in client.get(f"{LOGIN}?access=ended").content.decode() + ) + + +class TestPasswordLinks: + def _link_path(self, user: User, purpose: PasswordLinkPurpose) -> str: + url = DjangoPasswordLinkService().issue(user.pk, purpose).url + return url.split("8000", 1)[-1] if "8000" in url else url + + def test_setting_password_works_once( + self, client: Client, make_user: Callable[..., User] + ) -> None: + user = make_user(password=None) + path = self._link_path(user, PasswordLinkPurpose.SETUP) + new = "Uusi-Salasana-2026!" + response = client.post(path, {"new_password1": new, "new_password2": new}) + assert response.status_code == 302 + user.refresh_from_db() + assert user.check_password(new) + assert client.get(path).status_code == 400 # single use + + def test_new_link_invalidates_older( + self, client: Client, make_user: Callable[..., User] + ) -> None: + user = make_user() + old = self._link_path(user, PasswordLinkPurpose.SETUP) + self._link_path(user, PasswordLinkPurpose.SETUP) + assert client.get(old).status_code == 400 + + def test_weak_password_is_rejected( + self, client: Client, make_user: Callable[..., User] + ) -> None: + user = make_user() + path = self._link_path(user, PasswordLinkPurpose.RESET) + response = client.post(path, {"new_password1": "lyhyt", "new_password2": "lyhyt"}) + assert response.status_code == 422 + assert "vähintään 12 merkkiä" in response.content.decode() + + def test_reset_link_expires_after_60_minutes( + self, client: Client, make_user: Callable[..., User], settings: Any + ) -> None: + settings.PASSWORD_RESET_TIMEOUT = -1 + user = make_user() + assert client.get(self._link_path(user, PasswordLinkPurpose.RESET)).status_code == 400 + + def test_password_change_ends_other_sessions(self, make_user: Callable[..., User]) -> None: + user = make_user() + other_device = Client() + other_device.force_login(user) + path = self._link_path(user, PasswordLinkPurpose.RESET) + new = "Uusi-Salasana-2026!" + Client().post(path, {"new_password1": new, "new_password2": new}) + assert other_device.get("/").status_code == 302 + + def test_forgot_password_gives_same_answer( + self, client: Client, make_user: Callable[..., User] + ) -> None: + make_user(email="eeva@example.test") + known = client.post("/password/forgot/", {"email": "eeva@example.test"}, follow=True) + unknown = client.post("/password/forgot/", {"email": "nobody@example.test"}, follow=True) + assert len(mail.outbox) == 1 + text = "Jos osoite kuuluu käyttäjälle" + assert text in known.content.decode() + assert text in unknown.content.decode() + + +class TestCreateAdminCommand: + def test_creates_admin_and_prints_link(self, capsys: Any) -> None: + from django.core.management import call_command + + call_command("create_admin", "Aino Admin", "aino@example.test") + out = capsys.readouterr().out + assert User.objects.get(email="aino@example.test").role == "admin" + assert "/password/set/setup/" in out + assert reverse("users:login") diff --git a/apps/users/tests/integration/test_user_management.py b/apps/users/tests/integration/test_user_management.py new file mode 100644 index 0000000..9a68b83 --- /dev/null +++ b/apps/users/tests/integration/test_user_management.py @@ -0,0 +1,149 @@ +from collections.abc import Callable +from datetime import date +from typing import Any + +import pytest +from django.core import mail +from django.test import Client + +from apps.shared.domain.value_objects import EmailAddress +from apps.users.domain.entities import UserAccount +from apps.users.domain.enums import Role +from apps.users.domain.value_objects import PersonName +from apps.users.infrastructure.orm import User +from apps.users.infrastructure.repositories import DjangoUserRepository + +pytestmark = pytest.mark.django_db + + +class TestPermissions: + @pytest.mark.parametrize("role", ["management", "employee", "intern", "subcontractor"]) + def test_non_admin_gets_403( + self, client: Client, make_user: Callable[..., User], role: str + ) -> None: + boss = make_user() + extra = ( + {"supervisor": boss, "employment_ends_on": date(2099, 1, 1)} if role == "intern" else {} + ) + client.force_login(make_user(role=role, **extra)) + for path in ("/users/", "/users/new/", f"/users/{boss.pk}/edit/"): + assert client.get(path).status_code == 403 + assert client.post(f"/users/{boss.pk}/password-link/").status_code == 403 + + def test_menu_shows_users_only_to_admin( + self, client: Client, admin_client: Client, make_user: Callable[..., User] + ) -> None: + assert 'href="/users/"' in admin_client.get("/").content.decode() + other = Client() + other.force_login(make_user()) + assert 'href="/users/"' not in other.get("/").content.decode() + + +class TestList: + def test_search_and_htmx_partial( + self, admin_client: Client, make_user: Callable[..., User] + ) -> None: + make_user(name="Eeva Esimerkki") + make_user(name="Kalle Koe") + response = admin_client.get("/users/?q=eeva", headers={"HX-Request": "true"}) + html = response.content.decode() + assert "Eeva Esimerkki" in html + assert "Kalle Koe" not in html + assert " None: + make_user(name="Old Timer", is_active=False) + html = admin_client.get("/users/?active=0").content.decode() + assert "Old Timer" in html + assert "Admin" not in html.split("")[1].split("")[0] + + +class TestCreateAndEdit: + def test_create_user_shows_copyable_link_and_sends_email(self, admin_client: Client) -> None: + response = admin_client.post( + "/users/new/", {"name": "Eeva", "email": "eeva@example.test", "role": "employee"} + ) + html = response.content.decode() + assert response.status_code == 200 + assert "/password/set/setup/" in html + assert "Kopioi" in html + assert len(mail.outbox) == 1 + assert User.objects.get(email="eeva@example.test").has_usable_password() is False + + def test_intern_requires_fields(self, admin_client: Client) -> None: + response = admin_client.post( + "/users/new/", {"name": "Iida", "email": "iida@example.test", "role": "intern"} + ) + assert response.status_code == 422 + assert "Harjoittelijalla on oltava viimeinen päivä." in response.content.decode() + + def test_duplicate_email(self, admin_client: Client, make_user: Callable[..., User]) -> None: + make_user(email="eeva@example.test") + response = admin_client.post( + "/users/new/", {"name": "Eeva", "email": "EEVA@example.test", "role": "employee"} + ) + assert response.status_code == 422 + assert "Tällä sähköpostiosoitteella on jo käyttäjä." in response.content.decode() + + def test_last_admin_cannot_be_deactivated(self, admin_client: Client, admin: User) -> None: + response = admin_client.post( + f"/users/{admin.pk}/edit/", + { + "name": "Admin", + "email": "admin@example.test", + "role": "admin", + }, # is_active unchecked + ) + assert response.status_code == 422 + admin.refresh_from_db() + assert admin.is_active + + def test_edit_saves_and_redirects( + self, admin_client: Client, make_user: Callable[..., User] + ) -> None: + user = make_user(name="Eeva") + response = admin_client.post( + f"/users/{user.pk}/edit/", + {"name": "Eeva Uusi", "email": user.email, "role": "management", "is_active": "on"}, + ) + assert response.status_code == 302 + user.refresh_from_db() + assert (user.name, user.role) == ("Eeva Uusi", "management") + + def test_password_link_partial( + self, admin_client: Client, make_user: Callable[..., User] + ) -> None: + user = make_user() + response = admin_client.post( + f"/users/{user.pk}/password-link/", headers={"HX-Request": "true"} + ) + html = response.content.decode() + assert " None: + assert admin_client.get("/users/9999/edit/").status_code == 404 + + +class TestRepository: + def test_save_and_reload(self) -> None: + repo = DjangoUserRepository() + saved = repo.save( + UserAccount.register( + name=PersonName("Eeva"), email=EmailAddress("eeva@example.test"), role=Role.EMPLOYEE + ) + ) + assert saved.id is not None + assert repo.get_by_email(EmailAddress("EEVA@example.test")) == saved + assert repo.is_email_taken(EmailAddress("eeva@example.test")) + assert not repo.is_email_taken(EmailAddress("eeva@example.test"), exclude_id=saved.id) + + def test_lock_counts_active_admins(self, make_user: Callable[..., User], admin: User) -> None: + make_user(role="admin", is_active=False) + assert DjangoUserRepository().lock_active_admin_count() == 1 + + def test_reconstitute_tolerates_bad_rows(self, make_user: Callable[..., User]) -> Any: + # An intern without supervisor/end date must load (and simply not log in). + bad = make_user(role="intern") + assert DjangoUserRepository().get_by_id(bad.pk) is not None diff --git a/config/asgi.py b/config/asgi.py index ed7c431..cd6907c 100644 --- a/config/asgi.py +++ b/config/asgi.py @@ -11,6 +11,6 @@ import os from django.core.asgi import get_asgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = get_asgi_application() diff --git a/config/settings.py b/config/settings.py index b2af45f..cd52b81 100644 --- a/config/settings.py +++ b/config/settings.py @@ -37,58 +37,76 @@ ALLOWED_HOSTS = [h.strip() for h in os.getenv("DJANGO_ALLOWED_HOSTS", "").split( # Application definition INSTALLED_APPS = [ - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "django.forms", + "django_htmx", + "apps.shared", + "apps.users", ] MIDDLEWARE = [ - 'django.middleware.security.SecurityMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.locale.LocaleMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.auth.middleware.LoginRequiredMiddleware", + "apps.users.presentation.middleware.EnsureAccountIsUsable", + "django_htmx.middleware.HtmxMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", ] -ROOT_URLCONF = 'config.urls' +ROOT_URLCONF = "config.urls" TEMPLATES = [ { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [BASE_DIR / 'templates'], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.request', - 'django.contrib.auth.context_processors.auth', - 'django.contrib.messages.context_processors.messages', + "BACKEND": "django.template.backends.django.DjangoTemplates", + # Project templates + each module's presentation/templates. + "DIRS": [ + BASE_DIR / "templates", + *sorted((BASE_DIR / "apps").glob("*/presentation/templates")), + ], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", ], + "builtins": ["django.templatetags.i18n"], + # Module template tags live in /presentation/templatetags. + "libraries": { + "users_tags": "apps.users.presentation.templatetags.users_tags", + }, }, }, ] -WSGI_APPLICATION = 'config.wsgi.application' +WSGI_APPLICATION = "config.wsgi.application" + +FORM_RENDERER = "apps.shared.presentation.forms.DaisyFormRenderer" # Database # https://docs.djangoproject.com/en/5.2/ref/settings/#databases DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.mysql', - 'NAME': os.getenv('DB_NAME', 'django-toiminnanohjaus'), - 'USER': os.getenv('DB_USER', 'root'), - 'PASSWORD': os.getenv('DB_PASSWORD', ''), - 'HOST': os.getenv('DB_HOST', '127.0.0.1'), - 'PORT': os.getenv('DB_PORT', '3306'), - 'OPTIONS': { - 'charset': 'utf8mb4', - 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", + "default": { + "ENGINE": "django.db.backends.mysql", + "NAME": os.getenv("DB_NAME", "django-toiminnanohjaus"), + "USER": os.getenv("DB_USER", "root"), + "PASSWORD": os.getenv("DB_PASSWORD", ""), + "HOST": os.getenv("DB_HOST", "127.0.0.1"), + "PORT": os.getenv("DB_PORT", "3306"), + "OPTIONS": { + "charset": "utf8mb4", + "init_command": "SET sql_mode='STRICT_TRANS_TABLES'", }, } } @@ -99,16 +117,16 @@ DATABASES = { AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + "NAME": "apps.users.infrastructure.password.ComplexityValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] @@ -116,23 +134,67 @@ AUTH_PASSWORD_VALIDATORS = [ # Internationalization # https://docs.djangoproject.com/en/5.2/topics/i18n/ -LANGUAGE_CODE = 'fi' +LANGUAGE_CODE = "fi" -TIME_ZONE = 'Europe/Helsinki' +TIME_ZONE = "Europe/Helsinki" USE_I18N = True +LANGUAGES = [("fi", "Suomi")] +LOCALE_PATHS = [BASE_DIR / "locale"] + +# Business day boundaries (intern end dates, cash days) are computed in this zone. +BUSINESS_TIME_ZONE = "Europe/Helsinki" + USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.2/howto/static-files/ -STATIC_URL = 'static/' -STATICFILES_DIRS = [BASE_DIR / 'static'] -STATIC_ROOT = BASE_DIR / 'staticfiles' +STATIC_URL = "static/" +STATICFILES_DIRS = [BASE_DIR / "static"] +STATIC_ROOT = BASE_DIR / "staticfiles" # Default primary key field type # https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field -DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" + + +# Authentication (docs/architecture.md, luku 14) +AUTH_USER_MODEL = "users.User" +AUTHENTICATION_BACKENDS = ["apps.users.infrastructure.auth.EmailBackend"] +LOGIN_URL = "users:login" +LOGIN_REDIRECT_URL = "home" +LOGOUT_REDIRECT_URL = "users:login" +PASSWORD_LINK_SETUP_TIMEOUT = 72 * 60 * 60 # link created by an admin +PASSWORD_RESET_TIMEOUT = 60 * 60 # "forgot password" link +SESSION_COOKIE_AGE = 14 * 24 * 60 * 60 # "remember me" + +# Login throttling uses the cache, so it must be shared between processes. +CACHES = { + "default": { + "BACKEND": "django.core.cache.backends.db.DatabaseCache", + "LOCATION": "django_cache", + } +} + +# Email +EMAIL_BACKEND = os.getenv("EMAIL_BACKEND", "django.core.mail.backends.console.EmailBackend") +EMAIL_HOST = os.getenv("EMAIL_HOST", "localhost") +EMAIL_PORT = int(os.getenv("EMAIL_PORT", "25")) +EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER", "") +EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "") +EMAIL_USE_TLS = os.getenv("EMAIL_USE_TLS", "False").lower() in ("1", "true", "yes") +DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "toiminnanohjaus@localhost") + +# Absolute base URL for links in emails. +SITE_URL = os.getenv("SITE_URL", "http://127.0.0.1:8000") + +LOGGING = { + "version": 1, + "disable_existing_loggers": False, + "handlers": {"console": {"class": "logging.StreamHandler"}}, + "root": {"handlers": ["console"], "level": "WARNING"}, +} diff --git a/config/urls.py b/config/urls.py index 35a0802..9d30395 100644 --- a/config/urls.py +++ b/config/urls.py @@ -1,22 +1,8 @@ -""" -URL configuration for config project. +from django.urls import include, path -The `urlpatterns` list routes URLs to views. For more information please see: - https://docs.djangoproject.com/en/5.2/topics/http/urls/ -Examples: -Function views - 1. Add an import: from my_app import views - 2. Add a URL to urlpatterns: path('', views.home, name='home') -Class-based views - 1. Add an import: from other_app.views import Home - 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') -Including another URLconf - 1. Import the include() function: from django.urls import include, path - 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) -""" -from django.contrib import admin -from django.urls import path +from apps.shared.presentation.views import home urlpatterns = [ - path('admin/', admin.site.urls), + path("", home, name="home"), + path("", include("apps.users.presentation.urls")), ] diff --git a/config/wsgi.py b/config/wsgi.py index e2fbd58..27c0377 100644 --- a/config/wsgi.py +++ b/config/wsgi.py @@ -11,6 +11,6 @@ import os from django.core.wsgi import get_wsgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = get_wsgi_application() diff --git a/docs/architecture.md b/docs/architecture.md index fc21847..3f61f65 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -31,9 +31,10 @@ apps/ │ │ ├── events.py # DjangoEventPublisher (on_commit), kuuntelijarekisteri │ │ └── models.py # abstrakti TimestampedModel │ └── presentation/ -│ ├── templates/ # base.html, layout, daisyUI-komponenttien osapohjat (components/) -│ └── templatetags/ -├── users/ # käyttäjät, roolit, kirjautuminen (ks. luku 14) +│ ├── forms.py # DaisyFormRenderer, DaisyFormMixin (daisyUI-luokat, ARIA, domain-virheet) +│ └── views.py +├── users/ # käyttäjät, roolit, kirjautuminen (ks. luku 14) – ensimmäinen valmis moduuli +│ └── presentation/templatetags/users_tags.py # {% load users_tags %}: can, role_label └── customers/ ├── domain/ │ ├── entities.py # Customer (dataclass) @@ -60,11 +61,14 @@ apps/ ├── apps.py # CustomersConfig.ready(): tapahtumakuuntelijat ├── migrations/ └── tests/ # domain/, application/, integration/ +templates/ # yhteiset pohjat: base.html, layouts/auth.html, components/, 403/404 locale/fi/LC_MESSAGES/ # käännökset (django.po) -static/src/app.css # Tailwind + daisyUI -lähde → static/dist/app.css +static/src/app.css, app.js # Tailwind + daisyUI -lähde → static/dist/app.css; teema ja fokus tests/browser/ # selaintestit (Playwright + axe) ``` +- Moduulin templatet ovat `presentation/templates`-kansiossa. Ne lisätään `TEMPLATES['DIRS']`iin asetusten globilla, koska Django etsii appien templateja vain appin juuresta. Template-tagikirjastot rekisteröidään `TEMPLATES['OPTIONS']['libraries']`iin samasta syystä. + - Appin nimi on `apps.customers`, `label` = `customers`. Moduulit rekisteröidään `INSTALLED_APPS`iin. - Migraatiot ovat appin omassa `migrations/`-kansiossa (Djangon käytäntö). Taulujen nimet asetetaan `Meta.db_table`:llä määrittelyn (luku 14) mukaisiksi. - Kansioita ja tiedostoja luodaan vain tarpeeseen. Pienessä moduulissa `use_cases.py` voi olla yksi tiedosto; se jaetaan paketiksi (`use_cases/`), kun se kasvaa. @@ -111,7 +115,7 @@ Käyttöliittymä: **Django-templatet, daisyUI 5 -komponentit, HTMX ja Alpine.js - JSON-rajapinta (esim. Fennoa) lisätään `presentation/api/`-kansioon vasta, kun sitä tarvitaan. ### Kokoamispiste: `container.py` -Moduulin ainoa paikka, joka tuntee sekä application- että infrastructure-luokat. Se tarjoaa tehdasfunktiot, esim. `register_customer() -> RegisterCustomer` ja `customer_queries() -> CustomerQueries`. Testit korvaavat riippuvuudet antamalla fake-toteutukset suoraan use casen konstruktorille. +Moduulin ainoa paikka, joka tuntee sekä application- että infrastructure-luokat. Se tarjoaa tehdasfunktiot, esim. `register_customer() -> RegisterCustomer` ja `customer_queries() -> CustomerQueries`. Testit korvaavat riippuvuudet antamalla fake-toteutukset suoraan use casen konstruktorille. Jos presentation tarvitsee infrastruktuurin palvelua (esim. salasanalinkin tokenin tarkistus), container tarjoaa sille funktion; import-linter estää presentationia importtaamasta infrastructurea suoraan. ## 4. Riippuvuussäännöt @@ -191,7 +195,7 @@ Testityökalu on **pytest + pytest-django** (asetukset `pyproject.toml`:ssa). |---|---|---|---| | Arkkitehtuuri | `lint-imports` | riippuvuussäännöt (luku 4) | ei | | Domain | `apps//tests/domain` | entiteetit, value objectit, invarianssit | ei | -| Application | `apps//tests/application` | use caset fakeilla (`tests/fakes.py`: `InMemoryCustomerRepository`, `FakeUnitOfWork`, `FakeEventPublisher`) | ei | +| Application | `apps//tests/application` | use caset fakeilla (`apps//tests/fakes.py`, esim. users: `InMemoryUserRepository`, `FakeUnitOfWork`, `FakePasswordLinkService`, `FixedClock`) | ei | | Integraatio | `apps//tests/integration` | repositoryt ja kyselyt oikeaa kantaa vasten, näkymät (Django test client, HTMX-otsakkeet), transaktiot ja tapahtumat | kyllä, `@pytest.mark.django_db` | | Selain | `tests/browser` | saavutettavuus (axe-core, vaalea/tumma teema, työpöytä/mobiili), näppäimistökäyttö | kyllä, `pytest-playwright` + `live_server` | @@ -224,8 +228,8 @@ Esimerkki: vaiheen 1 `jobs` (asiakastyöt). ## 12. Käyttöliittymä: daisyUI, HTMX ja Alpine.js - **Tyylit:** Tailwind CSS 4 + daisyUI 5 rakennetaan npm:llä (`package.json`: `npm run dev` = watch, `npm run build` = minifioitu). Lähde `static/src/app.css` (`@import "tailwindcss"; @plugin "daisyui" { themes: light --default, dark --prefersdark; }`, `@source "../../apps/**/templates"`), tuloste `static/dist/app.css`, joka on versionhallinnan ulkopuolella ja rakennetaan julkaisussa. `collectstatic` kokoaa tiedostot `STATIC_ROOT`iin. -- **Komponentit:** käytetään daisyUI:n luokkia (`btn`, `card`, `table`, `input`, `select`, `checkbox`, `modal`, `dropdown`, `menu`, `drawer`, `navbar`, `tabs`, `badge`, `alert`, `toast`, `loading`). Toistuvat rakenteet (lomakekenttä otsikkoineen ja virheineen, vahvistusdialogi, ilmoitus, sivutus) ovat yhteisiä osapohjia `apps/shared/presentation/templates/components/` (`{% include … with … %}`; Djangon `{% partialdef %}` tulee vasta Django 6.0:ssa, tarvittaessa `django-template-partials`). Lomakekentät renderöidään omalla `FormRenderer`illä/kenttäpohjalla, jotta daisyUI-luokat ja ARIA-attribuutit tulevat kaikkiin lomakkeisiin samoin. -- **Teemat:** daisyUI:n `light` ja `dark` (käyttäjän valinta tai `prefers-color-scheme`). Teemavärien kontrasti tarkistetaan (WCAG AA 4,5:1 tekstille); tarvittaessa projektille tehdään oma teema. +- **Komponentit:** käytetään daisyUI:n luokkia (`btn`, `card`, `table`, `input`, `select`, `checkbox`, `modal`, `dropdown`, `menu`, `drawer`, `navbar`, `tabs`, `badge`, `alert`, `toast`, `loading`). Toistuvat rakenteet (lomakekenttä otsikkoineen ja virheineen, vahvistusdialogi, ilmoitus, sivutus) ovat yhteisiä osapohjia projektin `templates/components/`-kansiossa (`{% include … with … %}`; Djangon `{% partialdef %}` tulee vasta Django 6.0:ssa, tarvittaessa `django-template-partials`). Lomakekentät renderöidään omalla `FormRenderer`illä/kenttäpohjalla, jotta daisyUI-luokat ja ARIA-attribuutit tulevat kaikkiin lomakkeisiin samoin. +- **Teemat:** daisyUI:n `light` ja `dark` (käyttäjän valinta tai `prefers-color-scheme`). Daisyn oletusvärit eivät kaikkialla täytä WCAG AA -kontrastia: `static/src/app.css` korjaa soft-alertit ja -badget, `.menu-title`n sekä vaalean teeman error- ja success-värit (`@plugin "daisyui/theme"`). Tekstilinkeissä käytetään `link`-luokkaa, ei `link-primary`a. Selaintestien axe-tarkistus havaitsee regressiot. - **HTMX** (`django-htmx`): lomakkeiden lähetys ja kenttätason tallennus (`hx-post`, `hx-trigger="change"`), haut ja suodattimet (`hx-get` + `hx-push-url`), Kanbanin tilanvaihto, viikkonäkymän solut, dialogien sisältö. CSRF-token lisätään kaikkiin HTMX-pyyntöihin (`hx-headers` body-elementissä). Ilmoitukset palautetaan `HX-Trigger`-otsakkeella tai out-of-band-swapilla (`hx-swap-oob`) toast-alueelle. - **Alpine.js:** vain paikallinen selaintila (dialogin avaus, valikot, laskettu summa ennen tallennusta, vedä ja pudota yhdessä SortableJS:n kanssa). Liiketoimintalogiikkaa ei kirjoiteta JavaScriptiin. - HTMX ja Alpine asennetaan npm:llä ja niputetaan staattisiksi tiedostoiksi; CDN:ää ei käytetä tuotannossa. @@ -244,7 +248,7 @@ WCAG 2.2 AA / EN 301 549 on hyväksymiskriteeri koko käyttöliittymälle. Perus ## 14. Users-moduuli ja kirjautuminen -- **Käyttäjämalli:** oma `User` (`AbstractBaseUser` + `PermissionsMixin`, tunnisteena sähköposti) asetetaan `AUTH_USER_MODEL = "users.User"` **ennen ensimmäistä migraatiota**. Se on users-moduulin infrastructure-malli; Djangon auth, admin ja vierasavaimet (`settings.AUTH_USER_MODEL`) viittaavat siihen. +- **Käyttäjämalli:** oma `User` (`AbstractBaseUser`, tunnisteena sähköposti, ei `PermissionsMixin`iä) on asetettu `AUTH_USER_MODEL = "users.User"`. Se on users-moduulin infrastructure-malli; Djangon auth ja vierasavaimet (`settings.AUTH_USER_MODEL`) viittaavat siihen. Django admin ei ole käytössä, jotta käyttäjiä muutetaan vain use casejen kautta eivätkä domain-säännöt ohitu. - **Roolit** (`Role`): pääkäyttäjä, johto, työntekijä, harjoittelija ja alihankkija. Vain pääkäyttäjä hallitsee käyttäjiä (`users.manage`). Alihankkijat eivät käytä asiakasrekisteriä (`customers.use`). Oikeustarkistukset ovat users-moduulin funktioita (`can(user, "customers.use")`), joita näkymien mixinit ja templatet käyttävät. - **`UserAccount`-entiteetti** on liiketoimintanäkymä käyttäjään. Harjoittelijalla on aina viimeinen päivä ja vastuuhenkilö (aktiivinen johto tai työntekijä); muilla rooleilla niitä ei ole. Viimeistä aktiivista pääkäyttäjää ei voi poistaa käytöstä eikä vaihtaa toiseen rooliin; tarkistus lukitsee pääkäyttäjärivit (`select_for_update`), joten samanaikaiset muutokset eivät ohita sitä. Aktiivisten harjoittelijoiden vastuuhenkilöä ei voi poistaa käytöstä eikä siirtää rooliin, joka ei voi toimia vastuuhenkilönä (`SupervisorHasInterns`). Tallennettu käyttäjä ladataan tarkistamatta sääntöjä (`reconstitute`), jotta virheellinen rivi ei kaada kirjautumista. - **Kirjautuminen:** Djangon `LoginView` omalla authentication-backendillä, joka tarkistaa `CheckLoginAllowed`-ehdon: käyttäjä on aktiivinen eikä harjoittelijan viimeinen päivä ole mennyt. Päivä lasketaan aikavyöhykkeessä `settings.BUSINESS_TIME_ZONE` (oletus `Europe/Helsinki`). Yrityksiä rajoitetaan sähköposti+IP-paria kohden (5 / 5 min, Djangon välimuistilla tai django-axesilla). Väärä salasana ja käytöstä poistettu tunnus saavat saman viestin. diff --git a/locale/fi/LC_MESSAGES/django.po b/locale/fi/LC_MESSAGES/django.po new file mode 100644 index 0000000..fcf6bd9 --- /dev/null +++ b/locale/fi/LC_MESSAGES/django.po @@ -0,0 +1,499 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-11-29 12:10+0200\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: fi\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: .\apps\users\infrastructure\password.py:15 +#, python-format +msgid "The password must be at least %(min)d characters long." +msgstr "Salasanassa on oltava vähintään %(min)d merkkiä." + +#: .\apps\users\infrastructure\password.py:21 +msgid "The password must contain an upper case letter." +msgstr "Salasanassa on oltava iso kirjain." + +#: .\apps\users\infrastructure\password.py:22 +msgid "The password must contain a lower case letter." +msgstr "Salasanassa on oltava pieni kirjain." + +#: .\apps\users\infrastructure\password.py:23 +msgid "The password must contain a digit." +msgstr "Salasanassa on oltava numero." + +#: .\apps\users\infrastructure\password.py:26 +msgid "The password must contain a special character." +msgstr "Salasanassa on oltava erikoismerkki." + +#: .\apps\users\infrastructure\password.py:36 +#, python-format +msgid "" +"At least %(min)d characters, including upper and lower case letters, a digit " +"and a special character." +msgstr "Vähintään %(min)d merkkiä, joista on oltava iso ja pieni kirjain, numero ja erikoismerkki." + +#: .\apps\users\presentation\forms.py:22 .\apps\users\presentation\forms.py:52 +#: .\apps\users\presentation\forms.py:66 +#: .\apps\users\presentation\templates\users\partials\user_table.html:9 +msgid "Email" +msgstr "Sähköposti" + +#: .\apps\users\presentation\forms.py:25 +msgid "Remember me" +msgstr "Muista minut" + +#: .\apps\users\presentation\forms.py:29 .\apps\users\presentation\forms.py:30 +msgid "The email address or password is incorrect." +msgstr "Sähköpostiosoite tai salasana on väärin." + +#: .\apps\users\presentation\forms.py:31 +msgid "Too many login attempts. Try again in a few minutes." +msgstr "Liian monta kirjautumisyritystä. Yritä uudelleen muutaman minuutin kuluttua." + +#: .\apps\users\presentation\forms.py:65 +#: .\apps\users\presentation\templates\users\partials\user_table.html:8 +msgid "Name" +msgstr "Nimi" + +#: .\apps\users\presentation\forms.py:67 .\apps\users\presentation\forms.py:110 +#: .\apps\users\presentation\templates\users\partials\user_table.html:10 +msgid "Role" +msgstr "Rooli" + +#: .\apps\users\presentation\forms.py:68 .\apps\users\presentation\forms.py:115 +#: .\apps\users\presentation\templates\users\partials\user_table.html:23 +msgid "Active" +msgstr "Aktiivinen" + +#: .\apps\users\presentation\forms.py:70 +#: .\apps\users\presentation\templates\users\partials\user_table.html:12 +msgid "Last day" +msgstr "Viimeinen päivä" + +#: .\apps\users\presentation\forms.py:73 +msgid "The intern cannot log in after this day." +msgstr "Harjoittelija ei voi kirjautua tämän päivän jälkeen." + +#: .\apps\users\presentation\forms.py:76 +#: .\apps\users\presentation\templates\users\partials\user_table.html:13 +msgid "Supervisor" +msgstr "Vastuuhenkilö" + +#: .\apps\users\presentation\forms.py:87 +msgid "Choose a supervisor" +msgstr "Valitse vastuuhenkilö" + +#: .\apps\users\presentation\forms.py:108 +msgid "Search" +msgstr "Haku" + +#: .\apps\users\presentation\forms.py:110 +msgid "All roles" +msgstr "Kaikki roolit" + +#: .\apps\users\presentation\forms.py:113 +#: .\apps\users\presentation\templates\users\partials\user_table.html:11 +msgid "Status" +msgstr "Tila" + +#: .\apps\users\presentation\forms.py:115 +msgid "All" +msgstr "Kaikki" + +#: .\apps\users\presentation\forms.py:115 +#: .\apps\users\presentation\templates\users\partials\user_table.html:24 +msgid "Inactive" +msgstr "Ei aktiivinen" + +#: .\apps\users\presentation\labels.py:8 +msgid "Admin" +msgstr "Pääkäyttäjä" + +#: .\apps\users\presentation\labels.py:9 +msgid "Management" +msgstr "Johto" + +#: .\apps\users\presentation\labels.py:10 +msgid "Employee" +msgstr "Työntekijä" + +#: .\apps\users\presentation\labels.py:11 +msgid "Intern" +msgstr "Harjoittelija" + +#: .\apps\users\presentation\labels.py:12 +msgid "Subcontractor" +msgstr "Alihankkija" + +#: .\apps\users\presentation\labels.py:18 +msgid "Enter a name (at most 150 characters)." +msgstr "Anna nimi (enintään 150 merkkiä)." + +#: .\apps\users\presentation\labels.py:19 +msgid "Enter a valid email address." +msgstr "Anna kelvollinen sähköpostiosoite." + +#: .\apps\users\presentation\labels.py:20 +msgid "A user with this email address already exists." +msgstr "Tällä sähköpostiosoitteella on jo käyttäjä." + +#: .\apps\users\presentation\labels.py:21 +msgid "An intern must have an end date." +msgstr "Harjoittelijalla on oltava viimeinen päivä." + +#: .\apps\users\presentation\labels.py:22 +msgid "An intern must have a supervisor." +msgstr "Harjoittelijalla on oltava vastuuhenkilö." + +#: .\apps\users\presentation\labels.py:23 +msgid "The supervisor must be an active management or employee user." +msgstr "Vastuuhenkilön on oltava aktiivinen johdon jäsen tai työntekijä." + +#: .\apps\users\presentation\labels.py:25 +msgid "" +"This is the last active admin. It cannot be deactivated or moved to another " +"role." +msgstr "Tämä on viimeinen aktiivinen pääkäyttäjä. Sitä ei voi poistaa käytöstä eikä siirtää toiseen rooliin." + +#: .\apps\users\presentation\labels.py:28 +msgid "This user supervises active interns. Change their supervisor first." +msgstr "Käyttäjä on aktiivisten harjoittelijoiden vastuuhenkilö. Vaihda ensin heidän vastuuhenkilönsä." + +#: .\apps\users\presentation\labels.py:30 +msgid "The user was not found." +msgstr "Käyttäjää ei löytynyt." + +#: .\apps\users\presentation\labels.py:31 +msgid "The change could not be saved." +msgstr "Muutosta ei voitu tallentaa." + +#: .\apps\users\presentation\templates\users\email\password_link.txt:1 +#, python-format +msgid "Hello %(name)s," +msgstr "Hei %(name)s," + +#: .\apps\users\presentation\templates\users\email\password_link.txt:3 +msgid "You asked for a link for setting a new password." +msgstr "Pyysit linkkiä uuden salasanan asettamiseen." + +#: .\apps\users\presentation\templates\users\email\password_link.txt:3 +msgid "" +"An account has been created or a new password link has been requested for " +"you." +msgstr "Sinulle on luotu käyttäjätunnus tai pyydetty uusi salasanalinkki." + +#: .\apps\users\presentation\templates\users\email\password_link.txt:4 +msgid "Set your password with this link:" +msgstr "Aseta salasanasi tällä linkillä:" + +#: .\apps\users\presentation\templates\users\email\password_link.txt:8 +#, python-format +msgid "The link can be used once and it is valid until %(expires)s." +msgstr "Linkin voi käyttää kerran, ja se on voimassa %(expires)s asti." + +#: .\apps\users\presentation\templates\users\email\password_link.txt:9 +msgid "If you did not expect this message, you can ignore it." +msgstr "Jos et odottanut tätä viestiä, voit jättää sen huomiotta." + +#: .\apps\users\presentation\templates\users\email\password_link_subject.txt:1 +msgid "Set a new password" +msgstr "Aseta uusi salasana" + +#: .\apps\users\presentation\templates\users\email\password_link_subject.txt:1 +msgid "Set your password" +msgstr "Aseta salasanasi" + +#: .\apps\users\presentation\templates\users\forgot_password.html:2 +#: .\apps\users\presentation\templates\users\forgot_password.html:4 +#: .\apps\users\presentation\templates\users\login.html:16 +msgid "Forgot your password?" +msgstr "Unohtuiko salasana?" + +#: .\apps\users\presentation\templates\users\forgot_password.html:5 +msgid "" +"Enter your email address. We will send you a link for setting a new password." +msgstr "Anna sähköpostiosoitteesi. Lähetämme sinulle linkin uuden salasanan asettamiseen." + +#: .\apps\users\presentation\templates\users\forgot_password.html:9 +msgid "Send link" +msgstr "Lähetä linkki" + +#: .\apps\users\presentation\templates\users\forgot_password.html:11 +msgid "Back to login" +msgstr "Takaisin kirjautumiseen" + +#: .\apps\users\presentation\templates\users\form.html:2 +#: .\apps\users\presentation\templates\users\form.html:8 +#: .\apps\users\presentation\templates\users\password_link_page.html:9 +msgid "Edit user" +msgstr "Muokkaa käyttäjää" + +#: .\apps\users\presentation\templates\users\form.html:2 +#: .\apps\users\presentation\templates\users\form.html:6 +#: .\apps\users\presentation\templates\users\form.html:8 +#: .\apps\users\presentation\templates\users\list.html:6 +msgid "New user" +msgstr "Uusi käyttäjä" + +#: .\apps\users\presentation\templates\users\form.html:4 +msgid "Breadcrumbs" +msgstr "Murupolku" + +#: .\apps\users\presentation\templates\users\form.html:5 +#: .\apps\users\presentation\templates\users\list.html:2 +#: .\apps\users\presentation\templates\users\list.html:5 +#: .\apps\users\presentation\templates\users\partials\user_table.html:5 +#: .\templates\base.html:56 +msgid "Users" +msgstr "Käyttäjät" + +#: .\apps\users\presentation\templates\users\form.html:20 +msgid "An intern must have a last day and a supervisor." +msgstr "Harjoittelijalla on oltava viimeinen päivä ja vastuuhenkilö." + +#: .\apps\users\presentation\templates\users\form.html:26 +#: .\templates\components\confirm_dialog.html:8 +msgid "Cancel" +msgstr "Peruuta" + +#: .\apps\users\presentation\templates\users\form.html:27 +msgid "Save" +msgstr "Tallenna" + +#: .\apps\users\presentation\templates\users\form.html:35 +#: .\apps\users\presentation\templates\users\password_link_page.html:2 +msgid "Password link" +msgstr "Salasanalinkki" + +#: .\apps\users\presentation\templates\users\form.html:36 +msgid "" +"Creates a new link for setting the password. The link is emailed to the user " +"and shown here for copying. Earlier links stop working." +msgstr "Luo uuden linkin salasanan asettamiseen. Linkki lähetetään käyttäjälle sähköpostilla ja näytetään tässä kopioitavaksi. Aiemmat linkit lakkaavat toimimasta." + +#: .\apps\users\presentation\templates\users\form.html:37 +msgid "Create password link" +msgstr "Luo salasanalinkki" + +#: .\apps\users\presentation\templates\users\form.html:42 +msgid "Create a new password link?" +msgstr "Luodaanko uusi salasanalinkki?" + +#: .\apps\users\presentation\templates\users\form.html:43 +msgid "Earlier links of this user stop working." +msgstr "Käyttäjän aiemmat linkit lakkaavat toimimasta." + +#: .\apps\users\presentation\templates\users\form.html:44 +msgid "Create link" +msgstr "Luo linkki" + +#: .\apps\users\presentation\templates\users\list.html:9 +msgid "Filter users" +msgstr "Suodata käyttäjiä" + +#: .\apps\users\presentation\templates\users\list.html:17 +msgid "Filter" +msgstr "Suodata" + +#: .\apps\users\presentation\templates\users\login.html:2 +#: .\apps\users\presentation\templates\users\login.html:4 +#: .\apps\users\presentation\templates\users\login.html:14 +msgid "Log in" +msgstr "Kirjaudu" + +#: .\apps\users\presentation\templates\users\login.html:7 +msgid "" +"Your access has ended: the account has been deactivated or the internship " +"has ended. Contact the admin if you think this is a mistake." +msgstr "Käyttöoikeutesi on päättynyt: tunnus on poistettu käytöstä tai harjoittelu on päättynyt. Ota yhteyttä pääkäyttäjään, jos tämä on mielestäsi virhe." + +#: .\apps\users\presentation\templates\users\partials\password_link.html:4 +#, python-format +msgid "The link has been emailed to %(email)s." +msgstr "Linkki on lähetetty osoitteeseen %(email)s." + +#: .\apps\users\presentation\templates\users\partials\password_link.html:6 +msgid "Sending the email failed." +msgstr "Sähköpostin lähetys epäonnistui." + +#: .\apps\users\presentation\templates\users\partials\password_link.html:7 +msgid "Deliver the link to the user in another way." +msgstr "Toimita linkki käyttäjälle muuta kautta." + +#: .\apps\users\presentation\templates\users\partials\password_link.html:9 +#, python-format +msgid "Valid until %(expires)s." +msgstr "Voimassa %(expires)s asti." + +#: .\apps\users\presentation\templates\users\partials\password_link.html:11 +msgid "Link" +msgstr "Linkki" + +#: .\apps\users\presentation\templates\users\partials\password_link.html:15 +#: .\apps\users\presentation\templates\users\partials\password_link.html:19 +msgid "Link copied" +msgstr "Linkki kopioitu" + +#: .\apps\users\presentation\templates\users\partials\password_link.html:16 +msgid "Copy" +msgstr "Kopioi" + +#: .\apps\users\presentation\templates\users\partials\user_table.html:2 +#, python-format +msgid "%(counter)s user found" +msgid_plural "%(counter)s users found" +msgstr[0] "%(counter)s käyttäjä löytyi" +msgstr[1] "%(counter)s käyttäjää löytyi" + +#: .\apps\users\presentation\templates\users\partials\user_table.html:30 +msgid "No users match the filters." +msgstr "Hakuehtoja vastaavia käyttäjiä ei löytynyt." + +#: .\apps\users\presentation\templates\users\partials\user_table.html:36 +msgid "Pages" +msgstr "Sivut" + +#: .\apps\users\presentation\templates\users\partials\user_table.html:39 +msgid "Previous" +msgstr "Edellinen" + +#: .\apps\users\presentation\templates\users\partials\user_table.html:41 +#, python-format +msgid "Page %(n)s / %(total)s" +msgstr "Sivu %(n)s / %(total)s" + +#: .\apps\users\presentation\templates\users\partials\user_table.html:44 +msgid "Next" +msgstr "Seuraava" + +#: .\apps\users\presentation\templates\users\password_link_page.html:4 +#, python-format +msgid "Password link for %(name)s" +msgstr "Salasanalinkki: %(name)s" + +#: .\apps\users\presentation\templates\users\password_link_page.html:10 +msgid "Back to users" +msgstr "Takaisin käyttäjiin" + +#: .\apps\users\presentation\templates\users\set_password.html:2 +#: .\apps\users\presentation\templates\users\set_password.html:4 +#: .\apps\users\presentation\templates\users\set_password.html:8 +msgid "Set password" +msgstr "Aseta salasana" + +#: .\apps\users\presentation\templates\users\set_password_invalid.html:2 +#: .\apps\users\presentation\templates\users\set_password_invalid.html:4 +msgid "The link is not valid" +msgstr "Linkki ei ole voimassa" + +#: .\apps\users\presentation\templates\users\set_password_invalid.html:5 +msgid "" +"The link has expired, it has already been used, or a newer link has been " +"created. Request a new link or ask the admin to create one." +msgstr "Linkki on vanhentunut, sitä on jo käytetty tai sen jälkeen on luotu uusi linkki. Tilaa uusi linkki tai pyydä pääkäyttäjää luomaan se." + +#: .\apps\users\presentation\templates\users\set_password_invalid.html:6 +msgid "Request a new link" +msgstr "Tilaa uusi linkki" + +#: .\apps\users\presentation\views.py:58 +msgid "" +"If the address belongs to a user who may log in, a link for setting the " +"password has been sent to it. The link is valid for 60 minutes." +msgstr "Jos osoite kuuluu käyttäjälle, joka saa kirjautua, siihen on lähetetty linkki salasanan asettamiseen. Linkki on voimassa 60 minuuttia." + +#: .\apps\users\presentation\views.py:95 +msgid "Your password has been set. You can now log in." +msgstr "Salasana on asetettu. Voit nyt kirjautua." + +#: .\apps\users\presentation\views.py:144 +msgid "User created." +msgstr "Käyttäjä luotu." + +#: .\apps\users\presentation\views.py:196 +msgid "Changes saved." +msgstr "Muutokset tallennettu." + +#: .\templates\403.html:2 .\templates\403.html:4 +msgid "Access denied" +msgstr "Ei käyttöoikeutta" + +#: .\templates\403.html:5 +msgid "You do not have permission to view this page." +msgstr "Sinulla ei ole oikeutta tähän sivuun." + +#: .\templates\403.html:6 .\templates\404.html:6 +msgid "Back to home" +msgstr "Takaisin etusivulle" + +#: .\templates\404.html:2 .\templates\404.html:4 +msgid "Page not found" +msgstr "Sivua ei löydy" + +#: .\templates\404.html:5 +msgid "The page you requested does not exist." +msgstr "Pyytämääsi sivua ei ole olemassa." + +#: .\templates\base.html:20 +msgid "Skip to content" +msgstr "Siirry sisältöön" + +#: .\templates\base.html:23 +msgid "Show menu" +msgstr "Näytä valikko" + +#: .\templates\base.html:26 +msgid "Open menu" +msgstr "Avaa valikko" + +#: .\templates\base.html:38 +msgid "Log out" +msgstr "Kirjaudu ulos" + +#: .\templates\base.html:50 +msgid "Close menu" +msgstr "Sulje valikko" + +#: .\templates\base.html:51 +msgid "Main menu" +msgstr "Päävalikko" + +#: .\templates\base.html:53 .\templates\home.html:2 +msgid "Home" +msgstr "Etusivu" + +#: .\templates\base.html:55 +msgid "Administration" +msgstr "Hallinto" + +#: .\templates\components\field.html:10 +msgid "(required)" +msgstr "(pakollinen)" + +#: .\templates\components\theme_toggle.html:5 +msgid "Dark theme" +msgstr "Tumma teema" + +#: .\templates\home.html:4 +#, python-format +msgid "Welcome, %(name)s" +msgstr "Tervetuloa, %(name)s" + +#: .\templates\home.html:5 +msgid "The dashboard will be built in a later step." + +msgstr "Työpöytä rakennetaan myöhemmässä vaiheessa." \ No newline at end of file diff --git a/manage.py b/manage.py index 8e7ac79..aabb818 100644 --- a/manage.py +++ b/manage.py @@ -1,12 +1,13 @@ #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" + import os import sys def main(): """Run administrative tasks.""" - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: @@ -18,5 +19,5 @@ def main(): execute_from_command_line(sys.argv) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..633525c --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1654 @@ +{ + "name": "toiminnanohjaus", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "toiminnanohjaus", + "devDependencies": { + "@tailwindcss/cli": "^4.3.5", + "alpinejs": "^3.17.5", + "daisyui": "^5.8.3", + "htmx.org": "^2.0.11", + "tailwindcss": "^4.3.5" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@parcel/watcher": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", + "dev": true, + "hasInstallScript": true, + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0" + } + }, + "node_modules/@parcel/watcher-android-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/cli": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.5.tgz", + "integrity": "sha512-+evrrLZEgNPDXgdIxD6Zfc23WhSYZQeGwniO5u9M4zC92kbEtIjKd8l2QWeO7du8kl4gF8z7YArnUGHG4y2Jzg==", + "dev": true, + "dependencies": { + "@parcel/watcher": "2.6.0", + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "enhanced-resolve": "^5.24.5", + "mri": "^1.2.0", + "picocolors": "^1.1.1", + "tailwindcss": "4.3.5" + }, + "bin": { + "tailwindcss": "dist/index.mjs" + } + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", + "dev": true, + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "dev": true, + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "dev": true, + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.46.tgz", + "integrity": "sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==", + "dev": true, + "dependencies": { + "@vue/shared": "3.5.46" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.46.tgz", + "integrity": "sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==", + "dev": true + }, + "node_modules/alpinejs": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.5.tgz", + "integrity": "sha512-XewMqRC6zjy8iaUPn86dxjvooAsNai3hUtQbdn0A5H2w7Jt10xHGZ1SczN5+Dvp3UKkuSEt9moy/UaUWOwKdnQ==", + "dev": true, + "dependencies": { + "@vue/reactivity": "~3.5.40" + } + }, + "node_modules/daisyui": { + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.8.3.tgz", + "integrity": "sha512-BCMsfKOgxxYWt4tYezGkn9VR/4IUqtnPFRSBvBjavI3n8sfk2t0CE1oGk4yQJSsd5x6beT1oGZt/WUvVeEP40g==", + "dev": true, + "funding": { + "url": "https://github.com/saadeghi/daisyui?sponsor=1" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true + }, + "node_modules/htmx.org": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/htmx.org/-/htmx.org-2.0.11.tgz", + "integrity": "sha512-Thx/WtpeOQqSrqBCw/A1cwGJGg4UrVa3+sW0GmrM3p4gJgO89ecH4qtbnyzDDWFvBTqjnIMCgELTNt636dtamA==", + "dev": true + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "dev": true + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "dev": true + }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "dev": true, + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + } + }, + "dependencies": { + "@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "requires": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "requires": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true + }, + "@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true + }, + "@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "@parcel/watcher": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", + "dev": true, + "requires": { + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0", + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + } + }, + "@parcel/watcher-android-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", + "dev": true, + "optional": true + }, + "@parcel/watcher-darwin-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", + "dev": true, + "optional": true + }, + "@parcel/watcher-darwin-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", + "dev": true, + "optional": true + }, + "@parcel/watcher-freebsd-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", + "dev": true, + "optional": true + }, + "@parcel/watcher-linux-arm-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", + "dev": true, + "optional": true + }, + "@parcel/watcher-linux-arm-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", + "dev": true, + "optional": true + }, + "@parcel/watcher-linux-arm64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", + "dev": true, + "optional": true + }, + "@parcel/watcher-linux-arm64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", + "dev": true, + "optional": true + }, + "@parcel/watcher-linux-x64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", + "dev": true, + "optional": true + }, + "@parcel/watcher-linux-x64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", + "dev": true, + "optional": true + }, + "@parcel/watcher-win32-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", + "dev": true, + "optional": true + }, + "@parcel/watcher-win32-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", + "dev": true, + "optional": true + }, + "@tailwindcss/cli": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.5.tgz", + "integrity": "sha512-+evrrLZEgNPDXgdIxD6Zfc23WhSYZQeGwniO5u9M4zC92kbEtIjKd8l2QWeO7du8kl4gF8z7YArnUGHG4y2Jzg==", + "dev": true, + "requires": { + "@parcel/watcher": "2.6.0", + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "enhanced-resolve": "^5.24.5", + "mri": "^1.2.0", + "picocolors": "^1.1.1", + "tailwindcss": "4.3.5" + } + }, + "@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", + "dev": true, + "requires": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } + }, + "@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "dev": true, + "requires": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "dev": true, + "optional": true, + "requires": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "dependencies": { + "@emnapi/core": { + "version": "1.11.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "@emnapi/runtime": { + "version": "1.11.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "tslib": "^2.4.0" + } + }, + "@emnapi/wasi-threads": { + "version": "1.2.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "tslib": "^2.4.0" + } + }, + "@napi-rs/wasm-runtime": { + "version": "1.2.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "@tybys/wasm-util": "^0.10.3" + } + }, + "@tybys/wasm-util": { + "version": "0.10.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "tslib": "^2.4.0" + } + }, + "tslib": { + "version": "2.8.1", + "bundled": true, + "dev": true, + "optional": true + } + } + }, + "@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "dev": true, + "optional": true + }, + "@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "dev": true, + "optional": true + }, + "@vue/reactivity": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.46.tgz", + "integrity": "sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==", + "dev": true, + "requires": { + "@vue/shared": "3.5.46" + } + }, + "@vue/shared": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.46.tgz", + "integrity": "sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==", + "dev": true + }, + "alpinejs": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.17.5.tgz", + "integrity": "sha512-XewMqRC6zjy8iaUPn86dxjvooAsNai3hUtQbdn0A5H2w7Jt10xHGZ1SczN5+Dvp3UKkuSEt9moy/UaUWOwKdnQ==", + "dev": true, + "requires": { + "@vue/reactivity": "~3.5.40" + } + }, + "daisyui": { + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.8.3.tgz", + "integrity": "sha512-BCMsfKOgxxYWt4tYezGkn9VR/4IUqtnPFRSBvBjavI3n8sfk2t0CE1oGk4yQJSsd5x6beT1oGZt/WUvVeEP40g==", + "dev": true + }, + "detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true + }, + "enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + } + }, + "graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true + }, + "htmx.org": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/htmx.org/-/htmx.org-2.0.11.tgz", + "integrity": "sha512-Thx/WtpeOQqSrqBCw/A1cwGJGg4UrVa3+sW0GmrM3p4gJgO89ecH4qtbnyzDDWFvBTqjnIMCgELTNt636dtamA==", + "dev": true + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true + }, + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true + }, + "lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "requires": { + "detect-libc": "^2.0.3", + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "dev": true, + "optional": true + }, + "lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "dev": true, + "optional": true + }, + "lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "dev": true, + "optional": true + }, + "lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "dev": true, + "optional": true + }, + "lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "dev": true, + "optional": true + }, + "lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "dev": true, + "optional": true + }, + "lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "dev": true, + "optional": true + }, + "lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "dev": true, + "optional": true + }, + "lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "dev": true, + "optional": true + }, + "lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "dev": true, + "optional": true + }, + "lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "dev": true, + "optional": true + }, + "magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "requires": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true + }, + "node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "dev": true + }, + "picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true + }, + "source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "dev": true + }, + "tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "dev": true + }, + "tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..af46285 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "toiminnanohjaus", + "private": true, + "type": "module", + "scripts": { + "build:css": "tailwindcss -i static/src/app.css -o static/dist/app.css --minify", + "dev:css": "tailwindcss -i static/src/app.css -o static/dist/app.css --watch", + "vendor": "node scripts/copy-vendor.mjs", + "build": "npm run vendor && npm run build:css", + "dev": "npm run vendor && npm run dev:css" + }, + "devDependencies": { + "@tailwindcss/cli": "^4.3.5", + "alpinejs": "^3.17.5", + "daisyui": "^5.8.3", + "htmx.org": "^2.0.11", + "tailwindcss": "^4.3.5" + } +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..8135b52 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,83 @@ +[project] +name = "toiminnanohjaus" +version = "0.1.0" +requires-python = ">=3.14" + +[tool.pytest.ini_options] +DJANGO_SETTINGS_MODULE = "config.settings" +python_files = ["test_*.py"] +testpaths = ["apps"] +addopts = "-p no:cacheprovider --strict-markers" +markers = [ + "browser: Playwright browser tests (run: pytest tests/browser -m browser)", +] + +[tool.ruff] +line-length = 100 +target-version = "py314" +extend-exclude = ["*/migrations/*", "node_modules", "static"] + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "UP", "B", "DJ", "SIM", "RUF"] +ignore = ["RUF001", "RUF002", "RUF003", "RUF012", "DJ008"] + +[tool.mypy] +python_version = "3.14" +plugins = ["mypy_django_plugin.main"] +ignore_missing_imports = true +exclude = ["migrations/", "tests/"] + +[[tool.mypy.overrides]] +module = ["apps.*.domain.*", "apps.*.application.*"] +strict = true + +[tool.django-stubs] +django_settings_module = "config.settings" + +[tool.importlinter] +root_package = "apps" +include_external_packages = true + +[[tool.importlinter.contracts]] +name = "Domain and application layers do not depend on Django" +type = "forbidden" +source_modules = [ + "apps.shared.domain", + "apps.shared.application", + "apps.users.domain", + "apps.users.application", +] +forbidden_modules = ["django"] +allow_indirect_imports = true + +[[tool.importlinter.contracts]] +name = "users layers" +type = "layers" +layers = [ + "apps.users.container", + "apps.users.presentation", + "apps.users.infrastructure", + "apps.users.application", + "apps.users.domain", +] +ignore_imports = [ + # Composition root and presentation may both see the container. + "apps.users.presentation.** -> apps.users.container", +] + +[[tool.importlinter.contracts]] +name = "Presentation does not use infrastructure directly" +type = "forbidden" +source_modules = ["apps.users.presentation"] +forbidden_modules = ["apps.users.infrastructure"] +allow_indirect_imports = true + +[[tool.importlinter.contracts]] +name = "shared layers" +type = "layers" +layers = [ + "apps.shared.presentation", + "apps.shared.infrastructure", + "apps.shared.application", + "apps.shared.domain", +] diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..ea9199a --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,10 @@ +-r requirements.txt +pytest +pytest-django +factory-boy +ruff +mypy +django-stubs[compatible-mypy] +import-linter +pytest-playwright +axe-playwright-python diff --git a/requirements.txt b/requirements.txt index 0db721d..1c99eb9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ Django>=5.2,<5.3 mysqlclient python-dotenv +django-htmx diff --git a/scripts/copy-vendor.mjs b/scripts/copy-vendor.mjs new file mode 100644 index 0000000..d960473 --- /dev/null +++ b/scripts/copy-vendor.mjs @@ -0,0 +1,12 @@ +// Copies HTMX and Alpine.js builds from node_modules to static/dist. +import { copyFileSync, mkdirSync } from "node:fs"; + +const files = [ + ["node_modules/htmx.org/dist/htmx.min.js", "static/dist/htmx.min.js"], + ["node_modules/alpinejs/dist/cdn.min.js", "static/dist/alpine.min.js"], +]; +mkdirSync("static/dist", { recursive: true }); +for (const [from, to] of files) { + copyFileSync(from, to); + console.log(`${from} -> ${to}`); +} diff --git a/static/src/app.css b/static/src/app.css new file mode 100644 index 0000000..285263c --- /dev/null +++ b/static/src/app.css @@ -0,0 +1,38 @@ +@import "tailwindcss"; +@plugin "daisyui" { + themes: light --default, dark --prefersdark; +} + +@source "../../apps"; +@source "../../templates"; + +/* Visible focus for all interactive elements (WCAG 2.4.7 / 2.4.11). */ +:focus-visible { + outline: 3px solid var(--color-primary); + outline-offset: 2px; +} + +[x-cloak] { + display: none !important; +} + +/* WCAG AA: daisyUI soft variants colour their text with the variant colour, + which is too light on the tinted background. Keep the tint, use body text colour. */ +.alert-soft, +.badge-soft { + color: var(--color-base-content); +} + +.menu-title { + color: var(--color-base-content); +} + +/* Status colours used as text must reach 4.5:1 on the light background. */ +@plugin "daisyui/theme" { + name: "light"; + default: true; + --color-error: oklch(50% 0.19 25); + --color-error-content: oklch(100% 0 0); + --color-success: oklch(48% 0.12 155); + --color-success-content: oklch(100% 0 0); +} diff --git a/static/src/app.js b/static/src/app.js new file mode 100644 index 0000000..b18dca5 --- /dev/null +++ b/static/src/app.js @@ -0,0 +1,31 @@ +// Shared client behaviour: theme toggle and focus management after HTMX swaps. +(function () { + const THEME_KEY = "theme"; + + window.setTheme = function (theme) { + document.documentElement.setAttribute("data-theme", theme); + localStorage.setItem(THEME_KEY, theme); + }; + + document.addEventListener("htmx:afterSettle", function (event) { + const target = event.detail.target; + if (!target) return; + const focusable = target.querySelector("[data-autofocus]"); + if (focusable) { + focusable.focus(); + } + }); + + // Announce HX-Trigger "notify" events in the live region and as a toast. + document.body.addEventListener("notify", function (event) { + window.notify(event.detail.value || event.detail.message || ""); + }); + + window.notify = function (message) { + const live = document.getElementById("live-region"); + if (live) { + live.textContent = ""; + window.setTimeout(function () { live.textContent = message; }, 50); + } + }; +})(); diff --git a/templates/403.html b/templates/403.html new file mode 100644 index 0000000..28ccaa5 --- /dev/null +++ b/templates/403.html @@ -0,0 +1,7 @@ +{% extends "layouts/auth.html" %}{% load i18n %} +{% block title %}{% translate "Access denied" %}{% endblock %} +{% block content %} +

{% translate "Access denied" %}

+

{% translate "You do not have permission to view this page." %}

+ {% translate "Back to home" %} +{% endblock %} diff --git a/templates/404.html b/templates/404.html new file mode 100644 index 0000000..e54857b --- /dev/null +++ b/templates/404.html @@ -0,0 +1,7 @@ +{% extends "layouts/auth.html" %}{% load i18n %} +{% block title %}{% translate "Page not found" %}{% endblock %} +{% block content %} +

{% translate "Page not found" %}

+

{% translate "The page you requested does not exist." %}

+ {% translate "Back to home" %} +{% endblock %} diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..765d4c4 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,75 @@ +{% load static i18n users_tags %} +{% get_current_language as LANGUAGE_CODE %} + + + + + {% block title %}{% endblock %} – Toiminnanohjaus + + + + + + + + {% translate "Skip to content" %} + {% block layout %} +
+ +
+ +
+ {% include "components/messages.html" %} + {% block content %}{% endblock %} +
+
+
+ + +
+
+ {% endblock %} +
+ + diff --git a/templates/components/confirm_dialog.html b/templates/components/confirm_dialog.html new file mode 100644 index 0000000..affc903 --- /dev/null +++ b/templates/components/confirm_dialog.html @@ -0,0 +1,17 @@ +{% load i18n %} +{# Usage: include with id, title, body, action_url, confirm_label (and optional hx_target). #} + + + diff --git a/templates/components/field.html b/templates/components/field.html new file mode 100644 index 0000000..6718a11 --- /dev/null +++ b/templates/components/field.html @@ -0,0 +1,23 @@ +{% load i18n %}{% with widget_type=field.widget_type %} +
+ {% if widget_type == "checkbox" %} + + {% else %} + + {{ field }} + {% endif %} + {% if field.help_text %} +

{{ field.help_text }}

+ {% endif %} + {% if field.errors %} +

+ {% for error in field.errors %}{{ error }}{% if not forloop.last %} {% endif %}{% endfor %} +

+ {% endif %} +
+{% endwith %} diff --git a/templates/components/form.html b/templates/components/form.html new file mode 100644 index 0000000..937066c --- /dev/null +++ b/templates/components/form.html @@ -0,0 +1,3 @@ +{% include "components/non_field_errors.html" %} +{% for field, errors in fields %}{{ field.as_field_group }}{% endfor %} +{% for field in hidden_fields %}{{ field }}{% endfor %} diff --git a/templates/components/messages.html b/templates/components/messages.html new file mode 100644 index 0000000..fe1dd45 --- /dev/null +++ b/templates/components/messages.html @@ -0,0 +1,9 @@ +{% if messages %} +
+ {% for message in messages %} +
+ {{ message }} +
+ {% endfor %} +
+{% endif %} diff --git a/templates/components/non_field_errors.html b/templates/components/non_field_errors.html new file mode 100644 index 0000000..7f55a1a --- /dev/null +++ b/templates/components/non_field_errors.html @@ -0,0 +1,5 @@ +{% if form.non_field_errors %} + +{% endif %} diff --git a/templates/components/theme_toggle.html b/templates/components/theme_toggle.html new file mode 100644 index 0000000..599ff3a --- /dev/null +++ b/templates/components/theme_toggle.html @@ -0,0 +1,7 @@ +{% load i18n %} +
+ +
diff --git a/templates/home.html b/templates/home.html new file mode 100644 index 0000000..b5aaa24 --- /dev/null +++ b/templates/home.html @@ -0,0 +1,6 @@ +{% extends "base.html" %}{% load i18n %} +{% block title %}{% translate "Home" %}{% endblock %} +{% block content %} +

{% blocktranslate with name=request.user.name %}Welcome, {{ name }}{% endblocktranslate %}

+

{% translate "The dashboard will be built in a later step." %}

+{% endblock %} diff --git a/templates/layouts/auth.html b/templates/layouts/auth.html new file mode 100644 index 0000000..62c5172 --- /dev/null +++ b/templates/layouts/auth.html @@ -0,0 +1,13 @@ +{% extends "base.html" %}{% load i18n %} +{% block layout %} +
+
{% include "components/theme_toggle.html" %}
+
+
+

Toiminnanohjaus

+ {% include "components/messages.html" %} + {% block content %}{% endblock %} +
+
+
+{% endblock %} diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/browser/__init__.py b/tests/browser/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/browser/conftest.py b/tests/browser/conftest.py new file mode 100644 index 0000000..23ceac0 --- /dev/null +++ b/tests/browser/conftest.py @@ -0,0 +1,40 @@ +"""Playwright + axe browser tests. Run: pytest tests/browser -m browser (after npm run build).""" + +import os +from collections.abc import Callable +from typing import Any + +import pytest + +# Playwright's sync API runs an event loop; Django ORM calls in fixtures are still synchronous. +os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "true") + +PASSWORD = "Vahva-Salasana-2026" + +VIEWPORTS = {"desktop": {"width": 1920, "height": 1080}, "mobile": {"width": 320, "height": 640}} + + +def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: + for item in items: + item.add_marker(pytest.mark.browser) + + +@pytest.fixture +def admin_user(transactional_db: Any) -> Any: + from apps.users.infrastructure.orm import User + + return User.objects.create_user( + email="admin@example.test", name="Aino Admin", password=PASSWORD, role="admin" + ) + + +@pytest.fixture +def login(live_server: Any) -> Callable[[Any, str], None]: + def do_login(page: Any, email: str) -> None: + page.goto(f"{live_server.url}/login/") + page.fill("#id_username", email) + page.fill("#id_password", PASSWORD) + page.click("button[type=submit]") + page.wait_for_url(f"{live_server.url}/") + + return do_login diff --git a/tests/browser/test_accessibility.py b/tests/browser/test_accessibility.py new file mode 100644 index 0000000..e6ac8bb --- /dev/null +++ b/tests/browser/test_accessibility.py @@ -0,0 +1,113 @@ +from collections.abc import Callable +from typing import Any + +import pytest +from axe_playwright_python.sync_playwright import Axe + +from tests.browser.conftest import VIEWPORTS + +THEMES = ["light", "dark"] + + +def assert_accessible(page: Any) -> None: + results = Axe().run( + page, options={"runOnly": ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]} + ) + assert results.violations_count == 0, results.generate_report() + + +def no_horizontal_scroll(page: Any) -> bool: + return bool(page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")) + + +@pytest.fixture +def themed_page(browser: Any, request: pytest.FixtureRequest) -> Any: + theme, viewport = request.param + context = browser.new_context(viewport=VIEWPORTS[viewport]) + context.add_init_script(f"localStorage.setItem('theme', '{theme}')") + page = context.new_page() + yield page + context.close() + + +ALL = [(t, v) for t in THEMES for v in VIEWPORTS] + + +@pytest.mark.parametrize("themed_page", ALL, indirect=True, ids=lambda p: f"{p[0]}-{p[1]}") +def test_public_pages(themed_page: Any, live_server: Any, transactional_db: Any) -> None: + for path in ( + "/login/", + "/login/?access=ended", + "/password/forgot/", + "/password/set/setup/x/y/", + ): + themed_page.goto(f"{live_server.url}{path}") + assert_accessible(themed_page) + assert no_horizontal_scroll(themed_page), path + + +@pytest.mark.parametrize("themed_page", ALL, indirect=True, ids=lambda p: f"{p[0]}-{p[1]}") +def test_user_management_pages( + themed_page: Any, live_server: Any, admin_user: Any, login: Callable[[Any, str], None] +) -> None: + login(themed_page, admin_user.email) + for path in ("/", "/users/", "/users/new/", f"/users/{admin_user.pk}/edit/"): + themed_page.goto(f"{live_server.url}{path}") + assert_accessible(themed_page) + assert no_horizontal_scroll(themed_page), path + + +def test_form_errors_are_accessible( + page: Any, live_server: Any, admin_user: Any, login: Callable[[Any, str], None] +) -> None: + login(page, admin_user.email) + page.goto(f"{live_server.url}/users/new/") + page.select_option("#id_role", "intern") + page.click("main button[type=submit]") + end_date = page.locator("#id_name") + assert end_date.get_attribute("aria-invalid") == "true" + assert "id_name_error" in (end_date.get_attribute("aria-describedby") or "") + assert_accessible(page) + + +def test_keyboard_password_link_flow( + page: Any, live_server: Any, admin_user: Any, login: Callable[[Any, str], None] +) -> None: + """Create a password link with the keyboard only and copy it.""" + page.context.grant_permissions(["clipboard-read", "clipboard-write"]) + login(page, admin_user.email) + page.goto(f"{live_server.url}/users/{admin_user.pk}/edit/") + page.get_by_role("button", name="Luo salasanalinkki").focus() + page.keyboard.press("Enter") + dialog = page.locator("dialog#confirm-password-link") + assert dialog.evaluate("d => d.open") + page.get_by_role("button", name="Luo linkki").focus() + page.keyboard.press("Enter") + link_box = page.locator("#password-link-box") + link_box.wait_for() + assert not dialog.evaluate("d => d.open") + page.wait_for_timeout(500) # let the modal close animation finish before axe + page.get_by_role("button", name="Kopioi").focus() + page.keyboard.press("Enter") + page.wait_for_function( + "document.getElementById('live-region').textContent.includes('kopioitu')" + ) + copied = page.evaluate("navigator.clipboard.readText()") + assert "/password/set/setup/" in copied + assert_accessible(page) + + +def test_htmx_search_updates_table( + page: Any, live_server: Any, admin_user: Any, login: Callable[[Any, str], None] +) -> None: + from apps.users.infrastructure.orm import User + + User.objects.create_user(email="eeva@example.test", name="Eeva Esimerkki") + login(page, admin_user.email) + page.goto(f"{live_server.url}/users/") + page.fill("#id_q", "eeva") + page.wait_for_url("**/users/?q=eeva**") + rows = page.locator("#user-table tbody tr") + rows.first.wait_for() + assert rows.count() == 1 + assert "Eeva Esimerkki" in rows.first.inner_text()