Files
celtic-life-science/app/audit/router.py
T
Shubhankar45 0d30c58bf0 Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic
Snapshot of the working tree on srv1071960 (branch main), taken during
server cleanup. .env files, node_modules, builds, logs and media were excluded.
2026-11-07 05:43:12 +00:00

69 lines
2.5 KiB
Python

import uuid
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.schemas import ApprovalHistoryItem, AuditLogRead
from app.audit.service import AuditService
from app.auth.dependencies import assert_can_view_dcr, get_current_user
from app.common.enums import EntityType, Role
from app.common.exceptions import NotFoundError
from app.database.session import get_db
from app.reports.repository import DCRRepository
from app.users.models import User
router = APIRouter(prefix="/audit", tags=["audit"])
@router.get("", response_model=list[AuditLogRead])
async def get_audit_history(
entity_type: EntityType = Query(...),
entity_id: uuid.UUID = Query(...),
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Scoped audit history.
For a report, the caller must be able to view the report itself — the audit log is
not a side door around the data-scope rules.
"""
if entity_type == EntityType.DCR:
dcr = await DCRRepository(db).get(entity_id)
if dcr is None:
raise NotFoundError("Report not found")
await assert_can_view_dcr(db, current_user, dcr)
elif current_user.role not in (Role.ADMIN, Role.AGM):
from app.common.exceptions import ForbiddenError
raise ForbiddenError("Only ADMIN or AGM may read non-report audit history")
return await AuditService(db).history_for(entity_type, entity_id)
@router.get("/dcr/{dcr_id}/approval-history", response_model=list[ApprovalHistoryItem])
async def approval_history(
dcr_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> list[ApprovalHistoryItem]:
""""Approval history" is a filtered view over audit_log, not a second table."""
dcr = await DCRRepository(db).get(dcr_id)
if dcr is None:
raise NotFoundError("Report not found")
await assert_can_view_dcr(db, current_user, dcr)
entries = await AuditService(db).approval_history_for(dcr_id)
items: list[ApprovalHistoryItem] = []
for entry in entries:
actor = await db.get(User, entry.actor_user_id)
items.append(
ApprovalHistoryItem(
action=entry.action,
actor_name=actor.full_name if actor else "Unknown",
actor_role=actor.role.value if actor else "-",
comment=entry.comment,
at=entry.created_at,
)
)
return items