- 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 <[email protected]>
321 lines
12 KiB
Python
321 lines
12 KiB
Python
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), "")]
|
|
)
|