Merge branch 'hugo-shipping-notice' into test

This commit is contained in:
hugo committed 2026-09-27 21:38:28 +08:00
commit e35f01bbe9
163 files changed
+21008 -2545

No files matched your search

+2
View File
@@ -204,6 +204,7 @@ from app.models.in_transit_transfer import (
TransferArchive,
TransferAttempt,
TransferAuditEvent,
TransferDocument,
TransferInvoiceItem,
TransferMatching,
TransferRun,
@@ -426,6 +427,7 @@ __all__ = [
'TransferRun',
'TransferSourceJob',
'TransferMatching',
'TransferDocument',
'TransferInvoiceItem',
'TransferAttempt',
'TransferAuditEvent',
+111 -3
View File
@@ -1,10 +1,12 @@
"""models/in_transit_transfer.py
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
Attempt、AuditEvent 与 Archive。
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive。
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖;
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖;
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
"""
@@ -59,6 +61,21 @@ 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 锁定)。
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')
@@ -215,10 +232,17 @@ class TransferInvoiceItem(Base):
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: Mapped[int] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=False, index=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)
@@ -226,6 +250,9 @@ class TransferInvoiceItem(Base):
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='')
@@ -253,6 +280,82 @@ class TransferInvoiceItem(Base):
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):
@@ -274,6 +377,10 @@ class TransferAttempt(Base):
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')
@@ -287,6 +394,7 @@ class TransferAttempt(Base):
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):
+37 -10
View File
@@ -1,11 +1,13 @@
"""models/integration_connector.py
用途:Integration Connector(外部系统连接器框架)P1 配置与运行时模型:
用途:Integration Connector(外部系统连接器框架)配置与运行时模型:
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。
连接器类型(rest/soap/database)与状态均用 CheckConstraint 兜底;database 客户端
另有 db_kind 专列(mysql/oracle/sqlserver/postgresql),fail-closed 语义在服务层。
Binding.steps_json 表达一对多有序接口配方(D10);旧单步列保留至 P2。
"""
from __future__ import annotations
@@ -31,8 +33,10 @@ from sqlalchemy.dialects.postgresql import JSONB
from app.models.base import Base
# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。
CONNECTOR_TYPES = ('rest', 'soap')
# 连接器类型白名单;模型 CHECK 由本常量动态生成,扩枚举须配套 Alembic 迁移重建 CHECK。
CONNECTOR_TYPES = ('rest', 'soap', 'database')
# database 专属库种(D16):专列 db_kind,非 config_json;API/transport 同源 fail-closed。
DB_KINDS = ('mysql', 'oracle', 'sqlserver', 'postgresql')
CONFIG_STATUSES = ('draft', 'published', 'retired')
CREDENTIAL_STATUSES = ('active', 'rotating', 'retired')
@@ -89,9 +93,12 @@ class IntegrationClientInstance(Base):
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点);
# database 为 host:port[/database|service_name]。
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# database 专属库种(仅 connector_type='database' 有值;rest/soap 为 NULL)。
db_kind: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
credential_ref_code: Mapped[Optional[str]] = mapped_column(
ForeignKey('integration_credential_references.code'), nullable=True,
@@ -144,7 +151,12 @@ class IntegrationInterfaceDefinition(Base):
class IntegrationBinding(Base):
"""绑定:(Capability, context_selector) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。"""
"""绑定:(Capability, context_selector) → 有序接口步骤配方;版本化、可发布、可退役。
一对多有序(D10/D13):steps_json = [{interface_code, param_mapping_json}, ...];
每步客户端由接口归属自带。旧列 interface_definition_code / param_mapping_json /
client_instance_code 迁移后保留镜像首步,解析不再读取,P2 删除。
"""
__tablename__ = 'integration_bindings'
__table_args__ = (
@@ -165,8 +177,11 @@ class IntegrationBinding(Base):
capability: Mapped[str] = mapped_column(String(128), nullable=False)
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
# 域参数 → 接口参数的声明式映射(map_response 规范:{接口参数: {expr/template/transform/args}});
# 空对象 = 域参数同名直通。结构属绑定(capability↔接口的翻译契约),不属接口定义。
# 有序步骤配方:每步 {interface_code, param_mapping_json};客户端由接口归属推导。
steps_json: Mapped[list[dict[str, Any]]] = mapped_column(
CONTEXT_SELECTOR_JSON, nullable=False, default=list,
)
# 域参数 → 接口参数的声明式映射(旧单步列,P2 删;迁移后镜像 steps_json[0])。
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
client_instance_code: Mapped[str] = mapped_column(
@@ -188,13 +203,20 @@ class IntegrationBinding(Base):
class IntegrationCall(Base):
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。"""
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。
多步顺序引擎(Task 4)一次能力调用按步骤落 N 条审计、共享同一 operation_id
(一票一次执行 = N 条,按 operation_id 串联 + binding_snapshot_json.step_index
定位),故 operation_id 无唯一约束;原唯一约束兼作的索引由普通索引
ix_integration_calls_operation_id 补回(迁移 tt5b6c7d8e9f)。
"""
__tablename__ = 'integration_calls'
__table_args__ = (
UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
Index('ix_integration_calls_operation_id', 'operation_id'),
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
Index('ix_integration_calls_trace_id', 'trace_id'),
Index('ix_integration_calls_business_ref', 'business_ref'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -206,4 +228,9 @@ class IntegrationCall(Base):
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='')
# 线级事实(database 最终 SQL/绑定/行数;soap endpoint+XML;rest HTTP 往返)。
# 可空:历史行与未捕获场景为 NULL,前台如实展示。
wire_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
# 通用业务锚点:调用方透传的业务单号/任务号(能力无关;不传为 NULL)。
business_ref: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)