feat: add views

This commit is contained in:
xingyu4j
2025-11-11 15:24:41 +08:00
parent 10f2583e2f
commit 736d91019e
206 changed files with 30261 additions and 0 deletions

View File

@@ -0,0 +1,255 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import {
CommonStatusEnum,
DICT_TYPE,
SystemDataScopeEnum,
} from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { z } from '#/adapter/form';
import { getRangePickerDefaultProps } from '#/utils';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'name',
label: '角色名称',
component: 'Input',
rules: 'required',
},
{
fieldName: 'code',
label: '角色标识',
component: 'Input',
rules: 'required',
},
{
fieldName: 'sort',
label: '显示顺序',
component: 'InputNumber',
componentProps: {
min: 0,
placeholder: '请输入显示顺序',
},
rules: 'required',
},
{
fieldName: 'status',
label: '角色状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
buttonStyle: 'solid',
optionType: 'button',
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
{
fieldName: 'remark',
label: '角色备注',
component: 'Textarea',
},
];
}
/** 分配数据权限的表单 */
export function useAssignDataPermissionFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'name',
label: '角色名称',
component: 'Input',
componentProps: {
disabled: true,
},
},
{
component: 'Input',
fieldName: 'code',
label: '角色标识',
componentProps: {
disabled: true,
},
},
{
component: 'Select',
fieldName: 'dataScope',
label: '权限范围',
componentProps: {
options: getDictOptions(DICT_TYPE.SYSTEM_DATA_SCOPE, 'number'),
},
},
{
fieldName: 'dataScopeDeptIds',
label: '部门范围',
component: 'Input',
formItemClass: 'items-start',
dependencies: {
triggerFields: ['dataScope'],
show: (values) => {
return values.dataScope === SystemDataScopeEnum.DEPT_CUSTOM;
},
},
},
];
}
/** 分配菜单的表单 */
export function useAssignMenuFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'name',
label: '角色名称',
component: 'Input',
componentProps: {
disabled: true,
},
},
{
fieldName: 'code',
label: '角色标识',
component: 'Input',
componentProps: {
disabled: true,
},
},
{
fieldName: 'menuIds',
label: '菜单权限',
component: 'Input',
formItemClass: 'items-start',
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '角色名称',
component: 'Input',
componentProps: {
placeholder: '请输入角色名称',
allowClear: true,
},
},
{
fieldName: 'code',
label: '角色标识',
component: 'Input',
componentProps: {
placeholder: '请输入角色标识',
allowClear: true,
},
},
{
fieldName: 'status',
label: '角色状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择角色状态',
allowClear: true,
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'checkbox', width: 40 },
{
field: 'id',
title: '角色编号',
minWidth: 100,
},
{
field: 'name',
title: '角色名称',
minWidth: 200,
},
{
field: 'type',
title: '角色类型',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.SYSTEM_ROLE_TYPE },
},
},
{
field: 'code',
title: '角色标识',
minWidth: 200,
},
{
field: 'sort',
title: '显示顺序',
minWidth: 100,
},
{
field: 'remark',
title: '角色备注',
minWidth: 100,
},
{
field: 'status',
title: '角色状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 240,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,230 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemRoleApi } from '#/api/system/role';
import { ref } from 'vue';
import { confirm, DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';
import { message } from '#/adapter/tdesign';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteRole,
deleteRoleList,
exportRole,
getRolePage,
} from '#/api/system/role';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import AssignDataPermissionForm from './modules/assign-data-permission-form.vue';
import AssignMenuForm from './modules/assign-menu-form.vue';
import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [AssignDataPermissionFormModel, assignDataPermissionFormApi] =
useVbenModal({
connectedComponent: AssignDataPermissionForm,
destroyOnClose: true,
});
const [AssignMenuFormModel, assignMenuFormApi] = useVbenModal({
connectedComponent: AssignMenuForm,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 导出表格 */
async function handleExport() {
const data = await exportRole(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '角色.xls', source: data });
}
/** 创建角色 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑角色 */
function handleEdit(row: SystemRoleApi.Role) {
formModalApi.setData(row).open();
}
/** 删除角色 */
async function handleDelete(row: SystemRoleApi.Role) {
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting', [row.name]),
duration: 0,
});
try {
await deleteRole(row.id!);
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
message.close(hideLoading);
}
}
/** 批量删除角色 */
async function handleDeleteBatch() {
await confirm($t('ui.actionMessage.deleteBatchConfirm'));
const hideLoading = message.loading({
content: $t('ui.actionMessage.deletingBatch'),
duration: 0,
});
try {
await deleteRoleList(checkedIds.value);
checkedIds.value = [];
message.success($t('ui.actionMessage.deleteSuccess'));
handleRefresh();
} finally {
message.close(hideLoading);
}
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
records,
}: {
records: SystemRoleApi.Role[];
}) {
checkedIds.value = records.map((item) => item.id!);
}
/** 分配角色的数据权限 */
function handleAssignDataPermission(row: SystemRoleApi.Role) {
assignDataPermissionFormApi.setData(row).open();
}
/** 分配角色的菜单权限 */
function handleAssignMenu(row: SystemRoleApi.Role) {
assignMenuFormApi.setData(row).open();
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getRolePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<SystemRoleApi.Role>,
gridEvents: {
checkboxAll: handleRowCheckboxChange,
checkboxChange: handleRowCheckboxChange,
},
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert
title="功能权限"
url="https://doc.iocoder.cn/resource-permission"
/>
<DocAlert title="数据权限" url="https://doc.iocoder.cn/data-permission" />
</template>
<FormModal @success="handleRefresh" />
<AssignDataPermissionFormModel @success="handleRefresh" />
<AssignMenuFormModel @success="handleRefresh" />
<Grid table-title="角色列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['角色']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['system:role:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['system:role:export'],
onClick: handleExport,
},
{
label: $t('ui.actionTitle.deleteBatch'),
type: 'danger',
icon: ACTION_ICON.DELETE,
disabled: isEmpty(checkedIds),
auth: ['system:role:delete'],
onClick: handleDeleteBatch,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
variant: 'text',
icon: ACTION_ICON.EDIT,
auth: ['system:role:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
variant: 'text',
type: 'danger',
icon: ACTION_ICON.DELETE,
auth: ['system:role:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
:drop-down-actions="[
{
label: '数据权限',
variant: 'text',
auth: ['system:permission:assign-role-data-scope'],
onClick: handleAssignDataPermission.bind(null, row),
},
{
label: '菜单权限',
variant: 'text',
auth: ['system:permission:assign-role-menu'],
onClick: handleAssignMenu.bind(null, row),
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,166 @@
<script lang="ts" setup>
import type { SystemDeptApi } from '#/api/system/dept';
import type { SystemRoleApi } from '#/api/system/role';
import { ref } from 'vue';
import { Tree, useVbenModal } from '@vben/common-ui';
import { SystemDataScopeEnum } from '@vben/constants';
import { handleTree } from '@vben/utils';
import { Checkbox } from 'tdesign-vue-next';
import { message } from '#/adapter/tdesign';
import { useVbenForm } from '#/adapter/form';
import { getDeptList } from '#/api/system/dept';
import { assignRoleDataScope } from '#/api/system/permission';
import { getRole } from '#/api/system/role';
import { $t } from '#/locales';
import { useAssignDataPermissionFormSchema } from '../data';
const emit = defineEmits(['success']);
const deptTree = ref<SystemDeptApi.Dept[]>([]); // 部门树
const deptLoading = ref(false); // 加载部门列表
const isAllSelected = ref(false); // 全选状态
const isExpanded = ref(false); // 展开状态
const isCheckStrictly = ref(true); // 父子联动状态
const expandedKeys = ref<number[]>([]); // 展开的节点
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 80,
},
layout: 'horizontal',
schema: useAssignDataPermissionFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
const data = await formApi.getValues();
try {
await assignRoleDataScope({
roleId: data.id,
dataScope: data.dataScope,
dataScopeDeptIds:
data.dataScope === SystemDataScopeEnum.DEPT_CUSTOM
? data.dataScopeDeptIds
: undefined,
});
await modalApi.close();
emit('success');
message.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
return;
}
const data = modalApi.getData<SystemRoleApi.Role>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
// 加载部门列表
await loadDeptTree();
handleExpandAll();
// 设置表单值,一定要在加载树之后
await formApi.setValues(await getRole(data.id));
} finally {
modalApi.unlock();
}
},
});
/** 加载部门树 */
async function loadDeptTree() {
deptLoading.value = true;
try {
const data = await getDeptList();
deptTree.value = handleTree(data) as SystemDeptApi.Dept[];
} finally {
deptLoading.value = false;
}
}
/** 全选/全不选 */
function handleSelectAll() {
isAllSelected.value = !isAllSelected.value;
if (isAllSelected.value) {
const allIds = getAllNodeIds(deptTree.value);
formApi.setFieldValue('dataScopeDeptIds', allIds);
} else {
formApi.setFieldValue('dataScopeDeptIds', []);
}
}
/** 展开/折叠所有节点 */
function handleExpandAll() {
isExpanded.value = !isExpanded.value;
expandedKeys.value = isExpanded.value ? getAllNodeIds(deptTree.value) : [];
}
/** 切换父子联动 */
function handleCheckStrictly() {
isCheckStrictly.value = !isCheckStrictly.value;
}
/** 递归获取所有节点 ID */
function getAllNodeIds(nodes: any[], ids: number[] = []): number[] {
nodes.forEach((node: any) => {
ids.push(node.id);
if (node.children && node.children.length > 0) {
getAllNodeIds(node.children, ids);
}
});
return ids;
}
</script>
<template>
<Modal title="数据权限" class="w-2/5">
<Form class="mx-4">
<template #dataScopeDeptIds="slotProps">
<Spin :spinning="deptLoading" wrapper-class-name="w-full">
<Tree
:tree-data="deptTree"
multiple
bordered
:default-expanded-keys="expandedKeys"
v-bind="slotProps"
:check-strictly="!isCheckStrictly"
value-field="id"
label-field="name"
/>
</Spin>
</template>
</Form>
<template #prepend-footer>
<div class="flex flex-auto items-center">
<Checkbox :checked="isAllSelected" @change="handleSelectAll">
全选
</Checkbox>
<Checkbox :checked="isExpanded" @change="handleExpandAll">
全部展开
</Checkbox>
<Checkbox :checked="isCheckStrictly" @change="handleCheckStrictly">
父子联动
</Checkbox>
</div>
</template>
</Modal>
</template>

