Инициализация в новом репозитории

This commit is contained in:
commit eb1f18f53e
374 changed files with 226678 additions and 0 deletions

View file

@ -0,0 +1,10 @@
import { ModalWindow, ModalContainer } from "./style"
import { modalNames } from "../../const/modals/names"
export const WindowComponent = ()=>{
return(
<ModalWindow>
</ModalWindow>
)
}

View file

@ -0,0 +1,58 @@
import Input from "../../UI/inputs/input"
import { MainButton } from "../../UI/buttons/mainButton";
import { useState } from "react";
import { ModalContainer, ModalTitle, ModalContent, ModalText, ButtonContainer } from "../style"
import { validateIPAddress } from "../../../utils/nodeController/validator";
interface Props {
onSave?: (data: string) => void;
onClose: () => void;
}
export const AddDevice = ({ onSave, onClose }: Props) => {
const [ipAddress, setIpAddress] = useState('')
const [error, setError] = useState(false)
const handleSubmit = () => {
if (!validateIPAddress(ipAddress)) {
setError(true)
return;
}
// e.preventDefault(); // Предотвращаем перезагрузку страницы
if (onSave && ipAddress) {
setError(false)
onSave(ipAddress);
onClose();
}
};
return (
<ModalContainer style={{ height: '230px' }}>
{/* <form onSubmit={handleSubmit}> */}
<ModalTitle>
<h3>Добавление узла</h3>
</ModalTitle>
<ModalContent style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
<Input
type="text"
placeholderText='Введите адрес узла...'
id="newIp"
value={ipAddress}
onChange={(id, value) => setIpAddress(value)}
/>
{error && (
<p style={{ color: 'red', marginTop: '5px' }}>
Некорректный адрес узла
</p>
)}
</ModalContent>
<ButtonContainer>
<MainButton type="button" size="small" title="Отмена" onClick={onClose} />
<MainButton type="submit" size="small" title="Сохранить" onClick={handleSubmit} />
</ButtonContainer>
{/* </form> */}
</ModalContainer>
)
}

View file

@ -0,0 +1,38 @@
import { ModalContainer, ModalTitle, ModalContent, ModalText, ButtonContainer } from "../style"
import { useModalContext } from "../../../store"
import { useIpStore } from "../../../store"
import { MainButton } from "../../UI/buttons/mainButton"
type Props={
message: string
}
export const ConnectionError = ({message}: Props)=>{
const {closeModal} = useModalContext()
const { setIpAddress } = useIpStore();
const close = ()=>{
setIpAddress('localhost')
closeModal()
}
return(
<ModalContainer>
<ModalTitle>
<h3>Соединение прервано</h3>
</ModalTitle>
<ModalContent>
<ModalText>
<h3>Произошёл разрыв с сервером</h3>
<p>Пожалуйста, проверьте доступ к адресу и попробуйте снова.</p>
</ModalText>
</ModalContent>
<ButtonContainer>
<MainButton title="Закрыть" onClick={close} size="small"/>
<MainButton title="Повторить" onClick={closeModal} size="small"/>
</ButtonContainer>
</ModalContainer>
)
}

View file

@ -0,0 +1,4 @@
export {IpConfirm} from './ipConfirm'
export {ConnectionError} from './connectionError'
export {AddDevice} from './addDevice'
export {RightsConfirm} from './rightsConfirm'

View file

