""" backend/app/models/shipping.py 用途:货代发货通知批次、任务、事件、库存文件、接入记录、文档/候选与库存映射模型。 依赖:models.base.Base;规范订单行见 shipping_task_line。 逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等; Intake.create_idempotency_key 承载混合/open_existing 确认请求重放; Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离; Document/Candidate 承载「一邮件多订单」识别;ShippingTask.source_candidate_id 记录正式建单来源; ShippingTask.supersedes_task_id 唯一约束保证修订链线性; order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本; current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实。 """ from __future__ import annotations from datetime import datetime from typing import List, Optional from sqlalchemy import ( Boolean, CheckConstraint, DateTime, Float, ForeignKey, ForeignKeyConstraint, Index, Integer, JSON, String, Text, UniqueConstraint, text, ) from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base class ShippingBatch(Base): """货代发货通知批次(一次多文件上传的聚合容器)""" __tablename__ = 'shipping_batches' __table_args__ = ( Index('ix_shipping_batches_user_created', 'user_id', 'created_at'), Index('ix_shipping_batches_conversation', 'conversation_id'), UniqueConstraint( 'user_id', 'create_idempotency_key', name='uq_shipping_batches_user_create_idempotency', ), ) id: Mapped[int] = mapped_column(primary_key=True) batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) current_focus_task_no: Mapped[Optional[str]] = mapped_column( String(64), ForeignKey( 'shipping_tasks.task_no', name='fk_shipping_batches_current_focus_task_no_shipping_tasks', use_alter=True, ), nullable=True, ) file_count: Mapped[int] = mapped_column(Integer, default=1) create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) tasks: Mapped[List['ShippingTask']] = relationship( 'ShippingTask', back_populates='batch', foreign_keys='ShippingTask.batch_id', ) class ShippingTask(Base): """货代发货通知 task(Chatflow Tool 编排状态机)""" __tablename__ = 'shipping_tasks' __table_args__ = ( Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'), Index('ix_shipping_tasks_conversation', 'conversation_id'), Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'), Index('ix_shipping_tasks_upload_status', 'upload_status'), Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'), Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'), Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'), Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'), Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'), Index('ix_shipping_tasks_user_business_fingerprint', 'user_id', 'business_fingerprint'), Index('ix_shipping_tasks_user_content_fingerprint', 'user_id', 'content_fingerprint'), # 线性版本链:同一父任务至多一个后继(NULL 不冲突) UniqueConstraint('supersedes_task_id', name='uq_shipping_tasks_supersedes_task_id'), Index('ix_shipping_tasks_duplicate_source_task_id', 'duplicate_source_task_id'), ) id: Mapped[int] = mapped_column(primary_key=True) task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) shipping_case_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_cases.id'), index=True, nullable=True, ) batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True) user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) source_type: Mapped[str] = mapped_column(String(32), default='manual') source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True) source_intake_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_notice_intakes.id'), index=True, nullable=True, ) # 阶段二:由 Candidate 正式建单时回填;与 Candidate.consumed_task_id 对向引用,用 use_alter source_candidate_id: Mapped[Optional[int]] = mapped_column( ForeignKey( 'shipping_notice_candidates.id', name='fk_shipping_tasks_source_candidate_id', use_alter=True, ), index=True, nullable=True, ) business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) supersedes_task_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_tasks.id'), nullable=True, ) duplicate_source_task_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_tasks.id'), nullable=True, ) duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) duplicate_resolution_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True) customer_resolution_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) customer_resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) customer_identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) customer_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) customer_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) inventory_connector_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) # 动态订单 FieldValue 编辑的乐观锁版本。 order_data_version: Mapped[int] = mapped_column( Integer, default=1, server_default=text('1'), nullable=False, ) current_order_extraction_id: Mapped[Optional[int]] = mapped_column( ForeignKey( 'shipping_order_extractions.id', name='fk_shipping_tasks_current_order_extraction_id', use_alter=True, ), nullable=True, index=True, ) # 阶段 1:库存、导出和上传必须通过此指针读取冻结订单快照。 order_snapshot_id: Mapped[Optional[int]] = mapped_column( ForeignKey( 'shipping_order_snapshots.id', name='fk_shipping_tasks_order_snapshot_id', use_alter=True, ), nullable=True, unique=True, index=True, ) process_status: Mapped[str] = mapped_column(String(32), default='created', index=True) current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True) inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) export_version: Mapped[int] = mapped_column(Integer, default=1) freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) upload_attempt: Mapped[int] = mapped_column(Integer, default=0) idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) # 任务处置与流程状态正交:process_status 继续驱动履约工作流,生命周期负责作废/归档。 lifecycle_status: Mapped[str] = mapped_column( String(16), nullable=False, default='active', server_default=text("'active'"), index=True, ) deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) deleted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) deletion_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) voided_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) voided_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) void_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) archived_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) archived_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) batch: Mapped[Optional['ShippingBatch']] = relationship( 'ShippingBatch', back_populates='tasks', foreign_keys=[batch_id], ) shipping_case: Mapped[Optional['ShippingCase']] = relationship( 'ShippingCase', back_populates='tasks', lazy='joined', ) events: Mapped[List['ShippingTaskEvent']] = relationship( 'ShippingTaskEvent', back_populates='task', cascade='all, delete-orphan', ) field_conflicts: Mapped[List['ShippingTaskFieldConflict']] = relationship( 'ShippingTaskFieldConflict', back_populates='task', cascade='all, delete-orphan', ) class ShippingTaskEvent(Base): """发货 task 审计事件""" __tablename__ = 'shipping_task_events' id: Mapped[int] = mapped_column(primary_key=True) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True) event_type: Mapped[str] = mapped_column(String(64), index=True) detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True) request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) task: Mapped['ShippingTask'] = relationship('ShippingTask', back_populates='events') class ShippingTaskPurgeAudit(Base): """任务永久删除后的独立快照审计;不保留 task 外键以允许物理清除。""" __tablename__ = 'shipping_task_purge_audits' __table_args__ = (Index('ix_shipping_task_purge_audits_task_no_created', 'task_no_snapshot', 'created_at'),) id: Mapped[int] = mapped_column(primary_key=True) task_no_snapshot: Mapped[str] = mapped_column(String(64), nullable=False) actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) reason: Mapped[str] = mapped_column(Text, nullable=False) snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) class ShippingInventoryFile(Base): """货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。""" __tablename__ = 'shipping_inventory_files' __table_args__ = ( Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'), Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'), Index( 'ix_shipping_inventory_files_source_snapshot', 'source_code', 'warehouse_id', 'snapshot_status', 'exported_at', ), Index( 'ix_shipping_inventory_files_source_warehouse', 'source_code', 'warehouse_id', ), Index( 'uq_shipping_inventory_files_rpa_identity_ready', 'rpa_run_no', 'source_code', 'warehouse_id', unique=True, postgresql_where=text( "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" ), sqlite_where=text( "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" ), ), # 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。 Index( 'uq_shipping_inventory_files_rpa_dynamic_source_ready', 'rpa_run_no', 'source_code', unique=True, postgresql_where=text( "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " "AND source_code IS NOT NULL AND warehouse_id IS NULL" ), sqlite_where=text( "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " "AND source_code IS NOT NULL AND warehouse_id IS NULL" ), ), ) id: Mapped[int] = mapped_column(primary_key=True) inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True) user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) storage_path: Mapped[str] = mapped_column(String(500), nullable=False) schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false')) inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) line_count: Mapped[int] = mapped_column(Integer, default=0) share_mode: Mapped[str] = mapped_column(String(32), default='task_only') warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True) source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) batch: Mapped[Optional['ShippingBatch']] = relationship('ShippingBatch', foreign_keys=[batch_id]) links: Mapped[List['ShippingTaskInventoryLink']] = relationship( 'ShippingTaskInventoryLink', back_populates='inventory_file', cascade='all, delete-orphan', ) class ShippingTaskInventoryLink(Base): """发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。""" __tablename__ = 'shipping_task_inventory_links' __table_args__ = ( Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'), Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'), Index( 'ix_shipping_task_inventory_links_task_source', 'task_id', 'matched_source_code', ), ) id: Mapped[int] = mapped_column(primary_key=True) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True) inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True) link_role: Mapped[str] = mapped_column(String(32), default='member') access_mode: Mapped[str] = mapped_column(String(32), default='readonly') is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True) link_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) matched_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) matched_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) audit_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) task: Mapped['ShippingTask'] = relationship('ShippingTask', foreign_keys=[task_id]) inventory_file: Mapped['ShippingInventoryFile'] = relationship( 'ShippingInventoryFile', back_populates='links', foreign_keys=[inventory_file_id], ) class ShippingNoticeIntake(Base): """发货通知接入记录:分别跟踪文件预处理与订单抽取状态。""" __tablename__ = 'shipping_notice_intakes' __table_args__ = ( CheckConstraint( "purpose IN ('shipping_notice', 'order_document_profile_sample')", name='ck_shipping_notice_intakes_purpose', ), UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'), UniqueConstraint( 'asset_id', 'purpose', 'parser_version', name='uq_shipping_notice_intakes_asset_purpose_parser', ), Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'), Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'), Index('ix_shipping_notice_intakes_expires', 'expires_at'), Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'), Index('ix_shipping_notice_intakes_duplicate_status_created', 'duplicate_status', 'created_at'), Index('ix_shipping_notice_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'), Index('ix_shipping_notice_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'), ) id: Mapped[int] = mapped_column(primary_key=True) intake_no: Mapped[str] = mapped_column(String(64), nullable=False) asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=False) user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False) parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True) order_extraction_status: Mapped[str] = mapped_column( String(32), default='not_started', server_default=text("'not_started'"), nullable=False, index=True, ) order_extraction_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True) structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) parser_version: Mapped[str] = mapped_column(String(32), nullable=False) parse_job_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True) # 解析执行代次:格式 "{job_id}:{job.attempts}";超时回收清空后旧 Worker 写回被拒绝 parse_lease: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) duplicate_status: Mapped[str] = mapped_column( String(32), default='unchecked', server_default=text("'unchecked'"), nullable=False, ) duplicate_matches_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) duplicate_resolution: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) consumed_batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True) consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True) create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) class ShippingNoticeDocument(Base): """ 发货通知文档单元:邮件正文或单个附件(阶段二)。 核心逻辑:Intake 解析后按 attachment_key 幂等 upsert;附件型 Document 可挂 derived FileAsset。 """ __tablename__ = 'shipping_notice_documents' __table_args__ = ( UniqueConstraint( 'intake_id', 'attachment_key', name='uq_shipping_notice_documents_intake_attachment_key', ), # 支撑 Candidate (primary_document_id, intake_id) 复合外键 UniqueConstraint('id', 'intake_id', name='uq_shipping_notice_documents_id_intake'), Index('ix_shipping_notice_documents_intake_id', 'intake_id'), Index('ix_shipping_notice_documents_asset_id', 'asset_id'), Index('ix_shipping_notice_documents_content_hash', 'content_hash'), Index('ix_shipping_notice_documents_parse_status', 'parse_status'), ) id: Mapped[int] = mapped_column(primary_key=True) intake_id: Mapped[int] = mapped_column( ForeignKey('shipping_notice_intakes.id'), nullable=False, ) asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True) document_type: Mapped[str] = mapped_column(String(32), nullable=False) attachment_key: Mapped[str] = mapped_column(String(64), nullable=False) filename: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) classification: Mapped[str] = mapped_column(String(32), default='unknown', nullable=False) parse_status: Mapped[str] = mapped_column(String(32), default='pending', nullable=False) extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True) parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) current_layout_version_id: Mapped[Optional[int]] = mapped_column( ForeignKey( 'shipping_document_layout_versions.id', name='fk_shipping_notice_documents_current_layout_version', ondelete='SET NULL', use_alter=True, ), nullable=True, ) order_extraction_status: Mapped[str] = mapped_column( String(32), default='not_started', server_default=text("'not_started'"), nullable=False, index=True, ) order_extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) order_extraction_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) order_extraction_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) current_layout_version = relationship( 'ShippingDocumentLayoutVersion', foreign_keys=[current_layout_version_id], post_update=True, ) layout_versions = relationship( 'ShippingDocumentLayoutVersion', foreign_keys='ShippingDocumentLayoutVersion.document_id', back_populates='document', cascade='all, delete-orphan', ) class ShippingNoticeCandidate(Base): """ 订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。 核心逻辑:一个 Document 可抽取多个 Candidate;candidate_key 保证重提取幂等, 重复检测、自动建单与待补字段状态均落在 Candidate 级。 """ __tablename__ = 'shipping_notice_candidates' __table_args__ = ( CheckConstraint( "candidate_status IN ('provisional', 'accepted', 'rejected', 'expired')", name='ck_shipping_notice_candidates_status', ), CheckConstraint( "acceptance_mode IS NULL OR acceptance_mode IN ('automatic', 'manual', 'legacy')", name='ck_shipping_notice_candidates_acceptance_mode', ), UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'), UniqueConstraint( 'intake_id', 'candidate_key', 'order_extraction_run_id', name='uq_shipping_notice_candidates_intake_key_run', ), # 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接 ForeignKeyConstraint( ['primary_document_id', 'intake_id'], ['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'], name='fk_shipping_notice_candidates_document_intake', ), Index('ix_shipping_notice_candidates_intake_id', 'intake_id'), Index('ix_shipping_notice_candidates_primary_document_id', 'primary_document_id'), Index('ix_shipping_notice_candidates_po_number', 'po_number'), Index( 'ix_shipping_notice_candidates_user_fingerprint', 'business_fingerprint', ), Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'), Index('ix_shipping_notice_candidates_fulfillment_gate', 'candidate_status', 'is_current_version'), ) id: Mapped[int] = mapped_column(primary_key=True) candidate_no: Mapped[str] = mapped_column(String(64), nullable=False) intake_id: Mapped[int] = mapped_column( ForeignKey('shipping_notice_intakes.id'), nullable=False, ) primary_document_id: Mapped[int] = mapped_column(Integer, nullable=False) candidate_key: Mapped[str] = mapped_column(String(128), nullable=False) source_order_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) # 当前 Candidate 对应的受控订单抽取真相;识别运行时不得再从 LLM 摘要 JSON 反查该关联。 order_extraction_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_extractions.id'), nullable=True, index=True, ) order_extraction_run_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True, ) # 仅当前版本候选可进入建单;旧版本保留为只读审计和重新识别失败时的回退依据。 is_current_version: Mapped[bool] = mapped_column( Boolean, default=True, server_default=text('true'), nullable=False, index=True, ) selected_before_superseded: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True) candidate_status_before_superseded: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) missing_fields_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) validation_status: Mapped[str] = mapped_column( String(32), default='pending', server_default=text("'pending'"), nullable=False, ) conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) # `selected` is a legacy UI projection. Fulfillment must use candidate_status. candidate_status: Mapped[str] = mapped_column( String(32), default='provisional', server_default=text("'provisional'"), nullable=False, index=True, ) acceptance_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) accepted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) accepted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) acceptance_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) acceptance_policy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) selected: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'), nullable=False) business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) duplicate_status: Mapped[str] = mapped_column( String(32), default='unchecked', server_default=text("'unchecked'"), nullable=False, ) duplicate_matches_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) duplicate_resolution: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) consumed_task_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_tasks.id'), nullable=True, ) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)