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
@@ -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