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 %}
+
+{% 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). #}
+
+ {{ 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. #}
+
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 %}
+
+{% endif %}
+{% if selected_customer or results %}
+
+ {% if selected_customer %}
+
+ {% endif %}
+ {% for c in results %}
+
+ {% endfor %}
+
+{% 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 %}
+
+
+
+
+{% endif %}
+{% if add_error %}
{{ 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" %}
+ {% include "jobs/partials/status_badge.html" with status=j.status %}
+ {% include "jobs/partials/priority_badge.html" with priority=j.priority %}
+ {% if j.is_late %}{% include "jobs/partials/late_badge.html" %}{% endif %}
+
+
+ {% translate "Edit" %}: {{ link.title }}
+
+ {% url 'jobs:link_delete' job.id link.id as delete_url %}
+ {% blocktranslate with title=link.title asvar dialog_title %}Delete link {{ title }}?{% endblocktranslate %}
+ {% translate "The link is removed from the job. The file itself is not touched." as dialog_body %}
+ {% translate "Delete" as dialog_confirm %}
+ {% with dialog_id="confirm-delete-link-"|add:id_str %}{% include "components/confirm_dialog.html" with id=dialog_id title=dialog_title body=dialog_body action_url=delete_url confirm_label=dialog_confirm hx_target="#links-section" %}{% endwith %}
+
+ {% endif %}
+
+ {% endwith %}{% endfor %}
+
+ {% else %}
+
{% translate "No links yet." %}
+ {% endif %}
+
+
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 %}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{% 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 %}