From a81c073d6afc121294b8cc0bd024f9e869665c54 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Sun, 29 Nov 2026 13:47:09 +0200 Subject: [PATCH] =?UTF-8?q?Vaihe=201/2:=20asiakkaat,=20yhteyshenkil=C3=B6t?= =?UTF-8?q?=20ja=20laskutusyksik=C3=B6t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .env.example | 6 + CLAUDE.md | 17 +- README.md | 7 +- apps/{users/tests => }/conftest.py | 0 apps/customers/__init__.py | 0 apps/customers/application/__init__.py | 0 apps/customers/application/dto.py | 82 +++ apps/customers/application/queries.py | 38 ++ apps/customers/application/use_cases.py | 213 +++++++ apps/customers/apps.py | 11 + apps/customers/container.py | 67 ++ apps/customers/domain/__init__.py | 0 apps/customers/domain/entities.py | 123 ++++ apps/customers/domain/enums.py | 6 + apps/customers/domain/exceptions.py | 98 +++ apps/customers/domain/repositories.py | 49 ++ apps/customers/domain/value_objects.py | 122 ++++ apps/customers/infrastructure/__init__.py | 0 apps/customers/infrastructure/orm.py | 59 ++ apps/customers/infrastructure/queries.py | 99 +++ apps/customers/infrastructure/references.py | 22 + apps/customers/infrastructure/repositories.py | 160 +++++ apps/customers/infrastructure/vault.py | 46 ++ apps/customers/migrations/0001_initial.py | 69 +++ .../migrations/0002_internal_customer.py | 15 + apps/customers/migrations/__init__.py | 0 apps/customers/models.py | 4 + apps/customers/presentation/__init__.py | 0 apps/customers/presentation/forms.py | 113 ++++ apps/customers/presentation/labels.py | 40 ++ .../templates/customers/child_form_page.html | 15 + .../templates/customers/detail.html | 42 ++ .../templates/customers/form.html | 34 + .../templates/customers/list.html | 23 + .../templates/customers/partials/actions.html | 13 + .../customers/partials/billing_units.html | 46 ++ .../customers/partials/child_form.html | 21 + .../customers/partials/contacts.html | 43 ++ .../customers/partials/customer_table.html | 41 ++ .../customers/partials/personal_id.html | 13 + .../presentation/templatetags/__init__.py | 0 .../templatetags/customers_tags.py | 13 + apps/customers/presentation/urls.py | 25 + apps/customers/presentation/views.py | 353 +++++++++++ apps/customers/tests/__init__.py | 0 apps/customers/tests/application/__init__.py | 0 .../tests/application/test_use_cases.py | 170 +++++ apps/customers/tests/domain/__init__.py | 0 .../tests/domain/test_value_objects.py | 153 +++++ apps/customers/tests/fakes.py | 89 +++ apps/customers/tests/integration/__init__.py | 0 .../tests/integration/test_customers.py | 223 +++++++ apps/shared/tests/fakes.py | 15 + apps/users/domain/enums.py | 2 + apps/users/domain/permissions.py | 1 + apps/users/tests/fakes.py | 13 +- apps/users/tests/integration/test_auth.py | 2 +- config/settings.py | 9 + config/urls.py | 1 + docs/architecture.md | 1 + locale/fi/LC_MESSAGES/django.po | 583 +++++++++++++++--- pyproject.toml | 38 +- requirements.txt | 1 + static/src/app.js | 28 +- templates/base.html | 3 + tests/browser/conftest.py | 28 + tests/browser/test_accessibility.py | 29 +- tests/browser/test_customers.py | 77 +++ 68 files changed, 3470 insertions(+), 144 deletions(-) rename apps/{users/tests => }/conftest.py (100%) create mode 100644 apps/customers/__init__.py create mode 100644 apps/customers/application/__init__.py create mode 100644 apps/customers/application/dto.py create mode 100644 apps/customers/application/queries.py create mode 100644 apps/customers/application/use_cases.py create mode 100644 apps/customers/apps.py create mode 100644 apps/customers/container.py create mode 100644 apps/customers/domain/__init__.py create mode 100644 apps/customers/domain/entities.py create mode 100644 apps/customers/domain/enums.py create mode 100644 apps/customers/domain/exceptions.py create mode 100644 apps/customers/domain/repositories.py create mode 100644 apps/customers/domain/value_objects.py create mode 100644 apps/customers/infrastructure/__init__.py create mode 100644 apps/customers/infrastructure/orm.py create mode 100644 apps/customers/infrastructure/queries.py create mode 100644 apps/customers/infrastructure/references.py create mode 100644 apps/customers/infrastructure/repositories.py create mode 100644 apps/customers/infrastructure/vault.py create mode 100644 apps/customers/migrations/0001_initial.py create mode 100644 apps/customers/migrations/0002_internal_customer.py create mode 100644 apps/customers/migrations/__init__.py create mode 100644 apps/customers/models.py create mode 100644 apps/customers/presentation/__init__.py create mode 100644 apps/customers/presentation/forms.py create mode 100644 apps/customers/presentation/labels.py create mode 100644 apps/customers/presentation/templates/customers/child_form_page.html create mode 100644 apps/customers/presentation/templates/customers/detail.html create mode 100644 apps/customers/presentation/templates/customers/form.html create mode 100644 apps/customers/presentation/templates/customers/list.html create mode 100644 apps/customers/presentation/templates/customers/partials/actions.html create mode 100644 apps/customers/presentation/templates/customers/partials/billing_units.html create mode 100644 apps/customers/presentation/templates/customers/partials/child_form.html create mode 100644 apps/customers/presentation/templates/customers/partials/contacts.html create mode 100644 apps/customers/presentation/templates/customers/partials/customer_table.html create mode 100644 apps/customers/presentation/templates/customers/partials/personal_id.html create mode 100644 apps/customers/presentation/templatetags/__init__.py create mode 100644 apps/customers/presentation/templatetags/customers_tags.py create mode 100644 apps/customers/presentation/urls.py create mode 100644 apps/customers/presentation/views.py create mode 100644 apps/customers/tests/__init__.py create mode 100644 apps/customers/tests/application/__init__.py create mode 100644 apps/customers/tests/application/test_use_cases.py create mode 100644 apps/customers/tests/domain/__init__.py create mode 100644 apps/customers/tests/domain/test_value_objects.py create mode 100644 apps/customers/tests/fakes.py create mode 100644 apps/customers/tests/integration/__init__.py create mode 100644 apps/customers/tests/integration/test_customers.py create mode 100644 apps/shared/tests/fakes.py create mode 100644 tests/browser/test_customers.py diff --git a/.env.example b/.env.example index fbf8e57..9fb30e2 100644 --- a/.env.example +++ b/.env.example @@ -14,3 +14,9 @@ DB_PORT=3306 SITE_URL=http://127.0.0.1:8000 EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend DEFAULT_FROM_EMAIL=toiminnanohjaus@localhost + +# Henkilötunnuksen salaus. Luo avaimet: +# python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" +# python -c "import secrets; print(secrets.token_urlsafe(48))" +FIELD_ENCRYPTION_KEYS=vaihda-fernet-avaimeen +PERSONAL_ID_HASH_KEY=vaihda-satunnaiseen-avaimeen diff --git a/CLAUDE.md b/CLAUDE.md index 99002e3..04b4aa7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,11 @@ Toiminnanohjaus is an ERP for a small (5–10 people) Finnish media and marketin - Stack: Django 5.2 LTS, Python 3.14, MariaDB 10.11 (XAMPP in development), HTMX, Alpine.js, Tailwind CSS 4 and daisyUI 5. - Language: code (identifiers, tables, columns, enum keys) is in English. Specs, UI texts, docs and commit messages are in Finnish. -**Current state:** phase 1 item 1 is done: the `shared` module and the `users` module (custom user model, login, password links, user management). It is the reference implementation of the architecture; copy its patterns for new modules. Other modules described in `docs/architecture.md` are not built yet. +**Current state:** phase 1 items 1–2 are done. +- `shared` and `users`: custom user model, login, password links, user management. +- `customers`: customers, contacts, billing units, the internal customer, and the encrypted personal identity code. + +`users` and `customers` are the reference implementations; copy their patterns for new modules. The other modules in `docs/architecture.md` are not built yet. Next in the spec is phase 1 item 3: service units, services and work types as base data. ## Source of truth @@ -43,6 +47,10 @@ Translations: source strings are English; Finnish is in `locale/fi/LC_MESSAGES/d - `AUTH_USER_MODEL = "users.User"` (`apps/users/infrastructure/orm.py`): email login, a role field, no `PermissionsMixin` and no Django admin. Permissions are role-based: `apps/users/domain/permissions.py` (`role_has`), `PermissionRequiredMixin`, and the template filter `{% if request.user|can:"users.manage" %}` (`{% load users_tags %}`). - `LoginRequiredMiddleware` is on, so mark public views with `login_not_required`. `EnsureAccountIsUsable` logs out deactivated users and interns past their end date on every request. - The cache is `DatabaseCache` (login throttling), so run `createcachetable` on new databases. +- **Personal identity code (henkilötunnus):** + - It is encrypted with Fernet (`FIELD_ENCRYPTION_KEYS`, comma-separated; the first key encrypts and all keys decrypt) and has an HMAC fingerprint (`PERSONAL_ID_HASH_KEY`) for duplicate checks. A system check fails if either key is missing. + - Never change these keys in `.env` without rotating them; otherwise stored codes cannot be decrypted. + - Only `customers.infrastructure.vault` touches plain codes. The domain `PersonalIdentityCode` hides the code in `repr`, and display uses `masked`. - **Templates and tags:** - Each module's templates live in `apps//presentation/templates` and are added to `TEMPLATES['DIRS']` by a glob in settings. - Template tag libraries live in `presentation/templatetags` and must be registered in `TEMPLATES['OPTIONS']['libraries']`. @@ -58,7 +66,8 @@ The project is a modular monolith. Each business area is a Django app under `app - `infrastructure/` holds the Django models (named `…Model`, in `orm.py` and re-exported from the app's `models.py`; set `Meta.db_table` to the table names in spec section 14), the repository implementations and the query implementations, which return DTOs straight from the ORM. - `presentation/` holds thin views, Django Forms and templates. Forms validate input shape and build DTOs. Domain errors are turned into field errors with `form.add_error()`. HTMX requests get partial templates. - `container.py` is the composition root, with factory functions that wire the use cases. There is no DI framework. Presentation reaches infrastructure only through the container (import-linter enforces this; add every new module to the contracts in `pyproject.toml`). -- Tests live in `apps//tests/{domain,application,integration}`. Application tests use in-memory fakes (`apps/users/tests/fakes.py` shows the pattern) and need no DB. +- Tests live in `apps//tests/{domain,application,integration}`. Application tests use in-memory fakes (`apps//tests/fakes.py`; `FakeUnitOfWork` is in `apps/shared/tests/fakes.py`) and need no DB. The shared pytest fixtures (`make_user`, `admin`, `admin_client`) are in `apps/conftest.py`, and the browser test helpers (`themed_page`, `ALL`, `assert_accessible`, `login`) are in `tests/browser/conftest.py`. +- **Deletion guards are generic.** `apps/customers/infrastructure/references.py` (`is_referenced`) checks every reverse relation. When a new module adds a `ForeignKey(..., on_delete=PROTECT)` to customers, contacts or billing units, the delete buttons and use cases block deletion automatically, so don't add cross-module checks. Copy the pattern for other modules' entities. Cross-cutting rules: @@ -79,5 +88,9 @@ WCAG 2.2 AA / EN 301 549 is the contract's acceptance criterion for the whole UI - **Layout:** no horizontal page scrolling from 320 px up to FullHD. The machine console needs touch targets of at least 44 × 44 px. - **Implementation:** use daisyUI classes and the shared partials in `templates/components/`. Alpine.js is for local UI state only, never for business logic. - **Colours:** daisyUI's default text colours fail WCAG contrast in places. `static/src/app.css` overrides soft alerts and badges, `.menu-title`, and the light theme's error and success colours. Use `link` rather than `link-primary` for text links. The browser tests (axe) catch regressions. +- **Dialog forms (customers module pattern):** + - The form is loaded with `hx-get` into the shared ``. + - When the form is invalid, the server returns the form with status 422. `static/src/app.js` makes HTMX swap 422 responses and focuses the first `aria-invalid` field. + - When the form is valid, the server re-renders the section with `HX-Retarget`/`HX-Reswap`. It sets `HX-Trigger-After-Settle: {"itemSaved": {"message", "focus"}}` (the handler in app.js closes the dialog, moves focus and announces the message) and adds any changed header actions as an out-of-band swap. - **Assets:** no CDN in production; build the assets with npm. - **Texts:** all UI text goes through `gettext` / `{% translate %}`. diff --git a/README.md b/README.md index a687443..c7f237c 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,12 @@ Määrittely: `docs/maarittely.md`, arkkitehtuuri: `docs/architecture.md`. ```powershell C:\xampp\mysql\bin\mysql.exe -u root -e "CREATE DATABASE IF NOT EXISTS ``django-toiminnanohjaus`` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" ``` -3. Kopioi `.env.example` → `.env` ja täytä arvot (`DJANGO_SECRET_KEY` vähintään). +3. Kopioi `.env.example` → `.env` ja täytä arvot (avaimet voi luoda kohdan 4 asennuksen jälkeen): vähintään `DJANGO_SECRET_KEY` sekä henkilötunnuksen salausavaimet `FIELD_ENCRYPTION_KEYS` ja `PERSONAL_ID_HASH_KEY`: + ```powershell + .venv\Scripts\python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" + .venv\Scripts\python -c "import secrets; print(secrets.token_urlsafe(48))" + ``` + **Älä vaihda salausavaimia** käytössä olevassa järjestelmässä: muuten tallennettuja henkilötunnuksia ei voi purkaa. Uuden avaimen voi lisätä listan alkuun (vanha jää purkuun). 4. Asenna riippuvuudet, rakenna käyttöliittymä ja käännökset, aja migraatiot: ```powershell py -3.14 -m venv .venv diff --git a/apps/users/tests/conftest.py b/apps/conftest.py similarity index 100% rename from apps/users/tests/conftest.py rename to apps/conftest.py diff --git a/apps/customers/__init__.py b/apps/customers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/application/__init__.py b/apps/customers/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/application/dto.py b/apps/customers/application/dto.py new file mode 100644 index 0000000..8090a46 --- /dev/null +++ b/apps/customers/application/dto.py @@ -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 diff --git a/apps/customers/application/queries.py b/apps/customers/application/queries.py new file mode 100644 index 0000000..78eca79 --- /dev/null +++ b/apps/customers/application/queries.py @@ -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.""" + ... diff --git a/apps/customers/application/use_cases.py b/apps/customers/application/use_cases.py new file mode 100644 index 0000000..cea8bcc --- /dev/null +++ b/apps/customers/application/use_cases.py @@ -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) diff --git a/apps/customers/apps.py b/apps/customers/apps.py new file mode 100644 index 0000000..6554ba3 --- /dev/null +++ b/apps/customers/apps.py @@ -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 diff --git a/apps/customers/container.py b/apps/customers/container.py new file mode 100644 index 0000000..337ee9d --- /dev/null +++ b/apps/customers/container.py @@ -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() diff --git a/apps/customers/domain/__init__.py b/apps/customers/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/domain/entities.py b/apps/customers/domain/entities.py new file mode 100644 index 0000000..da38c1b --- /dev/null +++ b/apps/customers/domain/entities.py @@ -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) diff --git a/apps/customers/domain/enums.py b/apps/customers/domain/enums.py new file mode 100644 index 0000000..6dc400b --- /dev/null +++ b/apps/customers/domain/enums.py @@ -0,0 +1,6 @@ +from enum import StrEnum + + +class CustomerType(StrEnum): + COMPANY = "company" + CONSUMER = "consumer" diff --git a/apps/customers/domain/exceptions.py b/apps/customers/domain/exceptions.py new file mode 100644 index 0000000..e481da2 --- /dev/null +++ b/apps/customers/domain/exceptions.py @@ -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" diff --git a/apps/customers/domain/repositories.py b/apps/customers/domain/repositories.py new file mode 100644 index 0000000..2c434a8 --- /dev/null +++ b/apps/customers/domain/repositories.py @@ -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.""" + ... diff --git a/apps/customers/domain/value_objects.py b/apps/customers/domain/value_objects.py new file mode 100644 index 0000000..6977267 --- /dev/null +++ b/apps/customers/domain/value_objects.py @@ -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 diff --git a/apps/customers/infrastructure/__init__.py b/apps/customers/infrastructure/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/infrastructure/orm.py b/apps/customers/infrastructure/orm.py new file mode 100644 index 0000000..03c6913 --- /dev/null +++ b/apps/customers/infrastructure/orm.py @@ -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 diff --git a/apps/customers/infrastructure/queries.py b/apps/customers/infrastructure/queries.py new file mode 100644 index 0000000..64e56c2 --- /dev/null +++ b/apps/customers/infrastructure/queries.py @@ -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) diff --git a/apps/customers/infrastructure/references.py b/apps/customers/infrastructure/references.py new file mode 100644 index 0000000..9dc2a73 --- /dev/null +++ b/apps/customers/infrastructure/references.py @@ -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 diff --git a/apps/customers/infrastructure/repositories.py b/apps/customers/infrastructure/repositories.py new file mode 100644 index 0000000..b6dc003 --- /dev/null +++ b/apps/customers/infrastructure/repositories.py @@ -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 diff --git a/apps/customers/infrastructure/vault.py b/apps/customers/infrastructure/vault.py new file mode 100644 index 0000000..ce8384f --- /dev/null +++ b/apps/customers/infrastructure/vault.py @@ -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 diff --git a/apps/customers/migrations/0001_initial.py b/apps/customers/migrations/0001_initial.py new file mode 100644 index 0000000..07e7101 --- /dev/null +++ b/apps/customers/migrations/0001_initial.py @@ -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'], + }, + ), + ] diff --git a/apps/customers/migrations/0002_internal_customer.py b/apps/customers/migrations/0002_internal_customer.py new file mode 100644 index 0000000..01ecc69 --- /dev/null +++ b/apps/customers/migrations/0002_internal_customer.py @@ -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)] diff --git a/apps/customers/migrations/__init__.py b/apps/customers/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/models.py b/apps/customers/models.py new file mode 100644 index 0000000..0f9f46c --- /dev/null +++ b/apps/customers/models.py @@ -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"] diff --git a/apps/customers/presentation/__init__.py b/apps/customers/presentation/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/presentation/forms.py b/apps/customers/presentation/forms.py new file mode 100644 index 0000000..91c79f5 --- /dev/null +++ b/apps/customers/presentation/forms.py @@ -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] + ) diff --git a/apps/customers/presentation/labels.py b/apps/customers/presentation/labels.py new file mode 100644 index 0000000..977c1a6 --- /dev/null +++ b/apps/customers/presentation/labels.py @@ -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."), +} diff --git a/apps/customers/presentation/templates/customers/child_form_page.html b/apps/customers/presentation/templates/customers/child_form_page.html new file mode 100644 index 0000000..1101eb0 --- /dev/null +++ b/apps/customers/presentation/templates/customers/child_form_page.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% block title %}{{ customer.name }}{% endblock %} +{% block content %} + +
+
+ {% include "customers/partials/child_form.html" %} +
+
+{% endblock %} diff --git a/apps/customers/presentation/templates/customers/detail.html b/apps/customers/presentation/templates/customers/detail.html new file mode 100644 index 0000000..a641d6a --- /dev/null +++ b/apps/customers/presentation/templates/customers/detail.html @@ -0,0 +1,42 @@ +{% extends "base.html" %}{% load customers_tags %} +{% block title %}{{ customer.name }}{% endblock %} +{% block content %} + +
+

