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

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

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>
)
}