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
View File
+82
View File
@@ -0,0 +1,82 @@
from dataclasses import dataclass
from apps.customers.domain.enums import CustomerType
@dataclass(frozen=True, slots=True)
class CustomerDetailsData:
"""Customer form input.
``personal_identity_code``: empty keeps the stored code, a value replaces it.
``remove_personal_id``: remove the stored code (admin and management only).
"""
name: str
type: CustomerType
business_id: str = ""
personal_identity_code: str = ""
remove_personal_id: bool = False
@dataclass(frozen=True, slots=True)
class ContactData:
name: str
title: str = ""
phone: str = ""
email: str = ""
note: str = ""
@dataclass(frozen=True, slots=True)
class BillingUnitData:
name: str
billing_address: str = ""
e_invoice_address: str = ""
e_invoice_operator: str = ""
reference: str = ""
@dataclass(frozen=True, slots=True)
class CustomerSummary:
"""What other modules (jobs, sales) see of a customer."""
id: int
name: str
type: CustomerType
business_id: str | None
is_internal: bool
@dataclass(frozen=True, slots=True)
class CustomerDetails:
id: int
name: str
type: CustomerType
business_id: str | None
is_internal: bool
personal_id_masked: str | None
personal_id_full: str | None # only when explicitly requested by an authorized caller
@dataclass(frozen=True, slots=True)
class ContactView:
id: int
customer_id: int
name: str
title: str
phone: str
email: str
note: str
in_use: bool
@dataclass(frozen=True, slots=True)
class BillingUnitView:
id: int
customer_id: int
name: str
billing_address: str
e_invoice_address: str
e_invoice_operator: str
reference: str
in_use: bool
+38
View File
@@ -0,0 +1,38 @@
from collections.abc import Sequence
from typing import Protocol
from apps.customers.application.dto import (
BillingUnitView,
ContactView,
CustomerDetails,
CustomerSummary,
)
from apps.customers.domain.enums import CustomerType
class CustomerQueries(Protocol):
"""Public read interface of the customers module."""
def list_customers(
self, *, search: str = "", type: CustomerType | None = None
) -> Sequence[CustomerSummary]:
"""Search by name or business ID (never by personal identity code); internal first."""
...
def search(self, term: str, *, limit: int = 20) -> Sequence[CustomerSummary]:
"""Autocomplete for other modules (e.g. job intake)."""
...
def get_summary(self, customer_id: int) -> CustomerSummary | None: ...
def get_details(
self, customer_id: int, *, include_full_personal_id: bool = False
) -> CustomerDetails | None: ...
def contacts(self, customer_id: int) -> Sequence[ContactView]: ...
def billing_units(self, customer_id: int) -> Sequence[BillingUnitView]: ...
def is_deletable(self, customer_id: int) -> bool:
"""Not internal and nothing (contacts, billing units, jobs, sales …) refers to it."""
...
+213
View File
@@ -0,0 +1,213 @@
from apps.customers.application.dto import BillingUnitData, ContactData, CustomerDetailsData
from apps.customers.domain.entities import BillingUnit, Contact, Customer
from apps.customers.domain.exceptions import (
BillingUnitNotFound,
BusinessIdTaken,
CompanyCannotHavePersonalId,
ContactNotFound,
CustomerNotFound,
InternalCustomerCannotBeDeleted,
PersonalIdRemovalNotAllowed,
PersonalIdTaken,
)
from apps.customers.domain.repositories import (
BillingUnitRepository,
ContactRepository,
CustomerRepository,
)
from apps.customers.domain.value_objects import (
BusinessId,
CustomerName,
EInvoiceAddress,
PersonalIdentityCode,
)
from apps.shared.application.ports import UnitOfWork
from apps.shared.domain.value_objects import EmailAddress
def _business_id(value: str) -> BusinessId | None:
return BusinessId(value) if value.strip() else None
def _personal_id(value: str) -> PersonalIdentityCode | None:
return PersonalIdentityCode(value) if value.strip() else None
class RegisterCustomer:
def __init__(self, repo: CustomerRepository, uow: UnitOfWork) -> None:
self.repo = repo
self.uow = uow
def execute(self, data: CustomerDetailsData) -> int:
name = CustomerName(data.name)
business_id = _business_id(data.business_id)
pic = _personal_id(data.personal_identity_code)
customer = Customer.register(name=name, type=data.type, business_id=business_id)
if pic is not None and not customer.can_have_personal_id:
raise CompanyCannotHavePersonalId()
with self.uow:
if business_id is not None and self.repo.is_business_id_taken(business_id):
raise BusinessIdTaken()
if pic is not None and self.repo.is_personal_id_taken(pic):
raise PersonalIdTaken()
saved = self.repo.save(customer)
assert saved.id is not None
if pic is not None:
self.repo.set_personal_id(saved.id, pic)
return saved.id
class UpdateCustomer:
def __init__(self, repo: CustomerRepository, uow: UnitOfWork) -> None:
self.repo = repo
self.uow = uow
def execute(
self, customer_id: int, data: CustomerDetailsData, *, can_manage_personal_id: bool
) -> None:
name = CustomerName(data.name)
business_id = _business_id(data.business_id)
pic = _personal_id(data.personal_identity_code)
if data.remove_personal_id and not can_manage_personal_id:
raise PersonalIdRemovalNotAllowed()
with self.uow:
current = self.repo.get(customer_id)
if current is None:
raise CustomerNotFound()
updated = current.change_details(name=name, type=data.type, business_id=business_id)
if pic is not None and not updated.can_have_personal_id:
raise CompanyCannotHavePersonalId()
if business_id is not None and self.repo.is_business_id_taken(
business_id, exclude_id=customer_id
):
raise BusinessIdTaken()
if pic is not None and self.repo.is_personal_id_taken(pic, exclude_id=customer_id):
raise PersonalIdTaken()
if data.remove_personal_id and pic is None:
updated = updated.with_personal_id(False)
self.repo.save(updated)
if pic is not None:
self.repo.set_personal_id(customer_id, pic)
class DeleteCustomer:
def __init__(self, repo: CustomerRepository, uow: UnitOfWork) -> None:
self.repo = repo
self.uow = uow
def execute(self, customer_id: int) -> None:
with self.uow:
customer = self.repo.get(customer_id)
if customer is None:
raise CustomerNotFound()
if customer.is_internal:
raise InternalCustomerCannotBeDeleted()
self.repo.delete(customer_id)
def _contact(customer_id: int, contact_id: int | None, data: ContactData) -> Contact:
return Contact(
id=contact_id,
customer_id=customer_id,
name=data.name,
title=data.title.strip(),
phone=data.phone.strip(),
email=EmailAddress(data.email) if data.email.strip() else None,
note=data.note.strip(),
)
def _billing_unit(customer_id: int, unit_id: int | None, data: BillingUnitData) -> BillingUnit:
return BillingUnit(
id=unit_id,
customer_id=customer_id,
name=data.name,
billing_address=data.billing_address.strip(),
e_invoice_address=(
EInvoiceAddress(data.e_invoice_address) if data.e_invoice_address.strip() else None
),
e_invoice_operator=data.e_invoice_operator,
reference=data.reference.strip(),
)
class _ContactUseCase:
def __init__(
self, customers: CustomerRepository, contacts: ContactRepository, uow: UnitOfWork
) -> None:
self.customers = customers
self.contacts = contacts
self.uow = uow
def _owned(self, customer_id: int, contact_id: int) -> Contact:
contact = self.contacts.get(contact_id)
if contact is None or contact.customer_id != customer_id:
raise ContactNotFound()
return contact
class AddContact(_ContactUseCase):
def execute(self, customer_id: int, data: ContactData) -> int:
contact = _contact(customer_id, None, data)
with self.uow:
if self.customers.get(customer_id) is None:
raise CustomerNotFound()
saved = self.contacts.save(contact)
assert saved.id is not None
return saved.id
class UpdateContact(_ContactUseCase):
def execute(self, customer_id: int, contact_id: int, data: ContactData) -> None:
contact = _contact(customer_id, contact_id, data)
with self.uow:
self._owned(customer_id, contact_id)
self.contacts.save(contact)
class DeleteContact(_ContactUseCase):
def execute(self, customer_id: int, contact_id: int) -> None:
with self.uow:
self._owned(customer_id, contact_id)
self.contacts.delete(contact_id)
class _BillingUnitUseCase:
def __init__(
self, customers: CustomerRepository, units: BillingUnitRepository, uow: UnitOfWork
) -> None:
self.customers = customers
self.units = units
self.uow = uow
def _owned(self, customer_id: int, unit_id: int) -> BillingUnit:
unit = self.units.get(unit_id)
if unit is None or unit.customer_id != customer_id:
raise BillingUnitNotFound()
return unit
class AddBillingUnit(_BillingUnitUseCase):
def execute(self, customer_id: int, data: BillingUnitData) -> int:
unit = _billing_unit(customer_id, None, data)
with self.uow:
if self.customers.get(customer_id) is None:
raise CustomerNotFound()
saved = self.units.save(unit)
assert saved.id is not None
return saved.id
class UpdateBillingUnit(_BillingUnitUseCase):
def execute(self, customer_id: int, unit_id: int, data: BillingUnitData) -> None:
unit = _billing_unit(customer_id, unit_id, data)
with self.uow:
self._owned(customer_id, unit_id)
self.units.save(unit)
class DeleteBillingUnit(_BillingUnitUseCase):
def execute(self, customer_id: int, unit_id: int) -> None:
with self.uow:
self._owned(customer_id, unit_id)
self.units.delete(unit_id)
+11
View File
@@ -0,0 +1,11 @@
from django.apps import AppConfig
class CustomersConfig(AppConfig):
name = "apps.customers"
label = "customers"
default_auto_field = "django.db.models.BigAutoField"
def ready(self) -> None:
# Registers the system check for the encryption keys.
from apps.customers.infrastructure import vault # noqa: F401
+67
View File
@@ -0,0 +1,67 @@
"""Composition root of the customers module."""
from apps.customers.application.queries import CustomerQueries
from apps.customers.application.use_cases import (
AddBillingUnit,
AddContact,
DeleteBillingUnit,
DeleteContact,
DeleteCustomer,
RegisterCustomer,
UpdateBillingUnit,
UpdateContact,
UpdateCustomer,
)
from apps.customers.infrastructure.queries import DjangoCustomerQueries
from apps.customers.infrastructure.repositories import (
DjangoBillingUnitRepository,
DjangoContactRepository,
DjangoCustomerRepository,
)
from apps.shared.infrastructure.unit_of_work import DjangoUnitOfWork
def register_customer() -> RegisterCustomer:
return RegisterCustomer(DjangoCustomerRepository(), DjangoUnitOfWork())
def update_customer() -> UpdateCustomer:
return UpdateCustomer(DjangoCustomerRepository(), DjangoUnitOfWork())
def delete_customer() -> DeleteCustomer:
return DeleteCustomer(DjangoCustomerRepository(), DjangoUnitOfWork())
def add_contact() -> AddContact:
return AddContact(DjangoCustomerRepository(), DjangoContactRepository(), DjangoUnitOfWork())
def update_contact() -> UpdateContact:
return UpdateContact(DjangoCustomerRepository(), DjangoContactRepository(), DjangoUnitOfWork())
def delete_contact() -> DeleteContact:
return DeleteContact(DjangoCustomerRepository(), DjangoContactRepository(), DjangoUnitOfWork())
def add_billing_unit() -> AddBillingUnit:
return AddBillingUnit(
DjangoCustomerRepository(), DjangoBillingUnitRepository(), DjangoUnitOfWork()
)
def update_billing_unit() -> UpdateBillingUnit:
return UpdateBillingUnit(
DjangoCustomerRepository(), DjangoBillingUnitRepository(), DjangoUnitOfWork()
)
def delete_billing_unit() -> DeleteBillingUnit:
return DeleteBillingUnit(
DjangoCustomerRepository(), DjangoBillingUnitRepository(), DjangoUnitOfWork()
)
def customer_queries() -> CustomerQueries:
return DjangoCustomerQueries()
View File
+123
View File
@@ -0,0 +1,123 @@
from dataclasses import dataclass, replace
from typing import Self
from apps.customers.domain.enums import CustomerType
from apps.customers.domain.exceptions import (
ConsumerCannotHaveBusinessId,
EInvoiceOperatorRequired,
InternalCustomerMustBeCompany,
InvalidBillingUnitName,
InvalidContactName,
)
from apps.customers.domain.value_objects import BusinessId, CustomerName, EInvoiceAddress
from apps.shared.domain.value_objects import EmailAddress
@dataclass(frozen=True, slots=True)
class Customer:
"""Customer (specification 4).
Rules: a consumer has no business ID and a company has no personal identity code;
the internal customer is always a company. The personal identity code itself never
lives in the entity; ``has_personal_id`` tells whether one is stored.
"""
id: int | None
name: CustomerName
type: CustomerType
business_id: BusinessId | None
is_internal: bool = False
has_personal_id: bool = False
@classmethod
def register(
cls, *, name: CustomerName, type: CustomerType, business_id: BusinessId | None = None
) -> Self:
cls._check(type=type, business_id=business_id, is_internal=False)
return cls(id=None, name=name, type=type, business_id=business_id)
@classmethod
def reconstitute(
cls,
*,
id: int,
name: CustomerName,
type: CustomerType,
business_id: BusinessId | None,
is_internal: bool,
has_personal_id: bool,
) -> Self:
return cls(id, name, type, business_id, is_internal, has_personal_id)
def change_details(
self, *, name: CustomerName, type: CustomerType, business_id: BusinessId | None
) -> Self:
"""A company loses its personal identity code (the repository removes it)."""
self._check(type=type, business_id=business_id, is_internal=self.is_internal)
has_pic = self.has_personal_id and type is CustomerType.CONSUMER
return replace(self, name=name, type=type, business_id=business_id, has_personal_id=has_pic)
def with_id(self, id: int) -> Self:
return replace(self, id=id)
def with_personal_id(self, present: bool) -> Self:
return replace(self, has_personal_id=present)
@property
def can_have_personal_id(self) -> bool:
return self.type is CustomerType.CONSUMER
@staticmethod
def _check(*, type: CustomerType, business_id: BusinessId | None, is_internal: bool) -> None:
if is_internal and type is not CustomerType.COMPANY:
raise InternalCustomerMustBeCompany()
if type is CustomerType.CONSUMER and business_id is not None:
raise ConsumerCannotHaveBusinessId()
def _required_text(value: str, max_length: int, error: type[Exception]) -> str:
normalized = " ".join(value.split())
if not normalized or len(normalized) > max_length:
raise error()
return normalized
@dataclass(frozen=True, slots=True)
class Contact:
"""A customer's contact person."""
id: int | None
customer_id: int
name: str
title: str = ""
phone: str = ""
email: EmailAddress | None = None
note: str = ""
def __post_init__(self) -> None:
object.__setattr__(self, "name", _required_text(self.name, 150, InvalidContactName))
def with_id(self, id: int) -> Self:
return replace(self, id=id)
@dataclass(frozen=True, slots=True)
class BillingUnit:
"""Invoicing target of a customer; each unit gets its own invoices."""
id: int | None
customer_id: int
name: str
billing_address: str = ""
e_invoice_address: EInvoiceAddress | None = None
e_invoice_operator: str = ""
reference: str = ""
def __post_init__(self) -> None:
object.__setattr__(self, "name", _required_text(self.name, 200, InvalidBillingUnitName))
object.__setattr__(self, "e_invoice_operator", self.e_invoice_operator.strip())
if self.e_invoice_address is not None and not self.e_invoice_operator:
raise EInvoiceOperatorRequired()
def with_id(self, id: int) -> Self:
return replace(self, id=id)
+6
View File
@@ -0,0 +1,6 @@
from enum import StrEnum
class CustomerType(StrEnum):
COMPANY = "company"
CONSUMER = "consumer"
+98
View File
@@ -0,0 +1,98 @@
from apps.shared.domain.exceptions import DomainError
class InvalidCustomerName(DomainError):
code = "invalid_customer_name"
field = "name"
class InvalidBusinessId(DomainError):
code = "invalid_business_id"
field = "business_id"
class InvalidPersonalIdentityCode(DomainError):
code = "invalid_personal_id"
field = "personal_identity_code"
class ConsumerCannotHaveBusinessId(DomainError):
code = "consumer_cannot_have_business_id"
field = "business_id"
class CompanyCannotHavePersonalId(DomainError):
code = "company_cannot_have_personal_id"
field = "personal_identity_code"
class InternalCustomerMustBeCompany(DomainError):
code = "internal_customer_must_be_company"
field = "type"
class BusinessIdTaken(DomainError):
code = "business_id_taken"
field = "business_id"
class PersonalIdTaken(DomainError):
code = "personal_id_taken"
field = "personal_identity_code"
class PersonalIdRemovalNotAllowed(DomainError):
"""Only admin and management may remove a personal identity code."""
code = "personal_id_removal_not_allowed"
field = "remove_personal_id"
class CustomerNotFound(DomainError):
code = "customer_not_found"
class CustomerInUse(DomainError):
"""Something (contacts, billing units, jobs, sales, invoices) still refers to the customer."""
code = "customer_in_use"
class InternalCustomerCannotBeDeleted(DomainError):
code = "internal_customer_cannot_be_deleted"
class InvalidContactName(DomainError):
code = "invalid_contact_name"
field = "name"
class InvalidBillingUnitName(DomainError):
code = "invalid_billing_unit_name"
field = "name"
class InvalidEInvoiceAddress(DomainError):
code = "invalid_e_invoice_address"
field = "e_invoice_address"
class EInvoiceOperatorRequired(DomainError):
code = "e_invoice_operator_required"
field = "e_invoice_operator"
class ContactNotFound(DomainError):
code = "contact_not_found"
class BillingUnitNotFound(DomainError):
code = "billing_unit_not_found"
class ContactInUse(DomainError):
code = "contact_in_use"
class BillingUnitInUse(DomainError):
code = "billing_unit_in_use"
+49
View File
@@ -0,0 +1,49 @@
from typing import Protocol
from apps.customers.domain.entities import BillingUnit, Contact, Customer
from apps.customers.domain.value_objects import BusinessId, PersonalIdentityCode
class CustomerRepository(Protocol):
def get(self, customer_id: int) -> Customer | None: ...
def save(self, customer: Customer) -> Customer:
"""Insert or update. Removes the stored personal identity code when
``customer.has_personal_id`` is False."""
...
def set_personal_id(self, customer_id: int, code: PersonalIdentityCode) -> None:
"""Store the code encrypted, with its fingerprint for duplicate checks."""
...
def is_business_id_taken(
self, business_id: BusinessId, *, exclude_id: int | None = None
) -> bool: ...
def is_personal_id_taken(
self, code: PersonalIdentityCode, *, exclude_id: int | None = None
) -> bool: ...
def delete(self, customer_id: int) -> None:
"""Raises CustomerInUse if anything still refers to the customer."""
...
class ContactRepository(Protocol):
def get(self, contact_id: int) -> Contact | None: ...
def save(self, contact: Contact) -> Contact: ...
def delete(self, contact_id: int) -> None:
"""Raises ContactInUse if a job refers to the contact."""
...
class BillingUnitRepository(Protocol):
def get(self, billing_unit_id: int) -> BillingUnit | None: ...
def save(self, billing_unit: BillingUnit) -> BillingUnit: ...
def delete(self, billing_unit_id: int) -> None:
"""Raises BillingUnitInUse if a job or invoice refers to the unit."""
...
+122
View File
@@ -0,0 +1,122 @@
import re
from dataclasses import dataclass, field
from datetime import date
from apps.customers.domain.exceptions import (
InvalidBusinessId,
InvalidCustomerName,
InvalidEInvoiceAddress,
InvalidPersonalIdentityCode,
)
def _normalize_spaces(value: str) -> str:
return " ".join(value.split())
@dataclass(frozen=True, slots=True)
class CustomerName:
value: str
def __post_init__(self) -> None:
normalized = _normalize_spaces(self.value)
if not normalized or len(normalized) > 200:
raise InvalidCustomerName()
object.__setattr__(self, "value", normalized)
def __str__(self) -> str:
return self.value
_BUSINESS_ID_RE = re.compile(r"^(\d{6,7})-?(\d)$")
_BUSINESS_ID_WEIGHTS = (7, 9, 10, 5, 8, 4, 2)
@dataclass(frozen=True, slots=True)
class BusinessId:
"""Finnish business ID (Y-tunnus), stored as ``1234567-8``."""
value: str
def __post_init__(self) -> None:
match = _BUSINESS_ID_RE.match(self.value.strip())
if not match:
raise InvalidBusinessId()
body = match.group(1).zfill(7)
check = int(match.group(2))
remainder = sum(int(d) * w for d, w in zip(body, _BUSINESS_ID_WEIGHTS, strict=True)) % 11
if remainder == 1:
raise InvalidBusinessId()
expected = 0 if remainder == 0 else 11 - remainder
if check != expected:
raise InvalidBusinessId()
object.__setattr__(self, "value", f"{body}-{check}")
def __str__(self) -> str:
return self.value
_PIC_RE = re.compile(r"^(\d{2})(\d{2})(\d{2})([+\-A-FU-Y])(\d{3})([0-9A-Y])$")
_PIC_CHECK_CHARS = "0123456789ABCDEFHJKLMNPRSTUVWXY"
_CENTURY = {"+": 1800, "-": 1900, "U": 1900, "V": 1900, "W": 1900, "X": 1900, "Y": 1900}
_CENTURY.update({c: 2000 for c in "ABCDEF"})
@dataclass(frozen=True, slots=True)
class PersonalIdentityCode:
"""Finnish personal identity code (henkilötunnus).
Specially protected data (tietosuojalaki 29 §): ``repr`` never shows it; use ``masked``
for display and only pass ``value`` to the encryption vault.
"""
value: str = field(repr=False)
def __post_init__(self) -> None:
normalized = self.value.strip().upper()
match = _PIC_RE.match(normalized)
if not match:
raise InvalidPersonalIdentityCode()
day, month, year, sign, individual, check = match.groups()
try:
date(_CENTURY[sign] + int(year), int(month), int(day))
except ValueError:
raise InvalidPersonalIdentityCode() from None
if (
int(individual) < 2
or _PIC_CHECK_CHARS[int(day + month + year + individual) % 31] != check
):
raise InvalidPersonalIdentityCode()
object.__setattr__(self, "value", normalized)
@property
def masked(self) -> str:
return mask_personal_id(self.value)
def __str__(self) -> str:
return self.masked
def __repr__(self) -> str:
return f"PersonalIdentityCode({self.masked!r})"
def mask_personal_id(code: str) -> str:
"""``010190-123A`` → ``••••••-123A`` (birth date hidden)."""
return "••••••" + code[6:]
_E_INVOICE_RE = re.compile(r"^[A-Za-z0-9]{12,35}$")
@dataclass(frozen=True, slots=True)
class EInvoiceAddress:
value: str
def __post_init__(self) -> None:
normalized = "".join(self.value.split()).upper()
if not _E_INVOICE_RE.match(normalized):
raise InvalidEInvoiceAddress()
object.__setattr__(self, "value", normalized)
def __str__(self) -> str:
return self.value
+59
View File
@@ -0,0 +1,59 @@
from django.db import models
from apps.customers.domain.enums import CustomerType
from apps.shared.infrastructure.models import TimestampedModel
class CustomerModel(TimestampedModel):
name = models.CharField(max_length=200)
type = models.CharField(max_length=20, default=CustomerType.COMPANY.value)
business_id = models.CharField(max_length=9, null=True, blank=True, unique=True)
# Fernet ciphertext of the henkilötunnus; never stored in plain text.
# NULL (not "") means no code, matching the nullable unique hash below.
personal_identity_code = models.TextField(null=True, blank=True) # noqa: DJ001
# HMAC-SHA256 fingerprint for duplicate checks (the code itself is not searchable).
personal_identity_code_hash = models.CharField(
max_length=64, null=True, blank=True, unique=True
)
is_internal = models.BooleanField(default=False)
class Meta:
db_table = "customers"
ordering = ["name"]
def __str__(self) -> str:
return self.name
class ContactModel(TimestampedModel):
customer = models.ForeignKey(CustomerModel, on_delete=models.PROTECT, related_name="contacts")
name = models.CharField(max_length=150)
title = models.CharField(max_length=150, blank=True)
phone = models.CharField(max_length=50, blank=True)
email = models.EmailField(max_length=254, blank=True)
note = models.TextField(blank=True)
class Meta:
db_table = "customer_contacts"
ordering = ["name", "id"]
def __str__(self) -> str:
return self.name
class BillingUnitModel(TimestampedModel):
customer = models.ForeignKey(
CustomerModel, on_delete=models.PROTECT, related_name="billing_units"
)
name = models.CharField(max_length=200)
billing_address = models.TextField(blank=True)
e_invoice_address = models.CharField(max_length=35, blank=True)
e_invoice_operator = models.CharField(max_length=35, blank=True)
reference = models.CharField(max_length=100, blank=True)
class Meta:
db_table = "billing_units"
ordering = ["name", "id"]
def __str__(self) -> str:
return self.name
+99
View File
@@ -0,0 +1,99 @@
from collections.abc import Sequence
from django.db.models import Q
from apps.customers.application.dto import (
BillingUnitView,
ContactView,
CustomerDetails,
CustomerSummary,
)
from apps.customers.domain.enums import CustomerType
from apps.customers.domain.value_objects import mask_personal_id
from apps.customers.infrastructure import vault
from apps.customers.infrastructure.orm import BillingUnitModel, ContactModel, CustomerModel
from apps.customers.infrastructure.references import is_referenced
def _summary(model: CustomerModel) -> CustomerSummary:
return CustomerSummary(
id=model.pk,
name=model.name,
type=CustomerType(model.type),
business_id=model.business_id,
is_internal=model.is_internal,
)
class DjangoCustomerQueries:
def list_customers(
self, *, search: str = "", type: CustomerType | None = None
) -> Sequence[CustomerSummary]:
qs = CustomerModel.objects.order_by("-is_internal", "name", "pk")
if search:
qs = qs.filter(Q(name__icontains=search) | Q(business_id__icontains=search))
if type is not None:
qs = qs.filter(type=type.value)
return [_summary(m) for m in qs.only("id", "name", "type", "business_id", "is_internal")]
def search(self, term: str, *, limit: int = 20) -> Sequence[CustomerSummary]:
return list(self.list_customers(search=term.strip()))[:limit]
def get_summary(self, customer_id: int) -> CustomerSummary | None:
model = CustomerModel.objects.filter(pk=customer_id).first()
return _summary(model) if model else None
def get_details(
self, customer_id: int, *, include_full_personal_id: bool = False
) -> CustomerDetails | None:
model = CustomerModel.objects.filter(pk=customer_id).first()
if model is None:
return None
masked = full = None
if model.personal_identity_code:
plain = vault.decrypt(model.personal_identity_code)
masked = mask_personal_id(plain)
full = plain if include_full_personal_id else None
return CustomerDetails(
id=model.pk,
name=model.name,
type=CustomerType(model.type),
business_id=model.business_id,
is_internal=model.is_internal,
personal_id_masked=masked,
personal_id_full=full,
)
def contacts(self, customer_id: int) -> Sequence[ContactView]:
return [
ContactView(
id=m.pk,
customer_id=m.customer_id,
name=m.name,
title=m.title,
phone=m.phone,
email=m.email,
note=m.note,
in_use=is_referenced(m),
)
for m in ContactModel.objects.filter(customer_id=customer_id)
]
def billing_units(self, customer_id: int) -> Sequence[BillingUnitView]:
return [
BillingUnitView(
id=m.pk,
customer_id=m.customer_id,
name=m.name,
billing_address=m.billing_address,
e_invoice_address=m.e_invoice_address,
e_invoice_operator=m.e_invoice_operator,
reference=m.reference,
in_use=is_referenced(m),
)
for m in BillingUnitModel.objects.filter(customer_id=customer_id)
]
def is_deletable(self, customer_id: int) -> bool:
model = CustomerModel.objects.filter(pk=customer_id).first()
return model is not None and not model.is_internal and not is_referenced(model)
@@ -0,0 +1,22 @@
"""Generic "is this row referenced?" check.
Every model that later points at a customer, contact or billing unit with a ForeignKey
(jobs, sales, invoices …) is picked up automatically through ``_meta.related_objects``,
so this module never needs to know those modules.
"""
from django.db import models
def is_referenced(instance: models.Model, *, ignore: tuple[str, ...] = ()) -> bool:
for relation in instance._meta.related_objects:
if relation.get_accessor_name() in ignore:
continue
related_model = relation.related_model
if relation.many_to_many:
if getattr(instance, relation.get_accessor_name()).exists(): # type: ignore[arg-type]
return True
continue
if related_model._default_manager.filter(**{relation.field.name: instance}).exists():
return True
return False
@@ -0,0 +1,160 @@
from django.db.models import ProtectedError
from apps.customers.domain.entities import BillingUnit, Contact, Customer
from apps.customers.domain.enums import CustomerType
from apps.customers.domain.exceptions import BillingUnitInUse, ContactInUse, CustomerInUse
from apps.customers.domain.value_objects import (
BusinessId,
CustomerName,
EInvoiceAddress,
PersonalIdentityCode,
)
from apps.customers.infrastructure import vault
from apps.customers.infrastructure.orm import BillingUnitModel, ContactModel, CustomerModel
from apps.customers.infrastructure.references import is_referenced
from apps.shared.domain.value_objects import EmailAddress
def customer_entity(model: CustomerModel) -> Customer:
return Customer.reconstitute(
id=model.pk,
name=CustomerName(model.name),
type=CustomerType(model.type),
business_id=BusinessId(model.business_id) if model.business_id else None,
is_internal=model.is_internal,
has_personal_id=bool(model.personal_identity_code),
)
class DjangoCustomerRepository:
def get(self, customer_id: int) -> Customer | None:
model = CustomerModel.objects.filter(pk=customer_id).first()
return customer_entity(model) if model else None
def save(self, customer: Customer) -> Customer:
model = (
CustomerModel() if customer.id is None else CustomerModel.objects.get(pk=customer.id)
)
model.name = customer.name.value
model.type = customer.type.value
model.business_id = customer.business_id.value if customer.business_id else None
if not customer.has_personal_id:
model.personal_identity_code = None
model.personal_identity_code_hash = None
model.save()
return customer.with_id(model.pk)
def set_personal_id(self, customer_id: int, code: PersonalIdentityCode) -> None:
CustomerModel.objects.filter(pk=customer_id).update(
personal_identity_code=vault.encrypt(code.value),
personal_identity_code_hash=vault.fingerprint(code.value),
)
def is_business_id_taken(
self, business_id: BusinessId, *, exclude_id: int | None = None
) -> bool:
qs = CustomerModel.objects.filter(business_id=business_id.value)
if exclude_id is not None:
qs = qs.exclude(pk=exclude_id)
return qs.exists()
def is_personal_id_taken(
self, code: PersonalIdentityCode, *, exclude_id: int | None = None
) -> bool:
qs = CustomerModel.objects.filter(personal_identity_code_hash=vault.fingerprint(code.value))
if exclude_id is not None:
qs = qs.exclude(pk=exclude_id)
return qs.exists()
def delete(self, customer_id: int) -> None:
model = CustomerModel.objects.get(pk=customer_id)
if is_referenced(model):
raise CustomerInUse()
try:
model.delete()
except ProtectedError:
raise CustomerInUse() from None
def contact_entity(model: ContactModel) -> Contact:
return Contact(
id=model.pk,
customer_id=model.customer_id,
name=model.name,
title=model.title,
phone=model.phone,
email=EmailAddress(model.email) if model.email else None,
note=model.note,
)
class DjangoContactRepository:
def get(self, contact_id: int) -> Contact | None:
model = ContactModel.objects.filter(pk=contact_id).first()
return contact_entity(model) if model else None
def save(self, contact: Contact) -> Contact:
model = ContactModel() if contact.id is None else ContactModel.objects.get(pk=contact.id)
model.customer_id = contact.customer_id
model.name = contact.name
model.title = contact.title
model.phone = contact.phone
model.email = contact.email.value if contact.email else ""
model.note = contact.note
model.save()
return contact.with_id(model.pk)
def delete(self, contact_id: int) -> None:
model = ContactModel.objects.get(pk=contact_id)
if is_referenced(model):
raise ContactInUse()
try:
model.delete()
except ProtectedError:
raise ContactInUse() from None
def billing_unit_entity(model: BillingUnitModel) -> BillingUnit:
return BillingUnit(
id=model.pk,
customer_id=model.customer_id,
name=model.name,
billing_address=model.billing_address,
e_invoice_address=EInvoiceAddress(model.e_invoice_address)
if model.e_invoice_address
else None,
e_invoice_operator=model.e_invoice_operator,
reference=model.reference,
)
class DjangoBillingUnitRepository:
def get(self, billing_unit_id: int) -> BillingUnit | None:
model = BillingUnitModel.objects.filter(pk=billing_unit_id).first()
return billing_unit_entity(model) if model else None
def save(self, billing_unit: BillingUnit) -> BillingUnit:
model = (
BillingUnitModel()
if billing_unit.id is None
else BillingUnitModel.objects.get(pk=billing_unit.id)
)
model.customer_id = billing_unit.customer_id
model.name = billing_unit.name
model.billing_address = billing_unit.billing_address
model.e_invoice_address = (
billing_unit.e_invoice_address.value if billing_unit.e_invoice_address else ""
)
model.e_invoice_operator = billing_unit.e_invoice_operator
model.reference = billing_unit.reference
model.save()
return billing_unit.with_id(model.pk)
def delete(self, billing_unit_id: int) -> None:
model = BillingUnitModel.objects.get(pk=billing_unit_id)
if is_referenced(model):
raise BillingUnitInUse()
try:
model.delete()
except ProtectedError:
raise BillingUnitInUse() from None
+46
View File
@@ -0,0 +1,46 @@
"""Encryption of personal identity codes (spec 4: stored encrypted, HMAC for duplicates)."""
import hashlib
import hmac
from functools import cache
from cryptography.fernet import Fernet, MultiFernet
from django.conf import settings
from django.core.checks import Error, register
@cache
def _fernet() -> MultiFernet:
return MultiFernet([Fernet(key.encode()) for key in settings.FIELD_ENCRYPTION_KEYS])
def encrypt(code: str) -> str:
return _fernet().encrypt(code.encode()).decode()
def decrypt(token: str) -> str:
return _fernet().decrypt(token.encode()).decode()
def fingerprint(code: str) -> str:
key = settings.PERSONAL_ID_HASH_KEY.encode()
return hmac.new(key, code.strip().upper().encode(), hashlib.sha256).hexdigest()
@register()
def check_keys(app_configs: object, **kwargs: object) -> list[Error]:
errors = []
if not settings.FIELD_ENCRYPTION_KEYS:
errors.append(Error("FIELD_ENCRYPTION_KEYS is not set in .env", id="customers.E001"))
else:
try:
_fernet()
except ValueError:
errors.append(
Error("FIELD_ENCRYPTION_KEYS has an invalid Fernet key", id="customers.E002")
)
if len(settings.PERSONAL_ID_HASH_KEY) < 32:
errors.append(
Error("PERSONAL_ID_HASH_KEY must be at least 32 characters", id="customers.E003")
)
return errors
+69
View File
@@ -0,0 +1,69 @@
# Generated by Django 5.2.19 on 2026-11-29 11:39
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CustomerModel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=200)),
('type', models.CharField(default='company', max_length=20)),
('business_id', models.CharField(blank=True, max_length=9, null=True, unique=True)),
('personal_identity_code', models.TextField(blank=True, null=True)),
('personal_identity_code_hash', models.CharField(blank=True, max_length=64, null=True, unique=True)),
('is_internal', models.BooleanField(default=False)),
],
options={
'db_table': 'customers',
'ordering': ['name'],
},
),
migrations.CreateModel(
name='ContactModel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=150)),
('title', models.CharField(blank=True, max_length=150)),
('phone', models.CharField(blank=True, max_length=50)),
('email', models.EmailField(blank=True, max_length=254)),
('note', models.TextField(blank=True)),
('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='contacts', to='customers.customermodel')),
],
options={
'db_table': 'customer_contacts',
'ordering': ['name', 'id'],
},
),
migrations.CreateModel(
name='BillingUnitModel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=200)),
('billing_address', models.TextField(blank=True)),
('e_invoice_address', models.CharField(blank=True, max_length=35)),
('e_invoice_operator', models.CharField(blank=True, max_length=35)),
('reference', models.CharField(blank=True, max_length=100)),
('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='billing_units', to='customers.customermodel')),
],
options={
'db_table': 'billing_units',
'ordering': ['name', 'id'],
},
),
]
@@ -0,0 +1,15 @@
"""Creates the company's own internal customer (specification 4, K39)."""
from django.db import migrations
def create_internal_customer(apps, schema_editor):
customer = apps.get_model("customers", "CustomerModel")
if not customer.objects.filter(is_internal=True).exists():
customer.objects.create(name="Oma yritys (sisäinen)", type="company", is_internal=True)
class Migration(migrations.Migration):
dependencies = [("customers", "0001_initial")]
operations = [migrations.RunPython(create_internal_customer, migrations.RunPython.noop)]
+4
View File
@@ -0,0 +1,4 @@
# Django discovers the module's ORM models through this file.
from apps.customers.infrastructure.orm import BillingUnitModel, ContactModel, CustomerModel
__all__ = ["BillingUnitModel", "ContactModel", "CustomerModel"]
+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)
View File
@@ -0,0 +1,170 @@
from dataclasses import replace
import pytest
from apps.customers.application.dto import BillingUnitData, ContactData, CustomerDetailsData
from apps.customers.application.use_cases import (
AddBillingUnit,
AddContact,
DeleteContact,
DeleteCustomer,
RegisterCustomer,
UpdateBillingUnit,
UpdateContact,
UpdateCustomer,
)
from apps.customers.domain.enums import CustomerType
from apps.customers.domain.exceptions import (
BillingUnitNotFound,
BusinessIdTaken,
CompanyCannotHavePersonalId,
ContactNotFound,
CustomerInUse,
CustomerNotFound,
InternalCustomerCannotBeDeleted,
PersonalIdRemovalNotAllowed,
PersonalIdTaken,
)
from apps.customers.tests.fakes import (
InMemoryBillingUnitRepository,
InMemoryContactRepository,
InMemoryCustomerRepository,
)
from apps.shared.tests.fakes import FakeUnitOfWork
PIC = "131052-308T"
PIC2 = "010594Y9032"
@pytest.fixture
def repo() -> InMemoryCustomerRepository:
return InMemoryCustomerRepository()
def company(**kw: object) -> CustomerDetailsData:
return CustomerDetailsData(**{"name": "Oy Esimerkki Ab", "type": CustomerType.COMPANY, **kw}) # type: ignore[arg-type]
def consumer(**kw: object) -> CustomerDetailsData:
return CustomerDetailsData(**{"name": "Kalle Kuluttaja", "type": CustomerType.CONSUMER, **kw}) # type: ignore[arg-type]
def register(repo: InMemoryCustomerRepository, data: CustomerDetailsData) -> int:
return RegisterCustomer(repo, FakeUnitOfWork()).execute(data)
class TestRegister:
def test_business_id_is_unique(self, repo: InMemoryCustomerRepository) -> None:
register(repo, company(business_id="0112038-9"))
with pytest.raises(BusinessIdTaken):
register(repo, company(name="Toinen", business_id="01120389"))
def test_personal_id_is_stored_and_unique(self, repo: InMemoryCustomerRepository) -> None:
cid = register(repo, consumer(personal_identity_code=PIC))
assert repo.personal_ids[cid] == PIC
assert repo.get(cid).has_personal_id # type: ignore[union-attr]
with pytest.raises(PersonalIdTaken):
register(repo, consumer(name="Toinen", personal_identity_code=PIC.lower()))
def test_company_cannot_get_personal_id(self, repo: InMemoryCustomerRepository) -> None:
with pytest.raises(CompanyCannotHavePersonalId):
register(repo, company(personal_identity_code=PIC))
class TestUpdatePersonalId:
def update(
self,
repo: InMemoryCustomerRepository,
cid: int,
data: CustomerDetailsData,
manage: bool = False,
) -> None:
UpdateCustomer(repo, FakeUnitOfWork()).execute(cid, data, can_manage_personal_id=manage)
def test_empty_field_keeps_code(self, repo: InMemoryCustomerRepository) -> None:
cid = register(repo, consumer(personal_identity_code=PIC))
self.update(repo, cid, consumer(name="Kalle K."))
assert repo.personal_ids[cid] == PIC
def test_new_value_replaces_code(self, repo: InMemoryCustomerRepository) -> None:
cid = register(repo, consumer(personal_identity_code=PIC))
self.update(repo, cid, consumer(personal_identity_code=PIC2))
assert repo.personal_ids[cid] == PIC2
def test_only_admin_or_management_may_remove(self, repo: InMemoryCustomerRepository) -> None:
cid = register(repo, consumer(personal_identity_code=PIC))
with pytest.raises(PersonalIdRemovalNotAllowed):
self.update(repo, cid, consumer(remove_personal_id=True))
self.update(repo, cid, consumer(remove_personal_id=True), manage=True)
assert cid not in repo.personal_ids
def test_becoming_company_removes_code(self, repo: InMemoryCustomerRepository) -> None:
cid = register(repo, consumer(personal_identity_code=PIC))
self.update(repo, cid, company(name="Kalle Oy"))
assert cid not in repo.personal_ids
assert repo.get(cid).type is CustomerType.COMPANY # type: ignore[union-attr]
def test_unknown_customer(self, repo: InMemoryCustomerRepository) -> None:
with pytest.raises(CustomerNotFound):
self.update(repo, 99, company())
class TestDelete:
def test_internal_customer_cannot_be_deleted(self, repo: InMemoryCustomerRepository) -> None:
cid = register(repo, company())
repo.customers[cid] = replace(repo.customers[cid], is_internal=True)
with pytest.raises(InternalCustomerCannotBeDeleted):
DeleteCustomer(repo, FakeUnitOfWork()).execute(cid)
def test_referenced_customer_cannot_be_deleted(self, repo: InMemoryCustomerRepository) -> None:
cid = register(repo, company())
repo.references.add(cid)
with pytest.raises(CustomerInUse):
DeleteCustomer(repo, FakeUnitOfWork()).execute(cid)
def test_delete(self, repo: InMemoryCustomerRepository) -> None:
cid = register(repo, company())
DeleteCustomer(repo, FakeUnitOfWork()).execute(cid)
assert repo.get(cid) is None
class TestContactsAndBillingUnits:
def test_contact_lifecycle_and_ownership(self, repo: InMemoryCustomerRepository) -> None:
contacts = InMemoryContactRepository()
a = register(repo, company())
b = register(repo, company(name="Toinen"))
contact_id = AddContact(repo, contacts, FakeUnitOfWork()).execute(
a, ContactData(name="Maija", email="[email protected]")
)
assert contacts.items[contact_id].email.value == "[email protected]" # type: ignore[union-attr]
with pytest.raises(ContactNotFound): # belongs to customer a, not b
UpdateContact(repo, contacts, FakeUnitOfWork()).execute(
b, contact_id, ContactData(name="X")
)
with pytest.raises(ContactNotFound):
DeleteContact(repo, contacts, FakeUnitOfWork()).execute(b, contact_id)
DeleteContact(repo, contacts, FakeUnitOfWork()).execute(a, contact_id)
assert contacts.items == {}
def test_contact_for_unknown_customer(self, repo: InMemoryCustomerRepository) -> None:
with pytest.raises(CustomerNotFound):
AddContact(repo, InMemoryContactRepository(), FakeUnitOfWork()).execute(
5, ContactData(name="Maija")
)
def test_billing_unit(self, repo: InMemoryCustomerRepository) -> None:
units = InMemoryBillingUnitRepository()
a = register(repo, company())
unit_id = AddBillingUnit(repo, units, FakeUnitOfWork()).execute(
a,
BillingUnitData(
name="Pääkonttori",
e_invoice_address="0037 0112 0389",
e_invoice_operator="003721291126",
),
)
assert units.items[unit_id].e_invoice_address.value == "003701120389" # type: ignore[union-attr]
with pytest.raises(BillingUnitNotFound):
UpdateBillingUnit(repo, units, FakeUnitOfWork()).execute(
a + 1, unit_id, BillingUnitData(name="X")
)
@@ -0,0 +1,153 @@
import pytest
from apps.customers.domain.entities import BillingUnit, Contact, Customer
from apps.customers.domain.enums import CustomerType
from apps.customers.domain.exceptions import (
ConsumerCannotHaveBusinessId,
EInvoiceOperatorRequired,
InternalCustomerMustBeCompany,
InvalidBusinessId,
InvalidContactName,
InvalidCustomerName,
InvalidEInvoiceAddress,
InvalidPersonalIdentityCode,
)
from apps.customers.domain.value_objects import (
BusinessId,
CustomerName,
EInvoiceAddress,
PersonalIdentityCode,
)
class TestBusinessId:
@pytest.mark.parametrize(
("value", "expected"),
[
("0112038-9", "0112038-9"), # Nokia
("01120389", "0112038-9"),
("112038-9", "0112038-9"), # leading zero missing
(" 1572860-0 ", "1572860-0"), # remainder 0 → check digit 0
],
)
def test_valid(self, value: str, expected: str) -> None:
assert BusinessId(value).value == expected
@pytest.mark.parametrize("value", ["0112038-8", "1234567", "abcdefg-1", "", "12345678-9"])
def test_invalid(self, value: str) -> None:
with pytest.raises(InvalidBusinessId):
BusinessId(value)
def test_remainder_one_is_never_valid(self) -> None:
weights = (7, 9, 10, 5, 8, 4, 2)
body = next(
f"{n:07d}"
for n in range(1, 10_000)
if sum(int(d) * w for d, w in zip(f"{n:07d}", weights, strict=True)) % 11 == 1
)
for check in range(10):
with pytest.raises(InvalidBusinessId):
BusinessId(f"{body}-{check}")
class TestPersonalIdentityCode:
@pytest.mark.parametrize(
"value", ["131052-308T", "131052-308t", "010594Y9032", "010594Y9021", "020300A123N"]
)
def test_valid(self, value: str) -> None:
assert PersonalIdentityCode(value).value == value.upper()
@pytest.mark.parametrize(
"value",
[
"131052-308X", # wrong check character
"310252-308T", # 31 February
"131052Z308T", # unknown century sign
"131052-001T", # individual number below 002
"13105-308T",
"",
],
)
def test_invalid(self, value: str) -> None:
with pytest.raises(InvalidPersonalIdentityCode):
PersonalIdentityCode(value)
def test_masked_and_repr_hide_birth_date(self) -> None:
code = PersonalIdentityCode("131052-308T")
assert code.masked == "••••••-308T"
assert "131052" not in repr(code)
assert "131052" not in str(code)
class TestOtherValueObjects:
def test_customer_name(self) -> None:
assert CustomerName(" Oy Esimerkki Ab ").value == "Oy Esimerkki Ab"
with pytest.raises(InvalidCustomerName):
CustomerName(" ")
def test_e_invoice_address(self) -> None:
assert EInvoiceAddress("0037 1234 5678").value == "003712345678"
for bad in ["12345678901", "x" * 36, "FI12-3456-7890"]:
with pytest.raises(InvalidEInvoiceAddress):
EInvoiceAddress(bad)
class TestCustomer:
def test_consumer_cannot_have_business_id(self) -> None:
with pytest.raises(ConsumerCannotHaveBusinessId):
Customer.register(
name=CustomerName("Kalle"),
type=CustomerType.CONSUMER,
business_id=BusinessId("0112038-9"),
)
def test_becoming_company_drops_personal_id(self) -> None:
consumer = Customer.reconstitute(
id=1,
name=CustomerName("Kalle"),
type=CustomerType.CONSUMER,
business_id=None,
is_internal=False,
has_personal_id=True,
)
company = consumer.change_details(
name=CustomerName("Kalle Oy"), type=CustomerType.COMPANY, business_id=None
)
assert not company.has_personal_id
def test_internal_customer_stays_company(self) -> None:
internal = Customer.reconstitute(
id=1,
name=CustomerName("Oma yritys"),
type=CustomerType.COMPANY,
business_id=None,
is_internal=True,
has_personal_id=False,
)
with pytest.raises(InternalCustomerMustBeCompany):
internal.change_details(
name=CustomerName("Oma"), type=CustomerType.CONSUMER, business_id=None
)
class TestChildren:
def test_contact_requires_name(self) -> None:
with pytest.raises(InvalidContactName):
Contact(id=None, customer_id=1, name=" ")
def test_e_invoice_needs_operator(self) -> None:
with pytest.raises(EInvoiceOperatorRequired):
BillingUnit(
id=None,
customer_id=1,
name="Laskutus",
e_invoice_address=EInvoiceAddress("003712345678"),
)
unit = BillingUnit(
id=None,
customer_id=1,
name="Laskutus",
e_invoice_address=EInvoiceAddress("003712345678"),
e_invoice_operator=" 003721291126 ",
)
assert unit.e_invoice_operator == "003721291126"
+89
View File
@@ -0,0 +1,89 @@
"""In-memory test doubles for the customers application layer (no database)."""
from dataclasses import replace
from apps.customers.domain.entities import BillingUnit, Contact, Customer
from apps.customers.domain.exceptions import CustomerInUse
from apps.customers.domain.value_objects import BusinessId, PersonalIdentityCode
class InMemoryCustomerRepository:
def __init__(self) -> None:
self.customers: dict[int, Customer] = {}
self.personal_ids: dict[int, str] = {}
self.references: set[int] = set() # customer ids that something refers to
self._next = 1
def get(self, customer_id: int) -> Customer | None:
return self.customers.get(customer_id)
def save(self, customer: Customer) -> Customer:
if customer.id is None:
customer = customer.with_id(self._next)
self._next += 1
assert customer.id is not None
if not customer.has_personal_id:
self.personal_ids.pop(customer.id, None)
self.customers[customer.id] = customer
return customer
def set_personal_id(self, customer_id: int, code: PersonalIdentityCode) -> None:
self.personal_ids[customer_id] = code.value
self.customers[customer_id] = replace(self.customers[customer_id], has_personal_id=True)
def is_business_id_taken(
self, business_id: BusinessId, *, exclude_id: int | None = None
) -> bool:
return any(
c.business_id == business_id and c.id != exclude_id for c in self.customers.values()
)
def is_personal_id_taken(
self, code: PersonalIdentityCode, *, exclude_id: int | None = None
) -> bool:
return any(v == code.value and k != exclude_id for k, v in self.personal_ids.items())
def delete(self, customer_id: int) -> None:
if customer_id in self.references:
raise CustomerInUse()
del self.customers[customer_id]
class InMemoryContactRepository:
def __init__(self) -> None:
self.items: dict[int, Contact] = {}
self._next = 1
def get(self, contact_id: int) -> Contact | None:
return self.items.get(contact_id)
def save(self, contact: Contact) -> Contact:
if contact.id is None:
contact = contact.with_id(self._next)
self._next += 1
assert contact.id is not None
self.items[contact.id] = contact
return contact
def delete(self, contact_id: int) -> None:
del self.items[contact_id]
class InMemoryBillingUnitRepository:
def __init__(self) -> None:
self.items: dict[int, BillingUnit] = {}
self._next = 1
def get(self, billing_unit_id: int) -> BillingUnit | None:
return self.items.get(billing_unit_id)
def save(self, billing_unit: BillingUnit) -> BillingUnit:
if billing_unit.id is None:
billing_unit = billing_unit.with_id(self._next)
self._next += 1
assert billing_unit.id is not None
self.items[billing_unit.id] = billing_unit
return billing_unit
def delete(self, billing_unit_id: int) -> None:
del self.items[billing_unit_id]
@@ -0,0 +1,223 @@
from collections.abc import Callable
from datetime import date
from typing import Any
import pytest
from django.test import Client
from apps.customers.infrastructure import vault
from apps.customers.infrastructure.orm import BillingUnitModel, ContactModel, CustomerModel
from apps.customers.infrastructure.queries import DjangoCustomerQueries
from apps.users.infrastructure.orm import User
pytestmark = pytest.mark.django_db
PIC = "131052-308T"
HX = {"HX-Request": "true"}
@pytest.fixture
def employee_client(client: Client, make_user: Callable[..., User]) -> Client:
client.force_login(make_user(role="employee"))
return client
@pytest.fixture
def management_client(make_user: Callable[..., User]) -> Client:
c = Client()
c.force_login(make_user(role="management"))
return c
def create(client: Client, **data: str) -> Any:
return client.post("/customers/new/", {"name": "Oy Esimerkki Ab", "type": "company", **data})
class TestInternalCustomer:
def test_migration_created_internal_customer(self) -> None:
internal = CustomerModel.objects.get(is_internal=True)
assert internal.name == "Oma yritys (sisäinen)"
assert internal.type == "company"
assert not DjangoCustomerQueries().is_deletable(internal.pk)
def test_internal_customer_cannot_be_deleted(self, employee_client: Client) -> None:
internal = CustomerModel.objects.get(is_internal=True)
employee_client.post(f"/customers/{internal.pk}/delete/")
assert CustomerModel.objects.filter(pk=internal.pk).exists()
class TestPermissions:
def test_subcontractor_gets_403(self, client: Client, make_user: Callable[..., User]) -> None:
client.force_login(make_user(role="subcontractor"))
assert client.get("/customers/").status_code == 403
assert client.get("/customers/new/").status_code == 403
def test_intern_can_use_customers(self, client: Client, make_user: Callable[..., User]) -> None:
boss = make_user()
client.force_login(
make_user(role="intern", supervisor=boss, employment_ends_on=date(2099, 1, 1))
)
assert client.get("/customers/").status_code == 200
class TestPersonalIdentityCode:
def test_stored_encrypted_with_fingerprint(self, employee_client: Client) -> None:
response = create(
employee_client, name="Kalle", type="consumer", personal_identity_code=PIC
)
assert response.status_code == 302
row = CustomerModel.objects.get(name="Kalle")
assert row.personal_identity_code and PIC not in row.personal_identity_code
assert vault.decrypt(row.personal_identity_code) == PIC
assert row.personal_identity_code_hash == vault.fingerprint(PIC)
def test_duplicate_is_rejected(self, employee_client: Client) -> None:
create(employee_client, name="Kalle", type="consumer", personal_identity_code=PIC)
response = create(
employee_client, name="Kalle 2", type="consumer", personal_identity_code=PIC
)
assert response.status_code == 422
assert "Henkilötunnus on jo toisella asiakkaalla." in response.content.decode()
def test_employee_sees_masked_only(self, employee_client: Client) -> None:
create(employee_client, name="Kalle", type="consumer", personal_identity_code=PIC)
pk = CustomerModel.objects.get(name="Kalle").pk
html = employee_client.get(f"/customers/{pk}/").content.decode()
assert "••••••-308T" in html
assert "131052" not in html
assert "Näytä henkilötunnus" not in html
assert employee_client.get(f"/customers/{pk}/personal-id/").status_code == 403
def test_management_can_reveal(
self, employee_client: Client, management_client: Client
) -> None:
create(employee_client, name="Kalle", type="consumer", personal_identity_code=PIC)
pk = CustomerModel.objects.get(name="Kalle").pk
response = management_client.get(f"/customers/{pk}/personal-id/", headers=HX)
assert PIC in response.content.decode()
assert response["Cache-Control"] == "no-store"
def test_form_never_shows_stored_code(self, management_client: Client) -> None:
create(management_client, name="Kalle", type="consumer", personal_identity_code=PIC)
pk = CustomerModel.objects.get(name="Kalle").pk
html = management_client.get(f"/customers/{pk}/edit/").content.decode()
assert "131052" not in html
assert "••••••-308T" in html
assert 'name="remove_personal_id"' in html
def test_employee_has_no_remove_option(self, employee_client: Client) -> None:
create(employee_client, name="Kalle", type="consumer", personal_identity_code=PIC)
pk = CustomerModel.objects.get(name="Kalle").pk
assert (
'name="remove_personal_id"'
not in employee_client.get(f"/customers/{pk}/edit/").content.decode()
)
def test_management_removes_code(self, management_client: Client) -> None:
create(management_client, name="Kalle", type="consumer", personal_identity_code=PIC)
pk = CustomerModel.objects.get(name="Kalle").pk
management_client.post(
f"/customers/{pk}/edit/",
{"name": "Kalle", "type": "consumer", "remove_personal_id": "on"},
)
row = CustomerModel.objects.get(pk=pk)
assert row.personal_identity_code is None
assert row.personal_identity_code_hash is None
def test_list_search_does_not_match_code(self, employee_client: Client) -> None:
create(employee_client, name="Kalle", type="consumer", personal_identity_code=PIC)
html = employee_client.get("/customers/?q=131052", headers=HX).content.decode()
assert "Kalle" not in html
class TestCreateAndList:
def test_create_company_redirects_to_customer_page(self, employee_client: Client) -> None:
response = create(employee_client, business_id="01120389")
pk = CustomerModel.objects.get(name="Oy Esimerkki Ab").pk
assert response["Location"] == f"/customers/{pk}/"
assert CustomerModel.objects.get(pk=pk).business_id == "0112038-9"
def test_invalid_business_id(self, employee_client: Client) -> None:
response = create(employee_client, business_id="0112038-8")
assert response.status_code == 422
assert "Anna kelvollinen Y-tunnus" in response.content.decode()
def test_search_by_business_id_and_internal_first(self, employee_client: Client) -> None:
create(employee_client, business_id="0112038-9")
html = employee_client.get("/customers/?q=0112038", headers=HX).content.decode()
assert "Oy Esimerkki Ab" in html
names = [c.name for c in DjangoCustomerQueries().list_customers()]
assert names[0] == "Oma yritys (sisäinen)"
class TestContactsAndBillingUnits:
def test_add_contact_via_htmx_updates_section(self, employee_client: Client) -> None:
create(employee_client)
pk = CustomerModel.objects.get(name="Oy Esimerkki Ab").pk
form = employee_client.get(f"/customers/{pk}/contacts/new/", headers=HX).content.decode()
assert "<html" not in form
response = employee_client.post(
f"/customers/{pk}/contacts/new/",
{"name": "Maija", "email": "[email protected]"},
headers=HX,
)
assert response["HX-Retarget"] == "#contacts-section"
assert "itemSaved" in response["HX-Trigger-After-Settle"]
html = response.content.decode()
assert "Maija" in html
assert 'id="customer-actions" class="flex gap-2" hx-swap-oob="true"' in html
def test_invalid_contact_returns_form_with_422(self, employee_client: Client) -> None:
create(employee_client)
pk = CustomerModel.objects.get(name="Oy Esimerkki Ab").pk
response = employee_client.post(f"/customers/{pk}/contacts/new/", {"name": ""}, headers=HX)
assert response.status_code == 422
assert 'aria-invalid="true"' in response.content.decode()
def test_billing_unit_defaults_to_customer_name(self, employee_client: Client) -> None:
create(employee_client)
pk = CustomerModel.objects.get(name="Oy Esimerkki Ab").pk
html = employee_client.get(
f"/customers/{pk}/billing-units/new/", headers=HX
).content.decode()
assert 'value="Oy Esimerkki Ab"' in html
def test_e_invoice_requires_operator(self, employee_client: Client) -> None:
create(employee_client)
pk = CustomerModel.objects.get(name="Oy Esimerkki Ab").pk
response = employee_client.post(
f"/customers/{pk}/billing-units/new/",
{"name": "Lasku", "e_invoice_address": "003701120389"},
headers=HX,
)
assert response.status_code == 422
assert "Anna välittäjätunnus" in response.content.decode()
def test_cannot_edit_other_customers_contact(self, employee_client: Client) -> None:
create(employee_client)
create(employee_client, name="Toinen Oy")
a = CustomerModel.objects.get(name="Oy Esimerkki Ab")
b = CustomerModel.objects.get(name="Toinen Oy")
contact = ContactModel.objects.create(customer=a, name="Maija")
response = employee_client.post(f"/customers/{b.pk}/contacts/{contact.pk}/delete/")
assert ContactModel.objects.filter(pk=contact.pk).exists()
assert response.status_code == 302
class TestDeleteCustomer:
def test_delete_blocked_while_children_exist(self, employee_client: Client) -> None:
create(employee_client)
customer = CustomerModel.objects.get(name="Oy Esimerkki Ab")
unit = BillingUnitModel.objects.create(customer=customer, name="Lasku")
html = employee_client.get(f"/customers/{customer.pk}/").content.decode()
assert "Poista asiakas" not in html
employee_client.post(f"/customers/{customer.pk}/delete/")
assert CustomerModel.objects.filter(pk=customer.pk).exists()
unit.delete()
assert (
"Poista asiakas" in employee_client.get(f"/customers/{customer.pk}/").content.decode()
)
response = employee_client.post(f"/customers/{customer.pk}/delete/")
assert response["Location"] == "/customers/"
assert not CustomerModel.objects.filter(pk=customer.pk).exists()