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