From 1ca03137fd915ced82150a40607e831e1adfe01f Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Sun, 29 Nov 2026 14:38:42 +0200 Subject: [PATCH] =?UTF-8?q?Vaihe=201/4:=20asiakasty=C3=B6t=20(numerointi,?= =?UTF-8?q?=20tagit,=20linkit,=20j=C3=A4senet,=20muutoshistoria)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Uusi jobs-moduuli: asiakastyön kentät ilman rahakenttiä, juokseva vuosinumero VVVV-NNNN (laskuririvi lukitaan), tagit, linkit dialogissa, jäsenet ja muutoshistoria nimiarvoineen. - Tilojen oikeudet: lasku luotu / laskutettu johto tai työn laskuttaja, arkistointi vain johto; alihankkija näkee vain jäsenyystyönsä eikä muokkaa. - Lista ja haku (numero, nimi, asiakas), suodattimet, omat työt oletuksena, arkistoidut piilossa, myöhässä tekstinä ja kuvakkeena. - Asiakasvalitsin hakuineen ja pikalisäyksineen (myös pikavastaanottoa varten). - Asiakkaan sivulle asiakastyöt-osio; valikkoon Asiakastyöt. - Lukurajapinnat muihin moduuleihin: UserQueries.choices, CustomerQueries.summaries, CatalogQueries.service_units; jobs.*-oikeudet. - Import-linter-sopimukset, käännökset, testit (domain, application, integraatio, selain) sekä määrittelyn ja CLAUDE.md:n päivitys. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 +- apps/catalog/application/queries.py | 4 + apps/catalog/infrastructure/queries.py | 6 + apps/customers/application/queries.py | 6 +- apps/customers/infrastructure/queries.py | 11 +- .../templates/customers/detail.html | 9 + apps/jobs/__init__.py | 0 apps/jobs/application/__init__.py | 0 apps/jobs/application/dto.py | 145 +++++ apps/jobs/application/queries.py | 42 ++ apps/jobs/application/use_cases.py | 320 +++++++++ apps/jobs/apps.py | 7 + apps/jobs/container.py | 89 +++ apps/jobs/domain/__init__.py | 0 apps/jobs/domain/entities.py | 126 ++++ apps/jobs/domain/enums.py | 53 ++ apps/jobs/domain/exceptions.py | 92 +++ apps/jobs/domain/repositories.py | 31 + apps/jobs/domain/status_rules.py | 31 + apps/jobs/domain/value_objects.py | 117 ++++ apps/jobs/infrastructure/__init__.py | 0 apps/jobs/infrastructure/orm.py | 156 +++++ apps/jobs/infrastructure/queries.py | 243 +++++++ apps/jobs/infrastructure/repositories.py | 176 +++++ apps/jobs/migrations/0001_initial.py | 145 +++++ apps/jobs/migrations/__init__.py | 0 apps/jobs/models.py | 22 + apps/jobs/presentation/__init__.py | 0 apps/jobs/presentation/forms.py | 220 +++++++ apps/jobs/presentation/labels.py | 104 +++ .../presentation/templates/jobs/detail.html | 86 +++ .../presentation/templates/jobs/form.html | 73 +++ .../templates/jobs/link_form_page.html | 15 + .../presentation/templates/jobs/list.html | 29 + .../jobs/partials/customer_fields.html | 5 + .../jobs/partials/customer_jobs.html | 24 + .../jobs/partials/customer_picker.html | 16 + .../jobs/partials/customer_results.html | 45 ++ .../jobs/partials/customer_search_input.html | 8 + .../templates/jobs/partials/history.html | 24 + .../templates/jobs/partials/job_table.html | 70 ++ .../templates/jobs/partials/late_badge.html | 1 + .../templates/jobs/partials/link_form.html | 17 + .../templates/jobs/partials/links.html | 38 ++ .../jobs/partials/priority_badge.html | 1 + .../templates/jobs/partials/status_badge.html | 1 + .../templates/jobs/partials/tags_input.html | 43 ++ .../presentation/templatetags/__init__.py | 0 .../presentation/templatetags/jobs_tags.py | 71 ++ apps/jobs/presentation/urls.py | 25 + apps/jobs/presentation/views.py | 424 ++++++++++++ apps/jobs/tests/__init__.py | 0 apps/jobs/tests/application/__init__.py | 0 apps/jobs/tests/application/test_use_cases.py | 236 +++++++ apps/jobs/tests/domain/__init__.py | 0 apps/jobs/tests/domain/test_domain.py | 153 +++++ apps/jobs/tests/fakes.py | 164 +++++ apps/jobs/tests/integration/__init__.py | 0 apps/jobs/tests/integration/test_jobs.py | 356 ++++++++++ apps/users/application/dto.py | 10 + apps/users/application/queries.py | 15 +- apps/users/domain/enums.py | 6 + apps/users/domain/permissions.py | 4 + apps/users/infrastructure/queries.py | 24 +- config/settings.py | 2 + config/urls.py | 1 + docs/maarittely.md | 6 +- locale/fi/LC_MESSAGES/django.po | 614 +++++++++++++++++- pyproject.toml | 54 ++ static/src/app.css | 11 + templates/base.html | 3 + tests/browser/test_jobs.py | 115 ++++ 72 files changed, 4907 insertions(+), 44 deletions(-) create mode 100644 apps/jobs/__init__.py create mode 100644 apps/jobs/application/__init__.py create mode 100644 apps/jobs/application/dto.py create mode 100644 apps/jobs/application/queries.py create mode 100644 apps/jobs/application/use_cases.py create mode 100644 apps/jobs/apps.py create mode 100644 apps/jobs/container.py create mode 100644 apps/jobs/domain/__init__.py create mode 100644 apps/jobs/domain/entities.py create mode 100644 apps/jobs/domain/enums.py create mode 100644 apps/jobs/domain/exceptions.py create mode 100644 apps/jobs/domain/repositories.py create mode 100644 apps/jobs/domain/status_rules.py create mode 100644 apps/jobs/domain/value_objects.py create mode 100644 apps/jobs/infrastructure/__init__.py create mode 100644 apps/jobs/infrastructure/orm.py create mode 100644 apps/jobs/infrastructure/queries.py create mode 100644 apps/jobs/infrastructure/repositories.py create mode 100644 apps/jobs/migrations/0001_initial.py create mode 100644 apps/jobs/migrations/__init__.py create mode 100644 apps/jobs/models.py create mode 100644 apps/jobs/presentation/__init__.py create mode 100644 apps/jobs/presentation/forms.py create mode 100644 apps/jobs/presentation/labels.py create mode 100644 apps/jobs/presentation/templates/jobs/detail.html create mode 100644 apps/jobs/presentation/templates/jobs/form.html create mode 100644 apps/jobs/presentation/templates/jobs/link_form_page.html create mode 100644 apps/jobs/presentation/templates/jobs/list.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/customer_fields.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/customer_jobs.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/customer_picker.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/customer_results.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/customer_search_input.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/history.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/job_table.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/late_badge.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/link_form.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/links.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/priority_badge.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/status_badge.html create mode 100644 apps/jobs/presentation/templates/jobs/partials/tags_input.html create mode 100644 apps/jobs/presentation/templatetags/__init__.py create mode 100644 apps/jobs/presentation/templatetags/jobs_tags.py create mode 100644 apps/jobs/presentation/urls.py create mode 100644 apps/jobs/presentation/views.py create mode 100644 apps/jobs/tests/__init__.py create mode 100644 apps/jobs/tests/application/__init__.py create mode 100644 apps/jobs/tests/application/test_use_cases.py create mode 100644 apps/jobs/tests/domain/__init__.py create mode 100644 apps/jobs/tests/domain/test_domain.py create mode 100644 apps/jobs/tests/fakes.py create mode 100644 apps/jobs/tests/integration/__init__.py create mode 100644 apps/jobs/tests/integration/test_jobs.py create mode 100644 tests/browser/test_jobs.py diff --git a/CLAUDE.md b/CLAUDE.md index 1226d5e..4d6692d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,12 +9,14 @@ 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 items 1–3 are done. +**Current state:** phase 1 items 1–4 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. - `catalog`: service units, services and work types (base data page `/catalog/`, permission `catalog.manage`), seeded by `catalog/migrations/0002_seed.py`. Rows are never deleted, only taken out of use; `CatalogQueries.work_type_options()` is the read API for tasks and time tracking. +- `jobs`: customer jobs without money fields (`/jobs/`, permissions `jobs.view`/`jobs.edit`/`jobs.archive`/`jobs.invoice_status`): yearly numbering `VVVV-NNNN` (`job_number_sequences`, locked with `select_for_update`), tags, links (dialog on the job page), members, change history and the list ("my jobs" by default). Who may set which status is `jobs.domain.status_rules`. `CustomerJobQueries` is the read API for later modules. The customer picker (`jobs/partials/customer_picker.html`, search and quick add by name) is meant for the quick intake too. +- **Cross-module wiring:** `jobs` reads customers, users and catalog through their application query protocols; only `apps/jobs/container.py` calls the other modules' containers (import-linter enforces it). Names shown in lists come from those queries in batches (`CustomerQueries.summaries`, `UserQueries.choices`, `CatalogQueries.service_units`), never from joins across modules. The customer page's job list is a jobs view loaded with `hx-get`, so customers does not depend on jobs. -`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 4: customer jobs. +`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 5: quick intake (`/jobs/quick`). ## Source of truth diff --git a/apps/catalog/application/queries.py b/apps/catalog/application/queries.py index 8df29e3..c7ac02a 100644 --- a/apps/catalog/application/queries.py +++ b/apps/catalog/application/queries.py @@ -18,6 +18,10 @@ class CatalogQueries(Protocol): """Active service units in order, the shared unit included (``is_shared``).""" ... + def service_units(self, ids: Iterable[int]) -> Sequence[ServiceUnitSummary]: + """The given service units in order, also inactive ones (for showing stored rows).""" + ... + def work_type_options(self, service_unit_ids: Iterable[int]) -> Sequence[WorkTypeOption]: """Selectable work types of the given units plus those of the shared unit.""" ... diff --git a/apps/catalog/infrastructure/queries.py b/apps/catalog/infrastructure/queries.py index 012ed3e..4bfff62 100644 --- a/apps/catalog/infrastructure/queries.py +++ b/apps/catalog/infrastructure/queries.py @@ -85,6 +85,12 @@ class DjangoCatalogQueries: for u in ServiceUnitModel.objects.filter(is_active=True) ] + def service_units(self, ids: Iterable[int]) -> Sequence[ServiceUnitSummary]: + return [ + ServiceUnitSummary(id=u.pk, name=u.name, is_shared=u.is_shared) + for u in ServiceUnitModel.objects.filter(pk__in=list(ids)) + ] + def work_type_options(self, service_unit_ids: Iterable[int]) -> Sequence[WorkTypeOption]: qs = ( WorkTypeModel.objects.filter(_SELECTABLE) diff --git a/apps/customers/application/queries.py b/apps/customers/application/queries.py index 78eca79..c6d9c7a 100644 --- a/apps/customers/application/queries.py +++ b/apps/customers/application/queries.py @@ -1,4 +1,4 @@ -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from typing import Protocol from apps.customers.application.dto import ( @@ -25,6 +25,10 @@ class CustomerQueries(Protocol): def get_summary(self, customer_id: int) -> CustomerSummary | None: ... + def summaries(self, customer_ids: Iterable[int]) -> dict[int, CustomerSummary]: + """Many customers at once, keyed by id (for lists in other modules).""" + ... + def get_details( self, customer_id: int, *, include_full_personal_id: bool = False ) -> CustomerDetails | None: ... diff --git a/apps/customers/infrastructure/queries.py b/apps/customers/infrastructure/queries.py index 64e56c2..c4ca013 100644 --- a/apps/customers/infrastructure/queries.py +++ b/apps/customers/infrastructure/queries.py @@ -1,4 +1,4 @@ -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from django.db.models import Q @@ -43,6 +43,15 @@ class DjangoCustomerQueries: model = CustomerModel.objects.filter(pk=customer_id).first() return _summary(model) if model else None + def summaries(self, customer_ids: Iterable[int]) -> dict[int, CustomerSummary]: + ids = set(customer_ids) + if not ids: + return {} + qs = CustomerModel.objects.filter(pk__in=ids) + return { + m.pk: _summary(m) for m in qs.only("id", "name", "type", "business_id", "is_internal") + } + def get_details( self, customer_id: int, *, include_full_personal_id: bool = False ) -> CustomerDetails | None: diff --git a/apps/customers/presentation/templates/customers/detail.html b/apps/customers/presentation/templates/customers/detail.html index a641d6a..fd0910f 100644 --- a/apps/customers/presentation/templates/customers/detail.html +++ b/apps/customers/presentation/templates/customers/detail.html @@ -35,6 +35,15 @@ {% include "customers/partials/billing_units.html" %} + {# The jobs module renders this section (no Python dependency from customers to jobs). #} +
+
+

{% translate "Customer jobs" %}

+

{% translate "Loading…" %}

