"""/timeline — events grouped by month (global, or one entity + what it develops).""" from __future__ import annotations from typing import Any from fastapi import APIRouter, Query, Request from aiatlas.api.common import COMPANY_TYPES, EVENT_COLS, EVENT_FROM, cached, change_event, csv, resolve_entity from aiatlas.db import connection, fetch_all router = APIRouter(prefix="/api/v1/timeline", tags=["timeline"]) @router.get("") @cached(120) async def timeline(request: Request, entity: str | None = None, year: int | None = Query(None, ge=1950, le=2100), category: str | None = None, importance_min: int | None = Query(None, ge=0, le=3), limit: int = Query(200, ge=1, le=1000)) -> dict[str, Any]: where = ["ev.event_type <> 'DOCUMENT_CHANGED'"] params: dict[str, Any] = {"lim": limit} async with connection() as conn: if entity: row = await resolve_entity(conn, entity) if row["entity_type"] in COMPANY_TYPES: where.append("(ev.entity_id = :eid or ev.entity_id in (select id from entities where organization_id = :eid union " "select object_id from relations where subject_id = :eid and predicate in ('develops','owns','operates','published') and valid_to is null))") else: where.append("ev.entity_id = :eid") params["eid"] = row["id"] if year: where.append("extract(year from coalesce(ev.effective_at, ev.observed_at)) = :year") params["year"] = year if category: where.append("ev.category = any(cast(:cats as text[]))") params["cats"] = csv(category) if importance_min is not None: where.append("ev.importance >= :imp") params["imp"] = importance_min rows = await fetch_all(conn, f"select to_char(coalesce(ev.effective_at, ev.observed_at) at time zone 'UTC', 'YYYY-MM') as month, {EVENT_COLS} from {EVENT_FROM} " f"where {' and '.join(where)} order by coalesce(ev.effective_at, ev.observed_at) desc, ev.id desc limit :lim", **params) groups: dict[str, list[dict[str, Any]]] = {} for r in rows: groups.setdefault(r["month"], []).append(change_event(r)) return {"items": [{"month": m, "count": len(evs), "events": evs} for m, evs in groups.items()], "total": len(rows)}