Files
syops/backend/app/models/in_transit_transfer.py
hugo abf3d48927 feat(in-transit-transfer): 自动调拨联动收料就绪并分层来源错误
- 调度整合:退役 in_transit_receipt_file_job,收料归档收敛 shipping_receipt_rpa_archive,排程注册表统一
- 自动调拨 Job:调拨前确保各来源当日收料文件就绪(缺失自动触发收料 RPA),严格等量匹配后生成 ERP 调拨单
- worker 手动唤醒:排程工作台支持手动唤醒与 runs 透视,heartbeat 协议同步
- 收料缺失幸存 T2:parse_failed 状态落库(迁移 q4c5)
- 来源错误分层与 stale 时钟换源:改挂 inventory_checked_at 库存查得时刻,展示阈值与执行门禁解耦(迁移 t5a6)
- 新增 wecom_sender 企微通知:每非空 Run 汇总一条,通知失败不影响 ERP 结果
- 同步排程工作台/调拨卡片前端、chat/admin 文案四语言、RPA 脚本与测试全家
2026-09-30 00:20:06 +08:00

489 lines
28 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""models/in_transit_transfer.py
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive。
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
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', 'matching', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
)
TRANSFER_RUN_STATUSES = (
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
'success', 'partial_failed', 'failed', 'cancelled',
)
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
TRANSFER_RUN_TYPES = (
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
)
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',
),
CheckConstraint(
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
name='ck_transfer_runs_transfer_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')
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定匹配收料数据范围。
transfer_type: Mapped[str] = mapped_column(
String(32), 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 业务口径):同一批号跨料号/跨日期拆分为多行。
"""
__tablename__ = 'transfer_invoice_items'
__table_args__ = (
UniqueConstraint(
'matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_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'),
)
id: Mapped[int] = mapped_column(primary_key=True)
# 行归属解耦后 matching_id 仅留痕(首次创建值);落地证据同步行尚无匹配归属
# (2026-09-25),放开非空。uq_transfer_invoice_items_matching_grain 含本列,
# NULL 行不受该唯一约束保护——同步的幂等去重由 evidence_sync 应用层按
# (source, invoice, material, receipt_date) 四元组负责(见 evidence_sync)。
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)
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 源映射行匹配键(拨出库位解析审计)。
receipt_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='')
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)
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')
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', 'receipt_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)
receipt_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)
@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')