"""Seed configurable permission roles. Revision ID: pr7b8c9d0e1f Revises: vc6a7b8c9d0e Create Date: 2026-09-17 13:30:00.000000 用途:新增 permission_roles / permission_role_agents;按现网 users.role 套标准包并重写授权。 依赖:users、agents、user_agent_permissions。 逻辑:user/hr/admin 映射内置组,另种子研发应用与货代专员;个人勾选的额外应用按确认策略丢弃。 不再种子设备维保专员。 """ from __future__ import annotations import json from datetime import datetime from alembic import op import sqlalchemy as sa from sqlalchemy import inspect revision = "pr7b8c9d0e1f" down_revision = "vc6a7b8c9d0e" branch_labels = None depends_on = None KNOWN_FEATURES = ( "training_hr_manage", "shipping_notice_force_create", "shipping_notice.audit_sensitive_read", "shipping_notice.xfa_split_rule_edit", "shipping_notice.xfa_split_rule_preview", "shipping_notice.xfa_split_rule_publish", "maintenance.ledger_write", ) def _content_profile(handler_config) -> str: raw = handler_config if isinstance(raw, str): try: raw = json.loads(raw) except Exception: raw = {} if not isinstance(raw, dict): return "" return str(raw.get("content_profile") or "").strip() def _matches(kind: str, agent_code: str, name: str, profile: str) -> bool: code = str(agent_code or "").strip() label = str(name or "") if kind == "entrance": return profile == "generic_entrance" if kind == "training": return profile == "training" if kind == "shipping": return code == "shipping_notice" if kind == "patent": return "专利" in label if kind == "maintenance": return "维保" in label or "维修" in label or code == "maintenance" return False def upgrade() -> None: """建表、加宽 users.role、种子权限组并按角色重写 user_agent_permissions。""" bind = op.get_bind() inspector = inspect(bind) tables = inspector.get_table_names() if "permission_roles" not in tables: op.create_table( "permission_roles", sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), sa.Column("code", sa.String(length=64), nullable=False), sa.Column("name", sa.String(length=100), nullable=False), sa.Column("description", sa.Text(), nullable=True), sa.Column("is_default", sa.Boolean(), nullable=False, server_default=sa.false()), sa.Column("is_system", sa.Boolean(), nullable=False, server_default=sa.false()), sa.Column("is_platform_admin", sa.Boolean(), nullable=False, server_default=sa.false()), sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"), sa.Column("feature_permissions", sa.JSON(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("updated_at", sa.DateTime(), nullable=False), sa.UniqueConstraint("code", name="uq_permission_roles_code"), ) op.create_index("ix_permission_roles_code", "permission_roles", ["code"]) if "permission_role_agents" not in tables: op.create_table( "permission_role_agents", sa.Column("role_id", sa.Integer(), sa.ForeignKey("permission_roles.id", ondelete="CASCADE"), primary_key=True), sa.Column("agent_id", sa.Integer(), sa.ForeignKey("agents.id", ondelete="CASCADE"), primary_key=True), ) user_columns = {col["name"]: col for col in inspector.get_columns("users")} role_col = user_columns.get("role") if role_col is not None: op.alter_column( "users", "role", existing_type=role_col["type"], type_=sa.String(length=64), existing_nullable=True, ) now = datetime.utcnow() roles = bind.execute(sa.text("SELECT code FROM permission_roles")).fetchall() existing = {row[0] for row in roles} seeds = [ ("user", "普通用户", "新建用户默认。勾通用入口即可使用企业知识库。", True, True, False, 10, {}, ("entrance",)), ("rd", "研发人员", "通用入口,以及研发侧应用(如专利)。", False, False, False, 20, {}, ("entrance", "patent")), ("hr", "培训 HR", "可进员工培训,并打开 HR 管理。", False, True, False, 30, {"training_hr_manage": True}, ("entrance", "training")), ("shipping", "货代专员", "聊天与工作台共用货代应用入口。", False, False, False, 40, {"shipping_notice_force_create": True}, ("entrance", "shipping")), ("admin", "管理员", "内置角色。应用入口隐式全开,可进入 /admin。", False, True, True, 90, {key: True for key in KNOWN_FEATURES}, ()), ] insert_role = sa.text( """ INSERT INTO permission_roles (code, name, description, is_default, is_system, is_platform_admin, sort_order, feature_permissions, created_at, updated_at) VALUES (:code, :name, :description, :is_default, :is_system, :is_platform_admin, :sort_order, :feature_permissions, :created_at, :updated_at) """ ).bindparams(sa.bindparam("feature_permissions", type_=sa.JSON())) for code, name, desc, is_default, is_system, is_admin, sort_order, features, _match in seeds: if code in existing: continue bind.execute( insert_role, { "code": code, "name": name, "description": desc, "is_default": is_default, "is_system": is_system, "is_platform_admin": is_admin, "sort_order": sort_order, "feature_permissions": features, "created_at": now, "updated_at": now, }, ) role_id_rows = bind.execute(sa.text("SELECT id, code FROM permission_roles")).fetchall() role_ids = {row[1]: row[0] for row in role_id_rows} agents = bind.execute( sa.text("SELECT id, name, agent_code, handler_config, is_active FROM agents") ).fetchall() active = [row for row in agents if bool(row[4])] def ids_for(*kinds: str) -> list[int]: found: list[int] = [] for row in active: profile = _content_profile(row[3]) for kind in kinds: if _matches(kind, row[2], row[1], profile): found.append(int(row[0])) break return found match_map = { "user": ("entrance",), "rd": ("entrance", "patent"), "hr": ("entrance", "training"), "shipping": ("entrance", "shipping"), "admin": (), } existing_links = { (int(row[0]), int(row[1])) for row in bind.execute(sa.text("SELECT role_id, agent_id FROM permission_role_agents")).fetchall() } insert_link = sa.text( "INSERT INTO permission_role_agents (role_id, agent_id) VALUES (:role_id, :agent_id)" ) for code, kinds in match_map.items(): role_id = role_ids.get(code) if not role_id: continue for agent_id in ids_for(*kinds): pair = (int(role_id), int(agent_id)) if pair in existing_links: continue bind.execute(insert_link, {"role_id": role_id, "agent_id": agent_id}) existing_links.add(pair) # 未知 role(含已废弃的 maintenance_manager)收口到默认普通用户。 bind.execute( sa.text( """ UPDATE users SET role = 'user' WHERE role IS NULL OR role NOT IN ('user', 'hr', 'admin', 'rd', 'shipping') """ ) ) empty_json = sa.text("UPDATE users SET feature_permissions = :empty").bindparams( sa.bindparam("empty", type_=sa.JSON()) ) bind.execute(empty_json, {"empty": {}}) # 非管理员:用角色包全量替换个人 Agent 勾选。 bind.execute(sa.text( """ DELETE FROM user_agent_permissions WHERE user_id IN (SELECT id FROM users WHERE role <> 'admin') """ )) bind.execute(sa.text( """ INSERT INTO user_agent_permissions (user_id, agent_id) SELECT u.id, pra.agent_id FROM users u JOIN permission_roles pr ON pr.code = u.role JOIN permission_role_agents pra ON pra.role_id = pr.id WHERE u.role <> 'admin' """ )) def downgrade() -> None: """删除权限组表;不回写已丢弃的个人 Agent 勾选。""" op.drop_table("permission_role_agents") op.drop_index("ix_permission_roles_code", table_name="permission_roles") op.drop_table("permission_roles") op.alter_column( "users", "role", existing_type=sa.String(length=64), type_=sa.String(length=20), existing_nullable=True, )