diff --git a/CHANGELOG.md b/CHANGELOG.md index 89465ac..ef6ab92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## 0.10.1 +- В index.html добавлен config.js +- Добавлены динамические стили для админок +## 0.10.0 +- - Добавлена страница 'Модули' +## 0.9.0 +-Добавлена страница приложений ## 0.8.1 - Перенос UserMenu в список главного меню в Layout ## 0.8.0 diff --git a/index.html b/index.html index 11c6825..e6b7b28 100644 --- a/index.html +++ b/index.html @@ -8,7 +8,9 @@ - + + Панель администратора +
diff --git a/package-lock.json b/package-lock.json index 2b2868a..de17851 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,17 +1,19 @@ { "name": "isp-admin-ui", - "version": "0.8.0", + "version": "0.8.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "isp-admin-ui", - "version": "0.8.0", + "version": "0.8.1", "dependencies": { "@reduxjs/toolkit": "^2.2.3", "@types/react-router-dom": "^5.3.3", "axios": "^1.6.8", - "isp-ui-kit": "https://github.com/txix-open/isp-ui-kit", + "isp-ui-kit": "github:txix-open/isp-ui-kit", + "moment": "^2.30.1", + "compare-versions": "^6.1.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-hook-form": "^7.51.2", @@ -4969,6 +4971,11 @@ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "dev": true }, + "node_modules/compare-versions": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.0.tgz", + "integrity": "sha512-LNZQXhqUvqUTotpZ00qLSaify3b4VFD588aRr8MKFw4CMUr98ytzCW5wDH5qx/DEY5kCDXcbcRuCqL0szEf2tg==" + }, "node_modules/compute-scroll-into-view": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.1.0.tgz", @@ -7055,8 +7062,8 @@ "dev": true }, "node_modules/isp-ui-kit": { - "version": "0.3.3", - "resolved": "git+ssh://git@github.com/txix-open/isp-ui-kit.git#508a5bd9cb4efac0e9389ad2f9f8c60683d1712e", + "version": "0.3.4", + "resolved": "git+ssh://git@github.com/txix-open/isp-ui-kit.git#ee517a533f9e4934d08bf6d70cdfda31198cba4c", "license": "ISC", "dependencies": { "@codemirror/lang-javascript": "^6.2.1", @@ -7371,6 +7378,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/moment": { + "version": "2.30.1", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.30.1.tgz", + "integrity": "sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==", + "engines": { + "node": "*" + } + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -7430,7 +7445,6 @@ "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -7810,7 +7824,6 @@ "version": "15.8.1", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", - "dev": true, "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", diff --git a/package.json b/package.json index 97da8fc..cfe918c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "isp-admin-ui", "private": true, - "version": "0.8.1", + "version": "0.10.1", "type": "module", "scripts": { "start": "vite", @@ -17,7 +17,9 @@ "@reduxjs/toolkit": "^2.2.3", "@types/react-router-dom": "^5.3.3", "axios": "^1.6.8", - "isp-ui-kit": "https://github.com/txix-open/isp-ui-kit", + "compare-versions": "^6.1.0", + "moment": "^2.30.1", + "isp-ui-kit": "github:txix-open/isp-ui-kit", "react": "^18.2.0", "react-dom": "^18.2.0", "react-hook-form": "^7.51.2", diff --git a/public/config.js b/public/config.js new file mode 100644 index 0000000..e69de29 diff --git a/src/components/ApplicationsContent/applications-content.scss b/src/components/ApplicationsContent/applications-content.scss new file mode 100644 index 0000000..ed9183c --- /dev/null +++ b/src/components/ApplicationsContent/applications-content.scss @@ -0,0 +1,19 @@ +@import "src/constants/style/styleConst"; + +.applications-content { + padding: $basic-padding *2 $basic-padding; + display: flex; + flex-direction: column; + &__add-btn { + max-width: 240px; + margin-left: auto; + margin-bottom: $basic-margin * 2; + } + &__update-btn { + margin-right: $basic-margin; + } + &__addToken-btn { + display: flex; + margin: 0 auto; + } +} \ No newline at end of file diff --git a/src/components/ApplicationsContent/index.tsx b/src/components/ApplicationsContent/index.tsx new file mode 100644 index 0000000..883c5b9 --- /dev/null +++ b/src/components/ApplicationsContent/index.tsx @@ -0,0 +1,360 @@ +import { + EditOutlined, + DeleteOutlined, + PlusSquareOutlined +} from '@ant-design/icons' +import {Button, message, Spin, Table} from 'antd' +import { ColumnsType } from 'antd/es/table' +import { FormComponents, Layout } from 'isp-ui-kit' +import { FC, useState } from 'react' +import { useForm } from 'react-hook-form' + +import { ValidationRules } from '@constants/form/validationRules.ts' + +import Modal from '@widgets/Modal' + +import CanEdit from '@components/CanEdit' + +import { + ApplicationAppType, + ApplicationsServiceType, + ApplicationTokenType, + NewApplicationAppType, + NewApplicationTokenType, + UpdateApplicationAppType +} from '@pages/ApplicationsPage/applications.type.ts' + +import applicationsApi from '@services/applicationsService.ts' +import tokensApi from '@services/tokensService.ts' + +import './applications-content.scss' + +const { FormInput, FormSelect } = FormComponents +const { EmptyData } = Layout + +interface ApplicationsContentPropTypes { + id: number +} + +const ApplicationsContent: FC = (id) => { + const { data: applications, isLoading: isLoadingApplicationsContent = [] } = + applicationsApi.useGetApplicationsByServiceIdQuery(id) + + const [createApplicationService] = + applicationsApi.useCreateApplicationServiceMutation() + const [updateApplication] = + applicationsApi.useUpdateApplicationsServiceMutation() + const [removeApplicationsService] = + applicationsApi.useRemoveApplicationsServiceMutation() + const [createToken] = tokensApi.useCreateTokenMutation() + const [showApplicationsModal, setShowApplicationsModal] = useState({ + addModal: false, + updateModal: false, + addToken: false + }) + const [currentApplicationsApp, setCurrentApplicationsApp] = + useState() + + const { + handleSubmit, + control: controlApplicationApp, + reset + } = useForm({ + mode: 'onChange' + }) + + const { handleSubmit: handleSubmitTokens, control: controlTokens } = + useForm({ + mode: 'onChange' + }) + + const handleShowUpdateModalApplicationApp = (data: ApplicationAppType) => { + setShowApplicationsModal({ + ...showApplicationsModal, + updateModal: true + }) + setCurrentApplicationsApp(data) + } + const handleShowCreateModalApplicationApp = () => { + setShowApplicationsModal({ + ...showApplicationsModal, + addModal: true + }) + } + const handleShowAddModalToken = (data: ApplicationAppType) => { + setShowApplicationsModal({ + ...showApplicationsModal, + addToken: true + }) + setCurrentApplicationsApp(data) + } + + const handleUpdateApplicationApp = (data: UpdateApplicationAppType) => { + if (currentApplicationsApp) { + const updateApplications: UpdateApplicationAppType = { + id: currentApplicationsApp.id, + name: data.name, + description: data.description + ? data.description + : currentApplicationsApp.description, + serviceId: id.id, + type: 'SYSTEM' + } + updateApplication({ ...currentApplicationsApp, ...updateApplications }) + .unwrap() + .then(() => { + setShowApplicationsModal({ + ...showApplicationsModal, + updateModal: false + }) + reset() + message.info('Элемент сохранен') + }) + .catch(() => message.error('Ошибка обновления элемента')) + } + } + + const handleCreateApplicationApp = (data: NewApplicationAppType) => { + const newApplicationApp: NewApplicationAppType = { + name: data.name, + description: data.description, + serviceId: id.id, + type: 'SYSTEM' + } + + createApplicationService(newApplicationApp) + .unwrap() + .then(message.info('Элемент сохранен')) + .catch((e) => message.error(e)) + setShowApplicationsModal({ + ...showApplicationsModal, + addModal: false + }) + reset() + } + const handleRemoveApplicationApp = (id: number) => + removeApplicationsService([id]) + .then(() => { + message.info('Элемент удален') + }) + .catch(message.error('Ошибка добавления элемента')) + + const handleCreateToken = (data: NewApplicationTokenType) => { + if (currentApplicationsApp) { + const newToken: NewApplicationTokenType = { + expireTimeMs: data.expireTimeMs, + appId: currentApplicationsApp.id + } + + createToken(newToken) + .then(() => { + setShowApplicationsModal({ + ...showApplicationsModal, + addToken: false + }) + reset() + message.info('Элемент добавлен') + }) + .catch(() => { + message.error('Ошибка добавления элемента') + }) + } + } + + const columns: ColumnsType = [ + { + title: 'id', + dataIndex: ['app', 'id'], + key: 'id' + }, + { + title: 'Наименование', + dataIndex: ['app', 'name'], + key: 'name' + }, + { + title: 'Описание', + dataIndex: ['app', 'description'], + key: 'description' + }, + { + title: 'Type', + dataIndex: ['app', 'type'], + key: 'Type' + }, + { + title: 'Количество токенов', + dataIndex: 'tokens', + key: 'tokensAmount', + render: (value) => { + return value.length + } + }, + { + title: 'Действия', + dataIndex: 'app', + key: 'actions', + render: (record) => { + return ( + + + + ( + + + + ) + }} + className="appliactions-content__table" + rowKey={(record) => record.app.id} + pagination={false} + dataSource={applications} + columns={columns} + /> + + + setShowApplicationsModal({ + ...showApplicationsModal, + updateModal: false + }) + } + > +
+ + + +
+ + + setShowApplicationsModal({ + ...showApplicationsModal, + addModal: false + }) + } + > +
+ + + +
+ + + setShowApplicationsModal({ + ...showApplicationsModal, + addToken: false + }) + } + > +
+ + +
+ + ) +} + +export default ApplicationsContent diff --git a/src/components/AdminPermission/index.tsx b/src/components/CanEdit/index.tsx similarity index 62% rename from src/components/AdminPermission/index.tsx rename to src/components/CanEdit/index.tsx index 557861f..a2c9993 100644 --- a/src/components/AdminPermission/index.tsx +++ b/src/components/CanEdit/index.tsx @@ -4,13 +4,13 @@ import { useRole } from '@hooks/useRole.tsx' import { PermissionKeysType } from '@type/roles.type.ts' -const AdminPermission = ({ children }: PropsWithChildren) => { +const CanEdit = ({ children }: PropsWithChildren) => { const { hasPermission } = useRole() - if (hasPermission(PermissionKeysType.read)) { + if (hasPermission(PermissionKeysType.write)) { return <>{children} } return null } -export default AdminPermission +export default CanEdit diff --git a/src/components/Connections/connections.scss b/src/components/Connections/connections.scss new file mode 100644 index 0000000..67f6a98 --- /dev/null +++ b/src/components/Connections/connections.scss @@ -0,0 +1,46 @@ +@import "src/constants/style/styleConst"; + +.connection-page { + &__content { + padding: 2 * $basic-padding 3 * $basic-padding 2 * $basic-padding 0; + width: 100%; + + &__wrap-table { + overflow-x: scroll; + height: calc(100vh - 100px); + } + } + + &__endpoint-list { + &__item { + height: 25px; + display: flex; + } + + &__inner-marker { + font-size: 11px; + border: 1px solid #15D1E6; + border-radius: 12px; + padding: 0 4px; + margin: 4px + } + } + + &__no-data { + user-select: none; + display: flex; + flex: 1; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + font-size: 1.5em; + overflow: hidden; + font-family: PT Sans, sans-serif; + font-weight: 500; + padding: 8px; + text-overflow: ellipsis; + white-space: nowrap; + color: rgba(0, 0, 0, 0.45); + } +} diff --git a/src/components/Connections/index.tsx b/src/components/Connections/index.tsx new file mode 100644 index 0000000..90420b6 --- /dev/null +++ b/src/components/Connections/index.tsx @@ -0,0 +1,151 @@ +import { Spin, Table, Tooltip } from 'antd' +import { ColumnsType } from 'antd/es/table' +import moment from 'moment' +import 'moment/dist/locale/ru' +import { useEffect, useState } from 'react' +import { useNavigate, useParams } from 'react-router-dom' + +import { + AddressType, + EndpointType, + ModuleStatusType, + ModuleType +} from '@pages/ModulesPage/module.type.ts' + +import useRole from '@hooks/useRole.tsx' + +import modulesServiceApi from '@services/modulesService.ts' + +import { routePaths } from '@routes/routePaths.ts' + +import { PermissionKeysType } from '@type/roles.type.ts' + +import './connections.scss' + +const Connections = () => { + const { data: ConnectionsList = [], isLoading: isModulesLoading } = + modulesServiceApi.useGetModulesQuery('modules') + const { role, hasPermission } = useRole() + const navigate = useNavigate() + const { id } = useParams() + const [obj, setObj] = useState([]) + + const isLoading = isModulesLoading + const isPageAvailable = hasPermission(PermissionKeysType.read) + + useEffect(() => { + const filterId = ConnectionsList.find((item: ModuleType) => item.id === id) + if (filterId && filterId.status) { + setObj(filterId.status) + } + }, [ConnectionsList, id]) + + useEffect(() => { + if (!isPageAvailable) { + navigate(routePaths.home) + } + }, [isPageAvailable]) + useEffect(() => { + if (!role) { + navigate(routePaths.error) + } + }, [role]) + + if (isLoading) { + return + } + + const formatFullDate = (obj: string) => + moment(obj).format('YYYY-MM-DD, HH:mm:ss') + + const keySelector = ({ + address: { ip, port }, + establishedAt + }: ModuleStatusType) => ip + port + establishedAt + + const renderEndpoints = ({ endpoints }: ModuleStatusType) => { + if (endpoints && endpoints.length) { + return ( +
    + {endpoints.map(({ path, inner }) => ( +
  • + {path} + {inner && ( + + Внутренний + + )} +
  • + ))} +
+ ) + } + + return ( +
Нет реализованных методов
+ ) + } + + const columns: ColumnsType = [ + { + title: '#', + dataIndex: '', + key: 'num', + render: ( + _val: ModuleStatusType, + _record: ModuleStatusType, + index: number + ) => index + 1 + }, + { + title: 'Версия', + dataIndex: 'version', + key: 'version' + }, + { + title: 'Версия библиотеки', + dataIndex: 'libVersion', + key: 'libVersion' + }, + { + title: 'Адрес', + dataIndex: 'address', + key: 'address', + render: (value: AddressType) => `${value.ip}:${value.port}` + }, + { + title: 'Соединение установлено', + dataIndex: 'establishedAt', + key: 'establishedAt', + render: (val: string) => ( + {moment(val).fromNow()} + ) + }, + { + title: 'Реализованные методы', + dataIndex: 'endpoints', + key: 'endpoints', + render: (value: EndpointType[]) => (value && value.length) || '0' + } + ] + + return ( +
+
+
+
renderEndpoints(i) + }} + /> + + + + ) +} + +export default Connections diff --git a/src/components/Layout/index.tsx b/src/components/Layout/index.tsx index cb4d411..b32fc0e 100644 --- a/src/components/Layout/index.tsx +++ b/src/components/Layout/index.tsx @@ -1,7 +1,8 @@ import { LockOutlined, LogoutOutlined, - ProfileOutlined + ProfileOutlined, + AppstoreAddOutlined } from '@ant-design/icons' import { ConfigProvider, Layout, Menu, Spin } from 'antd' import { useContext, useEffect, useState } from 'react' @@ -12,6 +13,7 @@ import { localStorageKeys } from '@constants/localStorageKeys.ts' import DefaultUser from '@components/Icons/DefaultUser.tsx' import { MenuItemKeysType, + MenuItemLabelsType, MenuItemType, menuKeys } from '@components/Layout/layout.type.ts' @@ -22,13 +24,15 @@ import { useAppDispatch, useAppSelector } from '@hooks/redux.ts' import useLogout from '@hooks/useLogout.tsx' import useRole from '@hooks/useRole.tsx' -import { fetchProfile } from '@stores/redusers/ActionCreators.ts' +import { fetchProfile, fetchUI } from '@stores/redusers/ActionCreators.ts' import { StateProfileStatus } from '@stores/redusers/ProfileSlice.ts' import { routePaths } from '@routes/routePaths.ts' import { PermissionKeysType } from '@type/roles.type.ts' +import Header from 'src/widgets/Header' + import './layout.scss' const { Content, Sider } = Layout @@ -38,6 +42,7 @@ const LayoutComponent = () => { const [selectedMenuKeys, setSelectedMenuKeys] = useState( [] ) + const [title, setTitle] = useState('') const [openKeys, setOpenKeys] = useState([]) const dispatch = useAppDispatch() const { @@ -81,6 +86,12 @@ const LayoutComponent = () => { } ] }, + { + label: 'Группа приложений', + key: 'applications', + className: hideItem([PermissionKeysType.read]), + icon: + }, { label: 'Доступы приложений', key: 'appAccess', @@ -114,6 +125,12 @@ const LayoutComponent = () => { className: hideItem(PermissionKeysType.read) } ] + }, + { + label: 'Модули', + key: 'modules', + className: hideItem(PermissionKeysType.read), + icon: } ] @@ -130,6 +147,7 @@ const LayoutComponent = () => { useEffect(() => { if (userToken) { dispatch(fetchProfile()) + dispatch(fetchUI()) } }, []) @@ -139,6 +157,7 @@ const LayoutComponent = () => { const menuItem = menuKeys[menuKey] if (menuItem) { + setTitle(MenuItemLabelsType[menuItem.key]) setSelectedMenuKeys([menuItem.key]) setOpenKeys(menuItem.parent) } @@ -169,6 +188,12 @@ const LayoutComponent = () => { case MenuItemKeysType.roles: navigate(routePaths.roles) break + case MenuItemKeysType.modules: + navigate(routePaths.modules) + break + case MenuItemKeysType.applications: + navigate(routePaths.applications) + break default: } } @@ -178,37 +203,40 @@ const LayoutComponent = () => { } return ( - - {status === StateProfileStatus.pending ? ( - - ) : ( - <> - setCollapsed(value)} - > - setOpenKeys(keys)} - openKeys={openKeys} - selectedKeys={selectedMenuKeys} - onClick={handlerOnClickMenu} +
+
+ + {status === StateProfileStatus.pending ? ( + + ) : ( + <> + - - - - - - - - )} - + collapsible + collapsed={collapsed} + onCollapse={(value) => setCollapsed(value)} + > + setOpenKeys(keys)} + openKeys={openKeys} + selectedKeys={selectedMenuKeys} + onClick={handlerOnClickMenu} + theme="light" + mode="inline" + items={menuItems} + /> + + + + + + + + )} + +
) } diff --git a/src/components/Layout/layout.scss b/src/components/Layout/layout.scss index f1254b7..06a9eda 100644 --- a/src/components/Layout/layout.scss +++ b/src/components/Layout/layout.scss @@ -1,7 +1,7 @@ @import 'src/constants/style/styleConst'; .layout { - min-height: 100vh !important; + min-height: calc(100vh - 65px) !important; position: relative; .hide-item { diff --git a/src/components/Layout/layout.type.ts b/src/components/Layout/layout.type.ts index 4e7f612..860ba52 100644 --- a/src/components/Layout/layout.type.ts +++ b/src/components/Layout/layout.type.ts @@ -7,7 +7,20 @@ export enum MenuItemKeysType { appAccess = 'appAccess', roles = 'roles', logout = 'logout', - profile = 'profile' + profile = 'profile', + modules = 'modules', + applications = 'applications' +} +export enum MenuItemLabelsType { + users = 'Пользователи', + sessions = 'Пользовательские сессии', + securityLog = 'Просмотр журналов ИБ', + appAccess = 'Доступы приложений', + roles = 'Роли', + profile = 'Профиль', + modules = 'Модули', + applications = 'Группа приложений', + logout = 'Выход', } interface MenuItem { @@ -42,6 +55,14 @@ export const menuKeys: Record = { [MenuItemKeysType.profile]: { key: MenuItemKeysType.profile, parent: [''] + }, + [MenuItemKeysType.modules]: { + key: MenuItemKeysType.modules, + parent: [] + }, + [MenuItemKeysType.applications]: { + key: MenuItemKeysType.applications, + parent: [''] } } diff --git a/src/components/app.scss b/src/components/app.scss index 6095f4b..d26913c 100644 --- a/src/components/app.scss +++ b/src/components/app.scss @@ -9,7 +9,6 @@ .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 1149e8c..17155ac 100644 --- a/src/constants/api/apiPaths.ts +++ b/src/constants/api/apiPaths.ts @@ -28,6 +28,23 @@ type PathKeys = | 'setList' | 'setOne' | 'getAllRoutes' + | 'getModules' + | 'deleteModule' + | 'createUpdateService' + | 'deleteService' + | 'getAllService' + | 'getServiceById' + | 'getServicesByDomainId' + | 'createUpdateApplication' + | 'deleteApplication' + | 'getApplicationById' + | 'getAllApplications' + | 'getApplicationsByServiceId' + | 'createToken' + | 'getTokensByAppId' + | 'revokeTokens' + | 'revokeTokensForApp' + | 'getUI' export const apiPaths: Record = { baseUrl: '/api/kkd-configuration-service', @@ -45,6 +62,7 @@ export const apiPaths: Record = { logout: '/api/admin/auth/logout', // ======= PROFILE ====== getProfile: '/api/admin/user/get_profile', + getUI: '/api/admin/user/get_design', // ======= USERS ====== getUsers: '/get_users', createUser: '/create_user', @@ -62,9 +80,28 @@ export const apiPaths: Record = { setLogEvents: '/log/set_events', // ======= APPLICATIONS ====== getSystemTree: '/application/get_system_tree', + getAllApplications: '/application/get_applications', + createUpdateApplication: '/application/create_update_application', + getApplicationsByServiceId: '/application/get_applications_by_service_id', + deleteApplication: '/application/delete_applications', + getApplicationById: '/application/get_application_by_id', // ======= ACCESS_LIST ====== getById: '/access_list/get_by_id', setList: '/access_list/set_list', setOne: '/access_list/set_one', - getAllRoutes: '/routing/get_routes' + getAllRoutes: '/routing/get_routes', + // ======= MODULES ====== + getModules: '/module/get_modules_info', + deleteModule: '/module/delete_module', + // ======= SERVICE ====== + getServiceById: '/service/get_service_by_id', + getAllService: '/service/get_service', + deleteService: '/service/delete_service', + createUpdateService: '/service/create_update_service', + getServicesByDomainId: '/service/get_services_by_domain_id', + // ======= TOKENS ====== + createToken: '/token/create_token', + getTokensByAppId: '/token/get_tokens_by_app_id', + revokeTokens: '/token/revoke_tokens', + revokeTokensForApp: '/token/revoke_tokens_for_app' } diff --git a/src/pages/ApplicationsPage/applications-page.scss b/src/pages/ApplicationsPage/applications-page.scss new file mode 100644 index 0000000..fdb1875 --- /dev/null +++ b/src/pages/ApplicationsPage/applications-page.scss @@ -0,0 +1,69 @@ +@import "src/constants/style/styleConst"; + +.applications-page { + height: 100%; + .three-columns { + display: flex; + background: #fff; + box-shadow: inset -1px 0px 0px $border-color; + + height: 100%; + + .column__header { + padding: $basic-padding * 2 $basic-padding; + + svg { + fill: $blue-color; + } + } + + .ant-input-affix-wrapper { + .ant-input-prefix { + margin-left: auto; + position: absolute; + right: 5px; + top: 50%; + transform: translateY(-50%); + z-index: 10; + cursor: pointer; + } + } + + .ant-input-affix-wrapper-focused { + .ant-input-prefix { + .anticon-search { + svg { + display: none; + } + } + } + } + + .ant-list-items { + .column__items__item { + .ant-list-item-meta-title { + font-family: 'Roboto', sans-serif; + font-size: 14px; + line-height: 22px; + font-weight: 400; + color: $text-color-gray; + margin-left: 5px; + } + + &.active { + background: $blue-light !important; + + .ant-list-item-meta-title { + color: $text-color-blue; + } + + svg { + path { + fill: $text-color-blue; + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/pages/ApplicationsPage/applications.type.ts b/src/pages/ApplicationsPage/applications.type.ts new file mode 100644 index 0000000..b0500c4 --- /dev/null +++ b/src/pages/ApplicationsPage/applications.type.ts @@ -0,0 +1,39 @@ +export interface ApplicationsGroupType { + createdAt: string, + description: string, + domainId: number, + id: number, + name: string, + updatedAt: string +} + +export type NewApplicationsGroupType = Omit +export type UpdateApplicationsGroupType = Omit + +export interface ApplicationsServiceType { + app:ApplicationAppType + tokens: ApplicationTokenType[] +} + +export type NewApplicationTokenType = Omit +export interface ApplicationAppType { + createdAt: string, + description: string, + id: number, + name: string, + serviceId: number, + type: string, + updatedAt: string +} + + +export type UpdateApplicationAppType = Omit +export type NewApplicationAppType = Omit + +export interface ApplicationTokenType { + appId: number, + createdAt: string, + expireTimeMs: number, + token: string +} + diff --git a/src/pages/ApplicationsPage/index.tsx b/src/pages/ApplicationsPage/index.tsx new file mode 100644 index 0000000..c20cd17 --- /dev/null +++ b/src/pages/ApplicationsPage/index.tsx @@ -0,0 +1,218 @@ +import { message, Spin } from 'antd' +import { Layout, FormComponents } from 'isp-ui-kit' +import { ColumnItem } from 'isp-ui-kit/dist/Layout/Column/column.type' +import { useEffect, useState } from 'react' +import { useForm } from 'react-hook-form' +import { useNavigate, useParams, useSearchParams } from 'react-router-dom' + +import { ValidationRules } from '@constants/form/validationRules.ts' + +import ListItem from '@widgets/ListItem' +import Modal from '@widgets/Modal' + +import ApplicationsContent from '@components/ApplicationsContent' + +import { + NewApplicationsGroupType, + ApplicationsGroupType, + UpdateApplicationsGroupType +} from '@pages/ApplicationsPage/applications.type.ts' + +import { setSearchValue, setSelectedItemId } from '@utils/columnLayoutUtils.ts' +import { filterFirstColumnItems } from '@utils/firstColumnUtils.ts' + +import useRole from '@hooks/useRole.tsx' + +import applicationsGroupApi from '@services/applicationsGroupService.ts' + +import { routePaths } from '@routes/routePaths.ts' + +import { PermissionKeysType } from '@type/roles.type.ts' + +import './applications-page.scss' + +const { Column, ContentColumn, EmptyData } = Layout +const { FormInput } = FormComponents + +const ApplicationsPage = () => { + const navigate = useNavigate() + const { id: selectedItemId = '' } = useParams() + const [searchParams, setSearchParams] = useSearchParams('') + const { hasPermission } = useRole() + + const { + data: applicationsGroup = [], + isError: isErrorApplicationsGroup, + isLoading: isLoadingApplicationsGroup + } = applicationsGroupApi.useGetApplicationsGroupByDomainIdQuery({ id: 2 }) + + const [createApplicationsGroup] = + applicationsGroupApi.useCreateApplicationsGroupMutation() + const [updateApplicationsGroup] = + applicationsGroupApi.useUpdateApplicationsGroupMutation() + + const [deleteApplicationsGroup] = + applicationsGroupApi.useRemoveApplicationsGroupMutation() + + const isPageAvailable = hasPermission(PermissionKeysType.read) + + useEffect(() => { + if (!isPageAvailable) { + navigate(routePaths.home) + } + }, [isPageAvailable]) + + const [showApplicationsModal, setShowApplicationsModal] = useState({ + addModal: false, + updateModal: false + }) + const searchValue = searchParams.get('search') || '' + const { handleSubmit, control, reset } = useForm({ + mode: 'onChange' + }) + + if (isErrorApplicationsGroup) { + return + } + + if (isLoadingApplicationsGroup) { + return + } + + const renderColumnItems = (item: ColumnItem) => + + const addApplicationModal = () => { + setShowApplicationsModal({ + ...showApplicationsModal, + addModal: true + }) + } + + const updateApplicationModal = () => { + setShowApplicationsModal({ + ...showApplicationsModal, + updateModal: true + }) + } + + const handleAddApplicationGroup = (data: any) => { + const newService: NewApplicationsGroupType = { + name: data.name, + description: data.description, + domainId: 2 + } + createApplicationsGroup(newService) + setShowApplicationsModal({ + ...showApplicationsModal, + addModal: false + }) + reset() + message.info('Сервис успешно создан') + } + + const handleUpdateApplicationsGroup = (data: NewApplicationsGroupType) => { + const updateService: UpdateApplicationsGroupType = { + name: data.name, + description: data.description, + domainId: 2, + id: Number(selectedItemId) + } + + updateApplicationsGroup(updateService) + setShowApplicationsModal({ + ...showApplicationsModal, + updateModal: false + }) + + reset() + message.info('Сервис успешно отредактирован') + } + + const renderMainContent = () => { + if (!selectedItemId) { + return + } + return + } + + return ( +
+
+ deleteApplicationsGroup([Number(selectedItemId)])} + items={filterFirstColumnItems( + applicationsGroup as unknown as ColumnItem[], + searchValue + )} + renderItems={renderColumnItems} + searchValue={searchValue} + selectedItemId={selectedItemId} + setSelectedItemId={(itemId) => { + setSelectedItemId( + `${routePaths.applications}`, + itemId, + searchValue, + navigate + ) + }} + onChangeSearchValue={(value) => + setSearchValue(value, setSearchParams) + } + /> + + {renderMainContent()} + + + setShowApplicationsModal({ + ...showApplicationsModal, + addModal: false + }) + } + > +
+ + + +
+ + + setShowApplicationsModal({ + ...showApplicationsModal, + updateModal: false + }) + } + > +
+ + + +
+
+
+ ) +} + +export default ApplicationsPage diff --git a/src/pages/ModulesPage/index.tsx b/src/pages/ModulesPage/index.tsx new file mode 100644 index 0000000..e5e6e37 --- /dev/null +++ b/src/pages/ModulesPage/index.tsx @@ -0,0 +1,239 @@ +import { ExclamationCircleOutlined } from '@ant-design/icons' +import { List, message, Spin, Tabs, Tag, Tooltip } from 'antd' +import { compareVersions } from 'compare-versions' +import { Layout } from 'isp-ui-kit' +import { useEffect, useState } from 'react' +import { + createSearchParams, + Outlet, + useLocation, + useNavigate, + useParams, + useSearchParams +} from 'react-router-dom' + +import { ModuleType } from '@pages/ModulesPage/module.type.ts' + +import { filterFirstColumnItems } from '@utils/firstColumnUtils.ts' + +import useRole from '@hooks/useRole.tsx' + +import modulesServiceApi from '@services/modulesService.ts' + +import { routePaths } from '@routes/routePaths.ts' + +import { PermissionKeysType } from '@type/roles.type.ts' + +import './modules-page.scss' + +const { Column, EmptyData, NoData } = Layout + +const ModulesPage = () => { + const [activeTab, setActiveTab] = useState('configurations') + const { id: selectedItemId = '' } = useParams() + const navigate = useNavigate() + const { role, hasPermission } = useRole() + const [searchParams, setSearchParams] = useSearchParams() + const { data: ModulesList = [], isLoading: isModulesLoading } = + modulesServiceApi.useGetModulesQuery('modules', { + pollingInterval: 1000, + skipPollingIfUnfocused: true + }) + const [removeModule] = modulesServiceApi.useRemoveModuleMutation() + const location = useLocation() + + const searchValue = searchParams.get('search') || '' + const isPageAvailable = hasPermission(PermissionKeysType.read) + const isRemoveModule = hasPermission(PermissionKeysType.write) + const isLoading = isModulesLoading + + useEffect(() => { + if (!isPageAvailable) { + navigate(routePaths.home) + } + }, [isPageAvailable]) + + useEffect(() => { + if (!role) { + navigate(routePaths.error) + } + }, [role]) + + useEffect(() => { + const url = location.pathname.substring( + location.pathname.lastIndexOf('/') + 1 + ) + switch (url) { + case 'configurations': + return setActiveTab('configurations') + case 'connections': + return setActiveTab('connections') + } + }, [location]) + + const setSelectedItemId = (id: string): void => { + if (id) { + navigate( + { + pathname: `${routePaths.modules}/${id}/${activeTab}`, + search: createSearchParams(searchParams).toString() + }, + { replace: true } + ) + } + } + + const handleOnChangeSearchValue = (value: string): void => { + setSearchParams((prev) => { + if (!value) { + prev.delete('search') + } else { + prev.set('search', value) + } + return prev + }) + } + + const handleRemoveModule = (id: string) => { + removeModule(id) + .unwrap() + .then(() => { + navigate(routePaths.modules) + message.success('Модуль успешно удален').then() + setSelectedItemId('') + }) + .catch(() => message.error('Не удалось удалить модуль')) + } + + const versionCompare = (versions: string[]) => { + const sorted = versions?.sort(compareVersions) + const firstVersion = sorted[0] + for (let i = 1; i < sorted.length; i++) { + if (compareVersions(firstVersion, sorted[i]) !== 0) { + return false + } + } + return true + } + + const getLastVersion = (versions: string[]) => { + const sorted = versions?.sort(compareVersions) + return sorted[sorted.length - 1] + } + + if (isLoading) { + return + } + + const currentRole = ModulesList + ? ModulesList.find( + (item: ModuleType) => item.id.toString() === selectedItemId + ) + : null + + const renderItems = (item: ModuleType) => { + const isSame = versionCompare(item.status.map((i) => i.version)) + const textTooltip = isSame + ? 'Активны экземпляры одинаковых версий' + : 'Активны экземпляры разных версий' + const lastVersion = getLastVersion(item.status.map((i) => i.version)) + + const renderVersion = () => { + if (!isSame && lastVersion) { + return ( + } color="warning"> + {lastVersion} + + ) + } + if (isSame && lastVersion) { + return {lastVersion} + } + return '' + } + + return ( + +
+
+ {item.name} + + {renderVersion()} + +
+
+ + активные экземпляры: + + + {(item.status && item.status.length) || '0'} + +
+
+
+ ) + } + + const renderMainContent = () => { + if (!selectedItemId) { + return + } + + if (!currentRole) { + return + } + + return + } + const secondColumnItems = [ + { + key: 'configurations', + name: 'Конфигурации' + }, + { key: 'connections', name: 'Подключения' } + ] + + return ( +
+ + { + setActiveTab(activeKey) + const path = `${selectedItemId}/${activeKey}` + navigate(path) + }} + className="modules-page__tabs" + tabPosition={'left'} + items={secondColumnItems.map((item) => { + return { + disabled: selectedItemId === '', + label: item.name, + key: item.key, + children: ( +
{renderMainContent()}
+ ) + } + })} + /> +
+ ) +} + +export default ModulesPage diff --git a/src/pages/ModulesPage/module.type.ts b/src/pages/ModulesPage/module.type.ts new file mode 100644 index 0000000..cdb7d1d --- /dev/null +++ b/src/pages/ModulesPage/module.type.ts @@ -0,0 +1,89 @@ +export interface RequiredModuleType { + id: string + name: string + required: boolean +} + +export interface AddressType { + ip: string + port: string +} + +export interface EndpointType { + extra: Record + inner: boolean + path: string + userAuthRequired: boolean +} + +export interface ModuleStatusType { + establishedAt: string + libVersion: string + version: string + address: AddressType + endpoints: EndpointType[] +} + +export interface ConfigType { + active: boolean + commonConfigs: string[] + createdAt: string + data: Record + description: string + id: string + moduleId: string + name: string + updatedAt: string + valid: boolean + version: number +} + +export interface JSONSchema { + $ref?: string + $schema?: string + additionalItems?: boolean | JSONSchema + additionalProperties?: boolean | JSONSchema + allOf?: JSONSchema[] + anyOf?: JSONSchema[] + default?: any + definitions?: Record + dependencies?: Record + description?: string + enum?: any[] + exclusiveMaximum?: boolean + exclusiveMinimum?: boolean + format?: string + items?: JSONSchema | JSONSchema[] + maxItems?: number + maxLength?: number + maxProperties?: number + maximum?: number + media?: JSONSchema + minItems?: number + minLength?: number + minProperties?: number + minimum?: number + multipleOf?: number + not?: JSONSchema + oneOf?: JSONSchema[] + pattern?: string + patternProperties?: Record + properties?: Record + required?: string[] + title?: string + type?: string | string[] + uniqueItems?: boolean +} + +export interface ModuleType { + active: boolean + configs: ConfigType[] + createdAt: string + id: string + lastConnectedAt: string + lastDisconnectedAt: string + name: string + requiredModules: RequiredModuleType[] + status: ModuleStatusType[] + configSchema: JSONSchema +} diff --git a/src/pages/ModulesPage/modules-page.scss b/src/pages/ModulesPage/modules-page.scss new file mode 100644 index 0000000..2555b1f --- /dev/null +++ b/src/pages/ModulesPage/modules-page.scss @@ -0,0 +1,136 @@ +@import "../../constants/style/styleConst"; + +.modules-page { + height: 100%; + + &__tabs { + overflow-x: scroll; + width: 100%; + } + + .ant-list-item { + padding-bottom: 20px; + + } + + .ant-tag { + height: 22px; + margin: 0; + } + + .module-item { + width: 100%; + + &__name { + display: flex; + padding-bottom: 5px; + justify-content: space-between; + width: 100%; + } + + &__content { + display: flex; + justify-content: space-between; + + &__description { + color: $grey; + display: inline-block; + } + + &__status { + border: 1px solid #15d1e6; + border-radius: 12px; + padding: 0 4px; + font-family: sans-serif; + opacity: .7; + height: 22px; + width: 22px; + justify-content: center; + display: flex; + align-items: center; + } + + &__status_zero { + border: 1px solid red; + } + } + } + + + &__content { + overflow-x: scroll; + width: 100%; + } +} + +.three-columns { + display: flex; + background: #fff; + box-shadow: inset -1px 0px 0px $border-color; + + height: 100%; + + .column__header { + padding: $basic-padding * 2 $basic-padding; + + svg { + fill: $blue-color; + } + } + + .ant-input-affix-wrapper { + .ant-input-prefix { + margin-left: auto; + position: absolute; + right: 5px; + top: 50%; + transform: translateY(-50%); + z-index: 10; + cursor: pointer; + } + } + + .ant-input-affix-wrapper-focused { + .ant-input-prefix { + .anticon-search { + svg { + display: none; + } + } + } + } + + .ant-list-items { + .column__items__item { + .ant-list-item-meta-title { + font-family: 'Roboto', sans-serif; + font-size: 14px; + line-height: 22px; + font-weight: 400; + color: $text-color-gray; + margin-left: 5px; + } + + &.active { + background: $blue-light !important; + + .ant-list-item-meta-title { + color: $text-color-blue; + } + } + } + } + + .ant-tabs-nav-list { + padding-top: 50px; + } + + .ant-tabs-tab { + justify-content: flex-end; + margin: 10px 0 0 0; + } +} + +.column .column__items__item span { + width: fit-content; +} \ No newline at end of file diff --git a/src/pages/ProfilePage/profile-page.type.ts b/src/pages/ProfilePage/profile-page.type.ts index 03aff61..8bb4565 100644 --- a/src/pages/ProfilePage/profile-page.type.ts +++ b/src/pages/ProfilePage/profile-page.type.ts @@ -15,3 +15,14 @@ export type ProfileType = { status: StateProfileStatus error: string } + +export type UIDataType = { + name: string + primaryColor: string +} + +export type UIType = { + ui: UIDataType + status: StateProfileStatus + error: string +} diff --git a/src/routes/Routers/index.tsx b/src/routes/Routers/index.tsx index 08083e1..b90aedf 100644 --- a/src/routes/Routers/index.tsx +++ b/src/routes/Routers/index.tsx @@ -18,6 +18,9 @@ const UserEditor = lazy(() => import('src/pages/UserEditor')) const SessionsPage = lazy(() => import('@pages/SessionsPage')) const SecurityLogPage = lazy(() => import('@pages/SecurityLogPage')) const AppAccessPage = lazy(() => import('@pages/AppAccessPage')) +const ModulesPage = lazy(() => import('@pages/ModulesPage')) +const Connections = lazy(() => import('@components/Connections')) +const ApplicationsPage = lazy(() => import('@pages/ApplicationsPage')) const Routers = () => { return ( @@ -73,6 +76,23 @@ const Routers = () => { } /> + }> + + + } + > + }> + + + } + /> + { } /> + }> + + + } + > + + }> +
Configurations
+ + } + /> + }> + + + } + /> + +
= { home: '/', @@ -20,5 +22,7 @@ export const routePaths: Record = { sessions: '/sessions', securityLog: '/securityLog', roles: '/roles', - appAccess: '/appAccess' + appAccess: '/appAccess', + modules: '/modules', + applications: '/applications' } diff --git a/src/services/appService.ts b/src/services/appService.ts index eec1c33..f4d6200 100644 --- a/src/services/appService.ts +++ b/src/services/appService.ts @@ -10,7 +10,7 @@ import { AppApiResponseType, DomainType } from '@type/app.type.ts' const appApi = createApi({ reducerPath: 'appService', refetchOnFocus: true, - tagTypes: ['SystemTreeApps'], + tagTypes: ['SystemTreeApps' , 'Application'], baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseSystemUrl }), endpoints: (builder) => ({ getSystemTree: builder.query({ diff --git a/src/services/applicationsGroupService.ts b/src/services/applicationsGroupService.ts new file mode 100644 index 0000000..420a814 --- /dev/null +++ b/src/services/applicationsGroupService.ts @@ -0,0 +1,81 @@ +import { createApi } from '@reduxjs/toolkit/query/react' + +import { apiPaths } from '@constants/api/apiPaths.ts' + +import { + ApplicationsGroupType, + NewApplicationsGroupType, + UpdateApplicationsGroupType +} from '@pages/ApplicationsPage/applications.type.ts' + +import { axiosBaseQuery } from '@utils/apiUtils.ts' + +const applicationsGroupApi = createApi({ + reducerPath: 'applicationsGroupApi', + refetchOnFocus: true, + tagTypes: ['ApplicationsGroup'], + baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseSystemUrl }), + endpoints: (builder) => ({ + getApplicationsGroupByDomainId: builder.query< + ApplicationsGroupType, + { id: number } + >({ + query: (id) => ({ + url: apiPaths.getServicesByDomainId, + data: id + }), + providesTags: () => ['ApplicationsGroup'] + }), + + getApplicationsGroupByServiceId: builder.query< + ApplicationsGroupType[], + { id: number } + >({ + query: (id) => ({ + url: apiPaths.getServiceById, + data: id + }), + providesTags: () => ['ApplicationsGroup'] + }), + + getAllApplicationsGroup: builder.query< + ApplicationsGroupType[], + { id: string } + >({ + query: () => ({ url: apiPaths.getAllService }), + providesTags: () => ['ApplicationsGroup'] + }), + + createApplicationsGroup: builder.mutation< + ApplicationsGroupType, + NewApplicationsGroupType + >({ + query: (newApplicationsGroup) => ({ + url: apiPaths.createUpdateService, + data: newApplicationsGroup + }), + invalidatesTags: ['ApplicationsGroup'] + }), + + updateApplicationsGroup: builder.mutation< + void, + UpdateApplicationsGroupType + >({ + query: (updateApplicationsGroup) => ({ + url: apiPaths.createUpdateService, + data: updateApplicationsGroup + }), + invalidatesTags: ['ApplicationsGroup'] + }), + + removeApplicationsGroup: builder.mutation({ + query: ([id]) => ({ + url: apiPaths.deleteService, + data: [id] + }), + invalidatesTags: ['ApplicationsGroup'] + }) + }) +}) + +export default applicationsGroupApi diff --git a/src/services/applicationsService.ts b/src/services/applicationsService.ts new file mode 100644 index 0000000..a6ec56b --- /dev/null +++ b/src/services/applicationsService.ts @@ -0,0 +1,70 @@ +import { createApi } from '@reduxjs/toolkit/query/react' +import { apiPaths } from '@constants/api/apiPaths.ts' + +import { + ApplicationAppType, + ApplicationsServiceType, NewApplicationAppType, + UpdateApplicationAppType +} from '@pages/ApplicationsPage/applications.type.ts' + +import { axiosBaseQuery } from '@utils/apiUtils.ts' + +const applicationsApi = createApi({ + reducerPath: 'applicationsApi', + refetchOnFocus: true, + tagTypes: ['Applications'], + baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseSystemUrl }), + endpoints: (builder) => ({ + + getAllApplicationsService: builder.query< + ApplicationsServiceType[], + { id: string } + >({ + query: () => ({ url: apiPaths.getAllApplications }), + providesTags: () => ['Applications'] + }), + + createApplicationService: builder.mutation< + ApplicationAppType, + NewApplicationAppType + >({ + query: ( NewApplicationsService) => ({ + url: apiPaths.createUpdateApplication, + data: NewApplicationsService + }), + invalidatesTags: ['Applications'] + }), + + getApplicationsServiceById: builder.query({ + query: (id) => ({ + url: apiPaths.getApplicationById, + data: id + }), + }), + + getApplicationsByServiceId: builder.query({ + query: (id) => ({ + url: apiPaths.getApplicationsByServiceId, + data: id + }), + }), + + updateApplicationsService: builder.mutation({ + query: (updateApplications) => ({ + url: apiPaths.createUpdateApplication, + data: updateApplications + }), + invalidatesTags: ['Applications'] + }), + + removeApplicationsService: builder.mutation({ + query: ([id]) => ({ + url: apiPaths.deleteApplication, + data: [ id] + }), + invalidatesTags: ['Applications'] + }) + }) +}) + +export default applicationsApi \ No newline at end of file diff --git a/src/services/modulesService.ts b/src/services/modulesService.ts new file mode 100644 index 0000000..3fb7392 --- /dev/null +++ b/src/services/modulesService.ts @@ -0,0 +1,29 @@ +import { createApi } from '@reduxjs/toolkit/query/react' + +import { apiPaths } from '@constants/api/apiPaths.ts' + +import { ModuleType } from '@pages/ModulesPage/module.type.ts' + +import { axiosBaseQuery } from '@utils/apiUtils.ts' + +const modulesServiceApi = createApi({ + reducerPath: 'modulesServiceApi', + refetchOnFocus: true, + tagTypes: ['modules'], + baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseConfigUrl }), + endpoints: (builder) => ({ + getModules: builder.query({ + query: () => ({ url: apiPaths.getModules, data: { limit: 1000 } }), + providesTags: () => ['modules'] + }), + removeModule: builder.mutation({ + query: (id) => ({ + url: apiPaths.deleteModule, + data: [id] + }), + invalidatesTags: ['modules'] + }) + }) +}) + +export default modulesServiceApi diff --git a/src/services/tokensService.ts b/src/services/tokensService.ts new file mode 100644 index 0000000..a29fbd0 --- /dev/null +++ b/src/services/tokensService.ts @@ -0,0 +1,30 @@ +import { createApi } from '@reduxjs/toolkit/query/react' +import { apiPaths } from '@constants/api/apiPaths.ts' + +import { + ApplicationTokenType, + NewApplicationTokenType, +} from '@pages/ApplicationsPage/applications.type.ts' + +import { axiosBaseQuery } from '@utils/apiUtils.ts' + +const tokensApi = createApi({ + reducerPath: 'tokensApi', + refetchOnFocus: true, + tagTypes: ['Tokens'], + baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseSystemUrl }), + endpoints: (builder) => ({ + createToken: builder.mutation< + ApplicationTokenType, + NewApplicationTokenType + >({ + query: ( NewApplicationTokenType) => ({ + url: apiPaths.createToken, + data: NewApplicationTokenType + }), + invalidatesTags: ['Tokens'] + }), + }) +}) + +export default tokensApi \ No newline at end of file diff --git a/src/stores/index.tsx b/src/stores/index.tsx index 2e37302..349e06a 100644 --- a/src/stores/index.tsx +++ b/src/stores/index.tsx @@ -3,15 +3,19 @@ import { theme } from 'antd' import { MapToken, SeedToken } from 'antd/es/theme/interface' import { createContext, Dispatch, SetStateAction } from 'react' -import sessionServiceApi from '@services/sessionService.ts' import accessListApi from '@services/accessListService.ts' import appApi from '@services/appService.ts' +import applicationsGroupApi from '@services/applicationsGroupService.ts' +import applicationsApi from '@services/applicationsService.ts' +import modulesServiceApi from '@services/modulesService.ts' import roleApi from '@services/roleService.ts' -import securityLogServiceApi from '@services/securityLogService.ts' -import userServiceApi from '@services/userService.ts' import routeApi from '@services/routeService.ts' +import securityLogServiceApi from '@services/securityLogService.ts' +import sessionServiceApi from '@services/sessionService.ts' +import userServiceApi from '@services/userService.ts' import profileReducer from './redusers/ProfileSlice.ts' +import UIReducer from './redusers/UISlice.ts' export interface ContextProps { setTheme: Dispatch< @@ -25,13 +29,17 @@ export const Context = createContext({ const rootReducer = combineReducers({ profileReducer, + UIReducer, [roleApi.reducerPath]: roleApi.reducer, [userServiceApi.reducerPath]: userServiceApi.reducer, [sessionServiceApi.reducerPath]: sessionServiceApi.reducer, [securityLogServiceApi.reducerPath]: securityLogServiceApi.reducer, [appApi.reducerPath]: appApi.reducer, [accessListApi.reducerPath]: accessListApi.reducer, - [routeApi.reducerPath]: routeApi.reducer + [routeApi.reducerPath]: routeApi.reducer, + [modulesServiceApi.reducerPath]: modulesServiceApi.reducer, + [applicationsGroupApi.reducerPath]: applicationsGroupApi.reducer, + [applicationsApi.reducerPath]: applicationsApi.reducer }) export const setupStore = () => @@ -46,7 +54,10 @@ export const setupStore = () => accessListApi.middleware, routeApi.middleware, userServiceApi.middleware, - sessionServiceApi.middleware + sessionServiceApi.middleware, + modulesServiceApi.middleware, + applicationsGroupApi.middleware, + applicationsApi.middleware ) }) diff --git a/src/stores/redusers/ActionCreators.ts b/src/stores/redusers/ActionCreators.ts index 8b249aa..e2547cf 100644 --- a/src/stores/redusers/ActionCreators.ts +++ b/src/stores/redusers/ActionCreators.ts @@ -2,11 +2,15 @@ import { createAsyncThunk } from '@reduxjs/toolkit' import { apiPaths } from '@constants/api/apiPaths.ts' -import { ProfileDataType } from '@pages/ProfilePage/profile-page.type.ts' +import { + ProfileDataType, + UIDataType +} from '@pages/ProfilePage/profile-page.type.ts' + +import { initUI } from '@utils/UIUtiles.tsx' import { apiService } from '@services/apiService.ts' - export const fetchProfile = createAsyncThunk( 'profile/fetchProfile', async (_, { rejectWithValue }) => { @@ -20,3 +24,15 @@ export const fetchProfile = createAsyncThunk( } } ) +export const fetchUI = createAsyncThunk( + 'ui/fetchUI', + async (_, { rejectWithValue }) => { + try { + const response = await apiService.post(apiPaths.getUI) + initUI(response.data) + return response.data + } catch (error) { + return rejectWithValue(error) + } + } +) diff --git a/src/stores/redusers/UISlice.ts b/src/stores/redusers/UISlice.ts new file mode 100644 index 0000000..196594c --- /dev/null +++ b/src/stores/redusers/UISlice.ts @@ -0,0 +1,49 @@ +import { + ActionReducerMapBuilder, + createSlice, + PayloadAction +} from '@reduxjs/toolkit' + +import { UIDataType, UIType } from '@pages/ProfilePage/profile-page.type.ts' + +import { StateProfileStatus } from '@stores/redusers/ProfileSlice.ts' + +import { fetchUI } from './ActionCreators.ts' + +export const initialState: UIType = { + ui: { + name: '', + primaryColor: '' + }, + status: StateProfileStatus.notInit, + error: '' +} + +export const UISlice = createSlice({ + name: 'ui', + initialState, + reducers: { + clearUI(state) { + state.ui = initialState.ui + } + }, + extraReducers: (builder: ActionReducerMapBuilder) => { + builder + .addCase( + fetchUI.fulfilled, + (state, action: PayloadAction) => { + state.status = StateProfileStatus.resolved + state.ui = { ...action.payload } + } + ) + .addCase(fetchUI.pending, (state) => { + state.status = StateProfileStatus.pending + }) + .addCase(fetchUI.rejected, (state, action: any) => { + state.status = StateProfileStatus.rejected + state.error = action.payload + }) + } +}) + +export default UISlice.reducer diff --git a/src/utils/UIUtiles.tsx b/src/utils/UIUtiles.tsx new file mode 100644 index 0000000..317ab96 --- /dev/null +++ b/src/utils/UIUtiles.tsx @@ -0,0 +1,26 @@ +import { UIDataType } from '@pages/ProfilePage/profile-page.type.ts' + +const drawSVG = (color: string) => + `` + +export const createSVG = (color: string) => { + const svgString = drawSVG(color) + return btoa(svgString) // base64 +} + +export const initSVG = (color: string) => { + const favicon = document.createElement('link') + favicon.id = 'favicon' + favicon.rel = 'shortcut icon' + favicon.type = 'image/x-icon' + favicon.href = `data:image/svg+xml;base64,${createSVG(color)}` + return favicon +} + +export const initUI = (ui: UIDataType) => { + let favicon = document.getElementById('favicon') + favicon = initSVG(ui.primaryColor) + const titles = document.getElementsByTagName('title') + document.head.insertBefore(favicon, titles[0]) + document.title = `${ui.name} — MSP` +} diff --git a/src/widgets/AccessListTree/access-list-tree.scss b/src/widgets/AccessListTree/access-list-tree.scss index 144b8b7..5a9d07f 100644 --- a/src/widgets/AccessListTree/access-list-tree.scss +++ b/src/widgets/AccessListTree/access-list-tree.scss @@ -1,5 +1,5 @@ .access-list-tree{ overflow-y: scroll; - height: calc(100vh - 130px); + height: calc(100vh - 250px); } diff --git a/src/widgets/Header/header.scss b/src/widgets/Header/header.scss new file mode 100644 index 0000000..4413b11 --- /dev/null +++ b/src/widgets/Header/header.scss @@ -0,0 +1,9 @@ +.header { + display: flex; + align-items: center; + padding: 0 28px; + width: 100%; + height: 65px; + justify-content: space-between; + box-sizing: border-box; +} \ No newline at end of file diff --git a/src/widgets/Header/header.type.ts b/src/widgets/Header/header.type.ts new file mode 100644 index 0000000..d366380 --- /dev/null +++ b/src/widgets/Header/header.type.ts @@ -0,0 +1,3 @@ +export interface HeaderPropsType { + title: string +} \ No newline at end of file diff --git a/src/widgets/Header/index.tsx b/src/widgets/Header/index.tsx new file mode 100644 index 0000000..ad988a6 --- /dev/null +++ b/src/widgets/Header/index.tsx @@ -0,0 +1,45 @@ +import { HomeOutlined } from '@ant-design/icons' +import { Breadcrumb } from 'antd' + +import { HeaderPropsType } from '@widgets/Header/header.type.ts' + +import { useAppSelector } from '@hooks/redux.ts' + +import './header.scss' + +const Header = ({ title }: HeaderPropsType) => { + const { + ui: { name, primaryColor } + } = useAppSelector((state) => state.UIReducer) + + return ( +
+
+ + + Главная + + ) + }, + { + title: {title} + } + ]} + /> +
+ {name} +
+ ) +} + +export default Header diff --git a/src/widgets/SelectedAccessMethod/selected-access-method.scss b/src/widgets/SelectedAccessMethod/selected-access-method.scss index ccc62b0..fdd14ec 100644 --- a/src/widgets/SelectedAccessMethod/selected-access-method.scss +++ b/src/widgets/SelectedAccessMethod/selected-access-method.scss @@ -8,6 +8,6 @@ border: 1px dashed $grey; overflow-y: scroll; - height: calc(100vh - 130px); + height: calc(100vh - 160px); }