+
+
+ diff --git a/apps/jobs/__init__.py b/apps/jobs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/application/__init__.py b/apps/jobs/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/application/dto.py b/apps/jobs/application/dto.py new file mode 100644 index 0000000..db3d2c1 --- /dev/null +++ b/apps/jobs/application/dto.py @@ -0,0 +1,145 @@ +from dataclasses import dataclass +from datetime import date, datetime +from decimal import Decimal + +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority +from apps.users.domain.enums import Role + + +@dataclass(frozen=True, slots=True) +class Actor: + """The signed-in user a use case acts for.""" + + user_id: int + role: Role + + +@dataclass(frozen=True, slots=True) +class CustomerJobData: + """Job form input (create and edit).""" + + name: str + customer_id: int + service_unit_ids: tuple[int, ...] + description: str = "" + starts_on: date | None = None + due_on: date | None = None + planned_from: date | None = None + planned_to: date | None = None + kind: JobKind = JobKind.ONE_OFF + status: JobStatus = JobStatus.TENTATIVE + priority: Priority = Priority.NORMAL + payment_basis: PaymentBasis = PaymentBasis.HOURLY + estimated_hours: Decimal | None = None + customer_reference: str = "" + instructions: str = "" + responsible_user_id: int | None = None + contact_user_id: int | None = None + customer_contact_id: int | None = None + biller_user_id: int | None = None + billing_unit_id: int | None = None + member_ids: tuple[int, ...] = () + tags: tuple[str, ...] = () + + +@dataclass(frozen=True, slots=True) +class CreatedJob: + id: int + number: str + + +@dataclass(frozen=True, slots=True) +class JobLinkData: + title: str + url: str + + +# --- Read models --------------------------------------------------------------------------------- + + +@dataclass(frozen=True, slots=True) +class Ref: + """Id and display name of a row of this or another module.""" + + id: int + name: str + + +@dataclass(frozen=True, slots=True) +class JobFilters: + search: str = "" + status: JobStatus | None = None + priority: Priority | None = None + service_unit_id: int | None = None + mine: bool = True + include_archived: bool = False + + +@dataclass(frozen=True, slots=True) +class JobListItem: + id: int + number: str + name: str + customer: Ref + status: JobStatus + priority: Priority + due_on: date | None + responsible: Ref | None + service_units: tuple[str, ...] + is_late: bool # past the due date and not done yet + + +@dataclass(frozen=True, slots=True) +class JobDetails: + id: int + number: str + name: str + description: str + customer: Ref + customer_is_internal: bool + service_units: tuple[Ref, ...] + starts_on: date | None + due_on: date | None + planned_from: date | None + planned_to: date | None + kind: JobKind + status: JobStatus + priority: Priority + payment_basis: PaymentBasis + estimated_hours: Decimal | None + customer_reference: str + instructions: str + responsible: Ref | None + contact_user: Ref | None + customer_contact: Ref | None + biller: Ref | None + billing_unit: Ref | None + members: tuple[Ref, ...] + tags: tuple[str, ...] + created_at: datetime + created_by: Ref | None + is_late: bool + + @property + def member_ids(self) -> tuple[int, ...]: + return tuple(m.id for m in self.members) + + @property + def service_unit_ids(self) -> tuple[int, ...]: + return tuple(u.id for u in self.service_units) + + +@dataclass(frozen=True, slots=True) +class JobChangeView: + field: str + old_value: str + new_value: str + user_name: str + created_at: datetime + + +@dataclass(frozen=True, slots=True) +class JobLinkView: + id: int + title: str + url: str diff --git a/apps/jobs/application/queries.py b/apps/jobs/application/queries.py new file mode 100644 index 0000000..8fc95cd --- /dev/null +++ b/apps/jobs/application/queries.py @@ -0,0 +1,42 @@ +from collections.abc import Sequence +from typing import Protocol + +from apps.jobs.application.dto import ( + Actor, + JobChangeView, + JobDetails, + JobFilters, + JobLinkView, + JobListItem, +) + + +class CustomerJobQueries(Protocol): + """Public read interface of the jobs module. + + A subcontractor sees only the jobs he or she is a member of (specification 16.4). + """ + + def list_jobs(self, filters: JobFilters, viewer: Actor) -> Sequence[JobListItem]: + """Newest first. Search matches the number, the name and the customer's name. + "Mine" = responsible, contact person, biller or member. Archived jobs only when + asked for (``include_archived`` or the archived status filter).""" + ... + + def jobs_for_customer(self, customer_id: int, viewer: Actor) -> Sequence[JobListItem]: + """All jobs of a customer, archived included, newest first.""" + ... + + def is_visible_to(self, job_id: int, viewer: Actor) -> bool: ... + + def get_details(self, job_id: int) -> JobDetails | None: ... + + def changes(self, job_id: int) -> Sequence[JobChangeView]: + """Change history, newest first.""" + ... + + def links(self, job_id: int) -> Sequence[JobLinkView]: ... + + def tag_names(self) -> Sequence[str]: + """Every tag in the shared list, alphabetically.""" + ... diff --git a/apps/jobs/application/use_cases.py b/apps/jobs/application/use_cases.py new file mode 100644 index 0000000..d3efd45 --- /dev/null +++ b/apps/jobs/application/use_cases.py @@ -0,0 +1,320 @@ +from collections.abc import Callable, Iterable +from datetime import date +from enum import StrEnum + +from apps.catalog.application.queries import CatalogQueries +from apps.customers.application.queries import CustomerQueries +from apps.jobs.application.dto import Actor, CreatedJob, CustomerJobData, JobLinkData +from apps.jobs.domain.entities import ChangeRecord, CustomerJob, JobFields, JobLink +from apps.jobs.domain.exceptions import ( + BillingUnitNotOfCustomer, + ContactNotOfCustomer, + CustomerJobNotFound, + JobLinkNotFound, + ServiceUnitNotSelectable, + StatusNotAllowed, + UnknownCustomer, + UserNotSelectable, +) +from apps.jobs.domain.repositories import CustomerJobRepository, JobLinkRepository +from apps.jobs.domain.status_rules import can_set_status +from apps.jobs.domain.value_objects import EstimatedHours, JobName, LinkTarget, TagName +from apps.shared.application.ports import Clock, UnitOfWork +from apps.users.application.queries import UserQueries +from apps.users.domain.enums import Role + + +def job_fields(data: CustomerJobData) -> JobFields: + """Build (and so validate) the domain fields before any transaction is opened.""" + return JobFields( + name=JobName(data.name), + customer_id=data.customer_id, + service_unit_ids=frozenset(data.service_unit_ids), + description=data.description, + starts_on=data.starts_on, + due_on=data.due_on, + planned_from=data.planned_from, + planned_to=data.planned_to, + kind=data.kind, + status=data.status, + priority=data.priority, + payment_basis=data.payment_basis, + estimated_hours=( + EstimatedHours(data.estimated_hours) if data.estimated_hours is not None else None + ), + customer_reference=data.customer_reference, + instructions=data.instructions, + responsible_user_id=data.responsible_user_id, + contact_user_id=data.contact_user_id, + customer_contact_id=data.customer_contact_id, + biller_user_id=data.biller_user_id, + billing_unit_id=data.billing_unit_id, + member_ids=frozenset(data.member_ids), + tags=tuple(TagName(t) for t in data.tags if t.strip()), + ) + + +# Change history field keys (presentation translates them) by JobFields attribute. +FIELD_KEYS: dict[str, str] = { + "name": "name", + "customer_id": "customer", + "service_unit_ids": "service_units", + "description": "description", + "starts_on": "starts_on", + "due_on": "due_on", + "planned_from": "planned_from", + "planned_to": "planned_to", + "kind": "kind", + "status": "status", + "priority": "priority", + "payment_basis": "payment_basis", + "estimated_hours": "estimated_hours", + "customer_reference": "customer_reference", + "instructions": "instructions", + "responsible_user_id": "responsible_user", + "contact_user_id": "contact_user", + "customer_contact_id": "customer_contact", + "biller_user_id": "biller_user", + "billing_unit_id": "billing_unit", + "member_ids": "members", + "tags": "tags", +} + +_ROLE_FIELDS = ( + ("responsible_user_id", "responsible_user"), + ("contact_user_id", "contact_user"), + ("biller_user_id", "biller_user"), +) + + +class _References: + """Checks the ids a job points to through the other modules' read interfaces.""" + + def __init__( + self, customers: CustomerQueries, users: UserQueries, catalog: CatalogQueries + ) -> None: + self.customers = customers + self.users = users + self.catalog = catalog + + def check(self, new: JobFields, previous: JobFields | None) -> None: + if self.customers.get_summary(new.customer_id) is None: + raise UnknownCustomer() + if new.customer_contact_id is not None and new.customer_contact_id not in { + c.id for c in self.customers.contacts(new.customer_id) + }: + raise ContactNotOfCustomer() + if new.billing_unit_id is not None and new.billing_unit_id not in { + u.id for u in self.customers.billing_units(new.customer_id) + }: + raise BillingUnitNotOfCustomer() + # A unit that has since been taken out of use may stay on the job. + kept = previous.service_unit_ids if previous else frozenset() + selectable = {u.id for u in self.catalog.active_service_units() if not u.is_shared} + if new.service_unit_ids - kept - selectable: + raise ServiceUnitNotSelectable() + self._check_users(new, previous) + + def _check_users(self, new: JobFields, previous: JobFields | None) -> None: + users = {u.id: u for u in self.users.choices(new.user_ids)} + for attr, field in _ROLE_FIELDS: + user_id = getattr(new, attr) + if user_id is None or (previous and getattr(previous, attr) == user_id): + continue + user = users.get(user_id) + if user is None or not user.is_active or user.role is Role.SUBCONTRACTOR: + raise UserNotSelectable(field) + kept = previous.member_ids if previous else frozenset() + for user_id in new.member_ids - kept: + user = users.get(user_id) + if user is None or not user.is_active: + raise UserNotSelectable("members") + + +class _ChangeFormatter: + """Turns changed fields into history rows with display values (names, not ids). + + Enum fields keep their key and dates their ISO form; presentation formats them. + """ + + def __init__( + self, customers: CustomerQueries, users: UserQueries, catalog: CatalogQueries + ) -> None: + self.customers = customers + self.users = users + self.catalog = catalog + + def records(self, old: JobFields, new: JobFields, attrs: Iterable[str]) -> list[ChangeRecord]: + result = [] + for attr in attrs: + show = self._display(attr, old, new) + result.append( + ChangeRecord( + field=FIELD_KEYS[attr], + old_value=show(getattr(old, attr)), + new_value=show(getattr(new, attr)), + ) + ) + return result + + def _display(self, attr: str, old: JobFields, new: JobFields) -> Callable[[object], str]: + names: dict[int, str] + if attr == "customer_id": + summaries = self.customers.summaries({old.customer_id, new.customer_id}) + names = {k: v.name for k, v in summaries.items()} + elif attr in ("responsible_user_id", "contact_user_id", "biller_user_id", "member_ids"): + names = {u.id: u.name for u in self.users.choices(old.user_ids | new.user_ids)} + elif attr == "service_unit_ids": + units = self.catalog.service_units(old.service_unit_ids | new.service_unit_ids) + names = {u.id: u.name for u in units} + order = [u.id for u in units] + return lambda value: ", ".join(names[i] for i in order if i in _ids(value)) + elif attr in ("customer_contact_id", "billing_unit_id"): + rows = ( + self.customers.contacts + if attr == "customer_contact_id" + else self.customers.billing_units + ) + names = {} + for customer_id in {old.customer_id, new.customer_id}: + names.update({row.id: row.name for row in rows(customer_id)}) + else: + return _plain + if attr == "member_ids": + return lambda value: ", ".join(sorted(names.get(i, "") for i in _ids(value))) + return lambda value: names.get(value, "") if isinstance(value, int) else "" + + +def _ids(value: object) -> frozenset[int]: + return value if isinstance(value, frozenset) else frozenset() + + +def _plain(value: object) -> str: + if value is None: + return "" + if isinstance(value, StrEnum): + return value.value + if isinstance(value, date): + return value.isoformat() + if isinstance(value, JobName): + return value.value + if isinstance(value, EstimatedHours): + return str(value.value) + if isinstance(value, tuple): # tags + return ", ".join(t.value for t in value if isinstance(t, TagName)) + return str(value) + + +class _JobUseCase: + def __init__( + self, + jobs: CustomerJobRepository, + uow: UnitOfWork, + customers: CustomerQueries, + users: UserQueries, + catalog: CatalogQueries, + clock: Clock, + ) -> None: + self.jobs = jobs + self.uow = uow + self.clock = clock + self.references = _References(customers, users, catalog) + self.formatter = _ChangeFormatter(customers, users, catalog) + + @staticmethod + def _check_status(actor: Actor, new: JobFields, previous: JobFields | None) -> None: + biller = previous.biller_user_id if previous else new.biller_user_id + if not can_set_status( + actor.role, + new.status, + current=previous.status if previous else None, + is_biller=biller == actor.user_id, + ): + raise StatusNotAllowed() + + +class CreateCustomerJob(_JobUseCase): + def execute(self, actor: Actor, data: CustomerJobData) -> CreatedJob: + details = job_fields(data) + self._check_status(actor, details, None) + with self.uow: + self.references.check(details, None) + number = self.jobs.next_number(self.clock.today().year) + job = CustomerJob.register(created_by=actor.user_id, details=details) + saved = self.jobs.save(job.numbered(number)) + assert saved.id is not None + return CreatedJob(id=saved.id, number=str(number)) + + +class UpdateCustomerJob(_JobUseCase): + def execute(self, actor: Actor, job_id: int, data: CustomerJobData) -> None: + details = job_fields(data) + with self.uow: + current = self.jobs.get(job_id) + if current is None: + raise CustomerJobNotFound() + self._check_status(actor, details, current.details) + self.references.check(details, current.details) + changed = details.changed_fields(current.details) + if not changed: + return + records = self.formatter.records(current.details, details, changed) + self.jobs.save(current.change_details(details)) + self.jobs.record_changes(job_id, actor.user_id, records) + + +class _LinkUseCase: + def __init__( + self, jobs: CustomerJobRepository, links: JobLinkRepository, uow: UnitOfWork + ) -> None: + self.jobs = jobs + self.links = links + self.uow = uow + + def _job(self, job_id: int) -> CustomerJob: + job = self.jobs.get(job_id) + if job is None: + raise CustomerJobNotFound() + return job + + def _owned(self, job_id: int, link_id: int) -> JobLink: + link = self.links.get(link_id) + if link is None or link.job_id != job_id: + raise JobLinkNotFound() + return link + + +class AddJobLink(_LinkUseCase): + def execute(self, actor: Actor, job_id: int, data: JobLinkData) -> int: + target = LinkTarget(title=data.title, url=data.url) + with self.uow: + self._job(job_id) + saved = self.links.save(JobLink(id=None, job_id=job_id, target=target)) + self.jobs.record_changes( + job_id, actor.user_id, [ChangeRecord("links", "", str(target))] + ) + assert saved.id is not None + return saved.id + + +class UpdateJobLink(_LinkUseCase): + def execute(self, actor: Actor, job_id: int, link_id: int, data: JobLinkData) -> None: + target = LinkTarget(title=data.title, url=data.url) + with self.uow: + current = self._owned(job_id, link_id) + if current.target == target: + return + self.links.save(JobLink(id=link_id, job_id=job_id, target=target)) + self.jobs.record_changes( + job_id, actor.user_id, [ChangeRecord("links", str(current.target), str(target))] + ) + + +class DeleteJobLink(_LinkUseCase): + def execute(self, actor: Actor, job_id: int, link_id: int) -> None: + with self.uow: + current = self._owned(job_id, link_id) + self.links.delete(link_id) + self.jobs.record_changes( + job_id, actor.user_id, [ChangeRecord("links", str(current.target), "")] + ) diff --git a/apps/jobs/apps.py b/apps/jobs/apps.py new file mode 100644 index 0000000..b2fee92 --- /dev/null +++ b/apps/jobs/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class JobsConfig(AppConfig): + name = "apps.jobs" + label = "jobs" + default_auto_field = "django.db.models.BigAutoField" diff --git a/apps/jobs/container.py b/apps/jobs/container.py new file mode 100644 index 0000000..c1290db --- /dev/null +++ b/apps/jobs/container.py @@ -0,0 +1,89 @@ +"""Composition root of the jobs module. + +Other modules' read interfaces and use cases come from their own containers; jobs never +touches their infrastructure. +""" + +from apps.catalog import container as catalog +from apps.catalog.application.queries import CatalogQueries +from apps.customers import container as customers +from apps.customers.application.queries import CustomerQueries +from apps.customers.application.use_cases import RegisterCustomer +from apps.jobs.application.queries import CustomerJobQueries +from apps.jobs.application.use_cases import ( + AddJobLink, + CreateCustomerJob, + DeleteJobLink, + UpdateCustomerJob, + UpdateJobLink, +) +from apps.jobs.infrastructure.queries import DjangoCustomerJobQueries +from apps.jobs.infrastructure.repositories import ( + DjangoCustomerJobRepository, + DjangoJobLinkRepository, +) +from apps.shared.infrastructure.clock import DjangoClock +from apps.shared.infrastructure.unit_of_work import DjangoUnitOfWork +from apps.users import container as users +from apps.users.application.queries import UserQueries + + +def customer_queries() -> CustomerQueries: + return customers.customer_queries() + + +def user_queries() -> UserQueries: + return users.user_queries() + + +def catalog_queries() -> CatalogQueries: + return catalog.catalog_queries() + + +def register_customer() -> RegisterCustomer: + """Quick add of a customer by name while recording a job.""" + return customers.register_customer() + + +def create_customer_job() -> CreateCustomerJob: + return CreateCustomerJob( + DjangoCustomerJobRepository(), + DjangoUnitOfWork(), + customer_queries(), + user_queries(), + catalog_queries(), + DjangoClock(), + ) + + +def update_customer_job() -> UpdateCustomerJob: + return UpdateCustomerJob( + DjangoCustomerJobRepository(), + DjangoUnitOfWork(), + customer_queries(), + user_queries(), + catalog_queries(), + DjangoClock(), + ) + + +def add_job_link() -> AddJobLink: + return AddJobLink(DjangoCustomerJobRepository(), DjangoJobLinkRepository(), DjangoUnitOfWork()) + + +def update_job_link() -> UpdateJobLink: + return UpdateJobLink( + DjangoCustomerJobRepository(), DjangoJobLinkRepository(), DjangoUnitOfWork() + ) + + +def delete_job_link() -> DeleteJobLink: + return DeleteJobLink( + DjangoCustomerJobRepository(), DjangoJobLinkRepository(), DjangoUnitOfWork() + ) + + +def job_queries() -> CustomerJobQueries: + return DjangoCustomerJobQueries( + customer_queries(), user_queries(), catalog_queries(), DjangoClock() + ) diff --git a/apps/jobs/domain/__init__.py b/apps/jobs/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/domain/entities.py b/apps/jobs/domain/entities.py new file mode 100644 index 0000000..548e638 --- /dev/null +++ b/apps/jobs/domain/entities.py @@ -0,0 +1,126 @@ +from dataclasses import dataclass, field, fields, replace +from datetime import date +from typing import Self + +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority +from apps.jobs.domain.exceptions import DueBeforeStart, PlannedRangeInvalid, ServiceUnitRequired +from apps.jobs.domain.value_objects import EstimatedHours, JobName, JobNumber, LinkTarget, TagName + + +@dataclass(frozen=True, slots=True) +class JobFields: + """The editable fields of a customer job (specification 5.1 and 5.6, no money yet). + + Rules: at least one service unit; the planned schedule and the start/due dates are + in order when both ends are given. + """ + + name: JobName + customer_id: int + service_unit_ids: frozenset[int] + description: str = "" + starts_on: date | None = None + due_on: date | None = None + planned_from: date | None = None + planned_to: date | None = None + kind: JobKind = JobKind.ONE_OFF + status: JobStatus = JobStatus.TENTATIVE + priority: Priority = Priority.NORMAL + payment_basis: PaymentBasis = PaymentBasis.HOURLY + estimated_hours: EstimatedHours | None = None + customer_reference: str = "" + instructions: str = "" + responsible_user_id: int | None = None + contact_user_id: int | None = None + customer_contact_id: int | None = None + biller_user_id: int | None = None + billing_unit_id: int | None = None + member_ids: frozenset[int] = field(default_factory=frozenset) + tags: tuple[TagName, ...] = () + + def __post_init__(self) -> None: + if not self.service_unit_ids: + raise ServiceUnitRequired() + if self.planned_from and self.planned_to and self.planned_to < self.planned_from: + raise PlannedRangeInvalid() + if self.starts_on and self.due_on and self.due_on < self.starts_on: + raise DueBeforeStart() + object.__setattr__(self, "description", self.description.strip()) + object.__setattr__(self, "customer_reference", " ".join(self.customer_reference.split())) + object.__setattr__(self, "instructions", self.instructions.strip()) + # Tags are unique regardless of case; keep the first spelling, sorted for comparison. + unique: dict[str, TagName] = {} + for tag in self.tags: + unique.setdefault(tag.key, tag) + object.__setattr__(self, "tags", tuple(sorted(unique.values(), key=lambda t: t.key))) + + @property + def user_ids(self) -> frozenset[int]: + """Everyone named on the job: role fields and members.""" + roles = {self.responsible_user_id, self.contact_user_id, self.biller_user_id} + return frozenset(u for u in roles if u is not None) | self.member_ids + + def changed_fields(self, previous: JobFields) -> list[str]: + """Names of the attributes that differ from ``previous``, in declaration order. + + Tags differing only in letter case are the same tags (the tag list ignores case). + """ + result = [] + for f in fields(self): + if f.name == "tags": + if [t.key for t in self.tags] != [t.key for t in previous.tags]: + result.append(f.name) + elif getattr(self, f.name) != getattr(previous, f.name): + result.append(f.name) + return result + + +@dataclass(frozen=True, slots=True) +class CustomerJob: + """A customer job. The number is given when it is first saved.""" + + id: int | None + number: JobNumber | None + created_by: int | None + details: JobFields + + @classmethod + def register(cls, *, created_by: int, details: JobFields) -> Self: + return cls(id=None, number=None, created_by=created_by, details=details) + + @classmethod + def reconstitute( + cls, *, id: int, number: JobNumber, created_by: int | None, details: JobFields + ) -> Self: + return cls(id=id, number=number, created_by=created_by, details=details) + + def change_details(self, details: JobFields) -> Self: + return replace(self, details=details) + + def numbered(self, number: JobNumber) -> Self: + return replace(self, number=number) + + def with_id(self, id: int) -> Self: + return replace(self, id=id) + + def is_member(self, user_id: int) -> bool: + return user_id in self.details.member_ids + + +@dataclass(frozen=True, slots=True) +class JobLink: + id: int | None + job_id: int + target: LinkTarget + + def with_id(self, id: int) -> Self: + return replace(self, id=id) + + +@dataclass(frozen=True, slots=True) +class ChangeRecord: + """One row of the change history (K27): field key and display values.""" + + field: str + old_value: str + new_value: str diff --git a/apps/jobs/domain/enums.py b/apps/jobs/domain/enums.py new file mode 100644 index 0000000..cb8ea60 --- /dev/null +++ b/apps/jobs/domain/enums.py @@ -0,0 +1,53 @@ +from enum import StrEnum + + +class JobKind(StrEnum): + """Duration / kind of a customer job (specification 5.2).""" + + SERVICE = "service" + ONE_OFF = "one_off" + FIXED_TERM = "fixed_term" + ONGOING = "ongoing" + + +class JobStatus(StrEnum): + """Status of a customer job; the order is the Kanban column order (specification 5.3).""" + + PROSPECT = "prospect" + TENTATIVE = "tentative" + QUOTE_REQUEST = "quote_request" + ORDER = "order" + IN_PRODUCTION = "in_production" + ON_HOLD = "on_hold" + DONE = "done" + INVOICED = "invoiced" + BILLED = "billed" + ARCHIVED = "archived" + + @property + def is_finished(self) -> bool: + """Done or later: such a job is no longer late.""" + return self in _FINISHED + + +_FINISHED = frozenset({JobStatus.DONE, JobStatus.INVOICED, JobStatus.BILLED, JobStatus.ARCHIVED}) + + +class Priority(StrEnum): + """Specification 5.4. Always shown as text too, never by colour alone.""" + + WAITING = "waiting" + NORMAL = "normal" + FIRST = "first" + URGENT = "urgent" + IMMEDIATE = "immediate" + + +class PaymentBasis(StrEnum): + """Specification 5.5.""" + + PRICE_LIST = "price_list" + FIXED_QUOTE = "fixed_quote" + MONTHLY_FEE = "monthly_fee" + HOURLY = "hourly" + NOT_BILLABLE = "not_billable" diff --git a/apps/jobs/domain/exceptions.py b/apps/jobs/domain/exceptions.py new file mode 100644 index 0000000..1e0de36 --- /dev/null +++ b/apps/jobs/domain/exceptions.py @@ -0,0 +1,92 @@ +from apps.shared.domain.exceptions import DomainError + + +class InvalidJobName(DomainError): + code = "invalid_job_name" + field = "name" + + +class InvalidJobNumber(DomainError): + code = "invalid_job_number" + + +class InvalidEstimatedHours(DomainError): + code = "invalid_estimated_hours" + field = "estimated_hours" + + +class InvalidTagName(DomainError): + code = "invalid_tag_name" + field = "tags" + + +class InvalidLinkUrl(DomainError): + code = "invalid_link_url" + field = "url" + + +class InvalidLinkTitle(DomainError): + code = "invalid_link_title" + field = "title" + + +class ServiceUnitRequired(DomainError): + code = "service_unit_required" + field = "service_units" + + +class ServiceUnitNotSelectable(DomainError): + code = "service_unit_not_selectable" + field = "service_units" + + +class PlannedRangeInvalid(DomainError): + """The planned schedule ends before it starts.""" + + code = "planned_range_invalid" + field = "planned_to" + + +class DueBeforeStart(DomainError): + code = "due_before_start" + field = "due_on" + + +class StatusNotAllowed(DomainError): + """The user's role may not set this status (specification 2.4, 16.4).""" + + code = "status_not_allowed" + field = "status" + + +class CustomerJobNotFound(DomainError): + code = "customer_job_not_found" + + +class JobLinkNotFound(DomainError): + code = "job_link_not_found" + + +class UnknownCustomer(DomainError): + code = "unknown_customer" + field = "customer" + + +class ContactNotOfCustomer(DomainError): + code = "contact_not_of_customer" + field = "customer_contact" + + +class BillingUnitNotOfCustomer(DomainError): + code = "billing_unit_not_of_customer" + field = "billing_unit" + + +class UserNotSelectable(DomainError): + """The user does not exist, is inactive or (in a role field) is a subcontractor.""" + + code = "user_not_selectable" + + def __init__(self, field: str) -> None: + super().__init__(field=field) + self.field = field diff --git a/apps/jobs/domain/repositories.py b/apps/jobs/domain/repositories.py new file mode 100644 index 0000000..249d8ff --- /dev/null +++ b/apps/jobs/domain/repositories.py @@ -0,0 +1,31 @@ +from collections.abc import Sequence +from typing import Protocol + +from apps.jobs.domain.entities import ChangeRecord, CustomerJob, JobLink +from apps.jobs.domain.value_objects import JobNumber + + +class CustomerJobRepository(Protocol): + def get(self, job_id: int) -> CustomerJob | None: ... + + def save(self, job: CustomerJob) -> CustomerJob: + """Insert or update, service units, members and tags included. New tag names + are added to the shared tag list.""" + ... + + def next_number(self, year: int) -> JobNumber: + """Reserve the next number of the year. Locks the year's counter, so call it + inside the use case's transaction; concurrent saves never share a number.""" + ... + + def record_changes( + self, job_id: int, user_id: int, changes: Sequence[ChangeRecord] + ) -> None: ... + + +class JobLinkRepository(Protocol): + def get(self, link_id: int) -> JobLink | None: ... + + def save(self, link: JobLink) -> JobLink: ... + + def delete(self, link_id: int) -> None: ... diff --git a/apps/jobs/domain/status_rules.py b/apps/jobs/domain/status_rules.py new file mode 100644 index 0000000..ea8cc82 --- /dev/null +++ b/apps/jobs/domain/status_rules.py @@ -0,0 +1,31 @@ +"""Who may set which status (specification 2.4, 5.3 and 16.4).""" + +from apps.jobs.domain.enums import JobStatus +from apps.users.domain.enums import Role + +_EDITORS = frozenset({Role.ADMIN, Role.MANAGEMENT, Role.EMPLOYEE, Role.INTERN}) +_LEADERS = frozenset({Role.ADMIN, Role.MANAGEMENT}) +_INVOICE_STATUSES = frozenset({JobStatus.INVOICED, JobStatus.BILLED}) + + +def can_set_status( + role: Role, target: JobStatus, *, current: JobStatus | None = None, is_biller: bool = False +) -> bool: + """Up to "done" every editor; "invoice created"/"invoiced" management or the job's + biller (an employee); "archived" management only. Keeping the current status is + always allowed.""" + if role not in _EDITORS: + return False + if target == current: + return True + if target in _INVOICE_STATUSES: + return role in _LEADERS or (is_biller and role is Role.EMPLOYEE) + if target is JobStatus.ARCHIVED: + return role in _LEADERS + return True + + +def allowed_statuses( + role: Role, *, current: JobStatus | None = None, is_biller: bool = False +) -> list[JobStatus]: + return [s for s in JobStatus if can_set_status(role, s, current=current, is_biller=is_biller)] diff --git a/apps/jobs/domain/value_objects.py b/apps/jobs/domain/value_objects.py new file mode 100644 index 0000000..0b36264 --- /dev/null +++ b/apps/jobs/domain/value_objects.py @@ -0,0 +1,117 @@ +import re +from dataclasses import dataclass +from decimal import Decimal, InvalidOperation +from typing import Self + +from apps.jobs.domain.exceptions import ( + InvalidEstimatedHours, + InvalidJobName, + InvalidJobNumber, + InvalidLinkTitle, + InvalidLinkUrl, + InvalidTagName, +) + +_NUMBER = re.compile(r"^(\d{4})-(\d{4,})$") + + +@dataclass(frozen=True, slots=True, order=True) +class JobNumber: + """Running job number ``2026-0042``; the sequence restarts every year (K23).""" + + year: int + sequence: int + + def __post_init__(self) -> None: + if not 2000 <= self.year <= 9999 or self.sequence < 1: + raise InvalidJobNumber() + + @classmethod + def parse(cls, value: str) -> Self: + match = _NUMBER.match(value.strip()) + if match is None: + raise InvalidJobNumber() + return cls(int(match.group(1)), int(match.group(2))) + + def __str__(self) -> str: + return f"{self.year}-{self.sequence:04d}" + + +def _collapse(value: str) -> str: + return " ".join(value.split()) + + +@dataclass(frozen=True, slots=True) +class JobName: + value: str + + MAX_LENGTH = 200 + + def __post_init__(self) -> None: + normalized = _collapse(self.value) + if not normalized or len(normalized) > self.MAX_LENGTH: + raise InvalidJobName() + object.__setattr__(self, "value", normalized) + + +@dataclass(frozen=True, slots=True) +class EstimatedHours: + """Hours as ``decimal(6,2)``: 0–9999.99.""" + + value: Decimal + + def __post_init__(self) -> None: + try: + hours = Decimal(self.value) + except InvalidOperation, TypeError, ValueError: + raise InvalidEstimatedHours() from None + if not hours.is_finite() or hours < 0 or hours >= 10_000: + raise InvalidEstimatedHours() + if hours != hours.quantize(Decimal("0.01")): + raise InvalidEstimatedHours() + object.__setattr__(self, "value", hours.quantize(Decimal("0.01"))) + + +@dataclass(frozen=True, slots=True, order=True) +class TagName: + value: str + + MAX_LENGTH = 50 + + def __post_init__(self) -> None: + normalized = _collapse(self.value) + if not normalized or len(normalized) > self.MAX_LENGTH or "," in normalized: + raise InvalidTagName() + object.__setattr__(self, "value", normalized) + + @property + def key(self) -> str: + """Tags are unique regardless of letter case.""" + return self.value.casefold() + + +_URL = re.compile(r"^https?://[^\s/$.?#][^\s]*$", re.IGNORECASE) + + +@dataclass(frozen=True, slots=True) +class LinkTarget: + """Title and URL of a link to files (Drive, Dropbox …); an empty title shows the URL.""" + + title: str + url: str + + MAX_TITLE = 200 + MAX_URL = 500 + + def __post_init__(self) -> None: + url = self.url.strip() + if not _URL.match(url) or len(url) > self.MAX_URL: + raise InvalidLinkUrl() + title = _collapse(self.title) or url[: self.MAX_TITLE] + if len(title) > self.MAX_TITLE: + raise InvalidLinkTitle() + object.__setattr__(self, "url", url) + object.__setattr__(self, "title", title) + + def __str__(self) -> str: + return self.url if self.title == self.url else f"{self.title} ({self.url})" diff --git a/apps/jobs/infrastructure/__init__.py b/apps/jobs/infrastructure/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/infrastructure/orm.py b/apps/jobs/infrastructure/orm.py new file mode 100644 index 0000000..757eecc --- /dev/null +++ b/apps/jobs/infrastructure/orm.py @@ -0,0 +1,156 @@ +from django.conf import settings +from django.db import models + +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority +from apps.shared.infrastructure.models import TimestampedModel + +_USER = settings.AUTH_USER_MODEL + + +class CustomerJobModel(TimestampedModel): + number = models.CharField(max_length=10, unique=True) + name = models.CharField(max_length=200) + description = models.TextField(blank=True) + # PROTECT: customers, contacts and billing units in use cannot be deleted (their + # generic deletion guard finds these relations; no cross-module checks needed). + customer = models.ForeignKey( + "customers.CustomerModel", on_delete=models.PROTECT, related_name="customer_jobs" + ) + starts_on = models.DateField(null=True, blank=True) + due_on = models.DateField(null=True, blank=True) + planned_from = models.DateField(null=True, blank=True) + planned_to = models.DateField(null=True, blank=True) + kind = models.CharField(max_length=20, default=JobKind.ONE_OFF.value) + status = models.CharField(max_length=20, default=JobStatus.TENTATIVE.value, db_index=True) + priority = models.CharField(max_length=20, default=Priority.NORMAL.value) + payment_basis = models.CharField(max_length=20, default=PaymentBasis.HOURLY.value) + estimated_hours = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) + customer_reference = models.CharField(max_length=100, blank=True) + instructions = models.TextField(blank=True) + responsible_user = models.ForeignKey( + _USER, on_delete=models.PROTECT, null=True, blank=True, related_name="+" + ) + contact_user = models.ForeignKey( + _USER, on_delete=models.PROTECT, null=True, blank=True, related_name="+" + ) + customer_contact = models.ForeignKey( + "customers.ContactModel", + on_delete=models.PROTECT, + null=True, + blank=True, + related_name="customer_jobs", + ) + biller_user = models.ForeignKey( + _USER, on_delete=models.PROTECT, null=True, blank=True, related_name="+" + ) + billing_unit = models.ForeignKey( + "customers.BillingUnitModel", + on_delete=models.PROTECT, + null=True, + blank=True, + related_name="customer_jobs", + ) + created_by = models.ForeignKey( + _USER, on_delete=models.PROTECT, null=True, blank=True, related_name="+" + ) + + class Meta: + db_table = "customer_jobs" + ordering = ["-id"] + + def __str__(self) -> str: + return f"{self.number} {self.name}" + + +class JobNumberSequenceModel(TimestampedModel): + year = models.PositiveSmallIntegerField(unique=True) + last_number = models.PositiveIntegerField(default=0) + + class Meta: + db_table = "job_number_sequences" + + +class CustomerJobServiceUnitModel(models.Model): + customer_job = models.ForeignKey( + CustomerJobModel, on_delete=models.CASCADE, related_name="service_unit_links" + ) + service_unit = models.ForeignKey( + "catalog.ServiceUnitModel", on_delete=models.PROTECT, related_name="customer_job_links" + ) + + class Meta: + db_table = "customer_job_service_unit" + constraints = [ + models.UniqueConstraint( + fields=["customer_job", "service_unit"], name="uniq_customer_job_service_unit" + ) + ] + + +class CustomerJobMemberModel(models.Model): + customer_job = models.ForeignKey( + CustomerJobModel, on_delete=models.CASCADE, related_name="member_links" + ) + user = models.ForeignKey(_USER, on_delete=models.PROTECT, related_name="+") + + class Meta: + db_table = "customer_job_members" + constraints = [ + models.UniqueConstraint( + fields=["customer_job", "user"], name="uniq_customer_job_member" + ) + ] + + +class TagModel(TimestampedModel): + name = models.CharField(max_length=50, unique=True) + + class Meta: + db_table = "tags" + ordering = ["name"] + + def __str__(self) -> str: + return self.name + + +class CustomerJobTagModel(models.Model): + customer_job = models.ForeignKey( + CustomerJobModel, on_delete=models.CASCADE, related_name="tag_links" + ) + tag = models.ForeignKey(TagModel, on_delete=models.PROTECT, related_name="job_links") + + class Meta: + db_table = "customer_job_tag" + constraints = [ + models.UniqueConstraint(fields=["customer_job", "tag"], name="uniq_customer_job_tag") + ] + + +class JobLinkModel(TimestampedModel): + customer_job = models.ForeignKey( + CustomerJobModel, on_delete=models.CASCADE, related_name="links" + ) + title = models.CharField(max_length=200) + url = models.CharField(max_length=500) + + class Meta: + db_table = "customer_job_links" + ordering = ["id"] + + def __str__(self) -> str: + return self.title + + +class JobChangeModel(models.Model): + customer_job = models.ForeignKey( + CustomerJobModel, on_delete=models.CASCADE, related_name="changes" + ) + user = models.ForeignKey(_USER, on_delete=models.PROTECT, related_name="+") + field = models.CharField(max_length=50) + old_value = models.TextField(blank=True) + new_value = models.TextField(blank=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + db_table = "customer_job_changes" + ordering = ["-created_at", "-id"] diff --git a/apps/jobs/infrastructure/queries.py b/apps/jobs/infrastructure/queries.py new file mode 100644 index 0000000..13e895c --- /dev/null +++ b/apps/jobs/infrastructure/queries.py @@ -0,0 +1,243 @@ +from collections.abc import Iterable, Sequence +from typing import Any + +from django.db.models import Q, QuerySet + +from apps.catalog.application.queries import CatalogQueries +from apps.customers.application.queries import CustomerQueries +from apps.jobs.application.dto import ( + Actor, + JobChangeView, + JobDetails, + JobFilters, + JobLinkView, + JobListItem, + Ref, +) +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority +from apps.jobs.infrastructure.orm import ( + CustomerJobMemberModel, + CustomerJobModel, + CustomerJobServiceUnitModel, + JobChangeModel, + JobLinkModel, + TagModel, +) +from apps.shared.application.ports import Clock +from apps.users.application.queries import UserQueries +from apps.users.domain.enums import Role + +_LIST_FIELDS = ( + "id", + "number", + "name", + "customer_id", + "status", + "priority", + "due_on", + "responsible_user_id", +) + + +def _visible(viewer: Actor) -> QuerySet[CustomerJobModel]: + qs = CustomerJobModel.objects.all() + if viewer.role is Role.SUBCONTRACTOR: + qs = qs.filter(member_links__user_id=viewer.user_id) + return qs + + +class DjangoCustomerJobQueries: + def __init__( + self, + customers: CustomerQueries, + users: UserQueries, + catalog: CatalogQueries, + clock: Clock, + ) -> None: + self.customers = customers + self.users = users + self.catalog = catalog + self.clock = clock + + # --- Lists ----------------------------------------------------------------------------------- + + def list_jobs(self, filters: JobFilters, viewer: Actor) -> Sequence[JobListItem]: + qs = _visible(viewer) + term = filters.search.strip() + if term: + customer_ids = [c.id for c in self.customers.list_customers(search=term)] + qs = qs.filter( + Q(number__icontains=term) + | Q(name__icontains=term) + | Q(customer_id__in=customer_ids) + ) + if filters.status is not None: + qs = qs.filter(status=filters.status.value) + elif not filters.include_archived: + qs = qs.exclude(status=JobStatus.ARCHIVED.value) + if filters.priority is not None: + qs = qs.filter(priority=filters.priority.value) + if filters.service_unit_id is not None: + qs = qs.filter(service_unit_links__service_unit_id=filters.service_unit_id) + if filters.mine: + me = viewer.user_id + qs = qs.filter( + Q(responsible_user_id=me) + | Q(contact_user_id=me) + | Q(biller_user_id=me) + | Q(member_links__user_id=me) + ) + return self._items(qs.distinct().order_by("-id").values(*_LIST_FIELDS)) + + def jobs_for_customer(self, customer_id: int, viewer: Actor) -> Sequence[JobListItem]: + qs = _visible(viewer).filter(customer_id=customer_id).distinct().order_by("-id") + return self._items(qs.values(*_LIST_FIELDS)) + + def _items(self, rows: Iterable[dict[str, Any]]) -> list[JobListItem]: + rows = list(rows) + if not rows: + return [] + job_ids = [r["id"] for r in rows] + customers = self.customers.summaries(r["customer_id"] for r in rows) + users = self._user_names(r["responsible_user_id"] for r in rows) + units_by_job = self._unit_names(job_ids) + today = self.clock.today() + items = [] + for r in rows: + status = JobStatus(r["status"]) + customer = customers.get(r["customer_id"]) + responsible = r["responsible_user_id"] + items.append( + JobListItem( + id=r["id"], + number=r["number"], + name=r["name"], + customer=Ref(r["customer_id"], customer.name if customer else ""), + status=status, + priority=Priority(r["priority"]), + due_on=r["due_on"], + responsible=Ref(responsible, users.get(responsible, "")) + if responsible + else None, + service_units=tuple(units_by_job.get(r["id"], ())), + is_late=_is_late(r["due_on"], status, today), + ) + ) + return items + + def _user_names(self, ids: Iterable[int | None]) -> dict[int, str]: + wanted = {i for i in ids if i is not None} + return {u.id: u.name for u in self.users.choices(wanted)} if wanted else {} + + def _unit_names(self, job_ids: list[int]) -> dict[int, list[str]]: + links = list( + CustomerJobServiceUnitModel.objects.filter(customer_job_id__in=job_ids).values_list( + "customer_job_id", "service_unit_id" + ) + ) + units = self.catalog.service_units({u for _, u in links}) + order = {u.id: (n, u.name) for n, u in enumerate(units)} + result: dict[int, list[tuple[int, str]]] = {} + for job_id, unit_id in links: + if unit_id in order: + result.setdefault(job_id, []).append(order[unit_id]) + return {job_id: [name for _, name in sorted(names)] for job_id, names in result.items()} + + # --- One job --------------------------------------------------------------------------------- + + def is_visible_to(self, job_id: int, viewer: Actor) -> bool: + return _visible(viewer).filter(pk=job_id).exists() + + def get_details(self, job_id: int) -> JobDetails | None: + m = CustomerJobModel.objects.filter(pk=job_id).first() + if m is None: + return None + member_ids = list( + CustomerJobMemberModel.objects.filter(customer_job=m).values_list("user_id", flat=True) + ) + role_ids = [m.responsible_user_id, m.contact_user_id, m.biller_user_id, m.created_by_id] + users = self._user_names([*role_ids, *member_ids]) + customer = self.customers.get_summary(m.customer_id) + unit_ids = CustomerJobServiceUnitModel.objects.filter(customer_job=m).values_list( + "service_unit_id", flat=True + ) + units = self.catalog.service_units(unit_ids) + contact = billing_unit = None + if m.customer_contact_id is not None: + names = {c.id: c.name for c in self.customers.contacts(m.customer_id)} + contact = Ref(m.customer_contact_id, names.get(m.customer_contact_id, "")) + if m.billing_unit_id is not None: + names = {u.id: u.name for u in self.customers.billing_units(m.customer_id)} + billing_unit = Ref(m.billing_unit_id, names.get(m.billing_unit_id, "")) + + def user(user_id: int | None) -> Ref | None: + return Ref(user_id, users.get(user_id, "")) if user_id is not None else None + + status = JobStatus(m.status) + return JobDetails( + id=m.pk, + number=m.number, + name=m.name, + description=m.description, + customer=Ref(m.customer_id, customer.name if customer else ""), + customer_is_internal=bool(customer and customer.is_internal), + service_units=tuple(Ref(u.id, u.name) for u in units), + starts_on=m.starts_on, + due_on=m.due_on, + planned_from=m.planned_from, + planned_to=m.planned_to, + kind=JobKind(m.kind), + status=status, + priority=Priority(m.priority), + payment_basis=PaymentBasis(m.payment_basis), + estimated_hours=m.estimated_hours, + customer_reference=m.customer_reference, + instructions=m.instructions, + responsible=user(m.responsible_user_id), + contact_user=user(m.contact_user_id), + customer_contact=contact, + biller=user(m.biller_user_id), + billing_unit=billing_unit, + members=tuple( + sorted((Ref(i, users.get(i, "")) for i in member_ids), key=lambda r: r.name) + ), + tags=tuple( + TagModel.objects.filter(job_links__customer_job=m) + .order_by("name") + .values_list("name", flat=True) + ), + created_at=m.created_at, + created_by=user(m.created_by_id), + is_late=_is_late(m.due_on, status, self.clock.today()), + ) + + def changes(self, job_id: int) -> Sequence[JobChangeView]: + rows = list( + JobChangeModel.objects.filter(customer_job_id=job_id).values( + "field", "old_value", "new_value", "user_id", "created_at" + ) + ) + names = self._user_names(r["user_id"] for r in rows) + return [ + JobChangeView( + field=r["field"], + old_value=r["old_value"], + new_value=r["new_value"], + user_name=names.get(r["user_id"], ""), + created_at=r["created_at"], + ) + for r in rows + ] + + def links(self, job_id: int) -> Sequence[JobLinkView]: + return [ + JobLinkView(id=m.pk, title=m.title, url=m.url) + for m in JobLinkModel.objects.filter(customer_job_id=job_id) + ] + + def tag_names(self) -> Sequence[str]: + return list(TagModel.objects.order_by("name").values_list("name", flat=True)) + + +def _is_late(due_on: Any, status: JobStatus, today: Any) -> bool: + return due_on is not None and due_on < today and not status.is_finished diff --git a/apps/jobs/infrastructure/repositories.py b/apps/jobs/infrastructure/repositories.py new file mode 100644 index 0000000..95b5794 --- /dev/null +++ b/apps/jobs/infrastructure/repositories.py @@ -0,0 +1,176 @@ +from collections.abc import Iterable, Sequence +from decimal import Decimal + +from django.db import IntegrityError, transaction + +from apps.jobs.domain.entities import ChangeRecord, CustomerJob, JobFields, JobLink +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority +from apps.jobs.domain.value_objects import ( + EstimatedHours, + JobName, + JobNumber, + LinkTarget, + TagName, +) +from apps.jobs.infrastructure.orm import ( + CustomerJobMemberModel, + CustomerJobModel, + CustomerJobServiceUnitModel, + CustomerJobTagModel, + JobChangeModel, + JobLinkModel, + JobNumberSequenceModel, + TagModel, +) + + +def _job_entity(model: CustomerJobModel) -> CustomerJob: + unit_ids = CustomerJobServiceUnitModel.objects.filter(customer_job=model).values_list( + "service_unit_id", flat=True + ) + member_ids = CustomerJobMemberModel.objects.filter(customer_job=model).values_list( + "user_id", flat=True + ) + tags = TagModel.objects.filter(job_links__customer_job=model).values_list("name", flat=True) + hours: Decimal | None = model.estimated_hours + details = JobFields( + name=JobName(model.name), + customer_id=model.customer_id, + service_unit_ids=frozenset(unit_ids), + description=model.description, + starts_on=model.starts_on, + due_on=model.due_on, + planned_from=model.planned_from, + planned_to=model.planned_to, + kind=JobKind(model.kind), + status=JobStatus(model.status), + priority=Priority(model.priority), + payment_basis=PaymentBasis(model.payment_basis), + estimated_hours=EstimatedHours(hours) if hours is not None else None, + customer_reference=model.customer_reference, + instructions=model.instructions, + responsible_user_id=model.responsible_user_id, + contact_user_id=model.contact_user_id, + customer_contact_id=model.customer_contact_id, + biller_user_id=model.biller_user_id, + billing_unit_id=model.billing_unit_id, + member_ids=frozenset(member_ids), + tags=tuple(TagName(t) for t in tags), + ) + return CustomerJob.reconstitute( + id=model.pk, + number=JobNumber.parse(model.number), + created_by=model.created_by_id, + details=details, + ) + + +def _tag_ids(tags: Iterable[TagName]) -> list[int]: + """Ids of the tags, adding new names to the shared list (case-insensitive match).""" + ids = [] + for tag in tags: + existing = TagModel.objects.filter(name__iexact=tag.value).first() + if existing is None: + try: + with transaction.atomic(): + existing = TagModel.objects.create(name=tag.value) + except IntegrityError: # added concurrently + existing = TagModel.objects.get(name__iexact=tag.value) + ids.append(existing.pk) + return ids + + +def _sync(model: type, job: CustomerJobModel, column: str, wanted: Iterable[int]) -> None: + wanted_ids = set(wanted) + links = model._default_manager.filter(customer_job=job) # type: ignore[attr-defined] + current = set(links.values_list(column, flat=True)) + links.filter(**{f"{column}__in": current - wanted_ids}).delete() + model._default_manager.bulk_create( # type: ignore[attr-defined] + [model(customer_job=job, **{column: i}) for i in sorted(wanted_ids - current)] + ) + + +class DjangoCustomerJobRepository: + def get(self, job_id: int) -> CustomerJob | None: + model = CustomerJobModel.objects.filter(pk=job_id).first() + return _job_entity(model) if model else None + + def save(self, job: CustomerJob) -> CustomerJob: + model = CustomerJobModel() if job.id is None else CustomerJobModel.objects.get(pk=job.id) + d = job.details + if job.number is not None: + model.number = str(job.number) + model.name = d.name.value + model.description = d.description + model.customer_id = d.customer_id + model.starts_on = d.starts_on + model.due_on = d.due_on + model.planned_from = d.planned_from + model.planned_to = d.planned_to + model.kind = d.kind.value + model.status = d.status.value + model.priority = d.priority.value + model.payment_basis = d.payment_basis.value + model.estimated_hours = d.estimated_hours.value if d.estimated_hours else None + model.customer_reference = d.customer_reference + model.instructions = d.instructions + model.responsible_user_id = d.responsible_user_id + model.contact_user_id = d.contact_user_id + model.customer_contact_id = d.customer_contact_id + model.biller_user_id = d.biller_user_id + model.billing_unit_id = d.billing_unit_id + if job.id is None: + model.created_by_id = job.created_by + model.save() + _sync(CustomerJobServiceUnitModel, model, "service_unit_id", d.service_unit_ids) + _sync(CustomerJobMemberModel, model, "user_id", d.member_ids) + _sync(CustomerJobTagModel, model, "tag_id", _tag_ids(d.tags)) + return job.with_id(model.pk) + + def next_number(self, year: int) -> JobNumber: + counter = JobNumberSequenceModel.objects.select_for_update().filter(year=year).first() + if counter is None: + try: + with transaction.atomic(): + JobNumberSequenceModel.objects.create(year=year, last_number=0) + except IntegrityError: # another save created the year's counter first + pass + counter = JobNumberSequenceModel.objects.select_for_update().get(year=year) + counter.last_number += 1 + counter.save(update_fields=["last_number", "updated_at"]) + return JobNumber(year, counter.last_number) + + def record_changes(self, job_id: int, user_id: int, changes: Sequence[ChangeRecord]) -> None: + JobChangeModel.objects.bulk_create( + JobChangeModel( + customer_job_id=job_id, + user_id=user_id, + field=c.field, + old_value=c.old_value, + new_value=c.new_value, + ) + for c in changes + ) + + +class DjangoJobLinkRepository: + def get(self, link_id: int) -> JobLink | None: + model = JobLinkModel.objects.filter(pk=link_id).first() + if model is None: + return None + return JobLink( + id=model.pk, + job_id=model.customer_job_id, + target=LinkTarget(title=model.title, url=model.url), + ) + + def save(self, link: JobLink) -> JobLink: + model = JobLinkModel() if link.id is None else JobLinkModel.objects.get(pk=link.id) + model.customer_job_id = link.job_id + model.title = link.target.title + model.url = link.target.url + model.save() + return link.with_id(model.pk) + + def delete(self, link_id: int) -> None: + JobLinkModel.objects.filter(pk=link_id).delete() diff --git a/apps/jobs/migrations/0001_initial.py b/apps/jobs/migrations/0001_initial.py new file mode 100644 index 0000000..44f6634 --- /dev/null +++ b/apps/jobs/migrations/0001_initial.py @@ -0,0 +1,145 @@ +# Generated by Django 5.2.19 on 2026-11-29 12:18 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('catalog', '0002_seed'), + ('customers', '0002_internal_customer'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='JobNumberSequenceModel', + 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)), + ('year', models.PositiveSmallIntegerField(unique=True)), + ('last_number', models.PositiveIntegerField(default=0)), + ], + options={ + 'db_table': 'job_number_sequences', + }, + ), + migrations.CreateModel( + name='TagModel', + 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=50, unique=True)), + ], + options={ + 'db_table': 'tags', + 'ordering': ['name'], + }, + ), + migrations.CreateModel( + name='CustomerJobModel', + 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)), + ('number', models.CharField(max_length=10, unique=True)), + ('name', models.CharField(max_length=200)), + ('description', models.TextField(blank=True)), + ('starts_on', models.DateField(blank=True, null=True)), + ('due_on', models.DateField(blank=True, null=True)), + ('planned_from', models.DateField(blank=True, null=True)), + ('planned_to', models.DateField(blank=True, null=True)), + ('kind', models.CharField(default='one_off', max_length=20)), + ('status', models.CharField(db_index=True, default='tentative', max_length=20)), + ('priority', models.CharField(default='normal', max_length=20)), + ('payment_basis', models.CharField(default='hourly', max_length=20)), + ('estimated_hours', models.DecimalField(blank=True, decimal_places=2, max_digits=6, null=True)), + ('customer_reference', models.CharField(blank=True, max_length=100)), + ('instructions', models.TextField(blank=True)), + ('biller_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)), + ('billing_unit', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='customer_jobs', to='customers.billingunitmodel')), + ('contact_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)), + ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)), + ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='customer_jobs', to='customers.customermodel')), + ('customer_contact', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='customer_jobs', to='customers.contactmodel')), + ('responsible_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'db_table': 'customer_jobs', + 'ordering': ['-id'], + }, + ), + migrations.CreateModel( + name='JobChangeModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('field', models.CharField(max_length=50)), + ('old_value', models.TextField(blank=True)), + ('new_value', models.TextField(blank=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('customer_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='changes', to='jobs.customerjobmodel')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'db_table': 'customer_job_changes', + 'ordering': ['-created_at', '-id'], + }, + ), + migrations.CreateModel( + name='JobLinkModel', + 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)), + ('title', models.CharField(max_length=200)), + ('url', models.CharField(max_length=500)), + ('customer_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='links', to='jobs.customerjobmodel')), + ], + options={ + 'db_table': 'customer_job_links', + 'ordering': ['id'], + }, + ), + migrations.CreateModel( + name='CustomerJobMemberModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)), + ('customer_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='member_links', to='jobs.customerjobmodel')), + ], + options={ + 'db_table': 'customer_job_members', + 'constraints': [models.UniqueConstraint(fields=('customer_job', 'user'), name='uniq_customer_job_member')], + }, + ), + migrations.CreateModel( + name='CustomerJobServiceUnitModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('customer_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='service_unit_links', to='jobs.customerjobmodel')), + ('service_unit', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='customer_job_links', to='catalog.serviceunitmodel')), + ], + options={ + 'db_table': 'customer_job_service_unit', + 'constraints': [models.UniqueConstraint(fields=('customer_job', 'service_unit'), name='uniq_customer_job_service_unit')], + }, + ), + migrations.CreateModel( + name='CustomerJobTagModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('customer_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tag_links', to='jobs.customerjobmodel')), + ('tag', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='job_links', to='jobs.tagmodel')), + ], + options={ + 'db_table': 'customer_job_tag', + 'constraints': [models.UniqueConstraint(fields=('customer_job', 'tag'), name='uniq_customer_job_tag')], + }, + ), + ] diff --git a/apps/jobs/migrations/__init__.py b/apps/jobs/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/models.py b/apps/jobs/models.py new file mode 100644 index 0000000..8135d09 --- /dev/null +++ b/apps/jobs/models.py @@ -0,0 +1,22 @@ +# Django discovers the module's ORM models through this file. +from apps.jobs.infrastructure.orm import ( + CustomerJobMemberModel, + CustomerJobModel, + CustomerJobServiceUnitModel, + CustomerJobTagModel, + JobChangeModel, + JobLinkModel, + JobNumberSequenceModel, + TagModel, +) + +__all__ = [ + "CustomerJobMemberModel", + "CustomerJobModel", + "CustomerJobServiceUnitModel", + "CustomerJobTagModel", + "JobChangeModel", + "JobLinkModel", + "JobNumberSequenceModel", + "TagModel", +] diff --git a/apps/jobs/presentation/__init__.py b/apps/jobs/presentation/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/presentation/forms.py b/apps/jobs/presentation/forms.py new file mode 100644 index 0000000..dcd4318 --- /dev/null +++ b/apps/jobs/presentation/forms.py @@ -0,0 +1,220 @@ +from collections.abc import Iterable, Sequence +from typing import Any + +from django import forms +from django.utils.translation import gettext_lazy as _ + +from apps.jobs.application.dto import CustomerJobData, JobFilters, JobLinkData +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority +from apps.jobs.presentation.labels import ( + KIND_LABELS, + PAYMENT_BASIS_LABELS, + PRIORITY_LABELS, + STATUS_LABELS, +) +from apps.shared.presentation.forms import DaisyFormMixin + +Choices = Sequence[tuple[Any, Any]] + + +def _choices(labels: dict[Any, Any], only: Iterable[Any] | None = None) -> list[tuple[str, Any]]: + allowed = set(only) if only is not None else None + return [(k.value, v) for k, v in labels.items() if allowed is None or k in allowed] + + +class _DateInput(forms.DateInput): + input_type = "date" + + def __init__(self) -> None: + super().__init__(format="%Y-%m-%d") + + +def _optional_id(label: Any) -> forms.TypedChoiceField: + return forms.TypedChoiceField(label=label, coerce=int, empty_value=None, required=False) + + +class TagsField(forms.Field): + """Any number of tag names from hidden inputs named ``tags`` (the tag editor adds them). + + Comma separated values are split, so the plain text fallback works too. + """ + + widget = forms.MultipleHiddenInput + + def to_python(self, value: Any) -> list[str]: + if not value: + return [] + values = [value] if isinstance(value, str) else list(value) + names: list[str] = [] + for item in values: + names.extend(part.strip() for part in str(item).split(",")) + return [n for n in names if n] + + +class CustomerJobForm(DaisyFormMixin, forms.Form): + # The customer is chosen in the customer picker (radio buttons named "customer"). + customer = forms.IntegerField( + label=_("Customer"), + widget=forms.HiddenInput, + error_messages={"required": _("Choose a customer."), "invalid": _("Choose a customer.")}, + ) + name = forms.CharField(label=_("Name"), max_length=200) + description = forms.CharField( + label=_("Description"), required=False, widget=forms.Textarea(attrs={"rows": 4}) + ) + service_units = forms.TypedMultipleChoiceField( + label=_("Service units"), + coerce=int, + widget=forms.CheckboxSelectMultiple, + error_messages={"required": _("Choose at least one service unit.")}, + ) + kind = forms.ChoiceField(label=_("Kind"), choices=_choices(KIND_LABELS)) + status = forms.ChoiceField(label=_("Status")) + priority = forms.ChoiceField(label=_("Priority"), choices=_choices(PRIORITY_LABELS)) + payment_basis = forms.ChoiceField( + label=_("Payment basis"), choices=_choices(PAYMENT_BASIS_LABELS) + ) + starts_on = forms.DateField(label=_("Start date"), required=False, widget=_DateInput()) + due_on = forms.DateField(label=_("Due date"), required=False, widget=_DateInput()) + planned_from = forms.DateField(label=_("Planned start"), required=False, widget=_DateInput()) + planned_to = forms.DateField(label=_("Planned end"), required=False, widget=_DateInput()) + estimated_hours = forms.DecimalField( + label=_("Estimated hours"), + required=False, + min_value=0, + max_digits=6, + decimal_places=2, + localize=True, + widget=forms.TextInput(attrs={"inputmode": "decimal"}), + ) + customer_reference = forms.CharField( + label=_("Customer reference (PO)"), max_length=100, required=False + ) + instructions = forms.CharField( + label=_("Instructions"), + required=False, + widget=forms.Textarea(attrs={"rows": 4}), + help_text=_("Things to note about the job; subcontractors see them too."), + ) + responsible_user = _optional_id(_("Responsible person")) + contact_user = _optional_id(_("Contact person")) + customer_contact = _optional_id(_("Customer's contact")) + biller_user = _optional_id(_("Biller")) + billing_unit = _optional_id(_("Billing unit")) + members = forms.TypedMultipleChoiceField( + label=_("Other members"), + coerce=int, + required=False, + widget=forms.CheckboxSelectMultiple, + help_text=_("The job shows in their own jobs. Subcontractors see only such jobs."), + ) + tags = TagsField(label=_("Tags"), required=False) + + def __init__( + self, + *args: Any, + service_unit_choices: Choices = (), + user_choices: Choices = (), + member_choices: Choices = (), + contact_choices: Choices = (), + billing_unit_choices: Choices = (), + statuses: Iterable[JobStatus] = (), + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + empty = [("", _("Not chosen"))] + fields: Any = self.fields + fields["service_units"].choices = list(service_unit_choices) + fields["members"].choices = list(member_choices) + for name in ("responsible_user", "contact_user", "biller_user"): + fields[name].choices = [*empty, *user_choices] + fields["customer_contact"].choices = [*empty, *contact_choices] + fields["billing_unit"].choices = [*empty, *billing_unit_choices] + fields["status"].choices = _choices(STATUS_LABELS, statuses) + + def to_dto(self) -> CustomerJobData: + d = self.cleaned_data + return CustomerJobData( + name=d["name"], + customer_id=d["customer"], + service_unit_ids=tuple(d["service_units"]), + description=d["description"], + starts_on=d["starts_on"], + due_on=d["due_on"], + planned_from=d["planned_from"], + planned_to=d["planned_to"], + kind=JobKind(d["kind"]), + status=JobStatus(d["status"]), + priority=Priority(d["priority"]), + payment_basis=PaymentBasis(d["payment_basis"]), + estimated_hours=d["estimated_hours"], + customer_reference=d["customer_reference"], + instructions=d["instructions"], + responsible_user_id=d["responsible_user"], + contact_user_id=d["contact_user"], + customer_contact_id=d["customer_contact"], + biller_user_id=d["biller_user"], + billing_unit_id=d["billing_unit"], + member_ids=tuple(d["members"]), + tags=tuple(d["tags"]), + ) + + +class JobLinkForm(DaisyFormMixin, forms.Form): + title = forms.CharField( + label=_("Title"), + max_length=200, + required=False, + help_text=_("For example: Material folder. Empty shows the address."), + ) + url = forms.CharField( + label=_("Web address"), + max_length=500, + widget=forms.URLInput(attrs={"placeholder": "https://"}), + ) + + def to_dto(self) -> JobLinkData: + return JobLinkData(title=self.cleaned_data["title"], url=self.cleaned_data["url"]) + + +SCOPE_MINE = "mine" +SCOPE_ALL = "all" + + +class JobFilterForm(DaisyFormMixin, forms.Form): + q = forms.CharField(label=_("Search"), required=False, help_text=_("Number, name or customer")) + # A select rather than a checkbox, so "my jobs" can be the default of a GET form. + scope = forms.ChoiceField( + label=_("Show"), + required=False, + choices=[(SCOPE_MINE, _("My jobs")), (SCOPE_ALL, _("All jobs"))], + ) + status = forms.ChoiceField(label=_("Status"), required=False) + priority = forms.ChoiceField( + label=_("Priority"), + required=False, + choices=[("", _("All priorities")), *_choices(PRIORITY_LABELS)], + ) + service_unit = forms.TypedChoiceField( + label=_("Service unit"), required=False, coerce=int, empty_value=None + ) + archived = forms.BooleanField(label=_("Show archived jobs"), required=False) + + def __init__(self, *args: Any, service_unit_choices: Choices = (), **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + fields: Any = self.fields + fields["status"].choices = [("", _("All statuses")), *_choices(STATUS_LABELS)] + fields["service_unit"].choices = [("", _("All service units")), *service_unit_choices] + + def to_filters(self) -> JobFilters: + if not self.is_valid(): + return JobFilters() + d = self.cleaned_data + return JobFilters( + search=d["q"].strip(), + status=JobStatus(d["status"]) if d["status"] else None, + priority=Priority(d["priority"]) if d["priority"] else None, + service_unit_id=d["service_unit"], + mine=d["scope"] != SCOPE_ALL, + include_archived=bool(d["archived"]), + ) diff --git a/apps/jobs/presentation/labels.py b/apps/jobs/presentation/labels.py new file mode 100644 index 0000000..fea0322 --- /dev/null +++ b/apps/jobs/presentation/labels.py @@ -0,0 +1,104 @@ +from django.utils.translation import gettext_lazy as _ + +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority + +STATUS_LABELS = { + JobStatus.PROSPECT: _("Prospect"), + JobStatus.TENTATIVE: _("Tentative"), + JobStatus.QUOTE_REQUEST: _("Quote request"), + JobStatus.ORDER: _("Order"), + JobStatus.IN_PRODUCTION: _("In production"), + JobStatus.ON_HOLD: _("On hold"), + JobStatus.DONE: _("Done"), + JobStatus.INVOICED: _("Invoice created"), + JobStatus.BILLED: _("Invoiced"), + JobStatus.ARCHIVED: _("Archived"), +} + +PRIORITY_LABELS = { + Priority.WAITING: _("Waiting"), + Priority.NORMAL: _("Normal"), + Priority.FIRST: _("First"), + Priority.URGENT: _("Urgent"), + Priority.IMMEDIATE: _("Immediately"), +} + +# daisyUI badge classes; the text and icon always carry the meaning too. +PRIORITY_CLASSES = { + Priority.WAITING: "badge-info badge-soft", + Priority.NORMAL: "badge-success badge-soft", + Priority.FIRST: "badge-warning badge-soft", + Priority.URGENT: "badge-error badge-soft", + Priority.IMMEDIATE: "badge-error priority-immediate", +} + +KIND_LABELS = { + JobKind.SERVICE: _("Service job"), + JobKind.ONE_OFF: _("One-off"), + JobKind.FIXED_TERM: _("Fixed-term"), + JobKind.ONGOING: _("Ongoing"), +} + +PAYMENT_BASIS_LABELS = { + PaymentBasis.PRICE_LIST: _("Fixed price list"), + PaymentBasis.FIXED_QUOTE: _("Fixed, based on a quote"), + PaymentBasis.MONTHLY_FEE: _("Fixed monthly fee"), + PaymentBasis.HOURLY: _("Hourly"), + PaymentBasis.NOT_BILLABLE: _("Not billable"), +} + +ENUM_LABELS = { + "status": STATUS_LABELS, + "priority": PRIORITY_LABELS, + "kind": KIND_LABELS, + "payment_basis": PAYMENT_BASIS_LABELS, +} + +# Change history field names (keys from the application layer's FIELD_KEYS, plus links). +FIELD_LABELS = { + "name": _("Name"), + "customer": _("Customer"), + "service_units": _("Service units"), + "description": _("Description"), + "starts_on": _("Start date"), + "due_on": _("Due date"), + "planned_from": _("Planned start"), + "planned_to": _("Planned end"), + "kind": _("Kind"), + "status": _("Status"), + "priority": _("Priority"), + "payment_basis": _("Payment basis"), + "estimated_hours": _("Estimated hours"), + "customer_reference": _("Customer reference (PO)"), + "instructions": _("Instructions"), + "responsible_user": _("Responsible person"), + "contact_user": _("Contact person"), + "customer_contact": _("Customer's contact"), + "biller_user": _("Biller"), + "billing_unit": _("Billing unit"), + "members": _("Other members"), + "tags": _("Tags"), + "links": _("Links"), +} + +DATE_FIELDS = frozenset({"starts_on", "due_on", "planned_from", "planned_to"}) + +ERROR_MESSAGES = { + "invalid_job_name": _("Enter a name (at most 200 characters)."), + "invalid_estimated_hours": _("Enter hours between 0 and 9999.99."), + "invalid_tag_name": _("A tag is at most 50 characters and contains no commas."), + "invalid_link_url": _("Enter a web address starting with http:// or https://."), + "invalid_link_title": _("Enter a title of at most 200 characters."), + "service_unit_required": _("Choose at least one service unit."), + "service_unit_not_selectable": _("A chosen service unit is no longer in use."), + "planned_range_invalid": _("The planned end cannot be before the planned start."), + "due_before_start": _("The due date cannot be before the start date."), + "status_not_allowed": _("You are not allowed to set this status."), + "customer_job_not_found": _("The job was not found."), + "job_link_not_found": _("The link was not found."), + "unknown_customer": _("Choose a customer."), + "contact_not_of_customer": _("Choose a contact of the selected customer."), + "billing_unit_not_of_customer": _("Choose a billing unit of the selected customer."), + "user_not_selectable": _("Choose an active user."), + "*": _("The change could not be saved."), +} diff --git a/apps/jobs/presentation/templates/jobs/detail.html b/apps/jobs/presentation/templates/jobs/detail.html new file mode 100644 index 0000000..b138a06 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/detail.html @@ -0,0 +1,86 @@ +{% extends "base.html" %}{% load jobs_tags %} +{% block title %}{{ job.number }} {{ job.name }}{% endblock %} +{% block content %} + +
+
+

