feat(@vben/web-antd): 新增角色管理功能

This commit is contained in:
Kven 2025-05-08 22:02:59 +08:00
parent cf11f2cdf5
commit 139aa926be
7 changed files with 503 additions and 0 deletions

View File

@ -2,6 +2,7 @@ export * from './auth';
export * from './chatflow';
export * from './dept';
export * from './menu';
export * from './role';
export * from './server';
export * from './user';
export * from './workflow';

View File

@ -0,0 +1,56 @@
import { requestClient } from '#/api/request';
export namespace RoleApi {
export interface Role {
name: string;
dataScope: string;
permissionIds: (number | undefined)[];
remark: string;
authorities: (number | undefined)[];
id?: string;
}
// 基础信息
export interface RoleRecord extends Role {
id: string;
}
export interface RoleListRecord extends RoleRecord {
name: string;
}
}
// 查询所有的角色列表、
export function queryRoleList(data: any) {
// return axios.get('/api/rest/role',data);
return requestClient.get('/api/rest/role', { data });
}
// 切换启用状态
export function enabled(id: string) {
return requestClient.patch(`/api/rest/role/${id}/toggle`);
}
// 删除
export function removeRole(id: string) {
return requestClient.delete(`/api/rest/role/${id}`);
}
// 添加
export function createRole(data: RoleApi.Role) {
return requestClient.post(`/api/rest/role`, data);
}
// 更新
export function updateRole(data: RoleApi.RoleRecord) {
return requestClient.patch(`/api/rest/role/${data.id}`, data);
}
// 获取详情
export function getDetail(id: string) {
return requestClient.get<RoleApi.RoleRecord>(`/api/rest/role/${id}`);
}
// export function queryRoles(params?: ListParams<Partial<RoleRecord>>) {
// return queryList<RoleRecord>(`/api/rest/role/query`, params);
// }

View File

@ -0,0 +1,18 @@
import type { RouteRecordRaw } from 'vue-router';
import { EosRole } from '@vben/icons';
const routes: RouteRecordRaw[] = [
{
name: 'role',
path: '/role',
component: () => import('#/views/role/list.vue'),
meta: {
icon: EosRole,
title: '角色管理',
order: 5,
},
},
];
export default routes;

View File

@ -0,0 +1,127 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { RoleApi } from '#/api';
import { $t } from '#/locales';
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'name',
label: '角色名称',
rules: 'required',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: $t('common.enabled'), value: 1 },
{ label: $t('common.disabled'), value: 0 },
],
optionType: 'button',
},
defaultValue: 1,
fieldName: 'status',
label: '状态',
},
{
component: 'Textarea',
fieldName: 'remark',
label: '备注',
},
{
component: 'Input',
fieldName: 'permissions',
formItemClass: 'items-start',
label: '权限',
modelPropName: 'modelValue',
},
];
}
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'name',
label: '角色名称',
},
{ component: 'Input', fieldName: 'id', label: '角色ID' },
{
component: 'Select',
componentProps: {
allowClear: true,
options: [
{ label: $t('common.enabled'), value: 1 },
{ label: $t('common.disabled'), value: 0 },
],
},
fieldName: 'status',
label: '状态',
},
{
component: 'Input',
fieldName: 'remark',
label: '备注',
},
{
component: 'RangePicker',
fieldName: 'createTime',
label: '创建时间',
},
];
}
export function useColumns<T = RoleApi.Role>(
onActionClick: OnActionClickFn<T>,
onStatusChange?: (newStatus: any, row: T) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
return [
{
field: 'name',
title: '角色名称',
width: 200,
},
{
field: 'id',
title: '角色ID',
width: 200,
},
{
cellRender: {
attrs: { beforeChange: onStatusChange },
name: onStatusChange ? 'CellSwitch' : 'CellTag',
},
field: 'status',
title: '角色状态',
width: 100,
},
{
field: 'remark',
minWidth: 100,
title: '备注',
},
{
field: 'createTime',
title: '创建时间',
width: 200,
},
{
align: 'center',
cellRender: {
attrs: {
nameField: 'name',
nameTitle: $t('system.role.name'),
onClick: onActionClick,
},
name: 'CellOperation',
},
field: 'operation',
fixed: 'right',
title: '操作',
width: 130,
},
];
}

View File