View File

@@ -0,0 +1,171 @@
<script lang="ts" setup>
import type { Recordable } from '@vben/types';
import type { SystemMenuApi } from '#/api/system/menu';
import type { SystemRoleApi } from '#/api/system/role';
import { nextTick, ref } from 'vue';
import { Tree, useVbenModal } from '@vben/common-ui';
import { SystemMenuTypeEnum } from '@vben/constants';
import { handleTree } from '@vben/utils';
import { Checkbox } from 'tdesign-vue-next';
import { message } from '#/adapter/tdesign';
import { useVbenForm } from '#/adapter/form';
import { getSimpleMenusList } from '#/api/system/menu';
import { assignRoleMenu, getRoleMenuList } from '#/api/system/permission';
import { $t } from '#/locales';
import { useAssignMenuFormSchema } from '../data';
const emit = defineEmits(['success']);
const menuTree = ref<SystemMenuApi.Menu[]>([]); // 菜单树
const menuLoading = ref(false); // 加载菜单列表
const isAllSelected = ref(false); // 全选状态
const isExpanded = ref(false); // 展开状态
const expandedKeys = ref<number[]>([]); // 展开的节点
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 80,
},
layout: 'horizontal',
schema: useAssignMenuFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = await formApi.getValues();
try {
await assignRoleMenu({
roleId: data.id,
menuIds: data.menuIds,
});
// 关闭并提示
await modalApi.close();
emit('success');
message.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
return;
}
// 加载菜单列表
await loadMenuTree();
const data = modalApi.getData<SystemRoleApi.Role>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
// 加载角色菜单
const menuIds = await getRoleMenuList(data.id);
await formApi.setFieldValue('menuIds', menuIds);
await formApi.setValues(data);
} finally {
await nextTick(); // 菜单过多,渲染较慢,需要等下一次事件循环
modalApi.unlock();
}
},
});
/** 加载菜单树 */
async function loadMenuTree() {
menuLoading.value = true;
try {
const data = await getSimpleMenusList();
menuTree.value = handleTree(data) as SystemMenuApi.Menu[];
} finally {
menuLoading.value = false;
}
}
/** 全选/全不选 */
function handleSelectAll() {
isAllSelected.value = !isAllSelected.value;
if (isAllSelected.value) {
const allIds = getAllNodeIds(menuTree.value);
formApi.setFieldValue('menuIds', allIds);
} else {
formApi.setFieldValue('menuIds', []);
}
}
/** 展开/折叠所有节点 */
function handleExpandAll() {
isExpanded.value = !isExpanded.value;
expandedKeys.value = isExpanded.value ? getAllNodeIds(menuTree.value) : [];
}
/** 递归获取所有节点 ID */
function getAllNodeIds(nodes: any[], ids: number[] = []): number[] {
nodes.forEach((node: any) => {
ids.push(node.id);
if (node.children && node.children.length > 0) {
getAllNodeIds(node.children, ids);
}
});
return ids;
}
function getNodeClass(node: Recordable<any>) {
const classes: string[] = [];
if (node.value?.type === SystemMenuTypeEnum.BUTTON) {
classes.push('inline-flex');
if (node.index % 3 >= 1) {
classes.push('!pl-0');
}
}
return classes.join(' ');
}
</script>
<template>
<Modal title="菜单权限" class="w-2/5">
<Form class="mx-4">
<template #menuIds="slotProps">
<Spin :spinning="menuLoading" wrapper-class-name="w-full">
<Tree
:tree-data="menuTree"
multiple
bordered
:default-expanded-keys="expandedKeys"
:get-node-class="getNodeClass"
v-bind="slotProps"
value-field="id"
label-field="name"
/>
</Spin>
</template>
</Form>
<template #prepend-footer>
<div class="flex flex-auto items-center">
<Checkbox :checked="isAllSelected" @change="handleSelectAll">
全选
</Checkbox>
<Checkbox :checked="isExpanded" @change="handleExpandAll">
全部展开
</Checkbox>
</div>
</template>
</Modal>
</template>

View File

@@ -0,0 +1,81 @@
<script lang="ts" setup>
import type { SystemRoleApi } from '#/api/system/role';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { message } from '#/adapter/tdesign';
import { createRole, getRole, updateRole } from '#/api/system/role';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<SystemRoleApi.Role>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['角色'])
: $t('ui.actionTitle.create', ['角色']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 80,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as SystemRoleApi.Role;
try {
await (formData.value?.id ? updateRole(data) : createRole(data));
// 关闭并提示
await modalApi.close();
emit('success');
message.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<SystemRoleApi.Role>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getRole(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle">
<Form class="mx-4" />
</Modal>
</template>