from app.db.database import get_connection from app.db.migrations import run_migrations def _incident_select() -> str: return """ SELECT i.id, i.service_id, COALESCE(a.name, i.service_id) AS service_name, i.status, i.started_at, i.ended_at, CASE WHEN i.duration_seconds IS NOT NULL THEN i.duration_seconds WHEN LOWER(COALESCE(i.status, '')) = 'open' THEN CAST(strftime('%s', 'now') - strftime('%s', i.started_at) AS INTEGER) ELSE NULL END AS duration_seconds, i.title, i.description FROM service_incidents i LEFT JOIN apps a ON a.id = i.service_id """ def get_open_incidents(limit: int | None = None): run_migrations() con = get_connection() sql = f""" {_incident_select()} WHERE LOWER(COALESCE(i.status, '')) = 'open' ORDER BY i.started_at DESC, i.id DESC """ params = () if limit is not None: sql += " LIMIT ?" params = (limit,) rows = con.execute(sql, params).fetchall() con.close() return [dict(row) for row in rows] def get_recent_incidents(limit: int = 100): run_migrations() con = get_connection() rows = con.execute( f""" {_incident_select()} ORDER BY i.started_at DESC, i.id DESC LIMIT ? """, (limit,), ).fetchall() con.close() return [dict(row) for row in rows] def get_service_incidents(service_id: str, limit: int = 20): run_migrations() con = get_connection() rows = con.execute( f""" {_incident_select()} WHERE i.service_id = ? ORDER BY i.started_at DESC, i.id DESC LIMIT ? """, (service_id, limit), ).fetchall() con.close() return [dict(row) for row in rows] def count_open_incidents() -> int: run_migrations() con = get_connection() row = con.execute( """ SELECT COUNT(*) AS count FROM service_incidents WHERE LOWER(COALESCE(status, '')) = 'open' """ ).fetchone() con.close() return row["count"] if row else 0