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:
@@ -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")
|
||||
)
|
||||
@@ -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>
|
||||
@@ -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"),
|
||||
]
|
||||
@@ -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),
|
||||
)
|
||||
Reference in New Issue
Block a user