update survey and questions
This commit is contained in:
parent
4c4e6ee619
commit
51f3469031
5 changed files with 122 additions and 40 deletions
|
|
@ -22,12 +22,16 @@ const LoginForm = () => {
|
|||
setError(null);
|
||||
|
||||
try{
|
||||
if (email === '' || password === '')
|
||||
setError('Заполните все поля')
|
||||
else {
|
||||
const responseData = await authUser({email, password});
|
||||
if (responseData && !responseData.error)
|
||||
navigate('/my-surveys');
|
||||
else
|
||||
setError('Неверный логин или пароль')
|
||||
}
|
||||
}
|
||||
catch(err){
|
||||
console.error('Ошибка при отправке запроса:', err);
|
||||
setError('Неверный логин или пароль')
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import React, {useEffect, useState} from "react";
|
||||
import QuestionItem from "../QuestionItem/QuestionItem.tsx";
|
||||
import AddQuestionButton from "../AddQuestionButton/AddQuestionButton.tsx";
|
||||
import {deleteQuestion} from "../../api/QuestionApi.ts";
|
||||
import {deleteQuestion, getListQuestions} from "../../api/QuestionApi.ts";
|
||||
|
||||
interface QuestionsListProps {
|
||||
questions: Question[];
|
||||
|
|
@ -18,11 +18,11 @@ export interface Question {
|
|||
const QuestionsList: React.FC<QuestionsListProps> = ({questions, setQuestions, surveyId}) => {
|
||||
const [selectedType, setSelectedType] = useState<'single' | 'multiply'>('single');
|
||||
|
||||
const [localQuestionId, setLocalQuestionId] = useState(2); // Начинаем с 2, так как первый вопрос имеет ID=1
|
||||
const [localQuestionId, setLocalQuestionId] = useState(1001); // Начинаем с 2, так как первый вопрос имеет ID=1
|
||||
|
||||
const handleAddQuestion = () => {
|
||||
const newQuestion: Question = {
|
||||
id: localQuestionId,
|
||||
id: localQuestionId, // ID >= 1001 — новые вопросы
|
||||
text: '',
|
||||
questionType: selectedType === 'single' ? 'singleanswerquestion' : 'multipleanswerquestion',
|
||||
};
|
||||
|
|
@ -45,6 +45,8 @@ const QuestionsList: React.FC<QuestionsListProps> = ({questions, setQuestions, s
|
|||
const handleDeleteQuestion = async (id: number) => {
|
||||
try {
|
||||
if (surveyId) {
|
||||
const listQuestions = await getListQuestions(surveyId);
|
||||
if (listQuestions.find(q => q.id === id)) {
|
||||
const response = await deleteQuestion(surveyId, id);
|
||||
if (!response?.success) {
|
||||
throw new Error('Не удалось удалить вопрос на сервере');
|
||||
|
|
@ -57,9 +59,14 @@ const QuestionsList: React.FC<QuestionsListProps> = ({questions, setQuestions, s
|
|||
}
|
||||
}
|
||||
setQuestions(newQuestions);
|
||||
}
|
||||
else{
|
||||
const questionsList = questions.filter(q => q.id !== id);
|
||||
setQuestions(questionsList);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при удалении вопроса:', error);
|
||||
alert('Не удалось удалить вопрос: ' + (error instanceof Error ? error.message : 'Неизвестная ошибка'));
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@
|
|||
color: #000000;
|
||||
outline: none;
|
||||
border: none;
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.2);
|
||||
border-bottom: 2px solid rgba(0, 0, 0, 0.2);
|
||||
padding: 5px 0;
|
||||
opacity: 1;
|
||||
}
|
||||
|
|
@ -55,7 +55,7 @@
|
|||
}
|
||||
|
||||
.input:focus {
|
||||
border-bottom: 1px solid black; /* Чёрная граница при фокусе */
|
||||
border-bottom: 2px solid black; /* Чёрная граница при фокусе */
|
||||
}
|
||||
|
||||
.signUp{
|
||||
|
|
|
|||
|
|
@ -31,6 +31,10 @@ const RegisterForm = () => {
|
|||
setError(null);
|
||||
|
||||
try{
|
||||
if (email === '' || password === '' || firstName === '' || lastName === '') {
|
||||
setError('Заполните все поля');
|
||||
}
|
||||
else{
|
||||
const responseData = await registerUser({username, firstName, lastName, email, password});
|
||||
if (responseData && !responseData.error) {
|
||||
console.log('Регистрация успешна');
|
||||
|
|
@ -44,6 +48,7 @@ const RegisterForm = () => {
|
|||
setError('Аккаунт с такой почтой уже зарегистрирован');
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof Error) {
|
||||
if (err.message.includes('409')) {
|
||||
|
|
|
|||
|
|
@ -3,10 +3,27 @@ import QuestionsList, {Question} from "../QuestionsList/QuestionsList.tsx";
|
|||
import {useEffect, useState} from "react";
|
||||
import {getSurveyById, ISurvey, updateSurvey} from "../../api/SurveyApi.ts";
|
||||
import {useParams} from "react-router-dom";
|
||||
import {getListQuestions} from "../../api/QuestionApi.ts";
|
||||
import {addNewQuestion, getListQuestions, updateQuestion} from "../../api/QuestionApi.ts";
|
||||
import styles from "./SurveyPage.module.css";
|
||||
import SaveButton from "../SaveButton/SaveButton.tsx";
|
||||
|
||||
type ActionType = 'create' | 'update';
|
||||
|
||||
class QuestionAction {
|
||||
type: ActionType;
|
||||
data: {
|
||||
surveyId: number;
|
||||
id?: number;
|
||||
title?: string;
|
||||
questionType?: string;
|
||||
};
|
||||
|
||||
constructor(type: ActionType, data: { surveyId: number, id?: number, title?: string, questionType?: string }) {
|
||||
this.type = type;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
export const SurveyPage: React.FC = () => {
|
||||
const [survey, setSurvey] = useState<ISurvey | null>(null);
|
||||
const [questions, setQuestions] = useState<Question[]>([]);
|
||||
|
|
@ -60,24 +77,73 @@ export const SurveyPage: React.FC = () => {
|
|||
if (loading) return <div>Загрузка...</div>;
|
||||
if (!survey) return <div>Опрос не найден</div>;
|
||||
|
||||
const handleSave = async() => {
|
||||
const handleSave = async () => {
|
||||
if (!surveyId || !survey) return;
|
||||
|
||||
try{
|
||||
try {
|
||||
setError(null);
|
||||
const id = parseInt(surveyId);
|
||||
|
||||
const surveyUpdated = await updateSurvey(id, {
|
||||
title: title,
|
||||
description: description,
|
||||
})
|
||||
});
|
||||
setSurvey(surveyUpdated);
|
||||
|
||||
const actions: QuestionAction[] = [];
|
||||
const serverQuestions = await getListQuestions(id);
|
||||
|
||||
questions.forEach(question => {
|
||||
const existsOnServer = serverQuestions.some(q => q.id === question.id);
|
||||
|
||||
if (existsOnServer) {
|
||||
actions.push(new QuestionAction("update", {
|
||||
surveyId: id,
|
||||
id: question.id,
|
||||
title: question.text,
|
||||
questionType: question.questionType
|
||||
}));
|
||||
} else {
|
||||
actions.push(new QuestionAction("create", {
|
||||
surveyId: id,
|
||||
title: question.text,
|
||||
questionType: question.questionType
|
||||
}));
|
||||
}
|
||||
catch(error){
|
||||
console.error('Ошибка при сохранении опроса:', error);
|
||||
});
|
||||
|
||||
for (const action of actions) {
|
||||
switch (action.type) {
|
||||
case "create":
|
||||
await addNewQuestion(id, {
|
||||
title: action.data.title as string,
|
||||
questionType: action.data.questionType as 'singleanswerquestion' | 'multipleanswerquestion',
|
||||
});
|
||||
break;
|
||||
case "update":
|
||||
if (action.data.id) {
|
||||
await updateQuestion(id, action.data.id, {
|
||||
title: action.data.title,
|
||||
questionType: action.data.questionType
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const updatedQuestions = await getListQuestions(id);
|
||||
const formattedQuestions = updatedQuestions.map(q => ({
|
||||
id: q.id,
|
||||
text: q.title,
|
||||
questionType: q.questionType as 'singleanswerquestion' | 'multipleanswerquestion',
|
||||
}));
|
||||
setQuestions(formattedQuestions);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Ошибка:', error);
|
||||
setError('Не удалось сохранить изменения');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.survey_page}>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue