From 6eb03dc11243966412d767416dc6f8bd3a1003b6 Mon Sep 17 00:00:00 2001 From: Tatiana Nikolaeva Date: Sun, 25 May 2025 20:24:54 +0500 Subject: [PATCH] fix add new answer --- SurveyFrontend/src/api/AuthApi.ts | 9 +- SurveyFrontend/src/api/SurveyApi.ts | 24 ---- .../components/AnswerOption/AnswerOption.tsx | 1 - .../components/MySurveyList/MySurveyList.tsx | 13 -- .../components/QuestionItem/QuestionItem.tsx | 31 +++-- .../QuestionsList/QuestionsList.tsx | 43 +++++-- .../RegisterForm/RegisterForm.module.css | 3 +- .../src/components/Survey/Survey.tsx | 5 - .../src/components/SurveyPage/SurveyPage.tsx | 114 ++++++------------ .../components/TimeEvent/TimeEvent.module.css | 4 +- 10 files changed, 87 insertions(+), 160 deletions(-) diff --git a/SurveyFrontend/src/api/AuthApi.ts b/SurveyFrontend/src/api/AuthApi.ts index da61451..f549b25 100644 --- a/SurveyFrontend/src/api/AuthApi.ts +++ b/SurveyFrontend/src/api/AuthApi.ts @@ -11,7 +11,7 @@ interface IRegistrationData extends IAuthData{ lastName: string; } -export const getCurrentUser = async (user: IRegistrationData) => { +export const getCurrentUser = async () => { const token = localStorage.getItem("token"); if (!token) { @@ -23,12 +23,7 @@ export const getCurrentUser = async (user: IRegistrationData) => { ...createRequestConfig('GET'), headers: { 'Authorization': `Bearer ${token}` - }, - body: JSON.stringify({ - email: user.email, - firstName: user.firstName, - lastName: user.lastName, - }) + } }); console.log(response); diff --git a/SurveyFrontend/src/api/SurveyApi.ts b/SurveyFrontend/src/api/SurveyApi.ts index bec3f70..d182347 100644 --- a/SurveyFrontend/src/api/SurveyApi.ts +++ b/SurveyFrontend/src/api/SurveyApi.ts @@ -51,30 +51,6 @@ export const getAllSurveys = async (): Promise => { * postNewSurvey - добавление нового опроса * @param survey */ -// export const postNewSurvey = async (survey: INewSurvey): Promise => { -// const token = localStorage.getItem("token"); -// if (!token) { -// throw new Error("Токен отсутствует"); -// } -// -// try{ -// const response = await fetch(`${BASE_URL}/surveys`, { -// ...createRequestConfig('POST'), -// body: JSON.stringify(survey) -// }) -// -// // return await handleResponse(response); -// -// if (response.status === 200) { -// return await handleResponse(response); -// } -// throw new Error(`Ожидался код 200, получен ${response.status}`); -// } catch (error) { -// console.error(`Error when adding a new survey: ${error}`); -// throw error; -// } -// } - export const postNewSurvey = async (survey: INewSurvey): Promise => { const token = localStorage.getItem("token"); if (!token) { diff --git a/SurveyFrontend/src/components/AnswerOption/AnswerOption.tsx b/SurveyFrontend/src/components/AnswerOption/AnswerOption.tsx index 639d027..811d693 100644 --- a/SurveyFrontend/src/components/AnswerOption/AnswerOption.tsx +++ b/SurveyFrontend/src/components/AnswerOption/AnswerOption.tsx @@ -29,7 +29,6 @@ const AnswerOption: React.FC = ({index, value, onChange, onDe const handleTextareaChange = (event: React.ChangeEvent) => { setCurrentValue(event.target.value); - // Автоматическое изменение высоты if (textAreaRef.current) { textAreaRef.current.style.height = 'auto'; textAreaRef.current.style.height = `${textAreaRef.current.scrollHeight}px`; diff --git a/SurveyFrontend/src/components/MySurveyList/MySurveyList.tsx b/SurveyFrontend/src/components/MySurveyList/MySurveyList.tsx index 963092a..6fa3d1a 100644 --- a/SurveyFrontend/src/components/MySurveyList/MySurveyList.tsx +++ b/SurveyFrontend/src/components/MySurveyList/MySurveyList.tsx @@ -24,13 +24,6 @@ export const MySurveyList = () => { setSurveys(surveysWithStatus); } catch (error) { console.error('Ошибка при получении списка опросов:', error); - - // if (error instanceof Error && error.message.includes("401")) { - // // Если ошибка 401, перенаправляем на страницу входа - // navigate('/login'); - // } else { - // alert("Ошибка при загрузке опросов: " + (error instanceof Error && error.message)); - // } } }; fetchSurvey(); @@ -52,12 +45,6 @@ export const MySurveyList = () => { } } catch (error) { console.error('Ошибка при удалении опроса:', error); - - // if (error instanceof Error && error.message.includes("401")) { - // navigate('/login'); - // } else { - // alert("Ошибка при удалении опроса: " + (error instanceof Error ? error.message : 'Неизвестная ошибка')); - // } } }; diff --git a/SurveyFrontend/src/components/QuestionItem/QuestionItem.tsx b/SurveyFrontend/src/components/QuestionItem/QuestionItem.tsx index 6ac4221..50dc767 100644 --- a/SurveyFrontend/src/components/QuestionItem/QuestionItem.tsx +++ b/SurveyFrontend/src/components/QuestionItem/QuestionItem.tsx @@ -26,7 +26,8 @@ interface QuestionItemProps { const QuestionItem: React.FC = ({ questionId, - initialTextQuestion = `Вопрос ${questionId}`, + // initialTextQuestion = `Вопрос ${questionId}`, + initialTextQuestion = `Вопрос`, valueQuestion, answerVariants: initialAnswerVariants, onChangeQuestion, @@ -45,26 +46,24 @@ const QuestionItem: React.FC = ({ setTextQuestion(valueQuestion); }, [valueQuestion]); - // useEffect(() => { - // if (initialAnswerVariants.length === 0 && surveyId) { - // handleAddAnswer(); - // } - // }, [initialAnswerVariants.length, surveyId]); - const handleTypeChange = (type: 'single' | 'multiply') => { setSelectedType(type); }; const handleAddAnswer = async () => { - if (surveyId) { - try { - const newAnswer = await addNewAnswerVariant(surveyId, questionId, { text: '' }); - onAnswerVariantsChange([...initialAnswerVariants, { id: newAnswer.id, text: '' }]); - } catch (error) { - console.error('Ошибка при добавлении варианта ответа:', error); - } - } else { + if (!surveyId) { onAnswerVariantsChange([...initialAnswerVariants, { text: '' }]); + return; + } + + try { + const newAnswer = await addNewAnswerVariant(surveyId, questionId, { text: '' }); + onAnswerVariantsChange([...initialAnswerVariants, { + id: newAnswer.id, + text: newAnswer.text + }]); + } catch (error) { + console.error('Ошибка при добавлении варианта ответа:', error); } }; @@ -109,7 +108,6 @@ const QuestionItem: React.FC = ({ newAnswerVariants[index] = { ...newAnswerVariants[index], text: value }; onAnswerVariantsChange(newAnswerVariants); - // Обновляем на сервере только если вариант уже существует (имеет id) if (surveyId && newAnswerVariants[index].id) { try { await updateAnswerVariant( @@ -134,7 +132,6 @@ const QuestionItem: React.FC = ({ onAnswerVariantsChange(newAnswerVariants); setSelectedAnswers(selectedAnswers.filter((i) => i !== index)); - // Обновляем список после удаления if (surveyId) { const variants = await getAnswerVariants(surveyId, questionId); const answers = variants.map((v: { id: number, text: string }) => ({ id: v.id, text: v.text })); diff --git a/SurveyFrontend/src/components/QuestionsList/QuestionsList.tsx b/SurveyFrontend/src/components/QuestionsList/QuestionsList.tsx index 8a4afb4..24dcdb9 100644 --- a/SurveyFrontend/src/components/QuestionsList/QuestionsList.tsx +++ b/SurveyFrontend/src/components/QuestionsList/QuestionsList.tsx @@ -1,7 +1,8 @@ import React, {useState} from "react"; import QuestionItem from "../QuestionItem/QuestionItem.tsx"; import AddQuestionButton from "../AddQuestionButton/AddQuestionButton.tsx"; -import {deleteQuestion, getListQuestions} from "../../api/QuestionApi.ts"; +import {addNewQuestion, deleteQuestion, getListQuestions} from "../../api/QuestionApi.ts"; +import {addNewAnswerVariant} from "../../api/AnswerApi.ts"; interface QuestionsListProps { questions: Question[]; @@ -22,14 +23,38 @@ export interface Question { const QuestionsList: React.FC = ({questions, setQuestions, surveyId}) => { const [selectedType, setSelectedType] = useState<'single' | 'multiply'>('single'); - const handleAddQuestion = () => { - const newQuestion: Question = { - id: questions.length + 1, // ID >= 1001 — новые вопросы - text: '', - questionType: selectedType === 'single' ? 'singleanswerquestion' : 'multipleanswerquestion', - answerVariants: [{text: ''}], - }; - setQuestions([...questions, newQuestion]); + const handleAddQuestion = async () => { + if (!surveyId) { + const newQuestion: Question = { + id: questions.length + 1, + text: '', + questionType: selectedType === 'single' ? 'singleanswerquestion' : 'multipleanswerquestion', + answerVariants: [{ text: '' }], + }; + setQuestions([...questions, newQuestion]); + return; + } + + try { + const newQuestion = await addNewQuestion(surveyId, { + title: '', + questionType: selectedType === 'single' ? 'singleanswerquestion' : 'multipleanswerquestion' + }); + + const questionToAdd: Question = { + id: newQuestion.id, + text: newQuestion.title, + questionType: newQuestion.questionType as 'singleanswerquestion' | 'multipleanswerquestion', + answerVariants: [] + }; + + const newAnswer = await addNewAnswerVariant(surveyId, newQuestion.id, { text: '' }); + questionToAdd.answerVariants = [{ id: newAnswer.id, text: newAnswer.text }]; + + setQuestions([...questions, questionToAdd]); + } catch (error) { + console.error('Ошибка при добавлении вопроса:', error); + } }; const handleQuestionChange = (id: number, value: string) => { diff --git a/SurveyFrontend/src/components/RegisterForm/RegisterForm.module.css b/SurveyFrontend/src/components/RegisterForm/RegisterForm.module.css index 642ea69..cac537d 100644 --- a/SurveyFrontend/src/components/RegisterForm/RegisterForm.module.css +++ b/SurveyFrontend/src/components/RegisterForm/RegisterForm.module.css @@ -48,14 +48,13 @@ opacity: 0; } -/* Отключаем стиль для input, когда в нём есть данные */ .input:not(:placeholder-shown) { color: black; opacity: 1; } .input:focus { - border-bottom: 2px solid black; /* Чёрная граница при фокусе */ + border-bottom: 2px solid black; } .signUp{ diff --git a/SurveyFrontend/src/components/Survey/Survey.tsx b/SurveyFrontend/src/components/Survey/Survey.tsx index f9fe704..b0f5448 100644 --- a/SurveyFrontend/src/components/Survey/Survey.tsx +++ b/SurveyFrontend/src/components/Survey/Survey.tsx @@ -25,7 +25,6 @@ const Survey: React.FC = () => { description: descriptionSurvey }); - // Сначала создаем все вопросы const updatedQuestions: Question[] = []; for (const question of questions) { const newQuestion = await addNewQuestion(savedSurvey.id, { @@ -33,14 +32,12 @@ const Survey: React.FC = () => { questionType: question.questionType }); - // Создаем копию вопроса с новым ID const updatedQuestion: Question = { ...question, id: newQuestion.id, answerVariants: [] }; - // Затем создаем варианты ответов для каждого вопроса if (question.answerVariants && question.answerVariants.length > 0) { const newVariants = await Promise.all( question.answerVariants.map(answer => @@ -52,7 +49,6 @@ const Survey: React.FC = () => { ) ); - // Обновляем варианты ответов с их ID updatedQuestion.answerVariants = newVariants.map((variant: { id: number, text: string }) => ({ id: variant.id, text: variant.text @@ -62,7 +58,6 @@ const Survey: React.FC = () => { updatedQuestions.push(updatedQuestion); } - // Обновляем состояние с новыми ID setQuestions(updatedQuestions); navigate('/my-surveys'); } catch (error) { diff --git a/SurveyFrontend/src/components/SurveyPage/SurveyPage.tsx b/SurveyFrontend/src/components/SurveyPage/SurveyPage.tsx index ce5a462..e6e4655 100644 --- a/SurveyFrontend/src/components/SurveyPage/SurveyPage.tsx +++ b/SurveyFrontend/src/components/SurveyPage/SurveyPage.tsx @@ -8,7 +8,6 @@ import styles from "./SurveyPage.module.css"; import SaveButton from "../SaveButton/SaveButton.tsx"; import { addNewAnswerVariant, deleteAnswerVariant, getAnswerVariants, IAnswerVariant, updateAnswerVariant } from "../../api/AnswerApi.ts"; -// Типы для действий type ActionType = | 'update-survey' | 'create-question' @@ -18,7 +17,6 @@ type ActionType = | 'update-answer' | 'delete-answer'; -// Интерфейсы для данных действий interface SurveyActionData { id: number; title: string; @@ -54,16 +52,6 @@ class ActionQueue { } async execute() { - console.log(`Выполнение очереди с ${this.actions.length} действиями`); - for (const [index, action] of this.actions.entries()) { - console.log(`Обработка действия ${index + 1}/${this.actions.length}:`, action); - try { - // ... существующий код - } catch (error) { - console.error(`Ошибка в действии ${index + 1}:`, error); - throw error; - } - } for (const action of this.actions) { try { switch (action.type) { @@ -147,21 +135,13 @@ class ActionQueue { } private async handleUpdateAnswer(data: AnswerActionData & { id: number }) { - console.log('1. Начало handleUpdateAnswer', data); try { - console.log('2. Перед вызовом updateAnswerVariant', { - surveyId: data.surveyId, - questionId: data.questionId, - id: data.id, - text: data.text - }); const result = await updateAnswerVariant(data.surveyId, data.questionId, data.id, { text: data.text }); - console.log('3. После вызова updateAnswerVariant', result); return result; } catch (error) { - console.error('4. Ошибка в handleUpdateAnswer:', error); + console.error(error); throw error; } @@ -228,86 +208,62 @@ export const SurveyPage: React.FC = () => { }, [surveyId]); const handleSave = async () => { - console.log('0. Начало handleSave'); - if (!surveyId || !survey) { - console.log('0.1. Прерывание - нет surveyId или survey', { surveyId, survey }); - return; - } + if (!surveyId || !survey) return; try { setError(null); const id = parseInt(surveyId); const actionQueue = new ActionQueue(); - // 1. Обновление опроса actionQueue.add({ type: 'update-survey', data: { id, title, description } as SurveyActionData }); - // 2. Получаем текущие вопросы с сервера const serverQuestions = await getListQuestions(id); - // 3. Обработка вопросов questions.forEach(question => { - const isNewQuestion = !serverQuestions.some(q => q.id === question.id); - - if (isNewQuestion) { + const serverQuestion = serverQuestions.find(q => q.id === question.id); + if (serverQuestion && + (serverQuestion.title !== question.text || + serverQuestion.questionType !== question.questionType)) { actionQueue.add({ - type: 'create-question', + type: 'update-question', data: { surveyId: id, + id: question.id, title: question.text, questionType: question.questionType - } as QuestionActionData, - tempId: question.id - }); - } else { - // Обновляем только если текст изменился - const serverQuestion = serverQuestions.find(q => q.id === question.id); - if (serverQuestion && (serverQuestion.title !== question.text || serverQuestion.questionType !== question.questionType)) { - actionQueue.add({ - type: 'update-question', - data: { - surveyId: id, - id: question.id, - title: question.text, - questionType: question.questionType - } as QuestionActionData & { id: number } - }); - } - } - - // 4. Обработка вариантов ответов - if (question.answerVariants) { - question.answerVariants.forEach(answer => { - if (isNewQuestion || !answer.id) { - actionQueue.add({ - type: 'create-answer', - data: { - surveyId: id, - questionId: question.id, - text: answer.text - } as AnswerActionData, - tempId: question.id - }); - } else { - // Обновляем только если текст изменился - actionQueue.add({ - type: 'update-answer', - data: { - surveyId: id, - questionId: question.id, - id: answer.id, - text: answer.text - } as AnswerActionData & { id: number } - }); - } + } as QuestionActionData & { id: number } }); } }); - // 5. Удаление удаленных вопросов + questions.forEach(question => { + question.answerVariants.forEach(answer => { + if (!answer.id) { + actionQueue.add({ + type: 'create-answer', + data: { + surveyId: id, + questionId: question.id, + text: answer.text + } as AnswerActionData + }); + } else { + actionQueue.add({ + type: 'update-answer', + data: { + surveyId: id, + questionId: question.id, + id: answer.id, + text: answer.text + } as AnswerActionData & { id: number } + }); + } + }); + }); + serverQuestions.forEach(serverQuestion => { if (!questions.some(q => q.id === serverQuestion.id)) { actionQueue.add({ @@ -320,10 +276,8 @@ export const SurveyPage: React.FC = () => { } }); - // Выполняем все действия await actionQueue.execute(); - // Обновляем данные const updatedQuestions = await getListQuestions(id); const formattedQuestions = await Promise.all(updatedQuestions.map(async q => { const answerVariants = await getAnswerVariants(id, q.id); diff --git a/SurveyFrontend/src/components/TimeEvent/TimeEvent.module.css b/SurveyFrontend/src/components/TimeEvent/TimeEvent.module.css index 4417f66..0809dc9 100644 --- a/SurveyFrontend/src/components/TimeEvent/TimeEvent.module.css +++ b/SurveyFrontend/src/components/TimeEvent/TimeEvent.module.css @@ -23,7 +23,7 @@ .inputDate{ border: 3px solid #007AFF26; padding: 12px 107px 12px 21px; - font-size: 20px; /*??????????????????????? в макете указано bodyLarge/Size*/ + font-size: 20px; font-weight: 400; border-radius: 3px; } @@ -31,7 +31,7 @@ .inputTime{ border: 3px solid #007AFF26; padding: 12px 42px; - font-size: 20px; /*??????????????????????? в макете указано bodyLarge/Size*/ + font-size: 20px; font-weight: 400; border-radius: 3px; }