From 09829cb39e0ef784a8788c6247d779d943186455 Mon Sep 17 00:00:00 2001 From: "mula.liu" Date: Thu, 22 Oct 2026 16:06:18 +0800 Subject: [PATCH] v 0.1.1 --- README.md | 18 +++-- app/api/v1/system.py | 33 ++++++-- app/core/permissions.py | 44 +++++++++++ app/main.py | 22 ++++++ app/seed.py | 25 ++++++- app/services/seed_rbac.py | 51 ++++++++++++- scripts/deploy.sh | 1 + tests/test_rbac_sync.py | 133 +++++++++++++++++++++++++++++++++ web/src/pages/system/Roles.tsx | 31 ++++++-- 9 files changed, 339 insertions(+), 19 deletions(-) create mode 100644 tests/test_rbac_sync.py diff --git a/README.md b/README.md index cb42c8e..d45fcd2 100644 --- a/README.md +++ b/README.md @@ -277,7 +277,7 @@ Web 用 antd 表格 / 抽屉 / 表头筛选,H5 用卡片 / 胶囊 tab / `MChip **用户 → 角色 → 权限码 + 数据范围**,菜单由后端按权限下发(前端不做硬编码菜单)。 -- **权限码**:`module:resource:action`,共 **160** 个(`app/core/permissions.py` 是唯一事实来源, +- **权限码**:`module:resource:action`,共 **170** 个(`app/core/permissions.py` 是唯一事实来源, 播种进 `sys_permission`)。action ∈ `read / create / update / delete / import / export` 及业务动作(`approve`、`calculate`、`pay`…)。 - **数据范围**:`all > dept_tree > dept > self`,取用户所有角色的最大范围(`core/deps.py: SCOPE_RANK`); 列表查询通过 `apply_employee_scope()` 自动注入可见员工集合。 @@ -288,13 +288,19 @@ Web 用 antd 表格 / 抽屉 / 表头筛选,H5 用卡片 / 胶囊 tab / `MChip (`web/src/api/routePerms.ts` 维护「页面 URL → 所需 `:read` 权限码」对照表, 事实来源是 `services/seed_rbac.py` 的菜单定义;子路由如 `/employees/:id` 前缀继承父页面)。 - **7 个内置角色**:超级管理员 / HR 负责人 / 人事专员 / 招聘经理 / 薪酬福利专员 / 部门经理 / 普通员工, - 在 `/system/roles` 用权限树可视化调整并另存新角色。 -- **改了 `core/permissions.py` 必须重跑播种**:`./.venv/bin/python -m app.seed`, - 否则新权限码不会进 `sys_permission`,接口会持续 403(播种幂等,只补差异)。 + 在 `/system/roles` 用权限树可视化调整并另存新角色。权限树**模块与资源的顺序跟随主界面菜单** + (`permissions.py: menu_catalogue_order()` 从菜单树反解而来,不是另抄一份常量), + 工具条上的「全部收拢 / 全部展开」用于按模块整块勾选;超级管理员固定全权限,面板只读。 +- **RBAC 基线随启动自动同步**(升级发版不再需要手工播种):`services/seed_rbac.py: sync_rbac()` + 按 `permissions.py` 幂等补齐 `sys_permission` / `sys_menu` / 内置角色,并把超级管理员角色补齐到 + **全部权限点**(新增功能无需手工授权)。`app/main.py` 在 `AUTO_SEED=false` 时也会调用它, + 因此**只要重启一次服务,新菜单与新权限点就落库**;只想同步 RBAC、不动业务数据时用 + `./.venv/bin/python -m app.seed --rbac`(Docker:`./scripts/deploy.sh seed --rbac`)。 + 演示数据仍走 `python -m app.seed [--force|--fresh]`。 ### 4.1 角色 × 模块能力矩阵(当前播种结果) -权限码共 **160** 个:`employee` 26 · `recruitment` 27 · `payroll` 30 · `benefits` 27 · `selfservice` 15 · `org` 12 · `system` 23。 +权限码共 **170** 个:`payroll` 30 · `employee` 26 · `recruitment` 27 · `benefits` 27 · `system` 27 · `org` 18 · `selfservice` 15。 | 角色(演示账号) | 数据范围 | 人事档案 | 招聘 | 薪资 | 福利保险 | 员工自助 | 组织 | 系统 | 可见 Web 页面 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | @@ -548,7 +554,7 @@ cd web && npm run build # tsc --noEmit && vite build | 列表里的启停开关点下去却弹出「删除确认」 | 开关列被右侧固定的操作列盖住了:数据列不要写 `fixed:'left'`,「启用」列放最后(见 §9.3),`ResourceTable` 已按此规则重排列序 | | 切换 Tab / 首次进入某页整页白屏,控制台报 `Rendered more hooks than during the previous render` | `loading / error` 的早退写在了 `useState / useMemo` 之前,违反 Hooks 规则;把 hook 全部上移到早退之前(见 §9.2 红线) | | 抽屉首次打开控制台报 `useForm … not connected` | 在 onClick 里直接 `setFieldsValue`,改用 `useModalFormFill()`(见 §9.1) | -| 改完权限码一直 403 | 忘了重跑 `python -m app.seed`,`sys_permission` 里还没有新码 | +| 升级后新菜单看不见 / 授权页搜不到新权限码 / 一直 403 | `sys_permission`、`sys_menu` 里还没有这几行:重启服务(启动钩子会跑 `sync_rbac()`),或直接 `./.venv/bin/python -m app.seed --rbac`(只同步 RBAC,不动业务数据) | | 启动脚本报 `unbound variable`(变量名带乱码) | macOS 自带 bash 3.2 在 UTF-8 下会把紧跟变量的全角字符吞进变量名;脚本内已统一写成 `${VAR})`,新增中文提示时记得给变量加花括号 | | 普通员工登录总进 H5 | 外壳由**设备 + 站内显式偏好**决定,与账号无关:桌面浏览器应落 `/dashboard`;若曾被 H5 记住偏好,用侧栏 📱 按钮或 H5 的「💻 想用大屏版」卡切回(见 §3.5.1);也可在浏览器控制台执行 `localStorage.removeItem('unis-hrms-shell-mode')` 恢复跟随设备 | | Web 自助与 H5 模块对不上 | 三处事实来源必须同步:`web/src/self/manifest.ts`、`permissions.py` 两份菜单树、`SELF_LINKS`;跑 `pytest tests/test_self_parity.py` 定位漂移项 | diff --git a/app/api/v1/system.py b/app/api/v1/system.py index 6d09cca..940d329 100644 --- a/app/api/v1/system.py +++ b/app/api/v1/system.py @@ -11,7 +11,7 @@ from sqlalchemy import delete, func, select, update from ...core.deps import AuthContext, Session, apply_employee_scope, get_auth_context, require_perm from ...core.errors import AppError -from ...core.permissions import MODULES +from ...core.permissions import MODULES, menu_catalogue_order from ...core.security import hash_password from ..crud import CrudSpec, build_router from ...models.employee import Employee @@ -360,11 +360,9 @@ async def save_role_permissions( router.include_router(role_router) -@router.get("/permissions", summary="权限清单(按模块分组)") +@router.get("/permissions", summary="权限清单(按模块分组,顺序跟随主界面菜单)") async def permission_catalogue(session: Session, auth: AuthCtxDep): - rows = ( - await session.execute(select(Permission).order_by(Permission.module, Permission.resource)) - ).scalars().all() + rows = (await session.execute(select(Permission))).scalars().all() grouped: dict[str, dict] = {} for perm in rows: module_meta = MODULES.get(perm.module, {}) @@ -381,8 +379,31 @@ async def permission_catalogue(session: Session, auth: AuthCtxDep): resource["actions"].append({"id": perm.id, "code": perm.code, "name": perm.name, "action": perm.action}) for module in grouped.values(): + declared = MODULES.get(module["module"], {}).get("resources", {}) + for resource in module["resources"].values(): + actions = declared.get(resource["resource"], {}).get("actions", []) + # 权限点顺序 = 代码里声明的动作顺序(read/create/…),未登记的排末尾 + resource["actions"].sort( + key=lambda a: (actions.index(a["action"]) if a["action"] in actions else len(actions), + a["id"]), + ) module["resources"] = list(module["resources"].values()) - return {"modules": list(grouped.values()), "total": len(rows)} + # 角色授权页的树必须和左侧主菜单同序,否则「系统管理排在最上面」非常别扭。 + # 顺序的唯一来源是菜单树本身(menu_catalogue_order),不再按 module 字母排。 + module_order, resource_order = menu_catalogue_order() + rank = module_order.index + modules = sorted( + grouped.values(), + key=lambda m: (rank(m["module"]) if m["module"] in module_order else len(module_order), + m["module"]), + ) + for module in modules: + order = resource_order.get(module["module"], []) + module["resources"].sort( + key=lambda r: (order.index(r["resource"]) if r["resource"] in order else len(order), + r["resource"]), + ) + return {"modules": modules, "total": len(rows)} # ------------------------------------------------------------------ 菜单导航 diff --git a/app/core/permissions.py b/app/core/permissions.py index c888678..2c632bc 100644 --- a/app/core/permissions.py +++ b/app/core/permissions.py @@ -325,3 +325,47 @@ def role_matches(code: str, patterns: list[str]) -> bool: if all(a == "*" or a == b for a, b in zip(pp, parts)): return True return False + + +def menu_catalogue_order() -> tuple[list[str], dict[str, list[str]]]: + """权限清单的排序基准:**与主界面菜单一致**(模块顺序 → 模块内资源顺序)。 + + 排序不是再抄一份常量,而是从 ``MENU_TREE`` / ``MOBILE_MENU_TREE`` 里按出现顺序 + 解析 ``perm`` 得到,于是「菜单挪位置」和「角色授权页顺序」永远同步: + + * 只统计分组节点的子项:顶层的「工作台」是单页叶子,不代表一个模块分组; + * 菜单里没有的模块/资源(员工自助、纯接口权限点)按 ``MODULES`` 声明顺序补在后面。 + + 返回 ``(模块顺序, {模块: 资源顺序})``。 + """ + modules: list[str] = [] + resources: dict[str, list[str]] = {} + + def touch(code: object) -> None: + parts = str(code or "").split(":") + if len(parts) != 3: + return + module, resource = parts[0], parts[1] + if module not in MODULES: + return + if module not in modules: + modules.append(module) + bucket = resources.setdefault(module, []) + if resource not in bucket: + bucket.append(resource) + + for node in MENU_TREE: + for child in node.get("children") or []: + touch(child.get("perm")) + # H5 导航给出「员工自助」内部资源的顺序(请假/工资条/福利/我的…) + for node in MOBILE_MENU_TREE: + touch(node.get("perm")) + + for module_key, module in MODULES.items(): + if module_key not in modules: + modules.append(module_key) + bucket = resources.setdefault(module_key, []) + for res_key in module["resources"]: + if res_key not in bucket: + bucket.append(res_key) + return modules, resources diff --git a/app/main.py b/app/main.py index 0cecc5f..58c0bad 100644 --- a/app/main.py +++ b/app/main.py @@ -46,10 +46,32 @@ async def lifespan(app: FastAPI): pass await seed_all() log.info("seed data ready") + else: + # 升级发版后必须自动补齐 RBAC 基线(新权限点 + 新菜单),否则新功能页面 + # 在老环境里既看不见菜单、也无法授权 —— 这一步只写 sys_permission/sys_menu, + # 不碰任何业务数据,因此可以每次启动都跑。 + await _sync_rbac() yield await engine.dispose() +async def _sync_rbac() -> None: + from .services.seed_rbac import sync_rbac + + try: + report = await sync_rbac() + except Exception as exc: # pragma: no cover -- 表还没建等场景,不阻断启动 + log.warning("RBAC 同步跳过:%s", exc) + return + if report.get("new_permissions") or report.get("menus") or report.get("super_admin_grants"): + # 走 uvicorn 的 logger:项目自身 logger 是 INFO,默认日志级别下看不见, + # 而「升级后菜单没进来」最需要的就是启动日志里这一行确认。 + logging.getLogger("uvicorn.error").info( + "RBAC 同步:新增权限点 %s、菜单 %s、超管补授权 %s", + report.get("new_permissions"), report.get("menus"), report.get("super_admin_grants"), + ) + + def _mount_uploads(app: FastAPI) -> None: upload_root = Path(settings.upload_dir) upload_root.mkdir(parents=True, exist_ok=True) diff --git a/app/seed.py b/app/seed.py index ab9207f..df74bf0 100644 --- a/app/seed.py +++ b/app/seed.py @@ -1,7 +1,9 @@ #!/usr/bin/env python -"""播种入口:``./.venv/bin/python -m app.seed [--force|--fresh]`` +"""播种入口:``./.venv/bin/python -m app.seed [--rbac|--force|--fresh]`` * 无参数 幂等:已播种则跳过,只补缺失的权限/字典 +* ``--rbac`` **只同步 RBAC 基线**(权限点 / 内置角色 / 菜单 / 超管补授权), + 不写任何业务与演示数据 —— 生产升级发版后专用 * ``--force`` 强制补齐缺失数据 * ``--fresh`` 删表重建 + 重新播种(仅开发环境重置演示数据) """ @@ -40,8 +42,29 @@ async def prepare() -> None: await sync_schema(engine, is_sqlite=settings.is_sqlite) +def sync_rbac_only() -> int: + """只补 RBAC:升级后新菜单/新权限点落库,业务数据一行不动。""" + logging.basicConfig(level=logging.INFO, format="%(message)s") + + async def go() -> dict: + from app.core.config import settings + from app.services.seed_rbac import sync_rbac + + # 生产(AUTO_CREATE_SCHEMA=false)以 Alembic 迁移为准,不顺手改表结构 + if settings.auto_create_schema: + await prepare() + return await sync_rbac() + + report = asyncio.run(go()) + print(json.dumps(report, ensure_ascii=False, indent=2)) + print("✔ RBAC 基线已同步(权限点 / 菜单 / 内置角色),业务数据未改动") + return 0 + + def main() -> int: logging.basicConfig(level=logging.INFO, format="%(message)s") + if "--rbac" in sys.argv or "--rbac-only" in sys.argv: + return sync_rbac_only() force = "--force" in sys.argv or "--fresh" in sys.argv if "--fresh" in sys.argv: asyncio.run(rebuild()) diff --git a/app/services/seed_rbac.py b/app/services/seed_rbac.py index 771e7dc..577915e 100644 --- a/app/services/seed_rbac.py +++ b/app/services/seed_rbac.py @@ -95,8 +95,57 @@ async def run(session, *, force: bool = False) -> dict: created_perms = await seed_permissions(session) roles = await seed_roles(session) menus = await seed_menus(session) + grants = await grant_all_to_superuser_role(session) return {"permissions": await count(session, Permission), "new_permissions": created_perms, - "roles": await count(session, Role), "new_roles": roles, "menus": menus} + "roles": await count(session, Role), "new_roles": roles, "menus": menus, + "super_admin_grants": grants} + + +async def sync_rbac(session=None) -> dict: + """把代码里的 RBAC 事实来源(权限点 / 内置角色 / 菜单)同步进库,幂等、不写演示数据。 + + 升级发版时的经典事故:代码里新增了 `system:maintenance:*` 与「数据维护」菜单, + 但库里 `sys_permission` / `sys_menu` 没有这几行 —— 结果菜单看不见、 + 角色授权页也搜不到这个权限点,只能让人去手工跑播种脚本。 + + 因此这里与「播种演示数据」解耦:只补 RBAC 基线,可在每次启动无脑执行。 + ``session`` 省略时自开会话并提交,供应用启动钩子直接调用。 + """ + if session is not None: + return await run(session) + from ..db.session import SessionFactory + + async with SessionFactory() as owned: + report = await run(owned) + await owned.commit() + return report + + +async def grant_all_to_superuser_role(session) -> int: + """超级管理员角色 = 全部权限点(新增权限点自动纳入,避免每次发版手工勾选)。""" + role = (await session.execute(select(Role).where(Role.code == "super_admin"))).scalar_one_or_none() + if role is None: + return 0 + # join 权限表:历史上被删过的权限点会在关联表里留下孤立行, + # 不过滤会让 diff 失真(也顺手把这些脏行清掉,避免授权页计数对不上)。 + linked = {pid for (pid,) in (await session.execute( + select(RolePermission.permission_id) + .join(Permission, Permission.id == RolePermission.permission_id) + .where(RolePermission.role_id == role.id))).all()} + stale = (await session.execute( + select(RolePermission) + .outerjoin(Permission, Permission.id == RolePermission.permission_id) + .where(RolePermission.role_id == role.id, Permission.id.is_(None)) + )).scalars().all() + for row in stale: + await session.delete(row) + all_ids = [pid for (pid,) in (await session.execute(select(Permission.id))).all()] + missing = [pid for pid in all_ids if pid not in linked] + for pid in missing: + session.add(RolePermission(role_id=role.id, permission_id=pid)) + if missing: + await session.flush() + return len(missing) # ------------------------------------------------------------------ 账号 ---- diff --git a/scripts/deploy.sh b/scripts/deploy.sh index c1b4297..0bfbab1 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -11,6 +11,7 @@ # ./scripts/deploy.sh down 删除容器(数据仍在 ./data) # ./scripts/deploy.sh migrate 在容器内执行 alembic upgrade head # ./scripts/deploy.sh seed [args] 在容器内播种/补齐数据,如 seed --force +# ./scripts/deploy.sh seed --rbac 升级发版后只同步权限点/菜单(不动业务数据) # ./scripts/deploy.sh shell 进入容器 shell # ./scripts/deploy.sh backup SQLite 热备份到 data/backups/(不依赖 Docker) # ./scripts/deploy.sh mysql-up 启动内置 MySQL(profile mysql)并等就绪 diff --git a/tests/test_rbac_sync.py b/tests/test_rbac_sync.py new file mode 100644 index 0000000..5bb00e1 --- /dev/null +++ b/tests/test_rbac_sync.py @@ -0,0 +1,133 @@ +"""升级发版后的 RBAC 自动同步(新权限点 / 新菜单 / 超管补授权)+ 权限清单顺序。 + +对应线上事故:代码里加了「数据维护」菜单与 system:maintenance:* 权限点, +老库没这几行 → 菜单看不见、角色授权页也搜不到,只能手工跑播种脚本。 +""" + +from __future__ import annotations + +import asyncio + +from sqlalchemy import delete, func, select + +from app.core.permissions import build_permissions, menu_catalogue_order +from app.db.session import SessionFactory +from app.models.rbac import Menu, Permission, Role, RolePermission, User, UserRole + +API = "/api/v1" +NEW_CODES = ["system:maintenance:read", "system:maintenance:backup", "system:maintenance:purge"] + + +def test_start_up_sync_backfills_permissions_and_menus(client, admin): + """删掉新权限点 + 菜单,再走一次启动同步,必须自动补齐(含超管补授权)。""" + + async def scenario(): + async with SessionFactory() as session: + await session.execute(delete(Permission).where(Permission.code.in_(NEW_CODES))) + await session.execute(delete(Menu).where(Menu.path == "/system/maintenance")) + await session.commit() + await asyncio.sleep(0) + + async def resync(): + from app.services.seed_rbac import sync_rbac + + return await sync_rbac() + + async def assert_backfilled(report): + assert report["new_permissions"] >= len(NEW_CODES), report + assert report["menus"] >= 1, report + # 超管的授权由「* 模板」+ 兜底补齐共同保证:同步后必须等于全部权限点 + assert report["super_admin_grants"] >= 0, report + async with SessionFactory() as session: + codes = set((await session.execute( + select(Permission.code).where(Permission.code.in_(NEW_CODES)))).scalars().all()) + assert set(NEW_CODES) <= codes + menu = (await session.execute( + select(Menu).where(Menu.path == "/system/maintenance"))).scalar_one_or_none() + assert menu is not None and menu.perm_code == "system:maintenance:read" + # 超管角色本身也被补齐(不只是靠 is_superuser 兜底) + role_id = (await session.execute(select(Role.id).where(Role.code == "super_admin"))).one()[0] + total = (await session.execute(select(func.count()).select_from(Permission))).scalar() + linked = (await session.execute( + select(func.count()) + .select_from(RolePermission) + .join(Permission, Permission.id == RolePermission.permission_id) + .where(RolePermission.role_id == role_id) + )).scalar() + assert linked == total + + async def drop_super_admin_links(): + """造出「新权限点没授权给超管」的现场,验证兜底补齐本身可用。""" + async with SessionFactory() as session: + role_id = (await session.execute(select(Role.id).where(Role.code == "super_admin"))).one()[0] + await session.execute(delete(RolePermission).where(RolePermission.role_id == role_id)) + await session.commit() + + async def grant_all(): + from app.services.seed_rbac import grant_all_to_superuser_role + + async with SessionFactory() as session: + n = await grant_all_to_superuser_role(session) + await session.commit() + return n + + asyncio.run(scenario()) + # 模拟重启:应用启动钩子会调用同一个 sync_rbac() + report = asyncio.run(resync()) + asyncio.run(assert_backfilled(report)) + asyncio.run(_cleanup()) + asyncio.run(drop_super_admin_links()) + assert asyncio.run(grant_all()) >= len(NEW_CODES) + + # 菜单接口对超管可见;权限清单里能搜到新权限点(前端授权页据此渲染) + menus = client.get(f"{API}/auth/menus", params={"platform": "web"}, headers=admin).json() + system = next((m for m in menus if m["name"] == "系统管理"), None) + assert system and any(c["path"] == "/system/maintenance" for c in system["children"]) + catalogue = client.get(f"{API}/system/permissions", headers=admin).json() + codes = {a["code"] for m in catalogue["modules"] for r in m["resources"] for a in r["actions"]} + assert set(NEW_CODES) <= codes + + +async def _cleanup(): + """把删掉的行补回来,避免影响同一会话里的其它用例(如维护页表计数)。""" + from app.services.seed_rbac import sync_rbac + + await sync_rbac() + async with SessionFactory() as session: + admin_id = (await session.execute(select(User.id).where(User.username == "admin"))).one()[0] + role_id = (await session.execute(select(Role.id).where(Role.code == "super_admin"))).one()[0] + if not (await session.execute( + select(UserRole).where(UserRole.user_id == admin_id, UserRole.role_id == role_id) + )).scalar_one_or_none(): + session.add(UserRole(user_id=admin_id, role_id=role_id)) + await session.commit() + + +def test_permission_catalogue_follows_menu_order(client, admin): + """角色授权页右侧树的顺序必须与主界面菜单一致(模块 + 模块内资源)。""" + body = client.get(f"{API}/system/permissions", headers=admin).json() + modules = body["modules"] + module_order, resource_order = menu_catalogue_order() + + shown = [m["module"] for m in modules] + assert shown == [m for m in module_order if m in shown], shown + # 菜单里的主线模块必须成段出现:人事档案 → 招聘 → 薪资 → 福利 → 组织 → 系统 + mainline = ["employee", "recruitment", "payroll", "benefits", "org", "system"] + assert [m for m in shown if m in mainline] == mainline, shown + + for module in modules: + order = resource_order[module["module"]] + resources = [r["resource"] for r in module["resources"]] + assert resources == [r for r in order if r in resources], (module["module"], resources) + # 权限点顺序 = 声明顺序,read 永远在首位,前端不再出现「删除」排在「查看」上面 + for resource in module["resources"]: + assert resource["actions"][0]["action"] == "read", resource["resource"] + + +def test_every_permission_is_listed(client, admin): + """清单必须覆盖代码里声明的全部权限点:漏一条就等于「无法授权」。""" + body = client.get(f"{API}/system/permissions", headers=admin).json() + codes = {a["code"] for m in body["modules"] for r in m["resources"] for a in r["actions"]} + declared = {item.code for item in build_permissions()} + assert declared - codes == set() + assert body["total"] == len(codes) diff --git a/web/src/pages/system/Roles.tsx b/web/src/pages/system/Roles.tsx index 00ab4cb..cf95bd9 100644 --- a/web/src/pages/system/Roles.tsx +++ b/web/src/pages/system/Roles.tsx @@ -1,6 +1,9 @@ -import { CheckSquareOutlined, ClearOutlined, LockOutlined, SaveOutlined } from '@ant-design/icons' +import { + CheckSquareOutlined, ClearOutlined, LockOutlined, NodeCollapseOutlined, NodeExpandOutlined, + SaveOutlined, +} from '@ant-design/icons' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { App, Button, Card, Col, Input, Row, Select, Space, Spin, Tag, Tree, Typography } from 'antd' +import { App, Button, Card, Col, Input, Row, Select, Space, Spin, Tag, Tooltip, Tree, Typography } from 'antd' import type { DataNode } from 'antd/es/tree' import { useEffect, useMemo, useState } from 'react' import { get, put } from '../../api/http' @@ -118,6 +121,13 @@ export default function Roles() { }) return out }, [treeData]) + // 默认全展开;「全部收拢」后只剩模块行,勾一个模块即可整块授权。 + // 搜索中强制展开命中项,否则「收拢 + 搜索」会让人以为搜不到结果。 + const searching = !!keyword.trim() + const expandState = searching ? expandedKeys : manualExpand ?? expandedKeys + const allExpanded = searching || manualExpand === null || manualExpand.length >= expandedKeys.length + const collapseAll = () => setManualExpand([]) + const expandAll = () => setManualExpand(null) const save = useMutation({ mutationFn: (v: { permission_ids: number[]; data_scope: string }) => @@ -137,7 +147,9 @@ export default function Roles() { const toggleAll = (on: boolean) => setChecked(on ? leafIds : []) const selectedCount = checked.filter((c) => leafIds.includes(c)).length - const editable = hasPerm('system:role:assign') + // 超级管理员固定全权限(含发版后新增的权限点),面板只读展示,避免勾完保存被后端拒绝 + const fixedAll = active?.code === 'super_admin' + const editable = hasPerm('system:role:assign') && !fixedAll return ( @@ -208,7 +220,7 @@ export default function Roles() { {active.name} - 已授权 {selectedCount} / {totalAll} 个权限点 + {fixedAll ? '超级管理员固定拥有全部权限(含后续新增的功能),无需配置' : `已授权 ${selectedCount} / ${totalAll} 个权限点`} ) : ( @@ -237,6 +249,15 @@ export default function Roles() { + + +