feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验

- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全
- 引入审计事件的哈希链校验机制,支持数据完整性验证
- 增强订单抽取与审计功能,支持敏感快照的访问控制
- 更新相关模型与服务,确保新功能的完整性与可追溯性
- 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
hugo committed 2026-07-31 08:59:44 +08:00
1 parent 95cdfe66b0
commit d0fe084999
225 files changed
+25923 -6653

No files matched your search

+10 -2
View File
@@ -73,7 +73,12 @@ from app.models.shipping_order_extraction_run import (
ShippingOrderExtractionUnit,
)
from app.models.shipping_audit_event import ShippingAuditEvent
from app.models.shipping_session_pdf_work_item import ShippingSessionPdfWorkItem
from app.models.shipping_notice_workflow import (
ShippingNoticeWorkflow,
ShippingNoticeWorkflowEvent,
ShippingNoticeWorkflowItem,
ShippingNoticeWorkflowItemVersion,
)
from app.models.shipping_order_document_profile import (
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
@@ -198,7 +203,10 @@ __all__ = [
'ShippingOrderExtractionProgressEvent',
'ShippingOrderExtractionDiagnosticAudit',
'ShippingAuditEvent',
'ShippingSessionPdfWorkItem',
'ShippingNoticeWorkflow',
'ShippingNoticeWorkflowItem',
'ShippingNoticeWorkflowItemVersion',
'ShippingNoticeWorkflowEvent',
'ShippingOrderExtractionQualityBatch',
'ShippingOrderExtractionQualityLabel',
'ShippingOrderDocumentProfile',
+24 -5
View File
@@ -2,11 +2,17 @@
backend/app/models/shipping_audit_event.py
用途:定义货代领域统一、仅追加的审计事件。
依赖:SQLAlchemy Base、货代 Run/Task/Intake/会话 PDF 工作项的稳定业务编号。
依赖:SQLAlchemy Base;Workflow / Run / Task / Intake 等稳定业务编号(软引用)。
逻辑:各业务服务通过 audit_service 追加事件;事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。
进度审计阶段扩展 operation_id、对象关联、白名单前后快照、证据引用、结果与保留到期时间;
会话工作项阶段追加 owner_user_id、session_item_id 与脱敏 client_ip_hash/user_agent_hash;
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
@@ -45,7 +51,9 @@ class ShippingAuditEvent(Base):
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_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'),
)
@@ -59,6 +67,8 @@ class ShippingAuditEvent(Base):
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)
@@ -69,8 +79,11 @@ class ShippingAuditEvent(Base):
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)
# 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。
@@ -84,6 +97,12 @@ class ShippingAuditEvent(Base):
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)
@@ -0,0 +1,311 @@
"""
backend/app/models/shipping_notice_workflow.py
用途:定义货代发货通知 Workflow / Item / Version / Event 四层事实源。
依赖:users、agents、shipping_notice_documents、shipping_order_extraction_runs、
shipping_order_review_cases、shipping_tasks。
逻辑:一次上传批次 = Workflow;每个 PDF 创建时即有 WorkflowItem;
重识别只新增 ItemVersion 并切换 current 指针;用户可见节点写入 WorkflowEvent;
审计通过业务编号软引用本表,禁止级联删除抹除追溯。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingNoticeWorkflow(Base):
"""一次上传/识别批次;重新打开对话复用未关闭 Workflow,不新建。"""
__tablename__ = 'shipping_notice_workflows'
__table_args__ = (
UniqueConstraint('workflow_no', name='uq_shipping_notice_workflows_no'),
CheckConstraint(
"status IN ("
"'open', 'completed', 'cancelled', 'failed'"
")",
name='ck_shipping_notice_workflows_status',
),
CheckConstraint('lock_version >= 1', name='ck_shipping_notice_workflows_lock_version'),
Index(
'ix_shipping_notice_workflows_conversation_status',
'conversation_id',
'status',
'updated_at',
),
Index(
'ix_shipping_notice_workflows_owner_status',
'owner_user_id',
'status',
'updated_at',
),
Index(
'ix_shipping_notice_workflows_open_conversation',
'conversation_id',
'updated_at',
postgresql_where=text("status = 'open'"),
sqlite_where=text("status = 'open'"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False)
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open')
current_stage: Mapped[str] = mapped_column(
String(64), nullable=False, default='queued', server_default='queued',
)
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
closed_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class ShippingNoticeWorkflowItem(Base):
"""PDF 级稳定实体;识别开始前即存在,覆盖解析到 Excel 全阶段。"""
__tablename__ = 'shipping_notice_workflow_items'
__table_args__ = (
UniqueConstraint('item_no', name='uq_shipping_notice_workflow_items_no'),
UniqueConstraint(
'workflow_id',
'root_document_id',
name='uq_shipping_notice_workflow_items_workflow_root_doc',
),
UniqueConstraint(
'current_case_id',
name='uq_shipping_notice_workflow_items_current_case',
),
CheckConstraint(
"lifecycle_status IN ("
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
"'building_order', 'inventory_matching', 'generating_excel', "
"'manual_upload_pending', 'reparse_failed', "
"'cancelled', 'failed', 'closed'"
")",
name='ck_shipping_notice_workflow_items_lifecycle',
),
CheckConstraint(
"closed_reason IS NULL OR closed_reason IN ("
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated', 'failed'"
")",
name='ck_shipping_notice_workflow_items_closed_reason',
),
CheckConstraint('lock_version >= 1', name='ck_shipping_notice_workflow_items_lock_version'),
CheckConstraint(
'current_version_no >= 1',
name='ck_shipping_notice_workflow_items_version_no',
),
Index(
'ix_shipping_notice_workflow_items_workflow_lifecycle',
'workflow_id',
'lifecycle_status',
'updated_at',
),
Index(
'ix_shipping_notice_workflow_items_conversation_lifecycle',
'conversation_id',
'lifecycle_status',
'updated_at',
),
Index(
'ix_shipping_notice_workflow_items_owner_lifecycle',
'owner_user_id',
'lifecycle_status',
'updated_at',
),
Index(
'ix_shipping_notice_workflow_items_open_conversation',
'conversation_id',
'updated_at',
postgresql_where=text(
"lifecycle_status NOT IN ('closed', 'cancelled')"
),
sqlite_where=text(
"lifecycle_status NOT IN ('closed', 'cancelled')"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
item_no: Mapped[str] = mapped_column(String(64), nullable=False)
workflow_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
)
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
# 同源 PDF 稳定身份:首次纳入时的 Document;替换文件不改变本字段。
root_document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
)
current_document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
)
# 软指针:避免与 Version.workflow_item_id 形成循环外键;由 ledger 保证一致性。
current_version_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
current_version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
current_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
)
current_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
current_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id'), nullable=True,
)
current_case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
current_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lifecycle_status: Mapped[str] = mapped_column(
String(32), nullable=False, default='queued', server_default='queued',
)
current_stage: Mapped[str] = mapped_column(
String(64), nullable=False, default='queued', server_default='queued',
)
closed_reason: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class ShippingNoticeWorkflowItemVersion(Base):
"""重识别版本链;关联 Run / Case / Task / Excel,旧版本只读留存。"""
__tablename__ = 'shipping_notice_workflow_item_versions'
__table_args__ = (
UniqueConstraint(
'workflow_item_id',
'version_no',
name='uq_shipping_notice_workflow_item_versions_item_no',
),
CheckConstraint('version_no >= 1', name='ck_shipping_notice_workflow_item_versions_no'),
CheckConstraint(
"status IN ("
"'active', 'superseded', 'failed', 'cancelled'"
")",
name='ck_shipping_notice_workflow_item_versions_status',
),
Index(
'ix_shipping_notice_workflow_item_versions_item_created',
'workflow_item_id',
'created_at',
),
Index(
'ix_shipping_notice_workflow_item_versions_run',
'run_id',
),
Index(
'ix_shipping_notice_workflow_item_versions_case',
'case_id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
workflow_item_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_workflow_items.id'), nullable=False, index=True,
)
item_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
workflow_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
)
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
)
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
)
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id'), nullable=True,
)
case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_tasks.id'), nullable=True,
)
task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
excel_artifact_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='active', server_default='active',
)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
is_readonly: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default='false')
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class ShippingNoticeWorkflowEvent(Base):
"""用户可见、按 Workflow 顺序递增的节点事件(与审计账本并存)。"""
__tablename__ = 'shipping_notice_workflow_events'
__table_args__ = (
UniqueConstraint(
'workflow_id',
'seq_no',
name='uq_shipping_notice_workflow_events_seq',
),
Index(
'ix_shipping_notice_workflow_events_workflow_occurred',
'workflow_id',
'occurred_at',
),
Index(
'ix_shipping_notice_workflow_events_item_occurred',
'workflow_item_id',
'occurred_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
workflow_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
)
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
workflow_item_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notice_workflow_items.id'), nullable=True, index=True,
)
item_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
workflow_item_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notice_workflow_item_versions.id'), nullable=True,
)
version_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
seq_no: Mapped[int] = mapped_column(Integer, nullable=False)
event_code: Mapped[str] = mapped_column(String(64), nullable=False)
stage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
message_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
occurred_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+15 -4
View File
@@ -4,6 +4,7 @@ backend/app/models/shipping_order_schema.py
用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、users。
逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json;
definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum);
写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。
"""
@@ -73,14 +74,16 @@ class ShippingOrderField(Base):
__tablename__ = 'shipping_order_fields'
__table_args__ = (
UniqueConstraint('field_code', name='uq_shipping_order_fields_field_code'),
# Header/Line may intentionally share a business code (for example
# reservation_id); scope is part of the asset identity.
UniqueConstraint('field_code', 'scope', name='uq_shipping_order_fields_code_scope'),
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'),
CheckConstraint(
"field_category IN ('order_header', 'order_line')",
"field_category IN ('general_context', 'order_header', 'order_line')",
name='ck_shipping_order_fields_category',
),
CheckConstraint(
"collection_mode IN ('llm_extraction')",
"collection_mode IN ('deterministic_context', 'llm_extraction')",
name='ck_shipping_order_fields_collection_mode',
),
CheckConstraint(
@@ -129,7 +132,15 @@ ShippingFieldAsset = ShippingOrderField
class ShippingOrderSchemaVersion(Base):
"""订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。"""
"""
订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。
definition_json 契约要点:
- fields[]:字段采用与识别规则
- auto_creation_policy:自动建单策略
- derivation_rules[]:同行明细字段派生(首期 copy_if_empty → line_no)
- derivation_rules_checksum:派生规则稳定校验和
"""
__tablename__ = 'shipping_order_schema_versions'
__table_args__ = (
@@ -4,6 +4,8 @@ backend/app/models/shipping_order_snapshot.py
用途:保存从订单解析候选冻结而来的不可变履约订单快照及人工复核审计。
依赖:shipping_order_schema 的 Extraction、shipping_tasks、shipping_customers 与 users。
逻辑:order_freeze_service 将已接受 Extraction 的字段按稳定 field_id 冻结为 Snapshot;库存、导出和上传阶段只消费本模块的快照。
Phase 0+ 扩展约定:rule_versions_json 可含 derivation_rules_snapshot / derivation_rules_checksum;
source_manifest_json 可含 field_lineage(值来源、规则引用、覆盖原因、证据引用)。
"""
from __future__ import annotations
@@ -35,8 +37,10 @@ class ShippingOrderSnapshot(Base):
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False)
# 可含 derivation_rules_snapshot / derivation_rules_checksum 等规则版本投影。
rule_versions_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实。
# 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实;
# 可含 field_lineage(按 field_code 记录 value_source / rule_id / override_reason / evidence_refs)。
source_manifest_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 保留所有已发布 Header 字段;核心字段同时写入下方强类型列,扩展字段由业务配置按 field_id 消费。
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
@@ -1,114 +0,0 @@
"""
backend/app/models/shipping_session_pdf_work_item.py
用途:定义聊天会话内「PDF 工作项」聚合实体,作为本次处理的唯一业务边界。
依赖:users、shipping_notice_documents、shipping_order_extraction_runs、shipping_order_review_cases。
逻辑:同会话同源 PDF 仅一条工作项;重识别只切换 current_* 版本指针,不新建工作项;
关闭后默认折叠。阶段 0 仅落库契约;写路径与读模型在阶段 1 实现。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
String,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingSessionPdfWorkItem(Base):
"""会话级 PDF 工作项;当前有效 Run/Case 仅由本表指针表达,禁止前端按最新 Run 猜测。"""
__tablename__ = 'shipping_session_pdf_work_items'
__table_args__ = (
UniqueConstraint('item_no', name='uq_shipping_session_pdf_work_items_no'),
UniqueConstraint(
'conversation_id',
'root_document_id',
name='uq_shipping_session_pdf_work_items_conversation_root_doc',
),
# 同一 Case 最多作为一条工作项的当前有效版本,防止双指针并发确认。
UniqueConstraint(
'current_case_id',
name='uq_shipping_session_pdf_work_items_current_case',
),
CheckConstraint(
"lifecycle_status IN ("
"'pending_review', 'extracting', 'reparse_failed', 'closed'"
")",
name='ck_shipping_session_pdf_work_items_lifecycle',
),
CheckConstraint(
"closed_reason IS NULL OR closed_reason IN ("
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated'"
")",
name='ck_shipping_session_pdf_work_items_closed_reason',
),
CheckConstraint('lock_version >= 1', name='ck_shipping_session_pdf_work_items_lock_version'),
CheckConstraint(
'current_version_no >= 1',
name='ck_shipping_session_pdf_work_items_version_no',
),
Index(
'ix_shipping_session_pdf_work_items_conversation_lifecycle',
'conversation_id',
'lifecycle_status',
'updated_at',
),
Index(
'ix_shipping_session_pdf_work_items_owner_lifecycle',
'owner_user_id',
'lifecycle_status',
'updated_at',
),
Index(
'ix_shipping_session_pdf_work_items_open_conversation',
'conversation_id',
'updated_at',
postgresql_where=text("lifecycle_status <> 'closed'"),
sqlite_where=text("lifecycle_status <> 'closed'"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
item_no: Mapped[str] = mapped_column(String(64), nullable=False)
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
# 同源 PDF 稳定身份:首次纳入会话时的 Document;替换文件不改变本字段。
root_document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
)
current_document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
)
current_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
)
current_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
current_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id'), nullable=True,
)
current_case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 面向用户的版本序号(V1/V2);重识别成功递增,失败回退不递增。
current_version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
lifecycle_status: Mapped[str] = mapped_column(
String(32), nullable=False, default='pending_review', server_default='pending_review',
)
closed_reason: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
+2
View File
@@ -91,6 +91,8 @@ class User(Base):
'training_hr_manage': self.role in {'admin', 'hr'},
# 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
'shipping_notice_force_create': self.role == 'admin',
# 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予
'shipping_notice.audit_sensitive_read': self.role == 'admin',
}
def get_feature_permissions(self) -> dict[str, bool]: