feat(in-transit-transfer): 实现在途仓自动调拨Agent一期完整功能
包含后端服务层、任务处理器与消费Worker、前端聊天组件、数据库模型与迁移脚本、测试用例,同时新增外部系统连接器框架基础能力并更新相关文档。
This commit is contained in:
1 parent
f3050164d0
commit
6b53b563e7
177 files changed
+17260
-36
No files matched your search
@@ -183,6 +183,22 @@ from app.models.shipping_inventory_preparation import (
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
)
|
||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
||||
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
|
||||
@@ -356,4 +372,16 @@ __all__ = [
|
||||
'ShippingTaskInventoryRpaAttempt',
|
||||
'VoucherCheckInvoiceState',
|
||||
'VoucherCheckRunItem',
|
||||
'TransferRun',
|
||||
'TransferSourceJob',
|
||||
'TransferPrecheck',
|
||||
'TransferInvoiceItem',
|
||||
'TransferAttempt',
|
||||
'TransferAuditEvent',
|
||||
'TransferArchive',
|
||||
'IntegrationCredentialReference',
|
||||
'IntegrationClientInstance',
|
||||
'IntegrationInterfaceDefinition',
|
||||
'IntegrationBinding',
|
||||
'IntegrationCall',
|
||||
]
|
||||
@@ -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')
|
||||
@@ -0,0 +1,193 @@
|
||||
"""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')
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
@@ -158,16 +158,26 @@ class ShippingInventorySourceParsingBindingAudit(Base):
|
||||
|
||||
|
||||
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'))
|
||||
|
||||
@@ -30,6 +30,10 @@ class ShippingReceiptReportConfig(Base):
|
||||
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,
|
||||
)
|
||||
@@ -47,6 +51,7 @@ class ShippingReceiptReportConfig(Base):
|
||||
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):
|
||||
|
||||
Reference in new issue
Block a user