diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bd8f72..c1fb188 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## 0.4.0 +- Добавлен экран управления доступами приложений +- Исправлены корневые стили приложения +- Обновлена поддержка пользовательских разрешений для страниц +- Добавлена локализация Antd ## 0.3.2 - Добавлен generateVersionFile.cjs ## 0.3.1 diff --git a/package.json b/package.json index 5deddeb..34396f7 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "isp-admin-ui", "private": true, - "version": "0.3.2", + "version": "0.4.0", "type": "module", "scripts": { "start": "vite", diff --git a/src/components/AdminPermission/index.tsx b/src/components/AdminPermission/index.tsx index 8fe29b8..310f505 100644 --- a/src/components/AdminPermission/index.tsx +++ b/src/components/AdminPermission/index.tsx @@ -7,7 +7,7 @@ import { PermissionKeys } from '@type/roles.type.ts' const AdminPermission = ({ children }: PropsWithChildren) => { const { hasPermission } = useRole() - if (hasPermission(PermissionKeys.admin_view)) { + if (hasPermission(PermissionKeys.read)) { return <>{children} } return null diff --git a/src/components/App.tsx b/src/components/App.tsx index 1b90113..0f72692 100644 --- a/src/components/App.tsx +++ b/src/components/App.tsx @@ -1,4 +1,5 @@ import { ConfigProvider } from 'antd' +import ruRu from 'antd/locale/ru_RU' import { useState } from 'react' import { lightTheme } from '@constants/theme.ts' @@ -15,7 +16,7 @@ const App = () => { return (
- + diff --git a/src/components/AppAccessContent/app-access-content.scss b/src/components/AppAccessContent/app-access-content.scss new file mode 100644 index 0000000..72cc6f7 --- /dev/null +++ b/src/components/AppAccessContent/app-access-content.scss @@ -0,0 +1,36 @@ +@import 'src/constants/style/styleConst'; + +.app-access-content { + height: 100%; + width: 100%; + min-width: 760px; + + padding: $basic-padding * 2; + border: 1px solid $border-color; + + &__header { + display: flex; + justify-content: space-between; + margin-bottom: $basic-margin * 2; + + &__action-buttons { + display: flex; + gap: $basic-margin * 2; + } + } + + &__main { + display: grid; + grid-template-columns:1fr 1fr; + + + &__tree-search-input { + width: 350px; + margin-bottom: $basic-margin * 2; + } + } + + .unknown-label { + color: $error-red + } +} diff --git a/src/components/AppAccessContent/app-access-content.type.ts b/src/components/AppAccessContent/app-access-content.type.ts new file mode 100644 index 0000000..3eb7c73 --- /dev/null +++ b/src/components/AppAccessContent/app-access-content.type.ts @@ -0,0 +1,4 @@ +export interface AppAccessContentPropsType { + id: number + paramPrefix: string +} diff --git a/src/components/AppAccessContent/index.tsx b/src/components/AppAccessContent/index.tsx new file mode 100644 index 0000000..b62d59a --- /dev/null +++ b/src/components/AppAccessContent/index.tsx @@ -0,0 +1,208 @@ +import { SearchOutlined } from '@ant-design/icons' +import { Button, Input, message, Spin, TreeProps } from 'antd' +import { ChangeEvent, FC, memo, useEffect, useState } from 'react' +import { Navigate, useSearchParams } from 'react-router-dom' + +import AccessListTree from '@widgets/AccessListTree' +import SelectedAccessMethod from '@widgets/SelectedAccessMethod' + +import { AppAccessContentPropsType } from '@components/AppAccessContent/app-access-content.type.ts' + +import { setSearchValue } from '@utils/columnLayoutUtils.ts' + +import useRole from '@hooks/useRole.tsx' + +import accessListApi from '@services/accessListService.ts' +import routeApi from '@services/routeService.ts' + +import { routePaths } from '@routes/routePaths.ts' + +import { AccessListMethodType, EndpointType } from '@type/accessList.type.ts' +import { PermissionKeys } from '@type/roles.type.ts' + +import './app-access-content.scss' + + +const unknownMethodKey = 'неизвестные методы' + +const AppAccessContent: FC = ({ + id, + paramPrefix +}) => { + const [messageApi, contextHolder] = message.useMessage() + const { hasPermission } = useRole() + + const canWrite = hasPermission(PermissionKeys.write) + + const { + data: methods = [], + isLoading: isMethodsLoading, + isError: isMethodsError, + isSuccess: isMethodsSuccess + } = accessListApi.useGetByIdQuery({ id }) + const [setList] = accessListApi.useSetListMutation() + const [setOne] = accessListApi.useSetOneMutation() + + const { + data: routes = { + originalResponse: [], + moduleEndpoints: {}, + allRouteMap: {} + }, + isLoading: isRouteLoading, + isError: isRouteError, + isSuccess: isRouteSuccess + } = routeApi.useGetAllRoutesQuery() + const { moduleEndpoints, allRouteMap } = routes + const [defaultAllRoutes, setDefaultAllRoutes] = useState< + Record + >({}) + + const [searchParams, setSearchParams] = useSearchParams() + const searchValue = searchParams.get(paramPrefix) || '' + + const isLoading = isMethodsLoading || isRouteLoading + const isError = isMethodsError || isRouteError + const isSuccess = isMethodsSuccess && isRouteSuccess + + const openSuccessMessage = (body: string) => { + messageApi.success(body) + } + + const openErrorMessage = (body: string) => { + messageApi.error(body) + } + + const createAllMethodList = (status: boolean) => { + return Object.keys(allRouteMap).map((key) => { + return { + method: key, + value: status + } + }) + } + + const onCheck: TreeProps['onCheck'] = (_, info): void | never[] => { + const { node } = info + if (!node.children) { + const sendData = { + appId: id, + method: node.key as string, + value: !node.checked + } + setOne(sendData) + .then(() => { + openSuccessMessage('Статус метода успешно изменен') + }) + .catch(() => { + openErrorMessage('Не удалось изменить статус метода') + }) + return + } + + const newCheckedKeys = node.children.map((child) => ({ + method: child.key as string, + value: !node.checked + })) + setListMethods(newCheckedKeys) + } + + const onChange = (e: ChangeEvent) => { + const { value } = e.target + setSearchValue(value.trim().toLowerCase(), setSearchParams, paramPrefix) + } + + const setListMethods = (methods: AccessListMethodType[]) => { + setList({ + appId: id, + methods: methods + }) + .then(() => { + openSuccessMessage('Статус методов успешно изменен') + }) + .catch(() => { + openErrorMessage('Не удалось изменить статус методов') + }) + } + + const setAllMethods = (status: boolean) => { + const methods = createAllMethodList(status) + setListMethods(methods) + } + + const getAllRoutes = () => { + const missingRoute: EndpointType[] = [] + const copyAllRoutes = { ...moduleEndpoints } + + methods.forEach((item) => { + if (!allRouteMap[item.method]) { + missingRoute.push({ path: item.method } as EndpointType) + } + }) + + if (missingRoute.length) { + copyAllRoutes[unknownMethodKey] = missingRoute + } + return copyAllRoutes + } + + useEffect(() => { + const allRoutes = getAllRoutes() + setDefaultAllRoutes(allRoutes) + }, [isSuccess]) + + if (isLoading) { + return + } + + if (isError) { + return + } + return ( +
+ {contextHolder} +
+ } + allowClear + className="app-access-content__main__tree-search-input" + value={searchValue} + placeholder="Найти метод" + onChange={onChange} + /> +
+ + +
+
+
+ + +
+
+ ) +} + +export default memo(AppAccessContent) diff --git a/src/components/Layout/index.tsx b/src/components/Layout/index.tsx index a8f4e17..fdffbf5 100644 --- a/src/components/Layout/index.tsx +++ b/src/components/Layout/index.tsx @@ -1,7 +1,7 @@ -import { ProfileOutlined } from '@ant-design/icons' +import { LockOutlined, ProfileOutlined } from '@ant-design/icons' import { Divider, Layout, Menu, Spin } from 'antd' import { useEffect, useState } from 'react' -import { Navigate, Outlet, useLocation } from 'react-router-dom' +import { Navigate, Outlet, useLocation, useNavigate } from 'react-router-dom' import { localStorageKeys } from '@constants/localStorageKeys.ts' @@ -26,10 +26,11 @@ import { PermissionKeys } from '@type/roles.type.ts' import './layout.scss' - const { Content, Sider } = Layout const LayoutComponent = () => { + const navigate = useNavigate() + const [collapsed, setCollapsed] = useState(false) const [selectedMenuKeys, setSelectedMenuKeys] = useState([]) const [openKeys, setOpenKeys] = useState([]) @@ -51,16 +52,22 @@ const LayoutComponent = () => { return hasPermission(permission) ? '' : 'hide-item' } const menuItems: MenuItemType[] = [ + { + label: 'Доступы приложений', + key: 'appAccess', + className: hideItem([PermissionKeys.read]), + icon: + }, { label: 'Пользователи и роли', key: 'sessionManagement', - className: hideItem([PermissionKeys.user_view]), + className: hideItem([PermissionKeys.read]), icon: , children: [ { label: 'Пользователи', key: 'users', - className: hideItem(PermissionKeys.user_view) + className: hideItem(PermissionKeys.read) } ] } @@ -85,6 +92,9 @@ const LayoutComponent = () => { const handlerOnClickMenu = ({ key }: any): void => { switch (key) { + case MenuItemKeys.appAccess: + navigate(routePaths.appAccess) + break default: } } diff --git a/src/components/Layout/layout.type.ts b/src/components/Layout/layout.type.ts index 414fad7..c3027ad 100644 --- a/src/components/Layout/layout.type.ts +++ b/src/components/Layout/layout.type.ts @@ -1,7 +1,8 @@ import { MenuProps } from 'antd' export enum MenuItemKeys { - users = 'users' + users = 'users', + appAccess = 'appAccess' } type MenuItem = { @@ -12,6 +13,10 @@ export const menuKeys: Record = { [MenuItemKeys.users]: { key: MenuItemKeys.users, parent: ['sessionManagement'] + }, + [MenuItemKeys.appAccess]: { + key: MenuItemKeys.appAccess, + parent: [] } } diff --git a/src/components/app.scss b/src/components/app.scss index 3242ed2..7f1477f 100644 --- a/src/components/app.scss +++ b/src/components/app.scss @@ -7,6 +7,8 @@ } .app{ + overflow: hidden; + height: 100vh; padding: 0 $basic-padding; min-height: 0; min-width: 500px; diff --git a/src/constants/api/apiPaths.ts b/src/constants/api/apiPaths.ts index 682273e..97f220e 100644 --- a/src/constants/api/apiPaths.ts +++ b/src/constants/api/apiPaths.ts @@ -1,5 +1,7 @@ type PathKeys = | 'baseUrl' + | 'baseSystemUrl' + | 'baseConfigUrl' | 'getAllRoles' | 'createRole' | 'updateRole' @@ -7,8 +9,15 @@ type PathKeys = | 'login' | 'logout' | 'getProfile' + | 'getSystemTree' + | 'getById' + | 'setList' + | 'setOne' + | 'getAllRoutes' export const apiPaths: Record = { baseUrl: '/api/admin', + baseSystemUrl: '/api/system', + baseConfigUrl: '/api/config', // ======= ROLES ====== getAllRoles: '/role/all', createRole: '/role/create', @@ -18,5 +27,12 @@ export const apiPaths: Record = { login: '/api/admin/auth/login', logout: '/api/admin/auth/logout', // ======= PROFILE ====== - getProfile: '/api/admin/user/get_profile' + getProfile: '/api/admin/user/get_profile', + // ======= APPLICATIONS ====== + getSystemTree: '/application/get_system_tree', + // ======= ACCESS_LIST ====== + getById: '/access_list/get_by_id', + setList: '/access_list/set_list', + setOne: '/access_list/set_one', + getAllRoutes: '/routing/get_routes' } diff --git a/src/constants/style/styleConst.scss b/src/constants/style/styleConst.scss index 363632d..870ffa5 100644 --- a/src/constants/style/styleConst.scss +++ b/src/constants/style/styleConst.scss @@ -7,5 +7,7 @@ $text-size-header2: 1.25rem; $text-color-gray: var(--ant-primary-color); $background-color: #F0F2F5; -$grey:#606060; +$grey: #606060; +$border-color: #d9d9d9; +$error-red: #cf1322; diff --git a/src/index.tsx b/src/index.tsx index 73f7703..17e575d 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -7,6 +7,9 @@ import App from './components/App.tsx' import { setupStore } from './stores' +import 'simplebar-react/dist/simplebar.min.css' + + const store = setupStore() setupListeners(store.dispatch) const root = createRoot(document.getElementById('root') as HTMLElement) diff --git a/src/pages/AppAccessPage/app-access-page.scss b/src/pages/AppAccessPage/app-access-page.scss new file mode 100644 index 0000000..57849f5 --- /dev/null +++ b/src/pages/AppAccessPage/app-access-page.scss @@ -0,0 +1,15 @@ +@import "src/constants/style/styleConst"; + +.app-access-page { + display: flex; + height: 100%; + + .ant-tree { + background: none; + } + + &__content-wrap{ + width: 100%; + overflow-x: scroll; + } +} diff --git a/src/pages/AppAccessPage/app-access-page.type.ts b/src/pages/AppAccessPage/app-access-page.type.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/pages/AppAccessPage/index.tsx b/src/pages/AppAccessPage/index.tsx new file mode 100644 index 0000000..fd00d4d --- /dev/null +++ b/src/pages/AppAccessPage/index.tsx @@ -0,0 +1,111 @@ +import { Spin } from 'antd' +import { Layout } from 'isp-ui-kit' +import { ColumnItem } from 'isp-ui-kit/dist/Layout/Column/column.type' +import { memo, useEffect } from 'react' +import { + createSearchParams, + Navigate, + useNavigate, + useParams, + useSearchParams +} from 'react-router-dom' + +import ListItem from '@widgets/ListItem' + +import AppAccessContent from '@components/AppAccessContent' + +import { setSearchValue, setSelectedItemId } from '@utils/columnLayoutUtils.ts' +import { filterFirstColumnItems } from '@utils/firstColumnUtils.ts' + +import useRole from '@hooks/useRole.tsx' + +import appApi from '@services/appService.ts' + +import { routePaths } from '@routes/routePaths.ts' + +import { SystemTreeAppType } from '@type/app.type.ts' +import { PermissionKeys } from '@type/roles.type.ts' + +import './app-access-page.scss' + + +const { Column, EmptyData } = Layout + +const firstColumnSearchParam = 'search' +const findMethodParam = 'method' + +const AppAccessPage = () => { + const { + data = { originalResponse: [], appList: [] }, + isLoading, + isError + } = appApi.useGetSystemTreeQuery() + + const { appList } = data + const navigate = useNavigate() + const { hasPermission } = useRole() + + const { id: selectedItemId = '' } = useParams() + const [searchParams, setSearchParams] = useSearchParams() + const searchValue = searchParams.get(firstColumnSearchParam) || '' + const canRead = hasPermission(PermissionKeys.read) + + useEffect(() => { + if (!canRead) { + navigate(routePaths.home) + } + }, [canRead]) + + const handleOnChangeSearchValue = (value: string): void => { + setSearchValue(value, setSearchParams) + } + + const onSelectedItemId = (id: string): void => { + setSearchValue('', setSearchParams, findMethodParam) + setSelectedItemId( + routePaths.appAccess, + id, + createSearchParams(searchParams).toString(), + navigate + ) + } + + if (isLoading) { + return + } + + if (isError) { + return + } + + return ( +
+ , + searchValue + )} + renderItems={(item) => } + searchValue={searchValue} + selectedItemId={selectedItemId} + setSelectedItemId={onSelectedItemId} + onChangeSearchValue={handleOnChangeSearchValue} + /> +
+ {selectedItemId ? ( + + ) : ( + + )} +
+
+ ) +} + +export default memo(AppAccessPage) diff --git a/src/routes/PrivateRoute/index.tsx b/src/routes/PrivateRoute/index.tsx index 4a2161c..d750a9f 100644 --- a/src/routes/PrivateRoute/index.tsx +++ b/src/routes/PrivateRoute/index.tsx @@ -6,6 +6,7 @@ import { LocalStorage } from '@utils/localStorageUtils.ts' import { routePaths } from '@routes/routePaths.ts' + const PrivateRoute = () => { const location = useLocation() const userToken = LocalStorage.get(localStorageKeys.USER_TOKEN) diff --git a/src/routes/Routers/index.tsx b/src/routes/Routers/index.tsx index b8fb38f..c5f233d 100644 --- a/src/routes/Routers/index.tsx +++ b/src/routes/Routers/index.tsx @@ -1,5 +1,5 @@ import { Spin } from 'antd' -import { Suspense, lazy } from 'react' +import { lazy, Suspense } from 'react' import { Route, Routes } from 'react-router-dom' import Layout from '@components/Layout' @@ -10,11 +10,9 @@ import PrivateRoute from '@routes/PrivateRoute' import { routePaths } from '@routes/routePaths.ts' const LoginPage = lazy(() => import('@pages/LoginPage')) - const ErrorPage = lazy(() => import('@components/ErrorPage')) - - const ProfilePage = lazy(() => import('@pages/ProfilePage')) +const AppAccessPage = lazy(() => import('@pages/AppAccessPage')) const Routers = () => { return ( @@ -29,17 +27,35 @@ const Routers = () => { } /> + }> + + + } + /> + }> + + + } + > }> - + } /> - + }> diff --git a/src/routes/routePaths.ts b/src/routes/routePaths.ts index 48a720b..b46d0f1 100644 --- a/src/routes/routePaths.ts +++ b/src/routes/routePaths.ts @@ -1,9 +1,16 @@ -type RoutePaths = 'home' | 'notFound' | 'error' | 'login' | 'profile' +type RoutePaths = + | 'home' + | 'notFound' + | 'error' + | 'login' + | 'profile' + | 'appAccess' export const routePaths: Record = { home: '/', error: '/error', notFound: '*', login: '/login', - profile: '/profile' + profile: '/profile', + appAccess: '/appAccess' } diff --git a/src/services/accessListService.ts b/src/services/accessListService.ts new file mode 100644 index 0000000..0b22cdf --- /dev/null +++ b/src/services/accessListService.ts @@ -0,0 +1,35 @@ +import { createApi } from '@reduxjs/toolkit/query/react' + +import { apiPaths } from '@constants/api/apiPaths.ts' + +import { axiosBaseQuery } from '@utils/apiUtils.ts' + +import { + AccessListMethodType, + AccessListSetListRequestType, + AccessListSetListSetOneRequestType +} from '@type/accessList.type.ts' + + +const accessListApi = createApi({ + reducerPath: 'accessListApi', + refetchOnFocus: true, + tagTypes: ['AccessItems'], + baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseSystemUrl }), + endpoints: (builder) => ({ + getById: builder.query({ + query: ({ id }) => ({ url: apiPaths.getById, data: { id } }), + providesTags: () => ['AccessItems'] + }), + setList: builder.mutation({ + query: (data) => ({ url: apiPaths.setList, data }), + invalidatesTags: () => ['AccessItems'] + }), + setOne: builder.mutation({ + query: (data) => ({ url: apiPaths.setOne, data }), + invalidatesTags: () => ['AccessItems'] + }) + }) +}) + +export default accessListApi diff --git a/src/services/appService.ts b/src/services/appService.ts new file mode 100644 index 0000000..eec1c33 --- /dev/null +++ b/src/services/appService.ts @@ -0,0 +1,33 @@ +import { createApi } from '@reduxjs/toolkit/query/react' + +import { apiPaths } from '@constants/api/apiPaths.ts' + +import { axiosBaseQuery } from '@utils/apiUtils.ts' + +import { AppApiResponseType, DomainType } from '@type/app.type.ts' + + +const appApi = createApi({ + reducerPath: 'appService', + refetchOnFocus: true, + tagTypes: ['SystemTreeApps'], + baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseSystemUrl }), + endpoints: (builder) => ({ + getSystemTree: builder.query({ + query: () => ({ url: apiPaths.getSystemTree }), + transformResponse: (response: DomainType[]) => { + const apps = response.flatMap(({ services }) => + services.flatMap(({ apps }) => apps) + ) + + return { + originalResponse: response, + appList: apps + } + }, + providesTags: () => ['SystemTreeApps'] + }) + }) +}) + +export default appApi diff --git a/src/services/routeService.ts b/src/services/routeService.ts new file mode 100644 index 0000000..9f048de --- /dev/null +++ b/src/services/routeService.ts @@ -0,0 +1,50 @@ +import { createApi } from '@reduxjs/toolkit/query/react' + +import { apiPaths } from '@constants/api/apiPaths.ts' + +import { axiosBaseQuery } from '@utils/apiUtils.ts' + +import { + EndpointType, + RouteApiResponseType, + RouteType +} from '@type/accessList.type.ts' + + +const routeApi = createApi({ + reducerPath: 'routeApi', + refetchOnFocus: true, + tagTypes: ['Routes'], + baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseConfigUrl }), + endpoints: (builder) => ({ + getAllRoutes: builder.query({ + query: () => ({ url: apiPaths.getAllRoutes }), + transformResponse: (response: RouteType[]) => { + const moduleEndpoints: Record = {} + const allRouteMap: Record = {} + + response.forEach((route) => { + if (route.endpoints && route.endpoints.length) { + moduleEndpoints[route.moduleName] = route.endpoints + } + }) + Object.keys(moduleEndpoints) + .sort() + .forEach((groupName) => { + moduleEndpoints[groupName].forEach((method) => { + allRouteMap[method.path] = method + }) + }) + + return { + originalResponse: response, + moduleEndpoints: moduleEndpoints, + allRouteMap: allRouteMap + } + }, + providesTags: () => ['Routes'] + }) + }) +}) + +export default routeApi diff --git a/src/stores/index.tsx b/src/stores/index.tsx index c9fcea7..65be389 100644 --- a/src/stores/index.tsx +++ b/src/stores/index.tsx @@ -3,7 +3,10 @@ import { theme } from 'antd' import { MapToken, SeedToken } from 'antd/es/theme/interface' import { createContext, Dispatch, SetStateAction } from 'react' +import accessListApi from '@services/accessListService.ts' +import appApi from '@services/appService.ts' import roleApi from '@services/roleService.ts' +import routeApi from '@services/routeService.ts' import profileReducer from './redusers/ProfileSlice.ts' @@ -20,14 +23,22 @@ export const Context = createContext({ const rootReducer = combineReducers({ profileReducer, - [roleApi.reducerPath]: roleApi.reducer + [roleApi.reducerPath]: roleApi.reducer, + [appApi.reducerPath]: appApi.reducer, + [accessListApi.reducerPath]: accessListApi.reducer, + [routeApi.reducerPath]: routeApi.reducer }) export const setupStore = () => configureStore({ reducer: rootReducer, middleware: (getDefaultMiddleware) => - getDefaultMiddleware().concat([roleApi.middleware]) + getDefaultMiddleware().concat( + roleApi.middleware, + appApi.middleware, + accessListApi.middleware, + routeApi.middleware + ) }) export type RootState = ReturnType diff --git a/src/type/accessList.type.ts b/src/type/accessList.type.ts new file mode 100644 index 0000000..8295f19 --- /dev/null +++ b/src/type/accessList.type.ts @@ -0,0 +1,48 @@ +export interface AccessListMethodType { + method: string + value: boolean +} + +export interface AccessListSetListRequestType { + appId: number + methods: AccessListMethodType[] + removeOld?: boolean +} + +export interface AccessListSetListSetOneRequestType { + appId: number + method: string + value: boolean +} + +export interface EndpointType { + extra: Record + inner: boolean + path: string + userAuthRequired: boolean +} + +export type AddressType = { + ip: string + port: string +} + +export type RequiredModuleType = { + name: string + required: boolean +} + +export type RouteType = { + address: AddressType + endpoints: EndpointType[] + libVersion: string + moduleName: string + requiredModules: RequiredModuleType[] + version: string +} + +export interface RouteApiResponseType { + originalResponse: RouteType[] + moduleEndpoints: Record + allRouteMap: Record +} diff --git a/src/type/app.type.ts b/src/type/app.type.ts new file mode 100644 index 0000000..138ddeb --- /dev/null +++ b/src/type/app.type.ts @@ -0,0 +1,33 @@ +interface TokenType { + appId: boolean + createdAt: string + expireTime: boolean + token: string +} + +export interface SystemTreeAppType { + description: string + id: boolean + name: string + tokens: TokenType[] + type: string +} + +interface SystemServiceType { + apps: SystemTreeAppType[] + description: string + id: boolean + name: string +} + +export interface DomainType { + description: string + id: boolean + name: string + services: SystemServiceType[] +} + +export interface AppApiResponseType { + originalResponse: DomainType[] + appList: SystemTreeAppType[] +} diff --git a/src/type/roles.type.ts b/src/type/roles.type.ts index fea0891..ce617ac 100644 --- a/src/type/roles.type.ts +++ b/src/type/roles.type.ts @@ -4,11 +4,8 @@ export enum RoleKeys { } export enum PermissionKeys { - user_view = 'user_view', // Просмотр списка пользователей - admin_view = 'admin_view', // роль суперадмина, требуется для интерфейса - session_view = 'session_view', // Просмотр списка пользовательских сессий - security_log_view = 'security_log_view', // Просмотр журналов ИБ - role_view = 'role_view', // Просмотр экрана ролей + read = 'read', // Просмотр страниц + write = 'write', // Редактирование страниц } export type RoleType = { diff --git a/src/utils/columnLayoutUtils.ts b/src/utils/columnLayoutUtils.ts new file mode 100644 index 0000000..0161c8e --- /dev/null +++ b/src/utils/columnLayoutUtils.ts @@ -0,0 +1,31 @@ +import { NavigateFunction, SetURLSearchParams } from 'react-router-dom' + +export const setSelectedItemId = ( + path: string, + id: string, + searchParams: string, + navigate: NavigateFunction +): void => { + navigate( + { + pathname: `${path}/${id}`, + search: searchParams + }, + { replace: true } + ) +} + +export const setSearchValue = ( + value: string, + setSearchParams: SetURLSearchParams, + prefix: string = 'search' +) => { + setSearchParams((prev) => { + if (!value) { + prev.delete(prefix) + } else { + prev.set(prefix, value) + } + return prev + }) +} diff --git a/src/utils/firstColumnUtils.ts b/src/utils/firstColumnUtils.ts new file mode 100644 index 0000000..026d31e --- /dev/null +++ b/src/utils/firstColumnUtils.ts @@ -0,0 +1,11 @@ +import { ColumnItem } from 'isp-ui-kit/dist/Layout/Column/column.type' + +export const filterFirstColumnItems = >( + listItems: ColumnItem[], + searchValue: string +): ColumnItem[] => + listItems + ? listItems.filter((el) => + el.name.toLowerCase().trim().includes(searchValue.toLowerCase().trim()) + ) + : [] diff --git a/src/widgets/AccessListTree/access-list-tree.scss b/src/widgets/AccessListTree/access-list-tree.scss new file mode 100644 index 0000000..144b8b7 --- /dev/null +++ b/src/widgets/AccessListTree/access-list-tree.scss @@ -0,0 +1,5 @@ +.access-list-tree{ + overflow-y: scroll; + height: calc(100vh - 130px); + +} diff --git a/src/widgets/AccessListTree/access-list-tree.type.ts b/src/widgets/AccessListTree/access-list-tree.type.ts new file mode 100644 index 0000000..bedd2ad --- /dev/null +++ b/src/widgets/AccessListTree/access-list-tree.type.ts @@ -0,0 +1,11 @@ +import { TreeProps } from 'antd' + +import { AccessListMethodType, EndpointType } from '@type/accessList.type.ts' + + +export interface AccessListTreePropsType { + searchValue: string + defaultAllRoutes: Record + methods: AccessListMethodType[] + onCheck: TreeProps['onCheck'] +} diff --git a/src/widgets/AccessListTree/index.tsx b/src/widgets/AccessListTree/index.tsx new file mode 100644 index 0000000..bac898d --- /dev/null +++ b/src/widgets/AccessListTree/index.tsx @@ -0,0 +1,137 @@ +import { WarningOutlined } from '@ant-design/icons' +import { Tag, Tree, TreeProps } from 'antd' +import { FC, memo, useCallback, useEffect, useState } from 'react' + +import { AccessListTreePropsType } from '@widgets/AccessListTree/access-list-tree.type.ts' + +import useRole from '@hooks/useRole.tsx' + +import { EndpointType } from '@type/accessList.type.ts' +import { PermissionKeys } from '@type/roles.type.ts' + +import './access-list-tree.scss' + + +const unknownMethodKey = 'неизвестные методы' + +const AccessListTree: FC = ({ + searchValue, + defaultAllRoutes, + methods, + onCheck = [] +}) => { + const { hasPermission } = useRole() + const [checkedKeys, setCheckedKeys] = useState([]) + const [expandedKeys, setExpandedKeys] = useState([]) + + const createTreeData = (data: Record) => { + return Object.keys(data) + .sort() + .map((routeKey) => { + if (routeKey === unknownMethodKey) { + return { + title: ( + + {routeKey} + + ), + key: routeKey, + children: data[routeKey].map((route) => createTreeNode(route, true)) + } + } + return { + title: routeKey, + key: routeKey, + children: data[routeKey].map((route) => createTreeNode(route)) + } + }) + } + + const createTreeNode = useCallback((obj: EndpointType, unknown = false) => { + return { + title: ( + + {obj.path} + {obj.inner ? ( + + Внутренний + + ) : null} + + ), + key: obj.path + } + }, []) + + const filteredRoute = () => { + if (!searchValue) { + return defaultAllRoutes + } + const filteredRoute: Record = {} + Object.keys(defaultAllRoutes).forEach((groupName) => { + const filterArray = defaultAllRoutes[groupName].filter(({ path }) => + path.toLowerCase().includes(searchValue) + ) + if (filterArray.length) { + filteredRoute[groupName] = filterArray + } + }) + return filteredRoute + } + + const treeData = createTreeData(filteredRoute()) + + const filteredCheckedKeys = () => { + const isStringPresent = (string: string) => { + for (const service of treeData) { + for (const endpoint of service.children) { + if (endpoint.key === string) { + return true + } + } + } + return false + } + + return checkedKeys.filter((string) => isStringPresent(string)) + } + + const filteredKeys = filteredCheckedKeys() + + useEffect(() => { + const checkedKeys = new Set() + methods.forEach(({ method, value }) => { + if (value) { + checkedKeys.add(method) + } + }) + + const arrayCheckedKeys = Array.from(checkedKeys) + setCheckedKeys(arrayCheckedKeys) + }, [methods]) + + useEffect(() => { + if (!searchValue) { + setExpandedKeys([]) + return + } + const keys = Object.values(treeData).map((node) => node.key) + setExpandedKeys(keys) + }, [searchValue, defaultAllRoutes]) + + return ( +
+ setExpandedKeys(keys as string[])} + onCheck={onCheck as TreeProps['onCheck']} + treeData={treeData} + /> +
+ ) +} + +export default memo(AccessListTree) diff --git a/src/widgets/ListItem/index.tsx b/src/widgets/ListItem/index.tsx new file mode 100644 index 0000000..3fb828f --- /dev/null +++ b/src/widgets/ListItem/index.tsx @@ -0,0 +1,17 @@ +import { List, Tooltip } from 'antd' +import { FC } from 'react' + +import { ListItemProps } from '@widgets/ListItem/list-item.type.ts' + + +const ListItem: FC = ({ item }) => { + return ( + + + + + + ) +} + +export default ListItem diff --git a/src/widgets/ListItem/list-item.type.ts b/src/widgets/ListItem/list-item.type.ts new file mode 100644 index 0000000..4492379 --- /dev/null +++ b/src/widgets/ListItem/list-item.type.ts @@ -0,0 +1,5 @@ +import { ColumnItem } from 'isp-ui-kit/dist/Layout/Column/column.type' + +export interface ListItemProps { + item: ColumnItem +} diff --git a/src/widgets/SelectedAccessMethod/index.tsx b/src/widgets/SelectedAccessMethod/index.tsx new file mode 100644 index 0000000..c6db9c2 --- /dev/null +++ b/src/widgets/SelectedAccessMethod/index.tsx @@ -0,0 +1,61 @@ +import { FC } from 'react' + +import { SelectedAccessMethodPropsType } from '@widgets/SelectedAccessMethod/selected-access-method.type.ts' + +import { AccessListMethodType } from '@type/accessList.type.ts' + +import './selected-access-method.scss' + + +const SelectedAccessMethod: FC = ({ + unknownMethodKey, + allRoutes, + methods +}) => { + const checkIsUnknownMethod = (method: string) => { + const routes = allRoutes[unknownMethodKey] || [] + return routes.find((route) => route.path === method) + } + + const renderMethodList = () => { + const knownMethods: AccessListMethodType[] = [] + const unknownMethods: AccessListMethodType[] = [] + const sortAlphabetically = (a: AccessListMethodType, b: AccessListMethodType) => + a.method.localeCompare(b.method) + methods.forEach((method) => { + const isUnknown = checkIsUnknownMethod(method.method) + if (isUnknown) { + unknownMethods.push(method) + } else { + knownMethods.push(method) + } + }) + + const mergedMethods = [ + ...knownMethods.sort(sortAlphabetically), + ...unknownMethods.sort(sortAlphabetically) + ] + const allMethodsDisabled = mergedMethods.every((method) => !method.value) + + if (allMethodsDisabled) { + return

Нет разрешенных методов

+ } + return mergedMethods.map((method) => { + if (!method.value) { + return null + } + return ( + + {method.method} + + ) + }) + } + + return
{renderMethodList()}
+} + +export default SelectedAccessMethod diff --git a/src/widgets/SelectedAccessMethod/selected-access-method.scss b/src/widgets/SelectedAccessMethod/selected-access-method.scss new file mode 100644 index 0000000..ccc62b0 --- /dev/null +++ b/src/widgets/SelectedAccessMethod/selected-access-method.scss @@ -0,0 +1,13 @@ +@import "src/constants/style/styleConst"; + +.selected-access-method { + display: flex; + flex-direction: column; + gap: $basic-margin; + padding: $basic-padding; + border: 1px dashed $grey; + + overflow-y: scroll; + height: calc(100vh - 130px); + +} diff --git a/src/widgets/SelectedAccessMethod/selected-access-method.type.ts b/src/widgets/SelectedAccessMethod/selected-access-method.type.ts new file mode 100644 index 0000000..4c0b391 --- /dev/null +++ b/src/widgets/SelectedAccessMethod/selected-access-method.type.ts @@ -0,0 +1,7 @@ +import { AccessListMethodType, EndpointType } from '@type/accessList.type.ts' + +export interface SelectedAccessMethodPropsType { + unknownMethodKey: string + methods: AccessListMethodType[] + allRoutes: Record +} diff --git a/vite.config.ts b/vite.config.ts index 717bef0..54b49fd 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -5,10 +5,12 @@ import svgr from 'vite-plugin-svgr' import tsconfigPaths from 'vite-tsconfig-paths' + // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), '') return { + optimizeDeps: { exclude: [] }, define: { __APP_ENV__: env.APP_ENV, APP_VERSION: JSON.stringify(process.env.npm_package_version)