Merge branch 'NewRegister' into dev

This commit is contained in:
KharchenkoVladimir 2021-10-25 12:05:32 +05:00
commit 1f7ad1cb80
4 changed files with 233 additions and 8 deletions

View File

@ -6,6 +6,7 @@ import {
import {ConfigProvider} from 'antd' import {ConfigProvider} from 'antd'
import locale from "antd/lib/locale/ru_RU" import locale from "antd/lib/locale/ru_RU"
import Login from './pages/Login' import Login from './pages/Login'
import Register from './pages/Register'
import Main from './pages/Main' import Main from './pages/Main'
import { OpenAPI } from './services/api' import { OpenAPI } from './services/api'
import { PrivateRoute } from './components/Private' import { PrivateRoute } from './components/Private'
@ -21,6 +22,9 @@ export default function App() {
<Route path="/login"> <Route path="/login">
<Login /> <Login />
</Route> </Route>
<Route path="/register">
<Register />
</Route>
<PrivateRoute path="/"> <PrivateRoute path="/">
<Main /> <Main />
</PrivateRoute> </PrivateRoute>

View File

@ -3,8 +3,9 @@ import { UserOutlined, LockOutlined } from '@ant-design/icons'
import logo from '../images/logo_32.png' import logo from '../images/logo_32.png'
import Loader from '../components/Loader' import Loader from '../components/Loader'
import { useState } from 'react' import { useState } from 'react'
import { useHistory } from "react-router-dom"; import {Link, useHistory} from "react-router-dom";
import { AuthService, OpenAPI } from '../services/api/' import { AuthService, OpenAPI } from '../services/api/'
import '../styles/index.css'
const { login } = AuthService const { login } = AuthService
@ -39,7 +40,7 @@ export default function Login() {
history.push('well') history.push('well')
}catch(e){ }catch(e){
if(e.status === 400) if(e.status === 400)
openNotificationError(e.message) openNotificationError(e.body)
console.error(`Error ${e}`) console.error(`Error ${e}`)
setErrorVisible(true) setErrorVisible(true)
@ -61,8 +62,9 @@ export default function Login() {
<Form form={form} onFinish={handleLogin}> <Form form={form} onFinish={handleLogin}>
<Form.Item <Form.Item
name="login" name="login"
validateStatus={isErrorVisible ? "error" : "validating"}
rules={[ rules={[
{ required: true, message: 'Пожалуйста введите имя!' }, { required: true, message: 'Пожалуйста, введите имя пользователя' },
() => ({ () => ({
validator() { validator() {
return showError(isErrorVisible, new Error('Неправильные логин или пароль!')) return showError(isErrorVisible, new Error('Неправильные логин или пароль!'))
@ -83,7 +85,7 @@ export default function Login() {
<Form.Item <Form.Item
name="password" name="password"
rules={[ rules={[
{ required: true, message: 'Пожалуйста введите пароль!' }, { required: true, message: 'Пожалуйста, введите пароль' },
() => ({ () => ({
validator() { validator() {
return showError(isErrorVisible) return showError(isErrorVisible)
@ -102,10 +104,17 @@ export default function Login() {
</Form.Item> </Form.Item>
<Form.Item> <Form.Item>
<Button type="primary" htmlType="submit"> <div className='login-button'>
Вход <Button type="primary" htmlType="submit">
</Button> Вход
</Form.Item> </Button>
</div>
</Form.Item>
<div className='text-align-center'>
<Link to={`/register`}>Отправить заявку на регистрацию</Link>
</div>
</Form> </Form>
</Card> </Card>
{loader && <Loader/>} {loader && <Loader/>}

198
src/pages/Register.jsx Normal file
View File

@ -0,0 +1,198 @@
import { Card, Form, Input, Select, Button, notification } from 'antd';
import { UserOutlined,
LockOutlined,
EyeInvisibleOutlined,
EyeTwoTone } from '@ant-design/icons'
import logo from '../images/logo_32.png'
import Loader from '../components/Loader'
import { useState } from 'react'
import { Link, useHistory } from "react-router-dom";
import { AuthService } from '../services/api/'
const openNotification = (message, type, title) => {
notification[type]({
message: title||'Ошибка',
description: message,
});
};
const { Option } = Select;
const companies = [
{ name: "ООО «Газпромнефть-Хантос» ", value: 1 },
{ name: "АО «НафтаГаз»", value: 2 },
{ name: "ООО «Нафтагаз Бурение»", value: 3 },
{ name: "ООО «Газпромнефть-ННГ»", value: 4 }
];
const showError = (isErrorVisible, errorObj) => {
if (isErrorVisible)
return Promise.reject(errorObj)
return Promise.resolve()
}
const getValidationRules = (isRequired, message, isErrorVisible, errorObj) => {
return [
{ required: isRequired, message: message },
() => ({
validator() {
return showError(isErrorVisible, errorObj)
}
})
]
}
export default function Register() {
const [loader, setLoader] = useState(false);
const [isLengthErrorVisible, setIsLengthErrorVisible] = useState(false);
const [isPasswordLengthErrorVisible, setIsPasswordLengthErrorVisible] = useState(false);
const [isPasswordMismatchErrorVisible, setIsPasswordMismatchErrorVisible] = useState(false);
const [selectedCompanyId, setSelectedCompanyId] = useState(companies[0].value);
const history = useHistory();
const [form] = Form.useForm();
const logoIcon = <img src={logo} alt="АСБ" className="logo"/>
const children = companies.map((line) => (
<Option key={line.value}>{line.name}</Option>
));
const checkFormErrors = (formData) => {
if(formData.login.length < 4 || formData.login.length > 50){
setIsLengthErrorVisible(true)
form.validateFields()
return true
}
if(formData.password.length < 4 || formData.password.length > 50) {
setIsPasswordLengthErrorVisible(true)
form.validateFields()
return true
}
if(formData.password !== formData.confirmPassword) {
setIsPasswordMismatchErrorVisible(true)
form.validateFields()
return true
}
return false
}
let handleRegister = async (formData) =>{
if(checkFormErrors(formData))
return
formData.idCompany = +selectedCompanyId
setLoader(true)
try{
await AuthService.register(formData)
setLoader(false)
openNotification("Заявка на регистрацию отправлена.", 'success')
history.push("/login");
}catch(e){
openNotification(e.body, 'error')
console.error(`Error ${e}`)
setLoader(false)
}
}
const createInput = (name, placeholder, isRequired, requiredValidationMessage, lengthValidationMessage) => {
const rules = getValidationRules(true, requiredValidationMessage,
isLengthErrorVisible, new Error(lengthValidationMessage))
return (
<Form.Item
name={name}
rules={isRequired ? rules : []}
>
<Input
placeholder={placeholder}
prefix={<UserOutlined />}
onChange={() => {
setIsLengthErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
)
}
const createPasswordInput = (name, message, errorObj, isErrorVisible, setIsErrorVisible) => {
return (
<Form.Item
name={name}
rules={getValidationRules(true, message, isErrorVisible, errorObj)}
>
<Input.Password
placeholder='Подтверждение пароля'
iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
prefix={<LockOutlined />}
onChange={() => {
setIsErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
)
}
return (
<div className='login_page shadow'>
<Card title="Система мониторинга" className='shadow' bordered={true} style={{ width: 350 }} extra={logoIcon}>
<Form form={form} onFinish={handleRegister}>
{createInput('login', 'Пользователь', true,
'Пожалуйста, введите имя!',
'Допустимая длина логина от 3 до 50 символов!')}
{createPasswordInput('password', 'Пожалуйста, введите пароль!',
new Error('Допускаются пароли от 3х до 50ти символов'),
isPasswordLengthErrorVisible, setIsPasswordLengthErrorVisible)}
{createPasswordInput('confirmPassword', 'Пожалуйста, введите пароль повторно!',
new Error('Пароли не совпадают!'), isPasswordMismatchErrorVisible,
setIsPasswordMismatchErrorVisible)}
{createInput('name', 'Имя', false)}
{createInput('surName', 'Фамилия', false)}
{createInput('patronymic', 'Отчество',false)}
{createInput('email', 'Email',false)}
{createInput('phone', 'Номер телефона',false)}
<Form.Item
name="idCompany"
initialValue={companies[0].name}
>
<Select
placeholder="Выберите компанию"
className="m-0"
value={selectedCompanyId}
onChange={setSelectedCompanyId}
>
{children}
</Select>
</Form.Item>
{createInput('position', 'Должность',false)}
<Form.Item>
<div className='register-button'>
<Button
type="primary"
htmlType="submit"
>
Зарегистрироваться
</Button>
</div>
</Form.Item>
<div className='text-align-center'>
<Link to={`/login`}>Назад</Link>
</div>
</Form>
</Card>
{loader && <Loader/>}
</div>
)
}

View File

@ -75,6 +75,10 @@ body {
vertical-align: center; vertical-align: center;
} }
.text-align-center {
text-align: center;
}
.text-align-r-container { .text-align-r-container {
width: 100%; width: 100%;
text-align: right; text-align: right;
@ -97,3 +101,13 @@ code {
width: 100%; width: 100%;
} }
.login-button {
width: 20%;
margin: auto;
}
.register-button {
width: 50%;
margin: auto;
}