@ -0,0 +1,209 @@
import styled from "styled-components";
import Loader from "../../UI/loader";
import { useEffect, useState } from "react";
import { changeIp } from '../../../const/types/types'
import { NetworkService } from '../../../api/request'
import { ModalContainer, ModalTitle, ModalContent, ModalText, ButtonContainer, ErrorMessage } from "../style"
import { useIpStore } from "../../../store";
import { MainButton } from "../../UI/buttons/mainButton";
import { useAdminStore } from "../../../store/adminStore";
import { useDevicesStore } from "../../../store";
type Props = {
ipData: changeIp
onClose: () => void;
smoothClose: () => void;
}
const Information = styled.div`
display: flex;
flex-direction: column;
gap: 15px;
`
const Info = styled.div`
display: flex;
gap: 10px;
`
const DataContainer = styled.div`
display: flex;
gap: 35px;
`
const CurrentData = styled.div`
display: flex;
flex-direction: column;
gap: 10px;
`
const NewData = styled.div`
display: flex;
flex-direction: column;
gap: 10px;
`
export const IpConfirm = ({ ipData, onClose, smoothClose }: Props) => {
const [loader, setLoader] = useState(true)
const [newIP, setNewIp] = useState(null)
const [currentIp, setCurrentIP] = useState({})
const [checkStatus, setcheckStatus] = useState(false)
const [message, setMessgae] = useState('')
const { ipAddress, setIpAddress } = useIpStore();
const {isAdmin} = useAdminStore()
const { devices, addDevice, deleteDevice } = useDevicesStore();
useEffect(() => {
if (ipData && isAdmin) {
const data = {
"connection_id": ipData.connection,
"ipv4_updates": {
"ipv4.method": "manual",
"ipv4.address-data": [
{
"address": ipData.newIp,
"prefix": ipData.prefix
}
],
"ipv4.gateway": ipData.newGate,
"ipv4.dns-data": ipData.newDns
}
};
const oldData = {
"connection_id": ipData.connection,
"ipv4_updates": {
"ipv4.method": "manual",
"ipv4.address-data": [
{
"address": ipData.currentIp,
"prefix": ipData.prefix
}
],
"ipv4.gateway": ipData.currentGate,
"ipv4.dns-data": ipData.currentDns
}
}
setCurrentIP(oldData)
checkIp(data);
}
}, [ipData, isAdmin]);
const checkIp = async (data: any) => {
try {
const result = await NetworkService.checkIp(ipAddress, data);
setcheckStatus(result.data.available)
setMessgae(result.data.message)
if (result.data.available) {
setNewIp(data)
}
} catch (err) {
console.error('Error:', err);
} finally {
setLoader(false);
}
};
const saveIp = async (data: any) => {
try {
const result = await NetworkService.saveIp(ipAddress, data);
if (result.status === 200) {
setIpAddress(ipData.newIp)
const updatedDevices = devices.map(device =>
device.address === ipData.currentIp
? { ...device, address: ipData.newIp }
: device
);
useDevicesStore.setState({ devices: updatedDevices });
onClose()
}
} catch (err) {
console.error('Error:', err);
} finally {
setLoader(false);
}
};
const cancelIp = async (data: any) => {
try {
const result = await NetworkService.saveIp(ipAddress, data);
if (result.status === 200) {
onClose()
}
} catch (err) {
console.error('Error:', err);
} finally {
setLoader(false);
}
};
return (
<>
{loader && isAdmin ? (
<Loader loaderText="Идет проверка корректности IP адреса" />
) : (
<ModalContainer {...(checkStatus ? { height: "unset" } : {})}>
<ModalTitle>
<h3>Изменение IP-Адреса</h3>
</ModalTitle>
{checkStatus ? (
<ModalContent>
<Information>
<h3>Общие сведения</h3>
<Info>
<p>Интерфейс: {ipData.device}</p>
<p>--{'>'}</p>
<p>{ipData.connection}</p>
</Info>
<h3>Сведения об IP</h3>
<DataContainer>
<CurrentData>
<p>Текущий ip: {ipData.currentIp}</p>
<p>Текущий шлюз: {ipData.currentGate}</p>
<p>Текущий DNS: {ipData.currentDns}</p>
</CurrentData>
<NewData>
<p>Новый ip: {ipData.newIp}</p>
<p>Новый шлюз: {ipData.newGate}</p>
<p>Новый DNS: {ipData.newDns}</p>
</NewData>
</DataContainer>
</Information>
<ButtonContainer>
<MainButton title="Отмена" size='small' onClick={() => cancelIp(currentIp)}/>
<MainButton title="Сохранить" size='small' onClick={() => saveIp(newIP)}/>
</ButtonContainer>
</ModalContent>
) : (
<>
<ModalContent>
<ModalText>
{isAdmin ? (
<>
<h3>Произошла ошибка проверки корректности</h3>
<ErrorMessage>{message}</ErrorMessage>
</>
):(
<h3>Для изменения сетевых настроек необходимо авторизироваться под администратором</h3>
)}
</ModalText>
</ModalContent>
<ButtonContainer>
<MainButton title="Закрыть" size='small' onClick={smoothClose}/>
</ButtonContainer>
</>
)}
</ModalContainer>
)}
</>
)
}

View file

