"""Explicit, application-level audit logging. Deliberately NOT automatic row-versioning (report §14.3 C4): an automatic versioner records *what* changed but cannot record *why* — and the manager's return reason is the single most important thing in this audit trail. Every `log()` call happens inside the caller's transaction, so a state change and its audit row commit together or not at all (V12). """ import uuid from typing import Any from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.audit.models import AuditLog from app.common.enums import AuditAction, EntityType class AuditService: def __init__(self, db: AsyncSession) -> None: self.db = db async def log( self, *, actor_user_id: uuid.UUID, entity_type: EntityType, entity_id: uuid.UUID, action: AuditAction, before: dict[str, Any] | None = None, after: dict[str, Any] | None = None, comment: str | None = None, ip_address: str | None = None, ) -> AuditLog: entry = AuditLog( actor_user_id=actor_user_id, entity_type=entity_type, entity_id=entity_id, action=action, before_data=before, after_data=after, comment=comment, ip_address=ip_address, ) self.db.add(entry) # Flush, not commit — the caller owns the transaction boundary. await self.db.flush() return entry async def history_for( self, entity_type: EntityType, entity_id: uuid.UUID ) -> list[AuditLog]: stmt = ( select(AuditLog) .where(AuditLog.entity_type == entity_type, AuditLog.entity_id == entity_id) .order_by(AuditLog.created_at.asc()) ) return list((await self.db.execute(stmt)).scalars().all()) async def approval_history_for(self, dcr_id: uuid.UUID) -> list[AuditLog]: """"Approval history" is a FILTERED QUERY, not a second table (report §13.2).""" workflow_actions = [ AuditAction.CREATE, AuditAction.SUBMIT, AuditAction.FORWARD, AuditAction.RETURN, AuditAction.APPROVE, ] stmt = ( select(AuditLog) .where( AuditLog.entity_type == EntityType.DCR, AuditLog.entity_id == dcr_id, AuditLog.action.in_(workflow_actions), ) .order_by(AuditLog.created_at.asc()) ) return list((await self.db.execute(stmt)).scalars().all())