Commit d006b3c7 by chenwq

```

feat(access): 完善权限系统本地存储和权限点管理

- 将权限点来源从后端mock改为本地用户信息的permCodes
- 新增clearLoginSession、getLoginSession、getUserInfo、getUserPermCodes等会话管理函数
- 更新本地存储键名为'uj-auth-user-info',优化过期处理逻辑
- 在登录时将权限码作为fallback保存到用户信息中

feat(access): 添加角色管理相关权限点

- 新增SYSTEM_ROLE_VIEW和SYSTEM_ROLE_EDIT权限点用于角色查看和编辑操作

refactor(access): 优化AccessProvider权限加载机制

- 移除fetchPermissions和normalizePermissions的依赖
- 修改权限点获取逻辑,直接从本地用户信息的permCodes读取
- 更新文档注释说明权限点来源变更

feat(components): 增强DataTable组件功能

- 添加rowActions支持行内操作按钮,自动应用权限控制
- 支持pageData分页数据自动映射
- 为工具栏按钮统一添加权限按钮支持
- 增加actionColumnTitle、actionColumnWidth等配置项

feat(components): 扩展SearchForm字段样式控制

- 为表单字段添加width属性支持自定义宽度
- 为选择框设置默认allowClear为false

feat(pages): 实现角色管理页面基础功能

- 创建角色管理页面,包含列表展示、搜索筛选功能
- 集成DataTable组件展示角色信息表格
- 实现角色类型、状态、数据范围等筛选条件
- 添加新增角色按钮和操作提示信息

chore(store): 优化应用状态初始化

- 从本地会话恢复当前用户信息
- 登出时清除登录会话数据
```
1 parent 0456afb7
Pipeline #299 for d006b3c7 failed in 0 seconds
...@@ -20,5 +20,13 @@ export { AccessProvider, useAccess } from './runtime/AccessProvider'; ...@@ -20,5 +20,13 @@ export { AccessProvider, useAccess } from './runtime/AccessProvider';
export { PermButton } from './ui/PermButton'; export { PermButton } from './ui/PermButton';
export { Perm } from './ui/Perm'; export { Perm } from './ui/Perm';
export { getAuthorization, saveLoginSession, saveUserInfo } from './session'; export {
clearLoginSession,
getAuthorization,
getLoginSession,
getUserInfo,
getUserPermCodes,
saveLoginSession,
saveUserInfo,
} from './session';
export type { LoginSession } from './session'; export type { LoginSession } from './session';
...@@ -18,6 +18,9 @@ export const P = { ...@@ -18,6 +18,9 @@ export const P = {
STORE_LISTING: 'store.listing', STORE_LISTING: 'store.listing',
STORE_LISTING_EXPORT: 'store.listing:export', STORE_LISTING_EXPORT: 'store.listing:export',
STORE_LISTING_DELETE: 'store.listing:delete', STORE_LISTING_DELETE: 'store.listing:delete',
// 角色管理
SYSTEM_ROLE_VIEW: 'system:role:view',
SYSTEM_ROLE_EDIT: 'system:role:save',
// 复用片段 // 复用片段
VIEW: ':view', VIEW: ':view',
MANAGE: ':manage', MANAGE: ':manage',
......
...@@ -6,19 +6,18 @@ import { ...@@ -6,19 +6,18 @@ import {
type ResourceKey, type ResourceKey,
type RoleKey, type RoleKey,
} from '../model'; } from '../model';
import { fetchPermissions } from '../backend/permissionsSource'; import { getUserPermCodes } from '../session';
import { normalizePermissions } from '../backend/adapter';
interface AccessContextValue { interface AccessContextValue {
role: RoleKey; role: RoleKey;
setRole: (r: RoleKey) => Promise<void>; setRole: (r: RoleKey) => Promise<void>;
matrix: PermissionMatrix; matrix: PermissionMatrix;
can: (resource: ResourceKey, required?: 'view' | 'full') => boolean; can: (resource: ResourceKey, required?: 'view' | 'full') => boolean;
/** 当前账号持有的权限点集合(由后端返回,经适配器归一化) */ /** 当前账号持有的权限点集合(来自本地用户信息的 permCodes) */
points: Set<string>; points: Set<string>;
/** 按钮/操作级权限判定:是否拥有某个权限点 */ /** 按钮/操作级权限判定:是否拥有某个权限点 */
canPoint: (point: string) => boolean; canPoint: (point: string) => boolean;
/** 用后端返回的原始权限数据刷新权限点(经 adapter 归一化) */ /** 本地用户信息更新后刷新权限点。 */
loadPermissions: (raw: unknown) => void; loadPermissions: (raw: unknown) => void;
} }
...@@ -27,17 +26,16 @@ const AccessContext = createContext<AccessContextValue | null>(null); ...@@ -27,17 +26,16 @@ const AccessContext = createContext<AccessContextValue | null>(null);
export function AccessProvider({ children }: { children: ReactNode }) { export function AccessProvider({ children }: { children: ReactNode }) {
const [role, setRoleState] = useState<RoleKey>('SYS_ADMIN'); const [role, setRoleState] = useState<RoleKey>('SYS_ADMIN');
const [matrix] = useState<PermissionMatrix>(defaultMatrix); const [matrix] = useState<PermissionMatrix>(defaultMatrix);
const [points, setPoints] = useState<Set<string>>(new Set()); const [points, setPoints] = useState<Set<string>>(() => new Set(getUserPermCodes()));
// 角色变化 → 重新拉取该角色的权限点(来源见 src/access/backend/permissionsSource.ts,目前为 mock) // 角色变化时,重新读取本地用户信息中的 permCodes;不再使用模拟权限。
const setRole = async (r: RoleKey) => { const setRole = async (r: RoleKey) => {
setRoleState(r); setRoleState(r);
const perms = await fetchPermissions(r); setPoints(new Set(getUserPermCodes()));
setPoints(new Set(normalizePermissions(perms)));
}; };
const loadPermissions = (raw: unknown) => { const loadPermissions = (_raw: unknown) => {
setPoints(new Set(normalizePermissions(raw))); setPoints(new Set(getUserPermCodes()));
}; };
const value = useMemo<AccessContextValue>( const value = useMemo<AccessContextValue>(
......
...@@ -13,23 +13,71 @@ export interface LoginSession { ...@@ -13,23 +13,71 @@ export interface LoginSession {
} }
const SESSION_KEY = 'session'; const SESSION_KEY = 'session';
const USER_INFO_KEY = 'user-info'; /** 用户信息及权限的统一本地存储键。 */
const USER_INFO_KEY = 'uj-auth-user-info';
export function saveLoginSession(session: LoginSession) { export function saveLoginSession(session: LoginSession) {
localStorage.setItem(SESSION_KEY, JSON.stringify(session)); localStorage.setItem(SESSION_KEY, JSON.stringify(session));
} }
export function getAuthorization() { export function getLoginSession(): LoginSession | undefined {
const raw = localStorage.getItem(SESSION_KEY); const raw = localStorage.getItem(SESSION_KEY);
if (!raw) return undefined; if (!raw) return undefined;
try { try {
const { token, tokenType = 'Bearer' } = JSON.parse(raw) as Partial<LoginSession>; const session = JSON.parse(raw) as LoginSession;
return token ? `${tokenType} ${token}` : undefined; if (
!session.token ||
(session.expireAt && new Date(session.expireAt).getTime() <= Date.now())
) {
localStorage.removeItem(SESSION_KEY);
return undefined;
}
return session;
} catch { } catch {
localStorage.removeItem(SESSION_KEY);
return undefined; return undefined;
} }
} }
export function saveUserInfo(info: unknown) { export function getAuthorization() {
localStorage.setItem(USER_INFO_KEY, JSON.stringify(info)); const session = getLoginSession();
return session ? `${session.tokenType || 'Bearer'} ${session.token}` : undefined;
}
export function saveUserInfo(info: unknown, fallbackPermCodes: string[] = []) {
const userInfo =
info && typeof info === 'object' && !Array.isArray(info)
? (info as Record<string, unknown>)
: {};
const permCodes = Array.isArray(userInfo.permCodes)
? userInfo.permCodes.filter((code): code is string => typeof code === 'string')
: fallbackPermCodes;
localStorage.setItem(USER_INFO_KEY, JSON.stringify({ ...userInfo, permCodes }));
}
/** 获取本地用户信息,权限按钮以其中的 permCodes 为唯一依据。 */
export function getUserInfo(): Record<string, unknown> | undefined {
const raw = localStorage.getItem(USER_INFO_KEY);
if (!raw) return undefined;
try {
const userInfo = JSON.parse(raw);
return userInfo && typeof userInfo === 'object' && !Array.isArray(userInfo)
? (userInfo as Record<string, unknown>)
: undefined;
} catch {
localStorage.removeItem(USER_INFO_KEY);
return undefined;
}
}
export function getUserPermCodes(): string[] {
const permCodes = getUserInfo()?.permCodes;
return Array.isArray(permCodes)
? permCodes.filter((code): code is string => typeof code === 'string')
: [];
}
export function clearLoginSession() {
localStorage.removeItem(SESSION_KEY);
localStorage.removeItem(USER_INFO_KEY);
} }
...@@ -10,6 +10,31 @@ export interface RoleItem { ...@@ -10,6 +10,31 @@ export interface RoleItem {
remark?: string; remark?: string;
createTime?: string; createTime?: string;
} }
export interface RolePageParams {
current?: number;
size?: number;
keyword?: string;
isBuiltin?: number;
status?: number;
defaultDataScope?: number;
}
export interface RolePageItem {
roleId: number;
roleName: string;
roleCode: string;
defaultDataScope: number;
accountCount: number;
description?: string;
isBuiltin: number;
status: number;
}
export interface RolePageResult {
records: RolePageItem[];
total: number;
current: number;
size: number;
pages: number;
}
export interface PermissionMatrix { export interface PermissionMatrix {
roleId: string; roleId: string;
...@@ -20,6 +45,9 @@ export interface PermissionMatrix { ...@@ -20,6 +45,9 @@ export interface PermissionMatrix {
} }
class Role extends ApiClient { class Role extends ApiClient {
page(params: RolePageParams) {
return this.get<RolePageResult>('/system/role/page', params as Record<string, unknown>);
}
list(params: Record<string, unknown> = {}) { list(params: Record<string, unknown> = {}) {
return this.get<PageResult<RoleItem>>('/store/role/list', params); return this.get<PageResult<RoleItem>>('/store/role/list', params);
} }
......
import type { ReactNode } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table'; import type { ColumnsType, TableProps } from 'antd/es/table';
import { UButton, UTable } from '@uj/ui'; import { UButton, UTable } from '@uj/ui';
import { PermButton } from '@/access'; import { PermButton } from '@/access';
import type { ActionSchema } from '../formSchema'; import type { ActionSchema } from '../formSchema';
/** 列表行操作配置;配置 permission 时自动使用权限按钮。 */
export interface RowActionSchema<T> extends Omit<ActionSchema, 'onClick'> {
onClick: (record: T) => void;
visible?: (record: T) => boolean;
}
export interface DataTableProps<T> extends Pick< export interface DataTableProps<T> extends Pick<
TableProps<T>, TableProps<T>,
'dataSource' | 'loading' | 'rowKey' | 'rowSelection' 'dataSource' | 'loading' | 'rowKey' | 'rowSelection'
...@@ -18,15 +25,82 @@ export interface DataTableProps<T> extends Pick< ...@@ -18,15 +25,82 @@ export interface DataTableProps<T> extends Pick<
} }
| false; | false;
actions?: ActionSchema[]; actions?: ActionSchema[];
/** 行内操作。配置 permission 时自动按权限显示,未配置则使用普通按钮。 */
rowActions?: RowActionSchema<T>[];
/** 行内操作列标题,默认“操作”。 */
actionColumnTitle?: ReactNode;
/** 行内操作列宽度。 */
actionColumnWidth?: number;
/** 接口返回的分页对象;传入后自动从 recordsKey 读取列表数据。 */
pageData?: Record<string, unknown>;
/** 分页对象中的列表字段名,默认 records。 */
recordsKey?: string;
/** 分页对象中的总数、页码和每页条数字段名。 */
totalKey?: string;
currentKey?: string;
sizeKey?: string;
} }
export function DataTable<T extends object>({ export function DataTable<T extends object>({
columns, columns,
showIndex, showIndex,
pagination, pagination,
actions, actions,
rowActions,
actionColumnTitle = '操作',
actionColumnWidth,
pageData,
recordsKey = 'records',
totalKey = 'total',
currentKey = 'current',
sizeKey = 'size',
...props ...props
}: DataTableProps<T>) { }: DataTableProps<T>) {
const page = pagination === false || !pagination ? undefined : pagination; const records = pageData?.[recordsKey];
const dataSource = Array.isArray(records) ? (records as T[]) : props.dataSource;
const resolvedPagination = pagination
? {
...pagination,
current: Number(pageData?.[currentKey] ?? pagination.current),
pageSize: Number(pageData?.[sizeKey] ?? pagination.pageSize),
total: Number(pageData?.[totalKey] ?? pagination.total),
}
: pagination;
const page = resolvedPagination || undefined;
const renderActionButton = (
action: Omit<ActionSchema, 'onClick'>,
onClick: () => void,
key: string,
isRowAction = false,
) => {
const buttonProps = {
key,
danger: action.danger,
disabled: action.disabled,
onClick,
...(isRowAction ? { type: 'link' as const } : {}),
};
return action.permission ? (
<PermButton permission={action.permission} {...buttonProps}>
{action.label}
</PermButton>
) : (
<UButton {...buttonProps}>{action.label}</UButton>
);
};
const actionColumn: ColumnsType<T>[number] | undefined = rowActions?.length
? {
title: actionColumnTitle,
key: '__actions',
width: actionColumnWidth,
render: (_: unknown, record: T) =>
rowActions
.filter((action) => action.visible?.(record) ?? true)
.map((action, index) =>
renderActionButton(action, () => action.onClick(record), `row-action-${index}`, true),
),
}
: undefined;
const tableColumns = showIndex const tableColumns = showIndex
? [ ? [
{ {
...@@ -37,45 +111,28 @@ export function DataTable<T extends object>({ ...@@ -37,45 +111,28 @@ export function DataTable<T extends object>({
((page?.current ?? 1) - 1) * (page?.pageSize ?? 0) + index + 1, ((page?.current ?? 1) - 1) * (page?.pageSize ?? 0) + index + 1,
}, },
...columns, ...columns,
...(actionColumn ? [actionColumn] : []),
] ]
: columns; : [...columns, ...(actionColumn ? [actionColumn] : [])];
return ( return (
<> <>
<div> <div>
{actions?.map((action) => {actions?.map((action, index) =>
action.permission ? ( renderActionButton(action, action.onClick, `toolbar-action-${index}`),
<PermButton
key={String(action.label)}
permission={action.permission}
danger={action.danger}
disabled={action.disabled}
onClick={action.onClick}
>
{action.label}
</PermButton>
) : (
<UButton
key={String(action.label)}
danger={action.danger}
disabled={action.disabled}
onClick={action.onClick}
>
{action.label}
</UButton>
),
)} )}
</div> </div>
<UTable <UTable
{...props} {...props}
dataSource={dataSource}
columns={tableColumns} columns={tableColumns}
pagination={ pagination={
pagination === false resolvedPagination === false
? false ? false
: pagination && { : resolvedPagination && {
current: pagination.current, current: resolvedPagination.current,
pageSize: pagination.pageSize, pageSize: resolvedPagination.pageSize,
total: pagination.total, total: resolvedPagination.total,
onChange: pagination.onChange, onChange: resolvedPagination.onChange,
} }
} }
/> />
......
...@@ -19,19 +19,26 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -19,19 +19,26 @@ export function SearchForm<T extends Record<string, unknown>>({
disabled: typeof field.disabled === 'boolean' ? field.disabled : false, disabled: typeof field.disabled === 'boolean' ? field.disabled : false,
placeholder: field.placeholder, placeholder: field.placeholder,
}; };
const width = field.width ?? (field.type === 'input' || field.type === 'textarea' ? 260 : 160);
if (field.type === 'select' || field.type === 'selectMultiple') if (field.type === 'select' || field.type === 'selectMultiple')
return ( return (
<USelect <USelect
{...common} {...common}
allowClear={false}
style={{ width }}
options={field.options} options={field.options}
mode={field.type === 'selectMultiple' ? 'multiple' : undefined} mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
/> />
); );
if (field.type === 'date') return <UDatePicker {...common} style={{ width: '100%' }} />; if (field.type === 'date') return <UDatePicker {...common} style={{ width }} />;
if (field.type === 'dateRange') if (field.type === 'dateRange')
return <UDatePicker.RangePicker disabled={common.disabled} style={{ width: '100%' }} />; return <UDatePicker.RangePicker disabled={common.disabled} style={{ width }} />;
if (field.type === 'radio') return <URadio.Group {...common} options={field.options} />; if (field.type === 'radio') return <URadio.Group {...common} options={field.options} />;
return field.type === 'textarea' ? <UInput.TextArea {...common} /> : <UInput {...common} />; return field.type === 'textarea' ? (
<UInput.TextArea {...common} style={{ width }} />
) : (
<UInput {...common} style={{ width }} />
);
}; };
return ( return (
<UForm <UForm
......
...@@ -11,6 +11,7 @@ export interface FieldSchema<T extends Record<string, unknown> = Record<string, ...@@ -11,6 +11,7 @@ export interface FieldSchema<T extends Record<string, unknown> = Record<string,
label: ReactNode; label: ReactNode;
type: FieldType; type: FieldType;
placeholder?: string; placeholder?: string;
width?: number | string;
options?: FieldOption[]; options?: FieldOption[];
hidden?: boolean | ((values: T) => boolean); hidden?: boolean | ((values: T) => boolean);
disabled?: boolean | ((values: T) => boolean); disabled?: boolean | ((values: T) => boolean);
......
...@@ -5,6 +5,6 @@ export { SearchForm } from './SearchForm'; ...@@ -5,6 +5,6 @@ export { SearchForm } from './SearchForm';
export type { SearchFormProps } from './SearchForm'; export type { SearchFormProps } from './SearchForm';
export type { ActionSchema, FieldOption, FieldSchema, FieldType } from './formSchema'; export type { ActionSchema, FieldOption, FieldSchema, FieldType } from './formSchema';
export { DataTable } from './DataTable'; export { DataTable } from './DataTable';
export type { DataTableProps } from './DataTable'; export type { DataTableProps, RowActionSchema } from './DataTable';
export { CombiForm } from './CombiForm'; export { CombiForm } from './CombiForm';
export type { CombiFormProps } from './CombiForm'; export type { CombiFormProps } from './CombiForm';
...@@ -29,7 +29,7 @@ export function LoginForm() { ...@@ -29,7 +29,7 @@ export function LoginForm() {
['SYS_ADMIN', 'YJ_FINANCE_MGR', 'ONLINE_OPS', 'OPS_LEADER', 'VIEWER'].includes(role), ['SYS_ADMIN', 'YJ_FINANCE_MGR', 'ONLINE_OPS', 'OPS_LEADER', 'VIEWER'].includes(role),
) ?? 'VIEWER') as RoleKey; ) ?? 'VIEWER') as RoleKey;
login({ name: session.name || session.account, role: r }); login({ name: session.name || session.account, role: r });
// 设置角色并加载该角色的权限点(来源见 src/access/permissionsSource.ts,目前为 mock) // 设置角色后读取本地用户信息中的 permCodes,用于按钮权限判定。
await setRole(r); await setRole(r);
message.success(`欢迎回来,${session.name || session.account}`); message.success(`欢迎回来,${session.name || session.account}`);
setTimeout(() => navigate('/'), 350); setTimeout(() => navigate('/'), 350);
...@@ -41,7 +41,7 @@ export function LoginForm() { ...@@ -41,7 +41,7 @@ export function LoginForm() {
const session = await system.login(values); const session = await system.login(values);
saveLoginSession(session); saveLoginSession(session);
const userInfo = await system.info(); const userInfo = await system.info();
saveUserInfo(userInfo); saveUserInfo(userInfo, session.permCodes);
await doLogin(session); await doLogin(session);
} catch (error) { } catch (error) {
console.error('登录流程失败', error); console.error('登录流程失败', error);
......
import PagePlaceholder from '@/components/PagePlaceholder'; import { useMemo, useState } from 'react';
import { Skeleton } from '@uj/ui'; import { useQuery } from '@tanstack/react-query';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { UAlert, UButton, UCard, UTag, UText, UTitle } from '@uj/ui';
import { DataTable, SearchForm, type FieldSchema, type RowActionSchema } from '@/components';
import { P } from '@/access';
import { role, type RolePageParams } from '@/api';
import { getBaseList } from './tools/constants';
interface Row {
id: number;
name: string;
code: string;
scope: string;
accounts: number;
description: string;
type: string;
status?: number;
}
export default function RoleManage() { export default function RoleManage() {
const loading = false; const [params, setParams] = useState<RolePageParams>({
if (loading) return <Skeleton variant="default" />; current: 1,
return <PagePlaceholder title="角色管理" description="角色定义与权限分配(建设中)" />; size: 20,
isBuiltin: undefined,
status: undefined,
defaultDataScope: undefined,
});
const [queryVersion, setQueryVersion] = useState(0);
const [page, setPage] = useState(1);
const {
data: result,
isLoading,
isFetching,
} = useQuery({ queryKey: ['role-page', params, queryVersion], queryFn: () => role.page(params) });
const data = useMemo(
() =>
result?.records?.map((item) => ({
id: item.roleId,
name: item.roleName,
code: item.roleCode,
scope:
{ 1: '全部数据', 2: '本部门及下级', 3: '本部门', 4: '仅本人' }[item.defaultDataScope] ??
'—',
accounts: item.accountCount,
description: item.description ?? '—',
type: item.isBuiltin === 1 ? '内置' : '自定义',
status: item.status,
})) ?? [],
[result],
);
const fields: FieldSchema<Record<string, unknown>>[] = [
{ name: 'keyword', label: '角色名称 / 编码', type: 'input', placeholder: '模糊搜索' },
{
name: 'type',
label: '类型',
type: 'select',
options: getBaseList('roleType'),
},
{
name: 'status',
label: '状态',
type: 'select',
options: getBaseList('roleStatus'),
},
{
name: 'scope',
label: '默认数据域',
type: 'select',
options: getBaseList('dataScope'),
},
];
const columns: ColumnsType<Row> = [
{ title: '角色名称', dataIndex: 'name', width: 150 },
{
title: '角色编码',
dataIndex: 'code',
width: 150,
render: (v) => <UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{v}</UText>,
},
{ title: '默认数据域', dataIndex: 'scope', width: 130 },
{ title: '账号数', dataIndex: 'accounts', width: 90, align: 'right' },
{ title: '角色描述', dataIndex: 'description' },
{
title: '类型',
dataIndex: 'type',
width: 90,
render: (v) => <UTag color={v === '内置' ? 'geekblue' : 'default'}>{v}</UTag>,
},
{
title: '状态',
width: 90,
render: (_, r) => (
<UTag color={r.status === 1 ? 'green' : 'default'}>
● {r.status === 1 ? '启用' : '停用'}
</UTag>
),
},
];
const rowActions: RowActionSchema<Row>[] = [
{ label: '查看详情', permission: P.SYSTEM_ROLE_VIEW, onClick: () => undefined },
{ label: '编辑', permission: P.SYSTEM_ROLE_EDIT, onClick: () => undefined },
{
label: '删除',
permission: P.SYSTEM_ROLE_EDIT,
danger: true,
onClick: () => undefined,
},
];
return (
<div style={{ padding: 10, display: 'flex', flexDirection: 'column', gap: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div>
<UTitle level={3} style={{ margin: 0 }}>
角色管理
</UTitle>
<UText type="secondary">
维护角色清单与基本信息,支持按关键字筛选;角色的菜单可见范围在「查看详情」中配置。
</UText>
</div>
<UButton icon={<PlusOutlined />}>新增角色</UButton>
</div>
<UCard size="small">
<SearchForm
fields={fields}
initialValues={{ type: '', status: '', scope: '' }}
onSearch={(v) => {
setPage(1);
setParams({
current: 1,
size: 20,
keyword: v.keyword as string,
isBuiltin: v.type === '' ? undefined : Number(v.type),
status: v.status === '' ? undefined : Number(v.status),
defaultDataScope: v.scope === '' ? undefined : Number(v.scope),
});
setQueryVersion((version) => version + 1);
}}
onReset={() => {
setPage(1);
setParams({ current: 1, size: 20 });
setQueryVersion((version) => version + 1);
}}
/>
<div style={{ marginTop: 12 }}>
<UText type="secondary">数据可见范围:全部数据(超级管理员)</UText>
</div>
</UCard>
<UCard size="small" styles={{ body: { padding: 0 } }}>
<DataTable<Row>
rowKey="id"
columns={columns}
rowActions={rowActions}
actionColumnWidth={170}
loading={isLoading || isFetching}
pageData={result ? { ...result, records: data } : undefined}
recordsKey="records"
pagination={{
current: page,
pageSize: params.size ?? 20,
total: result?.total ?? 0,
onChange: (current, size) => {
setPage(current);
setParams((prev) => ({ ...prev, current, size }));
setQueryVersion((version) => version + 1);
},
}}
/>
</UCard>
<UAlert
type="info"
showIcon
message="查看与配置入口:点击列表“查看详情”打开抽屉,抽屉内同时承载角色基本信息与菜单可见范围(权限矩阵),可直接编辑并保存。"
/>
</div>
);
} }
import type { FieldOption } from '@/components';
/** 角色管理页专用的下拉选项。 */
export const baseList = {
roleType: [
{ label: '内置', value: 1 },
{ label: '自定义', value: 0 },
],
roleStatus: [
{ label: '启用', value: 1 },
{ label: '停用', value: 0 },
],
dataScope: [
{ label: '全部数据', value: 1 },
{ label: '本部门及下级', value: 2 },
{ label: '本部门', value: 3 },
{ label: '仅本人', value: 4 },
],
} satisfies Record<string, FieldOption[]>;
export function getBaseList(key: keyof typeof baseList, includeAll = true): FieldOption[] {
return includeAll ? [{ label: '全部', value: '' }, ...baseList[key]] : baseList[key];
}
import { create } from 'zustand'; import { create } from 'zustand';
import { clearLoginSession, getLoginSession } from '@/access/session';
const savedSession = getLoginSession();
interface AppState { interface AppState {
collapsed: boolean; collapsed: boolean;
...@@ -13,9 +16,15 @@ interface AppState { ...@@ -13,9 +16,15 @@ interface AppState {
export const useAppStore = create<AppState>((set) => ({ export const useAppStore = create<AppState>((set) => ({
collapsed: false, collapsed: false,
toggleCollapsed: () => set((s) => ({ collapsed: !s.collapsed })), toggleCollapsed: () => set((s) => ({ collapsed: !s.collapsed })),
currentUser: { name: '管理员', role: 'admin' }, currentUser: {
name: savedSession?.name || savedSession?.account || '管理员',
role: savedSession?.roleCodes?.[0] || 'admin',
},
setCurrentUser: (u) => set({ currentUser: u }), setCurrentUser: (u) => set({ currentUser: u }),
loggedIn: false, loggedIn: Boolean(savedSession),
login: (u) => set({ loggedIn: true, currentUser: u }), login: (u) => set({ loggedIn: true, currentUser: u }),
logout: () => set({ loggedIn: false }), logout: () => {
clearLoginSession();
set({ loggedIn: false });
},
})); }));
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!