@ -0,0 +1,135 @@
import { useEffect, useState } from "react"
import { ModalContainer, ModalTitle, ModalContent, ModalText, ButtonContainer } from "../style"
import Input from "../../UI/inputs/input"
import { MainButton } from "../../UI/buttons/mainButton"
import { NetworkService } from "../../../api/request"
import { useIpStore } from "../../../store"
import { useAdminStore } from "../../../store/adminStore"
import { useCheckAdmin } from "../../../utils/checkAdmin"
import { buttonNames } from "../../../const/buttons/names"
import { IconComponent } from "../../../const/buttons/icons"
interface Props {
onClose: () => void;
}
export const RightsConfirm = ({ onClose }: Props) => {
const { ipAddress } = useIpStore();
const { isAdmin, setAdmin } = useAdminStore()
const checkAdmin = useCheckAdmin();
const [error, setError] = useState(false)
const [success, setSuccess] = useState({
message: '',
status: false
})
const [user, setUser] = useState({
username: 'operator',
password: ""
})
const handleChange = (id: string, value: string) => {
setUser(prevData => ({
...prevData,
[id]: value
}));
}
const login = async (user: object) => {
try {
const response = await NetworkService.login(ipAddress, user);
if(response.status === 200){
await checkAdmin();
setError(false)
setSuccess(prevData => ({
...prevData,
message: 'Успешный вход',
status: true
}));
await new Promise(resolve => setTimeout(resolve, 3000));
onClose();
}else{
setError(true)
}
} catch (err) {
console.error('Error:', err);
}
}
const logout = async () => {
await NetworkService.logout(ipAddress);
await checkAdmin();
setSuccess(prevData => ({
...prevData,
message: 'Успешный выход',
status: true
}));
await new Promise(resolve => setTimeout(resolve, 3000));
onClose();
}
return (
<ModalContainer style={!isAdmin ? {height: '250px'} : {height: 'unset'}}>
{!success.status ? (
!isAdmin ? (
<>
<ModalTitle>
<h3>Получение прав доступа</h3>
</ModalTitle>
<ModalContent style={{display: 'flex', flexDirection: 'column', gap: '10px'}}>
<h3 style={{marginLeft: '5px', fontSize: '14px'}}>Включить административный доступ</h3>
<Input
type="password"
placeholderText='Введите пароль администратора...'
id="password"
value={user.password}
onChange={(id, value) => handleChange(id, value)}
/>
{error && (
<p style={{ color: 'red', marginLeft: '10px', fontSize: '14px', textAlign: 'right' }}>
Неверный пароль оператора
</p>
)}
</ModalContent>
<ButtonContainer>
<MainButton size="small" title="Отмена" onClick={onClose} />
<MainButton size="small" title="Отправить" onClick={() => login(user)} />
</ButtonContainer>
</>
) : (
<>
<ModalTitle>
<h3>Переключиться на ограниченный доступ</h3>
</ModalTitle>
<ModalContent>
<p>В данном режиме доступа ограничиваются полномочия администратора.</p>
</ModalContent>
<ButtonContainer>
<MainButton size="small" title="Отмена" onClick={onClose} />
<MainButton size="small" title="Ограничить доступ" onClick={logout} />
</ButtonContainer>
</>
)
):(
<ModalContainer style={{display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', marginTop: '15px'}}>
<IconComponent name={buttonNames[8]} width="50" height="50"/>
<h3>{success.message}</h3>
<p style={{fontSize: '12px'}}>Это окно можно закрыть, либо оно пропадёт само</p>
<MainButton size="small" title="Закрыть" onClick={onClose} style={{width: '30%'}}/>
</ModalContainer>
)}
</ModalContainer>
)
}

View file

@ -0,0 +1,50 @@
import { useModalContext } from "../../store";
import { IpConfirm, ConnectionError, AddDevice, RightsConfirm } from "./modalContainers";
import { ModalMap } from "./windowsType";
import Loader from "../UI/loader";
import { ModalWindow } from "./style";
type Props = {
isOpen: boolean,
type: string
data: any;
}
export default function WindowComponent({ isOpen, type, data }: Props) {
const { closeModal, closeLoader } = useModalContext()
return (
<>
{isOpen &&
<ModalWindow>
{type == ModalMap['1'] && data &&
<IpConfirm
ipData={data}
onClose={closeModal}
smoothClose={closeLoader}
/>
}
{type == ModalMap['2'] &&
<Loader loaderText={data} />
}
{type === ModalMap['3'] &&
<ConnectionError
message={data.message}
/>
}
{type === ModalMap['4'] && (
<AddDevice onSave={data?.onSave} onClose={closeLoader} />
)}
{type === ModalMap['5'] && (
<RightsConfirm onClose={closeLoader} />
)}
</ModalWindow >
}
</>
)
}

View file

@ -0,0 +1,70 @@
import styled from "styled-components";
export const ModalWindow = styled.div`
width: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 9999;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
height: 100%;
`
export const ModalContainer = styled.div<{height?: string}>`
border-radius: 12px;
background: ${(props)=>props.theme.secondary};
color: ${(props=>props.theme.textColor)};
position: relative;
max-height: 100%;
overflow: auto;
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 15px;
height: ${(props) => props.height ? props.height : '200px'};
width: 520px;
`
export const ModalTitle = styled.div`
padding: 20px;
border-bottom: 1px solid #9D9D9D;
display: flex;
justify-content: space-between;
h3{
font-size: 18px;
}
`
export const ModalContent = styled.div`
padding: 0 20px;
h3{
font-size: 14px;
}
p{
font-size: 12px;
}
`
export const ModalText = styled.div`
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 10px;
`
export const ErrorMessage = styled.p`
color: #d95454;
`
export const ButtonContainer = styled.div`
justify-content: flex-end;
display: flex;
gap: 10px;
padding: 20px;
`

View file

@ -0,0 +1,9 @@
export type ModalType = Record<string, string>;
export const ModalMap: ModalType = {
'1': 'ipConfirm',
'2': 'loader',
'3': 'connectionError',
'4': 'addDevice',
'5': 'sudo'
}