@ -0,0 +1,161 @@
<script lang="ts" setup>
import type { Recordable } from '@vben/types';
import type {
OnActionClickParams,
VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { RoleApi } from '#/api';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';
import { Button, message, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { queryRoleList, removeRole, updateRole } from '#/api';
import { $t } from '#/locales';
import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const [FormDrawer, formDrawerApi] = useVbenDrawer({
connectedComponent: Form,
destroyOnClose: true,
});
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
fieldMappingTime: [['createTime', ['startTime', 'endTime']]],
schema: useGridFormSchema(),
submitOnChange: true,
},
gridOptions: {
columns: useColumns(onActionClick, onStatusChange),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await queryRoleList({
page: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
toolbarConfig: {
custom: true,
export: false,
refresh: { code: 'query' },
search: true,
zoom: true,
},
} as VxeTableGridOptions<RoleApi.Role>,
});
function onActionClick(e: OnActionClickParams<RoleApi.Role>) {
switch (e.code) {
case 'delete': {
onDelete(e.row);
break;
}
case 'edit': {
onEdit(e.row);
break;
}
}
}
/**
* 将Antd的Modal.confirm封装为promise方便在异步函数中调用
* @param content 提示内容
* @param title 提示标题
*/
function confirm(content: string, title: string) {
return new Promise((reslove, reject) => {
Modal.confirm({
content,
onCancel() {
reject(new Error('已取消'));
},
onOk() {
reslove(true);
},
title,
});
});
}
/**
* 状态开关即将改变
* @param newStatus 期望改变的状态值
* @param row 行数据
* @returns 返回false则中止改变返回其他值undefinedtrue则允许改变
*/
async function onStatusChange(newStatus: number, row: RoleApi.Role) {
const status: Recordable<string> = {
0: '禁用',
1: '启用',
};
try {
await confirm(
`你要将${row.name}的状态切换为 【${status[newStatus.toString()]}】 吗?`,
`切换状态`,
);
await updateRole(row.id, { status: newStatus });
return true;
} catch {
return false;
}
}
function onEdit(row: RoleApi.Role) {
formDrawerApi.setData(row).open();
}
function onDelete(row: RoleApi.Role) {
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting', [row.name]),
duration: 0,
key: 'action_process_msg',
});
removeRole(row.id)
.then(() => {
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
key: 'action_process_msg',
});
onRefresh();
})
.catch(() => {
hideLoading();
});
}
function onRefresh() {
gridApi.query();
}
function onCreate() {
formDrawerApi.setData({}).open();
}
</script>
<template>
<Page auto-content-height>
<FormDrawer />
<Grid table-title="角色列表">
<template #toolbar-tools>
<Button type="primary" @click="onCreate">
<Plus class="size-5" />
{{ $t('ui.actionTitle.create', ['角色']) }}
</Button>
</template>
</Grid>
</Page>
</template>

View File

@ -0,0 +1,139 @@
<script lang="ts" setup>
import type { DataNode } from 'ant-design-vue/es/tree';
import type { Recordable } from '@vben/types';
import type { RoleApi } from '#/api';
import { computed, ref } from 'vue';
import { useVbenDrawer, VbenTree } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { Spin } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
// import { getMenuList } from '#/api';
import { createRole, updateRole } from '#/api';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emits = defineEmits(['success']);
const formData = ref<RoleApi.SystemRole>();
const [Form, formApi] = useVbenForm({
schema: useFormSchema(),
showDefaultActions: false,
});
const permissions = ref<DataNode[]>([]);
const loadingPermissions = ref(false);
const id = ref();
const [Drawer, drawerApi] = useVbenDrawer({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) return;
const values = await formApi.getValues();
drawerApi.lock();
(id.value ? updateRole(id.value, values) : createRole(values))
.then(() => {
emits('success');
drawerApi.close();
})
.catch(() => {
drawerApi.unlock();
});
},
onOpenChange(isOpen) {
if (isOpen) {
const data = drawerApi.getData<RoleApi.SystemRole>();
formApi.resetForm();
if (data) {
formData.value = data;
id.value = data.id;
formApi.setValues(data);
} else {
id.value = undefined;
}
// if (permissions.value.length === 0) {
// loadPermissions();
// }
}
},
});
// async function loadPermissions() {
// loadingPermissions.value = true;
// try {
// const res = await getMenuList();
// permissions.value = res as unknown as DataNode[];
// } finally {
// loadingPermissions.value = false;
// }
// }
const getDrawerTitle = computed(() => {
return formData.value?.id
? $t('common.edit', '角色')
: $t('common.create', '角色');
});
function getNodeClass(node: Recordable<any>) {
const classes: string[] = [];
if (node.value?.type === 'button') {
classes.push('inline-flex');
if (node.index % 3 >= 1) {
classes.push('!pl-0');
}
}
return classes.join(' ');
}
</script>
<template>
<Drawer :title="getDrawerTitle">
<Form>
<template #permissions="slotProps">
<Spin :spinning="loadingPermissions" wrapper-class-name="w-full">
<VbenTree
:tree-data="permissions"
multiple
bordered
:default-expanded-level="2"
:get-node-class="getNodeClass"
v-bind="slotProps"
value-field="id"
label-field="meta.title"
icon-field="meta.icon"
>
<template #node="{ value }">
<IconifyIcon v-if="value.meta.icon" :icon="value.meta.icon" />
{{ $t(value.meta.title) }}
</template>
</VbenTree>
</Spin>
</template>
</Form>
</Drawer>
</template>
<style lang="css" scoped>
:deep(.ant-tree-title) {
.tree-actions {
display: none;
margin-left: 20px;
}
}
:deep(.ant-tree-title:hover) {
.tree-actions {
display: flex;
flex: auto;
justify-content: flex-end;
margin-left: 20px;
}
}
</style>

View File

@ -14,4 +14,5 @@ export const MdiChevron = createIconifyIcon('tabler:chevron-right');
export const MdiUser = createIconifyIcon('mdi:user');
export const MageRobot = createIconifyIcon('mage:robot');
export const RiDept = createIconifyIcon('ri:door-open-line');
export const EosRole = createIconifyIcon('eos-icons:role-binding-outlined');
// export const MdiUser = createIconifyIcon('mdi:user');