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,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)
|
||||
@@ -0,0 +1,6 @@
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class CustomerType(StrEnum):
|
||||
COMPANY = "company"
|
||||
CONSUMER = "consumer"
|
||||
@@ -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"
|
||||
@@ -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."""
|
||||
...
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user