Merge branch 'dev' into 'staging'
Dev See merge request frontend/squzanswerer!168
This commit is contained in:
commit
d33b5ec0c9
@ -75,11 +75,12 @@ function QuizAnswererInner({
|
|||||||
if (isLoading) return <LoadingSkeleton />;
|
if (isLoading) return <LoadingSkeleton />;
|
||||||
if (error) return <ApologyPage error={error} />;
|
if (error) return <ApologyPage error={error} />;
|
||||||
// if (!data) return <LoadingSkeleton />;
|
// if (!data) return <LoadingSkeleton />;
|
||||||
|
|
||||||
quizSettings ??= data;
|
quizSettings ??= data;
|
||||||
if (!quizSettings) return <ApologyPage error={new Error("Quiz data is null")} />;
|
if (!quizSettings) return <ApologyPage error={new Error("Quiz data is null")} />;
|
||||||
|
|
||||||
if (quizSettings.questions.length === 0) return <ApologyPage error={new Error("No questions found")} />;
|
if (quizSettings.questions.length === 1 && quizSettings?.settings.cfg.noStartPage)
|
||||||
|
return <ApologyPage error={new Error("Quiz is empty")} />;
|
||||||
|
// if (quizSettings.questions.length === 1) return <ApologyPage error={new Error("No questions found")} />;
|
||||||
if (!quizId) return <ApologyPage error={new Error("No quiz id")} />;
|
if (!quizId) return <ApologyPage error={new Error("No quiz id")} />;
|
||||||
|
|
||||||
const quizContainer = (
|
const quizContainer = (
|
||||||
|
@ -8,6 +8,7 @@ export const ApologyPage = ({ error }: Props) => {
|
|||||||
|
|
||||||
if (error.response?.data === "quiz is inactive") message = "Квиз не активирован";
|
if (error.response?.data === "quiz is inactive") message = "Квиз не активирован";
|
||||||
if (error.message === "No questions found") message = "Нет созданных вопросов";
|
if (error.message === "No questions found") message = "Нет созданных вопросов";
|
||||||
|
if (error.message === "Quiz is empty") message = "Квиз пуст";
|
||||||
if (error.message === "Quiz already completed") message = "Вы уже прошли этот опрос";
|
if (error.message === "Quiz already completed") message = "Вы уже прошли этот опрос";
|
||||||
if (error.message === "No quiz id") message = "Отсутствует id квиза";
|
if (error.message === "No quiz id") message = "Отсутствует id квиза";
|
||||||
if (error.message === "Quiz data is null") message = "Не были переданы параметры квиза";
|
if (error.message === "Quiz data is null") message = "Не были переданы параметры квиза";
|
||||||
|
@ -11,29 +11,44 @@ import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
|
|||||||
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
|
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
|
||||||
|
|
||||||
export function useQuestionFlowControl() {
|
export function useQuestionFlowControl() {
|
||||||
|
//Получаем инфо о квизе и список вопросов.
|
||||||
const { settings, questions } = useQuizSettings();
|
const { settings, questions } = useQuizSettings();
|
||||||
|
//Когда квиз линейный, не ветвящийся, мы идём по вопросам по их порядковому номеру. Это их page.
|
||||||
|
//За корректность page отвечает конструктор квизов. Интересный факт, если в конструкторе удалить из середины вопрос, то случится куча запросов изменения вопросов с изменением этого page
|
||||||
const sortedQuestions = useMemo(() => {
|
const sortedQuestions = useMemo(() => {
|
||||||
return [...questions].sort((a, b) => a.page - b.page);
|
return [...questions].sort((a, b) => a.page - b.page);
|
||||||
}, [questions]);
|
}, [questions]);
|
||||||
|
//React сам будет менять визуал - главное говорить из какого вопроса ему брать инфо. Изменение этой переменной меняет визуал.
|
||||||
const [currentQuestionId, setCurrentQuestionId] = useState<string | null>(getFirstQuestionId);
|
const [currentQuestionId, setCurrentQuestionId] = useState<string | null>(getFirstQuestionId);
|
||||||
|
//Список ответов на вопрос. Мы записываем ответы локально, параллельно отправляя на бек информацию о ответах
|
||||||
const answers = useQuizViewStore((state) => state.answers);
|
const answers = useQuizViewStore((state) => state.answers);
|
||||||
|
//Список засчитанных баллов для балловых квизов
|
||||||
const pointsSum = useQuizViewStore((state) => state.pointsSum);
|
const pointsSum = useQuizViewStore((state) => state.pointsSum);
|
||||||
|
//Текущий шаг "startpage" | "question" | "contactform"
|
||||||
const setCurrentQuizStep = useQuizViewStore((state) => state.setCurrentQuizStep);
|
const setCurrentQuizStep = useQuizViewStore((state) => state.setCurrentQuizStep);
|
||||||
|
//Получение возможности управлять состоянием метрик
|
||||||
const vkMetrics = useVkMetricsGoals(settings.cfg.vkMetricsNumber);
|
const vkMetrics = useVkMetricsGoals(settings.cfg.vkMetricsNumber);
|
||||||
const yandexMetrics = useYandexMetricsGoals(settings.cfg.yandexMetricsNumber);
|
const yandexMetrics = useYandexMetricsGoals(settings.cfg.yandexMetricsNumber);
|
||||||
|
|
||||||
|
//Изменение стейта (переменной currentQuestionId) ведёт к пересчёту что же за объект сейчас используется. Мы каждый раз просто ищем в списке
|
||||||
const currentQuestion = sortedQuestions.find((question) => question.id === currentQuestionId) ?? sortedQuestions[0];
|
const currentQuestion = sortedQuestions.find((question) => question.id === currentQuestionId) ?? sortedQuestions[0];
|
||||||
|
|
||||||
const linearQuestionIndex =
|
//Индекс текущего вопроса только если квиз линейный
|
||||||
|
const linearQuestionIndex = //: number | null
|
||||||
currentQuestion && sortedQuestions.every(({ content }) => content.rule.parentId !== "root") // null when branching enabled
|
currentQuestion && sortedQuestions.every(({ content }) => content.rule.parentId !== "root") // null when branching enabled
|
||||||
? sortedQuestions.indexOf(currentQuestion)
|
? sortedQuestions.indexOf(currentQuestion)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
//Индекс первого вопроса
|
||||||
function getFirstQuestionId() {
|
function getFirstQuestionId() {
|
||||||
if (sortedQuestions.length === 0) return null;
|
//: string | null
|
||||||
|
if (sortedQuestions.length === 0) return null; //Если нету сортированного списка, то и не рыпаемся
|
||||||
|
|
||||||
if (settings.cfg.haveRoot) {
|
if (settings.cfg.haveRoot) {
|
||||||
|
// Если есть ветвление, то settings.cfg.haveRoot будет заполнен
|
||||||
|
//Если заполнен, то дерево растёт с root и это 1 вопрос :)
|
||||||
const nextQuestion = sortedQuestions.find(
|
const nextQuestion = sortedQuestions.find(
|
||||||
|
//Функция ищет первое совпадение по массиву
|
||||||
(question) => question.id === settings.cfg.haveRoot || question.content.id === settings.cfg.haveRoot
|
(question) => question.id === settings.cfg.haveRoot || question.content.id === settings.cfg.haveRoot
|
||||||
);
|
);
|
||||||
if (!nextQuestion) return null;
|
if (!nextQuestion) return null;
|
||||||
@ -41,6 +56,7 @@ export function useQuestionFlowControl() {
|
|||||||
return nextQuestion.id;
|
return nextQuestion.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Если не возникло исключительных ситуаций - первый вопрос - нулевой элемент сортированного массива
|
||||||
return sortedQuestions[0].id;
|
return sortedQuestions[0].id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -48,21 +64,31 @@ export function useQuestionFlowControl() {
|
|||||||
return sortedQuestions.find((question) => question.type === "result" && question.content.rule.parentId === "line");
|
return sortedQuestions.find((question) => question.type === "result" && question.content.rule.parentId === "line");
|
||||||
}, [sortedQuestions]);
|
}, [sortedQuestions]);
|
||||||
|
|
||||||
|
//Анализируем какой вопрос должен быть следующим. Это главная логика
|
||||||
const nextQuestionIdMainLogic = useCallback(() => {
|
const nextQuestionIdMainLogic = useCallback(() => {
|
||||||
|
//Список ответов данных этому вопросу. Вернёт QuestionAnswer | undefined
|
||||||
const questionAnswer = answers.find(({ questionId }) => questionId === currentQuestion.id);
|
const questionAnswer = answers.find(({ questionId }) => questionId === currentQuestion.id);
|
||||||
|
|
||||||
|
//Если questionAnswer не undefined и ответ на вопрос не является временем:
|
||||||
if (questionAnswer && !moment.isMoment(questionAnswer.answer)) {
|
if (questionAnswer && !moment.isMoment(questionAnswer.answer)) {
|
||||||
|
//Вопрос типизации. Получаем список строк ответов на этот вопрос
|
||||||
const userAnswers = Array.isArray(questionAnswer.answer) ? questionAnswer.answer : [questionAnswer.answer];
|
const userAnswers = Array.isArray(questionAnswer.answer) ? questionAnswer.answer : [questionAnswer.answer];
|
||||||
|
|
||||||
|
//цикл. Перебираем список условий .main и обзываем их переменной branchingRule
|
||||||
for (const branchingRule of currentQuestion.content.rule.main) {
|
for (const branchingRule of currentQuestion.content.rule.main) {
|
||||||
|
// Перебираем список ответов. Если хоть один ответ из списка совпадает с прописанным правилом из условий - этот вопрос нужный нам. Его и дадимкак следующий
|
||||||
if (userAnswers.some((answer) => branchingRule.rules[0].answers.includes(answer))) {
|
if (userAnswers.some((answer) => branchingRule.rules[0].answers.includes(answer))) {
|
||||||
return branchingRule.next;
|
return branchingRule.next;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Не помню что это, но чёт при первом взгляде оно true только у результатов
|
||||||
if (!currentQuestion.required) {
|
if (!currentQuestion.required) {
|
||||||
|
//Готовим себе дефолтный путь
|
||||||
const defaultNextQuestionId = currentQuestion.content.rule.default;
|
const defaultNextQuestionId = currentQuestion.content.rule.default;
|
||||||
|
|
||||||
|
//Если строка не пустая и не пробел. (Обычно при получении данных мы сразу чистим пустые строки только с пробелом на просто пустые строки. Это прост доп защита)
|
||||||
if (defaultNextQuestionId.length > 1 && defaultNextQuestionId !== " ") return defaultNextQuestionId;
|
if (defaultNextQuestionId.length > 1 && defaultNextQuestionId !== " ") return defaultNextQuestionId;
|
||||||
//Вопросы типа страница, ползунок, своё поле для ввода и дата не могут иметь больше 1 ребёнка. Пользователь не может настроить там дефолт
|
//Вопросы типа страница, ползунок, своё поле для ввода и дата не могут иметь больше 1 ребёнка. Пользователь не может настроить там дефолт
|
||||||
//Кинуть на ребёнка надо даже если там нет дефолта
|
//Кинуть на ребёнка надо даже если там нет дефолта
|
||||||
@ -79,6 +105,7 @@ export function useQuestionFlowControl() {
|
|||||||
})?.id;
|
})?.id;
|
||||||
}, [answers, currentQuestion, sortedQuestions]);
|
}, [answers, currentQuestion, sortedQuestions]);
|
||||||
|
|
||||||
|
//Анализ следующего вопроса. Это логика для вопроса с баллами
|
||||||
const nextQuestionId = useMemo(() => {
|
const nextQuestionId = useMemo(() => {
|
||||||
if (settings.cfg.score) {
|
if (settings.cfg.score) {
|
||||||
return nextQuestionIdPointsLogic();
|
return nextQuestionIdPointsLogic();
|
||||||
@ -86,6 +113,7 @@ export function useQuestionFlowControl() {
|
|||||||
return nextQuestionIdMainLogic();
|
return nextQuestionIdMainLogic();
|
||||||
}, [nextQuestionIdMainLogic, nextQuestionIdPointsLogic, settings.cfg.score]);
|
}, [nextQuestionIdMainLogic, nextQuestionIdPointsLogic, settings.cfg.score]);
|
||||||
|
|
||||||
|
//Поиск предыдущго вопроса либо по индексу либо по id родителя
|
||||||
const prevQuestion =
|
const prevQuestion =
|
||||||
linearQuestionIndex !== null
|
linearQuestionIndex !== null
|
||||||
? sortedQuestions[linearQuestionIndex - 1]
|
? sortedQuestions[linearQuestionIndex - 1]
|
||||||
@ -94,31 +122,42 @@ export function useQuestionFlowControl() {
|
|||||||
q.id === currentQuestion?.content.rule.parentId || q.content.id === currentQuestion?.content.rule.parentId
|
q.id === currentQuestion?.content.rule.parentId || q.content.id === currentQuestion?.content.rule.parentId
|
||||||
);
|
);
|
||||||
|
|
||||||
|
//Анализ результата по количеству баллов
|
||||||
const findResultPointsLogic = useCallback(() => {
|
const findResultPointsLogic = useCallback(() => {
|
||||||
|
//Отбираем из массива только тип резулт И результы с информацией о ожидаемых баллах И те результы, чьи суммы баллов меньше или равны насчитанным баллам юзера
|
||||||
const results = sortedQuestions.filter(
|
const results = sortedQuestions.filter(
|
||||||
(e) => e.type === "result" && e.content.rule.minScore !== undefined && e.content.rule.minScore <= pointsSum
|
(e) => e.type === "result" && e.content.rule.minScore !== undefined && e.content.rule.minScore <= pointsSum
|
||||||
);
|
);
|
||||||
|
//Создаём массив строк из результатов. У кого есть инфо о баллах - дают свои, остальные 0
|
||||||
const numbers = results.map((e) =>
|
const numbers = results.map((e) =>
|
||||||
e.type === "result" && e.content.rule.minScore !== undefined ? e.content.rule.minScore : 0
|
e.type === "result" && e.content.rule.minScore !== undefined ? e.content.rule.minScore : 0
|
||||||
);
|
);
|
||||||
|
//Извлекаем самое большое число
|
||||||
const indexOfNext = Math.max(...numbers);
|
const indexOfNext = Math.max(...numbers);
|
||||||
|
|
||||||
|
//Отдаём индекс нужного нам результата
|
||||||
return results[numbers.indexOf(indexOfNext)];
|
return results[numbers.indexOf(indexOfNext)];
|
||||||
}, [pointsSum, sortedQuestions]);
|
}, [pointsSum, sortedQuestions]);
|
||||||
|
|
||||||
|
//Ищем следующий вопрос (не его индекс, или id). Сам вопрос
|
||||||
const nextQuestion = useMemo(() => {
|
const nextQuestion = useMemo(() => {
|
||||||
let next;
|
let next;
|
||||||
|
|
||||||
if (settings.cfg.score) {
|
if (settings.cfg.score) {
|
||||||
|
//Ессли квиз балловый
|
||||||
if (linearQuestionIndex !== null) {
|
if (linearQuestionIndex !== null) {
|
||||||
next = sortedQuestions[linearQuestionIndex + 1];
|
next = sortedQuestions[linearQuestionIndex + 1]; //ищем по индексу
|
||||||
if (next?.type === "result" || next == undefined) next = findResultPointsLogic();
|
if (next?.type === "result" || next == undefined) next = findResultPointsLogic(); //если в поисках пришли к результату - считаем нужный
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
//иначе
|
||||||
if (linearQuestionIndex !== null) {
|
if (linearQuestionIndex !== null) {
|
||||||
|
//для линейных ищем по индексу
|
||||||
next =
|
next =
|
||||||
sortedQuestions[linearQuestionIndex + 1] ??
|
sortedQuestions[linearQuestionIndex + 1] ??
|
||||||
sortedQuestions.find((question) => question.type === "result" && question.content.rule.parentId === "line");
|
sortedQuestions.find((question) => question.type === "result" && question.content.rule.parentId === "line");
|
||||||
} else {
|
} else {
|
||||||
|
// для нелинейных ищем по вычесленному id
|
||||||
next = sortedQuestions.find((q) => q.id === nextQuestionId || q.content.id === nextQuestionId);
|
next = sortedQuestions.find((q) => q.id === nextQuestionId || q.content.id === nextQuestionId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -126,10 +165,13 @@ export function useQuestionFlowControl() {
|
|||||||
return next;
|
return next;
|
||||||
}, [nextQuestionId, findResultPointsLogic, linearQuestionIndex, sortedQuestions, settings.cfg.score]);
|
}, [nextQuestionId, findResultPointsLogic, linearQuestionIndex, sortedQuestions, settings.cfg.score]);
|
||||||
|
|
||||||
|
//Показать визуалом юзеру результат
|
||||||
const showResult = useCallback(() => {
|
const showResult = useCallback(() => {
|
||||||
if (nextQuestion?.type !== "result") throw new Error("Current question is not result");
|
if (nextQuestion?.type !== "result") throw new Error("Current question is not result");
|
||||||
|
|
||||||
|
//Записать в переменную ид текущего вопроса
|
||||||
setCurrentQuestionId(nextQuestion.id);
|
setCurrentQuestionId(nextQuestion.id);
|
||||||
|
//Смотрим по настройкам показывать ли вообще форму контактов. Показывать ли страницу результатов до или после формы контактов (ФК)
|
||||||
if (
|
if (
|
||||||
settings.cfg.showfc !== false &&
|
settings.cfg.showfc !== false &&
|
||||||
(settings.cfg.resultInfo.showResultForm === "after" || isResultQuestionEmpty(nextQuestion))
|
(settings.cfg.resultInfo.showResultForm === "after" || isResultQuestionEmpty(nextQuestion))
|
||||||
@ -137,6 +179,7 @@ export function useQuestionFlowControl() {
|
|||||||
setCurrentQuizStep("contactform");
|
setCurrentQuizStep("contactform");
|
||||||
}, [nextQuestion, setCurrentQuizStep, settings.cfg.resultInfo.showResultForm, settings.cfg.showfc]);
|
}, [nextQuestion, setCurrentQuizStep, settings.cfg.resultInfo.showResultForm, settings.cfg.showfc]);
|
||||||
|
|
||||||
|
//рычаг управления из визуала в эту функцию
|
||||||
const showResultAfterContactForm = useCallback(() => {
|
const showResultAfterContactForm = useCallback(() => {
|
||||||
if (currentQuestion?.type !== "result") throw new Error("Current question is not result");
|
if (currentQuestion?.type !== "result") throw new Error("Current question is not result");
|
||||||
if (isResultQuestionEmpty(currentQuestion)) {
|
if (isResultQuestionEmpty(currentQuestion)) {
|
||||||
@ -147,12 +190,14 @@ export function useQuestionFlowControl() {
|
|||||||
setCurrentQuizStep("question");
|
setCurrentQuizStep("question");
|
||||||
}, [currentQuestion, setCurrentQuizStep]);
|
}, [currentQuestion, setCurrentQuizStep]);
|
||||||
|
|
||||||
|
//рычаг управления из визуала в эту функцию
|
||||||
const moveToPrevQuestion = useCallback(() => {
|
const moveToPrevQuestion = useCallback(() => {
|
||||||
if (!prevQuestion) throw new Error("Previous question not found");
|
if (!prevQuestion) throw new Error("Previous question not found");
|
||||||
|
|
||||||
setCurrentQuestionId(prevQuestion.id);
|
setCurrentQuestionId(prevQuestion.id);
|
||||||
}, [prevQuestion]);
|
}, [prevQuestion]);
|
||||||
|
|
||||||
|
//рычаг управления из визуала в эту функцию
|
||||||
const moveToNextQuestion = useCallback(() => {
|
const moveToNextQuestion = useCallback(() => {
|
||||||
if (!nextQuestion) throw new Error("Next question not found");
|
if (!nextQuestion) throw new Error("Next question not found");
|
||||||
|
|
||||||
@ -165,6 +210,7 @@ export function useQuestionFlowControl() {
|
|||||||
setCurrentQuestionId(nextQuestion.id);
|
setCurrentQuestionId(nextQuestion.id);
|
||||||
}, [currentQuestion.id, nextQuestion, showResult, vkMetrics, yandexMetrics]);
|
}, [currentQuestion.id, nextQuestion, showResult, vkMetrics, yandexMetrics]);
|
||||||
|
|
||||||
|
//рычаг управления из визуала в эту функцию
|
||||||
const setQuestion = useCallback(
|
const setQuestion = useCallback(
|
||||||
(questionId: string) => {
|
(questionId: string) => {
|
||||||
const question = sortedQuestions.find((q) => q.id === questionId);
|
const question = sortedQuestions.find((q) => q.id === questionId);
|
||||||
@ -175,8 +221,10 @@ export function useQuestionFlowControl() {
|
|||||||
[sortedQuestions]
|
[sortedQuestions]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
//Анализ дисаблить ли кнопки навигации
|
||||||
const isPreviousButtonEnabled = Boolean(prevQuestion);
|
const isPreviousButtonEnabled = Boolean(prevQuestion);
|
||||||
|
|
||||||
|
//Анализ дисаблить ли кнопки навигации
|
||||||
const isNextButtonEnabled = useMemo(() => {
|
const isNextButtonEnabled = useMemo(() => {
|
||||||
const hasAnswer = answers.some(({ questionId }) => questionId === currentQuestion.id);
|
const hasAnswer = answers.some(({ questionId }) => questionId === currentQuestion.id);
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user