外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。 Co-authored-by: Cursor <cursoragent@cursor.com>
649 lines
40 KiB
Python
649 lines
40 KiB
Python
"""models/in_transit_transfer.py
|
||
|
||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
|
||
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive;另含调拨类型
|
||
配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档
|
||
TransferMovementLedger(外部系统入站/出站记录镜像,ADR 0001)。
|
||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁);
|
||
source_file_id 外键指向 freight_rpa_inbound_report_files(FreightRpaInboundReportFile 原样归档,入站证据)。
|
||
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
|
||
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
|
||
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
|
||
Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖;
|
||
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除;
|
||
transfer_runs.transfer_type 合法值由 TransferTypeConfig 配置承接
|
||
(原枚举 CHECK 约束已移除);
|
||
TransferMovementLedger 以自然键 (source_code, record_kind, doc_no,
|
||
line_no, line_seq, in_out_flag, carton_id, lot_no) 幂等增量落地外部记录,
|
||
已执行记录经 transfer_executed 封存(防二次调拨),来源文件删除后档事实留存
|
||
(ON DELETE SET NULL,链接仅溯源)。
|
||
"""
|
||
|
||
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 保持一致的冻结枚举(数据库级兜底)。
|
||
# 【not_matured 已退役 2026-10-16】成熟概念删除,存量行经 tt16 重映射 cancelled。
|
||
TRANSFER_ITEM_STATUSES = (
|
||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||
'success', 'duplicate_success', 'blocked_recoverable',
|
||
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
||
)
|
||
TRANSFER_RUN_STATUSES = (
|
||
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
||
'success', 'partial_failed', 'failed', 'cancelled',
|
||
)
|
||
TRANSFER_SOURCE_JOB_STATUSES = (
|
||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||
)
|
||
TRANSFER_MATCH_STATUSES = (
|
||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||
'success', 'failed', 'cancelled', 'expired',
|
||
)
|
||
TRANSFER_ATTEMPT_KINDS = ('match', 'rpa', 'external_query', 'external_write')
|
||
TRANSFER_ATTEMPT_STATUSES = (
|
||
'queued', 'running', 'waiting_external', 'success', 'failed',
|
||
'result_unknown', 'superseded',
|
||
)
|
||
# ERP 调拨单(TransferDocument)状态冻结枚举:服务层口径真相源;
|
||
# ck_transfer_documents_status CHECK 由该元组生成(DB 兜底,非法态 fail-closed)。
|
||
TRANSFER_DOCUMENT_STATUSES = (
|
||
'pending', 'executing', 'success', 'duplicate_success',
|
||
'business_failed', 'technical_failed', 'result_unknown', 'cancelled',
|
||
)
|
||
# 未完结单状态集合(组锁生效范围,D7①/D15):同五元组存在任一未完结单时
|
||
# 复用其 doc_no+submit_timestamp,禁止新建;部分唯一索引的 WHERE 子句由该
|
||
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(原锁定测试 test_document_model.py
|
||
# 已删除,改动本元组时须人工核对迁移内 CHECK/WHERE 字面量同口径)。
|
||
UNRESOLVED_DOC_STATUSES = (
|
||
'pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed',
|
||
)
|
||
UNRESOLVED_DOC_STATUS_WHERE = "status IN ({})".format(
|
||
', '.join(repr(s) for s in UNRESOLVED_DOC_STATUSES),
|
||
)
|
||
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')
|
||
# 调拨业务类型(合法值由 TransferTypeConfig 配置承接,合法 code 正则
|
||
# ^[a-z][a-z0-9_]{1,63}$ 上限 64);决定匹配入站数据范围。列宽 64 与配置表
|
||
# code 上限对齐(终审 I2:33~64 字符 code 建匹配时写 32 宽列会 DB 500)。
|
||
transfer_type: Mapped[str] = mapped_column(
|
||
String(64), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||
)
|
||
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',
|
||
)
|
||
matchings: Mapped[list['TransferMatching']] = 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 TransferMatching(Base):
|
||
"""一次冻结快照的匹配结果;确认/执行绑定其 Hash。"""
|
||
|
||
__tablename__ = 'transfer_matchings'
|
||
__table_args__ = (
|
||
UniqueConstraint('matching_no', name='uq_transfer_matchings_matching_no'),
|
||
CheckConstraint(
|
||
f"status IN ({', '.join(repr(s) for s in TRANSFER_MATCH_STATUSES)})",
|
||
name='ck_transfer_matchings_status',
|
||
),
|
||
Index('ix_transfer_matchings_run_status', 'run_id', 'status'),
|
||
Index('ix_transfer_matchings_business_date', 'business_date'),
|
||
)
|
||
|
||
id: Mapped[int] = mapped_column(primary_key=True)
|
||
matching_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='matching', server_default='matching')
|
||
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_external_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||
matching_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='matchings')
|
||
items: Mapped[list['TransferInvoiceItem']] = relationship(
|
||
back_populates='matching', cascade='all, delete-orphan',
|
||
)
|
||
|
||
|
||
class TransferInvoiceItem(Base):
|
||
"""匹配明细项;同一匹配内 (来源,Invoice,料号,异动日期) 唯一,保留原始行追溯。
|
||
|
||
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
||
【2026-10-14 出生翻转(ADR 0001/D4)】行不再由文件落地写入,而是匹配创建时
|
||
从库存异动档圈定生成:ledger_record_id 指向档记录(业务字段=档原值),
|
||
matching_id 创建即绑定(D17:一条档记录一生只生成一次 items 绑定)。
|
||
"""
|
||
|
||
__tablename__ = 'transfer_invoice_items'
|
||
__table_args__ = (
|
||
UniqueConstraint(
|
||
'matching_id', 'source_code', 'invoice_no', 'material_no', 'movement_date',
|
||
name='uq_transfer_invoice_items_matching_grain',
|
||
),
|
||
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_external_document_no', 'external_document_no'),
|
||
# 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决,
|
||
# 并入 tt0d1e2f3a4b 避免额外迁移节点)。
|
||
Index('ix_transfer_invoice_items_document_id', 'document_id'),
|
||
# 匹配创建圈档的占用互斥检查(D17)高频「按档记录查行」:单列索引
|
||
# (并入 tt12c3d4e5f6a7 避免额外迁移节点)。
|
||
Index('ix_transfer_invoice_items_ledger_record_id', 'ledger_record_id'),
|
||
)
|
||
|
||
id: Mapped[int] = mapped_column(primary_key=True)
|
||
# 【2026-10-14 出生翻转】matching_id 回归「创建即绑定」:行由匹配创建时从档
|
||
# 圈定生成(落地不再写 items,见 evidence_sync/ADR 0001),新行恒非空
|
||
# (模型层不强制 NOT NULL,存量兼容,服务层保证);D17 圈档互斥的占用判定
|
||
# 以本列 + 所属匹配状态为准(取消匹配即释放占用)。
|
||
matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True)
|
||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||
# 【2026-10-14 出生翻转】行来源档记录外键(可空:隔离的历史行允许 NULL);
|
||
# 行上业务字段=档原值,批号等转换只在系统边界按匹配快照规则派生(不落库)。
|
||
ledger_record_id: Mapped[Optional[int]] = mapped_column(
|
||
ForeignKey('transfer_movement_ledger.id'), nullable=True,
|
||
)
|
||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
||
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||
movement_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim,
|
||
# 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。
|
||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='')
|
||
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='')
|
||
movement_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 文本保存,杜绝浮点误差;比较在服务层完成。
|
||
movement_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
|
||
# 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段,
|
||
# 仅匹配评估/重查/写前复查在真实取数时写入;置空库存时同步置空)。NULL=无库存数据。
|
||
inventory_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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)
|
||
external_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,
|
||
)
|
||
|
||
matching: Mapped[TransferMatching] = relationship(back_populates='items')
|
||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='items')
|
||
attempts: Mapped[list['TransferAttempt']] = relationship(
|
||
back_populates='item', cascade='all, delete-orphan',
|
||
)
|
||
# 所属单(D14/D18):行随单执行推进;人工关闭调拨单(cancelled)时行脱离
|
||
# (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。
|
||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
||
document: Mapped[Optional['TransferDocument']] = relationship(back_populates='items')
|
||
# 【2026-10-14 改锚(规格 §10)】行 → 档记录只读导航:file_current 门禁与行装饰
|
||
# 的版本戳取档记录 file_sha256(档记录是证据权威)。纯 ORM relationship——
|
||
# 不新增列/索引/约束(ledger_record_id 列与索引既有),无配套迁移。
|
||
ledger_record: Mapped[Optional['TransferMovementLedger']] = relationship(
|
||
foreign_keys=[ledger_record_id],
|
||
)
|
||
|
||
|
||
class TransferDocument(Base):
|
||
"""一张 ERP 调拨单(单):五元组一组一单;doc_no/submit_timestamp 终身复用(D3)。
|
||
|
||
防双单(D7/D15):同五元组至多一张未完结单,由部分唯一索引
|
||
uq_transfer_documents_group_live 在 DB 层强制(并发提交竞态兜底;
|
||
竞态方捕获 IntegrityError 后按同组复用重试);终态单(success/
|
||
duplicate_success/cancelled)不占组锁。status 由
|
||
ck_transfer_documents_status CHECK 兜底(非法态 fail-closed)。
|
||
本表不存行集快照(D14:完整行集随写 Attempt 的 request_snapshot_json
|
||
留档);closed_reason 为人工关闭原因(D18,审计之外的可视留档,
|
||
仅失败单关闭时写入)。
|
||
"""
|
||
|
||
__tablename__ = 'transfer_documents'
|
||
__table_args__ = (
|
||
UniqueConstraint('doc_no', name='uq_transfer_documents_doc_no'),
|
||
UniqueConstraint('submit_timestamp', name='uq_transfer_documents_submit_timestamp'),
|
||
# 状态冻结枚举 DB 兜底(D15 纵深):组锁 WHERE 依赖状态字面量逐字匹配,
|
||
# 非法态必须在 DB 层拒绝(fail-closed),生成口径同 TRANSFER_DOCUMENT_STATUSES。
|
||
CheckConstraint(
|
||
f"status IN ({', '.join(repr(s) for s in TRANSFER_DOCUMENT_STATUSES)})",
|
||
name='ck_transfer_documents_status',
|
||
),
|
||
# D15 防线:同组至多一张未完结单,由 DB 强制(并发提交竞态兜底;竞态方
|
||
# 捕获 IntegrityError 按复用重试)。WHERE 子句由 UNRESOLVED_DOC_STATUSES
|
||
# 生成;同时声明 postgresql_where/sqlite_where,保证 PG 与测试 SQLite
|
||
# 建表同语义(部分唯一,非全组唯一)。
|
||
Index(
|
||
'uq_transfer_documents_group_live',
|
||
'source_code', 'external_org', 'movement_date', 'from_warehouse', 'to_warehouse',
|
||
unique=True,
|
||
postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE),
|
||
sqlite_where=text(UNRESOLVED_DOC_STATUS_WHERE),
|
||
),
|
||
Index('ix_transfer_documents_run_status', 'run_id', 'status'),
|
||
Index('ix_transfer_documents_erp_no', 'erp_document_no'),
|
||
)
|
||
|
||
id: Mapped[int] = mapped_column(primary_key=True)
|
||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
external_org: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
movement_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
# 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由
|
||
# uq_transfer_documents_doc_no / uq_transfer_documents_submit_timestamp 强制。
|
||
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
submit_timestamp: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
status: Mapped[str] = mapped_column(
|
||
String(32), nullable=False, default='pending', server_default='pending',
|
||
)
|
||
# 写中间表成功时刻(D7② 末步跳过依据)。
|
||
stage_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||
erp_document_no: 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)
|
||
# D18 人工关闭原因(仅失败单可关闭,状态 → cancelled 以释放组锁)。
|
||
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,
|
||
)
|
||
|
||
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='document')
|
||
attempts: Mapped[list['TransferAttempt']] = relationship(back_populates='document')
|
||
# 只读投影关系(评审修正轮 ①):按 run_id 取现任 Run(Task 17 已执行单投影
|
||
# serialize_executed_order / 关闭调拨单审计需要 run_no)。单向 relationship 不带
|
||
# back_populates,避免与 TransferRun.items 环纠缠;纯 ORM 增量,无迁移。
|
||
run: Mapped[Optional['TransferRun']] = relationship(foreign_keys=[run_id])
|
||
|
||
|
||
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)
|
||
# 单据级外键(D14:单:Attempt=1:N,外键在 Attempt 侧)。语义与 item_id 并存:
|
||
# 写 Attempt(external_write)挂单(document_id=单 id),其 request_snapshot_json
|
||
# 必须含单字段+完整行集;重查 Attempt(external_query)仍只挂 item,不挂单。
|
||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
||
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')
|
||
document: Mapped[Optional['TransferDocument']] = 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)
|
||
matching_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)
|
||
|
||
|
||
class TransferTypeConfig(Base):
|
||
"""调拨类型配置(ADR 0002):编码/四语言名称/启停/排序 + 范围规则/仓库定义/转换规则。
|
||
|
||
code 创建后不可变(transfer_runs.transfer_type 引用);只有停用没有删除;
|
||
配置为空时匹配链路 fail-closed(TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED)。
|
||
"""
|
||
|
||
__tablename__ = 'transfer_type_configs'
|
||
__table_args__ = (
|
||
UniqueConstraint('code', name='uq_transfer_type_configs_code'),
|
||
)
|
||
|
||
id: Mapped[int] = mapped_column(primary_key=True)
|
||
code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
names_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||
enabled: Mapped[bool] = mapped_column(default=False, server_default=text('false'), nullable=False)
|
||
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False)
|
||
scope_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||
warehouse_config_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||
transform_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||
description: Mapped[Optional[str]] = mapped_column(Text, 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)
|
||
|
||
|
||
class TransferMovementLedger(Base):
|
||
"""库存异动档(ADR 0001):外部系统入站/出站记录的平台镜像(参照 ERP inaj_t 形态)。
|
||
|
||
用途:外部系统入站(一期)/出站(结构就位,record_kind='outbound')记录统一落档;
|
||
匹配明细(items)由匹配创建时从档圈定生成(落地不再写 items,出生翻转)。
|
||
幂等增量落地:自然键 (source_code, record_kind, doc_no, line_no, line_seq,
|
||
in_out_flag, carton_id, lot_no, external_doc_no, external_line_no) 唯一约束
|
||
去重——不存在则插入、证据变化则原行更新、文件缺席不删(tt14 扩维:真实 WMS
|
||
行身份=单据+行+箱/批,carton_id/lot_no 加入键防同箱/批塌缩丢行;R7 终审:
|
||
两列同步 NOT NULL + default '',nullable 成分的 NULL 不参与 PG/SQLite 唯一
|
||
比对会逃逸约束,空值成分一律以空串入库保证唯一约束可比;2026-10-21 再扩维:
|
||
外部单号/外部项次=WMS Order #/Line # 入键,外部单据身份作为档幂等主键管控);
|
||
已执行记录 transfer_executed=true 封存(executed_doc_no 回写),永不更新、
|
||
永不复活、永不再次被圈定(防二次调拨,档级封存兜底)。
|
||
刻意双字段:record_kind(文件种类声明,权威)与 in_out_flag(数据列原值),
|
||
两者矛盾即解析错位,由落档链路打审计事件,记录照常落档。
|
||
可空语义:自然键 8 成分一律 NOT NULL(line_seq/in_out_flag/carton_id/lot_no
|
||
default '' 保证唯一约束可比、防 PG NULL 逃逸唯一比对),业务/证据列一律
|
||
nullable(外部列宽松落地);movement_date 可空——空值记录照常落档但不进
|
||
异动日期圈定(日期条件恒排除 NULL)。
|
||
source_file_id ON DELETE SET NULL:来源文件被清理(文件资产保留策略)后
|
||
档记录必须留存(事实不随文件消失,链接仅溯源)。
|
||
D 组 ⭐5 列(order_type/odm_id/odm_name/carton_id/pallet_id)为本期新增强
|
||
业务字段(进解析 Profile 可映射);🔖预留列(doc_nature/movement_type/
|
||
reason_code/source_ref_no/partner_code/remark)出货报告确认后直接映射,
|
||
免后续迁移。
|
||
"""
|
||
|
||
__tablename__ = 'transfer_movement_ledger'
|
||
__table_args__ = (
|
||
# 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。tt14 扩维 8 成分:
|
||
# carton_id/lot_no 进键(真实 WMS 行身份=单据+行+箱/批),R7 终审同步
|
||
# NOT NULL + default ''(可空成分以空串入库,防 PG NULL 逃逸唯一比对)。
|
||
# 2026-10-21 扩维 10 成分:external_doc_no/external_line_no(外部单号/
|
||
# 外部项次,WMS Order #/Line #)进键——外部单据身份作为档幂等主键管控,
|
||
# 同一外部单号+项次的重复落档/证据更新收敛到同一档行(存量行以空串参与
|
||
# 键;配置外部映射后重放同文件即按新键收敛,必要时走清空并重解析重建)。
|
||
UniqueConstraint(
|
||
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
|
||
'carton_id', 'lot_no', 'external_doc_no', 'external_line_no',
|
||
name='uq_transfer_movement_ledger_natural_key',
|
||
),
|
||
# 匹配创建圈档主路径:来源 + 记录种类 + 异动日期范围扫描。
|
||
Index('ix_transfer_movement_ledger_source_kind_date', 'source_code', 'record_kind', 'movement_date'),
|
||
# 档级封存/待匹配桶扫描:按记录种类过滤已执行位。
|
||
Index('ix_transfer_movement_ledger_kind_executed', 'record_kind', 'transfer_executed'),
|
||
)
|
||
|
||
id: Mapped[int] = mapped_column(primary_key=True)
|
||
# --- A 单据标识(自然键成分,NOT NULL;line_seq/in_out_flag 可空成分 default '')---
|
||
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
line_no: Mapped[str] = mapped_column(String(32), nullable=False)
|
||
line_seq: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
|
||
# 数据列原值(入站=收发标记),与 record_kind 交叉校验用,不参与权威判定。
|
||
in_out_flag: Mapped[str] = mapped_column(String(8), nullable=False, default='', server_default='')
|
||
# --- A+ 外部单据身份(2026-10-21 起入自然键:外部单号/外部项次 = WMS Order #/
|
||
# --- 行号;NOT NULL + default '' 与 line_seq 同口径,防 NULL 逃逸唯一比对)---
|
||
external_doc_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||
external_line_no: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
|
||
# --- B 物料与数量(数量 Decimal 文本,与 items.movement_quantity 同约定)---
|
||
material_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
material_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||
specification: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||
# 批号原值(tt14 起入自然键:NOT NULL + default '' 防 PG NULL 逃逸唯一比对;
|
||
# 空值成分以空串入库保证唯一约束可比,与 line_seq/in_out_flag 同口径)。
|
||
lot_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||
quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||
# --- C 仓储与日期(movement_date 可空:空值不进异动日期圈定)---
|
||
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
storage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||
# --- D 业务属性(⭐本期新增强业务字段;carton_id tt14 起入自然键 NOT NULL
|
||
# --- default '';🔖预留列 nullable,出货侧直接映射)---
|
||
order_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
odm_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||
# 箱号(tt14 起入自然键:NOT NULL + default '',与 lot_no 同口径,防 NULL 逃逸唯一比对)。
|
||
carton_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||
pallet_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
doc_nature: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
movement_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
reason_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||
source_ref_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
partner_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||
# --- E 平台溯源(证据字段:evidence_sync 原行更新时整体换新)---
|
||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
# 文件种类声明(tt14 值迁移后 'inbound'/'outbound',权威);与 in_out_flag 矛盾打审计事件。
|
||
record_kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||
# 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。
|
||
source_file_id: Mapped[Optional[int]] = mapped_column(
|
||
ForeignKey('freight_rpa_inbound_report_files.id', ondelete='SET NULL'), nullable=True,
|
||
)
|
||
file_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
sheet_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||
row_no: Mapped[Optional[int]] = mapped_column(Integer, 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,
|
||
)
|
||
# --- F 平台回写(档级封存:票据执行成功落单号时回写,永不解除)---
|
||
transfer_executed: Mapped[bool] = mapped_column(
|
||
default=False, server_default=text('false'), nullable=False,
|
||
)
|
||
executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
|
||
# 溯源关系:档案行 → FreightRpaInboundReportFile 原样归档文件(单向,不回挂;FreightRpaInboundReportFile
|
||
# 不感知调拨域,避免跨域 back_populates 环)。
|
||
source_file: Mapped[Optional['FreightRpaInboundReportFile']] = relationship()
|
||
|
||
|
||
@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')
|