Merge branch 'hugo-shipping-notice' into dev

# Conflicts:
#	backend/app/api/__init__.py
#	backend/app/jobs/types.py
#	backend/app/models/__init__.py
#	backend/app/services/schedule/job_registry.py
#	docs/features/README.md
#	docs/funclist.md
#	docs/tec.md
#	frontend/src/locales/zh-CN/admin.json
This commit is contained in:
hugo committed 2026-09-07 10:15:13 +08:00
commit dac31e48bd
691 files changed
+53341 -14863

No files matched your search

@@ -0,0 +1,157 @@
"""add integration connector tables
Revision ID: ic1a2b3c4d5f
Revises: it1a2b3c4d5e
Create Date: 2026-08-27 21:00:00.000000
用途:Integration Connector(外部系统连接器框架)P1 配置与运行模型建表:
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
依赖:integration_* 全部新表;不依赖既有 shipping/transfer 表。
逻辑:配置层实体维护版本与状态;IntegrationCall 记录一次技术调用(冻结绑定版本 + 脱敏摘要)。
连接器类型(rest/soap)与状态用 CheckConstraint 兜底;fail-closed 语义在服务层。
"""
from alembic import op
import sqlalchemy as sa
revision = 'ic1a2b3c4d5f'
down_revision = 'it1a2b3c4d5e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建 5 张连接器框架表(先建凭据/客户端,再建接口/绑定,最后调用记录)。"""
op.create_table(
'integration_credential_references',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('code', sa.String(length=64), nullable=False),
sa.Column('secret_ref', sa.String(length=128), nullable=False),
sa.Column('secret_provider', sa.String(length=32), nullable=False, server_default='env'),
sa.Column('credential_type', sa.String(length=32), nullable=False, server_default='password'),
sa.Column('version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('status', sa.String(length=16), nullable=False, server_default='active'),
sa.Column('last_verified_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('code', name='uq_integration_credential_references_code'),
sa.CheckConstraint(
"status IN ('active', 'rotating', 'retired')",
name='ck_integration_credential_references_status',
),
)
op.create_table(
'integration_client_instances',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('code', sa.String(length=64), nullable=False),
sa.Column('name', sa.String(length=128), nullable=False),
sa.Column('connector_type', sa.String(length=16), nullable=False),
sa.Column('environment', sa.String(length=16), nullable=False, server_default='prod'),
sa.Column('config_json', sa.JSON(), nullable=False),
sa.Column('credential_ref_code', sa.String(length=64), sa.ForeignKey('integration_credential_references.code'), nullable=True),
sa.Column('enabled', sa.Boolean(), nullable=False, server_default='true'),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('code', name='uq_integration_client_instances_code'),
sa.CheckConstraint(
"connector_type IN ('rest', 'soap')",
name='ck_integration_client_instances_connector_type',
),
)
op.create_index(
'ix_integration_client_instances_type_env',
'integration_client_instances', ['connector_type', 'environment'],
)
op.create_table(
'integration_interface_definitions',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('code', sa.String(length=64), nullable=False),
sa.Column('name', sa.String(length=128), nullable=False),
sa.Column('client_instance_code', sa.String(length=64), sa.ForeignKey('integration_client_instances.code'), nullable=False),
sa.Column('connector_type', sa.String(length=16), nullable=False),
sa.Column('request_spec_json', sa.JSON(), nullable=False),
sa.Column('input_schema_json', sa.JSON(), nullable=False),
sa.Column('response_mapping_json', sa.JSON(), nullable=False),
sa.Column('output_schema_json', sa.JSON(), nullable=False),
sa.Column('version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'),
sa.Column('enabled', sa.Boolean(), nullable=False, server_default='true'),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('code', name='uq_integration_interface_definitions_code'),
sa.CheckConstraint(
"connector_type IN ('rest', 'soap')",
name='ck_integration_interface_definitions_connector_type',
),
sa.CheckConstraint(
"status IN ('draft', 'published', 'retired')",
name='ck_integration_interface_definitions_status',
),
)
op.create_index(
'ix_integration_interface_definitions_client',
'integration_interface_definitions', ['client_instance_code'],
)
op.create_table(
'integration_bindings',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('capability', sa.String(length=128), nullable=False),
sa.Column('context_selector_json', sa.JSON().with_variant(sa.dialects.postgresql.JSONB(), 'postgresql'), nullable=False),
sa.Column('client_instance_code', sa.String(length=64), sa.ForeignKey('integration_client_instances.code'), nullable=False),
sa.Column('interface_definition_code', sa.String(length=64), sa.ForeignKey('integration_interface_definitions.code'), nullable=False),
sa.Column('mapping_version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('priority', sa.Integer(), nullable=False, server_default='0'),
sa.Column('environment', sa.String(length=16), nullable=False, server_default='prod'),
sa.Column('effective_from', sa.DateTime(), nullable=True),
sa.Column('effective_to', sa.DateTime(), nullable=True),
sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint(
'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx',
),
sa.CheckConstraint(
"status IN ('draft', 'published', 'retired')",
name='ck_integration_bindings_status',
),
sa.CheckConstraint('priority >= 0', name='ck_integration_bindings_priority'),
)
op.create_index(
'ix_integration_bindings_cap_env_status',
'integration_bindings', ['capability', 'environment', 'status'],
)
op.create_table(
'integration_calls',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('operation_id', sa.String(length=128), nullable=False),
sa.Column('capability', sa.String(length=128), nullable=False),
sa.Column('binding_snapshot_json', sa.JSON(), nullable=False),
sa.Column('request_summary_json', sa.JSON(), nullable=False),
sa.Column('response_summary_json', sa.JSON(), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('elapsed_ms', sa.Integer(), nullable=False, server_default='0'),
sa.Column('trace_id', sa.String(length=64), nullable=False, server_default=''),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
)
op.create_index('ix_integration_calls_capability_created', 'integration_calls', ['capability', 'created_at'])
op.create_index('ix_integration_calls_trace_id', 'integration_calls', ['trace_id'])
def downgrade() -> None:
"""回滚:按外键依赖逆序删除连接器表。"""
op.drop_index('ix_integration_calls_trace_id', table_name='integration_calls')
op.drop_index('ix_integration_calls_capability_created', table_name='integration_calls')
op.drop_table('integration_calls')
op.drop_index('ix_integration_bindings_cap_env_status', table_name='integration_bindings')
op.drop_table('integration_bindings')
op.drop_index('ix_integration_interface_definitions_client', table_name='integration_interface_definitions')
op.drop_table('integration_interface_definitions')
op.drop_index('ix_integration_client_instances_type_env', table_name='integration_client_instances')
op.drop_table('integration_client_instances')
op.drop_table('integration_credential_references')
@@ -0,0 +1,45 @@
"""add purpose to inventory parsing profiles
Revision ID: if1b2c3d4e5g
Revises: ic1a2b3c4d5f
Create Date: 2026-08-28 10:30:00.000000
用途:把库存解析规则泛化为通用文件解析规则——为 shipping_inventory_parsing_profiles
增 purpose 列(inventory / movement)。inventory 沿用库存字段目录;movement
端点用定死领域字段(MOVEMENT_FIELDS),供收料/异动文件映射。既有行默认 inventory,
不改变既有库存语义。
依赖:shipping_inventory_parsing_profiles 表。
逻辑:仅加列 + CheckConstraint,无数据回填(默认 inventory)。
"""
from alembic import op
import sqlalchemy as sa
revision = 'if1b2c3d4e5g'
down_revision = 'ic1a2b3c4d5f'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增 purpose 列并加 CheckConstraint(inventory / movement)。"""
op.add_column(
'shipping_inventory_parsing_profiles',
sa.Column('purpose', sa.String(length=16), nullable=False, server_default='inventory'),
)
op.create_check_constraint(
'ck_shipping_inventory_parsing_profiles_purpose',
'shipping_inventory_parsing_profiles',
"purpose IN ('inventory', 'movement')",
)
def downgrade() -> None:
"""移除 purpose 约束与列。"""
op.drop_constraint(
'ck_shipping_inventory_parsing_profiles_purpose',
'shipping_inventory_parsing_profiles',
type_='check',
)
op.drop_column('shipping_inventory_parsing_profiles', 'purpose')
@@ -0,0 +1,53 @@
"""add parsing_profile_id to shipping_receipt_report_configs
Revision ID: if1b2c3d4e5h
Revises: if1b2c3d4e5g
Create Date: 2026-08-28 10:45:00.000000
用途:收料报表配置绑定其收料文件解析规则(purpose='movement')。空则无法解析收料文件。
依赖:shipping_receipt_report_configs 表 + shipping_inventory_parsing_profiles 表。
逻辑:仅新增可空外键列,无数据回填。
"""
from alembic import op
import sqlalchemy as sa
revision = 'if1b2c3d4e5h'
down_revision = 'if1b2c3d4e5g'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增 parsing_profile_id 外键列。"""
op.add_column(
'shipping_receipt_report_configs',
sa.Column('parsing_profile_id', sa.Integer(), nullable=True),
)
op.create_index(
'ix_shipping_receipt_report_configs_parsing_profile',
'shipping_receipt_report_configs',
['parsing_profile_id'],
)
op.create_foreign_key(
'fk_shipping_receipt_report_configs_parsing_profile',
'shipping_receipt_report_configs',
'shipping_inventory_parsing_profiles',
['parsing_profile_id'],
['id'],
)
def downgrade() -> None:
"""移除外键、索引与列。"""
op.drop_constraint(
'fk_shipping_receipt_report_configs_parsing_profile',
'shipping_receipt_report_configs',
type_='foreignkey',
)
op.drop_index(
'ix_shipping_receipt_report_configs_parsing_profile',
table_name='shipping_receipt_report_configs',
)
op.drop_column('shipping_receipt_report_configs', 'parsing_profile_id')
@@ -0,0 +1,42 @@
"""add file_ready to transfer_source_jobs status constraint
Revision ID: if1b2c3d4e5i
Revises: if1b2c3d4e5h
Create Date: 2026-08-28 11:15:00.000000
用途:让 TransferSourceJob.status 状态集与来源准备流程阶段(file_ready)对齐。
原 CHECK 缺少 file_ready,导致来源文件就绪时 job 无法用 file_ready 表达
(create_precheck 只能硬映射为 pending)。
依赖:transfer_source_jobs 表。
逻辑:drop 旧 CHECK → 重新 create(追加 file_ready),无数据回填。
"""
from alembic import op
revision = 'if1b2c3d4e5i'
down_revision = 'if1b2c3d4e5h'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""更新 status 检查约束,允许 file_ready。"""
op.drop_constraint('ck_transfer_source_jobs_status', 'transfer_source_jobs', type_='check')
op.create_check_constraint(
'ck_transfer_source_jobs_status',
'transfer_source_jobs',
"status IN ('pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', "
"'parsing', 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')",
)
def downgrade() -> None:
"""恢复原检查约束(不含 file_ready)。"""
op.drop_constraint('ck_transfer_source_jobs_status', 'transfer_source_jobs', type_='check')
op.create_check_constraint(
'ck_transfer_source_jobs_status',
'transfer_source_jobs',
"status IN ('pending', 'checking_file', 'waiting_rpa_callback', 'parsing', "
"'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')",
)
@@ -0,0 +1,275 @@
"""add in-transit transfer domain tables
Revision ID: it1a2b3c4d5e
Revises: hw6x7y8z9a0b
Create Date: 2026-08-27 14:00:00.000000
用途:在途仓自动调拨 Agent 一期领域模型建表:Run、SourceJob、Precheck、
InvoiceItem、Attempt、AuditEvent 与 Archive。
依赖:transfer_* 全部新表;不依赖既有 shipping 表(来源配置在服务层只读复用)。
逻辑:Run 为业务真相源;InvoiceItem 按 (precheck_id, invoice_no) 唯一;
AuditEvent 只追加;Archive 记录 MinIO 对象路径与 Hash。
"""
from alembic import op
import sqlalchemy as sa
revision = 'it1a2b3c4d5e'
down_revision = 'hw6x7y8z9a0b'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建 7 张调拨领域表。"""
op.create_table(
'transfer_runs',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_no', sa.String(length=64), nullable=False),
sa.Column('trigger_type', sa.String(length=16), nullable=False, server_default='manual'),
sa.Column('business_date', sa.String(length=16), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'),
sa.Column('source_codes_json', sa.JSON(), nullable=False),
sa.Column('counts_json', sa.JSON(), nullable=False),
sa.Column('result_summary_json', sa.JSON(), nullable=False),
sa.Column('notification_status', sa.String(length=16), nullable=False, server_default='pending'),
sa.Column('notification_error_code', sa.String(length=64), nullable=True),
sa.Column('notification_error_message', sa.Text(), nullable=True),
sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('started_at', sa.DateTime(), nullable=True),
sa.Column('completed_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('run_no', name='uq_transfer_runs_run_no'),
sa.CheckConstraint(
"status IN ('queued', 'preparing_files', 'prechecking', 'ready_to_execute', "
"'executing', 'success', 'partial_failed', 'failed', 'cancelled')",
name='ck_transfer_runs_status',
),
sa.CheckConstraint(
"notification_status IN ('pending', 'success', 'failed')",
name='ck_transfer_runs_notification_status',
),
sa.CheckConstraint(
"trigger_type IN ('manual', 'schedule')",
name='ck_transfer_runs_trigger_type',
),
)
op.create_index('ix_transfer_runs_status_created', 'transfer_runs', ['status', 'created_at'])
op.create_index('ix_transfer_runs_business_date', 'transfer_runs', ['business_date'])
op.create_table(
'transfer_source_jobs',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=False),
sa.Column('source_code', sa.String(length=64), nullable=False),
sa.Column('source_config_version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'),
sa.Column('file_no', sa.String(length=64), nullable=True),
sa.Column('file_sha256', 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('lease_until', sa.DateTime(), nullable=True),
sa.Column('started_at', sa.DateTime(), nullable=True),
sa.Column('finished_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('run_id', 'source_code', name='uq_transfer_source_jobs_run_source'),
sa.CheckConstraint(
"status IN ('pending', 'checking_file', 'waiting_rpa_callback', 'parsing', "
"'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')",
name='ck_transfer_source_jobs_status',
),
)
op.create_index('ix_transfer_source_jobs_source_status', 'transfer_source_jobs', ['source_code', 'status'])
op.create_table(
'transfer_prechecks',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('precheck_no', sa.String(length=64), nullable=False),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True),
sa.Column('business_date', sa.String(length=16), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='prechecking'),
sa.Column('scope_json', sa.JSON(), nullable=False),
sa.Column('file_snapshot_json', sa.JSON(), nullable=False),
sa.Column('mapping_version', sa.String(length=64), nullable=True),
sa.Column('strategy_version', sa.String(length=64), nullable=True),
sa.Column('counts_json', sa.JSON(), nullable=False),
sa.Column('estimated_transfer_quantity', sa.String(length=40), nullable=True),
sa.Column('estimated_erp_write_count', sa.Integer(), nullable=False, server_default='0'),
sa.Column('precheck_hash', sa.String(length=128), nullable=False),
sa.Column('expires_at', sa.DateTime(), nullable=True),
sa.Column('confirmed_at', sa.DateTime(), nullable=True),
sa.Column('confirmed_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'),
sa.CheckConstraint(
"status IN ('file_pending', 'file_ready', 'prechecking', 'ready_to_execute', "
"'executing', 'success', 'failed', 'cancelled', 'expired')",
name='ck_transfer_prechecks_status',
),
)
op.create_index('ix_transfer_prechecks_run_status', 'transfer_prechecks', ['run_id', 'status'])
op.create_index('ix_transfer_prechecks_business_date', 'transfer_prechecks', ['business_date'])
op.create_table(
'transfer_invoice_items',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('precheck_id', sa.Integer(), sa.ForeignKey('transfer_prechecks.id'), nullable=False),
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('invoice_no', sa.String(length=64), nullable=False),
sa.Column('material_no', sa.String(length=64), nullable=False),
sa.Column('material_name', sa.String(length=200), nullable=False, server_default=''),
sa.Column('specification', sa.String(length=200), nullable=False, server_default=''),
sa.Column('receipt_date', sa.String(length=16), nullable=True),
sa.Column('from_warehouse', sa.String(length=64), nullable=False),
sa.Column('to_warehouse', sa.String(length=64), nullable=False),
sa.Column('receipt_quantity', sa.String(length=40), nullable=False),
sa.Column('erp_quantity', sa.String(length=40), nullable=True),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('result_code', sa.String(length=64), nullable=True),
sa.Column('result_message', sa.Text(), nullable=True),
sa.Column('erp_document_no', sa.String(length=64), nullable=True),
sa.Column('raw_lines_json', sa.JSON(), nullable=False),
sa.Column('attempt_no', sa.Integer(), nullable=False, server_default='0'),
sa.Column('manually_closed_reason', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'),
sa.CheckConstraint(
"status IN ('file_pending', 'file_ready', 'prechecking', 'ready_to_execute', "
"'executing', 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', "
"'result_unknown', 'manually_closed', 'cancelled', 'notification_failed')",
name='ck_transfer_invoice_items_status',
),
)
op.create_index(
'ix_transfer_invoice_items_source_invoice_status',
'transfer_invoice_items', ['source_code', 'invoice_no', 'status'],
)
op.create_index('ix_transfer_invoice_items_run_id', 'transfer_invoice_items', ['run_id'])
op.create_index('ix_transfer_invoice_items_erp_document_no', 'transfer_invoice_items', ['erp_document_no'])
op.create_table(
'transfer_attempts',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('item_id', sa.Integer(), sa.ForeignKey('transfer_invoice_items.id'), nullable=False),
sa.Column('attempt_no', sa.Integer(), nullable=False),
sa.Column('kind', sa.String(length=16), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'),
sa.Column('request_snapshot_json', sa.JSON(), nullable=False),
sa.Column('response_summary_json', sa.JSON(), nullable=False),
sa.Column('operation_id', sa.String(length=128), nullable=True),
sa.Column('error_code', sa.String(length=64), nullable=True),
sa.Column('error_message', sa.Text(), nullable=True),
sa.Column('started_at', sa.DateTime(), nullable=True),
sa.Column('completed_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('item_id', 'attempt_no', name='uq_transfer_attempts_item_no'),
sa.CheckConstraint(
"kind IN ('precheck', 'rpa', 'erp_query', 'erp_write')",
name='ck_transfer_attempts_kind',
),
sa.CheckConstraint(
"status IN ('queued', 'running', 'waiting_external', 'success', 'failed', "
"'result_unknown', 'superseded')",
name='ck_transfer_attempts_status',
),
)
op.create_index('ix_transfer_attempts_item_created', 'transfer_attempts', ['item_id', 'created_at'])
op.create_table(
'transfer_audit_events',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('event_type', sa.String(length=64), nullable=False),
sa.Column('aggregate_type', sa.String(length=64), nullable=False),
sa.Column('aggregate_id', sa.String(length=128), nullable=False),
sa.Column('run_no', sa.String(length=64), nullable=True),
sa.Column('precheck_no', sa.String(length=64), nullable=True),
sa.Column('invoice_no', sa.String(length=64), nullable=True),
sa.Column('item_id', sa.String(length=64), nullable=True),
sa.Column('attempt_no', sa.Integer(), nullable=True),
sa.Column('actor_type', sa.String(length=16), nullable=False, server_default='system'),
sa.Column('actor_id', sa.String(length=128), nullable=True),
sa.Column('actor_role', sa.String(length=64), nullable=True),
sa.Column('actor_display', sa.String(length=128), nullable=True),
sa.Column('request_id', sa.String(length=64), nullable=True),
sa.Column('operation_id', sa.String(length=64), nullable=True),
sa.Column('source', sa.String(length=32), nullable=True),
sa.Column('result', sa.String(length=16), nullable=True),
sa.Column('error_code', sa.String(length=64), nullable=True),
sa.Column('before_json', sa.JSON(), nullable=False),
sa.Column('after_json', sa.JSON(), nullable=False),
sa.Column('diff_json', sa.JSON(), nullable=False),
sa.Column('before_hash', sa.String(length=64), nullable=True),
sa.Column('after_hash', sa.String(length=64), nullable=True),
sa.Column('event_hash', sa.String(length=64), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.CheckConstraint(
"actor_type IN ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')",
name='ck_transfer_audit_events_actor_type',
),
sa.CheckConstraint(
"result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')",
name='ck_transfer_audit_events_result',
),
)
op.create_index(
'ix_transfer_audit_events_aggregate_created',
'transfer_audit_events', ['aggregate_type', 'aggregate_id', 'created_at'],
)
op.create_index('ix_transfer_audit_events_run_created', 'transfer_audit_events', ['run_no', 'created_at'])
op.create_index('ix_transfer_audit_events_invoice_created', 'transfer_audit_events', ['invoice_no', 'created_at'])
op.create_index('ix_transfer_audit_events_operation_created', 'transfer_audit_events', ['operation_id', 'created_at'])
op.create_index('ix_transfer_audit_events_event_hash', 'transfer_audit_events', ['event_hash'])
op.create_table(
'transfer_archives',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('archive_no', sa.String(length=64), nullable=False),
sa.Column('object_type', sa.String(length=64), nullable=False),
sa.Column('object_id', sa.String(length=128), nullable=False),
sa.Column('storage_provider', sa.String(length=32), nullable=False),
sa.Column('storage_bucket', sa.String(length=128), nullable=False),
sa.Column('storage_key', sa.String(length=1024), nullable=False),
sa.Column('original_filename', sa.String(length=255), nullable=False),
sa.Column('content_type', sa.String(length=128), nullable=True),
sa.Column('file_size', sa.Integer(), nullable=False),
sa.Column('sha256', sa.String(length=64), nullable=False),
sa.Column('archive_expires_at', sa.DateTime(), nullable=True),
sa.Column('archive_deleted_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('archive_no', name='uq_transfer_archives_archive_no'),
sa.UniqueConstraint('object_type', 'object_id', 'sha256', name='uq_transfer_archives_object_sha'),
sa.CheckConstraint('file_size >= 0', name='ck_transfer_archives_file_size'),
)
op.create_index('ix_transfer_archives_object', 'transfer_archives', ['object_type', 'object_id'])
def downgrade() -> None:
"""回滚:按外键依赖逆序删除调拨表。"""
op.drop_index('ix_transfer_archives_object', table_name='transfer_archives')
op.drop_table('transfer_archives')
op.drop_index('ix_transfer_audit_events_event_hash', table_name='transfer_audit_events')
op.drop_index('ix_transfer_audit_events_operation_created', table_name='transfer_audit_events')
op.drop_index('ix_transfer_audit_events_invoice_created', table_name='transfer_audit_events')
op.drop_index('ix_transfer_audit_events_run_created', table_name='transfer_audit_events')
op.drop_index('ix_transfer_audit_events_aggregate_created', table_name='transfer_audit_events')
op.drop_table('transfer_audit_events')
op.drop_index('ix_transfer_attempts_item_created', table_name='transfer_attempts')
op.drop_table('transfer_attempts')
op.drop_index('ix_transfer_invoice_items_erp_document_no', table_name='transfer_invoice_items')
op.drop_index('ix_transfer_invoice_items_run_id', table_name='transfer_invoice_items')
op.drop_index('ix_transfer_invoice_items_source_invoice_status', table_name='transfer_invoice_items')
op.drop_table('transfer_invoice_items')
op.drop_index('ix_transfer_prechecks_business_date', table_name='transfer_prechecks')
op.drop_index('ix_transfer_prechecks_run_status', table_name='transfer_prechecks')
op.drop_table('transfer_prechecks')
op.drop_index('ix_transfer_source_jobs_source_status', table_name='transfer_source_jobs')
op.drop_table('transfer_source_jobs')
op.drop_index('ix_transfer_runs_business_date', table_name='transfer_runs')
op.drop_index('ix_transfer_runs_status_created', table_name='transfer_runs')
op.drop_table('transfer_runs')
@@ -0,0 +1,385 @@
"""订单明细身份、项次及 OT 生命周期契约的一次性硬切换。"""
from __future__ import annotations
import copy
from alembic import op
import sqlalchemy as sa
revision = 'iw1a2b3c4d5e'
down_revision = 'if1b2c3d4e5i'
branch_labels = None
depends_on = None
def _i(): return sa.inspect(op.get_bind())
def _tables(): return set(_i().get_table_names())
def _cols(t): return {x['name'] for x in _i().get_columns(t)}
def _drop_uq(t, n):
if n in {x.get('name') for x in _i().get_unique_constraints(t)}: op.drop_constraint(n, t, type_='unique')
def _drop_idx(t, n):
if n in {x.get('name') for x in _i().get_indexes(t)}: op.drop_index(n, table_name=t)
def _drop_column_with_dependencies(t, column):
"""按实际库结构先解除列级外键/索引,再删除已退役的 OT 投影列。"""
if column not in _cols(t):
return
with op.batch_alter_table(t) as b:
for fk in _i().get_foreign_keys(t):
if column in (fk.get('constrained_columns') or []) and fk.get('name'):
b.drop_constraint(fk['name'], type_='foreignkey')
for index in _i().get_indexes(t):
if column in (index.get('column_names') or []) and index.get('name'):
b.drop_index(index['name'])
b.drop_column(column)
def _clean_task_step_payloads():
"""删除 OT JSON 中已迁移的业务事实,仅保留 UI/解析摘要。"""
if 'shipping_order_tasks' not in _tables() or 'step_payload_json' not in _cols('shipping_order_tasks'):
return
table = sa.table('shipping_order_tasks', sa.column('id', sa.Integer()), sa.column('step_payload_json', sa.JSON()))
removed = {
'field_conflicts', 'process_field_gate', 'inventory_rpa_skipped',
'last_inventory_rpa_runtime', 'line_inventory_candidates',
'candidate_inventory_prep', 'line_inventory_resolutions',
'forced_match_source_code', 'current_match_projection',
'resolved_ok_source_codes', 'multi_source_excel_block',
'inventory_source_resolution', 'rpa_inventory_source', 'export_meta',
'invalidated_from_stage', 'last_conflict_resolve_idempotency_key',
'last_notice_edit_idempotency',
}
bind = op.get_bind()
for row in bind.execute(sa.select(table.c.id, table.c.step_payload_json)).all():
payload = row.step_payload_json
if not isinstance(payload, dict):
continue
cleaned = {key: value for key, value in payload.items() if key not in removed}
if cleaned != payload:
bind.execute(table.update().where(table.c.id == row.id).values(step_payload_json=cleaned or None))
_OT_COLUMNS = {
'order_data_version': sa.Column('order_data_version', sa.Integer(), nullable=False, server_default='1'),
'current_order_extraction_id': sa.Column('current_order_extraction_id', sa.Integer(), nullable=True),
'order_snapshot_id': sa.Column('order_snapshot_id', sa.Integer(), nullable=True),
'active_inventory_candidate_set_id': sa.Column('active_inventory_candidate_set_id', sa.Integer(), nullable=True),
'step_payload_json': sa.Column('step_payload_json', sa.JSON(), nullable=True),
'active_process_execution_id': sa.Column('active_process_execution_id', sa.Integer(), nullable=True),
}
_TASK_FKS = {
'shipping_order_snapshots': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_events': ('task_id', 'shipping_order_tasks'),
'shipping_order_review_confirmed_revisions': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_wave_lines': ('task_id', 'shipping_order_tasks'),
'shipping_order_review_wave_idempotency': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_line_decisions': ('task_id', 'shipping_order_tasks'),
'shipping_inventory_candidate_sets': ('task_id', 'shipping_order_tasks'), 'shipping_process_executions': ('task_id', 'shipping_order_tasks'),
'shipping_process_gates': ('task_id', 'shipping_order_tasks'), 'shipping_inventory_preparation_attempts': ('task_id', 'shipping_order_tasks'),
'shipping_notice_reservations': ('task_id', 'shipping_order_tasks'), 'shipping_notice_inventory_verifications': ('task_id', 'shipping_order_tasks'),
'shipping_task_inventory_links': ('task_id', 'shipping_order_tasks'), 'shipping_temporary_inventory_sessions': ('task_id', 'shipping_order_tasks'),
'shipping_task_events': ('task_id', 'shipping_order_tasks'),
'shipping_notice_line_inventory_matches': ('task_id', 'shipping_order_tasks'), 'shipping_task_field_conflicts': ('task_id', 'shipping_order_tasks'),
'shipping_order_extractions': ('task_id', 'shipping_order_tasks'), 'shipping_order_intakes': ('consumed_task_id', 'shipping_order_tasks'),
'shipping_order_candidates': ('consumed_task_id', 'shipping_order_tasks'),
}
def _repoint(t, c, target):
if t not in _tables(): return
fks = [x for x in _i().get_foreign_keys(t) if c in (x.get('constrained_columns') or [])]
with op.batch_alter_table(t) as b:
for fk in fks:
if fk.get('name'): b.drop_constraint(fk['name'], type_='foreignkey')
b.create_foreign_key(f'fk_{t}_{c}_order_task', target, [c], ['id'], ondelete='CASCADE')
def upgrade() -> None:
tables = _tables()
_clean_task_step_payloads()
# Notice 的库存确认人/时间是旧的单头运行投影;正式确认事实由
# PreparationAttempt/SourceAttempt 与 GateAttempt 承载。
if 'shipping_notices' in tables:
for n in (
'inventory_connector_type',
'active_inventory_candidate_set_id',
'active_process_execution_id',
'inventory_snapshot_id',
'inventory_source_confirmed_by',
'inventory_source_confirmed_at',
'inventory_lines_json',
'match_status',
'shortage_json',
'line_results_json',
'inventory_source_code',
'inventory_source_status',
'inventory_source_method',
'inventory_source_config_version',
'inventory_routing_fingerprint',
'inventory_rpa_consumed_run_no',
):
_drop_column_with_dependencies('shipping_notices', n)
if 'shipping_order_tasks' in tables:
existing = _cols('shipping_order_tasks')
with op.batch_alter_table('shipping_order_tasks') as b:
for n, c in _OT_COLUMNS.items():
if n not in existing: b.add_column(c)
for n in (
'inventory_source_code', 'inventory_connector_type', 'inventory_source_status',
'inventory_source_method', 'inventory_source_config_version',
'inventory_routing_fingerprint', 'inventory_snapshot_id',
):
if n in existing: b.drop_column(n)
for n in (
'customer_id', 'customer_resolution_status', 'customer_resolution_method',
'customer_identity_fingerprint', 'customer_confirmed_by', 'customer_confirmed_at',
'pending_human_reason',
):
_drop_column_with_dependencies('shipping_order_tasks', n)
# 已部署环境可能在本迁移到达 head 后仍残留历史 OT 投影列(例如旧分支
# 曾先执行过迁移、再补充模型字段)。这里再次按实际 schema 幂等清理,
# 确保“模型无字段、数据库也无字段”最终一致,而不依赖迁移执行时序。
for n in (
'customer_name_snapshot', 'customer_short_code_snapshot',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'inventory_source_code', 'inventory_connector_type', 'inventory_source_status',
'inventory_source_method', 'inventory_source_config_version',
'inventory_routing_fingerprint', 'inventory_snapshot_id',
'inventory_lines_json', 'match_status', 'shortage_json', 'line_results_json',
):
_drop_column_with_dependencies('shipping_order_tasks', n)
cols = _cols('shipping_order_tasks')
if 'shipping_notice_id' in cols:
fks = [x for x in _i().get_foreign_keys('shipping_order_tasks') if 'shipping_notice_id' in (x.get('constrained_columns') or [])]
with op.batch_alter_table('shipping_order_tasks') as b:
for fk in fks:
if fk.get('name'): b.drop_constraint(fk['name'], type_='foreignkey')
b.drop_column('shipping_notice_id')
# 订单/通知项次及身份硬切换(旧身份数据不回填)。
if 'shipping_order_lines' in tables:
c = _cols('shipping_order_lines')
with op.batch_alter_table('shipping_order_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'draft_line_id' not in c: b.add_column(sa.Column('draft_line_id', sa.String(128), nullable=True))
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY extraction_id ORDER BY position,id) x FROM shipping_order_lines) UPDATE shipping_order_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
with op.batch_alter_table('shipping_order_lines') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer())
if 'uq_shipping_order_lines_line_no' not in {x.get('name') for x in _i().get_unique_constraints('shipping_order_lines')}: b.create_unique_constraint('uq_shipping_order_lines_line_no', ['extraction_id','line_no'])
for t in ('shipping_order_review_suggestions','shipping_order_review_line_decisions'):
if t in tables:
c=_cols(t)
with op.batch_alter_table(t) as b:
if 'line_key' in c and 'draft_line_id' not in c: b.alter_column('line_key', new_column_name='draft_line_id')
elif 'line_key' in c: b.drop_column('line_key')
if 'shipping_order_snapshot_lines' in tables:
with op.batch_alter_table('shipping_order_snapshot_lines') as b:
if 'line_no' in _cols('shipping_order_snapshot_lines'): b.alter_column('line_no', existing_type=sa.String(64), type_=sa.Integer(), postgresql_using='line_no::integer')
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY snapshot_id ORDER BY position,id) x FROM shipping_order_snapshot_lines) UPDATE shipping_order_snapshot_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
if 'shipping_notice_lines' in tables:
c=_cols('shipping_notice_lines')
with op.batch_alter_table('shipping_notice_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
if 'inventory_source_code' not in c: b.add_column(sa.Column('inventory_source_code', sa.String(64), nullable=True))
if 'inventory_file_id' not in c: b.add_column(sa.Column('inventory_file_id', sa.Integer(), nullable=True))
if 'inventory_warehouse_id' not in c: b.add_column(sa.Column('inventory_warehouse_id', sa.String(64), nullable=True))
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY notice_id ORDER BY position,id) x FROM shipping_notice_lines) UPDATE shipping_notice_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
with op.batch_alter_table('shipping_notice_lines') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer())
if 'uq_shipping_notice_lines_line_no' not in {x.get('name') for x in _i().get_unique_constraints('shipping_notice_lines')}: b.create_unique_constraint('uq_shipping_notice_lines_line_no', ['notice_id','line_no'])
if 'fk_shipping_notice_lines_inventory_file' not in {x.get('name') for x in _i().get_foreign_keys('shipping_notice_lines')}:
b.create_foreign_key('fk_shipping_notice_lines_inventory_file', 'shipping_inventory_files', ['inventory_file_id'], ['id'], ondelete='SET NULL')
existing_indexes = {x.get('name') for x in _i().get_indexes('shipping_notice_lines')}
if 'ix_shipping_notice_lines_inventory_source_code' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_source_code', ['inventory_source_code'])
if 'ix_shipping_notice_lines_inventory_file_id' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_file_id', ['inventory_file_id'])
if 'ix_shipping_notice_lines_inventory_warehouse_id' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_warehouse_id', ['inventory_warehouse_id'])
if 'shipping_notices' in tables and 'inventory_warehouse_id' in _cols('shipping_notices'):
with op.batch_alter_table('shipping_notices') as b:
b.drop_column('inventory_warehouse_id')
if 'shipping_order_review_wave_lines' in tables:
c=_cols('shipping_order_review_wave_lines'); _drop_uq('shipping_order_review_wave_lines','uq_shipping_review_wave_lines_case_line'); op.execute(sa.text('DELETE FROM shipping_order_review_wave_lines'))
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_order_review_wave_lines')}
has_snapshot_line_fk = any('snapshot_line_id' in (x.get('constrained_columns') or []) for x in _i().get_foreign_keys('shipping_order_review_wave_lines'))
existing_uqs = {x.get('name') for x in _i().get_unique_constraints('shipping_order_review_wave_lines')}
with op.batch_alter_table('shipping_order_review_wave_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'snapshot_line_id' not in c: b.add_column(sa.Column('snapshot_line_id', sa.Integer(), nullable=False))
if not has_snapshot_line_fk and 'fk_shipping_review_wave_lines_snapshot_line' not in existing_fks:
b.create_foreign_key('fk_shipping_review_wave_lines_snapshot_line','shipping_order_snapshot_lines',['snapshot_line_id'],['id'],ondelete='CASCADE')
if 'uq_shipping_review_wave_lines_case_snapshot_line' not in existing_uqs:
b.create_unique_constraint('uq_shipping_review_wave_lines_case_snapshot_line',['review_case_id','snapshot_line_id'])
if 'shipping_order_review_wave_idempotency' in tables:
c=_cols('shipping_order_review_wave_idempotency')
with op.batch_alter_table('shipping_order_review_wave_idempotency') as b:
if 'line_keys_json' in c and 'snapshot_line_ids_json' not in c: b.alter_column('line_keys_json',new_column_name='snapshot_line_ids_json')
if 'line_keys_hash' in c and 'snapshot_line_ids_hash' not in c: b.alter_column('line_keys_hash',new_column_name='snapshot_line_ids_hash')
if 'shipping_notice_line_inventory_matches' in tables:
c=_cols('shipping_notice_line_inventory_matches'); op.execute(sa.text('DELETE FROM shipping_notice_line_inventory_matches')); _drop_idx('shipping_notice_line_inventory_matches','uq_shipping_notice_line_inv_match_current'); _drop_uq('shipping_notice_line_inventory_matches','uq_shipping_notice_line_inv_match_task_line_snap')
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_notice_line_inventory_matches')}
has_snapshot_line_fk = any('snapshot_line_id' in (x.get('constrained_columns') or []) for x in _i().get_foreign_keys('shipping_notice_line_inventory_matches'))
existing_uqs = {x.get('name') for x in _i().get_unique_constraints('shipping_notice_line_inventory_matches')}
with op.batch_alter_table('shipping_notice_line_inventory_matches') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
if 'snapshot_line_id' not in c: b.add_column(sa.Column('snapshot_line_id',sa.Integer(),nullable=False))
else: b.alter_column('snapshot_line_id',nullable=False,existing_type=sa.Integer())
if not has_snapshot_line_fk and 'fk_shipping_notice_line_inventory_matches_snapshot_line' not in existing_fks:
b.create_foreign_key('fk_shipping_notice_line_inventory_matches_snapshot_line','shipping_order_snapshot_lines',['snapshot_line_id'],['id'],ondelete='CASCADE')
if 'uq_shipping_notice_line_inv_match_task_snapshot_line_snap' not in existing_uqs:
b.create_unique_constraint('uq_shipping_notice_line_inv_match_task_snapshot_line_snap',['task_id','snapshot_line_id','inventory_snapshot_id'])
if 'uq_shipping_notice_line_inv_match_current' not in {x.get('name') for x in _i().get_indexes('shipping_notice_line_inventory_matches')}:
b.create_index('uq_shipping_notice_line_inv_match_current',['task_id','snapshot_line_id'],unique=True,postgresql_where=sa.text('is_current IS TRUE'))
op.execute(sa.text("""
UPDATE shipping_notice_line_inventory_matches m
SET line_no = COALESCE(sl.line_no, m.line_index + 1, 1)
FROM shipping_order_snapshot_lines sl
WHERE m.snapshot_line_id = sl.id
AND m.line_no IS NULL
"""))
with op.batch_alter_table('shipping_notice_line_inventory_matches') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer(), server_default='1')
# shipping_task_events.task_id 记录正式 ShippingOrderTask.id;部分旧环境
# 的外键错误指向 shipping_notices,导致确认建单写审计事件时触发 FK 违反。
if 'shipping_task_events' in tables and 'shipping_order_tasks' in tables:
event_fk = next(
(
fk for fk in _i().get_foreign_keys('shipping_task_events')
if tuple(fk.get('constrained_columns') or []) == ('task_id',)
),
None,
)
if not event_fk or event_fk.get('referred_table') != 'shipping_order_tasks':
old_fk_name = str(event_fk.get('name') or 'shipping_task_events_task_id_fkey') if event_fk else None
if old_fk_name:
with op.batch_alter_table('shipping_task_events') as b:
b.drop_constraint(old_fk_name, type_='foreignkey')
invalid_count = op.get_bind().execute(sa.text(
"""
SELECT COUNT(*)
FROM shipping_task_events e
WHERE NOT EXISTS (
SELECT 1 FROM shipping_order_tasks t WHERE t.id = e.task_id
)
"""
)).scalar_one()
if int(invalid_count or 0):
raise RuntimeError(
'shipping_task_events contains rows whose task_id is not a '
'shipping_order_tasks.id; repair those audit rows before migration'
)
with op.batch_alter_table('shipping_task_events') as b:
b.create_foreign_key(
'fk_shipping_task_events_task_id_order_task',
'shipping_order_tasks', ['task_id'], ['id'], ondelete='CASCADE',
)
bind=op.get_bind()
if 'shipping_excel_templates' in tables:
t=sa.table('shipping_excel_templates',sa.column('id',sa.Integer()),sa.column('definition_json',sa.JSON()))
def rw(v):
if isinstance(v,dict):
r={k:rw(x) for k,x in v.items()}
if r.get('source_kind') == 'system_fact' and r.get('source_key') == 'export_sequence':
r['source_key'] = 'notice_line_no'
return r
return [rw(x) for x in v] if isinstance(v,list) else v
for row in bind.execute(sa.select(t.c.id,t.c.definition_json)).all():
v=rw(row.definition_json)
if v!=row.definition_json: bind.execute(t.update().where(t.c.id==row.id).values(definition_json=v))
if 'shipping_order_schema_versions' in tables:
t=sa.table('shipping_order_schema_versions',sa.column('id',sa.Integer()),sa.column('definition_json',sa.JSON()))
for row in bind.execute(sa.select(t.c.id,t.c.definition_json)).all():
v=copy.deepcopy(row.definition_json)
if isinstance(v,dict):
# line_no 是系统项次标准字段,必须保留;这里只移除已废弃的派生规则配置。
v.pop('derivation_rules',None); v.pop('derivation_rules_checksum',None)
if v!=row.definition_json: bind.execute(t.update().where(t.c.id==row.id).values(definition_json=v))
if 'shipping_order_fields' in tables:
# line_no 已硬切换为系统生成整数项次;纠偏旧资产种子遗留的 string 类型。
op.execute(sa.text("""
UPDATE shipping_order_fields
SET value_type = 'integer', updated_at = CURRENT_TIMESTAMP
WHERE field_code = 'line_no'
AND scope = 'line'
AND asset_kind = 'system_standard'
"""))
if 'shipping_order_tasks' in tables:
with op.batch_alter_table('shipping_order_tasks') as b:
for n,c in _OT_COLUMNS.items():
pass
if 'lifecycle_status' not in _cols('shipping_order_tasks'): b.add_column(sa.Column('lifecycle_status',sa.String(16),nullable=False,server_default='active'))
for n, typ in (('current_step', sa.String(64)), ('review_status', sa.String(32)), ('pending_human_reason', sa.String(64))):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n, typ, nullable=True))
for n in ('deleted_at','voided_at','archived_at'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.DateTime(),nullable=True))
for n in ('deletion_reason','void_reason'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.Text(),nullable=True))
for n in ('deleted_by_id','voided_by_id','archived_by_id'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.Integer(),nullable=True))
if 'lifecycle_status' not in _cols('shipping_order_tasks'):
b.create_check_constraint('ck_shipping_order_tasks_lifecycle_status', "lifecycle_status IN ('active', 'voided', 'archived')")
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_order_tasks')}
for name, column in (
('fk_shipping_order_tasks_deleted_by', 'deleted_by_id'),
('fk_shipping_order_tasks_voided_by', 'voided_by_id'),
('fk_shipping_order_tasks_archived_by', 'archived_by_id'),
):
if name not in existing_fks:
b.create_foreign_key(name, 'users', [column], ['id'])
obsolete_cols = {
'customer_name_snapshot', 'customer_short_code_snapshot',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'inventory_lines_json', 'match_status', 'shortage_json', 'line_results_json',
} & _cols('shipping_order_tasks')
if obsolete_cols:
with op.batch_alter_table('shipping_order_tasks') as b:
for column in sorted(obsolete_cols):
b.drop_column(column)
if 'shipping_notices' in tables:
_drop_idx('shipping_notices', 'ix_shipping_notices_current_step')
_drop_idx('shipping_notices', 'ix_shipping_notices_upload_status')
_drop_idx('shipping_notices', 'ix_shipping_notices_order_snapshot_id')
_drop_idx('shipping_notices', 'ix_shipping_tasks_order_snapshot_id')
obsolete_notice_cols = {
'export_file_path', 'export_file_name', 'export_version', 'freight_ref_no',
'upload_status', 'upload_mode', 'upload_attempt', 'idempotency_key',
'upload_started_at', 'upload_finished_at', 'upload_error_code',
'upload_error_message', 'upload_receipt_json',
'current_step', 'review_status', 'step_payload_json', 'pending_human_reason', 'error_message',
'customer_id', 'customer_name_snapshot', 'customer_short_code_snapshot',
'customer_resolution_status', 'customer_resolution_method', 'customer_identity_fingerprint',
'customer_confirmed_by', 'customer_confirmed_at',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'parse_confidence', 'order_data_version', 'current_order_extraction_id',
'order_snapshot_id', 'raw_content', 'source_file_name', 'source_file_type', 'source_content_hash',
'business_fingerprint', 'fingerprint_version', 'content_fingerprint', 'content_fingerprint_version',
'batch_index', 'batch_total',
} & _cols('shipping_notices')
for column in sorted(obsolete_notice_cols):
_drop_column_with_dependencies('shipping_notices', column)
if 'shipping_order_tasks' in tables:
_drop_idx('shipping_order_tasks', 'ix_shipping_tasks_order_snapshot_id')
_drop_idx('shipping_order_tasks', 'ix_shipping_order_tasks_order_snapshot_id')
_drop_uq('shipping_order_tasks', 'uq_shipping_order_tasks_order_snapshot_id')
# 统一所有履约事实的 task_id 外键目标;旧通知表中的孤儿数据不做猜测回填。
for table, (column, target) in _TASK_FKS.items():
if table not in _tables():
continue
# 不同历史表的任务关联列名并不统一;列不存在时跳过该映射,避免生成无效 SQL。
if column not in _cols(table):
continue
# 已被发货通知引用的快照不能作为孤儿删除,否则会触发外键冲突。
keep_referenced = (
" AND NOT EXISTS (SELECT 1 FROM shipping_notices sn WHERE sn.order_task_id = t.task_id)"
if table == 'shipping_order_snapshots' and 'shipping_notices' in _tables()
else ''
)
op.execute(sa.text(
f'DELETE FROM {table} t WHERE t.{column} IS NOT NULL AND NOT EXISTS '
f'(SELECT 1 FROM shipping_order_tasks ot WHERE ot.id = t.{column})'
f'{keep_referenced}'
))
_repoint(table, column, target)
if 'shipping_order_review_cases' in _tables():
_repoint('shipping_order_review_cases', 'confirmed_task_id', 'shipping_order_tasks')
def downgrade() -> None:
raise RuntimeError('order line identity contract is intentionally irreversible')
@@ -0,0 +1,43 @@
"""split integration connector columns
Revision ID: ix1a2b3c4d5e
Revises: iy1a2b3c4d5e
Create Date: 2026-09-01 09:00:00.000000
用途:把集成连接器"真正强类型的关键字段"从 JSON 拆成独立列,JSON 保留作兜底。
ClientInstance:endpoint(连接地址:REST=接口地址,SOAP=WSDL 地址)/ timeout_seconds;
InterfaceDefinition:http_method / request_path;
Binding:context_source_code。
依赖:ic1a2b3c4d5f 建表;不新建表,仅加列。
逻辑:SOAP 只需 WSDL(其内已含服务端点),故合一为 endpoint 字段;列可为空(存量数据
回填后由应用层拼回 JSON);不删 JSON,保证兼容层运行时零改动。
"""
from alembic import op
import sqlalchemy as sa
revision = 'ix1a2b3c4d5e'
down_revision = 'iy1a2b3c4d5e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""在三张连接器表上新增关键字段列(nullable:存量数据回填后走兼容层)。"""
op.add_column('integration_client_instances', sa.Column('endpoint', sa.String(length=512), nullable=True))
op.add_column('integration_client_instances', sa.Column('timeout_seconds', sa.Integer(), nullable=True))
op.add_column('integration_interface_definitions', sa.Column('http_method', sa.String(length=16), nullable=True))
op.add_column('integration_interface_definitions', sa.Column('request_path', sa.String(length=512), nullable=True))
op.add_column('integration_bindings', sa.Column('context_source_code', sa.String(length=64), nullable=True))
def downgrade() -> None:
"""回滚:删除新增列(JSON 兜底仍在,数据不丢)。"""
op.drop_column('integration_bindings', 'context_source_code')
op.drop_column('integration_interface_definitions', 'request_path')
op.drop_column('integration_interface_definitions', 'http_method')
op.drop_column('integration_client_instances', 'timeout_seconds')
op.drop_column('integration_client_instances', 'endpoint')
@@ -0,0 +1,125 @@
"""收敛客户确认主链并删除已退役的订单角色匹配表。"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = 'iy1a2b3c4d5e'
down_revision = 'iw1a2b3c4d5e'
branch_labels = None
depends_on = None
def _columns(table_name: str) -> set[str]:
"""返回表当前列名,支持工作区迁移的幂等升级。"""
return {item['name'] for item in sa.inspect(op.get_bind()).get_columns(table_name)}
def upgrade() -> None:
"""补齐当前主链字段后删除已无生产读写方的旧角色匹配表。"""
# [STEP 1] 合并原 35d4 任务进度补列。
with op.batch_alter_table('shipping_order_tasks') as batch:
columns = _columns('shipping_order_tasks')
if 'current_step' not in columns:
batch.add_column(sa.Column('current_step', sa.String(length=64), nullable=True))
if 'review_status' not in columns:
batch.add_column(sa.Column('review_status', sa.String(length=32), nullable=True))
# [STEP 2] 合并原 ix1 客户 Resolution 确认字段升级。
if 'shipping_customer_shadow_resolutions' in set(sa.inspect(op.get_bind()).get_table_names()):
columns = _columns('shipping_customer_shadow_resolutions')
with op.batch_alter_table('shipping_customer_shadow_resolutions') as batch:
constraints = {
item.get('name')
for item in sa.inspect(op.get_bind()).get_check_constraints('shipping_customer_shadow_resolutions')
}
if 'ck_shipping_customer_shadow_status' in constraints:
batch.drop_constraint('ck_shipping_customer_shadow_status', type_='check')
batch.create_check_constraint(
'ck_shipping_customer_shadow_status',
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')",
)
if 'confirmed_customer_id' not in columns:
batch.add_column(sa.Column('confirmed_customer_id', sa.Integer(), nullable=True))
batch.create_foreign_key(
'fk_shipping_customer_resolution_confirmed_customer',
'shipping_customers', ['confirmed_customer_id'], ['id'],
)
if 'confirmation_method' not in columns:
batch.add_column(sa.Column('confirmation_method', sa.String(length=32), nullable=True))
if 'confirmation_reason' not in columns:
batch.add_column(sa.Column('confirmation_reason', sa.String(length=500), nullable=True))
if 'confirmed_by_id' not in columns:
batch.add_column(sa.Column('confirmed_by_id', sa.Integer(), nullable=True))
batch.create_foreign_key('fk_shipping_customer_resolution_confirmed_by', 'users', ['confirmed_by_id'], ['id'])
if 'confirmed_at' not in columns:
batch.add_column(sa.Column('confirmed_at', sa.DateTime(), nullable=True))
# [STEP 3] 旧表物理删除。
bind = op.get_bind()
if 'shipping_order_customer_matches' in set(sa.inspect(bind).get_table_names()):
op.drop_table('shipping_order_customer_matches')
def downgrade() -> None:
"""恢复旧表空结构并回退本迁移合并的新增字段;不恢复已删除数据。"""
op.create_table(
'shipping_order_customer_matches',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('extraction_id', sa.Integer(), nullable=False),
sa.Column('role', sa.String(length=16), nullable=False),
sa.Column('raw_name', sa.Text(), nullable=True),
sa.Column('normalized_name', sa.String(length=500), nullable=True),
sa.Column('source_system', sa.String(length=64), nullable=True),
sa.Column('external_code', sa.String(length=128), nullable=True),
sa.Column('identity_fingerprint', sa.String(length=64), nullable=True),
sa.Column('identity_rule_version', sa.String(length=32), nullable=True),
sa.Column('identity_components_json', sa.JSON(), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.Column('site_id', sa.Integer(), nullable=True),
sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True),
sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True),
sa.Column('candidates_json', sa.JSON(), nullable=False),
sa.Column('resolution_method', sa.String(length=32), nullable=True),
sa.Column('confirmation_reason', sa.Text(), nullable=True),
sa.Column('confirmed_by_id', sa.Integer(), nullable=True),
sa.Column('confirmed_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'),
sa.CheckConstraint(
"status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')",
name='ck_shipping_order_customer_matches_status',
),
sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']),
sa.ForeignKeyConstraint(['confirmed_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['extraction_id'], ['shipping_order_extractions.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['site_id'], ['shipping_customer_sites.id']),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'),
)
op.create_index('ix_shipping_order_customer_matches_extraction_id', 'shipping_order_customer_matches', ['extraction_id'])
op.create_index('ix_shipping_order_customer_matches_customer_role', 'shipping_order_customer_matches', ['customer_id', 'role'])
op.create_index('ix_shipping_order_customer_matches_identity_fingerprint', 'shipping_order_customer_matches', ['identity_fingerprint'])
if 'shipping_customer_shadow_resolutions' in set(sa.inspect(op.get_bind()).get_table_names()):
with op.batch_alter_table('shipping_customer_shadow_resolutions') as batch:
for name in (
'fk_shipping_customer_resolution_confirmed_by',
'fk_shipping_customer_resolution_confirmed_customer',
):
try:
batch.drop_constraint(name, type_='foreignkey')
except Exception:
pass
columns = _columns('shipping_customer_shadow_resolutions')
for name in ('confirmed_at', 'confirmed_by_id', 'confirmation_reason', 'confirmation_method', 'confirmed_customer_id'):
if name in columns:
batch.drop_column(name)
with op.batch_alter_table('shipping_order_tasks') as batch:
columns = _columns('shipping_order_tasks')
for name in ('review_status', 'current_step'):
if name in columns:
batch.drop_column(name)
@@ -0,0 +1,30 @@
"""合并集成连接器列拆分与合同付款/发货通知两条 Alembic 头。
Revision ID: n9a0b1c2d3e4
Revises: ix1a2b3c4d5e, n8f9a0b1c2d3
Create Date: 2026-09-07 10:00:00.000000
用途:将 ``ix1a2b3c4d5e``(集成连接器强类型列拆分)与
``n8f9a0b1c2d3``(合同付款与发货通知 head 合并)收成单一升级路径,
避免 ``flask db upgrade`` / pre-commit 因 Multiple head revisions 失败。
依赖:``ix1a2b3c4d5e``、``n8f9a0b1c2d3``。
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
"""
from alembic import op # noqa: F401 - Alembic migration module contract
revision = "n9a0b1c2d3e4"
down_revision = ("ix1a2b3c4d5e", "n8f9a0b1c2d3")
branch_labels = None
depends_on = None
def upgrade() -> None:
"""合并集成连接器 head 与合同付款/发货通知 head,不执行数据库结构变更。"""
pass
def downgrade() -> None:
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
pass