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})"