примерно раскиданная логика резултов

This commit is contained in:
Nastya 2023-12-21 11:29:51 +03:00
parent 25bdf1ba87
commit c382f6b7ab
14 changed files with 151 additions and 200 deletions

@ -12,6 +12,7 @@ export const QUIZ_QUESTION_RESULT: Omit<QuizQuestionResult, "id" | "backendId">
innerName: "", innerName: "",
text: "", text: "",
price: [0], price: [0],
useImage: true useImage: true,
usage: true
}, },
}; };

@ -18,5 +18,6 @@ export interface QuizQuestionResult extends QuizQuestionBase {
rule: QuestionBranchingRule, rule: QuestionBranchingRule,
hint: QuestionHint; hint: QuestionHint;
autofill: boolean; autofill: boolean;
usage: boolean
}; };
} }

@ -16,7 +16,7 @@ import {
updateQuestion, updateQuestion,
getQuestionByContentId, getQuestionByContentId,
clearRuleForAll, clearRuleForAll,
createFrontResult, createResult,
} from "@root/questions/actions"; } from "@root/questions/actions";
import { import {
updateModalInfoWhyCantCreate, updateModalInfoWhyCantCreate,
@ -130,7 +130,7 @@ function CsComponent({
if (Object.keys(targetQuestion).length !== 0 && parentNodeContentId && parentNodeChildren !== undefined) { if (Object.keys(targetQuestion).length !== 0 && parentNodeContentId && parentNodeChildren !== undefined) {
clearDataAfterAddNode({ parentNodeContentId, targetQuestion, parentNodeChildren }) clearDataAfterAddNode({ parentNodeContentId, targetQuestion, parentNodeChildren })
cy?.data('changed', true) cy?.data('changed', true)
createFrontResult(quiz?.backendId, targetQuestion.content.id) createResult(quiz?.backendId, targetQuestion.content.id)
const es = cy?.add([ const es = cy?.add([
{ {
data: { data: {
@ -157,10 +157,10 @@ function CsComponent({
const parentQuestion = { ...getQuestionByContentId(parentNodeContentId) } as AnyTypedQuizQuestion const parentQuestion = { ...getQuestionByContentId(parentNodeContentId) } as AnyTypedQuizQuestion
//смотрим не добавлен ли родителю result. Если да - убираем его. Веточкам result не нужен //смотрим не добавлен ли родителю result. Если да - делаем его неактивным. Веточкам result не нужен
trashQuestions.forEach((targetQuestion) => { trashQuestions.forEach((targetQuestion) => {
if (targetQuestion.type === "result" && targetQuestion.content.rule.parentId === parentQuestion.content.id) { if (targetQuestion.type === "result" && targetQuestion.content.rule.parentId === parentQuestion.content.id) {
deleteQuestion(targetQuestion.id); updateQuestion(targetQuestion.id, (q) => q.content.usage = false);
} }
}) })

@ -1,6 +1,6 @@
import { Box } from "@mui/material" import { Box } from "@mui/material"
import { useEffect, useRef, useLayoutEffect } from "react"; import { useEffect, useRef, useLayoutEffect } from "react";
import { deleteQuestion, clearRuleForAll, updateQuestion } from "@root/questions/actions" import { deleteQuestion, clearRuleForAll, updateQuestion, createResult } from "@root/questions/actions"
import { updateOpenedModalSettingsId } from "@root/uiTools/actions" import { updateOpenedModalSettingsId } from "@root/uiTools/actions"
import { updateRootContentId } from "@root/quizes/actions" import { updateRootContentId } from "@root/quizes/actions"
import { useCurrentQuiz } from "@root/quizes/hooks" import { useCurrentQuiz } from "@root/quizes/hooks"
@ -34,11 +34,7 @@ export const FirstNodeField = ({ setOpenedModalQuestions, modalQuestionTargetCon
if (dragQuestionContentId) { if (dragQuestionContentId) {
updateRootContentId(quiz?.id, dragQuestionContentId) updateRootContentId(quiz?.id, dragQuestionContentId)
updateQuestion(dragQuestionContentId, (question) => question.content.rule.parentId = "root") updateQuestion(dragQuestionContentId, (question) => question.content.rule.parentId = "root")
//если были результаты - удалить createResult(quiz?.backendId, dragQuestionContentId)
questions.forEach((q) => {
if (q.type === 'result') deleteQuestion(q.id)
})
} }
} else { } else {
enqueueSnackbar("Нет информации о взятом опроснике") enqueueSnackbar("Нет информации о взятом опроснике")
@ -61,10 +57,7 @@ export const FirstNodeField = ({ setOpenedModalQuestions, modalQuestionTargetCon
if (modalQuestionTargetContentId) { if (modalQuestionTargetContentId) {
updateRootContentId(quiz?.id, modalQuestionTargetContentId) updateRootContentId(quiz?.id, modalQuestionTargetContentId)
updateQuestion(modalQuestionTargetContentId, (question) => question.content.rule.parentId = "root") updateQuestion(modalQuestionTargetContentId, (question) => question.content.rule.parentId = "root")
//если были результаты - удалить createResult(quiz?.backendId, modalQuestionTargetContentId)
questions.forEach((q) => {
if (q.type === 'result') deleteQuestion(q.id)
})
} }
} else { } else {
enqueueSnackbar("Нет информации о взятом опроснике") enqueueSnackbar("Нет информации о взятом опроснике")

@ -3,7 +3,6 @@ import {
updateQuestion, updateQuestion,
getQuestionByContentId, getQuestionByContentId,
clearRuleForAll, clearRuleForAll,
createFrontResult,
} from "@root/questions/actions"; } from "@root/questions/actions";
import { useQuestionsStore } from "@root/questions/store"; import { useQuestionsStore } from "@root/questions/store";
import { useCurrentQuiz } from "@root/quizes/hooks"; import { useCurrentQuiz } from "@root/quizes/hooks";
@ -143,11 +142,6 @@ export const useRemoveNode = ({
question.content.rule.children = []; question.content.rule.children = [];
question.content.rule.default = ""; question.content.rule.default = "";
}); });
trashQuestions.forEach((q) => {
if (q.type === "result") {
deleteQuestion(q.id);
}
});
clearRuleForAll(); clearRuleForAll();
} else { } else {
const parentQuestionContentId = cy const parentQuestionContentId = cy
@ -159,7 +153,7 @@ export const useRemoveNode = ({
quiz && quiz &&
cy?.edges(`[source="${parentQuestionContentId}"]`).length === 0 cy?.edges(`[source="${parentQuestionContentId}"]`).length === 0
) { ) {
createFrontResult(quiz.backendId, parentQuestionContentId); //createFrontResult(quiz.backendId, parentQuestionContentId);
} }
clearDataAfterRemoveNode({ clearDataAfterRemoveNode({
targetQuestionContentId: targetNodeContentId, targetQuestionContentId: targetNodeContentId,

@ -57,11 +57,6 @@ export default function ButtonsOptions({
if (question.content.rule.parentId === "root") { //удалить из стора root и очистить rule всем вопросам if (question.content.rule.parentId === "root") { //удалить из стора root и очистить rule всем вопросам
updateRootContentId(quiz.id, ""); updateRootContentId(quiz.id, "");
clearRuleForAll(); clearRuleForAll();
questions.forEach(q => {
if (q.type === "result") {
deleteQuestion(q.id);
}
});
deleteQuestion(question.id); deleteQuestion(question.id);
} else if (question.content.rule.parentId.length > 0) { //удалить из стора вопрос из дерева и очистить его потомков } else if (question.content.rule.parentId.length > 0) { //удалить из стора вопрос из дерева и очистить его потомков
const clearQuestions = [] as string[]; const clearQuestions = [] as string[];
@ -69,10 +64,8 @@ export default function ButtonsOptions({
//записываем потомков , а их результаты удаляем //записываем потомков , а их результаты удаляем
const getChildren = (parentQuestion: AnyTypedQuizQuestion) => { const getChildren = (parentQuestion: AnyTypedQuizQuestion) => {
questions.forEach((targetQuestion) => { questions.forEach((targetQuestion) => {
if (targetQuestion.content.rule.parentId === parentQuestion.content.id) {//если у вопроса совпал родитель с родителем => он потомок, в кучу его if (targetQuestion.type !== null && targetQuestion.content.rule.parentId === parentQuestion.content.id) {//если у вопроса совпал родитель с родителем => он потомок, в кучу его
if (targetQuestion.type === "result") { if (targetQuestion.type !== "result" && targetQuestion.type !== null) {
deleteQuestion(targetQuestion.id);
} else {
if (!clearQuestions.includes(targetQuestion.content.id)) clearQuestions.push(targetQuestion.content.id); if (!clearQuestions.includes(targetQuestion.content.id)) clearQuestions.push(targetQuestion.content.id);
getChildren(targetQuestion); //и ищем его потомков getChildren(targetQuestion); //и ищем его потомков
} }

@ -58,11 +58,6 @@ export default function ButtonsOptionsAndPict({
if (question.content.rule.parentId === "root") { //удалить из стора root и очистить rule всем вопросам if (question.content.rule.parentId === "root") { //удалить из стора root и очистить rule всем вопросам
updateRootContentId(quiz.id, ""); updateRootContentId(quiz.id, "");
clearRuleForAll(); clearRuleForAll();
questions.forEach(q => {
if (q.type === "result") {
deleteQuestion(q.id);
}
});
deleteQuestion(question.id); deleteQuestion(question.id);
} else if (question.content.rule.parentId.length > 0) { //удалить из стора вопрос из дерева и очистить его потомков } else if (question.content.rule.parentId.length > 0) { //удалить из стора вопрос из дерева и очистить его потомков
const clearQuestions = [] as string[]; const clearQuestions = [] as string[];
@ -71,9 +66,7 @@ export default function ButtonsOptionsAndPict({
const getChildren = (parentQuestion: AnyTypedQuizQuestion) => { const getChildren = (parentQuestion: AnyTypedQuizQuestion) => {
questions.forEach((targetQuestion) => { questions.forEach((targetQuestion) => {
if (targetQuestion.content.rule.parentId === parentQuestion.content.id) {//если у вопроса совпал родитель с родителем => он потомок, в кучу его if (targetQuestion.content.rule.parentId === parentQuestion.content.id) {//если у вопроса совпал родитель с родителем => он потомок, в кучу его
if (targetQuestion.type === "result") { if (targetQuestion.type !== null && targetQuestion.type !== "result") {
deleteQuestion(targetQuestion.id);
} else {
if (!clearQuestions.includes(targetQuestion.content.id)) clearQuestions.push(targetQuestion.content.id); if (!clearQuestions.includes(targetQuestion.content.id)) clearQuestions.push(targetQuestion.content.id);
getChildren(targetQuestion); //и ищем его потомков getChildren(targetQuestion); //и ищем его потомков
} }

@ -93,21 +93,14 @@ const maxLengthTextField = 225;
updateRootContentId(quiz.id, ""); updateRootContentId(quiz.id, "");
clearRuleForAll(); clearRuleForAll();
deleteQuestion(question.id); deleteQuestion(question.id);
questions.forEach(q => {
if (q.type === "result") {
deleteQuestion(q.id);
}
});
} else if (question.content.rule.parentId.length > 0) { //удалить из стора вопрос из дерева и очистить его потомков } else if (question.content.rule.parentId.length > 0) { //удалить из стора вопрос из дерева и очистить его потомков
const clearQuestions = [] as string[]; const clearQuestions = [] as string[];
//записываем потомков , а их результаты удаляем //записываем потомков , а их результаты удаляем
const getChildren = (parentQuestion: AnyTypedQuizQuestion) => { const getChildren = (parentQuestion: AnyTypedQuizQuestion) => {
questions.forEach((targetQuestion) => { questions.forEach((targetQuestion) => {
if (targetQuestion.content.rule.parentId === parentQuestion.content.id) {//если у вопроса совпал родитель с родителем => он потомок, в кучу его if (targetQuestion.type !== null && targetQuestion.content.rule.parentId === parentQuestion.content.id) {//если у вопроса совпал родитель с родителем => он потомок, в кучу его
if (targetQuestion.type === "result") { if (targetQuestion.type !== null && targetQuestion.type !== "result") {
deleteQuestion(targetQuestion.id);
} else {
if (!clearQuestions.includes(targetQuestion.content.id)) clearQuestions.push(targetQuestion.content.id); if (!clearQuestions.includes(targetQuestion.content.id)) clearQuestions.push(targetQuestion.content.id);
getChildren(targetQuestion); //и ищем его потомков getChildren(targetQuestion); //и ищем его потомков
} }

@ -1,38 +1,10 @@
import { ResultSettings } from "./ResultSettings";
import { createFrontResult } from "@root/questions/actions";
import { useQuestionsStore } from "@root/questions/store";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { Box, Typography, useTheme, useMediaQuery, Button } from "@mui/material"; import { Box, Typography, useTheme, useMediaQuery, Button } from "@mui/material";
import image from "../../assets/Rectangle 110.png"; import image from "../../assets/Rectangle 110.png";
import { enqueueSnackbar } from "notistack";
import { AnyTypedQuizQuestion } from "@model/questionTypes/shared";
import ArrowLeft from "../../assets/icons/questionsPage/arrowLeft";
import { decrementCurrentStep } from "@root/quizes/actions";
export const FirstEntry = () => { export const FirstEntry = () => {
const theme = useTheme(); const theme = useTheme();
const quiz = useCurrentQuiz();
const { questions } = useQuestionsStore();
const isSmallMonitor = useMediaQuery(theme.breakpoints.down(1250)); const isSmallMonitor = useMediaQuery(theme.breakpoints.down(1250));
const create = () => {
if (quiz?.config.haveRoot) {
questions
.filter((question: AnyTypedQuizQuestion) => {
return (
question.type !== null &&
question.content.rule.parentId.length !== 0 &&
question.content.rule.children.length === 0
);
})
.forEach((question) => {
createFrontResult(quiz.backendId, question.content.id);
});
} else {
createFrontResult(quiz.backendId, "line");
}
};
return ( return (
<> <>
<Box <Box
@ -99,35 +71,6 @@ export const FirstEntry = () => {
}} }}
/> />
</Box> </Box>
<Box sx={{ display: "flex", justifyContent: "flex-start", alignItems: "center", gap: "8px", mt: "30px" }}>
<Button
variant="outlined"
sx={{
padding: "10px 20px",
borderRadius: "8px",
height: "44px",
}}
onClick={decrementCurrentStep}
>
<ArrowLeft />
</Button>
<Button
onClick={create}
variant="contained"
sx={{
backgroundColor: "#7E2AEA",
fontSize: "18px",
lineHeight: "18px",
width: "216px",
height: "44px",
p: "10px 20px",
}}
>
Создать результаты
</Button>
</Box>
</> </>
); );
}; };

@ -1,15 +1,27 @@
import { useQuestionsStore } from "@root/questions/store";
import { FirstEntry } from "./FirstEntry" import { FirstEntry } from "./FirstEntry"
import { ResultSettings } from "./ResultSettings" import { ResultSettings } from "./ResultSettings"
import { decrementCurrentStep } from "@root/quizes/actions";
import { Box, Button } from "@mui/material";
import ArrowLeft from "@icons/questionsPage/arrowLeft"
export const ResultPage = () => { export const ResultPage = () => {
const { questions } = useQuestionsStore();
//ищём хотя бы один result
const haveResult = questions.some((question) => question.type === "result")
return ( return (
haveResult ? <>
<ResultSettings />
:
<FirstEntry /> <FirstEntry />
); <ResultSettings />
<Box sx={{ display: "flex", justifyContent: "flex-start", alignItems: "center", gap: "8px", mt: "30px" }}>
<Button
variant="outlined"
sx={{
padding: "10px 20px",
borderRadius: "8px",
height: "44px",
}}
onClick={decrementCurrentStep}
>
<ArrowLeft />
</Button>
</Box>
</>
)
} }

@ -14,7 +14,7 @@ import { ResultCard, checkEmptyData } from "./cards/ResultCard";
import { EmailSettingsCard } from "./cards/EmailSettingsCard"; import { EmailSettingsCard } from "./cards/EmailSettingsCard";
import { useCurrentQuiz } from "@root/quizes/hooks"; import { useCurrentQuiz } from "@root/quizes/hooks";
import { useQuestionsStore } from "@root/questions/store"; import { useQuestionsStore } from "@root/questions/store";
import { createFrontResult, deleteQuestion } from "@root/questions/actions"; import { deleteQuestion } from "@root/questions/actions";
import { QuizQuestionResult } from "@model/questionTypes/result"; import { QuizQuestionResult } from "@model/questionTypes/result";
export const ResultSettings = () => { export const ResultSettings = () => {
@ -25,6 +25,8 @@ export const ResultSettings = () => {
const [resultContract, setResultContract] = useState(true); const [resultContract, setResultContract] = useState(true);
const isReadyToLeaveRef = useRef(true); const isReadyToLeaveRef = useRef(true);
console.log(quiz)
console.log(results)
useEffect( useEffect(
function calcIsReadyToLeave() { function calcIsReadyToLeave() {
let isReadyToLeave = true; let isReadyToLeave = true;

@ -32,7 +32,7 @@ import { Link, useNavigate } from "react-router-dom";
import useSWR from "swr"; import useSWR from "swr";
import { useDebouncedCallback } from "use-debounce"; import { useDebouncedCallback } from "use-debounce";
import { SidebarMobile } from "./Sidebar/SidebarMobile"; import { SidebarMobile } from "./Sidebar/SidebarMobile";
import { cleanQuestions, setQuestions } from "@root/questions/actions"; import { cleanQuestions, createResult, setQuestions } from "@root/questions/actions";
import { updateOpenBranchingPanel, updateCanCreatePublic, updateModalInfoWhyCantCreate } from "@root/uiTools/actions"; import { updateOpenBranchingPanel, updateCanCreatePublic, updateModalInfoWhyCantCreate } from "@root/uiTools/actions";
import { BranchingPanel } from "../Questions/BranchingPanel"; import { BranchingPanel } from "../Questions/BranchingPanel";
import { useQuestionsStore } from "@root/questions/store"; import { useQuestionsStore } from "@root/questions/store";
@ -59,10 +59,14 @@ export default function EditPage() {
const questions = await questionApi.getList({ quiz_id: editQuizId }); const questions = await questionApi.getList({ quiz_id: editQuizId });
setQuestions(questions); setQuestions(questions);
if (questions === null || !questions.find(q => q.type !== null && q.content?.rule.parentId === "line")) createResult(quiz?.backendId, "line")
}; };
getData(); getData();
}, []); }, []);
console.log(quiz)
console.log(questions)
const { openBranchingPanel, whyCantCreatePublic, canCreatePublic } = useUiTools(); const { openBranchingPanel, whyCantCreatePublic, canCreatePublic } = useUiTools();
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
@ -78,10 +82,12 @@ export default function EditPage() {
}, [navigate, editQuizId]); }, [navigate, editQuizId]);
useEffect( useEffect(
() => () => { () => {
resetEditConfig(); return () => {
cleanQuestions(); resetEditConfig();
updateModalInfoWhyCantCreate(false) cleanQuestions();
updateModalInfoWhyCantCreate(false)
}
}, },
[] []
); );
@ -123,7 +129,7 @@ export default function EditPage() {
useEffect(() => { useEffect(() => {
updateQuestionHint(questions) updateQuestionHint(questions)
}, [questions]); }, [questions]);
async function handleLogoutClick() { async function handleLogoutClick() {
const [, logoutError] = await logout(); const [, logoutError] = await logout();
@ -376,11 +382,11 @@ export default function EditPage() {
height: "34px", height: "34px",
minWidth: "130px", minWidth: "130px",
}} }}
onClick={() => Object.keys(whyCantCreatePublic).length === 0 ? () => {} : updateModalInfoWhyCantCreate(true)} onClick={() => Object.keys(whyCantCreatePublic).length === 0 ? () => { } : updateModalInfoWhyCantCreate(true)}
> >
Тестовый просмотр Тестовый просмотр
</Button> </Button>
: :
<a href={`/view`} target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}> <a href={`/view`} target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}>
<Button <Button
variant="contained" variant="contained"
@ -411,22 +417,22 @@ export default function EditPage() {
() => updateQuiz(quiz?.id, (state) => { () => updateQuiz(quiz?.id, (state) => {
state.status = quiz?.status === "start" ? "stop" : "start"; state.status = quiz?.status === "start" ? "stop" : "start";
}) })
: :
() => updateModalInfoWhyCantCreate(true) () => updateModalInfoWhyCantCreate(true)
} }
> >
{quiz?.status === "start" ? "Стоп" : "Старт"} {quiz?.status === "start" ? "Стоп" : "Старт"}
</Button> </Button>
{quiz?.status === "start" && <Box {quiz?.status === "start" && <Box
component={Link} component={Link}
sx={{ sx={{
color: "#7e2aea", color: "#7e2aea",
fontSize: "14px" fontSize: "14px"
}} }}
target="_blank" to={"https://hbpn.link/" + quiz.qid}>https://hbpn.link/{quiz.qid} target="_blank" to={"https://hbpn.link/" + quiz.qid}>https://hbpn.link/{quiz.qid}
</Box>} </Box>}
</Box> </Box>
</Box > </Box >
<ModalInfoWhyCantCreate /> <ModalInfoWhyCantCreate />
</> </>
); );

@ -15,6 +15,7 @@ import { useCurrentQuiz } from "@root/quizes/hooks";
import { QuestionsStore, useQuestionsStore } from "./store"; import { QuestionsStore, useQuestionsStore } from "./store";
import { useUiTools } from "../uiTools/store"; import { useUiTools } from "../uiTools/store";
import { withErrorBoundary } from "react-error-boundary"; import { withErrorBoundary } from "react-error-boundary";
import { QuizQuestionResult } from "@model/questionTypes/result";
export const setQuestions = (questions: RawQuestion[] | null) => setProducedState(state => { export const setQuestions = (questions: RawQuestion[] | null) => setProducedState(state => {
@ -481,7 +482,12 @@ export const getQuestionByContentId = (questionContentId: string | null) => {
export const clearRuleForAll = () => { export const clearRuleForAll = () => {
const { questions } = useQuestionsStore.getState(); const { questions } = useQuestionsStore.getState();
questions.forEach(question => { questions.forEach(question => {
if (question.type !== null && (question.content.rule.main.length > 0 || question.content.rule.default.length > 0 || question.content.rule.parentId.length > 0)) { if (question.type !== null &&
(question.content.rule.main.length > 0
|| question.content.rule.default.length > 0
|| question.content.rule.parentId.length > 0)
&& question.type !== "result") {
updateQuestion(question.content.id, question => { updateQuestion(question.content.id, question => {
question.content.rule.parentId = ""; question.content.rule.parentId = "";
question.content.rule.main = []; question.content.rule.main = [];
@ -491,63 +497,48 @@ export const clearRuleForAll = () => {
}); });
}; };
export const createResult = async (
export const createFrontResult = (quizId: number, parentContentId?: string) => setProducedState(state => { quizId: number,
const frontId = nanoid(); parentContentId?: string
const content = JSON.parse(JSON.stringify(defaultQuestionByType["result"].content));
content.id = frontId;
if (parentContentId) content.rule.parentId = parentContentId;
state.questions.push({
id: frontId,
quizId,
type: "result",
title: "",
description: "",
deleted: false,
expanded: true,
page: 101,
required: true,
content
});
}, {
type: "createFrontResult",
quizId,
});
export const createBackResult = async (
questionId: string,
type: QuestionType,
) => requestQueue.enqueue(async () => { ) => requestQueue.enqueue(async () => {
const question = useQuestionsStore.getState().questions.find(q => q.id === questionId); if (!quizId || !parentContentId) {
if (!question) return; console.error("Нет данных для создания результата. quizId: ", quizId, ", quizId: ", parentContentId)
if (question.type !== "result") throw new Error("Cannot upgrade already typed question");
try {
const createdQuestion = await questionApi.create({
quiz_id: question.quizId,
type,
title: question.title,
description: question.description,
page: 0,
required: true,
content: JSON.stringify(defaultQuestionByType[type].content),
});
setProducedState(state => {
const questionIndex = state.questions.findIndex(q => q.id === questionId);
if (questionIndex !== -1) state.questions.splice(
questionIndex,
1,
rawQuestionToQuestion(createdQuestion)
);
}, {
type: "createBackResult",
question,
});
} catch (error) {
devlog("Error creating question", error);
enqueueSnackbar("Не удалось создать вопрос");
} }
//Мы получили запрос на создание резулта. Анализируем существует ли такой. Если да - просто делаем его активным
const question = useQuestionsStore.getState().questions.find(q=> q.type !== null && q?.content.rule.parentContentId === parentContentId)
if (question) {//существует, делаем активным
updateQuestion(question.id, (q) => {
q.content.usage = true
})
} else {//не существует, создаём
const content = JSON.parse(JSON.stringify(defaultQuestionByType["result"].content));
content.rule.parentId = parentContentId;
try {
const createdQuestion:RawQuestion = await questionApi.create({
quiz_id: quizId,
type: "result",
title: "",
description: "",
page: 101,
required: true,
content: JSON.stringify(content),
});
setProducedState(state => {
state.questions.push(rawQuestionToQuestion(createdQuestion))
}, {
type: "createBackResult",
createdQuestion,
});
} catch (error) {
devlog("Error creating question", error);
enqueueSnackbar("Не удалось создать вопрос");
}
}
}); });

@ -9,8 +9,9 @@ import { NavigateFunction } from "react-router-dom";
import { isAxiosCanceledError } from "../../utils/isAxiosCanceledError"; import { isAxiosCanceledError } from "../../utils/isAxiosCanceledError";
import { RequestQueue } from "../../utils/requestQueue"; import { RequestQueue } from "../../utils/requestQueue";
import { QuizStore, useQuizStore } from "./store"; import { QuizStore, useQuizStore } from "./store";
import { createUntypedQuestion } from "@root/questions/actions"; import { createUntypedQuestion, updateQuestion } from "@root/questions/actions";
import { useCurrentQuiz } from "./hooks" import { useCurrentQuiz } from "./hooks"
import { useQuestionsStore } from "@root/questions/store";
export const setEditQuizId = (quizId: number | null) => setProducedState(state => { export const setEditQuizId = (quizId: number | null) => setProducedState(state => {
@ -176,12 +177,40 @@ export const deleteQuiz = async (quizId: string) => requestQueue.enqueue(async (
enqueueSnackbar(`Не удалось удалить квиз. ${message}`); enqueueSnackbar(`Не удалось удалить квиз. ${message}`);
} }
}); });
export const updateRootContentId = (quizId: string, id:string) => updateQuiz( export const updateRootContentId = (quizId: string, id: string) => {
quizId,
quiz => { if (id.length === 0) {//дерева больше не существует, все результаты неактивны кроме результата линейности
quiz.config.haveRoot = id useQuestionsStore.getState().questions.forEach((q) => {
}, if (q.type !== null && q.type === "result") {
); if (q.content.rule.parentId === "line" && q.content.usage === false) {
updateQuestion(q.id, (q) => {
q.content.usage === true
})
} else {
updateQuestion(q.id, (q) => {
q.content.usage === false
})
}
}
})
} else { //было создано дерево, результат линейности неактивен
useQuestionsStore.getState().questions.forEach((q) => {
if (q.type !== null && q.content.rule.parentId === "line") {
updateQuestion(q.id, (q) => {
q.content.usage === false
})
}
})
}
updateQuiz(
quizId,
quiz => {
quiz.config.haveRoot = id
},
);
}
// TODO copy quiz // TODO copy quiz