Vaihe 1/2: asiakkaat, yhteyshenkilöt ja laskutusyksiköt

- customers-moduuli Clean Architecture -kerroksin: asiakas (yritys/kuluttaja),
  Y-tunnuksen tarkiste ja yksilöllisyys, yhteyshenkilöt, laskutusyksiköt
  (verkkolaskuosoite vaatii välittäjätunnuksen)
- henkilötunnus salattuna (Fernet) ja HMAC-tiiviste päällekkäisyyksiin;
  pääkäyttäjä ja johto näkevät ja poistavat, muut näkevät peitettynä
- sisäinen asiakas data-migraatiolla, ei poistettavissa
- yleinen poistonesto käänteisten relaatioiden perusteella (tulevat
  PROTECT-viiteavaimet estävät poiston automaattisesti)
- asiakkaan sivu: lisäys ja muokkaus dialogissa HTMX:llä, fokuksen hallinta
  ja ruudunlukijailmoitukset; HTMX näyttää nyt 422-validointivirheet
- testit: domain, application, integraatio ja selaintestit (axe);
  yhteiset fixturet apps/conftest.py:hin, FakeUnitOfWork shared-moduuliin
- import-linter: moduulien riippumattomuussäännöt
- dokumentit päivitetty

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-29 13:47:09 +02:00
co-authored by Claude Opus 5.5
parent e7b2745916
commit a81c073d6a
68 changed files with 3470 additions and 144 deletions
+113
View File
@@ -0,0 +1,113 @@
from typing import Any
from django import forms
from django.utils.translation import gettext_lazy as _
from apps.customers.application.dto import BillingUnitData, ContactData, CustomerDetailsData
from apps.customers.domain.enums import CustomerType
from apps.customers.presentation.labels import TYPE_CHOICES
from apps.shared.presentation.forms import DaisyFormMixin
class CustomerForm(DaisyFormMixin, forms.Form):
name = forms.CharField(label=_("Name"), max_length=200)
type = forms.ChoiceField(
label=_("Type"), choices=TYPE_CHOICES, initial=CustomerType.COMPANY.value
)
business_id = forms.CharField(
label=_("Business ID"), max_length=20, required=False, help_text=_("For example 1234567-1")
)
personal_identity_code = forms.CharField(
label=_("Personal identity code"),
max_length=20,
required=False,
# The stored code is never sent back to the browser.
widget=forms.TextInput(attrs={"autocomplete": "off", "spellcheck": "false"}),
help_text=_("Needed only for invoicing a consumer."),
)
remove_personal_id = forms.BooleanField(
label=_("Remove personal identity code"), required=False
)
def __init__(
self,
*args: Any,
stored_personal_id: str | None = None,
can_manage_personal_id: bool = False,
is_internal: bool = False,
**kwargs: Any,
) -> None:
super().__init__(*args, **kwargs)
self.fields["type"].widget.attrs["x-model"] = "type"
if stored_personal_id:
self.fields["personal_identity_code"].help_text = _(
"Stored: %(masked)s. Leave empty to keep it."
) % {"masked": stored_personal_id}
if not (stored_personal_id and can_manage_personal_id):
del self.fields["remove_personal_id"]
if is_internal:
self.fields["type"].disabled = True
self.fields["type"].help_text = _("The internal customer is always a company.")
def to_dto(self) -> CustomerDetailsData:
data = self.cleaned_data
customer_type = CustomerType(data["type"])
is_company = customer_type is CustomerType.COMPANY
return CustomerDetailsData(
name=data["name"],
type=customer_type,
business_id=data["business_id"] if is_company else "",
personal_identity_code="" if is_company else data["personal_identity_code"],
remove_personal_id=bool(data.get("remove_personal_id")) and not is_company,
)
class ContactForm(DaisyFormMixin, forms.Form):
name = forms.CharField(label=_("Name"), max_length=150)
title = forms.CharField(label=_("Title or role"), max_length=150, required=False)
phone = forms.CharField(
label=_("Phone"),
max_length=50,
required=False,
widget=forms.TextInput(attrs={"type": "tel"}),
)
email = forms.EmailField(label=_("Email"), required=False)
note = forms.CharField(
label=_("Note"), required=False, widget=forms.Textarea(attrs={"rows": 3})
)
def to_dto(self) -> ContactData:
return ContactData(**self.cleaned_data)
class BillingUnitForm(DaisyFormMixin, forms.Form):
name = forms.CharField(label=_("Name"), max_length=200)
billing_address = forms.CharField(
label=_("Billing address"),
required=False,
widget=forms.Textarea(attrs={"rows": 3}),
help_text=_("Postal address or billing email address."),
)
e_invoice_address = forms.CharField(
label=_("E-invoice address"),
max_length=40,
required=False,
help_text=_("12–35 letters or digits."),
)
e_invoice_operator = forms.CharField(
label=_("Operator ID"),
max_length=35,
required=False,
help_text=_("Required when an e-invoice address is given."),
)
reference = forms.CharField(label=_("Reference"), max_length=100, required=False)
def to_dto(self) -> BillingUnitData:
return BillingUnitData(**self.cleaned_data)
class CustomerFilterForm(DaisyFormMixin, forms.Form):
q = forms.CharField(label=_("Search"), required=False, help_text=_("Name or business ID"))
type = forms.ChoiceField(
label=_("Type"), required=False, choices=[("", _("All types")), *TYPE_CHOICES]
)
+40
View File
@@ -0,0 +1,40 @@
from django.utils.translation import gettext_lazy as _
from apps.customers.domain.enums import CustomerType
TYPE_LABELS = {
CustomerType.COMPANY: _("Company"),
CustomerType.CONSUMER: _("Consumer"),
}
TYPE_CHOICES = [(t.value, label) for t, label in TYPE_LABELS.items()]
ERROR_MESSAGES = {
"invalid_customer_name": _("Enter a name (at most 200 characters)."),
"invalid_business_id": _("Enter a valid business ID, for example 1234567-1."),
"invalid_personal_id": _("Enter a valid personal identity code."),
"consumer_cannot_have_business_id": _("A consumer cannot have a business ID."),
"company_cannot_have_personal_id": _("A company cannot have a personal identity code."),
"internal_customer_must_be_company": _("The internal customer is always a company."),
"business_id_taken": _("Another customer already has this business ID."),
"personal_id_taken": _("Another customer already has this personal identity code."),
"personal_id_removal_not_allowed": _(
"You are not allowed to remove the personal identity code."
),
"customer_not_found": _("The customer was not found."),
"customer_in_use": _(
"The customer cannot be deleted because it has contacts, billing units, jobs, "
"sales or invoices."
),
"internal_customer_cannot_be_deleted": _("The internal customer cannot be deleted."),
"invalid_contact_name": _("Enter a name (at most 150 characters)."),
"invalid_billing_unit_name": _("Enter a name (at most 200 characters)."),
"invalid_e_invoice_address": _("The e-invoice address must be 12–35 letters or digits."),
"e_invoice_operator_required": _("Enter the operator ID when an e-invoice address is given."),
"invalid_email": _("Enter a valid email address."),
"contact_not_found": _("The contact was not found."),
"billing_unit_not_found": _("The billing unit was not found."),
"contact_in_use": _("The contact cannot be deleted because a job refers to it."),
"billing_unit_in_use": _("The billing unit cannot be deleted because a job refers to it."),
"*": _("The change could not be saved."),
}
@@ -0,0 +1,15 @@
{% extends "base.html" %}
{% block title %}{{ customer.name }}{% endblock %}
{% block content %}
<nav class="breadcrumbs text-sm" aria-label="{% translate 'Breadcrumbs' %}">
<ul>
<li><a href="{% url 'customers:list' %}">{% translate "Customers" %}</a></li>
<li><a href="{% url 'customers:detail' customer.id %}">{{ customer.name }}</a></li>
</ul>
</nav>
<div class="card bg-base-100 shadow-sm max-w-2xl">
<div class="card-body">
{% include "customers/partials/child_form.html" %}
</div>
</div>
{% endblock %}
@@ -0,0 +1,42 @@
{% extends "base.html" %}{% load customers_tags %}
{% block title %}{{ customer.name }}{% endblock %}
{% block content %}
<nav class="breadcrumbs text-sm" aria-label="{% translate 'Breadcrumbs' %}">
<ul><li><a href="{% url 'customers:list' %}">{% translate "Customers" %}</a></li><li aria-current="page">{{ customer.name }}</li></ul>
</nav>
<div class="flex flex-wrap items-center justify-between gap-2 mb-4">
<h1 class="text-2xl font-bold">
{{ customer.name }}
{% if customer.is_internal %}<span class="badge badge-info badge-soft align-middle">{% translate "Internal" %}</span>{% endif %}
</h1>
{% include "customers/partials/actions.html" %}
</div>
<section class="card bg-base-100 shadow-sm mb-4" aria-labelledby="basic-heading">
<div class="card-body">
<h2 id="basic-heading" class="card-title">{% translate "Basic information" %}</h2>
<dl class="grid gap-x-6 gap-y-2 sm:grid-cols-[max-content_1fr]">
<dt class="font-semibold">{% translate "Type" %}</dt><dd>{{ customer.type|customer_type_label }}</dd>
{% if customer.type == "company" %}
<dt class="font-semibold">{% translate "Business ID" %}</dt><dd>{{ customer.business_id|default:"–" }}</dd>
{% else %}
<dt class="font-semibold">{% translate "Personal identity code" %}</dt>
<dd id="personal-id">{% include "customers/partials/personal_id.html" %}</dd>
{% endif %}
</dl>
{% if customer.is_internal %}
<p class="text-sm mt-2">{% translate "Internal work (administration, sales, training) is recorded on the jobs of the internal customer. It cannot be deleted." %}</p>
{% endif %}
</div>
</section>
<div class="grid gap-4 lg:grid-cols-2">
{% include "customers/partials/contacts.html" %}
{% include "customers/partials/billing_units.html" %}
</div>
<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,34 @@
{% extends "base.html" %}
{% block title %}{% if customer %}{% translate "Edit customer" %}{% else %}{% translate "New customer" %}{% endif %}{% endblock %}
{% block content %}
<nav class="breadcrumbs text-sm" aria-label="{% translate 'Breadcrumbs' %}">
<ul>
<li><a href="{% url 'customers:list' %}">{% translate "Customers" %}</a></li>
{% if customer %}<li><a href="{% url 'customers:detail' customer.id %}">{{ customer.name }}</a></li>{% endif %}
<li aria-current="page">{% if customer %}{% translate "Edit" %}{% else %}{% translate "New customer" %}{% endif %}</li>
</ul>
</nav>
<h1 class="text-2xl font-bold mb-4">{% if customer %}{% translate "Edit customer" %}{% else %}{% translate "New customer" %}{% endif %}</h1>
<form method="post" novalidate class="card bg-base-100 shadow-sm max-w-2xl"
x-data="{ type: '{{ form.type.value|default:'company'|escapejs }}' }">
{% csrf_token %}
<div class="card-body">
{% include "components/non_field_errors.html" %}
{{ form.name.as_field_group }}
{{ form.type.as_field_group }}
<div x-show="type === 'company'" x-cloak>
{{ form.business_id.as_field_group }}
</div>
<div x-show="type === 'consumer'" x-cloak>
{{ form.personal_identity_code.as_field_group }}
{% if form.remove_personal_id %}{{ form.remove_personal_id.as_field_group }}{% endif %}
<p class="text-sm mt-2">{% translate "The personal identity code is specially protected data. It is stored encrypted and used only for invoicing." %}</p>
</div>
<div class="card-actions justify-end mt-4">
<a href="{% if customer %}{% url 'customers:detail' customer.id %}{% else %}{% url 'customers:list' %}{% endif %}" class="btn">{% translate "Cancel" %}</a>
<button type="submit" class="btn btn-primary">{% translate "Save" %}</button>
</div>
</div>
</form>
{% endblock %}
@@ -0,0 +1,23 @@
{% extends "base.html" %}
{% block title %}{% translate "Customers" %}{% endblock %}
{% block content %}
<div class="flex flex-wrap items-center justify-between gap-2 mb-4">
<h1 class="text-2xl font-bold">{% translate "Customers" %}</h1>
<a href="{% url 'customers:create' %}" class="btn btn-primary">{% translate "New customer" %}</a>
</div>
<form method="get" role="search" aria-label="{% translate 'Filter customers' %}"
class="card bg-base-100 shadow-sm mb-4"
hx-get="{% url 'customers:list' %}" hx-target="#customer-table" hx-push-url="true"
hx-trigger="input changed delay:300ms from:input[name='q'], change from:select, submit">
<div class="card-body grid gap-2 sm:grid-cols-2 py-4">
{{ filters.q.as_field_group }}
{{ filters.type.as_field_group }}
<noscript><button type="submit" class="btn">{% translate "Filter" %}</button></noscript>
</div>
</form>
<div id="customer-table">
{% include "customers/partials/customer_table.html" %}
</div>
{% endblock %}
@@ -0,0 +1,13 @@
<div id="customer-actions" class="flex gap-2"{% if oob %} hx-swap-oob="true"{% endif %}>
<a href="{% url 'customers:edit' customer.id %}" class="btn">{% translate "Edit" %}</a>
{% if is_deletable %}
<button type="button" class="btn btn-error btn-outline" onclick="document.getElementById('confirm-delete-customer').showModal()">{% translate "Delete customer" %}</button>
{% endif %}
{% if is_deletable %}
{% url 'customers:delete' customer.id as delete_url %}
{% translate "Delete the customer?" as dialog_title %}
{% translate "The customer is deleted permanently." as dialog_body %}
{% translate "Delete" as dialog_confirm %}
{% include "components/confirm_dialog.html" with id="confirm-delete-customer" title=dialog_title body=dialog_body action_url=delete_url confirm_label=dialog_confirm %}
{% endif %}
</div>
@@ -0,0 +1,46 @@
<section id="billing-units-section" class="card bg-base-100 shadow-sm" aria-labelledby="billing-units-heading">
<div class="card-body">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 id="billing-units-heading" class="card-title" tabindex="-1">{% translate "Billing units" %}</h2>
<a href="{% url 'customers:child_create' customer.id 'billing-units' %}" class="btn btn-sm"
hx-get="{% url 'customers:child_create' customer.id 'billing-units' %}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">{% translate "Add billing unit" %}</a>
</div>
<p class="text-sm">{% translate "Each billing unit is invoiced separately." %}</p>
{% if billing_units %}
<ul class="divide-y divide-base-300">
{% for u in billing_units %}{% with id_str=u.id|stringformat:"s" %}
<li class="py-3 flex flex-wrap justify-between gap-2">
<div>
<p class="font-semibold">{{ u.name }}</p>
{% if u.billing_address %}<p class="whitespace-pre-line">{{ u.billing_address }}</p>{% endif %}
{% if u.e_invoice_address %}
<p>{% translate "E-invoice" %}: {{ u.e_invoice_address }} ({% translate "operator" %} {{ u.e_invoice_operator }})</p>
{% endif %}
{% if u.reference %}<p>{% translate "Reference" %}: {{ u.reference }}</p>{% endif %}
</div>
<div class="flex gap-1 items-start">
<a class="btn btn-sm btn-ghost" href="{% url 'customers:child_edit' customer.id 'billing-units' u.id %}"
hx-get="{% url 'customers:child_edit' customer.id 'billing-units' u.id %}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">
{% translate "Edit" %}<span class="sr-only">: {{ u.name }}</span></a>
{% if u.in_use %}
<span class="text-sm">{% translate "In use in a job" %}</span>
{% else %}
<button type="button" class="btn btn-sm btn-ghost" onclick="document.getElementById('confirm-delete-unit-{{ u.id }}').showModal()">
{% translate "Delete" %}<span class="sr-only">: {{ u.name }}</span></button>
{% url 'customers:child_delete' customer.id 'billing-units' u.id as delete_url %}
{% blocktranslate with name=u.name asvar dialog_title %}Delete billing unit {{ name }}?{% endblocktranslate %}
{% translate "The billing unit is deleted permanently." as dialog_body %}
{% translate "Delete" as dialog_confirm %}
{% with dialog_id="confirm-delete-unit-"|add:id_str %}{% include "components/confirm_dialog.html" with id=dialog_id title=dialog_title body=dialog_body action_url=delete_url confirm_label=dialog_confirm hx_target="#billing-units-section" %}{% endwith %}
{% endif %}
</div>
</li>
{% endwith %}{% endfor %}
</ul>
{% else %}
<p>{% translate "No billing units yet." %}</p>
{% endif %}
</div>
</section>
@@ -0,0 +1,21 @@
{% if item_id %}
{% url 'customers:child_edit' customer.id section item_id as action_url %}
{% else %}
{% url 'customers:child_create' customer.id section as action_url %}
{% endif %}
<h2 id="item-dialog-title" class="text-lg font-bold">
{% if section == "contacts" %}
{% if item_id %}{% translate "Edit contact" %}{% else %}{% translate "Add contact" %}{% endif %}
{% else %}
{% if item_id %}{% translate "Edit billing unit" %}{% else %}{% translate "Add billing unit" %}{% endif %}
{% endif %}
</h2>
<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,43 @@
<section id="contacts-section" class="card bg-base-100 shadow-sm" aria-labelledby="contacts-heading">
<div class="card-body">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 id="contacts-heading" class="card-title" tabindex="-1">{% translate "Contacts" %}</h2>
<a href="{% url 'customers:child_create' customer.id 'contacts' %}" class="btn btn-sm"
hx-get="{% url 'customers:child_create' customer.id 'contacts' %}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">{% translate "Add contact" %}</a>
</div>
{% if contacts %}
<ul class="divide-y divide-base-300">
{% for c in contacts %}{% with id_str=c.id|stringformat:"s" %}
<li class="py-3 flex flex-wrap justify-between gap-2">
<div>
<p class="font-semibold">{{ c.name }}{% if c.title %}, <span class="font-normal">{{ c.title }}</span>{% endif %}</p>
{% if c.phone %}<p><a class="link" href="tel:{{ c.phone }}">{{ c.phone }}</a></p>{% endif %}
{% if c.email %}<p><a class="link break-all" href="mailto:{{ c.email }}">{{ c.email }}</a></p>{% endif %}
{% if c.note %}<p class="text-sm whitespace-pre-line">{{ c.note }}</p>{% endif %}
</div>
<div class="flex gap-1 items-start">
<a class="btn btn-sm btn-ghost" href="{% url 'customers:child_edit' customer.id 'contacts' c.id %}"
hx-get="{% url 'customers:child_edit' customer.id 'contacts' c.id %}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">
{% translate "Edit" %}<span class="sr-only">: {{ c.name }}</span></a>
{% if c.in_use %}
<span class="text-sm">{% translate "In use in a job" %}</span>
{% else %}
<button type="button" class="btn btn-sm btn-ghost" onclick="document.getElementById('confirm-delete-contact-{{ c.id }}').showModal()">
{% translate "Delete" %}<span class="sr-only">: {{ c.name }}</span></button>
{% url 'customers:child_delete' customer.id 'contacts' c.id as delete_url %}
{% blocktranslate with name=c.name asvar dialog_title %}Delete contact {{ name }}?{% endblocktranslate %}
{% translate "The contact is deleted permanently." as dialog_body %}
{% translate "Delete" as dialog_confirm %}
{% with dialog_id="confirm-delete-contact-"|add:id_str %}{% include "components/confirm_dialog.html" with id=dialog_id title=dialog_title body=dialog_body action_url=delete_url confirm_label=dialog_confirm hx_target="#contacts-section" %}{% endwith %}
{% endif %}
</div>
</li>
{% endwith %}{% endfor %}
</ul>
{% else %}
<p>{% translate "No contacts yet." %}</p>
{% endif %}
</div>
</section>
@@ -0,0 +1,41 @@
{% load customers_tags %}
<p class="sr-only" role="status">{% blocktranslate count counter=page.paginator.count %}{{ counter }} customer found{% plural %}{{ counter }} customers found{% endblocktranslate %}</p>
<div class="overflow-x-auto card bg-base-100 shadow-sm">
<table class="table">
<caption class="sr-only">{% translate "Customers" %}</caption>
<thead>
<tr>
<th scope="col">{% translate "Name" %}</th>
<th scope="col">{% translate "Type" %}</th>
<th scope="col">{% translate "Business ID" %}</th>
</tr>
</thead>
<tbody>
{% for c in page.object_list %}
<tr>
<td>
<a class="link" href="{% url 'customers:detail' c.id %}">{{ c.name }}</a>
{% if c.is_internal %}<span class="badge badge-info badge-soft ml-1">{% translate "Internal" %}</span>{% endif %}
</td>
<td>{{ c.type|customer_type_label }}</td>
<td>{{ c.business_id|default:"–" }}</td>
</tr>
{% empty %}
<tr><td colspan="3">{% translate "No customers match the filters." %}</td></tr>
{% endfor %}
</tbody>
</table>
</div>
{% if page.paginator.num_pages > 1 %}
<nav aria-label="{% translate 'Pages' %}" class="join mt-4">
{% if page.has_previous %}
<a class="join-item btn" href="?{{ query }}{% if query %}&amp;{% endif %}page={{ page.previous_page_number }}"
hx-get="?{{ query }}{% if query %}&amp;{% endif %}page={{ page.previous_page_number }}" hx-target="#customer-table" hx-push-url="true">{% translate "Previous" %}</a>
{% endif %}
<span class="join-item btn btn-disabled" aria-current="page">{% blocktranslate with n=page.number total=page.paginator.num_pages %}Page {{ n }} / {{ total }}{% endblocktranslate %}</span>
{% if page.has_next %}
<a class="join-item btn" href="?{{ query }}{% if query %}&amp;{% endif %}page={{ page.next_page_number }}"
hx-get="?{{ query }}{% if query %}&amp;{% endif %}page={{ page.next_page_number }}" hx-target="#customer-table" hx-push-url="true">{% translate "Next" %}</a>
{% endif %}
</nav>
{% endif %}
@@ -0,0 +1,13 @@
{% if customer.personal_id_full %}
<span class="font-mono" tabindex="-1" data-autofocus>{{ customer.personal_id_full }}</span>
{% elif customer.personal_id_masked %}
<span class="font-mono">{{ customer.personal_id_masked }}</span>
{% if can_view_personal_id %}
<button type="button" class="btn btn-ghost btn-sm ml-2"
hx-get="{% url 'customers:personal_id' customer.id %}" hx-target="#personal-id">
{% translate "Show personal identity code" %}
</button>
{% endif %}
{% else %}
<span>{% translate "Not given" %}</span>
{% endif %}
@@ -0,0 +1,13 @@
from typing import Any
from django import template
from apps.customers.domain.enums import CustomerType
from apps.customers.presentation.labels import TYPE_LABELS
register = template.Library()
@register.filter
def customer_type_label(value: Any) -> str:
return str(TYPE_LABELS.get(CustomerType(value), value))
+25
View File
@@ -0,0 +1,25 @@
from django.urls import path
from apps.customers.presentation import views
app_name = "customers"
urlpatterns = [
path("", views.CustomerListView.as_view(), name="list"),
path("new/", views.CustomerCreateView.as_view(), name="create"),
path("<int:pk>/", views.CustomerDetailView.as_view(), name="detail"),
path("<int:pk>/edit/", views.CustomerUpdateView.as_view(), name="edit"),
path("<int:pk>/delete/", views.CustomerDeleteView.as_view(), name="delete"),
path("<int:pk>/personal-id/", views.PersonalIdRevealView.as_view(), name="personal_id"),
path("<int:pk>/<str:section>/new/", views.ChildFormView.as_view(), name="child_create"),
path(
"<int:pk>/<str:section>/<int:item_id>/edit/",
views.ChildFormView.as_view(),
name="child_edit",
),
path(
"<int:pk>/<str:section>/<int:item_id>/delete/",
views.ChildDeleteView.as_view(),
name="child_delete",
),
]
+353
View File
@@ -0,0 +1,353 @@
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)