""" Activity & audit log endpoints. """ from fastapi import APIRouter from app.database import get_activity_log, get_upload_history, get_conn router = APIRouter(prefix="/activity", tags=["Activity & Audit"]) @router.get("/log") def activity_log(limit: int = 100): """Return the most recent user activity log entries.""" return get_activity_log(limit=limit) @router.get("/uploads") def upload_history(limit: int = 50): """Return upload history.""" return get_upload_history(limit=limit) @router.get("/stats") def activity_stats(): """Return high-level counts from the activity log.""" conn = get_conn() total = conn.execute("SELECT COUNT(*) FROM activity_log").fetchone()[0] uploads = conn.execute("SELECT COUNT(*) FROM upload_history").fetchone()[0] errors = conn.execute("SELECT COUNT(*) FROM upload_history WHERE status='error'").fetchone()[0] last_event = conn.execute( "SELECT timestamp, action FROM activity_log ORDER BY timestamp DESC LIMIT 1" ).fetchone() # DB data row counts bms_rows = conn.execute("SELECT COUNT(*) FROM bms_data").fetchone()[0] fleet_rows = conn.execute("SELECT COUNT(*) FROM fleet_data").fetchone()[0] supplier_rows = conn.execute("SELECT COUNT(*) FROM supplier_data").fetchone()[0] inspection_rows = conn.execute("SELECT COUNT(*) FROM inspection_data").fetchone()[0] conn.close() return { "total_activity_events": total, "total_uploads": uploads, "failed_uploads": errors, "last_event": dict(last_event) if last_event else None, "stored_data": { "bms_readings": bms_rows, "fleet_assets": fleet_rows, "suppliers": supplier_rows, "inspections": inspection_rows, } } @router.delete("/log") def clear_activity_log(): """Clear the activity log (keeps upload history).""" conn = get_conn() conn.execute("DELETE FROM activity_log") conn.commit() conn.close() return {"message": "Activity log cleared"}