Vaihe 1/3: pohjatiedot (palveluyksiköt, palvelut ja työtehtävät)

- Uusi catalog-moduuli: palveluyksikkö → (palvelu) → työtehtävä ilman hintoja.
- Pohjatiedot-sivu /catalog/ pääkäyttäjälle ja johdolle (oikeus catalog.manage):
  lisäys ja muokkaus dialogissa, Siirrä ylös / Siirrä alas, käytöstä poisto ja
  käyttöön otto. Fokus ja aria-live-ilmoitus jokaisen muutoksen jälkeen.
- Rivejä ei poisteta. Käytöstä poistetun yläkohdan alla olevat rivit säilyttävät
  oman tilansa, mutta eivät ole valittavissa. Nimi on yksilöllinen samalla
  tasolla kirjainkoosta riippumatta.
- Työtehtävän voi siirtää saman yksikön toiseen palveluun tai suoraan yksikön alle.
- Luvun 11.1 lista data-migraationa (0002_seed), jos taulut ovat tyhjiä.
- CatalogQueries: work_type_options, active_service_units ja get_work_type
  tehtäviä ja tuntikirjausta varten.
- Import-linter-sopimukset, suomennokset, yksikkö-, integraatio- ja selaintestit.
- Päivitetty CLAUDE.md ja määrittelyn kohta 16.3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-29 14:07:41 +02:00
co-authored by Claude Opus 5.5
parent a81c073d6a
commit 679bf57eb4
51 changed files with 2722 additions and 132 deletions
View File
+80
View File
@@ -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)
+27
View File
@@ -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)."""
...
+194
View File
@@ -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))
+7
View File
@@ -0,0 +1,7 @@
from django.apps import AppConfig
class CatalogConfig(AppConfig):
name = "apps.catalog"
label = "catalog"
default_auto_field = "django.db.models.BigAutoField"
+84
View File
@@ -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()
View File
+131
View File
@@ -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()
+47
View File
@@ -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"
+22
View File
@@ -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
+55
View File
@@ -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: ...
+25
View File
@@ -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
+64
View File
@@ -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
+111
View File
@@ -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
+156
View File
@@ -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)
+69
View File
@@ -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'),
),
]
+66
View File
@@ -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)]
View File
+4
View File
@@ -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"]
+53
View File
@@ -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")
)
+14
View File
@@ -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."),
}
@@ -0,0 +1,18 @@
{% extends "base.html" %}
{% block title %}{% translate "Base data" %}{% endblock %}
{% block content %}
<div class="flex flex-wrap items-center justify-between gap-2 mb-2">
<h1 class="text-2xl font-bold">{% translate "Base data" %}</h1>
{% url 'catalog:unit_create' as add_url %}
<a href="{{ add_url }}" class="btn btn-primary"
hx-get="{{ add_url }}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">{% translate "Add service unit" %}</a>
</div>
<p class="mb-4 max-w-3xl">{% 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." %}</p>
{% include "catalog/partials/tree.html" %}
<dialog id="item-dialog" class="modal" aria-labelledby="item-dialog-title">
<div class="modal-box" id="item-dialog-body"></div>
</dialog>
{% endblock %}
@@ -0,0 +1,12 @@
{% extends "base.html" %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<nav class="breadcrumbs text-sm" aria-label="{% translate 'Breadcrumbs' %}">
<ul><li><a href="{% url 'catalog:index' %}">{% translate "Base data" %}</a></li><li aria-current="page">{{ title }}</li></ul>
</nav>
<div class="card bg-base-100 shadow-sm max-w-2xl">
<div class="card-body">
{% include "catalog/partials/item_form.html" %}
</div>
</div>
{% endblock %}
@@ -0,0 +1,2 @@
{% if item.is_shared %} <span class="badge badge-info badge-soft">{% translate "Shared by all units" %}</span>{% endif %}
{% if not item.is_active %} <span class="badge badge-warning badge-soft gap-1"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path stroke-linecap="round" d="M5.6 5.6l12.8 12.8"/></svg>{% translate "Not in use" %}</span>{% endif %}
@@ -0,0 +1,35 @@
{# Row buttons. Include with kind (URL segment), prefix (DOM id prefix), item, first, last. #}
<div class="flex flex-wrap items-center gap-1">
{% url 'catalog:edit' kind item.id as edit_url %}
<a class="btn btn-sm btn-ghost" href="{{ edit_url }}"
hx-get="{{ edit_url }}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">
{% translate "Edit" %}<span class="sr-only">: {{ item.name }}</span></a>
{% url 'catalog:move' kind item.id 'up' as up_url %}
<form method="post" action="{{ up_url }}" hx-post="{{ up_url }}" hx-target="#catalog-tree" hx-swap="outerHTML">
{% csrf_token %}
<button type="submit" id="move-{{ prefix }}-{{ item.id }}-up" class="btn btn-sm btn-ghost btn-square" title="{% translate 'Move up' %}"{% if first %} disabled{% endif %}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M12 19V5m0 0l-6 6m6-6l6 6"/></svg>
<span class="sr-only">{% blocktranslate with name=item.name %}Move up: {{ name }}{% endblocktranslate %}</span>
</button>
</form>
{% url 'catalog:move' kind item.id 'down' as down_url %}
<form method="post" action="{{ down_url }}" hx-post="{{ down_url }}" hx-target="#catalog-tree" hx-swap="outerHTML">
{% csrf_token %}
<button type="submit" id="move-{{ prefix }}-{{ item.id }}-down" class="btn btn-sm btn-ghost btn-square" title="{% translate 'Move down' %}"{% if last %} disabled{% endif %}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M12 5v14m0 0l6-6m-6 6l-6-6"/></svg>
<span class="sr-only">{% blocktranslate with name=item.name %}Move down: {{ name }}{% endblocktranslate %}</span>
</button>
</form>
{% url 'catalog:toggle' kind item.id as toggle_url %}
<form method="post" action="{{ toggle_url }}" hx-post="{{ toggle_url }}" hx-target="#catalog-tree" hx-swap="outerHTML">
{% csrf_token %}
<input type="hidden" name="active" value="{% if item.is_active %}0{% else %}1{% endif %}">
<button type="submit" id="toggle-{{ prefix }}-{{ item.id }}" class="btn btn-sm btn-ghost">
{% if item.is_active %}{% translate "Take out of use" %}{% else %}{% translate "Take into use" %}{% endif %}<span class="sr-only">: {{ item.name }}</span>
</button>
</form>
</div>
@@ -0,0 +1,11 @@
<h2 id="item-dialog-title" class="text-lg font-bold">{{ title }}</h2>
{% if parent_name %}<p class="text-sm">{% translate "Service unit" %}: {{ parent_name }}</p>{% endif %}
<form method="post" action="{{ action_url }}" novalidate class="space-y-1 mt-2"
hx-post="{{ action_url }}" hx-target="#item-dialog-body">
{% csrf_token %}
{{ form }}
<div class="modal-action">
<button type="button" class="btn" onclick="this.closest('dialog') ? this.closest('dialog').close() : history.back()">{% translate "Cancel" %}</button>
<button type="submit" class="btn btn-primary">{% translate "Save" %}</button>
</div>
</form>
@@ -0,0 +1,52 @@
<div id="catalog-tree" class="space-y-4">
{% for unit in tree %}
<section id="row-unit-{{ unit.id }}" class="card bg-base-100 shadow-sm" aria-labelledby="name-unit-{{ unit.id }}">
<div class="card-body gap-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 id="name-unit-{{ unit.id }}" class="card-title flex-wrap" tabindex="-1">{{ unit.name }}{% include "catalog/partials/badges.html" with item=unit %}</h2>
{% include "catalog/partials/item_actions.html" with kind="service-units" prefix="unit" item=unit first=forloop.first last=forloop.last %}
</div>
{% if unit.services %}
<ul class="space-y-3" aria-label="{% blocktranslate with name=unit.name %}Services of {{ name }}{% endblocktranslate %}">
{% for service in unit.services %}
<li id="row-service-{{ service.id }}" class="border border-base-300 rounded-box p-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<h3 id="name-service-{{ service.id }}" class="font-semibold flex flex-wrap items-center gap-2" tabindex="-1">{{ service.name }}{% include "catalog/partials/badges.html" with item=service %}</h3>
{% include "catalog/partials/item_actions.html" with kind="services" prefix="service" item=service first=forloop.first last=forloop.last %}
</div>
{% if service.work_types %}
{% include "catalog/partials/work_types.html" with work_types=service.work_types %}
{% else %}
<p class="text-sm mt-2">{% translate "No work types yet." %}</p>
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% if unit.work_types %}
{% if unit.services %}<h3 class="font-semibold">{% translate "Directly under the service unit" %}</h3>{% endif %}
{% include "catalog/partials/work_types.html" with work_types=unit.work_types %}
{% elif not unit.services %}
<p>{% translate "No services or work types yet." %}</p>
{% endif %}
<div class="card-actions">
{% url 'catalog:child_create' unit.id 'services' as service_url %}
<a href="{{ service_url }}" class="btn btn-sm"
hx-get="{{ service_url }}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">
{% translate "Add service" %}<span class="sr-only">: {{ unit.name }}</span></a>
{% url 'catalog:child_create' unit.id 'work-types' as work_type_url %}
<a href="{{ work_type_url }}" class="btn btn-sm"
hx-get="{{ work_type_url }}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">
{% translate "Add work type" %}<span class="sr-only">: {{ unit.name }}</span></a>
</div>
</div>
</section>
{% empty %}
<p>{% translate "No service units yet." %}</p>
{% endfor %}
</div>
@@ -0,0 +1,8 @@
<ul class="divide-y divide-base-300 mt-1">
{% for wt in work_types %}
<li id="row-worktype-{{ wt.id }}" class="py-2 flex flex-wrap items-center justify-between gap-2">
<span id="name-worktype-{{ wt.id }}" class="flex flex-wrap items-center gap-2" tabindex="-1">{{ wt.name }}{% include "catalog/partials/badges.html" with item=wt %}</span>
{% include "catalog/partials/item_actions.html" with kind="work-types" prefix="worktype" item=wt first=forloop.first last=forloop.last %}
</li>
{% endfor %}
</ul>
+27
View File
@@ -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/<int:unit_id>/<str:kind>/new/",
views.ItemFormView.as_view(),
name="child_create",
),
path("<str:kind>/<int:item_id>/edit/", views.ItemFormView.as_view(), name="edit"),
path(
"<str:kind>/<int:item_id>/move/<str:direction>/",
views.MoveView.as_view(),
name="move",
),
path("<str:kind>/<int:item_id>/active/", views.ToggleActiveView.as_view(), name="toggle"),
]
+324
View File
@@ -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),
)
View File
@@ -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)
+62
View File
@@ -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
+90
View File
@@ -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))
@@ -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
+2
View File
@@ -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"
+1
View File
@@ -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}),
}