Files
tanami-admin-panel/src/Pages/Master/Sponser/AddSponser.jsx

335 lines
9.5 KiB
React
Raw Normal View History

2024-07-19 18:36:47 +05:30
import React, { useContext, useEffect, useState } from "react";
2024-06-24 12:08:21 +05:30
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
2024-09-19 16:45:05 +05:30
import { Box, Button, Text, useToast } from "@chakra-ui/react";
2024-06-24 12:08:21 +05:30
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
2024-07-19 18:36:47 +05:30
import { useNavigate, useParams } from "react-router-dom";
2024-06-25 20:35:03 +05:30
import { v4 as uuidv4 } from "uuid";
2024-07-01 12:33:55 +05:30
import FormInputMain from "../../../Components/FormInputMain";
2024-07-19 18:36:47 +05:30
import ToastBox from "../../../Components/ToastBox";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
2024-07-24 19:57:31 +05:30
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
2024-07-29 12:20:40 +05:30
import SwitchButton from "../../../Components/SwitchButton";
2024-08-08 19:37:14 +05:30
import DummyComponent from "../../../Components/DummyComponent";
2024-09-17 15:33:27 +05:30
import {
useCreateSponserMutation,
useGetSponserByIdQuery,
useUpdateSponserMutation,
} from "../../../Services/io.service";
2024-09-19 16:45:05 +05:30
import { ArrowBackIcon } from "@chakra-ui/icons";
2024-07-24 19:57:31 +05:30
// ======================= [validation] =========================
2024-06-24 12:08:21 +05:30
2024-07-01 12:33:55 +05:30
export const addSponser = yup.object().shape({
2024-09-17 15:33:27 +05:30
sponsorName: yup
2024-09-20 18:04:58 +05:30
.string()
.required("Sponsor Name is required")
.min(3, "Sponsor Name must be at least 3 characters long")
.max(50, "Sponsor Name cannot exceed 50 characters")
.matches(/^[^\d]+$/, "Sponsor Name cannot contain numbers"),
2024-09-17 15:33:27 +05:30
sponsorNameArabic: yup
.string()
.required("Sponser name in arabic is required"),
2024-08-13 13:46:41 +05:30
email: yup.string().email("Invalid email address").notRequired(),
2024-09-17 15:33:27 +05:30
// .test("emailValidity", "Email address is invalid", async function (value) {
// if (!value) {
// return true; // Allow if the field is empty
// }
// return await checkEmailValidity(value);
// }),
2024-06-24 12:08:21 +05:30
});
2024-07-24 19:57:31 +05:30
// ==================== [debounce] ========================
2024-06-25 20:35:03 +05:30
export function debounce(func, delay) {
let debounceTimer;
2024-07-01 12:47:47 +05:30
return function (...args) {
2024-06-25 20:35:03 +05:30
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(this, args), delay);
};
}
2024-06-27 18:46:12 +05:30
2024-06-24 12:08:21 +05:30
const AddSponser = () => {
2024-07-22 16:52:19 +05:30
const toast = useToast();
2024-07-19 18:36:47 +05:30
const params = useParams();
2024-06-25 20:35:03 +05:30
const navigate = useNavigate();
2024-07-24 19:57:31 +05:30
const id = params?.id;
2024-09-17 15:33:27 +05:30
// =====================[useState]=======================
2024-07-24 19:57:31 +05:30
2024-07-22 16:52:19 +05:30
const [isLoadingBtn, setIsLoadingBtn] = useState(false);
2024-07-24 19:57:31 +05:30
const [alert, setAlert] = useState(false);
const [form, setForm] = useState();
2024-08-14 18:48:25 +05:30
const [isSwitchOn, setIsSwitchOn] = useState(true);
2024-07-01 12:33:55 +05:30
2024-07-19 18:36:47 +05:30
const [createSponser] = useCreateSponserMutation();
const [updateSponser] = useUpdateSponserMutation();
2024-07-22 14:50:31 +05:30
2024-07-22 16:52:19 +05:30
// Fetch sponsor data only if id exists
2024-09-17 15:33:27 +05:30
const {
data: sponserByIdData,
error,
isLoading,
} = useGetSponserByIdQuery(id, { skip: !id });
2024-07-22 16:52:19 +05:30
2024-07-24 19:57:31 +05:30
// ======================== [validators] ===========================
2024-07-19 18:36:47 +05:30
2024-06-24 12:08:21 +05:30
const {
control,
2024-08-13 13:46:41 +05:30
watch,
2024-06-24 12:08:21 +05:30
handleSubmit,
formState: { errors },
2024-07-19 18:36:47 +05:30
reset,
2024-06-24 12:08:21 +05:30
} = useForm({
2024-07-01 12:33:55 +05:30
resolver: yupResolver(addSponser),
2024-06-24 12:08:21 +05:30
});
2024-09-17 15:33:27 +05:30
// ========================== [useEffect] ================================
2024-07-24 19:57:31 +05:30
2024-07-22 16:52:19 +05:30
useEffect(() => {
if (sponserByIdData?.data) {
reset({
sponsorName: sponserByIdData?.data?.sponsorName,
sponsorNameArabic: sponserByIdData?.data?.sponsorNameArabic,
email: sponserByIdData?.data?.email,
});
2024-09-17 15:33:27 +05:30
setIsSwitchOn(sponserByIdData?.data?.isActive);
2024-08-08 19:37:14 +05:30
console.log(sponserByIdData?.data?.isActive);
2024-07-22 16:52:19 +05:30
}
}, [sponserByIdData, reset]);
2024-07-01 12:33:55 +05:30
2024-08-08 19:37:14 +05:30
// console.log(isSwitchOn);
2024-07-24 19:57:31 +05:30
if (false) {
2024-07-19 18:36:47 +05:30
return <FullscreenLoaders />;
}
2024-07-03 12:13:09 +05:30
2024-07-24 19:57:31 +05:30
// ============================ [API]===============================
const handleConfirm = async () => {
setIsLoadingBtn(true);
const id = params?.id;
if (id) {
try {
const formData = {
...form,
2024-07-30 13:30:34 +05:30
isActive: isSwitchOn,
2024-09-17 15:33:27 +05:30
};
// Remove email field if it's an empty string
if (formData.email === "") {
delete formData.email;
}
2024-07-24 19:57:31 +05:30
await updateSponser({ data: formData, id }).then((response) => {
if (response?.data?.statusCode) {
toast({
render: () => <ToastBox message={response?.data?.message} />,
});
setIsLoadingBtn(false);
setAlert(false);
navigate("/sponser");
2024-09-17 15:33:27 +05:30
} else if (response?.error?.status === 400) {
2024-07-24 19:57:31 +05:30
toast({
render: () => (
2024-09-17 15:33:27 +05:30
<ToastBox
message={response?.error?.data?.message}
status={"error"}
/>
2024-07-24 19:57:31 +05:30
),
});
setIsLoadingBtn(false);
2024-09-17 15:33:27 +05:30
setAlert(false);
2024-07-24 19:57:31 +05:30
}
});
} catch (error) {
console.log(error);
setIsLoadingBtn(false);
navigate("/sponser");
}
} else {
try {
const formData = {
...form,
2024-07-30 13:30:34 +05:30
isActive: isSwitchOn,
2024-07-24 19:57:31 +05:30
};
await createSponser(formData).then((response) => {
console.log(response);
2024-09-17 15:33:27 +05:30
if (response?.data?.statusCode === 201) {
2024-07-24 19:57:31 +05:30
toast({
render: () => <ToastBox message={response?.data?.message} />,
});
setIsLoadingBtn(false);
navigate("/sponser");
2024-09-17 15:33:27 +05:30
} else if (response?.error?.status === 400) {
2024-07-24 19:57:31 +05:30
toast({
render: () => (
2024-09-17 15:33:27 +05:30
<ToastBox
message={response?.error?.data?.message}
status={"error"}
/>
2024-07-24 19:57:31 +05:30
),
});
setIsLoadingBtn(false);
2024-09-17 15:33:27 +05:30
setAlert(false);
2024-07-24 19:57:31 +05:30
}
});
} catch (error) {
console.log(error);
setIsLoadingBtn(false);
navigate("/sponser");
}
}
};
2024-09-17 15:33:27 +05:30
// ====================== [Update Form Object] =========================
2024-07-24 19:57:31 +05:30
2024-07-01 12:33:55 +05:30
const formFields = [
{
2024-08-14 18:48:25 +05:30
label: "Sponsor name (English)",
2024-07-19 18:36:47 +05:30
placeHolder: " ",
name: "sponsorName",
2024-07-03 12:13:09 +05:30
type: "text",
isRequired: true,
2024-08-14 18:48:25 +05:30
section: "",
2024-09-17 15:33:27 +05:30
maxLength: 50,
helperText: `Maximum length should be 50 characters. You have entered ${
watch()?.sponsorName?.length || 0
} characters.`,
2024-07-03 12:13:09 +05:30
},
{
2024-08-14 18:48:25 +05:30
label: "Sponsor name (Arabic)",
2024-07-19 18:36:47 +05:30
name: "sponsorNameArabic",
placeHolder: " ",
2024-07-01 12:33:55 +05:30
type: "text",
isRequired: true,
2024-08-14 18:48:25 +05:30
section: "",
2024-07-25 12:26:18 +05:30
arabic: true,
2024-07-24 19:57:31 +05:30
right: true,
2024-09-17 15:33:27 +05:30
maxLength: 55,
helperText: `Maximum length should be 55 characters. You have entered ${
watch()?.sponsorNameArabic?.length || 0
} characters.`,
2024-07-01 12:33:55 +05:30
},
{
2024-07-22 16:52:19 +05:30
label: "Email address",
name: "email",
2024-07-19 18:36:47 +05:30
placeHolder: " ",
2024-07-22 16:52:19 +05:30
type: "email",
// isRequired: true,
2024-08-14 18:48:25 +05:30
section: "",
2024-07-01 12:33:55 +05:30
},
2024-07-19 18:36:47 +05:30
];
2024-07-24 19:57:31 +05:30
// ==================== [Create Form Object] =======================
2024-07-19 18:36:47 +05:30
const formEditFields = [
2024-07-01 12:33:55 +05:30
{
2024-08-14 18:48:25 +05:30
label: "Sponsor name",
2024-07-19 18:36:47 +05:30
placeHolder: " ",
2024-07-24 19:57:31 +05:30
name: "sponsorName",
2024-07-03 12:13:09 +05:30
type: "text",
2024-07-01 12:33:55 +05:30
isRequired: true,
2024-08-14 18:48:25 +05:30
section: "",
2024-09-17 15:33:27 +05:30
maxLength: 55,
helperText: `Maximum length should be 55 characters. You have entered ${
watch()?.sponsorName?.length || 0
} characters.`,
2024-07-01 12:33:55 +05:30
},
{
2024-08-14 18:48:25 +05:30
label: "Sponsor name (Arabic)",
2024-07-19 18:36:47 +05:30
name: "sponsorNameArabic",
placeHolder: " ",
2024-07-01 12:33:55 +05:30
type: "text",
isRequired: true,
2024-08-14 18:48:25 +05:30
section: "",
2024-07-25 12:26:18 +05:30
arabic: true,
2024-09-17 15:33:27 +05:30
maxLength: 55,
helperText: `Maximum length should be 55 characters. You have entered ${
watch()?.sponsorNameArabic?.length || 0
} characters.`,
2024-07-01 12:33:55 +05:30
},
{
2024-07-22 16:52:19 +05:30
label: "Email adress",
name: "email",
2024-07-19 18:36:47 +05:30
placeHolder: " ",
2024-07-22 16:52:19 +05:30
type: "email",
// isRequired: true,
2024-08-14 18:48:25 +05:30
section: "",
2024-07-03 12:13:09 +05:30
},
2024-07-01 12:33:55 +05:30
];
2024-09-17 15:33:27 +05:30
// ====================== [Group Create Fields] =========================
2024-07-24 19:57:31 +05:30
2024-07-19 18:36:47 +05:30
const groupedEditFields = formEditFields.reduce((groups, field) => {
const { section } = field;
if (!groups[section]) {
groups[section] = [];
}
groups[section].push(field);
return groups;
}, {});
2024-07-24 19:57:31 +05:30
// ====================== [Group Update Fields] =======================
2024-07-01 12:33:55 +05:30
const groupedFields = formFields.reduce((groups, field) => {
const { section } = field;
if (!groups[section]) {
groups[section] = [];
}
groups[section].push(field);
return groups;
}, {});
2024-07-24 19:57:31 +05:30
// ==================== [On Submit] ========================
2024-07-22 16:52:19 +05:30
2024-07-24 19:57:31 +05:30
const onSubmit = async (data) => {
if (Object.keys(errors).length === 0) {
setForm(data);
setAlert(true);
2024-07-19 18:36:47 +05:30
}
2024-06-24 12:08:21 +05:30
};
2024-09-17 15:33:27 +05:30
return isLoading ? (
<FullscreenLoaders />
) : (
2024-06-24 12:08:21 +05:30
<Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={14}>
2024-09-17 15:33:27 +05:30
{/* ===================== [Switch Button] ======================== */}
2024-09-19 16:45:05 +05:30
<Box display={"flex"} justifyContent={"space-between"} alignItems={"center"} mt={5} px={4}>
<Text fontSize={"sm"} mb={0} onClick={() => navigate(-1)} cursor={"pointer"}>
<ArrowBackIcon fontSize={"xl"} me={2} />Add Details
</Text>
2024-07-29 12:20:40 +05:30
<SwitchButton isSwitchOn={isSwitchOn} setIsSwitchOn={setIsSwitchOn} />
2024-08-09 12:24:29 +05:30
</Box>
2024-08-08 19:37:14 +05:30
2024-07-24 19:57:31 +05:30
{/* ====================== [Form Input] ====================== */}
2024-07-03 12:13:09 +05:30
<FormInputMain
2024-07-19 18:36:47 +05:30
groupedFields={params?.id ? groupedEditFields : groupedFields}
2024-07-03 12:13:09 +05:30
control={control}
errors={errors}
onSubmit={handleSubmit(onSubmit)}
2024-07-22 16:52:19 +05:30
submitTitle={params?.id ? "Update" : "Submit"}
2024-07-24 19:57:31 +05:30
></FormInputMain>
2024-09-17 15:33:27 +05:30
2024-07-24 19:57:31 +05:30
{/* ======================= [Modal] =========================== */}
<CustomAlertDialog
isOpen={alert}
onClose={() => setAlert(false)}
alertHandler={handleConfirm}
2024-10-24 19:05:52 +05:30
message={id ? "Are you sure you want to update this?" : "Are you sure you want to add this?"}
2024-07-24 19:57:31 +05:30
isLoading={isLoadingBtn}
2024-07-03 12:13:09 +05:30
/>
2024-08-09 12:24:29 +05:30
2024-09-17 15:33:27 +05:30
{/* <DummyComponent /> */}
2024-07-03 12:13:09 +05:30
</Box>
2024-06-24 12:08:21 +05:30
);
};
export default AddSponser;