Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	frontend/src/features/user/views/UserProfilePage.vue
This commit is contained in:
HTEWJ\26070045 committed 2026-09-23 14:34:20 +08:00
commit 5faf86b184
691 files changed
+55948 -17728

No files matched your search

@@ -0,0 +1,27 @@
"""merge_transfer_naming_and_invoice_lot
用途:合并平行迁移分支,恢复 Alembic 单 head 链。
依赖:无表结构操作,仅声明多父级(ex1a2b3c4d5e6 在途调拨命名外置 × rc5e6f7a8b9c 调拨发票明细批号)。
逻辑:本分支在途调拨/集成连接器链与另一条发票 lot_no 链产生分叉;本 Revision 只做图合并,
upgrade/downgrade 均为空操作,实际 DDL 由两个父迁移各自负责。
Revision ID: 43a8179cdd88
Revises: ex1a2b3c4d5e6, rc5e6f7a8b9c
Create Date: 2026-09-23 00:56:18.780405
"""
revision = "43a8179cdd88"
down_revision = ("ex1a2b3c4d5e6", "rc5e6f7a8b9c")
branch_labels = None
depends_on = None
def upgrade():
"""空操作:仅合并 revision 图,无 DDL。"""
pass
def downgrade():
"""空操作:合并节点降级不回滚父迁移 DDL。"""
pass
@@ -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,54 @@
"""customer odm scope: add odm_ids to shipping_customers
Revision ID: aa11bb22cc33
Revises: fb26bc033d27
Create Date: 2026-09-16 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "aa11bb22cc33"
down_revision = "fb26bc033d27"
branch_labels = None
depends_on = None
def _add_column(insp, table: str, column: sa.Column) -> None:
if table not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns(table)}
if column.name not in columns:
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.add_column(column)
def _drop_column(insp, table: str, name: str) -> None:
if table not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns(table)}
if name in columns:
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.drop_column(name)
def upgrade():
insp = sa.inspect(op.get_bind())
_add_column(
insp,
"shipping_customers",
sa.Column("odm_ids", sa.JSON(), nullable=True),
)
_add_column(
insp,
"shipping_notice_line_inventory_matches",
sa.Column("chosen_odm_id", sa.String(length=64), nullable=True),
)
def downgrade():
insp = sa.inspect(op.get_bind())
_drop_column(insp, "shipping_notice_line_inventory_matches", "chosen_odm_id")
_drop_column(insp, "shipping_customers", "odm_ids")
@@ -0,0 +1,163 @@
"""Seed contract_payment Chat Agent and migrate feature-permission grants.
Revision ID: cp8a9b0c1d2e
Revises: fb26bc033d27
Create Date: 2026-09-15 17:50:00.000000
用途:为合同付款预警注册 builtin Chat Agent,并把旧功能权限 `contract_payment.access`
迁移为 user_agent_permissions;随后从 users.feature_permissions 去掉该键。
依赖:agents、users、user_agent_permissions 表已存在。
逻辑:先按 agent_code 复用已有实例(含停用);没有则插入。插入前把 agents.id
序列对齐 MAX(id),避免本地库序列落后时撞主键。显式勾选过访问权的普通用户
获得该 Agent;admin 仍按运行时角色看到全部 Agent,不必写关联表。
"""
from __future__ import annotations
import json
from alembic import op
from sqlalchemy import text
revision = "cp8a9b0c1d2e"
down_revision = "fb26bc033d27"
branch_labels = None
depends_on = None
AGENT_CODE = "contract_payment"
def _resync_agents_id_sequence() -> None:
"""把 agents 主键序列对齐现有最大 id,避免 nextval 撞上已占用主键。"""
bind = op.get_bind()
if bind.dialect.name != "postgresql":
return
op.execute(
"""
SELECT setval(
pg_get_serial_sequence('public.agents', 'id'),
COALESCE((SELECT MAX(id) FROM public.agents), 1),
true
)
"""
)
def _write_feature_permissions(conn, user_id: int, permissions: dict) -> None:
"""把功能权限 JSON 写回 users;psycopg2 不能直接绑定 Python dict。"""
conn.execute(
text(
"UPDATE users SET feature_permissions = CAST(:perms AS JSON) "
"WHERE id = :user_id"
),
{"perms": json.dumps(permissions, ensure_ascii=False), "user_id": user_id},
)
def upgrade() -> None:
"""插入或复用合同付款预警 Agent,并把旧功能权限授予改写为 Agent 授权。"""
conn = op.get_bind()
agent_id = conn.execute(
text(
"SELECT id FROM agents WHERE agent_code = :code "
"ORDER BY id ASC LIMIT 1"
),
{"code": AGENT_CODE},
).scalar()
if agent_id is not None:
conn.execute(
text(
"""
UPDATE agents
SET is_active = true,
runtime_provider = 'builtin',
conversation_mode = 'task_chat',
dify_app_type = 'chatflow',
updated_at = CURRENT_TIMESTAMP
WHERE id = :agent_id
"""
),
{"agent_id": agent_id},
)
else:
_resync_agents_id_sequence()
conn.execute(
text(
"""
INSERT INTO agents (
name, description, type, is_active, is_aggregate,
agent_code, runtime_provider, conversation_mode, dify_app_type,
suggested_questions_style, sort_order, created_at, updated_at
) VALUES (
:name, :description, 'api', true, false,
:code, 'builtin', 'task_chat', 'chatflow',
'plain', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)
"""
),
{
"name": "合同付款预警",
"description": "查看采购合同台账、待确认项和周五付款预警汇总。",
"code": AGENT_CODE,
},
)
agent_id = conn.execute(
text(
"SELECT id FROM agents WHERE agent_code = :code AND is_active = true "
"ORDER BY id ASC LIMIT 1"
),
{"code": AGENT_CODE},
).scalar()
users = conn.execute(text("SELECT id, feature_permissions FROM users")).fetchall()
for user_id, raw_permissions in users:
permissions = raw_permissions if isinstance(raw_permissions, dict) else {}
granted = bool(permissions.get("contract_payment.access"))
if granted and agent_id is not None:
conn.execute(
text(
"""
INSERT INTO user_agent_permissions (user_id, agent_id)
SELECT :user_id, :agent_id
WHERE NOT EXISTS (
SELECT 1 FROM user_agent_permissions
WHERE user_id = :user_id AND agent_id = :agent_id
)
"""
),
{"user_id": user_id, "agent_id": agent_id},
)
if "contract_payment.access" in permissions:
cleaned = {
key: value
for key, value in permissions.items()
if key != "contract_payment.access"
}
_write_feature_permissions(conn, user_id, cleaned)
def downgrade() -> None:
"""恢复功能权限键;不删除已创建的 Agent 实例,以免误伤运营配置。"""
conn = op.get_bind()
agent_id = conn.execute(
text(
"SELECT id FROM agents WHERE agent_code = :code "
"ORDER BY id ASC LIMIT 1"
),
{"code": AGENT_CODE},
).scalar()
if agent_id is None:
return
granted_user_ids = conn.execute(
text("SELECT user_id FROM user_agent_permissions WHERE agent_id = :agent_id"),
{"agent_id": agent_id},
).fetchall()
for (user_id,) in granted_user_ids:
row = conn.execute(
text("SELECT feature_permissions FROM users WHERE id = :user_id"),
{"user_id": user_id},
).fetchone()
permissions = dict(row[0] if row and isinstance(row[0], dict) else {})
permissions["contract_payment.access"] = True
_write_feature_permissions(conn, user_id, permissions)
@@ -0,0 +1,26 @@
"""合并合同付款 Chat Agent 与立账凭证 PO 打印两条 Alembic 头。
用途:invoice-check 合入 dev 后,``vc4e5f6a7b8c`` 与 ``cp8a9b0c1d2e`` 并列成双 head,
导致 ``flask db upgrade`` 无法解析默认 ``head``。
依赖:``cp8a9b0c1d2e``(合同付款预警 Chat Agent seed)、
``vc4e5f6a7b8c``(立账凭证 PO 订单生成周批 seed)。
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
"""
from alembic import op # noqa: F401 - Alembic migration module contract
revision = "cp9b0c1d2e3f"
down_revision = ("cp8a9b0c1d2e", "vc4e5f6a7b8c")
branch_labels = None
depends_on = None
def upgrade() -> None:
"""合并合同付款 Agent seed 与 PO 打印排程 seed,不执行数据库结构变更。"""
pass
def downgrade() -> None:
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
pass
@@ -0,0 +1,25 @@
"""merge migration heads
用途:合并平行迁移分支,恢复 Alembic 单 head 链。
依赖:无表结构操作,仅声明多父级(aa11bb22cc33 客户 ODM 字段 × vc6a7b8c9d0e 凭证检核通知配置)。
逻辑:hugo-shipping-notice 与 dev 两侧各自新增迁移产生分叉;本 Revision 只做图合并,
upgrade/downgrade 均为空操作,实际 DDL 由两个父迁移各自负责。
Revision ID: dd22ee33ff44
Revises: aa11bb22cc33, vc6a7b8c9d0e
Create Date: 2026-09-17 00:00:00.000000
"""
revision = "dd22ee33ff44"
down_revision = ("aa11bb22cc33", "vc6a7b8c9d0e")
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,99 @@
"""在途调拨存储层去 ERP 化:列/索引改名、枚举值刷写、约束替换
Revision ID: ex1a2b3c4d5e6
Revises: tt3d4e5f6a7b
Create Date: 2026-09-22 21:40:00.000000
用途:与代码去 ERP 化(外部系统通用命名)配套的存储层改造——
1) 列改名:transfer_invoice_items.erp_quantity→external_quantity、
erp_document_no→external_document_no;transfer_prechecks.estimated_erp_write_count→
estimated_external_write_count;同步索引 ix_transfer_invoice_items_erp_document_no 改名。
2) 枚举/审计值刷写:transfer_attempts.kind(erp_query/erp_write→external_query/external_write)、
transfer_invoice_items.result_code(blocked_erp_query_failed→blocked_external_query_failed、
erp_query_timeout→external_query_timeout)与 result_message 前缀、
transfer_audit_events.event_type(TRANSFER_ERP_→TRANSFER_EXTERNAL_)、
transfer_archives.object_type(erp_inventory_snapshot→external_inventory_snapshot)。
3) 约束替换:ck_transfer_attempts_kind 枚举集合改为 external_*。
依赖:tt3d4e5f6a7b 为上一 head。
逻辑:先删旧约束再刷历史行数据(避免刷写被旧 CHECK 拦截)后建新约束;列/索引经 batch 兼容 SQLite;
downgrade 全量反向恢复。
"""
from alembic import op
import sqlalchemy as sa
revision = 'ex1a2b3c4d5e6'
down_revision = 'tt3d4e5f6a7b'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删旧约束 → 刷历史枚举值 → 建新约束 → 列/索引改名。"""
# [STEP 1] 先删旧 Attempt 类型约束,否则刷写 external_* 值会被旧 CHECK 拦截。
with op.batch_alter_table('transfer_attempts') as batch:
batch.drop_constraint('ck_transfer_attempts_kind', type_='check')
# [STEP 2] 历史行数据刷写。
op.execute("UPDATE transfer_attempts SET kind = 'external_query' WHERE kind = 'erp_query'")
op.execute("UPDATE transfer_attempts SET kind = 'external_write' WHERE kind = 'erp_write'")
op.execute("UPDATE transfer_invoice_items SET result_code = 'blocked_external_query_failed' "
"WHERE result_code = 'blocked_erp_query_failed'")
op.execute("UPDATE transfer_invoice_items SET result_code = 'external_query_timeout' "
"WHERE result_code = 'erp_query_timeout'")
op.execute("UPDATE transfer_invoice_items SET result_message = REPLACE(result_message, 'erp ', 'external ') "
"WHERE result_message LIKE '%erp %'")
op.execute("UPDATE transfer_audit_events SET event_type = REPLACE(event_type, 'TRANSFER_ERP_', 'TRANSFER_EXTERNAL_') "
"WHERE event_type LIKE 'TRANSFER_ERP_%'")
op.execute("UPDATE transfer_archives SET object_type = 'external_inventory_snapshot' "
"WHERE object_type = 'erp_inventory_snapshot'")
# [STEP 3] 建新 Attempt 类型约束(新枚举集合)。
with op.batch_alter_table('transfer_attempts') as batch:
batch.create_check_constraint(
'ck_transfer_attempts_kind',
"kind IN ('precheck', 'rpa', 'external_query', 'external_write')",
)
# [STEP 3] 列与索引改名(与模型 external_* 命名对齐)。
with op.batch_alter_table('transfer_invoice_items') as batch:
batch.alter_column('erp_quantity', new_column_name='external_quantity', existing_type=sa.String(length=40))
batch.alter_column('erp_document_no', new_column_name='external_document_no', existing_type=sa.String(length=64))
batch.drop_index('ix_transfer_invoice_items_erp_document_no')
batch.create_index('ix_transfer_invoice_items_external_document_no', ['external_document_no'])
with op.batch_alter_table('transfer_prechecks') as batch:
batch.alter_column(
'estimated_erp_write_count', new_column_name='estimated_external_write_count', existing_type=sa.Integer(),
)
def downgrade() -> None:
"""反向恢复:列/索引改回 → 删新约束 → 枚举值还原 → 旧约束回补。"""
with op.batch_alter_table('transfer_prechecks') as batch:
batch.alter_column(
'estimated_external_write_count', new_column_name='estimated_erp_write_count', existing_type=sa.Integer(),
)
with op.batch_alter_table('transfer_invoice_items') as batch:
batch.drop_index('ix_transfer_invoice_items_external_document_no')
batch.create_index('ix_transfer_invoice_items_erp_document_no', ['erp_document_no'])
batch.alter_column('external_document_no', new_column_name='erp_document_no', existing_type=sa.String(length=64))
batch.alter_column('external_quantity', new_column_name='erp_quantity', existing_type=sa.String(length=40))
with op.batch_alter_table('transfer_attempts') as batch:
batch.drop_constraint('ck_transfer_attempts_kind', type_='check')
op.execute("UPDATE transfer_archives SET object_type = 'erp_inventory_snapshot' "
"WHERE object_type = 'external_inventory_snapshot'")
op.execute("UPDATE transfer_audit_events SET event_type = REPLACE(event_type, 'TRANSFER_EXTERNAL_', 'TRANSFER_ERP_') "
"WHERE event_type LIKE 'TRANSFER_EXTERNAL_%'")
op.execute("UPDATE transfer_invoice_items SET result_message = REPLACE(result_message, 'external ', 'erp ') "
"WHERE result_message LIKE '%external %'")
op.execute("UPDATE transfer_invoice_items SET result_code = 'blocked_erp_query_failed' "
"WHERE result_code = 'blocked_external_query_failed'")
op.execute("UPDATE transfer_invoice_items SET result_code = 'erp_query_timeout' "
"WHERE result_code = 'external_query_timeout'")
op.execute("UPDATE transfer_attempts SET kind = 'erp_write' WHERE kind = 'external_write'")
op.execute("UPDATE transfer_attempts SET kind = 'erp_query' WHERE kind = 'external_query'")
with op.batch_alter_table('transfer_attempts') as batch:
batch.create_check_constraint(
'ck_transfer_attempts_kind',
"kind IN ('precheck', 'rpa', 'erp_query', 'erp_write')",
)
@@ -0,0 +1,41 @@
"""仓库映射新增在途仓编码;调拨明细记录收料仓库匹配键
Revision ID: it2c3d4e5f6a7
Revises: re1f3a4b5c6d
Create Date: 2026-09-22 12:00:00.000000
用途:shipping_inventory_external_mappings 增加 in_transit_warehouse_code(在途调拨拨出库位
来源,保存端必填);transfer_invoice_items 增加 receipt_warehouse_code(收料文件
「仓库」列原值,inventory_match 源映射行匹配键的审计留痕)。
依赖:re1f3a4b5c6d 为当前 head。
逻辑:两列均为带 '' 默认值的追加列,不改既有数据;downgrade 直接删列。
"""
from alembic import op
import sqlalchemy as sa
revision = 'it2c3d4e5f6a7'
down_revision = 're1f3a4b5c6d'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""映射表加在途仓编码(拨出库位来源)、调拨明细表加收料仓库匹配键。"""
op.add_column(
'shipping_inventory_external_mappings',
sa.Column('in_transit_warehouse_code', sa.String(length=64), nullable=False,
server_default='', comment='在途仓编码(在途调拨拨出库位来源)'),
)
op.add_column(
'transfer_invoice_items',
sa.Column('receipt_warehouse_code', sa.String(length=64), nullable=False,
server_default='', comment='收料文件仓库列原值(映射行匹配键)'),
)
def downgrade() -> None:
"""回滚:删除两列(存量数据随列丢弃,无其他依赖)。"""
op.drop_column('transfer_invoice_items', 'receipt_warehouse_code')
op.drop_column('shipping_inventory_external_mappings', 'in_transit_warehouse_code')
@@ -0,0 +1,34 @@
"""
backend/migrations/versions/rc1a2b3c4d5e_drop_receipt_config_enabled.py
用途:删除收料报表配置的独立 enabled 列,站点启停即库存+收料统一开关。
依赖:Alembic revision dd22ee33ff44;shipping_receipt_report_configs 已存在。
逻辑:收料是否运行改为只看库存站点 enabled 与配置是否存在;四处后端门禁同步去掉该列过滤。
Revision ID: rc1a2b3c4d5e
Revises: dd22ee33ff44
Create Date: 2026-09-18 11:30:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "rc1a2b3c4d5e"
down_revision = "dd22ee33ff44"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除 shipping_receipt_report_configs.enabled;启用语义统一归属库存站点。"""
op.drop_column("shipping_receipt_report_configs", "enabled")
def downgrade() -> None:
"""恢复 enabled 列并统一置 true;历史双开关状态无法无损还原。"""
op.add_column(
"shipping_receipt_report_configs",
sa.Column("enabled", sa.Boolean(), server_default=sa.text("true"), nullable=False),
)
@@ -0,0 +1,103 @@
"""
backend/migrations/versions/rc2b3c4d5e6f_drop_receipt_warehouse_list.py
用途:删除收料配置的 warehouse_ids_json 列,仓库清单改为查询条件中的 Warehouse 条件。
依赖:Alembic revision rc1a2b3c4d5e;shipping_receipt_report_configs 与 shipping_inventory_sources 已存在。
逻辑:升级时先把存量 DBS 配置的仓库清单注入为一条 Warehouse 查询条件(数据保全)再删列;
降级时从 Warehouse 条件反提清单尽力恢复,条件本身保留。
Revision ID: rc2b3c4d5e6f
Revises: rc1a2b3c4d5e
Create Date: 2026-09-18 12:20:00.000000
"""
from __future__ import annotations
import json
from typing import Any
import sqlalchemy as sa
from alembic import op
revision = "rc2b3c4d5e6f"
down_revision = "rc1a2b3c4d5e"
branch_labels = None
depends_on = None
def _as_list(raw: Any) -> list:
"""把 JSON 列读成 list;驱动可能返回 list 或字符串。"""
if raw is None:
return []
if isinstance(raw, list):
return list(raw)
if isinstance(raw, str):
text = raw.strip()
if not text:
return []
loaded = json.loads(text)
return list(loaded) if isinstance(loaded, list) else []
return []
def _warehouse_values(parameters: list) -> list[str]:
"""提取查询条件里的 Warehouse 值(去空去重,保持顺序)。"""
values: list[str] = []
for item in parameters:
if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse':
continue
for value in (item.get('values') or []):
cleaned = str(value or '').strip()
if cleaned and cleaned not in values:
values.append(cleaned)
return values
def upgrade() -> None:
"""先把存量 DBS 仓库清单转为 Warehouse 查询条件,再删除 warehouse_ids_json 列。"""
conn = op.get_bind()
rows = conn.execute(sa.text(
"SELECT c.id, c.query_parameters_json, c.warehouse_ids_json"
" FROM shipping_receipt_report_configs c"
" JOIN shipping_inventory_sources s ON s.id = c.inventory_source_id"
" WHERE s.connector_type = 'dbs'"
)).mappings().all()
for row in rows:
parameters = _as_list(row['query_parameters_json'])
warehouses = [str(v or '').strip() for v in _as_list(row['warehouse_ids_json']) if str(v or '').strip()]
has_warehouse_condition = any(
isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse'
for item in parameters
)
if warehouses and not has_warehouse_condition:
parameters.append({
'name': 'Warehouse', 'mode': 'single' if len(warehouses) == 1 else 'multi_text',
'values': warehouses, 'required': False, 'select_all': False,
})
conn.execute(
sa.text("UPDATE shipping_receipt_report_configs SET query_parameters_json = CAST(:params AS JSON) WHERE id = :id"),
{'params': json.dumps(parameters), 'id': row['id']},
)
op.drop_column('shipping_receipt_report_configs', 'warehouse_ids_json')
def downgrade() -> None:
"""恢复 warehouse_ids_json 列并从 Warehouse 条件尽力反提;条件本身保留。"""
op.add_column(
'shipping_receipt_report_configs',
sa.Column('warehouse_ids_json', sa.JSON(), nullable=False, server_default=sa.text("'[]'")),
)
conn = op.get_bind()
rows = conn.execute(sa.text(
"SELECT c.id, c.query_parameters_json"
" FROM shipping_receipt_report_configs c"
" JOIN shipping_inventory_sources s ON s.id = c.inventory_source_id"
" WHERE s.connector_type = 'dbs'"
)).mappings().all()
for row in rows:
warehouses = _warehouse_values(_as_list(row['query_parameters_json']))
if warehouses:
conn.execute(
sa.text("UPDATE shipping_receipt_report_configs SET warehouse_ids_json = CAST(:warehouses AS JSON) WHERE id = :id"),
{'warehouses': json.dumps(warehouses), 'id': row['id']},
)
@@ -0,0 +1,39 @@
"""
backend/migrations/versions/rc3c4d5e6f7a_allow_null_receipt_unit_schedule_run.py
用途:收料 RPA 执行单元 schedule_run_id 改为可空,支持无排程的按需触发。
依赖:Alembic revision rc2b3c4d5e6f;shipping_receipt_rpa_unit_runs 已存在。
逻辑:调拨重试/预检补抓按需触发不产生 ScheduleRun,原 NOT NULL+FK 下只能写
0 占位并被 PostgreSQL 外键拒绝(0 不在 schedule_runs);改为 NULL 表示无排程。
降级前必须先确认表内不存在 schedule_run_id 为 NULL 的行。
Revision ID: rc3c4d5e6f7a
Revises: rc2b3c4d5e6f
Create Date: 2026-09-21 09:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "rc3c4d5e6f7a"
down_revision = "rc2b3c4d5e6f"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""放开 shipping_receipt_rpa_unit_runs.schedule_run_id 的 NOT NULL 约束。"""
op.alter_column(
'shipping_receipt_rpa_unit_runs', 'schedule_run_id',
existing_type=sa.Integer(), nullable=True,
)
def downgrade() -> None:
"""恢复 NOT NULL;执行前必须清理 schedule_run_id 为 NULL 的按需触发单元行。"""
op.alter_column(
'shipping_receipt_rpa_unit_runs', 'schedule_run_id',
existing_type=sa.Integer(), nullable=False,
)
@@ -0,0 +1,44 @@
"""
backend/migrations/versions/rc4d5e6f7a8b_widen_transfer_invoice_item_unique_grain.py
用途:预检明细唯一约束从 (预检,Invoice) 升粒度为 (预检,来源,Invoice,料号,收料日期)。
依赖:Alembic revision sd9e8f7a6b5c;transfer_invoice_items 已存在。
逻辑:调拨 Invoice 自 2026-09-21 锚定批号(External ASN),同一批号按料号/收料日期
拆分为多行;旧约束 (precheck_id, invoice_no) 与新粒度矛盾导致预检 500。
降级前必须确认不存在同批号多料号/多日期的明细行。
Revision ID: rc4d5e6f7a8b
Revises: sd9e8f7a6b5c
Create Date: 2026-09-21 17:20:00.000000
"""
from __future__ import annotations
from alembic import op
revision = "rc4d5e6f7a8b"
down_revision = "sd9e8f7a6b5c"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除 (预检,Invoice) 唯一约束,改为含料号与收料日期的完整业务粒度。"""
op.drop_constraint(
'uq_transfer_invoice_items_precheck_invoice', 'transfer_invoice_items', type_='unique',
)
op.create_unique_constraint(
'uq_transfer_invoice_items_precheck_grain', 'transfer_invoice_items',
['precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date'],
)
def downgrade() -> None:
"""恢复旧约束;执行前必须清理同批号多料号/多日期产生的拆分明细行。"""
op.drop_constraint(
'uq_transfer_invoice_items_precheck_grain', 'transfer_invoice_items', type_='unique',
)
op.create_unique_constraint(
'uq_transfer_invoice_items_precheck_invoice', 'transfer_invoice_items',
['precheck_id', 'invoice_no'],
)
@@ -0,0 +1,31 @@
"""
backend/migrations/versions/rc5e6f7a8b9c_add_transfer_invoice_item_lot_no.py
用途:预检明细增加批号 lot_no 列(拨出/拨入批号展示与追溯的数据来源)。
依赖:Alembic revision rc4d5e6f7a8b;transfer_invoice_items 已存在。
逻辑:批号为收料行的 External ASN 等批号原值;拨入批号展示由 WTP→HOW 转换派生,不落库。
Revision ID: rc5e6f7a8b9c
Revises: rc4d5e6f7a8b
Create Date: 2026-09-21 18:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "rc5e6f7a8b9c"
down_revision = "rc4d5e6f7a8b"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""transfer_invoice_items 增加 lot_no 可空列。"""
op.add_column('transfer_invoice_items', sa.Column('lot_no', sa.String(length=64), nullable=True))
def downgrade() -> None:
"""删除 lot_no 列(展示数据派生自收料文件,可随时重算)。"""
op.drop_column('transfer_invoice_items', 'lot_no')
@@ -0,0 +1,45 @@
"""
backend/migrations/versions/rd1e2f3a4b5c_integration_connector_param_mapping_and_db_credentials.py
用途:集成连接器两项增强——绑定增加参数映射列、凭据引用增加密文列(db 维护模式)。
依赖:Alembic revision dd22ee33ff44(当前唯一 head);integration_bindings / integration_credential_references 已存在。
逻辑:param_mapping_json 承载域参数→接口参数的声明式映射(空对象=同名直通);
secret_ciphertext 承载凭据 JSON 的 Fernet 密文(主密钥 INTEGRATION_CREDENTIAL_KEY
环境注入),与既有 env 引用模式并存(secret_provider 区分)。
Revision ID: rd1e2f3a4b5c
Revises: dd22ee33ff44
Create Date: 2026-09-21 19:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "rd1e2f3a4b5c"
down_revision = "dd22ee33ff44"
branch_labels = None
depends_on = None
# 与 context_selector_json 同类型约定:PostgreSQL 用 JSONB,SQLite/测试用 JSON。
PARAM_MAPPING_JSON = sa.JSON().with_variant(postgresql.JSONB(), 'postgresql')
def upgrade() -> None:
"""绑定加参数映射列;凭据引用加密文列(可空,兼容既有 env 模式行)。"""
op.add_column(
'integration_bindings',
sa.Column('param_mapping_json', PARAM_MAPPING_JSON, nullable=False, server_default=sa.text("'{}'")),
)
op.add_column(
'integration_credential_references',
sa.Column('secret_ciphertext', sa.Text(), nullable=True),
)
def downgrade() -> None:
"""删除两列(param_mapping/密文均可由配置与凭据重新维护,无衍生数据)。"""
op.drop_column('integration_credential_references', 'secret_ciphertext')
op.drop_column('integration_bindings', 'param_mapping_json')
@@ -0,0 +1,31 @@
"""drop integration binding context_source_code
Revision ID: re1f3a4b5c6d
Revises: rd1e2f3a4b5c
Create Date: 2026-09-22 10:00:00.000000
用途:删除 IntegrationBinding.context_source_code 独立列(过度设计一刀切)。
依赖:ix1a2b3c4d5e 加列;rd1e2f3a4b5c 为当前 head。
逻辑:context_source_code 只是 context_selector_json 中 source_code 键的快捷列,
与高级配置(context_selector_json)机制重复;按路由条件统一走
context_selector_json 的约定删列,不设兼容层(框架未上线,无存量数据顾虑)。
"""
from alembic import op
import sqlalchemy as sa
revision = 're1f3a4b5c6d'
down_revision = 'rd1e2f3a4b5c'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除绑定表的 context_source_code 快捷列(路由条件统一由 context_selector_json 表达)。"""
op.drop_column('integration_bindings', 'context_source_code')
def downgrade() -> None:
"""回滚:恢复 context_source_code 列(nullable,与拆列迁移 ix1a2b3c4d5e 时的定义一致)。"""
op.add_column('integration_bindings', sa.Column('context_source_code', sa.String(length=64), nullable=True))
@@ -0,0 +1,37 @@
"""
backend/migrations/versions/sd9e8f7a6b5c_allow_duplicate_customer_short_code.py
用途:放开 shipping_customers.short_code 的全局唯一约束,允许不同标准客户共用简码。
依赖:Alembic revision rc3c4d5e6f7a;shipping_customers 表由 f1a2b3c4d5e6 创建。
逻辑:实际业务中客户简码可重复(简码仅作业务编号前缀,客户身份以 id/识别证据为准),
原 UniqueConstraint('short_code')(未命名,PostgreSQL 默认名
shipping_customers_short_code_key)导致新增/改名报「客户简码已存在」。
降级前必须先合并或改开重复简码,否则重建唯一约束会因存量重复数据失败。
Revision ID: sd9e8f7a6b5c
Revises: rc3c4d5e6f7a
Create Date: 2026-09-21 11:40:00.000000
"""
from __future__ import annotations
from alembic import op
revision = "sd9e8f7a6b5c"
down_revision = "rc3c4d5e6f7a"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除客户简码的唯一约束,允许重复。"""
op.drop_constraint(
'shipping_customers_short_code_key', 'shipping_customers', type_='unique',
)
def downgrade() -> None:
"""恢复唯一约束;执行前必须先处理存量重复简码,否则约束创建失败。"""
op.create_unique_constraint(
'shipping_customers_short_code_key', 'shipping_customers', ['short_code'],
)
@@ -0,0 +1,42 @@
"""transfer_runs 新增调拨业务类型列
Revision ID: tt3d4e5f6a7b
Revises: it2c3d4e5f6a7
Create Date: 2026-09-22 18:00:00.000000
用途:transfer_runs 增加 transfer_type(调拨业务类型:在途仓至HUB仓/HUB仓维修出/
HUB仓间调拨),作为 Run 级数据范围真相源;一期仅 in_transit_to_hub 进入
处理链路,其余为占位值(服务层 fail-closed)。
依赖:it2c3d4e5f6a7 为当前 head。
逻辑:带 'in_transit_to_hub' 默认值的追加列,存量 Run 归类型 1(与原行为一致);
downgrade 直接删列。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt3d4e5f6a7b'
down_revision = 'it2c3d4e5f6a7'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""调拨 Run 表加调拨业务类型列(存量数据默认归在途仓至HUB仓)。"""
op.add_column(
'transfer_runs',
sa.Column('transfer_type', sa.String(length=32), nullable=False,
server_default='in_transit_to_hub', comment='调拨业务类型(in_transit_to_hub/hub_repair_out/hub_to_hub)'),
)
op.create_check_constraint(
'ck_transfer_runs_transfer_type',
'transfer_runs',
"transfer_type IN ('in_transit_to_hub', 'hub_repair_out', 'hub_to_hub')",
)
def downgrade() -> None:
"""回滚:删除检查约束与列(存量数据随列丢弃,无其他依赖)。"""
op.drop_constraint('ck_transfer_runs_transfer_type', 'transfer_runs', type_='check')
op.drop_column('transfer_runs', 'transfer_type')
@@ -0,0 +1,136 @@
"""
backend/migrations/versions/vc4e5f6a7b8c_seed_voucher_po_print_schedule.py
用途:写入立账凭证 PO 订单生成周批(周二 05:00),早于检核周批(06:00)。
依赖:Alembic revision vc3d4e5f6a7b;schedule_tasks / users 已存在。
逻辑:有用户则插入 SCH-ACCOUNTING-VOUCHER-PO-PRINT;无用户时跳过,由应用钩子补建。
企微接收人尽量从检核排程复制。downgrade 只删本 schedule_no。
Revision ID: vc4e5f6a7b8c
Revises: vc3d4e5f6a7b
Create Date: 2026-09-14 19:40:00.000000
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
import sqlalchemy as sa
from alembic import op
revision = "vc4e5f6a7b8c"
down_revision = "vc3d4e5f6a7b"
branch_labels = None
depends_on = None
_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-PO-PRINT"
_CRON_EXPR = "0 5 * * 2"
_TZ_NAME = "Asia/Shanghai"
_JOB_PARAMS = {
"profile_code": "sales",
"scope_code": "HXJM",
"notify_failure_enabled": True,
}
def _compute_next_run_at_utc_naive() -> datetime:
"""按周二 05:00 Asia/Shanghai 计算下次执行,返回 UTC naive。"""
try:
from croniter import croniter
from zoneinfo import ZoneInfo
tz = ZoneInfo(_TZ_NAME)
base = datetime.now(tz)
next_local = croniter(_CRON_EXPR, base).get_next(datetime)
if next_local.tzinfo is None:
next_local = next_local.replace(tzinfo=tz)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
except Exception:
tz = timezone(timedelta(hours=8))
now_local = datetime.now(tz)
next_local = now_local.replace(hour=5, minute=0, second=0, microsecond=0)
while next_local <= now_local or next_local.weekday() != 1:
next_local = next_local + timedelta(days=1)
next_local = next_local.replace(hour=5, minute=0, second=0, microsecond=0)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
def upgrade() -> None:
conn = op.get_bind()
exists = conn.execute(
sa.text(
"SELECT 1 FROM schedule_tasks "
"WHERE schedule_no = :sno OR platform_api_path = 'accounting-voucher-po-print' "
"LIMIT 1"
),
{"sno": _SCHEDULE_NO},
).first()
if exists:
return
owner = conn.execute(
sa.text("SELECT id FROM users WHERE role = 'admin' ORDER BY id ASC LIMIT 1")
).first()
if owner is None:
owner = conn.execute(sa.text("SELECT id FROM users ORDER BY id ASC LIMIT 1")).first()
if owner is None:
return
notify_row = conn.execute(
sa.text(
"SELECT notify_user_ids_json FROM schedule_tasks "
"WHERE schedule_no = 'SCH-ACCOUNTING-VOUCHER-CHECK' "
" OR platform_api_path = 'accounting-voucher-check' "
"LIMIT 1"
)
).first()
notify_ids = notify_row[0] if notify_row and notify_row[0] is not None else []
if not isinstance(notify_ids, list):
notify_ids = []
now = datetime.utcnow()
next_run = _compute_next_run_at_utc_naive()
conn.execute(
sa.text(
"""
INSERT INTO schedule_tasks (
schedule_no, name, schedule_type, owner_user_id,
cron_expr, schedule_timezone, wait_seconds,
platform_api_path, job_params, notify_user_ids_json,
kb_sync_enabled, notify_enabled,
enabled, next_run_at, last_run_at,
created_by, updated_by, created_at, updated_at
) VALUES (
:schedule_no, :name, 'platform_job', :owner_user_id,
:cron_expr, 'Asia/Shanghai', 0,
'accounting-voucher-po-print', CAST(:job_params AS JSONB), CAST(:notify_ids AS JSONB),
false, true,
true, :next_run_at, NULL,
:owner_user_id, :owner_user_id, :now, :now
)
"""
).bindparams(
sa.bindparam("job_params", type_=sa.String()),
sa.bindparam("notify_ids", type_=sa.String()),
),
{
"schedule_no": _SCHEDULE_NO,
"name": "立账凭证 PO 订单生成(周批)",
"owner_user_id": int(owner[0]),
"cron_expr": _CRON_EXPR,
"job_params": json.dumps(_JOB_PARAMS, ensure_ascii=False),
"notify_ids": json.dumps(notify_ids, ensure_ascii=False),
"next_run_at": next_run,
"now": now,
},
)
def downgrade() -> None:
"""仅删除本迁移约定的 schedule_no,避免误删管理员手工创建的同路径排程。"""
conn = op.get_bind()
conn.execute(
sa.text("DELETE FROM schedule_tasks WHERE schedule_no = :sno"),
{"sno": _SCHEDULE_NO},
)
@@ -0,0 +1,97 @@
"""Seed voucher_check Chat Agent.
Revision ID: vc5f6a7b8c9d
Revises: cp9b0c1d2e3f
Create Date: 2026-09-16 13:30:00.000000
用途:为立账凭证检核注册 builtin Chat Agent。此前入口在工作台且仅 admin 可见,
没有独立功能权限键可迁移;普通用户需在用户管理授予该 Agent。
依赖:agents 表已存在。
逻辑:先按 agent_code 复用已有实例(含停用);没有则插入。插入前把 agents.id
序列对齐 MAX(id),避免本地库序列落后时撞主键。admin 仍按运行时角色看到
全部 Agent,不必写关联表。
"""
from __future__ import annotations
from alembic import op
from sqlalchemy import text
revision = "vc5f6a7b8c9d"
down_revision = "cp9b0c1d2e3f"
branch_labels = None
depends_on = None
AGENT_CODE = "voucher_check"
def _resync_agents_id_sequence() -> None:
"""把 agents 主键序列对齐现有最大 id,避免 nextval 撞上已占用主键。"""
bind = op.get_bind()
if bind.dialect.name != "postgresql":
return
op.execute(
"""
SELECT setval(
pg_get_serial_sequence('public.agents', 'id'),
COALESCE((SELECT MAX(id) FROM public.agents), 1),
true
)
"""
)
def upgrade() -> None:
"""插入或复用立账凭证检核 Agent。"""
conn = op.get_bind()
agent_id = conn.execute(
text(
"SELECT id FROM agents WHERE agent_code = :code "
"ORDER BY id ASC LIMIT 1"
),
{"code": AGENT_CODE},
).scalar()
if agent_id is not None:
conn.execute(
text(
"""
UPDATE agents
SET is_active = true,
runtime_provider = 'builtin',
conversation_mode = 'task_chat',
dify_app_type = 'chatflow',
updated_at = CURRENT_TIMESTAMP
WHERE id = :agent_id
"""
),
{"agent_id": agent_id},
)
return
_resync_agents_id_sequence()
conn.execute(
text(
"""
INSERT INTO agents (
name, description, type, is_active, is_aggregate,
agent_code, runtime_provider, conversation_mode, dify_app_type,
suggested_questions_style, sort_order, created_at, updated_at
) VALUES (
:name, :description, 'api', true, false,
:code, 'builtin', 'task_chat', 'chatflow',
'plain', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)
"""
),
{
"name": "立账凭证",
"description": "查看立账凭证检核任务、最近一次检核进度和企业微信发送记录。",
"code": AGENT_CODE,
},
)
def downgrade() -> None:
"""不删除已创建的 Agent 实例,以免误伤运营配置。"""
return
@@ -0,0 +1,40 @@
"""Add voucher_check_notify_configs.
Revision ID: vc6a7b8c9d0e
Revises: vc5f6a7b8c9d
Create Date: 2026-09-16 15:55:00.000000
用途:按业务方保存立账凭证缺件通知的文件类型接收人。
依赖:voucher_check 引擎表、users 表。
逻辑:与 Profile 版本解耦,换人不需要发版 file_rules。
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "vc6a7b8c9d0e"
down_revision = "vc5f6a7b8c9d"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增按文件类型配置企微接收人的表。"""
op.create_table(
"voucher_check_notify_configs",
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
sa.Column("profile_code", sa.String(length=32), nullable=False),
sa.Column("recipients_json", sa.JSON(), nullable=False),
sa.Column("updated_by", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint("profile_code", name="uq_voucher_check_notify_configs_profile"),
)
def downgrade() -> None:
"""删除按文件类型接收人配置表。"""
op.drop_table("voucher_check_notify_configs")