"""Service d'évaluation : géocodage, appel des modules en parallèle, application des seuils. Ni l'adresse ni les coordonnées ne sont conservées ou journalisées. """ import asyncio import logging import httpx from asgiref.sync import async_to_sync from django.conf import settings from factors.models import ContentBlock, DataSource, Factor, Region, ThresholdClass from .geocoding import Location, geocode from .providers import RawResult, get_providers logger = logging.getLogger(__name__) def http_client() -> httpx.AsyncClient: return httpx.AsyncClient( timeout=settings.PRISM_HTTP_TIMEOUT, headers={"User-Agent": settings.PRISM_USER_AGENT}, follow_redirects=True, ) async def _fetch(provider, client: httpx.AsyncClient, location: Location) -> RawResult: try: return await provider.fetch(client, location) except Exception as exc: # Seuls le code du facteur et le type d'erreur sont journalisés : les messages # d'httpx contiennent l'URL, donc les coordonnées. logger.warning("Facteur %s indisponible (%s)", provider.code, type(exc).__name__) return RawResult(provider.code, "unavailable") async def collect(address: str, codes: list[str]) -> tuple[Location, list[RawResult]]: providers = get_providers() async with http_client() as client: location = await geocode(client, address) results = await asyncio.gather( *( _fetch(providers[code], client, location) if code in providers else _missing_provider(code) for code in codes ) ) return location, list(results) async def _missing_provider(code: str) -> RawResult: return RawResult(code, "unavailable") def assess(address: str) -> dict: """Évalue une adresse ; lève les exceptions de `geocoding` en cas d'échec global.""" factors = list(Factor.objects.filter(active=True)) location, results = async_to_sync(collect)(address, [f.code for f in factors]) by_code = {result.code: result for result in results} return { "location": {"lat": location.lat, "lon": location.lon, "region": location.region}, "factors": [build_factor_result(f, by_code[f.code], location.region) for f in factors], } def build_factor_result(factor: Factor, raw: RawResult, region: str) -> dict: threshold = None if raw.status == "ok" and raw.source_value is not None: threshold = find_threshold(factor, region, raw.source_value) content = validated_content(factor, threshold) return { "code": factor.code, "label": factor.label, "status": raw.status, "level": threshold.level if threshold else None, "color": threshold.color if threshold else None, "summary": (threshold.label if threshold and threshold.label else raw.summary), "details": raw.details, "tabs": { "health_effects": content.health_effects if content else "", "actions": content.actions if content else "", "legend": legend(factor, region, content), }, "references": references(content), } def find_threshold(factor: Factor, region: str, source_value: str) -> ThresholdClass | None: """Classe de la région, sinon classe nationale (ex. qualité de l'air).""" candidates = { c.region: c for c in ThresholdClass.objects.filter( factor=factor, region__in=[region, Region.BELGIUM], source_value=source_value ) } return candidates.get(region) or candidates.get(Region.BELGIUM) def validated_content(factor: Factor, threshold: ThresholdClass | None) -> ContentBlock | None: contents = ContentBlock.objects.filter(factor=factor, status=ContentBlock.Status.VALIDATED) if threshold is not None: specific = contents.filter(threshold_class=threshold).first() if specific: return specific return contents.filter(threshold_class__isnull=True).first() def legend(factor: Factor, region: str, content: ContentBlock | None = None) -> dict: regions = [region, Region.BELGIUM] sources = DataSource.objects.filter(factor=factor, region__in=regions) scale = ThresholdClass.objects.filter(factor=factor, region__in=regions).order_by("level") return { "source": ", ".join(sorted({s.provider for s in sources})), "text": content.legend_text if content else "", "scale": [ {"level": c.level, "color": c.color, "label": c.label or c.source_value} for c in scale ], } def references(content: ContentBlock | None) -> list[dict]: if content is None: return [] return [ {"n": cited.order, "title": cited.reference.title, "url": cited.reference.url} for cited in content.contentreference_set.select_related("reference") ]