import json from collections.abc import Callable from typing import Any from django import forms from django.contrib import messages from django.core.paginator import Paginator from django.http import Http404, HttpRequest, HttpResponse from django.shortcuts import redirect, render from django.template.loader import render_to_string from django.urls import reverse from django.utils.functional import cached_property from django.utils.translation import gettext as _ from django.utils.translation import gettext_noop from django.views import View from django.views.generic import FormView, TemplateView from apps.customers import container from apps.customers.application.dto import CustomerDetails from apps.customers.domain.enums import CustomerType from apps.customers.presentation.forms import ( BillingUnitForm, ContactForm, CustomerFilterForm, CustomerForm, ) from apps.customers.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, user_has def _details(request: HttpRequest, customer_id: int, *, full: bool = False) -> CustomerDetails: details = container.customer_queries().get_details( customer_id, include_full_personal_id=full and user_has(request.user, Permission.CUSTOMERS_PERSONAL_ID_VIEW), ) if details is None: raise Http404 return details class CustomerAccessMixin(PermissionRequiredMixin): permission = Permission.CUSTOMERS_USE class CustomerListView(CustomerAccessMixin, TemplateView): template_name = "customers/list.html" page_size = 25 def get_context_data(self, **kwargs: Any) -> dict[str, Any]: context = super().get_context_data(**kwargs) filters = CustomerFilterForm(self.request.GET or None) search, customer_type = "", None if filters.is_valid(): search = filters.cleaned_data["q"].strip() if filters.cleaned_data["type"]: customer_type = CustomerType(filters.cleaned_data["type"]) customers = container.customer_queries().list_customers(search=search, type=customer_type) page = Paginator(customers, self.page_size).get_page(self.request.GET.get("page")) query = self.request.GET.copy() query.pop("page", None) context.update(filters=filters, page=page, query=query.urlencode()) return context def get_template_names(self) -> list[str]: if getattr(self.request, "htmx", False): return ["customers/partials/customer_table.html"] return [self.template_name] class CustomerCreateView(CustomerAccessMixin, FormView): # type: ignore[type-arg] form_class = CustomerForm template_name = "customers/form.html" def form_valid(self, form: CustomerForm) -> HttpResponse: try: customer_id = container.register_customer().execute(form.to_dto()) except DomainError as error: form.add_domain_error(error, ERROR_MESSAGES) return self.form_invalid(form) messages.success(self.request, _("Customer created.")) return redirect("customers:detail", pk=customer_id) def form_invalid(self, form: CustomerForm) -> HttpResponse: return self.render_to_response(self.get_context_data(form=form), status=422) class CustomerUpdateView(CustomerAccessMixin, FormView): # type: ignore[type-arg] form_class = CustomerForm template_name = "customers/form.html" @cached_property def details(self) -> CustomerDetails: return _details(self.request, self.kwargs["pk"]) def get_initial(self) -> dict[str, Any]: return { "name": self.details.name, "type": self.details.type.value, "business_id": self.details.business_id or "", } def get_form_kwargs(self) -> dict[str, Any]: kwargs = super().get_form_kwargs() kwargs.update( stored_personal_id=self.details.personal_id_masked, can_manage_personal_id=user_has( self.request.user, Permission.CUSTOMERS_PERSONAL_ID_VIEW ), is_internal=self.details.is_internal, ) return kwargs def get_context_data(self, **kwargs: Any) -> dict[str, Any]: context = super().get_context_data(**kwargs) context["customer"] = self.details return context def form_valid(self, form: CustomerForm) -> HttpResponse: try: container.update_customer().execute( self.details.id, form.to_dto(), can_manage_personal_id=user_has( self.request.user, Permission.CUSTOMERS_PERSONAL_ID_VIEW ), ) except DomainError as error: form.add_domain_error(error, ERROR_MESSAGES) return self.form_invalid(form) messages.success(self.request, _("Changes saved.")) return redirect("customers:detail", pk=self.details.id) def form_invalid(self, form: CustomerForm) -> HttpResponse: return self.render_to_response(self.get_context_data(form=form), status=422) def _detail_context(request: HttpRequest, customer_id: int) -> dict[str, Any]: queries = container.customer_queries() return { "customer": _details(request, customer_id), "contacts": queries.contacts(customer_id), "billing_units": queries.billing_units(customer_id), "is_deletable": queries.is_deletable(customer_id), "can_view_personal_id": user_has(request.user, Permission.CUSTOMERS_PERSONAL_ID_VIEW), } class CustomerDetailView(CustomerAccessMixin, View): def get(self, request: HttpRequest, pk: int) -> HttpResponse: return render(request, "customers/detail.html", _detail_context(request, pk)) class PersonalIdRevealView(PermissionRequiredMixin, View): """Shows the full personal identity code (admin and management only).""" permission = Permission.CUSTOMERS_PERSONAL_ID_VIEW def get(self, request: HttpRequest, pk: int) -> HttpResponse: details = _details(request, pk, full=True) response = render(request, "customers/partials/personal_id.html", {"customer": details}) response["Cache-Control"] = "no-store" return response class CustomerDeleteView(CustomerAccessMixin, View): def post(self, request: HttpRequest, pk: int) -> HttpResponse: try: container.delete_customer().execute(pk) except DomainError as error: messages.error(request, str(ERROR_MESSAGES.get(error.code, ERROR_MESSAGES["*"]))) return redirect("customers:detail", pk=pk) messages.success(request, _("Customer deleted.")) return redirect("customers:list") # --- Contacts and billing units: forms load into a dialog with HTMX ----------------------------- class _ChildSection: """Configuration of one child section (contacts or billing units) on the customer page.""" def __init__( self, *, key: str, form_class: type[forms.Form], template: str, heading_id: str, saved: str, deleted: str, add: Callable[[], Any], update: Callable[[], Any], delete: Callable[[], Any], initial: Callable[[CustomerDetails, int | None], dict[str, Any]], ) -> None: self.key = key self.form_class = form_class self.template = template self.heading_id = heading_id self.saved = saved self.deleted = deleted self.add = add self.update = update self.delete = delete self.initial = initial def _contact_initial(customer: CustomerDetails, item_id: int | None) -> dict[str, Any]: if item_id is None: return {} for c in container.customer_queries().contacts(customer.id): if c.id == item_id: return { "name": c.name, "title": c.title, "phone": c.phone, "email": c.email, "note": c.note, } raise Http404 def _billing_unit_initial(customer: CustomerDetails, item_id: int | None) -> dict[str, Any]: if item_id is None: return {"name": customer.name} for u in container.customer_queries().billing_units(customer.id): if u.id == item_id: return { "name": u.name, "billing_address": u.billing_address, "e_invoice_address": u.e_invoice_address, "e_invoice_operator": u.e_invoice_operator, "reference": u.reference, } raise Http404 SECTIONS = { "contacts": _ChildSection( key="contacts", form_class=ContactForm, template="customers/partials/contacts.html", heading_id="contacts-heading", saved=gettext_noop("Contact saved."), deleted=gettext_noop("Contact deleted."), add=container.add_contact, update=container.update_contact, delete=container.delete_contact, initial=_contact_initial, ), "billing-units": _ChildSection( key="billing-units", form_class=BillingUnitForm, template="customers/partials/billing_units.html", heading_id="billing-units-heading", saved=gettext_noop("Billing unit saved."), deleted=gettext_noop("Billing unit deleted."), add=container.add_billing_unit, update=container.update_billing_unit, delete=container.delete_billing_unit, initial=_billing_unit_initial, ), } def _section_response( request: HttpRequest, section: _ChildSection, customer_id: int, message: str ) -> HttpResponse: """Re-render the section in place, close the dialog, announce and move focus.""" context = _detail_context(request, customer_id) response = render(request, section.template, context) # Deletability may have changed: refresh the header actions out of band. response.content += render_to_string( "customers/partials/actions.html", {**context, "oob": True}, request=request ).encode() response["HX-Retarget"] = f"#{section.key}-section" response["HX-Reswap"] = "outerHTML" response["HX-Trigger-After-Settle"] = json.dumps( {"itemSaved": {"message": _(message), "focus": f"#{section.heading_id}"}} ) return response class ChildFormView(CustomerAccessMixin, View): """GET: form (dialog body for HTMX, full page otherwise). POST: save.""" def setup(self, request: HttpRequest, *args: Any, **kwargs: Any) -> None: super().setup(request, *args, **kwargs) section = SECTIONS.get(kwargs["section"]) if section is None: raise Http404 self.section = section self.item_id: int | None = kwargs.get("item_id") def _render( self, request: HttpRequest, customer: CustomerDetails, form: forms.Form, status: int = 200 ) -> HttpResponse: context = { "customer": customer, "form": form, "section": self.section.key, "item_id": self.item_id, } template = ( "customers/partials/child_form.html" if getattr(request, "htmx", False) else "customers/child_form_page.html" ) return render(request, template, context, status=status) def get(self, request: HttpRequest, pk: int, **kwargs: Any) -> HttpResponse: customer = _details(request, pk) form = self.section.form_class(initial=self.section.initial(customer, self.item_id)) return self._render(request, customer, form) def post(self, request: HttpRequest, pk: int, **kwargs: Any) -> HttpResponse: customer = _details(request, pk) form: Any = self.section.form_class(request.POST) if form.is_valid(): try: if self.item_id is None: self.section.add().execute(pk, form.to_dto()) else: self.section.update().execute(pk, self.item_id, form.to_dto()) except DomainError as error: form.add_domain_error(error, ERROR_MESSAGES) else: if getattr(request, "htmx", False): return _section_response(request, self.section, pk, self.section.saved) messages.success(request, _(self.section.saved)) return redirect( reverse("customers:detail", kwargs={"pk": pk}) + f"#{self.section.key}-section" ) return self._render(request, customer, form, status=422) class ChildDeleteView(CustomerAccessMixin, View): def post(self, request: HttpRequest, pk: int, section: str, item_id: int) -> HttpResponse: child = SECTIONS.get(section) if child is None: raise Http404 message = child.deleted try: child.delete().execute(pk, item_id) except DomainError as error: message = str(ERROR_MESSAGES.get(error.code, ERROR_MESSAGES["*"])) if getattr(request, "htmx", False): return _section_response(request, child, pk, message) messages.info(request, _(message)) return redirect("customers:detail", pk=pk)