Merge pull request #30 from mizhexiaoxiao/dev

Dev
This commit is contained in:
mizhexiaoxiao 2024-05-30 15:20:50 +08:00 committed by GitHub
commit 9421a95bef
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 1168 additions and 333 deletions

View File

@ -10,7 +10,6 @@ from app.schemas.apis import *
router = APIRouter()
@router.get("/list", summary="查看API列表")
async def list_api(
page: int = Query(1, description="页码"),
@ -52,7 +51,7 @@ async def create_api(
async def update_api(
api_in: ApiUpdate,
):
await api_controller.update(id=api_in.id, obj_in=api_in.update_dict())
await api_controller.update(id=api_in.id, obj_in=api_in)
return Success(msg="Update Successfully")

View File

@ -16,13 +16,15 @@ async def list_menu(
page: int = Query(1, description="页码"),
page_size: int = Query(10, description="每页数量"),
):
parent_menus = await menu_controller.model.filter(parent_id=0).order_by("order")
res_menu = []
for menu in parent_menus:
child_menu = await menu_controller.model.filter(parent_id=menu.id).order_by("order")
async def get_menu_with_children(menu_id: int):
menu = await menu_controller.model.get(id=menu_id)
menu_dict = await menu.to_dict()
menu_dict["children"] = [await obj.to_dict() for obj in child_menu]
res_menu.append(menu_dict)
child_menus = await menu_controller.model.filter(parent_id=menu_id).order_by("order")
menu_dict["children"] = [await get_menu_with_children(child.id) for child in child_menus]
return menu_dict
parent_menus = await menu_controller.model.filter(parent_id=0).order_by("order")
res_menu = [await get_menu_with_children(menu.id) for menu in parent_menus]
return SuccessExtra(data=res_menu, total=len(res_menu), page=page, page_size=page_size)
@ -46,7 +48,7 @@ async def create_menu(
async def update_menu(
menu_in: MenuUpdate,
):
await menu_controller.update(id=menu_in.id, obj_in=menu_in.update_dict())
await menu_controller.update(id=menu_in.id, obj_in=menu_in)
return Success(msg="Updated Success")

View File

@ -47,7 +47,7 @@ async def create_role(role_in: RoleCreate):
@router.post("/update", summary="更新角色")
async def update_role(role_in: RoleUpdate):
await role_controller.update(id=role_in.id, obj_in=role_in.update_dict())
await role_controller.update(id=role_in.id, obj_in=role_in)
return Success(msg="Updated Successfully")

View File

@ -5,7 +5,6 @@ from fastapi.exceptions import HTTPException
from tortoise.expressions import Q
from app.controllers.user import UserController
from app.core.dependency import DependPermisson
from app.schemas.base import Success, SuccessExtra
from app.schemas.users import *
from app.controllers.dept import dept_controller
@ -62,7 +61,7 @@ async def create_user(
detail="The user with this email already exists in the system.",
)
new_user = await user_controller.create(obj_in=user_in)
await user_controller.update_roles(new_user, user_in.roles)
await user_controller.update_roles(new_user, user_in.role_ids)
return Success(msg="Created Successfully")
@ -72,7 +71,7 @@ async def update_user(
):
user_controller = UserController()
user = await user_controller.update(obj_in=user_in)
await user_controller.update_roles(user, user_in.roles)
await user_controller.update_roles(user, user_in.role_ids)
return Success(msg="Updated Successfully")

View File

@ -28,7 +28,7 @@ class UserController(CRUDBase[User, UserCreate, UserUpdate]):
return obj
async def update(self, obj_in: UserUpdate) -> User:
return await super().update(id=obj_in.id, obj_in=obj_in.update_dict())
return await super().update(id=obj_in.id, obj_in=obj_in)
async def update_last_login(self, id: int) -> None:
user = await self.model.get(id=id)
@ -46,9 +46,9 @@ class UserController(CRUDBase[User, UserCreate, UserUpdate]):
raise HTTPException(status_code=400, detail="用户已被禁用")
return user
async def update_roles(self, user: User, roles: List[int]) -> None:
async def update_roles(self, user: User, role_ids: List[int]) -> None:
await user.roles.clear()
for role_id in roles:
for role_id in role_ids:
role_obj = await role_controller.get(id=role_id)
await user.roles.add(role_obj)

View File

@ -34,7 +34,7 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
if isinstance(obj_in, Dict):
obj_dict = obj_in
else:
obj_dict = obj_in.model_dump(exclude_unset=True)
obj_dict = obj_in.model_dump(exclude_unset=True, exclude={"id"})
obj = await self.get(id=id)
obj = obj.update_from_dict(obj_dict)
await obj.save()

View File

@ -80,7 +80,7 @@ async def init_menus():
parent_menu = await Menu.create(
menu_type=MenuType.CATALOG,
name="系统管理",
path="system",
path="/system",
order=1,
parent_id=0,
icon="carbon:gui-management",
@ -134,5 +134,39 @@ async def init_menus():
component="/system/api",
keepalive=True,
),
Menu(
menu_type=MenuType.MENU,
name="部门管理",
path="dept",
order=5,
parent_id=parent_menu.id,
icon="mingcute:department-line",
is_hidden=False,
component="/system/dept",
keepalive=True,
),
]
await Menu.bulk_create(children_menu)
parent_menu = await Menu.create(
menu_type=MenuType.CATALOG,
name="一级菜单",
path="/",
order=2,
parent_id=0,
icon="mdi-fan-speed-1",
is_hidden=False,
component="Layout",
keepalive=True,
redirect="",
)
await Menu.create(
menu_type=MenuType.MENU,
name="一级菜单",
path="top-menu",
order=1,
parent_id=parent_menu.id,
icon="mdi-fan-speed-1",
is_hidden=False,
component="/top-menu",
keepalive=True,
)

View File

@ -1,2 +1,2 @@
# 新增model需要在这里导入
from .admin import *
from .admin import *

View File

@ -1,3 +1,4 @@
import asyncio
from datetime import datetime
from tortoise import fields, models
@ -20,18 +21,18 @@ class BaseModel(models.Model):
value = value.strftime(settings.DATETIME_FORMAT)
d[field] = value
if m2m:
for field in self._meta.m2m_fields:
if field not in exclude_fields:
values = [value for value in await getattr(self, field).all().values()]
for value in values:
value.update(
(k, v.strftime(settings.DATETIME_FORMAT))
for k, v in value.items()
if isinstance(v, datetime)
)
d[field] = values
tasks = [self.__fetch_m2m_field(field) for field in self._meta.m2m_fields if field not in exclude_fields]
results = await asyncio.gather(*tasks)
for field, values in results:
d[field] = values
return d
async def __fetch_m2m_field(self, field):
values = [value for value in await getattr(self, field).all().values()]
for value in values:
value.update((k, v.strftime(settings.DATETIME_FORMAT)) for k, v in value.items() if isinstance(v, datetime))
return field, values
class Meta:
abstract = True

View File

@ -1,4 +1,4 @@
from enum import Enum
from enum import Enum, StrEnum
class EnumBase(Enum):
@ -11,14 +11,6 @@ class EnumBase(Enum):
return [name for name in cls._member_names_]
class IntEnum(int, EnumBase):
...
class StrEnum(str, EnumBase):
...
class MethodType(StrEnum):
GET = "GET"
POST = "POST"

View File

@ -16,6 +16,3 @@ class ApiCreate(BaseApi):
class ApiUpdate(BaseApi):
id: int
def update_dict(self):
return self.model_dump(exclude_unset=True, exclude={"id"})

View File

@ -1,10 +1,10 @@
from enum import Enum
from enum import StrEnum
from typing import Optional
from pydantic import BaseModel, Field
class MenuType(str, Enum):
class MenuType(StrEnum):
CATALOG = "catalog" # 目录
MENU = "menu" # 菜单
@ -50,6 +50,3 @@ class MenuUpdate(BaseModel):
component: str = Field(example="/system/user")
keepalive: Optional[bool] = False
redirect: Optional[str] = ""
def update_dict(self):
return self.model_dump(exclude_unset=True, exclude={"id"})

View File

@ -25,9 +25,6 @@ class RoleUpdate(BaseModel):
name: str = Field(example="管理员")
desc: str = Field("", example="管理员角色")
def update_dict(self):
return self.model_dump(exclude_unset=True, exclude={"id"})
class RoleUpdateMenusApis(BaseModel):
id: int

View File

@ -22,11 +22,11 @@ class UserCreate(BaseModel):
password: str = Field(example="123456")
is_active: Optional[bool] = True
is_superuser: Optional[bool] = False
roles: Optional[List[int]] = []
role_ids: Optional[List[int]] = []
dept_id: Optional[int] = Field(0, description="部门ID")
def create_dict(self):
return self.model_dump(exclude_unset=True, exclude={"roles"})
return self.model_dump(exclude_unset=True, exclude={"role_ids"})
class UserUpdate(BaseModel):
@ -35,12 +35,9 @@ class UserUpdate(BaseModel):
username: str
is_active: Optional[bool] = True
is_superuser: Optional[bool] = False
roles: Optional[List[int]] = []
role_ids: Optional[List[int]] = []
dept_id: Optional[int] = 0
def update_dict(self):
return self.model_dump(exclude_unset=True, exclude={"roles", "id"})
class UpdatePassword(BaseModel):
id: int = Field(description="用户ID")

1295
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -7,10 +7,10 @@ readme = "README.md"
[tool.poetry.dependencies]
python = "^3.11"
fastapi = "^0.100.0"
uvicorn = "^0.23.1"
tortoise-orm = "^0.19.3"
pydantic = "^2.3.0"
fastapi = "0.111.0"
uvicorn = "^0.23.0"
tortoise-orm = "^0.20.1"
pydantic = "^2.7.1"
email-validator = "^2.0.0.post2"
passlib = "^1.7.4"
pyjwt = "^2.7.0"
@ -20,6 +20,9 @@ ruff = "^0.0.281"
loguru = "^0.7.0"
pydantic-settings = "^2.0.3"
argon2-cffi = "^23.1.0"
pydantic-core = "^2.18.2"
annotated-types = "^0.6.0"
setuptools = "^70.0.0"
[tool.black]
line-length = 120

View File

@ -8,7 +8,7 @@ import api from '@/api'
function buildRoutes(routes = []) {
return routes.map((e) => ({
name: e.name,
path: e.component !== 'Layout' ? '/' : '/' + e.path, // 处理目录是一级菜单的情况
path: e.path, // 处理目录是一级菜单的情况
component: shallowRef(Layout), // ? 不使用 shallowRef 控制台会有 warning
isHidden: e.is_hidden,
redirect: e.redirect,

View File

@ -135,9 +135,9 @@ const columns = [
handleAdd()
},
},
{ default: () => '子菜单', icon: renderIcon('material-symbols:add', { size: 16 }) },
{ default: () => '子菜单', icon: renderIcon('material-symbols:add', { size: 16 }) }
),
[[vPermission, 'post/api/v1/menu/create']],
[[vPermission, 'post/api/v1/menu/create']]
),
withDirectives(
h(
@ -154,9 +154,9 @@ const columns = [
{
default: () => '编辑',
icon: renderIcon('material-symbols:edit-outline', { size: 16 }),
},
}
),
[[vPermission, 'post/api/v1/menu/update']],
[[vPermission, 'post/api/v1/menu/update']]
),
h(
NPopconfirm,
@ -177,12 +177,12 @@ const columns = [
{
default: () => '删除',
icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
},
}
),
[[vPermission, 'delete/api/v1/menu/delete']],
[[vPermission, 'delete/api/v1/menu/delete']]
),
default: () => h('div', {}, '确定删除该菜单吗?'),
},
}
),
]
},

