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,156 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority
|
||||
from apps.shared.infrastructure.models import TimestampedModel
|
||||
|
||||
_USER = settings.AUTH_USER_MODEL
|
||||
|
||||
|
||||
class CustomerJobModel(TimestampedModel):
|
||||
number = models.CharField(max_length=10, unique=True)
|
||||
name = models.CharField(max_length=200)
|
||||
description = models.TextField(blank=True)
|
||||
# PROTECT: customers, contacts and billing units in use cannot be deleted (their
|
||||
# generic deletion guard finds these relations; no cross-module checks needed).
|
||||
customer = models.ForeignKey(
|
||||
"customers.CustomerModel", on_delete=models.PROTECT, related_name="customer_jobs"
|
||||
)
|
||||
starts_on = models.DateField(null=True, blank=True)
|
||||
due_on = models.DateField(null=True, blank=True)
|
||||
planned_from = models.DateField(null=True, blank=True)
|
||||
planned_to = models.DateField(null=True, blank=True)
|
||||
kind = models.CharField(max_length=20, default=JobKind.ONE_OFF.value)
|
||||
status = models.CharField(max_length=20, default=JobStatus.TENTATIVE.value, db_index=True)
|
||||
priority = models.CharField(max_length=20, default=Priority.NORMAL.value)
|
||||
payment_basis = models.CharField(max_length=20, default=PaymentBasis.HOURLY.value)
|
||||
estimated_hours = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
|
||||
customer_reference = models.CharField(max_length=100, blank=True)
|
||||
instructions = models.TextField(blank=True)
|
||||
responsible_user = models.ForeignKey(
|
||||
_USER, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
|
||||
)
|
||||
contact_user = models.ForeignKey(
|
||||
_USER, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
|
||||
)
|
||||
customer_contact = models.ForeignKey(
|
||||
"customers.ContactModel",
|
||||
on_delete=models.PROTECT,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="customer_jobs",
|
||||
)
|
||||
biller_user = models.ForeignKey(
|
||||
_USER, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
|
||||
)
|
||||
billing_unit = models.ForeignKey(
|
||||
"customers.BillingUnitModel",
|
||||
on_delete=models.PROTECT,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="customer_jobs",
|
||||
)
|
||||
created_by = models.ForeignKey(
|
||||
_USER, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
|
||||
)
|
||||
|
||||
class Meta:
|
||||
db_table = "customer_jobs"
|
||||
ordering = ["-id"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.number} {self.name}"
|
||||
|
||||
|
||||
class JobNumberSequenceModel(TimestampedModel):
|
||||
year = models.PositiveSmallIntegerField(unique=True)
|
||||
last_number = models.PositiveIntegerField(default=0)
|
||||
|
||||
class Meta:
|
||||
db_table = "job_number_sequences"
|
||||
|
||||
|
||||
class CustomerJobServiceUnitModel(models.Model):
|
||||
customer_job = models.ForeignKey(
|
||||
CustomerJobModel, on_delete=models.CASCADE, related_name="service_unit_links"
|
||||
)
|
||||
service_unit = models.ForeignKey(
|
||||
"catalog.ServiceUnitModel", on_delete=models.PROTECT, related_name="customer_job_links"
|
||||
)
|
||||
|
||||
class Meta:
|
||||
db_table = "customer_job_service_unit"
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["customer_job", "service_unit"], name="uniq_customer_job_service_unit"
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class CustomerJobMemberModel(models.Model):
|
||||
customer_job = models.ForeignKey(
|
||||
CustomerJobModel, on_delete=models.CASCADE, related_name="member_links"
|
||||
)
|
||||
user = models.ForeignKey(_USER, on_delete=models.PROTECT, related_name="+")
|
||||
|
||||
class Meta:
|
||||
db_table = "customer_job_members"
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["customer_job", "user"], name="uniq_customer_job_member"
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class TagModel(TimestampedModel):
|
||||
name = models.CharField(max_length=50, unique=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "tags"
|
||||
ordering = ["name"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
|
||||
class CustomerJobTagModel(models.Model):
|
||||
customer_job = models.ForeignKey(
|
||||
CustomerJobModel, on_delete=models.CASCADE, related_name="tag_links"
|
||||
)
|
||||
tag = models.ForeignKey(TagModel, on_delete=models.PROTECT, related_name="job_links")
|
||||
|
||||
class Meta:
|
||||
db_table = "customer_job_tag"
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["customer_job", "tag"], name="uniq_customer_job_tag")
|
||||
]
|
||||
|
||||
|
||||
class JobLinkModel(TimestampedModel):
|
||||
customer_job = models.ForeignKey(
|
||||
CustomerJobModel, on_delete=models.CASCADE, related_name="links"
|
||||
)
|
||||
title = models.CharField(max_length=200)
|
||||
url = models.CharField(max_length=500)
|
||||
|
||||
class Meta:
|
||||
db_table = "customer_job_links"
|
||||
ordering = ["id"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.title
|
||||
|
||||
|
||||
class JobChangeModel(models.Model):
|
||||
customer_job = models.ForeignKey(
|
||||
CustomerJobModel, on_delete=models.CASCADE, related_name="changes"
|
||||
)
|
||||
user = models.ForeignKey(_USER, on_delete=models.PROTECT, related_name="+")
|
||||
field = models.CharField(max_length=50)
|
||||
old_value = models.TextField(blank=True)
|
||||
new_value = models.TextField(blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "customer_job_changes"
|
||||
ordering = ["-created_at", "-id"]
|
||||
@@ -0,0 +1,243 @@
|
||||
from collections.abc import Iterable, Sequence
|
||||
from typing import Any
|
||||
|
||||
from django.db.models import Q, QuerySet
|
||||
|
||||
from apps.catalog.application.queries import CatalogQueries
|
||||
from apps.customers.application.queries import CustomerQueries
|
||||
from apps.jobs.application.dto import (
|
||||
Actor,
|
||||
JobChangeView,
|
||||
JobDetails,
|
||||
JobFilters,
|
||||
JobLinkView,
|
||||
JobListItem,
|
||||
Ref,
|
||||
)
|
||||
from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority
|
||||
from apps.jobs.infrastructure.orm import (
|
||||
CustomerJobMemberModel,
|
||||
CustomerJobModel,
|
||||
CustomerJobServiceUnitModel,
|
||||
JobChangeModel,
|
||||
JobLinkModel,
|
||||
TagModel,
|
||||
)
|
||||
from apps.shared.application.ports import Clock
|
||||
from apps.users.application.queries import UserQueries
|
||||
from apps.users.domain.enums import Role
|
||||
|
||||
_LIST_FIELDS = (
|
||||
"id",
|
||||
"number",
|
||||
"name",
|
||||
"customer_id",
|
||||
"status",
|
||||
"priority",
|
||||
"due_on",
|
||||
"responsible_user_id",
|
||||
)
|
||||
|
||||
|
||||
def _visible(viewer: Actor) -> QuerySet[CustomerJobModel]:
|
||||
qs = CustomerJobModel.objects.all()
|
||||
if viewer.role is Role.SUBCONTRACTOR:
|
||||
qs = qs.filter(member_links__user_id=viewer.user_id)
|
||||
return qs
|
||||
|
||||
|
||||
class DjangoCustomerJobQueries:
|
||||
def __init__(
|
||||
self,
|
||||
customers: CustomerQueries,
|
||||
users: UserQueries,
|
||||
catalog: CatalogQueries,
|
||||
clock: Clock,
|
||||
) -> None:
|
||||
self.customers = customers
|
||||
self.users = users
|
||||
self.catalog = catalog
|
||||
self.clock = clock
|
||||
|
||||
# --- Lists -----------------------------------------------------------------------------------
|
||||
|
||||
def list_jobs(self, filters: JobFilters, viewer: Actor) -> Sequence[JobListItem]:
|
||||
qs = _visible(viewer)
|
||||
term = filters.search.strip()
|
||||
if term:
|
||||
customer_ids = [c.id for c in self.customers.list_customers(search=term)]
|
||||
qs = qs.filter(
|
||||
Q(number__icontains=term)
|
||||
| Q(name__icontains=term)
|
||||
| Q(customer_id__in=customer_ids)
|
||||
)
|
||||
if filters.status is not None:
|
||||
qs = qs.filter(status=filters.status.value)
|
||||
elif not filters.include_archived:
|
||||
qs = qs.exclude(status=JobStatus.ARCHIVED.value)
|
||||
if filters.priority is not None:
|
||||
qs = qs.filter(priority=filters.priority.value)
|
||||
if filters.service_unit_id is not None:
|
||||
qs = qs.filter(service_unit_links__service_unit_id=filters.service_unit_id)
|
||||
if filters.mine:
|
||||
me = viewer.user_id
|
||||
qs = qs.filter(
|
||||
Q(responsible_user_id=me)
|
||||
| Q(contact_user_id=me)
|
||||
| Q(biller_user_id=me)
|
||||
| Q(member_links__user_id=me)
|
||||
)
|
||||
return self._items(qs.distinct().order_by("-id").values(*_LIST_FIELDS))
|
||||
|
||||
def jobs_for_customer(self, customer_id: int, viewer: Actor) -> Sequence[JobListItem]:
|
||||
qs = _visible(viewer).filter(customer_id=customer_id).distinct().order_by("-id")
|
||||
return self._items(qs.values(*_LIST_FIELDS))
|
||||
|
||||
def _items(self, rows: Iterable[dict[str, Any]]) -> list[JobListItem]:
|
||||
rows = list(rows)
|
||||
if not rows:
|
||||
return []
|
||||
job_ids = [r["id"] for r in rows]
|
||||
customers = self.customers.summaries(r["customer_id"] for r in rows)
|
||||
users = self._user_names(r["responsible_user_id"] for r in rows)
|
||||
units_by_job = self._unit_names(job_ids)
|
||||
today = self.clock.today()
|
||||
items = []
|
||||
for r in rows:
|
||||
status = JobStatus(r["status"])
|
||||
customer = customers.get(r["customer_id"])
|
||||
responsible = r["responsible_user_id"]
|
||||
items.append(
|
||||
JobListItem(
|
||||
id=r["id"],
|
||||
number=r["number"],
|
||||
name=r["name"],
|
||||
customer=Ref(r["customer_id"], customer.name if customer else ""),
|
||||
status=status,
|
||||
priority=Priority(r["priority"]),
|
||||
due_on=r["due_on"],
|
||||
responsible=Ref(responsible, users.get(responsible, ""))
|
||||
if responsible
|
||||
else None,
|
||||
service_units=tuple(units_by_job.get(r["id"], ())),
|
||||
is_late=_is_late(r["due_on"], status, today),
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
def _user_names(self, ids: Iterable[int | None]) -> dict[int, str]:
|
||||
wanted = {i for i in ids if i is not None}
|
||||
return {u.id: u.name for u in self.users.choices(wanted)} if wanted else {}
|
||||
|
||||
def _unit_names(self, job_ids: list[int]) -> dict[int, list[str]]:
|
||||
links = list(
|
||||
CustomerJobServiceUnitModel.objects.filter(customer_job_id__in=job_ids).values_list(
|
||||
"customer_job_id", "service_unit_id"
|
||||
)
|
||||
)
|
||||
units = self.catalog.service_units({u for _, u in links})
|
||||
order = {u.id: (n, u.name) for n, u in enumerate(units)}
|
||||
result: dict[int, list[tuple[int, str]]] = {}
|
||||
for job_id, unit_id in links:
|
||||
if unit_id in order:
|
||||
result.setdefault(job_id, []).append(order[unit_id])
|
||||
return {job_id: [name for _, name in sorted(names)] for job_id, names in result.items()}
|
||||
|
||||
# --- One job ---------------------------------------------------------------------------------
|
||||
|
||||
def is_visible_to(self, job_id: int, viewer: Actor) -> bool:
|
||||
return _visible(viewer).filter(pk=job_id).exists()
|
||||
|
||||
def get_details(self, job_id: int) -> JobDetails | None:
|
||||
m = CustomerJobModel.objects.filter(pk=job_id).first()
|
||||
if m is None:
|
||||
return None
|
||||
member_ids = list(
|
||||
CustomerJobMemberModel.objects.filter(customer_job=m).values_list("user_id", flat=True)
|
||||
)
|
||||
role_ids = [m.responsible_user_id, m.contact_user_id, m.biller_user_id, m.created_by_id]
|
||||
users = self._user_names([*role_ids, *member_ids])
|
||||
customer = self.customers.get_summary(m.customer_id)
|
||||
unit_ids = CustomerJobServiceUnitModel.objects.filter(customer_job=m).values_list(
|
||||
"service_unit_id", flat=True
|
||||
)
|
||||
units = self.catalog.service_units(unit_ids)
|
||||
contact = billing_unit = None
|
||||
if m.customer_contact_id is not None:
|
||||
names = {c.id: c.name for c in self.customers.contacts(m.customer_id)}
|
||||
contact = Ref(m.customer_contact_id, names.get(m.customer_contact_id, ""))
|
||||
if m.billing_unit_id is not None:
|
||||
names = {u.id: u.name for u in self.customers.billing_units(m.customer_id)}
|
||||
billing_unit = Ref(m.billing_unit_id, names.get(m.billing_unit_id, ""))
|
||||
|
||||
def user(user_id: int | None) -> Ref | None:
|
||||
return Ref(user_id, users.get(user_id, "")) if user_id is not None else None
|
||||
|
||||
status = JobStatus(m.status)
|
||||
return JobDetails(
|
||||
id=m.pk,
|
||||
number=m.number,
|
||||
name=m.name,
|
||||
description=m.description,
|
||||
customer=Ref(m.customer_id, customer.name if customer else ""),
|
||||
customer_is_internal=bool(customer and customer.is_internal),
|
||||
service_units=tuple(Ref(u.id, u.name) for u in units),
|
||||
starts_on=m.starts_on,
|
||||
due_on=m.due_on,
|
||||
planned_from=m.planned_from,
|
||||
planned_to=m.planned_to,
|
||||
kind=JobKind(m.kind),
|
||||
status=status,
|
||||
priority=Priority(m.priority),
|
||||
payment_basis=PaymentBasis(m.payment_basis),
|
||||
estimated_hours=m.estimated_hours,
|
||||
customer_reference=m.customer_reference,
|
||||
instructions=m.instructions,
|
||||
responsible=user(m.responsible_user_id),
|
||||
contact_user=user(m.contact_user_id),
|
||||
customer_contact=contact,
|
||||
biller=user(m.biller_user_id),
|
||||
billing_unit=billing_unit,
|
||||
members=tuple(
|
||||
sorted((Ref(i, users.get(i, "")) for i in member_ids), key=lambda r: r.name)
|
||||
),
|
||||
tags=tuple(
|
||||
TagModel.objects.filter(job_links__customer_job=m)
|
||||
.order_by("name")
|
||||
.values_list("name", flat=True)
|
||||
),
|
||||
created_at=m.created_at,
|
||||
created_by=user(m.created_by_id),
|
||||
is_late=_is_late(m.due_on, status, self.clock.today()),
|
||||
)
|
||||
|
||||
def changes(self, job_id: int) -> Sequence[JobChangeView]:
|
||||
rows = list(
|
||||
JobChangeModel.objects.filter(customer_job_id=job_id).values(
|
||||
"field", "old_value", "new_value", "user_id", "created_at"
|
||||
)
|
||||
)
|
||||
names = self._user_names(r["user_id"] for r in rows)
|
||||
return [
|
||||
JobChangeView(
|
||||
field=r["field"],
|
||||
old_value=r["old_value"],
|
||||
new_value=r["new_value"],
|
||||
user_name=names.get(r["user_id"], ""),
|
||||
created_at=r["created_at"],
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
|
||||
def links(self, job_id: int) -> Sequence[JobLinkView]:
|
||||
return [
|
||||
JobLinkView(id=m.pk, title=m.title, url=m.url)
|
||||
for m in JobLinkModel.objects.filter(customer_job_id=job_id)
|
||||
]
|
||||
|
||||
def tag_names(self) -> Sequence[str]:
|
||||
return list(TagModel.objects.order_by("name").values_list("name", flat=True))
|
||||
|
||||
|
||||
def _is_late(due_on: Any, status: JobStatus, today: Any) -> bool:
|
||||
return due_on is not None and due_on < today and not status.is_finished
|
||||
@@ -0,0 +1,176 @@
|
||||
from collections.abc import Iterable, Sequence
|
||||
from decimal import Decimal
|
||||
|
||||
from django.db import IntegrityError, transaction
|
||||
|
||||
from apps.jobs.domain.entities import ChangeRecord, CustomerJob, JobFields, JobLink
|
||||
from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority
|
||||
from apps.jobs.domain.value_objects import (
|
||||
EstimatedHours,
|
||||
JobName,
|
||||
JobNumber,
|
||||
LinkTarget,
|
||||
TagName,
|
||||
)
|
||||
from apps.jobs.infrastructure.orm import (
|
||||
CustomerJobMemberModel,
|
||||
CustomerJobModel,
|
||||
CustomerJobServiceUnitModel,
|
||||
CustomerJobTagModel,
|
||||
JobChangeModel,
|
||||
JobLinkModel,
|
||||
JobNumberSequenceModel,
|
||||
TagModel,
|
||||
)
|
||||
|
||||
|
||||
def _job_entity(model: CustomerJobModel) -> CustomerJob:
|
||||
unit_ids = CustomerJobServiceUnitModel.objects.filter(customer_job=model).values_list(
|
||||
"service_unit_id", flat=True
|
||||
)
|
||||
member_ids = CustomerJobMemberModel.objects.filter(customer_job=model).values_list(
|
||||
"user_id", flat=True
|
||||
)
|
||||
tags = TagModel.objects.filter(job_links__customer_job=model).values_list("name", flat=True)
|
||||
hours: Decimal | None = model.estimated_hours
|
||||
details = JobFields(
|
||||
name=JobName(model.name),
|
||||
customer_id=model.customer_id,
|
||||
service_unit_ids=frozenset(unit_ids),
|
||||
description=model.description,
|
||||
starts_on=model.starts_on,
|
||||
due_on=model.due_on,
|
||||
planned_from=model.planned_from,
|
||||
planned_to=model.planned_to,
|
||||
kind=JobKind(model.kind),
|
||||
status=JobStatus(model.status),
|
||||
priority=Priority(model.priority),
|
||||
payment_basis=PaymentBasis(model.payment_basis),
|
||||
estimated_hours=EstimatedHours(hours) if hours is not None else None,
|
||||
customer_reference=model.customer_reference,
|
||||
instructions=model.instructions,
|
||||
responsible_user_id=model.responsible_user_id,
|
||||
contact_user_id=model.contact_user_id,
|
||||
customer_contact_id=model.customer_contact_id,
|
||||
biller_user_id=model.biller_user_id,
|
||||
billing_unit_id=model.billing_unit_id,
|
||||
member_ids=frozenset(member_ids),
|
||||
tags=tuple(TagName(t) for t in tags),
|
||||
)
|
||||
return CustomerJob.reconstitute(
|
||||
id=model.pk,
|
||||
number=JobNumber.parse(model.number),
|
||||
created_by=model.created_by_id,
|
||||
details=details,
|
||||
)
|
||||
|
||||
|
||||
def _tag_ids(tags: Iterable[TagName]) -> list[int]:
|
||||
"""Ids of the tags, adding new names to the shared list (case-insensitive match)."""
|
||||
ids = []
|
||||
for tag in tags:
|
||||
existing = TagModel.objects.filter(name__iexact=tag.value).first()
|
||||
if existing is None:
|
||||
try:
|
||||
with transaction.atomic():
|
||||
existing = TagModel.objects.create(name=tag.value)
|
||||
except IntegrityError: # added concurrently
|
||||
existing = TagModel.objects.get(name__iexact=tag.value)
|
||||
ids.append(existing.pk)
|
||||
return ids
|
||||
|
||||
|
||||
def _sync(model: type, job: CustomerJobModel, column: str, wanted: Iterable[int]) -> None:
|
||||
wanted_ids = set(wanted)
|
||||
links = model._default_manager.filter(customer_job=job) # type: ignore[attr-defined]
|
||||
current = set(links.values_list(column, flat=True))
|
||||
links.filter(**{f"{column}__in": current - wanted_ids}).delete()
|
||||
model._default_manager.bulk_create( # type: ignore[attr-defined]
|
||||
[model(customer_job=job, **{column: i}) for i in sorted(wanted_ids - current)]
|
||||
)
|
||||
|
||||
|
||||
class DjangoCustomerJobRepository:
|
||||
def get(self, job_id: int) -> CustomerJob | None:
|
||||
model = CustomerJobModel.objects.filter(pk=job_id).first()
|
||||
return _job_entity(model) if model else None
|
||||
|
||||
def save(self, job: CustomerJob) -> CustomerJob:
|
||||
model = CustomerJobModel() if job.id is None else CustomerJobModel.objects.get(pk=job.id)
|
||||
d = job.details
|
||||
if job.number is not None:
|
||||
model.number = str(job.number)
|
||||
model.name = d.name.value
|
||||
model.description = d.description
|
||||
model.customer_id = d.customer_id
|
||||
model.starts_on = d.starts_on
|
||||
model.due_on = d.due_on
|
||||
model.planned_from = d.planned_from
|
||||
model.planned_to = d.planned_to
|
||||
model.kind = d.kind.value
|
||||
model.status = d.status.value
|
||||
model.priority = d.priority.value
|
||||
model.payment_basis = d.payment_basis.value
|
||||
model.estimated_hours = d.estimated_hours.value if d.estimated_hours else None
|
||||
model.customer_reference = d.customer_reference
|
||||
model.instructions = d.instructions
|
||||
model.responsible_user_id = d.responsible_user_id
|
||||
model.contact_user_id = d.contact_user_id
|
||||
model.customer_contact_id = d.customer_contact_id
|
||||
model.biller_user_id = d.biller_user_id
|
||||
model.billing_unit_id = d.billing_unit_id
|
||||
if job.id is None:
|
||||
model.created_by_id = job.created_by
|
||||
model.save()
|
||||
_sync(CustomerJobServiceUnitModel, model, "service_unit_id", d.service_unit_ids)
|
||||
_sync(CustomerJobMemberModel, model, "user_id", d.member_ids)
|
||||
_sync(CustomerJobTagModel, model, "tag_id", _tag_ids(d.tags))
|
||||
return job.with_id(model.pk)
|
||||
|
||||
def next_number(self, year: int) -> JobNumber:
|
||||
counter = JobNumberSequenceModel.objects.select_for_update().filter(year=year).first()
|
||||
if counter is None:
|
||||
try:
|
||||
with transaction.atomic():
|
||||
JobNumberSequenceModel.objects.create(year=year, last_number=0)
|
||||
except IntegrityError: # another save created the year's counter first
|
||||
pass
|
||||
counter = JobNumberSequenceModel.objects.select_for_update().get(year=year)
|
||||
counter.last_number += 1
|
||||
counter.save(update_fields=["last_number", "updated_at"])
|
||||
return JobNumber(year, counter.last_number)
|
||||
|
||||
def record_changes(self, job_id: int, user_id: int, changes: Sequence[ChangeRecord]) -> None:
|
||||
JobChangeModel.objects.bulk_create(
|
||||
JobChangeModel(
|
||||
customer_job_id=job_id,
|
||||
user_id=user_id,
|
||||
field=c.field,
|
||||
old_value=c.old_value,
|
||||
new_value=c.new_value,
|
||||
)
|
||||
for c in changes
|
||||
)
|
||||
|
||||
|
||||
class DjangoJobLinkRepository:
|
||||
def get(self, link_id: int) -> JobLink | None:
|
||||
model = JobLinkModel.objects.filter(pk=link_id).first()
|
||||
if model is None:
|
||||
return None
|
||||
return JobLink(
|
||||
id=model.pk,
|
||||
job_id=model.customer_job_id,
|
||||
target=LinkTarget(title=model.title, url=model.url),
|
||||
)
|
||||
|
||||
def save(self, link: JobLink) -> JobLink:
|
||||
model = JobLinkModel() if link.id is None else JobLinkModel.objects.get(pk=link.id)
|
||||
model.customer_job_id = link.job_id
|
||||
model.title = link.target.title
|
||||
model.url = link.target.url
|
||||
model.save()
|
||||
return link.with_id(model.pk)
|
||||
|
||||
def delete(self, link_id: int) -> None:
|
||||
JobLinkModel.objects.filter(pk=link_id).delete()
|
||||
Reference in New Issue
Block a user