+ {{ customer.name }} + {% if customer.is_internal %}{% translate "Internal" %}{% endif %} +

+ {% include "customers/partials/actions.html" %} +
+ +
+
+

{% translate "Basic information" %}

+
+
{% translate "Type" %}
{{ customer.type|customer_type_label }}
+ {% if customer.type == "company" %} +
{% translate "Business ID" %}
{{ customer.business_id|default:"–" }}
+ {% else %} +
{% translate "Personal identity code" %}
+
{% include "customers/partials/personal_id.html" %}
+ {% endif %} +
+ {% if customer.is_internal %} +

{% translate "Internal work (administration, sales, training) is recorded on the jobs of the internal customer. It cannot be deleted." %}

+ {% endif %} +
+
+ +
+ {% include "customers/partials/contacts.html" %} + {% include "customers/partials/billing_units.html" %} +
+ + + + + +{% endblock %} diff --git a/apps/customers/presentation/templates/customers/form.html b/apps/customers/presentation/templates/customers/form.html new file mode 100644 index 0000000..90b8a2a --- /dev/null +++ b/apps/customers/presentation/templates/customers/form.html @@ -0,0 +1,34 @@ +{% extends "base.html" %} +{% block title %}{% if customer %}{% translate "Edit customer" %}{% else %}{% translate "New customer" %}{% endif %}{% endblock %} +{% block content %} + +

