from collections.abc import Iterable, Sequence from django.db.models import Q from apps.catalog.application.dto import ( ServiceNode, ServiceUnitNode, ServiceUnitSummary, WorkTypeNode, WorkTypeOption, ) from apps.catalog.infrastructure.orm import ServiceUnitModel, WorkTypeModel def _is_selectable(model: WorkTypeModel) -> bool: return ( model.is_active and model.service_unit.is_active and (model.service is None or model.service.is_active) ) def _option(model: WorkTypeModel) -> WorkTypeOption: return WorkTypeOption( id=model.pk, name=model.name, service_unit_id=model.service_unit_id, service_unit_name=model.service_unit.name, service_name=model.service.name if model.service else None, is_selectable=_is_selectable(model), ) # Selectable = the row and every parent above it are active (specification 16.3). _SELECTABLE = Q(is_active=True, service_unit__is_active=True) & ( Q(service__isnull=True) | Q(service__is_active=True) ) class DjangoCatalogQueries: def tree(self) -> Sequence[ServiceUnitNode]: units = ServiceUnitModel.objects.prefetch_related("services", "work_types") result = [] for unit in units: by_service: dict[int | None, list[WorkTypeNode]] = {} services = {s.pk: s for s in unit.services.all()} for wt in unit.work_types.all(): service = services.get(wt.service_id) if wt.service_id else None by_service.setdefault(wt.service_id, []).append( WorkTypeNode( id=wt.pk, service_unit_id=unit.pk, service_id=wt.service_id, name=wt.name, is_active=wt.is_active, is_selectable=wt.is_active and unit.is_active and (service is None or service.is_active), ) ) result.append( ServiceUnitNode( id=unit.pk, name=unit.name, is_shared=unit.is_shared, is_active=unit.is_active, services=tuple( ServiceNode( id=s.pk, service_unit_id=unit.pk, name=s.name, is_active=s.is_active, work_types=tuple(by_service.get(s.pk, [])), ) for s in services.values() ), work_types=tuple(by_service.get(None, [])), ) ) return result def active_service_units(self) -> Sequence[ServiceUnitSummary]: return [ ServiceUnitSummary(id=u.pk, name=u.name, is_shared=u.is_shared) for u in ServiceUnitModel.objects.filter(is_active=True) ] def work_type_options(self, service_unit_ids: Iterable[int]) -> Sequence[WorkTypeOption]: qs = ( WorkTypeModel.objects.filter(_SELECTABLE) .filter(Q(service_unit_id__in=list(service_unit_ids)) | Q(service_unit__is_shared=True)) .select_related("service_unit", "service") .order_by( "service_unit__is_shared", "service_unit__sort_order", "service_unit_id", "service__sort_order", "service_id", "sort_order", "id", ) ) return [_option(m) for m in qs] def get_work_type(self, work_type_id: int) -> WorkTypeOption | None: model = ( WorkTypeModel.objects.select_related("service_unit", "service") .filter(pk=work_type_id) .first() ) return _option(model) if model else None