frontAnswerer/src/pages/ViewPublicationPage/ContactForm.tsx

504 lines
18 KiB
TypeScript
Raw Normal View History

import AddressIcon from "@icons/ContactFormIcon/AddressIcon";
import EmailIcon from "@icons/ContactFormIcon/EmailIcon";
2024-02-02 14:35:02 +00:00
import NameIcon from "@icons/ContactFormIcon/NameIcon";
import PhoneIcon from "@icons/ContactFormIcon/PhoneIcon";
import TextIcon from "@icons/ContactFormIcon/TextIcon";
import { Box, Button, InputAdornment, Link, TextField as MuiTextField, TextFieldProps, Typography, useTheme } from "@mui/material";
import CustomCheckbox from "@ui_kit/CustomCheckbox";
import { FC, useRef, useState } from "react";
2023-12-16 14:55:56 +00:00
import { sendFC } from "@api/quizRelase";
import { NameplateLogo } from "@icons/NameplateLogo";
import { QuizQuestionResult } from "@model/questionTypes/result";
2024-02-02 14:35:02 +00:00
import { useQuizData } from "@utils/hooks/useQuizData";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import { enqueueSnackbar } from "notistack";
import { useRootContainerSize } from "../../contexts/RootContainerWidthContext";
import { ApologyPage } from "./ApologyPage";
import { checkEmptyData } from "./tools/checkEmptyData";
2023-12-16 14:55:56 +00:00
const TextField = MuiTextField as unknown as FC<TextFieldProps>; // temporary fix ts(2590)
const EMAIL_REGEXP = /^(([^<>()[\].,:\s@"]+(\.[^<>()[\].,:\s@"]+)*)|(".+"))@(([^<>()[\].,:\s@"]+\.)+[^<>()[\].,:\s@"]{2,})$/iu;
2023-12-16 14:55:56 +00:00
type ContactFormProps = {
currentQuestion: any;
showResultForm: boolean;
setShowContactForm: (show: boolean) => void;
setShowResultForm: (show: boolean) => void;
2023-12-16 14:55:56 +00:00
};
const icons = [
2024-01-31 12:57:07 +00:00
{
type: "name",
icon: NameIcon,
defaultText: "Введите имя",
defaultTitle: "имя",
backendName: "name",
},
{
type: "email",
icon: EmailIcon,
defaultText: "Введите Email",
defaultTitle: "Email",
backendName: "email",
},
{
type: "phone",
icon: PhoneIcon,
defaultText: "Введите номер телефона",
defaultTitle: "номер телефона",
backendName: "phone",
},
{
type: "text",
icon: TextIcon,
defaultText: "Введите фамилию",
defaultTitle: "фамилию",
backendName: "adress",
},
{
type: "address",
icon: AddressIcon,
defaultText: "Введите адрес",
defaultTitle: "адрес",
backendName: "adress",
},
2024-01-25 07:36:45 +00:00
];
2023-12-16 14:55:56 +00:00
export const ContactForm = ({
currentQuestion,
showResultForm,
setShowContactForm,
setShowResultForm,
2023-12-16 14:55:56 +00:00
}: ContactFormProps) => {
const theme = useTheme();
2024-02-02 14:35:02 +00:00
const { settings, questions } = useQuizData();
2024-01-31 12:57:07 +00:00
const [ready, setReady] = useState(false);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [text, setText] = useState("");
const [adress, setAdress] = useState("");
2024-01-31 12:57:07 +00:00
const fireOnce = useRef(true);
const [fire, setFire] = useState(false);
const isMobile = useRootContainerSize() < 850;
2024-01-31 12:57:07 +00:00
const followNextForm = () => {
setShowContactForm(false);
setShowResultForm(true);
};
//@ts-ignore
2024-02-02 14:35:02 +00:00
const resultQuestion: QuizQuestionResult = questions.find((question) => {
2024-01-31 12:57:07 +00:00
if (settings?.cfg.haveRoot) {
//ветвимся
return (
question.type === "result" &&
2024-01-31 12:57:07 +00:00
//@ts-ignore
question.content.rule.parentId === currentQuestion.content.id
);
2024-01-31 12:57:07 +00:00
} else {
// не ветвимся
return (
2024-01-31 12:57:07 +00:00
question.type === "result" && question.content.rule.parentId === "line"
);
}
2024-01-31 12:57:07 +00:00
});
const inputHC = async () => {
2024-01-31 12:57:07 +00:00
//@ts-ignore
const FC = settings?.cfg.formContact.fields || settings?.cfg.formContact;
const body = {};
//@ts-ignore
if (name.length > 0) body.name = name;
2024-01-31 12:57:07 +00:00
//@ts-ignore
if (email.length > 0) body.email = email;
2024-01-31 12:57:07 +00:00
//@ts-ignore
if (phone.length > 0) body.phone = phone;
2024-01-31 12:57:07 +00:00
//@ts-ignore
if (adress.length > 0) body.address = adress;
//@ts-ignore
if (text.length > 0) body.customs = { [FC.text.text || "Фамилия"]: text };
if (Object.keys(body).length > 0) {
try {
await sendFC({
questionId: resultQuestion?.id,
body: body,
2024-01-31 12:57:07 +00:00
qid: settings.qid,
});
const sessions = JSON.parse(localStorage.getItem("sessions") || "{}");
localStorage.setItem(
"sessions",
JSON.stringify({ ...sessions, [settings.qid]: new Date().getTime() })
);
} catch (e) {
2024-01-31 12:57:07 +00:00
enqueueSnackbar("ответ не был засчитан");
}
}
2024-01-31 12:57:07 +00:00
};
//@ts-ignore
2024-01-31 12:57:07 +00:00
let FCcopy: any = settings?.cfg.formContact.fields || settings?.cfg.formContact;
2024-01-31 12:57:07 +00:00
let filteredFC: any = {};
for (let i in FCcopy) {
let field = FCcopy[i];
console.log(filteredFC);
if (field.used) {
filteredFC[i] = field;
}
}
2024-01-31 12:57:07 +00:00
let isWide = Object.keys(filteredFC).length > 2;
2024-01-31 12:57:07 +00:00
if (!resultQuestion)
return (
<ApologyPage message="не получилось найти результат для этой ветки :(" />
);
return (
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
backgroundColor: theme.palette.background.default,
height: "100vh",
overflow: "auto",
2024-01-31 12:57:07 +00:00
"&::-webkit-scrollbar": {
width: "0",
display: "none",
msOverflowStyle: "none",
},
scrollbarWidth: "none",
2024-01-31 12:57:07 +00:00
msOverflowStyle: "none",
}}
>
<Box
sx={{
2024-01-31 12:57:07 +00:00
width: isWide && !isMobile ? "100%" : isMobile ? undefined : "530px",
borderRadius: "4px",
height: "90vh",
2024-01-31 12:57:07 +00:00
display: isWide && !isMobile ? "flex" : undefined,
}}
>
<Box
sx={{
width: isWide && !isMobile ? "100%" : undefined,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
2024-01-31 12:57:07 +00:00
borderRight: isWide && !isMobile ? "1px solid gray" : undefined,
}}
>
<Typography
sx={{
textAlign: "center",
m: "20px 0",
fontSize: "28px",
2024-01-31 12:57:07 +00:00
color: theme.palette.text.primary,
}}
>
2024-01-31 12:57:07 +00:00
{settings?.cfg.formContact.title ||
"Заполните форму, чтобы получить результаты теста"}
</Typography>
2024-01-31 12:57:07 +00:00
{settings?.cfg.formContact.desc && (
<Typography
sx={{
color: theme.palette.text.primary,
textAlign: "center",
m: "20px 0",
2024-01-31 12:57:07 +00:00
fontSize: "18px",
}}
>
{settings?.cfg.formContact.desc}
</Typography>
2024-01-31 12:57:07 +00:00
)}
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
backgroundColor: theme.palette.background.default,
2024-01-31 12:57:07 +00:00
p: "30px",
}}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
2024-01-31 12:57:07 +00:00
my: "20px",
}}
>
<Inputs
2024-01-31 12:57:07 +00:00
name={name}
setName={setName}
email={email}
setEmail={setEmail}
phone={phone}
setPhone={setPhone}
text={text}
setText={setText}
adress={adress}
setAdress={setAdress}
/>
</Box>
{
// resultQuestion &&
2024-01-31 12:57:07 +00:00
// settings?.cfg.resultInfo.when === "after" &&
<Button
disabled={!(ready && !fire)}
variant="contained"
onClick={async () => {
//@ts-ignore
const FC: any = settings?.cfg.formContact.fields || settings?.cfg.formContact;
if (FC["email"].used === EMAIL_REGEXP.test(email)) {
//почта валидна
setFire(true);
2024-01-31 12:57:07 +00:00
if (fireOnce.current) {
if (
name.length > 0 ||
email.length > 0 ||
phone.length > 0 ||
text.length > 0 ||
adress.length > 0
) {
try {
await inputHC();
fireOnce.current = false;
const QID =
process.env.NODE_ENV === "production"
? window.location.pathname.replace(/\//g, "")
: "ef836ff8-35b1-4031-9acf-af5766bac2b2";
const sessions: any = JSON.parse(
localStorage.getItem("sessions") || "{}"
);
sessions[QID] = Date.now();
localStorage.setItem(
"sessions",
JSON.stringify(sessions)
);
enqueueSnackbar("Данные успешно отправлены");
} catch (e) {
enqueueSnackbar("повторите попытку позже");
}
if (
2024-01-31 12:57:07 +00:00
settings?.cfg.resultInfo.showResultForm === "after" &&
!checkEmptyData({ resultData: resultQuestion })
) {
2024-01-31 12:57:07 +00:00
setShowContactForm(false);
setShowResultForm(true);
}
2024-01-31 12:57:07 +00:00
} else {
enqueueSnackbar("Пожалуйста, заполните поля");
}
}
2024-01-31 12:57:07 +00:00
setFire(false);
} else {
enqueueSnackbar("введена некорректная почта");
}
}}
>
{settings?.cfg.formContact?.button || "Получить результаты"}
</Button>
}
<Box
sx={{
display: "flex",
mt: "20px",
width: isMobile ? "300px" : "450px",
}}
>
2024-01-31 12:57:07 +00:00
<CustomCheckbox
label=""
handleChange={({ target }) => {
setReady(target.checked);
}}
checked={ready}
colorIcon={theme.palette.primary.main}
/>
<Typography sx={{ color: theme.palette.text.primary }}>
С&ensp;
<Link href={"https://shub.pena.digital/ppdd"} target="_blank">
2024-01-31 12:57:07 +00:00
Положением об обработке персональных данных{" "}
</Link>
&ensp;и&ensp;
2024-01-31 12:57:07 +00:00
<Link
href={"https://shub.pena.digital/docs/privacy"}
target="_blank"
>
{" "}
Политикой конфиденциальности{" "}
</Link>
&ensp;ознакомлен
</Typography>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
mt: "20px",
2024-01-31 12:57:07 +00:00
gap: "15px",
}}
>
2024-01-31 12:57:07 +00:00
<NameplateLogo
style={{
fontSize: "34px",
2024-02-02 14:35:02 +00:00
color: quizThemes[settings.cfg.theme].isLight ? "#151515" : "#FFFFFF",
2024-01-31 12:57:07 +00:00
}}
/>
<Typography
sx={{
fontSize: "20px",
2024-02-02 14:35:02 +00:00
color: quizThemes[settings.cfg.theme].isLight ? "#4D4D4D" : "#F5F7FF",
2024-01-31 12:57:07 +00:00
whiteSpace: "nowrap",
}}
>
Сделано на PenaQuiz
</Typography>
</Box>
</Box>
2024-01-31 12:57:07 +00:00
</Box>
</Box>
);
};
const Inputs = ({
2024-01-31 12:57:07 +00:00
name,
setName,
email,
setEmail,
phone,
setPhone,
text,
setText,
adress,
setAdress,
}: any) => {
2024-02-02 14:35:02 +00:00
const { settings } = useQuizData();
2024-01-31 12:57:07 +00:00
// @ts-ignore
const FC = settings?.cfg.formContact.fields || settings?.cfg.formContact;
2024-01-31 12:57:07 +00:00
if (!FC) return null;
//@ts-ignore
2024-01-31 12:57:07 +00:00
const Name = (
<CustomInput
//@ts-ignore
onChange={({ target }) => setName(target.value)}
id={name}
title={FC["name"].innerText || "Введите имя"}
desc={FC["name"].text || "имя"}
Icon={NameIcon}
/>
2024-01-25 07:36:45 +00:00
);
//@ts-ignore
2024-01-31 12:57:07 +00:00
const Email = (
<CustomInput
error={!EMAIL_REGEXP.test(email)}
label={!EMAIL_REGEXP.test(email) ? "" : "Некорректная почта"}
//@ts-ignore
onChange={({ target }) => setEmail(target.value)}
id={email}
title={FC["email"].innerText || "Введите Email"}
desc={FC["email"].text || "Email"}
Icon={EmailIcon}
/>
);
const Phone = (
<CustomInput
//@ts-ignore
onChange={({ target }) => setPhone(target.value)}
id={phone}
title={FC["phone"].innerText || "Введите номер телефона"}
desc={FC["phone"].text || "номер телефона"}
Icon={PhoneIcon}
/>
2024-01-25 07:36:45 +00:00
);
//@ts-ignore
2024-01-31 12:57:07 +00:00
const Text = (
<CustomInput
//@ts-ignore
onChange={({ target }) => setText(target.value)}
id={text}
title={FC["text"].text || "Введите фамилию"}
desc={FC["text"].innerText || "фамилию"}
Icon={TextIcon}
/>
);
//@ts-ignore
2024-01-31 12:57:07 +00:00
const Adress = (
<CustomInput
//@ts-ignore
onChange={({ target }) => setAdress(target.value)}
id={adress}
title={FC["address"].innerText || "Введите адрес"}
desc={FC["address"].text || "адрес"}
Icon={AddressIcon}
/>
);
//@ts-ignore
if (Object.values(FC).some((data) => data.used)) {
2024-01-31 12:57:07 +00:00
return (
<>
{FC["name"].used ? Name : <></>}
{FC["email"].used ? Email : <></>}
{FC["phone"].used ? Phone : <></>}
{FC["text"].used ? Text : <></>}
{FC["address"].used ? Adress : <></>}
</>
);
} else {
2024-01-31 12:57:07 +00:00
return (
<>
{Name}
{Email}
{Phone}
</>
);
}
2024-01-25 07:36:45 +00:00
};
const CustomInput = ({ title, desc, Icon, onChange }: any) => {
const theme = useTheme();
const isMobile = useRootContainerSize() < 600;
2024-01-31 12:57:07 +00:00
//@ts-ignore
return (
<Box m="15px 0">
2024-01-31 12:57:07 +00:00
<Typography mb="7px" color={theme.palette.text.primary}>
{title}
</Typography>
<TextField
onChange={onChange}
sx={{
width: isMobile ? "300px" : "350px",
}}
placeholder={desc}
InputProps={{
2024-01-31 12:57:07 +00:00
startAdornment: (
<InputAdornment position="start">
<Icon color="gray" />
</InputAdornment>
),
}}
/>
</Box>
2024-01-31 12:57:07 +00:00
);
2024-01-25 07:36:45 +00:00
};