Merge branch 'MSP-3125_router' into 'main'
MSP-3125 "Router" See merge request isp/isp-admin-ui!4
This commit is contained in:
commit
6a9a45a4cc
43 files changed
+5657
-84
No files matched your search
+15
@@ -0,0 +1,15 @@
|
||||
.idea/
|
||||
dist/
|
||||
build/
|
||||
node_modules/
|
||||
src/**/*.jsx
|
||||
tests/__coverage__/
|
||||
tests/**/*.jsx
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/releases
|
||||
!.yarn/plugins
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
.pnp.*
|
||||
.env
|
||||
@@ -0,0 +1,10 @@
|
||||
##0.2.2
|
||||
- Добавлен редирект после логина
|
||||
##0.2.1
|
||||
- ThemeProvider заменен на ConfigProvider в компоненте <App>
|
||||
##0.2.0
|
||||
- Добавлены роли и приватный роутер
|
||||
##0.1.0
|
||||
- Инициализирован проект
|
||||
- Добавлена темная тема antd
|
||||
- Добавлен layout
|
||||
@@ -1,93 +1,30 @@
|
||||
# isp-admin-ui
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
## Getting started
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
|
||||
|
||||
## Add your files
|
||||
- Configure the top-level `parserOptions` property like this:
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin https://gitlab.txix.ru/isp/isp-admin-ui.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```js
|
||||
export default {
|
||||
// other rules...
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
project: ['./tsconfig.json', './tsconfig.node.json'],
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
|
||||
- [ ] [Set up project integrations](https://gitlab.txix.ru/isp/isp-admin-ui/-/settings/integrations)
|
||||
|
||||
## Collaborate with your team
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
||||
|
||||
## Test and Deploy
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
|
||||
***
|
||||
|
||||
# Editing this README
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
|
||||
## Suggestions for a good README
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
|
||||
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
|
||||
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<link rel="icon" type="image/svg+xml" href="/"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<title>Vite + React + TS</title>
|
||||
<script>
|
||||
window.AppVersion = "<%=APP_VERSION%>";
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"name": "unsubscribe_landing",
|
||||
"private": true,
|
||||
"version": "0.2.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"preview": "vite preview",
|
||||
"fix:prettier": "prettier --write \"src/**/*.{ts,tsx, js}\"",
|
||||
"lint:fix": "eslint --fix .",
|
||||
"analyze": "source-map-explorer 'build/static/js/*.js'",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"dependencies": {
|
||||
"@reduxjs/toolkit": "^2.2.2",
|
||||
"@types/react-router-dom": "^5.3.3",
|
||||
"axios": "^1.6.8",
|
||||
"isp-ui-kit": "https://github.com/integration-system/isp-ui-kit.git",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-redux": "^9.1.0",
|
||||
"react-router-dom": "^6.22.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
|
||||
"@types/node": "^20.11.24",
|
||||
"@types/react": "^18.2.56",
|
||||
"@types/react-dom": "^18.2.19",
|
||||
"@typescript-eslint/eslint-plugin": "^7.0.2",
|
||||
"@typescript-eslint/parser": "^7.0.2",
|
||||
"@vitejs/plugin-react": "^4.1.1",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"antd": "5.15.3",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-prettier": "^8.8.0",
|
||||
"eslint-import-resolver-typescript": "^3.5.5",
|
||||
"eslint-plugin-import": "^2.27.5",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"eslint-plugin-react": "^7.32.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.5",
|
||||
"husky": "^8.0.0",
|
||||
"prettier": "^2.8.7",
|
||||
"sass": "^1.71.1",
|
||||
"terser": "^5.28.1",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^5.1.4",
|
||||
"vite-plugin-style-import": "^2.0.0",
|
||||
"vite-plugin-svgr": "^4.2.0",
|
||||
"vite-tsconfig-paths": "^4.2.3"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"pre-coomit": "eslint --fix .",
|
||||
"pre-push": "eslint --fix ."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import {PropsWithChildren} from 'react';
|
||||
import useRole from '../../hooks/useRole.tsx';
|
||||
import {PermissionKeys} from '../../types/roles.type.ts';
|
||||
|
||||
const AdminPermission = ({children}: PropsWithChildren) => {
|
||||
const {hasPermission} = useRole();
|
||||
|
||||
if (hasPermission(PermissionKeys.admin_view)) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export default AdminPermission;
|
||||
@@ -0,0 +1,22 @@
|
||||
import {useState} from 'react';
|
||||
import {ConfigProvider} from 'antd';
|
||||
import {Context} from '../store';
|
||||
import Routers from './Routers';
|
||||
import {lightTheme} from '../constants/theme.ts';
|
||||
import './app.scss'
|
||||
|
||||
const App = () => {
|
||||
const [themes, setTheme] = useState(lightTheme);
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<Context.Provider value={{setTheme}}>
|
||||
<ConfigProvider theme={themes}>
|
||||
<Routers/>
|
||||
</ConfigProvider>
|
||||
</Context.Provider>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -0,0 +1,5 @@
|
||||
.error-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
const ErrorPage = () => {
|
||||
return (
|
||||
<section className="error-page">
|
||||
<p>Извините, ошибка</p>
|
||||
</section>
|
||||
)
|
||||
};
|
||||
|
||||
export default ErrorPage;
|
||||
@@ -0,0 +1,6 @@
|
||||
.header {
|
||||
width: 100%;
|
||||
border: none;
|
||||
display: flex;
|
||||
justify-content: end
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import {useContext} from 'react';
|
||||
import {Segmented, theme} from 'antd';
|
||||
import {Context} from '../../store';
|
||||
import {darkTheme, lightTheme} from '../../constants/theme.ts';
|
||||
import './header.scss'
|
||||
|
||||
const options = [
|
||||
{label: "Light", value: "light"},
|
||||
{label: "Dark", value: "dark"},
|
||||
];
|
||||
|
||||
const Header = () => {
|
||||
const {setTheme} = useContext(Context)
|
||||
const {useToken} = theme;
|
||||
const {token} = useToken();
|
||||
|
||||
return <header className="header" style={{backgroundColor: token.colorBgLayout}}>
|
||||
<Segmented onChange={(v) => setTheme(v === "light" ? lightTheme : darkTheme)} options={options}/>
|
||||
</header>;
|
||||
}
|
||||
|
||||
export default Header;
|
||||
@@ -0,0 +1,89 @@
|
||||
import {useEffect, useState} from 'react';
|
||||
import {Navigate, Outlet, useNavigate} from 'react-router-dom';
|
||||
import {Menu} from 'antd';
|
||||
import Header from '../Header';
|
||||
import useRole from '../../hooks/useRole.tsx';
|
||||
import {PermissionKeys} from '../../types/roles.type.ts';
|
||||
import {MenuItemKeys, menuKeys} from '../../types/layout.type.ts';
|
||||
import {routePaths} from '../../constants/routes.ts';
|
||||
import {StateProfileStatus} from '../../redusers/ProfileSlice.ts';
|
||||
import {useAppSelector} from '../../hooks/redux.ts';
|
||||
import './layout.scss'
|
||||
|
||||
const Layout = () => {
|
||||
const {hasPermission} = useRole();
|
||||
const navigate = useNavigate();
|
||||
const {status} = useAppSelector((state) => state.profileReducer);
|
||||
|
||||
const [openKeys, setOpenKeys] = useState<string[]>([]);
|
||||
const [selectedMenuKeys, setSelectedMenuKeys] = useState<MenuItemKeys[]>([]);
|
||||
|
||||
const hideItem = (permission: PermissionKeys | PermissionKeys[]) => {
|
||||
if (Array.isArray(permission)) {
|
||||
const result = permission.reduce((acc, currentValue) => {
|
||||
const isHasPermission = hasPermission(currentValue);
|
||||
return isHasPermission || acc;
|
||||
}, false);
|
||||
return result ? "" : "hide-item";
|
||||
}
|
||||
return hasPermission(permission) ? "" : "hide-item";
|
||||
};
|
||||
|
||||
const menuItems = [
|
||||
{
|
||||
label: "Profile",
|
||||
key: "users",
|
||||
className: hideItem(PermissionKeys.user_view),
|
||||
},
|
||||
{
|
||||
label: "Profile2",
|
||||
key: "roles",
|
||||
className: hideItem(PermissionKeys.user_view),
|
||||
}
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
const menuKey = location.pathname.split("/")[1] as MenuItemKeys;
|
||||
|
||||
const menuItem = menuKeys[menuKey];
|
||||
|
||||
if (menuItem) {
|
||||
setSelectedMenuKeys([menuItem.key]);
|
||||
setOpenKeys(menuItem.parent);
|
||||
}
|
||||
}, [location]);
|
||||
|
||||
const handlerOnClickMenu = ({key}: any): void => {
|
||||
switch (key) {
|
||||
case MenuItemKeys.roles:
|
||||
navigate(routePaths.error);
|
||||
break;
|
||||
case MenuItemKeys.users:
|
||||
navigate(routePaths.home);
|
||||
break;
|
||||
default:
|
||||
}
|
||||
};
|
||||
|
||||
if (status === StateProfileStatus.rejected) {
|
||||
return <Navigate to={routePaths.error} replace/>;
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="layout">
|
||||
<Header/>
|
||||
<Menu
|
||||
onOpenChange={(keys) => setOpenKeys(keys)}
|
||||
openKeys={openKeys}
|
||||
selectedKeys={selectedMenuKeys}
|
||||
onClick={handlerOnClickMenu}
|
||||
theme="light"
|
||||
mode="inline"
|
||||
items={menuItems}
|
||||
/>
|
||||
<Outlet/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,4 @@
|
||||
.layout {
|
||||
min-height: calc(100vh - 96px);
|
||||
width: 100%;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {Navigate, Outlet, useLocation} from 'react-router-dom';
|
||||
import {LocalStorage} from '../../utils/localStorageUtils.ts';
|
||||
import {localStorageKeys} from '../../constants/localStorageKeys.ts';
|
||||
import {routePaths} from '../../constants/routes.ts';
|
||||
|
||||
const PrivateRoute = () => {
|
||||
const location = useLocation();
|
||||
const userToken = LocalStorage.get(localStorageKeys.USER_TOKEN);
|
||||
|
||||
if (!userToken) {
|
||||
LocalStorage.set("redirectUrl", location.pathname)
|
||||
return (
|
||||
<Navigate
|
||||
to={routePaths.login}
|
||||
replace
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <Outlet/>;
|
||||
}
|
||||
|
||||
export default PrivateRoute;
|
||||
@@ -0,0 +1,25 @@
|
||||
import {Route, Routes} from 'react-router-dom';
|
||||
import {App} from 'antd';
|
||||
import HomePages from '../../pages/HomePage';
|
||||
import ErrorPage from '../ErrorPage';
|
||||
import PrivateRoute from '../PrivateRoute';
|
||||
import LoginPage from '../../pages/LoginPage';
|
||||
import Layout from '../Layout';
|
||||
|
||||
const Routers = () => {
|
||||
return (
|
||||
<App>
|
||||
<Routes>
|
||||
<Route element={<PrivateRoute/>}>
|
||||
<Route path="/" element={<Layout/>}>
|
||||
<Route index element={<HomePages/>}/>
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="/login" element={<LoginPage/>}/>
|
||||
<Route path="/error" element={<ErrorPage/>}/>
|
||||
</Routes>
|
||||
</App>
|
||||
)
|
||||
}
|
||||
|
||||
export default Routers
|
||||
@@ -0,0 +1,4 @@
|
||||
#root {
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
type PathKeys =
|
||||
| 'baseUrl'
|
||||
|
||||
export const apiPaths: Record<PathKeys, string> = {
|
||||
baseUrl: '/',
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
type LocalStorageKeys = "HEADER_NAME" | "USER_TOKEN";
|
||||
|
||||
export const localStorageKeys: Record<LocalStorageKeys, string> = {
|
||||
HEADER_NAME: "HEADER_NAME",
|
||||
USER_TOKEN: "USER_TOKEN"
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
type RoutePaths =
|
||||
| 'home'
|
||||
| 'notFound'
|
||||
| 'error'
|
||||
| 'login'
|
||||
|
||||
export const routePaths: Record<RoutePaths, string> = {
|
||||
home: '/',
|
||||
error: '/error',
|
||||
notFound: '*',
|
||||
login: '/login'
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
import {theme} from "antd";
|
||||
|
||||
export const darkTheme = {algorithm: theme.darkAlgorithm}
|
||||
|
||||
export const lightTheme = {algorithm: theme.defaultAlgorithm}
|
||||
@@ -0,0 +1,6 @@
|
||||
import {TypedUseSelectorHook, useDispatch, useSelector} from 'react-redux';
|
||||
|
||||
import {AppDispatch, RootState} from '../store';
|
||||
|
||||
export const useAppDispatch = () => useDispatch<AppDispatch>();
|
||||
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
||||
@@ -0,0 +1,17 @@
|
||||
import {useMemo} from 'react';
|
||||
import {useAppSelector} from './redux.ts';
|
||||
import {PermissionKeys} from '../types/roles.type.ts';
|
||||
|
||||
export const useRole = () => {
|
||||
const {profile} = useAppSelector((state: any) => state.profileReducer);
|
||||
const role: string = useMemo(() => profile && profile.role, [profile]);
|
||||
|
||||
const hasPermission = (permission: PermissionKeys) => {
|
||||
const userPermission = profile.permissions || [];
|
||||
return userPermission.includes(permission);
|
||||
};
|
||||
|
||||
return {role, hasPermission};
|
||||
};
|
||||
|
||||
export default useRole;
|
||||
@@ -0,0 +1,4 @@
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import {BrowserRouter} from 'react-router-dom';
|
||||
import {setupListeners} from '@reduxjs/toolkit/query';
|
||||
import {Provider} from 'react-redux';
|
||||
import App from './components/App.tsx'
|
||||
import {setupStore} from './store';
|
||||
import './index.css'
|
||||
|
||||
const store = setupStore();
|
||||
setupListeners(store.dispatch);
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||
<Provider store={store}>
|
||||
<BrowserRouter>
|
||||
<App/>
|
||||
</BrowserRouter>
|
||||
</Provider>,
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
.main {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {Button, theme} from 'antd';
|
||||
import useRole from '../../hooks/useRole.tsx';
|
||||
import {PermissionKeys} from '../../types/roles.type.ts';
|
||||
import './home.scss'
|
||||
|
||||
const HomePages = () => {
|
||||
const {hasPermission} = useRole();
|
||||
const {useToken} = theme;
|
||||
const {token} = useToken();
|
||||
|
||||
const isPageAvailable = hasPermission(PermissionKeys.user_view);
|
||||
|
||||
return (
|
||||
<main className="main" style={{backgroundColor: token.colorBgLayout}}>
|
||||
{isPageAvailable && <Button ghost type="primary">
|
||||
Border
|
||||
</Button>}
|
||||
<div>Проверка шрифтов</div>
|
||||
<Button type="primary">Primary</Button>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default HomePages;
|
||||
@@ -0,0 +1,20 @@
|
||||
import {useNavigate} from 'react-router-dom';
|
||||
|
||||
const LoginPage = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<main className="login-page">
|
||||
<button onClick={() => {
|
||||
const url = localStorage.getItem("redirectUrl")
|
||||
if (url) {
|
||||
navigate(url)
|
||||
localStorage.removeItem("redirectUrl")
|
||||
}
|
||||
}}>Зарегистрироваться
|
||||
</button>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export default LoginPage;
|
||||
@@ -0,0 +1,4 @@
|
||||
.login-page {
|
||||
display: flex;
|
||||
justify-content: center
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import {createAsyncThunk} from '@reduxjs/toolkit';
|
||||
import {ProfileDataType} from '../types/profile.type.ts';
|
||||
import {apiService} from '../services/apiService.ts';
|
||||
import {apiPaths} from '../constants/api/apiPaths.ts';
|
||||
|
||||
export const fetchProfile = createAsyncThunk(
|
||||
"profile/fetchProfile",
|
||||
async (_, {rejectWithValue}) => {
|
||||
try {
|
||||
const response = await apiService.post<ProfileDataType>(
|
||||
apiPaths.baseUrl,
|
||||
);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
return rejectWithValue(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,50 @@
|
||||
import {PayloadAction, createSlice, ActionReducerMapBuilder} from '@reduxjs/toolkit';
|
||||
import {ProfileDataType, ProfileType} from '../types/profile.type.ts';
|
||||
import {fetchProfile} from './ActionCreators.ts';
|
||||
|
||||
export enum StateProfileStatus {
|
||||
resolved = "resolved",
|
||||
pending = "pending",
|
||||
rejected = "rejected",
|
||||
notInit = "notInit",
|
||||
}
|
||||
|
||||
export const initialState: ProfileType = {
|
||||
profile: {
|
||||
email: "",
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
role: "",
|
||||
roles: [],
|
||||
permissions: [],
|
||||
idleTimeoutMs: 0,
|
||||
},
|
||||
status: StateProfileStatus.notInit,
|
||||
error: "",
|
||||
};
|
||||
|
||||
export const profileSlice = createSlice({
|
||||
name: "profile",
|
||||
initialState,
|
||||
reducers: {
|
||||
clearProfile(state) {
|
||||
state.profile = initialState.profile;
|
||||
},
|
||||
},
|
||||
extraReducers: (builder: ActionReducerMapBuilder<ProfileType>) => {
|
||||
builder
|
||||
.addCase(fetchProfile.fulfilled, (state, action: PayloadAction<ProfileDataType>) => {
|
||||
state.status = StateProfileStatus.resolved;
|
||||
state.profile = {...action.payload};
|
||||
})
|
||||
.addCase(fetchProfile.pending, (state) => {
|
||||
state.status = StateProfileStatus.pending;
|
||||
})
|
||||
.addCase(fetchProfile.rejected, (state, action: any) => {
|
||||
state.status = StateProfileStatus.rejected;
|
||||
state.error = action.payload;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export default profileSlice.reducer;
|
||||
@@ -0,0 +1,43 @@
|
||||
import {message} from 'antd';
|
||||
import axios, {AxiosError} from 'axios';
|
||||
import {LocalStorage} from '../utils/localStorageUtils.ts';
|
||||
import {getConfigProperty} from '../utils/configUtils.ts';
|
||||
import {MSPError} from '../types';
|
||||
import {routePaths} from '../constants/routes.ts';
|
||||
import {localStorageKeys} from '../constants/localStorageKeys.ts';
|
||||
|
||||
export const apiService = axios.create({
|
||||
timeout: 15000,
|
||||
data: {},
|
||||
});
|
||||
|
||||
apiService.defaults.headers.post["X-APPLICATION-TOKEN"] = getConfigProperty(
|
||||
"APP_TOKEN",
|
||||
import.meta.env.APP_TOKEN,
|
||||
);
|
||||
|
||||
apiService.interceptors.request.use(
|
||||
async (config: any) => {
|
||||
const headerName = LocalStorage.get(localStorageKeys.HEADER_NAME);
|
||||
config.headers[headerName] = LocalStorage.get(localStorageKeys.USER_TOKEN);
|
||||
|
||||
return config;
|
||||
},
|
||||
(error: AxiosError<MSPError>) => Promise.reject(error),
|
||||
);
|
||||
|
||||
apiService.interceptors.response.use(
|
||||
async (response: any) => response,
|
||||
(error: AxiosError<MSPError>) => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
window.location.href = routePaths.home;
|
||||
LocalStorage.clear();
|
||||
}
|
||||
|
||||
if (error.response && error.response.status === 500) {
|
||||
message.error("Внутренняя ошибка сервиса").then();
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
import {Dispatch, SetStateAction, createContext} from 'react'
|
||||
import {combineReducers, configureStore} from '@reduxjs/toolkit';
|
||||
import {theme} from 'antd';
|
||||
import {MapToken, SeedToken} from 'antd/es/theme/interface';
|
||||
import profileReducer from '../redusers/ProfileSlice.ts';
|
||||
|
||||
export interface ContextProps {
|
||||
setTheme: Dispatch<SetStateAction<{ algorithm: (token: SeedToken) => MapToken }>>
|
||||
}
|
||||
|
||||
export const Context = createContext<ContextProps>({
|
||||
setTheme: () => theme.defaultAlgorithm
|
||||
})
|
||||
|
||||
const rootReducer = combineReducers({
|
||||
profileReducer
|
||||
});
|
||||
|
||||
export const setupStore = () =>
|
||||
configureStore({
|
||||
reducer: rootReducer,
|
||||
});
|
||||
|
||||
export type RootState = ReturnType<typeof rootReducer>;
|
||||
export type AppStore = ReturnType<typeof setupStore>;
|
||||
export type AppDispatch = AppStore["dispatch"];
|
||||
@@ -0,0 +1,5 @@
|
||||
export interface MSPError {
|
||||
details: Array<any>;
|
||||
errorCode: string;
|
||||
errorMessage: string;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {MenuProps} from 'antd';
|
||||
|
||||
export enum MenuItemKeys {
|
||||
users = "users",
|
||||
roles = "roles",
|
||||
}
|
||||
|
||||
type MenuItem = {
|
||||
key: MenuItemKeys;
|
||||
parent: string[];
|
||||
};
|
||||
export const menuKeys: Record<MenuItemKeys, MenuItem> = {
|
||||
[MenuItemKeys.users]: {
|
||||
key: MenuItemKeys.users,
|
||||
parent: ["sessionManagement"],
|
||||
},
|
||||
[MenuItemKeys.roles]: {
|
||||
key: MenuItemKeys.roles,
|
||||
parent: ["sessionManagement"],
|
||||
},
|
||||
};
|
||||
|
||||
export type MenuItemType = Required<MenuProps>["items"][number];
|
||||
@@ -0,0 +1,17 @@
|
||||
import {StateProfileStatus} from '../redusers/ProfileSlice.ts';
|
||||
|
||||
export type ProfileDataType = {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
role: string;
|
||||
roles: number[];
|
||||
permissions: string[];
|
||||
idleTimeoutMs: number;
|
||||
};
|
||||
|
||||
export type ProfileType = {
|
||||
profile: ProfileDataType;
|
||||
status: StateProfileStatus;
|
||||
error: string;
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
export enum RoleKeys {
|
||||
user = "user",
|
||||
admin = "admin",
|
||||
}
|
||||
|
||||
export enum PermissionKeys {
|
||||
user_view = "user_view", // Просмотр списка пользователей
|
||||
admin_view = "admin_view", // роль суперадмина, требуется для интерфейса
|
||||
}
|
||||
|
||||
export type ConfigRoles = {
|
||||
operator: string[];
|
||||
supervisor: string[];
|
||||
ontologist: string[];
|
||||
businessMonitoring: string[];
|
||||
technicalMonitoring: string[];
|
||||
administratorIS: string[];
|
||||
};
|
||||
|
||||
export type RoleType = {
|
||||
changeMessage?: string;
|
||||
createdAt: string;
|
||||
description: string;
|
||||
externalGroup: string;
|
||||
id: number;
|
||||
name: string;
|
||||
permissions: PermissionKeys[];
|
||||
updatedAt: string;
|
||||
immutable: boolean;
|
||||
exclusive: boolean;
|
||||
};
|
||||
|
||||
export type NewRoleType = Omit<RoleType, "id" | "createdAt" | "updatedAt">;
|
||||
|
||||
export type PermissionType = {
|
||||
key: PermissionKeys;
|
||||
name: string;
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
declare global {
|
||||
interface Window {
|
||||
config?: any;
|
||||
}
|
||||
}
|
||||
|
||||
export const getConfigProperty = (property: string, defaultValue: any) => {
|
||||
if (window.config && Object.prototype.hasOwnProperty.call(window.config, property)) {
|
||||
return window.config[property];
|
||||
}
|
||||
return defaultValue;
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
export const LocalStorage = {
|
||||
set(key: string, value: any): void {
|
||||
const item = typeof value === "string" ? value : JSON.stringify(value);
|
||||
localStorage.setItem(key, item);
|
||||
},
|
||||
get(key: string): any | null {
|
||||
const value = localStorage.getItem(key);
|
||||
try {
|
||||
return value ? JSON.parse(value) : null;
|
||||
} catch (error) {
|
||||
return value;
|
||||
}
|
||||
},
|
||||
remove(key: string): void {
|
||||
localStorage.removeItem(key);
|
||||
},
|
||||
clear(): void {
|
||||
localStorage.clear();
|
||||
},
|
||||
};
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"typeRoots": ["./node_modules/@types", "./src/types"]
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import react from '@vitejs/plugin-react'
|
||||
import path from 'path'
|
||||
import { defineConfig, loadEnv, splitVendorChunkPlugin } from 'vite'
|
||||
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 {
|
||||
define: {
|
||||
__APP_ENV__: env.APP_ENV,
|
||||
APP_VERSION: JSON.stringify(process.env.npm_package_version)
|
||||
},
|
||||
build: {
|
||||
minify: 'terser',
|
||||
outDir: 'build',
|
||||
sourcemap: false,
|
||||
chunkSizeWarningLimit: 200,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks(id: string) {
|
||||
return 'vendor'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
server: {
|
||||
watch: {
|
||||
usePolling: true
|
||||
},
|
||||
host: true,
|
||||
strictPort: true,
|
||||
port: 8070,
|
||||
proxy: {
|
||||
'/api': 'https://land.mos.ru/'
|
||||
}
|
||||
},
|
||||
plugins: [react(), svgr(), tsconfigPaths(), splitVendorChunkPlugin()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@styles': path.resolve(__dirname, './src/styles')
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user