feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议

This commit is contained in:
hugo committed 2026-07-18 11:41:02 +08:00
1 parent 46eb63f5bb
commit e9bdd81f1a
320 files changed
+28361 -10487

No files matched your search

+59 -3
View File
@@ -20,7 +20,6 @@ from app.models.file_asset import FileAsset
from app.models.shipping import (
ShippingBatch,
ShippingInventoryFile,
ShippingInventoryMapping,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
@@ -29,15 +28,45 @@ from app.models.shipping import (
ShippingTaskInventoryLink,
)
from app.models.shipping_task_line import ShippingTaskFieldConflict, ShippingTaskLine
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
from app.models.shipping_order_schema import (
ShippingOrderExtraction,
ShippingOrderSchemaAuditEvent,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
)
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
from app.models.shipping_inventory_config import (
ShippingInventoryField,
ShippingInventoryExternalMapping,
ShippingInventoryConfigurationTestRun,
ShippingInventoryParsingProfile,
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingInventoryRoutingRuleVersion,
ShippingInventorySource,
ShippingInventoryStructureAnalysis,
ShippingRpaProfile,
)
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
from app.models.shipping_customer import (
ShippingBusinessSequence,
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerMerge,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
)
from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow
from app.models.shipping_customer_resolution import ShippingCustomerShadowResolution
from app.models.shipping_customer_resolution import ShippingCustomerShadowMatch, ShippingCustomerShadowResolution
from app.models.training import TrainingRecord
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
@@ -78,18 +107,45 @@ __all__ = [
'ShippingTask',
'ShippingTaskLine',
'ShippingTaskFieldConflict',
'ShippingOrderSchema',
'ShippingOrderSchemaVersion',
'ShippingOrderSchemaAuditEvent',
'ShippingOrderField',
'ShippingOrderExtraction',
'ShippingOrderLine',
'ShippingOrderFieldObservation',
'ShippingOrderFieldDecision',
'ShippingOrderFieldValue',
'ShippingOrderCustomerMatch',
'ShippingCustomer',
'ShippingCustomerIdentifier',
'ShippingCustomerExternalRef',
'ShippingCustomerLifecycleEvent',
'ShippingCustomerMerge',
'ShippingCustomerSite',
'ShippingCustomerSiteIdentifier',
'ShippingCustomerImportBatch',
'ShippingCustomerImportRow',
'ShippingCase',
'ShippingBusinessSequence',
'ShippingCustomerShadowResolution',
'ShippingCustomerShadowMatch',
'ShippingTaskEvent',
'ShippingInventoryFile',
'ShippingTaskInventoryLink',
'ShippingInventoryMapping',
'ShippingRpaProfile',
'ShippingInventorySource',
'ShippingInventoryField',
'ShippingInventoryStructureAnalysis',
'ShippingInventoryRoutingRule',
'ShippingInventoryRoutingRuleCondition',
'ShippingInventoryRoutingRuleVersion',
'ShippingInventoryExternalMapping',
'ShippingInventoryConfigurationTestRun',
'ShippingInventoryParsingProfile',
'ShippingTemporaryInventorySession',
'ShippingExcelTemplate',
'ShippingExportArtifact',
'ShippingNoticeIntake',
'ShippingNoticeDocument',
'ShippingNoticeCandidate',
+27 -35
View File
@@ -67,7 +67,6 @@ class ShippingBatch(Base):
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',
@@ -85,7 +84,6 @@ class ShippingTask(Base):
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_site_id', 'inventory_site_id'),
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'),
@@ -160,7 +158,6 @@ class ShippingTask(Base):
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_site_id: Mapped[Optional[str]] = mapped_column(String(64), 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)
@@ -186,6 +183,15 @@ class ShippingTask(Base):
server_default=text("'pending'"),
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,
)
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -215,7 +221,6 @@ class ShippingTask(Base):
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',
@@ -273,25 +278,38 @@ class ShippingInventoryFile(Base):
'exported_at',
),
Index(
'ix_shipping_inventory_files_source_site_wh',
'ix_shipping_inventory_files_source_warehouse',
'source_code',
'site_id',
'warehouse_id',
),
Index(
'uq_shipping_inventory_files_rpa_identity_ready',
'rpa_run_no',
'source_code',
'site_id',
'warehouse_id',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id 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 site_id IS NOT NULL AND warehouse_id 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"
),
),
)
@@ -311,7 +329,6 @@ class ShippingInventoryFile(Base):
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)
site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=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)
@@ -344,7 +361,6 @@ class ShippingTaskInventoryLink(Base):
'ix_shipping_task_inventory_links_task_source',
'task_id',
'matched_source_code',
'matched_site_id',
),
)
@@ -357,7 +373,6 @@ class ShippingTaskInventoryLink(Base):
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)
matched_site_id: 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)
@@ -442,8 +457,6 @@ class ShippingNoticeIntake(Base):
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):
"""
发货通知文档单元:邮件正文或单个附件(阶段二)。
@@ -493,8 +506,6 @@ class ShippingNoticeDocument(Base):
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)
class ShippingNoticeCandidate(Base):
"""
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
@@ -572,22 +583,3 @@ class ShippingNoticeCandidate(Base):
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class ShippingInventoryMapping(Base):
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
__tablename__ = 'shipping_inventory_mappings'
__table_args__ = (
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_code: Mapped[str] = mapped_column(String(64), nullable=False)
header_hash: Mapped[str] = mapped_column(String(64), nullable=False)
headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
last_used_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, index=True)
+122 -2
View File
@@ -11,7 +11,7 @@ from __future__ import annotations
from datetime import date, datetime
from typing import List, Optional
from sqlalchemy import Boolean, CheckConstraint, Date, ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
from sqlalchemy import Boolean, CheckConstraint, Date, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
@@ -39,6 +39,11 @@ class ShippingCustomer(Base):
standard_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
short_code: Mapped[str] = mapped_column(String(6), nullable=False, unique=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
merged_into_customer_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_customers.id'),
nullable=True,
index=True,
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
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)
@@ -51,6 +56,21 @@ class ShippingCustomer(Base):
cascade='all, delete-orphan',
)
cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer')
merged_into_customer: Mapped[Optional['ShippingCustomer']] = relationship(
'ShippingCustomer',
remote_side='ShippingCustomer.id',
back_populates='merged_source_customers',
)
external_refs: Mapped[List['ShippingCustomerExternalRef']] = relationship(
'ShippingCustomerExternalRef', back_populates='customer', cascade='all, delete-orphan',
)
sites: Mapped[List['ShippingCustomerSite']] = relationship(
'ShippingCustomerSite', back_populates='customer', cascade='all, delete-orphan',
)
merged_source_customers: Mapped[List['ShippingCustomer']] = relationship(
'ShippingCustomer',
back_populates='merged_into_customer',
)
class ShippingCustomerIdentifier(Base):
@@ -108,7 +128,65 @@ class ShippingCustomerExternalRef(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer')
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='external_refs')
class ShippingCustomerSite(Base):
"""标准客户下的送货/收货站点;Ship-to 匹配指向站点而不是复制一条账款客户。"""
__tablename__ = 'shipping_customer_sites'
__table_args__ = (
UniqueConstraint('customer_id', 'site_code', name='uq_shipping_customer_sites_customer_code'),
Index('ix_shipping_customer_sites_status_name', 'status', 'site_name'),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
site_name: Mapped[str] = mapped_column(String(200), nullable=False)
site_code: Mapped[str] = mapped_column(String(64), nullable=False)
address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
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(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='sites')
identifiers: Mapped[List['ShippingCustomerSiteIdentifier']] = relationship(
'ShippingCustomerSiteIdentifier', back_populates='site', cascade='all, delete-orphan',
)
class ShippingCustomerSiteIdentifier(Base):
"""送货站点的名称、外部站点编码或地址别名,用于 Ship-to 确定性匹配。"""
__tablename__ = 'shipping_customer_site_identifiers'
__table_args__ = (
UniqueConstraint(
'site_id', 'identifier_type', 'source_system', 'normalized_value',
name='uq_shipping_customer_site_identifiers_value',
),
Index(
'ix_shipping_customer_site_identifiers_lookup',
'identifier_type', 'source_system', 'normalized_value', 'status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
site_id: Mapped[int] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=False, index=True)
identifier_type: Mapped[str] = mapped_column(String(32), nullable=False)
source_system: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
raw_value: Mapped[str] = mapped_column(String(500), nullable=False)
normalized_value: Mapped[str] = mapped_column(String(500), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='approved', server_default='approved')
remark: 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)
site: Mapped['ShippingCustomerSite'] = relationship('ShippingCustomerSite', back_populates='identifiers')
class ShippingCase(Base):
@@ -174,3 +252,45 @@ class ShippingBusinessSequence(Base):
current_value: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class ShippingCustomerLifecycleEvent(Base):
"""客户生命周期审计;只保存客户快照,不能反向阻断受控删除。"""
__tablename__ = 'shipping_customer_lifecycle_events'
__table_args__ = (
Index('ix_shipping_customer_lifecycle_events_customer_created', 'customer_id_snapshot', 'created_at'),
Index('ix_shipping_customer_lifecycle_events_event_created', 'event_type', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
customer_id_snapshot: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
detail_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
class ShippingCustomerMerge(Base):
"""客户身份归并审计;仅存快照,不给历史审计链增加客户外键依赖。"""
__tablename__ = 'shipping_customer_merges'
__table_args__ = (
UniqueConstraint('source_customer_id_snapshot', name='uq_shipping_customer_merges_source_snapshot'),
Index('ix_shipping_customer_merges_target_created', 'target_customer_id_snapshot', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_customer_id_snapshot: Mapped[int] = mapped_column(Integer, nullable=False)
source_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
source_short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
target_customer_id_snapshot: Mapped[int] = mapped_column(Integer, nullable=False)
target_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
target_short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
reason: Mapped[str] = mapped_column(Text, nullable=False)
detail_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -9,10 +9,10 @@ backend/app/models/shipping_customer_resolution.py
from __future__ import annotations
from datetime import datetime
from typing import Optional
from typing import List, Optional
from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, JSON, String
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
@@ -52,3 +52,40 @@ class ShippingCustomerShadowResolution(Base):
labeled_at: Mapped[Optional[datetime]] = mapped_column(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)
matches: Mapped[List['ShippingCustomerShadowMatch']] = relationship(
'ShippingCustomerShadowMatch',
back_populates='resolution',
cascade='all, delete-orphan',
order_by='ShippingCustomerShadowMatch.match_rank',
)
class ShippingCustomerShadowMatch(Base):
"""影子识别候选的规范化关联,供删除资格与合并可靠反查。"""
__tablename__ = 'shipping_customer_shadow_matches'
__table_args__ = (
UniqueConstraint('resolution_id', 'customer_id', name='uq_shipping_customer_shadow_matches_resolution_customer'),
Index('ix_shipping_customer_shadow_matches_customer', 'customer_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
resolution_id: Mapped[int] = mapped_column(
ForeignKey('shipping_customer_shadow_resolutions.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False)
match_rank: Mapped[int] = mapped_column(Integer, nullable=False)
score: Mapped[float] = mapped_column(Float, nullable=False)
standard_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
reasons_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
resolution: Mapped['ShippingCustomerShadowResolution'] = relationship(
'ShippingCustomerShadowResolution',
back_populates='matches',
)
@@ -0,0 +1,77 @@
"""
models/shipping_excel_template.py
用途:定义版本化发货 Excel 模板及不可变任务导出产物。
依赖:models.base.Base、库存源、订单 Schema、发货任务与库存快照模型。
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingExcelTemplate(Base):
"""可跨库存源复用的发货 Excel 模板版本。"""
__tablename__ = 'shipping_excel_templates'
__table_args__ = (
UniqueConstraint('template_code', 'version', name='uq_shipping_excel_templates_code_version'),
Index('ix_shipping_excel_templates_status', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
template_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='minio', server_default='minio')
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(512), nullable=False)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
definition_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template')
class ShippingExportArtifact(Base):
"""一次任务导出的不可变产物及生成输入快照。"""
__tablename__ = 'shipping_export_artifacts'
__table_args__ = (
UniqueConstraint('artifact_no', name='uq_shipping_export_artifacts_no'),
Index('ix_shipping_export_artifacts_task_created', 'task_id', 'created_at'),
Index('ix_shipping_export_artifacts_batch_created', 'batch_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
artifact_no: Mapped[str] = mapped_column(String(64), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False, index=True)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='ready', server_default='ready')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
template: Mapped[ShippingExcelTemplate] = relationship()
task: Mapped['ShippingTask'] = relationship()
@@ -0,0 +1,317 @@
"""
models/shipping_inventory_config.py
用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置,
外部系统映射仅供后端内部复用,不承载调拨决策。
"""
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, relationship
from app.models.base import Base
class ShippingInventoryField(Base):
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
__tablename__ = 'shipping_inventory_fields'
__table_args__ = (
UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'),
UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'),
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'),
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'),
CheckConstraint(
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
name='ck_shipping_inventory_fields_usage_type',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
# Internal stable code supports runtime contracts; it is deliberately not exposed in the business UI.
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
value_type: Mapped[str] = mapped_column(String(16), nullable=False, default='text', server_default='text')
usage_type: Mapped[str] = mapped_column(String(32), nullable=False, default='general', server_default='general')
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=100, server_default='100')
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: 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)
class ShippingRpaProfile(Base):
"""货代库存登录连接配置;凭据字段始终保存密文。"""
__tablename__ = 'shipping_rpa_profiles'
__table_args__ = (
UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
login_url: Mapped[str] = mapped_column(String(500), nullable=False)
username_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
password_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
login_config_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
credential_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: 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)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile')
class ShippingInventorySource(Base):
"""库存业务来源;固定仓或库存行动态解析 Warehouse。"""
__tablename__ = 'shipping_inventory_sources'
__table_args__ = (
UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'),
CheckConstraint(
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)",
name='ck_shipping_inventory_sources_warehouse_mode',
),
CheckConstraint(
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)",
name='ck_shipping_inventory_sources_enabled_bindings',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True)
parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True)
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。
report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False)
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
match_aliases_json: Mapped[list[str]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: 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)
rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources')
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources')
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship(
back_populates='inventory_source', cascade='all, delete-orphan'
)
class ShippingInventoryParsingProfile(Base):
"""可跨库存源复用的库存文件结构与订单匹配配置。"""
__tablename__ = 'shipping_inventory_parsing_profiles'
__table_args__ = (
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
file_format: Mapped[str] = mapped_column(String(16), nullable=False, default='xlsx', server_default='xlsx')
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
structure_definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
class ShippingInventoryStructureAnalysis(Base):
"""库存文件结构分析记录;保存受控样例与建议,不承载正式库存快照。"""
__tablename__ = 'shipping_inventory_structure_analyses'
__table_args__ = (
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
Index('ix_inv_structure_analysis_created', 'created_at'),
Index('ix_inv_structure_analysis_exact_fp', 'exact_structure_fingerprint'),
Index('ix_inv_structure_analysis_compat_fp', 'compatibility_fingerprint'),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='sample_upload', server_default='sample_upload')
source_file_name: Mapped[str] = mapped_column(String(255), nullable=False)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_format: Mapped[str] = mapped_column(String(16), nullable=False)
analysis_status: Mapped[str] = mapped_column(String(32), nullable=False, default='ready', server_default='ready')
structure_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
suggested_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
validation_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
warning_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
match_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryConfigurationTestRun(Base):
"""库存站点配置测试的异步 RPA 运行;测试文件不能进入生产库存池。"""
__tablename__ = 'shipping_inventory_configuration_test_runs'
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
class ShippingInventoryRoutingRule(Base):
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
__tablename__ = 'shipping_inventory_routing_rules'
__table_args__ = (
UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'),
CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'),
CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
rule_code: Mapped[str] = mapped_column(String(64), nullable=False)
rule_name: Mapped[str] = mapped_column(String(128), nullable=False)
scope: Mapped[str] = mapped_column(String(16), nullable=False)
priority: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False)
match_mode: Mapped[str] = mapped_column(String(16), default='all', server_default=text("'all'"), nullable=False)
status: Mapped[str] = mapped_column(String(16), default='draft', server_default=text("'draft'"), nullable=False)
action_type: Mapped[str] = mapped_column(String(64), nullable=False)
action_payload_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: 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)
conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship(
back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence'
)
class ShippingInventoryRoutingRuleCondition(Base):
"""库存源路由条件;订单字段引用稳定 field_id,系统事实使用受控 key。"""
__tablename__ = 'shipping_inventory_routing_rule_conditions'
__table_args__ = (
UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'),
CheckConstraint(
"(source_kind = 'order_field' AND order_field_id IS NOT NULL AND system_fact_key IS NULL) OR "
"(source_kind = 'system_fact' AND order_field_id IS NULL AND system_fact_key IS NOT NULL)",
name='ck_inventory_routing_condition_source',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field')
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
system_fact_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
operator: Mapped[str] = mapped_column(String(32), nullable=False)
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
sequence: Mapped[int] = mapped_column(Integer, nullable=False)
rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions')
class ShippingInventoryRoutingRuleVersion(Base):
"""已发布路由规则的不可变定义快照,供任务审计回放使用。"""
__tablename__ = 'shipping_inventory_routing_rule_versions'
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),)
id: Mapped[int] = mapped_column(primary_key=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
version: Mapped[int] = mapped_column(Integer, nullable=False)
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryExternalMapping(Base):
"""货代库存身份到外部系统仓库的单向映射;不承载调拨规则。"""
__tablename__ = 'shipping_inventory_external_mappings'
__table_args__ = (
Index(
'uq_shipping_inventory_external_mappings_source_default_enabled',
'inventory_source_id',
unique=True,
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
),
Index(
'uq_shipping_inventory_external_mappings_source_warehouse_enabled',
'inventory_source_id',
'freight_warehouse_id',
unique=True,
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'),
sqlite_where=text('freight_warehouse_id IS NOT NULL AND enabled = 1'),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_site_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False)
external_warehouse_name: Mapped[str] = mapped_column(String(128), nullable=False)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: 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)
inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings')
@@ -0,0 +1,59 @@
"""
backend/app/models/shipping_order_customer_match.py
用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。
依赖:ShippingOrderExtraction、ShippingCustomer、users。
逻辑:动态订单字段保留原文客户名称;本表按角色保存候选、确认客户及名称/简称快照,供复核和导出读取。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderCustomerMatch(Base):
"""一次订单解析中的角色化客户匹配;每个解析记录的每种客户角色仅保留一条当前结果。"""
__tablename__ = 'shipping_order_customer_matches'
__table_args__ = (
UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'),
CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'),
CheckConstraint(
"status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')",
name='ck_shipping_order_customer_matches_status',
),
Index('ix_shipping_order_customer_matches_customer_role', 'customer_id', 'role'),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False, index=True,
)
role: Mapped[str] = mapped_column(String(16), nullable=False)
raw_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched')
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=True)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_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,
)
extraction = relationship('ShippingOrderExtraction')
customer = relationship('ShippingCustomer')
site = relationship('ShippingCustomerSite')
+311
View File
@@ -0,0 +1,311 @@
"""
backend/app/models/shipping_order_schema.py
用途:定义货代订单唯一 Schema、不可变版本、配置审计及动态订单解析结果。
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、users。
逻辑:草稿和发布版本统一保存完整 JSON 定义;写操作追加审计事件;解析链锁定发布版本并保存裁决结果。
"""
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())
class ShippingOrderSchema(Base):
"""全局唯一货代订单 Schema;当前业务只允许一个逻辑 Schema。"""
__tablename__ = 'shipping_order_schemas'
__table_args__ = (
CheckConstraint("schema_code = 'SHIPPING_ORDER'", name='ck_shipping_order_schemas_single_code'),
)
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)
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)
fields: Mapped[list['ShippingOrderField']] = relationship(
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderField.field_code'
)
versions: Mapped[list['ShippingOrderSchemaVersion']] = relationship(
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderSchemaVersion.version'
)
class ShippingOrderField(Base):
"""订单字段稳定身份;下游使用 field_id,版本快照冻结当时的名称和规则。"""
__tablename__ = 'shipping_order_fields'
__table_args__ = (
UniqueConstraint('schema_id', 'field_code', name='uq_shipping_order_fields_schema_code'),
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'),
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'),
Index('ix_shipping_order_fields_schema_scope', 'schema_id', 'scope'),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
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)
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'))
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: Mapped['ShippingOrderSchema'] = relationship(back_populates='fields')
class ShippingOrderSchemaVersion(Base):
"""订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。"""
__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_deleted')",
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[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
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)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_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(ForeignKey('shipping_order_fields.id'), nullable=False)
source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_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)
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(ForeignKey('shipping_order_fields.id'), nullable=False)
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(ForeignKey('shipping_order_fields.id'), nullable=False)
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')
@@ -0,0 +1,51 @@
"""
models/shipping_temporary_inventory.py
用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续批次使用过程。
依赖:Base、FileAsset、ChatSession、ShippingBatch/ShippingTask、库存结构分析记录。
逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
本表不代表库存站点配置,也不代表生产库存快照。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingTemporaryInventorySession(Base):
"""对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。"""
__tablename__ = 'shipping_temporary_inventory_sessions'
__table_args__ = (
UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'),
Index('ix_shipping_temp_inventory_user_created', 'user_id', 'created_at'),
Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'),
Index('ix_shipping_temp_inventory_asset', 'asset_id'),
Index('ix_shipping_temp_inventory_status_expires', 'status', 'expires_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
session_no: Mapped[str] = mapped_column(String(64), nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True)
analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True, index=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True, index=True)
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
file_classification_status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
classification_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
candidate_source_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False, index=True)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)