{% if customer %}{% translate "Edit customer" %}{% else %}{% translate "New customer" %}{% endif %}

+ +
+ {% csrf_token %} +
+ {% include "components/non_field_errors.html" %} + {{ form.name.as_field_group }} + {{ form.type.as_field_group }} +
+ {{ form.business_id.as_field_group }} +
+
+ {{ form.personal_identity_code.as_field_group }} + {% if form.remove_personal_id %}{{ form.remove_personal_id.as_field_group }}{% endif %} +

{% translate "The personal identity code is specially protected data. It is stored encrypted and used only for invoicing." %}

+
+
+ {% translate "Cancel" %} + +
+
+
+{% endblock %} diff --git a/apps/customers/presentation/templates/customers/list.html b/apps/customers/presentation/templates/customers/list.html new file mode 100644 index 0000000..1a9b0c6 --- /dev/null +++ b/apps/customers/presentation/templates/customers/list.html @@ -0,0 +1,23 @@ +{% extends "base.html" %} +{% block title %}{% translate "Customers" %}{% endblock %} +{% block content %} +
+

{% translate "Customers" %}

+ {% translate "New customer" %} +
+ + + +
+ {% include "customers/partials/customer_table.html" %} +
+{% endblock %} diff --git a/apps/customers/presentation/templates/customers/partials/actions.html b/apps/customers/presentation/templates/customers/partials/actions.html new file mode 100644 index 0000000..58132c0 --- /dev/null +++ b/apps/customers/presentation/templates/customers/partials/actions.html @@ -0,0 +1,13 @@ +
+ {% translate "Edit" %} + {% if is_deletable %} + + {% 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 %} +
diff --git a/apps/customers/presentation/templates/customers/partials/billing_units.html b/apps/customers/presentation/templates/customers/partials/billing_units.html new file mode 100644 index 0000000..adbe298 --- /dev/null +++ b/apps/customers/presentation/templates/customers/partials/billing_units.html @@ -0,0 +1,46 @@ +
+
+
+

{% translate "Billing units" %}

+ {% translate "Add billing unit" %} +
+

{% translate "Each billing unit is invoiced separately." %}

+ {% if billing_units %} +
    + {% for u in billing_units %}{% with id_str=u.id|stringformat:"s" %} +
  • +
    +

    {{ u.name }}

    + {% if u.billing_address %}

    {{ u.billing_address }}

    {% endif %} + {% if u.e_invoice_address %} +

    {% translate "E-invoice" %}: {{ u.e_invoice_address }} ({% translate "operator" %} {{ u.e_invoice_operator }})

    + {% endif %} + {% if u.reference %}

    {% translate "Reference" %}: {{ u.reference }}

    {% endif %} +
    +
    + + {% translate "Edit" %}: {{ u.name }} + {% if u.in_use %} + {% translate "In use in a job" %} + {% else %} + + {% 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 %} +
    +
  • + {% endwith %}{% endfor %} +
+ {% else %} +

{% translate "No billing units yet." %}

+ {% endif %} +
+
diff --git a/apps/customers/presentation/templates/customers/partials/child_form.html b/apps/customers/presentation/templates/customers/partials/child_form.html new file mode 100644 index 0000000..ac12c25 --- /dev/null +++ b/apps/customers/presentation/templates/customers/partials/child_form.html @@ -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 %} +

+ {% 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 %} +

+
+ {% csrf_token %} + {{ form }} + +
diff --git a/apps/customers/presentation/templates/customers/partials/contacts.html b/apps/customers/presentation/templates/customers/partials/contacts.html new file mode 100644 index 0000000..9e3760e --- /dev/null +++ b/apps/customers/presentation/templates/customers/partials/contacts.html @@ -0,0 +1,43 @@ +
+
+
+

{% translate "Contacts" %}

+ {% translate "Add contact" %} +
+ {% if contacts %} +
    + {% for c in contacts %}{% with id_str=c.id|stringformat:"s" %} +
  • +
    +

    {{ c.name }}{% if c.title %}, {{ c.title }}{% endif %}

    + {% if c.phone %}

    {{ c.phone }}

    {% endif %} + {% if c.email %}

    {{ c.email }}

    {% endif %} + {% if c.note %}

    {{ c.note }}

    {% endif %} +
    +
    + + {% translate "Edit" %}: {{ c.name }} + {% if c.in_use %} + {% translate "In use in a job" %} + {% else %} + + {% 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 %} +
    +
  • + {% endwith %}{% endfor %} +
