Files
syops/backend/app/models/shipping_audit_event.py
hugoandCursor 323928626b feat(shipping-process-gates): 落地全门禁中断恢复并消除双真相
纳入 Execution/Gate/Attempt 模型与迁移、Worker/API/前端恢复卡片与 Admin 诊断,
Gate 阻断时清零旧 action_buttons,异常摘要统一脱敏,并为运维筛选与 Attempt Diff 补齐入口。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:08:32 +08:00

125 lines
8.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/models/shipping_audit_event.py
用途:定义货代领域统一、仅追加的审计事件。
依赖:SQLAlchemy Base;Workflow / Run / Task / Intake 等稳定业务编号(软引用)。
逻辑:各业务服务通过 audit_service 追加事件;actor_type 含 worker(门禁 Job);
事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。
进度审计阶段扩展 operation_id、对象关联、白名单前后快照、证据引用、结果与保留到期时间;
Workflow 阶段以 workflow_id / workflow_item_id / workflow_item_version_id 软引用批次与 PDF 项,
并写入 previous_event_hash / event_hash 哈希链与 diff_json;另含 owner_user_id 与脱敏
client_ip_hash/user_agent_hash;
项次派生阶段使用 LINE_DERIVATION_AUDIT_EVENT_TYPES(FIELD_DERIVED / LINE_NO_OVERRIDDEN /
DERIVATION_SIMULATED / EXPORT_GENERATED 等),元数据仅存脱敏摘要与规则校验和;
禁止存储 PDF/邮件正文、模型原文、对象存储 URL、原始 IP/UA 或密钥。
ORM before_update/before_delete 拒绝改删;PostgreSQL 另有 append-only 触发器
(迁移 a0e1f2b3c4d5);到期清理须 set_config('hxops.shipping_audit_purge','1')。
"""
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', 'worker')",
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_workflow_created', 'workflow_id', 'created_at'),
Index('ix_shipping_audit_events_workflow_item_created', 'workflow_item_id', 'created_at'),
Index('ix_shipping_audit_events_event_hash', 'event_hash'),
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)
# 操作者展示名(可选);与 actor_id 并存,禁止写入敏感联系方式。
actor_display: Mapped[str | None] = mapped_column(String(128), 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)
# Workflow 软引用:workflow_no / item_no / version id(字符串),避免级联删除抹除审计。
workflow_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
workflow_item_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
workflow_item_version_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
version_no: Mapped[int | None] = mapped_column(Integer, 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)
# 白名单前后快照差异;与哈希链一并支撑离线校验。
diff_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
previous_event_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
event_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
# 敏感等级:normal | sensitive;用于查询脱敏与访问审计分级。
sensitivity_level: Mapped[str | None] = mapped_column(String(16), 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')