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()