Переписываю спорные решения

This commit is contained in:
Дмитрий Савенко 2023-01-16 19:12:44 +03:00
parent e15ce861a3
commit 1d8b30370d
15 changed files with 97 additions and 223 deletions

View File

@ -42,20 +42,20 @@ const App = () => {
<Route exact path='/report' element={<ReportPage/>}/>
<Route path='/report/:id' element={<SingleReportPage/>}/>
<Route path='/quiz' element={<QuizPage/>}/>
<Route path='/quiz-interjacent' element={<InterjacentPage/>}/>
<Route path='/quiz-test' element={<QuizTestPage/>}/>
<Route path='/quiz-instruction' element={<InstructionPage/>}/>
<Route path='/quiz-result' element={<ResultPage/>}/>
<Route exact path='quiz'>
<Route index element={<QuizPage/>}/>
<Route path='interjacent' element={<InterjacentPage/>}/>
<Route path='test' element={<QuizTestPage/>}/>
<Route path='instruction' element={<InstructionPage/>}/>
<Route path='result' element={<ResultPage/>}/>
</Route>
<Route exact path='/profile' element={<Profile/>}>
<Route exact path='profile'>
<Route index element={<Profile/>}/>
<Route exact path='calendar' element={<ProfileCalendarPage/>}/>
<Route exact path='summary' element={<Summary/>}/>
</Route>
{/*<Route component={() => <div>Page not found</div>} />*/}
{/*<Route path='*' component={() => <div>Page not found</div>}/>*/}
<Route path="*" element={<Navigate to="/" replace/>}/>
</Routes>
</Router>

View File

@ -2,7 +2,7 @@ import React from 'react'
import { Link } from 'react-router-dom'
import { Achievement } from '../Achievement/Achievement'
import { LEVELS, SKILLS } from '../constants/constants'
import { LEVELS, SKILLS } from '../../constants/constants'
import './candidateSidebar.scss'

View File

@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react'
import male from '../../images/medium_male.png'
import rectangle from '../../images/rectangle_secondPage.png'
import { Link } from 'react-router-dom'
import { LEVELS, SKILLS } from '../constants/constants'
import { LEVELS, SKILLS } from '../../constants/constants'
import {
selectProfiles,
selectFilteredCandidates,

View File

@ -1,6 +1,4 @@
import React, { useState } from 'react'
import { fetchPost } from '../../server/server'
import { auth } from '../../redux/outstaffingSlice'
import {useParams, useNavigate} from 'react-router-dom'
import { Loader } from '../Loader/Loader'
import PhoneInput from 'react-phone-input-2'
@ -9,59 +7,57 @@ import './form.scss'
import { withSwalInstance } from 'sweetalert2-react'
import swal from 'sweetalert2'
import { useSelector, useDispatch } from 'react-redux'
import { getRole } from '../../redux/roleSlice'
import {useRequest} from "../../hooks/useRequest";
const SweetAlert = withSwalInstance(swal)
const SweetAlert = withSwalInstance(swal);
const Form = () => {
const dispatch = useDispatch()
const navigate = useNavigate()
const role = useSelector(getRole)
const urlParams = useParams()
const [status, setStatus] = useState(null)
const navigate = useNavigate();
const urlParams = useParams();
const [status, setStatus] = useState(null);
const [data, setData] = useState({
email: '',
phone: '',
comment: ''
})
const [isFetching, setIsFetching] = useState(false)
});
const [isFetching, setIsFetching] = useState(false);
const {apiRequest} = useRequest();
const handleChange = (e) => {
const { id, value } = e.target
const { id, value } = e.target;
setData((prev) => ({
...prev,
[id]: value
}))
}
};
const handleSubmit = (e) => {
e.preventDefault()
e.preventDefault();
setIsFetching(true)
const formData = new FormData()
formData.append('profile_id', urlParams.id)
formData.append('email', data.email)
formData.append('phone', data.phone)
formData.append('comment', data.comment)
setIsFetching(true);
const formData = new FormData();
formData.append('profile_id', urlParams.id);
formData.append('email', data.email);
formData.append('phone', data.phone);
formData.append('comment', data.comment);
fetchPost({
link: `${process.env.REACT_APP_API_URL}/api/interview-request/create-interview-request`,
apiRequest('/interview-request/create-interview-request',{
method: 'POST',
params: {
profile_id: urlParams.id,
...data
},
role,
logout: () => dispatch(auth(false))
}).then((res) =>
res.json().then((resJSON) => {
setStatus(resJSON)
setIsFetching(false)
})
)
}
}).then((res) => {
setStatus(res);
setIsFetching(false)
}
)
};
return (
<>
@ -135,6 +131,6 @@ const Form = () => {
</div>
</>
)
}
};
export default Form

