"""操作日志模型(全链路可追溯)""" from datetime import datetime from typing import Optional from sqlalchemy import BigInteger, Integer, ForeignKey, Text, VARCHAR from sqlalchemy.orm import Mapped, mapped_column from .base import Base from .types import JSONB from ..utils.audited_write import format_beijing_datetime class OperationLog(Base): __tablename__ = "operation_logs" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) user_id: Mapped[int] = mapped_column( BigInteger, ForeignKey("users.id"), nullable=False, index=True ) project_id: Mapped[Optional[int]] = mapped_column( BigInteger, ForeignKey("projects.id"), nullable=True, index=True ) entity_type: Mapped[str] = mapped_column(VARCHAR(64), nullable=False, index=True) entity_id: Mapped[str] = mapped_column(VARCHAR(128), nullable=False, index=True) action: Mapped[str] = mapped_column(VARCHAR(64), nullable=False, index=True) before_data: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True) after_data: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True) remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) trace_id: Mapped[Optional[str]] = mapped_column(VARCHAR(64), nullable=True, index=True) interface_path: Mapped[Optional[str]] = mapped_column(VARCHAR(255), nullable=True, index=True) caller: Mapped[str] = mapped_column(VARCHAR(16), nullable=False, default="system", index=True) @property def created_at_beijing(self) -> Optional[str]: return format_beijing_datetime(self.created_at if isinstance(self.created_at, datetime) else None)