import uuid from datetime import datetime from sqlalchemy import CheckConstraint, DateTime, Index, String from sqlalchemy.dialects.postgresql import JSONB, UUID from sqlalchemy.orm import Mapped, mapped_column from app.core.db import Base from app.models.mixins import UUIDPrimaryKeyMixin ACTOR_TYPES = ("user", "service", "system") class AuditEvent(UUIDPrimaryKeyMixin, Base): __tablename__ = "audit_events" __table_args__ = ( CheckConstraint("actor_type IN ('user','service','system')", name="ck_audit_actor_type"), Index("ix_audit_action_occurred", "action", "occurred_at"), Index("ix_audit_entity", "entity_type", "entity_id"), ) actor_type: Mapped[str] = mapped_column(String(20), nullable=False) actor_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True)) actor_label: Mapped[str] = mapped_column(String(120), nullable=False) action: Mapped[str] = mapped_column(String(80), nullable=False) entity_type: Mapped[str] = mapped_column(String(30), nullable=False) entity_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True)) correlation_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) before_json: Mapped[dict | None] = mapped_column(JSONB) after_json: Mapped[dict | None] = mapped_column(JSONB) metadata_json: Mapped[dict | None] = mapped_column(JSONB) occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)