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