Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	backend/app/services/knowledge_cleaning/dify_sync_service.py
#	backend/app/services/knowledge_cleaning/settings_service.py
#	backend/tests/test_dify_sync_process_rule.py
#	docker-compose.yml
#	docs/funclist.md
#	frontend/package-lock.json
#	frontend/src/config.ts
#	frontend/src/features/admin/components/AdminNav.vue
#	frontend/src/features/admin/constants/modules.ts
#	frontend/src/features/admin/stores/admin-nav.store.ts
#	frontend/src/features/chat/components/messages/ChatMessageBubble.vue
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/auth.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/auth.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/auth.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/auth.json
#	frontend/src/locales/zh-TW/errors.json
This commit is contained in:
HTEWJ\26070045 committed 2026-09-11 14:55:20 +08:00
commit ca9c174f29
2050 files changed
+511839 -42320

No files matched your search

+360 -16
View File
@@ -13,26 +13,228 @@ from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlL
from app.models.department import Department
from app.models.linked_service import LinkedService
from app.models.job import Job
from app.jobs.types import JobType # noqa: F401 — 与 Job 配合读库,聚合在 models 一处导入
from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob
from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord
from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
from app.models.settings import AppSetting
from app.models.file_asset import FileAsset
from app.models.contract import ContractReview, ContractRiskRule, ContractTemplate
from app.models.contract_payment import (
ContractPaymentAlert,
ContractPaymentAttachment,
ContractPaymentContract,
ContractPaymentEvent,
ContractPaymentNode,
ContractPaymentSyncState,
ContractPaymentVendorRequest,
)
from app.models.shipping import (
ShippingBatch,
ShippingInventoryFile,
ShippingInventoryMapping,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingTaskEvent,
ShippingTaskPurgeAudit,
ShippingTaskInventoryLink,
)
from app.models.training import TrainingRecord
from app.models.shipping_order_submission import ShippingOrderSubmission
from app.models.shipping_order_task import ShippingOrderTask
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
from app.models.shipping_notice_line import ShippingNoticeLine
from app.models.shipping_order_document_version import ShippingOrderDocumentVersion
from app.models.shipping_task_line import ShippingTaskFieldConflict
# [BE-14] 已移除 ShippingTask=ShippingNotice 兼容别名;正式发货通知统一用 ShippingNotice,
# 建单前 OT 用 ShippingOrderTask,禁止再引入 ShippingTask 混淆二者。
from app.models.shipping_context_provider import ShippingContextProvider, ShippingContextProviderOption
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
from app.models.shipping_fulfillment import (
ShippingExportArtifactLine,
ShippingInventoryVerification,
ShippingInventoryVerificationLine,
ShippingReservation,
ShippingUploadAttempt,
)
from app.models.shipping_process_gate import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
)
# 短期兼容别名:历史代码仍可 import ShippingNotice*;新代码优先用 ShippingOrder*。
ShippingNoticeIntake = ShippingOrderIntake
ShippingNoticeDocument = ShippingOrderDocument
ShippingNoticeCandidate = ShippingOrderCandidate
from app.models.shipping_order_schema import (
ShippingFieldAsset,
ShippingOrderExtraction,
ShippingOrderSchemaAuditEvent,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingSchemaFamily,
)
from app.models.shipping_order_snapshot import (
ShippingOrderReviewEvent,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
)
from app.models.shipping_order_review import (
ShippingOrderReviewCase,
ShippingOrderReviewStream,
ShippingOrderReviewDraft,
ShippingOrderReviewCaseEvent,
ShippingOrderReviewConfirmedRevision,
)
from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
from app.models.shipping_order_extraction_run import (
ShippingOrderExtractionDiagnosticAudit,
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionSubmission,
ShippingOrderProcessingPlan,
ShippingOrderProcessingRun,
ShippingOrderProcessingRunIntake,
ShippingOrderProcessingUnit,
ShippingOrderRouteDecision,
)
# 短期兼容别名:历史代码仍可 import ShippingOrderExtractionRun*;新代码优先用 Processing*。
ShippingOrderExtractionRun = ShippingOrderProcessingRun
ShippingOrderExtractionRunIntake = ShippingOrderProcessingRunIntake
ShippingOrderExtractionPlan = ShippingOrderProcessingPlan
ShippingOrderExtractionUnit = ShippingOrderProcessingUnit
ShippingOrderExtractionRouteDecision = ShippingOrderRouteDecision
from app.models.shipping_audit_event import ShippingAuditEvent
from app.models.shipping_order_document_profile import (
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingOrderDocumentProfileDraftRevision,
ShippingOrderDocumentProfileEditLease,
ShippingOrderDocumentProfileSuggestionDecision,
ShippingOrderDocumentProfileValidationRun,
ShippingOrderDocumentProfilePublishCheckReport,
ShippingOrderDocumentProfileSample,
)
from app.models.shipping_document_profile_quality import (
ShippingDocumentProfileTestRun,
ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
)
from app.models.shipping_document_profile_auto_freeze import ShippingDocumentProfileAutoFreezeQualification
from app.models.shipping_order_candidate_qualification import ShippingOrderCandidateQualification
from app.models.shipping_freight_cancellation import ShippingFreightCancellation
from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
from app.models.shipping_eml_preview_snapshot import ShippingEmlPreviewSnapshot
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
from app.models.shipping_inventory_config import (
ShippingInventoryField,
ShippingInventoryExternalMapping,
ShippingInventoryConfigurationTestRun,
ShippingInventoryValidationBatch,
ShippingInventorySourceParsingBindingAudit,
ShippingInventoryParsingProfile,
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingInventoryRoutingRuleVersion,
ShippingInventorySource,
ShippingInventoryStructureAnalysis,
ShippingRpaProfile,
)
from app.models.shipping_receipt_report import (
ShippingReceiptNotificationDelivery,
ShippingReceiptReportConfig,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
)
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
from app.models.shipping_customer import (
ShippingBusinessSequence,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerMerge,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
)
from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow
from app.models.shipping_customer_resolution import ShippingCustomerShadowMatch, ShippingCustomerShadowResolution
from app.models.shipping_order_extraction_quality import (
ShippingOrderExtractionQualityBatch,
ShippingOrderExtractionQualityLabel,
)
from app.models.shipping_identity_rule import (
ShippingIdentityDefinition,
ShippingIdentityEvidence,
ShippingIdentityRuleAuditEvent,
ShippingIdentityRuleSet,
)
from app.models.shipping_inventory_candidates import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
)
from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt
from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan
from app.models.shipping_inventory_preparation import (
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
)
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
from app.models.training import (
LeanTrainingCompletion,
LeanTrainingReminder,
LeanTrainingVideoPushLog,
LeanTrainingWeeklyTask,
TrainingConfig,
TrainingConfigResource,
TrainingRecord,
)
from app.models.in_transit_transfer import (
TransferArchive,
TransferAttempt,
TransferAuditEvent,
TransferInvoiceItem,
TransferPrecheck,
TransferRun,
TransferSourceJob,
)
from app.models.integration_connector import (
IntegrationBinding,
IntegrationCall,
IntegrationClientInstance,
IntegrationCredentialReference,
IntegrationInterfaceDefinition,
)
from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckNotification,
VoucherCheckProfile,
VoucherCheckRun,
VoucherCheckSubject,
)
from app.models.contract_payment import (
ContractPaymentAlert,
ContractPaymentAlertBatch,
ContractPaymentAttachment,
ContractPaymentContract,
ContractPaymentEvent,
ContractPaymentNode,
ContractPaymentSyncState,
ContractPaymentVendorRequest,
)
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
__all__ = [
@@ -63,30 +265,172 @@ __all__ = [
'KbDocumentVersion',
'KbJob',
'Job',
'JobType',
'KbDifySyncRecord',
'WecomCallbackAudit',
'ScheduleTask',
'ScheduleTaskConfig',
'ScheduleRun',
'ShippingBatch',
'ShippingTask',
'ShippingNotice',
'ShippingTaskFieldConflict',
'ShippingContextProvider',
'ShippingContextProviderOption',
'ShippingOrderSchema',
'ShippingSchemaFamily',
'ShippingOrderSchemaVersion',
'ShippingOrderSchemaAuditEvent',
'ShippingOrderField',
'ShippingFieldAsset',
'ShippingOrderExtraction',
'ShippingOrderLine',
'ShippingOrderFieldObservation',
'ShippingOrderFieldDecision',
'ShippingOrderFieldValue',
'ShippingOrderSnapshot',
'ShippingOrderSnapshotLine',
'ShippingOrderReviewEvent',
'ShippingOrderReviewCase',
'ShippingOrderReviewStream',
'ShippingOrderReviewDraft',
'ShippingOrderReviewCaseEvent',
'ShippingOrderReviewConfirmedRevision',
'ShippingOrderReviewLineDecision',
'ShippingOrderReviewWaveLine',
'ShippingOrderReviewWaveIdempotency',
'ShippingNoticeLineInventoryMatch',
'ShippingOrderReviewSuggestion',
'ShippingOrderProcessingRun',
'ShippingOrderProcessingRunIntake',
'ShippingOrderProcessingPlan',
'ShippingOrderProcessingUnit',
'ShippingOrderRouteDecision',
'ShippingOrderExtractionRun',
'ShippingOrderExtractionRunIntake',
'ShippingOrderExtractionSubmission',
'ShippingOrderExtractionPlan',
'ShippingOrderExtractionRouteDecision',
'ShippingOrderExtractionUnit',
'ShippingOrderExtractionProgressEvent',
'ShippingOrderExtractionDiagnosticAudit',
'ShippingAuditEvent',
'ShippingOrderExtractionQualityBatch',
'ShippingOrderExtractionQualityLabel',
'ShippingOrderDocumentProfile',
'ShippingOrderDocumentProfileAudit',
'ShippingOrderDocumentProfileSample',
'ShippingDocumentProfileTestSuite',
'ShippingDocumentProfileTestSample',
'ShippingDocumentProfileTestRun',
'ShippingDocumentProfileAutoFreezeQualification',
'ShippingOrderCandidateQualification',
'ShippingFreightCancellation',
'ShippingDocumentLayoutVersion',
'ShippingEmlPreviewSnapshot',
'ShippingXfaStructureAnalysis',
'ShippingXfaAuditSnapshot',
'ShippingCustomer',
'ShippingCustomerIdentifier',
'ShippingCustomerExternalRef',
'ShippingCustomerLifecycleEvent',
'ShippingCustomerMerge',
'ShippingCustomerSite',
'ShippingCustomerSiteIdentifier',
'ShippingCustomerImportBatch',
'ShippingCustomerImportRow',
'ShippingBusinessSequence',
'ShippingCustomerShadowResolution',
'ShippingCustomerShadowMatch',
'ShippingIdentityDefinition',
'ShippingIdentityEvidence',
'ShippingIdentityRuleSet',
'ShippingIdentityRuleAuditEvent',
'ShippingTaskEvent',
'ShippingTaskPurgeAudit',
'ShippingInventoryFile',
'ShippingTaskInventoryLink',
'ShippingInventoryMapping',
'ShippingNoticeIntake',
'ShippingNoticeDocument',
'ShippingNoticeCandidate',
'ShippingRpaProfile',
'ShippingInventorySource',
'ShippingReceiptReportConfig',
'ShippingReceiptRpaUnitRun',
'ShippingReceiptReportFile',
'ShippingReceiptNotificationDelivery',
'ShippingInventoryField',
'ShippingInventoryStructureAnalysis',
'ShippingInventoryRoutingRule',
'ShippingInventoryRoutingRuleCondition',
'ShippingInventoryRoutingRuleVersion',
'ShippingInventoryExternalMapping',
'ShippingInventoryConfigurationTestRun',
'ShippingInventoryValidationBatch',
'ShippingInventorySourceParsingBindingAudit',
'ShippingInventoryParsingProfile',
'ShippingTemporaryInventorySession',
'ShippingExcelTemplate',
'ShippingExportArtifact',
'ShippingReservation',
'ShippingInventoryVerification',
'ShippingInventoryVerificationLine',
'ShippingExportArtifactLine',
'ShippingUploadAttempt',
'ShippingProcessExecution',
'ShippingProcessGate',
'ShippingProcessGateAttempt',
'ShippingOrderIntake',
'ShippingOrderDocument',
'ShippingOrderCandidate',
'ShippingNoticeIntake', # 兼容别名
'ShippingNoticeDocument', # 兼容别名
'ShippingNoticeCandidate', # 兼容别名
'ShippingOrderSubmission',
'ShippingOrderTask',
'ShippingOrderCandidateEvidence',
'ShippingNoticeLine',
'ShippingOrderDocumentVersion',
'FileAsset',
'ContractTemplate',
'ContractReview',
'ContractRiskRule',
'ContractPaymentContract',
'ContractPaymentAttachment',
'ContractPaymentNode',
'ContractPaymentEvent',
'ContractPaymentVendorRequest',
'ContractPaymentAlert',
'AgentGuide',
'AgentDirectoryMember',
'TrainingRecord',
'TrainingConfig',
'TrainingConfigResource',
'MaintenanceDevice',
'MaintenanceRecord',
'MaintenanceAuditLog',
'VoucherCheckInvoiceState',
'VoucherCheckRunItem',
'ShippingInventoryCandidateSet',
'ShippingInventoryCandidateSource',
'ShippingInventoryCandidateLine',
'ShippingTaskInventoryRpaAttempt',
'VoucherCheckProfile',
'VoucherCheckRun',
'VoucherCheckSubject',
'VoucherCheckFileResult',
'VoucherCheckNotification',
'ContractPaymentContract',
'ContractPaymentAttachment',
'ContractPaymentNode',
'ContractPaymentEvent',
'ContractPaymentVendorRequest',
'ContractPaymentAlert',
'ContractPaymentAlertBatch',
'ContractPaymentSyncState',
'TransferRun',
'TransferSourceJob',
'TransferPrecheck',
'TransferInvoiceItem',
'TransferAttempt',
'TransferAuditEvent',
'TransferArchive',
'IntegrationCredentialReference',
'IntegrationClientInstance',
'IntegrationInterfaceDefinition',
'IntegrationBinding',
'IntegrationCall',
]
+6 -1
View File
@@ -11,7 +11,7 @@ from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, Index, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base, user_agent_permissions
@@ -25,6 +25,11 @@ class Agent(Base):
"""
__tablename__ = 'agents'
__table_args__ = (
Index('uq_agents_one_active_shipping_notice', 'agent_code', unique=True,
postgresql_where=text("agent_code = 'shipping_notice' AND is_active = true"),
sqlite_where=text("agent_code = 'shipping_notice' AND is_active = 1")),
)
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
+1
View File
@@ -34,6 +34,7 @@ class QuickQuestion(Base):
"""
常用问题表
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
"""
__tablename__ = 'quick_questions'
+208
View File
@@ -0,0 +1,208 @@
"""
backend/app/models/contract_payment.py
用途:采购合同付款预警域模型,保存 OA 合同台账、附件来源、付款节点、履约事件和企微预警幂等记录。
依赖:models.base.Base、users、file_assets。
逻辑:同步服务写入合同、付款请款与事件,解析服务生成付款节点,预警服务按节点状态写入提醒记录并调用企业微信。
"""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import Date, DateTime, ForeignKey, Index, JSON, LargeBinary, Numeric, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ContractPaymentContract(Base):
"""OA 归档后的采购合同主记录。"""
__tablename__ = "contract_payment_contracts"
__table_args__ = (
UniqueConstraint("contract_no", name="uq_contract_payment_contracts_contract_no"),
Index("ix_contract_payment_contracts_purchase_order_no", "purchase_order_no"),
Index("ix_contract_payment_contracts_status", "status"),
)
id: Mapped[int] = mapped_column(primary_key=True)
# 合同附件解析前可能为空;OA 表单中的流程编号不再写入此字段。
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
supplier_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
applicant_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
total_amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 2), nullable=True)
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
effective_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
delivery_due_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
warranty_period_days: Mapped[Optional[int]] = mapped_column(nullable=True)
owner_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
oa_record_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
workflow_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
oa_archive_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(String(32), default="active", nullable=False)
parse_status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
plan_status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
source_payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
parse_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, 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 ContractPaymentAttachment(Base):
"""合同附件来源记录;OA 为主来源,文档管理系统为延迟补充。"""
__tablename__ = "contract_payment_attachments"
__table_args__ = (
UniqueConstraint("contract_id", "source", "source_key", name="uq_contract_payment_attachments_source"),
Index("ix_contract_payment_attachments_contract", "contract_id"),
)
id: Mapped[int] = mapped_column(primary_key=True)
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
source: Mapped[str] = mapped_column(String(32), nullable=False) # oa | dms
source_key: Mapped[str] = mapped_column(String(512), nullable=False)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
mime_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
file_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey("file_assets.id"), nullable=True)
dms_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
created_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
metadata_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(32), default="discovered", nullable=False)
created_record_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ContractPaymentNode(Base):
"""从合同条款编译出的付款节点。"""
__tablename__ = "contract_payment_nodes"
__table_args__ = (
UniqueConstraint("contract_id", "node_code", name="uq_contract_payment_nodes_code"),
Index("ix_contract_payment_nodes_due_date", "due_date", "status"),
)
id: Mapped[int] = mapped_column(primary_key=True)
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
node_code: Mapped[str] = mapped_column(String(64), nullable=False)
node_type: Mapped[str] = mapped_column(String(32), nullable=False)
amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 2), nullable=True)
percentage: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 4), nullable=True)
anchor_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
anchor_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
offset_days: Mapped[int] = mapped_column(default=0, nullable=False)
due_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
reminder_days: Mapped[int] = mapped_column(default=14, nullable=False)
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, 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 ContractPaymentEvent(Base):
"""OA 验收归档及可选履约事件。"""
__tablename__ = "contract_payment_events"
__table_args__ = (
UniqueConstraint("event_type", "source_event_id", name="uq_contract_payment_events_source"),
Index("ix_contract_payment_events_contract_type", "contract_id", "event_type"),
)
id: Mapped[int] = mapped_column(primary_key=True)
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
event_date: Mapped[date] = mapped_column(Date, nullable=False)
source_event_id: Mapped[str] = mapped_column(String(128), nullable=False)
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ContractPaymentVendorRequest(Base):
"""OA 厂商预付款请款作业的标准化记录,用于判定预付款与出货款是否还需提醒。"""
__tablename__ = "contract_payment_vendor_requests"
__table_args__ = (
UniqueConstraint("source_request_id", name="uq_contract_payment_vendor_requests_source"),
Index("ix_contract_payment_vendor_requests_contract_stage", "contract_id", "payment_stage"),
)
id: Mapped[int] = mapped_column(primary_key=True)
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
source_request_id: Mapped[str] = mapped_column(String(128), nullable=False)
request_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
payment_stage: Mapped[str] = mapped_column(String(32), nullable=False)
request_status: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
requested_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, 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 ContractPaymentAlert(Base):
"""付款预警发送幂等和审计记录。"""
__tablename__ = "contract_payment_alerts"
__table_args__ = (
UniqueConstraint("node_id", "trigger_key", "recipient_user_id", name="uq_contract_payment_alerts_trigger"),
Index("ix_contract_payment_alerts_status_scheduled", "status", "scheduled_at"),
)
id: Mapped[int] = mapped_column(primary_key=True)
contract_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_contracts.id", ondelete="CASCADE"), nullable=False)
node_id: Mapped[int] = mapped_column(ForeignKey("contract_payment_nodes.id", ondelete="CASCADE"), nullable=False)
trigger_key: Mapped[str] = mapped_column(String(64), nullable=False)
scheduled_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
recipient_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
alert_round: Mapped[int] = mapped_column(default=1, nullable=False)
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False, index=True)
message_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ContractPaymentAlertBatch(Base):
"""按周、按收件人归并的合同付款预警发送批次。"""
__tablename__ = "contract_payment_alert_batches"
__table_args__ = (
UniqueConstraint("week_key", "recipient_user_id", name="uq_contract_payment_alert_batches_week_recipient"),
Index("ix_contract_payment_alert_batches_status_created", "status", "created_at"),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
week_key: Mapped[str] = mapped_column(String(16), nullable=False)
recipient_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
wecom_trace_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ContractPaymentSyncState(Base):
"""合同付款域外部来源的 OA 增量同步断点(游标)。
用途:记录 OA 合同 HTTP 列表与验收 SQL 同步上次成功位置,供时间窗口增量拉取。
依赖:models.base.Base。
逻辑:同一 state_key 只保留一行;合同列表用 `oa-contract-archive`,验收归档用 `oa-acceptance-archive`。
成功同步后更新 last_successful_sync_at,下次以它减去 overlap 作为时间下限。
"""
__tablename__ = "contract_payment_sync_states"
id: Mapped[int] = mapped_column(primary_key=True)
state_key: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
last_successful_sync_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_archive_seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
synced_contract_count: Mapped[int] = mapped_column(default=0, nullable=False)
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)
+1 -1
View File
@@ -3,7 +3,7 @@ backend/app/models/file_asset.py
用途:平台级通用文件资产模型,承载私有 MinIO 存储元数据与生命周期。
依赖:models.base.Base。
逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 经 asset_id 引用上传根资产;
逻辑:由 file_assets.service 创建与更新;ShippingOrderIntake 经 asset_id 引用上传根资产;
EML 解析后的订单附件以 parent_asset_id 挂为 derived 子资产(阶段二);
派生资产对 (parent_asset_id, content_hash) 使用未删除行的部分唯一索引。
"""
+352
View File
@@ -0,0 +1,352 @@
"""models/in_transit_transfer.py
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Precheck、InvoiceItem、
Attempt、AuditEvent 与 Archive。
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
逻辑:Run 是异步真相源;InvoiceItem 按(precheck_id, invoice_no)唯一防止重复建单;
Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖;
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
"""
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,
event,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.errors import ValidationError
from app.models.base import Base
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
TRANSFER_ITEM_STATUSES = (
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
)
TRANSFER_RUN_STATUSES = (
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
'success', 'partial_failed', 'failed', 'cancelled',
)
TRANSFER_SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
)
TRANSFER_PRECHECK_STATUSES = (
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
'success', 'failed', 'cancelled', 'expired',
)
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'erp_query', 'erp_write')
TRANSFER_ATTEMPT_STATUSES = (
'queued', 'running', 'waiting_external', 'success', 'failed',
'result_unknown', 'superseded',
)
TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')
class TransferRun(Base):
"""一次调拨执行(或只读预检)的业务真相源。"""
__tablename__ = 'transfer_runs'
__table_args__ = (
UniqueConstraint('run_no', name='uq_transfer_runs_run_no'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_RUN_STATUSES)})",
name='ck_transfer_runs_status',
),
CheckConstraint(
"notification_status IN ('pending', 'success', 'failed')",
name='ck_transfer_runs_notification_status',
),
CheckConstraint(
"trigger_type IN ('manual', 'schedule')",
name='ck_transfer_runs_trigger_type',
),
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
Index('ix_transfer_runs_business_date', 'business_date'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
result_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
notification_status: Mapped[str] = mapped_column(
String(16), nullable=False, default='pending', server_default='pending',
)
notification_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
notification_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)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
source_jobs: Mapped[list['TransferSourceJob']] = relationship(
back_populates='run', cascade='all, delete-orphan',
)
prechecks: Mapped[list['TransferPrecheck']] = relationship(
back_populates='run', cascade='all, delete-orphan',
)
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='run')
class TransferSourceJob(Base):
"""来源实例级的文件准备/预检执行单元;来源间互不阻断。"""
__tablename__ = 'transfer_source_jobs'
__table_args__ = (
UniqueConstraint('run_id', 'source_code', name='uq_transfer_source_jobs_run_source'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_SOURCE_JOB_STATUSES)})",
name='ck_transfer_source_jobs_status',
),
Index('ix_transfer_source_jobs_source_status', 'source_code', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(ForeignKey('transfer_runs.id'), nullable=False, index=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
file_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: 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)
lease_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_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,
)
run: Mapped[TransferRun] = relationship(back_populates='source_jobs')
class TransferPrecheck(Base):
"""一次冻结快照的预检结果;确认/执行绑定其 Hash。"""
__tablename__ = 'transfer_prechecks'
__table_args__ = (
UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_PRECHECK_STATUSES)})",
name='ck_transfer_prechecks_status',
),
Index('ix_transfer_prechecks_run_status', 'run_id', 'status'),
Index('ix_transfer_prechecks_business_date', 'business_date'),
)
id: Mapped[int] = mapped_column(primary_key=True)
precheck_no: Mapped[str] = mapped_column(String(64), nullable=False)
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True, index=True)
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='prechecking', server_default='prechecking')
scope_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
file_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
strategy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
estimated_erp_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
confirmed_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,
)
run: Mapped[Optional[TransferRun]] = relationship(back_populates='prechecks')
items: Mapped[list['TransferInvoiceItem']] = relationship(
back_populates='precheck', cascade='all, delete-orphan',
)
class TransferInvoiceItem(Base):
"""预检明细项;同一预检内 Invoice 唯一,保留原始行追溯。"""
__tablename__ = 'transfer_invoice_items'
__table_args__ = (
UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
name='ck_transfer_invoice_items_status',
),
Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'),
Index('ix_transfer_invoice_items_run_id', 'run_id'),
Index('ix_transfer_invoice_items_erp_document_no', 'erp_document_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
precheck_id: Mapped[int] = mapped_column(ForeignKey('transfer_prechecks.id'), nullable=False, index=True)
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
erp_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False)
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 原始文件行追溯:Sheet + 行号 + 文件版本(决策 11)。
raw_lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
manually_closed_reason: Mapped[Optional[str]] = mapped_column(Text, 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,
)
precheck: Mapped[TransferPrecheck] = relationship(back_populates='items')
run: Mapped[Optional[TransferRun]] = relationship(back_populates='items')
attempts: Mapped[list['TransferAttempt']] = relationship(
back_populates='item', cascade='all, delete-orphan',
)
class TransferAttempt(Base):
"""一次恢复/重查/执行尝试;每次恢复创建新 Attempt,旧记录不可覆盖。"""
__tablename__ = 'transfer_attempts'
__table_args__ = (
UniqueConstraint('item_id', 'attempt_no', name='uq_transfer_attempts_item_no'),
CheckConstraint(
f"kind IN ({', '.join(repr(s) for s in TRANSFER_ATTEMPT_KINDS)})",
name='ck_transfer_attempts_kind',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_ATTEMPT_STATUSES)})",
name='ck_transfer_attempts_status',
),
Index('ix_transfer_attempts_item_created', 'item_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
item_id: Mapped[int] = mapped_column(ForeignKey('transfer_invoice_items.id'), nullable=False)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
kind: Mapped[str] = mapped_column(String(16), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
request_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
item: Mapped[TransferInvoiceItem] = relationship(back_populates='attempts')
class TransferAuditEvent(Base):
"""调拨领域只追加审计事件;禁止更新与删除。"""
__tablename__ = 'transfer_audit_events'
__table_args__ = (
CheckConstraint(
f"actor_type IN ({', '.join(repr(s) for s in TRANSFER_AUDIT_ACTOR_TYPES)})",
name='ck_transfer_audit_events_actor_type',
),
CheckConstraint(
"result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')",
name='ck_transfer_audit_events_result',
),
Index('ix_transfer_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'),
Index('ix_transfer_audit_events_run_created', 'run_no', 'created_at'),
Index('ix_transfer_audit_events_invoice_created', 'invoice_no', 'created_at'),
Index('ix_transfer_audit_events_operation_created', 'operation_id', 'created_at'),
Index('ix_transfer_audit_events_event_hash', 'event_hash'),
)
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
precheck_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
invoice_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
attempt_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
actor_role: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
actor_display: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
result: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
before_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
after_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
diff_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
before_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
after_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
event_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class TransferArchive(Base):
"""大对象归档索引(MinIO);Hash 用于归档完整性校验。"""
__tablename__ = 'transfer_archives'
__table_args__ = (
UniqueConstraint('archive_no', name='uq_transfer_archives_archive_no'),
UniqueConstraint('object_type', 'object_id', 'sha256', name='uq_transfer_archives_object_sha'),
CheckConstraint("file_size >= 0", name='ck_transfer_archives_file_size'),
Index('ix_transfer_archives_object', 'object_type', 'object_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
archive_no: Mapped[str] = mapped_column(String(64), nullable=False)
object_type: Mapped[str] = mapped_column(String(64), nullable=False)
object_id: Mapped[str] = mapped_column(String(128), nullable=False)
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@event.listens_for(TransferAuditEvent, 'before_update')
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
"""拒绝 ORM 更新,确保审计事件不可改写。"""
raise ValidationError('Transfer audit event is append-only', code='IN_TRANSIT_TRANSFER.AUDIT_IMMUTABLE')
@event.listens_for(TransferAuditEvent, 'before_delete')
def _reject_transfer_audit_delete(_mapper, _connection, _target) -> None:
"""拒绝 ORM 删除,保留跨生命周期追溯事实。"""
raise ValidationError('Transfer audit event is append-only', code='IN_TRANSIT_TRANSFER.AUDIT_IMMUTABLE')
+202
View File
@@ -0,0 +1,202 @@
"""models/integration_connector.py
用途:Integration Connector(外部系统连接器框架)P1 配置与运行时模型:
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import JSONB
from app.models.base import Base
# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。
CONNECTOR_TYPES = ('rest', 'soap')
CONFIG_STATUSES = ('draft', 'published', 'retired')
CREDENTIAL_STATUSES = ('active', 'rotating', 'retired')
# context_selector_json 需要参与唯一约束/索引:PostgreSQL 的 JSON 无默认 btree 操作符表,
# 无法建唯一索引;映射为 JSONB 即可。SQLite/测试仍用 JSON(TEXT)。
CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql')
class IntegrationCredentialReference(Base):
"""凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。"""
__tablename__ = 'integration_credential_references'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_credential_references_code'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CREDENTIAL_STATUSES)})",
name='ck_integration_credential_references_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
secret_ref: Mapped[str] = mapped_column(String(128), nullable=False)
secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env')
credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password')
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
last_verified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationClientInstance(Base):
"""客户端实例:一份到外部系统的连接配置(连到哪 + 凭据引用 + 超时/TLS/默认 org)。"""
__tablename__ = 'integration_client_instances'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_client_instances_code'),
CheckConstraint(
f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})",
name='ck_integration_client_instances_connector_type',
),
Index('ix_integration_client_instances_type_env', 'connector_type', 'environment'),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
credential_ref_code: Mapped[Optional[str]] = mapped_column(
ForeignKey('integration_credential_references.code'), nullable=True,
)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('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 IntegrationInterfaceDefinition(Base):
"""接口定义:一个可调操作(请求模板 + 入参 Schema + 返回值映射 + 出参 Schema)。"""
__tablename__ = 'integration_interface_definitions'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_interface_definitions_code'),
CheckConstraint(
f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})",
name='ck_integration_interface_definitions_connector_type',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})",
name='ck_integration_interface_definitions_status',
),
Index('ix_integration_interface_definitions_client', 'client_instance_code'),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False,
)
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
# 关键强类型字段独立列(JSON 保留作兜底)。
http_method: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
request_path: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
request_spec_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
input_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
output_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
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')
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('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 IntegrationBinding(Base):
"""绑定:(Capability, context_selector) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。"""
__tablename__ = 'integration_bindings'
__table_args__ = (
UniqueConstraint(
'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})",
name='ck_integration_bindings_status',
),
CheckConstraint(
"priority >= 0", name='ck_integration_bindings_priority',
),
Index('ix_integration_bindings_cap_env_status', 'capability', 'environment', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
capability: Mapped[str] = mapped_column(String(128), nullable=False)
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
# 最常用的 context 匹配键独立列(JSON 保留作兜底)。
context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False,
)
interface_definition_code: Mapped[str] = mapped_column(
ForeignKey('integration_interface_definitions.code'), nullable=False,
)
mapping_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
priority: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
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 IntegrationCall(Base):
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。"""
__tablename__ = 'integration_calls'
__table_args__ = (
UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
Index('ix_integration_calls_trace_id', 'trace_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
operation_id: Mapped[str] = mapped_column(String(128), nullable=False)
capability: Mapped[str] = mapped_column(String(128), nullable=False)
binding_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
request_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(32), nullable=False)
elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+88
View File
@@ -29,6 +29,7 @@ class Job(Base):
Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'),
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
Index('ix_jobs_locked_at', 'locked_at'),
Index('ix_jobs_retry_of_job_id', 'retry_of_job_id'),
# 仅预解析 Job:同业务锚点同时只允许一条 queued
# (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限)
Index(
@@ -48,6 +49,78 @@ class Job(Base):
"AND business_ref IS NOT NULL"
),
),
Index(
'uq_jobs_shipping_order_extraction_active_ref',
'domain',
'job_type',
'business_ref',
unique=True,
postgresql_where=text(
"job_type = 'shipping_order_extraction' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
sqlite_where=text(
"job_type = 'shipping_order_extraction' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
),
Index(
'uq_jobs_shipping_document_layout_active_ref',
'domain',
'job_type',
'business_ref',
unique=True,
postgresql_where=text(
"job_type = 'shipping_document_layout' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
sqlite_where=text(
"job_type = 'shipping_document_layout' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
),
# STP 自动建单:同幂等键同时只允许一条 queued/running(failed 可保留审计并新建重试 Job)
Index(
'uq_jobs_shipping_stp_auto_create_active_ref',
'domain',
'job_type',
'business_ref',
unique=True,
postgresql_where=text(
"job_type = 'shipping_stp_auto_create' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
sqlite_where=text(
"job_type = 'shipping_stp_auto_create' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
),
# Review Revalidate Job:同 Case 同时只允许一条 queued/running(failed 可新建重试 Job)
Index(
'uq_jobs_shipping_review_revalidate_progress_active_ref',
'domain',
'job_type',
'business_ref',
unique=True,
postgresql_where=text(
"domain = 'shipping_notice' "
"AND job_type = 'shipping_review_revalidate_progress' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
sqlite_where=text(
"domain = 'shipping_notice' "
"AND job_type = 'shipping_review_revalidate_progress' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -65,6 +138,20 @@ class Job(Base):
max_attempts: Mapped[int] = mapped_column(Integer, default=3)
locked_by: Mapped[Optional[str]] = mapped_column(String(128))
locked_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
# 重试链:新 Job 指向被替换的 failed/dead Job,保留旧行审计。
retry_of_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True)
# 正式编排作用域。payload 仍保留相同 identity,列用于数据库唯一约束、恢复扫描和审计查询。
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True, index=True)
execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_executions.id'), nullable=True, index=True,
)
gate_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
)
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True,
)
fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
@@ -72,3 +159,4 @@ class Job(Base):
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
created_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[created_by_id])
retry_of_job: Mapped[Optional['Job']] = relationship('Job', remote_side=[id], foreign_keys=[retry_of_job_id])
+268 -211
View File
@@ -1,22 +1,30 @@
"""
backend/app/models/shipping.py
用途:货代发货通知批次、任务、事件、库存文件、接入记录、文档/候选与库存映射模型。
依赖:models.base.Base。
逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等;
用途:货代发货通知正式 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);
ShippingUploadAttempt.idempotency_key 为货代上传幂等;
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载阶段二「一邮件多订单」识别;ShippingTask.source_candidate_id 预留给建单;
ShippingTask.supersedes_task_id 唯一约束保证修订链线性。
Intake/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载「一邮件多订单」识别;ShippingNotice.source_candidate_id 记录正式建单来源;
ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性;
OT 的 order_data_version/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,
Date,
DateTime,
Float,
ForeignKey,
@@ -34,172 +42,89 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingBatch(Base):
"""货代发货通知批次(一次多文件上传的聚合容器)"""
class ShippingNotice(Base):
"""
正式发货通知(Candidate 建单后的履约实体)。
__tablename__ = 'shipping_batches'
核心逻辑:Chatflow Tool 编排状态机;建单前 OT 聚合根见 ShippingOrderTask(shipping_order_tasks)。
"""
__tablename__ = 'shipping_notices'
__table_args__ = (
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
Index('ix_shipping_batches_conversation', 'conversation_id'),
UniqueConstraint(
'user_id',
'create_idempotency_key',
name='uq_shipping_batches_user_create_idempotency',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
current_focus_task_no: Mapped[Optional[str]] = mapped_column(
String(64),
ForeignKey(
'shipping_tasks.task_no',
name='fk_shipping_batches_current_focus_task_no_shipping_tasks',
use_alter=True,
),
nullable=True,
)
file_count: Mapped[int] = mapped_column(Integer, default=1)
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
tasks: Mapped[List['ShippingTask']] = relationship(
'ShippingTask',
back_populates='batch',
foreign_keys='ShippingTask.batch_id',
)
class ShippingTask(Base):
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
__tablename__ = 'shipping_tasks'
__table_args__ = (
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
Index('ix_shipping_tasks_conversation', 'conversation_id'),
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
Index('ix_shipping_tasks_upload_status', 'upload_status'),
Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'),
Index('ix_shipping_tasks_inventory_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'),
Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'),
Index('ix_shipping_tasks_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_notices_conversation', 'conversation_id'),
Index('ix_shipping_notices_business_no', 'business_no'),
# 线性版本链:同一父任务至多一个后继(NULL 不冲突)
UniqueConstraint('supersedes_task_id', name='uq_shipping_tasks_supersedes_task_id'),
Index('ix_shipping_tasks_duplicate_source_task_id', 'duplicate_source_task_id'),
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)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
# 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=True)
business_sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
business_numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), default='manual')
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
source_intake_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notice_intakes.id'),
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_notice_candidates.id',
name='fk_shipping_tasks_source_candidate_id',
'shipping_order_candidates.id',
name='fk_shipping_notices_source_candidate_id',
use_alter=True,
),
index=True,
nullable=True,
)
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
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,
)
document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
supersedes_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_tasks.id'),
ForeignKey('shipping_notices.id'),
nullable=True,
)
duplicate_source_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_tasks.id'),
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_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
ship_to: Mapped[Optional[str]] = mapped_column(Text, 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_source_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)
inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=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)
# 任务处置与业务阶段正交:生命周期负责作废/归档。
lifecycle_status: Mapped[str] = mapped_column(
String(16),
nullable=False,
default='active',
server_default=text("'active'"),
index=True,
)
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
deleted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
deletion_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
voided_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
voided_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
void_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
archived_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archived_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
batch: Mapped[Optional['ShippingBatch']] = relationship(
'ShippingBatch',
back_populates='tasks',
foreign_keys=[batch_id],
)
events: Mapped[List['ShippingTaskEvent']] = relationship(
'ShippingTaskEvent',
back_populates='task',
cascade='all, delete-orphan',
)
class ShippingTaskEvent(Base):
"""发货 task 审计事件"""
@@ -207,12 +132,36 @@ class ShippingTaskEvent(Base):
__tablename__ = 'shipping_task_events'
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_tasks.id', name='fk_shipping_task_events_task_id_order_task'),
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 记录触发/来源码(如 freight_upload_rpa_callback_succeeded);保证能容纳长触发码。
source: Mapped[Optional[str]] = mapped_column(String(64), 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['ShippingTask'] = relationship('ShippingTask', back_populates='events')
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', 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):
@@ -220,7 +169,6 @@ class ShippingInventoryFile(Base):
__tablename__ = 'shipping_inventory_files'
__table_args__ = (
Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'),
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
Index(
'ix_shipping_inventory_files_source_snapshot',
@@ -230,32 +178,44 @@ 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"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
@@ -268,7 +228,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)
@@ -279,10 +238,18 @@ class ShippingInventoryFile(Base):
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)
batch: Mapped[Optional['ShippingBatch']] = relationship('ShippingBatch', foreign_keys=[batch_id])
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
'ShippingTaskInventoryLink',
back_populates='inventory_file',
@@ -301,12 +268,11 @@ class ShippingTaskInventoryLink(Base):
'ix_shipping_task_inventory_links_task_source',
'task_id',
'matched_source_code',
'matched_site_id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), 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')
@@ -314,15 +280,20 @@ 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)
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['ShippingTask'] = relationship('ShippingTask', foreign_keys=[task_id])
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
'ShippingInventoryFile',
back_populates='links',
@@ -330,25 +301,41 @@ class ShippingTaskInventoryLink(Base):
)
class ShippingNoticeIntake(Base):
"""发货通知预解析接入记录(上传成功至正式建单前的异步解析阶段)。"""
class ShippingOrderIntake(Base):
"""
发货通知接入记录:分别跟踪文件预处理与订单抽取状态。
__tablename__ = 'shipping_notice_intakes'
阶段 1:source_type=eml|direct_pdf 标识裁决边界;order_submission_id 挂接上传 Submission。
表名 shipping_order_intakes(建单前接入层)。
"""
__tablename__ = 'shipping_order_intakes'
__table_args__ = (
UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'),
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_notice_intakes_asset_purpose_parser',
name='uq_shipping_order_intakes_asset_purpose_parser',
),
Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'),
Index('ix_shipping_notice_intakes_expires', 'expires_at'),
Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_notice_intakes_duplicate_status_created', 'duplicate_status', 'created_at'),
Index('ix_shipping_notice_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'),
Index('ix_shipping_notice_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'),
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)
@@ -356,8 +343,26 @@ class ShippingNoticeIntake(Base):
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)
@@ -384,39 +389,37 @@ class ShippingNoticeIntake(Base):
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
# co8e9f0a1b2c 已 DROP shipping_batches 与 consumed_batch_id;消费绑定仅保留任务侧。
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class ShippingNoticeDocument(Base):
class ShippingOrderDocument(Base):
"""
发货通知文档单元:邮件正文或单个附件(阶段二)。
核心逻辑:Intake 解析后按 attachment_key 幂等 upsert;附件型 Document 可挂 derived FileAsset。
"""
__tablename__ = 'shipping_notice_documents'
__tablename__ = 'shipping_order_documents'
__table_args__ = (
UniqueConstraint(
'intake_id',
'attachment_key',
name='uq_shipping_notice_documents_intake_attachment_key',
name='uq_shipping_order_documents_intake_attachment_key',
),
# 支撑 Candidate (primary_document_id, intake_id) 复合外键
UniqueConstraint('id', 'intake_id', name='uq_shipping_notice_documents_id_intake'),
Index('ix_shipping_notice_documents_intake_id', 'intake_id'),
Index('ix_shipping_notice_documents_asset_id', 'asset_id'),
Index('ix_shipping_notice_documents_content_hash', 'content_hash'),
Index('ix_shipping_notice_documents_parse_status', 'parse_status'),
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_notice_intakes.id'),
ForeignKey('shipping_order_intakes.id'),
nullable=False,
)
asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
@@ -428,48 +431,108 @@ class ShippingNoticeDocument(Base):
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 ShippingNoticeCandidate(Base):
class ShippingOrderCandidate(Base):
"""
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
核心逻辑:通常 1 Document → 1 Candidate;重复检测与决策落在 Candidate 级,互不影响。
核心逻辑:一个 Document 可抽取多个 Candidate;candidate_key 保证重提取幂等,
重复检测、自动建单与待补字段状态均落在 Candidate 级。
"""
__tablename__ = 'shipping_notice_candidates'
__tablename__ = 'shipping_order_candidates'
__table_args__ = (
UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'),
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',
'primary_document_id',
name='uq_shipping_notice_candidates_intake_primary_document',
'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_notice_documents.id', 'shipping_notice_documents.intake_id'],
name='fk_shipping_notice_candidates_document_intake',
['shipping_order_documents.id', 'shipping_order_documents.intake_id'],
name='fk_shipping_order_candidates_document_intake',
),
Index('ix_shipping_notice_candidates_intake_id', 'intake_id'),
Index('ix_shipping_notice_candidates_primary_document_id', 'primary_document_id'),
Index('ix_shipping_notice_candidates_po_number', 'po_number'),
Index('ix_shipping_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_notice_candidates_user_fingerprint',
'ix_shipping_order_candidates_user_fingerprint',
'business_fingerprint',
),
Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'),
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_notice_intakes.id'),
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)
@@ -480,10 +543,21 @@ class ShippingNoticeCandidate(Base):
nullable=False,
)
conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
selected: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), nullable=False)
# `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',
@@ -495,28 +569,11 @@ class ShippingNoticeCandidate(Base):
duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_tasks.id'),
ForeignKey('shipping_order_tasks.id'),
nullable=True,
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
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)
+124
View File
@@ -0,0 +1,124 @@
"""
backend/app/models/shipping_audit_event.py
用途:定义货代领域统一、仅追加的审计事件。
依赖:SQLAlchemy Base;Workflow / Run / Task / Intake 等稳定业务编号(软引用)。
逻辑:各业务服务通过 audit_service 追加事件;actor_type 含 worker(门禁 Job);
事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。
进度审计阶段扩展 operation_id、对象关联、白名单前后快照、证据引用、结果与保留到期时间;
Workflow 阶段以 workflow_id / workflow_item_id / workflow_item_version_id 软引用批次与 PDF 项,
并写入 previous_event_hash / event_hash 哈希链与 diff_json;另含 owner_user_id 与脱敏
client_ip_hash/user_agent_hash;
项次派生阶段使用 LINE_DERIVATION_AUDIT_EVENT_TYPES(FIELD_DERIVED / LINE_NO_OVERRIDDEN /
DERIVATION_SIMULATED / EXPORT_GENERATED 等),元数据仅存脱敏摘要与规则校验和;
禁止存储 PDF/邮件正文、模型原文、对象存储 URL、原始 IP/UA 或密钥。
ORM before_update/before_delete 拒绝改删;PostgreSQL 另有 append-only 触发器
(迁移 a0e1f2b3c4d5);到期清理须 set_config('hxops.shipping_audit_purge','1')。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, Index, Integer, JSON, String, Text, event
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
from app.core.errors import ValidationError
class ShippingAuditEvent(Base):
"""货代领域的不可变审计事件;禁止业务代码更新或删除既有记录。"""
__tablename__ = 'shipping_audit_events'
__table_args__ = (
CheckConstraint(
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')",
name='ck_shipping_audit_events_actor_type',
),
CheckConstraint(
"result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')",
name='ck_shipping_audit_events_result',
),
Index('ix_shipping_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'),
Index('ix_shipping_audit_events_run_created', 'run_no', 'created_at'),
Index('ix_shipping_audit_events_task_created', 'task_no', 'created_at'),
Index('ix_shipping_audit_events_operation_created', 'operation_id', 'created_at'),
Index('ix_shipping_audit_events_request_created', 'request_id', 'created_at'),
Index('ix_shipping_audit_events_conversation_created', 'conversation_id', 'created_at'),
Index('ix_shipping_audit_events_document_created', 'document_id', 'created_at'),
Index('ix_shipping_audit_events_unit_created', 'unit_id', 'created_at'),
Index('ix_shipping_audit_events_actor_created', 'actor_type', 'actor_id', 'created_at'),
Index('ix_shipping_audit_events_event_type_created', 'event_type', 'created_at'),
Index('ix_shipping_audit_events_retention_expires', 'retention_expires_at', 'id'),
Index('ix_shipping_audit_events_workflow_created', 'workflow_id', 'created_at'),
Index('ix_shipping_audit_events_workflow_item_created', 'workflow_item_id', 'created_at'),
Index('ix_shipping_audit_events_event_hash', 'event_hash'),
Index('ix_shipping_audit_events_owner_created', 'owner_user_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
run_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
task_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
intake_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
actor_role: Mapped[str | None] = mapped_column(String(64), nullable=True)
# 操作者展示名(可选);与 actor_id 并存,禁止写入敏感联系方式。
actor_display: Mapped[str | None] = mapped_column(String(128), nullable=True)
request_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
operation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
correlation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
source: Mapped[str | None] = mapped_column(String(32), nullable=True)
result: Mapped[str | None] = mapped_column(String(16), nullable=True)
error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
conversation_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
unit_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
document_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
review_case_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
# Workflow 软引用:workflow_no / item_no / version id(字符串),避免级联删除抹除审计。
workflow_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
workflow_item_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
workflow_item_version_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
# 业务属主(非操作者);代操作场景与 actor_id 区分。
owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
# 仅存哈希,禁止写入原始 IP / User-Agent。
client_ip_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
user_agent_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
attempt_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
action: Mapped[str | None] = mapped_column(String(64), nullable=True)
reason_code: Mapped[str | None] = mapped_column(String(128), nullable=True)
reason: Mapped[str | None] = mapped_column(Text, nullable=True)
before_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
after_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
# 白名单前后快照差异;与哈希链一并支撑离线校验。
diff_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
previous_event_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
event_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
# 敏感等级:normal | sensitive;用于查询脱敏与访问审计分级。
sensitivity_level: Mapped[str | None] = mapped_column(String(16), nullable=True)
evidence_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True)
artifact_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True)
context_refs_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
metadata_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
retention_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@event.listens_for(ShippingAuditEvent, 'before_update')
def _reject_shipping_audit_update(_mapper, _connection, _target) -> None:
"""拒绝 ORM 更新,确保即使未调用审计服务也不能改写历史事件。"""
raise ValidationError('Shipping audit event is append-only', code='SHIPPING_NOTICE.AUDIT_IMMUTABLE')
@event.listens_for(ShippingAuditEvent, 'before_delete')
def _reject_shipping_audit_delete(_mapper, _connection, _target) -> None:
"""拒绝 ORM 删除,避免业务清理或级联关系抹除审计事实。"""
raise ValidationError('Shipping audit event is append-only', code='SHIPPING_NOTICE.AUDIT_IMMUTABLE')
@@ -0,0 +1,75 @@
"""
backend/app/models/shipping_context_provider.py
用途:定义订单通用上下文字段可选择的确定性来源目录及受控选项。
依赖:models.base.Base、SQLAlchemy。
逻辑:数据库维护来源展示与启停状态;代码注册表校验 provider_key/option_key 是否具有真实采集实现。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import CheckConstraint, ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingContextProvider(Base):
"""确定性上下文来源族;只允许绑定代码注册的 provider_key。"""
__tablename__ = 'shipping_context_providers'
__table_args__ = (
CheckConstraint("status IN ('active', 'disabled')", name='ck_shipping_context_providers_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
provider_key: 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_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
options: Mapped[list['ShippingContextProviderOption']] = relationship(
back_populates='provider', cascade='all, delete-orphan', order_by='ShippingContextProviderOption.id'
)
class ShippingContextProviderOption(Base):
"""来源族下的受控值选项;option_key 必须与代码注册表中的能力一致。"""
__tablename__ = 'shipping_context_provider_options'
__table_args__ = (
UniqueConstraint('provider_id', 'option_key', name='uq_shipping_context_provider_options_key'),
CheckConstraint("value_type IN ('string')", name='ck_shipping_context_provider_options_value_type'),
CheckConstraint(
"sensitivity_level IN ('low', 'personal', 'confidential')",
name='ck_shipping_context_provider_options_sensitivity',
),
CheckConstraint(
"default_dify_exposure_policy IN ('never', 'redacted', 'confirmed_readonly')",
name='ck_shipping_context_provider_options_dify_policy',
),
CheckConstraint("status IN ('active', 'disabled')", name='ck_shipping_context_provider_options_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
provider_id: Mapped[int] = mapped_column(
ForeignKey('shipping_context_providers.id', ondelete='CASCADE'), nullable=False
)
option_key: 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='string', server_default='string')
sensitivity_level: Mapped[str] = mapped_column(String(16), nullable=False)
default_dify_exposure_policy: Mapped[str] = mapped_column(
String(32), nullable=False, default='never', server_default='never'
)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
provider: Mapped[ShippingContextProvider] = relationship(back_populates='options')
+261
View File
@@ -0,0 +1,261 @@
"""
backend/app/models/shipping_customer.py
用途:货代标准客户、客户识别证据与业务编号流水模型。
依赖:models.base.Base、users、shipping_notices。
逻辑:客户主数据提供稳定身份;发货通知自持履约事实;流水表供编号服务原子递增。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import List, Optional
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
class ShippingCustomer(Base):
"""货代标准客户主数据;简码由管理员维护并用于业务编号前缀。"""
__tablename__ = 'shipping_customers'
__table_args__ = (
CheckConstraint(
"length(short_code) BETWEEN 2 AND 6 "
"AND short_code = upper(short_code) "
"AND short_code NOT GLOB '*[^A-Z]*'",
name='ck_shipping_customers_short_code_shape',
).ddl_if(dialect='sqlite'),
CheckConstraint(
"short_code ~ '^[A-Z]{2,6}$'",
name='ck_shipping_customers_short_code_shape',
).ddl_if(dialect='postgresql'),
Index('ix_shipping_customers_status_name', 'status', 'standard_name'),
)
id: Mapped[int] = mapped_column(primary_key=True)
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)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
identifiers: Mapped[List['ShippingCustomerIdentifier']] = relationship(
'ShippingCustomerIdentifier',
back_populates='customer',
cascade='all, delete-orphan',
)
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):
"""标准客户的可审核识别证据;同一别名可属于多个客户以表达歧义。"""
__tablename__ = 'shipping_customer_identifiers'
__table_args__ = (
UniqueConstraint(
'customer_id',
'identifier_type',
'normalized_value',
name='uq_shipping_customer_identifiers_customer_type_value',
),
Index(
'ix_shipping_customer_identifiers_lookup',
'identifier_type',
'normalized_value',
'status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
identifier_type: Mapped[str] = mapped_column(String(32), nullable=False)
raw_value: Mapped[str] = mapped_column(String(500), nullable=False)
normalized_value: Mapped[str] = mapped_column(String(500), nullable=False)
auto_match_allowed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
source: Mapped[str] = mapped_column(String(32), nullable=False, default='manual', server_default='manual')
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_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)
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='identifiers')
class ShippingCustomerExternalRef(Base):
"""客户在期初文件或外部系统中的稳定来源键,用于重复导入幂等。"""
__tablename__ = 'shipping_customer_external_refs'
__table_args__ = (
UniqueConstraint(
'source_system',
'legacy_customer_key',
name='uq_shipping_customer_external_refs_source_key',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
source_system: Mapped[str] = mapped_column(String(64), nullable=False)
legacy_customer_key: Mapped[str] = mapped_column(String(128), nullable=False)
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', 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 ShippingBusinessSequence(Base):
"""按业务类型、客户和 Asia/Shanghai 业务日期保存当前流水值。"""
__tablename__ = 'shipping_business_sequences'
__table_args__ = (
CheckConstraint(
'current_value BETWEEN 0 AND 99',
name='ck_shipping_business_sequences_current_value',
),
UniqueConstraint(
'business_type',
'customer_id',
'business_date',
name='uq_shipping_business_sequences_type_customer_date',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
business_type: Mapped[str] = mapped_column(
String(32),
nullable=False,
default='shipping_notice',
server_default='shipping_notice',
)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
business_date: Mapped[date] = mapped_column(Date, nullable=False, index=True)
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)
@@ -0,0 +1,86 @@
"""
backend/app/models/shipping_customer_import.py
用途:保存货代期初客户导入批次、原始文件与逐行预检/发布结果。
依赖:models.base.Base、users、shipping_customers。
逻辑:上传仅写暂存批次与行;管理员解决冲突后由发布服务单事务写入正式客户主数据。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingCustomerImportBatch(Base):
"""期初客户导入批次,保存文件哈希、原始内容、统计和发布审计。"""
__tablename__ = 'shipping_customer_import_batches'
__table_args__ = (
UniqueConstraint('file_hash', 'source_system', name='uq_shipping_customer_import_batches_hash_source'),
Index('ix_shipping_customer_import_batches_status_created', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
file_hash: Mapped[str] = mapped_column(String(64), nullable=False)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
source_system: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='validated', server_default='validated')
total_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
valid_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
warning_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
error_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
published_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
uploaded_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(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)
rows: Mapped[List['ShippingCustomerImportRow']] = relationship(
'ShippingCustomerImportRow',
back_populates='batch',
cascade='all, delete-orphan',
order_by='ShippingCustomerImportRow.row_order',
)
class ShippingCustomerImportRow(Base):
"""导入文件逐行暂存、校验、人工决定与正式发布结果。"""
__tablename__ = 'shipping_customer_import_rows'
__table_args__ = (
UniqueConstraint('batch_id', 'sheet_name', 'row_no', name='uq_shipping_customer_import_rows_location'),
Index('ix_shipping_customer_import_rows_batch_status', 'batch_id', 'validation_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_id: Mapped[int] = mapped_column(ForeignKey('shipping_customer_import_batches.id'), nullable=False, index=True)
sheet_name: Mapped[str] = mapped_column(String(32), nullable=False)
row_no: Mapped[int] = mapped_column(Integer, nullable=False)
row_order: Mapped[int] = mapped_column(Integer, nullable=False)
row_type: Mapped[str] = mapped_column(String(32), nullable=False)
legacy_customer_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
raw_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
normalized_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
validation_status: Mapped[str] = mapped_column(String(32), nullable=False, default='valid')
errors_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
warnings_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
suggested_action: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
decision_action: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
target_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
decision_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
result_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
result_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
batch: Mapped['ShippingCustomerImportBatch'] = relationship('ShippingCustomerImportBatch', back_populates='rows')
@@ -0,0 +1,107 @@
"""
backend/app/models/shipping_customer_resolution.py
用途:保存订单候选的正式客户识别结果、识别证据与人工标签。
依赖:ShippingOrderCandidate、ShippingOrderIntake、ShippingCustomer、User。
逻辑:订单候选抽取后幂等刷新识别证据和候选;确认字段独立保存最终客户,
不得以订单中的任一字段(例如 bill_to)充当客户身份真相。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingCustomerShadowResolution(Base):
"""每个订单候选唯一一条正式客户识别快照,可追加确认和质量标签。"""
__tablename__ = 'shipping_customer_shadow_resolutions'
__table_args__ = (
CheckConstraint(
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')",
name='ck_shipping_customer_shadow_status',
),
Index('ix_shipping_customer_shadow_status_created', 'status', 'created_at'),
Index('ix_shipping_customer_shadow_labeled_created', 'manual_customer_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_candidates.id', ondelete='CASCADE'),
nullable=False,
unique=True,
)
intake_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_intakes.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
identity_rule_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_identity_rule_sets.id'), nullable=True, index=True,
)
identity_rule_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
identity_rule_set_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
order_schema_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=True,
)
resolution_version: Mapped[str] = mapped_column(String(32), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
evidence_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
candidate_matches_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
resolution_context_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
top_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
top_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
# 客户确认是识别结果的独立事实;不得覆盖 evidence_json 或原始身份指纹。
confirmed_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
confirmation_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
confirmation_reason: Mapped[Optional[str]] = mapped_column(String(500), 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)
manual_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
labeled_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
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,71 @@
"""
backend/app/models/shipping_document_layout.py
用途:持久化每份发货通知 Document 的版本化版面解析生命周期、冻结快照和质量结果。
依赖:shipping_order_documents、jobs、SQLAlchemy Base。
逻辑:同一 Document 版本递增;运行租约隔离旧 Worker,只有成功版本可成为 Document 当前布局。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingDocumentLayoutVersion(Base):
"""单文档版面解析版本;payload/checksum 一旦完成即不可原地改写。"""
__tablename__ = 'shipping_order_document_layout_versions'
__table_args__ = (
UniqueConstraint('document_id', 'version', name='uq_shipping_order_document_layout_document_version'),
CheckConstraint(
"status IN ('queued', 'running', 'ready', 'needs_review', 'failed', 'unsupported')",
name='ck_shipping_order_document_layout_status',
),
Index('ix_shipping_order_document_layout_document_status', 'document_id', 'status'),
Index('ix_shipping_order_document_layout_content_parser', 'source_content_hash', 'parser_key'),
Index(
'uq_shipping_order_document_layout_one_active',
'document_id',
unique=True,
postgresql_where=text("status IN ('queued', 'running')"),
sqlite_where=text("status IN ('queued', 'running')"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_documents.id', ondelete='CASCADE'), nullable=False,
)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(24), default='queued', server_default='queued', nullable=False)
source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
parser_key: Mapped[str] = mapped_column(String(128), nullable=False)
parser_name: Mapped[str] = mapped_column(String(32), nullable=False)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
backend: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
contract_version: Mapped[str] = mapped_column(String(64), nullable=False)
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
payload_size_bytes: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
quality_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
issues_json: Mapped[list] = mapped_column(JSON, default=list, nullable=False)
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True, index=True)
lease_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
attempt_count: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
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,
)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
document = relationship(
'ShippingOrderDocument', foreign_keys=[document_id], back_populates='layout_versions',
)
job = relationship('Job', foreign_keys=[job_id])
@@ -0,0 +1,66 @@
"""
订单模板自动冻结资格的版本化发布凭证。
用途:把模板可发布状态与自动冻结资格分离,并冻结 Profile、Schema、解析器和质量凭证身份。
依赖:订单 Profile、Schema 版本、盲测套件、用户和 SQLAlchemy Base。
逻辑:每个已发布模板版本独立持有一条资格记录;首版只能是人工确认,后续自动冻结须显式批准。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingDocumentProfileAutoFreezeQualification(Base):
"""模板版本的自动冻结资格;发布、暂停和撤销均保留独立审计身份。"""
__tablename__ = 'shipping_document_profile_auto_freeze_qualifications'
__table_args__ = (
UniqueConstraint(
'profile_id', 'profile_version', 'profile_checksum',
name='uq_shipping_document_profile_auto_freeze_qualification_version',
),
CheckConstraint(
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
name='ck_shipping_document_profile_auto_freeze_qualification_status',
),
Index(
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
'profile_id', 'status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=False)
profile_version: Mapped[int] = mapped_column(Integer, nullable=False)
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
parser_version: Mapped[str] = mapped_column(String(64), nullable=False)
quality_suite_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_document_profile_test_suites.id'), nullable=True,
)
customer_ids_json: Mapped[Optional[list[int]]] = mapped_column(JSON, nullable=True)
business_scenarios_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
requires_customer_confirmation: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=True, server_default=text('true'),
)
scope_updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
scope_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='manual_confirmation', server_default='manual_confirmation',
)
approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
suspended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
suspended_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
suspension_reason: Mapped[Optional[str]] = mapped_column(Text, 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,
)
@@ -0,0 +1,93 @@
"""
backend/app/models/shipping_document_profile_quality.py
用途:保存订单文档 Profile 的独立盲测集、样本期望值和不可变执行结果。
依赖:订单 Profile、订单文档、用户和 SQLAlchemy Base。
逻辑:每个 Profile 版本以冻结 checksum 绑定至少三个盲测样本;全部通过并经管理员批准后,才可用于确定性自动建单。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingDocumentProfileTestSuite(Base):
"""一个发布 Profile 版本的盲测集;批准状态是确定性自动建单的发布凭证。"""
__tablename__ = 'shipping_document_profile_test_suites'
__table_args__ = (
UniqueConstraint('profile_id', 'profile_checksum', name='uq_shipping_document_profile_test_suites_profile_checksum'),
CheckConstraint("status IN ('draft', 'approved', 'superseded')", name='ck_shipping_document_profile_test_suites_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=False, index=True)
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
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)
samples: Mapped[list['ShippingDocumentProfileTestSample']] = relationship(
back_populates='suite', cascade='all, delete-orphan', order_by='ShippingDocumentProfileTestSample.id',
)
runs: Mapped[list['ShippingDocumentProfileTestRun']] = relationship(
back_populates='suite', cascade='all, delete-orphan', order_by='ShippingDocumentProfileTestRun.id',
)
class ShippingDocumentProfileTestSample(Base):
"""盲测真值及确认时冻结的规范化 Layout 身份;不与建模样本自动复用。"""
__tablename__ = 'shipping_document_profile_test_samples'
__table_args__ = (
UniqueConstraint('suite_id', 'document_id', 'table_id', name='uq_shipping_document_profile_test_samples_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
suite_id: Mapped[int] = mapped_column(ForeignKey('shipping_document_profile_test_suites.id', ondelete='CASCADE'), nullable=False)
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
table_id: Mapped[str] = mapped_column(String(128), nullable=False)
layout_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_layout_versions.id'), nullable=True,
)
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
layout_parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
layout_parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
expected_rows_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
expected_order_fields_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
suite: Mapped['ShippingDocumentProfileTestSuite'] = relationship(back_populates='samples')
class ShippingDocumentProfileTestRun(Base):
"""一次可审计盲测执行;只存计数和失败码,避免把订单正文复制到测试日志。"""
__tablename__ = 'shipping_document_profile_test_runs'
__table_args__ = (
CheckConstraint("status IN ('passed', 'failed')", name='ck_shipping_document_profile_test_runs_status'),
Index('ix_shipping_document_profile_test_runs_suite_created', 'suite_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
suite_id: Mapped[int] = mapped_column(ForeignKey('shipping_document_profile_test_suites.id', ondelete='CASCADE'), nullable=False)
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False)
sample_count: Mapped[int] = mapped_column(Integer, nullable=False)
passed_sample_count: Mapped[int] = mapped_column(Integer, nullable=False)
failure_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
evidence_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
executed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
suite: Mapped['ShippingDocumentProfileTestSuite'] = relationship(back_populates='runs')
@@ -0,0 +1,40 @@
"""
models/shipping_eml_preview_snapshot.py
用途:持久化 EML 正文的安全 HTML 预览快照。
依赖:ShippingOrderDocument、SQLAlchemy Base。
逻辑:原始 EML 保持在私有 FileAsset;本表仅缓存已清洗、无图片和无主动内容的预览 HTML。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingEmlPreviewSnapshot(Base):
"""按正文 Document、源哈希和清洗器版本复用的安全 EML 预览。"""
__tablename__ = 'shipping_eml_preview_snapshots'
__table_args__ = (
UniqueConstraint(
'document_id', 'source_content_hash', 'sanitizer_version',
name='uq_shipping_eml_preview_snapshot_identity',
),
Index('ix_shipping_eml_preview_snapshot_document', 'document_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_documents.id', ondelete='CASCADE'), nullable=False,
)
source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
sanitizer_version: Mapped[str] = mapped_column(String(32), nullable=False)
html: Mapped[str] = mapped_column(Text, nullable=False)
html_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
html_size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,76 @@
"""
models/shipping_excel_template.py
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
"""
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):
"""一次 Notice 导出的不可变产物及生成输入快照。"""
__tablename__ = 'shipping_notice_export_artifacts'
__table_args__ = (
UniqueConstraint('artifact_no', name='uq_shipping_notice_export_artifacts_no'),
Index('ix_shipping_notice_export_artifacts_task_created', 'task_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_notices.id'), nullable=False, index=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['ShippingNotice'] = relationship()
@@ -0,0 +1,34 @@
"""货代上传后版本替代的外部撤销审计事实。"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingFreightCancellation(Base):
"""已上传旧 Notice 的撤销申请与外部撤销确认;成功前新版本不得履约。"""
__tablename__ = 'shipping_notice_freight_cancellations'
__table_args__ = (
UniqueConstraint('old_task_id', 'new_task_id', name='uq_shipping_notice_freight_cancellations_version_pair'),
Index('ix_shipping_notice_freight_cancellations_old_status', 'old_task_id', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
old_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
new_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='cancellation_required')
requested_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
requested_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
freight_receipt_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
receipt_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
reason: Mapped[str] = mapped_column(Text, nullable=False)
failure_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+164
View File
@@ -0,0 +1,164 @@
"""
backend/app/models/shipping_fulfillment.py
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingReservation(Base):
"""预约单当前履约注册表;Reservation ID 全局只能归属一个采购单。"""
__tablename__ = 'shipping_notice_reservations'
__table_args__ = (
UniqueConstraint('reservation_id', name='uq_shipping_notice_reservations_reservation_id'),
CheckConstraint(
"status IN ('pending', 'available', 'artifact_reserved', 'uploaded', 'external_change_required')",
name='ck_shipping_notice_reservations_status',
),
Index('ix_shipping_notice_reservations_task_status', 'task_id', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False)
reservation_id: Mapped[str] = mapped_column(String(64), nullable=False)
po_number_normalized: Mapped[str] = mapped_column(String(255), nullable=False)
part_number: Mapped[str] = mapped_column(String(255), nullable=False)
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
current_artifact_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notice_export_artifacts.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 ShippingInventoryVerification(Base):
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
__tablename__ = 'shipping_notice_inventory_verifications'
__table_args__ = (
CheckConstraint(
"status IN ('completed', 'expired', 'superseded')",
name='ck_shipping_notice_inventory_verifications_status',
),
Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship(
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id',
)
class ShippingInventoryVerificationLine(Base):
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
__tablename__ = 'shipping_notice_inventory_verification_lines'
__table_args__ = (
UniqueConstraint(
'verification_id', 'reservation_id',
name='uq_shipping_notice_inventory_verification_lines_reservation',
),
CheckConstraint(
"status IN ('available', 'shortage', 'invalid')",
name='ck_shipping_notice_inventory_verification_lines_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
verification_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False,
)
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
available_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines')
class ShippingExportArtifactLine(Base):
"""将本轮 Excel 与预约单一对一绑定,防止同一预约单进入两个有效 Artifact。"""
__tablename__ = 'shipping_notice_export_artifact_lines'
__table_args__ = (
UniqueConstraint(
'artifact_id', 'reservation_id',
name='uq_shipping_notice_export_artifact_lines_artifact_reservation',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
artifact_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_export_artifacts.id', ondelete='CASCADE'), nullable=False,
)
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
verification_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingUploadAttempt(Base):
"""一次 Artifact 上传尝试;回调幂等键和人工回执均在此处归档。"""
__tablename__ = 'shipping_notice_upload_attempts'
__table_args__ = (
UniqueConstraint('artifact_id', 'attempt_no', name='uq_shipping_notice_upload_attempts_artifact_attempt'),
UniqueConstraint('idempotency_key', name='uq_shipping_notice_upload_attempts_idempotency'),
UniqueConstraint('callback_id', name='uq_shipping_notice_upload_attempts_callback'),
CheckConstraint("mode IN ('rpa', 'manual')", name='ck_shipping_notice_upload_attempts_mode'),
CheckConstraint(
"status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out', 'unknown')",
name='ck_shipping_notice_upload_attempts_status',
),
Index('ix_shipping_notice_upload_attempts_artifact_created', 'artifact_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
artifact_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_export_artifacts.id'), nullable=False)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
mode: Mapped[str] = mapped_column(String(16), nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
callback_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
superseded_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_upload_attempts.id'), nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
# 历史资产关联字段仅为兼容旧数据;新货代上传不写截图或文件证据。
evidence_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
# RPA 仅保存最小状态摘要(kind/selector/observed_at/filename 等),不保存截图或 DOM。
success_evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
operator_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,139 @@
"""
backend/app/models/shipping_identity_rule.py
用途:定义货代客户/送货站点的可配置识别定义、发布规则集和追加式审计。
依赖:订单字段目录、客户/站点主数据、users。
逻辑:定义只引用已发布订单上下文字段;规则集冻结字段配置;证据值绑定定义。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import Boolean, CheckConstraint, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
def _uuid() -> str:
"""生成跨 PostgreSQL/SQLite 通用的字符串 UUID 主键。"""
return str(uuid.uuid4())
class ShippingIdentityDefinition(Base):
"""管理员维护的稳定识别定义;取值规则唯一来自已发布订单 Schema 字段。"""
__tablename__ = 'shipping_identity_definitions'
__table_args__ = (
UniqueConstraint('definition_code', name='uq_shipping_identity_definitions_code'),
CheckConstraint("target_type IN ('customer', 'site')", name='ck_shipping_identity_definitions_target'),
CheckConstraint("max_automation IN ('none', 'conditional')", name='ck_shipping_identity_definitions_automation'),
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_identity_definitions_status'),
Index('ix_shipping_identity_definitions_target_status', 'target_type', 'status'),
Index('ix_shipping_identity_definitions_context_field', 'context_field_id'),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
definition_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False, default='', server_default='')
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
evidence_label: Mapped[str] = mapped_column(String(128), nullable=False, default='', server_default='')
target_type: Mapped[str] = mapped_column(String(16), nullable=False)
context_field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
default_weight: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
max_automation: Mapped[str] = mapped_column(String(16), nullable=False, default='none', server_default='none')
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(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingIdentityRuleSet(Base):
"""全局客户识别规则集版本;发布后定义快照不可修改。"""
__tablename__ = 'shipping_identity_rule_sets'
__table_args__ = (
UniqueConstraint('version', name='uq_shipping_identity_rule_sets_version'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_identity_rule_sets_status'),
Index('ix_shipping_identity_rule_sets_status_version', 'status', 'version'),
)
id: Mapped[int] = mapped_column(primary_key=True)
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)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
source_rule_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_identity_rule_sets.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(nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingIdentityRuleAuditEvent(Base):
"""识别定义和规则集变更的只追加审计;快照避免后续配置污染历史。"""
__tablename__ = 'shipping_identity_rule_audit_events'
__table_args__ = (
CheckConstraint(
"event_type IN ('definition_created', 'definition_updated', 'definition_retired', "
"'rule_set_created', 'rule_set_saved', 'rule_set_published')",
name='ck_shipping_identity_rule_audits_event',
),
Index('ix_shipping_identity_rule_audits_rule_created', 'rule_set_id', 'created_at'),
Index('ix_shipping_identity_rule_audits_definition_created', 'definition_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
definition_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_identity_definitions.id'), nullable=True)
rule_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_identity_rule_sets.id'), nullable=True)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
class ShippingIdentityEvidence(Base):
"""客户或站点的审核识别证据值;必须且只能归属一个目标对象。"""
__tablename__ = 'shipping_identity_evidences'
__table_args__ = (
CheckConstraint(
'(customer_id IS NOT NULL AND site_id IS NULL) OR (customer_id IS NULL AND site_id IS NOT NULL)',
name='ck_shipping_identity_evidences_one_target',
),
CheckConstraint("status IN ('pending', 'approved', 'disabled')", name='ck_shipping_identity_evidences_status'),
Index(
'uq_shipping_identity_evidence_customer', 'definition_id', 'customer_id', 'normalized_value', unique=True,
postgresql_where=text('customer_id IS NOT NULL'), sqlite_where=text('customer_id IS NOT NULL'),
),
Index(
'uq_shipping_identity_evidence_site', 'definition_id', 'site_id', 'normalized_value', unique=True,
postgresql_where=text('site_id IS NOT NULL'), sqlite_where=text('site_id IS NOT NULL'),
),
Index('ix_shipping_identity_evidences_lookup', 'definition_id', 'normalized_value', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
definition_id: Mapped[str] = mapped_column(ForeignKey('shipping_identity_definitions.id'), nullable=False)
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)
raw_value: Mapped[str] = mapped_column(String(500), nullable=False)
normalized_value: Mapped[str] = mapped_column(String(500), nullable=False)
auto_match_allowed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
@@ -0,0 +1,220 @@
"""
models/shipping_inventory_candidates.py
用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。
InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
同一时刻的完整不可变副本,用于审计与回滚。
依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、
ShippingInventoryRoutingRule(可选外键,路由规则版本)。
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。
"""
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,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _utc_now() -> datetime:
"""返回 naive UTC 时间,与仓库其他模型一致。"""
return datetime.utcnow()
class ShippingInventoryCandidateSet(Base):
"""
库存候选集合(冻结真相根)。
核心逻辑:一次候选冻结对应一个 Set;input_fingerprint 相同 + 绑定对象相同则幂等复用;
同时支持绑定 task_id(建单后)和 review_case_id(建单前草稿复核)两种场景,
二者至少一个非空(CheckConstraint 强制)。
"""
__tablename__ = 'shipping_inventory_candidate_sets'
__table_args__ = (
CheckConstraint(
'task_id IS NOT NULL OR review_case_id IS NOT NULL',
name='ck_shipping_inv_cand_sets_binding',
),
CheckConstraint('set_version >= 1', name='ck_shipping_inv_cand_sets_version'),
CheckConstraint(
"lifecycle_status IN ('draft', 'frozen', 'superseded', 'invalidated')",
name='ck_shipping_inv_cand_sets_lifecycle',
),
Index(
'uq_shipping_inv_cand_sets_task_fp',
'task_id', 'input_fingerprint',
unique=True,
postgresql_where=text('task_id IS NOT NULL'),
sqlite_where=text('task_id IS NOT NULL'),
),
UniqueConstraint('task_id', 'set_version', name='uq_shipping_inv_cand_sets_task_version'),
Index(
'uq_shipping_inv_cand_sets_review_fp',
'review_case_id', 'input_fingerprint',
unique=True,
postgresql_where=text('review_case_id IS NOT NULL'),
sqlite_where=text('review_case_id IS NOT NULL'),
),
Index('ix_shipping_inv_cand_sets_task_frozen', 'task_id', 'frozen_at'),
Index('ix_shipping_inv_cand_sets_review_frozen', 'review_case_id', 'frozen_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
set_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=True,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=True,
)
execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True,
)
lifecycle_status: Mapped[str] = mapped_column(
String(32), nullable=False, default='frozen', server_default='frozen',
)
frozen_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
frozen_by_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('users.id'), nullable=True,
)
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
superseded_by_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True,
)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
input_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
routing_rule_version_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
manifest_snapshot_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship(
back_populates='candidate_set',
cascade='all, delete-orphan',
order_by='ShippingInventoryCandidateSource.candidate_order',
)
lines: Mapped[list['ShippingInventoryCandidateLine']] = relationship(
back_populates='candidate_set',
cascade='all, delete-orphan',
order_by='ShippingInventoryCandidateLine.line_no',
)
class ShippingInventoryCandidateSource(Base):
"""
任务级候选库存源(Set 的子级)。
核心逻辑:多源 RPA 按 (set_id, source_code) 唯一创建 Trigger / Attempt,
candidate_order 本身就是路由优先级(不能丢),不能用 SET 无序存储。
candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。
"""
__tablename__ = 'shipping_inventory_candidate_sources'
__table_args__ = (
UniqueConstraint(
'candidate_set_id', 'source_code',
name='uq_shipping_inv_cand_sources_set_source',
),
CheckConstraint(
"candidate_origin IN ('rule', 'manual_override')",
name='ck_shipping_inv_cand_sources_origin',
),
CheckConstraint('candidate_order >= 1', name='ck_shipping_inv_cand_sources_order'),
Index(
'ix_shipping_inv_cand_sources_set_order',
'candidate_set_id', 'candidate_order',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_set_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
candidate_order: Mapped[int] = mapped_column(Integer, nullable=False)
candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule')
routing_rule_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), nullable=True,
)
routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
override_by_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('users.id'), nullable=True,
)
override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
back_populates='sources',
)
class ShippingInventoryCandidateLine(Base):
"""
行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。
核心逻辑:source_codes_json 是**有序列表**(不是 set),顺序即行级路由优先级;
line_no 始终使用任务快照内稳定顺序号,source_line_no 只保存原始单据行号做审计;
跨源匹配需要按行读取候选集合,所以结构化存 line_no + source_line_no +
part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。
"""
__tablename__ = 'shipping_inventory_candidate_lines'
__table_args__ = (
UniqueConstraint(
'candidate_set_id', 'line_no',
name='uq_shipping_inv_cand_lines_set_line',
),
Index(
'ix_shipping_inv_cand_lines_set_pn_resv',
'candidate_set_id', 'part_number', 'reservation_id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_set_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False,
)
line_no: Mapped[int] = mapped_column(Integer, nullable=False)
source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
override_by_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('users.id'), nullable=True,
)
override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
back_populates='lines',
)
@@ -0,0 +1,397 @@
"""
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,
)
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
# result_mode / result_selector / success_texts / timeout_seconds。
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
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)
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'
)
receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship(
back_populates='inventory_source', uselist=False, cascade='all, delete-orphan',
)
class ShippingInventorySourceParsingBindingAudit(Base):
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
__tablename__ = 'shipping_inventory_source_parsing_binding_audits'
__table_args__ = (
Index('ix_inventory_source_parsing_binding_audit_source_created', 'inventory_source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False)
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True,
)
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
operation: Mapped[str] = mapped_column(String(32), nullable=False)
reason: Mapped[str] = mapped_column(String(500), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
source_config_version_before: Mapped[int] = mapped_column(Integer, nullable=False)
source_config_version_after: Mapped[int] = mapped_column(Integer, nullable=False)
before_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
after_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryParsingProfile(Base):
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
"""
__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'),
CheckConstraint(
"purpose IN ('inventory', 'movement')",
name='ck_shipping_inventory_parsing_profiles_purpose',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory')
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)
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
)
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, nullable=False, default=list, server_default=text("'[]'"),
)
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')
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship(
foreign_keys=[sample_analysis_id],
)
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)
# Only temporary conversation sessions retain a short-lived source file for confirmation.
storage_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
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)
sample_rows_json: Mapped[list[list[Any]]] = mapped_column(JSON, nullable=False, default=list)
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)
validation_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, index=True,
)
rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
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)
rpa_profile_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 ShippingInventoryValidationBatch(Base):
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
__tablename__ = 'shipping_inventory_validation_batches'
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
total_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
success_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
empty_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
failed_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
retry_of_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_validation_batches.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):
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
__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",
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)
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_inv_ext_map_src_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_inv_ext_map_src_wh_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,40 @@
"""
models/shipping_inventory_mapping.py
用途:保存不可变库存字段映射版本。
依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingInventoryMapping(Base):
"""库存文件的不可变字段映射版本。"""
__tablename__ = 'shipping_inventory_mappings'
__table_args__ = (
UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,79 @@
"""
models/shipping_inventory_preparation.py
用途:表达一次任务级库存准备轮次及逐库存源状态。
依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingInventoryPreparationAttempt(Base):
"""一次任务级库存准备恢复轮次。"""
__tablename__ = 'shipping_inventory_preparation_attempts'
__table_args__ = (
UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
CheckConstraint(
"status IN ('queued','running','waiting_external','waiting_manual','succeeded','failed','cancelled','superseded')",
name='ck_shipping_inventory_preparation_status',
),
Index('ix_shipping_inventory_preparation_task_status', 'task_id', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False)
execution_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True)
gate_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
recovery_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id', ondelete='SET NULL'), nullable=True)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True)
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan')
class ShippingInventoryPreparationSourceAttempt(Base):
"""准备轮次中某个库存源的业务状态。"""
__tablename__ = 'shipping_inventory_preparation_source_attempts'
__table_args__ = (
UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
CheckConstraint(
"status IN ('ready','reusable','skipped','failed','waiting','queued','running')",
name='ck_shipping_inventory_preparation_source_status',
),
Index('ix_shipping_inventory_preparation_source_status', 'source_code', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True)
task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True)
input_fingerprint: 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(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts')
@@ -0,0 +1,54 @@
"""
backend/app/models/shipping_notice_line.py
用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。
依赖:shipping_notices、shipping_order_snapshot_lines、SQLAlchemy Base。
逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingNoticeLine(Base):
"""
正式发货通知行投影。
核心逻辑:由 Snapshot 冻结路径幂等写入;position 在同一 Notice 内唯一。
"""
__tablename__ = 'shipping_notice_lines'
__table_args__ = (
UniqueConstraint('notice_id', 'position', name='uq_shipping_notice_lines_position'),
UniqueConstraint('notice_id', 'line_no', name='uq_shipping_notice_lines_line_no'),
Index('ix_shipping_notice_lines_notice_id', 'notice_id'),
Index('ix_shipping_notice_lines_snapshot_line_id', 'snapshot_line_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
notice_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'), nullable=False,
)
position: Mapped[int] = mapped_column(Integer, nullable=False)
# 发货通知项次:每个 Notice 从 1 开始连续编号,禁止使用导出序号或客户 PO 行号。
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
# 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True,
)
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,147 @@
"""
models/shipping_notice_line_inventory_match.py
用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。
依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。
逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingNoticeLineInventoryMatch(Base):
"""一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。"""
__tablename__ = 'shipping_notice_line_inventory_matches'
__table_args__ = (
UniqueConstraint(
'task_id',
'snapshot_line_id',
'inventory_snapshot_id',
name='uq_shipping_notice_line_inv_match_task_line_snap',
),
# 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。
Index(
'uq_shipping_notice_line_inv_match_current',
'task_id',
'snapshot_line_id',
unique=True,
postgresql_where=text('is_current IS TRUE'),
),
Index('ix_shipping_notice_line_inv_match_task', 'task_id'),
Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'),
Index('ix_shipping_notice_line_inv_match_snapshot', 'inventory_snapshot_id'),
CheckConstraint(
"match_result IN ("
"'matched', 'not_found', 'result_missing', 'preparing', "
"'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable', 'invalid'"
")",
name='ck_shipping_notice_line_inv_match_result',
),
CheckConstraint(
"inventory_status IN ("
"'ready', 'preparing', 'mapping_failed', 'source_conflict', "
"'unavailable', 'invalid_key', 'invalid'"
")",
name='ck_shipping_notice_line_inv_match_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='SET NULL'),
nullable=True,
)
snapshot_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'),
nullable=True,
index=True,
)
candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_line_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_lines.id', ondelete='SET NULL'),
nullable=True,
index=True,
)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'),
nullable=True,
)
match_result: Mapped[str] = mapped_column(String(32), nullable=False)
inventory_status: Mapped[str] = mapped_column(String(32), nullable=False)
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# BE-7:自动履约失败独立存储(非 decision_code 枚举)
auto_fulfill_failed: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=False, server_default='false',
)
auto_fulfill_error_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
auto_fulfill_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
auto_fulfill_failed_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,
)
# T6: 行级实际源证据(决策 E1 硬约束)——用于幂等保护与跨源匹配审计。
matched_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
matched_row_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
evidence_ref: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
allowed_source_codes_snapshot: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
matched_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
evidence_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
match_attempt_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'),
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)
superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True)
verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True)
@@ -0,0 +1,55 @@
"""
backend/app/models/shipping_order_candidate_evidence.py
用途:Candidate 主证据/辅助证据/冲突证据的可查询关系表(蓝图 §六)。
依赖:shipping_order_candidates、shipping_order_documents、SQLAlchemy Base。
逻辑:替代仅落在 Candidate.evidence_json 的不可查询结构;PDF 优先裁决审计可按字段检索。
"""
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
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderCandidateEvidence(Base):
"""
Candidate 与文档证据的角色化关联。
核心逻辑:primary_pdf 标识主证据;conflict 记录跨证据冲突;payload_json 存轻量引用非全文。
"""
__tablename__ = 'shipping_order_candidate_evidences'
__table_args__ = (
CheckConstraint(
"evidence_role IN ('primary_pdf', 'auxiliary', 'conflict', 'context')",
name='ck_shipping_order_candidate_evidences_role',
),
CheckConstraint(
"evidence_kind IN ('pdf', 'email_body', 'excel', 'word', 'image', 'ocr', 'model', 'other')",
name='ck_shipping_order_candidate_evidences_kind',
),
Index('ix_shipping_order_candidate_evidences_candidate', 'candidate_id'),
Index('ix_shipping_order_candidate_evidences_document', 'document_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_candidates.id', ondelete='CASCADE'), nullable=False,
)
document_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_documents.id', ondelete='SET NULL'), nullable=True,
)
evidence_role: Mapped[str] = mapped_column(String(32), nullable=False)
evidence_kind: Mapped[str] = mapped_column(String(32), nullable=False)
is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
field_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
value_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
decision_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,70 @@
"""
models/shipping_order_candidate_qualification.py
用途:持久化 Candidate 级统一自动建单资格评估快照(追加式历史)。
依赖:SQLAlchemy Base、shipping_order_candidates / shipping_order_processing_runs / users。
逻辑:每次评估追加一行;is_current 标记最新;模板质量信息仅出现在 parser_trace_json。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderCandidateQualification(Base):
"""Candidate 自动建单资格快照;同一 Candidate 可有多条历史评估。"""
__tablename__ = 'shipping_order_candidate_qualifications'
__table_args__ = (
UniqueConstraint(
'candidate_id',
'evaluation_seq',
name='ix_ship_order_cand_qual_candidate_seq',
),
CheckConstraint(
"status IN ('eligible', 'review_required', 'blocked', 'rejected')",
name='ck_shipping_order_candidate_qualifications_status',
),
Index(
'ix_ship_order_cand_qual_status_evaluated',
'status', 'evaluated_at',
),
Index(
'ix_ship_order_cand_qual_candidate_current',
'candidate_id', 'is_current',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_candidates.id'),
nullable=False,
index=True,
)
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'),
nullable=True,
index=True,
)
evaluation_seq: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
qualification_score: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
gate_results_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
blocking_reason_codes_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
parser_trace_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
evidence_snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
evaluator_version: Mapped[str] = mapped_column(String(64), nullable=False)
evaluated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
evaluated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), 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,
)
@@ -0,0 +1,304 @@
"""
backend/app/models/shipping_order_document_profile.py
用途:保存订单坐标 Profile 的版本、样本绑定、可选客户范围、版面签名引用与追加式配置审计。
依赖:订单 Schema、订单文档、用户和 SQLAlchemy Base。
逻辑:Profile 主表保存可索引摘要、scoring_policy_version 与当前有效版面签名轻量引用;
完整签名存 ValidationRun.result_snapshot_json;完整 v2 定义仍在 definition_json。
"""
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, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderDocumentProfile(Base):
"""版本化订单文档模板解析配置;published/retired 行不可原地修改。"""
__tablename__ = 'shipping_order_document_profiles'
__table_args__ = (
UniqueConstraint('profile_code', 'version', name='uq_shipping_order_document_profiles_code_version'),
CheckConstraint(
"status IN ('draft', 'published', 'retired')",
name='ck_shipping_order_document_profiles_status',
),
Index('ix_shipping_order_document_profiles_schema_status', 'schema_version_id', 'status'),
Index('ix_shipping_order_document_profiles_fingerprint', 'structure_fingerprint'),
Index('ix_shipping_order_document_profiles_mode_status', 'template_mode', 'status'),
Index(
'uq_shipping_order_document_profiles_one_published',
'profile_code',
unique=True,
postgresql_where=text("status = 'published'"),
sqlite_where=text("status = 'published'"),
),
Index('ix_shipping_order_document_profiles_matching_signature_run', 'matching_signature_run_id'),
Index('ix_shipping_order_document_profiles_matching_signature_checksum', 'matching_signature_checksum'),
)
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)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
schema_version_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=False,
)
structure_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
template_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='coordinate', server_default='coordinate')
training_sample_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
match_strategy_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
customer_ids_json: Mapped[Optional[list[int]]] = mapped_column(JSON, nullable=True)
scoring_policy_version: Mapped[str] = mapped_column(
String(64), nullable=False, default='order-profile-scoring.v1', server_default='order-profile-scoring.v1',
)
# 当前有效版面签名轻量引用;完整签名仅存在于 ValidationRun.result_snapshot_json。
matching_signature_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_document_profile_validation_runs.id',
ondelete='SET NULL',
use_alter=True,
name='fk_sodp_matching_signature_run',
),
nullable=True,
)
matching_signature_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matching_signature_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
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_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_profiles.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)
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,
)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
schema_version = relationship('ShippingOrderSchemaVersion')
source_profile: Mapped[Optional['ShippingOrderDocumentProfile']] = relationship(
remote_side='ShippingOrderDocumentProfile.id', foreign_keys=[source_profile_id],
)
matching_signature_run: Mapped[Optional['ShippingOrderDocumentProfileValidationRun']] = relationship(
'ShippingOrderDocumentProfileValidationRun',
foreign_keys=[matching_signature_run_id],
post_update=True,
)
class ShippingOrderDocumentProfileSample(Base):
"""绑定 Profile 与建模/盲测样本文档;不复制正文、PDF 或对象存储地址。"""
__tablename__ = 'shipping_order_document_profile_samples'
__table_args__ = (
CheckConstraint("sample_role IN ('annotation', 'training', 'blind_test')", name='ck_shipping_order_document_profile_samples_role'),
UniqueConstraint('profile_id', 'document_id', 'table_id', 'sample_role', name='uq_shipping_order_document_profile_samples_source_role'),
Index('ix_shipping_order_document_profile_samples_document', 'document_id'),
Index('ix_shipping_order_document_profile_samples_layout_version', 'layout_version_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
table_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
sample_role: Mapped[str] = mapped_column(String(16), nullable=False, default='annotation', server_default='annotation')
layout_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_layout_versions.id'), nullable=True,
)
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
layout_contract_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
parser_name: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
evidence_frozen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
source_filename_snapshot: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
page_count_snapshot: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
table_identity_snapshot: 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)
class ShippingOrderDocumentProfileAudit(Base):
"""追加式 Profile 操作审计;详情只保存无敏感值的结构摘要和对象身份。"""
__tablename__ = 'shipping_order_document_profile_audits'
__table_args__ = (
Index('ix_shipping_order_document_profile_audits_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_audits_profile_request', 'profile_id', 'request_id', 'id'),
Index('ix_shipping_order_document_profile_audits_operation', 'operation_id', 'id'),
Index('ix_shipping_order_document_profile_audits_document', 'document_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='SET NULL'), nullable=True)
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_documents.id', ondelete='SET NULL'), nullable=True)
event_type: Mapped[str] = mapped_column(String(48), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
browser_session_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
revision_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderDocumentProfileDraftRevision(Base):
"""草稿每次有效保存的不可变定义快照;同 checksum 重试只能复用同一修订。"""
__tablename__ = 'shipping_order_document_profile_draft_revisions'
__table_args__ = (
UniqueConstraint('profile_id', 'revision_no', name='uq_shipping_order_document_profile_draft_revisions_number'),
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_draft_revisions_operation'),
Index('ix_shipping_order_document_profile_draft_revisions_operation', 'operation_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
base_lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
result_lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
change_source: Mapped[str] = mapped_column(String(32), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
browser_session_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
change_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
definition_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderDocumentProfileEditLease(Base):
"""Profile 单写者编辑租约;令牌仅保存 SHA-256 哈希,不能从数据库还原。"""
__tablename__ = 'shipping_order_document_profile_edit_leases'
__table_args__ = (
UniqueConstraint('profile_id', name='uq_shipping_order_document_profile_edit_leases_profile'),
Index('ix_shipping_order_document_profile_edit_leases_expires', 'expires_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
lease_token_hash: Mapped[str] = mapped_column(String(64), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
browser_session_id: Mapped[str] = mapped_column(String(128), nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
last_renewed_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
taken_over_from_actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
class ShippingOrderDocumentProfileSuggestionDecision(Base):
"""冻结算法建议及管理员决定;建议永不直接覆盖已保存或人工画布配置。"""
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
__table_args__ = (
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'),
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'),
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
sample_binding_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_samples.id', ondelete='SET NULL'), nullable=True)
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_layout_versions.id'), nullable=True)
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
algorithm_version: Mapped[str] = mapped_column(String(64), nullable=False)
suggestion_id: Mapped[str] = mapped_column(String(64), nullable=False)
suggestion_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
decision: Mapped[str] = mapped_column(String(24), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderDocumentProfileValidationRun(Base):
"""不可变验证运行;输出绑定精确草稿 checksum,草稿变化后只能标记 stale 而不重写历史。"""
__tablename__ = 'shipping_order_document_profile_validation_runs'
__table_args__ = (
CheckConstraint(
"run_type IN ('instant_check', 'current_sample', 'blind_test', 'scenario_coverage', "
"'schema_compatibility', 'layout_signature', 'cross_template_overlap', 'xfa_structure_signature')",
name='ck_shipping_order_document_profile_validation_runs_type',
),
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
schema_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
sample_binding_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_samples.id', ondelete='SET NULL'), nullable=True)
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_layout_versions.id'), nullable=True)
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
run_type: Mapped[str] = mapped_column(String(32), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False)
summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
result_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
actor_id: 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 ShippingOrderDocumentProfilePublishCheckReport(Base):
"""不可变发布检查报告;只能由与冻结草稿完全一致的一次原子发布消费。"""
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
__table_args__ = (
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'),
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'),
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True),
)
id: Mapped[int] = mapped_column(primary_key=True)
report_no: Mapped[str] = mapped_column(String(64), nullable=False)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
validation_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'), nullable=True)
matching_signature_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'),
nullable=True,
)
matching_signature_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
overlap_validation_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'),
nullable=True,
)
matcher_policy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
base_published_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='SET NULL'), nullable=True)
semantic_diff_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
blocking_items_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
warning_items_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
confirmed_warning_keys_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='valid')
expires_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
@@ -0,0 +1,40 @@
"""
backend/app/models/shipping_order_document_version.py
用途:OT 文档/重识别版本台账(shipping_order_document_versions),对齐蓝图。
依赖:shipping_order_tasks、shipping_order_processing_runs、SQLAlchemy Base。
逻辑:每次新建/重识别 Run 挂到同一 OT 时追加版本;替代仅靠 Notice.document_version 的弱模型。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderDocumentVersion(Base):
"""
OT 下的文档识别版本。
核心逻辑:(order_task_id, version) 唯一;extraction_run_id 追溯本次识别。
"""
__tablename__ = 'shipping_order_document_versions'
__table_args__ = (
UniqueConstraint('order_task_id', 'version', name='uq_shipping_order_document_versions_task_version'),
Index('ix_shipping_order_document_versions_run', 'extraction_run_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
extraction_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='SET NULL'), nullable=True,
)
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,83 @@
"""
backend/app/models/shipping_order_extraction_quality.py
用途:保存订单抽取 L7 影子验收批次、双人匿名标签和双角色批准事实。
依赖:Agent、User、ShippingOrderSchemaVersion、ShippingOrderProcessingRun。
逻辑:批次锁定 owner/schema/阈值;同 Run 两名管理员标签一致后计入指标,达标后双人批准供 Runtime Binding 门禁引用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderExtractionQualityBatch(Base):
"""L7 影子验收批次;批准后成为不可变自动建单发布凭证。"""
__tablename__ = 'shipping_order_extraction_quality_batches'
__table_args__ = (
UniqueConstraint('batch_no', name='uq_shipping_order_extraction_quality_batches_no'),
CheckConstraint(
"status IN ('collecting', 'ready', 'approved', 'rejected')",
name='ck_shipping_order_extraction_quality_batches_status',
),
Index('ix_shipping_order_extraction_quality_batches_owner_created', 'owner_agent_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), nullable=False)
owner_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), nullable=False, index=True)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
threshold_version: Mapped[str] = mapped_column(String(32), nullable=False, default='l7.v1', server_default='l7.v1')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='collecting', server_default='collecting')
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
business_approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
business_approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
technical_approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
technical_approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
rejected_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
rejected_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
rejection_reason: Mapped[Optional[str]] = mapped_column(Text, 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)
labels: Mapped[list['ShippingOrderExtractionQualityLabel']] = relationship(
back_populates='batch', cascade='all, delete-orphan', order_by='ShippingOrderExtractionQualityLabel.id',
)
class ShippingOrderExtractionQualityLabel(Base):
"""单个管理员对真实 Run 提交的匿名质量计数;不保存订单字段值或正文。"""
__tablename__ = 'shipping_order_extraction_quality_labels'
__table_args__ = (
UniqueConstraint('batch_id', 'run_id', 'reviewer_id', name='uq_shipping_order_quality_label_reviewer'),
CheckConstraint('core_expected_count >= 0', name='ck_shipping_order_quality_expected_nonnegative'),
CheckConstraint('core_extracted_count >= 0', name='ck_shipping_order_quality_extracted_nonnegative'),
CheckConstraint('core_correct_count >= 0', name='ck_shipping_order_quality_correct_nonnegative'),
Index('ix_shipping_order_quality_labels_batch_run', 'batch_id', 'run_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_extraction_quality_batches.id', ondelete='CASCADE'), nullable=False,
)
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id'), nullable=False)
reviewer_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
core_expected_count: Mapped[int] = mapped_column(Integer, nullable=False)
core_extracted_count: Mapped[int] = mapped_column(Integer, nullable=False)
core_correct_count: Mapped[int] = mapped_column(Integer, nullable=False)
wrong_merge: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
wrong_split: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
wrong_auto_create: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
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)
batch: Mapped['ShippingOrderExtractionQualityBatch'] = relationship(back_populates='labels')
@@ -0,0 +1,501 @@
"""
backend/app/models/shipping_order_extraction_run.py
用途:定义建单前订单 Processing Run 的领域运行记录及其冻结 Intake 集合。
物理表名:shipping_order_processing_runs / _run_intakes / _plans / _units /
shipping_order_route_decisions(本文件名保留以减少 import 变更)。
依赖:agents、users、jobs、shipping_order_intakes、shipping_order_schema_versions。
逻辑:Run 保存用户可见生命周期和不可变输入快照;自动建单策略随 Schema 快照冻结。
取消为请求语义:cancellation_* 元数据记录请求与生效;Worker 在安全点收口,
progress_version 作为最后活动版本供轮询与乐观协作。
会话多任务聚合(2026-08-03 阶段 1):用户可见任务(OT-…)与内部 Run(WF-/SNER-…)分层;
已移除 uq_*_active_conversation,同会话允许多个 queued|processing Run;
统一提交靠 can_append / composer_context / focused_user_task 裁决追加或新建。
upload_batch_id 仅隔离 Intake 选择,不得充当 user_task_no;
user_task_no 延迟至 Candidate/OT 形成后分配(nullable);reparse/后继 Run 继承谱系 OT。
client_submission_id 为客户端幂等键(与 user_id 部分唯一);
根任务 submission_ordinal 在 (user_id, conversation_id) 上部分唯一。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
ForeignKeyConstraint,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _default_user_task_no() -> str:
"""生成默认用户可见任务号;正式创建路径会覆盖为与 Run 对齐的 OT- 编号。"""
return f"OT-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
class ShippingOrderProcessingRun(Base):
"""一次建单前订单 Processing 业务运行;状态只允许按领域状态机单调推进。"""
__tablename__ = 'shipping_order_processing_runs'
__table_args__ = (
UniqueConstraint('run_no', name='uq_shipping_order_processing_runs_no'),
UniqueConstraint('idempotency_key', name='uq_shipping_order_processing_runs_idempotency'),
CheckConstraint(
"status IN ('queued', 'processing', 'completed', "
"'partially_completed', 'review_required', 'failed', 'cancelled')",
name='ck_shipping_order_processing_runs_status',
),
CheckConstraint(
"input_lifecycle IN ('open', 'freezing', 'frozen', 'closed')",
name='ck_shipping_order_processing_runs_input_lifecycle',
),
Index('ix_shipping_order_processing_runs_user_created', 'user_id', 'created_at'),
Index('ix_shipping_order_processing_runs_conversation_created', 'conversation_id', 'created_at'),
Index('ix_shipping_order_processing_runs_status_created', 'status', 'created_at'),
# 阶段 1:非唯一查询索引,替代原 partial unique(同会话多活跃 Run)。
Index(
'ix_shipping_order_processing_runs_conversation_status',
'user_id',
'owner_agent_id',
'conversation_id',
'status',
),
Index(
'ix_shipping_order_processing_runs_user_task_no',
'user_task_no',
),
Index(
'uq_shipping_order_processing_runs_client_submission',
'user_id',
'client_submission_id',
unique=True,
postgresql_where=text('client_submission_id IS NOT NULL'),
sqlite_where=text('client_submission_id IS NOT NULL'),
),
# 根任务(非 reparse/后继)会话内提交序号唯一;后继 Run 可继承同一序号。
Index(
'uq_shipping_order_processing_runs_submission_ordinal',
'user_id',
'conversation_id',
'submission_ordinal',
unique=True,
postgresql_where=text(
'reparse_of_run_id IS NULL AND submission_ordinal IS NOT NULL'
),
sqlite_where=text(
'reparse_of_run_id IS NULL AND submission_ordinal IS NOT NULL'
),
),
Index(
'ix_shipping_order_processing_runs_cancel_requested',
'cancellation_requested_at',
'status',
),
CheckConstraint(
"cancellation_actor_type IS NULL OR cancellation_actor_type IN "
"('user', 'admin', 'system')",
name='ck_shipping_order_processing_runs_cancel_actor',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
# 用户可见任务号(OT-…);Candidate/OT 形成前为 NULL;reparse 继承源号。
user_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
owner_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), nullable=False, index=True)
parser_engine_version: Mapped[str] = mapped_column(String(64), nullable=False, default='deterministic-order-parser.v1')
parser_policy_version: Mapped[str] = mapped_column(String(64), nullable=False, default='deterministic-order-policy.v1')
auto_freeze_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 重新识别创建新 Run;谱系字段保留旧结果,禁止用原地覆盖破坏审计事实。
reparse_of_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
)
superseded_by_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
)
reparse_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
reparse_comment: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
schema_version_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=False,
)
# 请求快照是发送时的审计与幂等锚点;Worker 后续可物化 input_snapshot_* 作为执行快照。
request_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
request_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
phase: Mapped[str] = mapped_column(String(64), nullable=False, default='queued', server_default='queued')
# 用户可见任务输入生命周期;前端只消费 can_append,不展示原文案。
input_lifecycle: Mapped[str] = mapped_column(
String(16), nullable=False, default='open', server_default='open',
)
input_frozen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
composer_context_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
submission_ordinal: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# 客户端提交幂等键;与 user_id 组成部分唯一索引。
client_submission_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
current_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True, index=True)
execution_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
extraction_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
attempt_count: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 当前投影只包含用户安全的阶段事实;高频原始事件写入独立明细表。
progress_version: Mapped[int] = mapped_column(Integer, default=1, server_default='1', nullable=False)
current_stage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
active_stage_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
completed_stage_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
progress_message_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
progress_health: Mapped[str] = mapped_column(String(32), default='normal', server_default='normal', nullable=False)
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
progress_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
progress_mapping_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
attention_generated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# 取消请求元数据:请求不等于生效;排队 Unit 可立即 cancelled,执行中须等安全检查点。
cancellation_requested_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
cancellation_actor_type: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
cancellation_actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
cancellation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
cancellation_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
cancellation_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, default=1, server_default='1', nullable=False)
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,
)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
result_persisted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
intakes: Mapped[list['ShippingOrderProcessingRunIntake']] = relationship(
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderProcessingRunIntake.position',
)
reparse_source: Mapped[Optional['ShippingOrderProcessingRun']] = relationship(
'ShippingOrderProcessingRun', foreign_keys=[reparse_of_run_id], remote_side='ShippingOrderProcessingRun.id',
)
superseding_run: Mapped[Optional['ShippingOrderProcessingRun']] = relationship(
'ShippingOrderProcessingRun', foreign_keys=[superseded_by_run_id], remote_side='ShippingOrderProcessingRun.id',
)
extraction_plan: Mapped[Optional['ShippingOrderProcessingPlan']] = relationship(
back_populates='run', cascade='all, delete-orphan', uselist=False,
)
route_decisions: Mapped[list['ShippingOrderRouteDecision']] = relationship(
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderRouteDecision.id',
)
review_cases: Mapped[list['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', back_populates='run', cascade='all, delete-orphan',
order_by='ShippingOrderReviewCase.id',
)
class ShippingOrderProcessingRunIntake(Base):
"""Run 冻结的 Intake 成员;position 保证输入集合顺序稳定且可审计。"""
__tablename__ = 'shipping_order_processing_run_intakes'
__table_args__ = (
UniqueConstraint('run_id', 'intake_id', name='uq_shipping_order_processing_run_intake'),
UniqueConstraint('run_id', 'position', name='uq_shipping_order_processing_run_position'),
Index('ix_shipping_order_processing_run_intakes_intake', 'intake_id'),
# 同一 EML Intake 可由批次重解析拆成多个、各自冻结一个 PDF 的子 Run。
# 并发互斥改由创建服务在锁定 Intake 后按目标 Document 裁决;不能再用
# Intake 单列唯一索引,否则第二份 PDF 会被错误拒绝。
Index(
'ix_shipping_order_processing_run_intakes_active_intake',
'intake_id',
postgresql_where=text('released_at IS NULL'),
sqlite_where=text('released_at IS NULL'),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
)
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
released_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='intakes')
class ShippingOrderProcessingPlan(Base):
"""Run 的不可变抽取计划;计划版本和快照哈希共同锚定冻结输入。"""
__tablename__ = 'shipping_order_processing_plans'
__table_args__ = (
UniqueConstraint('run_id', name='uq_shipping_order_processing_plans_run'),
CheckConstraint(
"status IN ('planned', 'running', 'completed', 'partial_failed', 'failed')",
name='ck_shipping_order_processing_plans_status',
),
Index('ix_shipping_order_processing_plans_status_created', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
)
# 版本标识是稳定的可读契约,须容纳带业务命名空间的版本号。
plan_version: Mapped[str] = mapped_column(String(64), nullable=False)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='planned', server_default='planned')
unit_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
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,
)
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='extraction_plan')
units: Mapped[list['ShippingOrderProcessingUnit']] = relationship(
back_populates='plan', cascade='all, delete-orphan', order_by='ShippingOrderProcessingUnit.position',
)
class ShippingOrderProcessingUnit(Base):
"""计划内单个冻结附件抽取单元;状态、选择事实和错误相互隔离。"""
__tablename__ = 'shipping_order_processing_units'
__table_args__ = (
UniqueConstraint('plan_id', 'document_id', name='uq_shipping_order_processing_units_document'),
UniqueConstraint('plan_id', 'position', name='uq_shipping_order_processing_units_position'),
CheckConstraint(
"unit_type IN ('document_extraction', 'email_relation')",
name='ck_shipping_order_processing_units_type',
),
CheckConstraint(
"status IN ('pending', 'routing', 'matching_profile', 'extracting', "
"'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled')",
name='ck_shipping_order_processing_units_status',
),
ForeignKeyConstraint(
['document_id', 'intake_id'],
['shipping_order_documents.id', 'shipping_order_documents.intake_id'],
name='fk_shipping_order_processing_units_document_intake',
),
Index('ix_shipping_order_processing_units_plan_status', 'plan_id', 'status'),
Index('ix_shipping_order_processing_units_document', 'document_id'),
Index(
'ix_shipping_order_processing_units_cancel_requested',
'cancellation_requested_at',
'status',
),
CheckConstraint(
"cancellation_actor_type IS NULL OR cancellation_actor_type IN "
"('user', 'admin', 'system')",
name='ck_shipping_order_processing_units_cancel_actor',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
plan_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_plans.id', ondelete='CASCADE'), nullable=False,
)
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=False)
document_id: Mapped[int] = mapped_column(nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
unit_type: Mapped[str] = mapped_column(String(32), nullable=False)
document_type: Mapped[str] = mapped_column(String(32), nullable=False)
content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
selection_batch: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
selection_reason_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
group_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
budget_cost_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
retry_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
technical_failure_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
attempt_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# 单 Unit 活动版本;取消/重试与状态迁移同事务递增,供乐观协作与投影。
activity_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
cancellation_requested_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
cancellation_actor_type: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
cancellation_actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
cancellation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
cancellation_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
cancellation_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_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,
)
plan: Mapped['ShippingOrderProcessingPlan'] = relationship(back_populates='units')
route_decisions: Mapped[list['ShippingOrderRouteDecision']] = relationship(
back_populates='unit', cascade='all, delete-orphan', order_by='ShippingOrderRouteDecision.id',
)
review_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', back_populates='unit', uselist=False,
)
class ShippingOrderRouteDecision(Base):
"""Unit 每次模板分流的不可变脱敏审计;禁止存储文档、字段值和 Provider 输入。"""
__tablename__ = 'shipping_order_route_decisions'
__table_args__ = (
UniqueConstraint('unit_id', 'job_id', 'attempt_no', name='uq_shipping_order_route_decision_attempt'),
CheckConstraint(
"decision IN ('deterministic', 'review_required', 'skipped')",
name='ck_shipping_order_route_decision',
),
CheckConstraint(
"match_status IN ("
"'unique_match', 'selected_by_score', 'no_special_profile_feature', "
"'no_match', 'ambiguous', 'layout_drift', 'evidence_insufficient'"
")",
name='ck_shipping_order_route_match_status',
),
Index('ix_shipping_order_route_decisions_run_unit', 'run_id', 'unit_id', 'id'),
Index('ix_shipping_order_route_decisions_unit_created', 'unit_id', 'created_at'),
Index('ix_shipping_order_route_decisions_profile_id', 'selected_profile_id', 'id'),
Index(
'ix_shipping_order_route_decisions_profile_snapshot',
'selected_profile_code', 'selected_profile_version', 'selected_profile_checksum', 'id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False)
unit_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=False)
job_id: Mapped[int] = mapped_column(ForeignKey('jobs.id'), nullable=False)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
decision: Mapped[str] = mapped_column(String(16), nullable=False)
match_status: Mapped[str] = mapped_column(String(32), nullable=False)
selected_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=True)
selected_profile_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
selected_profile_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
selected_profile_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
auto_create_approved: Mapped[Optional[bool]] = mapped_column(nullable=True)
candidate_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
document_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
business_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
matched_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
parsed_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
approved_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
candidate_summary_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
fallback_reason_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='route_decisions')
unit: Mapped['ShippingOrderProcessingUnit'] = relationship(back_populates='route_decisions')
class ShippingOrderExtractionProgressEvent(Base):
"""订单抽取的可恢复业务事件;用户态与管理员态通过 visibility 隔离。"""
__tablename__ = 'shipping_order_extraction_progress_events'
__table_args__ = (
UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_progress_event_key'),
UniqueConstraint('run_id', 'sequence_no', name='uq_shipping_order_extraction_progress_event_sequence'),
Index('ix_shipping_order_extraction_progress_events_run_sequence', 'run_id', 'sequence_no'),
Index('ix_shipping_order_extraction_progress_events_expires_id', 'expires_at', 'id'),
Index('ix_shipping_order_extraction_progress_events_run_visibility', 'run_id', 'visibility', 'sequence_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False)
unit_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=True)
document_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True)
attempt_count: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
sequence_no: Mapped[int] = mapped_column(Integer, nullable=False)
visibility: Mapped[str] = mapped_column(String(32), nullable=False, default='workspace', server_default='workspace')
event_code: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='completed', server_default='completed')
occurred_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
received_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
mapping_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderExtractionSubmission(Base):
"""
统一提交幂等记录:每次用户发送独立一行,禁止用 Run.client_submission_id 覆盖历史键。
用途:submission_id 重放只返回原决策;追加不会破坏更早的 submission 幂等。
"""
__tablename__ = 'shipping_order_extraction_submissions'
__table_args__ = (
UniqueConstraint(
'user_id', 'submission_id',
name='uq_shipping_order_extraction_submissions_user_submission',
),
Index(
'ix_shipping_order_extraction_submissions_run',
'run_id',
),
Index(
'ix_shipping_order_extraction_submissions_conversation',
'user_id',
'conversation_id',
'created_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
submission_id: 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)
user_task_no: Mapped[str] = mapped_column(String(64), nullable=False)
run_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'),
nullable=False,
)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
decision: Mapped[str] = mapped_column(String(32), nullable=False)
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
composer_context_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
intake_nos_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
appended_intake_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderExtractionDiagnosticAudit(Base):
"""管理员订单抽取诊断访问审计;不记录Run业务正文或原始筛选参数。"""
__tablename__ = 'shipping_order_extraction_diagnostic_audits'
__table_args__ = (
Index('ix_shipping_order_extraction_diagnostic_audits_run_created', 'run_id', 'created_at'),
Index('ix_shipping_order_extraction_diagnostic_audits_admin_created', 'admin_user_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
admin_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_processing_runs.id'), nullable=True)
action: Mapped[str] = mapped_column(String(64), nullable=False)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
query_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+224
View File
@@ -0,0 +1,224 @@
"""
建单前订单人工复核领域模型。
依赖:订单抽取 Run/Unit、候选 Candidate、用户和后续 ShippingNotice、
ShippingOrderReviewLineDecision(行级履约决定)、
ShippingOrderReviewWaveLine(波次行不可变归属)。
逻辑:ReviewStream 是文件级复核主线,Case 是该主线的一次不可变复核版本;
Draft 保存独立人工版本,机器 Candidate 始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task;
行级决定支持完整明细先行履约波次,禁止拆分数量;
wave_lines 保证同一 (case, snapshot_line_id) 最多关联一个 task_id。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderReviewStream(Base):
"""一个原始订单文件的复核主线;唯一保存当前可操作 Case 的裁决事实。"""
__tablename__ = 'shipping_order_review_streams'
__table_args__ = (
UniqueConstraint('document_id', name='uq_shipping_order_review_streams_document'),
UniqueConstraint('current_case_id', name='uq_shipping_order_review_streams_current_case'),
UniqueConstraint('confirmed_case_id', name='uq_shipping_order_review_streams_confirmed_case'),
CheckConstraint(
"state IN ('active', 'reparsing', 'confirmed', 'closed', 'conflict')",
name='ck_shipping_order_review_streams_state',
),
Index('ix_shipping_order_review_streams_owner_state_updated', 'owner_user_id', 'state', 'updated_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
content_identity: Mapped[str] = mapped_column(String(96), nullable=False)
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
current_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', use_alter=True, name='fk_shipping_order_review_streams_current_case'),
nullable=True,
)
confirmed_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', use_alter=True, name='fk_shipping_order_review_streams_confirmed_case'),
nullable=True,
)
state: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
revision: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
current_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', foreign_keys=[current_case_id], post_update=True,
)
confirmed_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', foreign_keys=[confirmed_case_id], post_update=True,
)
cases: Mapped[list['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', back_populates='stream', foreign_keys='ShippingOrderReviewCase.stream_id',
order_by='ShippingOrderReviewCase.revision_no',
)
class ShippingOrderReviewCase(Base):
"""一份 PDF 的建单前复核生命周期;终态 Case 不允许后续草稿写入。"""
__tablename__ = 'shipping_order_review_cases'
__table_args__ = (
UniqueConstraint('case_no', name='uq_shipping_order_review_cases_no'),
UniqueConstraint('unit_id', name='uq_shipping_order_review_cases_unit'),
UniqueConstraint('confirmed_task_id', name='uq_shipping_order_review_cases_confirmed_task'),
CheckConstraint(
"status IN ('unreviewed', 'draft', 'ready', 'confirming', 'confirmed', "
"'non_order', 'quality_issue', 'reparse_pending', 'superseded')",
name='ck_shipping_order_review_cases_status',
),
Index('ix_shipping_order_review_cases_run_status', 'run_id', 'status'),
Index('ix_shipping_order_review_cases_owner_updated', 'owner_user_id', 'updated_at'),
UniqueConstraint('stream_id', 'revision_no', name='uq_shipping_order_review_cases_stream_revision'),
Index('ix_shipping_order_review_cases_stream_revision', 'stream_id', 'revision_no'),
Index('ix_shipping_order_review_cases_supersedes', 'supersedes_case_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_no: Mapped[str] = mapped_column(String(64), nullable=False)
run_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
)
unit_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=False,
)
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
stream_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_review_streams.id'), nullable=True)
revision_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
supersedes_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_review_cases.id'), nullable=True)
superseded_by_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_review_cases.id'), nullable=True)
became_current_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
candidate_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_candidates.id'), nullable=True)
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unreviewed', server_default='unreviewed')
disposition: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
current_draft_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'),
nullable=True,
)
confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.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)
run: Mapped['ShippingOrderProcessingRun'] = relationship('ShippingOrderProcessingRun', back_populates='review_cases')
stream: Mapped[Optional['ShippingOrderReviewStream']] = relationship(
'ShippingOrderReviewStream', back_populates='cases', foreign_keys=[stream_id],
)
supersedes_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', foreign_keys=[supersedes_case_id], remote_side='ShippingOrderReviewCase.id',
)
superseded_by_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', foreign_keys=[superseded_by_case_id], remote_side='ShippingOrderReviewCase.id',
)
unit: Mapped['ShippingOrderProcessingUnit'] = relationship('ShippingOrderProcessingUnit', back_populates='review_case')
current_draft: Mapped[Optional['ShippingOrderReviewDraft']] = relationship(
'ShippingOrderReviewDraft', foreign_keys=[current_draft_id], post_update=True,
)
drafts: Mapped[list['ShippingOrderReviewDraft']] = relationship(
'ShippingOrderReviewDraft', back_populates='case', foreign_keys='ShippingOrderReviewDraft.case_id',
cascade='all, delete-orphan', order_by='ShippingOrderReviewDraft.draft_version',
)
llm_suggestions: Mapped[list['ShippingOrderReviewSuggestion']] = relationship(
'ShippingOrderReviewSuggestion', back_populates='case', cascade='all, delete-orphan',
order_by='ShippingOrderReviewSuggestion.created_at.desc()',
)
line_decisions: Mapped[list['ShippingOrderReviewLineDecision']] = relationship(
'ShippingOrderReviewLineDecision',
back_populates='case',
cascade='all, delete-orphan',
order_by='ShippingOrderReviewLineDecision.draft_line_id, ShippingOrderReviewLineDecision.decision_version',
)
wave_lines: Mapped[list['ShippingOrderReviewWaveLine']] = relationship(
'ShippingOrderReviewWaveLine',
back_populates='case',
cascade='all, delete-orphan',
order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.snapshot_line_id',
)
class ShippingOrderReviewDraft(Base):
"""当前人工草稿;阶段 1 只初始化和投影,阶段 3 才允许写入。"""
__tablename__ = 'shipping_order_review_drafts'
__table_args__ = (
UniqueConstraint('case_id', 'draft_version', name='uq_shipping_order_review_drafts_case_version'),
CheckConstraint('draft_version >= 1', name='ck_shipping_order_review_drafts_version'),
Index('ix_shipping_order_review_drafts_case_updated', 'case_id', 'updated_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
)
draft_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
issue_summary_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
validation_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
change_reason_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
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)
case: Mapped['ShippingOrderReviewCase'] = relationship(
'ShippingOrderReviewCase', back_populates='drafts', foreign_keys=[case_id],
)
class ShippingOrderReviewCaseEvent(Base):
"""复核域追加审计事件;阶段 3 起记录每项草稿变更,阶段 1 记录初始化事实。"""
__tablename__ = 'shipping_order_review_case_events'
__table_args__ = (
Index('ix_shipping_order_review_case_events_case_occurred', 'case_id', 'occurred_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False)
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
draft_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
actor_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
operation_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
occurred_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderReviewConfirmedRevision(Base):
"""一次不可变建单确认快照;同一 Case 可对应多个履约波次 Task。"""
__tablename__ = 'shipping_order_review_confirmed_revisions'
__table_args__ = (
UniqueConstraint('case_id', 'task_id', name='uq_shipping_order_review_confirmed_revisions_case_task'),
UniqueConstraint('idempotency_key', name='uq_shipping_order_review_confirmed_revisions_idempotency'),
Index('ix_shipping_order_review_confirmed_revisions_task', 'task_id'),
Index('ix_shipping_order_review_confirmed_revisions_case', 'case_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
draft_version: Mapped[int] = mapped_column(Integer, nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
validation_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
warning_acknowledgements_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
confirmed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
confirmed_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,87 @@
"""
models/shipping_order_review_line_decision.py
用途:复核 Case 的行级履约决定(版本化、可追溯);含 OT 后系统/人工来源。
依赖:ShippingOrderReviewCase、ShippingOrderTask、users。
逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, draft_line_id, version) 唯一;
活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联;
decision_source 区分 system/user(历史可空)。
"""
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 ShippingOrderReviewLineDecision(Base):
"""一条订单明细的履约决定版本;禁止拆分数量。"""
__tablename__ = 'shipping_order_review_line_decisions'
__table_args__ = (
UniqueConstraint(
'review_case_id',
'draft_line_id',
'decision_version',
name='uq_shipping_review_line_decisions_case_line_ver',
),
CheckConstraint(
"decision_code IN ("
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'"
")",
name='ck_shipping_review_line_decisions_code',
),
CheckConstraint(
"line_status IN ("
"'pending_decision', 'waiting_inventory', 'ready_to_fulfill', "
"'task_created', 'fulfilled', 'closed_unfulfillable', 'reopened', 'released_shortage'"
")",
name='ck_shipping_review_line_decisions_status',
),
CheckConstraint(
"decision_source IS NULL OR decision_source IN ('system', 'user', 'unknown')",
name='ck_shipping_review_line_decisions_source',
),
CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'),
Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'draft_line_id'),
Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'),
Index('ix_shipping_review_line_decisions_task', 'task_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
draft_line_id: Mapped[str] = mapped_column(String(64), nullable=False)
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
decision_code: Mapped[str] = mapped_column(String(48), nullable=False)
line_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending_decision')
is_active: Mapped[bool] = mapped_column(nullable=False, default=True, server_default='true')
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# system=自动履约;user=人工异常/显式履约;unknown=历史无法判定。
decision_source: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
actor_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
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,
)
case: Mapped['ShippingOrderReviewCase'] = relationship(
'ShippingOrderReviewCase',
back_populates='line_decisions',
)
@@ -0,0 +1,105 @@
"""
backend/app/models/shipping_order_review_suggestion.py
用途:持久化订单复核 LLM 建议请求、验证结果与人工裁决。
依赖:SQLAlchemy Base、Review Case / Document 外键。
逻辑:
- 建议只能预填草稿;accept/modify/reject 写入裁决字段;不得自动冻结。
- v2:新增 status=gated_failed;evidence_level 扩展新枚举;
新增 8 个 provider & trace 独立列;旧数据不 backfill。
"""
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
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderReviewSuggestion(Base):
"""一次最小证据 LLM 建议及其人工裁决记录。"""
__tablename__ = 'shipping_order_review_suggestions'
__table_args__ = (
UniqueConstraint('suggestion_no', name='uq_shipping_order_review_suggestions_no'),
CheckConstraint(
"status IN ('pending', 'gated_failed', 'validated', 'validation_failed', "
"'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable')",
name='ck_shipping_order_review_suggestions_status',
),
CheckConstraint(
"evidence_level IN ("
"'L1_field', 'L2_table', 'L3_page', 'L4_pdf', "
"'L2_row', 'L3_table', 'L4_page', 'L5_document')",
name='ck_shipping_order_review_suggestions_evidence_level',
),
CheckConstraint(
"decision IS NULL OR decision IN ('accept', 'modify', 'reject')",
name='ck_shipping_order_review_suggestions_decision',
),
Index('ix_shipping_order_review_suggestions_case', 'review_case_id', 'created_at'),
Index('ix_shipping_order_review_suggestions_document', 'document_id', 'id'),
Index(
'ix_shipping_order_review_suggestions_provider_conversation',
'provider_conversation_id',
),
Index(
'ix_shipping_order_review_suggestions_context_hash',
'context_hash',
),
Index(
'ix_shipping_order_review_suggestions_status_created',
'status', 'created_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
suggestion_no: Mapped[str] = mapped_column(String(64), nullable=False)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
)
document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_documents.id'), nullable=False,
)
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True,
)
field_id: Mapped[str] = mapped_column(String(64), nullable=False)
draft_line_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
scope: Mapped[str] = mapped_column(String(16), nullable=False, default='header', server_default='header')
evidence_level: Mapped[str] = mapped_column(String(16), nullable=False, default='L1_field')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
contract_version: Mapped[str] = mapped_column(String(64), nullable=False)
draft_version_at_request: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
request_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
validated_suggestions_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
validation_issues_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
suggested_value_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
decision: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
decision_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
decision_note: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
decided_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
decided_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
requested_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(String(512), 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,
)
# —— v2 新增列:provider & trace 独立列;历史数据保持 NULL/默认值,不回填
provider: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
provider_conversation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
provider_message_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
latency_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
context_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
evidence_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
context_truncated: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default='false')
auto_upgrade_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
case = relationship('ShippingOrderReviewCase', back_populates='llm_suggestions')
@@ -0,0 +1,67 @@
"""
models/shipping_order_review_wave_idempotency.py
用途:post-OT 履约 wave 请求幂等表(idempotency_key → wave 身份),无 wave 主表时提供强约束。
依赖:shipping_order_review_cases、shipping_order_tasks。
逻辑:create_post_ot_fulfillment_wave 写入/回放;同 key 参数不一致 → 409;
progress_* 记录本 wave Excel/RPA 推进状态(失败不回滚已提交 wave)。
"""
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 ShippingOrderReviewWaveIdempotency(Base):
"""一次 post-OT wave 创建请求的幂等记录。"""
__tablename__ = 'shipping_order_review_wave_idempotency'
__table_args__ = (
UniqueConstraint(
'idempotency_key',
name='uq_shipping_review_wave_idempotency_key',
),
Index('ix_shipping_review_wave_idempotency_case', 'review_case_id'),
Index('ix_shipping_review_wave_idempotency_task', 'task_id'),
Index('ix_shipping_review_wave_idempotency_wave', 'review_case_id', 'wave_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
idempotency_key: Mapped[str] = mapped_column(String(191), nullable=False)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False,
)
task_no: Mapped[str] = mapped_column(String(64), nullable=False)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_source: Mapped[str] = mapped_column(String(16), nullable=False)
# 稳定排序后的冻结订单行 ID 数组指纹(冲突比对)。
snapshot_line_ids_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
snapshot_line_ids_hash: Mapped[str] = mapped_column(String(64), nullable=False)
# 行集合共享快照 ID;多快照时为空,靠 fingerprint 比对。
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
inventory_snapshot_fingerprint: Mapped[str] = mapped_column(String(256), nullable=False, default='')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='succeeded')
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 本 wave 下游推进(Excel/RPA);失败不回滚 wave 创建事实。
progress_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending')
progress_job_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
progress_error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
progress_idempotency_key: Mapped[Optional[str]] = mapped_column(String(191), 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,
)
@@ -0,0 +1,55 @@
"""
models/shipping_order_review_wave_line.py
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。
依赖:ShippingOrderReviewCase、ShippingOrderTask、ShippingOrderReviewConfirmedRevision。
逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入;
(review_case_id, snapshot_line_id) 数据库唯一约束防并发重复入波次。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderReviewWaveLine(Base):
"""一条复核明细行与履约 Task 的不可变归属记录。"""
__tablename__ = 'shipping_order_review_wave_lines'
__table_args__ = (
UniqueConstraint(
'review_case_id',
'snapshot_line_id',
name='uq_shipping_review_wave_lines_case_line',
),
Index('ix_shipping_review_wave_lines_task', 'task_id'),
Index('ix_shipping_review_wave_lines_case_wave', 'review_case_id', 'wave_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
snapshot_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'),
nullable=False,
)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
wave_no: Mapped[int] = mapped_column(Integer, nullable=False)
confirmed_revision_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'),
nullable=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
case: Mapped['ShippingOrderReviewCase'] = relationship(
'ShippingOrderReviewCase',
back_populates='wave_lines',
)
+371
View File
@@ -0,0 +1,371 @@
"""
backend/app/models/shipping_order_schema.py
用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。
依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。
逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json;
definition_json 含 fields / auto_creation_policy;
写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。
"""
from __future__ import annotations
import uuid
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
Date,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
Numeric,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _uuid() -> str:
"""生成跨 PostgreSQL/SQLite 通用的 UUID 字符串主键。"""
return str(uuid.uuid4())
def _default_field_category(context: Any) -> str:
"""为未显式分类的既有 ORM 创建路径按 scope 生成订单字段分类。"""
return 'order_line' if context.get_current_parameters().get('scope') == 'line' else 'order_header'
class ShippingOrderSchema(Base):
"""Schema 族容器;本轮默认族编码 STANDARD_SHIPPING_NOTICE,模型允许多族。"""
__tablename__ = 'shipping_order_schemas'
id: Mapped[int] = mapped_column(primary_key=True)
schema_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
auto_creation_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
versions: Mapped[list['ShippingOrderSchemaVersion']] = relationship(
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderSchemaVersion.version'
)
ShippingSchemaFamily = ShippingOrderSchema
class ShippingOrderField(Base):
"""全局字段资产(系统标准或扩展)。标准不可弃用/删除;扩展仅 active⇄retired。"""
__tablename__ = 'shipping_order_fields'
__table_args__ = (
# Header/Line may intentionally share a business code (for example
# reservation_id); scope is part of the asset identity.
UniqueConstraint('field_code', 'scope', name='uq_shipping_order_fields_code_scope'),
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'),
CheckConstraint(
"field_category IN ('general_context', 'order_header', 'order_line')",
name='ck_shipping_order_fields_category',
),
CheckConstraint(
"collection_mode IN ('deterministic_context', 'llm_extraction')",
name='ck_shipping_order_fields_collection_mode',
),
CheckConstraint(
"value_type IN ('string', 'decimal', 'integer', 'date', 'boolean', 'enum')",
name='ck_shipping_order_fields_value_type',
),
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_order_fields_status'),
CheckConstraint(
"asset_kind IN ('system_standard', 'extension')",
name='ck_shipping_order_fields_asset_kind',
),
CheckConstraint(
"storage_mode IN ('typed_column', 'json_only')",
name='ck_shipping_order_fields_storage_mode',
),
Index('ix_shipping_order_fields_scope_status', 'scope', 'status'),
Index('ix_shipping_order_fields_asset_kind', 'asset_kind'),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
scope: Mapped[str] = mapped_column(String(16), nullable=False)
value_type: Mapped[str] = mapped_column(String(16), nullable=False)
field_category: Mapped[str] = mapped_column(String(32), nullable=False, default=_default_field_category)
collection_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='llm_extraction')
asset_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='extension', server_default='extension')
storage_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='json_only', server_default='json_only')
storage_column: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
semantic_description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
display_name_default: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
fulfillment_role: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
display_sequence: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
published_once: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
retired_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
retired_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
restored_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
restored_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
ShippingFieldAsset = ShippingOrderField
class ShippingOrderSchemaVersion(Base):
"""
订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。
definition_json 契约要点:
- fields[]:字段采用与识别规则
- auto_creation_policy:自动建单策略
- line_no:运行时按 Extraction 内明细顺序生成,不属于 Schema 配置或派生规则。
"""
__tablename__ = 'shipping_order_schema_versions'
__table_args__ = (
UniqueConstraint('schema_id', 'version', name='uq_shipping_order_schema_versions_schema_version'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_order_schema_versions_status'),
Index(
'uq_shipping_order_schema_one_published',
'schema_id',
unique=True,
postgresql_where=text("status = 'published'"),
sqlite_where=text("status = 'published'"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
source_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=True
)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
schema: Mapped['ShippingOrderSchema'] = relationship(back_populates='versions')
source_version: Mapped[Optional['ShippingOrderSchemaVersion']] = relationship(
remote_side='ShippingOrderSchemaVersion.id', foreign_keys=[source_version_id]
)
class ShippingOrderSchemaAuditEvent(Base):
"""字段资产与 Schema 配置的追加式审计事件;不提供修改入口。"""
__tablename__ = 'shipping_order_schema_audit_events'
__table_args__ = (
CheckConstraint(
"event_type IN ("
"'draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', "
"'field_saved', 'field_retired', 'field_restored', "
"'extension_created', 'extension_updated', 'extension_retired', 'extension_restored', "
"'family_created', 'field_adopted', 'field_unadopted', 'publish_blocked'"
")",
name='ck_shipping_order_schema_audit_event_type',
),
Index('ix_shipping_order_schema_audit_version_created', 'version_id', 'created_at'),
Index('ix_shipping_order_schema_audit_schema_created', 'schema_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schema_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=True)
field_id: Mapped[Optional[str]] = mapped_column(String(36), nullable=True)
version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_schema_versions.id', ondelete='SET NULL'), nullable=True
)
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
change_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderExtraction(Base):
"""一次订单解析审计;锁定 Schema 和输入快照,承载 LLM 原始结果及最终状态。"""
__tablename__ = 'shipping_order_extractions'
__table_args__ = (
Index('ix_shipping_order_extractions_task_created', 'task_id', 'created_at'),
Index('ix_shipping_order_extractions_intake_created', 'intake_id', 'created_at'),
# Version history pages aggregate and paginate the runtime records that used a Schema snapshot.
Index('ix_shipping_order_extractions_schema_version_created', 'schema_version_id', 'created_at'),
CheckConstraint(
"status IN ('created', 'extracting', 'needs_review', 'accepted', 'failed', 'superseded')",
name='ck_shipping_order_extractions_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created', server_default='created')
raw_llm_output_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
normalized_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
validation_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
schema_version: Mapped['ShippingOrderSchemaVersion'] = relationship()
lines: Mapped[list['ShippingOrderLine']] = relationship(
back_populates='extraction', cascade='all, delete-orphan', order_by='ShippingOrderLine.position'
)
observations: Mapped[list['ShippingOrderFieldObservation']] = relationship(
back_populates='extraction', cascade='all, delete-orphan'
)
decisions: Mapped[list['ShippingOrderFieldDecision']] = relationship(
back_populates='extraction', cascade='all, delete-orphan'
)
values: Mapped[list['ShippingOrderFieldValue']] = relationship(
back_populates='extraction', cascade='all, delete-orphan'
)
class ShippingOrderLine(Base):
"""动态订单解析中的行身份;业务值全部位于 FieldValue。"""
__tablename__ = 'shipping_order_lines'
__table_args__ = (
UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),
UniqueConstraint('extraction_id', 'line_no', name='uq_shipping_order_lines_line_no'),
)
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_no: Mapped[int] = mapped_column(Integer, nullable=False)
draft_line_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines')
class ShippingOrderFieldObservation(Base):
"""某字段来自某 Document/解析器的原始观察及可回查文本或版面证据。"""
__tablename__ = 'shipping_order_field_observations'
__table_args__ = (Index('ix_shipping_order_observations_extraction_field', 'extraction_id', 'field_id'),)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), nullable=False)
extractor: Mapped[str] = mapped_column(String(32), nullable=False)
raw_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
normalized_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
evidence_quote: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
evidence_ref: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
evidence_metadata_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
confidence: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 4), nullable=True)
evidence_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='observations')
class ShippingOrderFieldDecision(Base):
"""后端对字段观察集合的最终裁决;下游只能消费 accepted 决定。"""
__tablename__ = 'shipping_order_field_decisions'
__table_args__ = (
Index(
'uq_shipping_order_decisions_header_field', 'extraction_id', 'field_id', unique=True,
postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'),
),
Index(
'uq_shipping_order_decisions_line_field', 'extraction_id', 'line_id', 'field_id', unique=True,
postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'),
),
CheckConstraint(
"decision_status IN ('accepted', 'corroborated', 'needs_review', 'blocked', 'missing')",
name='ck_shipping_order_decisions_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
decision_status: Mapped[str] = mapped_column(String(32), nullable=False)
selected_observation_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_field_observations.id'), nullable=True
)
supporting_observation_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list)
resolved_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
decided_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='decisions')
class ShippingOrderFieldValue(Base):
"""已接受订单字段的类型化查询投影,供路由、匹配和 Excel 模板稳定引用。"""
__tablename__ = 'shipping_order_field_values'
__table_args__ = (
Index(
'uq_shipping_order_field_values_header_field', 'extraction_id', 'field_id', unique=True,
postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'),
),
Index(
'uq_shipping_order_field_values_line_field', 'extraction_id', 'line_id', 'field_id', unique=True,
postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'),
),
Index('ix_shipping_order_field_values_field_text', 'field_id', 'value_text'),
Index('ix_shipping_order_field_values_field_decimal', 'field_id', 'value_decimal'),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
value_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
value_decimal: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
value_integer: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
value_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
value_boolean: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
decision_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_field_decisions.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='values')
@@ -0,0 +1,127 @@
"""
backend/app/models/shipping_order_snapshot.py
用途:保存从订单解析候选冻结而来的不可变履约订单快照及人工复核审计。
依赖:shipping_order_schema 的 Extraction、shipping_order_tasks、shipping_customers 与 users。
逻辑:order_freeze_service 将已接受 Extraction 的字段按稳定 field_id 冻结为 Snapshot;库存、导出和上传阶段只消费本模块的快照。
source_manifest_json 可含 field_lineage(值来源、覆盖原因、证据引用)。
"""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import CheckConstraint, Date, DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderSnapshot(Base):
"""不可变的订单单头履约事实;一个已接受 Extraction 最多冻结一次。"""
__tablename__ = 'shipping_order_snapshots'
__table_args__ = (
UniqueConstraint('task_id', name='uq_shipping_order_snapshots_task'),
UniqueConstraint('extraction_id', name='uq_shipping_order_snapshots_extraction'),
Index('ix_shipping_order_snapshots_customer_created', 'customer_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False, index=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False)
# 保存冻结时采用的业务规则版本,不保存已下线的派生规则。
rule_versions_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实;
# 可含 field_lineage(按 field_code 记录 value_source / rule_id / override_reason / evidence_refs)。
source_manifest_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 保留所有已发布 Header 字段;核心字段同时写入下方强类型列,扩展字段由业务配置按 field_id 消费。
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
customer_po_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_code: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
bill_to_customer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
bill_to_address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
ship_to_customer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
ship_to_address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
destination: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
incoterm: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
order_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
payment_term: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
frozen_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
frozen_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
lines: Mapped[list['ShippingOrderSnapshotLine']] = relationship(
back_populates='snapshot', cascade='all, delete-orphan', order_by='ShippingOrderSnapshotLine.position',
)
review_events: Mapped[list['ShippingOrderReviewEvent']] = relationship(
back_populates='snapshot', cascade='all, delete-orphan', order_by='ShippingOrderReviewEvent.created_at',
)
schema_version = relationship('ShippingOrderSchemaVersion')
class ShippingOrderSnapshotLine(Base):
"""不可变订单单身履约事实;料号和预约单始终保存为字符串以保留前导零。"""
__tablename__ = 'shipping_order_snapshot_lines'
__table_args__ = (
UniqueConstraint('snapshot_id', 'position', name='uq_shipping_order_snapshot_lines_position'),
CheckConstraint('qty IS NULL OR qty > 0', name='ck_shipping_order_snapshot_lines_positive_qty'),
)
id: Mapped[int] = mapped_column(primary_key=True)
snapshot_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
# 冻结订单项次:每个 Snapshot 从 1 开始连续编号,冻结后不可修改。
line_no: Mapped[int] = mapped_column(Integer, nullable=False)
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
uom: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
unit_price: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
warehouse: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
inventory_source_hint: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 与 Header 同理:以 field_id 为键,避免后续字段重命名改变已冻结履约事实。
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
snapshot: Mapped['ShippingOrderSnapshot'] = relationship(back_populates='lines')
class ShippingOrderReviewEvent(Base):
"""冻结前人工纠错的追加式审计;每项变更必须保留原值、新值、证据和原因。"""
__tablename__ = 'shipping_order_review_events'
__table_args__ = (
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_review_events_scope'),
Index('ix_shipping_order_review_events_task_created', 'task_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=True)
scope: Mapped[str] = mapped_column(String(16), nullable=False)
line_position: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
old_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
new_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
evidence_ref: Mapped[str] = mapped_column(String(512), nullable=False)
reason: Mapped[str] = mapped_column(Text, nullable=False)
reviewed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
snapshot: Mapped[Optional['ShippingOrderSnapshot']] = relationship(back_populates='review_events')
@@ -0,0 +1,96 @@
"""
models/shipping_order_submission.py
用途:一次文件选择/上传批次的订单材料 Submission 边界(多 EML / 直接 PDF 阶段 1)。
依赖:users、agents、shipping_order_intakes(反向关联)。
逻辑:同一 (user_id, upload_batch_id) 唯一;仅承载幂等、文件集合汇总与会话关联,
不拥有端到端业务进度。由 order_submission_service 创建;Intake 通过
order_submission_id 挂接。与 shipping_order_extraction_submissions(OT 发送决策)
概念分离。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
def generate_order_submission_no() -> str:
"""
生成上传 Submission 业务编号。
核心逻辑:SOS-日期-短 UUID,保证可读且碰撞概率极低。
Returns:
形如 SOS-YYYYMMDD-XXXXXXXX 的编号。
"""
return f"SOS-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
class ShippingOrderSubmission(Base):
"""一次上传提交:聚合同 upload_batch 下的多个 Intake。"""
__tablename__ = 'shipping_order_submissions'
__table_args__ = (
UniqueConstraint('submission_no', name='uq_shipping_order_submissions_submission_no'),
UniqueConstraint(
'user_id',
'upload_batch_id',
name='uq_shipping_order_submissions_user_upload_batch',
),
CheckConstraint(
"status IN ('accepted', 'processing', 'completed', 'failed', 'cancelled')",
name='ck_shipping_order_submissions_status',
),
Index(
'ix_shipping_order_submissions_user_conversation_created',
'user_id',
'conversation_id',
'created_at',
),
Index('ix_shipping_order_submissions_status_created', 'status', 'created_at'),
Index(
'ix_shipping_order_submissions_client_submission',
'user_id',
'client_submission_id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
submission_no: Mapped[str] = mapped_column(String(64), nullable=False)
client_submission_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
upload_batch_id: Mapped[str] = mapped_column(String(36), nullable=False)
status: Mapped[str] = mapped_column(
String(32),
nullable=False,
default='accepted',
server_default=text("'accepted'"),
)
intake_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
eml_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
direct_pdf_count: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default=text('0')
)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+130
View File
@@ -0,0 +1,130 @@
"""
backend/app/models/shipping_order_task.py
用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。
依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs。
逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。
页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _default_order_task_no() -> str:
"""生成默认 OT 编号;正式路径由 Run 派生覆盖。"""
return f"OT-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
class ShippingOrderTask(Base):
"""
建单前订单任务(OT)聚合根。
核心逻辑:与 Extraction Run.user_task_no 对齐;进度由领域服务单调推进并 bump progress_version。
"""
__tablename__ = 'shipping_order_tasks'
__table_args__ = (
UniqueConstraint('task_no', name='uq_shipping_order_tasks_task_no'),
CheckConstraint("lifecycle_status IN ('active', 'voided', 'archived')", name='ck_shipping_order_tasks_lifecycle_status'),
CheckConstraint(
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
name='ck_shipping_order_tasks_source_type',
),
Index('ix_shipping_order_tasks_user_created', 'user_id', 'created_at'),
Index('ix_shipping_order_tasks_conversation', 'conversation_id'),
Index('ix_shipping_order_tasks_status', 'status'),
Index('ix_shipping_order_tasks_extraction_run_id', 'extraction_run_id'),
# 一 Candidate 一 OT;NULL candidate_id 仅遗留行,新创建路径禁止。
Index(
'uq_shipping_order_tasks_candidate_id',
'candidate_id',
unique=True,
postgresql_where=text('candidate_id IS NOT NULL'),
sqlite_where=text('candidate_id IS NOT NULL'),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), nullable=False, default=_default_order_task_no)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
submission_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_submissions.id'), nullable=True,
)
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True)
candidate_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_candidates.id'), nullable=True,
)
extraction_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True,
)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='processing')
stage: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
progress_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, 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,
)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# OT 的客户确认事实由 ShippingCustomerShadowResolution 承载。
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
current_order_extraction_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_extractions.id', name='fk_shipping_order_tasks_current_extraction', use_alter=True), nullable=True, index=True,
)
order_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_snapshots.id', name='fk_shipping_order_tasks_order_snapshot', use_alter=True), nullable=True, index=True,
)
active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', use_alter=True), nullable=True, index=True,
)
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_executions.id', use_alter=True), nullable=True, index=True,
)
# OT 在正式通知创建前也必须具备独立的回收/归档生命周期,不能借用 Notice 字段。
lifecycle_status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=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)
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',
)
+273
View File
@@ -0,0 +1,273 @@
"""
models/shipping_process_gate.py
用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。
依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job;状态枚举与 process_gate_contract 对齐。
逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。
由领域服务独占写入;Job 仅调度。
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
"""
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,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _utc_now() -> datetime:
"""返回 naive UTC 时间,与仓库现有模型一致。"""
return datetime.utcnow()
class ShippingProcessExecution(Base):
"""业务执行实例;门禁恢复状态唯一真相,不保存大体量订单原文。"""
__tablename__ = 'shipping_process_executions'
__table_args__ = (
UniqueConstraint('execution_no', name='uq_shipping_process_executions_no'),
CheckConstraint(
"status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed', 'superseded')",
name='ck_shipping_process_executions_status',
),
CheckConstraint('lock_version >= 1', name='ck_shipping_process_executions_lock_version'),
Index(
'ix_shipping_process_executions_status_updated',
'status',
'updated_at',
),
Index(
'ix_shipping_process_executions_current_gate',
'current_gate_code',
'status',
'updated_at',
),
Index(
'ix_shipping_process_executions_review_case',
'review_case_id',
),
Index(
'ix_shipping_process_executions_task',
'task_id',
),
Index('ix_shipping_process_executions_candidate_set', 'candidate_set_id', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
execution_no: Mapped[str] = mapped_column(String(64), nullable=False)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id'), nullable=True,
)
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_tasks.id'), nullable=True,
)
# 绑定候选版本,防止旧 callback/job 写入新候选链。
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True,
)
execution_revision: Mapped[int] = mapped_column(
Integer, nullable=False, default=1, server_default='1',
)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='active', server_default='active',
)
current_gate_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
last_passed_gate_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
primary_next_action_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
responsible_party: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
gates: Mapped[list['ShippingProcessGate']] = relationship(
back_populates='execution',
cascade='all, delete-orphan',
order_by='ShippingProcessGate.sequence_no',
)
class ShippingProcessGate(Base):
"""单门禁实例;保存状态、输入指纹、阻断原因与最新 Attempt 指针。"""
__tablename__ = 'shipping_process_gates'
__table_args__ = (
UniqueConstraint(
'execution_id',
'gate_code',
name='uq_shipping_process_gates_execution_code',
),
UniqueConstraint(
'execution_id',
'sequence_no',
name='uq_shipping_process_gates_execution_sequence',
),
CheckConstraint(
"status IN ("
"'pending', 'queued', 'running', 'passed', 'blocked_retryable', "
"'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped', 'cancelled'"
")",
name='ck_shipping_process_gates_status',
),
CheckConstraint('sequence_no >= 1', name='ck_shipping_process_gates_sequence'),
CheckConstraint('evaluation_version >= 1', name='ck_shipping_process_gates_eval_version'),
CheckConstraint('lock_version >= 1', name='ck_shipping_process_gates_lock_version'),
Index(
'ix_shipping_process_gates_execution_status',
'execution_id',
'status',
'updated_at',
),
Index(
'ix_shipping_process_gates_code_status',
'gate_code',
'status',
'updated_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
execution_id: Mapped[int] = mapped_column(
ForeignKey('shipping_process_executions.id', ondelete='CASCADE'), nullable=False,
)
gate_code: Mapped[str] = mapped_column(String(64), nullable=False)
sequence_no: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='pending', server_default='pending',
)
evaluation_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
blocking_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
blocking_reason_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
recommendation_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
effective_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
next_action_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
# 软指针:避免与 Attempt.gate_id 循环外键;由领域服务保证一致性。
latest_attempt_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
passed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
execution: Mapped[ShippingProcessExecution] = relationship(back_populates='gates')
attempts: Mapped[list['ShippingProcessGateAttempt']] = relationship(
back_populates='gate',
cascade='all, delete-orphan',
order_by='ShippingProcessGateAttempt.attempt_no',
foreign_keys='ShippingProcessGateAttempt.gate_id',
)
class ShippingProcessGateAttempt(Base):
"""不可变门禁执行尝试;成功或失败后业务结果不得被后续重试覆盖。"""
__tablename__ = 'shipping_process_gate_attempts'
__table_args__ = (
UniqueConstraint(
'gate_id',
'attempt_no',
name='uq_shipping_process_gate_attempts_gate_no',
),
UniqueConstraint(
'idempotency_key',
name='uq_shipping_process_gate_attempts_idempotency',
),
CheckConstraint(
"status IN ('queued', 'running', 'succeeded', 'failed', 'cancelled', 'superseded')",
name='ck_shipping_process_gate_attempts_status',
),
CheckConstraint('attempt_no >= 1', name='ck_shipping_process_gate_attempts_no'),
CheckConstraint(
"trigger_type IN ("
"'auto', 'user_retry', 'user_manual', 'worker_takeover', "
"'upstream_invalidation', 'system_requeue'"
")",
name='ck_shipping_process_gate_attempts_trigger',
),
CheckConstraint(
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')",
name='ck_shipping_process_gate_attempts_actor_type',
),
# 同一 Gate 同时最多一个 queued/running Attempt。
Index(
'uq_shipping_process_gate_attempts_one_active',
'gate_id',
unique=True,
postgresql_where=text("status IN ('queued', 'running')"),
sqlite_where=text("status IN ('queued', 'running')"),
),
Index(
'ix_shipping_process_gate_attempts_lease',
'lease_token',
'lease_expires_at',
),
Index(
'ix_shipping_process_gate_attempts_job',
'job_id',
),
Index(
'ix_shipping_process_gate_attempts_gate_status',
'gate_id',
'status',
'created_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
gate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_process_gates.id', ondelete='CASCADE'), nullable=False,
)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='queued', server_default='queued',
)
trigger_type: Mapped[str] = mapped_column(String(32), nullable=False, default='auto', server_default='auto')
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
input_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
rule_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
rule_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
output_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
output_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True)
worker_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lease_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lease_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
heartbeat_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_summary: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
recovery_plan_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_recovery_plans.id', use_alter=True), nullable=True, index=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
gate: Mapped[ShippingProcessGate] = relationship(
back_populates='attempts',
foreign_keys=[gate_id],
)
recovery_plan = relationship(
'ShippingProcessRecoveryPlan', back_populates='attempts', foreign_keys=[recovery_plan_id],
)
@@ -0,0 +1,64 @@
"""
models/shipping_process_recovery_plan.py
用途:持久化一次跨阶段门禁恢复业务意图及其生命周期。
依赖:ShippingProcessExecution、ShippingProcessGateAttempt、User、Base。
逻辑:RecoveryPlan 记录目标 Gate、失效计划、幂等键和最终结果;一个计划可关联多个 Gate Attempt。
"""
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
RECOVERY_PLAN_STATUSES = (
'planned', 'invalidating', 'queued', 'running', 'waiting_external',
'waiting_manual', 'succeeded', 'failed', 'conflicted', 'cancelled',
)
class ShippingProcessRecoveryPlan(Base):
"""一次跨阶段恢复意图;不可用 Gate Attempt JSON 替代。"""
__tablename__ = 'shipping_process_recovery_plans'
__table_args__ = (
UniqueConstraint('plan_no', name='uq_shipping_process_recovery_plans_no'),
UniqueConstraint('execution_id', 'idempotency_key', name='uq_shipping_process_recovery_plans_execution_idempotency'),
CheckConstraint(
"status IN ('planned','invalidating','queued','running','waiting_external','waiting_manual','succeeded','failed','conflicted','cancelled')",
name='ck_shipping_process_recovery_plans_status',
),
Index('ix_shipping_process_recovery_plans_execution_status', 'execution_id', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
plan_no: Mapped[str] = mapped_column(String(64), nullable=False)
execution_id: Mapped[int] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='CASCADE'), nullable=False)
current_gate: Mapped[str] = mapped_column(String(64), nullable=False)
action_code: Mapped[str] = mapped_column(String(64), nullable=False)
target_gate: Mapped[str] = mapped_column(String(64), nullable=False)
resume_after_gate: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='planned', server_default='planned')
invalidation_plan_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
recovery_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
expected_gate_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
failure_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
failure_detail_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
superseded_by_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
execution = relationship('ShippingProcessExecution', foreign_keys=[execution_id])
attempts = relationship('ShippingProcessGateAttempt', back_populates='recovery_plan', foreign_keys='ShippingProcessGateAttempt.recovery_plan_id')
@@ -0,0 +1,164 @@
"""
收料报表 RPA 的配置、运行、归档与通知投递持久化模型。
用途:为独立收料排程保存站点级配置、每站点/仓库执行单元、原样归档文件及企微投递事实。
依赖:库存站点、排程运行、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
逻辑:模型只复用库存站点的连接资料,通过独立外键与唯一约束隔离库存快照、匹配和旧 RPA Worker 链路。
"""
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, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingReceiptReportConfig(Base):
"""库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。"""
__tablename__ = 'shipping_receipt_report_configs'
__table_args__ = (
UniqueConstraint('inventory_source_id', name='uq_shipping_receipt_report_configs_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
)
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,
)
# DBS 可包含多个 Warehouse;Crane 固定 Inbound Details,保留空数组。
warehouse_ids_json: Mapped[list[str]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), 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)
inventory_source: Mapped['ShippingInventorySource'] = relationship(back_populates='receipt_report_config')
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship()
class ShippingReceiptRpaUnitRun(Base):
"""一次收料排程内的站点或站点-Warehouse 不可重复执行单元。"""
__tablename__ = 'shipping_receipt_rpa_unit_runs'
__table_args__ = (
UniqueConstraint('callback_id', name='uq_shipping_receipt_rpa_unit_runs_callback'),
CheckConstraint(
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
name='ck_shipping_receipt_rpa_unit_runs_status',
),
Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'),
Index('ix_shipping_receipt_unit_run_source_created', 'inventory_source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schedule_run_id: Mapped[int] = mapped_column(ForeignKey('schedule_runs.id'), nullable=False, index=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
retry_of_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
schedule_run: Mapped['ScheduleRun'] = relationship(foreign_keys=[schedule_run_id])
inventory_source: Mapped['ShippingInventorySource'] = relationship()
retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id])
files: Mapped[list['ShippingReceiptReportFile']] = relationship(
back_populates='unit_run', cascade='all, delete-orphan',
)
class ShippingReceiptReportFile(Base):
"""收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
__tablename__ = 'shipping_receipt_report_files'
__table_args__ = (
UniqueConstraint('unit_run_id', 'sha256', name='uq_shipping_receipt_report_files_unit_sha256'),
CheckConstraint("file_size >= 0", name='ck_shipping_receipt_report_files_size'),
Index('ix_shipping_receipt_report_files_unit', 'unit_run_id'),
Index('ix_shipping_receipt_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
unit_run_id: Mapped[int] = mapped_column(ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=False, index=True)
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
unit_run: Mapped[ShippingReceiptRpaUnitRun] = relationship(back_populates='files')
deliveries: Mapped[list['ShippingReceiptNotificationDelivery']] = relationship(
back_populates='report_file', cascade='all, delete-orphan',
)
class ShippingReceiptNotificationDelivery(Base):
"""收料文件或汇总企微消息的幂等投递事实,响应仅保存脱敏摘要。"""
__tablename__ = 'shipping_receipt_notification_deliveries'
__table_args__ = (
UniqueConstraint('idempotency_key', name='uq_shipping_receipt_notification_deliveries_idempotency'),
CheckConstraint("message_type IN ('file', 'summary')", name='ck_shipping_receipt_notification_deliveries_type'),
CheckConstraint(
"status IN ('pending', 'sending', 'success', 'failed')",
name='ck_shipping_receipt_notification_deliveries_status',
),
Index('ix_shipping_receipt_delivery_file_recipient', 'report_file_id', 'recipient_user_id'),
Index('ix_shipping_receipt_delivery_unit_created', 'unit_run_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
unit_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
)
report_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_report_files.id'), nullable=True, index=True,
)
recipient_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
message_type: Mapped[str] = mapped_column(String(16), nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(255), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sent_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)
unit_run: Mapped[Optional[ShippingReceiptRpaUnitRun]] = relationship(foreign_keys=[unit_run_id])
report_file: Mapped[Optional[ShippingReceiptReportFile]] = relationship(back_populates='deliveries')
@@ -0,0 +1,122 @@
"""
models/shipping_task_inventory_rpa_attempts.py
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。
逻辑:每个库存源(task_no, source_code)独立计数 attempt_no / run_no;
Trigger 文件名格式 SN-<task_no>__<SOURCE_CODE>.trigger.json;回调按三元组
(task_no, source_code, run_no) 定位 Attempt;迟到回调(run_no < 当前 consumed)
标记 superseded 不写快照,保证幂等。
"""
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any, Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship, synonym
from app.models.base import Base
_JSON_FOR_SQLITE = JSON().with_variant(JSONB(), "postgresql")
if TYPE_CHECKING:
pass
PER_SOURCE_RPA_ATTEMPT_STATUSES = (
'queued', # 已写 trigger 文件,等待 RPA Worker 领取
'running', # RPA Worker 已领取(租约写入 lease_token)
'succeeded', # 回调成功,快照已 ingest 并校验通过
'failed', # 回调返回失败或超时判定失败
'consumed', # 业务侧已消费该快照(推进到下一 Gate)
'superseded', # 迟到回调:run_no 早于已 consumed 的 run_no,忽略不写业务
'exhausted', # 当前 (task, source) 对已达最大 attempt 且未成功
)
class ShippingTaskInventoryRpaAttempt(Base):
"""逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。"""
__tablename__ = 'shipping_task_inventory_rpa_attempts'
__table_args__ = (
# 三元组唯一:同一运行号同一源只允许一条记录
UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'),
# PostgreSQL 部分唯一索引:每个 (task, source) 同时只允许 1 条活动(queued/running)Attempt
Index(
'uq_shipping_task_inv_rpa_active_per_source',
'task_no', 'source_code',
unique=True,
postgresql_where="status IN ('queued','running')",
),
# 扫描超时 & 最新 Attempt 常用查询维度
Index('ix_shipping_task_inv_rpa_task_source', 'task_no', 'source_code', 'attempt_no'),
Index('ix_shipping_task_inv_rpa_status_updated', 'status', 'updated_at'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in PER_SOURCE_RPA_ATTEMPT_STATUSES)})",
name='ck_shipping_task_inv_rpa_status_enum',
),
CheckConstraint('attempt_no >= 1', name='ck_shipping_task_inv_rpa_attempt_positive'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
task_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
source_code: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
source_run_no: Mapped[str] = mapped_column(String(128), nullable=False)
# 仅为历史调用方提供 Python 层读取兼容;数据库正式事实只有 source_run_no。
run_no = synonym('source_run_no')
callback_id: Mapped[str | None] = mapped_column(String(256), nullable=True, unique=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', index=True)
trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lease_token: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
leased_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
lease_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
callback_payload_json: Mapped[dict[str, Any]] = mapped_column(_JSON_FOR_SQLITE, nullable=False, default=dict)
extra_json: Mapped[dict[str, Any]] = mapped_column(_JSON_FOR_SQLITE, nullable=False, default=dict)
triggered_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
callback_received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
claimed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
worker_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
execution_phase: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_generated: Mapped[bool] = mapped_column(default=False, nullable=False)
file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
file_exists_at_callback: Mapped[Optional[bool]] = mapped_column(nullable=True)
transaction_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
transaction_error_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
transaction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=False), nullable=False, default=datetime.utcnow, index=True,
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=False), nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, index=True,
)
+94
View File
@@ -0,0 +1,94 @@
"""
backend/app/models/shipping_task_line.py
用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。
依赖:models.base.Base、shipping_order_tasks、users。
逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import (
CheckConstraint,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingTaskFieldConflict(Base):
"""
订单字段级冲突审计;未解决冲突将在后续阶段阻断下游流程。
核心逻辑:独立于 Candidate/TaskLine,记录双方值、来源、证据与解决结果。
"""
__tablename__ = 'shipping_task_field_conflicts'
__table_args__ = (
CheckConstraint(
"status IN ('open', 'resolved', 'dismissed')",
name='ck_shipping_task_field_conflicts_status',
),
Index('ix_shipping_task_field_conflicts_task_status', 'task_id', 'status'),
Index(
'uq_shipping_task_field_conflicts_open_task_field',
'task_id',
'field_name',
unique=True,
postgresql_where=text("status = 'open' AND position IS NULL"),
sqlite_where=text("status = 'open' AND position IS NULL"),
),
Index(
'uq_shipping_task_field_conflicts_open_position_field',
'task_id',
'position',
'field_name',
unique=True,
postgresql_where=text("status = 'open' AND position IS NOT NULL"),
sqlite_where=text("status = 'open' AND position IS NOT NULL"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
position: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
field_name: Mapped[str] = mapped_column(String(64), nullable=False)
existing_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
incoming_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
existing_source: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
incoming_source: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
existing_evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
incoming_evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(
String(32),
nullable=False,
default='open',
server_default=text("'open'"),
)
resolved_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
resolved_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
conflict_version: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=1,
server_default=text('1'),
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', back_populates='field_conflicts')
@@ -0,0 +1,51 @@
"""
models/shipping_temporary_inventory.py
用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续任务挂接过程。
依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、库存结构分析记录。
逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id;
本表不代表库存站点配置,也不代表生产库存快照。
"""
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,
)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_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)
@@ -0,0 +1,81 @@
"""
backend/app/models/shipping_xfa_audit_snapshot.py
用途:持久化 XFA 审计完整快照密文(不可变、可校验、默认保留 3 年)。
依赖:SQLAlchemy Base;由 audit_snapshot_service 写入/只读解密;禁止业务层直接改删。
逻辑:普通 ShippingAuditEvent 仅保存脱敏 diff 与 snapshot_ref;完整请求/definition/
受控原值经 envelope encryption 落入本表。ORM before_update/before_delete 与
PostgreSQL 触发器共同保证 append-only;到期清理须 set_config
('hxops.shipping_xfa_audit_purge','1')。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import JSON, CheckConstraint, DateTime, Index, Integer, String, Text, event
from sqlalchemy.orm import Mapped, mapped_column
from app.core.errors import ValidationError
from app.models.base import Base
class ShippingXfaAuditSnapshot(Base):
"""XFA 审计完整快照密文行;禁止业务更新或删除。"""
__tablename__ = 'shipping_xfa_audit_snapshots'
__table_args__ = (
CheckConstraint(
"purpose IN ('before', 'after', 'request', 'full', 'sample_values')",
name='ck_shipping_xfa_audit_snapshots_purpose',
),
CheckConstraint(
"encryption_alg IN ('fernet-v1')",
name='ck_shipping_xfa_audit_snapshots_encryption_alg',
),
Index('ix_shipping_xfa_audit_snapshots_object', 'object_type', 'object_id', 'created_at'),
Index('ix_shipping_xfa_audit_snapshots_retention', 'retention_expires_at', 'id'),
Index('ix_shipping_xfa_audit_snapshots_operation', 'operation_id', 'created_at'),
Index('ix_shipping_xfa_audit_snapshots_request', 'request_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
# 对外稳定引用(写入审计事件 context_refs / evidence_refs),禁止猜测递增 id。
snapshot_ref: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
object_type: Mapped[str] = mapped_column(String(64), nullable=False)
object_id: Mapped[str] = mapped_column(String(128), nullable=False)
purpose: Mapped[str] = mapped_column(String(32), nullable=False)
schema_version: Mapped[str] = mapped_column(String(32), nullable=False, default='xfa_audit_v1')
encryption_alg: Mapped[str] = mapped_column(String(32), nullable=False, default='fernet-v1')
key_id: Mapped[str] = mapped_column(String(64), nullable=False, default='primary')
# Fernet 密文;静态不可读,仅敏感读 API 在权限校验后解密。
ciphertext: Mapped[str] = mapped_column(Text, nullable=False)
ciphertext_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
plaintext_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
# 脱敏摘要(可进普通导出);不得含明文订单值或 XML。
redacted_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
audit_event_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
retention_expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@event.listens_for(ShippingXfaAuditSnapshot, 'before_update')
def _reject_xfa_audit_snapshot_update(_mapper, _connection, _target) -> None:
"""拒绝 ORM 更新,保证完整快照不可篡改。"""
raise ValidationError(
'Shipping XFA audit snapshot is append-only',
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_IMMUTABLE',
)
@event.listens_for(ShippingXfaAuditSnapshot, 'before_delete')
def _reject_xfa_audit_snapshot_delete(_mapper, _connection, _target) -> None:
"""拒绝 ORM 删除,避免业务清理抹除加密审计事实。"""
raise ValidationError(
'Shipping XFA audit snapshot is append-only',
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_IMMUTABLE',
)
@@ -0,0 +1,64 @@
"""
backend/app/models/shipping_xfa_structure_analysis.py
用途:持久化 XFA 样本/文档的结构分析摘要(document_kind、packet checksum、结构指纹、统计与安全摘要)。
依赖:shipping_order_documents、shipping_order_document_layout_versions、SQLAlchemy Base。
逻辑:由 shipping_document_layout Job 在 XFA 分支写入;admin API 只读投影,不返回原始 XML/PDF。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingXfaStructureAnalysis(Base):
"""单文档 XFA 结构分析记录;保存脱敏结构证据,完整敏感值仅通过 encrypted_snapshot_ref 占位。"""
__tablename__ = 'shipping_xfa_structure_analyses'
__table_args__ = (
CheckConstraint(
"analysis_status IN ('ready', 'failed', 'rejected')",
name='ck_shipping_xfa_structure_analysis_status',
),
CheckConstraint(
"document_kind IN ('plain_pdf', 'acroform', 'xfa_hybrid', 'pure_xfa', 'unsupported')",
name='ck_shipping_xfa_structure_analysis_document_kind',
),
Index('ix_shipping_xfa_structure_analysis_document', 'document_id', 'created_at'),
Index('ix_shipping_xfa_structure_analysis_content_hash', 'source_content_hash'),
Index('ix_shipping_xfa_structure_analysis_fingerprint', 'dataset_structure_fingerprint'),
)
id: Mapped[int] = mapped_column(primary_key=True)
document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_documents.id', ondelete='CASCADE'), nullable=False,
)
layout_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_layout_versions.id', ondelete='SET NULL'), nullable=True,
)
source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
document_kind: Mapped[str] = mapped_column(String(32), nullable=False)
analysis_status: Mapped[str] = mapped_column(String(16), nullable=False, default='ready', server_default='ready')
template_packet_checksum: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
datasets_packet_checksum: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
dataset_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
packet_checksums_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
stats_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
security_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
tree_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
route_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
encrypted_snapshot_ref: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
parser_identity: Mapped[str] = mapped_column(String(64), nullable=False)
contract_version: Mapped[str] = mapped_column(String(64), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
document = relationship('ShippingOrderDocument', foreign_keys=[document_id])
layout_version = relationship('ShippingDocumentLayoutVersion', foreign_keys=[layout_version_id])
+164 -6
View File
@@ -1,9 +1,9 @@
"""
backend/app/models/training.py
用途:定义新人入职培训记录模型,承载学员当前培训进度、成绩结算与 HR 统计来源。
用途:定义员工培训记录模型,承载入职培训/安全培训的进度、考试结果与 HR 统计来源。
依赖:models.base.Base、SQLAlchemy 映射、users 主表外键。
逻辑:每个用户维护一条当前培训记录;前端学习流与管理端统计都基于该表读写。
逻辑:每个用户在每种培训类型下维护一条当前记录;P0 阶段先为安全培训补齐三级状态、考试模式和版本号持久化。
"""
from __future__ import annotations
@@ -11,19 +11,25 @@ from __future__ import annotations
from datetime import date, datetime
from typing import Optional
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class TrainingRecord(Base):
"""新人入职培训当前记录。"""
"""培训记录。"""
__tablename__ = "training_records"
__table_args__ = (UniqueConstraint("user_id", "training_type", name="uq_user_training_type"),)
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), unique=True, index=True, nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True, nullable=False)
training_type: Mapped[str] = mapped_column(String(50), nullable=False, default="onboarding", index=True)
training_version: Mapped[str] = mapped_column(String(64), nullable=False, default="onboarding-v1", index=True)
exam_mode: Mapped[str] = mapped_column(String(20), nullable=False, default="unified")
safety_stage: Mapped[Optional[str]] = mapped_column(String(20), nullable=True, index=True)
safety_progress: Mapped[dict | None] = mapped_column(JSON, nullable=True)
employee_id: Mapped[Optional[str]] = mapped_column(String(50), nullable=True, index=True)
name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)
department: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)
@@ -45,4 +51,156 @@ class TrainingRecord(Base):
index=True,
)
user = relationship("User", back_populates="training_record")
user = relationship("User", back_populates="training_records")
class TrainingConfig(Base):
__tablename__ = "training_configs"
id: Mapped[int] = mapped_column(primary_key=True)
training_type: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
name: Mapped[str] = mapped_column(String(100), nullable=False)
version: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(20), nullable=False, default="draft", index=True)
pass_score: Mapped[int] = mapped_column(Integer, nullable=False, default=90)
settings: Mapped[dict | None] = mapped_column(JSON, 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)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
resources: Mapped[list["TrainingConfigResource"]] = relationship(
"TrainingConfigResource", back_populates="config", cascade="all, delete-orphan", order_by="TrainingConfigResource.sort_order"
)
class TrainingConfigResource(Base):
__tablename__ = "training_config_resources"
id: Mapped[int] = mapped_column(primary_key=True)
config_id: Mapped[int] = mapped_column(ForeignKey("training_configs.id", ondelete="CASCADE"), nullable=False, index=True)
resource_type: Mapped[str] = mapped_column(String(32), nullable=False)
training_level: Mapped[Optional[str]] = mapped_column(String(20), nullable=True, index=True)
agent_guide_id: Mapped[Optional[int]] = mapped_column(ForeignKey("agent_guides.id"), nullable=True)
kb_document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey("kb_document_versions.id"), nullable=True)
inline_questions: Mapped[list | None] = mapped_column(JSON, nullable=True)
title: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
required_duration: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
config: Mapped[TrainingConfig] = relationship("TrainingConfig", back_populates="resources")
agent_guide = relationship("AgentGuide", foreign_keys=[agent_guide_id])
kb_document_version = relationship("KbDocumentVersion", foreign_keys=[kb_document_version_id])
class LeanTrainingWeeklyTask(Base):
"""
精益管理周度培训任务。
用途:冻结每个自然周由 HR 指定的培训视频集合和受训对象,作为员工完成状态、视频推送与提醒扫描的统一事实源。
依赖:TrainingConfigResource、TrainingConfig、User。
逻辑:配置页创建或更新任务并设定每周推送数量;员工提交观看与总结时关联本表;
视频推送服务按 pushed_video_count 游标每周推进 weekly_count 个,提醒服务只扫描已发布周任务。
"""
__tablename__ = "lean_training_weekly_tasks"
__table_args__ = (UniqueConstraint("week_key", name="uq_lean_training_week_key"),)
id: Mapped[int] = mapped_column(primary_key=True)
config_id: Mapped[int] = mapped_column(ForeignKey("training_configs.id"), nullable=False, index=True)
week_key: Mapped[str] = mapped_column(String(10), nullable=False, index=True)
due_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
video_resource_ids: Mapped[list] = mapped_column(JSON, nullable=False)
weekly_count: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default="1")
pushed_video_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
target_roles: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
target_user_ids: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
status: Mapped[str] = mapped_column(String(20), nullable=False, default="published", index=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
config: Mapped[TrainingConfig] = relationship("TrainingConfig", foreign_keys=[config_id])
push_logs: Mapped[list["LeanTrainingVideoPushLog"]] = relationship(
"LeanTrainingVideoPushLog", back_populates="task", cascade="all, delete-orphan", order_by="LeanTrainingVideoPushLog.id.desc()"
)
class LeanTrainingVideoPushLog(Base):
"""
精益管理视频推送日志。
用途:记录每一轮(每周一排程或 HR 手动)按每周任务数量推送视频的执行结果与失败原因,供管理端展示报错日志。
依赖:LeanTrainingWeeklyTask、User。
逻辑:推送服务每执行一轮写入一行;推送游标推进后天然幂等,重复触发不会重复推送同一批视频;
failed_count>0 时 error_message 保存按用户聚合的失败明细。
"""
__tablename__ = "lean_training_video_push_logs"
id: Mapped[int] = mapped_column(primary_key=True)
weekly_task_id: Mapped[int] = mapped_column(ForeignKey("lean_training_weekly_tasks.id"), nullable=False, index=True)
trigger: Mapped[str] = mapped_column(String(20), nullable=False, default="schedule", index=True)
pushed_resource_ids: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
pushed_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
recipient_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
sent_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
skipped_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
failed_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
status: Mapped[str] = mapped_column(String(20), nullable=False, default="sent", index=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, index=True)
task: Mapped[LeanTrainingWeeklyTask] = relationship("LeanTrainingWeeklyTask", back_populates="push_logs")
class LeanTrainingCompletion(Base):
"""
精益管理周度学习完成事实。
用途:保存员工对周度已推送视频的观看时间及不少于 50 字的学习感悟。
依赖:LeanTrainingWeeklyTask、User。
逻辑:员工只能写入本人的记录;服务端依据视频集合和总结长度判定完成,管理看板与提醒任务读取该事实。
"""
__tablename__ = "lean_training_completions"
__table_args__ = (UniqueConstraint("weekly_task_id", "user_id", name="uq_lean_training_task_user"),)
id: Mapped[int] = mapped_column(primary_key=True)
weekly_task_id: Mapped[int] = mapped_column(ForeignKey("lean_training_weekly_tasks.id"), nullable=False, index=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True)
watched_at_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
summary_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
summary_char_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
status: Mapped[str] = mapped_column(String(20), nullable=False, default="in_progress", index=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
class LeanTrainingReminder(Base):
"""
精益管理提醒发送审计。
用途:对指派、逾期轮次和班组长定向提醒去重并保留发送结果。
依赖:LeanTrainingWeeklyTask、User、企微通知审计 trace_id。
逻辑:扫描服务先写 pending 行,再调用企微服务更新最终状态,数据库唯一约束防止重复排程产生重复消息。
"""
__tablename__ = "lean_training_reminders"
__table_args__ = (UniqueConstraint("weekly_task_id", "recipient_user_id", "event_key", name="uq_lean_training_reminder_event"),)
id: Mapped[int] = mapped_column(primary_key=True)
weekly_task_id: Mapped[int] = mapped_column(ForeignKey("lean_training_weekly_tasks.id"), nullable=False, index=True)
recipient_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True)
event_key: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(20), nullable=False, default="pending", index=True)
trace_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
+14 -3
View File
@@ -79,10 +79,9 @@ class User(Base):
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
training_record: Mapped[Optional['TrainingRecord']] = relationship(
training_records: Mapped[List['TrainingRecord']] = relationship(
'TrainingRecord',
back_populates='user',
uselist=False,
)
def _role_default_feature_permissions(self) -> dict[str, bool]:
@@ -91,6 +90,14 @@ class User(Base):
'training_hr_manage': self.role in {'admin', 'hr'},
# 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
'shipping_notice_force_create': self.role == 'admin',
# 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予
'shipping_notice.audit_sensitive_read': self.role == 'admin',
# XFA 字段拆分:编辑 / 预览 / 发布审核;admin 默认开,可显式收紧
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
# 合同付款预警工作台:admin 默认开;不新建角色,可给采购同事单独授予
'contract_payment.access': self.role == 'admin',
}
def get_feature_permissions(self) -> dict[str, bool]:
@@ -98,7 +105,7 @@ class User(Base):
返回当前用户的有效功能权限。
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训类业务权限硬编码在多个模块。
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训、合同付款等业务权限硬编码在多个模块。
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
"""
defaults = self._role_default_feature_permissions()
@@ -138,6 +145,10 @@ class User(Base):
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
return self.has_feature_permission('training_hr_manage')
def can_access_contract_payment(self) -> bool:
"""判断当前用户是否可查看合同付款预警工作台并触发同步/扫描。"""
return self.has_feature_permission('contract_payment.access')
def set_password(self, password: str) -> None:
"""设置密码哈希。"""
self.password_hash = generate_password_hash(password)
+124 -58
View File
@@ -1,9 +1,9 @@
"""
backend/app/models/voucher_check.py
用途:立账凭证检核单票最新状态与批次明细 ORM。
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。
依赖:models.base.Base、schedule_runs。
逻辑:runner/persistence 写入;query_service 与工作台 API 读取;增量跳过依赖 invoice_states。
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;工作台与查询服务只读这些表。
"""
from __future__ import annotations
@@ -13,7 +13,6 @@ from typing import Optional
from sqlalchemy import (
BigInteger,
Boolean,
Date,
DateTime,
ForeignKey,
@@ -28,41 +27,20 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class VoucherCheckInvoiceState(Base):
"""账套+月份+发票号的最新材料齐全状态(增量跳过真相源)。"""
class VoucherCheckProfile(Base):
"""已发布 Profile 版本;批次绑定不可变快照,运行时不以本表热更新覆盖。"""
__tablename__ = "voucher_check_invoice_states"
__tablename__ = "voucher_check_profiles"
__table_args__ = (
UniqueConstraint(
"scope_code",
"period_month",
"invoice_no",
name="uq_voucher_check_invoice_states_scope_period_invoice",
),
Index("ix_voucher_check_invoice_states_period_status", "period_month", "status"),
Index("ix_voucher_check_invoice_states_invoice_no", "invoice_no"),
Index("ix_voucher_check_invoice_states_notified_on", "last_missing_notified_on"),
UniqueConstraint("profile_code", "version", name="uq_voucher_check_profiles_code_version"),
Index("ix_voucher_check_profiles_status", "status"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
scope_code: Mapped[str] = mapped_column(String(32), nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
status: Mapped[str] = mapped_column(String(24), nullable=False)
folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
last_actual_run_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
)
last_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_seen_erp_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_missing_notified_on: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
profile_code: Mapped[str] = mapped_column(String(32), nullable=False)
version: Mapped[str] = mapped_column(String(32), nullable=False)
definition_json: Mapped[dict] = mapped_column(JSON, nullable=False)
status: Mapped[str] = mapped_column(String(24), nullable=False, default="published")
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
@@ -72,43 +50,131 @@ class VoucherCheckInvoiceState(Base):
)
class VoucherCheckRunItem(Base):
"""单次 ScheduleRun 的发票检核快照(含跳过项,供审计与 Excel)。"""
class VoucherCheckRun(Base):
"""一次检核批次;列表统计取本表快照,不在查询时重算单文件结果。"""
__tablename__ = "voucher_check_run_items"
__tablename__ = "voucher_check_runs"
__table_args__ = (
UniqueConstraint(
"schedule_run_id",
"invoice_no",
name="uq_voucher_check_run_items_run_invoice",
),
Index("ix_voucher_check_run_items_run_result", "schedule_run_id", "result"),
Index("ix_voucher_check_run_items_period_result", "period_month", "result"),
Index("ix_voucher_check_runs_period_profile", "period_month", "profile_code"),
Index("ix_voucher_check_runs_status", "status"),
Index("ix_voucher_check_runs_finished_at", "finished_at"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
schedule_run_id: Mapped[int] = mapped_column(
schedule_run_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="CASCADE"),
ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
index=True,
)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
profile_code: Mapped[str] = mapped_column(String(32), nullable=False)
profile_version: Mapped[str] = mapped_column(String(32), nullable=False)
profile_snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
mode: Mapped[str] = mapped_column(String(24), nullable=False, default="incremental")
status: Mapped[str] = mapped_column(String(24), nullable=False, default="running")
subject_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
archived_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
skipped_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
missing_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
missing_invoice_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
technical_error_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
staged_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
stats_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class VoucherCheckSubject(Base):
"""批次内一张销售 invoice 主体。"""
__tablename__ = "voucher_check_subjects"
__table_args__ = (
UniqueConstraint("run_id", "invoice_no", name="uq_voucher_check_subjects_run_invoice"),
Index("ix_voucher_check_subjects_invoice_no", "invoice_no"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
invoice_state_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"),
nullable=True,
)
scope_code: Mapped[str] = mapped_column(String(32), nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
result: Mapped[str] = mapped_column(String(24), nullable=False)
folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
source_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
attributes_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class VoucherCheckFileResult(Base):
"""invoice × 文件规则 的单文件结果,是缺件统计与 Excel 的真相源。"""
__tablename__ = "voucher_check_file_results"
__table_args__ = (
UniqueConstraint(
"run_id",
"invoice_no",
"rule_code",
name="uq_voucher_check_file_results_run_invoice_rule",
),
Index("ix_voucher_check_file_results_status", "run_id", "status"),
Index("ix_voucher_check_file_results_invoice", "invoice_no"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
subject_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("voucher_check_subjects.id", ondelete="SET NULL"),
nullable=True,
)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
rule_code: Mapped[str] = mapped_column(String(64), nullable=False)
rule_name: Mapped[str] = mapped_column(String(128), nullable=False)
source_type: Mapped[str] = mapped_column(String(32), nullable=False)
expected_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
matched_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
source_folder_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
archive_folder_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
archive_item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
archive_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
status: Mapped[str] = mapped_column(String(24), nullable=False)
missing_reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
source_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class VoucherCheckNotification(Base):
"""一个检核批次对应一条企微汇总通知审计。"""
__tablename__ = "voucher_check_notifications"
__table_args__ = (Index("ix_voucher_check_notifications_status", "send_status"),)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
nullable=False,
unique=True,
)
excel_filename: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
recipient_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
send_status: Mapped[str] = mapped_column(String(32), nullable=False)
skip_reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)