Vaihe 1/4: asiakastyöt (numerointi, tagit, linkit, jäsenet, muutoshistoria)
- 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]>
This commit is contained in:
@@ -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
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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: ...
|
||||
@@ -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)]
|
||||
@@ -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})"
|
||||
Reference in New Issue
Block a user