{{ job.number }}

+

{{ job.name }}

+
+ {% include "jobs/partials/status_badge.html" with status=job.status %} + {% include "jobs/partials/priority_badge.html" with priority=job.priority %} + {% if job.is_late %}{% include "jobs/partials/late_badge.html" %}{% endif %} +
+
+ {% if can_edit %}{% translate "Edit" %}{% endif %} +
+ +
+
+
+

{% translate "Basic information" %}

+
+
{% translate "Customer" %}
+
{% if can_see_customer %}{{ job.customer.name }}{% else %}{{ job.customer.name }}{% endif %}
+
{% translate "Service units" %}
+
{% for u in job.service_units %}{{ u.name }}{% if not forloop.last %}, {% endif %}{% empty %}–{% endfor %}
+
{% translate "Kind" %}
{{ job.kind|kind_label }}
+
{% translate "Payment basis" %}
{{ job.payment_basis|payment_basis_label }}
+
{% translate "Estimated hours" %}
{% if job.estimated_hours is not None %}{{ job.estimated_hours }} h{% else %}–{% endif %}
+
{% translate "Customer reference (PO)" %}
{{ job.customer_reference|default:"–" }}
+
{% translate "Tags" %}
+
{% if job.tags %}
    {% for t in job.tags %}
  • {{ t }}
  • {% endfor %}
{% else %}–{% endif %}
+
{% translate "Created" %}
+
{{ job.created_at|date:"SHORT_DATE_FORMAT" }}{% if job.created_by %}, {{ job.created_by.name }}{% endif %}
+
+
+
+ +
+
+

