""" backend/app/models/shipping_order_schema.py 用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。 依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。 逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json; definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum); 写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。 """ from __future__ import annotations import uuid from datetime import date, datetime from decimal import Decimal from typing import Any, Optional from sqlalchemy import ( Boolean, CheckConstraint, Date, DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, Text, UniqueConstraint, text, ) from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base def _uuid() -> str: """生成跨 PostgreSQL/SQLite 通用的 UUID 字符串主键。""" return str(uuid.uuid4()) def _default_field_category(context: Any) -> str: """为未显式分类的既有 ORM 创建路径按 scope 生成订单字段分类。""" return 'order_line' if context.get_current_parameters().get('scope') == 'line' else 'order_header' class ShippingOrderSchema(Base): """Schema 族容器;本轮默认族编码 STANDARD_SHIPPING_NOTICE,模型允许多族。""" __tablename__ = 'shipping_order_schemas' id: Mapped[int] = mapped_column(primary_key=True) schema_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) display_name: Mapped[str] = mapped_column(String(128), nullable=False) description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) auto_creation_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), 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) versions: Mapped[list['ShippingOrderSchemaVersion']] = relationship( back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderSchemaVersion.version' ) ShippingSchemaFamily = ShippingOrderSchema class ShippingOrderField(Base): """全局字段资产(系统标准或扩展)。标准不可弃用/删除;扩展仅 active⇄retired。""" __tablename__ = 'shipping_order_fields' __table_args__ = ( # 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 ('general_context', 'order_header', 'order_line')", name='ck_shipping_order_fields_category', ), CheckConstraint( "collection_mode IN ('deterministic_context', 'llm_extraction')", name='ck_shipping_order_fields_collection_mode', ), CheckConstraint( "value_type IN ('string', 'decimal', 'integer', 'date', 'boolean', 'enum')", name='ck_shipping_order_fields_value_type', ), CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_order_fields_status'), CheckConstraint( "asset_kind IN ('system_standard', 'extension')", name='ck_shipping_order_fields_asset_kind', ), CheckConstraint( "storage_mode IN ('typed_column', 'json_only')", name='ck_shipping_order_fields_storage_mode', ), Index('ix_shipping_order_fields_scope_status', 'scope', 'status'), Index('ix_shipping_order_fields_asset_kind', 'asset_kind'), ) id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid) field_code: Mapped[str] = mapped_column(String(64), nullable=False) scope: Mapped[str] = mapped_column(String(16), nullable=False) value_type: Mapped[str] = mapped_column(String(16), nullable=False) field_category: Mapped[str] = mapped_column(String(32), nullable=False, default=_default_field_category) collection_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='llm_extraction') asset_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='extension', server_default='extension') storage_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='json_only', server_default='json_only') storage_column: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) semantic_description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) display_name_default: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) fulfillment_role: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) display_sequence: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') published_once: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false')) retired_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) retired_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) restored_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) restored_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), 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) ShippingFieldAsset = ShippingOrderField class ShippingOrderSchemaVersion(Base): """ 订单 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__ = ( UniqueConstraint('schema_id', 'version', name='uq_shipping_order_schema_versions_schema_version'), CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_order_schema_versions_status'), Index( 'uq_shipping_order_schema_one_published', 'schema_id', unique=True, postgresql_where=text("status = 'published'"), sqlite_where=text("status = 'published'"), ), ) id: Mapped[int] = mapped_column(primary_key=True) schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True) source_version_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_schema_versions.id'), nullable=True ) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) retired_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) schema: Mapped['ShippingOrderSchema'] = relationship(back_populates='versions') source_version: Mapped[Optional['ShippingOrderSchemaVersion']] = relationship( remote_side='ShippingOrderSchemaVersion.id', foreign_keys=[source_version_id] ) class ShippingOrderSchemaAuditEvent(Base): """字段资产与 Schema 配置的追加式审计事件;不提供修改入口。""" __tablename__ = 'shipping_order_schema_audit_events' __table_args__ = ( CheckConstraint( "event_type IN (" "'draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', " "'field_saved', 'field_retired', 'field_restored', " "'extension_created', 'extension_updated', 'extension_retired', 'extension_restored', " "'family_created', 'field_adopted', 'field_unadopted', 'publish_blocked'" ")", name='ck_shipping_order_schema_audit_event_type', ), Index('ix_shipping_order_schema_audit_version_created', 'version_id', 'created_at'), Index('ix_shipping_order_schema_audit_schema_created', 'schema_id', 'created_at'), ) id: Mapped[int] = mapped_column(primary_key=True) schema_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=True) field_id: Mapped[Optional[str]] = mapped_column(String(36), nullable=True) version_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_schema_versions.id', ondelete='SET NULL'), nullable=True ) event_type: Mapped[str] = mapped_column(String(32), nullable=False) actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), 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) change_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) class ShippingOrderExtraction(Base): """一次订单解析审计;锁定 Schema 和输入快照,承载 LLM 原始结果及最终状态。""" __tablename__ = 'shipping_order_extractions' __table_args__ = ( Index('ix_shipping_order_extractions_task_created', 'task_id', 'created_at'), Index('ix_shipping_order_extractions_intake_created', 'intake_id', 'created_at'), # Version history pages aggregate and paginate the runtime records that used a Schema snapshot. Index('ix_shipping_order_extractions_schema_version_created', 'schema_version_id', 'created_at'), CheckConstraint( "status IN ('created', 'extracting', 'needs_review', 'accepted', 'failed', 'superseded')", name='ck_shipping_order_extractions_status', ), ) id: Mapped[int] = mapped_column(primary_key=True) run_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True, ) task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True) schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False) input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) status: Mapped[str] = mapped_column(String(32), nullable=False, default='created', server_default='created') raw_llm_output_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) normalized_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) validation_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), 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) schema_version: Mapped['ShippingOrderSchemaVersion'] = relationship() lines: Mapped[list['ShippingOrderLine']] = relationship( back_populates='extraction', cascade='all, delete-orphan', order_by='ShippingOrderLine.position' ) observations: Mapped[list['ShippingOrderFieldObservation']] = relationship( back_populates='extraction', cascade='all, delete-orphan' ) decisions: Mapped[list['ShippingOrderFieldDecision']] = relationship( back_populates='extraction', cascade='all, delete-orphan' ) values: Mapped[list['ShippingOrderFieldValue']] = relationship( back_populates='extraction', cascade='all, delete-orphan' ) class ShippingOrderLine(Base): """动态订单解析中的行身份;业务值全部位于 FieldValue。""" __tablename__ = 'shipping_order_lines' __table_args__ = (UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),) id: Mapped[int] = mapped_column(primary_key=True) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) position: Mapped[int] = mapped_column(Integer, nullable=False) line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines') class ShippingOrderFieldObservation(Base): """某字段来自某 Document/解析器的原始观察及可回查文本或版面证据。""" __tablename__ = 'shipping_order_field_observations' __table_args__ = (Index('ix_shipping_order_observations_extraction_field', 'extraction_id', 'field_id'),) id: Mapped[int] = mapped_column(primary_key=True) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True) field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=True) source_type: Mapped[str] = mapped_column(String(32), nullable=False) extractor: Mapped[str] = mapped_column(String(32), nullable=False) raw_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) normalized_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) evidence_quote: Mapped[Optional[str]] = mapped_column(Text, nullable=True) evidence_ref: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) evidence_metadata_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) confidence: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 4), nullable=True) evidence_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false')) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='observations') class ShippingOrderFieldDecision(Base): """后端对字段观察集合的最终裁决;下游只能消费 accepted 决定。""" __tablename__ = 'shipping_order_field_decisions' __table_args__ = ( Index( 'uq_shipping_order_decisions_header_field', 'extraction_id', 'field_id', unique=True, postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'), ), Index( 'uq_shipping_order_decisions_line_field', 'extraction_id', 'line_id', 'field_id', unique=True, postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'), ), CheckConstraint( "decision_status IN ('accepted', 'corroborated', 'needs_review', 'blocked', 'missing')", name='ck_shipping_order_decisions_status', ), ) id: Mapped[int] = mapped_column(primary_key=True) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True) field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id decision_status: Mapped[str] = mapped_column(String(32), nullable=False) selected_observation_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_field_observations.id'), nullable=True ) supporting_observation_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list) resolved_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) decided_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='decisions') class ShippingOrderFieldValue(Base): """已接受订单字段的类型化查询投影,供路由、匹配和 Excel 模板稳定引用。""" __tablename__ = 'shipping_order_field_values' __table_args__ = ( Index( 'uq_shipping_order_field_values_header_field', 'extraction_id', 'field_id', unique=True, postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'), ), Index( 'uq_shipping_order_field_values_line_field', 'extraction_id', 'line_id', 'field_id', unique=True, postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'), ), Index('ix_shipping_order_field_values_field_text', 'field_id', 'value_text'), Index('ix_shipping_order_field_values_field_decimal', 'field_id', 'value_decimal'), ) id: Mapped[int] = mapped_column(primary_key=True) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True) field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id value_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True) value_decimal: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True) value_integer: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) value_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) value_boolean: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True) value_json: Mapped[Any] = mapped_column(JSON, nullable=True) decision_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_field_decisions.id'), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='values')