Files

38 lines
1.6 KiB
Python
Raw Permalink Normal View History

from datetime import datetime
from sqlalchemy import BigInteger, DateTime, ForeignKey, Index, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base, utcnow
from app.models.user import User
class AuditLog(Base):
"""Immutable audit record. The application exposes no update or delete
path for these rows; one row per changed field (field_name null for
record-level events such as create/transition/attachment/reopen)."""
__tablename__ = "audit_log"
__table_args__ = (
Index("ix_audit_log_ncr", "ncr_id", "created_at"),
Index("ix_audit_log_created_at", "created_at"),
)
# BigInteger on MySQL; plain INTEGER on SQLite (required for autoincrement).
id: Mapped[int] = mapped_column(
BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True
)
# Nullable so admin actions without an NCR (settings, role changes) are auditable too.
ncr_id: Mapped[int | None] = mapped_column(
ForeignKey("ncrs.id", ondelete="SET NULL"), nullable=True
)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
created_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow)
action: Mapped[str] = mapped_column(String(40))
field_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
old_value: Mapped[str | None] = mapped_column(Text, nullable=True)
new_value: Mapped[str | None] = mapped_column(Text, nullable=True)
detail: Mapped[str | None] = mapped_column(String(500), nullable=True)
user: Mapped[User] = relationship(lazy="selectin")