Squash of branch refactor/phase0-guardrails-and-models-split — 4 commits,
81 files, 173/173 pytest green, OpenAPI contract preserved (360 paths /
484 operations).
## Phase 0 — Architecture guardrails
Three defense-in-depth layers to keep the architecture rules enforced
regardless of who opens Claude Code in this repo:
1. .claude/settings.json PreToolUse hook on Write/Edit blocks any file
that would exceed the 500-line hard cap. Auto-loads in every Claude
session in this repo.
2. scripts/githooks/pre-commit (install via scripts/install-hooks.sh)
enforces the LOC cap locally, freezes migrations/ without
[migration-approved], and protects guardrail files without
[guardrail-change].
3. .gitea/workflows/ci.yaml gains loc-budget + guardrail-integrity +
sbom-scan (syft+grype) jobs, adds mypy --strict for the new Python
packages (compliance/{services,repositories,domain,schemas}), and
tsc --noEmit for admin-compliance + developer-portal.
Per-language conventions documented in AGENTS.python.md, AGENTS.go.md,
AGENTS.typescript.md at the repo root — layering, tooling, and explicit
"what you may NOT do" lists. Root CLAUDE.md is prepended with the six
non-negotiable rules. Each of the 10 services gets a README.md.
scripts/check-loc.sh enforces soft 300 / hard 500 and surfaces the
current baseline of 205 hard + 161 soft violations so Phases 1-4 can
drain it incrementally. CI gates only CHANGED files in PRs so the
legacy baseline does not block unrelated work.
## Deprecation sweep
47 files. Pydantic V1 regex= -> pattern= (2 sites), class Config ->
ConfigDict in source_policy_router.py (schemas.py intentionally skipped;
it is the Phase 1 Step 3 split target). datetime.utcnow() ->
datetime.now(timezone.utc) everywhere including SQLAlchemy default=
callables. All DB columns already declare timezone=True, so this is a
latent-bug fix at the Python side, not a schema change.
DeprecationWarning count dropped from 158 to 35.
## Phase 1 Step 1 — Contract test harness
tests/contracts/test_openapi_baseline.py diffs the live FastAPI /openapi.json
against tests/contracts/openapi.baseline.json on every test run. Fails on
removed paths, removed status codes, or new required request body fields.
Regenerate only via tests/contracts/regenerate_baseline.py after a
consumer-updated contract change. This is the safety harness for all
subsequent refactor commits.
## Phase 1 Step 2 — models.py split (1466 -> 85 LOC shim)
compliance/db/models.py is decomposed into seven sibling aggregate modules
following the existing repo pattern (dsr_models.py, vvt_models.py, ...):
regulation_models.py (134) — Regulation, Requirement
control_models.py (279) — Control, Mapping, Evidence, Risk
ai_system_models.py (141) — AISystem, AuditExport
service_module_models.py (176) — ServiceModule, ModuleRegulation, ModuleRisk
audit_session_models.py (177) — AuditSession, AuditSignOff
isms_governance_models.py (323) — ISMSScope, Context, Policy, Objective, SoA
isms_audit_models.py (468) — Finding, CAPA, MgmtReview, InternalAudit,
AuditTrail, Readiness
models.py becomes an 85-line re-export shim in dependency order so
existing imports continue to work unchanged. Schema is byte-identical:
__tablename__, column definitions, relationship strings, back_populates,
cascade directives all preserved.
All new sibling files are under the 500-line hard cap; largest is
isms_audit_models.py at 468. No file in compliance/db/ now exceeds
the hard cap.
## Phase 1 Step 3 — infrastructure only
backend-compliance/compliance/{schemas,domain,repositories}/ packages
are created as landing zones with docstrings. compliance/domain/
exports DomainError / NotFoundError / ConflictError / ValidationError /
PermissionError — the base classes services will use to raise
domain-level errors instead of HTTPException.
PHASE1_RUNBOOK.md at backend-compliance/PHASE1_RUNBOOK.md documents
the nine-step execution plan for Phase 1: snapshot baseline,
characterization tests, split models.py (this commit), split schemas.py
(next), extract services, extract repositories, mypy --strict, coverage.
## Verification
backend-compliance/.venv-phase1: uv python install 3.12 + pip -r requirements.txt
PYTHONPATH=. pytest compliance/tests/ tests/contracts/
-> 173 passed, 0 failed, 35 warnings, OpenAPI 360/484 unchanged
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
322 lines
10 KiB
Python
322 lines
10 KiB
Python
"""
|
|
FastAPI routes for Compliance Escalations.
|
|
|
|
Endpoints:
|
|
GET /escalations — list with filters (status, priority, limit, offset)
|
|
POST /escalations — create new escalation
|
|
GET /escalations/stats — counts per status and priority
|
|
GET /escalations/{id} — get single escalation
|
|
PUT /escalations/{id} — update escalation
|
|
PUT /escalations/{id}/status — update status only
|
|
DELETE /escalations/{id} — delete escalation
|
|
"""
|
|
|
|
import logging
|
|
from datetime import datetime, timezone
|
|
from typing import Optional, Any, Dict
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, Header
|
|
from pydantic import BaseModel
|
|
from sqlalchemy import text
|
|
from sqlalchemy.orm import Session
|
|
|
|
from classroom_engine.database import get_db
|
|
from .tenant_utils import get_tenant_id as _get_tenant_id
|
|
from .db_utils import row_to_dict as _row_to_dict
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter(prefix="/escalations", tags=["escalations"])
|
|
|
|
|
|
# =============================================================================
|
|
# Pydantic Schemas
|
|
# =============================================================================
|
|
|
|
class EscalationCreate(BaseModel):
|
|
title: str
|
|
description: Optional[str] = None
|
|
priority: str = 'medium' # low|medium|high|critical
|
|
category: Optional[str] = None # dsgvo_breach|ai_act|vendor|internal|other
|
|
assignee: Optional[str] = None
|
|
reporter: Optional[str] = None
|
|
source_module: Optional[str] = None
|
|
source_id: Optional[str] = None
|
|
due_date: Optional[datetime] = None
|
|
|
|
|
|
class EscalationUpdate(BaseModel):
|
|
title: Optional[str] = None
|
|
description: Optional[str] = None
|
|
priority: Optional[str] = None
|
|
status: Optional[str] = None
|
|
category: Optional[str] = None
|
|
assignee: Optional[str] = None
|
|
due_date: Optional[datetime] = None
|
|
|
|
|
|
class EscalationStatusUpdate(BaseModel):
|
|
status: str
|
|
resolved_at: Optional[datetime] = None
|
|
|
|
|
|
# =============================================================================
|
|
# Routes
|
|
# =============================================================================
|
|
|
|
@router.get("")
|
|
async def list_escalations(
|
|
status: Optional[str] = Query(None),
|
|
priority: Optional[str] = Query(None),
|
|
limit: int = Query(50, ge=1, le=500),
|
|
offset: int = Query(0, ge=0),
|
|
tenant_id: str = Depends(_get_tenant_id),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""List escalations with optional filters."""
|
|
where_clauses = ["tenant_id = :tenant_id"]
|
|
params: Dict[str, Any] = {"tenant_id": tenant_id, "limit": limit, "offset": offset}
|
|
|
|
if status:
|
|
where_clauses.append("status = :status")
|
|
params["status"] = status
|
|
if priority:
|
|
where_clauses.append("priority = :priority")
|
|
params["priority"] = priority
|
|
|
|
where_sql = " AND ".join(where_clauses)
|
|
|
|
rows = db.execute(
|
|
text(
|
|
f"SELECT * FROM compliance_escalations WHERE {where_sql} "
|
|
f"ORDER BY created_at DESC LIMIT :limit OFFSET :offset"
|
|
),
|
|
params,
|
|
).fetchall()
|
|
|
|
total_row = db.execute(
|
|
text(f"SELECT COUNT(*) FROM compliance_escalations WHERE {where_sql}"),
|
|
{k: v for k, v in params.items() if k not in ("limit", "offset")},
|
|
).fetchone()
|
|
|
|
return {
|
|
"items": [_row_to_dict(r) for r in rows],
|
|
"total": total_row[0] if total_row else 0,
|
|
"limit": limit,
|
|
"offset": offset,
|
|
}
|
|
|
|
|
|
@router.post("", status_code=201)
|
|
async def create_escalation(
|
|
request: EscalationCreate,
|
|
tenant_id: str = Depends(_get_tenant_id),
|
|
user_id: Optional[str] = Header(None, alias="x-user-id"),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Create a new escalation."""
|
|
row = db.execute(
|
|
text(
|
|
"""
|
|
INSERT INTO compliance_escalations
|
|
(tenant_id, title, description, priority, status, category,
|
|
assignee, reporter, source_module, source_id, due_date)
|
|
VALUES
|
|
(:tenant_id, :title, :description, :priority, 'open', :category,
|
|
:assignee, :reporter, :source_module, :source_id, :due_date)
|
|
RETURNING *
|
|
"""
|
|
),
|
|
{
|
|
"tenant_id": tenant_id,
|
|
"title": request.title,
|
|
"description": request.description,
|
|
"priority": request.priority,
|
|
"category": request.category,
|
|
"assignee": request.assignee,
|
|
"reporter": request.reporter,
|
|
"source_module": request.source_module,
|
|
"source_id": request.source_id,
|
|
"due_date": request.due_date,
|
|
},
|
|
).fetchone()
|
|
|
|
db.commit()
|
|
return _row_to_dict(row)
|
|
|
|
|
|
@router.get("/stats")
|
|
async def get_stats(
|
|
tenant_id: str = Depends(_get_tenant_id),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Return counts per status and priority."""
|
|
status_rows = db.execute(
|
|
text(
|
|
"SELECT status, COUNT(*) as cnt FROM compliance_escalations "
|
|
"WHERE tenant_id = :tenant_id GROUP BY status"
|
|
),
|
|
{"tenant_id": tenant_id},
|
|
).fetchall()
|
|
|
|
priority_rows = db.execute(
|
|
text(
|
|
"SELECT priority, COUNT(*) as cnt FROM compliance_escalations "
|
|
"WHERE tenant_id = :tenant_id GROUP BY priority"
|
|
),
|
|
{"tenant_id": tenant_id},
|
|
).fetchall()
|
|
|
|
total_row = db.execute(
|
|
text("SELECT COUNT(*) FROM compliance_escalations WHERE tenant_id = :tenant_id"),
|
|
{"tenant_id": tenant_id},
|
|
).fetchone()
|
|
|
|
active_row = db.execute(
|
|
text(
|
|
"SELECT COUNT(*) FROM compliance_escalations "
|
|
"WHERE tenant_id = :tenant_id AND status NOT IN ('resolved', 'closed')"
|
|
),
|
|
{"tenant_id": tenant_id},
|
|
).fetchone()
|
|
|
|
by_status = {"open": 0, "in_progress": 0, "escalated": 0, "resolved": 0, "closed": 0}
|
|
for r in status_rows:
|
|
key = r[0] if r[0] in by_status else r[0]
|
|
by_status[key] = r[1]
|
|
|
|
by_priority = {"low": 0, "medium": 0, "high": 0, "critical": 0}
|
|
for r in priority_rows:
|
|
if r[0] in by_priority:
|
|
by_priority[r[0]] = r[1]
|
|
|
|
return {
|
|
"by_status": by_status,
|
|
"by_priority": by_priority,
|
|
"total": total_row[0] if total_row else 0,
|
|
"active": active_row[0] if active_row else 0,
|
|
}
|
|
|
|
|
|
@router.get("/{escalation_id}")
|
|
async def get_escalation(
|
|
escalation_id: str,
|
|
tenant_id: str = Depends(_get_tenant_id),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Get a single escalation by ID."""
|
|
row = db.execute(
|
|
text(
|
|
"SELECT * FROM compliance_escalations "
|
|
"WHERE id = :id AND tenant_id = :tenant_id"
|
|
),
|
|
{"id": escalation_id, "tenant_id": tenant_id},
|
|
).fetchone()
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail=f"Escalation {escalation_id} not found")
|
|
return _row_to_dict(row)
|
|
|
|
|
|
@router.put("/{escalation_id}")
|
|
async def update_escalation(
|
|
escalation_id: str,
|
|
request: EscalationUpdate,
|
|
tenant_id: str = Depends(_get_tenant_id),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Update an escalation's fields."""
|
|
existing = db.execute(
|
|
text(
|
|
"SELECT id FROM compliance_escalations "
|
|
"WHERE id = :id AND tenant_id = :tenant_id"
|
|
),
|
|
{"id": escalation_id, "tenant_id": tenant_id},
|
|
).fetchone()
|
|
if not existing:
|
|
raise HTTPException(status_code=404, detail=f"Escalation {escalation_id} not found")
|
|
|
|
updates = request.dict(exclude_none=True)
|
|
if not updates:
|
|
row = db.execute(
|
|
text("SELECT * FROM compliance_escalations WHERE id = :id"),
|
|
{"id": escalation_id},
|
|
).fetchone()
|
|
return _row_to_dict(row)
|
|
|
|
set_clauses = ", ".join(f"{k} = :{k}" for k in updates.keys())
|
|
updates["id"] = escalation_id
|
|
updates["updated_at"] = datetime.now(timezone.utc)
|
|
|
|
row = db.execute(
|
|
text(
|
|
f"UPDATE compliance_escalations SET {set_clauses}, updated_at = :updated_at "
|
|
f"WHERE id = :id RETURNING *"
|
|
),
|
|
updates,
|
|
).fetchone()
|
|
db.commit()
|
|
return _row_to_dict(row)
|
|
|
|
|
|
@router.put("/{escalation_id}/status")
|
|
async def update_status(
|
|
escalation_id: str,
|
|
request: EscalationStatusUpdate,
|
|
tenant_id: str = Depends(_get_tenant_id),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Update only the status of an escalation."""
|
|
existing = db.execute(
|
|
text(
|
|
"SELECT id FROM compliance_escalations "
|
|
"WHERE id = :id AND tenant_id = :tenant_id"
|
|
),
|
|
{"id": escalation_id, "tenant_id": tenant_id},
|
|
).fetchone()
|
|
if not existing:
|
|
raise HTTPException(status_code=404, detail=f"Escalation {escalation_id} not found")
|
|
|
|
resolved_at = request.resolved_at
|
|
if request.status in ('resolved', 'closed') and resolved_at is None:
|
|
resolved_at = datetime.now(timezone.utc)
|
|
|
|
row = db.execute(
|
|
text(
|
|
"UPDATE compliance_escalations "
|
|
"SET status = :status, resolved_at = :resolved_at, updated_at = :updated_at "
|
|
"WHERE id = :id RETURNING *"
|
|
),
|
|
{
|
|
"status": request.status,
|
|
"resolved_at": resolved_at,
|
|
"updated_at": datetime.now(timezone.utc),
|
|
"id": escalation_id,
|
|
},
|
|
).fetchone()
|
|
db.commit()
|
|
return _row_to_dict(row)
|
|
|
|
|
|
@router.delete("/{escalation_id}")
|
|
async def delete_escalation(
|
|
escalation_id: str,
|
|
tenant_id: str = Depends(_get_tenant_id),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Delete an escalation."""
|
|
existing = db.execute(
|
|
text(
|
|
"SELECT id FROM compliance_escalations "
|
|
"WHERE id = :id AND tenant_id = :tenant_id"
|
|
),
|
|
{"id": escalation_id, "tenant_id": tenant_id},
|
|
).fetchone()
|
|
if not existing:
|
|
raise HTTPException(status_code=404, detail=f"Escalation {escalation_id} not found")
|
|
|
|
db.execute(
|
|
text("DELETE FROM compliance_escalations WHERE id = :id"),
|
|
{"id": escalation_id},
|
|
)
|
|
db.commit()
|
|
return {"success": True, "message": f"Escalation {escalation_id} deleted"}
|