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