""" backend/app/models/shipping_audit_event.py 用途:定义货代领域统一、仅追加的审计事件。 依赖:SQLAlchemy Base、货代 Run/Task/Intake/会话 PDF 工作项的稳定业务编号。 逻辑:各业务服务通过 audit_service 追加事件;事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。 进度审计阶段扩展 operation_id、对象关联、白名单前后快照、证据引用、结果与保留到期时间; 会话工作项阶段追加 owner_user_id、session_item_id 与脱敏 client_ip_hash/user_agent_hash; 禁止存储 PDF/邮件正文、模型原文、对象存储 URL、原始 IP/UA 或密钥。 """ from __future__ import annotations from datetime import datetime from typing import Any, Optional from sqlalchemy import CheckConstraint, DateTime, Index, Integer, JSON, String, Text, event from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base from app.core.errors import ValidationError class ShippingAuditEvent(Base): """货代领域的不可变审计事件;禁止业务代码更新或删除既有记录。""" __tablename__ = 'shipping_audit_events' __table_args__ = ( CheckConstraint( "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')", name='ck_shipping_audit_events_actor_type', ), CheckConstraint( "result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')", name='ck_shipping_audit_events_result', ), Index('ix_shipping_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'), Index('ix_shipping_audit_events_run_created', 'run_no', 'created_at'), Index('ix_shipping_audit_events_task_created', 'task_no', 'created_at'), Index('ix_shipping_audit_events_operation_created', 'operation_id', 'created_at'), Index('ix_shipping_audit_events_request_created', 'request_id', 'created_at'), Index('ix_shipping_audit_events_conversation_created', 'conversation_id', 'created_at'), Index('ix_shipping_audit_events_document_created', 'document_id', 'created_at'), Index('ix_shipping_audit_events_unit_created', 'unit_id', 'created_at'), Index('ix_shipping_audit_events_actor_created', 'actor_type', 'actor_id', 'created_at'), Index('ix_shipping_audit_events_event_type_created', 'event_type', 'created_at'), Index('ix_shipping_audit_events_retention_expires', 'retention_expires_at', 'id'), Index('ix_shipping_audit_events_session_item_created', 'session_item_id', 'created_at'), Index('ix_shipping_audit_events_owner_created', 'owner_user_id', 'created_at'), ) id: Mapped[int] = mapped_column(primary_key=True) event_type: Mapped[str] = mapped_column(String(64), nullable=False) aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False) aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False) run_no: Mapped[str | None] = mapped_column(String(64), nullable=True) task_no: Mapped[str | None] = mapped_column(String(64), nullable=True) intake_no: Mapped[str | None] = mapped_column(String(64), nullable=True) actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system') actor_id: Mapped[str | None] = mapped_column(String(128), nullable=True) actor_role: Mapped[str | None] = mapped_column(String(64), nullable=True) request_id: Mapped[str | None] = mapped_column(String(64), nullable=True) operation_id: Mapped[str | None] = mapped_column(String(64), nullable=True) correlation_id: Mapped[str | None] = mapped_column(String(64), nullable=True) source: Mapped[str | None] = mapped_column(String(32), nullable=True) result: Mapped[str | None] = mapped_column(String(16), nullable=True) error_code: Mapped[str | None] = mapped_column(String(64), nullable=True) conversation_id: Mapped[str | None] = mapped_column(String(100), nullable=True) unit_id: Mapped[str | None] = mapped_column(String(64), nullable=True) document_id: Mapped[str | None] = mapped_column(String(64), nullable=True) review_case_no: Mapped[str | None] = mapped_column(String(64), nullable=True) # 会话 PDF 工作项稳定编号(item_no);软引用,避免级联删除抹除审计。 session_item_id: Mapped[str | None] = mapped_column(String(64), nullable=True) # 业务属主(非操作者);代操作场景与 actor_id 区分。 owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True) # 仅存哈希,禁止写入原始 IP / User-Agent。 client_ip_hash: Mapped[str | None] = mapped_column(String(64), nullable=True) user_agent_hash: Mapped[str | None] = mapped_column(String(64), nullable=True) attempt_no: Mapped[int | None] = mapped_column(Integer, nullable=True) action: Mapped[str | None] = mapped_column(String(64), nullable=True) reason_code: Mapped[str | None] = mapped_column(String(128), nullable=True) reason: Mapped[str | None] = mapped_column(Text, nullable=True) before_hash: Mapped[str | None] = mapped_column(String(64), nullable=True) after_hash: Mapped[str | None] = mapped_column(String(64), nullable=True) before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) evidence_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True) artifact_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True) context_refs_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) metadata_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) retention_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) @event.listens_for(ShippingAuditEvent, 'before_update') def _reject_shipping_audit_update(_mapper, _connection, _target) -> None: """拒绝 ORM 更新,确保即使未调用审计服务也不能改写历史事件。""" raise ValidationError('Shipping audit event is append-only', code='SHIPPING_NOTICE.AUDIT_IMMUTABLE') @event.listens_for(ShippingAuditEvent, 'before_delete') def _reject_shipping_audit_delete(_mapper, _connection, _target) -> None: """拒绝 ORM 删除,避免业务清理或级联关系抹除审计事实。""" raise ValidationError('Shipping audit event is append-only', code='SHIPPING_NOTICE.AUDIT_IMMUTABLE')