Files
petriandClaude Opus 5.5 1ca03137fd 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]>
2026-11-29 14:38:42 +02:00

221 lines
8.4 KiB
Python

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"]),
)