Vaihe 1/1: users-moduuli, kirjautuminen ja käyttäjähallinta

- shared-moduuli: DomainError, EmailAddress, UnitOfWork, tapahtumat,
  TimestampedModel, daisyUI-lomakerenderöinti ja yhteiset pohjat
- users-moduuli Clean Architecture -kerroksin: oma käyttäjämalli
  (AUTH_USER_MODEL), roolit ja oikeudet, harjoittelija-, vastuuhenkilö-
  ja viimeisen pääkäyttäjän säännöt
- kirjautuminen sähköpostilla, yritysten rajoitus, "muista minut",
  istunnon katkaisu kun tunnus poistetaan käytöstä tai harjoittelu päättyy
- kertakäyttöiset salasanalinkit (72 h / 60 min, uusi mitätöi vanhan),
  salasanasääntö ja create_admin-komento
- käyttäjähallinta: lista (HTMX-haku), lomakkeet ja kopioitava linkki
- Tailwind 4 + daisyUI 5 + HTMX + Alpine npm-buildilla, suomennokset
- testit: domain, application (fakeilla), integraatio ja selaintestit
  (axe, vaalea/tumma, 1920/320 px); ruff, mypy ja import-linter
- dokumentit päivitetty toteutuksen mukaisiksi

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-29 13:20:24 +02:00
co-authored by Claude Opus 5.5
parent ba7a7ecfcf
commit e7b2745916
113 changed files with 5558 additions and 98 deletions
+24 -18
View File
@@ -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 <app>
.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 <app> ; .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/<module>/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/<module>/` (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/<module>/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 `<dialog>` (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 %}`.