diff --git a/CLAUDE.md b/CLAUDE.md index 04b4aa7..1226d5e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,11 +9,12 @@ 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:** phase 1 items 1–2 are done. +**Current state:** phase 1 items 1–3 are done. - `shared` and `users`: custom user model, login, password links, user management. - `customers`: customers, contacts, billing units, the internal customer, and the encrypted personal identity code. +- `catalog`: service units, services and work types (base data page `/catalog/`, permission `catalog.manage`), seeded by `catalog/migrations/0002_seed.py`. Rows are never deleted, only taken out of use; `CatalogQueries.work_type_options()` is the read API for tasks and time tracking. -`users` and `customers` are the reference implementations; copy their patterns for new modules. The other modules in `docs/architecture.md` are not built yet. Next in the spec is phase 1 item 3: service units, services and work types as base data. +`users` and `customers` are the reference implementations; copy their patterns for new modules. The other modules in `docs/architecture.md` are not built yet. Next in the spec is phase 1 item 4: customer jobs. ## Source of truth diff --git a/apps/catalog/__init__.py b/apps/catalog/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/application/__init__.py b/apps/catalog/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/application/dto.py b/apps/catalog/application/dto.py new file mode 100644 index 0000000..e8d747f --- /dev/null +++ b/apps/catalog/application/dto.py @@ -0,0 +1,80 @@ +from dataclasses import dataclass + + +@dataclass(frozen=True, slots=True) +class ServiceUnitData: + name: str + + +@dataclass(frozen=True, slots=True) +class ServiceData: + name: str + + +@dataclass(frozen=True, slots=True) +class WorkTypeData: + """``service_id`` None places the work type directly under its service unit.""" + + name: str + service_id: int | None = None + + +# --- Read models --------------------------------------------------------------------------------- + + +@dataclass(frozen=True, slots=True) +class WorkTypeNode: + id: int + service_unit_id: int + service_id: int | None + name: str + is_active: bool + is_selectable: bool # active and every parent active + + +@dataclass(frozen=True, slots=True) +class ServiceNode: + id: int + service_unit_id: int + name: str + is_active: bool + work_types: tuple[WorkTypeNode, ...] + + +@dataclass(frozen=True, slots=True) +class ServiceUnitNode: + """One service unit of the base data tree, inactive rows included.""" + + id: int + name: str + is_shared: bool + is_active: bool + services: tuple[ServiceNode, ...] + work_types: tuple[WorkTypeNode, ...] # directly under the unit + + +@dataclass(frozen=True, slots=True) +class ServiceUnitSummary: + """What other modules (jobs) see of a service unit.""" + + id: int + name: str + is_shared: bool + + +@dataclass(frozen=True, slots=True) +class WorkTypeOption: + """A work type as other modules (tasks, time tracking) list and show it.""" + + id: int + name: str + service_unit_id: int + service_unit_name: str + service_name: str | None + is_selectable: bool + + @property + def label(self) -> str: + """E.g. "Mediatuotanto / Videotuotanto / Editointi".""" + parts = [self.service_unit_name, self.service_name, self.name] + return " / ".join(p for p in parts if p) diff --git a/apps/catalog/application/queries.py b/apps/catalog/application/queries.py new file mode 100644 index 0000000..8df29e3 --- /dev/null +++ b/apps/catalog/application/queries.py @@ -0,0 +1,27 @@ +from collections.abc import Iterable, Sequence +from typing import Protocol + +from apps.catalog.application.dto import ServiceUnitNode, ServiceUnitSummary, WorkTypeOption + + +class CatalogQueries(Protocol): + """Public read interface of the catalog module. + + A row is selectable when it and every parent above it are active. + """ + + def tree(self) -> Sequence[ServiceUnitNode]: + """The whole hierarchy in order, inactive rows included (base data page).""" + ... + + def active_service_units(self) -> Sequence[ServiceUnitSummary]: + """Active service units in order, the shared unit included (``is_shared``).""" + ... + + def work_type_options(self, service_unit_ids: Iterable[int]) -> Sequence[WorkTypeOption]: + """Selectable work types of the given units plus those of the shared unit.""" + ... + + def get_work_type(self, work_type_id: int) -> WorkTypeOption | None: + """Any work type, also one no longer selectable (for showing stored rows).""" + ... diff --git a/apps/catalog/application/use_cases.py b/apps/catalog/application/use_cases.py new file mode 100644 index 0000000..ceba062 --- /dev/null +++ b/apps/catalog/application/use_cases.py @@ -0,0 +1,194 @@ +from apps.catalog.application.dto import ServiceData, ServiceUnitData, WorkTypeData +from apps.catalog.domain.entities import Service, ServiceUnit, WorkType +from apps.catalog.domain.exceptions import ( + ServiceNameTaken, + ServiceNotFound, + ServiceUnitNameTaken, + ServiceUnitNotFound, + WorkTypeNameTaken, + WorkTypeNotFound, +) +from apps.catalog.domain.ordering import Direction, move +from apps.catalog.domain.repositories import ( + CatalogItem, + OrderedRepository, + ServiceRepository, + ServiceUnitRepository, + WorkTypeRepository, +) +from apps.catalog.domain.value_objects import CatalogName +from apps.shared.application.ports import UnitOfWork +from apps.shared.domain.exceptions import DomainError + + +class AddServiceUnit: + def __init__(self, units: ServiceUnitRepository, uow: UnitOfWork) -> None: + self.units = units + self.uow = uow + + def execute(self, data: ServiceUnitData) -> int: + name = CatalogName(data.name) + with self.uow: + if self.units.is_name_taken(name): + raise ServiceUnitNameTaken() + unit = ServiceUnit.register(name=name, sort_order=self.units.next_sort_order()) + saved = self.units.save(unit) + assert saved.id is not None + return saved.id + + +class RenameServiceUnit: + def __init__(self, units: ServiceUnitRepository, uow: UnitOfWork) -> None: + self.units = units + self.uow = uow + + def execute(self, unit_id: int, data: ServiceUnitData) -> None: + name = CatalogName(data.name) + with self.uow: + unit = self.units.get(unit_id) + if unit is None: + raise ServiceUnitNotFound() + if self.units.is_name_taken(name, exclude_id=unit_id): + raise ServiceUnitNameTaken() + self.units.save(unit.rename(name)) + + +class AddService: + def __init__( + self, units: ServiceUnitRepository, services: ServiceRepository, uow: UnitOfWork + ) -> None: + self.units = units + self.services = services + self.uow = uow + + def execute(self, unit_id: int, data: ServiceData) -> int: + name = CatalogName(data.name) + with self.uow: + if self.units.get(unit_id) is None: + raise ServiceUnitNotFound() + if self.services.is_name_taken(unit_id, name): + raise ServiceNameTaken() + service = Service.register( + service_unit_id=unit_id, + name=name, + sort_order=self.services.next_sort_order(unit_id), + ) + saved = self.services.save(service) + assert saved.id is not None + return saved.id + + +class RenameService: + def __init__(self, services: ServiceRepository, uow: UnitOfWork) -> None: + self.services = services + self.uow = uow + + def execute(self, service_id: int, data: ServiceData) -> None: + name = CatalogName(data.name) + with self.uow: + service = self.services.get(service_id) + if service is None: + raise ServiceNotFound() + if self.services.is_name_taken(service.service_unit_id, name, exclude_id=service_id): + raise ServiceNameTaken() + self.services.save(service.rename(name)) + + +class _WorkTypeUseCase: + def __init__( + self, + units: ServiceUnitRepository, + services: ServiceRepository, + work_types: WorkTypeRepository, + uow: UnitOfWork, + ) -> None: + self.units = units + self.services = services + self.work_types = work_types + self.uow = uow + + def _service(self, service_id: int | None) -> Service | None: + if service_id is None: + return None + service = self.services.get(service_id) + if service is None: + raise ServiceNotFound() + return service + + +class AddWorkType(_WorkTypeUseCase): + def execute(self, unit_id: int, data: WorkTypeData) -> int: + name = CatalogName(data.name) + with self.uow: + if self.units.get(unit_id) is None: + raise ServiceUnitNotFound() + work_type = WorkType.register( + service_unit_id=unit_id, + service=self._service(data.service_id), + name=name, + sort_order=self.work_types.next_sort_order(unit_id, data.service_id), + ) + if self.work_types.is_name_taken(unit_id, data.service_id, name): + raise WorkTypeNameTaken() + saved = self.work_types.save(work_type) + assert saved.id is not None + return saved.id + + +class UpdateWorkType(_WorkTypeUseCase): + """Rename, and move under another service of the same unit or directly under the unit + (a moved work type goes last on its new level).""" + + def execute(self, work_type_id: int, data: WorkTypeData) -> None: + name = CatalogName(data.name) + with self.uow: + work_type = self.work_types.get(work_type_id) + if work_type is None: + raise WorkTypeNotFound() + unit_id = work_type.service_unit_id + if data.service_id != work_type.service_id: + work_type = work_type.move_to( + self._service(data.service_id), + sort_order=self.work_types.next_sort_order(unit_id, data.service_id), + ) + if self.work_types.is_name_taken( + unit_id, work_type.service_id, name, exclude_id=work_type_id + ): + raise WorkTypeNameTaken() + self.work_types.save(work_type.rename(name)) + + +class SetActive[T: CatalogItem]: + """Deactivate or reactivate a service unit, service or work type (never deleted).""" + + def __init__( + self, repo: OrderedRepository[T], uow: UnitOfWork, not_found: type[DomainError] + ) -> None: + self.repo = repo + self.uow = uow + self.not_found = not_found + + def execute(self, item_id: int, active: bool) -> None: + with self.uow: + item = self.repo.get(item_id) + if item is None: + raise self.not_found() + self.repo.save(item.with_active(active)) + + +class MoveItem[T: CatalogItem]: + """Swap a row with its previous or next sibling.""" + + def __init__( + self, repo: OrderedRepository[T], uow: UnitOfWork, not_found: type[DomainError] + ) -> None: + self.repo = repo + self.uow = uow + self.not_found = not_found + + def execute(self, item_id: int, direction: Direction) -> None: + with self.uow: + item = self.repo.get(item_id) + if item is None: + raise self.not_found() + self.repo.set_order(move(self.repo.sibling_ids(item), item_id, direction)) diff --git a/apps/catalog/apps.py b/apps/catalog/apps.py new file mode 100644 index 0000000..97e81c6 --- /dev/null +++ b/apps/catalog/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class CatalogConfig(AppConfig): + name = "apps.catalog" + label = "catalog" + default_auto_field = "django.db.models.BigAutoField" diff --git a/apps/catalog/container.py b/apps/catalog/container.py new file mode 100644 index 0000000..2976b6e --- /dev/null +++ b/apps/catalog/container.py @@ -0,0 +1,84 @@ +"""Composition root of the catalog module.""" + +from apps.catalog.application.queries import CatalogQueries +from apps.catalog.application.use_cases import ( + AddService, + AddServiceUnit, + AddWorkType, + MoveItem, + RenameService, + RenameServiceUnit, + SetActive, + UpdateWorkType, +) +from apps.catalog.domain.entities import Service, ServiceUnit, WorkType +from apps.catalog.domain.exceptions import ServiceNotFound, ServiceUnitNotFound, WorkTypeNotFound +from apps.catalog.infrastructure.queries import DjangoCatalogQueries +from apps.catalog.infrastructure.repositories import ( + DjangoServiceRepository, + DjangoServiceUnitRepository, + DjangoWorkTypeRepository, +) +from apps.shared.infrastructure.unit_of_work import DjangoUnitOfWork + + +def add_service_unit() -> AddServiceUnit: + return AddServiceUnit(DjangoServiceUnitRepository(), DjangoUnitOfWork()) + + +def rename_service_unit() -> RenameServiceUnit: + return RenameServiceUnit(DjangoServiceUnitRepository(), DjangoUnitOfWork()) + + +def add_service() -> AddService: + return AddService(DjangoServiceUnitRepository(), DjangoServiceRepository(), DjangoUnitOfWork()) + + +def rename_service() -> RenameService: + return RenameService(DjangoServiceRepository(), DjangoUnitOfWork()) + + +def add_work_type() -> AddWorkType: + return AddWorkType( + DjangoServiceUnitRepository(), + DjangoServiceRepository(), + DjangoWorkTypeRepository(), + DjangoUnitOfWork(), + ) + + +def update_work_type() -> UpdateWorkType: + return UpdateWorkType( + DjangoServiceUnitRepository(), + DjangoServiceRepository(), + DjangoWorkTypeRepository(), + DjangoUnitOfWork(), + ) + + +def set_service_unit_active() -> SetActive[ServiceUnit]: + return SetActive(DjangoServiceUnitRepository(), DjangoUnitOfWork(), ServiceUnitNotFound) + + +def set_service_active() -> SetActive[Service]: + return SetActive(DjangoServiceRepository(), DjangoUnitOfWork(), ServiceNotFound) + + +def set_work_type_active() -> SetActive[WorkType]: + return SetActive(DjangoWorkTypeRepository(), DjangoUnitOfWork(), WorkTypeNotFound) + + +def move_service_unit() -> MoveItem[ServiceUnit]: + return MoveItem(DjangoServiceUnitRepository(), DjangoUnitOfWork(), ServiceUnitNotFound) + + +def move_service() -> MoveItem[Service]: + return MoveItem(DjangoServiceRepository(), DjangoUnitOfWork(), ServiceNotFound) + + +def move_work_type() -> MoveItem[WorkType]: + return MoveItem(DjangoWorkTypeRepository(), DjangoUnitOfWork(), WorkTypeNotFound) + + +def catalog_queries() -> CatalogQueries: + return DjangoCatalogQueries() diff --git a/apps/catalog/domain/__init__.py b/apps/catalog/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/domain/entities.py b/apps/catalog/domain/entities.py new file mode 100644 index 0000000..1c17cde --- /dev/null +++ b/apps/catalog/domain/entities.py @@ -0,0 +1,131 @@ +"""Service units, services and work types (specification 11.1). + +Hierarchy: service unit → (service) → work type. Rows are never deleted, only deactivated. +A deactivated row keeps its children's own ``is_active`` flags; the children are just not +selectable while a parent is inactive. +""" + +from dataclasses import dataclass, replace +from typing import Self + +from apps.catalog.domain.exceptions import ServiceNotInUnit +from apps.catalog.domain.value_objects import CatalogName + + +@dataclass(frozen=True, slots=True) +class ServiceUnit: + id: int | None + name: CatalogName + is_shared: bool = False # "Kaikille yhteiset": its work types are selectable in every unit + is_active: bool = True + sort_order: int = 0 + + @classmethod + def register(cls, *, name: CatalogName, sort_order: int) -> Self: + return cls(id=None, name=name, sort_order=sort_order) + + @classmethod + def reconstitute( + cls, *, id: int, name: CatalogName, is_shared: bool, is_active: bool, sort_order: int + ) -> Self: + return cls(id, name, is_shared, is_active, sort_order) + + def rename(self, name: CatalogName) -> Self: + return replace(self, name=name) + + def with_active(self, active: bool) -> Self: + return replace(self, is_active=active) + + def with_id(self, id: int) -> Self: + return replace(self, id=id) + + +@dataclass(frozen=True, slots=True) +class Service: + id: int | None + service_unit_id: int + name: CatalogName + is_active: bool = True + sort_order: int = 0 + + @classmethod + def register(cls, *, service_unit_id: int, name: CatalogName, sort_order: int) -> Self: + return cls(id=None, service_unit_id=service_unit_id, name=name, sort_order=sort_order) + + @classmethod + def reconstitute( + cls, *, id: int, service_unit_id: int, name: CatalogName, is_active: bool, sort_order: int + ) -> Self: + return cls(id, service_unit_id, name, is_active, sort_order) + + def rename(self, name: CatalogName) -> Self: + return replace(self, name=name) + + def with_active(self, active: bool) -> Self: + return replace(self, is_active=active) + + def with_id(self, id: int) -> Self: + return replace(self, id=id) + + +@dataclass(frozen=True, slots=True) +class WorkType: + """A work type sits directly under its service unit (``service_id`` None) or under one + of that unit's services.""" + + id: int | None + service_unit_id: int + service_id: int | None + name: CatalogName + is_active: bool = True + sort_order: int = 0 + + @classmethod + def register( + cls, + *, + service_unit_id: int, + service: Service | None, + name: CatalogName, + sort_order: int, + ) -> Self: + _check_service(service_unit_id, service) + return cls( + id=None, + service_unit_id=service_unit_id, + service_id=service.id if service else None, + name=name, + sort_order=sort_order, + ) + + @classmethod + def reconstitute( + cls, + *, + id: int, + service_unit_id: int, + service_id: int | None, + name: CatalogName, + is_active: bool, + sort_order: int, + ) -> Self: + return cls(id, service_unit_id, service_id, name, is_active, sort_order) + + def move_to(self, service: Service | None, *, sort_order: int) -> Self: + """Move under another service of the same unit, or directly under the unit.""" + _check_service(self.service_unit_id, service) + return replace(self, service_id=service.id if service else None, sort_order=sort_order) + + def rename(self, name: CatalogName) -> Self: + return replace(self, name=name) + + def with_active(self, active: bool) -> Self: + return replace(self, is_active=active) + + def with_id(self, id: int) -> Self: + return replace(self, id=id) + + +def _check_service(service_unit_id: int, service: Service | None) -> None: + if service is not None and service.service_unit_id != service_unit_id: + raise ServiceNotInUnit() diff --git a/apps/catalog/domain/exceptions.py b/apps/catalog/domain/exceptions.py new file mode 100644 index 0000000..d03bd36 --- /dev/null +++ b/apps/catalog/domain/exceptions.py @@ -0,0 +1,47 @@ +from apps.shared.domain.exceptions import DomainError + + +class InvalidCatalogName(DomainError): + code = "invalid_catalog_name" + field = "name" + + +class ServiceUnitNameTaken(DomainError): + code = "service_unit_name_taken" + field = "name" + + +class ServiceNameTaken(DomainError): + code = "service_name_taken" + field = "name" + + +class WorkTypeNameTaken(DomainError): + code = "work_type_name_taken" + field = "name" + + +class ServiceUnitNotFound(DomainError): + code = "service_unit_not_found" + + +class ServiceNotFound(DomainError): + code = "service_not_found" + field = "service" + + +class WorkTypeNotFound(DomainError): + code = "work_type_not_found" + + +class ServiceNotInUnit(DomainError): + """A work type can only belong to a service of its own service unit.""" + + code = "service_not_in_unit" + field = "service" + + +class CannotMove(DomainError): + """The first row cannot move up and the last row cannot move down.""" + + code = "cannot_move" diff --git a/apps/catalog/domain/ordering.py b/apps/catalog/domain/ordering.py new file mode 100644 index 0000000..be8612f --- /dev/null +++ b/apps/catalog/domain/ordering.py @@ -0,0 +1,22 @@ +"""Manual ordering of sibling rows with "Move up" / "Move down" buttons (specification 16.3).""" + +from collections.abc import Sequence +from enum import StrEnum + +from apps.catalog.domain.exceptions import CannotMove + + +class Direction(StrEnum): + UP = "up" + DOWN = "down" + + +def move(ids: Sequence[int], item_id: int, direction: Direction) -> list[int]: + """Return ``ids`` with ``item_id`` swapped with its neighbour in ``direction``.""" + order = list(ids) + index = order.index(item_id) + target = index - 1 if direction is Direction.UP else index + 1 + if not 0 <= target < len(order): + raise CannotMove() + order[index], order[target] = order[target], order[index] + return order diff --git a/apps/catalog/domain/repositories.py b/apps/catalog/domain/repositories.py new file mode 100644 index 0000000..ccd9a8e --- /dev/null +++ b/apps/catalog/domain/repositories.py @@ -0,0 +1,55 @@ +from collections.abc import Sequence +from typing import Protocol, Self + +from apps.catalog.domain.entities import Service, ServiceUnit, WorkType +from apps.catalog.domain.value_objects import CatalogName + + +class CatalogItem(Protocol): + """What service units, services and work types share: activation and ordering.""" + + @property + def id(self) -> int | None: ... + + def with_active(self, active: bool) -> Self: ... + + +class OrderedRepository[T: CatalogItem](Protocol): + def get(self, item_id: int) -> T | None: ... + + def save(self, item: T) -> T: ... + + def sibling_ids(self, item: T) -> list[int]: + """Ids of the rows on the same level as ``item`` (itself included), in order.""" + ... + + def set_order(self, ids: Sequence[int]) -> None: + """Renumber ``sort_order`` of these rows in the given order.""" + ... + + +class ServiceUnitRepository(OrderedRepository[ServiceUnit], Protocol): + def is_name_taken(self, name: CatalogName, *, exclude_id: int | None = None) -> bool: ... + + def next_sort_order(self) -> int: ... + + +class ServiceRepository(OrderedRepository[Service], Protocol): + def is_name_taken( + self, service_unit_id: int, name: CatalogName, *, exclude_id: int | None = None + ) -> bool: ... + + def next_sort_order(self, service_unit_id: int) -> int: ... + + +class WorkTypeRepository(OrderedRepository[WorkType], Protocol): + def is_name_taken( + self, + service_unit_id: int, + service_id: int | None, + name: CatalogName, + *, + exclude_id: int | None = None, + ) -> bool: ... + + def next_sort_order(self, service_unit_id: int, service_id: int | None) -> int: ... diff --git a/apps/catalog/domain/value_objects.py b/apps/catalog/domain/value_objects.py new file mode 100644 index 0000000..eb09349 --- /dev/null +++ b/apps/catalog/domain/value_objects.py @@ -0,0 +1,25 @@ +from dataclasses import dataclass + +from apps.catalog.domain.exceptions import InvalidCatalogName + +NAME_MAX_LENGTH = 100 + + +@dataclass(frozen=True, slots=True) +class CatalogName: + """Name of a service unit, service or work type: 1–100 characters, spaces normalized.""" + + value: str + + def __post_init__(self) -> None: + normalized = " ".join(self.value.split()) + if not normalized or len(normalized) > NAME_MAX_LENGTH: + raise InvalidCatalogName() + object.__setattr__(self, "value", normalized) + + def same_as(self, other: str) -> bool: + """Names are unique case-insensitively within one level.""" + return self.value.casefold() == " ".join(other.split()).casefold() + + def __str__(self) -> str: + return self.value diff --git a/apps/catalog/infrastructure/__init__.py b/apps/catalog/infrastructure/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/infrastructure/orm.py b/apps/catalog/infrastructure/orm.py new file mode 100644 index 0000000..7274cc6 --- /dev/null +++ b/apps/catalog/infrastructure/orm.py @@ -0,0 +1,64 @@ +from django.db import models + +from apps.catalog.domain.value_objects import NAME_MAX_LENGTH +from apps.shared.infrastructure.models import TimestampedModel + + +class ServiceUnitModel(TimestampedModel): + name = models.CharField(max_length=NAME_MAX_LENGTH) + is_shared = models.BooleanField(default=False) + is_active = models.BooleanField(default=True) + sort_order = models.PositiveIntegerField(default=0) + + class Meta: + db_table = "service_units" + ordering = ["sort_order", "id"] + # The utf8mb4 collation is case-insensitive, matching the rule in the domain. + constraints = [models.UniqueConstraint(fields=["name"], name="service_units_name_uniq")] + + def __str__(self) -> str: + return self.name + + +class ServiceModel(TimestampedModel): + service_unit = models.ForeignKey( + ServiceUnitModel, on_delete=models.PROTECT, related_name="services" + ) + name = models.CharField(max_length=NAME_MAX_LENGTH) + is_active = models.BooleanField(default=True) + sort_order = models.PositiveIntegerField(default=0) + + class Meta: + db_table = "services" + ordering = ["sort_order", "id"] + constraints = [ + models.UniqueConstraint(fields=["service_unit", "name"], name="services_unit_name_uniq") + ] + + def __str__(self) -> str: + return self.name + + +class WorkTypeModel(TimestampedModel): + # Unique name per level is checked in the use case: a NULL service would slip past + # a database unique constraint. + service_unit = models.ForeignKey( + ServiceUnitModel, on_delete=models.PROTECT, related_name="work_types" + ) + service = models.ForeignKey( + ServiceModel, + on_delete=models.PROTECT, + null=True, + blank=True, + related_name="work_types", + ) + name = models.CharField(max_length=NAME_MAX_LENGTH) + is_active = models.BooleanField(default=True) + sort_order = models.PositiveIntegerField(default=0) + + class Meta: + db_table = "work_types" + ordering = ["sort_order", "id"] + + def __str__(self) -> str: + return self.name diff --git a/apps/catalog/infrastructure/queries.py b/apps/catalog/infrastructure/queries.py new file mode 100644 index 0000000..012ed3e --- /dev/null +++ b/apps/catalog/infrastructure/queries.py @@ -0,0 +1,111 @@ +from collections.abc import Iterable, Sequence + +from django.db.models import Q + +from apps.catalog.application.dto import ( + ServiceNode, + ServiceUnitNode, + ServiceUnitSummary, + WorkTypeNode, + WorkTypeOption, +) +from apps.catalog.infrastructure.orm import ServiceUnitModel, WorkTypeModel + + +def _is_selectable(model: WorkTypeModel) -> bool: + return ( + model.is_active + and model.service_unit.is_active + and (model.service is None or model.service.is_active) + ) + + +def _option(model: WorkTypeModel) -> WorkTypeOption: + return WorkTypeOption( + id=model.pk, + name=model.name, + service_unit_id=model.service_unit_id, + service_unit_name=model.service_unit.name, + service_name=model.service.name if model.service else None, + is_selectable=_is_selectable(model), + ) + + +# Selectable = the row and every parent above it are active (specification 16.3). +_SELECTABLE = Q(is_active=True, service_unit__is_active=True) & ( + Q(service__isnull=True) | Q(service__is_active=True) +) + + +class DjangoCatalogQueries: + def tree(self) -> Sequence[ServiceUnitNode]: + units = ServiceUnitModel.objects.prefetch_related("services", "work_types") + result = [] + for unit in units: + by_service: dict[int | None, list[WorkTypeNode]] = {} + services = {s.pk: s for s in unit.services.all()} + for wt in unit.work_types.all(): + service = services.get(wt.service_id) if wt.service_id else None + by_service.setdefault(wt.service_id, []).append( + WorkTypeNode( + id=wt.pk, + service_unit_id=unit.pk, + service_id=wt.service_id, + name=wt.name, + is_active=wt.is_active, + is_selectable=wt.is_active + and unit.is_active + and (service is None or service.is_active), + ) + ) + result.append( + ServiceUnitNode( + id=unit.pk, + name=unit.name, + is_shared=unit.is_shared, + is_active=unit.is_active, + services=tuple( + ServiceNode( + id=s.pk, + service_unit_id=unit.pk, + name=s.name, + is_active=s.is_active, + work_types=tuple(by_service.get(s.pk, [])), + ) + for s in services.values() + ), + work_types=tuple(by_service.get(None, [])), + ) + ) + return result + + def active_service_units(self) -> Sequence[ServiceUnitSummary]: + return [ + ServiceUnitSummary(id=u.pk, name=u.name, is_shared=u.is_shared) + for u in ServiceUnitModel.objects.filter(is_active=True) + ] + + def work_type_options(self, service_unit_ids: Iterable[int]) -> Sequence[WorkTypeOption]: + qs = ( + WorkTypeModel.objects.filter(_SELECTABLE) + .filter(Q(service_unit_id__in=list(service_unit_ids)) | Q(service_unit__is_shared=True)) + .select_related("service_unit", "service") + .order_by( + "service_unit__is_shared", + "service_unit__sort_order", + "service_unit_id", + "service__sort_order", + "service_id", + "sort_order", + "id", + ) + ) + return [_option(m) for m in qs] + + def get_work_type(self, work_type_id: int) -> WorkTypeOption | None: + model = ( + WorkTypeModel.objects.select_related("service_unit", "service") + .filter(pk=work_type_id) + .first() + ) + return _option(model) if model else None diff --git a/apps/catalog/infrastructure/repositories.py b/apps/catalog/infrastructure/repositories.py new file mode 100644 index 0000000..96927b8 --- /dev/null +++ b/apps/catalog/infrastructure/repositories.py @@ -0,0 +1,156 @@ +from collections.abc import Sequence +from typing import Any + +from django.db.models import Max, Model, QuerySet + +from apps.catalog.domain.entities import Service, ServiceUnit, WorkType +from apps.catalog.domain.value_objects import CatalogName +from apps.catalog.infrastructure.orm import ServiceModel, ServiceUnitModel, WorkTypeModel + + +def _next_sort_order(qs: QuerySet[Any]) -> int: + return int(qs.aggregate(m=Max("sort_order"))["m"] or 0) + 1 + + +def _ids(qs: QuerySet[Any]) -> list[int]: + return list(qs.order_by("sort_order", "id").values_list("id", flat=True)) + + +def _set_order(model: type[Model], ids: Sequence[int]) -> None: + for position, pk in enumerate(ids, start=1): + model._default_manager.filter(pk=pk).update(sort_order=position) + + +def service_unit_entity(model: ServiceUnitModel) -> ServiceUnit: + return ServiceUnit.reconstitute( + id=model.pk, + name=CatalogName(model.name), + is_shared=model.is_shared, + is_active=model.is_active, + sort_order=model.sort_order, + ) + + +class DjangoServiceUnitRepository: + def get(self, item_id: int) -> ServiceUnit | None: + model = ServiceUnitModel.objects.filter(pk=item_id).first() + return service_unit_entity(model) if model else None + + def save(self, item: ServiceUnit) -> ServiceUnit: + model = ServiceUnitModel() if item.id is None else ServiceUnitModel.objects.get(pk=item.id) + model.name = item.name.value + model.is_shared = item.is_shared + model.is_active = item.is_active + model.sort_order = item.sort_order + model.save() + return item.with_id(model.pk) + + def is_name_taken(self, name: CatalogName, *, exclude_id: int | None = None) -> bool: + qs = ServiceUnitModel.objects.filter(name__iexact=name.value) + if exclude_id is not None: + qs = qs.exclude(pk=exclude_id) + return qs.exists() + + def next_sort_order(self) -> int: + return _next_sort_order(ServiceUnitModel.objects.all()) + + def sibling_ids(self, item: ServiceUnit) -> list[int]: + return _ids(ServiceUnitModel.objects.all()) + + def set_order(self, ids: Sequence[int]) -> None: + _set_order(ServiceUnitModel, ids) + + +def service_entity(model: ServiceModel) -> Service: + return Service.reconstitute( + id=model.pk, + service_unit_id=model.service_unit_id, + name=CatalogName(model.name), + is_active=model.is_active, + sort_order=model.sort_order, + ) + + +class DjangoServiceRepository: + def get(self, item_id: int) -> Service | None: + model = ServiceModel.objects.filter(pk=item_id).first() + return service_entity(model) if model else None + + def save(self, item: Service) -> Service: + model = ServiceModel() if item.id is None else ServiceModel.objects.get(pk=item.id) + model.service_unit_id = item.service_unit_id + model.name = item.name.value + model.is_active = item.is_active + model.sort_order = item.sort_order + model.save() + return item.with_id(model.pk) + + def is_name_taken( + self, service_unit_id: int, name: CatalogName, *, exclude_id: int | None = None + ) -> bool: + qs = ServiceModel.objects.filter(service_unit_id=service_unit_id, name__iexact=name.value) + if exclude_id is not None: + qs = qs.exclude(pk=exclude_id) + return qs.exists() + + def next_sort_order(self, service_unit_id: int) -> int: + return _next_sort_order(ServiceModel.objects.filter(service_unit_id=service_unit_id)) + + def sibling_ids(self, item: Service) -> list[int]: + return _ids(ServiceModel.objects.filter(service_unit_id=item.service_unit_id)) + + def set_order(self, ids: Sequence[int]) -> None: + _set_order(ServiceModel, ids) + + +def work_type_entity(model: WorkTypeModel) -> WorkType: + return WorkType.reconstitute( + id=model.pk, + service_unit_id=model.service_unit_id, + service_id=model.service_id, + name=CatalogName(model.name), + is_active=model.is_active, + sort_order=model.sort_order, + ) + + +def _level(service_unit_id: int, service_id: int | None) -> QuerySet[WorkTypeModel]: + return WorkTypeModel.objects.filter(service_unit_id=service_unit_id, service_id=service_id) + + +class DjangoWorkTypeRepository: + def get(self, item_id: int) -> WorkType | None: + model = WorkTypeModel.objects.filter(pk=item_id).first() + return work_type_entity(model) if model else None + + def save(self, item: WorkType) -> WorkType: + model = WorkTypeModel() if item.id is None else WorkTypeModel.objects.get(pk=item.id) + model.service_unit_id = item.service_unit_id + model.service_id = item.service_id + model.name = item.name.value + model.is_active = item.is_active + model.sort_order = item.sort_order + model.save() + return item.with_id(model.pk) + + def is_name_taken( + self, + service_unit_id: int, + service_id: int | None, + name: CatalogName, + *, + exclude_id: int | None = None, + ) -> bool: + qs = _level(service_unit_id, service_id).filter(name__iexact=name.value) + if exclude_id is not None: + qs = qs.exclude(pk=exclude_id) + return qs.exists() + + def next_sort_order(self, service_unit_id: int, service_id: int | None) -> int: + return _next_sort_order(_level(service_unit_id, service_id)) + + def sibling_ids(self, item: WorkType) -> list[int]: + return _ids(_level(item.service_unit_id, item.service_id)) + + def set_order(self, ids: Sequence[int]) -> None: + _set_order(WorkTypeModel, ids) diff --git a/apps/catalog/migrations/0001_initial.py b/apps/catalog/migrations/0001_initial.py new file mode 100644 index 0000000..f18f307 --- /dev/null +++ b/apps/catalog/migrations/0001_initial.py @@ -0,0 +1,69 @@ +# Generated by Django 5.2.19 on 2026-11-29 11:55 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='ServiceUnitModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=100)), + ('is_shared', models.BooleanField(default=False)), + ('is_active', models.BooleanField(default=True)), + ('sort_order', models.PositiveIntegerField(default=0)), + ], + options={ + 'db_table': 'service_units', + 'ordering': ['sort_order', 'id'], + 'constraints': [models.UniqueConstraint(fields=('name',), name='service_units_name_uniq')], + }, + ), + migrations.CreateModel( + name='ServiceModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=100)), + ('is_active', models.BooleanField(default=True)), + ('sort_order', models.PositiveIntegerField(default=0)), + ('service_unit', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='services', to='catalog.serviceunitmodel')), + ], + options={ + 'db_table': 'services', + 'ordering': ['sort_order', 'id'], + }, + ), + migrations.CreateModel( + name='WorkTypeModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=100)), + ('is_active', models.BooleanField(default=True)), + ('sort_order', models.PositiveIntegerField(default=0)), + ('service', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='work_types', to='catalog.servicemodel')), + ('service_unit', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='work_types', to='catalog.serviceunitmodel')), + ], + options={ + 'db_table': 'work_types', + 'ordering': ['sort_order', 'id'], + }, + ), + migrations.AddConstraint( + model_name='servicemodel', + constraint=models.UniqueConstraint(fields=('service_unit', 'name'), name='services_unit_name_uniq'), + ), + ] diff --git a/apps/catalog/migrations/0002_seed.py b/apps/catalog/migrations/0002_seed.py new file mode 100644 index 0000000..b7658fd --- /dev/null +++ b/apps/catalog/migrations/0002_seed.py @@ -0,0 +1,66 @@ +"""Initial service units, services and work types (specification 11.1, 16.3). + +Added only when the tables are empty, so a database that already has base data is left as is. +""" + +from django.db import migrations + +# (service unit, is_shared, {service or None: [work types]}) +SEED = [ + ( + "Mediatuotanto", + False, + { + "Videotuotanto": [ + "Videokuvaus", + "Kuvausassistentti", + "Editointi", + "Animointi", + "3D-mallinnus", + ], + "Valokuvaus": ["Kuvaus", "Editointi"], + "Äänituotanto": ["Äänitys", "Editointi"], + }, + ), + ("Markkinointi", False, {None: ["Graafinen työ", "Julkaisutyö", "Kampanjatyö"]}), + ("Painotuotanto", False, {None: ["Painotyö", "Asennus"]}), + ("Ylläpitopalvelut", False, {None: ["Asennustyö", "Päivitystyö"]}), + ("Verkkosivut", False, {None: ["Ohjelmointityö"]}), + ( + "Ohjelmistot", + False, + {None: ["Ohjelmointityö", "Ohjelmointityö vaativa", "Pelimoottoritoteutukset"]}, + ), + ("Kuluttajapalvelut", False, {None: ["Valokuvaus", "Tulosteet", "Passikuvat", "Digitointi"]}), + ( + "Kaikille yhteiset", + True, + {None: ["Suunnittelu", "Tuotanto", "Projektin johtaminen", "Konsultointi", "Koulutus"]}, + ), +] + + +def seed(apps, schema_editor): + unit_model = apps.get_model("catalog", "ServiceUnitModel") + service_model = apps.get_model("catalog", "ServiceModel") + work_type_model = apps.get_model("catalog", "WorkTypeModel") + if unit_model.objects.exists(): + return + for unit_order, (unit_name, is_shared, groups) in enumerate(SEED, start=1): + unit = unit_model.objects.create(name=unit_name, is_shared=is_shared, sort_order=unit_order) + for service_order, (service_name, work_types) in enumerate(groups.items(), start=1): + service = None + if service_name is not None: + service = service_model.objects.create( + service_unit=unit, name=service_name, sort_order=service_order + ) + for order, name in enumerate(work_types, start=1): + work_type_model.objects.create( + service_unit=unit, service=service, name=name, sort_order=order + ) + + +class Migration(migrations.Migration): + dependencies = [("catalog", "0001_initial")] + + operations = [migrations.RunPython(seed, migrations.RunPython.noop)] diff --git a/apps/catalog/migrations/__init__.py b/apps/catalog/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/models.py b/apps/catalog/models.py new file mode 100644 index 0000000..d00b12e --- /dev/null +++ b/apps/catalog/models.py @@ -0,0 +1,4 @@ +# Django discovers the module's ORM models through this file. +from apps.catalog.infrastructure.orm import ServiceModel, ServiceUnitModel, WorkTypeModel + +__all__ = ["ServiceModel", "ServiceUnitModel", "WorkTypeModel"] diff --git a/apps/catalog/presentation/__init__.py b/apps/catalog/presentation/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/presentation/forms.py b/apps/catalog/presentation/forms.py new file mode 100644 index 0000000..d83d530 --- /dev/null +++ b/apps/catalog/presentation/forms.py @@ -0,0 +1,53 @@ +from collections.abc import Sequence +from typing import Any + +from django import forms +from django.utils.translation import gettext_lazy as _ + +from apps.catalog.application.dto import ServiceData, ServiceNode, ServiceUnitData, WorkTypeData +from apps.catalog.domain.value_objects import NAME_MAX_LENGTH +from apps.shared.presentation.forms import DaisyFormMixin + + +class ServiceUnitForm(DaisyFormMixin, forms.Form): + name = forms.CharField(label=_("Name"), max_length=NAME_MAX_LENGTH) + + def to_dto(self) -> ServiceUnitData: + return ServiceUnitData(name=self.cleaned_data["name"]) + + +class ServiceForm(DaisyFormMixin, forms.Form): + name = forms.CharField(label=_("Name"), max_length=NAME_MAX_LENGTH) + + def to_dto(self) -> ServiceData: + return ServiceData(name=self.cleaned_data["name"]) + + +class WorkTypeForm(DaisyFormMixin, forms.Form): + name = forms.CharField(label=_("Name"), max_length=NAME_MAX_LENGTH) + service = forms.TypedChoiceField( + label=_("Service"), + required=False, + coerce=int, + empty_value=None, + help_text=_("A work type can be moved to another service of the same service unit."), + ) + + def __init__(self, *args: Any, services: Sequence[ServiceNode] = (), **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + if not services: + del self.fields["service"] + return + field: Any = self.fields["service"] + field.choices = [ + ("", _("Directly under the service unit")), + *( + (s.id, s.name if s.is_active else _("%(name)s (not in use)") % {"name": s.name}) + for s in services + ), + ] + + def to_dto(self) -> WorkTypeData: + return WorkTypeData( + name=self.cleaned_data["name"], service_id=self.cleaned_data.get("service") + ) diff --git a/apps/catalog/presentation/labels.py b/apps/catalog/presentation/labels.py new file mode 100644 index 0000000..fc0f9d5 --- /dev/null +++ b/apps/catalog/presentation/labels.py @@ -0,0 +1,14 @@ +from django.utils.translation import gettext_lazy as _ + +ERROR_MESSAGES = { + "invalid_catalog_name": _("Enter a name (at most 100 characters)."), + "service_unit_name_taken": _("A service unit with this name already exists."), + "service_name_taken": _("This service unit already has a service with this name."), + "work_type_name_taken": _("There is already a work type with this name on this level."), + "service_unit_not_found": _("The service unit was not found."), + "service_not_found": _("The service was not found."), + "work_type_not_found": _("The work type was not found."), + "service_not_in_unit": _("Choose a service of the same service unit."), + "cannot_move": _("The row cannot be moved further."), + "*": _("The change could not be saved."), +} diff --git a/apps/catalog/presentation/templates/catalog/index.html b/apps/catalog/presentation/templates/catalog/index.html new file mode 100644 index 0000000..525cc21 --- /dev/null +++ b/apps/catalog/presentation/templates/catalog/index.html @@ -0,0 +1,18 @@ +{% extends "base.html" %} +{% block title %}{% translate "Base data" %}{% endblock %} +{% block content %} +
+

