Merge branch 'dev' into order-delivery-reply

# Conflicts:
#	backend/app/__init__.py
#	backend/app/services/admin/permission_service.py
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-TW/admin.json
This commit is contained in:
HTEWJ\26070045 committed 2026-09-29 15:08:04 +08:00
commit 42d8b70250
300 files changed
+32072 -6411

No files matched your search

@@ -0,0 +1,24 @@
"""merge snow feedback status and dev transfer naming heads
Revision ID: 6d7b0d04ac25
Revises: 353ebb6187ce, 43a8179cdd88
Create Date: 2026-09-23 13:45:05.502424
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '6d7b0d04ac25'
down_revision = ('353ebb6187ce', '43a8179cdd88')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,31 @@
"""add contract payment company name
Revision ID: cp2f3a4b5c6d
Revises: 43a8179cdd88
用途:合同台账保存 OA 合同申请单「公司」,供预付款/出货款按账套查询 ERP。
依赖:当前迁移头 43a8179cdd88。
逻辑:新增可空 company_name;存量合同保持空值,扫描时按 HXJM 账套处理,直到下次 OA 同步补上公司。
"""
from alembic import op
import sqlalchemy as sa
revision = "cp2f3a4b5c6d"
down_revision = "43a8179cdd88"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""为合同台账增加 OA 公司字段。"""
op.add_column(
"contract_payment_contracts",
sa.Column("company_name", sa.String(length=255), nullable=True),
)
def downgrade() -> None:
"""移除合同台账 OA 公司字段。"""
op.drop_column("contract_payment_contracts", "company_name")
@@ -0,0 +1,35 @@
"""strip purchase order edge spaces and chinese
Revision ID: cp3a4b5c6d7e
Revises: cp2f3a4b5c6d
用途:清掉合同台账采购单号首尾的空格和汉字,使 ERP apaud03 能精确匹配。
依赖:合同公司字段迁移 cp2f3a4b5c6d。
逻辑:只改已有数据,不改表结构。中间的数字和横杠保留;清完为空则写成 NULL。
"""
from alembic import op
revision = "cp3a4b5c6d7e"
down_revision = "cp2f3a4b5c6d"
branch_labels = None
depends_on = None
_EDGE = "^[[:space:] 一-龥]+|[[:space:] 一-龥]+$"
def upgrade() -> None:
"""去掉存量采购单号两端的空格和汉字。"""
op.execute(
f"""
UPDATE contract_payment_contracts
SET purchase_order_no = NULLIF(regexp_replace(purchase_order_no, '{_EDGE}', '', 'g'), '')
WHERE purchase_order_no ~ '{_EDGE}'
"""
)
def downgrade() -> None:
"""首尾汉字已被去掉,无法从剩余单号还原原文。"""
pass
@@ -0,0 +1,24 @@
"""merge migration heads after dev merge
Revision ID: d0304d47d364
Revises: 6d7b0d04ac25, d425edfa336c, p1b2c3d4e5f6
Create Date: 2026-09-29 14:39:03.805744
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd0304d47d364'
down_revision = ('6d7b0d04ac25', 'd425edfa336c', 'p1b2c3d4e5f6')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,30 @@
"""合并 integration_calls.wire_json 与采购单号/合同/在途调拨两条 Alembic 头。
Revision ID: mg0f1a2b3c4d5
Revises: mg9e8f7a6b5c4, wd7e8f9a0b1c
Create Date: 2026-09-27 20:40:00.000000
用途:将 ``wd7e8f9a0b1c``(integration_calls.wire_json / business_ref)与
``mg9e8f7a6b5c4``(采购单号清洗 × 合同公司/在途调拨既有合并头)收成单一升级路径,
避免 ``flask db upgrade`` / pre-commit 因 Multiple head revisions 失败。
依赖:``mg9e8f7a6b5c4``、``wd7e8f9a0b1c``。
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
"""
from alembic import op # noqa: F401 - Alembic migration module contract
revision = "mg0f1a2b3c4d5"
down_revision = ("mg9e8f7a6b5c4", "wd7e8f9a0b1c")
branch_labels = None
depends_on = None
def upgrade() -> None:
"""合并 wire_json head 与采购/合同/在途调拨合并头,不执行数据库结构变更。"""
pass
def downgrade() -> None:
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
pass
@@ -0,0 +1,30 @@
"""合并合同公司账套字段与在途调拨术语重构两条 Alembic 头。
Revision ID: mg8c7d6e5f4a3
Revises: cp2f3a4b5c6d, rn1a2b3c4d5e6
Create Date: 2026-09-24 10:00:00.000000
用途:将 ``cp2f3a4b5c6d``(采购合同请款按公司查不同账套)与
``rn1a2b3c4d5e6``(在途调拨预检术语重构为匹配)收成单一升级路径,
避免 ``flask db upgrade`` / pre-commit 因 Multiple head revisions 失败。
依赖:``cp2f3a4b5c6d``、``rn1a2b3c4d5e6``。
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
"""
from alembic import op # noqa: F401 - Alembic migration module contract
revision = "mg8c7d6e5f4a3"
down_revision = ("cp2f3a4b5c6d", "rn1a2b3c4d5e6")
branch_labels = None
depends_on = None
def upgrade() -> None:
"""合并合同公司 head 与在途调拨匹配 head,不执行数据库结构变更。"""
pass
def downgrade() -> None:
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
pass
@@ -0,0 +1,30 @@
"""合并采购单号清洗与合同公司/在途调拨两条 Alembic 头。
Revision ID: mg9e8f7a6b5c4
Revises: cp3a4b5c6d7e, mg8c7d6e5f4a3
Create Date: 2026-09-24 22:30:00.000000
用途:将 ``cp3a4b5c6d7e``(清掉采购单号首尾空格和汉字)与
``mg8c7d6e5f4a3``(合同公司账套字段 × 在途调拨术语重构)收成单一升级路径,
避免 ``flask db upgrade`` / pre-push 因 Multiple head revisions 失败。
依赖:``cp3a4b5c6d7e``、``mg8c7d6e5f4a3``。
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
"""
from alembic import op # noqa: F401 - Alembic migration module contract
revision = "mg9e8f7a6b5c4"
down_revision = ("cp3a4b5c6d7e", "mg8c7d6e5f4a3")
branch_labels = None
depends_on = None
def upgrade() -> None:
"""合并采购单号清洗 head 与合同公司/在途调拨 head,不执行数据库结构变更。"""
pass
def downgrade() -> None:
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
pass
@@ -0,0 +1,27 @@
"""merge migration heads
用途:合并平行迁移分支,恢复 Alembic 单 head 链。
依赖:无表结构操作,仅声明多父级(mg0f1a2b3c4d5 调用日志 wire_json×PO 契约合并节点
× we9f0a1b2c3d 库存 RPA 回调 source_run_no 加宽)。
逻辑:hugo-shipping-notice 的 we9f0a1b2c3d 基于旧头 wd7e8f9a0b1c 开发,与 test 侧
合并节点 mg0f1a2b3c4d5 形成分叉;本 Revision 只做图合并,upgrade/downgrade
均为空操作,实际 DDL 由两个父迁移各自负责。
Revision ID: p1b2c3d4e5f6
Revises: mg0f1a2b3c4d5, we9f0a1b2c3d
Create Date: 2026-09-28 00:00:00.000000
"""
revision = "p1b2c3d4e5f6"
down_revision = ("mg0f1a2b3c4d5", "we9f0a1b2c3d")
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,245 @@
"""在途调拨术语重构:precheck → match(表/列/约束/状态值全量改名)
Revision ID: rn1a2b3c4d5e6
Revises: 43a8179cdd88
Create Date: 2026-09-23 22:30:00.000000
用途:与代码术语重构(precheck→match,中文「匹配」)配套的存储层改造——
1) 表改名:transfer_prechecks → transfer_matchings。
2) 列改名:transfer_matchings.precheck_no→matching_no、precheck_hash→matching_hash;
transfer_invoice_items.precheck_id→matching_id;transfer_audit_events.precheck_no→matching_no;
transfer_matchings.status server_default 'prechecking'→'matching'。
3) 枚举值刷写:transfer_matchings / transfer_runs / transfer_source_jobs /
transfer_invoice_items 四表 status 'prechecking'→'matching';
transfer_attempts.kind 'precheck'→'match'。
4) 约束/索引替换:uq/ck 旧名 drop 后按新名与新增值列表重建
(uq_transfer_matchings_matching_no、ck_transfer_matchings_status、
uq_transfer_invoice_items_matching_grain、各表 ck_*_status、ck_transfer_attempts_kind);
索引 ix_transfer_prechecks_run_status/business_date 改名。
依赖:43a8179cdd88 为上一 head(模块未上线,无历史数据兼容包袱,直改新值)。
逻辑:先改表名 → drop 旧名约束 → 刷历史行数据(避免被旧 CHECK 拦截)→ 列改名 →
建新名约束/索引;约束与列经 batch 兼容 SQLite(batch 在 PG 上渲染为原生 ALTER),
索引用独立 DROP/CREATE(两种库均支持);downgrade 全量对称回滚。
"""
from alembic import op
import sqlalchemy as sa
revision = 'rn1a2b3c4d5e6'
down_revision = '43a8179cdd88'
branch_labels = None
depends_on = None
# 13 状态中仅 'prechecking'→'matching' 更名,其余 12 个值不动。
_OLD_MATCH_STATUSES = (
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
'success', 'failed', 'cancelled', 'expired',
)
_NEW_MATCH_STATUSES = (
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
'success', 'failed', 'cancelled', 'expired',
)
_OLD_ITEM_STATUSES = (
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
)
_NEW_ITEM_STATUSES = (
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
)
_OLD_RUN_STATUSES = (
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
'success', 'partial_failed', 'failed', 'cancelled',
)
_NEW_RUN_STATUSES = (
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
'success', 'partial_failed', 'failed', 'cancelled',
)
_OLD_SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
)
_NEW_SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
)
_OLD_ATTEMPT_KINDS = ('precheck', 'rpa', 'external_query', 'external_write')
_NEW_ATTEMPT_KINDS = ('match', 'rpa', 'external_query', 'external_write')
def _repr_list(values) -> str:
return ', '.join(repr(v) for v in values)
def upgrade() -> None:
"""表改名 → drop 旧约束 → 刷枚举值 → 列改名 → 建新约束/索引。"""
# [STEP 1] 表改名(RENAME 保留旧索引与约束名,需后续逐一替换)。
op.rename_table('transfer_prechecks', 'transfer_matchings')
# [STEP 2] drop 旧名索引(独立 DDL,PG/SQLite 均支持)。
op.drop_index('ix_transfer_prechecks_run_status', table_name='transfer_matchings')
op.drop_index('ix_transfer_prechecks_business_date', table_name='transfer_matchings')
# [STEP 3] drop 旧名约束(引用旧列名的约束必须先删,列改名后再按新名重建)。
with op.batch_alter_table('transfer_matchings') as batch:
batch.drop_constraint('uq_transfer_prechecks_precheck_no', type_='unique')
batch.drop_constraint('ck_transfer_prechecks_status', type_='check')
with op.batch_alter_table('transfer_invoice_items') as batch:
batch.drop_constraint('uq_transfer_invoice_items_precheck_grain', type_='unique')
batch.drop_constraint('ck_transfer_invoice_items_status', type_='check')
with op.batch_alter_table('transfer_runs') as batch:
batch.drop_constraint('ck_transfer_runs_status', type_='check')
with op.batch_alter_table('transfer_source_jobs') as batch:
batch.drop_constraint('ck_transfer_source_jobs_status', type_='check')
with op.batch_alter_table('transfer_attempts') as batch:
batch.drop_constraint('ck_transfer_attempts_kind', type_='check')
# [STEP 4] 历史行数据刷写(先 UPDATE 再建新 CHECK,避免刷写被旧值列表拦截)。
op.execute("UPDATE transfer_matchings SET status = 'matching' WHERE status = 'prechecking'")
op.execute("UPDATE transfer_runs SET status = 'matching' WHERE status = 'prechecking'")
op.execute("UPDATE transfer_source_jobs SET status = 'matching' WHERE status = 'prechecking'")
op.execute("UPDATE transfer_invoice_items SET status = 'matching' WHERE status = 'prechecking'")
op.execute("UPDATE transfer_attempts SET kind = 'match' WHERE kind = 'precheck'")
# [STEP 5] 列改名与默认值(batch 兼容 SQLite;PG 渲染为 ALTER COLUMN RENAME/SET DEFAULT)。
with op.batch_alter_table('transfer_matchings') as batch:
batch.alter_column('precheck_no', new_column_name='matching_no', existing_type=sa.String(length=64))
batch.alter_column('precheck_hash', new_column_name='matching_hash', existing_type=sa.String(length=128))
batch.alter_column(
'status', existing_type=sa.String(length=32),
server_default='matching', existing_server_default='prechecking',
)
with op.batch_alter_table('transfer_invoice_items') as batch:
batch.alter_column('precheck_id', new_column_name='matching_id', existing_type=sa.Integer())
with op.batch_alter_table('transfer_audit_events') as batch:
batch.alter_column('precheck_no', new_column_name='matching_no', existing_type=sa.String(length=64))
# [STEP 6] 按新名重建约束(值列表换 'matching'/'match')。
with op.batch_alter_table('transfer_matchings') as batch:
batch.create_unique_constraint(
'uq_transfer_matchings_matching_no', ['matching_no'],
)
batch.create_check_constraint(
'ck_transfer_matchings_status',
f"status IN ({_repr_list(_NEW_MATCH_STATUSES)})",
)
with op.batch_alter_table('transfer_invoice_items') as batch:
batch.create_unique_constraint(
'uq_transfer_invoice_items_matching_grain',
['matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date'],
)
batch.create_check_constraint(
'ck_transfer_invoice_items_status',
f"status IN ({_repr_list(_NEW_ITEM_STATUSES)})",
)
with op.batch_alter_table('transfer_runs') as batch:
batch.create_check_constraint(
'ck_transfer_runs_status',
f"status IN ({_repr_list(_NEW_RUN_STATUSES)})",
)
with op.batch_alter_table('transfer_source_jobs') as batch:
batch.create_check_constraint(
'ck_transfer_source_jobs_status',
f"status IN ({_repr_list(_NEW_SOURCE_JOB_STATUSES)})",
)
with op.batch_alter_table('transfer_attempts') as batch:
batch.create_check_constraint(
'ck_transfer_attempts_kind',
f"kind IN ({_repr_list(_NEW_ATTEMPT_KINDS)})",
)
# [STEP 7] 按新名重建索引。
op.create_index(
'ix_transfer_matchings_run_status', 'transfer_matchings', ['run_id', 'status'],
)
op.create_index(
'ix_transfer_matchings_business_date', 'transfer_matchings', ['business_date'],
)
def downgrade() -> None:
"""对称回滚:drop 新约束/索引 → 刷回旧枚举值 → 列改回 → 旧约束/索引回补 → 表名还原。"""
# [STEP 1] drop 新名索引。
op.drop_index('ix_transfer_matchings_run_status', table_name='transfer_matchings')
op.drop_index('ix_transfer_matchings_business_date', table_name='transfer_matchings')
# [STEP 2] drop 新名约束。
with op.batch_alter_table('transfer_matchings') as batch:
batch.drop_constraint('uq_transfer_matchings_matching_no', type_='unique')
batch.drop_constraint('ck_transfer_matchings_status', type_='check')
with op.batch_alter_table('transfer_invoice_items') as batch:
batch.drop_constraint('uq_transfer_invoice_items_matching_grain', type_='unique')
batch.drop_constraint('ck_transfer_invoice_items_status', type_='check')
with op.batch_alter_table('transfer_runs') as batch:
batch.drop_constraint('ck_transfer_runs_status', type_='check')
with op.batch_alter_table('transfer_source_jobs') as batch:
batch.drop_constraint('ck_transfer_source_jobs_status', type_='check')
with op.batch_alter_table('transfer_attempts') as batch:
batch.drop_constraint('ck_transfer_attempts_kind', type_='check')
# [STEP 3] 枚举值还原(旧 CHECK 尚未重建,可安全刷写)。
op.execute("UPDATE transfer_matchings SET status = 'prechecking' WHERE status = 'matching'")
op.execute("UPDATE transfer_runs SET status = 'prechecking' WHERE status = 'matching'")
op.execute("UPDATE transfer_source_jobs SET status = 'prechecking' WHERE status = 'matching'")
op.execute("UPDATE transfer_invoice_items SET status = 'prechecking' WHERE status = 'matching'")
op.execute("UPDATE transfer_attempts SET kind = 'precheck' WHERE kind = 'match'")
# [STEP 4] 列名与默认值还原。
with op.batch_alter_table('transfer_matchings') as batch:
batch.alter_column('matching_no', new_column_name='precheck_no', existing_type=sa.String(length=64))
batch.alter_column('matching_hash', new_column_name='precheck_hash', existing_type=sa.String(length=128))
batch.alter_column(
'status', existing_type=sa.String(length=32),
server_default='prechecking', existing_server_default='matching',
)
with op.batch_alter_table('transfer_invoice_items') as batch:
batch.alter_column('matching_id', new_column_name='precheck_id', existing_type=sa.Integer())
with op.batch_alter_table('transfer_audit_events') as batch:
batch.alter_column('matching_no', new_column_name='precheck_no', existing_type=sa.String(length=64))
# [STEP 5] 旧名约束回补(旧值列表含 'prechecking'/'precheck')。
with op.batch_alter_table('transfer_matchings') as batch:
batch.create_unique_constraint(
'uq_transfer_prechecks_precheck_no', ['precheck_no'],
)
batch.create_check_constraint(
'ck_transfer_prechecks_status',
f"status IN ({_repr_list(_OLD_MATCH_STATUSES)})",
)
with op.batch_alter_table('transfer_invoice_items') as batch:
batch.create_unique_constraint(
'uq_transfer_invoice_items_precheck_grain',
['precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date'],
)
batch.create_check_constraint(
'ck_transfer_invoice_items_status',
f"status IN ({_repr_list(_OLD_ITEM_STATUSES)})",
)
with op.batch_alter_table('transfer_runs') as batch:
batch.create_check_constraint(
'ck_transfer_runs_status',
f"status IN ({_repr_list(_OLD_RUN_STATUSES)})",
)
with op.batch_alter_table('transfer_source_jobs') as batch:
batch.create_check_constraint(
'ck_transfer_source_jobs_status',
f"status IN ({_repr_list(_OLD_SOURCE_JOB_STATUSES)})",
)
with op.batch_alter_table('transfer_attempts') as batch:
batch.create_check_constraint(
'ck_transfer_attempts_kind',
f"kind IN ({_repr_list(_OLD_ATTEMPT_KINDS)})",
)
# [STEP 6] 旧名索引回补。
op.create_index(
'ix_transfer_prechecks_run_status', 'transfer_matchings', ['run_id', 'status'],
)
op.create_index(
'ix_transfer_prechecks_business_date', 'transfer_matchings', ['business_date'],
)
# [STEP 7] 表名还原。
op.rename_table('transfer_matchings', 'transfer_prechecks')
@@ -0,0 +1,117 @@
"""transfer_documents 票表与行/尝试票级外键
路径:backend/migrations/versions/tt0d1e2f3a4b_add_transfer_documents.py
用途:新建 ERP 调拨单(票)表 transfer_documents——五元组一组一票,
doc_no/submit_timestamp 终身复用(D3);部分唯一索引
uq_transfer_documents_group_live 强制「同组至多一张未完结票」
(D15 防线,DB 层防双单兜底);transfer_invoice_items 与
transfer_attempts 增加可空 document_id 外键(D14:票:Attempt=1:N,
外键在 Attempt 侧;票表不存行集快照,完整行集随写 Attempt 留档)。
依赖:当前 alembic head tt9c0d1e2f3a;生产数据库为 PostgreSQL;
部分唯一索引同时声明 postgresql_where / sqlite_where(SQLite 与 PG
均支持 WHERE 形式,测试建表同语义)。
逻辑:upgrade 先建表(唯一约束 + 状态 CHECK 兜底 + 部分唯一索引 + 普通索引;
CHECK 随 create_table 落地、随 downgrade drop_table 一并移除,反向完整),
再为两张既有表加可空外键列并为 transfer_invoice_items.document_id
建单列索引(T10 票级执行按票查行);downgrade 精确反向:先删行表
document_id 索引与两 FK 列,再删票表索引、drop 票表。
Revision ID: tt0d1e2f3a4b
Revises: tt9c0d1e2f3a
Create Date: 2026-09-24 05:30:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'tt0d1e2f3a4b'
down_revision = 'tt9c0d1e2f3a'
branch_labels = None
depends_on = None
# 组锁 WHERE 子句:必须与 app/models/in_transit_transfer.py 的
# UNRESOLVED_DOC_STATUSES 完全一致(test_document_model.py 锁定双方言同口径)。
_UNRESOLVED_DOC_STATUS_WHERE = (
"status IN ('pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed')"
)
# 状态冻结枚举 CHECK(ck_transfer_documents_status):与模型侧由
# TRANSFER_DOCUMENT_STATUSES 生成的 CHECK 同口径(八态逐一对应,非法态 DB 层拒绝)。
_STATUS_CHECK = (
"status IN ('pending', 'executing', 'success', 'duplicate_success', "
"'business_failed', 'technical_failed', 'result_unknown', 'cancelled')"
)
def upgrade() -> None:
"""建票表(含全部约束/索引)并为行/尝试表加票级外键列。"""
op.create_table(
'transfer_documents',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True),
sa.Column('source_code', sa.String(length=64), nullable=False),
sa.Column('external_org', sa.String(length=64), nullable=False),
sa.Column('receipt_date', sa.String(length=16), nullable=False),
sa.Column('from_warehouse', sa.String(length=64), nullable=False),
sa.Column('to_warehouse', sa.String(length=64), nullable=False),
sa.Column('doc_no', sa.String(length=64), nullable=False),
sa.Column('submit_timestamp', sa.String(length=64), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'),
sa.Column('stage_confirmed_at', sa.DateTime(), nullable=True),
sa.Column('erp_document_no', sa.String(length=64), nullable=True),
sa.Column('error_code', sa.String(length=64), nullable=True),
sa.Column('error_message', sa.Text(), nullable=True),
sa.Column('closed_reason', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('doc_no', name='uq_transfer_documents_doc_no'),
sa.UniqueConstraint('submit_timestamp', name='uq_transfer_documents_submit_timestamp'),
sa.CheckConstraint(_STATUS_CHECK, name='ck_transfer_documents_status'),
)
op.create_index('ix_transfer_documents_run_status', 'transfer_documents', ['run_id', 'status'])
op.create_index('ix_transfer_documents_erp_no', 'transfer_documents', ['erp_document_no'])
op.create_index(
'uq_transfer_documents_group_live',
'transfer_documents',
['source_code', 'external_org', 'receipt_date', 'from_warehouse', 'to_warehouse'],
unique=True,
postgresql_where=sa.text(_UNRESOLVED_DOC_STATUS_WHERE),
sqlite_where=sa.text(_UNRESOLVED_DOC_STATUS_WHERE),
)
# 行表加票级外键(D18 关票脱离语义由服务层置 NULL,列为可空)。
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.add_column(sa.Column('document_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key(
'fk_transfer_invoice_items_document_id', 'transfer_documents',
['document_id'], ['id'],
)
# 票级执行(T10)高频「按票查行」:document_id 单列索引(控制器裁决并入本迁移)。
op.create_index(
'ix_transfer_invoice_items_document_id',
'transfer_invoice_items', ['document_id'],
)
# 尝试表加票级外键(写 Attempt 挂票;重查 Attempt 仍只挂 item)。
with op.batch_alter_table('transfer_attempts') as batch_op:
batch_op.add_column(sa.Column('document_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key(
'fk_transfer_attempts_document_id', 'transfer_documents',
['document_id'], ['id'],
)
def downgrade() -> None:
"""精确反向:先删行表 document_id 索引与两 FK 列(约束随列移除),再删索引并 drop 票表。"""
op.drop_index('ix_transfer_invoice_items_document_id', table_name='transfer_invoice_items')
with op.batch_alter_table('transfer_attempts') as batch_op:
batch_op.drop_column('document_id')
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.drop_column('document_id')
op.drop_index('uq_transfer_documents_group_live', table_name='transfer_documents')
op.drop_index('ix_transfer_documents_run_status', table_name='transfer_documents')
op.drop_index('ix_transfer_documents_erp_no', table_name='transfer_documents')
op.drop_table('transfer_documents')
@@ -0,0 +1,26 @@
"""transfer_invoice_items.matching_id 放开非空
Revision ID: tt1a2b3c4d5e6f
Revises: tt0d1e2f3a4b
Create Date: 2026-09-25
用途:落地证据同步行(evidence_sync)尚无匹配归属,matching_id 允许 NULL。
注意:downgrade 要求表中不存在 matching_id IS NULL 的行(先清同步行再降级)。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt1a2b3c4d5e6f'
down_revision = 'tt0d1e2f3a4b'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.alter_column('matching_id', existing_type=sa.Integer(), nullable=True)
def downgrade():
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.alter_column('matching_id', existing_type=sa.Integer(), nullable=False)
@@ -0,0 +1,51 @@
"""
backend/migrations/versions/tt5b6c7d8e9f_drop_integration_calls_operation_unique.py
用途:integration_calls.operation_id 唯一约束 → 普通索引(多步顺序引擎审计 N 行同 operation_id)。
依赖:Alembic head tta9b0c1d2e3;IntegrationCall 模型已同步删除
UniqueConstraint('operation_id') 并新增 Index('ix_integration_calls_operation_id')。
逻辑:多步顺序引擎(Task 4)一次能力调用按步骤落 N 条审计、共享同一 operation_id
(计划 D13/全局约束:一票一次执行 = N 条,按 operation_id 串联);原唯一约束
uq_integration_calls_operation_id 兼作的索引由普通索引
ix_integration_calls_operation_id 补回(无任何代码按 operation_id 查询单行,
删约束无消费方风险)。downgrade 精确反向(重建唯一约束);若库中已存在
同 operation_id 多行,downgrade 会因唯一约束失败——这是预期:
多步审计本身就不兼容旧约束(必要时应先人工清理多步行)。
Revision ID: tt5b6c7d8e9f
Revises: tta9b0c1d2e3
Create Date: 2026-09-24 03:00:00.000000
"""
from __future__ import annotations
from alembic import op
revision = 'tt5b6c7d8e9f'
down_revision = 'tta9b0c1d2e3'
branch_labels = None
depends_on = None
# 与模型 IntegrationCall.__table_args__ 同源的约束/索引命名(ic1a2b3c4d5f 创建时的原名)。
_UQ_NAME = 'uq_integration_calls_operation_id'
_IX_NAME = 'ix_integration_calls_operation_id'
def upgrade() -> None:
"""删 operation_id 唯一约束,补回同名普通索引(查询性能不回退)。"""
# batch_alter_table:SQLite 不支持 DROP CONSTRAINT,须经批处理模式重建表;
# PostgreSQL 等方言按普通 ALTER 执行。
with op.batch_alter_table('integration_calls') as batch:
batch.drop_constraint(_UQ_NAME, type_='unique')
op.create_index(_IX_NAME, 'integration_calls', ['operation_id'])
def downgrade() -> None:
"""回滚:删普通索引并重建唯一约束。
注意:若已存在同 operation_id 多行(多步审计的正常数据形态),重建唯一约束
将失败——这是预期,多步审计与旧约束不兼容;必要时应先人工归并/清理多步行。
"""
op.drop_index(_IX_NAME, table_name='integration_calls')
with op.batch_alter_table('integration_calls') as batch:
batch.create_unique_constraint(_UQ_NAME, ['operation_id'])
@@ -0,0 +1,54 @@
"""add database connector type and db_kind column
Revision ID: tt7a8b9c0d1e
Revises: rn1a2b3c4d5e6
Create Date: 2026-09-24 00:30:00.000000
用途:Integration Connector 扩枚举 database;客户端实例新增 db_kind 专列
(mysql/oracle/sqlserver/postgresql);重建 client/interface 两表 connector_type CHECK。
依赖:当前 alembic head rn1a2b3c4d5e6;integration_client_instances /
integration_interface_definitions 已存在。
逻辑:先删后建两表 CHECK(含 database);client_instances 加可空 db_kind 列
(存量 rest/soap 为 NULL);downgrade 反向(删列 + CHECK 回 rest/soap)。
采用与 if1b2c3d4e5i 相同的直连 drop/create(生产 PostgreSQL);不走 SQLite
batch 表重建,避免同批改 CHECK+加列时的临时表约束冲突。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt7a8b9c0d1e'
down_revision = 'rn1a2b3c4d5e6'
branch_labels = None
depends_on = None
_CLIENT_CK = 'ck_integration_client_instances_connector_type'
_IFACE_CK = 'ck_integration_interface_definitions_connector_type'
_TYPES_WITH_DATABASE = "connector_type IN ('rest', 'soap', 'database')"
_TYPES_LEGACY = "connector_type IN ('rest', 'soap')"
def upgrade() -> None:
"""扩 connector_type CHECK 含 database,并为客户端实例加 db_kind 列。"""
# [STEP 1] 客户端实例:先删后建 CHECK,再加 db_kind 列。
op.drop_constraint(_CLIENT_CK, 'integration_client_instances', type_='check')
op.create_check_constraint(_CLIENT_CK, 'integration_client_instances', _TYPES_WITH_DATABASE)
op.add_column(
'integration_client_instances',
sa.Column('db_kind', sa.String(length=32), nullable=True),
)
# [STEP 2] 接口定义:同步扩 CHECK(接口类型跟随客户端)。
op.drop_constraint(_IFACE_CK, 'integration_interface_definitions', type_='check')
op.create_check_constraint(_IFACE_CK, 'integration_interface_definitions', _TYPES_WITH_DATABASE)
def downgrade() -> None:
"""回滚:删 db_kind,两表 CHECK 恢复为 rest/soap(须无 database 存量行)。"""
op.drop_constraint(_IFACE_CK, 'integration_interface_definitions', type_='check')
op.create_check_constraint(_IFACE_CK, 'integration_interface_definitions', _TYPES_LEGACY)
op.drop_column('integration_client_instances', 'db_kind')
op.drop_constraint(_CLIENT_CK, 'integration_client_instances', type_='check')
op.create_check_constraint(_CLIENT_CK, 'integration_client_instances', _TYPES_LEGACY)
@@ -0,0 +1,36 @@
"""add transfer_doc_no_seq sequence
Revision ID: tt8b9c0d1e2f
Revises: tt5b6c7d8e9f
Create Date: 2026-09-24 04:00:00.000000
用途:为在途调拨来源单号(计划 D2)创建 PostgreSQL 全局序列
transfer_doc_no_seq(单号格式 {org}-OR-{yyMMdd}{seq:05d})。
依赖:当前 alembic head tt5b6c7d8e9f;生产数据库为 PostgreSQL。
逻辑:CREATE SEQUENCE IF NOT EXISTS(START WITH 1 / INCREMENT BY 1,
全局单调递增、不按日重置;超 99999 由应用层 %05d 自然扩位);
IF NOT EXISTS 防重跑;downgrade 用 DROP SEQUENCE IF EXISTS 反向。
SQLite 测试库无序列,不做兼容——测试一律注入 sequence_loader 替身。
"""
from alembic import op
revision = 'tt8b9c0d1e2f'
down_revision = 'tt5b6c7d8e9f'
branch_labels = None
depends_on = None
_CREATE_SEQ_SQL = (
"CREATE SEQUENCE IF NOT EXISTS transfer_doc_no_seq START WITH 1 INCREMENT BY 1"
)
_DROP_SEQ_SQL = "DROP SEQUENCE IF EXISTS transfer_doc_no_seq"
def upgrade() -> None:
"""创建全局单号序列(幂等:IF NOT EXISTS 防重跑)。"""
op.execute(_CREATE_SEQ_SQL)
def downgrade() -> None:
"""回滚:删除全局单号序列(IF EXISTS 防未建先删)。"""
op.execute(_DROP_SEQ_SQL)
@@ -0,0 +1,36 @@
"""transfer_invoice_items 新增交易单位列
Revision ID: tt9c0d1e2f3a
Revises: tt8b9c0d1e2f
Create Date: 2026-09-24 05:00:00.000000
用途:transfer_invoice_items 增加 unit(交易单位,计划 D4:movement 契约第
11 字段)——解析自异动文件「单位」列原值(仅 trim、不换算),作为 ERP
写入行(gls_cm19)输入;空值行在匹配阶段落 blocked_missing_unit。
依赖:当前 alembic head tt8b9c0d1e2f;生产数据库为 PostgreSQL。
逻辑:追加可空文本列(String(32))带 server_default='',存量行归空串
(与 ORM default 一致,避免 NULL 展示歧义);unit 不参与匹配 Hash
快照(口径冻结,历史预检哈希不因本次字段追加而变化);downgrade 直接删列。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt9c0d1e2f3a'
down_revision = 'tt8b9c0d1e2f'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""明细行表加交易单位列(存量行默认空串,匹配阶段对空值行级阻断)。"""
op.add_column(
'transfer_invoice_items',
sa.Column('unit', sa.String(length=32), nullable=True, server_default='', comment='交易单位原值(movement 契约第 11 字段,仅 trim 不换算)'),
)
def downgrade() -> None:
"""回滚:删除交易单位列(存量数据随列丢弃,无其他依赖)。"""
op.drop_column('transfer_invoice_items', 'unit')
@@ -0,0 +1,83 @@
"""
backend/migrations/versions/tta9b0c1d2e3_add_binding_steps_json.py
用途:IntegrationBinding 增加 steps_json(一对多有序绑定步骤);存量行回填为单元素数组。
依赖:Alembic head tt7a8b9c0d1e;integration_bindings 已有 interface_definition_code /
param_mapping_json(旧单步列保留至 P2)。
逻辑:加列(默认 [])→ 按旧列回填 [{"interface_code", "param_mapping_json"}];
downgrade 仅删列。旧列不删、不改 NOT NULL(解析层优先读 steps_json)。
Revision ID: tta9b0c1d2e3
Revises: tt7a8b9c0d1e
Create Date: 2026-09-24 01:10:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = 'tta9b0c1d2e3'
down_revision = 'tt7a8b9c0d1e'
branch_labels = None
depends_on = None
# 与 context_selector_json / param_mapping_json 同类型约定:PostgreSQL JSONB,其余 JSON。
STEPS_JSON = sa.JSON().with_variant(postgresql.JSONB(), 'postgresql')
def upgrade() -> None:
"""加 steps_json 并将存量单步绑定回填为一元素数组。"""
# [STEP 1] 加列(server_default 便于存量 NOT NULL 加列;回填后业务不再依赖默认空数组)。
op.add_column(
'integration_bindings',
sa.Column('steps_json', STEPS_JSON, nullable=False, server_default=sa.text("'[]'")),
)
# [STEP 2] 存量回填:旧 interface_definition_code + param_mapping_json → 单元素 steps。
# PostgreSQL:jsonb_build_*;其他方言(如 SQLite 迁移单测)用 JSON 文本拼接兜底。
bind = op.get_bind()
if bind.dialect.name == 'postgresql':
op.execute(
sa.text(
"""
UPDATE integration_bindings
SET steps_json = jsonb_build_array(
jsonb_build_object(
'interface_code', interface_definition_code,
'param_mapping_json', COALESCE(param_mapping_json, '{}'::jsonb)
)
)
"""
)
)
else:
# SQLite / 其他:用 Python 侧逐行回填,避免方言 JSON 函数差异。
rows = bind.execute(
sa.text(
'SELECT id, interface_definition_code, param_mapping_json '
'FROM integration_bindings'
)
).fetchall()
import json
for row_id, iface_code, mapping in rows:
# 原生 SELECT 绕过 ORM 类型层:JSON 列读回是 JSON 文本,须先还原为
# dict 再回填,否则 steps 里 param_mapping_json 是字符串,
# 解析层会按 param_mapping_not_dict fail-closed(存量绑定全灭)。
if isinstance(mapping, str):
try:
mapping = json.loads(mapping)
except (TypeError, ValueError):
mapping = {}
steps = [{'interface_code': iface_code, 'param_mapping_json': mapping or {}}]
bind.execute(
sa.text('UPDATE integration_bindings SET steps_json = :steps WHERE id = :id'),
{'steps': json.dumps(steps), 'id': row_id},
)
def downgrade() -> None:
"""回滚:删除 steps_json(旧单步列仍在,可继续服务)。"""
op.drop_column('integration_bindings', 'steps_json')
@@ -0,0 +1,35 @@
"""Add integration_calls.wire_json.
Revision ID: wd7e8f9a0b1c
Revises: tt1a2b3c4d5e6f
Create Date: 2026-09-27 00:00:00.000000
用途:集成调用审计增列 wire_json(传输层线级事实)与 business_ref(通用业务
锚点:调用方透传的业务单号/任务号,能力无关,不传为 NULL)。
依赖:integration_calls 表。
逻辑:均可空;历史行保持 NULL(前端如实展示「无线级详情」,不回填)。
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "wd7e8f9a0b1c"
down_revision = "tt1a2b3c4d5e6f"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("integration_calls", sa.Column("wire_json", sa.JSON(), nullable=True))
op.add_column("integration_calls",
sa.Column("business_ref", sa.String(length=128), nullable=True))
op.create_index("ix_integration_calls_business_ref", "integration_calls", ["business_ref"])
def downgrade() -> None:
op.drop_index("ix_integration_calls_business_ref", table_name="integration_calls")
op.drop_column("integration_calls", "business_ref")
op.drop_column("integration_calls", "wire_json")
@@ -0,0 +1,49 @@
"""Widen inventory RPA attempts.source_run_no to 128.
Revision ID: we9f0a1b2c3d
Revises: wd7e8f9a0b1c
Create Date: 2026-09-27 00:00:00.000000
用途:shipping_task_inventory_rpa_attempts.source_run_no 由 varchar(64) 加宽到
varchar(128),与模型 String(128) 对齐。
依赖:shipping_task_inventory_rpa_attempts 表(含 uq_shipping_task_inv_rpa_triplet
唯一约束,覆盖 task_no/source_code/source_run_no 三列)。
逻辑:RPA Worker 回传的 source_run_no 由源系统/仓库/厂商/尝试序号等外部段拼装,
长度不受后端控制(2026-09-27 test:65 字符的 PSR 组合超 64 上限,门禁 Attempt
以 StringDataRightTruncation 终态失败,Gate 收口为 blocked_retryable)。历史迁移
gw4d5e6f7g8h 仅做了 run_no→source_run_no 改名、漏了加宽,本迁移补齐。
注意:downgrade 收窄前须确认不存在长度 >64 的行,否则将失败(不做静默截断,
标识符截断会破坏与 RPA Worker 的精确回关联)。
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "we9f0a1b2c3d"
down_revision = "wd7e8f9a0b1c"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.alter_column(
"shipping_task_inventory_rpa_attempts",
"source_run_no",
existing_type=sa.String(length=64),
type_=sa.String(length=128),
existing_nullable=False,
)
def downgrade() -> None:
op.alter_column(
"shipping_task_inventory_rpa_attempts",
"source_run_no",
existing_type=sa.String(length=128),
type_=sa.String(length=64),
existing_nullable=False,
)