fix: 切换角色&更新角色菜单回显

This commit is contained in:
zy7y
2022-09-16 17:37:24 +08:00
parent 7ba3f23684
commit 8e725d3f78
16 changed files with 201 additions and 141 deletions

View File

@@ -1,18 +1,13 @@
from fastapi import Query
from core.utils import list_to_tree
from dbhelper.menu import del_menu, get_menus, get_tree_menu, insert_menu, put_menu
from schemas import ListAll, MenuIn, MenuRead, Response
from dbhelper.menu import del_menu, get_tree_menu, insert_menu, put_menu
from schemas import MenuIn, MenuRead, Response
async def menu_add(data: MenuIn) -> Response[MenuRead]:
return Response(data=await insert_menu(data))
async def menu_arr(
offset: int = Query(default=1, description="偏移量"),
limit: int = Query(default=10, description="数量"),
) -> Response:
async def menu_arr() -> Response:
menus = await get_tree_menu()
return Response(data=list_to_tree(menus))

View File

@@ -3,7 +3,7 @@ import json
from fastapi import Query
from core.utils import list_to_tree
from dbhelper.relation import role_assigned_menu
from dbhelper.menu import get_menu
from dbhelper.role import (
del_role,
get_role,
@@ -12,7 +12,7 @@ from dbhelper.role import (
new_role,
put_role,
)
from schemas import ListAll, Response, RoleIn, RoleInfo, RoleMenuIn, RoleQuery, RoleRead
from schemas import ListAll, Response, RoleIn, RoleInfo, RoleQuery, RoleRead
async def role_add(data: RoleIn) -> Response[RoleInfo]:
@@ -40,15 +40,6 @@ async def role_arr(
return Response(data=ListAll(total=count, items=roles))
async def assigned_menu(data: RoleMenuIn) -> Response:
"""分配菜单给角色"""
if await get_role({"id": data.rid, "status__not": 9}) is None:
return Response(code=400, msg="角色不存在")
if isinstance(await role_assigned_menu(data), int):
return Response(code=400, msg=f"菜单不存在")
return Response()
async def role_del(pk: int) -> Response:
if await del_role(pk) == 0:
return Response(code=400, msg="角色不存在")
@@ -57,6 +48,14 @@ async def role_del(pk: int) -> Response:
async def role_put(pk: int, data: RoleIn) -> Response:
"""更新角色"""
print(await get_role({"id": pk}))
if await get_role({"id": pk}) is None:
return Response(code=400, msg="角色不存在")
# 如果不为ture -> 有菜单id不存在
if not all([await get_menu({"id": mid}) for mid in data.menus]):
return Response(code=400, msg="菜单不存在")
if await put_role(pk, data) == 0:
return Response(code=400, msg="角色不存在")
return Response()

View File

@@ -68,6 +68,11 @@ async def del_role(rid: int):
return await RoleModel.filter(id=rid).update(status=9)
async def put_role(pk: int, data):
"""更新角色"""
return await RoleModel.filter(id=pk).update(**data.dict())
async def put_role(pk, data):
"""更新角色 菜单"""
await RoleModel.filter(id=pk).update(name=data.name, remark=data.remark)
await RoleMenuModel.filter(rid=pk).update(status=9)
await RoleMenuModel.bulk_create(
[RoleMenuModel(rid=pk, mid=mid) for mid in data.menus]
)

View File

@@ -23,11 +23,11 @@ async def get_user_info(user: UserModel):
根据id查用户角色列表 按激活角色倒序显示
"""
db = connections.get("default")
# 查角色表 用户角色表中 角色状态 = 1 关联表中 状态 != 9 为有效角色
sql_result = await db.execute_query_dict(
"""
select r.id, r.name, ur.status from sys_role as r
left join sys_user_role as ur on r.id = ur.rid where
ur.uid = (?) and ur.status != 9 and r.status != 9 order by ur.status desc
select r.id, r.name, ur.status from sys_role as r , sys_user_role as ur where r.id = ur.rid and
ur.uid = (?) and r.status = 1 and ur.status !=9 order by ur.status desc
""",
[user.id],
)
@@ -65,7 +65,7 @@ async def insert_user(user, roles):
# 创建用户
obj = await UserModel.create(**user.dict())
# 已有角色 关联 角色id 和是否选中状态
await UserRoleModel.bulk_create(
[UserRoleModel(rid=role.rid, uid=obj.id, status=role.status) for role in roles]
)
@@ -81,8 +81,8 @@ async def put_user(uid: int, data: UserPut):
"""更新用户"""
from core.security import get_password_hash
roles = data.rids
del data.rids
roles = data.roles
del data.roles
for role in roles:
if await get_role({"id": role.rid, "status__not": 9}) is None:
return role.rid
@@ -96,13 +96,27 @@ async def put_user(uid: int, data: UserPut):
# todo 1. 先前有的角色,这次更新成没有 2. 先前没有的角色 这次更新成有, 3. 只更新了状态
db = connections.get("default")
# 1. 先把所有数据做删除
await db.execute_query_dict(
# 1. 先把用户有的角色做删除
has_roles = await db.execute_query_dict(
"""
update sys_user_role set status = 9 where uid = (?)
select r.id from sys_role as r , sys_user_role as ur where r.id = ur.rid and
ur.uid = (?) and r.status = 1 and ur.status !=9
""",
[uid],
)
print(has_roles)
# 2. 将先有的数据标记 删除
[
await db.execute_query_dict(
"""
update sys_user_role set status = 9 where rid = (?)
""",
[role["id"]],
)
for role in has_roles
]
# 2. 新增次此更新的数据
await UserRoleModel.bulk_create(
[UserRoleModel(uid=uid, **role.dict()) for role in roles]

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -5,7 +5,6 @@ from fastapi import Depends, routing
from controller.common import about, login
from controller.menu import menu_add, menu_arr, menu_del, menu_put
from controller.role import (
assigned_menu,
role_add,
role_arr,
role_del,
@@ -122,6 +121,7 @@ class Route(routing.APIRoute):
has_perm = {"dependencies": [Depends(check_permissions)]}
# has_perm = {}
routes = [
Route.post("/login", endpoint=login, tags=["公共"], summary="登录"),
@@ -163,13 +163,6 @@ routes = [
Route.post(
"/role/query", endpoint=role_query, tags=["角色管理"], summary="角色条件查询", **has_perm
),
Route.post(
"/role/assigned/menu",
endpoint=assigned_menu,
tags=["角色管理"],
summary="角色分配菜单",
**has_perm
),
# 菜单新增
Route.get("/menu", endpoint=menu_arr, tags=["菜单管理"], summary="菜单列表", **has_perm),
Route.post("/menu", endpoint=menu_add, tags=["菜单管理"], summary="菜单新增", **has_perm),

View File

@@ -66,4 +66,4 @@ class UserPut(BaseModel):
nickname: str = Field(..., description="用户昵称")
password: str = Field(..., description="密码")
rids: list[RoleActive] = Field(..., description="选择角色列表")
roles: list[RoleActive] = Field(..., description="选择角色列表")

View File

@@ -3,42 +3,13 @@ import requests as client
from core.log import logger
from schemas.menu import MenuIn
from schemas.role import RoleIn, RoleMenuIn
from schemas.role import RoleIn
from schemas.user import RoleActive, UserAdd
base = "http://localhost:8000"
params = [
# 创建角色
("/role", RoleIn(name="super", remark="全部权限").dict()),
("/role", RoleIn(name="user", remark="用户权限").dict()),
# 创建用户
(
"/user",
UserAdd(
username="admin",
nickname="管理员",
password="123456",
rids=[
RoleActive(rid=1, status=5),
RoleActive(rid=2),
],
).dict(),
),
(
"/user",
UserAdd(
username="tester",
nickname="测试员",
password="123456",
rids=[
RoleActive(rid=2, status=5),
],
).dict(),
),
# 创建菜单
# 目录
(
"/menu",
MenuIn( # id 1
@@ -252,20 +223,6 @@ params = [
method="POST",
).dict(),
),
(
"/menu",
MenuIn(
name="分配权限",
meta={"icon": "Delete"},
path=None,
type=2,
component=None,
pid=4,
identifier="role:assign",
api="/role/assigned/menu",
method="POST",
).dict(),
),
(
"/menu",
MenuIn(
@@ -309,17 +266,41 @@ params = [
method="DELETE",
).dict(),
),
# 分配权限
]
datas = [
(
"/role/assigned/menu",
RoleMenuIn(rid=1, menus=[num for num in range(1, 20)]).dict(),
"/role",
RoleIn(
name="super",
remark="全部权限",
menus=[num for num in range(1, len(params) + 1)],
).dict(),
),
# 创建用户
(
"/user",
UserAdd(
username="admin",
nickname="管理员",
password="123456",
roles=[RoleActive(rid=1, status=5)],
).dict(),
),
("/role/assigned/menu", RoleMenuIn(rid=2, menus=[1, 3, 7, 8, 9, 11]).dict()),
]
@pytest.mark.parametrize("path, data", params)
def test_add_data(path, data):
"""注册菜单"""
res = client.post(url=base + path, json=data)
logger.info(res.json())
assert res.status_code == 200
@pytest.mark.parametrize("path, data", datas)
def test_add_user(path, data):
"""添加账号"""
res = client.post(url=base + path, json=data)
logger.info(res.json())
assert res.status_code == 200