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:
2026-11-29 14:38:42 +02:00
co-authored by Claude Opus 5.5
parent 679bf57eb4
commit 1ca03137fd
72 changed files with 4907 additions and 44 deletions
View File
+220
View File
@@ -0,0 +1,220 @@
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"]),
)
+104
View File
@@ -0,0 +1,104 @@
from django.utils.translation import gettext_lazy as _
from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority
STATUS_LABELS = {
JobStatus.PROSPECT: _("Prospect"),
JobStatus.TENTATIVE: _("Tentative"),
JobStatus.QUOTE_REQUEST: _("Quote request"),
JobStatus.ORDER: _("Order"),
JobStatus.IN_PRODUCTION: _("In production"),
JobStatus.ON_HOLD: _("On hold"),
JobStatus.DONE: _("Done"),
JobStatus.INVOICED: _("Invoice created"),
JobStatus.BILLED: _("Invoiced"),
JobStatus.ARCHIVED: _("Archived"),
}
PRIORITY_LABELS = {
Priority.WAITING: _("Waiting"),
Priority.NORMAL: _("Normal"),
Priority.FIRST: _("First"),
Priority.URGENT: _("Urgent"),
Priority.IMMEDIATE: _("Immediately"),
}
# daisyUI badge classes; the text and icon always carry the meaning too.
PRIORITY_CLASSES = {
Priority.WAITING: "badge-info badge-soft",
Priority.NORMAL: "badge-success badge-soft",
Priority.FIRST: "badge-warning badge-soft",
Priority.URGENT: "badge-error badge-soft",
Priority.IMMEDIATE: "badge-error priority-immediate",
}
KIND_LABELS = {
JobKind.SERVICE: _("Service job"),
JobKind.ONE_OFF: _("One-off"),
JobKind.FIXED_TERM: _("Fixed-term"),
JobKind.ONGOING: _("Ongoing"),
}
PAYMENT_BASIS_LABELS = {
PaymentBasis.PRICE_LIST: _("Fixed price list"),
PaymentBasis.FIXED_QUOTE: _("Fixed, based on a quote"),
PaymentBasis.MONTHLY_FEE: _("Fixed monthly fee"),
PaymentBasis.HOURLY: _("Hourly"),
PaymentBasis.NOT_BILLABLE: _("Not billable"),
}
ENUM_LABELS = {
"status": STATUS_LABELS,
"priority": PRIORITY_LABELS,
"kind": KIND_LABELS,
"payment_basis": PAYMENT_BASIS_LABELS,
}
# Change history field names (keys from the application layer's FIELD_KEYS, plus links).
FIELD_LABELS = {
"name": _("Name"),
"customer": _("Customer"),
"service_units": _("Service units"),
"description": _("Description"),
"starts_on": _("Start date"),
"due_on": _("Due date"),
"planned_from": _("Planned start"),
"planned_to": _("Planned end"),
"kind": _("Kind"),
"status": _("Status"),
"priority": _("Priority"),
"payment_basis": _("Payment basis"),
"estimated_hours": _("Estimated hours"),
"customer_reference": _("Customer reference (PO)"),
"instructions": _("Instructions"),
"responsible_user": _("Responsible person"),
"contact_user": _("Contact person"),
"customer_contact": _("Customer's contact"),
"biller_user": _("Biller"),
"billing_unit": _("Billing unit"),
"members": _("Other members"),
"tags": _("Tags"),
"links": _("Links"),
}
DATE_FIELDS = frozenset({"starts_on", "due_on", "planned_from", "planned_to"})
ERROR_MESSAGES = {
"invalid_job_name": _("Enter a name (at most 200 characters)."),
"invalid_estimated_hours": _("Enter hours between 0 and 9999.99."),
"invalid_tag_name": _("A tag is at most 50 characters and contains no commas."),
"invalid_link_url": _("Enter a web address starting with http:// or https://."),
"invalid_link_title": _("Enter a title of at most 200 characters."),
"service_unit_required": _("Choose at least one service unit."),
"service_unit_not_selectable": _("A chosen service unit is no longer in use."),
"planned_range_invalid": _("The planned end cannot be before the planned start."),
"due_before_start": _("The due date cannot be before the start date."),
"status_not_allowed": _("You are not allowed to set this status."),
"customer_job_not_found": _("The job was not found."),
"job_link_not_found": _("The link was not found."),
"unknown_customer": _("Choose a customer."),
"contact_not_of_customer": _("Choose a contact of the selected customer."),
"billing_unit_not_of_customer": _("Choose a billing unit of the selected customer."),
"user_not_selectable": _("Choose an active user."),
"*": _("The change could not be saved."),
}
@@ -0,0 +1,86 @@
{% extends "base.html" %}{% load jobs_tags %}
{% block title %}{{ job.number }} {{ job.name }}{% endblock %}
{% block content %}
<nav class="breadcrumbs text-sm" aria-label="{% translate 'Breadcrumbs' %}">
<ul><li><a href="{% url 'jobs:list' %}">{% translate "Customer jobs" %}</a></li><li aria-current="page">{{ job.number }}</li></ul>
</nav>
<div class="flex flex-wrap items-start justify-between gap-2 mb-4">
<div class="min-w-0">
<p class="text-sm">{{ job.number }}</p>
<h1 class="text-2xl font-bold break-words">{{ job.name }}</h1>
<div class="flex flex-wrap gap-1 mt-2">
{% include "jobs/partials/status_badge.html" with status=job.status %}
{% include "jobs/partials/priority_badge.html" with priority=job.priority %}
{% if job.is_late %}{% include "jobs/partials/late_badge.html" %}{% endif %}
</div>
</div>
{% if can_edit %}<a href="{% url 'jobs:edit' job.id %}" class="btn">{% translate "Edit" %}</a>{% endif %}
</div>
<div class="grid gap-4 lg:grid-cols-2">
<section class="card bg-base-100 shadow-sm" aria-labelledby="basic-heading">
<div class="card-body">
<h2 id="basic-heading" class="card-title">{% translate "Basic information" %}</h2>
<dl class="grid gap-x-6 gap-y-2 sm:grid-cols-[max-content_1fr]">
<dt class="font-semibold">{% translate "Customer" %}</dt>
<dd>{% if can_see_customer %}<a class="link" href="{% url 'customers:detail' job.customer.id %}">{{ job.customer.name }}</a>{% else %}{{ job.customer.name }}{% endif %}</dd>
<dt class="font-semibold">{% translate "Service units" %}</dt>
<dd>{% for u in job.service_units %}{{ u.name }}{% if not forloop.last %}, {% endif %}{% empty %}–{% endfor %}</dd>
<dt class="font-semibold">{% translate "Kind" %}</dt><dd>{{ job.kind|kind_label }}</dd>
<dt class="font-semibold">{% translate "Payment basis" %}</dt><dd>{{ job.payment_basis|payment_basis_label }}</dd>
<dt class="font-semibold">{% translate "Estimated hours" %}</dt><dd>{% if job.estimated_hours is not None %}{{ job.estimated_hours }} h{% else %}–{% endif %}</dd>
<dt class="font-semibold">{% translate "Customer reference (PO)" %}</dt><dd>{{ job.customer_reference|default:"–" }}</dd>
<dt class="font-semibold">{% translate "Tags" %}</dt>
<dd>{% if job.tags %}<ul class="flex flex-wrap gap-1" aria-label="{% translate 'Tags' %}">{% for t in job.tags %}<li class="badge badge-outline">{{ t }}</li>{% endfor %}</ul>{% else %}–{% endif %}</dd>
<dt class="font-semibold">{% translate "Created" %}</dt>
<dd>{{ job.created_at|date:"SHORT_DATE_FORMAT" }}{% if job.created_by %}, {{ job.created_by.name }}{% endif %}</dd>
</dl>
</div>
</section>
<section class="card bg-base-100 shadow-sm" aria-labelledby="schedule-heading">
<div class="card-body">
<h2 id="schedule-heading" class="card-title">{% translate "Schedule" %}</h2>
<dl class="grid gap-x-6 gap-y-2 sm:grid-cols-[max-content_1fr]">
<dt class="font-semibold">{% translate "Start date" %}</dt><dd>{{ job.starts_on|date:"SHORT_DATE_FORMAT"|default:"–" }}</dd>
<dt class="font-semibold">{% translate "Due date" %}</dt>
<dd>{{ job.due_on|date:"SHORT_DATE_FORMAT"|default:"–" }}{% if job.is_late %} {% include "jobs/partials/late_badge.html" %}{% endif %}</dd>
<dt class="font-semibold">{% translate "Planned schedule" %}</dt>
<dd>{% if job.planned_from or job.planned_to %}{{ job.planned_from|date:"SHORT_DATE_FORMAT"|default:"…" }} – {{ job.planned_to|date:"SHORT_DATE_FORMAT"|default:"…" }}{% else %}–{% endif %}</dd>
</dl>
</div>
</section>
<section class="card bg-base-100 shadow-sm" aria-labelledby="people-heading">
<div class="card-body">
<h2 id="people-heading" class="card-title">{% translate "People and invoicing" %}</h2>
<dl class="grid gap-x-6 gap-y-2 sm:grid-cols-[max-content_1fr]">
<dt class="font-semibold">{% translate "Responsible person" %}</dt><dd>{{ job.responsible.name|default:"–" }}</dd>
<dt class="font-semibold">{% translate "Contact person" %}</dt><dd>{{ job.contact_user.name|default:"–" }}</dd>
<dt class="font-semibold">{% translate "Customer's contact" %}</dt><dd>{{ job.customer_contact.name|default:"–" }}</dd>
<dt class="font-semibold">{% translate "Biller" %}</dt><dd>{{ job.biller.name|default:"–" }}</dd>
<dt class="font-semibold">{% translate "Billing unit" %}</dt><dd>{{ job.billing_unit.name|default:"–" }}</dd>
<dt class="font-semibold">{% translate "Other members" %}</dt>
<dd>{% for m in job.members %}{{ m.name }}{% if not forloop.last %}, {% endif %}{% empty %}–{% endfor %}</dd>
</dl>
</div>
</section>
{% include "jobs/partials/links.html" %}
<section class="card bg-base-100 shadow-sm lg:col-span-2" aria-labelledby="description-heading">
<div class="card-body">
<h2 id="description-heading" class="card-title">{% translate "Description" %}</h2>
<p class="whitespace-pre-line break-words">{{ job.description|default:"–" }}</p>
<h2 class="card-title mt-2">{% translate "Instructions" %}</h2>
<p class="whitespace-pre-line break-words">{{ job.instructions|default:"–" }}</p>
</div>
</section>
</div>
<div class="mt-4">{% include "jobs/partials/history.html" %}</div>
<dialog id="item-dialog" class="modal" aria-labelledby="item-dialog-title">
<div class="modal-box" id="item-dialog-body"></div>
</dialog>
{% endblock %}
@@ -0,0 +1,73 @@
{% extends "base.html" %}
{% block title %}{% if job %}{% translate "Edit job" %}{% else %}{% translate "New job" %}{% endif %}{% endblock %}
{% block content %}
<nav class="breadcrumbs text-sm" aria-label="{% translate 'Breadcrumbs' %}">
<ul>
<li><a href="{% url 'jobs:list' %}">{% translate "Customer jobs" %}</a></li>
{% if job %}<li><a href="{% url 'jobs:detail' job.id %}">{{ job.number }}</a></li>{% endif %}
<li aria-current="page">{% if job %}{% translate "Edit" %}{% else %}{% translate "New job" %}{% endif %}</li>
</ul>
</nav>
<h1 class="text-2xl font-bold mb-4">{% if job %}{% blocktranslate with number=job.number %}Edit job {{ number }}{% endblocktranslate %}{% else %}{% translate "New job" %}{% endif %}</h1>
<form method="post" novalidate class="space-y-4 max-w-4xl">
{% csrf_token %}
{% include "components/non_field_errors.html" %}
<section class="card bg-base-100 shadow-sm" aria-labelledby="form-basic-heading">
<div class="card-body">
<h2 id="form-basic-heading" class="card-title">{% translate "Basic information" %}</h2>
{% include "jobs/partials/customer_picker.html" %}
{{ form.name.as_field_group }}
{{ form.description.as_field_group }}
{{ form.service_units.as_field_group }}
<div class="grid gap-x-4 sm:grid-cols-2">
{{ form.status.as_field_group }}
{{ form.priority.as_field_group }}
{{ form.kind.as_field_group }}
{{ form.payment_basis.as_field_group }}
{{ form.estimated_hours.as_field_group }}
{{ form.customer_reference.as_field_group }}
</div>
{% include "jobs/partials/tags_input.html" %}
</div>
</section>
<section class="card bg-base-100 shadow-sm" aria-labelledby="form-schedule-heading">
<div class="card-body">
<h2 id="form-schedule-heading" class="card-title">{% translate "Schedule" %}</h2>
<div class="grid gap-x-4 sm:grid-cols-2">
{{ form.starts_on.as_field_group }}
{{ form.due_on.as_field_group }}
{{ form.planned_from.as_field_group }}
{{ form.planned_to.as_field_group }}
</div>
</div>
</section>
<section class="card bg-base-100 shadow-sm" aria-labelledby="form-people-heading">
<div class="card-body">
<h2 id="form-people-heading" class="card-title">{% translate "People and invoicing" %}</h2>
<div class="grid gap-x-4 sm:grid-cols-2">
{{ form.responsible_user.as_field_group }}
{{ form.contact_user.as_field_group }}
{{ form.biller_user.as_field_group }}
</div>
<div id="customer-fields">{% include "jobs/partials/customer_fields.html" %}</div>
{{ form.members.as_field_group }}
</div>
</section>
<section class="card bg-base-100 shadow-sm" aria-labelledby="form-instructions-heading">
<div class="card-body">
<h2 id="form-instructions-heading" class="card-title">{% translate "Instructions" %}</h2>
{{ form.instructions.as_field_group }}
</div>
</section>
<div class="flex justify-end gap-2">
<a href="{% if job %}{% url 'jobs:detail' job.id %}{% else %}{% url 'jobs:list' %}{% endif %}" class="btn">{% translate "Cancel" %}</a>
<button type="submit" class="btn btn-primary">{% translate "Save" %}</button>
</div>
</form>
{% endblock %}
@@ -0,0 +1,15 @@
{% extends "base.html" %}
{% block title %}{{ job.number }} {{ job.name }}{% endblock %}
{% block content %}
<nav class="breadcrumbs text-sm" aria-label="{% translate 'Breadcrumbs' %}">
<ul>
<li><a href="{% url 'jobs:list' %}">{% translate "Customer jobs" %}</a></li>
<li><a href="{% url 'jobs:detail' job.id %}">{{ job.number }}</a></li>
</ul>
</nav>
<div class="card bg-base-100 shadow-sm max-w-2xl">
<div class="card-body">
{% include "jobs/partials/link_form.html" %}
</div>
</div>
{% endblock %}
@@ -0,0 +1,29 @@
{% extends "base.html" %}{% load users_tags %}
{% block title %}{% translate "Customer jobs" %}{% endblock %}
{% block content %}
<div class="flex flex-wrap items-center justify-between gap-2 mb-4">
<h1 class="text-2xl font-bold">{% translate "Customer jobs" %}</h1>
{% if request.user|can:"jobs.edit" %}
<a href="{% url 'jobs:create' %}" class="btn btn-primary">{% translate "New job" %}</a>
{% endif %}
</div>
<form method="get" role="search" aria-label="{% translate 'Filter jobs' %}"
class="card bg-base-100 shadow-sm mb-4"
hx-get="{% url 'jobs:list' %}" hx-target="#job-table" hx-push-url="true"
hx-trigger="input changed delay:300ms from:input[name='q'], change from:select, change from:input[type='checkbox'], submit">
<div class="card-body grid gap-2 sm:grid-cols-2 lg:grid-cols-3 py-4">
{{ filters.q.as_field_group }}
{{ filters.scope.as_field_group }}
{{ filters.status.as_field_group }}
{{ filters.priority.as_field_group }}
{{ filters.service_unit.as_field_group }}
<div class="self-end">{{ filters.archived.as_field_group }}</div>
<noscript><button type="submit" class="btn">{% translate "Filter" %}</button></noscript>
</div>
</form>
<div id="job-table">
{% include "jobs/partials/job_table.html" %}
</div>
{% endblock %}
@@ -0,0 +1,5 @@
{# Contact and billing unit of the chosen customer (reloaded when the customer changes). #}
<div class="grid gap-x-4 sm:grid-cols-2">
{{ form.customer_contact.as_field_group }}
{{ form.billing_unit.as_field_group }}
</div>
@@ -0,0 +1,24 @@
{# The customer page's job list; loaded into the customers module's page. #}
<section id="customer-jobs" class="card bg-base-100 shadow-sm mt-4" aria-labelledby="customer-jobs-heading">
<div class="card-body">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 id="customer-jobs-heading" class="card-title">{% translate "Customer jobs" %}</h2>
{% if can_edit %}<a href="{% url 'jobs:create' %}?customer={{ customer.id }}" class="btn btn-sm">{% translate "New job" %}</a>{% endif %}
</div>
{% if jobs %}
<ul class="divide-y divide-base-300">
{% for j in jobs %}
<li class="py-2 flex flex-wrap items-center justify-between gap-2">
<span class="min-w-0"><span class="text-sm">{{ j.number }}</span> <a class="link break-words" href="{% url 'jobs:detail' j.id %}">{{ j.name }}</a></span>
<span class="flex flex-wrap gap-1">
{% include "jobs/partials/status_badge.html" with status=j.status %}
{% if j.is_late %}{% include "jobs/partials/late_badge.html" %}{% endif %}
</span>
</li>
{% endfor %}
</ul>
{% else %}
<p>{% translate "The customer has no jobs yet." %}</p>
{% endif %}
</div>
</section>
@@ -0,0 +1,16 @@
{# Customer picker: search, choose a result (radio buttons named "customer") or add one by name. #}
<fieldset id="customer-picker" class="fieldset"
{% if form.customer.errors %}aria-describedby="customer-picker-error"{% endif %}>
<legend class="fieldset-legend text-sm">
{% translate "Customer" %} <span aria-hidden="true">*</span><span class="sr-only">{% translate "(required)" %}</span>
</legend>
{% include "jobs/partials/customer_search_input.html" %}
<div id="customer-results"
hx-get="{% url 'jobs:customer_fields' %}" hx-trigger="change[event.target.name === 'customer']"
hx-target="#customer-fields" hx-include="[name='customer']:checked">
{% include "jobs/partials/customer_results.html" with term="" results=None %}
</div>
{% if form.customer.errors %}
<p class="text-error text-sm" id="customer-picker-error">{% for error in form.customer.errors %}{{ error }} {% endfor %}</p>
{% endif %}
</fieldset>
@@ -0,0 +1,45 @@
{# Results of the customer search. The selected customer always stays first and checked. #}
{% if term %}
<p class="sr-only" role="status">{% blocktranslate count counter=results|length %}{{ counter }} customer found{% plural %}{{ counter }} customers found{% endblocktranslate %}</p>
{% endif %}
{% if selected_customer or results %}
<ul class="space-y-1 mt-1" aria-label="{% translate 'Customers' %}">
{% if selected_customer %}
<li><label class="label cursor-pointer justify-start gap-3 text-base-content whitespace-normal">
<input type="radio" class="radio" name="customer" value="{{ selected_customer.id }}" checked{% if oob %} data-autofocus{% endif %}>
<span>{{ selected_customer.name }}{% if selected_customer.business_id %} <span class="text-sm">({{ selected_customer.business_id }})</span>{% endif %}</span>
</label></li>
{% endif %}
{% for c in results %}
<li><label class="label cursor-pointer justify-start gap-3 text-base-content whitespace-normal">
<input type="radio" class="radio" name="customer" value="{{ c.id }}">
<span>{{ c.name }}{% if c.business_id %} <span class="text-sm">({{ c.business_id }})</span>{% endif %}</span>
</label></li>
{% endfor %}
</ul>
{% elif term %}
<p class="text-sm mt-1">{% translate "No customers found." %}</p>
{% else %}
<p class="text-sm mt-1">{% translate "Type to search. If the customer is not found, you can add it by name." %}</p>
{% endif %}
{% if term and can_add_customer %}
<div class="flex flex-wrap items-end gap-2 mt-2 p-2 rounded-box border border-base-300">
<fieldset>
<legend class="text-sm">{% blocktranslate %}Add “{{ term }}” as a new customer{% endblocktranslate %}</legend>
<div class="flex flex-wrap gap-x-4">
<label class="label cursor-pointer gap-2 text-base-content"><input type="radio" class="radio radio-sm" name="new_customer_type" value="company" checked> {% translate "Company" %}</label>
<label class="label cursor-pointer gap-2 text-base-content"><input type="radio" class="radio radio-sm" name="new_customer_type" value="consumer"> {% translate "Consumer" %}</label>
</div>
</fieldset>
<button type="button" class="btn btn-sm"
hx-post="{% url 'jobs:customer_add' %}" hx-target="#customer-results"
hx-include="#customer-search, [name='new_customer_type']:checked, [name='customer']:checked">
{% translate "Add customer" %}</button>
</div>
{% endif %}
{% if add_error %}<p class="text-error text-sm mt-1" role="alert">{{ add_error }}</p>{% endif %}
{% if oob %}
{# A customer was just added: clear the search and empty the contact and billing unit choices. #}
{% include "jobs/partials/customer_search_input.html" %}
<div id="customer-fields" hx-swap-oob="true">{% include "jobs/partials/customer_fields.html" %}</div>
{% endif %}
@@ -0,0 +1,8 @@
<div id="customer-search-field"{% if oob %} hx-swap-oob="true"{% endif %}>
<label class="text-sm" for="customer-search">{% translate "Search customer by name or business ID" %}</label>
<input type="search" id="customer-search" name="customer_q" class="input w-full" autocomplete="off"
{% if form.customer.errors %}aria-invalid="true" aria-describedby="customer-picker-error"{% endif %}
hx-get="{% url 'jobs:customer_search' %}" hx-trigger="input changed delay:300ms, search"
hx-target="#customer-results" hx-include="this, [name='customer']:checked" hx-sync="this:replace"
hx-on:keydown="if (event.key === 'Enter') { event.preventDefault(); htmx.trigger(this, 'search'); }">
</div>
@@ -0,0 +1,24 @@
{% load jobs_tags %}
<section id="history-section" class="card bg-base-100 shadow-sm" aria-labelledby="history-heading"{% if oob %} hx-swap-oob="true"{% endif %}>
<div class="card-body">
<h2 id="history-heading" class="card-title">{% translate "Change history" %}</h2>
{% if changes %}
<ol class="divide-y divide-base-300">
{% for c in changes %}
<li class="py-2">
<p class="text-sm"><time datetime="{{ c.created_at|date:'c' }}">{{ c.created_at|date:"SHORT_DATETIME_FORMAT" }}</time> · {{ c.user_name }}</p>
<p class="font-semibold">{{ c.field|change_field_label }}</p>
<div class="grid gap-x-4 sm:grid-cols-[max-content_1fr] text-sm">
<span>{% translate "Before" %}:</span>
<span class="whitespace-pre-line break-words">{% change_value c.field c.old_value as old %}{{ old|default:"–" }}</span>
<span>{% translate "After" %}:</span>
<span class="whitespace-pre-line break-words">{% change_value c.field c.new_value as new %}{{ new|default:"–" }}</span>
</div>
</li>
{% endfor %}
</ol>
{% else %}
<p>{% translate "No changes since the job was created." %}</p>
{% endif %}
</div>
</section>
@@ -0,0 +1,70 @@
<p class="sr-only" role="status">{% blocktranslate count counter=page.paginator.count %}{{ counter }} job found{% plural %}{{ counter }} jobs found{% endblocktranslate %}</p>
{% if page.object_list %}
{# Wide screens: a table. Narrow screens: one card per job (no horizontal scrolling). #}
<div class="hidden md:block card bg-base-100 shadow-sm overflow-x-auto">
<table class="table">
<caption class="sr-only">{% translate "Customer jobs" %}</caption>
<thead>
<tr>
<th scope="col">{% translate "Number" %}</th>
<th scope="col">{% translate "Name" %}</th>
<th scope="col">{% translate "Customer" %}</th>
<th scope="col">{% translate "Status" %}</th>
<th scope="col">{% translate "Priority" %}</th>
<th scope="col">{% translate "Due date" %}</th>
<th scope="col">{% translate "Responsible person" %}</th>
</tr>
</thead>
<tbody>
{% for j in page.object_list %}
<tr>
<td class="whitespace-nowrap">{{ j.number }}</td>
<td>
<a class="link" href="{% url 'jobs:detail' j.id %}">{{ j.name }}</a>
{% if j.service_units %}<p class="text-sm">{{ j.service_units|join:", " }}</p>{% endif %}
</td>
<td>{{ j.customer.name }}</td>
<td>{% include "jobs/partials/status_badge.html" with status=j.status %}</td>
<td>{% include "jobs/partials/priority_badge.html" with priority=j.priority %}</td>
<td class="whitespace-nowrap">
{{ j.due_on|date:"SHORT_DATE_FORMAT"|default:"–" }}
{% if j.is_late %}<br>{% include "jobs/partials/late_badge.html" %}{% endif %}
</td>
<td>{{ j.responsible.name|default:"–" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<ul class="md:hidden space-y-2">
{% for j in page.object_list %}
<li class="card bg-base-100 shadow-sm">
<div class="card-body p-4 gap-1">
<p class="text-sm">{{ j.number }} · {{ j.customer.name }}</p>
<a class="link font-semibold break-words" href="{% url 'jobs:detail' j.id %}">{{ j.name }}</a>
<div class="flex flex-wrap gap-1">
{% include "jobs/partials/status_badge.html" with status=j.status %}
{% include "jobs/partials/priority_badge.html" with priority=j.priority %}
{% if j.is_late %}{% include "jobs/partials/late_badge.html" %}{% endif %}
</div>
{% if j.due_on %}<p class="text-sm">{% translate "Due date" %}: {{ j.due_on|date:"SHORT_DATE_FORMAT" }}</p>{% endif %}
</div>
</li>
{% endfor %}
</ul>
{% else %}
<div class="card bg-base-100 shadow-sm"><div class="card-body"><p>{% translate "No jobs match the filters." %}</p></div></div>
{% endif %}
{% if page.paginator.num_pages > 1 %}
<nav aria-label="{% translate 'Pages' %}" class="join mt-4">
{% if page.has_previous %}
<a class="join-item btn" href="?{{ query }}{% if query %}&amp;{% endif %}page={{ page.previous_page_number }}"
hx-get="?{{ query }}{% if query %}&amp;{% endif %}page={{ page.previous_page_number }}" hx-target="#job-table" hx-push-url="true">{% translate "Previous" %}</a>
{% endif %}
<span class="join-item btn btn-disabled" aria-current="page">{% blocktranslate with n=page.number total=page.paginator.num_pages %}Page {{ n }} / {{ total }}{% endblocktranslate %}</span>
{% if page.has_next %}
<a class="join-item btn" href="?{{ query }}{% if query %}&amp;{% endif %}page={{ page.next_page_number }}"
hx-get="?{{ query }}{% if query %}&amp;{% endif %}page={{ page.next_page_number }}" hx-target="#job-table" hx-push-url="true">{% translate "Next" %}</a>
{% endif %}
</nav>
{% endif %}
@@ -0,0 +1 @@
<span class="badge badge-error badge-soft gap-1 whitespace-nowrap"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm.75-12.5a.75.75 0 0 0-1.5 0V10c0 .2.08.39.22.53l2.5 2.5a.75.75 0 1 0 1.06-1.06l-2.28-2.28V5.5z" clip-rule="evenodd"/></svg>{% translate "Late" %}</span>
@@ -0,0 +1,17 @@
{% if link_id %}
{% url 'jobs:link_edit' job.id link_id as action_url %}
{% else %}
{% url 'jobs:link_create' job.id as action_url %}
{% endif %}
<h2 id="item-dialog-title" class="text-lg font-bold">
{% if link_id %}{% translate "Edit link" %}{% else %}{% translate "Add link" %}{% endif %}
</h2>
<form method="post" action="{{ action_url }}" novalidate class="space-y-1 mt-2"
hx-post="{{ action_url }}" hx-target="#item-dialog-body">
{% csrf_token %}
{{ form }}
<div class="modal-action">
<button type="button" class="btn" onclick="this.closest('dialog') ? this.closest('dialog').close() : history.back()">{% translate "Cancel" %}</button>
<button type="submit" class="btn btn-primary">{% translate "Save" %}</button>
</div>
</form>
@@ -0,0 +1,38 @@
<section id="links-section" class="card bg-base-100 shadow-sm" aria-labelledby="links-heading">
<div class="card-body">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 id="links-heading" class="card-title" tabindex="-1">{% translate "Links" %}</h2>
{% if can_edit %}
<a href="{% url 'jobs:link_create' job.id %}" class="btn btn-sm"
hx-get="{% url 'jobs:link_create' job.id %}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">{% translate "Add link" %}</a>
{% endif %}
</div>
{% if links %}
<ul class="divide-y divide-base-300">
{% for link in links %}{% with id_str=link.id|stringformat:"s" %}
<li class="py-2 flex flex-wrap justify-between gap-2">
<a class="link break-all" href="{{ link.url }}" target="_blank" rel="noopener noreferrer">{{ link.title }}<span class="sr-only"> {% translate "(opens in a new tab)" %}</span></a>
{% if can_edit %}
<div class="flex gap-1 items-start">
<a class="btn btn-sm btn-ghost" href="{% url 'jobs:link_edit' job.id link.id %}"
hx-get="{% url 'jobs:link_edit' job.id link.id %}" hx-target="#item-dialog-body"
hx-on::after-request="document.getElementById('item-dialog').showModal()">
{% translate "Edit" %}<span class="sr-only">: {{ link.title }}</span></a>
<button type="button" class="btn btn-sm btn-ghost" onclick="document.getElementById('confirm-delete-link-{{ link.id }}').showModal()">
{% translate "Delete" %}<span class="sr-only">: {{ link.title }}</span></button>
{% url 'jobs:link_delete' job.id link.id as delete_url %}
{% blocktranslate with title=link.title asvar dialog_title %}Delete link {{ title }}?{% endblocktranslate %}
{% translate "The link is removed from the job. The file itself is not touched." as dialog_body %}
{% translate "Delete" as dialog_confirm %}
{% with dialog_id="confirm-delete-link-"|add:id_str %}{% include "components/confirm_dialog.html" with id=dialog_id title=dialog_title body=dialog_body action_url=delete_url confirm_label=dialog_confirm hx_target="#links-section" %}{% endwith %}
</div>
{% endif %}
</li>
{% endwith %}{% endfor %}
</ul>
{% else %}
<p>{% translate "No links yet." %}</p>
{% endif %}
</div>
</section>
@@ -0,0 +1 @@
{% load jobs_tags %}<span class="badge {{ priority|priority_class }} gap-1 whitespace-nowrap"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path d="M4 2a1 1 0 0 1 1 1v.5h9.4a1 1 0 0 1 .8 1.6L13.3 8l1.9 2.9a1 1 0 0 1-.8 1.6H5V18a1 1 0 1 1-2 0V3a1 1 0 0 1 1-1z"/></svg><span class="sr-only">{% translate "Priority" %}: </span>{{ priority|priority_label }}</span>
@@ -0,0 +1 @@
{% load jobs_tags %}<span class="badge badge-outline gap-1 whitespace-nowrap"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><circle cx="10" cy="10" r="5"/></svg><span class="sr-only">{% translate "Status" %}: </span>{{ status|status_label }}</span>
@@ -0,0 +1,43 @@
{# Tag editor: choose from the list or type a new tag; each tag becomes a hidden input "tags". #}
{{ form.tags.value|default_if_none:""|json_script:"tags-initial" }}
{% translate "Tag added" as added_label %}{% translate "Tag removed" as removed_label %}{% translate "Remove tag" as remove_label %}
<div class="fieldset" data-added="{{ added_label }}" data-removed="{{ removed_label }}" data-remove="{{ remove_label }}"
x-data="{
tags: JSON.parse(document.getElementById('tags-initial').textContent) || [],
draft: '',
add() {
const added = [];
this.draft.split(',').map(t => t.trim().replace(/\s+/g, ' ')).filter(Boolean).forEach(t => {
if (!this.tags.some(x => x.toLowerCase() === t.toLowerCase())) { this.tags.push(t); added.push(t); }
});
this.draft = '';
if (added.length) window.notify(this.$root.dataset.added + ': ' + added.join(', '));
},
remove(i) {
const [t] = this.tags.splice(i, 1);
window.notify(this.$root.dataset.removed + ': ' + t);
this.$refs.input.focus();
}
}">
<label class="fieldset-legend text-sm" for="tag-input">{% translate "Tags" %}</label>
<ul class="flex flex-wrap gap-1" aria-label="{% translate 'Chosen tags' %}" x-show="tags.length" x-cloak>
<template x-for="(tag, i) in tags" :key="tag">
<li class="badge badge-outline gap-1 h-auto py-1">
<span x-text="tag"></span>
<button type="button" class="btn btn-ghost btn-xs min-h-6 min-w-6 px-1" @click="remove(i)"
:aria-label="$root.dataset.remove + ' ' + tag"><span aria-hidden="true">✕</span></button>
<input type="hidden" name="tags" :value="tag">
</li>
</template>
</ul>
<div class="join w-full">
<input id="tag-input" x-ref="input" type="text" class="input join-item w-full" list="tag-options"
maxlength="50" autocomplete="off" x-model="draft" @keydown.enter.prevent="add()"
aria-describedby="tag-input_helptext{% if form.tags.errors %} tag-input_error{% endif %}"
{% if form.tags.errors %}aria-invalid="true"{% endif %}>
<button type="button" class="btn join-item" @click="add()">{% translate "Add tag" %}</button>
</div>
<datalist id="tag-options">{% for t in tag_options %}<option value="{{ t }}"></option>{% endfor %}</datalist>
<p class="label text-sm whitespace-normal" id="tag-input_helptext">{% translate "Choose from the list or type a new tag and press Enter." %}</p>
{% if form.tags.errors %}<p class="text-error text-sm" id="tag-input_error">{% for e in form.tags.errors %}{{ e }} {% endfor %}</p>{% endif %}
</div>
@@ -0,0 +1,71 @@
from datetime import date
from typing import Any
from django import template
from django.utils.formats import date_format
from apps.jobs.presentation.labels import (
DATE_FIELDS,
ENUM_LABELS,
FIELD_LABELS,
KIND_LABELS,
PAYMENT_BASIS_LABELS,
PRIORITY_CLASSES,
PRIORITY_LABELS,
STATUS_LABELS,
)
register = template.Library()
def _label(labels: dict[Any, Any], value: Any) -> str:
for key, label in labels.items():
if key == value:
return str(label)
return str(value)
@register.filter
def status_label(value: Any) -> str:
return _label(STATUS_LABELS, value)
@register.filter
def priority_label(value: Any) -> str:
return _label(PRIORITY_LABELS, value)
@register.filter
def priority_class(value: Any) -> str:
return _label(PRIORITY_CLASSES, value)
@register.filter
def kind_label(value: Any) -> str:
return _label(KIND_LABELS, value)
@register.filter
def payment_basis_label(value: Any) -> str:
return _label(PAYMENT_BASIS_LABELS, value)
@register.filter
def change_field_label(field: str) -> str:
return _label(FIELD_LABELS, field)
@register.simple_tag
def change_value(field: str, value: str) -> str:
"""A stored history value for display: enum keys translated, ISO dates formatted."""
if not value:
return ""
labels: Any = ENUM_LABELS.get(field)
if labels is not None:
return _label(labels, value)
if field in DATE_FIELDS:
try:
return date_format(date.fromisoformat(value), "SHORT_DATE_FORMAT")
except ValueError:
return value
return value
+25
View File
@@ -0,0 +1,25 @@
from django.urls import path
from apps.jobs.presentation import views
app_name = "jobs"
urlpatterns = [
path("", views.JobListView.as_view(), name="list"),
path("new/", views.JobCreateView.as_view(), name="create"),
path("<int:pk>/", views.JobDetailView.as_view(), name="detail"),
path("<int:pk>/edit/", views.JobUpdateView.as_view(), name="edit"),
path("<int:pk>/links/new/", views.LinkFormView.as_view(), name="link_create"),
path("<int:pk>/links/<int:link_id>/edit/", views.LinkFormView.as_view(), name="link_edit"),
path(
"<int:pk>/links/<int:link_id>/delete/", views.LinkDeleteView.as_view(), name="link_delete"
),
path("customer-picker/search/", views.CustomerSearchView.as_view(), name="customer_search"),
path("customer-picker/add/", views.CustomerQuickAddView.as_view(), name="customer_add"),
path("customer-fields/", views.CustomerFieldsView.as_view(), name="customer_fields"),
path(
"for-customer/<int:customer_id>/",
views.CustomerJobsSectionView.as_view(),
name="for_customer",
),
]
+424
View File
@@ -0,0 +1,424 @@
import json
from typing import Any
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator
from django.http import Http404, HttpRequest, HttpResponse
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views import View
from apps.customers.application.dto import CustomerDetailsData
from apps.customers.domain.enums import CustomerType
from apps.jobs import container
from apps.jobs.application.dto import Actor, JobDetails
from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority
from apps.jobs.domain.status_rules import allowed_statuses
from apps.jobs.presentation.forms import CustomerJobForm, JobFilterForm, JobLinkForm
from apps.jobs.presentation.labels import ERROR_MESSAGES
from apps.shared.domain.exceptions import DomainError
from apps.users.domain.enums import Permission, Role
from apps.users.presentation.mixins import PermissionRequiredMixin, user_has
def actor(request: HttpRequest) -> Actor:
user: Any = request.user
return Actor(user_id=user.pk, role=Role(user.role))
def _is_htmx(request: HttpRequest) -> bool:
return bool(getattr(request, "htmx", False))
def _visible_details(request: HttpRequest, job_id: int) -> JobDetails:
queries = container.job_queries()
if not queries.is_visible_to(job_id, actor(request)):
raise Http404
details = queries.get_details(job_id)
if details is None:
raise Http404
return details
def _int(value: Any) -> int | None:
try:
return int(value)
except TypeError, ValueError:
return None
# --- Choices for the job form --------------------------------------------------------------------
def _service_unit_choices(keep: tuple[int, ...] = ()) -> list[tuple[int, str]]:
"""Active units other than the shared one, plus units already on the job."""
catalog = container.catalog_queries()
active = [(u.id, u.name) for u in catalog.active_service_units() if not u.is_shared]
known = {i for i, _ in active}
stored = [(u.id, u.name) for u in catalog.service_units(set(keep) - known)]
return active + stored
def _user_choices(keep: set[int | None], *, members: bool) -> list[tuple[int, str]]:
"""Active users (roles: no subcontractors) plus anyone already on the job."""
users = container.user_queries()
excluded = () if members else (Role.SUBCONTRACTOR,)
active = list(users.choices(active_only=True, exclude_roles=excluded))
known = {u.id for u in active}
extra = [u for u in users.choices({k for k in keep if k is not None} - known)]
return sorted(((u.id, u.name) for u in active + extra), key=lambda c: c[1].casefold())
def _customer_child_choices(customer_id: int | None) -> tuple[list[Any], list[Any]]:
if customer_id is None:
return [], []
customers = container.customer_queries()
return (
[(c.id, c.name) for c in customers.contacts(customer_id)],
[(u.id, u.name) for u in customers.billing_units(customer_id)],
)
def _initial(details: JobDetails) -> dict[str, Any]:
def ref_id(ref: Any) -> int | None:
return ref.id if ref else None
return {
"customer": details.customer.id,
"name": details.name,
"description": details.description,
"service_units": list(details.service_unit_ids),
"kind": details.kind.value,
"status": details.status.value,
"priority": details.priority.value,
"payment_basis": details.payment_basis.value,
"starts_on": details.starts_on,
"due_on": details.due_on,
"planned_from": details.planned_from,
"planned_to": details.planned_to,
"estimated_hours": details.estimated_hours,
"customer_reference": details.customer_reference,
"instructions": details.instructions,
"responsible_user": ref_id(details.responsible),
"contact_user": ref_id(details.contact_user),
"customer_contact": ref_id(details.customer_contact),
"biller_user": ref_id(details.biller),
"billing_unit": ref_id(details.billing_unit),
"members": list(details.member_ids),
"tags": list(details.tags),
}
class _JobFormView(PermissionRequiredMixin, View):
"""Create and edit share the form, its choices and the template."""
permission = Permission.JOBS_EDIT
details: JobDetails | None = None
def _form(self, request: HttpRequest, data: Any = None) -> CustomerJobForm:
d = self.details
if data is not None:
customer_id = _int(data.get("customer"))
elif d is not None:
customer_id = d.customer.id
else:
customer_id = _int(request.GET.get("customer"))
contacts, units = _customer_child_choices(customer_id)
me = actor(request)
keep_roles = {r.id for r in (d.responsible, d.contact_user, d.biller) if r} if d else set()
kwargs: dict[str, Any] = {
"service_unit_choices": _service_unit_choices(d.service_unit_ids if d else ()),
"user_choices": _user_choices(set(keep_roles), members=False),
"member_choices": _user_choices(set(d.member_ids) if d else set(), members=True),
"contact_choices": contacts,
"billing_unit_choices": units,
"statuses": allowed_statuses(
me.role,
current=d.status if d else None,
is_biller=bool(d and d.biller and d.biller.id == me.user_id),
),
}
if d is not None:
kwargs["initial"] = _initial(d)
else:
kwargs["initial"] = {
"customer": customer_id,
"status": JobStatus.TENTATIVE.value,
"priority": Priority.NORMAL.value,
"kind": JobKind.ONE_OFF.value,
"payment_basis": PaymentBasis.HOURLY.value,
"responsible_user": me.user_id,
}
return CustomerJobForm(data, **kwargs)
def _render(
self, request: HttpRequest, form: CustomerJobForm, status: int = 200
) -> HttpResponse:
customer_id = _int(form["customer"].value())
customer = container.customer_queries().get_summary(customer_id) if customer_id else None
context = {
"form": form,
"job": self.details,
"selected_customer": customer,
"tag_options": container.job_queries().tag_names(),
"can_add_customer": user_has(request.user, Permission.CUSTOMERS_USE),
}
return render(request, "jobs/form.html", context, status=status)
class JobCreateView(_JobFormView):
def get(self, request: HttpRequest) -> HttpResponse:
return self._render(request, self._form(request))
def post(self, request: HttpRequest) -> HttpResponse:
form = self._form(request, request.POST)
if form.is_valid():
try:
created = container.create_customer_job().execute(actor(request), form.to_dto())
except DomainError as error:
form.add_domain_error(error, ERROR_MESSAGES)
else:
messages.success(request, _("Job %(number)s created.") % {"number": created.number})
return redirect("jobs:detail", pk=created.id)
return self._render(request, form, status=422)
class JobUpdateView(_JobFormView):
def setup(self, request: HttpRequest, *args: Any, **kwargs: Any) -> None:
super().setup(request, *args, **kwargs)
self.pk = kwargs["pk"]
def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Any:
if user_has(request.user, Permission.JOBS_EDIT):
self.details = _visible_details(request, self.pk)
return super().dispatch(request, *args, **kwargs)
def get(self, request: HttpRequest, pk: int) -> HttpResponse:
return self._render(request, self._form(request))
def post(self, request: HttpRequest, pk: int) -> HttpResponse:
form = self._form(request, request.POST)
if form.is_valid():
try:
container.update_customer_job().execute(actor(request), pk, form.to_dto())
except DomainError as error:
form.add_domain_error(error, ERROR_MESSAGES)
else:
messages.success(request, _("Changes saved."))
return redirect("jobs:detail", pk=pk)
return self._render(request, form, status=422)
# --- List and job page ---------------------------------------------------------------------------
class JobListView(PermissionRequiredMixin, View):
permission = Permission.JOBS_VIEW
page_size = 25
def get(self, request: HttpRequest) -> HttpResponse:
units = _service_unit_choices()
filters = JobFilterForm(request.GET or None, service_unit_choices=units)
jobs = container.job_queries().list_jobs(filters.to_filters(), actor(request))
page = Paginator(jobs, self.page_size).get_page(request.GET.get("page"))
query = request.GET.copy()
query.pop("page", None)
context = {"filters": filters, "page": page, "query": query.urlencode()}
template = "jobs/partials/job_table.html" if _is_htmx(request) else "jobs/list.html"
return render(request, template, context)
def _detail_context(request: HttpRequest, job_id: int) -> dict[str, Any]:
queries = container.job_queries()
return {
"job": _visible_details(request, job_id),
"links": queries.links(job_id),
"changes": queries.changes(job_id),
"can_edit": user_has(request.user, Permission.JOBS_EDIT),
"can_see_customer": user_has(request.user, Permission.CUSTOMERS_USE),
}
class JobDetailView(PermissionRequiredMixin, View):
permission = Permission.JOBS_VIEW
def get(self, request: HttpRequest, pk: int) -> HttpResponse:
return render(request, "jobs/detail.html", _detail_context(request, pk))
class CustomerJobsSectionView(PermissionRequiredMixin, View):
"""The customer page's job list (loaded into the customers module's page with HTMX)."""
permission = Permission.CUSTOMERS_USE
def get(self, request: HttpRequest, customer_id: int) -> HttpResponse:
customer = container.customer_queries().get_summary(customer_id)
if customer is None:
raise Http404
jobs = container.job_queries().jobs_for_customer(customer_id, actor(request))
context = {
"customer": customer,
"jobs": jobs,
"can_edit": user_has(request.user, Permission.JOBS_EDIT),
}
return render(request, "jobs/partials/customer_jobs.html", context)
# --- Links: the form loads into a dialog on the job page -----------------------------------------
def _links_response(request: HttpRequest, job_id: int, message: str) -> HttpResponse:
"""Re-render links and history in place, close the dialog, announce and move focus."""
context = _detail_context(request, job_id)
response = render(request, "jobs/partials/links.html", context)
response.content += render(
request, "jobs/partials/history.html", {**context, "oob": True}
).content
response["HX-Retarget"] = "#links-section"
response["HX-Reswap"] = "outerHTML"
response["HX-Trigger-After-Settle"] = json.dumps(
{"itemSaved": {"message": message, "focus": "#links-heading"}}
)
return response
class LinkFormView(PermissionRequiredMixin, View):
"""GET: form (dialog body for HTMX, full page otherwise). POST: save."""
permission = Permission.JOBS_EDIT
def _render(
self,
request: HttpRequest,
job: JobDetails,
form: JobLinkForm,
link_id: int | None,
status: int = 200,
) -> HttpResponse:
context = {"job": job, "form": form, "link_id": link_id}
template = (
"jobs/partials/link_form.html" if _is_htmx(request) else "jobs/link_form_page.html"
)
return render(request, template, context, status=status)
def get(self, request: HttpRequest, pk: int, link_id: int | None = None) -> HttpResponse:
job = _visible_details(request, pk)
initial = {}
if link_id is not None:
link = next((li for li in container.job_queries().links(pk) if li.id == link_id), None)
if link is None:
raise Http404
initial = {"title": link.title, "url": link.url}
return self._render(request, job, JobLinkForm(initial=initial), link_id)
def post(self, request: HttpRequest, pk: int, link_id: int | None = None) -> HttpResponse:
job = _visible_details(request, pk)
form = JobLinkForm(request.POST)
if form.is_valid():
try:
if link_id is None:
container.add_job_link().execute(actor(request), pk, form.to_dto())
else:
container.update_job_link().execute(actor(request), pk, link_id, form.to_dto())
except DomainError as error:
form.add_domain_error(error, ERROR_MESSAGES)
else:
if _is_htmx(request):
return _links_response(request, pk, _("Link saved."))
messages.success(request, _("Link saved."))
return redirect(reverse("jobs:detail", kwargs={"pk": pk}) + "#links-section")
return self._render(request, job, form, link_id, status=422)
class LinkDeleteView(PermissionRequiredMixin, View):
permission = Permission.JOBS_EDIT
def post(self, request: HttpRequest, pk: int, link_id: int) -> HttpResponse:
_visible_details(request, pk)
message = _("Link deleted.")
try:
container.delete_job_link().execute(actor(request), pk, link_id)
except DomainError as error:
message = str(ERROR_MESSAGES.get(error.code, ERROR_MESSAGES["*"]))
if _is_htmx(request):
return _links_response(request, pk, message)
messages.info(request, message)
return redirect("jobs:detail", pk=pk)
# --- Customer picker (reused by the quick intake) ------------------------------------------------
def _picker_context(
request: HttpRequest, term: str, selected_id: int | None, **extra: Any
) -> dict[str, Any]:
customers = container.customer_queries()
selected = customers.get_summary(selected_id) if selected_id else None
found = customers.search(term) if term else []
results = [c for c in found if not selected or c.id != selected.id]
exact = any(c.name.casefold() == term.casefold() for c in results) or bool(
selected and selected.name.casefold() == term.casefold()
)
return {
"term": term,
"selected_customer": selected,
"results": results,
"can_add_customer": user_has(request.user, Permission.CUSTOMERS_USE) and not exact,
**extra,
}
class CustomerSearchView(PermissionRequiredMixin, View):
permission = Permission.JOBS_EDIT
def get(self, request: HttpRequest) -> HttpResponse:
term = request.GET.get("customer_q", "").strip()[:200]
context = _picker_context(request, term, _int(request.GET.get("customer")))
return render(request, "jobs/partials/customer_results.html", context)
class CustomerQuickAddView(PermissionRequiredMixin, View):
"""Adds a customer by name (and type) and selects it; details are completed later."""
permission = Permission.CUSTOMERS_USE
def post(self, request: HttpRequest) -> HttpResponse:
if not user_has(request.user, Permission.JOBS_EDIT):
raise PermissionDenied
name = request.POST.get("customer_q", "").strip()
try:
customer_type = CustomerType(request.POST.get("new_customer_type", "company"))
except ValueError:
customer_type = CustomerType.COMPANY
try:
customer_id = container.register_customer().execute(
CustomerDetailsData(name=name, type=customer_type)
)
except DomainError:
context = _picker_context(
request,
name,
_int(request.POST.get("customer")),
add_error=_("Enter a customer name of at most 200 characters."),
)
return render(request, "jobs/partials/customer_results.html", context, status=422)
# The new customer has no contacts or billing units: empty those choices too.
context = _picker_context(request, "", customer_id, form=CustomerJobForm(), oob=True)
response = render(request, "jobs/partials/customer_results.html", context)
response["HX-Trigger-After-Settle"] = json.dumps(
{"notify": _("Customer %(name)s added and selected.") % {"name": name}}
)
return response
class CustomerFieldsView(PermissionRequiredMixin, View):
"""The contact and billing unit choices of the chosen customer."""
permission = Permission.JOBS_EDIT
def get(self, request: HttpRequest) -> HttpResponse:
contacts, units = _customer_child_choices(_int(request.GET.get("customer")))
form = CustomerJobForm(contact_choices=contacts, billing_unit_choices=units)
return render(request, "jobs/partials/customer_fields.html", {"form": form})