{% translate "Schedule" %}

+
+
{% translate "Start date" %}
{{ job.starts_on|date:"SHORT_DATE_FORMAT"|default:"–" }}
+
{% translate "Due date" %}
+
{{ job.due_on|date:"SHORT_DATE_FORMAT"|default:"–" }}{% if job.is_late %} {% include "jobs/partials/late_badge.html" %}{% endif %}
+
{% translate "Planned schedule" %}
+
{% if job.planned_from or job.planned_to %}{{ job.planned_from|date:"SHORT_DATE_FORMAT"|default:"…" }} – {{ job.planned_to|date:"SHORT_DATE_FORMAT"|default:"…" }}{% else %}–{% endif %}
+
+
+
+ +
+
+

{% translate "People and invoicing" %}

+
+
{% translate "Responsible person" %}
{{ job.responsible.name|default:"–" }}
+
{% translate "Contact person" %}
{{ job.contact_user.name|default:"–" }}
+
{% translate "Customer's contact" %}
{{ job.customer_contact.name|default:"–" }}
+
{% translate "Biller" %}
{{ job.biller.name|default:"–" }}
+
{% translate "Billing unit" %}
{{ job.billing_unit.name|default:"–" }}
+
{% translate "Other members" %}
+
{% for m in job.members %}{{ m.name }}{% if not forloop.last %}, {% endif %}{% empty %}–{% endfor %}
+
+
+
+ + {% include "jobs/partials/links.html" %} + +
+
+

{% translate "Description" %}

+

{{ job.description|default:"–" }}

+

{% translate "Instructions" %}

+

{{ job.instructions|default:"–" }}

+
+
+
+ +
{% include "jobs/partials/history.html" %}
+ + + + +{% endblock %} diff --git a/apps/jobs/presentation/templates/jobs/form.html b/apps/jobs/presentation/templates/jobs/form.html new file mode 100644 index 0000000..d939e0e --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/form.html @@ -0,0 +1,73 @@ +{% extends "base.html" %} +{% block title %}{% if job %}{% translate "Edit job" %}{% else %}{% translate "New job" %}{% endif %}{% endblock %} +{% block content %} + +

{% if job %}{% blocktranslate with number=job.number %}Edit job {{ number }}{% endblocktranslate %}{% else %}{% translate "New job" %}{% endif %}

+ +
+ {% csrf_token %} + {% include "components/non_field_errors.html" %} + +
+
+

{% translate "Basic information" %}

+ {% include "jobs/partials/customer_picker.html" %} + {{ form.name.as_field_group }} + {{ form.description.as_field_group }} + {{ form.service_units.as_field_group }} +
+ {{ form.status.as_field_group }} + {{ form.priority.as_field_group }} + {{ form.kind.as_field_group }} + {{ form.payment_basis.as_field_group }} + {{ form.estimated_hours.as_field_group }} + {{ form.customer_reference.as_field_group }} +
+ {% include "jobs/partials/tags_input.html" %} +
+
+ +
+
+

{% translate "Schedule" %}

+
+ {{ form.starts_on.as_field_group }} + {{ form.due_on.as_field_group }} + {{ form.planned_from.as_field_group }} + {{ form.planned_to.as_field_group }} +
+
+
+ +
+
+

{% translate "People and invoicing" %}

+
+ {{ form.responsible_user.as_field_group }} + {{ form.contact_user.as_field_group }} + {{ form.biller_user.as_field_group }} +
+
{% include "jobs/partials/customer_fields.html" %}
+ {{ form.members.as_field_group }} +
+
+ +
+
+

{% translate "Instructions" %}

+ {{ form.instructions.as_field_group }} +
+
+ +
+ {% translate "Cancel" %} + +
+
+{% endblock %} diff --git a/apps/jobs/presentation/templates/jobs/link_form_page.html b/apps/jobs/presentation/templates/jobs/link_form_page.html new file mode 100644 index 0000000..b18562b --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/link_form_page.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% block title %}{{ job.number }} {{ job.name }}{% endblock %} +{% block content %} + +
+
+ {% include "jobs/partials/link_form.html" %} +
+
+{% endblock %} diff --git a/apps/jobs/presentation/templates/jobs/list.html b/apps/jobs/presentation/templates/jobs/list.html new file mode 100644 index 0000000..a405fbd --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/list.html @@ -0,0 +1,29 @@ +{% extends "base.html" %}{% load users_tags %} +{% block title %}{% translate "Customer jobs" %}{% endblock %} +{% block content %} +
+

{% translate "Customer jobs" %}

