/* eslint-disable react/jsx-curly-newline */ /* eslint-disable sonarjs/no-small-switch */ import TelegramIcon from '../public/assets/images/telegram.svg'; import styles from './Form.module.scss'; import { publicRuntimeConfig } from '@/config/runtime'; import { FormStateContext } from '@/context/form-state'; import type { LdapUser } from '@/types/user'; import axios from 'axios'; import Image from 'next/image'; import type { PropsWithChildren } from 'react'; import { useContext } from 'react'; import { useForm } from 'react-hook-form'; const ERROR_INVALID_CREDENTIALS = 'Неверный логин или пароль'; const ERROR_SERVER = 'Не удалось войти. Повторите попытку позже'; const { APP_BASE_PATH, TELEGRAM_BOT_URL } = publicRuntimeConfig; type FormData = { readonly login: string; readonly password: string; }; type FormProps = { readonly onSubmit: (data: FormData) => void; }; function BaseForm({ children, onSubmit }: FormProps & PropsWithChildren) { const { handleSubmit, register } = useForm(); const { state: { error, step }, } = useContext(FormStateContext); return (
{step === 'telegram-login' ? ( Открыть чат с ботом ) : null} {error ? {error} : null} {children}
); } export const Form = { Default() { const { dispatch } = useContext(FormStateContext); function handleLogin(data: FormData) { const redirectUrl = (window.location.pathname.replace(APP_BASE_PATH, '') || '/') + (window.location.search || ''); return axios .post('/login', data) .then(() => window.location.replace(redirectUrl)) .catch(() => dispatch({ payload: { error: ERROR_INVALID_CREDENTIALS }, type: 'set-error', }) ); } return ( handleLogin(data)}> ); }, Telegram() { const { dispatch, state: { step, user }, } = useContext(FormStateContext); function handleLogin(data: FormData) { axios .post('/login', data) .then((res) => { dispatch({ payload: { step: 'telegram', user: res.data, }, type: 'set-step', }); }) .catch(() => dispatch({ payload: { error: ERROR_INVALID_CREDENTIALS }, type: 'set-error', }) ); } function handleTelegramLogin() { // window.open(TELEGRAM_BOT_URL); axios .post('/login-telegram') .then(() => { dispatch({ payload: { step: 'telegram-login', }, type: 'set-step', }); }) .catch(() => dispatch({ payload: { error: ERROR_SERVER }, type: 'set-error', }) ); } if (step === 'telegram') { return ( handleTelegramLogin()}> ); } if (step === 'telegram-login') { return ( {}}> ); } return ( handleLogin(data)}> ); }, };