"""Pack API, mounted by core under ``/packs/appointments`` (read-only, plus the undo button). * ``GET /appointments?day=&staff=&status=&limit=`` -> ``{"items": [...], "total": n}`` (``day``: ``today`` / ``tomorrow`` / ``YYYY-MM-DD``; default: upcoming). * ``GET /appointments/{number}`` -> one appointment. * ``GET /day?date=YYYY-MM-DD`` -> the day view: per staff member, working windows, bookings and free start times for the shortest service. * ``GET /escalations?status=open`` -> handovers to staff (medical questions, ...). * ``GET /messages?status=queued`` -> the outbox (inbound bodies are never returned). * ``POST /messages/{id}/cancel`` -> undo a queued message via the gateway (T1 ``appointments.cancel_message``, audited, as the operator). Everything runs in a session bound to the caller's tenant (RLS). Client data follows the tenant's PII mode (masked in strict mode). """ from __future__ import annotations import uuid from datetime import UTC, datetime, timedelta from typing import Any from fastapi import APIRouter, Depends, HTTPException, Query, Request from sqlalchemy import func, select from core.auth.deps import Principal, current_principal, require_role from core.db.session import Database from core.gateway.gateway import ToolCall from core.services import Services from core.tenancy.models import Role from packs.appointments.config import load_config from packs.appointments.models import ( APPOINTMENT_STATUSES, Appointment, Escalation, Message, Service, Staff, ) from packs.appointments.slots import free_starts, staff_days from packs.appointments.timeutil import day_bounds, human, resolve_day from packs.appointments.tools.common import ( CANCEL_TOOL, appointment_by_number, appointment_view, iso, ) router = APIRouter() def _svc(request: Request) -> Services: svc: Services = request.app.state.services return svc def _db(request: Request) -> Database: db: Database = request.app.state.services.db return db @router.get("/appointments") async def appointments( day: str | None = Query(default=None, max_length=20), staff: str | None = Query(default=None, max_length=80), status: str | None = Query(default=None, max_length=12), limit: int = Query(default=100, ge=1, le=500), p: Principal = Depends(current_principal), db: Database = Depends(_db), ) -> dict[str, Any]: if status and status not in APPOINTMENT_STATUSES: raise HTTPException(422, f"status must be one of {', '.join(APPOINTMENT_STATUSES)}") async with db.session(tenant_id=p.tenant_id) as s: cfg = await load_config(s, p.tenant_id) q = select(Appointment) if day: d = resolve_day(day, cfg.tz) if d is None: raise HTTPException(422, "bad day") lo, hi = day_bounds(d, cfg.tz) q = q.where(Appointment.starts_at >= lo, Appointment.starts_at < hi) else: q = q.where(Appointment.starts_at >= datetime.now(UTC) - timedelta(hours=1)) if staff: q = q.join(Staff, Staff.id == Appointment.staff_id).where( Staff.name.ilike(f"%{staff}%") ) if status: q = q.where(Appointment.status == status) total = (await s.execute(select(func.count()).select_from(q.subquery()))).scalar_one() rows = (await s.execute(q.order_by(Appointment.starts_at).limit(limit))).scalars() items = [await appointment_view(s, a, cfg) for a in rows] return {"items": items, "total": total} @router.get("/appointments/{number}") async def appointment( number: str, p: Principal = Depends(current_principal), db: Database = Depends(_db) ) -> dict[str, Any]: async with db.session(tenant_id=p.tenant_id) as s: cfg = await load_config(s, p.tenant_id) a = await appointment_by_number(s, number) if a is None: raise HTTPException(404, f"appointment {number} not found") return await appointment_view(s, a, cfg) @router.get("/day") async def day_view( date: str = Query(default="today", max_length=20), p: Principal = Depends(current_principal), db: Database = Depends(_db), ) -> dict[str, Any]: async with db.session(tenant_id=p.tenant_id) as s: cfg = await load_config(s, p.tenant_id) tz = cfg.tz d = resolve_day(date, tz) if d is None: raise HTTPException(422, "bad date") lo, hi = day_bounds(d, tz) staff = list( ( await s.execute(select(Staff).where(Staff.active.is_(True)).order_by(Staff.name)) ).scalars() ) shortest = ( await s.execute(select(func.min(Service.duration_min)).where(Service.active.is_(True))) ).scalar_one_or_none() or 30 rows = list( ( await s.execute( select(Appointment) .where(Appointment.starts_at >= lo, Appointment.starts_at < hi) .order_by(Appointment.starts_at) ) ).scalars() ) columns = [] for sd in await staff_days(s, d, tz, staff): mine = [a for a in rows if a.staff_id == sd.staff.id] free = free_starts(sd.windows, sd.busy, int(shortest), datetime.now(UTC)) columns.append( { "staff": sd.staff.name, "windows": [{"start": iso(a), "end": iso(b)} for a, b in sd.windows], "appointments": [await appointment_view(s, a, cfg) for a in mine], "free": [human(t, tz) for t in free], } ) return {"date": d.isoformat(), "timezone": cfg.timezone, "staff": columns} @router.get("/escalations") async def escalations( status: str = Query(default="open", max_length=12), p: Principal = Depends(current_principal), db: Database = Depends(_db), ) -> dict[str, Any]: async with db.session(tenant_id=p.tenant_id) as s: rows = ( await s.execute( select(Escalation) .where(Escalation.status == status) .order_by(Escalation.created_at.desc()) .limit(200) ) ).scalars() items = [ { "id": str(e.id), "kind": e.kind, "status": e.status, "summary": e.summary, "created_at": iso(e.created_at), } for e in rows ] return {"items": items} @router.get("/messages") async def messages( status: str | None = Query(default=None, max_length=12), limit: int = Query(default=50, ge=1, le=200), p: Principal = Depends(current_principal), db: Database = Depends(_db), ) -> dict[str, Any]: async with db.session(tenant_id=p.tenant_id) as s: q = select(Message).where(Message.direction == "outbound") if status: q = q.where(Message.status == status) rows = (await s.execute(q.order_by(Message.created_at.desc()).limit(limit))).scalars() items = [] for m in rows: queued = m.status == "queued" items.append( { "id": str(m.id), "kind": m.kind, "body": m.body, "template": m.template, "status": m.status, "send_after": iso(m.send_after) if queued else None, "sent_at": iso(m.sent_at), "undo_url": f"/packs/appointments/messages/{m.id}/cancel" if queued else None, } ) return {"items": items} @router.post("/messages/{message_id}/cancel") async def cancel_message( message_id: uuid.UUID, p: Principal = Depends(require_role(Role.AGENT_OPERATOR)), svc: Services = Depends(_svc), ) -> dict[str, Any]: out = await svc.gateway.execute( ToolCall( tenant_id=p.tenant_id, actor=p.actor, tool=CANCEL_TOOL, args={"message_id": str(message_id)}, ) ) if out.status not in ("executed", "replayed") or out.result is None or not out.result.ok: raise HTTPException(409, out.reason or "cannot cancel") return dict(out.result.data or {})