cosmo/backend/app/services/menu_service.py

74 lines
2.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""管理端菜单预置。
后台菜单是数据库驱动的(menus + role_menus),新页面加进前端路由后,
老库里不会出现对应菜单,新一套环境也缺导航入口,因此这里做一次幂等回填:
只补插按 name 判断仍缺失的菜单,并把它授权给已经能看到父菜单的角色。
管理端自己改过的标题、排序、图标一律不再改动。
"""
import logging
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.db import Menu, RoleMenu
logger = logging.getLogger(__name__)
# 需要存在的后台菜单;parent 为父菜单 name,同层按 sort_order 升序展示
ADMIN_MENUS: list[dict] = [
{
"name": "rocket_events",
"title": "火箭发射事件",
"icon": "rocket",
"path": "/admin/rocket-events",
"component": "admin/RocketEvents",
"parent": "data_management",
"sort_order": 6,
},
]
async def ensure_admin_menus(db: AsyncSession) -> list[str]:
"""补插缺失的管理端菜单,返回新入库的菜单 name 列表。"""
existing = set((await db.execute(select(Menu.name))).scalars().all())
missing = [item for item in ADMIN_MENUS if item["name"] not in existing]
if not missing:
return []
parents = {
menu.name: menu
for menu in (await db.execute(
select(Menu).where(Menu.name.in_({item["parent"] for item in missing}))
)).scalars().all()
}
added: list[str] = []
for item in missing:
parent = parents.get(item["parent"])
if parent is None:
logger.warning("菜单预置跳过 %s:找不到父菜单 %s", item["name"], item["parent"])
continue
menu = Menu(
parent_id=parent.id,
name=item["name"],
title=item["title"],
icon=item["icon"],
path=item["path"],
component=item["component"],
sort_order=item["sort_order"],
is_active=True,
)
db.add(menu)
await db.flush()
# 能看到父菜单的角色即可看到新页面
for role_id in (await db.execute(
select(RoleMenu.role_id).where(RoleMenu.menu_id == parent.id)
)).scalars().all():
db.add(RoleMenu(role_id=role_id, menu_id=menu.id))
added.append(item["name"])
if added:
await db.flush()
logger.info("管理端菜单预置补齐:%s", ", ".join(added))
return added