+ {% if request.user|can:"jobs.edit" %} + {% translate "New job" %} + {% endif %} +
+ + + +
+ {% include "jobs/partials/job_table.html" %} +
+{% endblock %} diff --git a/apps/jobs/presentation/templates/jobs/partials/customer_fields.html b/apps/jobs/presentation/templates/jobs/partials/customer_fields.html new file mode 100644 index 0000000..524d701 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/customer_fields.html @@ -0,0 +1,5 @@ +{# Contact and billing unit of the chosen customer (reloaded when the customer changes). #} +
+ {{ form.customer_contact.as_field_group }} + {{ form.billing_unit.as_field_group }} +
diff --git a/apps/jobs/presentation/templates/jobs/partials/customer_jobs.html b/apps/jobs/presentation/templates/jobs/partials/customer_jobs.html new file mode 100644 index 0000000..d26aeb0 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/customer_jobs.html @@ -0,0 +1,24 @@ +{# The customer page's job list; loaded into the customers module's page. #} +
+
+
+

{% translate "Customer jobs" %}

+ {% if can_edit %}{% translate "New job" %}{% endif %} +
+ {% if jobs %} +
    + {% for j in jobs %} +
  • + {{ j.number }} {{ j.name }} + + {% include "jobs/partials/status_badge.html" with status=j.status %} + {% if j.is_late %}{% include "jobs/partials/late_badge.html" %}{% endif %} + +
  • + {% endfor %} +
+ {% else %} +

{% translate "The customer has no jobs yet." %}

+ {% endif %} +
+
diff --git a/apps/jobs/presentation/templates/jobs/partials/customer_picker.html b/apps/jobs/presentation/templates/jobs/partials/customer_picker.html new file mode 100644 index 0000000..5a9a600 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/customer_picker.html @@ -0,0 +1,16 @@ +{# Customer picker: search, choose a result (radio buttons named "customer") or add one by name. #} +
+ + {% translate "Customer" %} {% translate "(required)" %} + + {% include "jobs/partials/customer_search_input.html" %} +
+ {% include "jobs/partials/customer_results.html" with term="" results=None %} +
+ {% if form.customer.errors %} +

{% for error in form.customer.errors %}{{ error }} {% endfor %}

+ {% endif %} +
diff --git a/apps/jobs/presentation/templates/jobs/partials/customer_results.html b/apps/jobs/presentation/templates/jobs/partials/customer_results.html new file mode 100644 index 0000000..e2773d9 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/customer_results.html @@ -0,0 +1,45 @@ +{# Results of the customer search. The selected customer always stays first and checked. #} +{% if term %} +

{% blocktranslate count counter=results|length %}{{ counter }} customer found{% plural %}{{ counter }} customers found{% endblocktranslate %}

+{% endif %} +{% if selected_customer or results %} + +{% elif term %} +

{% translate "No customers found." %}

+{% else %} +

{% translate "Type to search. If the customer is not found, you can add it by name." %}

+{% endif %} +{% if term and can_add_customer %} +
+
+ {% blocktranslate %}Add “{{ term }}” as a new customer{% endblocktranslate %} +
+ + +
+
+ +
+{% endif %} +{% if add_error %}{% endif %} +{% if oob %} + {# A customer was just added: clear the search and empty the contact and billing unit choices. #} + {% include "jobs/partials/customer_search_input.html" %} +
{% include "jobs/partials/customer_fields.html" %}
+{% endif %} diff --git a/apps/jobs/presentation/templates/jobs/partials/customer_search_input.html b/apps/jobs/presentation/templates/jobs/partials/customer_search_input.html new file mode 100644 index 0000000..afa2266 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/customer_search_input.html @@ -0,0 +1,8 @@ +
+ + +
diff --git a/apps/jobs/presentation/templates/jobs/partials/history.html b/apps/jobs/presentation/templates/jobs/partials/history.html new file mode 100644 index 0000000..f45c7cf --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/history.html @@ -0,0 +1,24 @@ +{% load jobs_tags %} +
+
+

{% translate "Change history" %}

+ {% if changes %} +
    + {% for c in changes %} +
  1. +

    · {{ c.user_name }}

    +

    {{ c.field|change_field_label }}

    +
    + {% translate "Before" %}: + {% change_value c.field c.old_value as old %}{{ old|default:"–" }} + {% translate "After" %}: + {% change_value c.field c.new_value as new %}{{ new|default:"–" }} +
    +
  2. + {% endfor %} +
+ {% else %} +

{% translate "No changes since the job was created." %}

+ {% endif %} +
+
diff --git a/apps/jobs/presentation/templates/jobs/partials/job_table.html b/apps/jobs/presentation/templates/jobs/partials/job_table.html new file mode 100644 index 0000000..01d1d16 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/job_table.html @@ -0,0 +1,70 @@ +

{% blocktranslate count counter=page.paginator.count %}{{ counter }} job found{% plural %}{{ counter }} jobs found{% endblocktranslate %}

+{% if page.object_list %} + {# Wide screens: a table. Narrow screens: one card per job (no horizontal scrolling). #} + + +{% else %} +

{% translate "No jobs match the filters." %}

+{% endif %} +{% if page.paginator.num_pages > 1 %} + +{% endif %} diff --git a/apps/jobs/presentation/templates/jobs/partials/late_badge.html b/apps/jobs/presentation/templates/jobs/partials/late_badge.html new file mode 100644 index 0000000..c9e83df --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/late_badge.html @@ -0,0 +1 @@ +{% translate "Late" %} diff --git a/apps/jobs/presentation/templates/jobs/partials/link_form.html b/apps/jobs/presentation/templates/jobs/partials/link_form.html new file mode 100644 index 0000000..bef7d97 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/link_form.html @@ -0,0 +1,17 @@ +{% if link_id %} + {% url 'jobs:link_edit' job.id link_id as action_url %} +{% else %} + {% url 'jobs:link_create' job.id as action_url %} +{% endif %} +

+ {% if link_id %}{% translate "Edit link" %}{% else %}{% translate "Add link" %}{% endif %} +

+
+ {% csrf_token %} + {{ form }} + +
diff --git a/apps/jobs/presentation/templates/jobs/partials/links.html b/apps/jobs/presentation/templates/jobs/partials/links.html new file mode 100644 index 0000000..1708c92 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/links.html @@ -0,0 +1,38 @@ + diff --git a/apps/jobs/presentation/templates/jobs/partials/priority_badge.html b/apps/jobs/presentation/templates/jobs/partials/priority_badge.html new file mode 100644 index 0000000..72b0df6 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/priority_badge.html @@ -0,0 +1 @@ +{% load jobs_tags %}{% translate "Priority" %}: {{ priority|priority_label }} diff --git a/apps/jobs/presentation/templates/jobs/partials/status_badge.html b/apps/jobs/presentation/templates/jobs/partials/status_badge.html new file mode 100644 index 0000000..88e5d8f --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/status_badge.html @@ -0,0 +1 @@ +{% load jobs_tags %}{% translate "Status" %}: {{ status|status_label }} diff --git a/apps/jobs/presentation/templates/jobs/partials/tags_input.html b/apps/jobs/presentation/templates/jobs/partials/tags_input.html new file mode 100644 index 0000000..df33894 --- /dev/null +++ b/apps/jobs/presentation/templates/jobs/partials/tags_input.html @@ -0,0 +1,43 @@ +{# Tag editor: choose from the list or type a new tag; each tag becomes a hidden input "tags". #} +{{ form.tags.value|default_if_none:""|json_script:"tags-initial" }} +{% translate "Tag added" as added_label %}{% translate "Tag removed" as removed_label %}{% translate "Remove tag" as remove_label %} +
+ +
    + +
+
+ + +
+ {% for t in tag_options %}{% endfor %} +

{% translate "Choose from the list or type a new tag and press Enter." %}

+ {% if form.tags.errors %}

{% for e in form.tags.errors %}{{ e }} {% endfor %}

{% endif %} +
diff --git a/apps/jobs/presentation/templatetags/__init__.py b/apps/jobs/presentation/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/presentation/templatetags/jobs_tags.py b/apps/jobs/presentation/templatetags/jobs_tags.py new file mode 100644 index 0000000..4daddc8 --- /dev/null +++ b/apps/jobs/presentation/templatetags/jobs_tags.py @@ -0,0 +1,71 @@ +from datetime import date +from typing import Any + +from django import template +from django.utils.formats import date_format + +from apps.jobs.presentation.labels import ( + DATE_FIELDS, + ENUM_LABELS, + FIELD_LABELS, + KIND_LABELS, + PAYMENT_BASIS_LABELS, + PRIORITY_CLASSES, + PRIORITY_LABELS, + STATUS_LABELS, +) + +register = template.Library() + + +def _label(labels: dict[Any, Any], value: Any) -> str: + for key, label in labels.items(): + if key == value: + return str(label) + return str(value) + + +@register.filter +def status_label(value: Any) -> str: + return _label(STATUS_LABELS, value) + + +@register.filter +def priority_label(value: Any) -> str: + return _label(PRIORITY_LABELS, value) + + +@register.filter +def priority_class(value: Any) -> str: + return _label(PRIORITY_CLASSES, value) + + +@register.filter +def kind_label(value: Any) -> str: + return _label(KIND_LABELS, value) + + +@register.filter +def payment_basis_label(value: Any) -> str: + return _label(PAYMENT_BASIS_LABELS, value) + + +@register.filter +def change_field_label(field: str) -> str: + return _label(FIELD_LABELS, field) + + +@register.simple_tag +def change_value(field: str, value: str) -> str: + """A stored history value for display: enum keys translated, ISO dates formatted.""" + if not value: + return "" + labels: Any = ENUM_LABELS.get(field) + if labels is not None: + return _label(labels, value) + if field in DATE_FIELDS: + try: + return date_format(date.fromisoformat(value), "SHORT_DATE_FORMAT") + except ValueError: + return value + return value diff --git a/apps/jobs/presentation/urls.py b/apps/jobs/presentation/urls.py new file mode 100644 index 0000000..596ca2b --- /dev/null +++ b/apps/jobs/presentation/urls.py @@ -0,0 +1,25 @@ +from django.urls import path + +from apps.jobs.presentation import views + +app_name = "jobs" + +urlpatterns = [ + path("", views.JobListView.as_view(), name="list"), + path("new/", views.JobCreateView.as_view(), name="create"), + path("/", views.JobDetailView.as_view(), name="detail"), + path("/edit/", views.JobUpdateView.as_view(), name="edit"), + path("/links/new/", views.LinkFormView.as_view(), name="link_create"), + path("/links//edit/", views.LinkFormView.as_view(), name="link_edit"), + path( + "/links//delete/", views.LinkDeleteView.as_view(), name="link_delete" + ), + path("customer-picker/search/", views.CustomerSearchView.as_view(), name="customer_search"), + path("customer-picker/add/", views.CustomerQuickAddView.as_view(), name="customer_add"), + path("customer-fields/", views.CustomerFieldsView.as_view(), name="customer_fields"), + path( + "for-customer//", + views.CustomerJobsSectionView.as_view(), + name="for_customer", + ), +] diff --git a/apps/jobs/presentation/views.py b/apps/jobs/presentation/views.py new file mode 100644 index 0000000..4256faf --- /dev/null +++ b/apps/jobs/presentation/views.py @@ -0,0 +1,424 @@ +import json +from typing import Any + +from django.contrib import messages +from django.core.exceptions import PermissionDenied +from django.core.paginator import Paginator +from django.http import Http404, HttpRequest, HttpResponse +from django.shortcuts import redirect, render +from django.urls import reverse +from django.utils.translation import gettext as _ +from django.views import View + +from apps.customers.application.dto import CustomerDetailsData +from apps.customers.domain.enums import CustomerType +from apps.jobs import container +from apps.jobs.application.dto import Actor, JobDetails +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority +from apps.jobs.domain.status_rules import allowed_statuses +from apps.jobs.presentation.forms import CustomerJobForm, JobFilterForm, JobLinkForm +from apps.jobs.presentation.labels import ERROR_MESSAGES +from apps.shared.domain.exceptions import DomainError +from apps.users.domain.enums import Permission, Role +from apps.users.presentation.mixins import PermissionRequiredMixin, user_has + + +def actor(request: HttpRequest) -> Actor: + user: Any = request.user + return Actor(user_id=user.pk, role=Role(user.role)) + + +def _is_htmx(request: HttpRequest) -> bool: + return bool(getattr(request, "htmx", False)) + + +def _visible_details(request: HttpRequest, job_id: int) -> JobDetails: + queries = container.job_queries() + if not queries.is_visible_to(job_id, actor(request)): + raise Http404 + details = queries.get_details(job_id) + if details is None: + raise Http404 + return details + + +def _int(value: Any) -> int | None: + try: + return int(value) + except TypeError, ValueError: + return None + + +# --- Choices for the job form -------------------------------------------------------------------- + + +def _service_unit_choices(keep: tuple[int, ...] = ()) -> list[tuple[int, str]]: + """Active units other than the shared one, plus units already on the job.""" + catalog = container.catalog_queries() + active = [(u.id, u.name) for u in catalog.active_service_units() if not u.is_shared] + known = {i for i, _ in active} + stored = [(u.id, u.name) for u in catalog.service_units(set(keep) - known)] + return active + stored + + +def _user_choices(keep: set[int | None], *, members: bool) -> list[tuple[int, str]]: + """Active users (roles: no subcontractors) plus anyone already on the job.""" + users = container.user_queries() + excluded = () if members else (Role.SUBCONTRACTOR,) + active = list(users.choices(active_only=True, exclude_roles=excluded)) + known = {u.id for u in active} + extra = [u for u in users.choices({k for k in keep if k is not None} - known)] + return sorted(((u.id, u.name) for u in active + extra), key=lambda c: c[1].casefold()) + + +def _customer_child_choices(customer_id: int | None) -> tuple[list[Any], list[Any]]: + if customer_id is None: + return [], [] + customers = container.customer_queries() + return ( + [(c.id, c.name) for c in customers.contacts(customer_id)], + [(u.id, u.name) for u in customers.billing_units(customer_id)], + ) + + +def _initial(details: JobDetails) -> dict[str, Any]: + def ref_id(ref: Any) -> int | None: + return ref.id if ref else None + + return { + "customer": details.customer.id, + "name": details.name, + "description": details.description, + "service_units": list(details.service_unit_ids), + "kind": details.kind.value, + "status": details.status.value, + "priority": details.priority.value, + "payment_basis": details.payment_basis.value, + "starts_on": details.starts_on, + "due_on": details.due_on, + "planned_from": details.planned_from, + "planned_to": details.planned_to, + "estimated_hours": details.estimated_hours, + "customer_reference": details.customer_reference, + "instructions": details.instructions, + "responsible_user": ref_id(details.responsible), + "contact_user": ref_id(details.contact_user), + "customer_contact": ref_id(details.customer_contact), + "biller_user": ref_id(details.biller), + "billing_unit": ref_id(details.billing_unit), + "members": list(details.member_ids), + "tags": list(details.tags), + } + + +class _JobFormView(PermissionRequiredMixin, View): + """Create and edit share the form, its choices and the template.""" + + permission = Permission.JOBS_EDIT + details: JobDetails | None = None + + def _form(self, request: HttpRequest, data: Any = None) -> CustomerJobForm: + d = self.details + if data is not None: + customer_id = _int(data.get("customer")) + elif d is not None: + customer_id = d.customer.id + else: + customer_id = _int(request.GET.get("customer")) + contacts, units = _customer_child_choices(customer_id) + me = actor(request) + keep_roles = {r.id for r in (d.responsible, d.contact_user, d.biller) if r} if d else set() + kwargs: dict[str, Any] = { + "service_unit_choices": _service_unit_choices(d.service_unit_ids if d else ()), + "user_choices": _user_choices(set(keep_roles), members=False), + "member_choices": _user_choices(set(d.member_ids) if d else set(), members=True), + "contact_choices": contacts, + "billing_unit_choices": units, + "statuses": allowed_statuses( + me.role, + current=d.status if d else None, + is_biller=bool(d and d.biller and d.biller.id == me.user_id), + ), + } + if d is not None: + kwargs["initial"] = _initial(d) + else: + kwargs["initial"] = { + "customer": customer_id, + "status": JobStatus.TENTATIVE.value, + "priority": Priority.NORMAL.value, + "kind": JobKind.ONE_OFF.value, + "payment_basis": PaymentBasis.HOURLY.value, + "responsible_user": me.user_id, + } + return CustomerJobForm(data, **kwargs) + + def _render( + self, request: HttpRequest, form: CustomerJobForm, status: int = 200 + ) -> HttpResponse: + customer_id = _int(form["customer"].value()) + customer = container.customer_queries().get_summary(customer_id) if customer_id else None + context = { + "form": form, + "job": self.details, + "selected_customer": customer, + "tag_options": container.job_queries().tag_names(), + "can_add_customer": user_has(request.user, Permission.CUSTOMERS_USE), + } + return render(request, "jobs/form.html", context, status=status) + + +class JobCreateView(_JobFormView): + def get(self, request: HttpRequest) -> HttpResponse: + return self._render(request, self._form(request)) + + def post(self, request: HttpRequest) -> HttpResponse: + form = self._form(request, request.POST) + if form.is_valid(): + try: + created = container.create_customer_job().execute(actor(request), form.to_dto()) + except DomainError as error: + form.add_domain_error(error, ERROR_MESSAGES) + else: + messages.success(request, _("Job %(number)s created.") % {"number": created.number}) + return redirect("jobs:detail", pk=created.id) + return self._render(request, form, status=422) + + +class JobUpdateView(_JobFormView): + def setup(self, request: HttpRequest, *args: Any, **kwargs: Any) -> None: + super().setup(request, *args, **kwargs) + self.pk = kwargs["pk"] + + def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Any: + if user_has(request.user, Permission.JOBS_EDIT): + self.details = _visible_details(request, self.pk) + return super().dispatch(request, *args, **kwargs) + + def get(self, request: HttpRequest, pk: int) -> HttpResponse: + return self._render(request, self._form(request)) + + def post(self, request: HttpRequest, pk: int) -> HttpResponse: + form = self._form(request, request.POST) + if form.is_valid(): + try: + container.update_customer_job().execute(actor(request), pk, form.to_dto()) + except DomainError as error: + form.add_domain_error(error, ERROR_MESSAGES) + else: + messages.success(request, _("Changes saved.")) + return redirect("jobs:detail", pk=pk) + return self._render(request, form, status=422) + + +# --- List and job page --------------------------------------------------------------------------- + + +class JobListView(PermissionRequiredMixin, View): + permission = Permission.JOBS_VIEW + page_size = 25 + + def get(self, request: HttpRequest) -> HttpResponse: + units = _service_unit_choices() + filters = JobFilterForm(request.GET or None, service_unit_choices=units) + jobs = container.job_queries().list_jobs(filters.to_filters(), actor(request)) + page = Paginator(jobs, self.page_size).get_page(request.GET.get("page")) + query = request.GET.copy() + query.pop("page", None) + context = {"filters": filters, "page": page, "query": query.urlencode()} + template = "jobs/partials/job_table.html" if _is_htmx(request) else "jobs/list.html" + return render(request, template, context) + + +def _detail_context(request: HttpRequest, job_id: int) -> dict[str, Any]: + queries = container.job_queries() + return { + "job": _visible_details(request, job_id), + "links": queries.links(job_id), + "changes": queries.changes(job_id), + "can_edit": user_has(request.user, Permission.JOBS_EDIT), + "can_see_customer": user_has(request.user, Permission.CUSTOMERS_USE), + } + + +class JobDetailView(PermissionRequiredMixin, View): + permission = Permission.JOBS_VIEW + + def get(self, request: HttpRequest, pk: int) -> HttpResponse: + return render(request, "jobs/detail.html", _detail_context(request, pk)) + + +class CustomerJobsSectionView(PermissionRequiredMixin, View): + """The customer page's job list (loaded into the customers module's page with HTMX).""" + + permission = Permission.CUSTOMERS_USE + + def get(self, request: HttpRequest, customer_id: int) -> HttpResponse: + customer = container.customer_queries().get_summary(customer_id) + if customer is None: + raise Http404 + jobs = container.job_queries().jobs_for_customer(customer_id, actor(request)) + context = { + "customer": customer, + "jobs": jobs, + "can_edit": user_has(request.user, Permission.JOBS_EDIT), + } + return render(request, "jobs/partials/customer_jobs.html", context) + + +# --- Links: the form loads into a dialog on the job page ----------------------------------------- + + +def _links_response(request: HttpRequest, job_id: int, message: str) -> HttpResponse: + """Re-render links and history in place, close the dialog, announce and move focus.""" + context = _detail_context(request, job_id) + response = render(request, "jobs/partials/links.html", context) + response.content += render( + request, "jobs/partials/history.html", {**context, "oob": True} + ).content + response["HX-Retarget"] = "#links-section" + response["HX-Reswap"] = "outerHTML" + response["HX-Trigger-After-Settle"] = json.dumps( + {"itemSaved": {"message": message, "focus": "#links-heading"}} + ) + return response + + +class LinkFormView(PermissionRequiredMixin, View): + """GET: form (dialog body for HTMX, full page otherwise). POST: save.""" + + permission = Permission.JOBS_EDIT + + def _render( + self, + request: HttpRequest, + job: JobDetails, + form: JobLinkForm, + link_id: int | None, + status: int = 200, + ) -> HttpResponse: + context = {"job": job, "form": form, "link_id": link_id} + template = ( + "jobs/partials/link_form.html" if _is_htmx(request) else "jobs/link_form_page.html" + ) + return render(request, template, context, status=status) + + def get(self, request: HttpRequest, pk: int, link_id: int | None = None) -> HttpResponse: + job = _visible_details(request, pk) + initial = {} + if link_id is not None: + link = next((li for li in container.job_queries().links(pk) if li.id == link_id), None) + if link is None: + raise Http404 + initial = {"title": link.title, "url": link.url} + return self._render(request, job, JobLinkForm(initial=initial), link_id) + + def post(self, request: HttpRequest, pk: int, link_id: int | None = None) -> HttpResponse: + job = _visible_details(request, pk) + form = JobLinkForm(request.POST) + if form.is_valid(): + try: + if link_id is None: + container.add_job_link().execute(actor(request), pk, form.to_dto()) + else: + container.update_job_link().execute(actor(request), pk, link_id, form.to_dto()) + except DomainError as error: + form.add_domain_error(error, ERROR_MESSAGES) + else: + if _is_htmx(request): + return _links_response(request, pk, _("Link saved.")) + messages.success(request, _("Link saved.")) + return redirect(reverse("jobs:detail", kwargs={"pk": pk}) + "#links-section") + return self._render(request, job, form, link_id, status=422) + + +class LinkDeleteView(PermissionRequiredMixin, View): + permission = Permission.JOBS_EDIT + + def post(self, request: HttpRequest, pk: int, link_id: int) -> HttpResponse: + _visible_details(request, pk) + message = _("Link deleted.") + try: + container.delete_job_link().execute(actor(request), pk, link_id) + except DomainError as error: + message = str(ERROR_MESSAGES.get(error.code, ERROR_MESSAGES["*"])) + if _is_htmx(request): + return _links_response(request, pk, message) + messages.info(request, message) + return redirect("jobs:detail", pk=pk) + + +# --- Customer picker (reused by the quick intake) ------------------------------------------------ + + +def _picker_context( + request: HttpRequest, term: str, selected_id: int | None, **extra: Any +) -> dict[str, Any]: + customers = container.customer_queries() + selected = customers.get_summary(selected_id) if selected_id else None + found = customers.search(term) if term else [] + results = [c for c in found if not selected or c.id != selected.id] + exact = any(c.name.casefold() == term.casefold() for c in results) or bool( + selected and selected.name.casefold() == term.casefold() + ) + return { + "term": term, + "selected_customer": selected, + "results": results, + "can_add_customer": user_has(request.user, Permission.CUSTOMERS_USE) and not exact, + **extra, + } + + +class CustomerSearchView(PermissionRequiredMixin, View): + permission = Permission.JOBS_EDIT + + def get(self, request: HttpRequest) -> HttpResponse: + term = request.GET.get("customer_q", "").strip()[:200] + context = _picker_context(request, term, _int(request.GET.get("customer"))) + return render(request, "jobs/partials/customer_results.html", context) + + +class CustomerQuickAddView(PermissionRequiredMixin, View): + """Adds a customer by name (and type) and selects it; details are completed later.""" + + permission = Permission.CUSTOMERS_USE + + def post(self, request: HttpRequest) -> HttpResponse: + if not user_has(request.user, Permission.JOBS_EDIT): + raise PermissionDenied + name = request.POST.get("customer_q", "").strip() + try: + customer_type = CustomerType(request.POST.get("new_customer_type", "company")) + except ValueError: + customer_type = CustomerType.COMPANY + try: + customer_id = container.register_customer().execute( + CustomerDetailsData(name=name, type=customer_type) + ) + except DomainError: + context = _picker_context( + request, + name, + _int(request.POST.get("customer")), + add_error=_("Enter a customer name of at most 200 characters."), + ) + return render(request, "jobs/partials/customer_results.html", context, status=422) + # The new customer has no contacts or billing units: empty those choices too. + context = _picker_context(request, "", customer_id, form=CustomerJobForm(), oob=True) + response = render(request, "jobs/partials/customer_results.html", context) + response["HX-Trigger-After-Settle"] = json.dumps( + {"notify": _("Customer %(name)s added and selected.") % {"name": name}} + ) + return response + + +class CustomerFieldsView(PermissionRequiredMixin, View): + """The contact and billing unit choices of the chosen customer.""" + + permission = Permission.JOBS_EDIT + + def get(self, request: HttpRequest) -> HttpResponse: + contacts, units = _customer_child_choices(_int(request.GET.get("customer"))) + form = CustomerJobForm(contact_choices=contacts, billing_unit_choices=units) + return render(request, "jobs/partials/customer_fields.html", {"form": form}) diff --git a/apps/jobs/tests/__init__.py b/apps/jobs/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/tests/application/__init__.py b/apps/jobs/tests/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/tests/application/test_use_cases.py b/apps/jobs/tests/application/test_use_cases.py new file mode 100644 index 0000000..4a9f091 --- /dev/null +++ b/apps/jobs/tests/application/test_use_cases.py @@ -0,0 +1,236 @@ +from dataclasses import replace +from datetime import date +from decimal import Decimal +from typing import Any + +import pytest + +from apps.jobs.application.dto import Actor, CustomerJobData, JobLinkData +from apps.jobs.application.use_cases import ( + AddJobLink, + CreateCustomerJob, + DeleteJobLink, + UpdateCustomerJob, + UpdateJobLink, +) +from apps.jobs.domain.enums import JobStatus, Priority +from apps.jobs.domain.exceptions import ( + BillingUnitNotOfCustomer, + ContactNotOfCustomer, + CustomerJobNotFound, + InvalidJobName, + JobLinkNotFound, + ServiceUnitNotSelectable, + StatusNotAllowed, + UnknownCustomer, + UserNotSelectable, +) +from apps.jobs.tests.fakes import ( + FakeCatalogQueries, + FakeCustomerQueries, + FakeUserQueries, + FixedClock, + InMemoryJobRepository, + InMemoryLinkRepository, +) +from apps.shared.tests.fakes import FakeUnitOfWork +from apps.users.domain.enums import Role + +EMPLOYEE = Actor(user_id=1, role=Role.EMPLOYEE) +MANAGER = Actor(user_id=2, role=Role.MANAGEMENT) + + +class World: + def __init__(self) -> None: + self.jobs = InMemoryJobRepository() + self.links = InMemoryLinkRepository() + self.uow = FakeUnitOfWork() + self.customers = FakeCustomerQueries() + self.customers.add(10, "Oy Asiakas Ab", contacts=[(100, "Maija")], units=[(200, "HQ")]) + self.customers.add(11, "Toinen Oy", contacts=[(101, "Pekka")], units=[(201, "Konttori")]) + self.users = FakeUserQueries() + self.users.add(1, "Eero Työntekijä") + self.users.add(2, "Johanna Johto", Role.MANAGEMENT) + self.users.add(3, "Aili Alihankkija", Role.SUBCONTRACTOR) + self.users.add(4, "Lauri Lähtenyt", active=False) + self.catalog = FakeCatalogQueries() + self.catalog.add(1, "Mediatuotanto") + self.catalog.add(2, "Painotuotanto") + self.catalog.add(3, "Yhteiset", shared=True) + self.catalog.add(4, "Vanha", active=False) + self.clock = FixedClock(date(2026, 11, 29)) + + def _deps(self) -> tuple[Any, ...]: + return (self.jobs, self.uow, self.customers, self.users, self.catalog, self.clock) + + def create(self, actor: Actor = EMPLOYEE, **overrides: Any) -> Any: + return CreateCustomerJob(*self._deps()).execute(actor, data(**overrides)) + + def update(self, job_id: int, actor: Actor = EMPLOYEE, **overrides: Any) -> None: + UpdateCustomerJob(*self._deps()).execute(actor, job_id, data(**overrides)) + + +def data(**overrides: Any) -> CustomerJobData: + base = CustomerJobData( + name="Esite", customer_id=10, service_unit_ids=(1,), responsible_user_id=1 + ) + return replace(base, **overrides) + + +@pytest.fixture +def world() -> World: + return World() + + +class TestCreate: + def test_numbering_restarts_every_year(self, world: World) -> None: + assert world.create().number == "2026-0001" + assert world.create().number == "2026-0002" + world.clock.set(date(2027, 1, 1)) + assert world.create().number == "2027-0001" + + def test_defaults_and_creator(self, world: World) -> None: + created = world.create() + job = world.jobs.get(created.id) + assert job is not None + assert job.created_by == EMPLOYEE.user_id + assert job.details.status is JobStatus.TENTATIVE + assert job.details.priority is Priority.NORMAL + assert world.uow.entered == 1 + + def test_invalid_input_fails_before_transaction(self, world: World) -> None: + with pytest.raises(InvalidJobName): + world.create(name=" ") + assert world.uow.entered == 0 + + def test_unknown_customer(self, world: World) -> None: + with pytest.raises(UnknownCustomer): + world.create(customer_id=99) + + def test_contact_and_billing_unit_must_belong_to_customer(self, world: World) -> None: + world.create(customer_contact_id=100, billing_unit_id=200) + with pytest.raises(ContactNotOfCustomer): + world.create(customer_contact_id=101) + with pytest.raises(BillingUnitNotOfCustomer): + world.create(billing_unit_id=201) + + @pytest.mark.parametrize("unit_id", [3, 4, 99]) + def test_shared_inactive_or_unknown_unit_rejected(self, world: World, unit_id: int) -> None: + with pytest.raises(ServiceUnitNotSelectable): + world.create(service_unit_ids=(1, unit_id)) + + def test_subcontractor_not_in_role_fields_but_may_be_member(self, world: World) -> None: + with pytest.raises(UserNotSelectable) as error: + world.create(biller_user_id=3) + assert error.value.field == "biller_user" + world.create(member_ids=(3,)) + + def test_inactive_user_rejected(self, world: World) -> None: + with pytest.raises(UserNotSelectable): + world.create(responsible_user_id=4) + with pytest.raises(UserNotSelectable): + world.create(member_ids=(4,)) + + def test_status_rules(self, world: World) -> None: + with pytest.raises(StatusNotAllowed): + world.create(status=JobStatus.ARCHIVED) + with pytest.raises(StatusNotAllowed): + world.create(status=JobStatus.INVOICED) + world.create(MANAGER, status=JobStatus.ARCHIVED) + + def test_subcontractor_cannot_create(self, world: World) -> None: + with pytest.raises(StatusNotAllowed): + world.create(Actor(user_id=3, role=Role.SUBCONTRACTOR)) + + +class TestUpdate: + def test_records_changes_with_display_values(self, world: World) -> None: + job_id = world.create(member_ids=(1,), tags=("video",)).id + world.update( + job_id, + name="Esite 2", + customer_id=11, + customer_contact_id=101, + service_unit_ids=(1, 2), + responsible_user_id=2, + member_ids=(1, 2), + tags=("Video", "Messut"), + priority=Priority.URGENT, + due_on=date(2026, 12, 24), + estimated_hours=Decimal("7.5"), + ) + assert world.jobs.change_rows() == [ + ("name", "Esite", "Esite 2"), + ("customer", "Oy Asiakas Ab", "Toinen Oy"), + ("service_units", "Mediatuotanto", "Mediatuotanto, Painotuotanto"), + ("due_on", "", "2026-12-24"), + ("priority", "normal", "urgent"), + ("estimated_hours", "", "7.50"), + ("responsible_user", "Eero Työntekijä", "Johanna Johto"), + ("customer_contact", "", "Pekka"), + ("members", "Eero Työntekijä", "Eero Työntekijä, Johanna Johto"), + ("tags", "video", "Messut, Video"), + ] + assert all(user_id == EMPLOYEE.user_id for _, user_id, _ in world.jobs.changes) + + def test_no_change_records_nothing(self, world: World) -> None: + job_id = world.create().id + world.update(job_id) + assert world.jobs.changes == [] + + def test_kept_inactive_people_and_units_stay_valid(self, world: World) -> None: + job_id = world.create(member_ids=(1,)).id + world.users.add(1, "Eero Työntekijä", active=False) + world.catalog.units = [(u, False) if u.id == 1 else (u, a) for u, a in world.catalog.units] + world.update(job_id, name="Uusi nimi", member_ids=(1,)) + with pytest.raises(UserNotSelectable): + world.update(job_id, contact_user_id=1) + + def test_biller_employee_may_set_invoice_status(self, world: World) -> None: + job_id = world.create(biller_user_id=1).id + world.update(job_id, biller_user_id=1, status=JobStatus.INVOICED) + other = world.create().id + with pytest.raises(StatusNotAllowed): + world.update(other, status=JobStatus.BILLED) + + def test_employee_keeps_archived_status(self, world: World) -> None: + job_id = world.create(MANAGER, status=JobStatus.ARCHIVED).id + world.update(job_id, status=JobStatus.ARCHIVED, name="Korjattu") + world.update(job_id, status=JobStatus.ORDER) + with pytest.raises(StatusNotAllowed): + world.update(job_id, status=JobStatus.ARCHIVED) + + def test_missing_job(self, world: World) -> None: + with pytest.raises(CustomerJobNotFound): + world.update(99) + + +class TestLinks: + def _cases(self, world: World) -> tuple[AddJobLink, UpdateJobLink, DeleteJobLink]: + deps = (world.jobs, world.links, world.uow) + return AddJobLink(*deps), UpdateJobLink(*deps), DeleteJobLink(*deps) + + def test_add_edit_delete_are_in_history(self, world: World) -> None: + job_id = world.create().id + add, update, delete = self._cases(world) + link_id = add.execute(EMPLOYEE, job_id, JobLinkData("Aineisto", "https://a.test/1")) + update.execute(EMPLOYEE, job_id, link_id, JobLinkData("Aineisto", "https://a.test/2")) + update.execute(EMPLOYEE, job_id, link_id, JobLinkData("Aineisto", "https://a.test/2")) + delete.execute(EMPLOYEE, job_id, link_id) + assert world.links.links == {} + assert world.jobs.change_rows() == [ + ("links", "", "Aineisto (https://a.test/1)"), + ("links", "Aineisto (https://a.test/1)", "Aineisto (https://a.test/2)"), + ("links", "Aineisto (https://a.test/2)", ""), + ] + + def test_link_of_another_job_not_found(self, world: World) -> None: + first, second = world.create().id, world.create().id + add, update, delete = self._cases(world) + link_id = add.execute(EMPLOYEE, first, JobLinkData("", "https://a.test")) + with pytest.raises(JobLinkNotFound): + update.execute(EMPLOYEE, second, link_id, JobLinkData("", "https://b.test")) + with pytest.raises(JobLinkNotFound): + delete.execute(EMPLOYEE, second, link_id) + with pytest.raises(CustomerJobNotFound): + add.execute(EMPLOYEE, 99, JobLinkData("", "https://a.test")) diff --git a/apps/jobs/tests/domain/__init__.py b/apps/jobs/tests/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/tests/domain/test_domain.py b/apps/jobs/tests/domain/test_domain.py new file mode 100644 index 0000000..ad81f57 --- /dev/null +++ b/apps/jobs/tests/domain/test_domain.py @@ -0,0 +1,153 @@ +from datetime import date +from decimal import Decimal + +import pytest + +from apps.jobs.domain.entities import JobFields +from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority +from apps.jobs.domain.exceptions import ( + DueBeforeStart, + InvalidEstimatedHours, + InvalidJobName, + InvalidJobNumber, + InvalidLinkUrl, + InvalidTagName, + PlannedRangeInvalid, + ServiceUnitRequired, +) +from apps.jobs.domain.status_rules import allowed_statuses, can_set_status +from apps.jobs.domain.value_objects import ( + EstimatedHours, + JobName, + JobNumber, + LinkTarget, + TagName, +) +from apps.users.domain.enums import Role + + +def fields(**overrides: object) -> JobFields: + values: dict[str, object] = { + "name": JobName("Esite"), + "customer_id": 1, + "service_unit_ids": frozenset({1}), + } + values.update(overrides) + return JobFields(**values) # type: ignore[arg-type] + + +class TestJobNumber: + def test_format_pads_sequence(self) -> None: + assert str(JobNumber(2026, 42)) == "2026-0042" + assert str(JobNumber(2027, 1)) == "2027-0001" + + def test_sequence_over_9999_keeps_growing(self) -> None: + assert str(JobNumber(2026, 10000)) == "2026-10000" + + def test_parse_round_trip(self) -> None: + assert JobNumber.parse("2026-0042") == JobNumber(2026, 42) + + @pytest.mark.parametrize("value", ["", "2026", "26-0001", "2026-0000", "abcd-0001"]) + def test_invalid(self, value: str) -> None: + with pytest.raises(InvalidJobNumber): + JobNumber.parse(value) + + +class TestValueObjects: + def test_name_is_normalized_and_required(self) -> None: + assert JobName(" Uusi esite ").value == "Uusi esite" + with pytest.raises(InvalidJobName): + JobName(" ") + with pytest.raises(InvalidJobName): + JobName("x" * 201) + + @pytest.mark.parametrize("value", ["0", "1.5", "9999.99"]) + def test_hours_accepted(self, value: str) -> None: + assert EstimatedHours(Decimal(value)).value == Decimal(value).quantize(Decimal("0.01")) + + @pytest.mark.parametrize("value", ["-1", "10000", "1.255"]) + def test_hours_rejected(self, value: str) -> None: + with pytest.raises(InvalidEstimatedHours): + EstimatedHours(Decimal(value)) + + def test_tag_rules(self) -> None: + assert TagName(" Video tuotanto ").value == "Video tuotanto" + assert TagName("Video").key == TagName("video").key + for bad in ("", "a,b", "x" * 51): + with pytest.raises(InvalidTagName): + TagName(bad) + + def test_link_requires_http_url_and_defaults_title(self) -> None: + link = LinkTarget(title="", url=" https://drive.example.test/x ") + assert link.url == "https://drive.example.test/x" + assert link.title == link.url + assert ( + str(LinkTarget(title="Aineisto", url="https://a.test")) == "Aineisto (https://a.test)" + ) + for bad in ("javascript:alert(1)", "ftp://a.test", "drive.example.test", ""): + with pytest.raises(InvalidLinkUrl): + LinkTarget(title="x", url=bad) + + +class TestJobFields: + def test_defaults_of_a_new_job(self) -> None: + f = fields() + assert f.status is JobStatus.TENTATIVE + assert f.priority is Priority.NORMAL + assert f.kind is JobKind.ONE_OFF + assert f.payment_basis is PaymentBasis.HOURLY + + def test_needs_a_service_unit(self) -> None: + with pytest.raises(ServiceUnitRequired): + fields(service_unit_ids=frozenset()) + + def test_planned_range_in_order(self) -> None: + with pytest.raises(PlannedRangeInvalid): + fields(planned_from=date(2026, 5, 2), planned_to=date(2026, 5, 1)) + fields(planned_from=date(2026, 5, 1), planned_to=date(2026, 5, 1)) + + def test_due_not_before_start(self) -> None: + with pytest.raises(DueBeforeStart): + fields(starts_on=date(2026, 5, 2), due_on=date(2026, 5, 1)) + + def test_tags_unique_case_insensitively_and_sorted(self) -> None: + f = fields(tags=(TagName("video"), TagName("Esite"), TagName("Video"))) + assert [t.value for t in f.tags] == ["Esite", "video"] + + def test_changed_fields(self) -> None: + before = fields(tags=(TagName("a"),), member_ids=frozenset({1, 2})) + after = fields(name=JobName("Esite 2"), tags=(TagName("A"),), member_ids=frozenset({2, 1})) + assert after.changed_fields(before) == ["name"] + other_tags = fields(tags=(TagName("b"),), member_ids=frozenset({1, 2})) + assert other_tags.changed_fields(before) == ["tags"] + + def test_user_ids(self) -> None: + f = fields(responsible_user_id=1, biller_user_id=2, member_ids=frozenset({2, 3})) + assert f.user_ids == {1, 2, 3} + + +class TestStatusRules: + @pytest.mark.parametrize("role", [Role.ADMIN, Role.MANAGEMENT, Role.EMPLOYEE, Role.INTERN]) + def test_editors_reach_done(self, role: Role) -> None: + assert can_set_status(role, JobStatus.DONE) + assert can_set_status(role, JobStatus.ON_HOLD) + + def test_subcontractor_sets_nothing(self) -> None: + assert allowed_statuses(Role.SUBCONTRACTOR) == [] + + @pytest.mark.parametrize("target", [JobStatus.INVOICED, JobStatus.BILLED]) + def test_invoice_statuses(self, target: JobStatus) -> None: + assert can_set_status(Role.MANAGEMENT, target) + assert can_set_status(Role.ADMIN, target) + assert not can_set_status(Role.EMPLOYEE, target) + assert can_set_status(Role.EMPLOYEE, target, is_biller=True) + assert not can_set_status(Role.INTERN, target, is_biller=True) + + def test_archive_only_management(self) -> None: + assert can_set_status(Role.MANAGEMENT, JobStatus.ARCHIVED) + assert not can_set_status(Role.EMPLOYEE, JobStatus.ARCHIVED, is_biller=True) + + def test_current_status_may_always_stay(self) -> None: + assert can_set_status(Role.EMPLOYEE, JobStatus.ARCHIVED, current=JobStatus.ARCHIVED) + assert JobStatus.ARCHIVED in allowed_statuses(Role.INTERN, current=JobStatus.ARCHIVED) + assert JobStatus.ARCHIVED not in allowed_statuses(Role.INTERN) diff --git a/apps/jobs/tests/fakes.py b/apps/jobs/tests/fakes.py new file mode 100644 index 0000000..12134e2 --- /dev/null +++ b/apps/jobs/tests/fakes.py @@ -0,0 +1,164 @@ +"""In-memory test doubles for the jobs application layer (no database).""" + +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field +from datetime import date + +from apps.catalog.application.dto import ServiceUnitSummary +from apps.customers.application.dto import CustomerSummary +from apps.customers.domain.enums import CustomerType +from apps.jobs.domain.entities import ChangeRecord, CustomerJob, JobLink +from apps.jobs.domain.value_objects import JobNumber +from apps.users.application.dto import UserChoice +from apps.users.domain.enums import Role + + +class InMemoryJobRepository: + def __init__(self) -> None: + self.jobs: dict[int, CustomerJob] = {} + self.counters: dict[int, int] = {} + self.changes: list[tuple[int, int, ChangeRecord]] = [] + self._next = 1 + + def get(self, job_id: int) -> CustomerJob | None: + return self.jobs.get(job_id) + + def save(self, job: CustomerJob) -> CustomerJob: + if job.id is None: + job = job.with_id(self._next) + self._next += 1 + assert job.id is not None + self.jobs[job.id] = job + return job + + def next_number(self, year: int) -> JobNumber: + self.counters[year] = self.counters.get(year, 0) + 1 + return JobNumber(year, self.counters[year]) + + def record_changes(self, job_id: int, user_id: int, changes: Sequence[ChangeRecord]) -> None: + self.changes.extend((job_id, user_id, c) for c in changes) + + def change_rows(self) -> list[tuple[str, str, str]]: + return [(c.field, c.old_value, c.new_value) for _, _, c in self.changes] + + +class InMemoryLinkRepository: + def __init__(self) -> None: + self.links: dict[int, JobLink] = {} + self._next = 1 + + def get(self, link_id: int) -> JobLink | None: + return self.links.get(link_id) + + def save(self, link: JobLink) -> JobLink: + if link.id is None: + link = link.with_id(self._next) + self._next += 1 + assert link.id is not None + self.links[link.id] = link + return link + + def delete(self, link_id: int) -> None: + del self.links[link_id] + + +@dataclass(frozen=True) +class _Row: + id: int + name: str + + +@dataclass +class FakeCustomerQueries: + """Customers with their contacts and billing units, as the customers module shows them.""" + + customers: dict[int, str] = field(default_factory=dict) + contacts_by_customer: dict[int, list[_Row]] = field(default_factory=dict) + units_by_customer: dict[int, list[_Row]] = field(default_factory=dict) + + def add( + self, + customer_id: int, + name: str, + *, + contacts: Iterable[tuple[int, str]] = (), + units: Iterable[tuple[int, str]] = (), + ) -> None: + self.customers[customer_id] = name + self.contacts_by_customer[customer_id] = [_Row(i, n) for i, n in contacts] + self.units_by_customer[customer_id] = [_Row(i, n) for i, n in units] + + def _summary(self, customer_id: int) -> CustomerSummary: + return CustomerSummary( + id=customer_id, + name=self.customers[customer_id], + type=CustomerType.COMPANY, + business_id=None, + is_internal=False, + ) + + def get_summary(self, customer_id: int) -> CustomerSummary | None: + return self._summary(customer_id) if customer_id in self.customers else None + + def summaries(self, customer_ids: Iterable[int]) -> dict[int, CustomerSummary]: + return {i: self._summary(i) for i in customer_ids if i in self.customers} + + def contacts(self, customer_id: int) -> list[_Row]: + return self.contacts_by_customer.get(customer_id, []) + + def billing_units(self, customer_id: int) -> list[_Row]: + return self.units_by_customer.get(customer_id, []) + + +@dataclass +class FakeUserQueries: + users: dict[int, UserChoice] = field(default_factory=dict) + + def add(self, user_id: int, name: str, role: Role = Role.EMPLOYEE, active: bool = True) -> None: + self.users[user_id] = UserChoice(id=user_id, name=name, role=role, is_active=active) + + def choices( + self, + ids: Iterable[int] | None = None, + *, + active_only: bool = False, + exclude_roles: Iterable[Role] = (), + ) -> list[UserChoice]: + wanted = set(ids) if ids is not None else None + excluded = set(exclude_roles) + return sorted( + ( + u + for u in self.users.values() + if (wanted is None or u.id in wanted) + and (u.is_active or not active_only) + and u.role not in excluded + ), + key=lambda u: u.name, + ) + + +@dataclass +class FakeCatalogQueries: + units: list[tuple[ServiceUnitSummary, bool]] = field(default_factory=list) # (unit, active) + + def add(self, unit_id: int, name: str, *, shared: bool = False, active: bool = True) -> None: + self.units.append((ServiceUnitSummary(id=unit_id, name=name, is_shared=shared), active)) + + def active_service_units(self) -> list[ServiceUnitSummary]: + return [u for u, active in self.units if active] + + def service_units(self, ids: Iterable[int]) -> list[ServiceUnitSummary]: + wanted = set(ids) + return [u for u, _ in self.units if u.id in wanted] + + +class FixedClock: + def __init__(self, today: date) -> None: + self._today = today + + def today(self) -> date: + return self._today + + def set(self, today: date) -> None: + self._today = today diff --git a/apps/jobs/tests/integration/__init__.py b/apps/jobs/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/jobs/tests/integration/test_jobs.py b/apps/jobs/tests/integration/test_jobs.py new file mode 100644 index 0000000..be56cfc --- /dev/null +++ b/apps/jobs/tests/integration/test_jobs.py @@ -0,0 +1,356 @@ +import json +from collections.abc import Callable +from datetime import date +from typing import Any +from unittest import mock + +import pytest +from django.test import Client + +from apps.catalog.infrastructure.orm import ServiceUnitModel +from apps.customers.infrastructure.orm import BillingUnitModel, ContactModel, CustomerModel +from apps.jobs.infrastructure.orm import ( + CustomerJobModel, + JobChangeModel, + JobLinkModel, + JobNumberSequenceModel, + TagModel, +) +from apps.jobs.infrastructure.repositories import DjangoCustomerJobRepository +from apps.users.infrastructure.orm import User + +pytestmark = pytest.mark.django_db + +HX = {"HX-Request": "true"} + + +@pytest.fixture +def employee(make_user: Callable[..., User]) -> User: + return make_user(name="Eero Työntekijä", role="employee") + + +@pytest.fixture +def employee_client(client: Client, employee: User) -> Client: + client.force_login(employee) + return client + + +@pytest.fixture +def customer() -> CustomerModel: + return CustomerModel.objects.create(name="Oy Asiakas Ab", type="company") + + +@pytest.fixture +def unit() -> ServiceUnitModel: + return ServiceUnitModel.objects.filter(is_shared=False, is_active=True).order_by("id").first() + + +def job_data(customer: CustomerModel, unit: ServiceUnitModel, **extra: Any) -> dict[str, Any]: + data = { + "customer": customer.pk, + "name": "Esite", + "service_units": [unit.pk], + "kind": "one_off", + "status": "tentative", + "priority": "normal", + "payment_basis": "hourly", + } + data.update(extra) + return data + + +def create(client: Client, customer: CustomerModel, unit: ServiceUnitModel, **extra: Any) -> Any: + return client.post("/jobs/new/", job_data(customer, unit, **extra)) + + +class TestNumbering: + def test_sequential_numbers_per_year( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + with mock.patch( + "apps.shared.infrastructure.clock.DjangoClock.today", return_value=date(2026, 3, 1) + ): + create(employee_client, customer, unit) + create(employee_client, customer, unit, name="Toinen") + with mock.patch( + "apps.shared.infrastructure.clock.DjangoClock.today", return_value=date(2027, 1, 2) + ): + create(employee_client, customer, unit, name="Kolmas") + numbers = list(CustomerJobModel.objects.order_by("id").values_list("number", flat=True)) + assert numbers == ["2026-0001", "2026-0002", "2027-0001"] + assert JobNumberSequenceModel.objects.get(year=2026).last_number == 2 + + def test_counter_row_is_created_once(self) -> None: + repo = DjangoCustomerJobRepository() + assert str(repo.next_number(2030)) == "2030-0001" + assert str(repo.next_number(2030)) == "2030-0002" + assert JobNumberSequenceModel.objects.filter(year=2030).count() == 1 + + +class TestCreateAndEdit: + def test_create_with_defaults_tags_and_members( + self, + employee_client: Client, + employee: User, + customer: CustomerModel, + unit: ServiceUnitModel, + make_user: Callable[..., User], + ) -> None: + page = employee_client.get(f"/jobs/new/?customer={customer.pk}") + assert page.status_code == 200 + html = page.content.decode() + assert 'value="tentative" selected' in html + assert "Oy Asiakas Ab" in html + # The shared service unit is not offered for jobs. + shared = ServiceUnitModel.objects.get(is_shared=True) + assert f'name="service_units" value="{unit.pk}"' in html + assert f'name="service_units" value="{shared.pk}"' not in html + + sub = make_user(role="subcontractor", name="Aili Alihankkija") + response = create( + employee_client, + customer, + unit, + responsible_user=employee.pk, + members=[sub.pk], + tags=["Video", "messut"], + estimated_hours="7,5", + ) + assert response.status_code == 302 + job = CustomerJobModel.objects.get() + assert response["Location"] == f"/jobs/{job.pk}/" + assert job.created_by_id == employee.pk + assert str(job.estimated_hours) == "7.50" + assert set(TagModel.objects.values_list("name", flat=True)) == {"Video", "messut"} + detail = employee_client.get(f"/jobs/{job.pk}/").content.decode() + assert "Aili Alihankkija" in detail + assert "Alustava" in detail and "Normaali" in detail + + def test_existing_tag_is_reused_ignoring_case( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + TagModel.objects.create(name="Video") + create(employee_client, customer, unit, tags=["video"]) + assert TagModel.objects.count() == 1 + + def test_validation_errors_are_422( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + response = create( + employee_client, + customer, + unit, + name="", + planned_from="2026-05-02", + planned_to="2026-05-01", + ) + assert response.status_code == 422 + response = create( + employee_client, customer, unit, planned_from="2026-05-02", planned_to="2026-05-01" + ) + assert response.status_code == 422 + assert ( + "Suunniteltu loppu ei voi olla ennen suunniteltua alkua." in response.content.decode() + ) + assert not CustomerJobModel.objects.exists() + + def test_contact_of_another_customer_is_rejected( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + other = CustomerModel.objects.create(name="Toinen Oy", type="company") + contact = ContactModel.objects.create(customer=other, name="Pekka") + response = create(employee_client, customer, unit, customer_contact=contact.pk) + assert response.status_code == 422 + assert not CustomerJobModel.objects.exists() + + def test_employee_cannot_archive( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + response = create(employee_client, customer, unit, status="archived") + assert response.status_code == 422 + + def test_edit_records_history( + self, + employee_client: Client, + customer: CustomerModel, + unit: ServiceUnitModel, + ) -> None: + create(employee_client, customer, unit) + job = CustomerJobModel.objects.get() + contact = ContactModel.objects.create(customer=customer, name="Maija") + billing = BillingUnitModel.objects.create(customer=customer, name="HQ") + response = employee_client.post( + f"/jobs/{job.pk}/edit/", + job_data( + customer, + unit, + name="Esite 2", + priority="urgent", + due_on="2026-12-24", + customer_contact=contact.pk, + billing_unit=billing.pk, + ), + ) + assert response.status_code == 302 + rows = list(JobChangeModel.objects.order_by("id").values_list("field", "new_value")) + assert rows == [ + ("name", "Esite 2"), + ("due_on", "2026-12-24"), + ("priority", "urgent"), + ("customer_contact", "Maija"), + ("billing_unit", "HQ"), + ] + page = employee_client.get(f"/jobs/{job.pk}/").content.decode() + assert "Muutoshistoria" in page + assert "Kiire" in page # the stored key is shown translated + assert "24.12.2026" in page + + def test_referenced_contact_cannot_be_deleted( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + contact = ContactModel.objects.create(customer=customer, name="Maija") + create(employee_client, customer, unit, customer_contact=contact.pk) + employee_client.post(f"/customers/{customer.pk}/contacts/{contact.pk}/delete/") + assert ContactModel.objects.filter(pk=contact.pk).exists() + page = employee_client.get(f"/customers/{customer.pk}/").content.decode() + assert "Poista asiakas" not in page + + +class TestListAndVisibility: + def test_my_jobs_by_default_and_search_by_customer_name( + self, + employee_client: Client, + employee: User, + customer: CustomerModel, + unit: ServiceUnitModel, + make_user: Callable[..., User], + ) -> None: + other = make_user() + create(employee_client, customer, unit, name="Oma työ", responsible_user=employee.pk) + create(employee_client, customer, unit, name="Muiden työ", responsible_user=other.pk) + mine = employee_client.get("/jobs/").content.decode() + assert "Oma työ" in mine and "Muiden työ" not in mine + everything = employee_client.get("/jobs/?scope=all").content.decode() + assert "Muiden työ" in everything + found = employee_client.get("/jobs/?scope=all&q=asiakas", headers=HX).content.decode() + assert "Oma työ" in found and "Muiden työ" in found + none = employee_client.get("/jobs/?scope=all&q=xyz", headers=HX).content.decode() + assert "Oma työ" not in none + + def test_archived_hidden_unless_asked( + self, + client: Client, + make_user: Callable[..., User], + customer: CustomerModel, + unit: ServiceUnitModel, + ) -> None: + manager = make_user(role="management") + client.force_login(manager) + create(client, customer, unit, name="Vanha työ", status="archived") + assert "Vanha työ" not in client.get("/jobs/?scope=all").content.decode() + assert "Vanha työ" in client.get("/jobs/?scope=all&archived=on").content.decode() + assert "Vanha työ" in client.get("/jobs/?scope=all&status=archived").content.decode() + + def test_late_job_shows_text( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + create(employee_client, customer, unit, due_on="2020-01-01") + assert "Myöhässä" in employee_client.get("/jobs/?scope=all").content.decode() + + def test_subcontractor_sees_only_member_jobs_read_only( + self, + employee_client: Client, + customer: CustomerModel, + unit: ServiceUnitModel, + make_user: Callable[..., User], + ) -> None: + sub = make_user(role="subcontractor") + create(employee_client, customer, unit, name="Liitetty", members=[sub.pk]) + create(employee_client, customer, unit, name="Muu") + mine, other = CustomerJobModel.objects.order_by("id") + c = Client() + c.force_login(sub) + listing = c.get("/jobs/?scope=all").content.decode() + assert "Liitetty" in listing and "Muu" not in listing + assert c.get(f"/jobs/{mine.pk}/").status_code == 200 + assert c.get(f"/jobs/{other.pk}/").status_code == 404 + assert c.get(f"/jobs/{mine.pk}/edit/").status_code == 403 + assert c.get("/jobs/new/").status_code == 403 + assert "Muokkaa" not in c.get(f"/jobs/{mine.pk}/").content.decode() + + def test_customer_page_section( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + create(employee_client, customer, unit, name="Asiakkaan työ") + html = employee_client.get(f"/jobs/for-customer/{customer.pk}/", headers=HX) + assert html.status_code == 200 + assert "Asiakkaan työ" in html.content.decode() + assert f"/jobs/new/?customer={customer.pk}" in html.content.decode() + assert ( + f"/jobs/for-customer/{customer.pk}/" + in employee_client.get(f"/customers/{customer.pk}/").content.decode() + ) + + +class TestLinks: + def test_add_edit_delete_in_dialog( + self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel + ) -> None: + create(employee_client, customer, unit) + job = CustomerJobModel.objects.get() + base = f"/jobs/{job.pk}/links" + invalid = employee_client.post(f"{base}/new/", {"url": "javascript:alert(1)"}, headers=HX) + assert invalid.status_code == 422 + response = employee_client.post( + f"{base}/new/", {"title": "Aineisto", "url": "https://drive.example.test/a"}, headers=HX + ) + assert response.status_code == 200 + assert response["HX-Retarget"] == "#links-section" + trigger = json.loads(response["HX-Trigger-After-Settle"]) + assert trigger["itemSaved"]["message"] == "Linkki tallennettu." + assert 'hx-swap-oob="true"' in response.content.decode() # history refreshed too + link = JobLinkModel.objects.get() + employee_client.post( + f"{base}/{link.pk}/edit/", {"title": "Uusi", "url": link.url}, headers=HX + ) + employee_client.post(f"{base}/{link.pk}/delete/", headers=HX) + assert not JobLinkModel.objects.exists() + assert list(JobChangeModel.objects.order_by("id").values_list("field", flat=True)) == [ + "links", + "links", + "links", + ] + + +class TestCustomerPicker: + def test_search_keeps_selected_first( + self, employee_client: Client, customer: CustomerModel + ) -> None: + CustomerModel.objects.create(name="Asiakas Kaksi", type="company") + html = employee_client.get( + f"/jobs/customer-picker/search/?customer_q=asiakas&customer={customer.pk}", headers=HX + ).content.decode() + assert html.index("Oy Asiakas Ab") < html.index("Asiakas Kaksi") + assert f'value="{customer.pk}" checked' in html + assert "uudeksi asiakkaaksi" in html + + def test_quick_add_selects_new_customer(self, employee_client: Client) -> None: + response = employee_client.post( + "/jobs/customer-picker/add/", + {"customer_q": "Uusi Kuluttaja", "new_customer_type": "consumer"}, + headers=HX, + ) + assert response.status_code == 200 + new = CustomerModel.objects.get(name="Uusi Kuluttaja") + assert new.type == "consumer" + assert f'value="{new.pk}" checked' in response.content.decode() + assert "notify" in response["HX-Trigger-After-Settle"] + + def test_customer_fields_follow_customer( + self, employee_client: Client, customer: CustomerModel + ) -> None: + ContactModel.objects.create(customer=customer, name="Maija") + html = employee_client.get( + f"/jobs/customer-fields/?customer={customer.pk}", headers=HX + ).content.decode() + assert "Maija" in html diff --git a/apps/users/application/dto.py b/apps/users/application/dto.py index 20cea16..f558131 100644 --- a/apps/users/application/dto.py +++ b/apps/users/application/dto.py @@ -50,6 +50,16 @@ class SupervisorChoice: name: str +@dataclass(frozen=True, slots=True) +class UserChoice: + """What other modules (jobs) see of a user when choosing or showing people.""" + + id: int + name: str + role: Role + is_active: bool + + @dataclass(frozen=True, slots=True) class PasswordLink: url: str diff --git a/apps/users/application/queries.py b/apps/users/application/queries.py index fdd84a8..0f11a91 100644 --- a/apps/users/application/queries.py +++ b/apps/users/application/queries.py @@ -1,7 +1,7 @@ -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from typing import Protocol -from apps.users.application.dto import SupervisorChoice, UserDetailsData, UserSummary +from apps.users.application.dto import SupervisorChoice, UserChoice, UserDetailsData, UserSummary from apps.users.domain.enums import Role @@ -17,3 +17,14 @@ class UserQueries(Protocol): def supervisor_choices(self, *, exclude_id: int | None = None) -> Sequence[SupervisorChoice]: """Active management and employee users.""" ... + + def choices( + self, + ids: Iterable[int] | None = None, + *, + active_only: bool = False, + exclude_roles: Iterable[Role] = (), + ) -> Sequence[UserChoice]: + """Users by name; ``ids`` limits to those users (inactive ones included unless + ``active_only``).""" + ... diff --git a/apps/users/domain/enums.py b/apps/users/domain/enums.py index ca41ab3..22a31ee 100644 --- a/apps/users/domain/enums.py +++ b/apps/users/domain/enums.py @@ -22,3 +22,9 @@ class Permission(StrEnum): CUSTOMERS_PERSONAL_ID_VIEW = "customers.personal_id.view" # Base data: service units, services, work types (later price list, products). CATALOG_MANAGE = "catalog.manage" + # Customer jobs: everyone sees (subcontractors only jobs they are members of). + JOBS_VIEW = "jobs.view" + JOBS_EDIT = "jobs.edit" + JOBS_ARCHIVE = "jobs.archive" + # Set "invoice created" / "invoiced"; the job's biller may do it too (job rule). + JOBS_INVOICE_STATUS = "jobs.invoice_status" diff --git a/apps/users/domain/permissions.py b/apps/users/domain/permissions.py index bb30809..1480b03 100644 --- a/apps/users/domain/permissions.py +++ b/apps/users/domain/permissions.py @@ -9,6 +9,10 @@ _PERMISSIONS: dict[Permission, frozenset[Role]] = { Permission.CUSTOMERS_USE: _ALL_EXCEPT_SUBCONTRACTOR, Permission.CUSTOMERS_PERSONAL_ID_VIEW: frozenset({Role.ADMIN, Role.MANAGEMENT}), Permission.CATALOG_MANAGE: frozenset({Role.ADMIN, Role.MANAGEMENT}), + Permission.JOBS_VIEW: frozenset(Role), + Permission.JOBS_EDIT: _ALL_EXCEPT_SUBCONTRACTOR, + Permission.JOBS_ARCHIVE: frozenset({Role.ADMIN, Role.MANAGEMENT}), + Permission.JOBS_INVOICE_STATUS: frozenset({Role.ADMIN, Role.MANAGEMENT}), } diff --git a/apps/users/infrastructure/queries.py b/apps/users/infrastructure/queries.py index 3bdfdf9..1e967fc 100644 --- a/apps/users/infrastructure/queries.py +++ b/apps/users/infrastructure/queries.py @@ -1,8 +1,8 @@ -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from django.db.models import Q -from apps.users.application.dto import SupervisorChoice, UserDetailsData, UserSummary +from apps.users.application.dto import SupervisorChoice, UserChoice, UserDetailsData, UserSummary from apps.users.domain.enums import Role from apps.users.infrastructure.orm import User @@ -56,3 +56,23 @@ class DjangoUserQueries: if exclude_id is not None: qs = qs.exclude(pk=exclude_id) return [SupervisorChoice(id=u.pk, name=u.name) for u in qs] + + def choices( + self, + ids: Iterable[int] | None = None, + *, + active_only: bool = False, + exclude_roles: Iterable[Role] = (), + ) -> Sequence[UserChoice]: + qs = User.objects.order_by("name", "pk") + if ids is not None: + qs = qs.filter(pk__in=list(ids)) + if active_only: + qs = qs.filter(is_active=True) + excluded = [r.value for r in exclude_roles] + if excluded: + qs = qs.exclude(role__in=excluded) + return [ + UserChoice(id=u.pk, name=u.name, role=Role(u.role), is_active=u.is_active) + for u in qs.only("id", "name", "role", "is_active") + ] diff --git a/config/settings.py b/config/settings.py index 6f414ed..9492773 100644 --- a/config/settings.py +++ b/config/settings.py @@ -48,6 +48,7 @@ INSTALLED_APPS = [ "apps.users", "apps.customers", "apps.catalog", + "apps.jobs", ] MIDDLEWARE = [ @@ -86,6 +87,7 @@ TEMPLATES = [ "libraries": { "users_tags": "apps.users.presentation.templatetags.users_tags", "customers_tags": "apps.customers.presentation.templatetags.customers_tags", + "jobs_tags": "apps.jobs.presentation.templatetags.jobs_tags", }, }, }, diff --git a/config/urls.py b/config/urls.py index 052c858..d24ff98 100644 --- a/config/urls.py +++ b/config/urls.py @@ -7,4 +7,5 @@ urlpatterns = [ path("", include("apps.users.presentation.urls")), path("customers/", include("apps.customers.presentation.urls")), path("catalog/", include("apps.catalog.presentation.urls")), + path("jobs/", include("apps.jobs.presentation.urls")), ] diff --git a/docs/maarittely.md b/docs/maarittely.md index c9e2660..cef0c03 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -97,7 +97,7 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli - Lomake ei koskaan näytä tallennettua tunnusta; tyhjä kenttä säilyttää sen. Kun kuluttaja muutetaan yritykseksi, tunnus poistetaan. - **Yhteyshenkilöt**: useita; nimi (pakollinen), titteli tai rooli, puhelin, sähköposti ja lisätieto. - **Laskutusyksiköt**: useita; nimi (pakollinen, oletuksena asiakkaan nimi), laskutusosoite (vapaa teksti: postiosoite tai laskutussähköposti), verkkolaskuosoite (12–35 kirjainta tai numeroa), välittäjätunnus (pakollinen, jos verkkolaskuosoite on annettu) ja viite. Saman asiakkaan eri laskutusyksiköt laskutetaan omilla laskuillaan. -- Asiakkaalla on oma sivu, jolla näkyvät perustiedot, yhteyshenkilöt ja laskutusyksiköt. Uuden asiakkaan tallennus vie asiakkaan sivulle. +- Asiakkaalla on oma sivu, jolla näkyvät perustiedot, yhteyshenkilöt, laskutusyksiköt ja asiakastyöt (numero, nimi, tila; Uusi työ -painike asiakas valmiiksi valittuna). Uuden asiakkaan tallennus vie asiakkaan sivulle. - Asiakastyön vastaanotossa riittää asiakkaan nimi (ja tyyppi); muut tiedot täydennetään myöhemmin. - Yrityksen oma sisäinen asiakas, jonka asiakastöihin kirjataan sisäinen työ (hallinto, myynti, koulutus) *(K39)*. Data-migraatio luo yhden sisäisen asiakkaan "Oma yritys (sisäinen)"; nimen voi muuttaa, mutta se on aina yritys, eikä uusia sisäisiä asiakkaita luoda käyttöliittymästä. @@ -112,7 +112,7 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli | Nimi | `name` | Pakollinen | | Kuvaus | `description` | Pitkä teksti | | Asiakas | `customer_id` | Haku/autocomplete; jos ei löydy, uuden asiakkaan pikalisäys nimellä | -| Palveluyksiköt | `service_units` | Yksi tai useampi *(K28)* | +| Palveluyksiköt | `service_units` | Yksi tai useampi *(K28)*; kaikille yhteistä palveluyksikköä ei valita työlle | | Alkamispäivä | `starts_on` | | | Määräaika | `due_on` | | | Aikataulu | `planned_from`, `planned_to` | Suunniteltu toteutusaikataulu *(K20)*. Kalenterinäkymä näyttää työn tehtävät tekijöittäin, ei työtä itseään (18.3). | @@ -467,6 +467,8 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t - Asiakkaan voi hakea kirjoittamalla tai lisätä nimellä, jos sitä ei löydy. - Tagin voi valita listasta tai lisätä uuden, joka jää listaan. - Laskutusyksikön ja asiakkaan yhteyshenkilön valinta rajautuu valitun asiakkaan tietoihin. +- Vastuuhenkilö, kontaktihenkilö ja laskuttaja valitaan aktiivisista käyttäjistä ilman alihankkijoita; jäseniksi voi valita kenet tahansa aktiivisen käyttäjän. Työllä jo oleva käytöstä poistettu käyttäjä tai palveluyksikkö säilyy. Maksuperusteen oletus on tuntityö. +- Linkit lisätään, muokataan ja poistetaan työn sivulla dialogissa; muutokset näkyvät muutoshistoriassa. - Lista: haku (numero, nimi, asiakas), suodattimet tila, prioriteetti, palveluyksikkö, "omat työt" (oletus päällä). Arkistoidut piilossa oletuksena. - Muutoshistoria näkyy työn sivulla. diff --git a/locale/fi/LC_MESSAGES/django.po b/locale/fi/LC_MESSAGES/django.po index 4d453ba..406e2b5 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 13:59+0200\n" +"POT-Creation-Date: 2026-11-29 14:26+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -25,6 +25,8 @@ msgstr "" #: .\apps\customers\presentation\forms.py:66 #: .\apps\customers\presentation\forms.py:84 #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:8 +#: .\apps\jobs\presentation\forms.py:61 .\apps\jobs\presentation\labels.py:59 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:10 #: .\apps\users\presentation\forms.py:70 #: .\apps\users\presentation\templates\users\partials\user_table.html:8 msgid "Name" @@ -86,6 +88,7 @@ msgstr "Riviä ei voi siirtää pidemmälle." #: .\apps\catalog\presentation\labels.py:13 #: .\apps\customers\presentation\labels.py:39 +#: .\apps\jobs\presentation\labels.py:103 #: .\apps\users\presentation\labels.py:31 msgid "The change could not be saved." msgstr "Muutosta ei voitu tallentaa." @@ -93,12 +96,12 @@ msgstr "Muutosta ei voitu tallentaa." #: .\apps\catalog\presentation\templates\catalog\index.html:2 #: .\apps\catalog\presentation\templates\catalog\index.html:5 #: .\apps\catalog\presentation\templates\catalog\item_form_page.html:5 -#: .\templates\base.html:63 +#: .\templates\base.html:66 msgid "Base data" msgstr "Pohjatiedot" #: .\apps\catalog\presentation\templates\catalog\index.html:9 -#: .\apps\catalog\presentation\views.py:60 +#: .\apps\catalog\presentation\views.py:65 msgid "Add service unit" msgstr "Lisää palveluyksikkö" @@ -107,12 +110,19 @@ msgid "" "Service units, their services and work types. Work types of the shared unit " "can be chosen in every service unit. Rows are not deleted: a row taken out " "of use, and everything under it, can no longer be chosen." -msgstr "Palveluyksiköt, niiden palvelut ja työtehtävät. Kaikille yhteisten työtehtävät ovat valittavissa jokaisessa palveluyksikössä. Rivejä ei poisteta: käytöstä poistettua riviä ja kaikkea sen alla olevaa ei voi enää valita." +msgstr "" +"Palveluyksiköt, niiden palvelut ja työtehtävät. Kaikille yhteisten " +"työtehtävät ovat valittavissa jokaisessa palveluyksikössä. Rivejä ei " +"poisteta: käytöstä poistettua riviä ja kaikkea sen alla olevaa ei voi enää " +"valita." #: .\apps\catalog\presentation\templates\catalog\item_form_page.html:4 #: .\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\jobs\presentation\templates\jobs\detail.html:4 +#: .\apps\jobs\presentation\templates\jobs\form.html:4 +#: .\apps\jobs\presentation\templates\jobs\link_form_page.html:4 #: .\apps\users\presentation\templates\users\form.html:4 msgid "Breadcrumbs" msgstr "Murupolku" @@ -130,6 +140,9 @@ msgstr "Ei käytössä" #: .\apps\customers\presentation\templates\customers\partials\actions.html:2 #: .\apps\customers\presentation\templates\customers\partials\billing_units.html:26 #: .\apps\customers\presentation\templates\customers\partials\contacts.html:23 +#: .\apps\jobs\presentation\templates\jobs\detail.html:17 +#: .\apps\jobs\presentation\templates\jobs\form.html:8 +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:21 msgid "Edit" msgstr "Muokkaa" @@ -160,12 +173,15 @@ msgid "Take into use" msgstr "Ota käyttöön" #: .\apps\catalog\presentation\templates\catalog\partials\item_form.html:2 +#: .\apps\jobs\presentation\forms.py:199 msgid "Service unit" msgstr "Palveluyksikkö" #: .\apps\catalog\presentation\templates\catalog\partials\item_form.html:8 #: .\apps\customers\presentation\templates\customers\form.html:29 #: .\apps\customers\presentation\templates\customers\partials\child_form.html:18 +#: .\apps\jobs\presentation\templates\jobs\form.html:69 +#: .\apps\jobs\presentation\templates\jobs\partials\link_form.html:14 #: .\apps\users\presentation\templates\users\form.html:26 #: .\templates\components\confirm_dialog.html:8 msgid "Cancel" @@ -174,6 +190,8 @@ msgstr "Peruuta" #: .\apps\catalog\presentation\templates\catalog\partials\item_form.html:9 #: .\apps\customers\presentation\templates\customers\form.html:30 #: .\apps\customers\presentation\templates\customers\partials\child_form.html:19 +#: .\apps\jobs\presentation\templates\jobs\form.html:70 +#: .\apps\jobs\presentation\templates\jobs\partials\link_form.html:15 #: .\apps\users\presentation\templates\users\form.html:27 msgid "Save" msgstr "Tallenna" @@ -192,12 +210,12 @@ msgid "No services or work types yet." msgstr "Ei vielä palveluita eikä työtehtäviä." #: .\apps\catalog\presentation\templates\catalog\partials\tree.html:40 -#: .\apps\catalog\presentation\views.py:73 +#: .\apps\catalog\presentation\views.py:78 msgid "Add service" msgstr "Lisää palvelu" #: .\apps\catalog\presentation\templates\catalog\partials\tree.html:45 -#: .\apps\catalog\presentation\views.py:86 +#: .\apps\catalog\presentation\views.py:91 msgid "Add work type" msgstr "Lisää työtehtävä" @@ -205,46 +223,46 @@ msgstr "Lisää työtehtävä" msgid "No service units yet." msgstr "Ei vielä palveluyksiköitä." -#: .\apps\catalog\presentation\views.py:61 +#: .\apps\catalog\presentation\views.py:66 msgid "Edit service unit" msgstr "Muokkaa palveluyksikköä" -#: .\apps\catalog\presentation\views.py:62 +#: .\apps\catalog\presentation\views.py:67 msgid "Service unit saved." msgstr "Palveluyksikkö tallennettu." -#: .\apps\catalog\presentation\views.py:74 +#: .\apps\catalog\presentation\views.py:79 msgid "Edit service" msgstr "Muokkaa palvelua" -#: .\apps\catalog\presentation\views.py:75 +#: .\apps\catalog\presentation\views.py:80 msgid "Service saved." msgstr "Palvelu tallennettu." -#: .\apps\catalog\presentation\views.py:87 +#: .\apps\catalog\presentation\views.py:92 msgid "Edit work type" msgstr "Muokkaa työtehtävää" -#: .\apps\catalog\presentation\views.py:88 +#: .\apps\catalog\presentation\views.py:93 msgid "Work type saved." msgstr "Työtehtävä tallennettu." -#: .\apps\catalog\presentation\views.py:287 +#: .\apps\catalog\presentation\views.py:295 #, python-format msgid "%(name)s moved up." msgstr "%(name)s siirretty ylös." -#: .\apps\catalog\presentation\views.py:289 +#: .\apps\catalog\presentation\views.py:297 #, python-format msgid "%(name)s moved down." msgstr "%(name)s siirretty alas." -#: .\apps\catalog\presentation\views.py:307 +#: .\apps\catalog\presentation\views.py:315 #, python-format msgid "%(name)s is in use again." msgstr "%(name)s otettu käyttöön." -#: .\apps\catalog\presentation\views.py:309 +#: .\apps\catalog\presentation\views.py:317 #, python-format msgid "%(name)s is no longer in use." msgstr "%(name)s poistettu käytöstä." @@ -338,7 +356,7 @@ msgid "Reference" msgstr "Viite" #: .\apps\customers\presentation\forms.py:110 -#: .\apps\users\presentation\forms.py:113 +#: .\apps\jobs\presentation\forms.py:185 .\apps\users\presentation\forms.py:113 msgid "Search" msgstr "Haku" @@ -351,15 +369,18 @@ msgid "All types" msgstr "Kaikki tyypit" #: .\apps\customers\presentation\labels.py:6 +#: .\apps\jobs\presentation\templates\jobs\partials\customer_results.html:30 msgid "Company" msgstr "Yritys" #: .\apps\customers\presentation\labels.py:7 +#: .\apps\jobs\presentation\templates\jobs\partials\customer_results.html:31 msgid "Consumer" msgstr "Kuluttaja" #: .\apps\customers\presentation\labels.py:13 #: .\apps\customers\presentation\labels.py:31 +#: .\apps\jobs\presentation\labels.py:87 msgid "Enter a name (at most 200 characters)." msgstr "Anna nimi (enintään 200 merkkiä)." @@ -447,7 +468,8 @@ msgstr "Laskutusyksikköä ei voi poistaa, koska asiakastyö viittaa siihen." #: .\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 +#: .\apps\jobs\presentation\templates\jobs\partials\customer_results.html:6 +#: .\templates\base.html:60 msgid "Customers" msgstr "Asiakkaat" @@ -457,6 +479,8 @@ msgid "Internal" msgstr "Sisäinen" #: .\apps\customers\presentation\templates\customers\detail.html:17 +#: .\apps\jobs\presentation\templates\jobs\detail.html:23 +#: .\apps\jobs\presentation\templates\jobs\form.html:19 msgid "Basic information" msgstr "Perustiedot" @@ -468,6 +492,22 @@ 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:42 +#: .\apps\jobs\presentation\templates\jobs\detail.html:5 +#: .\apps\jobs\presentation\templates\jobs\form.html:6 +#: .\apps\jobs\presentation\templates\jobs\link_form_page.html:6 +#: .\apps\jobs\presentation\templates\jobs\list.html:2 +#: .\apps\jobs\presentation\templates\jobs\list.html:5 +#: .\apps\jobs\presentation\templates\jobs\partials\customer_jobs.html:5 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:6 +#: .\templates\base.html:57 +msgid "Customer jobs" +msgstr "Asiakastyöt" + +#: .\apps\customers\presentation\templates\customers\detail.html:43 +msgid "Loading…" +msgstr "Ladataan…" + #: .\apps\customers\presentation\templates\customers\form.html:2 #: .\apps\customers\presentation\templates\customers\form.html:11 msgid "Edit customer" @@ -493,6 +533,7 @@ msgid "Filter customers" msgstr "Suodata asiakkaita" #: .\apps\customers\presentation\templates\customers\list.html:16 +#: .\apps\jobs\presentation\templates\jobs\list.html:22 #: .\apps\users\presentation\templates\users\list.html:17 msgid "Filter" msgstr "Suodata" @@ -514,6 +555,8 @@ msgstr "Asiakas poistetaan pysyvästi." #: .\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 +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:23 +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:27 msgid "Delete" msgstr "Poista" @@ -587,6 +630,7 @@ msgid "No contacts yet." msgstr "Ei vielä yhteyshenkilöitä." #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:2 +#: .\apps\jobs\presentation\templates\jobs\partials\customer_results.html:3 #, python-format msgid "%(counter)s customer found" msgid_plural "%(counter)s customers found" @@ -598,22 +642,26 @@ msgid "No customers match the filters." msgstr "Hakuehtoja vastaavia asiakkaita ei löytynyt." #: .\apps\customers\presentation\templates\customers\partials\customer_table.html:30 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:59 #: .\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\jobs\presentation\templates\jobs\partials\job_table.html:62 #: .\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\jobs\presentation\templates\jobs\partials\job_table.html:64 #: .\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\jobs\presentation\templates\jobs\partials\job_table.html:67 #: .\apps\users\presentation\templates\users\partials\user_table.html:44 msgid "Next" msgstr "Seuraava" @@ -631,7 +679,7 @@ msgid "Customer created." msgstr "Asiakas luotu." #: .\apps\customers\presentation\views.py:133 -#: .\apps\users\presentation\views.py:198 +#: .\apps\jobs\presentation\views.py:209 .\apps\users\presentation\views.py:198 msgid "Changes saved." msgstr "Muutokset tallennettu." @@ -655,6 +703,516 @@ msgstr "Laskutusyksikkö tallennettu." msgid "Billing unit deleted." msgstr "Laskutusyksikkö poistettu." +#: .\apps\jobs\presentation\forms.py:57 .\apps\jobs\presentation\labels.py:60 +#: .\apps\jobs\presentation\templates\jobs\detail.html:25 +#: .\apps\jobs\presentation\templates\jobs\partials\customer_picker.html:5 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:11 +msgid "Customer" +msgstr "Asiakas" + +#: .\apps\jobs\presentation\forms.py:59 .\apps\jobs\presentation\labels.py:99 +msgid "Choose a customer." +msgstr "Valitse asiakas." + +#: .\apps\jobs\presentation\forms.py:63 .\apps\jobs\presentation\labels.py:62 +#: .\apps\jobs\presentation\templates\jobs\detail.html:73 +msgid "Description" +msgstr "Kuvaus" + +#: .\apps\jobs\presentation\forms.py:66 .\apps\jobs\presentation\labels.py:61 +#: .\apps\jobs\presentation\templates\jobs\detail.html:27 +msgid "Service units" +msgstr "Palveluyksiköt" + +#: .\apps\jobs\presentation\forms.py:69 .\apps\jobs\presentation\labels.py:92 +msgid "Choose at least one service unit." +msgstr "Valitse vähintään yksi palveluyksikkö." + +#: .\apps\jobs\presentation\forms.py:71 .\apps\jobs\presentation\labels.py:67 +#: .\apps\jobs\presentation\templates\jobs\detail.html:29 +msgid "Kind" +msgstr "Kesto / laji" + +#: .\apps\jobs\presentation\forms.py:72 .\apps\jobs\presentation\forms.py:192 +#: .\apps\jobs\presentation\labels.py:68 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:12 +#: .\apps\jobs\presentation\templates\jobs\partials\status_badge.html:1 +#: .\apps\users\presentation\forms.py:118 +#: .\apps\users\presentation\templates\users\partials\user_table.html:11 +msgid "Status" +msgstr "Tila" + +#: .\apps\jobs\presentation\forms.py:73 .\apps\jobs\presentation\forms.py:194 +#: .\apps\jobs\presentation\labels.py:69 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:13 +#: .\apps\jobs\presentation\templates\jobs\partials\priority_badge.html:1 +msgid "Priority" +msgstr "Prioriteetti" + +#: .\apps\jobs\presentation\forms.py:75 .\apps\jobs\presentation\labels.py:70 +#: .\apps\jobs\presentation\templates\jobs\detail.html:30 +msgid "Payment basis" +msgstr "Maksuperuste" + +#: .\apps\jobs\presentation\forms.py:77 .\apps\jobs\presentation\labels.py:63 +#: .\apps\jobs\presentation\templates\jobs\detail.html:45 +msgid "Start date" +msgstr "Alkamispäivä" + +#: .\apps\jobs\presentation\forms.py:78 .\apps\jobs\presentation\labels.py:64 +#: .\apps\jobs\presentation\templates\jobs\detail.html:46 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:14 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:50 +msgid "Due date" +msgstr "Määräaika" + +#: .\apps\jobs\presentation\forms.py:79 .\apps\jobs\presentation\labels.py:65 +msgid "Planned start" +msgstr "Suunniteltu alku" + +#: .\apps\jobs\presentation\forms.py:80 .\apps\jobs\presentation\labels.py:66 +msgid "Planned end" +msgstr "Suunniteltu loppu" + +#: .\apps\jobs\presentation\forms.py:82 .\apps\jobs\presentation\labels.py:71 +#: .\apps\jobs\presentation\templates\jobs\detail.html:31 +msgid "Estimated hours" +msgstr "Arvioidut tunnit" + +#: .\apps\jobs\presentation\forms.py:91 .\apps\jobs\presentation\labels.py:72 +#: .\apps\jobs\presentation\templates\jobs\detail.html:32 +msgid "Customer reference (PO)" +msgstr "Asiakkaan viite (PO)" + +#: .\apps\jobs\presentation\forms.py:94 .\apps\jobs\presentation\labels.py:73 +#: .\apps\jobs\presentation\templates\jobs\detail.html:75 +#: .\apps\jobs\presentation\templates\jobs\form.html:63 +msgid "Instructions" +msgstr "Ohjeistus" + +#: .\apps\jobs\presentation\forms.py:97 +msgid "Things to note about the job; subcontractors see them too." +msgstr "Työhön liittyvät asiat ja huomiot; myös alihankkijat näkevät ne." + +#: .\apps\jobs\presentation\forms.py:99 .\apps\jobs\presentation\labels.py:74 +#: .\apps\jobs\presentation\templates\jobs\detail.html:58 +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:15 +msgid "Responsible person" +msgstr "Vastuuhenkilö" + +#: .\apps\jobs\presentation\forms.py:100 .\apps\jobs\presentation\labels.py:75 +#: .\apps\jobs\presentation\templates\jobs\detail.html:59 +msgid "Contact person" +msgstr "Kontaktihenkilö" + +#: .\apps\jobs\presentation\forms.py:101 .\apps\jobs\presentation\labels.py:76 +#: .\apps\jobs\presentation\templates\jobs\detail.html:60 +msgid "Customer's contact" +msgstr "Asiakkaan yhteyshenkilö" + +#: .\apps\jobs\presentation\forms.py:102 .\apps\jobs\presentation\labels.py:77 +#: .\apps\jobs\presentation\templates\jobs\detail.html:61 +msgid "Biller" +msgstr "Laskuttaja" + +#: .\apps\jobs\presentation\forms.py:103 .\apps\jobs\presentation\labels.py:78 +#: .\apps\jobs\presentation\templates\jobs\detail.html:62 +msgid "Billing unit" +msgstr "Laskutusyksikkö" + +#: .\apps\jobs\presentation\forms.py:105 .\apps\jobs\presentation\labels.py:79 +#: .\apps\jobs\presentation\templates\jobs\detail.html:63 +msgid "Other members" +msgstr "Muut jäsenet" + +#: .\apps\jobs\presentation\forms.py:109 +msgid "The job shows in their own jobs. Subcontractors see only such jobs." +msgstr "Työ näkyy heidän omissa töissään. Alihankkijat näkevät vain tällaiset työt." + +#: .\apps\jobs\presentation\forms.py:111 .\apps\jobs\presentation\labels.py:80 +#: .\apps\jobs\presentation\templates\jobs\detail.html:33 +#: .\apps\jobs\presentation\templates\jobs\detail.html:34 +#: .\apps\jobs\presentation\templates\jobs\partials\tags_input.html:22 +msgid "Tags" +msgstr "Tagit" + +#: .\apps\jobs\presentation\forms.py:125 +msgid "Not chosen" +msgstr "Ei valittu" + +#: .\apps\jobs\presentation\forms.py:165 +msgid "Title" +msgstr "Otsikko" + +#: .\apps\jobs\presentation\forms.py:168 +msgid "For example: Material folder. Empty shows the address." +msgstr "Esimerkiksi: Aineistokansio. Tyhjänä näytetään osoite." + +#: .\apps\jobs\presentation\forms.py:171 +msgid "Web address" +msgstr "Verkko-osoite" + +#: .\apps\jobs\presentation\forms.py:185 +msgid "Number, name or customer" +msgstr "Numero, nimi tai asiakas" + +#: .\apps\jobs\presentation\forms.py:188 +msgid "Show" +msgstr "Näytä" + +#: .\apps\jobs\presentation\forms.py:190 +msgid "My jobs" +msgstr "Omat työt" + +#: .\apps\jobs\presentation\forms.py:190 +msgid "All jobs" +msgstr "Kaikki työt" + +#: .\apps\jobs\presentation\forms.py:196 +msgid "All priorities" +msgstr "Kaikki prioriteetit" + +#: .\apps\jobs\presentation\forms.py:201 +msgid "Show archived jobs" +msgstr "Näytä arkistoidut työt" + +#: .\apps\jobs\presentation\forms.py:206 +msgid "All statuses" +msgstr "Kaikki tilat" + +#: .\apps\jobs\presentation\forms.py:207 +msgid "All service units" +msgstr "Kaikki palveluyksiköt" + +#: .\apps\jobs\presentation\labels.py:6 +msgid "Prospect" +msgstr "Prospekti" + +#: .\apps\jobs\presentation\labels.py:7 +msgid "Tentative" +msgstr "Alustava" + +#: .\apps\jobs\presentation\labels.py:8 +msgid "Quote request" +msgstr "Tarjouspyyntö" + +#: .\apps\jobs\presentation\labels.py:9 +msgid "Order" +msgstr "Tilaus" + +#: .\apps\jobs\presentation\labels.py:10 +msgid "In production" +msgstr "Tuotannossa" + +#: .\apps\jobs\presentation\labels.py:11 +msgid "On hold" +msgstr "Keskeytetty" + +#: .\apps\jobs\presentation\labels.py:12 +msgid "Done" +msgstr "Valmis" + +#: .\apps\jobs\presentation\labels.py:13 +msgid "Invoice created" +msgstr "Lasku luotu" + +#: .\apps\jobs\presentation\labels.py:14 +msgid "Invoiced" +msgstr "Laskutettu" + +#: .\apps\jobs\presentation\labels.py:15 +msgid "Archived" +msgstr "Arkistoitu" + +#: .\apps\jobs\presentation\labels.py:19 +msgid "Waiting" +msgstr "Odottaa" + +#: .\apps\jobs\presentation\labels.py:20 +msgid "Normal" +msgstr "Normaali" + +#: .\apps\jobs\presentation\labels.py:21 +msgid "First" +msgstr "Ensin" + +#: .\apps\jobs\presentation\labels.py:22 +msgid "Urgent" +msgstr "Kiire" + +#: .\apps\jobs\presentation\labels.py:23 +msgid "Immediately" +msgstr "Heti" + +#: .\apps\jobs\presentation\labels.py:36 +msgid "Service job" +msgstr "Palvelutyö" + +#: .\apps\jobs\presentation\labels.py:37 +msgid "One-off" +msgstr "Kertaluonteinen" + +#: .\apps\jobs\presentation\labels.py:38 +msgid "Fixed-term" +msgstr "Määräaikainen" + +#: .\apps\jobs\presentation\labels.py:39 +msgid "Ongoing" +msgstr "Toistaiseksi jatkuva" + +#: .\apps\jobs\presentation\labels.py:43 +msgid "Fixed price list" +msgstr "Kiinteä hinnasto" + +#: .\apps\jobs\presentation\labels.py:44 +msgid "Fixed, based on a quote" +msgstr "Kiinteä tarjouksen perusteella" + +#: .\apps\jobs\presentation\labels.py:45 +msgid "Fixed monthly fee" +msgstr "Kiinteä kk-laskutus" + +#: .\apps\jobs\presentation\labels.py:46 +msgid "Hourly" +msgstr "Tuntityö" + +#: .\apps\jobs\presentation\labels.py:47 +msgid "Not billable" +msgstr "Ei laskutettava" + +#: .\apps\jobs\presentation\labels.py:81 +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:4 +msgid "Links" +msgstr "Linkit" + +#: .\apps\jobs\presentation\labels.py:88 +msgid "Enter hours between 0 and 9999.99." +msgstr "Anna tunnit väliltä 0–9999,99." + +#: .\apps\jobs\presentation\labels.py:89 +msgid "A tag is at most 50 characters and contains no commas." +msgstr "Tagissa on enintään 50 merkkiä eikä pilkkuja." + +#: .\apps\jobs\presentation\labels.py:90 +msgid "Enter a web address starting with http:// or https://." +msgstr "Anna verkko-osoite, joka alkaa http:// tai https://." + +#: .\apps\jobs\presentation\labels.py:91 +msgid "Enter a title of at most 200 characters." +msgstr "Anna enintään 200 merkin otsikko." + +#: .\apps\jobs\presentation\labels.py:93 +msgid "A chosen service unit is no longer in use." +msgstr "Valittu palveluyksikkö ei ole enää käytössä." + +#: .\apps\jobs\presentation\labels.py:94 +msgid "The planned end cannot be before the planned start." +msgstr "Suunniteltu loppu ei voi olla ennen suunniteltua alkua." + +#: .\apps\jobs\presentation\labels.py:95 +msgid "The due date cannot be before the start date." +msgstr "Määräaika ei voi olla ennen alkamispäivää." + +#: .\apps\jobs\presentation\labels.py:96 +msgid "You are not allowed to set this status." +msgstr "Sinulla ei ole oikeutta asettaa tätä tilaa." + +#: .\apps\jobs\presentation\labels.py:97 +msgid "The job was not found." +msgstr "Työtä ei löytynyt." + +#: .\apps\jobs\presentation\labels.py:98 +msgid "The link was not found." +msgstr "Linkkiä ei löytynyt." + +#: .\apps\jobs\presentation\labels.py:100 +msgid "Choose a contact of the selected customer." +msgstr "Valitse valitun asiakkaan yhteyshenkilö." + +#: .\apps\jobs\presentation\labels.py:101 +msgid "Choose a billing unit of the selected customer." +msgstr "Valitse valitun asiakkaan laskutusyksikkö." + +#: .\apps\jobs\presentation\labels.py:102 +msgid "Choose an active user." +msgstr "Valitse aktiivinen käyttäjä." + +#: .\apps\jobs\presentation\templates\jobs\detail.html:35 +msgid "Created" +msgstr "Luotu" + +#: .\apps\jobs\presentation\templates\jobs\detail.html:43 +#: .\apps\jobs\presentation\templates\jobs\form.html:38 +msgid "Schedule" +msgstr "Aikataulu" + +#: .\apps\jobs\presentation\templates\jobs\detail.html:48 +msgid "Planned schedule" +msgstr "Suunniteltu aikataulu" + +#: .\apps\jobs\presentation\templates\jobs\detail.html:56 +#: .\apps\jobs\presentation\templates\jobs\form.html:50 +msgid "People and invoicing" +msgstr "Henkilöt ja laskutus" + +#: .\apps\jobs\presentation\templates\jobs\form.html:2 +msgid "Edit job" +msgstr "Muokkaa työtä" + +#: .\apps\jobs\presentation\templates\jobs\form.html:2 +#: .\apps\jobs\presentation\templates\jobs\form.html:8 +#: .\apps\jobs\presentation\templates\jobs\form.html:11 +#: .\apps\jobs\presentation\templates\jobs\list.html:7 +#: .\apps\jobs\presentation\templates\jobs\partials\customer_jobs.html:6 +msgid "New job" +msgstr "Uusi työ" + +#: .\apps\jobs\presentation\templates\jobs\form.html:11 +#, python-format +msgid "Edit job %(number)s" +msgstr "Muokkaa työtä %(number)s" + +#: .\apps\jobs\presentation\templates\jobs\list.html:11 +msgid "Filter jobs" +msgstr "Suodata töitä" + +#: .\apps\jobs\presentation\templates\jobs\partials\customer_jobs.html:21 +msgid "The customer has no jobs yet." +msgstr "Asiakkaalla ei ole vielä töitä." + +#: .\apps\jobs\presentation\templates\jobs\partials\customer_picker.html:5 +#: .\templates\components\field.html:10 +msgid "(required)" +msgstr "(pakollinen)" + +#: .\apps\jobs\presentation\templates\jobs\partials\customer_results.html:21 +msgid "No customers found." +msgstr "Asiakkaita ei löytynyt." + +#: .\apps\jobs\presentation\templates\jobs\partials\customer_results.html:23 +msgid "Type to search. If the customer is not found, you can add it by name." +msgstr "Kirjoita hakeaksesi. Jos asiakasta ei löydy, voit lisätä sen nimellä." + +#: .\apps\jobs\presentation\templates\jobs\partials\customer_results.html:28 +#, python-format +msgid "Add “%(term)s” as a new customer" +msgstr "Lisää ”%(term)s” uudeksi asiakkaaksi" + +#: .\apps\jobs\presentation\templates\jobs\partials\customer_results.html:37 +msgid "Add customer" +msgstr "Lisää asiakas" + +#: .\apps\jobs\presentation\templates\jobs\partials\customer_search_input.html:2 +msgid "Search customer by name or business ID" +msgstr "Hae asiakasta nimellä tai Y-tunnuksella" + +#: .\apps\jobs\presentation\templates\jobs\partials\history.html:4 +msgid "Change history" +msgstr "Muutoshistoria" + +#: .\apps\jobs\presentation\templates\jobs\partials\history.html:12 +msgid "Before" +msgstr "Ennen" + +#: .\apps\jobs\presentation\templates\jobs\partials\history.html:14 +msgid "After" +msgstr "Jälkeen" + +#: .\apps\jobs\presentation\templates\jobs\partials\history.html:21 +msgid "No changes since the job was created." +msgstr "Ei muutoksia työn luonnin jälkeen." + +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:1 +#, python-format +msgid "%(counter)s job found" +msgid_plural "%(counter)s jobs found" +msgstr[0] "%(counter)s työ löytyi" +msgstr[1] "%(counter)s työtä löytyi" + +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:9 +msgid "Number" +msgstr "Numero" + +#: .\apps\jobs\presentation\templates\jobs\partials\job_table.html:56 +msgid "No jobs match the filters." +msgstr "Suodattimia vastaavia töitä ei ole." + +#: .\apps\jobs\presentation\templates\jobs\partials\late_badge.html:1 +msgid "Late" +msgstr "Myöhässä" + +#: .\apps\jobs\presentation\templates\jobs\partials\link_form.html:7 +msgid "Edit link" +msgstr "Muokkaa linkkiä" + +#: .\apps\jobs\presentation\templates\jobs\partials\link_form.html:7 +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:8 +msgid "Add link" +msgstr "Lisää linkki" + +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:15 +msgid "(opens in a new tab)" +msgstr "(avautuu uuteen välilehteen)" + +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:25 +#, python-format +msgid "Delete link %(title)s?" +msgstr "Poistetaanko linkki %(title)s?" + +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:26 +msgid "The link is removed from the job. The file itself is not touched." +msgstr "Linkki poistetaan työltä. Itse tiedostoon ei kosketa." + +#: .\apps\jobs\presentation\templates\jobs\partials\links.html:35 +msgid "No links yet." +msgstr "Ei vielä linkkejä." + +#: .\apps\jobs\presentation\templates\jobs\partials\tags_input.html:3 +msgid "Tag added" +msgstr "Tagi lisätty" + +#: .\apps\jobs\presentation\templates\jobs\partials\tags_input.html:3 +msgid "Tag removed" +msgstr "Tagi poistettu" + +#: .\apps\jobs\presentation\templates\jobs\partials\tags_input.html:3 +msgid "Remove tag" +msgstr "Poista tagi" + +#: .\apps\jobs\presentation\templates\jobs\partials\tags_input.html:23 +msgid "Chosen tags" +msgstr "Valitut tagit" + +#: .\apps\jobs\presentation\templates\jobs\partials\tags_input.html:38 +msgid "Add tag" +msgstr "Lisää tagi" + +#: .\apps\jobs\presentation\templates\jobs\partials\tags_input.html:41 +msgid "Choose from the list or type a new tag and press Enter." +msgstr "Valitse listasta tai kirjoita uusi tagi ja paina Enter." + +#: .\apps\jobs\presentation\views.py:183 +#, python-format +msgid "Job %(number)s created." +msgstr "Työ %(number)s luotu." + +#: .\apps\jobs\presentation\views.py:329 .\apps\jobs\presentation\views.py:330 +msgid "Link saved." +msgstr "Linkki tallennettu." + +#: .\apps\jobs\presentation\views.py:340 +msgid "Link deleted." +msgstr "Linkki poistettu." + +#: .\apps\jobs\presentation\views.py:404 +msgid "Enter a customer name of at most 200 characters." +msgstr "Anna asiakkaan nimi, enintään 200 merkkiä." + +#: .\apps\jobs\presentation\views.py:411 +#, python-format +msgid "Customer %(name)s added and selected." +msgstr "Asiakas %(name)s lisätty ja valittu." + #: .\apps\users\infrastructure\password.py:15 #, python-format msgid "The password must be at least %(min)d characters long." @@ -730,11 +1288,6 @@ msgstr "Valitse vastuuhenkilö" msgid "All roles" msgstr "Kaikki roolit" -#: .\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:120 msgid "All" msgstr "Kaikki" @@ -872,7 +1425,7 @@ msgstr "Uusi käyttäjä" #: .\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:66 +#: .\templates\base.html:69 msgid "Users" msgstr "Käyttäjät" @@ -1046,7 +1599,7 @@ msgstr "Siirry sisältöön" msgid "Open menu" msgstr "Avaa valikko" -#: .\templates\base.html:40 .\templates\base.html:74 +#: .\templates\base.html:40 .\templates\base.html:77 msgid "Log out" msgstr "Kirjaudu ulos" @@ -1058,14 +1611,10 @@ msgstr "Päävalikko" msgid "Home" msgstr "Etusivu" -#: .\templates\base.html:60 +#: .\templates\base.html:63 msgid "Administration" msgstr "Hallinto" -#: .\templates\components\field.html:10 -msgid "(required)" -msgstr "(pakollinen)" - #: .\templates\components\theme_toggle.html:5 msgid "Dark theme" msgstr "Tumma teema" @@ -1079,8 +1628,5 @@ msgstr "Tervetuloa, %(name)s" msgid "The dashboard will be built in a later step." msgstr "Työpöytä rakennetaan myöhemmässä vaiheessa." -#~ msgid "Show menu" -#~ msgstr "Näytä valikko" - #~ msgid "Close menu" #~ msgstr "Sulje valikko" diff --git a/pyproject.toml b/pyproject.toml index 80a3216..334d690 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,6 +50,8 @@ source_modules = [ "apps.customers.application", "apps.catalog.domain", "apps.catalog.application", + "apps.jobs.domain", + "apps.jobs.application", ] forbidden_modules = ["django"] allow_indirect_imports = true @@ -93,6 +95,18 @@ layers = [ ] ignore_imports = ["apps.catalog.presentation.** -> apps.catalog.container"] +[[tool.importlinter.contracts]] +name = "jobs layers" +type = "layers" +layers = [ + "apps.jobs.container", + "apps.jobs.presentation", + "apps.jobs.infrastructure", + "apps.jobs.application", + "apps.jobs.domain", +] +ignore_imports = ["apps.jobs.presentation.** -> apps.jobs.container"] + [[tool.importlinter.contracts]] name = "Presentation does not use infrastructure directly" type = "forbidden" @@ -100,11 +114,13 @@ source_modules = [ "apps.users.presentation", "apps.customers.presentation", "apps.catalog.presentation", + "apps.jobs.presentation", ] forbidden_modules = [ "apps.users.infrastructure", "apps.customers.infrastructure", "apps.catalog.infrastructure", + "apps.jobs.infrastructure", ] allow_indirect_imports = true @@ -123,6 +139,44 @@ ignore_imports = [ "apps.catalog.tests.** -> apps.users.infrastructure.**", ] +[[tool.importlinter.contracts]] +name = "jobs uses other modules only through application interfaces and containers" +type = "forbidden" +source_modules = ["apps.jobs"] +forbidden_modules = [ + "apps.users.infrastructure", + "apps.customers.infrastructure", + "apps.customers.presentation", + "apps.catalog.infrastructure", + "apps.catalog.presentation", +] +# The jobs container reaches their infrastructure only through their own containers. +allow_indirect_imports = true +ignore_imports = [ + # Integration tests may arrange data with another module's models. + "apps.jobs.tests.** -> apps.users.infrastructure.**", + "apps.jobs.tests.** -> apps.customers.infrastructure.**", + "apps.jobs.tests.** -> apps.catalog.infrastructure.**", +] + +[[tool.importlinter.contracts]] +name = "Only the jobs container wires other modules' containers" +type = "forbidden" +source_modules = [ + "apps.jobs.domain", + "apps.jobs.application", + "apps.jobs.infrastructure", + "apps.jobs.presentation", +] +forbidden_modules = ["apps.users.container", "apps.customers.container", "apps.catalog.container"] +allow_indirect_imports = true + +[[tool.importlinter.contracts]] +name = "Other modules do not depend on jobs" +type = "forbidden" +source_modules = ["apps.users", "apps.customers", "apps.catalog"] +forbidden_modules = ["apps.jobs"] + [[tool.importlinter.contracts]] name = "customers and catalog are independent" type = "independence" diff --git a/static/src/app.css b/static/src/app.css index 285263c..ad5abfb 100644 --- a/static/src/app.css +++ b/static/src/app.css @@ -36,3 +36,14 @@ --color-success: oklch(48% 0.12 155); --color-success-content: oklch(100% 0 0); } + +/* Job priority "immediately": striped, and always labelled with text and an icon. */ +.priority-immediate { + background-image: repeating-linear-gradient( + 135deg, + var(--color-error) 0 6px, + color-mix(in oklch, var(--color-error) 75%, black) 6px 12px + ); + border-color: var(--color-error); + color: var(--color-error-content); +} diff --git a/templates/base.html b/templates/base.html index 1c99f48..8905ab0 100644 --- a/templates/base.html +++ b/templates/base.html @@ -53,6 +53,9 @@