feat(projects): page manage_role

This commit is contained in:
Soybean 2024-01-28 00:44:21 +08:00
parent 2724169eb6
commit 237c6d227e
23 changed files with 909 additions and 60 deletions

View File

@ -9,6 +9,13 @@ export default defineConfig(
{ {
ignores: ['index', 'App', '[id]'] ignores: ['index', 'App', '[id]']
} }
],
'vue/component-name-in-template-casing': [
'warn',
'PascalCase',
{
ignores: ['/^icon-/']
}
] ]
} }
} }

View File

@ -58,6 +58,7 @@
"nprogress": "0.2.0", "nprogress": "0.2.0",
"pinia": "2.1.7", "pinia": "2.1.7",
"vue": "3.4.15", "vue": "3.4.15",
"vue-draggable-plus": "^0.3.5",
"vue-i18n": "9.9.0", "vue-i18n": "9.9.0",
"vue-router": "4.2.5" "vue-router": "4.2.5"
}, },

View File

@ -56,6 +56,9 @@ importers:
vue: vue:
specifier: 3.4.15 specifier: 3.4.15
version: 3.4.15(typescript@5.3.3) version: 3.4.15(typescript@5.3.3)
vue-draggable-plus:
specifier: ^0.3.5
version: 0.3.5(@types/sortablejs@1.15.7)
vue-i18n: vue-i18n:
specifier: 9.9.0 specifier: 9.9.0
version: 9.9.0(vue@3.4.15) version: 9.9.0(vue@3.4.15)
@ -1869,6 +1872,10 @@ packages:
resolution: {integrity: sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A==} resolution: {integrity: sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A==}
dev: true dev: true
/@types/sortablejs@1.15.7:
resolution: {integrity: sha512-PvgWCx1Lbgm88FdQ6S7OGvLIjWS66mudKPlfdrWil0TjsO5zmoZmzoKiiwRShs1dwPgrlkr0N4ewuy0/+QUXYQ==}
dev: false
/@types/svgo@2.6.4: /@types/svgo@2.6.4:
resolution: {integrity: sha512-l4cmyPEckf8moNYHdJ+4wkHvFxjyW6ulm9l4YGaOxeyBWPhBOT0gvni1InpFPdzx1dKf/2s62qGITwxNWnPQng==} resolution: {integrity: sha512-l4cmyPEckf8moNYHdJ+4wkHvFxjyW6ulm9l4YGaOxeyBWPhBOT0gvni1InpFPdzx1dKf/2s62qGITwxNWnPQng==}
dependencies: dependencies:
@ -8625,6 +8632,18 @@ packages:
dependencies: dependencies:
vue: 3.4.15(typescript@5.3.3) vue: 3.4.15(typescript@5.3.3)
/vue-draggable-plus@0.3.5(@types/sortablejs@1.15.7):
resolution: {integrity: sha512-HqIxV4Wr4U5LRPLRi2oV+EJ4g6ibyRKhuaiH4ZQo+LxK4zrk2XcBk9UyXC88OXp4SAq0XYH4Wco/T3LX5kJ79A==}
peerDependencies:
'@types/sortablejs': ^1.15.0
'@vue/composition-api': '*'
peerDependenciesMeta:
'@vue/composition-api':
optional: true
dependencies:
'@types/sortablejs': 1.15.7
dev: false
/vue-eslint-parser@9.4.2(eslint@8.56.0): /vue-eslint-parser@9.4.2(eslint@8.56.0):
resolution: {integrity: sha512-Ry9oiGmCAK91HrKMtCrKFWmSFWvYkpGglCeFAIqDdr9zdXmMMpJOmUJS7WWsW7fX81h6mwHmUZCQQ1E0PkSwYQ==} resolution: {integrity: sha512-Ry9oiGmCAK91HrKMtCrKFWmSFWvYkpGglCeFAIqDdr9zdXmMMpJOmUJS7WWsW7fX81h6mwHmUZCQQ1E0PkSwYQ==}
engines: {node: ^14.17.0 || >=16.0.0} engines: {node: ^14.17.0 || >=16.0.0}

View File

@ -0,0 +1,36 @@
<script setup lang="ts" generic="T extends Record<string, unknown>, K = never">
import { VueDraggable } from 'vue-draggable-plus';
import type { FilteredColumn } from '@/hooks/common/table';
import { $t } from '@/locales';
defineOptions({
name: 'TableColumnSetting'
});
const columns = defineModel<FilteredColumn[]>('columns', {
required: true
});
</script>
<template>
<NPopover placement="bottom-end" trigger="click">
<template #trigger>
<NButton size="small">
<template #icon>
<icon-ant-design-setting-outlined class="text-icon" />
</template>
{{ $t('common.columnSetting') }}
</NButton>
</template>
<VueDraggable v-model="columns">
<div v-for="item in columns" :key="item.key" class="flex-y-center h-36px hover:(bg-primary bg-opacity-20) rd-4px">
<icon-mdi-drag class="mr-8px text-icon cursor-move" />
<NCheckbox v-model:checked="item.checked">
{{ item.title }}
</NCheckbox>
</div>
</VueDraggable>
</NPopover>
</template>
<style scoped></style>

View File

