Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b000d5739 | |||
| 7bd538a1b4 | |||
| 50a1617388 |
@ -34,6 +34,7 @@ type Props = {
|
|||||||
};
|
};
|
||||||
//Костыль для особого квиза. Для него не нужно показывать email адрес
|
//Костыль для особого квиза. Для него не нужно показывать email адрес
|
||||||
const isDisableEmail = window.location.pathname.includes("/377c7570-1bee-4320-ac1e-d731b6223ce8");
|
const isDisableEmail = window.location.pathname.includes("/377c7570-1bee-4320-ac1e-d731b6223ce8");
|
||||||
|
let isCrutch13112025 = window.location.pathname === "/d557133f-26b6-4b0b-93da-c538758a65d4";
|
||||||
|
|
||||||
export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
|
export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
@ -176,7 +177,7 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
enqueueSnackbar(t("Please try again later"));
|
enqueueSnackbar(t("Please try again later"));
|
||||||
}
|
}
|
||||||
if (settings.cfg.resultInfo.showResultForm === "after") {
|
if (settings.cfg.resultInfo.showResultForm === "after" || isCrutch13112025) {
|
||||||
onShowResult();
|
onShowResult();
|
||||||
}
|
}
|
||||||
enqueueSnackbar(t("Data sent successfully"));
|
enqueueSnackbar(t("Data sent successfully"));
|
||||||
|
|||||||
@ -8,6 +8,9 @@ type ContactTextBlockProps = {
|
|||||||
settings: QuizSettingsConfig;
|
settings: QuizSettingsConfig;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const pathOnly = window.location.pathname;
|
||||||
|
const isCrutchNoDraw = pathOnly === "/28525cd7-9ddf-4c4a-a55b-e3d2f7d47583";
|
||||||
|
|
||||||
export const ContactTextBlock: FC<ContactTextBlockProps> = ({ settings }) => {
|
export const ContactTextBlock: FC<ContactTextBlockProps> = ({ settings }) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const isMobile = useRootContainerSize() < 850;
|
const isMobile = useRootContainerSize() < 850;
|
||||||
@ -47,7 +50,9 @@ export const ContactTextBlock: FC<ContactTextBlockProps> = ({ settings }) => {
|
|||||||
wordBreak: "break-word",
|
wordBreak: "break-word",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{settings.cfg.formContact.title || t("Fill out the form to receive your test results")}
|
{isCrutchNoDraw
|
||||||
|
? "Заполните форму, чтобы отправить ваши ответы"
|
||||||
|
: settings.cfg.formContact.title || t("Fill out the form to receive your test results")}
|
||||||
</Typography>
|
</Typography>
|
||||||
{settings.cfg.formContact.desc && (
|
{settings.cfg.formContact.desc && (
|
||||||
<Typography
|
<Typography
|
||||||
|
|||||||
@ -49,7 +49,6 @@ export const PointSystemResultList = () => {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
|
|||||||
@ -23,6 +23,9 @@ import { useQuizStore } from "@/stores/useQuizStore";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { NameplateLogoDark } from "@/assets/icons/NameplateLogoDark";
|
import { NameplateLogoDark } from "@/assets/icons/NameplateLogoDark";
|
||||||
|
|
||||||
|
const pathOnly = window.location.pathname;
|
||||||
|
let isCrutch13112025 = window.location.pathname === "/d557133f-26b6-4b0b-93da-c538758a65d4";
|
||||||
|
const isCrutchNoDraw = pathOnly === "/28525cd7-9ddf-4c4a-a55b-e3d2f7d47583" || isCrutch13112025;
|
||||||
type ResultFormProps = {
|
type ResultFormProps = {
|
||||||
resultQuestion: QuizQuestionResult;
|
resultQuestion: QuizQuestionResult;
|
||||||
};
|
};
|
||||||
@ -181,6 +184,7 @@ export const ResultForm = ({ resultQuestion }: ResultFormProps) => {
|
|||||||
backgroundColor: "#9A9AAF1A",
|
backgroundColor: "#9A9AAF1A",
|
||||||
borderRadius: "0 0 12px 12px",
|
borderRadius: "0 0 12px 12px",
|
||||||
padding: "20px 20px 15px",
|
padding: "20px 20px 15px",
|
||||||
|
opacity: isCrutchNoDraw ? "0" : "1",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography
|
<Typography
|
||||||
@ -243,6 +247,7 @@ export const ResultForm = ({ resultQuestion }: ResultFormProps) => {
|
|||||||
mt: "30px",
|
mt: "30px",
|
||||||
color: theme.palette.text.primary,
|
color: theme.palette.text.primary,
|
||||||
wordBreak: "break-word",
|
wordBreak: "break-word",
|
||||||
|
margin: isCrutchNoDraw ? "auto" : "0",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{resultQuestion.description}
|
{resultQuestion.description}
|
||||||
@ -274,7 +279,8 @@ export const ResultForm = ({ resultQuestion }: ResultFormProps) => {
|
|||||||
{resultQuestion.content.text}
|
{resultQuestion.content.text}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
{settings.cfg?.score && (
|
|
||||||
|
{((!isCrutchNoDraw && settings.cfg?.score) || isCrutch13112025) && (
|
||||||
<>
|
<>
|
||||||
<Typography
|
<Typography
|
||||||
sx={{
|
sx={{
|
||||||
@ -295,32 +301,34 @@ export const ResultForm = ({ resultQuestion }: ResultFormProps) => {
|
|||||||
>
|
>
|
||||||
{pointsSum} {t("of")} {totalQuestions}
|
{pointsSum} {t("of")} {totalQuestions}
|
||||||
</Typography>
|
</Typography>
|
||||||
<TextAccordion
|
{!isCrutchNoDraw && (
|
||||||
headerText={
|
<TextAccordion
|
||||||
<Typography
|
headerText={
|
||||||
sx={{
|
<Typography
|
||||||
color: theme.palette.primary.main,
|
sx={{
|
||||||
"&:hover": {
|
color: theme.palette.primary.main,
|
||||||
color: theme.palette.primary.dark,
|
"&:hover": {
|
||||||
},
|
color: theme.palette.primary.dark,
|
||||||
}}
|
},
|
||||||
>
|
}}
|
||||||
{t("View answers")}
|
>
|
||||||
</Typography>
|
{t("View answers")}
|
||||||
}
|
</Typography>
|
||||||
sx={{
|
}
|
||||||
mt: "60px",
|
|
||||||
width: "100%",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
sx={{
|
sx={{
|
||||||
mt: "25px",
|
mt: "60px",
|
||||||
|
width: "100%",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<PointSystemResultList />
|
<Box
|
||||||
</Box>
|
sx={{
|
||||||
</TextAccordion>
|
mt: "25px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<PointSystemResultList />
|
||||||
|
</Box>
|
||||||
|
</TextAccordion>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@ -19,6 +19,9 @@ import QuizVideo from "@/ui_kit/VideoIframe/VideoIframe";
|
|||||||
|
|
||||||
import { isProduction } from "@/utils/defineDomain";
|
import { isProduction } from "@/utils/defineDomain";
|
||||||
|
|
||||||
|
const pathOnly = window.location.pathname;
|
||||||
|
const isCrutchNoDraw = pathOnly === "/28525cd7-9ddf-4c4a-a55b-e3d2f7d47583";
|
||||||
|
|
||||||
export const StartPageViewPublication = () => {
|
export const StartPageViewPublication = () => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { settings, show_badge, quizId, questions } = useQuizStore();
|
const { settings, show_badge, quizId, questions } = useQuizStore();
|
||||||
@ -39,15 +42,6 @@ export const StartPageViewPublication = () => {
|
|||||||
yandexMetrics.phoneNumberOpened();
|
yandexMetrics.phoneNumberOpened();
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("------------------------------------------------");
|
|
||||||
console.log("Background type:", settings.cfg.startpage.background.type);
|
|
||||||
console.log("Is image type:", settings.cfg.startpage.background.type === "image");
|
|
||||||
console.log("Is video type:", settings.cfg.startpage.background.type === "video");
|
|
||||||
console.log("Video URL:", settings.cfg.startpage.background.video);
|
|
||||||
console.log("Desktop background:", settings.cfg.startpage.background.desktop);
|
|
||||||
console.log("Startpage type:", settings.cfg.startpageType);
|
|
||||||
console.log("------------------------------------------------");
|
|
||||||
|
|
||||||
const background =
|
const background =
|
||||||
settings.cfg.startpage.background.type === "image" ? (
|
settings.cfg.startpage.background.type === "image" ? (
|
||||||
<img
|
<img
|
||||||
@ -277,8 +271,9 @@ export const StartPageViewPublication = () => {
|
|||||||
margin: "12px 0 30px",
|
margin: "12px 0 30px",
|
||||||
overflowWrap: "break-word",
|
overflowWrap: "break-word",
|
||||||
width: "100%",
|
width: "100%",
|
||||||
textAlign:
|
textAlign: isCrutchNoDraw
|
||||||
settings.cfg.startpageType === "centered" || settings.cfg.startpage.position === "center"
|
? "justify"
|
||||||
|
: settings.cfg.startpageType === "centered" || settings.cfg.startpage.position === "center"
|
||||||
? "center"
|
? "center"
|
||||||
: "-moz-initial",
|
: "-moz-initial",
|
||||||
color: settings.cfg.startpageType === "expanded" ? "white" : theme.palette.text.primary,
|
color: settings.cfg.startpageType === "expanded" ? "white" : theme.palette.text.primary,
|
||||||
|
|||||||
@ -23,7 +23,7 @@ import { changeNextLoading, useQuizStore } from "@/stores/useQuizStore";
|
|||||||
import { polyfillCountryFlagEmojis } from "country-flag-emoji-polyfill";
|
import { polyfillCountryFlagEmojis } from "country-flag-emoji-polyfill";
|
||||||
|
|
||||||
polyfillCountryFlagEmojis();
|
polyfillCountryFlagEmojis();
|
||||||
|
let isCrutchFirst = true;
|
||||||
export default function ViewPublicationPage() {
|
export default function ViewPublicationPage() {
|
||||||
const { settings, recentlyCompleted, quizId, preview, changeFaviconAndTitle } = useQuizStore();
|
const { settings, recentlyCompleted, quizId, preview, changeFaviconAndTitle } = useQuizStore();
|
||||||
const answers = useQuizViewStore((state) => state.answers);
|
const answers = useQuizViewStore((state) => state.answers);
|
||||||
@ -79,17 +79,19 @@ export default function ViewPublicationPage() {
|
|||||||
|
|
||||||
if (settings.cfg.antifraud && recentlyCompleted) throw new Error("Quiz already completed");
|
if (settings.cfg.antifraud && recentlyCompleted) throw new Error("Quiz already completed");
|
||||||
|
|
||||||
|
let isCrutch13112025 = window.location.pathname === "/d557133f-26b6-4b0b-93da-c538758a65d4";
|
||||||
// Обработка noStartPage - обновляем состояние в store
|
// Обработка noStartPage - обновляем состояние в store
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (currentQuizStep === "startpage" && settings.cfg.noStartPage) {
|
console.log("currentQuizStep " + currentQuizStep);
|
||||||
|
if (currentQuizStep === "startpage" && settings.cfg.noStartPage && !isCrutch13112025) {
|
||||||
setCurrentQuizStep("question");
|
setCurrentQuizStep("question");
|
||||||
}
|
}
|
||||||
|
if (isCrutch13112025 && isCrutchFirst) {
|
||||||
|
setCurrentQuizStep("contactform");
|
||||||
|
isCrutchFirst = false;
|
||||||
|
}
|
||||||
}, [currentQuizStep, settings.cfg.noStartPage, setCurrentQuizStep]);
|
}, [currentQuizStep, settings.cfg.noStartPage, setCurrentQuizStep]);
|
||||||
|
|
||||||
// Определяем текущий шаг для рендеринга
|
|
||||||
const displayQuizStep: QuizStep =
|
|
||||||
currentQuizStep === "startpage" && settings.cfg.noStartPage ? "question" : currentQuizStep;
|
|
||||||
|
|
||||||
if (!currentQuestion) {
|
if (!currentQuestion) {
|
||||||
return (
|
return (
|
||||||
<ThemeProvider theme={quizThemes[settings.cfg.theme || "StandardTheme"].theme}>
|
<ThemeProvider theme={quizThemes[settings.cfg.theme || "StandardTheme"].theme}>
|
||||||
@ -106,7 +108,7 @@ export default function ViewPublicationPage() {
|
|||||||
const currentAnswer = answers.find(({ questionId }) => questionId === currentQuestion.id);
|
const currentAnswer = answers.find(({ questionId }) => questionId === currentQuestion.id);
|
||||||
|
|
||||||
let quizStepElement: ReactElement;
|
let quizStepElement: ReactElement;
|
||||||
switch (displayQuizStep) {
|
switch (currentQuizStep) {
|
||||||
case "startpage": {
|
case "startpage": {
|
||||||
quizStepElement = <StartPageViewPublication />;
|
quizStepElement = <StartPageViewPublication />;
|
||||||
break;
|
break;
|
||||||
@ -163,7 +165,7 @@ export default function ViewPublicationPage() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
notReachable(displayQuizStep);
|
notReachable(currentQuizStep);
|
||||||
}
|
}
|
||||||
|
|
||||||
const preloadLinks = new Set([
|
const preloadLinks = new Set([
|
||||||
|
|||||||
@ -17,6 +17,45 @@ interface TextNormalProps {
|
|||||||
stepNumber?: number | null;
|
stepNumber?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let isCrutch13112025 = window.location.pathname === "/d557133f-26b6-4b0b-93da-c538758a65d4";
|
||||||
|
|
||||||
|
const answresList = [
|
||||||
|
"обогащение",
|
||||||
|
"конфискация",
|
||||||
|
"обналичивание",
|
||||||
|
"протекция",
|
||||||
|
"честность",
|
||||||
|
|
||||||
|
"договорняк",
|
||||||
|
"доверие",
|
||||||
|
"кумовство",
|
||||||
|
"офшор",
|
||||||
|
"фаворитизм",
|
||||||
|
|
||||||
|
"мздоимство",
|
||||||
|
"схема",
|
||||||
|
"монополия",
|
||||||
|
"лоббизм",
|
||||||
|
"комплаенс",
|
||||||
|
|
||||||
|
"санкции",
|
||||||
|
"судимость",
|
||||||
|
"контрагент",
|
||||||
|
"казнокрад",
|
||||||
|
"откат",
|
||||||
|
|
||||||
|
"штраф",
|
||||||
|
"непотизм",
|
||||||
|
"легализация",
|
||||||
|
"бенефициар",
|
||||||
|
"анонимность",
|
||||||
|
|
||||||
|
"прачечная",
|
||||||
|
"аффилированность",
|
||||||
|
"декларация",
|
||||||
|
"фальсификация",
|
||||||
|
"расследование",
|
||||||
|
];
|
||||||
export const TextNormal = ({ currentQuestion, answer }: TextNormalProps) => {
|
export const TextNormal = ({ currentQuestion, answer }: TextNormalProps) => {
|
||||||
const { settings } = useQuizStore();
|
const { settings } = useQuizStore();
|
||||||
const { updateAnswer } = useQuizViewStore((state) => state);
|
const { updateAnswer } = useQuizViewStore((state) => state);
|
||||||
@ -25,7 +64,13 @@ export const TextNormal = ({ currentQuestion, answer }: TextNormalProps) => {
|
|||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
const onInputChange = async ({ target }: ChangeEvent<HTMLInputElement>) => {
|
const onInputChange = async ({ target }: ChangeEvent<HTMLInputElement>) => {
|
||||||
updateAnswer(currentQuestion.id, target.value, 0);
|
updateAnswer(
|
||||||
|
currentQuestion.id,
|
||||||
|
target.value,
|
||||||
|
isCrutch13112025
|
||||||
|
? Number(target.value.replace(/\s+/g, "").toLowerCase() === answresList[currentQuestion.page])
|
||||||
|
: 0
|
||||||
|
);
|
||||||
};
|
};
|
||||||
const choiceImgUrlQuestion = useMemo(() => {
|
const choiceImgUrlQuestion = useMemo(() => {
|
||||||
if (
|
if (
|
||||||
|
|||||||
@ -16,6 +16,8 @@ type VariantProps = {
|
|||||||
const pathOnly = window.location.pathname;
|
const pathOnly = window.location.pathname;
|
||||||
|
|
||||||
const isCrutchImg = pathOnly === "/28525cd7-9ddf-4c4a-a55b-e3d2f7d47583";
|
const isCrutchImg = pathOnly === "/28525cd7-9ddf-4c4a-a55b-e3d2f7d47583";
|
||||||
|
|
||||||
|
const isCrutchNoDraw = pathOnly === "/28525cd7-9ddf-4c4a-a55b-e3d2f7d47583";
|
||||||
// 23.02.2025
|
// 23.02.2025
|
||||||
const crutchlist = {
|
const crutchlist = {
|
||||||
115048: { x: 629, y: 491 },
|
115048: { x: 629, y: 491 },
|
||||||
@ -49,6 +51,7 @@ export const Variant = ({ currentQuestion }: VariantProps) => {
|
|||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const isMobile = useRootContainerSize() < 650;
|
const isMobile = useRootContainerSize() < 650;
|
||||||
const isTablet = useRootContainerSize() < 850;
|
const isTablet = useRootContainerSize() < 850;
|
||||||
|
const isDesctop = useRootContainerSize() > 900;
|
||||||
const answers = useQuizViewStore((state) => state.answers);
|
const answers = useQuizViewStore((state) => state.answers);
|
||||||
const ownVariants = useQuizViewStore((state) => state.ownVariants);
|
const ownVariants = useQuizViewStore((state) => state.ownVariants);
|
||||||
const updateOwnVariant = useQuizViewStore((state) => state.updateOwnVariant);
|
const updateOwnVariant = useQuizViewStore((state) => state.updateOwnVariant);
|
||||||
@ -145,14 +148,19 @@ export const Variant = ({ currentQuestion }: VariantProps) => {
|
|||||||
sx={{
|
sx={{
|
||||||
maxWidth: "400px",
|
maxWidth: "400px",
|
||||||
width: "100%",
|
width: "100%",
|
||||||
height: "300px",
|
height: isCrutchNoDraw ? "500px" : "300px",
|
||||||
}}
|
}}
|
||||||
onClick={(event) => event.preventDefault()}
|
onClick={(event) => event.preventDefault()}
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
key={currentQuestion.id}
|
key={currentQuestion.id}
|
||||||
src={choiceImgUrlQuestion}
|
src={choiceImgUrlQuestion}
|
||||||
style={{ width: "100%", height: "100%", objectFit: isCrutchImg ? "contain" : "cover" }}
|
style={{
|
||||||
|
maxWidth: "100%",
|
||||||
|
width: isDesctop && isCrutchNoDraw ? "600px" : "100%",
|
||||||
|
height: "100%",
|
||||||
|
objectFit: isCrutchImg ? "contain" : "cover",
|
||||||
|
}}
|
||||||
alt=""
|
alt=""
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@ -13,6 +13,7 @@ const isProduction = !(
|
|||||||
|
|
||||||
//туризм больше не в исключениях
|
//туризм больше не в исключениях
|
||||||
if (!isProduction) domain = "https://s.hbpn.link";
|
if (!isProduction) domain = "https://s.hbpn.link";
|
||||||
// domain = "https://hbpn.link";
|
|
||||||
|
domain = "https://hbpn.link";
|
||||||
|
|
||||||
export { domain, isProduction };
|
export { domain, isProduction };
|
||||||
|
|||||||
260
lib/utils/hooks/FlowControlLogic/useFirstFCQuiz.ts
Normal file
260
lib/utils/hooks/FlowControlLogic/useFirstFCQuiz.ts
Normal file
@ -0,0 +1,260 @@
|
|||||||
|
import { useCallback, useDebugValue, useEffect, useMemo, useState } from "react";
|
||||||
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
import moment from "moment";
|
||||||
|
|
||||||
|
import { isResultQuestionEmpty } from "@/components/ViewPublicationPage/tools/checkEmptyData";
|
||||||
|
import { useQuizStore } from "@/stores/useQuizStore";
|
||||||
|
|
||||||
|
import { useQuizViewStore } from "@stores/quizView";
|
||||||
|
|
||||||
|
import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
|
||||||
|
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
|
||||||
|
import { useQuestionTimer } from "./useQuestionTimer";
|
||||||
|
|
||||||
|
export function useFirstFCQuiz() {
|
||||||
|
console.log("I`m the useFirstFCQuiz");
|
||||||
|
//Получаем инфо о квизе и список вопросов.
|
||||||
|
const { settings, questions, quizId, cnt, preview } = useQuizStore();
|
||||||
|
|
||||||
|
//Когда квиз линейный, не ветвящийся, мы идём по вопросам по их порядковому номеру. Это их page.
|
||||||
|
//За корректность page отвечает конструктор квизов. Интересный факт, если в конструкторе удалить из середины вопрос, то случится куча запросов изменения вопросов с изменением этого page
|
||||||
|
const sortedQuestions = useMemo(() => {
|
||||||
|
return [...questions].sort((a, b) => a.page - b.page);
|
||||||
|
}, [questions]);
|
||||||
|
//React сам будет менять визуал - главное говорить из какого вопроса ему брать инфо. Изменение этой переменной меняет визуал.
|
||||||
|
const [currentQuestionId, setCurrentQuestionId] = useState<string | null>(getFirstQuestionId);
|
||||||
|
//Список ответов на вопрос. Мы записываем ответы локально, параллельно отправляя на бек информацию о ответах
|
||||||
|
const answers = useQuizViewStore((state) => state.answers);
|
||||||
|
//Список засчитанных баллов для балловых квизов
|
||||||
|
const pointsSum = useQuizViewStore((state) => state.pointsSum);
|
||||||
|
//Текущий шаг "startpage" | "question" | "contactform"
|
||||||
|
const currentQuizStep = useQuizViewStore((state) => state.currentQuizStep);
|
||||||
|
const setCurrentQuizStep = useQuizViewStore((state) => state.setCurrentQuizStep);
|
||||||
|
//Получение возможности управлять состоянием метрик
|
||||||
|
const vkMetrics = useVkMetricsGoals(settings.cfg.vkMetricsNumber);
|
||||||
|
const yandexMetrics = useYandexMetricsGoals(settings.cfg.yandexMetricsNumber);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setCurrentQuizStep("contactform");
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
//Изменение стейта (переменной currentQuestionId) ведёт к пересчёту что же за объект сейчас используется. Мы каждый раз просто ищем в списке
|
||||||
|
const currentQuestion = sortedQuestions.find((question) => question.id === currentQuestionId) ?? sortedQuestions[0];
|
||||||
|
|
||||||
|
//Индекс текущего вопроса только если квиз линейный
|
||||||
|
const linearQuestionIndex = //: number | null
|
||||||
|
currentQuestion && sortedQuestions.every(({ content }) => content.rule.parentId !== "root") // null when branching enabled
|
||||||
|
? sortedQuestions.indexOf(currentQuestion)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
//Индекс первого вопроса
|
||||||
|
function getFirstQuestionId() {
|
||||||
|
//: string | null
|
||||||
|
if (sortedQuestions.length === 0) return null; //Если нету сортированного списка, то и не рыпаемся
|
||||||
|
|
||||||
|
if (settings.cfg.haveRoot) {
|
||||||
|
// Если есть ветвление, то settings.cfg.haveRoot будет заполнен
|
||||||
|
//Если заполнен, то дерево растёт с root и это 1 вопрос :)
|
||||||
|
const nextQuestion = sortedQuestions.find(
|
||||||
|
//Функция ищет первое совпадение по массиву
|
||||||
|
(question) => question.id === settings.cfg.haveRoot || question.content.id === settings.cfg.haveRoot
|
||||||
|
);
|
||||||
|
if (!nextQuestion) return null;
|
||||||
|
|
||||||
|
return nextQuestion.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Если не возникло исключительных ситуаций - первый вопрос - нулевой элемент сортированного массива
|
||||||
|
return sortedQuestions[0].id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextQuestionIdPointsLogic = useCallback(() => {
|
||||||
|
return sortedQuestions.find((question) => question.type === "result" && question.content.rule.parentId === "line");
|
||||||
|
}, [sortedQuestions]);
|
||||||
|
|
||||||
|
//Анализируем какой вопрос должен быть следующим. Это главная логика
|
||||||
|
const nextQuestionIdMainLogic = useCallback(() => {
|
||||||
|
//Список ответов данных этому вопросу. Вернёт QuestionAnswer | undefined
|
||||||
|
const questionAnswer = answers.find(({ questionId }) => questionId === currentQuestion.id);
|
||||||
|
|
||||||
|
//Если questionAnswer не undefined и ответ на вопрос не является временем:
|
||||||
|
if (questionAnswer && !moment.isMoment(questionAnswer.answer)) {
|
||||||
|
//Вопрос типизации. Получаем список строк ответов на этот вопрос
|
||||||
|
const userAnswers = Array.isArray(questionAnswer.answer) ? questionAnswer.answer : [questionAnswer.answer];
|
||||||
|
|
||||||
|
//цикл. Перебираем список условий .main и обзываем их переменной branchingRule
|
||||||
|
for (const branchingRule of currentQuestion.content.rule.main) {
|
||||||
|
// Перебираем список ответов. Если хоть один ответ из списка совпадает с прописанным правилом из условий - этот вопрос нужный нам. Его и дадимкак следующий
|
||||||
|
if (userAnswers.some((answer) => branchingRule.rules[0].answers.includes(answer))) {
|
||||||
|
return branchingRule.next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Не помню что это, но чёт при первом взгляде оно true только у результатов
|
||||||
|
if (!currentQuestion.required) {
|
||||||
|
//Готовим себе дефолтный путь
|
||||||
|
const defaultNextQuestionId = currentQuestion.content.rule.default;
|
||||||
|
|
||||||
|
//Если строка не пустая и не пробел. (Обычно при получении данных мы сразу чистим пустые строки только с пробелом на просто пустые строки. Это прост доп защита)
|
||||||
|
if (defaultNextQuestionId.length > 1 && defaultNextQuestionId !== " ") return defaultNextQuestionId;
|
||||||
|
//Вопросы типа страница, ползунок, своё поле для ввода и дата не могут иметь больше 1 ребёнка. Пользователь не может настроить там дефолт
|
||||||
|
//Кинуть на ребёнка надо даже если там нет дефолта
|
||||||
|
if (
|
||||||
|
["date", "page", "text", "number"].includes(currentQuestion.type) &&
|
||||||
|
currentQuestion.content.rule.children.length === 1
|
||||||
|
)
|
||||||
|
return currentQuestion.content.rule.children[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
//ничё не нашли, ищем резулт
|
||||||
|
return sortedQuestions.find((q) => {
|
||||||
|
return q.type === "result" && q.content.rule.parentId === currentQuestion.content.id;
|
||||||
|
})?.id;
|
||||||
|
}, [answers, currentQuestion, sortedQuestions]);
|
||||||
|
|
||||||
|
//Анализ следующего вопроса. Это логика для вопроса с баллами
|
||||||
|
const nextQuestionId = useMemo(() => {
|
||||||
|
if (settings.cfg.score) {
|
||||||
|
return nextQuestionIdPointsLogic();
|
||||||
|
}
|
||||||
|
return nextQuestionIdMainLogic();
|
||||||
|
}, [nextQuestionIdMainLogic, nextQuestionIdPointsLogic, settings.cfg.score, questions]);
|
||||||
|
|
||||||
|
//Поиск предыдущго вопроса либо по индексу либо по id родителя
|
||||||
|
const prevQuestion =
|
||||||
|
linearQuestionIndex !== null
|
||||||
|
? sortedQuestions[linearQuestionIndex - 1]
|
||||||
|
: sortedQuestions.find(
|
||||||
|
(q) =>
|
||||||
|
q.id === currentQuestion?.content.rule.parentId || q.content.id === currentQuestion?.content.rule.parentId
|
||||||
|
);
|
||||||
|
|
||||||
|
//Анализ результата по количеству баллов
|
||||||
|
const findResultPointsLogic = useCallback(() => {
|
||||||
|
//Отбираем из массива только тип резулт И результы с информацией о ожидаемых баллах И те результы, чьи суммы баллов меньше или равны насчитанным баллам юзера
|
||||||
|
|
||||||
|
const results = sortedQuestions.filter(
|
||||||
|
(e) => e.type === "result" && e.content.rule.minScore !== undefined && e.content.rule.minScore <= pointsSum
|
||||||
|
);
|
||||||
|
//Создаём массив строк из результатов. У кого есть инфо о баллах - дают свои, остальные 0
|
||||||
|
const numbers = results.map((e) =>
|
||||||
|
e.type === "result" && e.content.rule.minScore !== undefined ? e.content.rule.minScore : 0
|
||||||
|
);
|
||||||
|
//Извлекаем самое большое число
|
||||||
|
const indexOfNext = Math.max(...numbers);
|
||||||
|
//Отдаём индекс нужного нам результата
|
||||||
|
return results[numbers.indexOf(indexOfNext)];
|
||||||
|
}, [pointsSum, sortedQuestions]);
|
||||||
|
|
||||||
|
//Ищем следующий вопрос (не его индекс, или id). Сам вопрос
|
||||||
|
const nextQuestion = useMemo(() => {
|
||||||
|
let next;
|
||||||
|
|
||||||
|
if (settings.cfg.score) {
|
||||||
|
//Ессли квиз балловый
|
||||||
|
if (linearQuestionIndex !== null) {
|
||||||
|
next = sortedQuestions[linearQuestionIndex + 1]; //ищем по индексу
|
||||||
|
if (next?.type === "result" || next == undefined) next = findResultPointsLogic(); //если в поисках пришли к результату - считаем нужный
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
//иначе
|
||||||
|
if (linearQuestionIndex !== null) {
|
||||||
|
//для линейных ищем по индексу
|
||||||
|
next =
|
||||||
|
sortedQuestions[linearQuestionIndex + 1] ??
|
||||||
|
sortedQuestions.find((question) => question.type === "result" && question.content.rule.parentId === "line");
|
||||||
|
} else {
|
||||||
|
// для нелинейных ищем по вычесленному id
|
||||||
|
next = sortedQuestions.find((q) => q.id === nextQuestionId || q.content.id === nextQuestionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return next;
|
||||||
|
}, [nextQuestionId, findResultPointsLogic, linearQuestionIndex, sortedQuestions, settings.cfg.score]);
|
||||||
|
|
||||||
|
// Таймер авто-перехода между вопросами
|
||||||
|
useQuestionTimer({
|
||||||
|
enabled: Boolean(settings.questionTimerEnabled),
|
||||||
|
seconds: settings.cfg.time_of_passing ?? 0,
|
||||||
|
quizId,
|
||||||
|
preview,
|
||||||
|
currentQuestion,
|
||||||
|
onNext: () => {
|
||||||
|
// Программный переход к следующему вопросу
|
||||||
|
moveToNextQuestion();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
//Показать визуалом юзеру результат
|
||||||
|
const showResult = useCallback(() => {
|
||||||
|
if (nextQuestion?.type !== "result") throw new Error("Current question is not result");
|
||||||
|
|
||||||
|
//Записать в переменную ид текущего вопроса
|
||||||
|
setCurrentQuestionId(nextQuestion.id);
|
||||||
|
}, [nextQuestion, setCurrentQuizStep, settings.cfg.resultInfo.showResultForm, settings.cfg.showfc]);
|
||||||
|
|
||||||
|
//рычаг управления из визуала в этот контроллер
|
||||||
|
const showResultAfterContactForm = useCallback(() => {
|
||||||
|
console.log("currentQuizStep " + currentQuizStep);
|
||||||
|
setCurrentQuizStep("question");
|
||||||
|
}, [currentQuestion, setCurrentQuizStep]);
|
||||||
|
|
||||||
|
//рычаг управления из визуала в этот контроллер
|
||||||
|
const moveToPrevQuestion = useCallback(() => {
|
||||||
|
if (!prevQuestion) throw new Error("Previous question not found");
|
||||||
|
|
||||||
|
setCurrentQuestionId(prevQuestion.id);
|
||||||
|
}, [prevQuestion]);
|
||||||
|
|
||||||
|
//рычаг управления из визуала в этот контроллер
|
||||||
|
const moveToNextQuestion = useCallback(async () => {
|
||||||
|
// Если есть следующий вопрос в уже загруженных - используем его
|
||||||
|
|
||||||
|
if (nextQuestion) {
|
||||||
|
vkMetrics.questionPassed(currentQuestion.id);
|
||||||
|
yandexMetrics.questionPassed(currentQuestion.id);
|
||||||
|
|
||||||
|
if (nextQuestion.type === "result") return showResult();
|
||||||
|
setCurrentQuestionId(nextQuestion.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}, [currentQuestion.id, nextQuestion, showResult, vkMetrics, yandexMetrics, linearQuestionIndex, questions]);
|
||||||
|
|
||||||
|
//рычаг управления из визуала в этот контроллер
|
||||||
|
const setQuestion = useCallback(
|
||||||
|
(questionId: string) => {
|
||||||
|
const question = sortedQuestions.find((q) => q.id === questionId);
|
||||||
|
if (!question) return;
|
||||||
|
|
||||||
|
setCurrentQuestionId(question.id);
|
||||||
|
},
|
||||||
|
[sortedQuestions]
|
||||||
|
);
|
||||||
|
|
||||||
|
//Анализ дисаблить ли кнопки навигации
|
||||||
|
const isPreviousButtonEnabled = settings.cfg?.backBlocked ? false : Boolean(prevQuestion);
|
||||||
|
|
||||||
|
//Анализ дисаблить ли кнопки навигации
|
||||||
|
const isNextButtonEnabled = true;
|
||||||
|
|
||||||
|
useDebugValue({
|
||||||
|
linearQuestionIndex,
|
||||||
|
currentQuestion: currentQuestion,
|
||||||
|
prevQuestion: prevQuestion,
|
||||||
|
nextQuestion: nextQuestion,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
currentQuestion,
|
||||||
|
currentQuestionStepNumber:
|
||||||
|
settings.status === "ai" ? null : linearQuestionIndex === null ? null : linearQuestionIndex + 1,
|
||||||
|
nextQuestion,
|
||||||
|
isNextButtonEnabled,
|
||||||
|
isPreviousButtonEnabled,
|
||||||
|
moveToPrevQuestion,
|
||||||
|
moveToNextQuestion,
|
||||||
|
showResultAfterContactForm,
|
||||||
|
setQuestion,
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -1,6 +1,7 @@
|
|||||||
import { useBranchingQuiz } from "./FlowControlLogic/useBranchingQuiz";
|
import { useBranchingQuiz } from "./FlowControlLogic/useBranchingQuiz";
|
||||||
import { useLinearQuiz } from "./FlowControlLogic/useLinearQuiz";
|
import { useLinearQuiz } from "./FlowControlLogic/useLinearQuiz";
|
||||||
import { useAIQuiz } from "./FlowControlLogic/useAIQuiz";
|
import { useAIQuiz } from "./FlowControlLogic/useAIQuiz";
|
||||||
|
import { useFirstFCQuiz } from "./FlowControlLogic/useFirstFCQuiz";
|
||||||
import { Status } from "@/model/settingsData";
|
import { Status } from "@/model/settingsData";
|
||||||
import { useQuizStore } from "@/stores/useQuizStore";
|
import { useQuizStore } from "@/stores/useQuizStore";
|
||||||
|
|
||||||
@ -11,18 +12,27 @@ interface StatusData {
|
|||||||
|
|
||||||
// выбор способа управления в зависимости от статуса
|
// выбор способа управления в зависимости от статуса
|
||||||
let cachedManager: () => ReturnType<typeof useLinearQuiz>;
|
let cachedManager: () => ReturnType<typeof useLinearQuiz>;
|
||||||
export let statusOfQuiz: "line" | "branch" | "ai";
|
export let statusOfQuiz: "line" | "branch" | "ai" | "FC";
|
||||||
let isInitialized = false;
|
let isInitialized = false;
|
||||||
|
|
||||||
function analyicStatus({ status, haveRoot }: StatusData) {
|
function analyicStatus({ status, haveRoot }: StatusData) {
|
||||||
|
let isCrutch13112025 = window.location.pathname === "/d557133f-26b6-4b0b-93da-c538758a65d4";
|
||||||
|
|
||||||
|
if (isCrutch13112025) {
|
||||||
|
statusOfQuiz = "FC";
|
||||||
|
console.log("statusOfQuiz: " + statusOfQuiz);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (status === "ai") {
|
if (status === "ai") {
|
||||||
statusOfQuiz = "ai";
|
statusOfQuiz = "ai";
|
||||||
|
console.log("statusOfQuiz: " + statusOfQuiz);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (status === "start") {
|
if (status === "start") {
|
||||||
// Если есть ветвление, то settings.cfg.haveRoot будет заполнен
|
// Если есть ветвление, то settings.cfg.haveRoot будет заполнен
|
||||||
if (haveRoot) statusOfQuiz = "branch";
|
if (haveRoot) statusOfQuiz = "branch";
|
||||||
else statusOfQuiz = "line";
|
else statusOfQuiz = "line";
|
||||||
|
console.log("statusOfQuiz: " + statusOfQuiz);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
throw new Error("quiz is inactive");
|
throw new Error("quiz is inactive");
|
||||||
@ -40,6 +50,9 @@ export const initDataManager = (data: StatusData) => {
|
|||||||
case "ai":
|
case "ai":
|
||||||
cachedManager = useAIQuiz;
|
cachedManager = useAIQuiz;
|
||||||
break;
|
break;
|
||||||
|
case "FC":
|
||||||
|
cachedManager = useFirstFCQuiz;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
isInitialized = true;
|
isInitialized = true;
|
||||||
};
|
};
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user