feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验
- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全 - 引入审计事件的哈希链校验机制,支持数据完整性验证 - 增强订单抽取与审计功能,支持敏感快照的访问控制 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
95cdfe66b0
commit
d0fe084999
225 files changed
+25923
-6653
No files matched your search
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
migrations/versions/4e7a1c9b2d3f_align_shipping_order_line_contract.py
|
||||
|
||||
用途:允许 Header/Line 同名 Reservation 字段资产,并补齐订单级 Reservation 标准资产。
|
||||
依赖:shipping_order_fields、字段资产注册表。
|
||||
逻辑:唯一键由 field_code 收敛为 (field_code, scope),使行级值可安全覆盖订单头值;
|
||||
仅补齐字段目录,不改历史 Schema 版本或履约数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '4e7a1c9b2d3f'
|
||||
down_revision = '3d6e8f0a1b2c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""替换字段资产唯一键,并幂等补齐 Header reservation_id。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
constraints = {item.get('name') for item in inspector.get_unique_constraints('shipping_order_fields')}
|
||||
if 'uq_shipping_order_fields_field_code' in constraints:
|
||||
with op.batch_alter_table('shipping_order_fields') as batch:
|
||||
batch.drop_constraint('uq_shipping_order_fields_field_code', type_='unique')
|
||||
inspector = sa.inspect(bind)
|
||||
constraints = {item.get('name') for item in inspector.get_unique_constraints('shipping_order_fields')}
|
||||
if 'uq_shipping_order_fields_code_scope' not in constraints:
|
||||
with op.batch_alter_table('shipping_order_fields') as batch:
|
||||
batch.create_unique_constraint('uq_shipping_order_fields_code_scope', ['field_code', 'scope'])
|
||||
|
||||
exists = bind.execute(sa.text(
|
||||
"SELECT 1 FROM shipping_order_fields WHERE field_code = 'reservation_id' AND scope = 'header'"
|
||||
)).scalar()
|
||||
if not exists:
|
||||
now = datetime.utcnow()
|
||||
bind.execute(sa.text(
|
||||
"""INSERT INTO shipping_order_fields
|
||||
(id, field_code, scope, value_type, field_category, collection_mode, asset_kind,
|
||||
storage_mode, storage_column, semantic_description, display_name_default,
|
||||
fulfillment_role, display_sequence, status, published_once, created_at, updated_at)
|
||||
VALUES (:id, 'reservation_id', 'header', 'string', 'order_header', 'llm_extraction',
|
||||
'system_standard', 'json_only', NULL, :semantic, :display_name, NULL,
|
||||
:sequence, 'active', false, :now, :now)"""
|
||||
), {
|
||||
'id': str(uuid.uuid4()),
|
||||
'semantic': '可选的订单级库存占用/预约单标识;明细可覆盖',
|
||||
'display_name': '预约单号',
|
||||
'sequence': 24, 'now': now,
|
||||
})
|
||||
bind.execute(sa.text(
|
||||
"""UPDATE shipping_order_fields
|
||||
SET display_name_default = :display_name, semantic_description = :semantic, updated_at = :now
|
||||
WHERE field_code = 'line_no' AND scope = 'line'"""
|
||||
), {
|
||||
'display_name': '内部项次',
|
||||
'semantic': (
|
||||
'内部业务项次;可识别、可由 Schema 派生规则补齐、冻结前可人工覆盖;'
|
||||
'仅接受 1–6 位数字并保留前导零;与 Excel 导出行序号 export_sequence 无关'
|
||||
),
|
||||
'now': datetime.utcnow(),
|
||||
})
|
||||
bind.execute(sa.text(
|
||||
"""UPDATE shipping_order_fields
|
||||
SET semantic_description = :semantic, updated_at = :now
|
||||
WHERE field_code = 'customer_po_line_no' AND scope = 'line'"""
|
||||
), {
|
||||
'semantic': '客户采购订单原始 Item No./LN/Line#;必须按字符串保留前导零;识别/复核后永久保留原始事实',
|
||||
'now': datetime.utcnow(),
|
||||
})
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""仅在未采用 Header Reservation 时允许恢复旧的单编码唯一键。"""
|
||||
bind = op.get_bind()
|
||||
definition_column = 'definition_json::text' if bind.dialect.name == 'postgresql' else 'definition_json'
|
||||
used = bind.execute(sa.text(
|
||||
f"SELECT 1 FROM shipping_order_schema_versions WHERE {definition_column} LIKE '%\"reservation_id\"%' LIMIT 1"
|
||||
)).scalar()
|
||||
if used:
|
||||
raise RuntimeError('Cannot downgrade while reservation_id is present in Schema history')
|
||||
bind.execute(sa.text("DELETE FROM shipping_order_fields WHERE field_code = 'reservation_id' AND scope = 'header'"))
|
||||
with op.batch_alter_table('shipping_order_fields') as batch:
|
||||
batch.drop_constraint('uq_shipping_order_fields_code_scope', type_='unique')
|
||||
batch.create_unique_constraint('uq_shipping_order_fields_field_code', ['field_code'])
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
migrations/versions/5f8b2d4e6a1c_restore_shipping_context_field_assets.py
|
||||
|
||||
用途:恢复邮件确定性上下文字段资产约束与种子(sender_email / sender_domain)。
|
||||
依赖:shipping_order_fields、字段资产治理迁移 1b2c3d4e5f6a / 4e7a1c9b2d3f。
|
||||
逻辑:放宽 field_category / collection_mode CHECK;幂等插入两条 general_context 资产。
|
||||
create_extension 仍禁止同名编码,仅种子与 ensure_context_assets_seeded 可写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '5f8b2d4e6a1c'
|
||||
down_revision = '4e7a1c9b2d3f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""放宽字段分类/采集模式约束,并幂等补齐上下文字段资产。"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
# SQLite 测试库多由 metadata.create_all 建表,约束以 ORM 模型为准;此处只对 PG 放宽 CHECK。
|
||||
if dialect != 'sqlite':
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_category'))
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_collection_mode'))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_category "
|
||||
"CHECK (field_category IN ('general_context', 'order_header', 'order_line'))"
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_collection_mode "
|
||||
"CHECK (collection_mode IN ('deterministic_context', 'llm_extraction'))"
|
||||
))
|
||||
|
||||
now = datetime.utcnow()
|
||||
for code, display_name, semantic in (
|
||||
(
|
||||
'sender_email',
|
||||
'发件人邮箱',
|
||||
'从原始 EML From 确定性采集的发件人邮箱;不可经扩展资产 API 创建。',
|
||||
),
|
||||
(
|
||||
'sender_domain',
|
||||
'发件人域名',
|
||||
'从原始 EML From 确定性采集的发件人域名;不可经扩展资产 API 创建。',
|
||||
),
|
||||
):
|
||||
exists = bind.execute(sa.text(
|
||||
"SELECT 1 FROM shipping_order_fields WHERE field_code = :code AND scope = 'header'"
|
||||
), {'code': code}).first()
|
||||
if exists:
|
||||
bind.execute(sa.text(
|
||||
"UPDATE shipping_order_fields SET "
|
||||
"field_category = 'general_context', collection_mode = 'deterministic_context', "
|
||||
"storage_mode = 'json_only', storage_column = NULL, status = 'active', "
|
||||
"display_name_default = COALESCE(NULLIF(display_name_default, ''), :display_name), "
|
||||
"semantic_description = COALESCE(NULLIF(semantic_description, ''), :semantic), "
|
||||
"updated_at = :now "
|
||||
"WHERE field_code = :code AND scope = 'header'"
|
||||
), {
|
||||
'code': code,
|
||||
'display_name': display_name,
|
||||
'semantic': semantic,
|
||||
'now': now,
|
||||
})
|
||||
continue
|
||||
bind.execute(sa.text(
|
||||
"INSERT INTO shipping_order_fields ("
|
||||
"id, field_code, scope, value_type, field_category, collection_mode, "
|
||||
"asset_kind, storage_mode, storage_column, semantic_description, display_name_default, "
|
||||
"fulfillment_role, display_sequence, status, published_once, created_at, updated_at"
|
||||
") VALUES ("
|
||||
":id, :code, 'header', 'string', 'general_context', 'deterministic_context', "
|
||||
"'extension', 'json_only', NULL, :semantic, :display_name, "
|
||||
"NULL, 0, 'active', false, :now, :now)"
|
||||
), {
|
||||
'id': str(uuid.uuid4()),
|
||||
'code': code,
|
||||
'semantic': semantic,
|
||||
'display_name': display_name,
|
||||
'now': now,
|
||||
})
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除上下文字段资产并收紧约束(回滚仅用于开发环境)。"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
bind.execute(sa.text(
|
||||
"DELETE FROM shipping_order_fields WHERE field_code IN ('sender_email', 'sender_domain') "
|
||||
"AND field_category = 'general_context'"
|
||||
))
|
||||
if dialect == 'sqlite':
|
||||
return
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_category'))
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_collection_mode'))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_category "
|
||||
"CHECK (field_category IN ('order_header', 'order_line'))"
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_collection_mode "
|
||||
"CHECK (collection_mode IN ('llm_extraction'))"
|
||||
))
|
||||
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
migrations/versions/6a9c3e5f7b2d_make_shipping_audit_events_permanent.py
|
||||
|
||||
用途:将货代统一审计账本改为全量永久保留。
|
||||
依赖:shipping_audit_events.retention_expires_at。
|
||||
逻辑:把既有行的 retention_expires_at 置空;清理 Job 仅删除仍带到期时间的遗留行(本迁移后应为 0)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '6a9c3e5f7b2d'
|
||||
down_revision = '5f8b2d4e6a1c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""清空全部审计到期时间,使既有与新增事件均永久保留。"""
|
||||
op.execute(sa.text('UPDATE shipping_audit_events SET retention_expires_at = NULL'))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""
|
||||
回滚不恢复历史到期时间(信息已丢弃)。
|
||||
|
||||
新写入若再次启用默认三年策略,由应用层 default_retention_expires_at 决定;
|
||||
本函数仅作空操作,避免伪造错误的到期时间。
|
||||
"""
|
||||
return
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
migrations/versions/7b0d4f6a8c3e_expand_shipping_inventory_source_checks.py
|
||||
|
||||
用途:扩展 shipping_tasks 库存源 status/method 检查约束,对齐 STP 建单冻结与行级匹配写入值。
|
||||
依赖:ck_shipping_tasks_inventory_source_status / ck_shipping_tasks_inventory_source_method(d6e7f8a9b0c1)。
|
||||
逻辑:删除旧 CHECK 后重建,纳入 candidates_frozen 与 stp_* / snapshot_match 等方法;否则确认建单 flush 会 500。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = '7b0d4f6a8c3e'
|
||||
down_revision = '6a9c3e5f7b2d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# 与 STP/库存门禁当前写入值对齐;保留历史 gate 枚举以免存量行无法回写。
|
||||
_STATUS_VALUES = (
|
||||
'resolved',
|
||||
'user_confirmed',
|
||||
'ambiguous',
|
||||
'unresolved',
|
||||
'invalid',
|
||||
'conflicted',
|
||||
'candidates_frozen',
|
||||
)
|
||||
_METHOD_VALUES = (
|
||||
'rule_exact',
|
||||
'rule_combined',
|
||||
'rule',
|
||||
'user_confirmed',
|
||||
'legacy_migrated',
|
||||
'manual',
|
||||
'manual_multi_source_resolve',
|
||||
'snapshot_match',
|
||||
'stp_build_freeze',
|
||||
'stp_line_match',
|
||||
'stp_line_match_multi',
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""重建 status/method CHECK,允许 STP 冻结与行级匹配枚举。"""
|
||||
op.drop_constraint('ck_shipping_tasks_inventory_source_status', 'shipping_tasks', type_='check')
|
||||
op.drop_constraint('ck_shipping_tasks_inventory_source_method', 'shipping_tasks', type_='check')
|
||||
status_list = ', '.join(f"'{item}'" for item in _STATUS_VALUES)
|
||||
method_list = ', '.join(f"'{item}'" for item in _METHOD_VALUES)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_tasks_inventory_source_status',
|
||||
'shipping_tasks',
|
||||
f'inventory_source_status IS NULL OR inventory_source_status IN ({status_list})',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_tasks_inventory_source_method',
|
||||
'shipping_tasks',
|
||||
f'inventory_source_method IS NULL OR inventory_source_method IN ({method_list})',
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复 d6e7f8a9b0c1 时期的窄枚举;若已有 STP 新值行,回滚会失败。"""
|
||||
op.drop_constraint('ck_shipping_tasks_inventory_source_status', 'shipping_tasks', type_='check')
|
||||
op.drop_constraint('ck_shipping_tasks_inventory_source_method', 'shipping_tasks', type_='check')
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_tasks_inventory_source_status',
|
||||
'shipping_tasks',
|
||||
"inventory_source_status IS NULL OR inventory_source_status IN "
|
||||
"('resolved', 'user_confirmed', 'ambiguous', 'unresolved', 'invalid', 'conflicted')",
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_tasks_inventory_source_method',
|
||||
'shipping_tasks',
|
||||
"inventory_source_method IS NULL OR inventory_source_method IN "
|
||||
"('rule_exact', 'rule_combined', 'user_confirmed', 'legacy_migrated', 'manual')",
|
||||
)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
migrations/versions/8c1e5a7b9d0f_shipping_audit_workflow_hash_chain.py
|
||||
|
||||
用途:将 shipping_audit_events 从 session_item 软引用迁移为 Workflow 软引用并增加哈希链字段。
|
||||
依赖:shipping_audit_events(3d6e8f0a1b2c / 2b4c6d8e0f1a 等既有列)。
|
||||
逻辑:删除 session_item_id 及其索引;新增 workflow_* / version_no / actor_display /
|
||||
diff_json / previous_event_hash / event_hash / sensitivity_level 与对应索引。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '8c1e5a7b9d0f'
|
||||
down_revision = '7b0d4f6a8c3e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _columns(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {column['name'] for column in inspector.get_columns(table_name)}
|
||||
|
||||
|
||||
def _indexes(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {index['name'] for index in inspector.get_indexes(table_name)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""追加 Workflow 软引用与哈希链列;移除 session_item_id。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'shipping_audit_events' not in set(inspector.get_table_names()):
|
||||
return
|
||||
|
||||
cols = _columns(inspector, 'shipping_audit_events')
|
||||
indexes = _indexes(inspector, 'shipping_audit_events')
|
||||
|
||||
if 'ix_shipping_audit_events_session_item_created' in indexes:
|
||||
op.drop_index(
|
||||
'ix_shipping_audit_events_session_item_created',
|
||||
table_name='shipping_audit_events',
|
||||
)
|
||||
|
||||
if 'session_item_id' in cols:
|
||||
op.drop_column('shipping_audit_events', 'session_item_id')
|
||||
|
||||
add_specs: list[tuple[str, sa.Column]] = [
|
||||
('workflow_id', sa.Column('workflow_id', sa.String(length=64), nullable=True)),
|
||||
('workflow_item_id', sa.Column('workflow_item_id', sa.String(length=64), nullable=True)),
|
||||
(
|
||||
'workflow_item_version_id',
|
||||
sa.Column('workflow_item_version_id', sa.String(length=64), nullable=True),
|
||||
),
|
||||
('version_no', sa.Column('version_no', sa.Integer(), nullable=True)),
|
||||
('actor_display', sa.Column('actor_display', sa.String(length=128), nullable=True)),
|
||||
('diff_json', sa.Column('diff_json', sa.JSON(), nullable=True)),
|
||||
('previous_event_hash', sa.Column('previous_event_hash', sa.String(length=64), nullable=True)),
|
||||
('event_hash', sa.Column('event_hash', sa.String(length=64), nullable=True)),
|
||||
('sensitivity_level', sa.Column('sensitivity_level', sa.String(length=16), nullable=True)),
|
||||
]
|
||||
cols = _columns(sa.inspect(bind), 'shipping_audit_events')
|
||||
for name, column in add_specs:
|
||||
if name not in cols:
|
||||
op.add_column('shipping_audit_events', column)
|
||||
|
||||
indexes = _indexes(sa.inspect(bind), 'shipping_audit_events')
|
||||
if 'ix_shipping_audit_events_workflow_created' not in indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_workflow_created',
|
||||
'shipping_audit_events',
|
||||
['workflow_id', 'created_at'],
|
||||
)
|
||||
if 'ix_shipping_audit_events_workflow_item_created' not in indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_workflow_item_created',
|
||||
'shipping_audit_events',
|
||||
['workflow_item_id', 'created_at'],
|
||||
)
|
||||
if 'ix_shipping_audit_events_event_hash' not in indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_event_hash',
|
||||
'shipping_audit_events',
|
||||
['event_hash'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚哈希链与 Workflow 列,恢复 session_item_id。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'shipping_audit_events' not in set(inspector.get_table_names()):
|
||||
return
|
||||
|
||||
indexes = _indexes(inspector, 'shipping_audit_events')
|
||||
for index_name in (
|
||||
'ix_shipping_audit_events_event_hash',
|
||||
'ix_shipping_audit_events_workflow_item_created',
|
||||
'ix_shipping_audit_events_workflow_created',
|
||||
):
|
||||
if index_name in indexes:
|
||||
op.drop_index(index_name, table_name='shipping_audit_events')
|
||||
|
||||
cols = _columns(sa.inspect(bind), 'shipping_audit_events')
|
||||
for column_name in (
|
||||
'sensitivity_level',
|
||||
'event_hash',
|
||||
'previous_event_hash',
|
||||
'diff_json',
|
||||
'actor_display',
|
||||
'version_no',
|
||||
'workflow_item_version_id',
|
||||
'workflow_item_id',
|
||||
'workflow_id',
|
||||
):
|
||||
if column_name in cols:
|
||||
op.drop_column('shipping_audit_events', column_name)
|
||||
|
||||
cols = _columns(sa.inspect(bind), 'shipping_audit_events')
|
||||
if 'session_item_id' not in cols:
|
||||
op.add_column(
|
||||
'shipping_audit_events',
|
||||
sa.Column('session_item_id', sa.String(length=64), nullable=True),
|
||||
)
|
||||
indexes = _indexes(sa.inspect(bind), 'shipping_audit_events')
|
||||
if 'ix_shipping_audit_events_session_item_created' not in indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_session_item_created',
|
||||
'shipping_audit_events',
|
||||
['session_item_id', 'created_at'],
|
||||
)
|
||||
+391
@@ -0,0 +1,391 @@
|
||||
"""
|
||||
migrations/versions/9d2f4a6b8c0e_replace_session_work_items_with_workflows.py
|
||||
|
||||
用途:创建 Workflow / Item / Version / Event 四表,并删除旧会话工作项表(不做历史数据迁移)。
|
||||
依赖:users、agents、shipping_notice_documents、shipping_order_extraction_runs、
|
||||
shipping_order_review_cases、shipping_tasks;审计列迁移 8c1e5a7b9d0f。
|
||||
逻辑:若缺则创建 Workflow 四表 → DROP shipping_session_pdf_work_items(若存在,不迁数据);
|
||||
downgrade 仅删除 Workflow 四表(不重建旧会话工作项表)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '9d2f4a6b8c0e'
|
||||
down_revision = '8c1e5a7b9d0f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _tables(inspector: sa.Inspector) -> set[str]:
|
||||
return set(inspector.get_table_names())
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 Workflow 四表(若缺),并直接删除旧会话工作项表(不迁移历史数据)。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
tables = _tables(inspector)
|
||||
|
||||
if 'shipping_notice_workflows' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_workflows',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('workflow_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('conversation_id', sa.String(length=100), nullable=False),
|
||||
sa.Column('owner_user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('owner_agent_id', sa.Integer(), nullable=True),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='open'),
|
||||
sa.Column('current_stage', sa.String(length=64), nullable=False, server_default='queued'),
|
||||
sa.Column('last_activity_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('closed_reason', sa.String(length=64), nullable=True),
|
||||
sa.Column('closed_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('open', 'completed', 'cancelled', 'failed')",
|
||||
name='ck_shipping_notice_workflows_status',
|
||||
),
|
||||
sa.CheckConstraint('lock_version >= 1', name='ck_shipping_notice_workflows_lock_version'),
|
||||
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['owner_agent_id'], ['agents.id']),
|
||||
sa.UniqueConstraint('workflow_no', name='uq_shipping_notice_workflows_no'),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_conversation_id',
|
||||
'shipping_notice_workflows',
|
||||
['conversation_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_owner_user_id',
|
||||
'shipping_notice_workflows',
|
||||
['owner_user_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_owner_agent_id',
|
||||
'shipping_notice_workflows',
|
||||
['owner_agent_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_conversation_status',
|
||||
'shipping_notice_workflows',
|
||||
['conversation_id', 'status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_owner_status',
|
||||
'shipping_notice_workflows',
|
||||
['owner_user_id', 'status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_open_conversation',
|
||||
'shipping_notice_workflows',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text("status = 'open'"),
|
||||
sqlite_where=sa.text("status = 'open'"),
|
||||
)
|
||||
|
||||
tables = _tables(sa.inspect(bind))
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_workflow_items',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('item_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('workflow_id', sa.Integer(), nullable=False),
|
||||
sa.Column('workflow_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('conversation_id', sa.String(length=100), nullable=False),
|
||||
sa.Column('owner_user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('root_document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('current_document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('current_version_id', sa.Integer(), nullable=True),
|
||||
sa.Column('current_version_no', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('current_run_id', sa.Integer(), nullable=True),
|
||||
sa.Column('current_run_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('current_case_id', sa.Integer(), nullable=True),
|
||||
sa.Column('current_case_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('current_task_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('lifecycle_status', sa.String(length=32), nullable=False, server_default='queued'),
|
||||
sa.Column('current_stage', sa.String(length=64), nullable=False, server_default='queued'),
|
||||
sa.Column('closed_reason', sa.String(length=32), nullable=True),
|
||||
sa.Column('closed_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('last_activity_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'excel_ready', 'reparse_failed', 'cancelled', 'failed', 'closed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_items_lifecycle',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"closed_reason IS NULL OR closed_reason IN ("
|
||||
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated', 'failed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_items_closed_reason',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
'lock_version >= 1',
|
||||
name='ck_shipping_notice_workflow_items_lock_version',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
'current_version_no >= 1',
|
||||
name='ck_shipping_notice_workflow_items_version_no',
|
||||
),
|
||||
sa.ForeignKeyConstraint(['workflow_id'], ['shipping_notice_workflows.id']),
|
||||
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['root_document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['current_document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['current_run_id'], ['shipping_order_extraction_runs.id']),
|
||||
sa.ForeignKeyConstraint(['current_case_id'], ['shipping_order_review_cases.id']),
|
||||
sa.UniqueConstraint('item_no', name='uq_shipping_notice_workflow_items_no'),
|
||||
sa.UniqueConstraint(
|
||||
'workflow_id',
|
||||
'root_document_id',
|
||||
name='uq_shipping_notice_workflow_items_workflow_root_doc',
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
'current_case_id',
|
||||
name='uq_shipping_notice_workflow_items_current_case',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_workflow_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['workflow_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_workflow_no',
|
||||
'shipping_notice_workflow_items',
|
||||
['workflow_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_conversation_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_owner_user_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['owner_user_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_root_document_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['root_document_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_current_document_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['current_document_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_current_version_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['current_version_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_current_run_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['current_run_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_workflow_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
['workflow_id', 'lifecycle_status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_conversation_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'lifecycle_status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_owner_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
['owner_user_id', 'lifecycle_status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(
|
||||
"lifecycle_status NOT IN ('closed', 'cancelled', 'excel_ready')"
|
||||
),
|
||||
sqlite_where=sa.text(
|
||||
"lifecycle_status NOT IN ('closed', 'cancelled', 'excel_ready')"
|
||||
),
|
||||
)
|
||||
|
||||
tables = _tables(sa.inspect(bind))
|
||||
if 'shipping_notice_workflow_item_versions' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_workflow_item_versions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('workflow_item_id', sa.Integer(), nullable=False),
|
||||
sa.Column('item_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('workflow_id', sa.Integer(), nullable=False),
|
||||
sa.Column('workflow_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('version_no', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('run_id', sa.Integer(), nullable=True),
|
||||
sa.Column('run_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('case_id', sa.Integer(), nullable=True),
|
||||
sa.Column('case_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('task_id', sa.Integer(), nullable=True),
|
||||
sa.Column('task_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('excel_artifact_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='active'),
|
||||
sa.Column('is_current', sa.Boolean(), nullable=False, server_default=sa.text('true')),
|
||||
sa.Column('is_readonly', sa.Boolean(), nullable=False, server_default=sa.text('false')),
|
||||
sa.Column('superseded_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
'version_no >= 1',
|
||||
name='ck_shipping_notice_workflow_item_versions_no',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('active', 'superseded', 'failed', 'cancelled')",
|
||||
name='ck_shipping_notice_workflow_item_versions_status',
|
||||
),
|
||||
sa.ForeignKeyConstraint(['workflow_item_id'], ['shipping_notice_workflow_items.id']),
|
||||
sa.ForeignKeyConstraint(['workflow_id'], ['shipping_notice_workflows.id']),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['run_id'], ['shipping_order_extraction_runs.id']),
|
||||
sa.ForeignKeyConstraint(['case_id'], ['shipping_order_review_cases.id']),
|
||||
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']),
|
||||
sa.UniqueConstraint(
|
||||
'workflow_item_id',
|
||||
'version_no',
|
||||
name='uq_shipping_notice_workflow_item_versions_item_no',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_workflow_item_id',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['workflow_item_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_item_no',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['item_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_workflow_id',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['workflow_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_workflow_no',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['workflow_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_document_id',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['document_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_item_created',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['workflow_item_id', 'created_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_run',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['run_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_case',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['case_id'],
|
||||
)
|
||||
|
||||
tables = _tables(sa.inspect(bind))
|
||||
if 'shipping_notice_workflow_events' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_workflow_events',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('workflow_id', sa.Integer(), nullable=False),
|
||||
sa.Column('workflow_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('workflow_item_id', sa.Integer(), nullable=True),
|
||||
sa.Column('item_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('workflow_item_version_id', sa.Integer(), nullable=True),
|
||||
sa.Column('version_no', sa.Integer(), nullable=True),
|
||||
sa.Column('seq_no', sa.Integer(), nullable=False),
|
||||
sa.Column('event_code', sa.String(length=64), nullable=False),
|
||||
sa.Column('stage_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('message_code', sa.String(length=128), 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('payload_json', sa.JSON(), nullable=True),
|
||||
sa.Column('reason', sa.Text(), nullable=True),
|
||||
sa.Column('occurred_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['workflow_id'], ['shipping_notice_workflows.id']),
|
||||
sa.ForeignKeyConstraint(['workflow_item_id'], ['shipping_notice_workflow_items.id']),
|
||||
sa.ForeignKeyConstraint(
|
||||
['workflow_item_version_id'],
|
||||
['shipping_notice_workflow_item_versions.id'],
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
'workflow_id',
|
||||
'seq_no',
|
||||
name='uq_shipping_notice_workflow_events_seq',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_workflow_id',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_workflow_no',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_workflow_item_id',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_item_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_item_no',
|
||||
'shipping_notice_workflow_events',
|
||||
['item_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_workflow_occurred',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_id', 'occurred_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_item_occurred',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_item_id', 'occurred_at'],
|
||||
)
|
||||
|
||||
# [STEP] 丢弃旧会话工作项表;不迁移历史行到 Workflow。
|
||||
tables = _tables(sa.inspect(bind))
|
||||
if 'shipping_session_pdf_work_items' in tables:
|
||||
op.drop_table('shipping_session_pdf_work_items')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""仅删除 Workflow 四表;不重建旧会话工作项表。"""
|
||||
bind = op.get_bind()
|
||||
tables = _tables(sa.inspect(bind))
|
||||
|
||||
for table_name in (
|
||||
'shipping_notice_workflow_events',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
'shipping_notice_workflow_items',
|
||||
'shipping_notice_workflows',
|
||||
):
|
||||
if table_name in tables:
|
||||
op.drop_table(table_name)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
migrations/versions/a0e1f2b3c4d5_shipping_audit_append_only_triggers.py
|
||||
|
||||
用途:为 shipping_audit_events 增加 PostgreSQL 层 append-only 触发器。
|
||||
依赖:shipping_audit_events(迁移 9d2f4a6b8c0e 之后);保留期清理依赖 GUC hxops.shipping_audit_purge。
|
||||
逻辑:UPDATE 一律拒绝;DELETE 仅当同事务已 set_config('hxops.shipping_audit_purge','1')
|
||||
且 retention_expires_at IS NOT NULL AND retention_expires_at < now() 时允许;
|
||||
SQLite / 非 PostgreSQL 方言 no-op(单元测试靠 ORM before_update/before_delete 守卫)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a0e1f2b3c4d5'
|
||||
down_revision = '9d2f4a6b8c0e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
在 PostgreSQL 上创建 append-only 触发器函数并挂到 shipping_audit_events。
|
||||
|
||||
SQLite 与其它方言跳过:测试库通常 create_all,无触发器亦可依赖 ORM 守卫。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != 'postgresql':
|
||||
return
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION hxops_shipping_audit_reject_update()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'shipping_audit_events is append-only: UPDATE forbidden'
|
||||
USING ERRCODE = 'integrity_constraint_violation';
|
||||
END;
|
||||
$$;
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION hxops_shipping_audit_guard_delete()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
IF current_setting('hxops.shipping_audit_purge', true) IS DISTINCT FROM '1' THEN
|
||||
RAISE EXCEPTION 'shipping_audit_events 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_audit_events purge only allows expired rows with retention_expires_at'
|
||||
USING ERRCODE = 'integrity_constraint_violation';
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
DROP TRIGGER IF EXISTS trg_shipping_audit_events_no_update
|
||||
ON shipping_audit_events;
|
||||
CREATE TRIGGER trg_shipping_audit_events_no_update
|
||||
BEFORE UPDATE ON shipping_audit_events
|
||||
FOR EACH ROW
|
||||
EXECUTE PROCEDURE hxops_shipping_audit_reject_update();
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
DROP TRIGGER IF EXISTS trg_shipping_audit_events_guard_delete
|
||||
ON shipping_audit_events;
|
||||
CREATE TRIGGER trg_shipping_audit_events_guard_delete
|
||||
BEFORE DELETE ON shipping_audit_events
|
||||
FOR EACH ROW
|
||||
EXECUTE PROCEDURE hxops_shipping_audit_guard_delete();
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除 PostgreSQL append-only 触发器与函数;其它方言 no-op。"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != 'postgresql':
|
||||
return
|
||||
|
||||
op.execute('DROP TRIGGER IF EXISTS trg_shipping_audit_events_guard_delete ON shipping_audit_events;')
|
||||
op.execute('DROP TRIGGER IF EXISTS trg_shipping_audit_events_no_update ON shipping_audit_events;')
|
||||
op.execute('DROP FUNCTION IF EXISTS hxops_shipping_audit_guard_delete();')
|
||||
op.execute('DROP FUNCTION IF EXISTS hxops_shipping_audit_reject_update();')
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
migrations/versions/b1c2d3e4f5a7_rename_manual_upload_pending_to_excel_ready.py
|
||||
|
||||
用途:将 WorkflowItem 终态 manual_upload_pending 收敛为 excel_ready(Excel 就绪即流程终点)。
|
||||
依赖:shipping_notice_workflow_items(迁移 9d2f4a6b8c0e / a0e1f2b3c4d5 之后)。
|
||||
逻辑:UPDATE 存量行 → 重建 lifecycle CHECK 与 open_conversation 部分索引;
|
||||
revision 使用 b1c2d3e4f5a7(b1c2d3e4f5a6 已被历史迁移占用)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'b1c2d3e4f5a7'
|
||||
down_revision = 'a0e1f2b3c4d5'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_LIFECYCLE_NEW = (
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'excel_ready', 'reparse_failed', 'cancelled', 'failed', 'closed'"
|
||||
")"
|
||||
)
|
||||
_LIFECYCLE_OLD = (
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'manual_upload_pending', 'reparse_failed', 'cancelled', 'failed', 'closed'"
|
||||
")"
|
||||
)
|
||||
_OPEN_WHERE_NEW = "lifecycle_status NOT IN ('closed', 'cancelled', 'excel_ready')"
|
||||
_OPEN_WHERE_OLD = "lifecycle_status NOT IN ('closed', 'cancelled', 'manual_upload_pending')"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
将 manual_upload_pending 重命名为 excel_ready,并更新 CHECK / 部分索引。
|
||||
|
||||
PostgreSQL:先改数据,再 drop/create constraint 与索引。
|
||||
SQLite:batch_alter_table recreate 重建约束;索引 drop/create。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
return
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_notice_workflow_items "
|
||||
"SET lifecycle_status = 'excel_ready', current_stage = 'excel_ready' "
|
||||
"WHERE lifecycle_status = 'manual_upload_pending'"
|
||||
)
|
||||
)
|
||||
|
||||
# [STEP 1] 重建 open_conversation 部分索引(WHERE 子句含终态名)。
|
||||
try:
|
||||
op.drop_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
table_name='shipping_notice_workflow_items',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if dialect == 'postgresql':
|
||||
op.drop_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
type_='check',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
_LIFECYCLE_NEW,
|
||||
)
|
||||
else:
|
||||
with op.batch_alter_table('shipping_notice_workflow_items', recreate='always') as batch:
|
||||
batch.drop_constraint('ck_shipping_notice_workflow_items_lifecycle', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
_LIFECYCLE_NEW,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(_OPEN_WHERE_NEW),
|
||||
sqlite_where=sa.text(_OPEN_WHERE_NEW),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回退 excel_ready → manual_upload_pending,并恢复旧 CHECK / 索引。"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
return
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_notice_workflow_items "
|
||||
"SET lifecycle_status = 'manual_upload_pending', "
|
||||
"current_stage = 'manual_upload_pending' "
|
||||
"WHERE lifecycle_status = 'excel_ready'"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
op.drop_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
table_name='shipping_notice_workflow_items',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if dialect == 'postgresql':
|
||||
op.drop_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
type_='check',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
_LIFECYCLE_OLD,
|
||||
)
|
||||
else:
|
||||
with op.batch_alter_table('shipping_notice_workflow_items', recreate='always') as batch:
|
||||
batch.drop_constraint('ck_shipping_notice_workflow_items_lifecycle', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
_LIFECYCLE_OLD,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(_OPEN_WHERE_OLD),
|
||||
sqlite_where=sa.text(_OPEN_WHERE_OLD),
|
||||
)
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
migrations/versions/d4e5f6a7b8c0_restore_manual_upload_pending_lifecycle.py
|
||||
|
||||
用途:恢复 WorkflowItem 唯一生命周期 manual_upload_pending(Excel 后待人工上传登记);
|
||||
清除存量 excel_ready,CHECK 不再接受该废弃状态。
|
||||
依赖:shipping_notice_workflow_items(b1c2d3e4f5a7 之后)。
|
||||
逻辑:UPDATE 存量 → 重建 lifecycle CHECK(无 excel_ready);
|
||||
open_conversation 部分索引仅排除 closed/cancelled。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'd4e5f6a7b8c0'
|
||||
down_revision = 'b1c2d3e4f5a7'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_LIFECYCLE_NEW = (
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'manual_upload_pending', 'reparse_failed', "
|
||||
"'cancelled', 'failed', 'closed'"
|
||||
")"
|
||||
)
|
||||
_LIFECYCLE_OLD = (
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'excel_ready', 'reparse_failed', 'cancelled', 'failed', 'closed'"
|
||||
")"
|
||||
)
|
||||
# 待人工上传登记仍属开放;仅真正终态排除。
|
||||
_OPEN_WHERE_NEW = "lifecycle_status NOT IN ('closed', 'cancelled')"
|
||||
_OPEN_WHERE_OLD = "lifecycle_status NOT IN ('closed', 'cancelled', 'excel_ready')"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
将 excel_ready 全部迁移为 manual_upload_pending,并从 CHECK 移除 excel_ready;
|
||||
重建 open 部分索引使 manual_upload_pending 计入开放项。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
return
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_notice_workflow_items "
|
||||
"SET lifecycle_status = 'manual_upload_pending', "
|
||||
"current_stage = 'manual_upload_pending', "
|
||||
"closed_at = NULL "
|
||||
"WHERE lifecycle_status = 'excel_ready'"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
op.drop_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
table_name='shipping_notice_workflow_items',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if dialect == 'postgresql':
|
||||
op.drop_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
type_='check',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
_LIFECYCLE_NEW,
|
||||
)
|
||||
else:
|
||||
with op.batch_alter_table('shipping_notice_workflow_items', recreate='always') as batch:
|
||||
batch.drop_constraint('ck_shipping_notice_workflow_items_lifecycle', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
_LIFECYCLE_NEW,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(_OPEN_WHERE_NEW),
|
||||
sqlite_where=sa.text(_OPEN_WHERE_NEW),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回退 manual_upload_pending → excel_ready,并恢复 b1 时代 CHECK / 索引。"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
return
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_notice_workflow_items "
|
||||
"SET lifecycle_status = 'excel_ready', current_stage = 'excel_ready' "
|
||||
"WHERE lifecycle_status = 'manual_upload_pending'"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
op.drop_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
table_name='shipping_notice_workflow_items',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if dialect == 'postgresql':
|
||||
op.drop_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
type_='check',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
_LIFECYCLE_OLD,
|
||||
)
|
||||
else:
|
||||
with op.batch_alter_table('shipping_notice_workflow_items', recreate='always') as batch:
|
||||
batch.drop_constraint('ck_shipping_notice_workflow_items_lifecycle', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
_LIFECYCLE_OLD,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(_OPEN_WHERE_OLD),
|
||||
sqlite_where=sa.text(_OPEN_WHERE_OLD),
|
||||
)
|
||||
Reference in new issue
Block a user