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

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: "",
text: "",
price: [0],
useImage: true
useImage: true,
usage: true
},
};

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

@ -16,7 +16,7 @@ import {
updateQuestion,
getQuestionByContentId,
clearRuleForAll,
createFrontResult,
createResult,
} from "@root/questions/actions";
import {
updateModalInfoWhyCantCreate,
@ -130,7 +130,7 @@ function CsComponent({
if (Object.keys(targetQuestion).length !== 0 && parentNodeContentId && parentNodeChildren !== undefined) {
clearDataAfterAddNode({ parentNodeContentId, targetQuestion, parentNodeChildren })
cy?.data('changed', true)
createFrontResult(quiz?.backendId, targetQuestion.content.id)
createResult(quiz?.backendId, targetQuestion.content.id)
const es = cy?.add([
{
data: {
@ -157,10 +157,10 @@ function CsComponent({
const parentQuestion = { ...getQuestionByContentId(parentNodeContentId) } as AnyTypedQuizQuestion
//смотрим не добавлен ли родителю result. Если да - убираем его. Веточкам result не нужен
//смотрим не добавлен ли родителю result. Если да - делаем его неактивным. Веточкам result не нужен
trashQuestions.forEach((targetQuestion) => {
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 { 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 { updateRootContentId } from "@root/quizes/actions"
import { useCurrentQuiz } from "@root/quizes/hooks"
@ -34,11 +34,7 @@ export const FirstNodeField = ({ setOpenedModalQuestions, modalQuestionTargetCon
if (dragQuestionContentId) {
updateRootContentId(quiz?.id, dragQuestionContentId)
updateQuestion(dragQuestionContentId, (question) => question.content.rule.parentId = "root")
//если были результаты - удалить
questions.forEach((q) => {
if (q.type === 'result') deleteQuestion(q.id)
})
createResult(quiz?.backendId, dragQuestionContentId)
}
} else {
enqueueSnackbar("Нет информации о взятом опроснике")
@ -61,10 +57,7 @@ export const FirstNodeField = ({ setOpenedModalQuestions, modalQuestionTargetCon
if (modalQuestionTargetContentId) {
updateRootContentId(quiz?.id, modalQuestionTargetContentId)
updateQuestion(modalQuestionTargetContentId, (question) => question.content.rule.parentId = "root")
//если были результаты - удалить
questions.forEach((q) => {
if (q.type === 'result') deleteQuestion(q.id)
})
createResult(quiz?.backendId, modalQuestionTargetContentId)
}
} else {
enqueueSnackbar("Нет информации о взятом опроснике")

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

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

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

@ -93,21 +93,14 @@ const maxLengthTextField = 225;
updateRootContentId(quiz.id, "");
clearRuleForAll();
deleteQuestion(question.id);
questions.forEach(q => {
if (q.type === "result") {
deleteQuestion(q.id);
}
});
} else if (question.content.rule.parentId.length > 0) { //удалить из стора вопрос из дерева и очистить его потомков
const clearQuestions = [] as string[];
//записываем потомков , а их результаты удаляем
const getChildren = (parentQuestion: AnyTypedQuizQuestion) => {
questions.forEach((targetQuestion) => {
if (targetQuestion.content.rule.parentId === parentQuestion.content.id) {//если у вопроса совпал родитель с родителем => он потомок, в кучу его
if (targetQuestion.type === "result") {
deleteQuestion(targetQuestion.id);
} else {
if (targetQuestion.type !== null && targetQuestion.content.rule.parentId === parentQuestion.content.id) {//если у вопроса совпал родитель с родителем => он потомок, в кучу его
if (targetQuestion.type !== null && targetQuestion.type !== "result") {
if (!clearQuestions.includes(targetQuestion.content.id)) clearQuestions.push(targetQuestion.content.id);
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 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 = () => {
const theme = useTheme();
const quiz = useCurrentQuiz();
const { questions } = useQuestionsStore();
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 (
<>
<Box
@ -99,35 +71,6 @@ export const FirstEntry = () => {
}}
/>
</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 { ResultSettings } from "./ResultSettings"
import { decrementCurrentStep } from "@root/quizes/actions";
import { Box, Button } from "@mui/material";
import ArrowLeft from "@icons/questionsPage/arrowLeft"
export const ResultPage = () => {
const { questions } = useQuestionsStore();
//ищём хотя бы один result
const haveResult = questions.some((question) => question.type === "result")
return (
haveResult ?
<ResultSettings />
:
<>
<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 { useCurrentQuiz } from "@root/quizes/hooks";
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";
export const ResultSettings = () => {
@ -25,6 +25,8 @@ export const ResultSettings = () => {
const [resultContract, setResultContract] = useState(true);
const isReadyToLeaveRef = useRef(true);
console.log(quiz)
console.log(results)
useEffect(
function calcIsReadyToLeave() {
let isReadyToLeave = true;

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

@ -15,6 +15,7 @@ import { useCurrentQuiz } from "@root/quizes/hooks";
import { QuestionsStore, useQuestionsStore } from "./store";
import { useUiTools } from "../uiTools/store";
import { withErrorBoundary } from "react-error-boundary";
import { QuizQuestionResult } from "@model/questionTypes/result";
export const setQuestions = (questions: RawQuestion[] | null) => setProducedState(state => {
@ -481,7 +482,12 @@ export const getQuestionByContentId = (questionContentId: string | null) => {
export const clearRuleForAll = () => {
const { questions } = useQuestionsStore.getState();
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 => {
question.content.rule.parentId = "";
question.content.rule.main = [];
@ -491,63 +497,48 @@ export const clearRuleForAll = () => {
});
};
export const createFrontResult = (quizId: number, parentContentId?: string) => setProducedState(state => {
const frontId = nanoid();
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,
export const createResult = async (
quizId: number,
parentContentId?: string
) => requestQueue.enqueue(async () => {
const question = useQuestionsStore.getState().questions.find(q => q.id === questionId);
if (!question) return;
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("Не удалось создать вопрос");
if (!quizId || !parentContentId) {
console.error("Нет данных для создания результата. quizId: ", quizId, ", quizId: ", parentContentId)
}
//Мы получили запрос на создание резулта. Анализируем существует ли такой. Если да - просто делаем его активным
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 { RequestQueue } from "../../utils/requestQueue";
import { QuizStore, useQuizStore } from "./store";
import { createUntypedQuestion } from "@root/questions/actions";
import { createUntypedQuestion, updateQuestion } from "@root/questions/actions";
import { useCurrentQuiz } from "./hooks"
import { useQuestionsStore } from "@root/questions/store";
export const setEditQuizId = (quizId: number | null) => setProducedState(state => {
@ -176,12 +177,40 @@ export const deleteQuiz = async (quizId: string) => requestQueue.enqueue(async (
enqueueSnackbar(`Не удалось удалить квиз. ${message}`);
}
});
export const updateRootContentId = (quizId: string, id:string) => updateQuiz(
quizId,
quiz => {
quiz.config.haveRoot = id
},
);
export const updateRootContentId = (quizId: string, id: string) => {
if (id.length === 0) {//дерева больше не существует, все результаты неактивны кроме результата линейности
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