View File

@ -18,13 +18,12 @@ export const ProfileCalendar = () => {
const [month, setMonth] = useState('');
const [reports, setReports] = useState([]);
const [totalHours, setTotalHours] = useState(0);
const [value, setValue] = useState(moment());
const [requestDates, setRequestDates] = useState('');
const {apiRequest} = useRequest();
useEffect(() => {
setRequestDates(getReports(value))
setRequestDates(getReports(moment()))
});
useEffect(async () => {
@ -69,7 +68,7 @@ export const ProfileCalendar = () => {
<div>
<Link to='/report'>
<button className='calendar__btn' onClick={() => {
dispatch(setReportDate(value))
dispatch(setReportDate(moment()))
}}>Заполнить отчет за день</button>
</Link>
</div>

View File

@ -1,18 +1,16 @@
import React, {useState} from 'react'
import {useSelector, useDispatch} from 'react-redux'
import {fetchPost} from '../../server/server'
import {useNavigate, useParams, Redirect, Link} from 'react-router-dom'
import {useSelector} from 'react-redux'
import {Link} from 'react-router-dom'
import {Loader} from '../Loader/Loader'
import {auth} from '../../redux/outstaffingSlice'
import {getReportDate} from '../../redux/reportSlice'
import {getRole} from '../../redux/roleSlice'
import calendarIcon from '../../images/calendar_icon.png'
import ellipse from '../../images/ellipse.png'
import remove from '../../images/remove.png'
import addIcon from '../../images/addIcon.png'
import {currentMonthAndDay, getReports} from '../Calendar/calendarHelper'
import {currentMonthAndDay} from '../Calendar/calendarHelper'
import './reportForm.scss'
import arrow from "../../images/right-arrow.png";
import {useRequest} from "../../hooks/useRequest";
const getCreatedDate = (day) => {
if (day) {
@ -27,10 +25,9 @@ const getCreatedDate = (day) => {
};
const ReportForm = () => {
const dispatch = useDispatch();
const reportDate = useSelector(getReportDate);
const role = useSelector(getRole);
const {apiRequest} = useRequest();
const [isFetching, setIsFetching] = useState(false);
const [reportSuccess, setReportSuccess] = useState(false);
@ -50,6 +47,29 @@ const ReportForm = () => {
}
};
const handler = () => {
apiRequest('/reports/create', {
method: 'POST',
body: {
tasks: inputs,
difficulties: troublesInputValue,
tomorrow: scheduledInputValue,
created_at: getCreatedDate(reportDate),
status: 1,
},
}).then((res) => {
if (res.status === 200) {
setReportSuccess(true);
setTimeout(() => setReportSuccess(false), 2000)
}
setInputs(() => []);
setTroublesInputValue('');
setScheduledInputValue('');
setIsFetching(false);
setInputs(() => [{task: '', hours_spent: '', minutes_spent: 0}]);
})
};
return (
<section className='report-form'>
<div className='row'>
@ -149,32 +169,7 @@ const ReportForm = () => {
<div className='row'>
<div className='col-12'>
<div className='report-form__footer'>
<button className='report-form__footer-btn' onClick={() => {
fetchPost({
link: `${process.env.REACT_APP_API_URL}/api/reports/create`,
role,
body: {
tasks: inputs,
difficulties: troublesInputValue,
tomorrow: scheduledInputValue,
created_at: getCreatedDate(reportDate),
status: 1,
},
logout: () => dispatch(auth(false))
}).then((res) =>
res.json().then((resJSON) => {
if (res.status === 200) {
setReportSuccess(true);
setTimeout(() => setReportSuccess(false), 2000)
}
setInputs(() => []);
setTroublesInputValue('');
setScheduledInputValue('');
setIsFetching(false);
setInputs(() => [{task: '', hours_spent: '', minutes_spent: 0}]);
})
)
}}>
<button className='report-form__footer-btn' onClick={() => handler()}>
{isFetching ? <Loader/> : 'Отправить'}
</button>
<p className='report-form__footer-text'>

View File

@ -6,7 +6,7 @@ import {selectedTest, selectUserInfo} from "../../../redux/quizSlice";
export const HeaderPageTestsQuiz = ({isVisibilityButton}) => {
const test = useSelector(selectedTest)
const test = useSelector(selectedTest);
const userInfo = useSelector(selectUserInfo);
return (
@ -23,8 +23,8 @@ export const HeaderPageTestsQuiz = ({isVisibilityButton}) => {
</div>
</div>
{isVisibilityButton &&
<Link to={'/quiz-instruction'} className='quiz-btn quiz-btn_restriction'>Пройти</Link>}
<Link to={'/quiz/instruction'} className='quiz-btn quiz-btn_restriction'>Пройти</Link>}
</div>
</div>
)
}
};

View File

@ -1,5 +1,4 @@
import {Link} from 'react-router-dom'
import {CodeSnippetlighter} from '../../../pages/CodeSnippetPage'
import comment from './../../../images/comment.jpg'
import './quiz.scss'
import {useEffect, useState} from "react";
@ -19,7 +18,6 @@ export const Instruction = () => {
apiRequest('/user-questionnaire/get-question-number', {
params: {user_questionnaire_uuid: test.uuid},
}
).then((res)=> setCountQuestions(res.question_number))
@ -39,7 +37,7 @@ export const Instruction = () => {
e
lit, sed do eiusmod tempo
</div>
<Link to="/quiz-test" className='instruction__btn quiz-btn quiz-btn_restriction'>Далее</Link>
<Link to="/quiz/test" className='instruction__btn quiz-btn quiz-btn_restriction'>Далее</Link>
<div className="instruction__info">
<div className="instruction__icon">
<img src={comment} alt=""/>

View File

@ -7,7 +7,7 @@ import {setSelectedTest} from "../../../redux/quizSlice";
export const MyTestsQuiz = ({listTests}) => {
const formationEndingOfScore = (score) => {
const lastNumber = score % 10
const lastNumber = score % 10;
if(score === 11 ||score === 12 ||score === 13 ||score === 14 ){
return 'баллов'
}else if(lastNumber === 2 || lastNumber === 3 || lastNumber === 4 ){
@ -17,10 +17,10 @@ export const MyTestsQuiz = ({listTests}) => {
}else{
return 'баллов'
}
}
};
const dispatch = useDispatch()
const recordSelectedTest = (item) => dispatch(setSelectedTest(item))
const dispatch = useDispatch();
const recordSelectedTest = (item) => dispatch(setSelectedTest(item));
return (
<div className="my-tests">
@ -35,10 +35,10 @@ export const MyTestsQuiz = ({listTests}) => {
{item.questionnaire_title}
</h3>
<div className="item-test__body test-data">
<Link to={'/quiz-interjacent'} className='quiz-btn'
<Link to={'/quiz/interjacent'} className='quiz-btn'
onClick={() => recordSelectedTest(item)}>Пройти</Link>
</div>
</article>
</article>;
case 2:
return <article className="my-tests__item item-test" key={item.questionnaire_title}>
<h3 className="item-test__name-test">
@ -52,7 +52,7 @@ export const MyTestsQuiz = ({listTests}) => {
<div className="test-data__hr"></div>
<div className="test-data__score quiz-text">{item.score} {formationEndingOfScore(item.score)}</div>
</div>
</article>
</article>;
case 3:
return <article className="my-tests__item item-test" key={item.questionnaire_title}>
<h3 className="item-test__name-test">
@ -61,7 +61,7 @@ export const MyTestsQuiz = ({listTests}) => {
<div className="item-test__body test-data">
<div className='quiz-btn'>На проверке</div>
</div>
</article>
</article>;
default:
break
}
@ -70,4 +70,4 @@ export const MyTestsQuiz = ({listTests}) => {
</div>
</div>
)
}
};

View File

@ -2,20 +2,15 @@ import React, {useEffect, useState} from 'react'
import {useNavigate} from "react-router-dom"
import {useSelector, useDispatch} from 'react-redux'
import {
fetchGetAnswers,
selectAnswer,
selectedTest
} from '../../../redux/quizSlice'
import {useRequest} from "../../../hooks/useRequest";
import {Progressbar} from './ProgressbarQuiz'
import {GetOptionTask} from './GetOptionTask'
import {fetchUserAnswersMany, fetchUserAnswerOne} from './../../../redux/quizSlice'
import {
fetchUserAnswersMany, fetchUserAnswerOne, fetchGetAnswers, selectAnswer, selectedTest
} from './../../../redux/quizSlice'
import './quiz.scss'
import {useRequest} from "../../../hooks/useRequest";
export const TaskQuiz = () => {
@ -38,11 +33,12 @@ export const TaskQuiz = () => {
useEffect(() => {
apiRequest(`/question/get-questions?uuid=${dataTest.uuid}`)
.then((response) => {
console.log(response)
setQuestions(response);
dispatch(fetchGetAnswers(response[0].id));
setStripValue((+index + 1) * 100 / response.length)
})
}, [dispatch]);
}, [dispatch, apiRequest]);
const nextQuestion = async (e) => {
e.preventDefault();
@ -70,7 +66,7 @@ export const TaskQuiz = () => {
setCheckedValues([]);
setInputValue('')
} else {
navigate(`/quiz-result`);
navigate(`/quiz/result`);
alert("Тест пройден!")
}

View File

@ -8,7 +8,7 @@ import {
import SVG from 'react-inlinesvg'
import {WithLogout} from '../hoc/withLogout'
import Form from '../components/Form/Form'
import {LEVELS, SKILLS} from '../components/constants/constants'
import {LEVELS, SKILLS} from '../constants/constants'
import {Footer} from '../components/Footer/Footer'
import arrow from '../images/right-arrow.png'

View File

@ -32,7 +32,7 @@ export const Profile = () => {
</div>
</div>
<div className='profile__items'>
<Link to={'/calendar'} className='item'>
<Link to={'/profile/calendar'} className='item'>
<div className='item__about'>
<img src={reportsIcon} alt='report'/>
<h3>Ваша отчетность</h3>
@ -44,7 +44,7 @@ export const Profile = () => {
</div>
</div>
</Link>
<Link to={'/summary'} className='item'>
<Link to={'/profile/summary'} className='item'>
<div className='item__about'>
<img src={summaryIcon} alt='summary'/>
<h3>Данные и резюме</h3>

View File

@ -70,17 +70,7 @@ export const fetchGetAnswers = createAsyncThunk(
)
}
);
// export const fetchGetQuestion = createAsyncThunk(
// 'questions',
// async (uuid) => {
// const resp = await fetchGet({
// link: `${process.env.REACT_APP_API_URL}/api/question/get-questions?uuid=${uuid}`,
// Origin: `${process.env.REACT_APP_BASE_URL}`,
// }
// )
// return resp
// }
// )
export const fetchResultTest = createAsyncThunk(
'result',
async (uuid) => {
@ -99,7 +89,7 @@ export const quizSlice = createSlice({
reducers: {
setQuestionnairesList: (state, action) => {
state.dataQuestionnairesOfUser = action.payload;
state.passedTests = action.payload.filter(item=>item.status === 2)
state.passedTests = action.payload.filter(item => item.status === 2)
},
setSelectedTest: (state, action) => {
state.selectedTest = action.payload

View File

@ -1,85 +1,5 @@
import { withAuthRedirect } from './authRedirect'
// export const fetchForm = withAuthRedirect(async (link, info) => {
// try {
// const response = await fetch(link, {
// method: 'POST',
// headers: {
// // 'Access-Control-Request-Headers': 'authorization',
// Authorization: `Bearer ${localStorage.getItem('auth_token')}`,
// Origin: `${process.env.REACT_APP_BASE_URL}`,
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(info)
// });
//
// return response
// } catch (error) {
// console.log('Query error', error)
// }
// });
// export const fetchAuth = async ({
// username,
// password,
// dispatch,
// catchError
// }) => {
// const apiURL = process.env.REACT_APP_API_URL;
// try {
// const response = await fetch(`${apiURL}/api/user/login`, {
// method: 'POST',
// mode: 'cors',
// headers: {
// 'Access-Control-Request-Headers': 'authorization',
// 'Content-Type': 'application/json'
// // Origin: `http://localhost`
// },
// body: JSON.stringify({
// username,
// password
// })
// });
//
// if (!response.ok) {
// catchError();
// return response.statusText
// }
//
// response.json().then((resJSON) => {
// localStorage.setItem('auth_token', resJSON.access_token);
// localStorage.setItem('id', resJSON.id);
// localStorage.setItem('cardId', resJSON.card_id);
// localStorage.setItem(
// 'access_token_expired_at',
// resJSON.access_token_expired_at
// );
// dispatch(resJSON)
// })
// } catch (error) {
// console.error('Error occured: ', error)
// }
// };
// export const fetchReportList = withAuthRedirect(async (link) => {
// try {
// const response = await fetch(
// `https://guild.loc/api/reports/index?user_id=26&fromDate=2021-10-18`,
// // link,
// {
// method: 'GET',
// headers: {
// Authorization: `Bearer ${localStorage.getItem('auth_token')}`
// }
// }
// );
// let data = await response.json();
//
// return data
// } catch (error) {
// console.log('Query error', error)
// }
// });
export const fetchGet = withAuthRedirect(async (link) => {
try {
@ -96,23 +16,3 @@ export const fetchGet = withAuthRedirect(async (link) => {
console.log('Query error', error)
}
});
export const fetchPost = withAuthRedirect(async (link, body) => {
console.log('i', body);
try {
const response = await fetch(link, {
method: 'POST',
headers: {
Authorization: `Bearer ${localStorage.getItem('auth_token')}`,
'Content-Type': 'application/json',
//Origin: `http://localhost:3000`
Origin: `${process.env.REACT_APP_BASE_URL}`
},
body: JSON.stringify(body)
});
return response
} catch (error) {
console.log('Query error', error)
}
});