+ {% else %} +

{% translate "No contacts yet." %}

+ {% endif %} +
+
diff --git a/apps/customers/presentation/templates/customers/partials/customer_table.html b/apps/customers/presentation/templates/customers/partials/customer_table.html new file mode 100644 index 0000000..03477a5 --- /dev/null +++ b/apps/customers/presentation/templates/customers/partials/customer_table.html @@ -0,0 +1,41 @@ +{% load customers_tags %} +

{% blocktranslate count counter=page.paginator.count %}{{ counter }} customer found{% plural %}{{ counter }} customers found{% endblocktranslate %}

+
+ + + + + + + + + + + {% for c in page.object_list %} + + + + + + {% empty %} + + {% endfor %} + +
{% translate "Customers" %}
{% translate "Name" %}{% translate "Type" %}{% translate "Business ID" %}
+ {{ c.name }} + {% if c.is_internal %}{% translate "Internal" %}{% endif %} + {{ c.type|customer_type_label }}{{ c.business_id|default:"–" }}
{% translate "No customers match the filters." %}
+
+{% if page.paginator.num_pages > 1 %} + +{% endif %} diff --git a/apps/customers/presentation/templates/customers/partials/personal_id.html b/apps/customers/presentation/templates/customers/partials/personal_id.html new file mode 100644 index 0000000..38d51ae --- /dev/null +++ b/apps/customers/presentation/templates/customers/partials/personal_id.html @@ -0,0 +1,13 @@ +{% if customer.personal_id_full %} + {{ customer.personal_id_full }} +{% elif customer.personal_id_masked %} + {{ customer.personal_id_masked }} + {% if can_view_personal_id %} + + {% endif %} +{% else %} + {% translate "Not given" %} +{% endif %} diff --git a/apps/customers/presentation/templatetags/__init__.py b/apps/customers/presentation/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/presentation/templatetags/customers_tags.py b/apps/customers/presentation/templatetags/customers_tags.py new file mode 100644 index 0000000..c7be286 --- /dev/null +++ b/apps/customers/presentation/templatetags/customers_tags.py @@ -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)) diff --git a/apps/customers/presentation/urls.py b/apps/customers/presentation/urls.py new file mode 100644 index 0000000..edac0e1 --- /dev/null +++ b/apps/customers/presentation/urls.py @@ -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("/", views.CustomerDetailView.as_view(), name="detail"), + path("/edit/", views.CustomerUpdateView.as_view(), name="edit"), + path("/delete/", views.CustomerDeleteView.as_view(), name="delete"), + path("/personal-id/", views.PersonalIdRevealView.as_view(), name="personal_id"), + path("//new/", views.ChildFormView.as_view(), name="child_create"), + path( + "///edit/", + views.ChildFormView.as_view(), + name="child_edit", + ), + path( + "///delete/", + views.ChildDeleteView.as_view(), + name="child_delete", + ), +] diff --git a/apps/customers/presentation/views.py b/apps/customers/presentation/views.py new file mode 100644 index 0000000..41da214 --- /dev/null +++ b/apps/customers/presentation/views.py @@ -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) diff --git a/apps/customers/tests/__init__.py b/apps/customers/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/tests/application/__init__.py b/apps/customers/tests/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/tests/application/test_use_cases.py b/apps/customers/tests/application/test_use_cases.py new file mode 100644 index 0000000..695e6b5 --- /dev/null +++ b/apps/customers/tests/application/test_use_cases.py @@ -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="MAIJA@example.test") + ) + assert contacts.items[contact_id].email.value == "maija@example.test" # 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") + ) diff --git a/apps/customers/tests/domain/__init__.py b/apps/customers/tests/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/tests/domain/test_value_objects.py b/apps/customers/tests/domain/test_value_objects.py new file mode 100644 index 0000000..f301564 --- /dev/null +++ b/apps/customers/tests/domain/test_value_objects.py @@ -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" diff --git a/apps/customers/tests/fakes.py b/apps/customers/tests/fakes.py new file mode 100644 index 0000000..0aceee9 --- /dev/null +++ b/apps/customers/tests/fakes.py @@ -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] diff --git a/apps/customers/tests/integration/__init__.py b/apps/customers/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/customers/tests/integration/test_customers.py b/apps/customers/tests/integration/test_customers.py new file mode 100644 index 0000000..4ee70c4 --- /dev/null +++ b/apps/customers/tests/integration/test_customers.py @@ -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 " 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() diff --git a/apps/shared/tests/fakes.py b/apps/shared/tests/fakes.py new file mode 100644 index 0000000..772ac5e --- /dev/null +++ b/apps/shared/tests/fakes.py @@ -0,0 +1,15 @@ +"""Test doubles for the shared ports, usable by every module's application tests.""" + +from __future__ import annotations + + +class FakeUnitOfWork: + def __init__(self) -> None: + self.entered = 0 + + def __enter__(self) -> FakeUnitOfWork: + self.entered += 1 + return self + + def __exit__(self, *exc: object) -> None: + return None diff --git a/apps/users/domain/enums.py b/apps/users/domain/enums.py index 6060d0a..3d6d8b3 100644 --- a/apps/users/domain/enums.py +++ b/apps/users/domain/enums.py @@ -18,3 +18,5 @@ class Role(StrEnum): class Permission(StrEnum): USERS_MANAGE = "users.manage" CUSTOMERS_USE = "customers.use" + # See the full personal identity code and remove it (others see it masked). + CUSTOMERS_PERSONAL_ID_VIEW = "customers.personal_id.view" diff --git a/apps/users/domain/permissions.py b/apps/users/domain/permissions.py index 29f82ea..e0adbfc 100644 --- a/apps/users/domain/permissions.py +++ b/apps/users/domain/permissions.py @@ -7,6 +7,7 @@ _ALL_EXCEPT_SUBCONTRACTOR = frozenset({Role.ADMIN, Role.MANAGEMENT, Role.EMPLOYE _PERMISSIONS: dict[Permission, frozenset[Role]] = { Permission.USERS_MANAGE: frozenset({Role.ADMIN}), Permission.CUSTOMERS_USE: _ALL_EXCEPT_SUBCONTRACTOR, + Permission.CUSTOMERS_PERSONAL_ID_VIEW: frozenset({Role.ADMIN, Role.MANAGEMENT}), } diff --git a/apps/users/tests/fakes.py b/apps/users/tests/fakes.py index 4053d1c..1ee1eb6 100644 --- a/apps/users/tests/fakes.py +++ b/apps/users/tests/fakes.py @@ -4,6 +4,7 @@ from dataclasses import replace from datetime import UTC, date, datetime from apps.shared.domain.value_objects import EmailAddress +from apps.shared.tests.fakes import FakeUnitOfWork # noqa: F401 (re-exported for users tests) from apps.users.application.dto import PasswordLink, PasswordLinkPurpose from apps.users.domain.entities import UserAccount from apps.users.domain.enums import Role @@ -42,18 +43,6 @@ class InMemoryUserRepository: ) -class FakeUnitOfWork: - def __init__(self) -> None: - self.entered = 0 - - def __enter__(self) -> FakeUnitOfWork: - self.entered += 1 - return self - - def __exit__(self, *exc: object) -> None: - return None - - class FakePasswordLinkService: def __init__(self, *, send_ok: bool = True) -> None: self.send_ok = send_ok diff --git a/apps/users/tests/integration/test_auth.py b/apps/users/tests/integration/test_auth.py index ec3ff11..7eb7797 100644 --- a/apps/users/tests/integration/test_auth.py +++ b/apps/users/tests/integration/test_auth.py @@ -7,10 +7,10 @@ from django.core import mail from django.test import Client from django.urls import reverse +from apps.conftest import PASSWORD from apps.users.application.dto import PasswordLinkPurpose from apps.users.infrastructure.orm import User from apps.users.infrastructure.password_links import DjangoPasswordLinkService -from apps.users.tests.conftest import PASSWORD pytestmark = pytest.mark.django_db diff --git a/config/settings.py b/config/settings.py index cd52b81..012108e 100644 --- a/config/settings.py +++ b/config/settings.py @@ -46,6 +46,7 @@ INSTALLED_APPS = [ "django_htmx", "apps.shared", "apps.users", + "apps.customers", ] MIDDLEWARE = [ @@ -83,6 +84,7 @@ TEMPLATES = [ # Module template tags live in /presentation/templatetags. "libraries": { "users_tags": "apps.users.presentation.templatetags.users_tags", + "customers_tags": "apps.customers.presentation.templatetags.customers_tags", }, }, }, @@ -198,3 +200,10 @@ LOGGING = { "handlers": {"console": {"class": "logging.StreamHandler"}}, "root": {"handlers": ["console"], "level": "WARNING"}, } + +# Personal identity codes (henkilötunnus) are stored encrypted (Fernet) with an HMAC fingerprint +# for duplicate checks. The first key encrypts; all keys decrypt, so keys can be rotated. +FIELD_ENCRYPTION_KEYS = [ + k.strip() for k in os.getenv("FIELD_ENCRYPTION_KEYS", "").split(",") if k.strip() +] +PERSONAL_ID_HASH_KEY = os.getenv("PERSONAL_ID_HASH_KEY", "") diff --git a/config/urls.py b/config/urls.py index 9d30395..7b63863 100644 --- a/config/urls.py +++ b/config/urls.py @@ -5,4 +5,5 @@ from apps.shared.presentation.views import home urlpatterns = [ path("", home, name="home"), path("", include("apps.users.presentation.urls")), + path("customers/", include("apps.customers.presentation.urls")), ] diff --git a/docs/architecture.md b/docs/architecture.md index 3f61f65..2560aa4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -157,6 +157,7 @@ Kiertäviä riippuvuuksia (A käyttää B:n rajapintaa ja B A:n) vältetään: t - `save()` hoitaa sekä lisäyksen että päivityksen ja palauttaa tallennetun entiteetin (uusi saa tässä id:n). - Rinnakkaisuutta vaativat tarkistukset lukitsevat rivit `select_for_update()`lla repositoryssä (esim. viimeinen aktiivinen pääkäyttäjä, juokseva työnumero). - **Lukupuoli on erillään:** listat, haut ja raportit tehdään kyselyrajapinnalla (`CustomerQueries`), joka palauttaa DTO:ita suoraan kyselystä. Entiteettejä ei rakenneta pelkkää näyttämistä varten. +- **Poistonestot ovat yleisiä:** `apps/customers/infrastructure/references.py` (`is_referenced`) käy läpi rivin kaikki käänteiset relaatiot. Kun uusi moduuli viittaa toisen moduulin riviin `ForeignKey(..., on_delete=PROTECT)`-avaimella, poisto estyy ja poistopainike piiloutuu automaattisesti. Viitattava moduuli ei tunne viittaajaa, joten moduulien välisiä tarkistuksia ei tarvita. - Repository luodaan vain, kun moduulilla on kirjoittavia use caseja ja sääntöjä. Pelkälle hakutaulukolle (esim. asetukset) riittää kyselyrajapinta ja yksinkertainen kirjoitusfunktio. ## 7. Transaktiot ja tapahtumat diff --git a/locale/fi/LC_MESSAGES/django.po b/locale/fi/LC_MESSAGES/django.po index fcf6bd9..032702d 100644 --- a/locale/fi/LC_MESSAGES/django.po +++ b/locale/fi/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-29 12:10+0200\n" +"POT-Creation-Date: 2026-11-29 13:39+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -18,40 +18,493 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" +#: .\apps\customers\presentation\forms.py:13 +#: .\apps\customers\presentation\forms.py:62 +#: .\apps\customers\presentation\forms.py:77 +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:8 +#: .\apps\users\presentation\forms.py:70 +#: .\apps\users\presentation\templates\users\partials\user_table.html:8 +msgid "Name" +msgstr "Nimi" + +#: .\apps\customers\presentation\forms.py:14 +#: .\apps\customers\presentation\forms.py:102 +#: .\apps\customers\presentation\templates\customers\detail.html:24 +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:9 +msgid "Type" +msgstr "Tyyppi" + +#: .\apps\customers\presentation\forms.py:16 +#: .\apps\customers\presentation\templates\customers\detail.html:26 +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:10 +msgid "Business ID" +msgstr "Y-tunnus" + +#: .\apps\customers\presentation\forms.py:16 +msgid "For example 1234567-1" +msgstr "Esimerkiksi 1234567-1" + +#: .\apps\customers\presentation\forms.py:19 +#: .\apps\customers\presentation\templates\customers\detail.html:28 +msgid "Personal identity code" +msgstr "Henkilötunnus" + +#: .\apps\customers\presentation\forms.py:24 +msgid "Needed only for invoicing a consumer." +msgstr "Tarvitaan vain kuluttajan laskutukseen." + +#: .\apps\customers\presentation\forms.py:26 +msgid "Remove personal identity code" +msgstr "Poista henkilötunnus" + +#: .\apps\customers\presentation\forms.py:40 +#, python-format +msgid "Stored: %(masked)s. Leave empty to keep it." +msgstr "Tallennettu: %(masked)s. Jätä tyhjäksi, niin tunnus säilyy." + +#: .\apps\customers\presentation\forms.py:46 +#: .\apps\customers\presentation\labels.py:18 +msgid "The internal customer is always a company." +msgstr "Sisäinen asiakas on aina yritys." + +#: .\apps\customers\presentation\forms.py:63 +msgid "Title or role" +msgstr "Titteli tai rooli" + +#: .\apps\customers\presentation\forms.py:65 +msgid "Phone" +msgstr "Puhelin" + +#: .\apps\customers\presentation\forms.py:67 +#: .\apps\users\presentation\forms.py:22 .\apps\users\presentation\forms.py:52 +#: .\apps\users\presentation\forms.py:71 +#: .\apps\users\presentation\templates\users\partials\user_table.html:9 +msgid "Email" +msgstr "Sähköposti" + +#: .\apps\customers\presentation\forms.py:69 +msgid "Note" +msgstr "Lisätieto" + +#: .\apps\customers\presentation\forms.py:79 +msgid "Billing address" +msgstr "Laskutusosoite" + +#: .\apps\customers\presentation\forms.py:82 +#| msgid "Enter a valid email address." +msgid "Postal address or billing email address." +msgstr "Postiosoite tai laskutussähköposti." + +#: .\apps\customers\presentation\forms.py:85 +msgid "E-invoice address" +msgstr "Verkkolaskuosoite" + +#: .\apps\customers\presentation\forms.py:85 +msgid "12–35 letters or digits." +msgstr "12–35 kirjainta tai numeroa." + +#: .\apps\customers\presentation\forms.py:88 +msgid "Operator ID" +msgstr "Välittäjätunnus" + +#: .\apps\customers\presentation\forms.py:91 +msgid "Required when an e-invoice address is given." +msgstr "Pakollinen, jos verkkolaskuosoite on annettu." + +#: .\apps\customers\presentation\forms.py:93 +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:20 +msgid "Reference" +msgstr "Viite" + +#: .\apps\customers\presentation\forms.py:100 +#: .\apps\users\presentation\forms.py:113 +msgid "Search" +msgstr "Haku" + +#: .\apps\customers\presentation\forms.py:100 +msgid "Name or business ID" +msgstr "Nimi tai Y-tunnus" + +#: .\apps\customers\presentation\forms.py:102 +#| msgid "All roles" +msgid "All types" +msgstr "Kaikki tyypit" + +#: .\apps\customers\presentation\labels.py:6 +msgid "Company" +msgstr "Yritys" + +#: .\apps\customers\presentation\labels.py:7 +msgid "Consumer" +msgstr "Kuluttaja" + +#: .\apps\customers\presentation\labels.py:13 +#: .\apps\customers\presentation\labels.py:31 +#| msgid "Enter a name (at most 150 characters)." +msgid "Enter a name (at most 200 characters)." +msgstr "Anna nimi (enintään 200 merkkiä)." + +#: .\apps\customers\presentation\labels.py:14 +msgid "Enter a valid business ID, for example 1234567-1." +msgstr "Anna kelvollinen Y-tunnus, esimerkiksi 1234567-1." + +#: .\apps\customers\presentation\labels.py:15 +#| msgid "Enter a valid email address." +msgid "Enter a valid personal identity code." +msgstr "Anna kelvollinen henkilötunnus." + +#: .\apps\customers\presentation\labels.py:16 +msgid "A consumer cannot have a business ID." +msgstr "Kuluttajalla ei voi olla Y-tunnusta." + +#: .\apps\customers\presentation\labels.py:17 +msgid "A company cannot have a personal identity code." +msgstr "Yrityksellä ei voi olla henkilötunnusta." + +#: .\apps\customers\presentation\labels.py:19 +msgid "Another customer already has this business ID." +msgstr "Y-tunnus on jo toisella asiakkaalla." + +#: .\apps\customers\presentation\labels.py:20 +msgid "Another customer already has this personal identity code." +msgstr "Henkilötunnus on jo toisella asiakkaalla." + +#: .\apps\customers\presentation\labels.py:22 +msgid "You are not allowed to remove the personal identity code." +msgstr "Sinulla ei ole oikeutta poistaa henkilötunnusta." + +#: .\apps\customers\presentation\labels.py:24 +#| msgid "The user was not found." +msgid "The customer was not found." +msgstr "Asiakasta ei löytynyt." + +#: .\apps\customers\presentation\labels.py:26 +msgid "" +"The customer cannot be deleted because it has contacts, billing units, jobs, " +"sales or invoices." +msgstr "Asiakasta ei voi poistaa, koska sillä on yhteyshenkilöitä, laskutusyksiköitä, asiakastöitä, myyntejä tai laskuja." + +#: .\apps\customers\presentation\labels.py:29 +#| msgid "An intern must have an end date." +msgid "The internal customer cannot be deleted." +msgstr "Sisäistä asiakasta ei voi poistaa." + +#: .\apps\customers\presentation\labels.py:30 +#: .\apps\users\presentation\labels.py:18 +msgid "Enter a name (at most 150 characters)." +msgstr "Anna nimi (enintään 150 merkkiä)." + +#: .\apps\customers\presentation\labels.py:32 +msgid "The e-invoice address must be 12–35 letters or digits." +msgstr "Verkkolaskuosoitteessa on oltava 12–35 kirjainta tai numeroa." + +#: .\apps\customers\presentation\labels.py:33 +msgid "Enter the operator ID when an e-invoice address is given." +msgstr "Anna välittäjätunnus, kun verkkolaskuosoite on annettu." + +#: .\apps\customers\presentation\labels.py:34 +#: .\apps\users\presentation\labels.py:19 +msgid "Enter a valid email address." +msgstr "Anna kelvollinen sähköpostiosoite." + +#: .\apps\customers\presentation\labels.py:35 +#| msgid "The user was not found." +msgid "The contact was not found." +msgstr "Yhteyshenkilöä ei löytynyt." + +#: .\apps\customers\presentation\labels.py:36 +#| msgid "The user was not found." +msgid "The billing unit was not found." +msgstr "Laskutusyksikköä ei löytynyt." + +#: .\apps\customers\presentation\labels.py:37 +msgid "The contact cannot be deleted because a job refers to it." +msgstr "Yhteyshenkilöä ei voi poistaa, koska asiakastyö viittaa siihen." + +#: .\apps\customers\presentation\labels.py:38 +msgid "The billing unit cannot be deleted because a job refers to it." +msgstr "Laskutusyksikköä ei voi poistaa, koska asiakastyö viittaa siihen." + +#: .\apps\customers\presentation\labels.py:39 +#: .\apps\users\presentation\labels.py:31 +msgid "The change could not be saved." +msgstr "Muutosta ei voitu tallentaa." + +#: .\apps\customers\presentation\templates\customers\child_form_page.html:4 +#: .\apps\customers\presentation\templates\customers\detail.html:4 +#: .\apps\customers\presentation\templates\customers\form.html:4 +#: .\apps\users\presentation\templates\users\form.html:4 +msgid "Breadcrumbs" +msgstr "Murupolku" + +#: .\apps\customers\presentation\templates\customers\child_form_page.html:6 +#: .\apps\customers\presentation\templates\customers\detail.html:5 +#: .\apps\customers\presentation\templates\customers\form.html:6 +#: .\apps\customers\presentation\templates\customers\list.html:2 +#: .\apps\customers\presentation\templates\customers\list.html:5 +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:5 +#: .\templates\base.html:57 +msgid "Customers" +msgstr "Asiakkaat" + +#: .\apps\customers\presentation\templates\customers\detail.html:10 +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:18 +#| msgid "Intern" +msgid "Internal" +msgstr "Sisäinen" + +#: .\apps\customers\presentation\templates\customers\detail.html:13 +#: .\apps\customers\presentation\templates\customers\form.html:8 +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:26 +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:23 +#| msgid "Edit user" +msgid "Edit" +msgstr "Muokkaa" + +#: .\apps\customers\presentation\templates\customers\detail.html:15 +msgid "Delete customer" +msgstr "Poista asiakas" + +#: .\apps\customers\presentation\templates\customers\detail.html:22 +msgid "Basic information" +msgstr "Perustiedot" + +#: .\apps\customers\presentation\templates\customers\detail.html:33 +msgid "" +"Internal work (administration, sales, training) is recorded on the jobs of " +"the internal customer. It cannot be deleted." +msgstr "Sisäinen työ (hallinto, myynti, koulutus) kirjataan sisäisen asiakkaan asiakastöille. Sisäistä asiakasta ei voi poistaa." + +#: .\apps\customers\presentation\templates\customers\detail.html:49 +msgid "Delete the customer?" +msgstr "Poistetaanko asiakas?" + +#: .\apps\customers\presentation\templates\customers\detail.html:50 +msgid "The customer is deleted permanently." +msgstr "Asiakas poistetaan pysyvästi." + +#: .\apps\customers\presentation\templates\customers\detail.html:51 +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:31 +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:35 +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:28 +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:32 +msgid "Delete" +msgstr "Poista" + +#: .\apps\customers\presentation\templates\customers\form.html:2 +#: .\apps\customers\presentation\templates\customers\form.html:11 +#| msgid "Edit user" +msgid "Edit customer" +msgstr "Muokkaa asiakasta" + +#: .\apps\customers\presentation\templates\customers\form.html:2 +#: .\apps\customers\presentation\templates\customers\form.html:8 +#: .\apps\customers\presentation\templates\customers\form.html:11 +#: .\apps\customers\presentation\templates\customers\list.html:6 +#| msgid "New user" +msgid "New customer" +msgstr "Uusi asiakas" + +#: .\apps\customers\presentation\templates\customers\form.html:26 +msgid "" +"The personal identity code is specially protected data. It is stored " +"encrypted and used only for invoicing." +msgstr "Henkilötunnus on erityisen suojattava tieto. Se tallennetaan salattuna ja sitä käytetään vain laskutukseen." + +#: .\apps\customers\presentation\templates\customers\form.html:29 +#: .\apps\customers\presentation\templates\customers\partials\child_form.html:18 +#: .\apps\users\presentation\templates\users\form.html:26 +#: .\templates\components\confirm_dialog.html:8 +msgid "Cancel" +msgstr "Peruuta" + +#: .\apps\customers\presentation\templates\customers\form.html:30 +#: .\apps\customers\presentation\templates\customers\partials\child_form.html:19 +#: .\apps\users\presentation\templates\users\form.html:27 +msgid "Save" +msgstr "Tallenna" + +#: .\apps\customers\presentation\templates\customers\list.html:9 +#| msgid "Filter users" +msgid "Filter customers" +msgstr "Suodata asiakkaita" + +#: .\apps\customers\presentation\templates\customers\list.html:16 +#: .\apps\users\presentation\templates\users\list.html:17 +msgid "Filter" +msgstr "Suodata" + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:4 +msgid "Billing units" +msgstr "Laskutusyksiköt" + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:7 +#: .\apps\customers\presentation\templates\customers\partials\child_form.html:10 +msgid "Add billing unit" +msgstr "Lisää laskutusyksikkö" + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:9 +msgid "Each billing unit is invoiced separately." +msgstr "Jokainen laskutusyksikkö laskutetaan omilla laskuillaan." + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:18 +msgid "E-invoice" +msgstr "Verkkolasku" + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:18 +msgid "operator" +msgstr "välittäjä" + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:28 +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:25 +msgid "In use in a job" +msgstr "Käytössä asiakastyössä" + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:33 +#, python-format +msgid "Delete billing unit %(name)s?" +msgstr "Poistetaanko laskutusyksikkö %(name)s?" + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:34 +msgid "The billing unit is deleted permanently." +msgstr "Laskutusyksikkö poistetaan pysyvästi." + +#: .\apps\customers\presentation\templates\customers\partials\billing_units.html:43 +msgid "No billing units yet." +msgstr "Ei vielä laskutusyksiköitä." + +#: .\apps\customers\presentation\templates\customers\partials\child_form.html:8 +msgid "Edit contact" +msgstr "Muokkaa yhteyshenkilöä" + +#: .\apps\customers\presentation\templates\customers\partials\child_form.html:8 +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:7 +msgid "Add contact" +msgstr "Lisää yhteyshenkilö" + +#: .\apps\customers\presentation\templates\customers\partials\child_form.html:10 +msgid "Edit billing unit" +msgstr "Muokkaa laskutusyksikköä" + +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:4 +msgid "Contacts" +msgstr "Yhteyshenkilöt" + +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:30 +#| msgid "Welcome, %(name)s" +msgid "Delete contact %(name)s?" +msgstr "Poistetaanko yhteyshenkilö %(name)s?" + +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:31 +msgid "The contact is deleted permanently." +msgstr "Yhteyshenkilö poistetaan pysyvästi." + +#: .\apps\customers\presentation\templates\customers\partials\contacts.html:40 +msgid "No contacts yet." +msgstr "Ei vielä yhteyshenkilöitä." + +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:2 +#| msgid "%(counter)s user found" +#| msgid_plural "%(counter)s users found" +msgid "%(counter)s customer found" +msgid_plural "%(counter)s customers found" +msgstr[0] "%(counter)s asiakas löytyi" +msgstr[1] "%(counter)s asiakasta löytyi" + +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:24 +#| msgid "No users match the filters." +msgid "No customers match the filters." +msgstr "Hakuehtoja vastaavia asiakkaita ei löytynyt." + +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:30 +#: .\apps\users\presentation\templates\users\partials\user_table.html:36 +msgid "Pages" +msgstr "Sivut" + +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:33 +#: .\apps\users\presentation\templates\users\partials\user_table.html:39 +msgid "Previous" +msgstr "Edellinen" + +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:35 +#: .\apps\users\presentation\templates\users\partials\user_table.html:41 +#, python-format +msgid "Page %(n)s / %(total)s" +msgstr "Sivu %(n)s / %(total)s" + +#: .\apps\customers\presentation\templates\customers\partials\customer_table.html:38 +#: .\apps\users\presentation\templates\users\partials\user_table.html:44 +msgid "Next" +msgstr "Seuraava" + +#: .\apps\customers\presentation\templates\customers\partials\personal_id.html:8 +msgid "Show personal identity code" +msgstr "Näytä henkilötunnus" + +#: .\apps\customers\presentation\templates\customers\partials\personal_id.html:12 +msgid "Not given" +msgstr "Ei annettu" + +#: .\apps\customers\presentation\views.py:82 +#| msgid "User created." +msgid "Customer created." +msgstr "Asiakas luotu." + +#: .\apps\customers\presentation\views.py:130 +#: .\apps\users\presentation\views.py:198 +msgid "Changes saved." +msgstr "Muutokset tallennettu." + +#: .\apps\customers\presentation\views.py:172 +#| msgid "User created." +msgid "Customer deleted." +msgstr "Asiakas poistettu." + +#: .\apps\customers\presentation\views.py:238 +#| msgid "Changes saved." +msgid "Contact saved." +msgstr "Yhteyshenkilö tallennettu." + +#: .\apps\customers\presentation\views.py:239 +msgid "Contact deleted." +msgstr "Yhteyshenkilö poistettu." + +#: .\apps\customers\presentation\views.py:250 +msgid "Billing unit saved." +msgstr "Laskutusyksikkö tallennettu." + +#: .\apps\customers\presentation\views.py:251 +msgid "Billing unit deleted." +msgstr "Laskutusyksikkö poistettu." + #: .\apps\users\infrastructure\password.py:15 #, python-format msgid "The password must be at least %(min)d characters long." msgstr "Salasanassa on oltava vähintään %(min)d merkkiä." -#: .\apps\users\infrastructure\password.py:21 +#: .\apps\users\infrastructure\password.py:23 msgid "The password must contain an upper case letter." msgstr "Salasanassa on oltava iso kirjain." -#: .\apps\users\infrastructure\password.py:22 +#: .\apps\users\infrastructure\password.py:28 msgid "The password must contain a lower case letter." msgstr "Salasanassa on oltava pieni kirjain." -#: .\apps\users\infrastructure\password.py:23 +#: .\apps\users\infrastructure\password.py:33 msgid "The password must contain a digit." msgstr "Salasanassa on oltava numero." -#: .\apps\users\infrastructure\password.py:26 +#: .\apps\users\infrastructure\password.py:38 msgid "The password must contain a special character." msgstr "Salasanassa on oltava erikoismerkki." -#: .\apps\users\infrastructure\password.py:36 +#: .\apps\users\infrastructure\password.py:48 #, python-format msgid "" "At least %(min)d characters, including upper and lower case letters, a digit " "and a special character." msgstr "Vähintään %(min)d merkkiä, joista on oltava iso ja pieni kirjain, numero ja erikoismerkki." -#: .\apps\users\presentation\forms.py:22 .\apps\users\presentation\forms.py:52 -#: .\apps\users\presentation\forms.py:66 -#: .\apps\users\presentation\templates\users\partials\user_table.html:9 -msgid "Email" -msgstr "Sähköposti" - #: .\apps\users\presentation\forms.py:25 msgid "Remember me" msgstr "Muista minut" @@ -64,57 +517,48 @@ msgstr "Sähköpostiosoite tai salasana on väärin." msgid "Too many login attempts. Try again in a few minutes." msgstr "Liian monta kirjautumisyritystä. Yritä uudelleen muutaman minuutin kuluttua." -#: .\apps\users\presentation\forms.py:65 -#: .\apps\users\presentation\templates\users\partials\user_table.html:8 -msgid "Name" -msgstr "Nimi" - -#: .\apps\users\presentation\forms.py:67 .\apps\users\presentation\forms.py:110 +#: .\apps\users\presentation\forms.py:72 .\apps\users\presentation\forms.py:115 #: .\apps\users\presentation\templates\users\partials\user_table.html:10 msgid "Role" msgstr "Rooli" -#: .\apps\users\presentation\forms.py:68 .\apps\users\presentation\forms.py:115 +#: .\apps\users\presentation\forms.py:73 .\apps\users\presentation\forms.py:120 #: .\apps\users\presentation\templates\users\partials\user_table.html:23 msgid "Active" msgstr "Aktiivinen" -#: .\apps\users\presentation\forms.py:70 +#: .\apps\users\presentation\forms.py:75 #: .\apps\users\presentation\templates\users\partials\user_table.html:12 msgid "Last day" msgstr "Viimeinen päivä" -#: .\apps\users\presentation\forms.py:73 +#: .\apps\users\presentation\forms.py:78 msgid "The intern cannot log in after this day." msgstr "Harjoittelija ei voi kirjautua tämän päivän jälkeen." -#: .\apps\users\presentation\forms.py:76 +#: .\apps\users\presentation\forms.py:81 #: .\apps\users\presentation\templates\users\partials\user_table.html:13 msgid "Supervisor" msgstr "Vastuuhenkilö" -#: .\apps\users\presentation\forms.py:87 +#: .\apps\users\presentation\forms.py:92 msgid "Choose a supervisor" msgstr "Valitse vastuuhenkilö" -#: .\apps\users\presentation\forms.py:108 -msgid "Search" -msgstr "Haku" - -#: .\apps\users\presentation\forms.py:110 +#: .\apps\users\presentation\forms.py:115 msgid "All roles" msgstr "Kaikki roolit" -#: .\apps\users\presentation\forms.py:113 +#: .\apps\users\presentation\forms.py:118 #: .\apps\users\presentation\templates\users\partials\user_table.html:11 msgid "Status" msgstr "Tila" -#: .\apps\users\presentation\forms.py:115 +#: .\apps\users\presentation\forms.py:120 msgid "All" msgstr "Kaikki" -#: .\apps\users\presentation\forms.py:115 +#: .\apps\users\presentation\forms.py:120 #: .\apps\users\presentation\templates\users\partials\user_table.html:24 msgid "Inactive" msgstr "Ei aktiivinen" @@ -139,14 +583,6 @@ msgstr "Harjoittelija" msgid "Subcontractor" msgstr "Alihankkija" -#: .\apps\users\presentation\labels.py:18 -msgid "Enter a name (at most 150 characters)." -msgstr "Anna nimi (enintään 150 merkkiä)." - -#: .\apps\users\presentation\labels.py:19 -msgid "Enter a valid email address." -msgstr "Anna kelvollinen sähköpostiosoite." - #: .\apps\users\presentation\labels.py:20 msgid "A user with this email address already exists." msgstr "Tällä sähköpostiosoitteella on jo käyttäjä." @@ -177,10 +613,6 @@ msgstr "Käyttäjä on aktiivisten harjoittelijoiden vastuuhenkilö. Vaihda ensi msgid "The user was not found." msgstr "Käyttäjää ei löytynyt." -#: .\apps\users\presentation\labels.py:31 -msgid "The change could not be saved." -msgstr "Muutosta ei voitu tallentaa." - #: .\apps\users\presentation\templates\users\email\password_link.txt:1 #, python-format msgid "Hello %(name)s," @@ -249,15 +681,11 @@ msgstr "Muokkaa käyttäjää" msgid "New user" msgstr "Uusi käyttäjä" -#: .\apps\users\presentation\templates\users\form.html:4 -msgid "Breadcrumbs" -msgstr "Murupolku" - #: .\apps\users\presentation\templates\users\form.html:5 #: .\apps\users\presentation\templates\users\list.html:2 #: .\apps\users\presentation\templates\users\list.html:5 #: .\apps\users\presentation\templates\users\partials\user_table.html:5 -#: .\templates\base.html:56 +#: .\templates\base.html:61 msgid "Users" msgstr "Käyttäjät" @@ -265,15 +693,6 @@ msgstr "Käyttäjät" msgid "An intern must have a last day and a supervisor." msgstr "Harjoittelijalla on oltava viimeinen päivä ja vastuuhenkilö." -#: .\apps\users\presentation\templates\users\form.html:26 -#: .\templates\components\confirm_dialog.html:8 -msgid "Cancel" -msgstr "Peruuta" - -#: .\apps\users\presentation\templates\users\form.html:27 -msgid "Save" -msgstr "Tallenna" - #: .\apps\users\presentation\templates\users\form.html:35 #: .\apps\users\presentation\templates\users\password_link_page.html:2 msgid "Password link" @@ -305,10 +724,6 @@ msgstr "Luo linkki" msgid "Filter users" msgstr "Suodata käyttäjiä" -#: .\apps\users\presentation\templates\users\list.html:17 -msgid "Filter" -msgstr "Suodata" - #: .\apps\users\presentation\templates\users\login.html:2 #: .\apps\users\presentation\templates\users\login.html:4 #: .\apps\users\presentation\templates\users\login.html:14 @@ -363,23 +778,6 @@ msgstr[1] "%(counter)s käyttäjää löytyi" msgid "No users match the filters." msgstr "Hakuehtoja vastaavia käyttäjiä ei löytynyt." -#: .\apps\users\presentation\templates\users\partials\user_table.html:36 -msgid "Pages" -msgstr "Sivut" - -#: .\apps\users\presentation\templates\users\partials\user_table.html:39 -msgid "Previous" -msgstr "Edellinen" - -#: .\apps\users\presentation\templates\users\partials\user_table.html:41 -#, python-format -msgid "Page %(n)s / %(total)s" -msgstr "Sivu %(n)s / %(total)s" - -#: .\apps\users\presentation\templates\users\partials\user_table.html:44 -msgid "Next" -msgstr "Seuraava" - #: .\apps\users\presentation\templates\users\password_link_page.html:4 #, python-format msgid "Password link for %(name)s" @@ -424,10 +822,6 @@ msgstr "Salasana on asetettu. Voit nyt kirjautua." msgid "User created." msgstr "Käyttäjä luotu." -#: .\apps\users\presentation\views.py:196 -msgid "Changes saved." -msgstr "Muutokset tallennettu." - #: .\templates\403.html:2 .\templates\403.html:4 msgid "Access denied" msgstr "Ei käyttöoikeutta" @@ -452,31 +846,23 @@ msgstr "Pyytämääsi sivua ei ole olemassa." msgid "Skip to content" msgstr "Siirry sisältöön" -#: .\templates\base.html:23 -msgid "Show menu" -msgstr "Näytä valikko" - -#: .\templates\base.html:26 +#: .\templates\base.html:28 msgid "Open menu" msgstr "Avaa valikko" -#: .\templates\base.html:38 +#: .\templates\base.html:40 .\templates\base.html:69 msgid "Log out" msgstr "Kirjaudu ulos" -#: .\templates\base.html:50 -msgid "Close menu" -msgstr "Sulje valikko" - -#: .\templates\base.html:51 +#: .\templates\base.html:53 msgid "Main menu" msgstr "Päävalikko" -#: .\templates\base.html:53 .\templates\home.html:2 +#: .\templates\base.html:55 .\templates\home.html:2 msgid "Home" msgstr "Etusivu" -#: .\templates\base.html:55 +#: .\templates\base.html:60 msgid "Administration" msgstr "Hallinto" @@ -495,5 +881,10 @@ msgstr "Tervetuloa, %(name)s" #: .\templates\home.html:5 msgid "The dashboard will be built in a later step." +msgstr "Työpöytä rakennetaan myöhemmässä vaiheessa." -msgstr "Työpöytä rakennetaan myöhemmässä vaiheessa." \ No newline at end of file +#~ msgid "Show menu" +#~ msgstr "Näytä valikko" + +#~ msgid "Close menu" +#~ msgstr "Sulje valikko" diff --git a/pyproject.toml b/pyproject.toml index 8135b52..05cfb7e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,6 +46,8 @@ source_modules = [ "apps.shared.application", "apps.users.domain", "apps.users.application", + "apps.customers.domain", + "apps.customers.application", ] forbidden_modules = ["django"] allow_indirect_imports = true @@ -65,13 +67,45 @@ ignore_imports = [ "apps.users.presentation.** -> apps.users.container", ] +[[tool.importlinter.contracts]] +name = "customers layers" +type = "layers" +layers = [ + "apps.customers.container", + "apps.customers.presentation", + "apps.customers.infrastructure", + "apps.customers.application", + "apps.customers.domain", +] +ignore_imports = ["apps.customers.presentation.** -> apps.customers.container"] + [[tool.importlinter.contracts]] name = "Presentation does not use infrastructure directly" type = "forbidden" -source_modules = ["apps.users.presentation"] -forbidden_modules = ["apps.users.infrastructure"] +source_modules = ["apps.users.presentation", "apps.customers.presentation"] +forbidden_modules = ["apps.users.infrastructure", "apps.customers.infrastructure"] allow_indirect_imports = true +[[tool.importlinter.contracts]] +name = "Modules use each other only through application interfaces" +type = "forbidden" +source_modules = ["apps.customers"] +forbidden_modules = [ + "apps.users.infrastructure", + "apps.users.container", + "apps.users.application", +] +ignore_imports = [ + # Integration tests may arrange data with another module's models. + "apps.customers.tests.** -> apps.users.infrastructure.**", +] + +[[tool.importlinter.contracts]] +name = "users does not depend on customers" +type = "forbidden" +source_modules = ["apps.users"] +forbidden_modules = ["apps.customers"] + [[tool.importlinter.contracts]] name = "shared layers" type = "layers" diff --git a/requirements.txt b/requirements.txt index 1c99eb9..22246b8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ Django>=5.2,<5.3 mysqlclient python-dotenv django-htmx +cryptography diff --git a/static/src/app.js b/static/src/app.js index b18dca5..da39d7d 100644 --- a/static/src/app.js +++ b/static/src/app.js @@ -7,10 +7,23 @@ localStorage.setItem(THEME_KEY, theme); }; + // Forms answer validation errors with 422; HTMX must swap those too so errors are shown. + if (window.htmx) { + window.htmx.config.responseHandling = [ + { code: "204", swap: false }, + { code: "[23]..", swap: true }, + { code: "422", swap: true }, + { code: "[45]..", swap: false, error: true }, + { code: "...", swap: true }, + ]; + } + + // After a swap: focus the first invalid field, else an element marked data-autofocus. document.addEventListener("htmx:afterSettle", function (event) { const target = event.detail.target; - if (!target) return; - const focusable = target.querySelector("[data-autofocus]"); + if (!target || !target.isConnected) return; + const focusable = + target.querySelector("[aria-invalid='true']") || target.querySelector("[data-autofocus]"); if (focusable) { focusable.focus(); } @@ -21,6 +34,17 @@ window.notify(event.detail.value || event.detail.message || ""); }); + // A dialog form saved: the server re-rendered the section (HX-Trigger-After-Settle "itemSaved"). + document.body.addEventListener("itemSaved", function (event) { + const detail = event.detail || {}; + document.querySelectorAll("dialog[open]").forEach(function (d) { d.close(); }); + if (detail.focus) { + const el = document.querySelector(detail.focus); + if (el) el.focus(); + } + if (detail.message) window.notify(detail.message); + }); + window.notify = function (message) { const live = document.getElementById("live-region"); if (live) { diff --git a/templates/base.html b/templates/base.html index 765d4c4..a44e1be 100644 --- a/templates/base.html +++ b/templates/base.html @@ -53,6 +53,9 @@