feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a9fbac2fc
commit
d2b3d74def
571 files changed
+78064
-24681
No files matched your search
@@ -0,0 +1,44 @@
|
||||
"""unify order profile template mode
|
||||
|
||||
Revision ID: ab2c3d4e5f6a
|
||||
Revises: ff6a7b8c9d0e
|
||||
Create Date: 2026-08-03 00:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'ab2c3d4e5f6a'
|
||||
down_revision = 'ff6a7b8c9d0e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""将历史 v2 状态收敛为当前唯一坐标模板状态。"""
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_order_document_profiles "
|
||||
"SET template_mode = 'coordinate' "
|
||||
"WHERE template_mode IS NULL OR template_mode = 'coordinate_v2'"
|
||||
)
|
||||
)
|
||||
with op.batch_alter_table('shipping_order_document_profiles') as batch_op:
|
||||
batch_op.alter_column(
|
||||
'template_mode',
|
||||
existing_type=sa.String(length=32),
|
||||
server_default='coordinate',
|
||||
existing_nullable=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""回滚仅恢复默认值,不恢复已清理的 v2 状态数据。"""
|
||||
with op.batch_alter_table('shipping_order_document_profiles') as batch_op:
|
||||
batch_op.alter_column(
|
||||
'template_mode',
|
||||
existing_type=sa.String(length=32),
|
||||
server_default='coordinate_v2',
|
||||
existing_nullable=False,
|
||||
)
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
migrations/versions/cm1a2b3c4d5e_merge_profile_mode_and_qualification_heads.py
|
||||
|
||||
用途:合并订单模板模式收敛与 Candidate 资格追加式两条并行 head。
|
||||
依赖:alembic.op。
|
||||
逻辑:ab2c3d4e5f6a 与 f3b4c5d6e7f8 并行;本 revision 仅拓扑合并,无 DDL。
|
||||
|
||||
Revision ID: cm1a2b3c4d5e
|
||||
Revises: ab2c3d4e5f6a, f3b4c5d6e7f8
|
||||
Create Date: 2026-08-03 15:10:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm1a2b3c4d5e'
|
||||
down_revision = ('ab2c3d4e5f6a', 'f3b4c5d6e7f8')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Merge-only:统一多 head,供会话多任务迁移线性升级。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Merge-only:无 DDL 可回滚。"""
|
||||
pass
|
||||
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
migrations/versions/cm2b3c4d5e6f_add_conversation_multi_task_run_fields.py
|
||||
|
||||
用途:会话多任务聚合阶段 1 — 为订单抽取 Run 增加用户可见任务与输入生命周期字段,
|
||||
放宽同会话活跃 Run 唯一约束,并建立客户端提交幂等索引。
|
||||
依赖:alembic.op、shipping_order_extraction_runs。
|
||||
逻辑:Revises cm1a2b3c4d5e;backfill 历史行;DROP partial unique
|
||||
uq_shipping_order_extraction_runs_active_conversation。
|
||||
|
||||
Revision ID: cm2b3c4d5e6f
|
||||
Revises: cm1a2b3c4d5e
|
||||
Create Date: 2026-08-03 15:15:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm2b3c4d5e6f'
|
||||
down_revision = 'cm1a2b3c4d5e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""新增 OT 任务字段、放宽活跃会话唯一约束、回填历史行。"""
|
||||
# [STEP 1] 可空添加新列,便于回填后再收紧 NOT NULL。
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch_op:
|
||||
batch_op.add_column(sa.Column('user_task_no', sa.String(length=64), nullable=True))
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
'input_lifecycle',
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default='open',
|
||||
)
|
||||
)
|
||||
batch_op.add_column(sa.Column('input_frozen_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('composer_context_id', sa.String(length=64), nullable=True))
|
||||
batch_op.add_column(sa.Column('submission_ordinal', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('client_submission_id', sa.String(length=64), nullable=True))
|
||||
|
||||
# [STEP 2] 回填:OT- + run_no;非 queued 视为已冻结输入。
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_order_extraction_runs "
|
||||
"SET user_task_no = 'OT-' || run_no "
|
||||
"WHERE user_task_no IS NULL"
|
||||
)
|
||||
)
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_order_extraction_runs "
|
||||
"SET input_lifecycle = CASE "
|
||||
" WHEN status = 'queued' THEN 'open' "
|
||||
" ELSE 'frozen' "
|
||||
"END"
|
||||
)
|
||||
)
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_order_extraction_runs "
|
||||
"SET input_frozen_at = created_at "
|
||||
"WHERE status <> 'queued' AND input_frozen_at IS NULL"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch_op:
|
||||
batch_op.alter_column('user_task_no', existing_type=sa.String(length=64), nullable=False)
|
||||
batch_op.create_index(
|
||||
'ix_shipping_order_extraction_runs_user_task_no',
|
||||
['user_task_no'],
|
||||
unique=False,
|
||||
)
|
||||
batch_op.create_index(
|
||||
'ix_shipping_order_extraction_runs_conversation_status',
|
||||
['user_id', 'owner_agent_id', 'conversation_id', 'status'],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
# [STEP 3] 客户端提交幂等(部分唯一:仅非空 client_submission_id)。
|
||||
op.create_index(
|
||||
'uq_shipping_order_extraction_runs_client_submission',
|
||||
'shipping_order_extraction_runs',
|
||||
['user_id', 'client_submission_id'],
|
||||
unique=True,
|
||||
postgresql_where=sa.text('client_submission_id IS NOT NULL'),
|
||||
sqlite_where=sa.text('client_submission_id IS NOT NULL'),
|
||||
)
|
||||
|
||||
# [STEP 4] 放宽同会话活跃唯一约束(若仍存在)。
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
indexes = {idx['name'] for idx in inspector.get_indexes('shipping_order_extraction_runs')}
|
||||
if 'uq_shipping_order_extraction_runs_active_conversation' in indexes:
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch_op:
|
||||
batch_op.drop_index('uq_shipping_order_extraction_runs_active_conversation')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复活跃会话 partial unique,并移除多任务字段。"""
|
||||
op.drop_index(
|
||||
'uq_shipping_order_extraction_runs_client_submission',
|
||||
table_name='shipping_order_extraction_runs',
|
||||
)
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch_op:
|
||||
batch_op.drop_index('ix_shipping_order_extraction_runs_conversation_status')
|
||||
batch_op.drop_index('ix_shipping_order_extraction_runs_user_task_no')
|
||||
batch_op.create_index(
|
||||
'uq_shipping_order_extraction_runs_active_conversation',
|
||||
['user_id', 'owner_agent_id', 'conversation_id'],
|
||||
unique=True,
|
||||
postgresql_where=sa.text("status IN ('queued', 'processing')"),
|
||||
sqlite_where=sa.text("status IN ('queued', 'processing')"),
|
||||
)
|
||||
batch_op.drop_column('client_submission_id')
|
||||
batch_op.drop_column('submission_ordinal')
|
||||
batch_op.drop_column('composer_context_id')
|
||||
batch_op.drop_column('input_frozen_at')
|
||||
batch_op.drop_column('input_lifecycle')
|
||||
batch_op.drop_column('user_task_no')
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
migrations/versions/cm3c4d5e6f7a_add_order_extraction_submissions.py
|
||||
|
||||
用途:会话多任务 P1 — 独立提交幂等表,避免 Run.client_submission_id 被追加覆盖。
|
||||
依赖:alembic.op、shipping_order_extraction_runs。
|
||||
逻辑:Revises cm2b3c4d5e6f;创建 shipping_order_extraction_submissions;
|
||||
可选回填历史 Run.client_submission_id 为提交行。
|
||||
|
||||
Revision ID: cm3c4d5e6f7a
|
||||
Revises: cm2b3c4d5e6f
|
||||
Create Date: 2026-08-03 18:40:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm3c4d5e6f7a'
|
||||
down_revision = 'cm2b3c4d5e6f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建独立 submission 幂等表并回填历史 client_submission_id。"""
|
||||
op.create_table(
|
||||
'shipping_order_extraction_submissions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('submission_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),
|
||||
sa.Column('conversation_id', sa.String(length=100), nullable=False),
|
||||
sa.Column('user_task_no', sa.String(length=64), nullable=False),
|
||||
sa.Column(
|
||||
'run_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column('run_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('decision', sa.String(length=32), nullable=False),
|
||||
sa.Column('reason_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('operation_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('composer_context_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('intake_nos_json', sa.JSON(), nullable=False),
|
||||
sa.Column('appended_intake_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
'user_id',
|
||||
'submission_id',
|
||||
name='uq_shipping_order_extraction_submissions_user_submission',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_submissions_run',
|
||||
'shipping_order_extraction_submissions',
|
||||
['run_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_submissions_conversation',
|
||||
'shipping_order_extraction_submissions',
|
||||
['user_id', 'conversation_id', 'created_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_submissions_user_id',
|
||||
'shipping_order_extraction_submissions',
|
||||
['user_id'],
|
||||
)
|
||||
|
||||
# 回填:将仍保留在 Run 上的最后一次 client_submission_id 写入独立表(决策未知则记 created)。
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
INSERT INTO shipping_order_extraction_submissions (
|
||||
submission_id, user_id, conversation_id, user_task_no, run_id, run_no,
|
||||
decision, reason_code, operation_id, composer_context_id,
|
||||
intake_nos_json, appended_intake_count, created_at
|
||||
)
|
||||
SELECT
|
||||
r.client_submission_id,
|
||||
r.user_id,
|
||||
r.conversation_id,
|
||||
COALESCE(r.user_task_no, 'OT-' || r.run_no),
|
||||
r.id,
|
||||
r.run_no,
|
||||
'created',
|
||||
'legacy_backfill',
|
||||
NULL,
|
||||
r.composer_context_id,
|
||||
'[]',
|
||||
0,
|
||||
COALESCE(r.created_at, CURRENT_TIMESTAMP)
|
||||
FROM shipping_order_extraction_runs r
|
||||
WHERE r.client_submission_id IS NOT NULL
|
||||
AND r.client_submission_id <> ''
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除独立提交表。"""
|
||||
op.drop_index(
|
||||
'ix_shipping_order_extraction_submissions_user_id',
|
||||
table_name='shipping_order_extraction_submissions',
|
||||
)
|
||||
op.drop_index(
|
||||
'ix_shipping_order_extraction_submissions_conversation',
|
||||
table_name='shipping_order_extraction_submissions',
|
||||
)
|
||||
op.drop_index(
|
||||
'ix_shipping_order_extraction_submissions_run',
|
||||
table_name='shipping_order_extraction_submissions',
|
||||
)
|
||||
op.drop_table('shipping_order_extraction_submissions')
|
||||
@@ -0,0 +1,145 @@
|
||||
"""
|
||||
migrations/versions/cm4d5e6f7a8b_add_shipping_review_line_decisions.py
|
||||
|
||||
用途:建单前行级履约决定表(版本化、活动唯一、波次关联)。
|
||||
依赖:alembic.op、shipping_order_review_cases、shipping_tasks、users。
|
||||
逻辑:Revises cm3c4d5e6f7a;创建 shipping_order_review_line_decisions 及约束索引。
|
||||
|
||||
Revision ID: cm4d5e6f7a8b
|
||||
Revises: cm3c4d5e6f7a
|
||||
Create Date: 2026-08-04 01:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm4d5e6f7a8b'
|
||||
down_revision = 'cm3c4d5e6f7a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建行级履约决定表。"""
|
||||
# [STEP 1] 建表与业务约束
|
||||
op.create_table(
|
||||
'shipping_order_review_line_decisions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
'review_case_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column('line_key', sa.String(length=64), nullable=False),
|
||||
sa.Column('line_index', sa.Integer(), nullable=True),
|
||||
sa.Column('decision_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('decision_code', sa.String(length=48), nullable=False),
|
||||
sa.Column('line_status', sa.String(length=32), nullable=False, server_default='pending_decision'),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=False, server_default=sa.text('true')),
|
||||
sa.Column('reason', sa.Text(), nullable=True),
|
||||
sa.Column('required_qty', sa.String(length=32), nullable=True),
|
||||
sa.Column('available_qty', sa.String(length=32), nullable=True),
|
||||
sa.Column('reservation_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('part_number', sa.String(length=128), nullable=True),
|
||||
sa.Column('task_id', sa.Integer(), sa.ForeignKey('shipping_tasks.id'), nullable=True),
|
||||
sa.Column('wave_no', sa.Integer(), nullable=True),
|
||||
sa.Column('actor_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||
sa.Column('snapshot_json', sa.JSON(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
'review_case_id',
|
||||
'line_key',
|
||||
'decision_version',
|
||||
name='uq_shipping_review_line_decisions_case_line_ver',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"decision_code IN ("
|
||||
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
|
||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen'"
|
||||
")",
|
||||
name='ck_shipping_review_line_decisions_code',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"line_status IN ("
|
||||
"'pending_decision', 'waiting_inventory', 'ready_to_fulfill', "
|
||||
"'task_created', 'fulfilled', 'closed_unfulfillable', 'reopened'"
|
||||
")",
|
||||
name='ck_shipping_review_line_decisions_status',
|
||||
),
|
||||
sa.CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'),
|
||||
)
|
||||
# [STEP 2] 查询索引
|
||||
op.create_index(
|
||||
'ix_shipping_review_line_decisions_case_line',
|
||||
'shipping_order_review_line_decisions',
|
||||
['review_case_id', 'line_key'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_review_line_decisions_case_active',
|
||||
'shipping_order_review_line_decisions',
|
||||
['review_case_id', 'is_active'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_review_line_decisions_task',
|
||||
'shipping_order_review_line_decisions',
|
||||
['task_id'],
|
||||
)
|
||||
# [STEP 3] 同一行最多一个活动决定(部分方言支持部分唯一索引)
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name == 'postgresql':
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
CREATE UNIQUE INDEX uq_shipping_review_line_decisions_active_line
|
||||
ON shipping_order_review_line_decisions (review_case_id, line_key)
|
||||
WHERE is_active IS TRUE
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
# [STEP 4] 允许多波次确认修订:Case 不再限制单次 confirmed revision
|
||||
op.drop_constraint(
|
||||
'uq_shipping_order_review_confirmed_revisions_case',
|
||||
'shipping_order_review_confirmed_revisions',
|
||||
type_='unique',
|
||||
)
|
||||
op.create_unique_constraint(
|
||||
'uq_shipping_order_review_confirmed_revisions_case_task',
|
||||
'shipping_order_review_confirmed_revisions',
|
||||
['case_id', 'task_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_review_confirmed_revisions_case',
|
||||
'shipping_order_review_confirmed_revisions',
|
||||
['case_id'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除行级履约决定表并恢复单次确认约束。"""
|
||||
op.drop_index(
|
||||
'ix_shipping_order_review_confirmed_revisions_case',
|
||||
table_name='shipping_order_review_confirmed_revisions',
|
||||
)
|
||||
op.drop_constraint(
|
||||
'uq_shipping_order_review_confirmed_revisions_case_task',
|
||||
'shipping_order_review_confirmed_revisions',
|
||||
type_='unique',
|
||||
)
|
||||
op.create_unique_constraint(
|
||||
'uq_shipping_order_review_confirmed_revisions_case',
|
||||
'shipping_order_review_confirmed_revisions',
|
||||
['case_id'],
|
||||
)
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name == 'postgresql':
|
||||
op.execute(sa.text('DROP INDEX IF EXISTS uq_shipping_review_line_decisions_active_line'))
|
||||
op.drop_index('ix_shipping_review_line_decisions_task', table_name='shipping_order_review_line_decisions')
|
||||
op.drop_index('ix_shipping_review_line_decisions_case_active', table_name='shipping_order_review_line_decisions')
|
||||
op.drop_index('ix_shipping_review_line_decisions_case_line', table_name='shipping_order_review_line_decisions')
|
||||
op.drop_table('shipping_order_review_line_decisions')
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
migrations/versions/cm5e6f7a8b9c_add_submission_ordinal_unique.py
|
||||
|
||||
用途:为根 Run 的会话提交序号增加部分唯一约束,防止绕过服务层产生重复序号。
|
||||
依赖:alembic.op、shipping_order_extraction_runs。
|
||||
逻辑:Revises cm4d5e6f7a8b;仅约束 reparse_of_run_id IS NULL 且 submission_ordinal
|
||||
非空的行;后继/重识别 Run 可继承同一序号。
|
||||
|
||||
Revision ID: cm5e6f7a8b9c
|
||||
Revises: cm4d5e6f7a8b
|
||||
Create Date: 2026-08-04 08:30:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm5e6f7a8b9c'
|
||||
down_revision = 'cm4d5e6f7a8b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
创建根任务提交序号部分唯一索引。
|
||||
|
||||
核心逻辑:与模型 Index 对齐;PostgreSQL / SQLite 均使用部分唯一条件。
|
||||
"""
|
||||
op.create_index(
|
||||
'uq_shipping_order_extraction_runs_submission_ordinal',
|
||||
'shipping_order_extraction_runs',
|
||||
['user_id', 'conversation_id', 'submission_ordinal'],
|
||||
unique=True,
|
||||
postgresql_where=sa.text(
|
||||
'reparse_of_run_id IS NULL AND submission_ordinal IS NOT NULL'
|
||||
),
|
||||
sqlite_where=sa.text(
|
||||
'reparse_of_run_id IS NULL AND submission_ordinal IS NOT NULL'
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除根任务提交序号部分唯一索引。"""
|
||||
op.drop_index(
|
||||
'uq_shipping_order_extraction_runs_submission_ordinal',
|
||||
table_name='shipping_order_extraction_runs',
|
||||
)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
migrations/versions/cm6f7a8b9c0d_add_shipping_review_wave_lines.py
|
||||
|
||||
用途:复核 Case 履约波次行归属表(不可变,行级唯一入 Task)。
|
||||
依赖:alembic.op、shipping_order_review_cases、shipping_tasks、confirmed_revisions。
|
||||
逻辑:Revises cm5e6f7a8b9c;创建 shipping_order_review_wave_lines 及 (case, line_key) 唯一约束。
|
||||
|
||||
Revision ID: cm6f7a8b9c0d
|
||||
Revises: cm5e6f7a8b9c
|
||||
Create Date: 2026-08-04 10:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm6f7a8b9c0d'
|
||||
down_revision = 'cm5e6f7a8b9c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建波次行归属表与唯一约束。"""
|
||||
# [STEP 1] 建表:同一 Case 明细行最多关联一个 Task
|
||||
op.create_table(
|
||||
'shipping_order_review_wave_lines',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
'review_case_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column('line_key', sa.String(length=64), nullable=False),
|
||||
sa.Column(
|
||||
'task_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_tasks.id'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column('wave_no', sa.Integer(), nullable=False),
|
||||
sa.Column(
|
||||
'confirmed_revision_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
'review_case_id',
|
||||
'line_key',
|
||||
name='uq_shipping_review_wave_lines_case_line',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_review_wave_lines_task',
|
||||
'shipping_order_review_wave_lines',
|
||||
['task_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_review_wave_lines_case_wave',
|
||||
'shipping_order_review_wave_lines',
|
||||
['review_case_id', 'wave_no'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除波次行归属表。"""
|
||||
op.drop_index('ix_shipping_review_wave_lines_case_wave', table_name='shipping_order_review_wave_lines')
|
||||
op.drop_index('ix_shipping_review_wave_lines_task', table_name='shipping_order_review_wave_lines')
|
||||
op.drop_table('shipping_order_review_wave_lines')
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
migrations/versions/cm7a8b9c0d1e_add_order_profile_matching_signature_refs.py
|
||||
|
||||
用途:为订单文档模板增加版面签名轻量引用,并扩展 ValidationRun / PublishCheckReport 契约。
|
||||
依赖:alembic.op、shipping_order_document_profiles、validation_runs、publish_check_reports。
|
||||
逻辑:Revises cm6f7a8b9c0d;不新建独立签名表;完整签名仍写入 ValidationRun.result_snapshot_json。
|
||||
|
||||
Revision ID: cm7a8b9c0d1e
|
||||
Revises: cm6f7a8b9c0d
|
||||
Create Date: 2026-08-04 12:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm7a8b9c0d1e'
|
||||
down_revision = 'cm6f7a8b9c0d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_RUN_TYPES_OLD = (
|
||||
"run_type IN ('instant_check', 'current_sample', 'blind_test', "
|
||||
"'scenario_coverage', 'schema_compatibility')"
|
||||
)
|
||||
_RUN_TYPES_NEW = (
|
||||
"run_type IN ('instant_check', 'current_sample', 'blind_test', "
|
||||
"'scenario_coverage', 'schema_compatibility', 'layout_signature', "
|
||||
"'cross_template_overlap')"
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""新增签名引用字段,并扩展 validation run_type 约束。"""
|
||||
# [STEP 1] Profile 主表:当前有效签名轻量引用
|
||||
with op.batch_alter_table('shipping_order_document_profiles', recreate='auto') as batch:
|
||||
batch.add_column(sa.Column('matching_signature_run_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('matching_signature_checksum', sa.String(length=64), nullable=True))
|
||||
batch.add_column(sa.Column('matching_signature_version', sa.String(length=64), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_sodp_matching_signature_run',
|
||||
'shipping_order_document_profile_validation_runs',
|
||||
['matching_signature_run_id'],
|
||||
['id'],
|
||||
ondelete='SET NULL',
|
||||
)
|
||||
batch.create_index(
|
||||
'ix_shipping_order_document_profiles_matching_signature_run',
|
||||
['matching_signature_run_id'],
|
||||
)
|
||||
batch.create_index(
|
||||
'ix_shipping_order_document_profiles_matching_signature_checksum',
|
||||
['matching_signature_checksum'],
|
||||
)
|
||||
|
||||
# [STEP 2] PublishCheckReport:签名与交叉验证引用
|
||||
with op.batch_alter_table('shipping_order_document_profile_publish_check_reports', recreate='auto') as batch:
|
||||
batch.add_column(sa.Column('matching_signature_run_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('matching_signature_checksum', sa.String(length=64), nullable=True))
|
||||
batch.add_column(sa.Column('overlap_validation_run_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('matcher_policy_version', sa.String(length=64), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_sodp_pcr_matching_signature_run',
|
||||
'shipping_order_document_profile_validation_runs',
|
||||
['matching_signature_run_id'],
|
||||
['id'],
|
||||
ondelete='SET NULL',
|
||||
)
|
||||
batch.create_foreign_key(
|
||||
'fk_sodp_pcr_overlap_validation_run',
|
||||
'shipping_order_document_profile_validation_runs',
|
||||
['overlap_validation_run_id'],
|
||||
['id'],
|
||||
ondelete='SET NULL',
|
||||
)
|
||||
|
||||
# [STEP 3] ValidationRun:允许 layout_signature / cross_template_overlap
|
||||
with op.batch_alter_table('shipping_order_document_profile_validation_runs', recreate='auto') as batch:
|
||||
batch.drop_constraint('ck_shipping_order_document_profile_validation_runs_type', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_document_profile_validation_runs_type',
|
||||
_RUN_TYPES_NEW,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚签名引用字段与新增 run_type;历史 layout_signature 行须先清理。"""
|
||||
with op.batch_alter_table('shipping_order_document_profile_validation_runs', recreate='auto') as batch:
|
||||
batch.drop_constraint('ck_shipping_order_document_profile_validation_runs_type', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_document_profile_validation_runs_type',
|
||||
_RUN_TYPES_OLD,
|
||||
)
|
||||
|
||||
with op.batch_alter_table('shipping_order_document_profile_publish_check_reports', recreate='auto') as batch:
|
||||
batch.drop_constraint('fk_sodp_pcr_overlap_validation_run', type_='foreignkey')
|
||||
batch.drop_constraint('fk_sodp_pcr_matching_signature_run', type_='foreignkey')
|
||||
batch.drop_column('matcher_policy_version')
|
||||
batch.drop_column('overlap_validation_run_id')
|
||||
batch.drop_column('matching_signature_checksum')
|
||||
batch.drop_column('matching_signature_run_id')
|
||||
|
||||
with op.batch_alter_table('shipping_order_document_profiles', recreate='auto') as batch:
|
||||
batch.drop_index('ix_shipping_order_document_profiles_matching_signature_checksum')
|
||||
batch.drop_index('ix_shipping_order_document_profiles_matching_signature_run')
|
||||
batch.drop_constraint('fk_sodp_matching_signature_run', type_='foreignkey')
|
||||
batch.drop_column('matching_signature_version')
|
||||
batch.drop_column('matching_signature_checksum')
|
||||
batch.drop_column('matching_signature_run_id')
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
migrations/versions/cm8b9c0d1e2f_freeze_blind_test_layout_identity.py
|
||||
|
||||
用途:为订单模板盲测样本冻结确认时的 Layout 版本、校验值和解析器身份。
|
||||
依赖:shipping_document_profile_test_samples、shipping_document_layout_versions、Alembic。
|
||||
逻辑:新样本必须写入稳定身份;历史样本保留空值并在执行时安全失败,禁止改用最新布局。
|
||||
|
||||
Revision ID: cm8b9c0d1e2f
|
||||
Revises: cm7a8b9c0d1e
|
||||
Create Date: 2026-08-04 18:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm8b9c0d1e2f'
|
||||
down_revision = 'cm7a8b9c0d1e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""增加可审计的盲测 Layout 冻结身份;不为历史记录猜测当前版本。"""
|
||||
op.add_column('shipping_document_profile_test_samples', sa.Column('layout_version_id', sa.Integer(), nullable=True))
|
||||
op.add_column('shipping_document_profile_test_samples', sa.Column('layout_payload_checksum', sa.String(length=64), nullable=True))
|
||||
op.add_column('shipping_document_profile_test_samples', sa.Column('layout_parser_key', sa.String(length=128), nullable=True))
|
||||
op.add_column('shipping_document_profile_test_samples', sa.Column('layout_parser_version', sa.String(length=64), nullable=True))
|
||||
op.create_foreign_key(
|
||||
'fk_shipping_profile_test_samples_layout_version',
|
||||
'shipping_document_profile_test_samples', 'shipping_document_layout_versions',
|
||||
['layout_version_id'], ['id'], ondelete='RESTRICT',
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除盲测样本的 Layout 冻结身份。"""
|
||||
op.drop_constraint(
|
||||
'fk_shipping_profile_test_samples_layout_version',
|
||||
'shipping_document_profile_test_samples', type_='foreignkey',
|
||||
)
|
||||
op.drop_column('shipping_document_profile_test_samples', 'layout_parser_version')
|
||||
op.drop_column('shipping_document_profile_test_samples', 'layout_parser_key')
|
||||
op.drop_column('shipping_document_profile_test_samples', 'layout_payload_checksum')
|
||||
op.drop_column('shipping_document_profile_test_samples', 'layout_version_id')
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
migrations/versions/cm9c0d1e2f3a_add_shipping_xfa_structure_analysis.py
|
||||
|
||||
用途:新增 XFA 结构分析表,持久化 document_kind、packet checksum、结构指纹与安全摘要。
|
||||
依赖:alembic.op、shipping_notice_documents、shipping_document_layout_versions。
|
||||
逻辑:接在 cm8b9c0d1e2f(盲测 Layout 冻结)之后;不保存原始 XML/PDF 正文,encrypted_snapshot_ref 仅占位。
|
||||
|
||||
Revision ID: cm9c0d1e2f3a
|
||||
Revises: cm8b9c0d1e2f
|
||||
Create Date: 2026-08-04 18:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cm9c0d1e2f3a'
|
||||
down_revision = 'cm8b9c0d1e2f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 shipping_xfa_structure_analyses 表及索引/约束。"""
|
||||
op.create_table(
|
||||
'shipping_xfa_structure_analyses',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
'document_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_notice_documents.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
'layout_version_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_document_layout_versions.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('source_content_hash', sa.String(length=64), nullable=False),
|
||||
sa.Column('document_kind', sa.String(length=32), nullable=False),
|
||||
sa.Column('analysis_status', sa.String(length=16), nullable=False, server_default='ready'),
|
||||
sa.Column('template_packet_checksum', sa.String(length=128), nullable=True),
|
||||
sa.Column('datasets_packet_checksum', sa.String(length=128), nullable=True),
|
||||
sa.Column('dataset_structure_fingerprint', sa.String(length=128), nullable=True),
|
||||
sa.Column('packet_checksums_json', sa.JSON(), nullable=False),
|
||||
sa.Column('stats_json', sa.JSON(), nullable=False),
|
||||
sa.Column('security_summary_json', sa.JSON(), nullable=False),
|
||||
sa.Column('tree_summary_json', sa.JSON(), nullable=False),
|
||||
sa.Column('error_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('route_reason', sa.String(length=64), nullable=True),
|
||||
sa.Column('encrypted_snapshot_ref', sa.String(length=256), nullable=True),
|
||||
sa.Column('parser_identity', sa.String(length=64), nullable=False),
|
||||
sa.Column('contract_version', sa.String(length=64), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('finished_at', sa.DateTime(), nullable=True),
|
||||
sa.CheckConstraint(
|
||||
"analysis_status IN ('ready', 'failed', 'rejected')",
|
||||
name='ck_shipping_xfa_structure_analysis_status',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"document_kind IN ('plain_pdf', 'acroform', 'xfa_hybrid', 'pure_xfa', 'unsupported')",
|
||||
name='ck_shipping_xfa_structure_analysis_document_kind',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_xfa_structure_analysis_document',
|
||||
'shipping_xfa_structure_analyses',
|
||||
['document_id', 'created_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_xfa_structure_analysis_content_hash',
|
||||
'shipping_xfa_structure_analyses',
|
||||
['source_content_hash'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_xfa_structure_analysis_fingerprint',
|
||||
'shipping_xfa_structure_analyses',
|
||||
['dataset_structure_fingerprint'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除 XFA 结构分析表。"""
|
||||
op.drop_index(
|
||||
'ix_shipping_xfa_structure_analysis_fingerprint',
|
||||
table_name='shipping_xfa_structure_analyses',
|
||||
)
|
||||
op.drop_index(
|
||||
'ix_shipping_xfa_structure_analysis_content_hash',
|
||||
table_name='shipping_xfa_structure_analyses',
|
||||
)
|
||||
op.drop_index(
|
||||
'ix_shipping_xfa_structure_analysis_document',
|
||||
table_name='shipping_xfa_structure_analyses',
|
||||
)
|
||||
op.drop_table('shipping_xfa_structure_analyses')
|
||||
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
migrations/versions/cn0d1e2f3a4b_add_xfa_structure_signature_run_type.py
|
||||
|
||||
用途:ValidationRun 允许 xfa_structure_signature,供 XFA Profile 发布门禁冻结结构身份。
|
||||
依赖:Alembic、既有 ck_shipping_order_document_profile_validation_runs_type。
|
||||
逻辑:扩展 CHECK;downgrade 时拒绝仍存在 xfa_structure_signature 行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = 'cn0d1e2f3a4b'
|
||||
down_revision = 'cm9c0d1e2f3a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_RUN_TYPES_OLD = (
|
||||
"run_type IN ('instant_check', 'current_sample', 'blind_test', 'scenario_coverage', "
|
||||
"'schema_compatibility', 'layout_signature', 'cross_template_overlap')"
|
||||
)
|
||||
_RUN_TYPES_NEW = (
|
||||
"run_type IN ('instant_check', 'current_sample', 'blind_test', 'scenario_coverage', "
|
||||
"'schema_compatibility', 'layout_signature', 'cross_template_overlap', 'xfa_structure_signature')"
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""扩展 ValidationRun.run_type 以支持 XFA 结构签名。"""
|
||||
with op.batch_alter_table('shipping_order_document_profile_validation_runs', recreate='auto') as batch:
|
||||
batch.drop_constraint('ck_shipping_order_document_profile_validation_runs_type', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_document_profile_validation_runs_type',
|
||||
_RUN_TYPES_NEW,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚 run_type;若仍有 xfa_structure_signature 行则失败关闭。"""
|
||||
conn = op.get_bind()
|
||||
remaining = conn.exec_driver_sql(
|
||||
"SELECT COUNT(1) FROM shipping_order_document_profile_validation_runs "
|
||||
"WHERE run_type = 'xfa_structure_signature'"
|
||||
).scalar()
|
||||
if int(remaining or 0) > 0:
|
||||
raise RuntimeError(
|
||||
'Cannot downgrade while xfa_structure_signature validation runs exist',
|
||||
)
|
||||
with op.batch_alter_table('shipping_order_document_profile_validation_runs', recreate='auto') as batch:
|
||||
batch.drop_constraint('ck_shipping_order_document_profile_validation_runs_type', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_order_document_profile_validation_runs_type',
|
||||
_RUN_TYPES_OLD,
|
||||
)
|
||||
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
migrations/versions/co2e3f4a5b6c_add_shipping_xfa_audit_snapshots.py
|
||||
|
||||
用途:新增 XFA 审计加密不可变快照表及 PostgreSQL append-only 触发器。
|
||||
依赖:alembic.op;接在 cn0d1e2f3a4b(XFA structure signature run_type)之后。
|
||||
逻辑:创建 shipping_xfa_audit_snapshots;UPDATE 一律拒绝;DELETE 仅当
|
||||
set_config('hxops.shipping_xfa_audit_purge','1') 且 retention 已到期。
|
||||
|
||||
Revision ID: co2e3f4a5b6c
|
||||
Revises: cn0d1e2f3a4b
|
||||
Create Date: 2026-08-04 21:30:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'co2e3f4a5b6c'
|
||||
down_revision = 'cn0d1e2f3a4b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 XFA 审计快照表、索引与 PostgreSQL 不可变触发器。"""
|
||||
op.create_table(
|
||||
'shipping_xfa_audit_snapshots',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('snapshot_ref', 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('purpose', sa.String(length=32), nullable=False),
|
||||
sa.Column('schema_version', sa.String(length=32), nullable=False, server_default='xfa_audit_v1'),
|
||||
sa.Column('encryption_alg', sa.String(length=32), nullable=False, server_default='fernet-v1'),
|
||||
sa.Column('key_id', sa.String(length=64), nullable=False, server_default='primary'),
|
||||
sa.Column('ciphertext', sa.Text(), nullable=False),
|
||||
sa.Column('ciphertext_sha256', sa.String(length=64), nullable=False),
|
||||
sa.Column('plaintext_sha256', sa.String(length=64), nullable=False),
|
||||
sa.Column('redacted_summary_json', sa.JSON(), nullable=True),
|
||||
sa.Column('actor_id', 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('audit_event_id', sa.Integer(), nullable=True),
|
||||
sa.Column('retention_expires_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint('snapshot_ref', name='uq_shipping_xfa_audit_snapshots_ref'),
|
||||
sa.CheckConstraint(
|
||||
"purpose IN ('before', 'after', 'request', 'full', 'sample_values')",
|
||||
name='ck_shipping_xfa_audit_snapshots_purpose',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"encryption_alg IN ('fernet-v1')",
|
||||
name='ck_shipping_xfa_audit_snapshots_encryption_alg',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_xfa_audit_snapshots_object',
|
||||
'shipping_xfa_audit_snapshots',
|
||||
['object_type', 'object_id', 'created_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_xfa_audit_snapshots_retention',
|
||||
'shipping_xfa_audit_snapshots',
|
||||
['retention_expires_at', 'id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_xfa_audit_snapshots_operation',
|
||||
'shipping_xfa_audit_snapshots',
|
||||
['operation_id', 'created_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_xfa_audit_snapshots_request',
|
||||
'shipping_xfa_audit_snapshots',
|
||||
['request_id', 'created_at'],
|
||||
)
|
||||
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != 'postgresql':
|
||||
return
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION hxops_shipping_xfa_audit_reject_update()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'shipping_xfa_audit_snapshots is append-only: UPDATE forbidden'
|
||||
USING ERRCODE = 'integrity_constraint_violation';
|
||||
END;
|
||||
$$;
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION hxops_shipping_xfa_audit_guard_delete()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
IF current_setting('hxops.shipping_xfa_audit_purge', true) IS DISTINCT FROM '1' THEN
|
||||
RAISE EXCEPTION 'shipping_xfa_audit_snapshots is append-only: DELETE forbidden'
|
||||
USING ERRCODE = 'integrity_constraint_violation';
|
||||
END IF;
|
||||
IF OLD.retention_expires_at IS NULL OR OLD.retention_expires_at >= now() THEN
|
||||
RAISE EXCEPTION
|
||||
'shipping_xfa_audit_snapshots purge only allows expired rows'
|
||||
USING ERRCODE = 'integrity_constraint_violation';
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
DROP TRIGGER IF EXISTS trg_shipping_xfa_audit_snapshots_no_update
|
||||
ON shipping_xfa_audit_snapshots;
|
||||
CREATE TRIGGER trg_shipping_xfa_audit_snapshots_no_update
|
||||
BEFORE UPDATE ON shipping_xfa_audit_snapshots
|
||||
FOR EACH ROW
|
||||
EXECUTE PROCEDURE hxops_shipping_xfa_audit_reject_update();
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
DROP TRIGGER IF EXISTS trg_shipping_xfa_audit_snapshots_guard_delete
|
||||
ON shipping_xfa_audit_snapshots;
|
||||
CREATE TRIGGER trg_shipping_xfa_audit_snapshots_guard_delete
|
||||
BEFORE DELETE ON shipping_xfa_audit_snapshots
|
||||
FOR EACH ROW
|
||||
EXECUTE PROCEDURE hxops_shipping_xfa_audit_guard_delete();
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除触发器与 XFA 审计快照表。"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name == 'postgresql':
|
||||
op.execute('DROP TRIGGER IF EXISTS trg_shipping_xfa_audit_snapshots_guard_delete ON shipping_xfa_audit_snapshots;')
|
||||
op.execute('DROP TRIGGER IF EXISTS trg_shipping_xfa_audit_snapshots_no_update ON shipping_xfa_audit_snapshots;')
|
||||
op.execute('DROP FUNCTION IF EXISTS hxops_shipping_xfa_audit_guard_delete();')
|
||||
op.execute('DROP FUNCTION IF EXISTS hxops_shipping_xfa_audit_reject_update();')
|
||||
op.drop_index('ix_shipping_xfa_audit_snapshots_request', table_name='shipping_xfa_audit_snapshots')
|
||||
op.drop_index('ix_shipping_xfa_audit_snapshots_operation', table_name='shipping_xfa_audit_snapshots')
|
||||
op.drop_index('ix_shipping_xfa_audit_snapshots_retention', table_name='shipping_xfa_audit_snapshots')
|
||||
op.drop_index('ix_shipping_xfa_audit_snapshots_object', table_name='shipping_xfa_audit_snapshots')
|
||||
op.drop_table('shipping_xfa_audit_snapshots')
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
"""
|
||||
migrations/versions/co3f4a5b6c7d_add_order_submissions_and_intake_source_type.py
|
||||
|
||||
用途:阶段 1 — 新增上传边界表 shipping_order_submissions,并为
|
||||
shipping_notice_intakes 增加 source_type / order_submission_id(增量适配,不重命名旧表)。
|
||||
依赖:alembic.op;接在 co2e3f4a5b6c 之后。
|
||||
逻辑:创建 Submission 表;Intake 增加 eml|direct_pdf 来源与 FK;按 FileAsset 扩展名回填
|
||||
历史 source_type;不改动 Extraction Submission / Run / Candidate 路径。
|
||||
|
||||
Revision ID: co3f4a5b6c7d
|
||||
Revises: co2e3f4a5b6c
|
||||
Create Date: 2026-08-04 21:40:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'co3f4a5b6c7d'
|
||||
down_revision = 'co2e3f4a5b6c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 shipping_order_submissions 并为 intakes 增加来源类型与 Submission 外键。"""
|
||||
op.create_table(
|
||||
'shipping_order_submissions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('submission_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('client_submission_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),
|
||||
sa.Column('owner_agent_id', sa.Integer(), sa.ForeignKey('agents.id'), nullable=True),
|
||||
sa.Column('conversation_id', sa.String(length=100), nullable=True),
|
||||
sa.Column('upload_batch_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='accepted'),
|
||||
sa.Column('intake_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('eml_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('direct_pdf_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('error_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('completed_at', sa.DateTime(), nullable=True),
|
||||
sa.UniqueConstraint('submission_no', name='uq_shipping_order_submissions_submission_no'),
|
||||
sa.UniqueConstraint(
|
||||
'user_id',
|
||||
'upload_batch_id',
|
||||
name='uq_shipping_order_submissions_user_upload_batch',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('accepted', 'processing', 'completed', 'failed', 'cancelled')",
|
||||
name='ck_shipping_order_submissions_status',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_submissions_user_conversation_created',
|
||||
'shipping_order_submissions',
|
||||
['user_id', 'conversation_id', 'created_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_submissions_status_created',
|
||||
'shipping_order_submissions',
|
||||
['status', 'created_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_submissions_client_submission',
|
||||
'shipping_order_submissions',
|
||||
['user_id', 'client_submission_id'],
|
||||
)
|
||||
|
||||
op.add_column(
|
||||
'shipping_notice_intakes',
|
||||
sa.Column('source_type', sa.String(length=32), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
'shipping_notice_intakes',
|
||||
sa.Column(
|
||||
'order_submission_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_submissions.id'),
|
||||
nullable=True,
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_intakes_source_type',
|
||||
'shipping_notice_intakes',
|
||||
['source_type'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_intakes_order_submission_id',
|
||||
'shipping_notice_intakes',
|
||||
['order_submission_id'],
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_intakes_source_type',
|
||||
'shipping_notice_intakes',
|
||||
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
|
||||
)
|
||||
|
||||
# [STEP] 按 FileAsset.extension 回填历史 Intake 来源(仅 eml/pdf;其余保持 NULL)。
|
||||
bind = op.get_bind()
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE shipping_notice_intakes AS i
|
||||
SET source_type = CASE
|
||||
WHEN lower(coalesce(a.extension, '')) = 'eml' THEN 'eml'
|
||||
WHEN lower(coalesce(a.extension, '')) = 'pdf' THEN 'direct_pdf'
|
||||
ELSE NULL
|
||||
END
|
||||
FROM file_assets AS a
|
||||
WHERE i.asset_id = a.id
|
||||
AND i.source_type IS NULL
|
||||
"""
|
||||
)
|
||||
if bind.dialect.name == 'postgresql'
|
||||
else sa.text(
|
||||
"""
|
||||
UPDATE shipping_notice_intakes
|
||||
SET source_type = (
|
||||
SELECT CASE
|
||||
WHEN lower(coalesce(a.extension, '')) = 'eml' THEN 'eml'
|
||||
WHEN lower(coalesce(a.extension, '')) = 'pdf' THEN 'direct_pdf'
|
||||
ELSE NULL
|
||||
END
|
||||
FROM file_assets AS a
|
||||
WHERE a.id = shipping_notice_intakes.asset_id
|
||||
)
|
||||
WHERE source_type IS NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚 Intake 来源列与 shipping_order_submissions。"""
|
||||
op.drop_constraint('ck_shipping_notice_intakes_source_type', 'shipping_notice_intakes', type_='check')
|
||||
op.drop_index('ix_shipping_notice_intakes_order_submission_id', table_name='shipping_notice_intakes')
|
||||
op.drop_index('ix_shipping_notice_intakes_source_type', table_name='shipping_notice_intakes')
|
||||
op.drop_column('shipping_notice_intakes', 'order_submission_id')
|
||||
op.drop_column('shipping_notice_intakes', 'source_type')
|
||||
op.drop_index('ix_shipping_order_submissions_client_submission', table_name='shipping_order_submissions')
|
||||
op.drop_index('ix_shipping_order_submissions_status_created', table_name='shipping_order_submissions')
|
||||
op.drop_index(
|
||||
'ix_shipping_order_submissions_user_conversation_created',
|
||||
table_name='shipping_order_submissions',
|
||||
)
|
||||
op.drop_table('shipping_order_submissions')
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
migrations/versions/co4a5b6c7d8e_rename_shipping_order_intake_document_candidate.py
|
||||
|
||||
用途:将建单前接入层三表 rename 为 shipping_order_*,对齐 technical.md §1.6.2。
|
||||
依赖:alembic.op;接在 co3f4a5b6c7d(order submissions + intake source_type)之后。
|
||||
逻辑:RENAME 三表;同步约束/索引名;downgrade 对称回滚。不改 API 契约与历史迁移。
|
||||
|
||||
Revision ID: co4a5b6c7d8e
|
||||
Revises: co3f4a5b6c7d
|
||||
Create Date: 2026-08-04 23:55:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'co4a5b6c7d8e'
|
||||
down_revision = 'co3f4a5b6c7d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
# 表内约束/索引:旧名 → 新名(不含 pkey,pkey 单独按表处理)
|
||||
_INTAKE_OBJECTS: list[tuple[str, str]] = [
|
||||
('ck_shipping_notice_intakes_purpose', 'ck_shipping_order_intakes_purpose'),
|
||||
('ck_shipping_notice_intakes_source_type', 'ck_shipping_order_intakes_source_type'),
|
||||
('uq_shipping_notice_intakes_intake_no', 'uq_shipping_order_intakes_intake_no'),
|
||||
('uq_shipping_notice_intakes_asset_purpose_parser', 'uq_shipping_order_intakes_asset_purpose_parser'),
|
||||
('ix_shipping_notice_intakes_user_conversation_created', 'ix_shipping_order_intakes_user_conversation_created'),
|
||||
('ix_shipping_notice_intakes_user_upload_batch_created', 'ix_shipping_order_intakes_user_upload_batch_created'),
|
||||
('ix_shipping_notice_intakes_parse_status_created', 'ix_shipping_order_intakes_parse_status_created'),
|
||||
('ix_shipping_notice_intakes_expires', 'ix_shipping_order_intakes_expires'),
|
||||
('ix_shipping_notice_intakes_user_business_fingerprint', 'ix_shipping_order_intakes_user_business_fingerprint'),
|
||||
('ix_shipping_notice_intakes_duplicate_status_created', 'ix_shipping_order_intakes_duplicate_status_created'),
|
||||
('ix_shipping_notice_intakes_fp_version_fingerprint', 'ix_shipping_order_intakes_fp_version_fingerprint'),
|
||||
('ix_shipping_notice_intakes_user_create_idempotency', 'ix_shipping_order_intakes_user_create_idempotency'),
|
||||
('ix_shipping_notice_intakes_source_type', 'ix_shipping_order_intakes_source_type'),
|
||||
('ix_shipping_notice_intakes_order_submission_id', 'ix_shipping_order_intakes_order_submission_id'),
|
||||
('ix_shipping_notice_intakes_asset_id', 'ix_shipping_order_intakes_asset_id'),
|
||||
('ix_shipping_notice_intakes_user_id', 'ix_shipping_order_intakes_user_id'),
|
||||
('ix_shipping_notice_intakes_parse_status', 'ix_shipping_order_intakes_parse_status'),
|
||||
('ix_shipping_notice_intakes_parse_job_id', 'ix_shipping_order_intakes_parse_job_id'),
|
||||
('ix_shipping_notice_intakes_order_extraction_status', 'ix_shipping_order_intakes_order_extraction_status'),
|
||||
('ix_shipping_notice_intakes_created_at', 'ix_shipping_order_intakes_created_at'),
|
||||
]
|
||||
|
||||
_DOCUMENT_OBJECTS: list[tuple[str, str]] = [
|
||||
('uq_shipping_notice_documents_intake_attachment_key', 'uq_shipping_order_documents_intake_attachment_key'),
|
||||
('uq_shipping_notice_documents_id_intake', 'uq_shipping_order_documents_id_intake'),
|
||||
('ix_shipping_notice_documents_intake_id', 'ix_shipping_order_documents_intake_id'),
|
||||
('ix_shipping_notice_documents_asset_id', 'ix_shipping_order_documents_asset_id'),
|
||||
('ix_shipping_notice_documents_content_hash', 'ix_shipping_order_documents_content_hash'),
|
||||
('ix_shipping_notice_documents_parse_status', 'ix_shipping_order_documents_parse_status'),
|
||||
('ix_shipping_notice_documents_created_at', 'ix_shipping_order_documents_created_at'),
|
||||
('ix_shipping_notice_documents_order_extraction_status', 'ix_shipping_order_documents_order_extraction_status'),
|
||||
(
|
||||
'fk_shipping_notice_documents_current_layout_version',
|
||||
'fk_shipping_order_documents_current_layout_version',
|
||||
),
|
||||
]
|
||||
|
||||
_CANDIDATE_OBJECTS: list[tuple[str, str]] = [
|
||||
('ck_shipping_notice_candidates_status', 'ck_shipping_order_candidates_status'),
|
||||
('ck_shipping_notice_candidates_acceptance_mode', 'ck_shipping_order_candidates_acceptance_mode'),
|
||||
('uq_shipping_notice_candidates_candidate_no', 'uq_shipping_order_candidates_candidate_no'),
|
||||
('uq_shipping_notice_candidates_intake_key_run', 'uq_shipping_order_candidates_intake_key_run'),
|
||||
# 历史唯一约束名(已被 intake_key_run 替代,若仍存在则一并改名)
|
||||
('uq_shipping_notice_candidates_intake_primary_document', 'uq_shipping_order_candidates_intake_primary_document'),
|
||||
('fk_shipping_notice_candidates_document_intake', 'fk_shipping_order_candidates_document_intake'),
|
||||
('ix_shipping_notice_candidates_intake_id', 'ix_shipping_order_candidates_intake_id'),
|
||||
('ix_shipping_notice_candidates_primary_document_id', 'ix_shipping_order_candidates_primary_document_id'),
|
||||
('ix_shipping_notice_candidates_po_number', 'ix_shipping_order_candidates_po_number'),
|
||||
('ix_shipping_notice_candidates_user_fingerprint', 'ix_shipping_order_candidates_user_fingerprint'),
|
||||
('ix_shipping_notice_candidates_duplicate_status', 'ix_shipping_order_candidates_duplicate_status'),
|
||||
('ix_shipping_notice_candidates_fulfillment_gate', 'ix_shipping_order_candidates_fulfillment_gate'),
|
||||
('ix_shipping_notice_candidates_created_at', 'ix_shipping_order_candidates_created_at'),
|
||||
('ix_shipping_notice_candidates_candidate_status', 'ix_shipping_order_candidates_candidate_status'),
|
||||
('ix_shipping_notice_candidates_is_current_version', 'ix_shipping_order_candidates_is_current_version'),
|
||||
('ix_shipping_notice_candidates_order_extraction_id', 'ix_shipping_order_candidates_order_extraction_id'),
|
||||
('ix_shipping_notice_candidates_order_extraction_run_id', 'ix_shipping_order_candidates_order_extraction_run_id'),
|
||||
]
|
||||
|
||||
|
||||
def _rename_constraint_if_exists(table: str, old: str, new: str) -> None:
|
||||
"""
|
||||
若旧约束存在则改名(PostgreSQL)。
|
||||
|
||||
核心逻辑:查 pg_constraint;存在则 ALTER TABLE RENAME CONSTRAINT。
|
||||
"""
|
||||
# 标识符来自本文件常量,禁止外部输入。
|
||||
op.execute(
|
||||
f"""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = '{old}'
|
||||
) THEN
|
||||
ALTER TABLE {table} RENAME CONSTRAINT {old} TO {new};
|
||||
END IF;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def _rename_index_if_exists(old: str, new: str) -> None:
|
||||
"""
|
||||
若旧索引存在则改名(PostgreSQL)。
|
||||
|
||||
核心逻辑:ALTER INDEX IF EXISTS;唯一约束同名索引由 RENAME CONSTRAINT 覆盖时可跳过。
|
||||
"""
|
||||
op.execute(sa.text(f'ALTER INDEX IF EXISTS {old} RENAME TO {new}'))
|
||||
|
||||
|
||||
def _rename_table_objects(table: str, pairs: list[tuple[str, str]]) -> None:
|
||||
"""
|
||||
对单表批量重命名约束与索引。
|
||||
|
||||
核心逻辑:先尝试约束改名,再尝试索引改名(覆盖非约束索引)。
|
||||
"""
|
||||
for old, new in pairs:
|
||||
_rename_constraint_if_exists(table, old, new)
|
||||
_rename_index_if_exists(old, new)
|
||||
|
||||
|
||||
def _rename_table_and_pkey(old_table: str, new_table: str) -> None:
|
||||
"""
|
||||
重命名表及其主键约束名。
|
||||
|
||||
Args:
|
||||
old_table: 旧表名。
|
||||
new_table: 新表名。
|
||||
"""
|
||||
op.rename_table(old_table, new_table)
|
||||
_rename_constraint_if_exists(new_table, f'{old_table}_pkey', f'{new_table}_pkey')
|
||||
_rename_index_if_exists(f'{old_table}_pkey', f'{new_table}_pkey')
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""将 notice intakes/documents/candidates 三表 rename 为 order_*。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
# [STEP 1] 幂等:已是目标名则跳过
|
||||
if 'shipping_order_intakes' in tables and 'shipping_notice_intakes' not in tables:
|
||||
return
|
||||
if 'shipping_notice_intakes' not in tables:
|
||||
raise RuntimeError('expected shipping_notice_intakes before rename migration')
|
||||
|
||||
# [STEP 2] 表 rename(FK 随 OID 自动跟随)
|
||||
_rename_table_and_pkey('shipping_notice_intakes', 'shipping_order_intakes')
|
||||
_rename_table_and_pkey('shipping_notice_documents', 'shipping_order_documents')
|
||||
_rename_table_and_pkey('shipping_notice_candidates', 'shipping_order_candidates')
|
||||
|
||||
# [STEP 3] 约束/索引名对齐可读性
|
||||
_rename_table_objects('shipping_order_intakes', _INTAKE_OBJECTS)
|
||||
_rename_table_objects('shipping_order_documents', _DOCUMENT_OBJECTS)
|
||||
_rename_table_objects('shipping_order_candidates', _CANDIDATE_OBJECTS)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""对称回滚为 shipping_notice_* 表名与约束名。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if 'shipping_notice_intakes' in tables and 'shipping_order_intakes' not in tables:
|
||||
return
|
||||
if 'shipping_order_intakes' not in tables:
|
||||
return
|
||||
|
||||
# [STEP 1] 先把约束/索引改回旧名(仍挂在 order_* 表上)
|
||||
_rename_table_objects(
|
||||
'shipping_order_intakes',
|
||||
[(new, old) for old, new in _INTAKE_OBJECTS],
|
||||
)
|
||||
_rename_table_objects(
|
||||
'shipping_order_documents',
|
||||
[(new, old) for old, new in _DOCUMENT_OBJECTS],
|
||||
)
|
||||
_rename_table_objects(
|
||||
'shipping_order_candidates',
|
||||
[(new, old) for old, new in _CANDIDATE_OBJECTS],
|
||||
)
|
||||
|
||||
# [STEP 2] 表与 pkey 回滚
|
||||
def _revert(new_table: str, old_table: str) -> None:
|
||||
_rename_constraint_if_exists(new_table, f'{new_table}_pkey', f'{old_table}_pkey')
|
||||
_rename_index_if_exists(f'{new_table}_pkey', f'{old_table}_pkey')
|
||||
op.rename_table(new_table, old_table)
|
||||
|
||||
_revert('shipping_order_candidates', 'shipping_notice_candidates')
|
||||
_revert('shipping_order_documents', 'shipping_notice_documents')
|
||||
_revert('shipping_order_intakes', 'shipping_notice_intakes')
|
||||
@@ -0,0 +1,312 @@
|
||||
"""
|
||||
migrations/versions/co5b6c7d8e9f_align_blueprint_order_notice_tables.py
|
||||
|
||||
用途:按多 EML/PDF 蓝图 §六 对齐核心表名:履约侧 shipping_notice_*、
|
||||
shipping_tasks→shipping_notices;布局版本 order_ 前缀;新建 OT 聚合根与
|
||||
Candidate 证据表。
|
||||
依赖:alembic.op;接在 co4a5b6c7d8e(接入层三表 rename)之后。
|
||||
逻辑:先 RENAME 既有表与约束名;再 CREATE shipping_order_tasks /
|
||||
shipping_order_candidate_evidences;从 extraction_runs.user_task_no 回填 OT。
|
||||
历史迁移不回改;extraction_*→processing_* 命名别名本轮不物理 rename。
|
||||
|
||||
Revision ID: co5b6c7d8e9f
|
||||
Revises: co4a5b6c7d8e
|
||||
Create Date: 2026-08-05 00:20:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'co5b6c7d8e9f'
|
||||
down_revision = 'co4a5b6c7d8e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
# (old_table, new_table)
|
||||
_TABLE_RENAMES: list[tuple[str, str]] = [
|
||||
('shipping_document_layout_versions', 'shipping_order_document_layout_versions'),
|
||||
('shipping_reservations', 'shipping_notice_reservations'),
|
||||
('shipping_inventory_verifications', 'shipping_notice_inventory_verifications'),
|
||||
('shipping_inventory_verification_lines', 'shipping_notice_inventory_verification_lines'),
|
||||
('shipping_export_artifacts', 'shipping_notice_export_artifacts'),
|
||||
('shipping_export_artifact_lines', 'shipping_notice_export_artifact_lines'),
|
||||
('shipping_upload_attempts', 'shipping_notice_upload_attempts'),
|
||||
('shipping_freight_cancellations', 'shipping_notice_freight_cancellations'),
|
||||
('shipping_tasks', 'shipping_notices'),
|
||||
]
|
||||
|
||||
|
||||
def _rename_constraint_if_exists(table: str, old: str, new: str) -> None:
|
||||
"""若旧约束存在则改名。"""
|
||||
op.execute(
|
||||
f"""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = '{old}') THEN
|
||||
ALTER TABLE {table} RENAME CONSTRAINT {old} TO {new};
|
||||
END IF;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def _rename_index_if_exists(old: str, new: str) -> None:
|
||||
"""若旧索引存在则改名。"""
|
||||
op.execute(sa.text(f'ALTER INDEX IF EXISTS {old} RENAME TO {new}'))
|
||||
|
||||
|
||||
def _rename_table_and_pkey(old_table: str, new_table: str) -> None:
|
||||
"""重命名表及其主键约束名。"""
|
||||
op.rename_table(old_table, new_table)
|
||||
_rename_constraint_if_exists(new_table, f'{old_table}_pkey', f'{new_table}_pkey')
|
||||
_rename_index_if_exists(f'{old_table}_pkey', f'{new_table}_pkey')
|
||||
|
||||
|
||||
def _bulk_rename_prefixed_objects(table: str, old_prefix: str, new_prefix: str) -> None:
|
||||
"""
|
||||
将表上以旧前缀开头的约束/索引名批量改为新前缀。
|
||||
|
||||
核心逻辑:查 pg_constraint / pg_class,仅改本表相关对象,避免误伤。
|
||||
"""
|
||||
op.execute(
|
||||
f"""
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
new_name TEXT;
|
||||
BEGIN
|
||||
FOR r IN
|
||||
SELECT c.conname
|
||||
FROM pg_constraint c
|
||||
JOIN pg_class t ON t.oid = c.conrelid
|
||||
JOIN pg_namespace n ON n.oid = t.relnamespace
|
||||
WHERE n.nspname = 'public'
|
||||
AND t.relname = '{table}'
|
||||
AND c.conname LIKE '{old_prefix}%'
|
||||
LOOP
|
||||
new_name := '{new_prefix}' || substr(r.conname, length('{old_prefix}') + 1);
|
||||
IF new_name <> r.conname AND NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = new_name
|
||||
) THEN
|
||||
EXECUTE format('ALTER TABLE %I RENAME CONSTRAINT %I TO %I', '{table}', r.conname, new_name);
|
||||
END IF;
|
||||
END LOOP;
|
||||
|
||||
FOR r IN
|
||||
SELECT i.relname AS idxname
|
||||
FROM pg_class i
|
||||
JOIN pg_index x ON x.indexrelid = i.oid
|
||||
JOIN pg_class t ON t.oid = x.indrelid
|
||||
JOIN pg_namespace n ON n.oid = t.relnamespace
|
||||
WHERE n.nspname = 'public'
|
||||
AND t.relname = '{table}'
|
||||
AND i.relname LIKE '{old_prefix}%'
|
||||
AND NOT x.indisprimary
|
||||
LOOP
|
||||
new_name := '{new_prefix}' || substr(r.idxname, length('{old_prefix}') + 1);
|
||||
IF new_name <> r.idxname AND NOT EXISTS (
|
||||
SELECT 1 FROM pg_class WHERE relname = new_name
|
||||
) THEN
|
||||
EXECUTE format('ALTER INDEX IF EXISTS %I RENAME TO %I', r.idxname, new_name);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""按蓝图对齐 Notice/OT 表层;创建缺失聚合表。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
|
||||
# [STEP 1] 幂等:已到目标态则跳过 rename
|
||||
if 'shipping_notices' in tables and 'shipping_tasks' not in tables:
|
||||
pass
|
||||
else:
|
||||
for old, new in _TABLE_RENAMES:
|
||||
if old in tables and new not in tables:
|
||||
_rename_table_and_pkey(old, new)
|
||||
# 约束/索引前缀尽量对齐新表名
|
||||
old_prefix = old.replace('shipping_', 'shipping_').rstrip('s')
|
||||
# 使用完整旧表名前缀更稳
|
||||
_bulk_rename_prefixed_objects(new, f'{old}_', f'{new}_')
|
||||
_bulk_rename_prefixed_objects(new, f'ix_{old}_', f'ix_{new}_')
|
||||
_bulk_rename_prefixed_objects(new, f'uq_{old}_', f'uq_{new}_')
|
||||
_bulk_rename_prefixed_objects(new, f'ck_{old}_', f'ck_{new}_')
|
||||
_bulk_rename_prefixed_objects(new, f'fk_{old}_', f'fk_{new}_')
|
||||
|
||||
# shipping_tasks 常用 ix_/uq_/fk_ 前缀不含完整表名时的补充
|
||||
if 'shipping_notices' in set(sa.inspect(op.get_bind()).get_table_names()):
|
||||
for old, new in [
|
||||
('ix_shipping_tasks_', 'ix_shipping_notices_'),
|
||||
('uq_shipping_tasks_', 'uq_shipping_notices_'),
|
||||
('fk_shipping_tasks_', 'fk_shipping_notices_'),
|
||||
]:
|
||||
_bulk_rename_prefixed_objects('shipping_notices', old, new)
|
||||
|
||||
# [STEP 2] shipping_order_tasks(OT 聚合根)
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if 'shipping_order_tasks' not in tables:
|
||||
op.create_table(
|
||||
'shipping_order_tasks',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('task_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),
|
||||
sa.Column('owner_agent_id', sa.Integer(), sa.ForeignKey('agents.id'), nullable=True),
|
||||
sa.Column('conversation_id', sa.String(length=100), nullable=True),
|
||||
sa.Column('submission_id', sa.Integer(), sa.ForeignKey('shipping_order_submissions.id'), nullable=True),
|
||||
sa.Column('intake_id', sa.Integer(), sa.ForeignKey('shipping_order_intakes.id'), nullable=True),
|
||||
sa.Column('candidate_id', sa.Integer(), sa.ForeignKey('shipping_order_candidates.id'), nullable=True),
|
||||
sa.Column(
|
||||
'extraction_run_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_extraction_runs.id'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('shipping_notice_id', sa.Integer(), sa.ForeignKey('shipping_notices.id'), nullable=True),
|
||||
sa.Column('source_type', sa.String(length=32), nullable=True),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='processing'),
|
||||
sa.Column('stage', sa.String(length=64), nullable=True),
|
||||
sa.Column('progress_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('error_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
|
||||
sa.Column('completed_at', sa.DateTime(), nullable=True),
|
||||
sa.UniqueConstraint('task_no', name='uq_shipping_order_tasks_task_no'),
|
||||
sa.CheckConstraint(
|
||||
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
|
||||
name='ck_shipping_order_tasks_source_type',
|
||||
),
|
||||
)
|
||||
op.create_index('ix_shipping_order_tasks_user_created', 'shipping_order_tasks', ['user_id', 'created_at'])
|
||||
op.create_index('ix_shipping_order_tasks_conversation', 'shipping_order_tasks', ['conversation_id'])
|
||||
op.create_index('ix_shipping_order_tasks_status', 'shipping_order_tasks', ['status'])
|
||||
op.create_index('ix_shipping_order_tasks_extraction_run_id', 'shipping_order_tasks', ['extraction_run_id'])
|
||||
op.create_index('ix_shipping_order_tasks_shipping_notice_id', 'shipping_order_tasks', ['shipping_notice_id'])
|
||||
|
||||
# 回填:每个有 user_task_no 的 Run 建一条 OT(同号幂等)
|
||||
op.execute(
|
||||
"""
|
||||
INSERT INTO shipping_order_tasks (
|
||||
task_no, user_id, owner_agent_id, conversation_id, extraction_run_id,
|
||||
status, progress_version, created_at, updated_at
|
||||
)
|
||||
SELECT DISTINCT ON (r.user_task_no)
|
||||
r.user_task_no,
|
||||
r.user_id,
|
||||
r.owner_agent_id,
|
||||
r.conversation_id,
|
||||
r.id,
|
||||
CASE
|
||||
WHEN r.status IN ('completed', 'partially_completed') THEN 'completed'
|
||||
WHEN r.status = 'failed' THEN 'failed'
|
||||
WHEN r.status = 'cancelled' THEN 'cancelled'
|
||||
WHEN r.status = 'review_required' THEN 'waiting_review'
|
||||
ELSE 'processing'
|
||||
END,
|
||||
COALESCE(r.progress_version, 1),
|
||||
COALESCE(r.created_at, CURRENT_TIMESTAMP),
|
||||
COALESCE(r.updated_at, CURRENT_TIMESTAMP)
|
||||
FROM shipping_order_extraction_runs r
|
||||
WHERE r.user_task_no IS NOT NULL
|
||||
AND r.user_task_no <> ''
|
||||
ORDER BY r.user_task_no, r.id DESC
|
||||
ON CONFLICT (task_no) DO NOTHING
|
||||
"""
|
||||
)
|
||||
|
||||
# [STEP 3] Candidate 证据关系表
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if 'shipping_order_candidate_evidences' not in tables:
|
||||
op.create_table(
|
||||
'shipping_order_candidate_evidences',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
'candidate_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_candidates.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
'document_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_documents.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('evidence_role', sa.String(length=32), nullable=False),
|
||||
sa.Column('evidence_kind', sa.String(length=32), nullable=False),
|
||||
sa.Column('is_primary', sa.Boolean(), nullable=False, server_default=sa.text('false')),
|
||||
sa.Column('field_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('value_hash', sa.String(length=64), nullable=True),
|
||||
sa.Column('payload_json', sa.JSON(), nullable=True),
|
||||
sa.Column('decision_rule_version', sa.String(length=64), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
|
||||
sa.CheckConstraint(
|
||||
"evidence_role IN ('primary_pdf', 'auxiliary', 'conflict', 'context')",
|
||||
name='ck_shipping_order_candidate_evidences_role',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"evidence_kind IN ('pdf', 'email_body', 'excel', 'word', 'image', 'ocr', 'model', 'other')",
|
||||
name='ck_shipping_order_candidate_evidences_kind',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_candidate_evidences_candidate',
|
||||
'shipping_order_candidate_evidences',
|
||||
['candidate_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_candidate_evidences_document',
|
||||
'shipping_order_candidate_evidences',
|
||||
['document_id'],
|
||||
)
|
||||
|
||||
# [STEP 4] Notice 挂回 OT:shipping_notices 增加 order_task_id(若尚无)
|
||||
notice_cols = {
|
||||
c['name'] for c in sa.inspect(op.get_bind()).get_columns('shipping_notices')
|
||||
} if 'shipping_notices' in set(sa.inspect(op.get_bind()).get_table_names()) else set()
|
||||
if 'shipping_notices' in set(sa.inspect(op.get_bind()).get_table_names()) and 'order_task_id' not in notice_cols:
|
||||
op.add_column(
|
||||
'shipping_notices',
|
||||
sa.Column('order_task_id', sa.Integer(), sa.ForeignKey('shipping_order_tasks.id'), nullable=True),
|
||||
)
|
||||
op.create_index('ix_shipping_notices_order_task_id', 'shipping_notices', ['order_task_id'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""对称回滚:删新表/列,再 rename 回旧表名。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
|
||||
if 'shipping_notices' in tables:
|
||||
cols = {c['name'] for c in sa.inspect(op.get_bind()).get_columns('shipping_notices')}
|
||||
if 'order_task_id' in cols:
|
||||
op.drop_index('ix_shipping_notices_order_task_id', table_name='shipping_notices')
|
||||
op.drop_column('shipping_notices', 'order_task_id')
|
||||
|
||||
if 'shipping_order_candidate_evidences' in tables:
|
||||
op.drop_table('shipping_order_candidate_evidences')
|
||||
|
||||
if 'shipping_order_tasks' in tables:
|
||||
op.drop_table('shipping_order_tasks')
|
||||
|
||||
# 逆序回滚 rename
|
||||
for old, new in reversed(_TABLE_RENAMES):
|
||||
current = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if new in current and old not in current:
|
||||
_bulk_rename_prefixed_objects(new, f'{new}_', f'{old}_')
|
||||
_bulk_rename_prefixed_objects(new, f'ix_{new}_', f'ix_{old}_')
|
||||
_bulk_rename_prefixed_objects(new, f'uq_{new}_', f'uq_{old}_')
|
||||
_bulk_rename_prefixed_objects(new, f'ck_{new}_', f'ck_{old}_')
|
||||
_bulk_rename_prefixed_objects(new, f'fk_{new}_', f'fk_{old}_')
|
||||
if new == 'shipping_notices':
|
||||
_bulk_rename_prefixed_objects(new, 'ix_shipping_notices_', 'ix_shipping_tasks_')
|
||||
_bulk_rename_prefixed_objects(new, 'uq_shipping_notices_', 'uq_shipping_tasks_')
|
||||
_bulk_rename_prefixed_objects(new, 'fk_shipping_notices_', 'fk_shipping_tasks_')
|
||||
_rename_constraint_if_exists(new, f'{new}_pkey', f'{old}_pkey')
|
||||
_rename_index_if_exists(f'{new}_pkey', f'{old}_pkey')
|
||||
op.rename_table(new, old)
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
"""
|
||||
migrations/versions/co6c7d8e9f0a_add_notice_lines_and_order_document_versions.py
|
||||
|
||||
用途:新建 shipping_notice_lines 与 shipping_order_document_versions(蓝图 §六 剩余实体)。
|
||||
依赖:alembic.op;接在 co5b6c7d8e9f 之后。
|
||||
逻辑:建表;从既有 Snapshot 行回填 Notice 行;从 shipping_order_tasks+runs 回填文档版本。
|
||||
|
||||
Revision ID: co6c7d8e9f0a
|
||||
Revises: co5b6c7d8e9f
|
||||
Create Date: 2026-08-05 00:40:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'co6c7d8e9f0a'
|
||||
down_revision = 'co5b6c7d8e9f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 Notice 行表与 OT 文档版本表并做最小回填。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
|
||||
if 'shipping_notice_lines' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_lines',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('notice_id', sa.Integer(), sa.ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False),
|
||||
sa.Column(
|
||||
'snapshot_line_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_snapshot_lines.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('position', sa.Integer(), nullable=False),
|
||||
sa.Column('line_key', sa.String(length=128), nullable=True),
|
||||
sa.Column('part_number', sa.String(length=255), nullable=True),
|
||||
sa.Column('reservation_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('required_qty', sa.Numeric(24, 8), nullable=True),
|
||||
sa.Column('field_values_json', sa.JSON(), nullable=False, server_default=sa.text("'{}'::json")),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
|
||||
sa.UniqueConstraint('notice_id', 'position', name='uq_shipping_notice_lines_position'),
|
||||
)
|
||||
op.create_index('ix_shipping_notice_lines_notice_id', 'shipping_notice_lines', ['notice_id'])
|
||||
op.create_index('ix_shipping_notice_lines_snapshot_line_id', 'shipping_notice_lines', ['snapshot_line_id'])
|
||||
|
||||
# 回填:每个 Snapshot 行投影到对应 Notice
|
||||
op.execute(
|
||||
"""
|
||||
INSERT INTO shipping_notice_lines (
|
||||
notice_id, snapshot_line_id, position, line_key, part_number,
|
||||
reservation_id, required_qty, field_values_json, created_at
|
||||
)
|
||||
SELECT
|
||||
s.task_id,
|
||||
l.id,
|
||||
l.position,
|
||||
l.line_no,
|
||||
l.part_number,
|
||||
l.reservation_id,
|
||||
l.qty,
|
||||
COALESCE(l.field_values_json, '{}'::json),
|
||||
COALESCE(s.created_at, CURRENT_TIMESTAMP)
|
||||
FROM shipping_order_snapshot_lines l
|
||||
JOIN shipping_order_snapshots s ON s.id = l.snapshot_id
|
||||
ON CONFLICT (notice_id, position) DO NOTHING
|
||||
"""
|
||||
)
|
||||
|
||||
if 'shipping_order_document_versions' not in tables:
|
||||
op.create_table(
|
||||
'shipping_order_document_versions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
'order_task_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column('version', sa.Integer(), nullable=False),
|
||||
sa.Column(
|
||||
'extraction_run_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_extraction_runs.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('content_fingerprint', sa.String(length=64), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
|
||||
sa.UniqueConstraint(
|
||||
'order_task_id', 'version', name='uq_shipping_order_document_versions_task_version',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_document_versions_run',
|
||||
'shipping_order_document_versions',
|
||||
['extraction_run_id'],
|
||||
)
|
||||
# 每个 OT 至少版本 1,挂当前 extraction_run_id
|
||||
op.execute(
|
||||
"""
|
||||
INSERT INTO shipping_order_document_versions (
|
||||
order_task_id, version, extraction_run_id, created_at
|
||||
)
|
||||
SELECT t.id, 1, t.extraction_run_id, COALESCE(t.created_at, CURRENT_TIMESTAMP)
|
||||
FROM shipping_order_tasks t
|
||||
ON CONFLICT (order_task_id, version) DO NOTHING
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除本迁移新建的两张表。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if 'shipping_order_document_versions' in tables:
|
||||
op.drop_table('shipping_order_document_versions')
|
||||
if 'shipping_notice_lines' in tables:
|
||||
op.drop_table('shipping_notice_lines')
|
||||
@@ -0,0 +1,145 @@
|
||||
"""
|
||||
migrations/versions/co7d8e9f0a1b_rename_extraction_to_processing_tables.py
|
||||
|
||||
用途:将建单前 Processing Run 相关表从 extraction_* 物理 rename 为 processing_* /
|
||||
shipping_order_route_decisions,对齐蓝图 §六。
|
||||
依赖:alembic.op;接在 co6c7d8e9f0a 之后。
|
||||
逻辑:RENAME 五张表并批量对齐约束/索引前缀;不改 extraction_submissions /
|
||||
progress_events / extractions(订单结果)/ quality_*。
|
||||
|
||||
Revision ID: co7d8e9f0a1b
|
||||
Revises: co6c7d8e9f0a
|
||||
Create Date: 2026-08-05 00:45:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'co7d8e9f0a1b'
|
||||
down_revision = 'co6c7d8e9f0a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
# (old_table, new_table)
|
||||
_TABLE_RENAMES: list[tuple[str, str]] = [
|
||||
('shipping_order_extraction_runs', 'shipping_order_processing_runs'),
|
||||
('shipping_order_extraction_run_intakes', 'shipping_order_processing_run_intakes'),
|
||||
('shipping_order_extraction_plans', 'shipping_order_processing_plans'),
|
||||
('shipping_order_extraction_units', 'shipping_order_processing_units'),
|
||||
('shipping_order_extraction_route_decisions', 'shipping_order_route_decisions'),
|
||||
]
|
||||
|
||||
|
||||
def _rename_constraint_if_exists(table: str, old: str, new: str) -> None:
|
||||
"""若旧约束存在则改名。"""
|
||||
op.execute(
|
||||
f"""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = '{old}') THEN
|
||||
ALTER TABLE {table} RENAME CONSTRAINT {old} TO {new};
|
||||
END IF;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def _rename_index_if_exists(old: str, new: str) -> None:
|
||||
"""若旧索引存在则改名。"""
|
||||
op.execute(sa.text(f'ALTER INDEX IF EXISTS {old} RENAME TO {new}'))
|
||||
|
||||
|
||||
def _rename_table_and_pkey(old_table: str, new_table: str) -> None:
|
||||
"""重命名表及其主键。"""
|
||||
op.rename_table(old_table, new_table)
|
||||
_rename_constraint_if_exists(new_table, f'{old_table}_pkey', f'{new_table}_pkey')
|
||||
_rename_index_if_exists(f'{old_table}_pkey', f'{new_table}_pkey')
|
||||
|
||||
|
||||
def _bulk_rename_prefixed_objects(table: str, old_prefix: str, new_prefix: str) -> None:
|
||||
"""将本表上以旧前缀开头的约束/索引改为新前缀。"""
|
||||
op.execute(
|
||||
f"""
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
new_name TEXT;
|
||||
BEGIN
|
||||
FOR r IN
|
||||
SELECT c.conname
|
||||
FROM pg_constraint c
|
||||
JOIN pg_class t ON t.oid = c.conrelid
|
||||
JOIN pg_namespace n ON n.oid = t.relnamespace
|
||||
WHERE n.nspname = 'public'
|
||||
AND t.relname = '{table}'
|
||||
AND c.conname LIKE '{old_prefix}%'
|
||||
LOOP
|
||||
new_name := '{new_prefix}' || substr(r.conname, length('{old_prefix}') + 1);
|
||||
IF new_name <> r.conname AND NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = new_name
|
||||
) THEN
|
||||
EXECUTE format('ALTER TABLE %I RENAME CONSTRAINT %I TO %I', '{table}', r.conname, new_name);
|
||||
END IF;
|
||||
END LOOP;
|
||||
|
||||
FOR r IN
|
||||
SELECT i.relname AS idxname
|
||||
FROM pg_class i
|
||||
JOIN pg_index x ON x.indexrelid = i.oid
|
||||
JOIN pg_class t ON t.oid = x.indrelid
|
||||
JOIN pg_namespace n ON n.oid = t.relnamespace
|
||||
WHERE n.nspname = 'public'
|
||||
AND t.relname = '{table}'
|
||||
AND i.relname LIKE '{old_prefix}%'
|
||||
AND NOT x.indisprimary
|
||||
LOOP
|
||||
new_name := '{new_prefix}' || substr(r.idxname, length('{old_prefix}') + 1);
|
||||
IF new_name <> r.idxname AND NOT EXISTS (
|
||||
SELECT 1 FROM pg_class WHERE relname = new_name
|
||||
) THEN
|
||||
EXECUTE format('ALTER INDEX IF EXISTS %I RENAME TO %I', r.idxname, new_name);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""extraction_* → processing_* / route_decisions。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if 'shipping_order_processing_runs' in tables and 'shipping_order_extraction_runs' not in tables:
|
||||
return
|
||||
|
||||
for old, new in _TABLE_RENAMES:
|
||||
current = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if old not in current:
|
||||
continue
|
||||
if new in current:
|
||||
continue
|
||||
_rename_table_and_pkey(old, new)
|
||||
_bulk_rename_prefixed_objects(new, f'{old}_', f'{new}_')
|
||||
_bulk_rename_prefixed_objects(new, f'ix_{old}_', f'ix_{new}_')
|
||||
_bulk_rename_prefixed_objects(new, f'uq_{old}_', f'uq_{new}_')
|
||||
_bulk_rename_prefixed_objects(new, f'ck_{old}_', f'ck_{new}_')
|
||||
_bulk_rename_prefixed_objects(new, f'fk_{old}_', f'fk_{new}_')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""对称回滚为 extraction_* 表名。"""
|
||||
for old, new in reversed(_TABLE_RENAMES):
|
||||
current = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if new not in current or old in current:
|
||||
continue
|
||||
_bulk_rename_prefixed_objects(new, f'{new}_', f'{old}_')
|
||||
_bulk_rename_prefixed_objects(new, f'ix_{new}_', f'ix_{old}_')
|
||||
_bulk_rename_prefixed_objects(new, f'uq_{new}_', f'uq_{old}_')
|
||||
_bulk_rename_prefixed_objects(new, f'ck_{new}_', f'ck_{old}_')
|
||||
_bulk_rename_prefixed_objects(new, f'fk_{new}_', f'fk_{old}_')
|
||||
_rename_constraint_if_exists(new, f'{new}_pkey', f'{old}_pkey')
|
||||
_rename_index_if_exists(f'{new}_pkey', f'{old}_pkey')
|
||||
op.rename_table(new, old)
|
||||
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
migrations/versions/co8e9f0a1b2c_drop_legacy_workflow_and_batch_tables.py
|
||||
|
||||
用途:无历史数据前提下,物理 DROP 旧 Workflow 台账与 shipping_batches,
|
||||
并解除 Process Gate 对 Workflow Item/Version 的硬外键。
|
||||
依赖:alembic.op;接在 co7d8e9f0a1b 之后。
|
||||
逻辑:先拆 process_executions → workflow_* FK 并置空列;再按叶→根 DROP
|
||||
workflow_events / item_versions / items / workflows;最后卸 batch 入站 FK
|
||||
与 batch_id 列后 DROP shipping_batches。审计表仅软引用,不改结构。
|
||||
|
||||
Revision ID: co8e9f0a1b2c
|
||||
Revises: co7d8e9f0a1b
|
||||
Create Date: 2026-08-05 08:20:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'co8e9f0a1b2c'
|
||||
down_revision = 'co7d8e9f0a1b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _drop_fk_if_exists(table: str, fk_name: str) -> None:
|
||||
"""尽力删除外键;不存在则忽略(兼容 SQLite/PG 与历史库差异)。"""
|
||||
try:
|
||||
op.drop_constraint(fk_name, table, type_='foreignkey')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _drop_constraint_if_exists(table: str, name: str, type_: str = 'unique') -> None:
|
||||
"""尽力删除约束。"""
|
||||
try:
|
||||
op.drop_constraint(name, table, type_=type_)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _drop_column_if_exists(table: str, column: str) -> None:
|
||||
"""尽力删除列。"""
|
||||
try:
|
||||
op.drop_column(table, column)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _drop_table_if_exists(table: str) -> None:
|
||||
"""尽力删除表。"""
|
||||
try:
|
||||
op.drop_table(table)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
物理清理旧 Workflow / Batch 表。
|
||||
|
||||
核心逻辑:无历史数据,直接 DROP;Process Gate 保留但不再强制挂 Workflow。
|
||||
"""
|
||||
# [STEP 1] 解除 Process Gate → Workflow 硬 FK,列改为可空软引用后删除列。
|
||||
_drop_constraint_if_exists(
|
||||
'shipping_process_executions',
|
||||
'uq_shipping_process_executions_workflow_item_version',
|
||||
type_='unique',
|
||||
)
|
||||
for fk in (
|
||||
'shipping_process_executions_workflow_item_id_fkey',
|
||||
'shipping_process_executions_workflow_item_version_id_fkey',
|
||||
'fk_shipping_process_executions_workflow_item_id_shipping_notice_workflow_items',
|
||||
'fk_shipping_process_executions_workflow_item_version_id_shipping_notice_workflow_item_versions',
|
||||
):
|
||||
_drop_fk_if_exists('shipping_process_executions', fk)
|
||||
|
||||
# PostgreSQL / 部分库可能用自动命名;再按 inspector 扫一遍。
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'shipping_process_executions' in inspector.get_table_names():
|
||||
for fk in inspector.get_foreign_keys('shipping_process_executions'):
|
||||
referred = fk.get('referred_table') or ''
|
||||
if referred in {
|
||||
'shipping_notice_workflow_items',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
}:
|
||||
name = fk.get('name')
|
||||
if name:
|
||||
_drop_fk_if_exists('shipping_process_executions', name)
|
||||
_drop_column_if_exists('shipping_process_executions', 'workflow_item_id')
|
||||
_drop_column_if_exists('shipping_process_executions', 'workflow_item_version_id')
|
||||
|
||||
# [STEP 2] Workflow 台账叶→根 DROP。
|
||||
for table in (
|
||||
'shipping_notice_workflow_events',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
'shipping_notice_workflow_items',
|
||||
'shipping_notice_workflows',
|
||||
):
|
||||
_drop_table_if_exists(table)
|
||||
|
||||
# [STEP 3] Batch 入站 FK / 列清理后 DROP shipping_batches。
|
||||
batch_inbound = (
|
||||
('shipping_notices', 'batch_id'),
|
||||
('shipping_inventory_files', 'batch_id'),
|
||||
('shipping_order_intakes', 'consumed_batch_id'),
|
||||
('shipping_temporary_inventory_sessions', 'batch_id'),
|
||||
('shipping_notice_export_artifacts', 'batch_id'),
|
||||
)
|
||||
for table, column in batch_inbound:
|
||||
if table not in inspector.get_table_names():
|
||||
# refresh inspector after drops
|
||||
inspector = sa.inspect(bind)
|
||||
if table not in inspector.get_table_names():
|
||||
continue
|
||||
for fk in inspector.get_foreign_keys(table):
|
||||
referred = fk.get('referred_table') or ''
|
||||
cols = set(fk.get('constrained_columns') or [])
|
||||
if referred == 'shipping_batches' or column in cols:
|
||||
name = fk.get('name')
|
||||
if name:
|
||||
_drop_fk_if_exists(table, name)
|
||||
_drop_column_if_exists(table, column)
|
||||
|
||||
# shipping_batches → shipping_notices 焦点任务 FK
|
||||
inspector = sa.inspect(bind)
|
||||
if 'shipping_batches' in inspector.get_table_names():
|
||||
for fk in inspector.get_foreign_keys('shipping_batches'):
|
||||
name = fk.get('name')
|
||||
if name:
|
||||
_drop_fk_if_exists('shipping_batches', name)
|
||||
_drop_table_if_exists('shipping_batches')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""
|
||||
不重建已删除的历史台账表。
|
||||
|
||||
核心逻辑:无历史兼容要求;downgrade 仅提示不可逆。
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
'co8e9f0a1b2c drops legacy workflow/batch tables irreversibly; restore from backup if needed'
|
||||
)
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
migrations/versions/co9f0a1b2c3d_nullable_run_user_task_no_and_ot_candidate_unique.py
|
||||
|
||||
用途:BE-01/BE-05 — Processing Run.user_task_no 延迟至 Candidate/OT 分配(nullable);
|
||||
shipping_order_tasks.candidate_id 部分唯一(一 Candidate 一 OT)。
|
||||
依赖:alembic.op;接在 co8e9f0a1b2c 之后。
|
||||
逻辑:ALTER shipping_order_processing_runs.user_task_no DROP NOT NULL;
|
||||
CREATE partial unique index on shipping_order_tasks.candidate_id WHERE NOT NULL。
|
||||
|
||||
Revision ID: co9f0a1b2c3d
|
||||
Revises: co8e9f0a1b2c
|
||||
Create Date: 2026-08-05 12:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'co9f0a1b2c3d'
|
||||
down_revision = 'co8e9f0a1b2c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_CANDIDATE_WHERE = sa.text('candidate_id IS NOT NULL')
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""允许 Run.user_task_no 为空;为 OT.candidate_id 建部分唯一索引。"""
|
||||
with op.batch_alter_table('shipping_order_processing_runs', schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
'user_task_no',
|
||||
existing_type=sa.String(length=64),
|
||||
nullable=True,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'uq_shipping_order_tasks_candidate_id',
|
||||
'shipping_order_tasks',
|
||||
['candidate_id'],
|
||||
unique=True,
|
||||
postgresql_where=_CANDIDATE_WHERE,
|
||||
sqlite_where=_CANDIDATE_WHERE,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚:删除部分唯一索引;user_task_no 恢复 NOT NULL(空值先回填 run_no 派生 OT)。"""
|
||||
op.drop_index('uq_shipping_order_tasks_candidate_id', table_name='shipping_order_tasks')
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE shipping_order_processing_runs
|
||||
SET user_task_no = 'OT-' || SUBSTRING(run_no FROM 6)
|
||||
WHERE user_task_no IS NULL OR TRIM(user_task_no) = ''
|
||||
"""
|
||||
)
|
||||
|
||||
with op.batch_alter_table('shipping_order_processing_runs', schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
'user_task_no',
|
||||
existing_type=sa.String(length=64),
|
||||
nullable=False,
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
migrations/versions/cp0a1b2c3d4e_add_upload_attempt_success_evidence_json.py
|
||||
|
||||
用途:BE-05 — ShippingUploadAttempt 持久化 RPA 绿色 DOM 成功证据 JSON。
|
||||
依赖:alembic.op;接在 co9f0a1b2c3d 之后。
|
||||
逻辑:ALTER shipping_notice_upload_attempts ADD success_evidence_json JSON NULL。
|
||||
|
||||
Revision ID: cp0a1b2c3d4e
|
||||
Revises: co9f0a1b2c3d
|
||||
Create Date: 2026-08-05 13:20:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cp0a1b2c3d4e'
|
||||
down_revision = 'co9f0a1b2c3d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为 upload attempt 增加 success_evidence_json。"""
|
||||
with op.batch_alter_table('shipping_notice_upload_attempts', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('success_evidence_json', sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除 success_evidence_json 列。"""
|
||||
with op.batch_alter_table('shipping_notice_upload_attempts', schema=None) as batch_op:
|
||||
batch_op.drop_column('success_evidence_json')
|
||||
Reference in new issue
Block a user