Files
PacketStation/server/packetstation/api/departments.py
T

30 lines
1.0 KiB
Python
Raw Normal View History

"""Departments and their stations (read-only in phase 1)."""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends
from .deps import Db, Principal, current_principal, get_db
router = APIRouter(prefix="/api", tags=["departments"])
@router.get("/departments")
def departments(_: Principal = Depends(current_principal), d: Db = Depends(get_db)) -> list[dict[str, Any]]: # noqa: B008
conn = d.conn
rows = conn.execute(
"SELECT code, slug, name, kind::text, weld FROM departments WHERE active ORDER BY sort, code"
).fetchall()
stations = conn.execute(
"SELECT dept_code, id, name FROM stations WHERE active ORDER BY dept_code, sort, name"
).fetchall()
by_dept: dict[str, list[dict[str, Any]]] = {}
for code, sid, name in stations:
by_dept.setdefault(code, []).append({"id": int(sid), "name": name})
return [
{"code": r[0], "slug": r[1], "name": r[2], "kind": r[3], "weld": bool(r[4]), "stations": by_dept.get(r[0], [])}
for r in rows
]