@ -0,0 +1,8 @@
import { transformRecordToOption } from '@/utils/common';
export const roleStatusRecord: Record<Api.SystemManage.RoleStatus, App.I18n.I18nKey> = {
'1': 'page.manage.role.status.enable',
'2': 'page.manage.role.status.disable'
};
export const roleStatusOptions = transformRecordToOption(roleStatusRecord);

View File

@ -47,7 +47,10 @@ export function useFormRules() {
] ]
} satisfies Record<string, App.Global.FormRule[]>; } satisfies Record<string, App.Global.FormRule[]>;
function createRequiredRule(message: string) { /** the default required rule */
const defaultRequiredRule = createRequiredRule($t('form.required'));
function createRequiredRule(message: string): App.Global.FormRule {
return { return {
required: true, required: true,
message message
@ -56,6 +59,7 @@ export function useFormRules() {
return { return {
constantRules, constantRules,
defaultRequiredRule,
createRequiredRule createRequiredRule
}; };
} }

223
src/hooks/common/table.ts Normal file
View File

@ -0,0 +1,223 @@
import { computed, effectScope, onScopeDispose, reactive, ref, watch } from 'vue';
import type { Ref } from 'vue';
import type { DataTableBaseColumn, DataTableExpandColumn, DataTableSelectionColumn, PaginationProps } from 'naive-ui';
import type { TableColumnGroup } from 'naive-ui/es/data-table/src/interface';
import { useBoolean, useLoading } from '@sa/hooks';
import { useAppStore } from '@/store/modules/app';
type BaseData = Record<string, unknown>;
type ApiFn = (args: any) => Promise<unknown>;
export type TableColumn<T extends BaseData = BaseData, CustomColumnKey = never> =
| (Omit<TableColumnGroup<T>, 'key'> & { key: keyof T | CustomColumnKey })
| (Omit<DataTableBaseColumn<T>, 'key'> & { key: keyof T | CustomColumnKey })
| DataTableSelectionColumn<T>
| DataTableExpandColumn<T>;
export type TransformedData<TableData extends BaseData = BaseData> = {
data: TableData[];
pageNum: number;
pageSize: number;
total: number;
};
/** transform api response to table data */
type Transformer<TableData extends BaseData = BaseData, Response = NonNullable<unknown>> = (
response: Response
) => TransformedData<TableData>;
/** table config */
export type TableConfig<TableData extends BaseData = BaseData, Fn extends ApiFn = ApiFn, CustomColumnKey = never> = {
/** api function to get table data */
apiFn: Fn;
/** api params */
apiParams: Parameters<Fn>[0];
/** transform api response to table data */
transformer: Transformer<TableData, Awaited<ReturnType<Fn>>>;
/** pagination */
pagination?: PaginationProps;
/**
* callback when pagination changed
*
* @param pagination
*/
onPaginationChanged?: (pagination: PaginationProps) => void | Promise<void>;
/**
* whether to get data immediately
*
* @default true
*/
immediate?: boolean;
/** columns factory */
columns: () => TableColumn<TableData, CustomColumnKey>[];
};
/** filter columns */
export type FilteredColumn = {
key: string;
title: string;
checked: boolean;
};
export function useTable<TableData extends BaseData, Fn extends ApiFn, CustomColumnKey = never>(
config: TableConfig<TableData, Fn, CustomColumnKey>
) {
const scope = effectScope();
const appStore = useAppStore();
const { loading, startLoading, endLoading } = useLoading();
const { bool: empty, setBool: setEmpty } = useBoolean();
const { apiFn, apiParams, transformer, onPaginationChanged, immediate = true } = config;
const searchParams: NonNullable<Parameters<Fn>[0]> = reactive(apiParams || {});
const { columns, filteredColumns, reloadColumns } = useTableColumn(config.columns);
const data: Ref<TableData[]> = ref([]);
const pagination = reactive({
page: 1,
pageSize: 10,
showSizePicker: true,
pageSizes: [10, 15, 20, 25, 30],
onChange: async (page: number) => {
pagination.page = page;
await onPaginationChanged?.(pagination);
},
onUpdatePageSize: async (pageSize: number) => {
pagination.pageSize = pageSize;
pagination.page = 1;
await onPaginationChanged?.(pagination);
},
...config.pagination
}) as PaginationProps;
function updatePagination(update: Partial<PaginationProps>) {
Object.assign(pagination, update);
}
async function getData() {
startLoading();
const response = await apiFn(searchParams);
const { data: tableData, pageNum, pageSize, total } = transformer(response as Awaited<ReturnType<Fn>>);
data.value = tableData;
setEmpty(tableData.length === 0);
updatePagination({ page: pageNum, pageSize, itemCount: total });
endLoading();
}
/**
* update search params
*
* @param params
*/
function updateSearchParams(params: Partial<Parameters<Fn>[0]>) {
Object.assign(searchParams, params);
}
/** reset search params */
function resetSearchParams() {
Object.keys(searchParams).forEach(key => {
searchParams[key as keyof typeof searchParams] = undefined;
});
}
if (immediate) {
getData();
}
scope.run(() => {
watch(
() => appStore.locale,
() => {
reloadColumns();
}
);
});
onScopeDispose(() => {
scope.stop();
});
return {
loading,
empty,
data,
columns,
filteredColumns,
reloadColumns,
pagination,
updatePagination,
getData,
searchParams,
resetSearchParams,
updateSearchParams
};
}
function useTableColumn<TableData extends BaseData, CustomColumnKey = never>(
factory: () => TableColumn<TableData, CustomColumnKey>[]
) {
const SELECTION_KEY = '__selection__';
const allColumns = ref(factory()) as Ref<TableColumn<TableData, CustomColumnKey>[]>;
const filteredColumns: Ref<FilteredColumn[]> = ref(getFilteredColumns(factory()));
const columns = computed(() => getColumns());
function reloadColumns() {
allColumns.value = factory();
}
function getFilteredColumns(aColumns: TableColumn<TableData, CustomColumnKey>[]) {
const cols: FilteredColumn[] = [];
aColumns.forEach(column => {
if (column.type === undefined) {
cols.push({
key: column.key as string,
title: column.title as string,
checked: true
});
}
if (column.type === 'selection') {
cols.push({
key: SELECTION_KEY,
title: '勾选',
checked: true
});
}
});
return cols;
}
function getColumns() {
const cols = filteredColumns.value
.filter(column => column.checked)
.map(column => {
if (column.key === SELECTION_KEY) {
return allColumns.value.find(col => col.type === 'selection');
}
return allColumns.value.find(col => (col as DataTableBaseColumn).key === column.key);
});
return cols as TableColumn<TableData, CustomColumnKey>[];
}
return {
columns,
reloadColumns,
filteredColumns
};
}

View File

@ -15,7 +15,7 @@ const appStore = useAppStore();
</script> </script>
<template> <template>
<NDrawer v-model:show="appStore.themeDrawerVisible" display-directive="show" :width="378"> <NDrawer v-model:show="appStore.themeDrawerVisible" display-directive="show" :width="360">
<NDrawerContent :title="$t('theme.themeDrawerTitle')" :native-scrollbar="false" closable> <NDrawerContent :title="$t('theme.themeDrawerTitle')" :native-scrollbar="false" closable>
<DarkMode /> <DarkMode />
<LayoutMode /> <LayoutMode />

View File

@ -3,6 +3,7 @@ import { computed } from 'vue';
import { $t } from '@/locales'; import { $t } from '@/locales';
import { useThemeStore } from '@/store/modules/theme'; import { useThemeStore } from '@/store/modules/theme';
import { themePageAnimationModeOptions, themeScrollModeOptions, themeTabModeOptions } from '@/constants/app'; import { themePageAnimationModeOptions, themeScrollModeOptions, themeTabModeOptions } from '@/constants/app';
import { translateOptions } from '@/utils/common';
import SettingItem from '../components/setting-item.vue'; import SettingItem from '../components/setting-item.vue';
defineOptions({ defineOptions({
@ -16,13 +17,6 @@ const layoutMode = computed(() => themeStore.layout.mode);
const isMixLayoutMode = computed(() => layoutMode.value.includes('mix')); const isMixLayoutMode = computed(() => layoutMode.value.includes('mix'));
const isWrapperScrollMode = computed(() => themeStore.layout.scrollMode === 'wrapper'); const isWrapperScrollMode = computed(() => themeStore.layout.scrollMode === 'wrapper');
function translateOptions(options: Common.Option<string>[]) {
return options.map(option => ({
...option,
label: $t(option.label as App.I18n.I18nKey)
}));
}
</script> </script>
<template> <template>

View File

@ -3,23 +3,34 @@ const local: App.I18n.Schema = {
title: 'SoybeanAdmin' title: 'SoybeanAdmin'
}, },
common: { common: {
tip: 'Tip', action: 'Action',
add: 'Add', add: 'Add',
addSuccess: 'Add Success', addSuccess: 'Add Success',
edit: 'Edit', backToHome: 'Back to home',
editSuccess: 'Edit Success', batchDelete: 'Batch Delete',
cancel: 'Cancel',
check: 'Check',
columnSetting: 'Column Setting',
confirm: 'Confirm',
delete: 'Delete', delete: 'Delete',
deleteSuccess: 'Delete Success', deleteSuccess: 'Delete Success',
batchDelete: 'Batch Delete', confirmDelete: 'Are you sure you want to delete?',
confirm: 'Confirm', edit: 'Edit',
cancel: 'Cancel', index: 'Index',
pleaseCheckValue: 'Please check whether the value is valid',
action: 'Action',
backToHome: 'Back to home',
lookForward: 'Coming soon',
userCenter: 'User Center',
logout: 'Logout', logout: 'Logout',
logoutConfirm: 'Are you sure you want to log out?' logoutConfirm: 'Are you sure you want to log out?',
lookForward: 'Coming soon',
modify: 'Modify',
modifySuccess: 'Modify Success',
operate: 'Operate',
pleaseCheckValue: 'Please check whether the value is valid',
refresh: 'Refresh',
reset: 'Reset',
search: 'Search',
tip: 'Tip',
update: 'Update',
updateSuccess: 'Update Success',
userCenter: 'User Center'
}, },
theme: { theme: {
themeSchema: { themeSchema: {
@ -240,9 +251,31 @@ const local: App.I18n.Schema = {
routeParam: 'Route Param', routeParam: 'Route Param',
backTab: 'Back function_tab' backTab: 'Back function_tab'
} }
},
manage: {
role: {
title: 'Role List',
form: {
roleName: 'Please enter role name',
roleCode: 'Please enter role code',
roleStatus: 'Please select role status',
roleDesc: 'Please enter role description'
},
roleName: 'Role Name',
roleCode: 'Role Code',
roleStatus: 'Role Status',
roleDesc: 'Role Description',
addRole: 'Add Role',
editRole: 'Edit Role',
status: {
enable: 'Enable',
disable: 'Disable'
}
}
} }
}, },
form: { form: {
required: 'Cannot be empty',
userName: { userName: {
required: 'Please enter user name', required: 'Please enter user name',
invalid: 'User name format is incorrect' invalid: 'User name format is incorrect'

View File

@ -3,23 +3,34 @@ const local: App.I18n.Schema = {
title: 'Soybean 管理系统' title: 'Soybean 管理系统'
}, },
common: { common: {
tip: '提示', action: '操作',
add: '添加', add: '添加',
addSuccess: '添加成功', addSuccess: '添加成功',
edit: '修改', backToHome: '返回首页',
editSuccess: '修改成功', batchDelete: '批量删除',
cancel: '取消',
check: '勾选',
columnSetting: '列设置',
confirm: '确认',
delete: '删除', delete: '删除',
deleteSuccess: '删除成功', deleteSuccess: '删除成功',
batchDelete: '批量删除', confirmDelete: '确认删除吗?',
confirm: '确认', edit: '编辑',
cancel: '取消', index: '序号',
pleaseCheckValue: '请检查输入的值是否合法',
action: '操作',
backToHome: '返回首页',
lookForward: '敬请期待',
userCenter: '个人中心',
logout: '退出登录', logout: '退出登录',
logoutConfirm: '确认退出登录吗?' logoutConfirm: '确认退出登录吗?',
lookForward: '敬请期待',
modify: '修改',
modifySuccess: '修改成功',
operate: '操作',
pleaseCheckValue: '请检查输入的值是否合法',
refresh: '刷新',
reset: '重置',
search: '搜索',
tip: '提示',
update: '更新',
updateSuccess: '更新成功',
userCenter: '个人中心'
}, },
theme: { theme: {
themeSchema: { themeSchema: {
@ -240,9 +251,31 @@ const local: App.I18n.Schema = {
routeParam: '路由参数', routeParam: '路由参数',
backTab: '返回 function_tab' backTab: '返回 function_tab'
} }
},
manage: {
role: {
title: '角色列表',
form: {
roleName: '请输入角色名称',
roleCode: '请输入角色编码',
roleStatus: '请选择角色状态',
roleDesc: '请输入角色描述'
},
roleName: '角色名称',
roleCode: '角色编码',
roleStatus: '角色状态',
roleDesc: '角色描述',
addRole: '添加角色',
editRole: '编辑角色',
status: {
enable: '启用',
disable: '禁用'
}
}
} }
}, },
form: { form: {
required: '不能为空',
userName: { userName: {
required: '请输入用户名', required: '请输入用户名',
invalid: '用户名格式不正确' invalid: '用户名格式不正确'

View File

@ -35,7 +35,7 @@ export function createPermissionGuard(router: Router) {
authStore.userInfo.roles.includes(SUPER_ADMIN) || authStore.userInfo.roles.includes(SUPER_ADMIN) ||
authStore.userInfo.roles.some(role => routeRoles.includes(role)); authStore.userInfo.roles.some(role => routeRoles.includes(role));
const strategicPatterns: Common.StrategicPattern[] = [ const strategicPatterns: CommonType.StrategicPattern[] = [
// 1. if it is login route when logged in, change to the root page // 1. if it is login route when logged in, change to the root page
{ {
condition: isLogin && to.name === loginRoute, condition: isLogin && to.name === loginRoute,

View File

@ -1,2 +1,3 @@
export * from './auth'; export * from './auth';
export * from './route'; export * from './route';
export * from './system-manage';

View File

@ -0,0 +1,10 @@
import { request } from '../request';
/** get role list */
export function fetchGetRoleList(params?: Api.SystemManage.RoleSearchParams) {
return request<Api.SystemManage.RoleList>({
url: '/systemManage/getRoleList',
method: 'get',
params
});
}

75
src/typings/api.d.ts vendored
View File

@ -4,10 +4,41 @@
* All backend api type * All backend api type
*/ */
declare namespace Api { declare namespace Api {
namespace Common {
/** common params of paginating */
interface PaginatingCommonParams {
/** current page number */
current: number;
/** page size */
size: number;
/** total count */
total: number;
}
/** common params of paginating query list data */
interface PaginatingQueryRecord<T extends NonNullable<unknown>> extends PaginatingCommonParams {
records: T[];
}
/** common record */
type CommonRecord<T extends NonNullable<unknown>> = {
/** record id */
id: number;
/** record creator */
createBy: string;
/** record create time */
createTime: string;
/** record updater */
updateBy: string;
/** record update time */
updateTime: string;
} & T;
}
/** /**
* Namespace Auth * namespace Auth
* *
* Backend api module: "auth" * backend api module: "auth"
*/ */
namespace Auth { namespace Auth {
interface LoginToken { interface LoginToken {
@ -23,9 +54,9 @@ declare namespace Api {
} }
/** /**
* Namespace Route * namespace Route
* *
* Backend api module: "route" * backend api module: "route"
*/ */
namespace Route { namespace Route {
type ElegantConstRoute = import('@elegant-router/types').ElegantConstRoute; type ElegantConstRoute = import('@elegant-router/types').ElegantConstRoute;
@ -39,4 +70,40 @@ declare namespace Api {
home: import('@elegant-router/types').LastLevelRouteKey; home: import('@elegant-router/types').LastLevelRouteKey;
} }
} }
/**
* namespace SystemManage
*
* backend api module: "systemManage"
*/
namespace SystemManage {
/**
* role status
*
* - "1": enabled
* - "2": disabled
*/
type RoleStatus = '1' | '2';
/** role */
type Role = Common.CommonRecord<{
/** role name */
roleName: string;
/** role code */
roleCode: string;
/** role description */
roleDesc: string;
/** role status */
roleStatus: RoleStatus | null;
}>;
/** role search params */
type RoleSearchParams = CommonType.RecordNullable<
Pick<Api.SystemManage.Role, 'roleName' | 'roleCode' | 'roleStatus'> &
Pick<Common.PaginatingCommonParams, 'current' | 'size'>
>;
/** role list */
type RoleList = Common.PaginatingQueryRecord<Role>;
}
} }

55
src/typings/app.d.ts vendored
View File

@ -249,23 +249,34 @@ declare namespace App {
title: string; title: string;
}; };
common: { common: {
tip: string; action: string;
add: string; add: string;
addSuccess: string; addSuccess: string;
edit: string; backToHome: string;
editSuccess: string; batchDelete: string;
cancel: string;
check: string;
columnSetting: string;
confirm: string;
delete: string; delete: string;
deleteSuccess: string; deleteSuccess: string;
batchDelete: string; confirmDelete: string;
confirm: string; edit: string;
cancel: string; index: string;
pleaseCheckValue: string;
action: string;
backToHome: string;
lookForward: string;
userCenter: string;
logout: string; logout: string;
logoutConfirm: string; logoutConfirm: string;
lookForward: string;
modify: string;
modifySuccess: string;
operate: string;
pleaseCheckValue: string;
refresh: string;
reset: string;
search: string;
tip: string;
update: string;
updateSuccess: string;
userCenter: string;
}; };
theme: { theme: {
themeSchema: { title: string } & Record<UnionKey.ThemeScheme, string>; themeSchema: { title: string } & Record<UnionKey.ThemeScheme, string>;
@ -428,8 +439,30 @@ declare namespace App {
backTab: string; backTab: string;
}; };
}; };
manage: {
role: {
title: string;
form: {
roleName: string;
roleCode: string;
roleStatus: string;
roleDesc: string;
};
roleName: string;
roleCode: string;
roleStatus: string;
roleDesc: string;
addRole: string;
editRole: string;
status: {
enable: string;
disable: string;
};
};
};
}; };
form: { form: {
required: string;
userName: FormMsg; userName: FormMsg;
phone: FormMsg; phone: FormMsg;
pwd: FormMsg; pwd: FormMsg;

View File

@ -1,5 +1,5 @@
/** The common type namespace */ /** The common type namespace */
declare namespace Common { declare namespace CommonType {
/** The strategic pattern */ /** The strategic pattern */
interface StrategicPattern { interface StrategicPattern {
/** The condition */ /** The condition */
@ -17,4 +17,9 @@ declare namespace Common {
type Option<K> = { value: K; label: string }; type Option<K> = { value: K; label: string };
type YesOrNo = 'Y' | 'N'; type YesOrNo = 'Y' | 'N';
/** add null to all properties */
type RecordNullable<T> = {
[K in keyof T]?: T[K] | null;
};
} }

View File

@ -16,10 +16,18 @@ declare module 'vue' {
ExceptionBase: typeof import('./../components/common/exception-base.vue')['default'] ExceptionBase: typeof import('./../components/common/exception-base.vue')['default']
FullScreen: typeof import('./../components/common/full-screen.vue')['default'] FullScreen: typeof import('./../components/common/full-screen.vue')['default']
IconAntDesignReloadOutlined: typeof import('~icons/ant-design/reload-outlined')['default'] IconAntDesignReloadOutlined: typeof import('~icons/ant-design/reload-outlined')['default']
IconAntDesignSettingOutlined: typeof import('~icons/ant-design/setting-outlined')['default']
IconGridiconsFullscreen: typeof import('~icons/gridicons/fullscreen')['default'] IconGridiconsFullscreen: typeof import('~icons/gridicons/fullscreen')['default']
IconGridiconsFullscreenExit: typeof import('~icons/gridicons/fullscreen-exit')['default'] IconGridiconsFullscreenExit: typeof import('~icons/gridicons/fullscreen-exit')['default']
IconIcRoundDelete: typeof import('~icons/ic/round-delete')['default']
IconIcRoundPlus: typeof import('~icons/ic/round-plus')['default']
IconIcRoundRefresh: typeof import('~icons/ic/round-refresh')['default']
IconIcRoundSearch: typeof import('~icons/ic/round-search')['default']
IconIcRoundSettings: typeof import('~icons/ic/round-settings')['default']
IconLocalBanner: typeof import('~icons/local/banner')['default'] IconLocalBanner: typeof import('~icons/local/banner')['default']
IconLocalLogo: typeof import('~icons/local/logo')['default'] IconLocalLogo: typeof import('~icons/local/logo')['default']
IconMdiDrag: typeof import('~icons/mdi/drag')['default']
IconMdiRefresh: typeof import('~icons/mdi/refresh')['default']
LangSwitch: typeof import('./../components/common/lang-switch.vue')['default'] LangSwitch: typeof import('./../components/common/lang-switch.vue')['default']
LookForward: typeof import('./../components/custom/look-forward.vue')['default'] LookForward: typeof import('./../components/custom/look-forward.vue')['default']
MenuToggler: typeof import('./../components/common/menu-toggler.vue')['default'] MenuToggler: typeof import('./../components/common/menu-toggler.vue')['default']
@ -30,6 +38,7 @@ declare module 'vue' {
NCard: typeof import('naive-ui')['NCard'] NCard: typeof import('naive-ui')['NCard']
NCheckbox: typeof import('naive-ui')['NCheckbox'] NCheckbox: typeof import('naive-ui')['NCheckbox']
NColorPicker: typeof import('naive-ui')['NColorPicker'] NColorPicker: typeof import('naive-ui')['NColorPicker']
NDataTable: typeof import('naive-ui')['NDataTable']
NDescriptions: typeof import('naive-ui')['NDescriptions'] NDescriptions: typeof import('naive-ui')['NDescriptions']
NDescriptionsItem: typeof import('naive-ui')['NDescriptionsItem'] NDescriptionsItem: typeof import('naive-ui')['NDescriptionsItem']
NDialogProvider: typeof import('naive-ui')['NDialogProvider'] NDialogProvider: typeof import('naive-ui')['NDialogProvider']
@ -39,6 +48,7 @@ declare module 'vue' {
NDropdown: typeof import('naive-ui')['NDropdown'] NDropdown: typeof import('naive-ui')['NDropdown']
NForm: typeof import('naive-ui')['NForm'] NForm: typeof import('naive-ui')['NForm']
NFormItem: typeof import('naive-ui')['NFormItem'] NFormItem: typeof import('naive-ui')['NFormItem']
NFormItemGi: typeof import('naive-ui')['NFormItemGi']
NGi: typeof import('naive-ui')['NGi'] NGi: typeof import('naive-ui')['NGi']
NGrid: typeof import('naive-ui')['NGrid'] NGrid: typeof import('naive-ui')['NGrid']
NGridItem: typeof import('naive-ui')['NGridItem'] NGridItem: typeof import('naive-ui')['NGridItem']
@ -51,6 +61,7 @@ declare module 'vue' {
NMenu: typeof import('naive-ui')['NMenu'] NMenu: typeof import('naive-ui')['NMenu']
NMessageProvider: typeof import('naive-ui')['NMessageProvider'] NMessageProvider: typeof import('naive-ui')['NMessageProvider']
NNotificationProvider: typeof import('naive-ui')['NNotificationProvider'] NNotificationProvider: typeof import('naive-ui')['NNotificationProvider']
NPopover: typeof import('naive-ui')['NPopover']
NSelect: typeof import('naive-ui')['NSelect'] NSelect: typeof import('naive-ui')['NSelect']
NSpace: typeof import('naive-ui')['NSpace'] NSpace: typeof import('naive-ui')['NSpace']
NStatistic: typeof import('naive-ui')['NStatistic'] NStatistic: typeof import('naive-ui')['NStatistic']
@ -67,6 +78,8 @@ declare module 'vue' {
SoybeanAvatar: typeof import('./../components/custom/soybean-avatar.vue')['default'] SoybeanAvatar: typeof import('./../components/custom/soybean-avatar.vue')['default']
SvgIcon: typeof import('./../components/custom/svg-icon.vue')['default'] SvgIcon: typeof import('./../components/custom/svg-icon.vue')['default']
SystemLogo: typeof import('./../components/common/system-logo.vue')['default'] SystemLogo: typeof import('./../components/common/system-logo.vue')['default']
TableColumnSetting: typeof import('./../components/advanced/table-column-setting.vue')['default']
TableColumnSettings: typeof import('./../components/advanced/table-column-settings.vue')['default']
ThemeSchemaSwitch: typeof import('./../components/common/theme-schema-switch.vue')['default'] ThemeSchemaSwitch: typeof import('./../components/common/theme-schema-switch.vue')['default']
WaveBg: typeof import('./../components/custom/wave-bg.vue')['default'] WaveBg: typeof import('./../components/custom/wave-bg.vue')['default']
} }

View File

@ -30,7 +30,7 @@ declare namespace Env {
* *
* Only valid in the development environment * Only valid in the development environment
*/ */
readonly VITE_HTTP_PROXY?: Common.YesOrNo; readonly VITE_HTTP_PROXY?: CommonType.YesOrNo;
/** The back service env */ /** The back service env */
readonly VITE_SERVICE_ENV?: App.Service.EnvType; readonly VITE_SERVICE_ENV?: App.Service.EnvType;
/** /**
@ -54,7 +54,7 @@ declare namespace Env {
*/ */
readonly VITE_MENU_ICON: string; readonly VITE_MENU_ICON: string;
/** Whether to build with sourcemap */ /** Whether to build with sourcemap */
readonly VITE_SOURCE_MAP?: Common.YesOrNo; readonly VITE_SOURCE_MAP?: CommonType.YesOrNo;
/** /**
* Iconify api provider url * Iconify api provider url
* *

View File

@ -1,3 +1,5 @@
import { $t } from '@/locales';
/** /**
* Transform record to option * Transform record to option
* *
@ -20,5 +22,17 @@ export function transformRecordToOption<T extends Record<string, string>>(record
return Object.entries(record).map(([value, label]) => ({ return Object.entries(record).map(([value, label]) => ({
value, value,
label label
})) as Common.Option<keyof T>[]; })) as CommonType.Option<keyof T>[];
}
/**
* Translate options
*
* @param options
*/
export function translateOptions(options: CommonType.Option<string>[]) {
return options.map(option => ({
...option,
label: $t(option.label as App.I18n.I18nKey)
}));
} }

View File

@ -1,7 +1,225 @@
<script setup lang="ts"></script> <script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { fetchGetRoleList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable } from '@/hooks/common/table';
import { $t } from '@/locales';
import { roleStatusOptions } from '@/constants/business';
import { translateOptions } from '@/utils/common';
import OperateRoleDrawer, { type OperateType } from './operate-role-drawer.vue';
const appStore = useAppStore();
const { bool: drawerVisible, setTrue: openDrawer } = useBoolean();
const { columns, filteredColumns, data, loading, pagination, getData, searchParams, resetSearchParams } = useTable<
Api.SystemManage.Role,
typeof fetchGetRoleList,
'index' | 'operate'
>({
apiFn: fetchGetRoleList,
apiParams: {
current: 1,
size: 10
},
transformer: res => {
const { records = [], current = 1, size = 10, total = 0 } = res.data || {};
return {
data: records,
pageNum: current,
pageSize: size,
total
};
},
columns: () => [
{
type: 'selection',
align: 'center',
width: 48
},
{
key: 'index',
title: $t('common.index'),
render: (_, index): string => getIndex(index),
width: 64,
align: 'center'
},
{
key: 'roleName',
title: $t('page.manage.role.roleName'),
align: 'center'
},
{
key: 'roleCode',
title: $t('page.manage.role.roleCode')
},
{
key: 'roleDesc',
title: $t('page.manage.role.roleDesc')
},
{
key: 'roleStatus',
title: $t('page.manage.role.roleStatus'),
align: 'center'
},
{
key: 'operate',
title: $t('common.operate'),
align: 'center',
width: 130,
render: row => (
<div class="flex-center gap-8px">
<NButton type="primary" ghost size="small" onClick={() => handleEdit(row.id)}>
{$t('common.edit')}
</NButton>
<NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
{{
default: () => $t('common.confirmDelete'),
trigger: () => (
<NButton type="error" ghost size="small">
{$t('common.delete')}
</NButton>
)
}}
</NPopconfirm>
</div>
)
}
]
});
const operateType = ref<OperateType>('add');
function handleAdd() {
operateType.value = 'add';
openDrawer();
}
const checkedRowKeys = ref<string[]>([]);
async function handleBatchDelete() {
// request
console.log(checkedRowKeys.value);
window.$message?.success($t('common.deleteSuccess'));
checkedRowKeys.value = [];
getData();
}
/** the editing row data */
const editingData = ref<Api.SystemManage.Role | null>(null);
function handleEdit(id: number) {
operateType.value = 'edit';
editingData.value = data.value.find(item => item.id === id) || null;
openDrawer();
}
async function handleDelete(id: number) {
// request
console.log(id);
window.$message?.success($t('common.deleteSuccess'));
getData();
}
function getIndex(index: number) {
const { page = 0, pageSize = 10 } = pagination;
return String((page - 1) * pageSize + index + 1);
}
</script>
<template> <template>
<LookForward /> <div class="flex-vertical-stretch gap-16px overflow-hidden <sm:overflow-auto">
<NCard :title="$t('common.search')" :bordered="false" size="small" class="card-wrapper">
<NForm :model="searchParams" label-placement="left">
<NGrid responsive="screen" item-responsive>
<NFormItemGi span="24 s:12 m:6" :label="$t('page.manage.role.roleName')" path="roleName" class="pr-24px">
<NInput v-model:value="searchParams.roleName" :placeholder="$t('page.manage.role.form.roleName')" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" :label="$t('page.manage.role.roleCode')" path="roleCode" class="pr-24px">
<NInput v-model:value="searchParams.roleCode" :placeholder="$t('page.manage.role.form.roleCode')" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" :label="$t('page.manage.role.roleStatus')" path="roleStatus" class="pr-24px">
<NSelect
v-model:value="searchParams.roleStatus"
:placeholder="$t('page.manage.role.form.roleStatus')"
:options="translateOptions(roleStatusOptions)"
clearable
/>
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6">
<NSpace class="w-full" justify="end">
<NButton @click="resetSearchParams">
<template #icon>
<icon-ic-round-refresh class="text-icon" />
</template>
{{ $t('common.reset') }}
</NButton>
<NButton type="primary" ghost @click="getData">
<template #icon>
<icon-ic-round-search class="text-icon" />
</template>
{{ $t('common.search') }}
</NButton>
</NSpace>
</NFormItemGi>
</NGrid>
</NForm>
</NCard>
<NCard :title="$t('page.manage.role.title')" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
<template #header-extra>
<NSpace wrap justify="end" class="<sm:w-200px">
<NButton size="small" ghost type="primary" @click="handleAdd">
<template #icon>
<icon-ic-round-plus class="text-icon" />
</template>
{{ $t('common.add') }}
</NButton>
<NPopconfirm @positive-click="handleBatchDelete">
<template #trigger>
<NButton size="small" ghost type="error" :disabled="checkedRowKeys.length === 0">
<template #icon>
<icon-ic-round-delete class="text-icon" />
</template>
{{ $t('common.batchDelete') }}
</NButton>
</template>
{{ $t('common.confirmDelete') }}
</NPopconfirm>
<NButton size="small" @click="getData">
<template #icon>
<icon-mdi-refresh class="text-icon" :class="{ 'animate-spin': loading }" />
</template>
{{ $t('common.refresh') }}
</NButton>
<TableColumnSetting v-model:columns="filteredColumns" />
</NSpace>
</template>
<NDataTable
v-model:checked-row-keys="checkedRowKeys"
:columns="columns"
:data="data"
size="small"
:flex-height="!appStore.isMobile"
:scroll-x="640"
:loading="loading"
:pagination="pagination"
:row-key="item => item.id"
class="sm:h-full"
/>
<OperateRoleDrawer
v-model:visible="drawerVisible"
:operate-type="operateType"
:row-data="editingData"
@submitted="getData"
/>
</NCard>
</div>
</template> </template>
<style scoped></style> <style scoped></style>

View File

@ -0,0 +1,132 @@
<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { roleStatusOptions } from '@/constants/business';
import { translateOptions } from '@/utils/common';
defineOptions({
name: 'OperateRoleDrawer'
});
/**
* the type of operation
*
* - add: add role
* - edit: edit role
*/
export type OperateType = 'add' | 'edit';
interface Props {
/** the type of operation */
operateType: OperateType;
/** the edit row data */
rowData?: Api.SystemManage.Role | null;
}
const props = defineProps<Props>();
interface Emits {
(e: 'submitted'): void;
}
const emit = defineEmits<Emits>();
const visible = defineModel<boolean>('visible', {
default: false
});
const { formRef, validate } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();
const title = computed(() => {
const titles: Record<OperateType, string> = {
add: $t('page.manage.role.addRole'),
edit: $t('page.manage.role.editRole')
};
return titles[props.operateType];
});
type Model = Pick<Api.SystemManage.Role, 'roleName' | 'roleCode' | 'roleDesc' | 'roleStatus'>;
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
return {
roleName: '',
roleCode: '',
roleDesc: '',
roleStatus: null
};
}
type RuleKey = Exclude<keyof Model, 'roleDesc'>;
const rules: Record<RuleKey, App.Global.FormRule> = {
roleName: defaultRequiredRule,
roleCode: defaultRequiredRule,
roleStatus: defaultRequiredRule
};
function handleUpdateModelWhenEdit() {
if (props.operateType === 'add') {
Object.assign(model, createDefaultModel());
return;
}
if (props.operateType === 'edit' && props.rowData) {
Object.assign(model, props.rowData);
}
}
function closeDrawer() {
visible.value = false;
}
async function handleSubmit() {
await validate();
// request
window.$message?.success($t('common.updateSuccess'));
closeDrawer();
emit('submitted');
}
watch(visible, () => {
if (visible.value) {
handleUpdateModelWhenEdit();
}
});
</script>
<template>
<NDrawer v-model:show="visible" :title="title" display-directive="show" :width="360">
<NDrawerContent :title="title" :native-scrollbar="false" closable>
<NForm ref="formRef" :model="model" :rules="rules">
<NFormItem :label="$t('page.manage.role.roleName')" path="roleName">
<NInput v-model:value="model.roleName" :placeholder="$t('page.manage.role.form.roleName')" />
</NFormItem>
<NFormItem :label="$t('page.manage.role.roleCode')" path="roleCode">
<NInput v-model:value="model.roleCode" :placeholder="$t('page.manage.role.form.roleCode')" />
</NFormItem>
<NFormItem :label="$t('page.manage.role.roleStatus')" path="roleStatus">
<NSelect
v-model:value="model.roleStatus"
:placeholder="$t('page.manage.role.form.roleStatus')"
:options="translateOptions(roleStatusOptions)"
/>
</NFormItem>
<NFormItem :label="$t('page.manage.role.roleDesc')" path="roleDesc">
<NInput v-model:value="model.roleDesc" :placeholder="$t('page.manage.role.form.roleDesc')" />
</NFormItem>
</NForm>
<template #footer>
<NSpace :size="16">
<NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
<NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
</NSpace>
</template>
</NDrawerContent>
</NDrawer>
</template>
<style scoped></style>

View File

@ -1,10 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import { onActivated } from 'vue'; import { fetchGetRoleList } from '@/service/api';
console.log('setup'); fetchGetRoleList().then(res => {
console.log(res);
onActivated(() => {
console.log('onActivated');
}); });
</script> </script>