Files
syops/backend/app/models/shipping.py
T
hugo c94d173f92 feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口
完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
2026-08-11 14:04:39 +08:00

703 lines
39 KiB
Python
Raw 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.py
用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
ShippingNotice.idempotency_key 为货代上传幂等;
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
Intake/Notice/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载「一邮件多订单」识别;ShippingNotice.source_candidate_id 记录正式建单来源;
ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性;
order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本;
current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实;
阶段 1:Intake.source_type / order_submission_id 挂接 shipping_order_submissions;
建单前接入层表名为 shipping_order_intakes / documents / candidates(类名 ShippingOrder*)。
"""
from __future__ import annotations
import uuid
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 ShippingNotice(Base):
"""
正式发货通知(Candidate 建单后的履约实体)。
核心逻辑:Chatflow Tool 编排状态机;建单前 OT 聚合根见 ShippingOrderTask(shipping_order_tasks)。
"""
__tablename__ = 'shipping_notices'
__table_args__ = (
Index('ix_shipping_notices_user_status', 'user_id', 'process_status'),
Index('ix_shipping_notices_conversation', 'conversation_id'),
Index('ix_shipping_notices_current_step', 'current_step'),
Index('ix_shipping_notices_upload_status', 'upload_status'),
Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'),
Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'),
Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
Index('ix_shipping_notices_active_inventory_candidate_set_id', 'active_inventory_candidate_set_id'),
Index('ix_shipping_notices_active_process_execution_id', 'active_process_execution_id'),
Index('ix_shipping_notices_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
Index('ix_shipping_notices_user_source_content_hash', 'user_id', 'source_content_hash'),
Index('ix_shipping_notices_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_notices_user_content_fingerprint', 'user_id', 'content_fingerprint'),
# 线性版本链:同一父任务至多一个后继(NULL 不冲突)
UniqueConstraint('supersedes_task_id', name='uq_shipping_notices_supersedes_task_id'),
Index('ix_shipping_notices_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,
)
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_order_intakes.id'),
index=True,
nullable=True,
)
# 阶段二:由 Candidate 正式建单时回填;与 Candidate.consumed_task_id 对向引用,用 use_alter
source_candidate_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_candidates.id',
name='fk_shipping_notices_source_candidate_id',
use_alter=True,
),
index=True,
nullable=True,
)
order_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_tasks.id',
name='fk_shipping_notices_order_task_id',
use_alter=True,
),
nullable=True,
index=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_notices.id'),
nullable=True,
)
duplicate_source_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.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)
active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_inventory_candidate_sets.id',
name='fk_shipping_notices_active_inventory_candidate_set_id',
use_alter=True,
),
nullable=True,
)
# P0-3:当前业务真相只由此 Execution 的六个正式 Gate 决定;历史 Execution 保留审计。
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_process_executions.id',
name='fk_shipping_notices_active_process_execution_id',
use_alter=True,
),
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_notices_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_notices_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)
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_notices.id'), index=True)
event_type: Mapped[str] = mapped_column(String(64), index=True)
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
before_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
after_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=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['ShippingNotice'] = relationship('ShippingNotice', 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_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)
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)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), 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)
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_notices.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)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True)
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), 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['ShippingNotice'] = relationship('ShippingNotice', foreign_keys=[task_id])
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
'ShippingInventoryFile',
back_populates='links',
foreign_keys=[inventory_file_id],
)
class ShippingOrderIntake(Base):
"""
发货通知接入记录:分别跟踪文件预处理与订单抽取状态。
阶段 1:source_type=eml|direct_pdf 标识裁决边界;order_submission_id 挂接上传 Submission。
表名 shipping_order_intakes(建单前接入层)。
"""
__tablename__ = 'shipping_order_intakes'
__table_args__ = (
CheckConstraint(
"purpose IN ('shipping_notice', 'order_document_profile_sample')",
name='ck_shipping_order_intakes_purpose',
),
CheckConstraint(
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
name='ck_shipping_order_intakes_source_type',
),
UniqueConstraint('intake_no', name='uq_shipping_order_intakes_intake_no'),
UniqueConstraint(
'asset_id',
'purpose',
'parser_version',
name='uq_shipping_order_intakes_asset_purpose_parser',
),
Index('ix_shipping_order_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
Index('ix_shipping_order_intakes_user_upload_batch_created', 'user_id', 'upload_batch_id', 'created_at'),
Index('ix_shipping_order_intakes_parse_status_created', 'parse_status', 'created_at'),
Index('ix_shipping_order_intakes_expires', 'expires_at'),
Index('ix_shipping_order_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_order_intakes_duplicate_status_created', 'duplicate_status', 'created_at'),
Index('ix_shipping_order_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'),
Index('ix_shipping_order_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'),
Index('ix_shipping_order_intakes_source_type', 'source_type'),
Index('ix_shipping_order_intakes_order_submission_id', 'order_submission_id'),
)
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)
# 同一输入框一次选取的上传批次;发送端只能冻结同一批次的 Intake。
upload_batch_id: Mapped[str] = mapped_column(String(36), nullable=False, default=lambda: str(uuid.uuid4()))
# 上传边界 Submission(阶段 1);与 OT 发送决策 submission 分离。
order_submission_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_submissions.id'),
nullable=True,
)
# eml = 一份邮件裁决边界;direct_pdf = 一份直接 PDF;其它类型暂 NULL。
source_type: Mapped[Optional[str]] = mapped_column(String(32), 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)
# co8e9f0a1b2c 已 DROP shipping_batches 与 consumed_batch_id;消费绑定仅保留任务侧。
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.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 ShippingOrderDocument(Base):
"""
发货通知文档单元:邮件正文或单个附件(阶段二)。
核心逻辑:Intake 解析后按 attachment_key 幂等 upsert;附件型 Document 可挂 derived FileAsset。
"""
__tablename__ = 'shipping_order_documents'
__table_args__ = (
UniqueConstraint(
'intake_id',
'attachment_key',
name='uq_shipping_order_documents_intake_attachment_key',
),
# 支撑 Candidate (primary_document_id, intake_id) 复合外键
UniqueConstraint('id', 'intake_id', name='uq_shipping_order_documents_id_intake'),
Index('ix_shipping_order_documents_intake_id', 'intake_id'),
Index('ix_shipping_order_documents_asset_id', 'asset_id'),
Index('ix_shipping_order_documents_content_hash', 'content_hash'),
Index('ix_shipping_order_documents_parse_status', 'parse_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
intake_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_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_order_document_layout_versions.id',
name='fk_shipping_order_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 ShippingOrderCandidate(Base):
"""
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
核心逻辑:一个 Document 可抽取多个 Candidate;candidate_key 保证重提取幂等,
重复检测、自动建单与待补字段状态均落在 Candidate 级。
"""
__tablename__ = 'shipping_order_candidates'
__table_args__ = (
CheckConstraint(
"candidate_status IN ('provisional', 'accepted', 'rejected', 'expired')",
name='ck_shipping_order_candidates_status',
),
CheckConstraint(
"acceptance_mode IS NULL OR acceptance_mode IN ('automatic', 'manual', 'legacy')",
name='ck_shipping_order_candidates_acceptance_mode',
),
UniqueConstraint('candidate_no', name='uq_shipping_order_candidates_candidate_no'),
UniqueConstraint(
'intake_id', 'candidate_key', 'order_extraction_run_id',
name='uq_shipping_order_candidates_intake_key_run',
),
# 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接
ForeignKeyConstraint(
['primary_document_id', 'intake_id'],
['shipping_order_documents.id', 'shipping_order_documents.intake_id'],
name='fk_shipping_order_candidates_document_intake',
),
Index('ix_shipping_order_candidates_intake_id', 'intake_id'),
Index('ix_shipping_order_candidates_primary_document_id', 'primary_document_id'),
Index('ix_shipping_order_candidates_po_number', 'po_number'),
Index(
'ix_shipping_order_candidates_user_fingerprint',
'business_fingerprint',
),
Index('ix_shipping_order_candidates_duplicate_status', 'duplicate_status'),
Index('ix_shipping_order_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_order_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_processing_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_notices.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)