{% translate "Base data" %}

+ {% url 'catalog:unit_create' as add_url %} + {% translate "Add service unit" %} +
+

{% translate "Service units, their services and work types. Work types of the shared unit can be chosen in every service unit. Rows are not deleted: a row taken out of use, and everything under it, can no longer be chosen." %}

+ + {% include "catalog/partials/tree.html" %} + + + + +{% endblock %} diff --git a/apps/catalog/presentation/templates/catalog/item_form_page.html b/apps/catalog/presentation/templates/catalog/item_form_page.html new file mode 100644 index 0000000..ec1aab0 --- /dev/null +++ b/apps/catalog/presentation/templates/catalog/item_form_page.html @@ -0,0 +1,12 @@ +{% extends "base.html" %} +{% block title %}{{ title }}{% endblock %} +{% block content %} + +
+
+ {% include "catalog/partials/item_form.html" %} +
+
+{% endblock %} diff --git a/apps/catalog/presentation/templates/catalog/partials/badges.html b/apps/catalog/presentation/templates/catalog/partials/badges.html new file mode 100644 index 0000000..81e9f1d --- /dev/null +++ b/apps/catalog/presentation/templates/catalog/partials/badges.html @@ -0,0 +1,2 @@ +{% if item.is_shared %} {% translate "Shared by all units" %}{% endif %} +{% if not item.is_active %} {% translate "Not in use" %}{% endif %} diff --git a/apps/catalog/presentation/templates/catalog/partials/item_actions.html b/apps/catalog/presentation/templates/catalog/partials/item_actions.html new file mode 100644 index 0000000..66f4e45 --- /dev/null +++ b/apps/catalog/presentation/templates/catalog/partials/item_actions.html @@ -0,0 +1,35 @@ +{# Row buttons. Include with kind (URL segment), prefix (DOM id prefix), item, first, last. #} +
+ {% url 'catalog:edit' kind item.id as edit_url %} + + {% translate "Edit" %}: {{ item.name }} + + {% url 'catalog:move' kind item.id 'up' as up_url %} +
+ {% csrf_token %} + +
+ + {% url 'catalog:move' kind item.id 'down' as down_url %} +
+ {% csrf_token %} + +
+ + {% url 'catalog:toggle' kind item.id as toggle_url %} +
+ {% csrf_token %} + + +
+
diff --git a/apps/catalog/presentation/templates/catalog/partials/item_form.html b/apps/catalog/presentation/templates/catalog/partials/item_form.html new file mode 100644 index 0000000..1701214 --- /dev/null +++ b/apps/catalog/presentation/templates/catalog/partials/item_form.html @@ -0,0 +1,11 @@ +

{{ title }}

+{% if parent_name %}

{% translate "Service unit" %}: {{ parent_name }}

{% endif %} +
+ {% csrf_token %} + {{ form }} + +
diff --git a/apps/catalog/presentation/templates/catalog/partials/tree.html b/apps/catalog/presentation/templates/catalog/partials/tree.html new file mode 100644 index 0000000..83f3fbf --- /dev/null +++ b/apps/catalog/presentation/templates/catalog/partials/tree.html @@ -0,0 +1,52 @@ +
+ {% for unit in tree %} +
+
+
+

{{ unit.name }}{% include "catalog/partials/badges.html" with item=unit %}

+ {% include "catalog/partials/item_actions.html" with kind="service-units" prefix="unit" item=unit first=forloop.first last=forloop.last %} +
+ + {% if unit.services %} +
    + {% for service in unit.services %} +
  • +
    +

    {{ service.name }}{% include "catalog/partials/badges.html" with item=service %}

    + {% include "catalog/partials/item_actions.html" with kind="services" prefix="service" item=service first=forloop.first last=forloop.last %} +
    + {% if service.work_types %} + {% include "catalog/partials/work_types.html" with work_types=service.work_types %} + {% else %} +

    {% translate "No work types yet." %}

    + {% endif %} +
  • + {% endfor %} +
+ {% endif %} + + {% if unit.work_types %} + {% if unit.services %}

{% translate "Directly under the service unit" %}

{% endif %} + {% include "catalog/partials/work_types.html" with work_types=unit.work_types %} + {% elif not unit.services %} +

{% translate "No services or work types yet." %}

+ {% endif %} + +
+ {% url 'catalog:child_create' unit.id 'services' as service_url %} + + {% translate "Add service" %}: {{ unit.name }} + {% url 'catalog:child_create' unit.id 'work-types' as work_type_url %} + + {% translate "Add work type" %}: {{ unit.name }} +
+
+
+ {% empty %} +

{% translate "No service units yet." %}

+ {% endfor %} +
diff --git a/apps/catalog/presentation/templates/catalog/partials/work_types.html b/apps/catalog/presentation/templates/catalog/partials/work_types.html new file mode 100644 index 0000000..02371e9 --- /dev/null +++ b/apps/catalog/presentation/templates/catalog/partials/work_types.html @@ -0,0 +1,8 @@ + diff --git a/apps/catalog/presentation/urls.py b/apps/catalog/presentation/urls.py new file mode 100644 index 0000000..d985ad2 --- /dev/null +++ b/apps/catalog/presentation/urls.py @@ -0,0 +1,27 @@ +from django.urls import path + +from apps.catalog.presentation import views + +app_name = "catalog" + +urlpatterns = [ + path("", views.CatalogIndexView.as_view(), name="index"), + path( + "service-units/new/", + views.ItemFormView.as_view(), + {"kind": views.UNITS}, + name="unit_create", + ), + path( + "service-units///new/", + views.ItemFormView.as_view(), + name="child_create", + ), + path("//edit/", views.ItemFormView.as_view(), name="edit"), + path( + "//move//", + views.MoveView.as_view(), + name="move", + ), + path("//active/", views.ToggleActiveView.as_view(), name="toggle"), +] diff --git a/apps/catalog/presentation/views.py b/apps/catalog/presentation/views.py new file mode 100644 index 0000000..0f79ffb --- /dev/null +++ b/apps/catalog/presentation/views.py @@ -0,0 +1,324 @@ +"""Base data page (specification 16.3): service units, services and work types. + +Forms open in the page's dialog with HTMX; every change re-renders the whole tree, moves +focus deliberately and announces the result in the live region. +""" + +import json +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any + +from django import forms +from django.contrib import messages +from django.http import Http404, HttpRequest, HttpResponse +from django.shortcuts import redirect, render +from django.urls import reverse +from django.utils.functional import Promise +from django.utils.translation import gettext as _ +from django.utils.translation import gettext_lazy, gettext_noop +from django.views import View +from django.views.generic import TemplateView + +from apps.catalog import container +from apps.catalog.application.dto import ServiceNode, ServiceUnitNode, WorkTypeNode +from apps.catalog.domain.ordering import Direction +from apps.catalog.presentation.forms import ServiceForm, ServiceUnitForm, WorkTypeForm +from apps.catalog.presentation.labels import ERROR_MESSAGES +from apps.shared.domain.exceptions import DomainError +from apps.users.domain.enums import Permission +from apps.users.presentation.mixins import PermissionRequiredMixin + +type Node = ServiceUnitNode | ServiceNode | WorkTypeNode + +UNITS, SERVICES, WORK_TYPES = "service-units", "services", "work-types" + + +@dataclass(frozen=True) +class _Kind: + """One level of the hierarchy; ``key`` is its URL segment, ``prefix`` its DOM id prefix.""" + + key: str + prefix: str + form_class: type[forms.Form] + has_parent: bool + add_title: Promise + edit_title: Promise + saved: str + add: Callable[[int | None, Any], int] + update: Callable[[int, Any], None] + set_active: Callable[[], Any] + move: Callable[[], Any] + + +def _parent(unit_id: int | None) -> int: + assert unit_id is not None, "services and work types are added under a service unit" + return unit_id + + +KINDS = { + UNITS: _Kind( + key=UNITS, + prefix="unit", + form_class=ServiceUnitForm, + has_parent=False, + add_title=gettext_lazy("Add service unit"), + edit_title=gettext_lazy("Edit service unit"), + saved=gettext_noop("Service unit saved."), + add=lambda _unit, dto: container.add_service_unit().execute(dto), + update=lambda item_id, dto: container.rename_service_unit().execute(item_id, dto), + set_active=container.set_service_unit_active, + move=container.move_service_unit, + ), + SERVICES: _Kind( + key=SERVICES, + prefix="service", + form_class=ServiceForm, + has_parent=True, + add_title=gettext_lazy("Add service"), + edit_title=gettext_lazy("Edit service"), + saved=gettext_noop("Service saved."), + add=lambda unit_id, dto: container.add_service().execute(_parent(unit_id), dto), + update=lambda item_id, dto: container.rename_service().execute(item_id, dto), + set_active=container.set_service_active, + move=container.move_service, + ), + WORK_TYPES: _Kind( + key=WORK_TYPES, + prefix="worktype", + form_class=WorkTypeForm, + has_parent=True, + add_title=gettext_lazy("Add work type"), + edit_title=gettext_lazy("Edit work type"), + saved=gettext_noop("Work type saved."), + add=lambda unit_id, dto: container.add_work_type().execute(_parent(unit_id), dto), + update=lambda item_id, dto: container.update_work_type().execute(item_id, dto), + set_active=container.set_work_type_active, + move=container.move_work_type, + ), +} + + +def _kind(key: str) -> _Kind: + kind = KINDS.get(key) + if kind is None: + raise Http404 + return kind + + +class _Lookup: + """Index of the tree: each row, its siblings in order and its service unit.""" + + def __init__(self, tree: Sequence[ServiceUnitNode]) -> None: + self.tree = tree + self._items: dict[tuple[str, int], tuple[Node, list[int], ServiceUnitNode]] = {} + unit_ids = [u.id for u in tree] + for unit in tree: + self._add(UNITS, unit, unit_ids, unit) + service_ids = [s.id for s in unit.services] + for service in unit.services: + self._add(SERVICES, service, service_ids, unit) + self._add_work_types(service.work_types, unit) + self._add_work_types(unit.work_types, unit) + + def _add(self, key: str, node: Node, siblings: list[int], unit: ServiceUnitNode) -> None: + self._items[(key, node.id)] = (node, siblings, unit) + + def _add_work_types(self, work_types: Sequence[WorkTypeNode], unit: ServiceUnitNode) -> None: + ids = [w.id for w in work_types] + for work_type in work_types: + self._add(WORK_TYPES, work_type, ids, unit) + + def _entry(self, key: str, item_id: int) -> tuple[Node, list[int], ServiceUnitNode]: + entry = self._items.get((key, item_id)) + if entry is None: + raise Http404 + return entry + + def get(self, key: str, item_id: int) -> Node: + return self._entry(key, item_id)[0] + + def siblings(self, key: str, item_id: int) -> list[int]: + return self._entry(key, item_id)[1] + + def unit(self, key: str, item_id: int) -> ServiceUnitNode: + return self._entry(key, item_id)[2] + + +def _lookup() -> _Lookup: + return _Lookup(container.catalog_queries().tree()) + + +def _tree_response( + request: HttpRequest, lookup: _Lookup, *, message: str, focus: str, error: bool = False +) -> HttpResponse: + """HTMX: re-render the tree, close the dialog, focus ``focus`` and announce ``message``. + Otherwise: flash the message and go back to the page at the row.""" + if not getattr(request, "htmx", False): + (messages.error if error else messages.success)(request, message) + return redirect(reverse("catalog:index") + focus.replace("#name-", "#row-")) + response = render(request, "catalog/partials/tree.html", {"tree": lookup.tree}) + response["HX-Retarget"] = "#catalog-tree" + response["HX-Reswap"] = "outerHTML" + response["HX-Trigger-After-Settle"] = json.dumps( + {"itemSaved": {"message": message, "focus": focus}} + ) + return response + + +def _error_message(error: DomainError) -> str: + return str(ERROR_MESSAGES.get(error.code, ERROR_MESSAGES["*"])) + + +class CatalogAccessMixin(PermissionRequiredMixin): + permission = Permission.CATALOG_MANAGE + + +class CatalogIndexView(CatalogAccessMixin, TemplateView): + template_name = "catalog/index.html" + + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: + context = super().get_context_data(**kwargs) + context["tree"] = container.catalog_queries().tree() + return context + + +class ItemFormView(CatalogAccessMixin, View): + """GET: the add or edit form (dialog body for HTMX, full page otherwise). POST: save.""" + + def _prepare(self) -> tuple[_Kind, Node | None, ServiceUnitNode | None]: + kind = _kind(self.kwargs["kind"]) + item_id: int | None = self.kwargs.get("item_id") + unit_id: int | None = self.kwargs.get("unit_id") + lookup = _lookup() + if item_id is not None: + return kind, lookup.get(kind.key, item_id), lookup.unit(kind.key, item_id) + if kind.has_parent != (unit_id is not None): + raise Http404 + unit = lookup.get(UNITS, unit_id) if unit_id is not None else None + assert unit is None or isinstance(unit, ServiceUnitNode) + return kind, None, unit + + def _form( + self, kind: _Kind, item: Node | None, unit: ServiceUnitNode | None, data: Any = None + ) -> Any: + initial: dict[str, Any] = {} + if item is not None: + initial["name"] = item.name + if isinstance(item, WorkTypeNode): + initial["service"] = item.service_id or "" + if kind.form_class is WorkTypeForm: + assert unit is not None + return WorkTypeForm(data, initial=initial, services=unit.services) + return kind.form_class(data, initial=initial) + + def _render( + self, + kind: _Kind, + item: Node | None, + unit: ServiceUnitNode | None, + form: Any, + status: int = 200, + ) -> HttpResponse: + if item is not None: + action_url = reverse("catalog:edit", args=[kind.key, item.id]) + elif unit is not None: + action_url = reverse("catalog:child_create", args=[unit.id, kind.key]) + else: + action_url = reverse("catalog:unit_create") + context = { + "form": form, + "title": kind.edit_title if item else kind.add_title, + "action_url": action_url, + "parent_name": unit.name if unit is not None and kind.has_parent else "", + } + template = ( + "catalog/partials/item_form.html" + if getattr(self.request, "htmx", False) + else "catalog/item_form_page.html" + ) + return render(self.request, template, context, status=status) + + def get(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + kind, item, unit = self._prepare() + return self._render(kind, item, unit, self._form(kind, item, unit)) + + def post(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + kind, item, unit = self._prepare() + form = self._form(kind, item, unit, request.POST) + if form.is_valid(): + try: + if item is None: + item_id = kind.add(unit.id if unit else None, form.to_dto()) + else: + item_id = item.id + kind.update(item_id, form.to_dto()) + except DomainError as error: + form.add_domain_error(error, ERROR_MESSAGES) + else: + return _tree_response( + request, + _lookup(), + message=_(kind.saved), + focus=f"#name-{kind.prefix}-{item_id}", + ) + return self._render(kind, item, unit, form, status=422) + + +class MoveView(CatalogAccessMixin, View): + def post(self, request: HttpRequest, kind: str, item_id: int, direction: str) -> HttpResponse: + level = _kind(kind) + try: + step = Direction(direction) + except ValueError: + raise Http404 from None + error: DomainError | None = None + try: + level.move().execute(item_id, step) + except DomainError as e: + error = e + lookup = _lookup() + name = lookup.get(level.key, item_id).name + siblings = lookup.siblings(level.key, item_id) + # Keep focus on the same button, unless the row reached the edge and it is now disabled. + position = siblings.index(item_id) + at_edge = position == 0 if step is Direction.UP else position == len(siblings) - 1 + focus_step = step + if at_edge: + focus_step = Direction.DOWN if step is Direction.UP else Direction.UP + focus = f"#move-{level.prefix}-{item_id}-{focus_step}" + if len(siblings) == 1: + focus = f"#name-{level.prefix}-{item_id}" + if error is not None: + message = _error_message(error) + elif step is Direction.UP: + message = _("%(name)s moved up.") % {"name": name} + else: + message = _("%(name)s moved down.") % {"name": name} + return _tree_response(request, lookup, message=message, focus=focus, error=bool(error)) + + +class ToggleActiveView(CatalogAccessMixin, View): + def post(self, request: HttpRequest, kind: str, item_id: int) -> HttpResponse: + level = _kind(kind) + active = request.POST.get("active") == "1" + error: DomainError | None = None + try: + level.set_active().execute(item_id, active) + except DomainError as e: + error = e + lookup = _lookup() + name = lookup.get(level.key, item_id).name + if error is not None: + message = _error_message(error) + elif active: + message = _("%(name)s is in use again.") % {"name": name} + else: + message = _("%(name)s is no longer in use.") % {"name": name} + return _tree_response( + request, + lookup, + message=message, + focus=f"#toggle-{level.prefix}-{item_id}", + error=bool(error), + ) diff --git a/apps/catalog/tests/__init__.py b/apps/catalog/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/tests/application/__init__.py b/apps/catalog/tests/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/tests/application/test_use_cases.py b/apps/catalog/tests/application/test_use_cases.py new file mode 100644 index 0000000..c70082b --- /dev/null +++ b/apps/catalog/tests/application/test_use_cases.py @@ -0,0 +1,187 @@ +import pytest + +from apps.catalog.application.dto import ServiceData, ServiceUnitData, WorkTypeData +from apps.catalog.application.use_cases import ( + AddService, + AddServiceUnit, + AddWorkType, + MoveItem, + RenameService, + RenameServiceUnit, + SetActive, + UpdateWorkType, +) +from apps.catalog.domain.exceptions import ( + CannotMove, + ServiceNameTaken, + ServiceNotFound, + ServiceNotInUnit, + ServiceUnitNameTaken, + ServiceUnitNotFound, + WorkTypeNameTaken, + WorkTypeNotFound, +) +from apps.catalog.domain.ordering import Direction +from apps.catalog.tests.fakes import ( + InMemoryServiceRepository, + InMemoryServiceUnitRepository, + InMemoryWorkTypeRepository, +) +from apps.shared.tests.fakes import FakeUnitOfWork + + +class Catalog: + def __init__(self) -> None: + self.units = InMemoryServiceUnitRepository() + self.services = InMemoryServiceRepository() + self.work_types = InMemoryWorkTypeRepository() + + def unit(self, name: str) -> int: + return AddServiceUnit(self.units, FakeUnitOfWork()).execute(ServiceUnitData(name)) + + def service(self, unit_id: int, name: str) -> int: + return AddService(self.units, self.services, FakeUnitOfWork()).execute( + unit_id, ServiceData(name) + ) + + def work_type(self, unit_id: int, name: str, service_id: int | None = None) -> int: + return AddWorkType(self.units, self.services, self.work_types, FakeUnitOfWork()).execute( + unit_id, WorkTypeData(name, service_id) + ) + + def update_work_type(self, work_type_id: int, name: str, service_id: int | None) -> None: + UpdateWorkType(self.units, self.services, self.work_types, FakeUnitOfWork()).execute( + work_type_id, WorkTypeData(name, service_id) + ) + + +@pytest.fixture +def cat() -> Catalog: + return Catalog() + + +class TestServiceUnits: + def test_new_units_go_last(self, cat: Catalog) -> None: + cat.unit("Markkinointi") + cat.unit("Painotuotanto") + assert cat.units.ordered_names(()) == ["Markkinointi", "Painotuotanto"] + + def test_name_is_unique_case_insensitively(self, cat: Catalog) -> None: + cat.unit("Markkinointi") + with pytest.raises(ServiceUnitNameTaken): + cat.unit("markkinointi") + + def test_rename(self, cat: Catalog) -> None: + a = cat.unit("Markkinointi") + b = cat.unit("Painotuotanto") + rename = RenameServiceUnit(cat.units, FakeUnitOfWork()) + rename.execute(a, ServiceUnitData("MARKKINOINTI")) # own name in another case is fine + assert cat.units.items[a].name.value == "MARKKINOINTI" + with pytest.raises(ServiceUnitNameTaken): + rename.execute(b, ServiceUnitData("markkinointi")) + with pytest.raises(ServiceUnitNotFound): + rename.execute(99, ServiceUnitData("X")) + + +class TestServices: + def test_name_unique_within_unit_only(self, cat: Catalog) -> None: + a, b = cat.unit("Mediatuotanto"), cat.unit("Kuluttajapalvelut") + cat.service(a, "Valokuvaus") + cat.service(b, "Valokuvaus") + with pytest.raises(ServiceNameTaken): + cat.service(a, "VALOKUVAUS") + + def test_unknown_unit(self, cat: Catalog) -> None: + with pytest.raises(ServiceUnitNotFound): + cat.service(5, "Valokuvaus") + + def test_rename(self, cat: Catalog) -> None: + a = cat.unit("Mediatuotanto") + s1 = cat.service(a, "Valokuvaus") + cat.service(a, "Videotuotanto") + rename = RenameService(cat.services, FakeUnitOfWork()) + with pytest.raises(ServiceNameTaken): + rename.execute(s1, ServiceData("videotuotanto")) + rename.execute(s1, ServiceData("Kuvaus")) + assert cat.services.items[s1].name.value == "Kuvaus" + + +class TestWorkTypes: + def test_same_name_allowed_on_different_levels(self, cat: Catalog) -> None: + unit = cat.unit("Mediatuotanto") + video, photo = cat.service(unit, "Videotuotanto"), cat.service(unit, "Valokuvaus") + cat.work_type(unit, "Editointi", video) + cat.work_type(unit, "Editointi", photo) + cat.work_type(unit, "Editointi") + with pytest.raises(WorkTypeNameTaken): + cat.work_type(unit, "editointi", video) + + def test_service_must_exist_and_belong_to_unit(self, cat: Catalog) -> None: + a, b = cat.unit("A"), cat.unit("B") + other = cat.service(b, "Palvelu") + with pytest.raises(ServiceNotFound): + cat.work_type(a, "X", 99) + with pytest.raises(ServiceNotInUnit): + cat.work_type(a, "X", other) + + def test_move_to_unit_and_back_goes_last(self, cat: Catalog) -> None: + unit = cat.unit("Mediatuotanto") + video = cat.service(unit, "Videotuotanto") + cat.work_type(unit, "Suunnittelu") + edit = cat.work_type(unit, "Editointi", video) + cat.work_type(unit, "Animointi", video) + + cat.update_work_type(edit, "Editointi", None) + assert cat.work_types.ordered_names((unit, None)) == ["Suunnittelu", "Editointi"] + assert cat.work_types.ordered_names((unit, video)) == ["Animointi"] + + cat.update_work_type(edit, "Videoeditointi", video) + assert cat.work_types.ordered_names((unit, video)) == ["Animointi", "Videoeditointi"] + + def test_moving_into_a_level_with_the_same_name_is_rejected(self, cat: Catalog) -> None: + unit = cat.unit("Mediatuotanto") + video = cat.service(unit, "Videotuotanto") + cat.work_type(unit, "Editointi") + edit = cat.work_type(unit, "Editointi", video) + with pytest.raises(WorkTypeNameTaken): + cat.update_work_type(edit, "Editointi", None) + assert cat.work_types.items[edit].service_id == video + + def test_unknown_work_type(self, cat: Catalog) -> None: + with pytest.raises(WorkTypeNotFound): + cat.update_work_type(1, "X", None) + + +class TestOrderAndActivation: + def test_move_up_and_down(self, cat: Catalog) -> None: + ids = [cat.unit(n) for n in ("A", "B", "C")] + move = MoveItem(cat.units, FakeUnitOfWork(), ServiceUnitNotFound) + move.execute(ids[2], Direction.UP) + assert cat.units.ordered_names(()) == ["A", "C", "B"] + move.execute(ids[0], Direction.DOWN) + assert cat.units.ordered_names(()) == ["C", "A", "B"] + with pytest.raises(CannotMove): + move.execute(ids[1], Direction.DOWN) + with pytest.raises(ServiceUnitNotFound): + move.execute(99, Direction.UP) + + def test_move_stays_within_siblings(self, cat: Catalog) -> None: + unit = cat.unit("U") + service = cat.service(unit, "S") + direct = cat.work_type(unit, "Suora") + first = cat.work_type(unit, "Eka", service) + with pytest.raises(CannotMove): # only work type directly under the unit + MoveItem(cat.work_types, FakeUnitOfWork(), WorkTypeNotFound).execute( + direct, Direction.DOWN + ) + assert cat.work_types.sibling_ids(cat.work_types.items[first]) == [first] + + def test_set_active(self, cat: Catalog) -> None: + unit = cat.unit("U") + toggle = SetActive(cat.units, FakeUnitOfWork(), ServiceUnitNotFound) + toggle.execute(unit, False) + assert not cat.units.items[unit].is_active + toggle.execute(unit, True) + assert cat.units.items[unit].is_active + with pytest.raises(ServiceUnitNotFound): + toggle.execute(42, False) diff --git a/apps/catalog/tests/domain/__init__.py b/apps/catalog/tests/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/tests/domain/test_domain.py b/apps/catalog/tests/domain/test_domain.py new file mode 100644 index 0000000..8ba24d1 --- /dev/null +++ b/apps/catalog/tests/domain/test_domain.py @@ -0,0 +1,62 @@ +import pytest + +from apps.catalog.domain.entities import Service, ServiceUnit, WorkType +from apps.catalog.domain.exceptions import CannotMove, InvalidCatalogName, ServiceNotInUnit +from apps.catalog.domain.ordering import Direction, move +from apps.catalog.domain.value_objects import CatalogName + + +class TestCatalogName: + def test_spaces_are_normalized(self) -> None: + assert CatalogName(" Graafinen työ ").value == "Graafinen työ" + + @pytest.mark.parametrize("value", ["", " ", "x" * 101]) + def test_invalid(self, value: str) -> None: + with pytest.raises(InvalidCatalogName): + CatalogName(value) + + def test_same_as_ignores_case_and_spaces(self) -> None: + assert CatalogName("Editointi").same_as(" EDITOINTI ") + assert not CatalogName("Editointi").same_as("Kuvaus") + + +class TestMove: + def test_up_and_down(self) -> None: + assert move([1, 2, 3], 2, Direction.UP) == [2, 1, 3] + assert move([1, 2, 3], 2, Direction.DOWN) == [1, 3, 2] + + def test_edges(self) -> None: + with pytest.raises(CannotMove): + move([1, 2], 1, Direction.UP) + with pytest.raises(CannotMove): + move([1, 2], 2, Direction.DOWN) + + +def service(id: int, unit_id: int) -> Service: + return Service.reconstitute( + id=id, service_unit_id=unit_id, name=CatalogName("S"), is_active=True, sort_order=1 + ) + + +class TestWorkType: + def test_service_must_belong_to_the_same_unit(self) -> None: + with pytest.raises(ServiceNotInUnit): + WorkType.register( + service_unit_id=1, service=service(5, 2), name=CatalogName("X"), sort_order=1 + ) + + def test_move_between_service_and_unit(self) -> None: + wt = WorkType.register( + service_unit_id=1, service=service(5, 1), name=CatalogName("X"), sort_order=1 + ) + assert wt.service_id == 5 + moved = wt.move_to(None, sort_order=7) + assert (moved.service_id, moved.sort_order) == (None, 7) + with pytest.raises(ServiceNotInUnit): + moved.move_to(service(6, 3), sort_order=1) + + def test_deactivate_and_activate(self) -> None: + unit = ServiceUnit.register(name=CatalogName("U"), sort_order=1) + assert unit.is_active + assert not unit.with_active(False).is_active + assert unit.with_active(False).with_active(True).is_active diff --git a/apps/catalog/tests/fakes.py b/apps/catalog/tests/fakes.py new file mode 100644 index 0000000..d40f21f --- /dev/null +++ b/apps/catalog/tests/fakes.py @@ -0,0 +1,90 @@ +"""In-memory test doubles for the catalog application layer (no database).""" + +from collections.abc import Sequence +from dataclasses import replace +from typing import Any + +from apps.catalog.domain.entities import Service, ServiceUnit, WorkType +from apps.catalog.domain.value_objects import CatalogName + + +class _InMemory[T: (ServiceUnit, Service, WorkType)]: + def __init__(self) -> None: + self.items: dict[int, T] = {} + self._next = 1 + + def _level(self, item: T) -> tuple[Any, ...]: + raise NotImplementedError + + def _on_level(self, level: tuple[Any, ...]) -> list[T]: + rows = [i for i in self.items.values() if self._level(i) == level] + return sorted(rows, key=lambda i: (i.sort_order, i.id or 0)) + + def get(self, item_id: int) -> T | None: + return self.items.get(item_id) + + def save(self, item: T) -> T: + if item.id is None: + item = item.with_id(self._next) + self._next += 1 + assert item.id is not None + self.items[item.id] = item + return item + + def sibling_ids(self, item: T) -> list[int]: + return [i.id for i in self._on_level(self._level(item)) if i.id is not None] + + def set_order(self, ids: Sequence[int]) -> None: + for position, pk in enumerate(ids, start=1): + self.items[pk] = replace(self.items[pk], sort_order=position) + + def _taken(self, level: tuple[Any, ...], name: CatalogName, exclude_id: int | None) -> bool: + return any(i.name.same_as(name.value) and i.id != exclude_id for i in self._on_level(level)) + + def _next_order(self, level: tuple[Any, ...]) -> int: + return max((i.sort_order for i in self._on_level(level)), default=0) + 1 + + def ordered_names(self, level: tuple[Any, ...]) -> list[str]: + return [i.name.value for i in self._on_level(level)] + + +class InMemoryServiceUnitRepository(_InMemory[ServiceUnit]): + def _level(self, item: ServiceUnit) -> tuple[Any, ...]: + return () + + def is_name_taken(self, name: CatalogName, *, exclude_id: int | None = None) -> bool: + return self._taken((), name, exclude_id) + + def next_sort_order(self) -> int: + return self._next_order(()) + + +class InMemoryServiceRepository(_InMemory[Service]): + def _level(self, item: Service) -> tuple[Any, ...]: + return (item.service_unit_id,) + + def is_name_taken( + self, service_unit_id: int, name: CatalogName, *, exclude_id: int | None = None + ) -> bool: + return self._taken((service_unit_id,), name, exclude_id) + + def next_sort_order(self, service_unit_id: int) -> int: + return self._next_order((service_unit_id,)) + + +class InMemoryWorkTypeRepository(_InMemory[WorkType]): + def _level(self, item: WorkType) -> tuple[Any, ...]: + return (item.service_unit_id, item.service_id) + + def is_name_taken( + self, + service_unit_id: int, + service_id: int | None, + name: CatalogName, + *, + exclude_id: int | None = None, + ) -> bool: + return self._taken((service_unit_id, service_id), name, exclude_id) + + def next_sort_order(self, service_unit_id: int, service_id: int | None) -> int: + return self._next_order((service_unit_id, service_id)) diff --git a/apps/catalog/tests/integration/__init__.py b/apps/catalog/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/catalog/tests/integration/test_catalog.py b/apps/catalog/tests/integration/test_catalog.py new file mode 100644 index 0000000..abacac9 --- /dev/null +++ b/apps/catalog/tests/integration/test_catalog.py @@ -0,0 +1,230 @@ +import json +from collections.abc import Callable +from datetime import date +from typing import Any + +import pytest +from django.db import IntegrityError, transaction +from django.test import Client + +from apps.catalog.infrastructure.orm import ServiceModel, ServiceUnitModel, WorkTypeModel +from apps.catalog.infrastructure.queries import DjangoCatalogQueries +from apps.users.infrastructure.orm import User + +pytestmark = pytest.mark.django_db + +HX = {"HX-Request": "true"} + + +def unit(name: str) -> ServiceUnitModel: + return ServiceUnitModel.objects.get(name=name) + + +def trigger(response: Any) -> dict[str, Any]: + return dict(json.loads(response["HX-Trigger-After-Settle"])["itemSaved"]) + + +class TestSeed: + def test_seed_matches_specification(self) -> None: + assert list(ServiceUnitModel.objects.values_list("name", flat=True)) == [ + "Mediatuotanto", + "Markkinointi", + "Painotuotanto", + "Ylläpitopalvelut", + "Verkkosivut", + "Ohjelmistot", + "Kuluttajapalvelut", + "Kaikille yhteiset", + ] + assert WorkTypeModel.objects.count() == 29 + media = unit("Mediatuotanto") + assert [s.name for s in media.services.all()] == [ + "Videotuotanto", + "Valokuvaus", + "Äänituotanto", + ] + assert not media.work_types.filter(service__isnull=True).exists() + video = media.services.get(name="Videotuotanto") + assert [w.name for w in video.work_types.all()][:2] == ["Videokuvaus", "Kuvausassistentti"] + shared = ServiceUnitModel.objects.get(is_shared=True) + assert shared.name == "Kaikille yhteiset" + assert shared.work_types.count() == 5 + + def test_service_unit_names_are_unique_in_database(self) -> None: + with pytest.raises(IntegrityError), transaction.atomic(): + ServiceUnitModel.objects.create(name="Markkinointi") + + +class TestPermissions: + @pytest.mark.parametrize("role", ["admin", "management"]) + def test_admin_and_management( + self, client: Client, make_user: Callable[..., User], role: str + ) -> None: + client.force_login(make_user(role=role)) + response = client.get("/catalog/") + assert response.status_code == 200 + assert "Pohjatiedot" in response.content.decode() + + @pytest.mark.parametrize("role", ["employee", "intern", "subcontractor"]) + def test_others_get_403( + self, client: Client, make_user: Callable[..., User], role: str + ) -> None: + extra: dict[str, Any] = {} + if role == "intern": + extra = {"supervisor": make_user(), "employment_ends_on": date(2099, 1, 1)} + client.force_login(make_user(role=role, **extra)) + assert client.get("/catalog/").status_code == 403 + marketing = unit("Markkinointi") + assert client.post(f"/catalog/service-units/{marketing.pk}/active/").status_code == 403 + assert "/catalog/" not in client.get("/").content.decode() + + +class TestForms: + def test_add_service_unit_with_htmx(self, admin_client: Client) -> None: + response = admin_client.post( + "/catalog/service-units/new/", {"name": "Tapahtumat"}, headers=HX + ) + assert response.status_code == 200 + new = unit("Tapahtumat") + assert new.sort_order == 9 + assert response["HX-Retarget"] == "#catalog-tree" + assert trigger(response) == { + "message": "Palveluyksikkö tallennettu.", + "focus": f"#name-unit-{new.pk}", + } + assert "Tapahtumat" in response.content.decode() + + def test_duplicate_name_returns_422(self, admin_client: Client) -> None: + response = admin_client.post("/catalog/service-units/new/", {"name": "markkinointi"}, **HX) + assert response.status_code == 422 + body = response.content.decode() + assert 'aria-invalid="true"' in body + assert "Samanniminen palveluyksikkö on jo olemassa." in body + + def test_add_service_and_work_type(self, admin_client: Client) -> None: + marketing = unit("Markkinointi") + admin_client.post( + f"/catalog/service-units/{marketing.pk}/services/new/", {"name": "Some"}, **HX + ) + some = ServiceModel.objects.get(name="Some") + form = admin_client.get( + f"/catalog/service-units/{marketing.pk}/work-types/new/", headers=HX + ) + assert "Suoraan palveluyksikön alle" in form.content.decode() + response = admin_client.post( + f"/catalog/service-units/{marketing.pk}/work-types/new/", + {"name": "Somemainonta", "service": str(some.pk)}, + headers=HX, + ) + assert response.status_code == 200 + assert WorkTypeModel.objects.get(name="Somemainonta").service_id == some.pk + + def test_move_work_type_to_another_service(self, admin_client: Client) -> None: + media = unit("Mediatuotanto") + animation = WorkTypeModel.objects.get(name="Animointi") + photo = media.services.get(name="Valokuvaus") + url = f"/catalog/work-types/{animation.pk}/edit/" + edit_form = admin_client.get(url).content.decode() + assert 'value="Animointi"' in edit_form + admin_client.post(url, {"name": "Animointi", "service": str(photo.pk)}, headers=HX) + animation.refresh_from_db() + assert animation.service_id == photo.pk + assert animation.sort_order == 3 # after Kuvaus and Editointi + admin_client.post(url, {"name": "Animointi", "service": ""}, headers=HX) + animation.refresh_from_db() + assert animation.service_id is None + + def test_service_of_another_unit_is_rejected(self, admin_client: Client) -> None: + animation = WorkTypeModel.objects.get(name="Animointi") + other = ServiceModel.objects.create(service_unit=unit("Markkinointi"), name="Some") + response = admin_client.post( + f"/catalog/work-types/{animation.pk}/edit/", + {"name": "Animointi", "service": str(other.pk)}, + headers=HX, + ) + assert response.status_code == 422 # not among the choices + + def test_child_create_needs_a_unit(self, admin_client: Client) -> None: + assert admin_client.get("/catalog/service-units/999/services/new/").status_code == 404 + assert admin_client.get("/catalog/nope/1/edit/").status_code == 404 + + def test_without_htmx_redirects(self, admin_client: Client) -> None: + response = admin_client.post("/catalog/service-units/new/", {"name": "Tapahtumat"}) + assert response.status_code == 302 + assert response["Location"] == f"/catalog/#row-unit-{unit('Tapahtumat').pk}" + + +class TestMoveAndToggle: + def test_move_down_keeps_focus_on_button(self, admin_client: Client) -> None: + media = unit("Mediatuotanto") + response = admin_client.post(f"/catalog/service-units/{media.pk}/move/down/", headers=HX) + assert response.status_code == 200 + assert list(ServiceUnitModel.objects.values_list("name", flat=True))[:2] == [ + "Markkinointi", + "Mediatuotanto", + ] + assert trigger(response) == { + "message": "Mediatuotanto siirretty alas.", + "focus": f"#move-unit-{media.pk}-down", + } + + def test_focus_moves_to_other_button_at_edge(self, admin_client: Client) -> None: + marketing = unit("Markkinointi") + response = admin_client.post(f"/catalog/service-units/{marketing.pk}/move/up/", headers=HX) + assert trigger(response)["focus"] == f"#move-unit-{marketing.pk}-down" + assert ServiceUnitModel.objects.first() == marketing + + def test_cannot_move_past_edge(self, admin_client: Client) -> None: + media = unit("Mediatuotanto") + response = admin_client.post(f"/catalog/service-units/{media.pk}/move/up/", headers=HX) + assert trigger(response)["message"] == "Riviä ei voi siirtää pidemmälle." + + def test_toggle(self, admin_client: Client) -> None: + media = unit("Mediatuotanto") + url = f"/catalog/service-units/{media.pk}/active/" + response = admin_client.post(url, {"active": "0"}, headers=HX) + media.refresh_from_db() + assert not media.is_active + assert trigger(response) == { + "message": "Mediatuotanto poistettu käytöstä.", + "focus": f"#toggle-unit-{media.pk}", + } + body = response.content.decode() + assert "Ei käytössä" in body + assert "Ota käyttöön" in body + admin_client.post(url, {"active": "1"}, headers=HX) + media.refresh_from_db() + assert media.is_active + + +class TestQueries: + def test_inactive_parents_hide_their_work_types(self) -> None: + q = DjangoCatalogQueries() + media, marketing = unit("Mediatuotanto"), unit("Markkinointi") + names = {o.name for o in q.work_type_options([media.pk])} + assert {"Videokuvaus", "Suunnittelu"} <= names # own and shared + assert "Graafinen työ" not in names + + ServiceModel.objects.filter(name="Videotuotanto").update(is_active=False) + names = {o.name for o in q.work_type_options([media.pk])} + assert "Videokuvaus" not in names + assert "Kuvaus" in names + videokuvaus = WorkTypeModel.objects.get(name="Videokuvaus") + assert videokuvaus.is_active # own flag untouched + option = q.get_work_type(videokuvaus.pk) + assert option is not None and not option.is_selectable + assert option.label == "Mediatuotanto / Videotuotanto / Videokuvaus" + + ServiceUnitModel.objects.filter(pk=marketing.pk).update(is_active=False) + assert not any( + o.service_unit_id == marketing.pk for o in q.work_type_options([marketing.pk]) + ) + assert marketing.pk not in [u.id for u in q.active_service_units()] + + def test_tree(self) -> None: + tree = DjangoCatalogQueries().tree() + assert len(tree) == 8 + media = tree[0] + assert [s.name for s in media.services] == ["Videotuotanto", "Valokuvaus", "Äänituotanto"] + assert media.work_types == () + assert tree[-1].is_shared diff --git a/apps/users/domain/enums.py b/apps/users/domain/enums.py index 3d6d8b3..ca41ab3 100644 --- a/apps/users/domain/enums.py +++ b/apps/users/domain/enums.py @@ -20,3 +20,5 @@ class Permission(StrEnum): CUSTOMERS_USE = "customers.use" # See the full personal identity code and remove it (others see it masked). CUSTOMERS_PERSONAL_ID_VIEW = "customers.personal_id.view" + # Base data: service units, services, work types (later price list, products). + CATALOG_MANAGE = "catalog.manage" diff --git a/apps/users/domain/permissions.py b/apps/users/domain/permissions.py index e0adbfc..bb30809 100644 --- a/apps/users/domain/permissions.py +++ b/apps/users/domain/permissions.py @@ -8,6 +8,7 @@ _PERMISSIONS: dict[Permission, frozenset[Role]] = { Permission.USERS_MANAGE: frozenset({Role.ADMIN}), Permission.CUSTOMERS_USE: _ALL_EXCEPT_SUBCONTRACTOR, Permission.CUSTOMERS_PERSONAL_ID_VIEW: frozenset({Role.ADMIN, Role.MANAGEMENT}), + Permission.CATALOG_MANAGE: frozenset({Role.ADMIN, Role.MANAGEMENT}), } diff --git a/config/settings.py b/config/settings.py index 012108e..6f414ed 100644 --- a/config/settings.py +++ b/config/settings.py @@ -47,6 +47,7 @@ INSTALLED_APPS = [ "apps.shared", "apps.users", "apps.customers", + "apps.catalog", ] MIDDLEWARE = [ diff --git a/config/urls.py b/config/urls.py index 7b63863..052c858 100644 --- a/config/urls.py +++ b/config/urls.py @@ -6,4 +6,5 @@ urlpatterns = [ path("", home, name="home"), path("", include("apps.users.presentation.urls")), path("customers/", include("apps.customers.presentation.urls")), + path("catalog/", include("apps.catalog.presentation.urls")), ] diff --git a/docs/maarittely.md b/docs/maarittely.md index cc88157..c9e2660 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -455,6 +455,7 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t ### 16.3 Pohjatiedot - Pääkäyttäjä ja johto voivat lisätä, nimetä uudelleen, järjestää ja poistaa käytöstä palveluyksiköitä, palveluita ja työtehtäviä Pohjatiedot-sivulla. Käytössä olleita ei poisteta, vaan ne poistetaan käytöstä. Järjestys muutetaan Siirrä ylös / Siirrä alas -painikkeilla (toimii näppäimistöllä). - Työtehtävän voi siirtää toiseen saman yksikön palveluun tai suoraan yksikön alle. +- Rivejä ei poisteta pysyvästi. Kun palveluyksikkö tai palvelu poistetaan käytöstä, sen alla olevat rivit säilyttävät oman käytössä-tietonsa, mutta niitä ei voi valita ennen kuin yläkohta otetaan taas käyttöön. Nimi on yksilöllinen samalla tasolla kirjainkoosta riippumatta. - Luvun 11.1 lista lisätään data-migraatiossa (`RunPython`), jos taulut ovat tyhjiä. ### 16.4 Asiakastyöt diff --git a/locale/fi/LC_MESSAGES/django.po b/locale/fi/LC_MESSAGES/django.po index 032702d..4d453ba 100644 --- a/locale/fi/LC_MESSAGES/django.po +++ b/locale/fi/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-29 13:39+0200\n" +"POT-Creation-Date: 2026-11-29 13:59+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -18,115 +18,335 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" +#: .\apps\catalog\presentation\forms.py:13 +#: .\apps\catalog\presentation\forms.py:20 +#: .\apps\catalog\presentation\forms.py:27 #: .\apps\customers\presentation\forms.py:13 -#: .\apps\customers\presentation\forms.py:62 -#: .\apps\customers\presentation\forms.py:77 +#: .\apps\customers\presentation\forms.py:66 +#: .\apps\customers\presentation\forms.py:84 #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:8 #: .\apps\users\presentation\forms.py:70 #: .\apps\users\presentation\templates\users\partials\user_table.html:8 msgid "Name" msgstr "Nimi" -#: .\apps\customers\presentation\forms.py:14 -#: .\apps\customers\presentation\forms.py:102 -#: .\apps\customers\presentation\templates\customers\detail.html:24 +#: .\apps\catalog\presentation\forms.py:29 +msgid "Service" +msgstr "Palvelu" + +#: .\apps\catalog\presentation\forms.py:33 +msgid "A work type can be moved to another service of the same service unit." +msgstr "Työtehtävän voi siirtää saman palveluyksikön toiseen palveluun." + +#: .\apps\catalog\presentation\forms.py:43 +#: .\apps\catalog\presentation\templates\catalog\partials\tree.html:29 +msgid "Directly under the service unit" +msgstr "Suoraan palveluyksikön alle" + +#: .\apps\catalog\presentation\forms.py:45 +#, python-format +msgid "%(name)s (not in use)" +msgstr "%(name)s (ei käytössä)" + +#: .\apps\catalog\presentation\labels.py:4 +msgid "Enter a name (at most 100 characters)." +msgstr "Anna nimi (enintään 100 merkkiä)." + +#: .\apps\catalog\presentation\labels.py:5 +msgid "A service unit with this name already exists." +msgstr "Samanniminen palveluyksikkö on jo olemassa." + +#: .\apps\catalog\presentation\labels.py:6 +msgid "This service unit already has a service with this name." +msgstr "Palveluyksiköllä on jo samanniminen palvelu." + +#: .\apps\catalog\presentation\labels.py:7 +msgid "There is already a work type with this name on this level." +msgstr "Samalla tasolla on jo samanniminen työtehtävä." + +#: .\apps\catalog\presentation\labels.py:8 +msgid "The service unit was not found." +msgstr "Palveluyksikköä ei löytynyt." + +#: .\apps\catalog\presentation\labels.py:9 +msgid "The service was not found." +msgstr "Palvelua ei löytynyt." + +#: .\apps\catalog\presentation\labels.py:10 +msgid "The work type was not found." +msgstr "Työtehtävää ei löytynyt." + +#: .\apps\catalog\presentation\labels.py:11 +msgid "Choose a service of the same service unit." +msgstr "Valitse saman palveluyksikön palvelu." + +#: .\apps\catalog\presentation\labels.py:12 +msgid "The row cannot be moved further." +msgstr "Riviä ei voi siirtää pidemmälle." + +#: .\apps\catalog\presentation\labels.py:13 +#: .\apps\customers\presentation\labels.py:39 +#: .\apps\users\presentation\labels.py:31 +msgid "The change could not be saved." +msgstr "Muutosta ei voitu tallentaa." + +#: .\apps\catalog\presentation\templates\catalog\index.html:2 +#: .\apps\catalog\presentation\templates\catalog\index.html:5 +#: .\apps\catalog\presentation\templates\catalog\item_form_page.html:5 +#: .\templates\base.html:63 +msgid "Base data" +msgstr "Pohjatiedot" + +#: .\apps\catalog\presentation\templates\catalog\index.html:9 +#: .\apps\catalog\presentation\views.py:60 +msgid "Add service unit" +msgstr "Lisää palveluyksikkö" + +#: .\apps\catalog\presentation\templates\catalog\index.html:11 +msgid "" +"Service units, their services and work types. Work types of the shared unit " +"can be chosen in every service unit. Rows are not deleted: a row taken out " +"of use, and everything under it, can no longer be chosen." +msgstr "Palveluyksiköt, niiden palvelut ja työtehtävät. Kaikille yhteisten työtehtävät ovat valittavissa jokaisessa palveluyksikössä. Rivejä ei poisteta: käytöstä poistettua riviä ja kaikkea sen alla olevaa ei voi enää valita." + +#: .\apps\catalog\presentation\templates\catalog\item_form_page.html:4 +#: .\apps\customers\presentation\templates\customers\child_form_page.html:4 +#: .\apps\customers\presentation\templates\customers\detail.html:4 +#: .\apps\customers\presentation\templates\customers\form.html:4 +#: .\apps\users\presentation\templates\users\form.html:4 +msgid "Breadcrumbs" +msgstr "Murupolku" + +#: .\apps\catalog\presentation\templates\catalog\partials\badges.html:1 +msgid "Shared by all units" +msgstr "Kaikille yhteiset" + +#: .\apps\catalog\presentation\templates\catalog\partials\badges.html:2 +msgid "Not in use" +msgstr "Ei käytössä" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_actions.html:7 +#: .\apps\customers\presentation\templates\customers\form.html:8 +#: .\apps\customers\presentation\templates\customers\partials\actions.html:2 +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:26 +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:23 +msgid "Edit" +msgstr "Muokkaa" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_actions.html:12 +msgid "Move up" +msgstr "Siirrä ylös" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_actions.html:14 +#, python-format +msgid "Move up: %(name)s" +msgstr "Siirrä ylös: %(name)s" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_actions.html:21 +msgid "Move down" +msgstr "Siirrä alas" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_actions.html:23 +#, python-format +msgid "Move down: %(name)s" +msgstr "Siirrä alas: %(name)s" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_actions.html:32 +msgid "Take out of use" +msgstr "Poista käytöstä" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_actions.html:32 +msgid "Take into use" +msgstr "Ota käyttöön" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_form.html:2 +msgid "Service unit" +msgstr "Palveluyksikkö" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_form.html:8 +#: .\apps\customers\presentation\templates\customers\form.html:29 +#: .\apps\customers\presentation\templates\customers\partials\child_form.html:18 +#: .\apps\users\presentation\templates\users\form.html:26 +#: .\templates\components\confirm_dialog.html:8 +msgid "Cancel" +msgstr "Peruuta" + +#: .\apps\catalog\presentation\templates\catalog\partials\item_form.html:9 +#: .\apps\customers\presentation\templates\customers\form.html:30 +#: .\apps\customers\presentation\templates\customers\partials\child_form.html:19 +#: .\apps\users\presentation\templates\users\form.html:27 +msgid "Save" +msgstr "Tallenna" + +#: .\apps\catalog\presentation\templates\catalog\partials\tree.html:11 +#, python-format +msgid "Services of %(name)s" +msgstr "Palveluyksikön %(name)s palvelut" + +#: .\apps\catalog\presentation\templates\catalog\partials\tree.html:21 +msgid "No work types yet." +msgstr "Ei vielä työtehtäviä." + +#: .\apps\catalog\presentation\templates\catalog\partials\tree.html:32 +msgid "No services or work types yet." +msgstr "Ei vielä palveluita eikä työtehtäviä." + +#: .\apps\catalog\presentation\templates\catalog\partials\tree.html:40 +#: .\apps\catalog\presentation\views.py:73 +msgid "Add service" +msgstr "Lisää palvelu" + +#: .\apps\catalog\presentation\templates\catalog\partials\tree.html:45 +#: .\apps\catalog\presentation\views.py:86 +msgid "Add work type" +msgstr "Lisää työtehtävä" + +#: .\apps\catalog\presentation\templates\catalog\partials\tree.html:50 +msgid "No service units yet." +msgstr "Ei vielä palveluyksiköitä." + +#: .\apps\catalog\presentation\views.py:61 +msgid "Edit service unit" +msgstr "Muokkaa palveluyksikköä" + +#: .\apps\catalog\presentation\views.py:62 +msgid "Service unit saved." +msgstr "Palveluyksikkö tallennettu." + +#: .\apps\catalog\presentation\views.py:74 +msgid "Edit service" +msgstr "Muokkaa palvelua" + +#: .\apps\catalog\presentation\views.py:75 +msgid "Service saved." +msgstr "Palvelu tallennettu." + +#: .\apps\catalog\presentation\views.py:87 +msgid "Edit work type" +msgstr "Muokkaa työtehtävää" + +#: .\apps\catalog\presentation\views.py:88 +msgid "Work type saved." +msgstr "Työtehtävä tallennettu." + +#: .\apps\catalog\presentation\views.py:287 +#, python-format +msgid "%(name)s moved up." +msgstr "%(name)s siirretty ylös." + +#: .\apps\catalog\presentation\views.py:289 +#, python-format +msgid "%(name)s moved down." +msgstr "%(name)s siirretty alas." + +#: .\apps\catalog\presentation\views.py:307 +#, python-format +msgid "%(name)s is in use again." +msgstr "%(name)s otettu käyttöön." + +#: .\apps\catalog\presentation\views.py:309 +#, python-format +msgid "%(name)s is no longer in use." +msgstr "%(name)s poistettu käytöstä." + +#: .\apps\customers\presentation\forms.py:15 +#: .\apps\customers\presentation\forms.py:112 +#: .\apps\customers\presentation\templates\customers\detail.html:19 #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:9 msgid "Type" msgstr "Tyyppi" -#: .\apps\customers\presentation\forms.py:16 -#: .\apps\customers\presentation\templates\customers\detail.html:26 +#: .\apps\customers\presentation\forms.py:18 +#: .\apps\customers\presentation\templates\customers\detail.html:21 #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:10 msgid "Business ID" msgstr "Y-tunnus" -#: .\apps\customers\presentation\forms.py:16 +#: .\apps\customers\presentation\forms.py:18 msgid "For example 1234567-1" msgstr "Esimerkiksi 1234567-1" -#: .\apps\customers\presentation\forms.py:19 -#: .\apps\customers\presentation\templates\customers\detail.html:28 +#: .\apps\customers\presentation\forms.py:21 +#: .\apps\customers\presentation\templates\customers\detail.html:23 msgid "Personal identity code" msgstr "Henkilötunnus" -#: .\apps\customers\presentation\forms.py:24 +#: .\apps\customers\presentation\forms.py:26 msgid "Needed only for invoicing a consumer." msgstr "Tarvitaan vain kuluttajan laskutukseen." -#: .\apps\customers\presentation\forms.py:26 +#: .\apps\customers\presentation\forms.py:29 msgid "Remove personal identity code" msgstr "Poista henkilötunnus" -#: .\apps\customers\presentation\forms.py:40 +#: .\apps\customers\presentation\forms.py:44 #, python-format msgid "Stored: %(masked)s. Leave empty to keep it." msgstr "Tallennettu: %(masked)s. Jätä tyhjäksi, niin tunnus säilyy." -#: .\apps\customers\presentation\forms.py:46 +#: .\apps\customers\presentation\forms.py:50 #: .\apps\customers\presentation\labels.py:18 msgid "The internal customer is always a company." msgstr "Sisäinen asiakas on aina yritys." -#: .\apps\customers\presentation\forms.py:63 +#: .\apps\customers\presentation\forms.py:67 msgid "Title or role" msgstr "Titteli tai rooli" -#: .\apps\customers\presentation\forms.py:65 +#: .\apps\customers\presentation\forms.py:69 msgid "Phone" msgstr "Puhelin" -#: .\apps\customers\presentation\forms.py:67 +#: .\apps\customers\presentation\forms.py:74 #: .\apps\users\presentation\forms.py:22 .\apps\users\presentation\forms.py:52 #: .\apps\users\presentation\forms.py:71 #: .\apps\users\presentation\templates\users\partials\user_table.html:9 msgid "Email" msgstr "Sähköposti" -#: .\apps\customers\presentation\forms.py:69 +#: .\apps\customers\presentation\forms.py:76 msgid "Note" msgstr "Lisätieto" -#: .\apps\customers\presentation\forms.py:79 +#: .\apps\customers\presentation\forms.py:86 msgid "Billing address" msgstr "Laskutusosoite" -#: .\apps\customers\presentation\forms.py:82 -#| msgid "Enter a valid email address." +#: .\apps\customers\presentation\forms.py:89 msgid "Postal address or billing email address." msgstr "Postiosoite tai laskutussähköposti." -#: .\apps\customers\presentation\forms.py:85 +#: .\apps\customers\presentation\forms.py:92 msgid "E-invoice address" msgstr "Verkkolaskuosoite" -#: .\apps\customers\presentation\forms.py:85 +#: .\apps\customers\presentation\forms.py:95 msgid "12–35 letters or digits." msgstr "12–35 kirjainta tai numeroa." -#: .\apps\customers\presentation\forms.py:88 +#: .\apps\customers\presentation\forms.py:98 msgid "Operator ID" msgstr "Välittäjätunnus" -#: .\apps\customers\presentation\forms.py:91 +#: .\apps\customers\presentation\forms.py:101 msgid "Required when an e-invoice address is given." msgstr "Pakollinen, jos verkkolaskuosoite on annettu." -#: .\apps\customers\presentation\forms.py:93 +#: .\apps\customers\presentation\forms.py:103 #: .\apps\customers\presentation\templates\customers\partials\billing_units.html:20 msgid "Reference" msgstr "Viite" -#: .\apps\customers\presentation\forms.py:100 +#: .\apps\customers\presentation\forms.py:110 #: .\apps\users\presentation\forms.py:113 msgid "Search" msgstr "Haku" -#: .\apps\customers\presentation\forms.py:100 +#: .\apps\customers\presentation\forms.py:110 msgid "Name or business ID" msgstr "Nimi tai Y-tunnus" -#: .\apps\customers\presentation\forms.py:102 -#| msgid "All roles" +#: .\apps\customers\presentation\forms.py:112 msgid "All types" msgstr "Kaikki tyypit" @@ -140,7 +360,6 @@ msgstr "Kuluttaja" #: .\apps\customers\presentation\labels.py:13 #: .\apps\customers\presentation\labels.py:31 -#| msgid "Enter a name (at most 150 characters)." msgid "Enter a name (at most 200 characters)." msgstr "Anna nimi (enintään 200 merkkiä)." @@ -149,7 +368,6 @@ msgid "Enter a valid business ID, for example 1234567-1." msgstr "Anna kelvollinen Y-tunnus, esimerkiksi 1234567-1." #: .\apps\customers\presentation\labels.py:15 -#| msgid "Enter a valid email address." msgid "Enter a valid personal identity code." msgstr "Anna kelvollinen henkilötunnus." @@ -174,7 +392,6 @@ msgid "You are not allowed to remove the personal identity code." msgstr "Sinulla ei ole oikeutta poistaa henkilötunnusta." #: .\apps\customers\presentation\labels.py:24 -#| msgid "The user was not found." msgid "The customer was not found." msgstr "Asiakasta ei löytynyt." @@ -182,10 +399,11 @@ msgstr "Asiakasta ei löytynyt." msgid "" "The customer cannot be deleted because it has contacts, billing units, jobs, " "sales or invoices." -msgstr "Asiakasta ei voi poistaa, koska sillä on yhteyshenkilöitä, laskutusyksiköitä, asiakastöitä, myyntejä tai laskuja." +msgstr "" +"Asiakasta ei voi poistaa, koska sillä on yhteyshenkilöitä, " +"laskutusyksiköitä, asiakastöitä, myyntejä tai laskuja." #: .\apps\customers\presentation\labels.py:29 -#| msgid "An intern must have an end date." msgid "The internal customer cannot be deleted." msgstr "Sisäistä asiakasta ei voi poistaa." @@ -208,12 +426,10 @@ msgid "Enter a valid email address." msgstr "Anna kelvollinen sähköpostiosoite." #: .\apps\customers\presentation\labels.py:35 -#| msgid "The user was not found." msgid "The contact was not found." msgstr "Yhteyshenkilöä ei löytynyt." #: .\apps\customers\presentation\labels.py:36 -#| msgid "The user was not found." msgid "The billing unit was not found." msgstr "Laskutusyksikköä ei löytynyt." @@ -225,18 +441,6 @@ msgstr "Yhteyshenkilöä ei voi poistaa, koska asiakastyö viittaa siihen." msgid "The billing unit cannot be deleted because a job refers to it." msgstr "Laskutusyksikköä ei voi poistaa, koska asiakastyö viittaa siihen." -#: .\apps\customers\presentation\labels.py:39 -#: .\apps\users\presentation\labels.py:31 -msgid "The change could not be saved." -msgstr "Muutosta ei voitu tallentaa." - -#: .\apps\customers\presentation\templates\customers\child_form_page.html:4 -#: .\apps\customers\presentation\templates\customers\detail.html:4 -#: .\apps\customers\presentation\templates\customers\form.html:4 -#: .\apps\users\presentation\templates\users\form.html:4 -msgid "Breadcrumbs" -msgstr "Murupolku" - #: .\apps\customers\presentation\templates\customers\child_form_page.html:6 #: .\apps\customers\presentation\templates\customers\detail.html:5 #: .\apps\customers\presentation\templates\customers\form.html:6 @@ -249,51 +453,23 @@ msgstr "Asiakkaat" #: .\apps\customers\presentation\templates\customers\detail.html:10 #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:18 -#| msgid "Intern" msgid "Internal" msgstr "Sisäinen" -#: .\apps\customers\presentation\templates\customers\detail.html:13 -#: .\apps\customers\presentation\templates\customers\form.html:8 -#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:26 -#: .\apps\customers\presentation\templates\customers\partials\contacts.html:23 -#| msgid "Edit user" -msgid "Edit" -msgstr "Muokkaa" - -#: .\apps\customers\presentation\templates\customers\detail.html:15 -msgid "Delete customer" -msgstr "Poista asiakas" - -#: .\apps\customers\presentation\templates\customers\detail.html:22 +#: .\apps\customers\presentation\templates\customers\detail.html:17 msgid "Basic information" msgstr "Perustiedot" -#: .\apps\customers\presentation\templates\customers\detail.html:33 +#: .\apps\customers\presentation\templates\customers\detail.html:28 msgid "" "Internal work (administration, sales, training) is recorded on the jobs of " "the internal customer. It cannot be deleted." -msgstr "Sisäinen työ (hallinto, myynti, koulutus) kirjataan sisäisen asiakkaan asiakastöille. Sisäistä asiakasta ei voi poistaa." - -#: .\apps\customers\presentation\templates\customers\detail.html:49 -msgid "Delete the customer?" -msgstr "Poistetaanko asiakas?" - -#: .\apps\customers\presentation\templates\customers\detail.html:50 -msgid "The customer is deleted permanently." -msgstr "Asiakas poistetaan pysyvästi." - -#: .\apps\customers\presentation\templates\customers\detail.html:51 -#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:31 -#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:35 -#: .\apps\customers\presentation\templates\customers\partials\contacts.html:28 -#: .\apps\customers\presentation\templates\customers\partials\contacts.html:32 -msgid "Delete" -msgstr "Poista" +msgstr "" +"Sisäinen työ (hallinto, myynti, koulutus) kirjataan sisäisen asiakkaan " +"asiakastöille. Sisäistä asiakasta ei voi poistaa." #: .\apps\customers\presentation\templates\customers\form.html:2 #: .\apps\customers\presentation\templates\customers\form.html:11 -#| msgid "Edit user" msgid "Edit customer" msgstr "Muokkaa asiakasta" @@ -301,7 +477,6 @@ msgstr "Muokkaa asiakasta" #: .\apps\customers\presentation\templates\customers\form.html:8 #: .\apps\customers\presentation\templates\customers\form.html:11 #: .\apps\customers\presentation\templates\customers\list.html:6 -#| msgid "New user" msgid "New customer" msgstr "Uusi asiakas" @@ -309,23 +484,11 @@ msgstr "Uusi asiakas" msgid "" "The personal identity code is specially protected data. It is stored " "encrypted and used only for invoicing." -msgstr "Henkilötunnus on erityisen suojattava tieto. Se tallennetaan salattuna ja sitä käytetään vain laskutukseen." - -#: .\apps\customers\presentation\templates\customers\form.html:29 -#: .\apps\customers\presentation\templates\customers\partials\child_form.html:18 -#: .\apps\users\presentation\templates\users\form.html:26 -#: .\templates\components\confirm_dialog.html:8 -msgid "Cancel" -msgstr "Peruuta" - -#: .\apps\customers\presentation\templates\customers\form.html:30 -#: .\apps\customers\presentation\templates\customers\partials\child_form.html:19 -#: .\apps\users\presentation\templates\users\form.html:27 -msgid "Save" -msgstr "Tallenna" +msgstr "" +"Henkilötunnus on erityisen suojattava tieto. Se tallennetaan salattuna ja " +"sitä käytetään vain laskutukseen." #: .\apps\customers\presentation\templates\customers\list.html:9 -#| msgid "Filter users" msgid "Filter customers" msgstr "Suodata asiakkaita" @@ -334,6 +497,26 @@ msgstr "Suodata asiakkaita" msgid "Filter" msgstr "Suodata" +#: .\apps\customers\presentation\templates\customers\partials\actions.html:4 +msgid "Delete customer" +msgstr "Poista asiakas" + +#: .\apps\customers\presentation\templates\customers\partials\actions.html:8 +msgid "Delete the customer?" +msgstr "Poistetaanko asiakas?" + +#: .\apps\customers\presentation\templates\customers\partials\actions.html:9 +msgid "The customer is deleted permanently." +msgstr "Asiakas poistetaan pysyvästi." + +#: .\apps\customers\presentation\templates\customers\partials\actions.html:10 +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:31 +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:35 +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:28 +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:32 +msgid "Delete" +msgstr "Poista" + #: .\apps\customers\presentation\templates\customers\partials\billing_units.html:4 msgid "Billing units" msgstr "Laskutusyksiköt" @@ -391,7 +574,7 @@ msgid "Contacts" msgstr "Yhteyshenkilöt" #: .\apps\customers\presentation\templates\customers\partials\contacts.html:30 -#| msgid "Welcome, %(name)s" +#, python-format msgid "Delete contact %(name)s?" msgstr "Poistetaanko yhteyshenkilö %(name)s?" @@ -404,15 +587,13 @@ msgid "No contacts yet." msgstr "Ei vielä yhteyshenkilöitä." #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:2 -#| msgid "%(counter)s user found" -#| msgid_plural "%(counter)s users found" +#, python-format msgid "%(counter)s customer found" msgid_plural "%(counter)s customers found" msgstr[0] "%(counter)s asiakas löytyi" msgstr[1] "%(counter)s asiakasta löytyi" #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:24 -#| msgid "No users match the filters." msgid "No customers match the filters." msgstr "Hakuehtoja vastaavia asiakkaita ei löytynyt." @@ -445,35 +626,32 @@ msgstr "Näytä henkilötunnus" msgid "Not given" msgstr "Ei annettu" -#: .\apps\customers\presentation\views.py:82 -#| msgid "User created." +#: .\apps\customers\presentation\views.py:83 msgid "Customer created." msgstr "Asiakas luotu." -#: .\apps\customers\presentation\views.py:130 +#: .\apps\customers\presentation\views.py:133 #: .\apps\users\presentation\views.py:198 msgid "Changes saved." msgstr "Muutokset tallennettu." -#: .\apps\customers\presentation\views.py:172 -#| msgid "User created." +#: .\apps\customers\presentation\views.py:175 msgid "Customer deleted." msgstr "Asiakas poistettu." -#: .\apps\customers\presentation\views.py:238 -#| msgid "Changes saved." +#: .\apps\customers\presentation\views.py:247 msgid "Contact saved." msgstr "Yhteyshenkilö tallennettu." -#: .\apps\customers\presentation\views.py:239 +#: .\apps\customers\presentation\views.py:248 msgid "Contact deleted." msgstr "Yhteyshenkilö poistettu." -#: .\apps\customers\presentation\views.py:250 +#: .\apps\customers\presentation\views.py:259 msgid "Billing unit saved." msgstr "Laskutusyksikkö tallennettu." -#: .\apps\customers\presentation\views.py:251 +#: .\apps\customers\presentation\views.py:260 msgid "Billing unit deleted." msgstr "Laskutusyksikkö poistettu." @@ -503,7 +681,9 @@ msgstr "Salasanassa on oltava erikoismerkki." 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." +msgstr "" +"Vähintään %(min)d merkkiä, joista on oltava iso ja pieni kirjain, numero ja " +"erikoismerkki." #: .\apps\users\presentation\forms.py:25 msgid "Remember me" @@ -515,7 +695,8 @@ 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." +msgstr "" +"Liian monta kirjautumisyritystä. Yritä uudelleen muutaman minuutin kuluttua." #: .\apps\users\presentation\forms.py:72 .\apps\users\presentation\forms.py:115 #: .\apps\users\presentation\templates\users\partials\user_table.html:10 @@ -603,11 +784,15 @@ msgstr "Vastuuhenkilön on oltava aktiivinen johdon jäsen tai työntekijä." 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." +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ä." +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." @@ -658,7 +843,9 @@ 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." +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" @@ -685,7 +872,7 @@ msgstr "Uusi käyttäjä" #: .\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:61 +#: .\templates\base.html:66 msgid "Users" msgstr "Käyttäjät" @@ -702,7 +889,10 @@ msgstr "Salasanalinkki" 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." +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" @@ -734,7 +924,9 @@ msgstr "Kirjaudu" 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." +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 @@ -802,7 +994,9 @@ msgstr "Linkki ei ole voimassa" 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." +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" @@ -812,7 +1006,9 @@ msgstr "Tilaa uusi linkki" 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." +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." @@ -850,7 +1046,7 @@ msgstr "Siirry sisältöön" msgid "Open menu" msgstr "Avaa valikko" -#: .\templates\base.html:40 .\templates\base.html:69 +#: .\templates\base.html:40 .\templates\base.html:74 msgid "Log out" msgstr "Kirjaudu ulos" diff --git a/pyproject.toml b/pyproject.toml index 05cfb7e..80a3216 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,6 +48,8 @@ source_modules = [ "apps.users.application", "apps.customers.domain", "apps.customers.application", + "apps.catalog.domain", + "apps.catalog.application", ] forbidden_modules = ["django"] allow_indirect_imports = true @@ -79,17 +81,37 @@ layers = [ ] ignore_imports = ["apps.customers.presentation.** -> apps.customers.container"] +[[tool.importlinter.contracts]] +name = "catalog layers" +type = "layers" +layers = [ + "apps.catalog.container", + "apps.catalog.presentation", + "apps.catalog.infrastructure", + "apps.catalog.application", + "apps.catalog.domain", +] +ignore_imports = ["apps.catalog.presentation.** -> apps.catalog.container"] + [[tool.importlinter.contracts]] name = "Presentation does not use infrastructure directly" type = "forbidden" -source_modules = ["apps.users.presentation", "apps.customers.presentation"] -forbidden_modules = ["apps.users.infrastructure", "apps.customers.infrastructure"] +source_modules = [ + "apps.users.presentation", + "apps.customers.presentation", + "apps.catalog.presentation", +] +forbidden_modules = [ + "apps.users.infrastructure", + "apps.customers.infrastructure", + "apps.catalog.infrastructure", +] allow_indirect_imports = true [[tool.importlinter.contracts]] name = "Modules use each other only through application interfaces" type = "forbidden" -source_modules = ["apps.customers"] +source_modules = ["apps.customers", "apps.catalog"] forbidden_modules = [ "apps.users.infrastructure", "apps.users.container", @@ -98,13 +120,19 @@ forbidden_modules = [ ignore_imports = [ # Integration tests may arrange data with another module's models. "apps.customers.tests.** -> apps.users.infrastructure.**", + "apps.catalog.tests.** -> apps.users.infrastructure.**", ] [[tool.importlinter.contracts]] -name = "users does not depend on customers" +name = "customers and catalog are independent" +type = "independence" +modules = ["apps.customers", "apps.catalog"] + +[[tool.importlinter.contracts]] +name = "users does not depend on customers or catalog" type = "forbidden" source_modules = ["apps.users"] -forbidden_modules = ["apps.customers"] +forbidden_modules = ["apps.customers", "apps.catalog"] [[tool.importlinter.contracts]] name = "shared layers" diff --git a/templates/base.html b/templates/base.html index a44e1be..1c99f48 100644 --- a/templates/base.html +++ b/templates/base.html @@ -56,8 +56,13 @@ {% if request.user|can:"customers.use" %}
  • {% translate "Customers" %}
  • {% endif %} - {% if request.user|can:"users.manage" %} + {% if request.user|can:"users.manage" or request.user|can:"catalog.manage" %} + {% endif %} + {% if request.user|can:"catalog.manage" %} +
  • {% translate "Base data" %}
  • + {% endif %} + {% if request.user|can:"users.manage" %}
  • {% translate "Users" %}
  • {% endif %} diff --git a/tests/browser/test_catalog.py b/tests/browser/test_catalog.py new file mode 100644 index 0000000..9f89dea --- /dev/null +++ b/tests/browser/test_catalog.py @@ -0,0 +1,87 @@ +import re +from collections.abc import Callable +from typing import Any + +import pytest + +from tests.browser.conftest import ALL, assert_accessible, no_horizontal_scroll + + +@pytest.fixture +def seeded(transactional_db: Any) -> None: + """transactional_db flushes tables between tests, so rerun the seed migration's data.""" + from importlib import import_module + + from django.apps import apps + + import_module("apps.catalog.migrations.0002_seed").seed(apps, None) + from apps.catalog.infrastructure.orm import ServiceUnitModel + + ServiceUnitModel.objects.filter(name="Markkinointi").update(is_active=False) + + +@pytest.mark.parametrize("themed_page", ALL, indirect=True, ids=lambda p: f"{p[0]}-{p[1]}") +def test_catalog_page( + themed_page: Any, + live_server: Any, + admin_user: Any, + seeded: None, + login: Callable[[Any, str], None], +) -> None: + login(themed_page, admin_user.email) + themed_page.goto(f"{live_server.url}/catalog/") + assert_accessible(themed_page) + assert no_horizontal_scroll(themed_page) + + # The work type dialog (loaded with HTMX) is accessible too. + themed_page.get_by_role( + "link", name=re.compile(r"^Lisää työtehtävä\s*: Mediatuotanto$") + ).click() + themed_page.locator("#item-dialog[open] #id_name").wait_for() + themed_page.wait_for_timeout(300) + assert_accessible(themed_page) + + themed_page.goto(f"{live_server.url}/catalog/service-units/new/") + assert_accessible(themed_page) + assert no_horizontal_scroll(themed_page) + + +def test_reorder_and_rename_with_keyboard( + page: Any, live_server: Any, admin_user: Any, seeded: None, login: Callable[[Any, str], None] +) -> None: + from apps.catalog.infrastructure.orm import ServiceUnitModel + + media = ServiceUnitModel.objects.get(name="Mediatuotanto") + login(page, admin_user.email) + page.goto(f"{live_server.url}/catalog/") + + page.get_by_role("button", name=re.compile(r"^Siirrä alas\s*: Mediatuotanto$")).focus() + page.keyboard.press("Enter") + page.wait_for_function( + "document.getElementById('live-region').textContent.includes('siirretty alas')" + ) + assert page.evaluate("document.activeElement.id") == f"move-unit-{media.pk}-down" + headings = page.locator("#catalog-tree h2").all_inner_texts() + assert headings[0].startswith("Markkinointi") + assert headings[1].startswith("Mediatuotanto") + + # Rename in the dialog; focus returns to the row's name. + page.get_by_role("link", name=re.compile(r"^Muokkaa\s*: Mediatuotanto$")).focus() + page.keyboard.press("Enter") + name = page.locator("#item-dialog[open] #id_name") + name.wait_for() + name.fill("Mediatuotannot") + page.keyboard.press("Enter") + page.wait_for_function( + "document.getElementById('live-region').textContent.includes('tallennettu')" + ) + assert page.evaluate("document.activeElement.id") == f"name-unit-{media.pk}" + assert not page.evaluate("document.getElementById('item-dialog').open") + + page.get_by_role("button", name=re.compile(r"^Poista käytöstä\s*: Mediatuotannot$")).focus() + page.keyboard.press("Enter") + page.wait_for_function( + "document.getElementById('live-region').textContent.includes('poistettu käytöstä')" + ) + assert page.evaluate("document.activeElement.id") == f"toggle-unit-{media.pk}" + assert "Ei käytössä" in page.locator(f"#row-unit-{media.pk} h2").inner_text()