"""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), )