352 lines
9.5 KiB
JavaScript
352 lines
9.5 KiB
JavaScript
import { ArrowBackIcon } from "@chakra-ui/icons";
|
|
import { Box, Text, useToast } from "@chakra-ui/react";
|
|
import { yupResolver } from "@hookform/resolvers/yup";
|
|
import React, { useEffect, useState } from "react";
|
|
import { useForm } from "react-hook-form";
|
|
import { useNavigate, useParams } from "react-router-dom";
|
|
import * as yup from "yup";
|
|
import CustomAlertDialog from "../../Components/CustomAlertDialog";
|
|
import FormInputMain from "../../Components/FormInputMain";
|
|
import FullscreenLoaders from "../../Components/Loaders/FullscreenLoaders";
|
|
import RoleSwitchButton from "../../Components/RoleSwitchButton";
|
|
import ToastBox from "../../Components/ToastBox";
|
|
import {
|
|
isMaker
|
|
} from "../../Constants/Constants";
|
|
import { OPACITY_ON_LOAD } from "../../Layout/animations";
|
|
import {
|
|
useCreateSubAdminMutation,
|
|
useGetSubAdminByIdQuery,
|
|
useUpdateSubAdminMutation,
|
|
} from "../../Services/subadmin.service";
|
|
// ======================= [validation] =========================
|
|
const addSubAdminSchema = yup.object().shape({
|
|
firstName: yup
|
|
.string()
|
|
.required("First Name is required dcdcdcd")
|
|
.min(3, "First Name must be at least 3 characters long")
|
|
.max(35, "First Name cannot exceed 35 characters")
|
|
.matches(/^[^\d]+$/, "First Name cannot contain numbers"),
|
|
|
|
lastName: yup.string().required("Last Name is required"),
|
|
emailAddress:yup.
|
|
string()
|
|
.required("Email address is required")
|
|
.min(6, "Email address must be at least 6 characters long")
|
|
.max(255, "Email address can be at most 255 characters long"),
|
|
});
|
|
|
|
// ==================== [debounce] ========================
|
|
|
|
export function debounce(func, delay) {
|
|
let debounceTimer;
|
|
return function (...args) {
|
|
clearTimeout(debounceTimer);
|
|
debounceTimer = setTimeout(() => func.apply(this, args), delay);
|
|
};
|
|
}
|
|
|
|
const SubAdminUpdateCreate = () => {
|
|
const toast = useToast();
|
|
const params = useParams();
|
|
const navigate = useNavigate();
|
|
const id = params?.id;
|
|
|
|
// =====================[useState]=======================
|
|
|
|
const [isLoadingBtn, setIsLoadingBtn] = useState(false);
|
|
const [alert, setAlert] = useState(false);
|
|
const [form, setForm] = useState();
|
|
const [isSwitchOn, setIsSwitchOn] = useState(false);
|
|
|
|
const [createSubAdmin] = useCreateSubAdminMutation();
|
|
const [updateSubAdmin] = useUpdateSubAdminMutation();
|
|
|
|
// Fetch sponsor data only if id exists
|
|
const { data: subAdminByIdData, isLoading } = useGetSubAdminByIdQuery(id, {
|
|
skip: !id,
|
|
});
|
|
|
|
// ======================== [validators] ===========================
|
|
|
|
const {
|
|
control,
|
|
watch,
|
|
handleSubmit,
|
|
formState: { errors },
|
|
reset,
|
|
} = useForm({
|
|
resolver: yupResolver(addSubAdminSchema),
|
|
mode: "all",
|
|
});
|
|
|
|
// ========================== [useEffect] ================================
|
|
|
|
useEffect(() => {
|
|
if (subAdminByIdData?.data) {
|
|
reset({
|
|
firstName: subAdminByIdData?.data?.firstName,
|
|
lastName: subAdminByIdData?.data?.lastName,
|
|
emailAddress: subAdminByIdData?.data?.emailAddress,
|
|
});
|
|
setIsSwitchOn(isMaker(subAdminByIdData?.data?.role[0]?.role));
|
|
}
|
|
}, [subAdminByIdData, reset]);
|
|
|
|
if (isLoading) {
|
|
return <FullscreenLoaders />;
|
|
}
|
|
|
|
// ============================ [API]===============================
|
|
|
|
const handleConfirm = async () => {
|
|
setIsLoadingBtn(true);
|
|
const id = params?.id;
|
|
console.log(isSwitchOn);
|
|
|
|
if (id) {
|
|
try {
|
|
const formData = {
|
|
...form,
|
|
role_xid: !isSwitchOn ? 2 : 1,
|
|
};
|
|
await updateSubAdmin({ data: formData, id }).then((response) => {
|
|
if (response?.data?.statusCode) {
|
|
toast({
|
|
render: () => <ToastBox message={response?.data?.message} />,
|
|
});
|
|
|
|
setIsLoadingBtn(false);
|
|
setAlert(false);
|
|
navigate("/subadmin");
|
|
} else if (response?.error?.status === 400) {
|
|
toast({
|
|
render: () => (
|
|
<ToastBox
|
|
message={response?.error?.data?.message}
|
|
status={"error"}
|
|
/>
|
|
),
|
|
});
|
|
|
|
setIsLoadingBtn(false);
|
|
setAlert(false);
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.log(error);
|
|
setIsLoadingBtn(false);
|
|
navigate("/subadmin");
|
|
}
|
|
} else {
|
|
try {
|
|
const formData = {
|
|
...form,
|
|
role_xid: isSwitchOn ? 1 : 2,
|
|
};
|
|
await createSubAdmin(formData).then((response) => {
|
|
console.log(response);
|
|
if (response?.data?.statusCode === 201) {
|
|
toast({
|
|
render: () => <ToastBox message={response?.data?.message} />,
|
|
});
|
|
|
|
setIsLoadingBtn(false);
|
|
navigate("/subadmin");
|
|
} else if (response?.error?.status === 400) {
|
|
toast({
|
|
render: () => (
|
|
<ToastBox
|
|
message={response?.error?.data?.message}
|
|
status={"error"}
|
|
/>
|
|
),
|
|
});
|
|
|
|
setIsLoadingBtn(false);
|
|
setAlert(false);
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.log(error);
|
|
|
|
setIsLoadingBtn(false);
|
|
navigate("/subadmin");
|
|
}
|
|
}
|
|
};
|
|
|
|
// ====================== [Update Form Object] =========================
|
|
|
|
const formFields = [
|
|
{
|
|
label: "First Name",
|
|
placeHolder: " ",
|
|
name: "firstName",
|
|
type: "text",
|
|
isRequired: true,
|
|
section: "",
|
|
maxLength: 34,
|
|
helperText: `Maximum length should be 34 characters. You have entered ${
|
|
watch()?.firstName?.length || 0
|
|
} characters.`,
|
|
},
|
|
{
|
|
label: "Last Name",
|
|
name: "lastName",
|
|
placeHolder: " ",
|
|
type: "text",
|
|
isRequired: true,
|
|
section: "",
|
|
maxLength: 34,
|
|
helperText: `Maximum length should be 34 characters. You have entered ${
|
|
watch()?.lastName?.length || 0
|
|
} characters.`,
|
|
},
|
|
{
|
|
label: "Email address",
|
|
name: "emailAddress",
|
|
placeHolder: " ",
|
|
type: "email",
|
|
isRequired: true,
|
|
section: "",
|
|
},
|
|
];
|
|
|
|
// ==================== [Create Form Object] =======================
|
|
|
|
const formEditFields = [
|
|
{
|
|
label: "First Name",
|
|
placeHolder: " ",
|
|
name: "firstName",
|
|
type: "text",
|
|
isRequired: true,
|
|
section: "",
|
|
maxLength: 34,
|
|
helperText: `Maximum length should be 35 characters. You have entered ${
|
|
watch()?.firstName?.length || 0
|
|
} characters.`,
|
|
},
|
|
{
|
|
label: "Last Name",
|
|
name: "lastName",
|
|
placeHolder: " ",
|
|
type: "text",
|
|
isRequired: true,
|
|
section: "",
|
|
maxLength: 34,
|
|
helperText: `Maximum length should be 35 characters. You have entered ${
|
|
watch()?.lastName?.length || 0
|
|
} characters.`,
|
|
},
|
|
{
|
|
label: "Email Address",
|
|
name: "emailAddress",
|
|
placeHolder: " ",
|
|
type: "email",
|
|
isRequired: true,
|
|
section: "",
|
|
},
|
|
];
|
|
|
|
// ====================== [Group Create Fields] =========================
|
|
|
|
const groupedEditFields = formEditFields.reduce((groups, field) => {
|
|
const { section } = field;
|
|
if (!groups[section]) {
|
|
groups[section] = [];
|
|
}
|
|
groups[section].push(field);
|
|
return groups;
|
|
}, {});
|
|
|
|
// ====================== [Group Update Fields] =======================
|
|
|
|
const groupedFields = formFields.reduce((groups, field) => {
|
|
const { section } = field;
|
|
if (!groups[section]) {
|
|
groups[section] = [];
|
|
}
|
|
groups[section].push(field);
|
|
return groups;
|
|
}, {});
|
|
|
|
// ==================== [On Submit] ========================
|
|
// console.log(errors);
|
|
|
|
const onSubmit = async (data) => {
|
|
console.log("Hit");
|
|
|
|
if (Object.keys(errors).length === 0) {
|
|
setForm(data);
|
|
setAlert(true);
|
|
}
|
|
};
|
|
|
|
return isLoading ? (
|
|
<FullscreenLoaders />
|
|
) : (
|
|
<Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={14}>
|
|
{/* ===================== [Switch Button] ======================== */}
|
|
<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} />
|
|
{params?.id ? "Edit Details" : "Add Details"}
|
|
</Text>
|
|
{/* {params?.id ? (
|
|
""
|
|
) : (
|
|
<RoleSwitchButton
|
|
isSwitchOn={isSwitchOn}
|
|
setIsSwitchOn={setIsSwitchOn}
|
|
/>
|
|
)} */}
|
|
<RoleSwitchButton
|
|
isSwitchOn={isSwitchOn}
|
|
setIsSwitchOn={setIsSwitchOn}
|
|
/>
|
|
</Box>
|
|
|
|
{/* ====================== [Form Input] ====================== */}
|
|
|
|
<FormInputMain
|
|
groupedFields={params?.id ? groupedEditFields : groupedFields}
|
|
control={control}
|
|
errors={errors}
|
|
onSubmit={handleSubmit(onSubmit)}
|
|
submitTitle={params?.id ? "Update" : "Submit"}
|
|
></FormInputMain>
|
|
|
|
{/* ======================= [Modal] =========================== */}
|
|
|
|
<CustomAlertDialog
|
|
isOpen={alert}
|
|
onClose={() => setAlert(false)}
|
|
alertHandler={handleConfirm}
|
|
message={
|
|
id
|
|
? "Are you sure you want to update this?"
|
|
: "Are you sure you want to add this?"
|
|
}
|
|
isLoading={isLoadingBtn}
|
|
/>
|
|
|
|
{/* <DummyComponent /> */}
|
|
</Box>
|
|
);
|
|
};
|
|
|
|
export default SubAdminUpdateCreate;
|