View File

@ -66,21 +66,6 @@ onMounted(() => {
})
const columns = [
{
title: '头像',
key: 'avatar',
width: 50,
align: 'center',
render(row) {
return h(NImage, {
height: 50,
imgProps: { style: { 'border-radius': '3px' } },
src: row.avatar,
'fallback-src': 'http://dummyimage.com/400x400', //
'show-toolbar-tooltip': true,
})
},
},
{
title: '名称',
key: 'username',
@ -180,10 +165,10 @@ const columns = [
type: 'primary',
style: 'margin-right: 8px;',
onClick: () => {
// roles => role_ids
handleEdit(row)
modalForm.value.dept_id = row.dept?.id
modalForm.value.roles = row.roles.map((e) => (e = e.id))
modalForm.value.role_ids = row.roles.map((e) => (e = e.id))
delete modalForm.value.dept
},
},
{
@ -238,7 +223,7 @@ async function handleUpdateDisable(row) {
row.roles.forEach((e) => {
role_ids.push(e.id)
})
row.roles = role_ids
row.role_ids = role_ids
row.dept_id = row.dept?.id
try {
await api.updateUser(row)
@ -252,12 +237,20 @@ async function handleUpdateDisable(row) {
}
}
let lastClickedNodeId = null
const nodeProps = ({ option }) => {
return {
onClick() {
api.getUserList({ dept_id: option.id }).then((res) => {
$table.value.tableData = res.data
})
if (lastClickedNodeId === option.id) {
$table.value?.handleSearch()
lastClickedNodeId = null
} else {
api.getUserList({ dept_id: option.id }).then((res) => {
$table.value.tableData = res.data
lastClickedNodeId = option.id
})
}
},
}
}
@ -325,8 +318,14 @@ const validateAddUser = {
<template>
<NLayout has-sider wh-full>
<NLayoutSider bordered content-style="padding: 24px;">
<h1>部门管理</h1>
<NLayoutSider
bordered
content-style="padding: 24px;"
:collapsed-width="0"
:width="240"
show-trigger="arrow-circle"
>
<h1>部门列表</h1>
<br />
<NTree
block-line
@ -413,8 +412,8 @@ const validateAddUser = {
placeholder="请确认密码"
/>
</NFormItem>
<NFormItem label="角色" path="roles">
<NCheckboxGroup v-model:value="modalForm.roles">
<NFormItem label="角色" path="role_ids">
<NCheckboxGroup v-model:value="modalForm.role_ids">
<NSpace item-style="display: flex;">
<NCheckbox
v-for="item in roleOption"

View File

@ -0,0 +1,5 @@
<template>
<AppPage>
<h1>一级菜单</h1>
</AppPage>
</template>