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:
@@ -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]]
|
||||
@@ -0,0 +1,7 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class SharedConfig(AppConfig):
|
||||
name = "apps.shared"
|
||||
label = "shared"
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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))
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
# The shared app has no concrete models; TimestampedModel is abstract.
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
Reference in New Issue
Block a user