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

@@ -0,0 +1,30 @@
"""合并 integration_calls.wire_json 与采购单号/合同/在途调拨两条 Alembic 头。
Revision ID: mg0f1a2b3c4d5
Revises: mg9e8f7a6b5c4, wd7e8f9a0b1c
Create Date: 2026-09-27 20:40:00.000000
用途:将 ``wd7e8f9a0b1c``(integration_calls.wire_json / business_ref)与
``mg9e8f7a6b5c4``(采购单号清洗 × 合同公司/在途调拨既有合并头)收成单一升级路径,
避免 ``flask db upgrade`` / pre-commit 因 Multiple head revisions 失败。
依赖:``mg9e8f7a6b5c4``、``wd7e8f9a0b1c``。
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
"""
from alembic import op # noqa: F401 - Alembic migration module contract
revision = "mg0f1a2b3c4d5"
down_revision = ("mg9e8f7a6b5c4", "wd7e8f9a0b1c")
branch_labels = None
depends_on = None
def upgrade() -> None:
"""合并 wire_json head 与采购/合同/在途调拨合并头,不执行数据库结构变更。"""
pass
def downgrade() -> None:
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
pass
@@ -0,0 +1,117 @@
"""transfer_documents 票表与行/尝试票级外键
路径:backend/migrations/versions/tt0d1e2f3a4b_add_transfer_documents.py
用途:新建 ERP 调拨单(票)表 transfer_documents——五元组一组一票,
doc_no/submit_timestamp 终身复用(D3);部分唯一索引
uq_transfer_documents_group_live 强制「同组至多一张未完结票」
(D15 防线,DB 层防双单兜底);transfer_invoice_items 与
transfer_attempts 增加可空 document_id 外键(D14:票:Attempt=1:N,
外键在 Attempt 侧;票表不存行集快照,完整行集随写 Attempt 留档)。
依赖:当前 alembic head tt9c0d1e2f3a;生产数据库为 PostgreSQL;
部分唯一索引同时声明 postgresql_where / sqlite_where(SQLite 与 PG
均支持 WHERE 形式,测试建表同语义)。
逻辑:upgrade 先建表(唯一约束 + 状态 CHECK 兜底 + 部分唯一索引 + 普通索引;
CHECK 随 create_table 落地、随 downgrade drop_table 一并移除,反向完整),
再为两张既有表加可空外键列并为 transfer_invoice_items.document_id
建单列索引(T10 票级执行按票查行);downgrade 精确反向:先删行表
document_id 索引与两 FK 列,再删票表索引、drop 票表。
Revision ID: tt0d1e2f3a4b
Revises: tt9c0d1e2f3a
Create Date: 2026-09-24 05:30:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'tt0d1e2f3a4b'
down_revision = 'tt9c0d1e2f3a'
branch_labels = None
depends_on = None
# 组锁 WHERE 子句:必须与 app/models/in_transit_transfer.py 的
# UNRESOLVED_DOC_STATUSES 完全一致(test_document_model.py 锁定双方言同口径)。
_UNRESOLVED_DOC_STATUS_WHERE = (
"status IN ('pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed')"
)
# 状态冻结枚举 CHECK(ck_transfer_documents_status):与模型侧由
# TRANSFER_DOCUMENT_STATUSES 生成的 CHECK 同口径(八态逐一对应,非法态 DB 层拒绝)。
_STATUS_CHECK = (
"status IN ('pending', 'executing', 'success', 'duplicate_success', "
"'business_failed', 'technical_failed', 'result_unknown', 'cancelled')"
)
def upgrade() -> None:
"""建票表(含全部约束/索引)并为行/尝试表加票级外键列。"""
op.create_table(
'transfer_documents',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True),
sa.Column('source_code', sa.String(length=64), nullable=False),
sa.Column('external_org', sa.String(length=64), nullable=False),
sa.Column('receipt_date', sa.String(length=16), nullable=False),
sa.Column('from_warehouse', sa.String(length=64), nullable=False),
sa.Column('to_warehouse', sa.String(length=64), nullable=False),
sa.Column('doc_no', sa.String(length=64), nullable=False),
sa.Column('submit_timestamp', sa.String(length=64), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'),
sa.Column('stage_confirmed_at', sa.DateTime(), nullable=True),
sa.Column('erp_document_no', sa.String(length=64), nullable=True),
sa.Column('error_code', sa.String(length=64), nullable=True),
sa.Column('error_message', sa.Text(), nullable=True),
sa.Column('closed_reason', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('doc_no', name='uq_transfer_documents_doc_no'),
sa.UniqueConstraint('submit_timestamp', name='uq_transfer_documents_submit_timestamp'),
sa.CheckConstraint(_STATUS_CHECK, name='ck_transfer_documents_status'),
)
op.create_index('ix_transfer_documents_run_status', 'transfer_documents', ['run_id', 'status'])
op.create_index('ix_transfer_documents_erp_no', 'transfer_documents', ['erp_document_no'])
op.create_index(
'uq_transfer_documents_group_live',
'transfer_documents',
['source_code', 'external_org', 'receipt_date', 'from_warehouse', 'to_warehouse'],
unique=True,
postgresql_where=sa.text(_UNRESOLVED_DOC_STATUS_WHERE),
sqlite_where=sa.text(_UNRESOLVED_DOC_STATUS_WHERE),
)
# 行表加票级外键(D18 关票脱离语义由服务层置 NULL,列为可空)。
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.add_column(sa.Column('document_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key(
'fk_transfer_invoice_items_document_id', 'transfer_documents',
['document_id'], ['id'],
)
# 票级执行(T10)高频「按票查行」:document_id 单列索引(控制器裁决并入本迁移)。
op.create_index(
'ix_transfer_invoice_items_document_id',
'transfer_invoice_items', ['document_id'],
)
# 尝试表加票级外键(写 Attempt 挂票;重查 Attempt 仍只挂 item)。
with op.batch_alter_table('transfer_attempts') as batch_op:
batch_op.add_column(sa.Column('document_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key(
'fk_transfer_attempts_document_id', 'transfer_documents',
['document_id'], ['id'],
)
def downgrade() -> None:
"""精确反向:先删行表 document_id 索引与两 FK 列(约束随列移除),再删索引并 drop 票表。"""
op.drop_index('ix_transfer_invoice_items_document_id', table_name='transfer_invoice_items')
with op.batch_alter_table('transfer_attempts') as batch_op:
batch_op.drop_column('document_id')
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.drop_column('document_id')
op.drop_index('uq_transfer_documents_group_live', table_name='transfer_documents')
op.drop_index('ix_transfer_documents_run_status', table_name='transfer_documents')
op.drop_index('ix_transfer_documents_erp_no', table_name='transfer_documents')
op.drop_table('transfer_documents')
@@ -0,0 +1,26 @@
"""transfer_invoice_items.matching_id 放开非空
Revision ID: tt1a2b3c4d5e6f
Revises: tt0d1e2f3a4b
Create Date: 2026-09-25
用途:落地证据同步行(evidence_sync)尚无匹配归属,matching_id 允许 NULL。
注意:downgrade 要求表中不存在 matching_id IS NULL 的行(先清同步行再降级)。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt1a2b3c4d5e6f'
down_revision = 'tt0d1e2f3a4b'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.alter_column('matching_id', existing_type=sa.Integer(), nullable=True)
def downgrade():
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.alter_column('matching_id', existing_type=sa.Integer(), nullable=False)
@@ -0,0 +1,51 @@
"""
backend/migrations/versions/tt5b6c7d8e9f_drop_integration_calls_operation_unique.py
用途:integration_calls.operation_id 唯一约束 → 普通索引(多步顺序引擎审计 N 行同 operation_id)。
依赖:Alembic head tta9b0c1d2e3;IntegrationCall 模型已同步删除
UniqueConstraint('operation_id') 并新增 Index('ix_integration_calls_operation_id')。
逻辑:多步顺序引擎(Task 4)一次能力调用按步骤落 N 条审计、共享同一 operation_id
(计划 D13/全局约束:一票一次执行 = N 条,按 operation_id 串联);原唯一约束
uq_integration_calls_operation_id 兼作的索引由普通索引
ix_integration_calls_operation_id 补回(无任何代码按 operation_id 查询单行,
删约束无消费方风险)。downgrade 精确反向(重建唯一约束);若库中已存在
同 operation_id 多行,downgrade 会因唯一约束失败——这是预期:
多步审计本身就不兼容旧约束(必要时应先人工清理多步行)。
Revision ID: tt5b6c7d8e9f
Revises: tta9b0c1d2e3
Create Date: 2026-09-24 03:00:00.000000
"""
from __future__ import annotations
from alembic import op
revision = 'tt5b6c7d8e9f'
down_revision = 'tta9b0c1d2e3'
branch_labels = None
depends_on = None
# 与模型 IntegrationCall.__table_args__ 同源的约束/索引命名(ic1a2b3c4d5f 创建时的原名)。
_UQ_NAME = 'uq_integration_calls_operation_id'
_IX_NAME = 'ix_integration_calls_operation_id'
def upgrade() -> None:
"""删 operation_id 唯一约束,补回同名普通索引(查询性能不回退)。"""
# batch_alter_table:SQLite 不支持 DROP CONSTRAINT,须经批处理模式重建表;
# PostgreSQL 等方言按普通 ALTER 执行。
with op.batch_alter_table('integration_calls') as batch:
batch.drop_constraint(_UQ_NAME, type_='unique')
op.create_index(_IX_NAME, 'integration_calls', ['operation_id'])
def downgrade() -> None:
"""回滚:删普通索引并重建唯一约束。
注意:若已存在同 operation_id 多行(多步审计的正常数据形态),重建唯一约束
将失败——这是预期,多步审计与旧约束不兼容;必要时应先人工归并/清理多步行。
"""
op.drop_index(_IX_NAME, table_name='integration_calls')
with op.batch_alter_table('integration_calls') as batch:
batch.create_unique_constraint(_UQ_NAME, ['operation_id'])
@@ -0,0 +1,54 @@
"""add database connector type and db_kind column
Revision ID: tt7a8b9c0d1e
Revises: rn1a2b3c4d5e6
Create Date: 2026-09-24 00:30:00.000000
用途:Integration Connector 扩枚举 database;客户端实例新增 db_kind 专列
(mysql/oracle/sqlserver/postgresql);重建 client/interface 两表 connector_type CHECK。
依赖:当前 alembic head rn1a2b3c4d5e6;integration_client_instances /
integration_interface_definitions 已存在。
逻辑:先删后建两表 CHECK(含 database);client_instances 加可空 db_kind 列
(存量 rest/soap 为 NULL);downgrade 反向(删列 + CHECK 回 rest/soap)。
采用与 if1b2c3d4e5i 相同的直连 drop/create(生产 PostgreSQL);不走 SQLite
batch 表重建,避免同批改 CHECK+加列时的临时表约束冲突。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt7a8b9c0d1e'
down_revision = 'rn1a2b3c4d5e6'
branch_labels = None
depends_on = None
_CLIENT_CK = 'ck_integration_client_instances_connector_type'
_IFACE_CK = 'ck_integration_interface_definitions_connector_type'
_TYPES_WITH_DATABASE = "connector_type IN ('rest', 'soap', 'database')"
_TYPES_LEGACY = "connector_type IN ('rest', 'soap')"
def upgrade() -> None:
"""扩 connector_type CHECK 含 database,并为客户端实例加 db_kind 列。"""
# [STEP 1] 客户端实例:先删后建 CHECK,再加 db_kind 列。
op.drop_constraint(_CLIENT_CK, 'integration_client_instances', type_='check')
op.create_check_constraint(_CLIENT_CK, 'integration_client_instances', _TYPES_WITH_DATABASE)
op.add_column(
'integration_client_instances',
sa.Column('db_kind', sa.String(length=32), nullable=True),
)
# [STEP 2] 接口定义:同步扩 CHECK(接口类型跟随客户端)。
op.drop_constraint(_IFACE_CK, 'integration_interface_definitions', type_='check')
op.create_check_constraint(_IFACE_CK, 'integration_interface_definitions', _TYPES_WITH_DATABASE)
def downgrade() -> None:
"""回滚:删 db_kind,两表 CHECK 恢复为 rest/soap(须无 database 存量行)。"""
op.drop_constraint(_IFACE_CK, 'integration_interface_definitions', type_='check')
op.create_check_constraint(_IFACE_CK, 'integration_interface_definitions', _TYPES_LEGACY)
op.drop_column('integration_client_instances', 'db_kind')
op.drop_constraint(_CLIENT_CK, 'integration_client_instances', type_='check')
op.create_check_constraint(_CLIENT_CK, 'integration_client_instances', _TYPES_LEGACY)
@@ -0,0 +1,36 @@
"""add transfer_doc_no_seq sequence
Revision ID: tt8b9c0d1e2f
Revises: tt5b6c7d8e9f
Create Date: 2026-09-24 04:00:00.000000
用途:为在途调拨来源单号(计划 D2)创建 PostgreSQL 全局序列
transfer_doc_no_seq(单号格式 {org}-OR-{yyMMdd}{seq:05d})。
依赖:当前 alembic head tt5b6c7d8e9f;生产数据库为 PostgreSQL。
逻辑:CREATE SEQUENCE IF NOT EXISTS(START WITH 1 / INCREMENT BY 1,
全局单调递增、不按日重置;超 99999 由应用层 %05d 自然扩位);
IF NOT EXISTS 防重跑;downgrade 用 DROP SEQUENCE IF EXISTS 反向。
SQLite 测试库无序列,不做兼容——测试一律注入 sequence_loader 替身。
"""
from alembic import op
revision = 'tt8b9c0d1e2f'
down_revision = 'tt5b6c7d8e9f'
branch_labels = None
depends_on = None
_CREATE_SEQ_SQL = (
"CREATE SEQUENCE IF NOT EXISTS transfer_doc_no_seq START WITH 1 INCREMENT BY 1"
)
_DROP_SEQ_SQL = "DROP SEQUENCE IF EXISTS transfer_doc_no_seq"
def upgrade() -> None:
"""创建全局单号序列(幂等:IF NOT EXISTS 防重跑)。"""
op.execute(_CREATE_SEQ_SQL)
def downgrade() -> None:
"""回滚:删除全局单号序列(IF EXISTS 防未建先删)。"""
op.execute(_DROP_SEQ_SQL)
@@ -0,0 +1,36 @@
"""transfer_invoice_items 新增交易单位列
Revision ID: tt9c0d1e2f3a
Revises: tt8b9c0d1e2f
Create Date: 2026-09-24 05:00:00.000000
用途:transfer_invoice_items 增加 unit(交易单位,计划 D4:movement 契约第
11 字段)——解析自异动文件「单位」列原值(仅 trim、不换算),作为 ERP
写入行(gls_cm19)输入;空值行在匹配阶段落 blocked_missing_unit。
依赖:当前 alembic head tt8b9c0d1e2f;生产数据库为 PostgreSQL。
逻辑:追加可空文本列(String(32))带 server_default='',存量行归空串
(与 ORM default 一致,避免 NULL 展示歧义);unit 不参与匹配 Hash
快照(口径冻结,历史预检哈希不因本次字段追加而变化);downgrade 直接删列。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt9c0d1e2f3a'
down_revision = 'tt8b9c0d1e2f'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""明细行表加交易单位列(存量行默认空串,匹配阶段对空值行级阻断)。"""
op.add_column(
'transfer_invoice_items',
sa.Column('unit', sa.String(length=32), nullable=True, server_default='', comment='交易单位原值(movement 契约第 11 字段,仅 trim 不换算)'),
)
def downgrade() -> None:
"""回滚:删除交易单位列(存量数据随列丢弃,无其他依赖)。"""
op.drop_column('transfer_invoice_items', 'unit')
@@ -0,0 +1,83 @@
"""
backend/migrations/versions/tta9b0c1d2e3_add_binding_steps_json.py
用途:IntegrationBinding 增加 steps_json(一对多有序绑定步骤);存量行回填为单元素数组。
依赖:Alembic head tt7a8b9c0d1e;integration_bindings 已有 interface_definition_code /
param_mapping_json(旧单步列保留至 P2)。
逻辑:加列(默认 [])→ 按旧列回填 [{"interface_code", "param_mapping_json"}];
downgrade 仅删列。旧列不删、不改 NOT NULL(解析层优先读 steps_json)。
Revision ID: tta9b0c1d2e3
Revises: tt7a8b9c0d1e
Create Date: 2026-09-24 01:10:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = 'tta9b0c1d2e3'
down_revision = 'tt7a8b9c0d1e'
branch_labels = None
depends_on = None
# 与 context_selector_json / param_mapping_json 同类型约定:PostgreSQL JSONB,其余 JSON。
STEPS_JSON = sa.JSON().with_variant(postgresql.JSONB(), 'postgresql')
def upgrade() -> None:
"""加 steps_json 并将存量单步绑定回填为一元素数组。"""
# [STEP 1] 加列(server_default 便于存量 NOT NULL 加列;回填后业务不再依赖默认空数组)。
op.add_column(
'integration_bindings',
sa.Column('steps_json', STEPS_JSON, nullable=False, server_default=sa.text("'[]'")),
)
# [STEP 2] 存量回填:旧 interface_definition_code + param_mapping_json → 单元素 steps。
# PostgreSQL:jsonb_build_*;其他方言(如 SQLite 迁移单测)用 JSON 文本拼接兜底。
bind = op.get_bind()
if bind.dialect.name == 'postgresql':
op.execute(
sa.text(
"""
UPDATE integration_bindings
SET steps_json = jsonb_build_array(
jsonb_build_object(
'interface_code', interface_definition_code,
'param_mapping_json', COALESCE(param_mapping_json, '{}'::jsonb)
)
)
"""
)
)
else:
# SQLite / 其他:用 Python 侧逐行回填,避免方言 JSON 函数差异。
rows = bind.execute(
sa.text(
'SELECT id, interface_definition_code, param_mapping_json '
'FROM integration_bindings'
)
).fetchall()
import json
for row_id, iface_code, mapping in rows:
# 原生 SELECT 绕过 ORM 类型层:JSON 列读回是 JSON 文本,须先还原为
# dict 再回填,否则 steps 里 param_mapping_json 是字符串,
# 解析层会按 param_mapping_not_dict fail-closed(存量绑定全灭)。
if isinstance(mapping, str):
try:
mapping = json.loads(mapping)
except (TypeError, ValueError):
mapping = {}
steps = [{'interface_code': iface_code, 'param_mapping_json': mapping or {}}]
bind.execute(
sa.text('UPDATE integration_bindings SET steps_json = :steps WHERE id = :id'),
{'steps': json.dumps(steps), 'id': row_id},
)
def downgrade() -> None:
"""回滚:删除 steps_json(旧单步列仍在,可继续服务)。"""
op.drop_column('integration_bindings', 'steps_json')
@@ -0,0 +1,35 @@
"""Add integration_calls.wire_json.
Revision ID: wd7e8f9a0b1c
Revises: tt1a2b3c4d5e6f
Create Date: 2026-09-27 00:00:00.000000
用途:集成调用审计增列 wire_json(传输层线级事实)与 business_ref(通用业务
锚点:调用方透传的业务单号/任务号,能力无关,不传为 NULL)。
依赖:integration_calls 表。
逻辑:均可空;历史行保持 NULL(前端如实展示「无线级详情」,不回填)。
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "wd7e8f9a0b1c"
down_revision = "tt1a2b3c4d5e6f"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("integration_calls", sa.Column("wire_json", sa.JSON(), nullable=True))
op.add_column("integration_calls",
sa.Column("business_ref", sa.String(length=128), nullable=True))
op.create_index("ix_integration_calls_business_ref", "integration_calls", ["business_ref"])
def downgrade() -> None:
op.drop_index("ix_integration_calls_business_ref", table_name="integration_calls")
op.drop_column("integration_calls", "business_ref")
op.drop_column("integration_calls", "wire_json")