From 91a9bf9c9f520f250f4844ecb6db4f27e242d86b Mon Sep 17 00:00:00 2001 From: goodmice Date: Tue, 7 Dec 2021 19:41:32 +0500 Subject: [PATCH] =?UTF-8?q?=D0=A1=D1=82=D1=80=D0=B0=D0=BD=D0=B8=D1=86?= =?UTF-8?q?=D1=8B=20=D0=B2=D1=85=D0=BE=D0=B4=D0=B0=20=D0=B8=20=D1=80=D0=B5?= =?UTF-8?q?=D0=B3=D0=B8=D1=81=D1=82=D1=80=D0=B0=D1=86=D0=B8=D0=B8=20=D1=83?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D1=89=D0=B5=D0=BD=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pages/Login.jsx | 126 +++++------------ src/pages/Register.jsx | 253 +++++++++++------------------------ src/utils/validationRules.ts | 15 ++- 3 files changed, 122 insertions(+), 272 deletions(-) diff --git a/src/pages/Login.jsx b/src/pages/Login.jsx index 055497b..46af033 100644 --- a/src/pages/Login.jsx +++ b/src/pages/Login.jsx @@ -1,22 +1,18 @@ -import { Card, Form, Input, Button, notification } from 'antd'; +import { Card, Form, Input, Button } from 'antd' import { UserOutlined, LockOutlined } 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 { Link, useHistory } from 'react-router-dom' import { AuthService, OpenAPI } from '../services/api/' +import LoaderPortal from '../components/LoaderPortal' +import { invokeWebApiWrapperAsync } from '../components/factory' +import { loginRules, passwordRules } from '../utils/validationRules' + import '../styles/index.css' +import logo from '../images/logo_32.png' -const { login } = AuthService +const logoIcon = {'АСБ'} -const openNotificationError = (message, title) => { - notification['error']({ - message: title||'Ошибка', - description: message, - }); -}; - -const setUser = (user) =>{ +const setUser = (user) => { OpenAPI.TOKEN = user.token localStorage['userId'] = user.id localStorage['token'] = user.token @@ -24,100 +20,40 @@ const setUser = (user) =>{ } export default function Login() { - const [loader, setLoader] = useState(false); - const [isErrorVisible, setErrorVisible] = useState(false); - const history = useHistory(); - const [form] = Form.useForm(); + const history = useHistory() + const [showLoader, setShowLoader] = useState(false) - const logoIcon = АСБ - - let handleLogin = async (formData) =>{ - setLoader(true) - try{ - let user = await login(formData) + const handleLogin = (formData) => invokeWebApiWrapperAsync( + async () => { + const user = await AuthService.login(formData) + if (!user) throw Error('Неправильный логин или пароль') setUser(user) - setLoader(false) - history.push('well') - }catch(e){ - if(e.status === 400) - openNotificationError(e.body) - console.error(`Error ${e}`) + history.push('well') + }, + setShowLoader, + (ex) => ex?.message ?? 'Ошибка входа' + ) - setErrorVisible(true) - form.validateFields() - setLoader(false) - } - } - - const showError = (isErrorVisible, errorObj) => { - if (isErrorVisible) - return Promise.reject(errorObj) - - return Promise.resolve() - } - return ( -
- -
- ({ - validator() { - return showError(isErrorVisible, new Error('Неправильные логин или пароль!')) - } - }) - ]} - > - } - onChange={() => { - setErrorVisible(false) - form.validateFields() - }} - /> + + + + + } /> - - ({ - validator() { - return showError(isErrorVisible) - } - }) - ]} - > - } - onChange={() => { - setErrorVisible(false) - form.validateFields() - }} - /> + + } /> - -
- +
+
- -
+
Отправить заявку на регистрацию
- - {loader && } -
+ ) } \ No newline at end of file diff --git a/src/pages/Register.jsx b/src/pages/Register.jsx index a84d68b..25d4f23 100644 --- a/src/pages/Register.jsx +++ b/src/pages/Register.jsx @@ -1,198 +1,101 @@ -import { Card, Form, Input, Select, Button, notification } from 'antd'; -import { UserOutlined, +import { memo, useState } from 'react' +import { Link, useHistory } from 'react-router-dom' +import { Card, Form, Input, Select, Button } 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"; + EyeTwoTone +} from '@ant-design/icons' import { AuthService } from '../services/api/' - -const openNotification = (message, type, title) => { - notification[type]({ - message: title||'Ошибка', - description: message, - }); -}; - -const { Option } = Select; +import LoaderPortal from '../components/LoaderPortal' +import { invokeWebApiWrapperAsync } from '../components/factory' +import { + createLoginRules, + createPasswordRules, + emailRules, + loginRules, + nameRules, + passwordRules, + phoneRules +} from '../utils/validationRules' +import logo from '../images/logo_32.png' const companies = [ - { name: "ООО «Газпромнефть-Хантос» ", value: 1 }, - { name: "АО «НафтаГаз»", value: 2 }, - { name: "ООО «Нафтагаз Бурение»", value: 3 }, - { name: "ООО «Газпромнефть-ННГ»", value: 4 } -]; + { label: 'ООО «Газпромнефть-Хантос» ', value: 1 }, + { label: 'АО «НафтаГаз»', value: 2 }, + { label: 'ООО «Нафтагаз Бурение»', value: 3 }, + { label: 'ООО «Газпромнефть-ННГ»', 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 = АСБ - - const children = companies.map((line) => ( - - )); - - const checkFormErrors = (formData) => { - if(formData.login.length < 4 || formData.login.length > 50){ - setIsLengthErrorVisible(true) - form.validateFields() - return true +const surnameRules = [...nameRules, { required: true, message: 'Пожалуйста, введите фамилию!' }] +const regEmailRules = [{ required: true, message: 'Пожалуйста, введите email!' }, ...emailRules] +const confirmPasswordRules = [ + ...createPasswordRules, + { required: true, message: 'Пожалуйста, введите пароль повторно!' }, + ({ getFieldValue }) => ({ + validator(_, value) { + if (!value || getFieldValue('password') === value) + return Promise.resolve() + return Promise.reject(new Error('Пароли не совпадают!')) } + }) +] - if(formData.password.length < 4 || formData.password.length > 50) { - setIsPasswordLengthErrorVisible(true) - form.validateFields() - return true - } +const logoIcon = {'АСБ'} +const showPasswordIcon = visible => (visible ? : ) - if(formData.password !== formData.confirmPassword) { - setIsPasswordMismatchErrorVisible(true) - form.validateFields() - return true - } +const createInput = (name, placeholder, rules, isPassword, dependencies) => ( + + {isPassword ? ( + } iconRender={showPasswordIcon} /> + ) : ( + } /> + )} + +) - return false - } +export const Register = memo(() => { + const [showLoader, setShowLoader] = useState(false) + const history = useHistory() - let handleRegister = async (formData) =>{ - - if(checkFormErrors(formData)) - return - - formData.idCompany = +selectedCompanyId - - setLoader(true) - try{ + const handleRegister = (formData) => invokeWebApiWrapperAsync( + async () => { 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 ( - - } - onChange={() => { - setIsLengthErrorVisible(false) - form.validateFields() - }} - /> - - ) - } - - const createPasswordInput = (name, message, errorObj, isErrorVisible, setIsErrorVisible) => { - return ( - - (visible ? : )} - prefix={} - onChange={() => { - setIsErrorVisible(false) - form.validateFields() - }} - /> - - ) - } + history.push('/login') + }, + setShowLoader, + `Ошибка отправки заявки на регистрацию` + ) return ( -
- -
- {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)} - - + + + + {createInput('login', 'Пользователь', [...loginRules, ...createLoginRules])} + {createInput('password', 'Пароль', [...passwordRules, ...createPasswordRules], true, null)} + {createInput('confirmPassword', 'Подтверждение пароля', confirmPasswordRules, true, ['password'])} + {createInput('name', 'Имя', nameRules)} + {createInput('surName', 'Фамилия', surnameRules)} + {createInput('patronymic', 'Отчество', nameRules)} + {createInput('email', 'Email', regEmailRules)} + {createInput('phone', 'Номер телефона', phoneRules)} + +