from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy import text from sqlalchemy.orm import Session from typing import Any from app.database import get_session from app.auth import get_current_user router = APIRouter() def _row(r) -> dict: return dict(r._mapping) @router.get("") def list_actions( colony_id: int = Query(...), session: Session = Depends(get_session), _: str = Depends(get_current_user), ) -> list[dict]: rows = session.execute(text(""" SELECT * FROM colony_actions WHERE colony_id = :colony_id ORDER BY date::DATE DESC, created_at DESC """), {"colony_id": colony_id}).fetchall() return [_row(r) for r in rows] @router.post("", status_code=201) def create_action( body: dict[str, Any], session: Session = Depends(get_session), _: str = Depends(get_current_user), ) -> dict: row = session.execute(text(""" INSERT INTO colony_actions (colony_id, date, time, type, notes, related_colony_id) VALUES (:colony_id, :date, :time, :type, :notes, :related_colony_id) RETURNING * """), { "colony_id": body.get("colony_id"), "date": body.get("date"), "time": body.get("time"), "type": body.get("type"), "notes": body.get("notes"), "related_colony_id": body.get("related_colony_id"), }).fetchone() session.commit() return _row(row) @router.get("/{id}") def get_action( id: int, session: Session = Depends(get_session), _: str = Depends(get_current_user), ) -> dict: row = session.execute( text("SELECT * FROM colony_actions WHERE id = :id"), {"id": id} ).fetchone() if row is None: raise HTTPException(status_code=404, detail="Not found") return _row(row) @router.put("/{id}") def update_action( id: int, body: dict[str, Any], session: Session = Depends(get_session), _: str = Depends(get_current_user), ) -> dict: result = session.execute(text(""" UPDATE colony_actions SET date = :date, type = :type, notes = :notes WHERE id = :id RETURNING * """), { "id": id, "date": body.get("date"), "type": body.get("type"), "notes": body.get("notes"), }).fetchone() session.commit() if result is None: raise HTTPException(status_code=404, detail="Not found") return _row(result) @router.delete("/{id}", status_code=204) def delete_action( id: int, session: Session = Depends(get_session), _: str = Depends(get_current_user), ): session.execute(text("DELETE FROM colony_actions WHERE id = :id"), {"id": id}) session.commit()