From 2d15461f864705c07240d5866cbb287a8e8e0db4 Mon Sep 17 00:00:00 2001 From: rockyeverlast Date: Mon, 17 Mar 2025 20:31:52 +0530 Subject: [PATCH] Working on subadmin update and add post --- dev-dist/sw.js | 2 +- src/Pages/ManageCMS/FAQ/FAQ.tsx | 46 ++- src/Pages/ManageGroups/ManageGroups.tsx | 12 +- src/Pages/ManageJobs/ManageJobs.tsx | 12 +- src/Pages/ManagePost/ManagePost.tsx | 12 +- .../RegisterUsers/RegisterUsers.tsx | 12 +- .../TemplateMaster/EditTemplateModel.tsx | 31 +- src/Pages/SubAdmin/SubAdmin.tsx | 156 +++++---- src/Pages/SubAdmin/ViewSubAdmin.tsx | 322 ++++++++++-------- src/Redux/Service/manage.subadmin.service.ts | 103 +++++- src/components/ActionIcons/Delete.tsx | 3 +- src/components/AlertDailog.tsx | 7 + src/components/EditSubAdmin.tsx | 179 +++++++++- 13 files changed, 608 insertions(+), 289 deletions(-) diff --git a/dev-dist/sw.js b/dev-dist/sw.js index 0a6dd31..8da00cf 100644 --- a/dev-dist/sw.js +++ b/dev-dist/sw.js @@ -82,7 +82,7 @@ define(['./workbox-54d0af47'], (function (workbox) { 'use strict'; "revision": "3ca0b8505b4bec776b69afdba2768812" }, { "url": "index.html", - "revision": "0.n8f1c1adqh8" + "revision": "0.7aakaijcn38" }], {}); workbox.cleanupOutdatedCaches(); workbox.registerRoute(new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), { diff --git a/src/Pages/ManageCMS/FAQ/FAQ.tsx b/src/Pages/ManageCMS/FAQ/FAQ.tsx index 3d9f8b4..cb93fa1 100644 --- a/src/Pages/ManageCMS/FAQ/FAQ.tsx +++ b/src/Pages/ManageCMS/FAQ/FAQ.tsx @@ -12,6 +12,7 @@ import { useEffect, useState } from "react"; import { FaqData, useDeleteFaqPostMutation, useFaqToggleMutation, useGetFaqQuery } from "../../../Redux/Service/faqs.service"; import SearchComponent from "../../../components/SearchComponent"; import NoData from "../../../components/NoData"; +import { Toaster, toaster } from "../../../components/ui/toaster"; // table data @@ -56,6 +57,7 @@ const FAQ = () => { const [faqToggle] = useFaqToggleMutation() const [deleteFaqPost] = useDeleteFaqPostMutation() const [searchTerm, setSearchTerm] = useState(""); + const [deleteModal, setDeleteModal] = useState(true) // console.log('DATA', data?.data); @@ -89,11 +91,23 @@ const FAQ = () => { const handleDeleteFaq = async (faqId: number) => { try { const response = await deleteFaqPost(faqId).unwrap(); - refetch() - console.log("FAQ deleted successfully:", response); + if (response.success) { + toaster.create({ + title: "Success", + description: "FAQ deleted successfully", + type: "success", + }); + refetch() + console.log("FAQ deleted successfully:", response); + } // Optionally, refetch data or update state after deletion } catch (error) { console.error("Error deleting FAQ:", error); + toaster.create({ + title: "Error", + description: "Something went wrong", + type: "error", + }); } }; @@ -113,12 +127,15 @@ const FAQ = () => { } - alertText="Delete Users" + isOpen={deleteModal} + AltertTiggerIcon={() => setDeleteModal(true)} />} + alertText="Delete FAQ" alertIcon={} alertCaption="are you sure you want to delete ?" + onClose={() => setDeleteModal(false)} onConfirm={() => { // console.log("User deleted:", index + 1); + setDeleteModal(false); handleDeleteFaq(agency.id) }} /> @@ -156,26 +173,6 @@ const FAQ = () => { - {/* - } - color={"#000"} - > - - */} { refetch={refetch} />} + ) } diff --git a/src/Pages/ManageGroups/ManageGroups.tsx b/src/Pages/ManageGroups/ManageGroups.tsx index 049db8a..86f0570 100644 --- a/src/Pages/ManageGroups/ManageGroups.tsx +++ b/src/Pages/ManageGroups/ManageGroups.tsx @@ -1,14 +1,16 @@ -import { Box, HStack, Image, Input, Text } from "@chakra-ui/react"; +import { Box, HStack, + // Image, + Input, Text } from "@chakra-ui/react"; import MainFrame from "../../components/MainFrame"; import { InputGroup } from "../../components/ui/input-group"; import { LuSearch } from "react-icons/lu"; import DataTable from "../../components/DataTable"; -import AlertDailog from "../../components/AlertDailog"; +// import AlertDailog from "../../components/AlertDailog"; // import { RiDeleteBin5Line } from "react-icons/ri"; import ViewManageGroup from "./ViewManageGroup"; import EditDetailGroups from "./EditDetailGroup"; import AddGroup from "./AddGroup"; -import Delete from "../../components/ActionIcons/Delete"; +// import Delete from "../../components/ActionIcons/Delete"; // import ViewSubAdmin from "./ViewSubAdmin" // table data @@ -33,7 +35,7 @@ const managepost: any[] = [ - } alertText="Delete Users" alertIcon={} @@ -41,7 +43,7 @@ const managepost: any[] = [ onConfirm={() => { console.log("User deleted:", i + 1); }} - /> + /> */} ), })), diff --git a/src/Pages/ManageJobs/ManageJobs.tsx b/src/Pages/ManageJobs/ManageJobs.tsx index c013b65..2daf901 100644 --- a/src/Pages/ManageJobs/ManageJobs.tsx +++ b/src/Pages/ManageJobs/ManageJobs.tsx @@ -1,13 +1,15 @@ -import { Box, HStack, Image, Input, Text } from "@chakra-ui/react"; +import { Box, HStack, + // Image, + Input, Text } from "@chakra-ui/react"; import { LuSearch } from "react-icons/lu"; // import { RiDeleteBin5Line } from "react-icons/ri"; -import AlertDailog from "../../components/AlertDailog"; +// import AlertDailog from "../../components/AlertDailog"; import DataTable from "../../components/DataTable"; import MainFrame from "../../components/MainFrame"; import { InputGroup } from "../../components/ui/input-group"; import ManageJobsAdd from "./ManageJobsAdd"; import ViewManageJob from "./ViewManageJob"; -import Delete from "../../components/ActionIcons/Delete"; +// import Delete from "../../components/ActionIcons/Delete"; // table data @@ -33,7 +35,7 @@ const managepost: any[] = [ - } alertText="Delete Users" alertIcon={} @@ -41,7 +43,7 @@ const managepost: any[] = [ onConfirm={() => { console.log("User deleted:", i + 1); }} - /> + /> */} ), })), diff --git a/src/Pages/ManagePost/ManagePost.tsx b/src/Pages/ManagePost/ManagePost.tsx index 4171718..c9e5dd2 100644 --- a/src/Pages/ManagePost/ManagePost.tsx +++ b/src/Pages/ManagePost/ManagePost.tsx @@ -1,14 +1,16 @@ -import { Box, HStack, Image, Input, Span, Text } from "@chakra-ui/react"; +import { Box, HStack, Image, Input, + // Span, + Text } from "@chakra-ui/react"; import MainFrame from "../../components/MainFrame"; import { InputGroup } from "../../components/ui/input-group"; import { LuSearch } from "react-icons/lu"; import DataTable from "../../components/DataTable"; -import AlertDailog from "../../components/AlertDailog"; +// import AlertDailog from "../../components/AlertDailog"; import { Switch } from "../../components/ui/switch"; import img from "../../assets/waterfall.jpg"; // import { RiDeleteBin5Line } from "react-icons/ri"; import ViewDailog from "./ViewDailog"; -import Delete from "../../components/ActionIcons/Delete"; +// import Delete from "../../components/ActionIcons/Delete"; // import ViewDailog from './ViewDailog' // table data @@ -46,7 +48,7 @@ const managepost: any[] = [ Action: ( - } alertText="Delete Users" alertIcon={} @@ -54,7 +56,7 @@ const managepost: any[] = [ onConfirm={() => { console.log("User deleted:", i + 1); }} - /> + /> */} ), })), diff --git a/src/Pages/ManageUsers/RegisterUsers/RegisterUsers.tsx b/src/Pages/ManageUsers/RegisterUsers/RegisterUsers.tsx index 086c0e0..ce674f1 100644 --- a/src/Pages/ManageUsers/RegisterUsers/RegisterUsers.tsx +++ b/src/Pages/ManageUsers/RegisterUsers/RegisterUsers.tsx @@ -1,6 +1,8 @@ -import { Box, HStack, Image, Input, Text } from "@chakra-ui/react"; +import { Box, HStack, + // Image, + Input, Text } from "@chakra-ui/react"; import MainFrame from "../../../components/MainFrame"; -import AlertDailog from "../../../components/AlertDailog"; +// import AlertDailog from "../../../components/AlertDailog"; // import { RiDeleteBin5Line } from "react-icons/ri"; import DataTable from "../../../components/DataTable"; import { Switch } from "../../../components/ui/switch"; @@ -9,7 +11,7 @@ import { LuSearch } from "react-icons/lu"; import ViewRegisterUsers from "./ViewRegisterUsers"; import EditRegisterUsers from "./EditRegisterUsers"; import AddRegisterUsers from "./AddRegisterUsers"; -import Delete from "../../../components/ActionIcons/Delete"; +// import Delete from "../../../components/ActionIcons/Delete"; const tableHeadRow = [ "Sr. No", @@ -42,7 +44,7 @@ const registerUser: any[] = [ {/* */} - } // Pass as function alertText="Delete Users" alertIcon={} @@ -50,7 +52,7 @@ const registerUser: any[] = [ onConfirm={() => { console.log("User deleted:", i + 1); }} - /> + /> */} ), })), diff --git a/src/Pages/MasterModule/TemplateMaster/EditTemplateModel.tsx b/src/Pages/MasterModule/TemplateMaster/EditTemplateModel.tsx index 85cccd8..dfe49c4 100644 --- a/src/Pages/MasterModule/TemplateMaster/EditTemplateModel.tsx +++ b/src/Pages/MasterModule/TemplateMaster/EditTemplateModel.tsx @@ -22,10 +22,10 @@ import { Toaster, toaster } from "../../../components/ui/toaster"; import { Template } from "../../../Redux/Service/template.master.service"; import axios from "axios"; -// const IMGURL = import.meta.env.VITE_IMG_TEMPLATES +const IMGURL = import.meta.env.VITE_IMG_TEMPLATES const APIURL = import.meta.env.VITE_API_URL -function EditTemplateModel({ id, localData, refetch }: { id: number, localData: any, refetch:VoidFunction }) { +function EditTemplateModel({ id, localData, refetch }: { id: number, localData: any, refetch: VoidFunction }) { const [title, setTitle] = useState(""); const [subTitle, setSubTitle] = useState(""); const [userType, setUserType] = useState(""); @@ -63,8 +63,8 @@ function EditTemplateModel({ id, localData, refetch }: { id: number, localData: setUserType(template.principle_type_xid?.toString() || ""); // Convert image URLs to File objects if needed - // const templateImages = template.post_template_image.map((img: any) => `${IMGURL}${img.image_name}`); - // setImages(templateImages); + const templateImages = template.post_template_image.map((img: any) => `${IMGURL}${img.image_name}`); + setImages(templateImages); setIsOpen(true); } @@ -90,7 +90,9 @@ function EditTemplateModel({ id, localData, refetch }: { id: number, localData: return; } - if (images.length === 0) { + const newImages = images.filter((image) => image instanceof File); + + if (newImages.length === 0) { toaster.create({ title: "Error", description: "Please upload at least one image.", @@ -105,14 +107,8 @@ function EditTemplateModel({ id, localData, refetch }: { id: number, localData: formData.append("title", title); formData.append("sub_title", subTitle); - images.forEach((image, index) => { - if (typeof image === "string") { - // Append existing image URLs - formData.append(`existing_images[${index}]`, image); - } else { - // Append new image files - formData.append(`new_images[${index}]`, image, image.name); - } + newImages.forEach((image, index) => { + formData.append(`image_name[${index}]`, image, image.name); }); try { @@ -130,7 +126,11 @@ function EditTemplateModel({ id, localData, refetch }: { id: number, localData: refetch() } catch (error) { console.error("Error updating template:", error); - alert("Failed to update template"); + toaster.create({ + title: "Error", + description: "Failed to update template. Please try again.", + type: "error", + }); } }; @@ -283,6 +283,9 @@ function EditTemplateModel({ id, localData, refetch }: { id: number, localData: + + + {/* */} diff --git a/src/Pages/SubAdmin/SubAdmin.tsx b/src/Pages/SubAdmin/SubAdmin.tsx index fa05266..0757fca 100644 --- a/src/Pages/SubAdmin/SubAdmin.tsx +++ b/src/Pages/SubAdmin/SubAdmin.tsx @@ -3,14 +3,15 @@ import MainFrame from "../../components/MainFrame" import { InputGroup } from "../../components/ui/input-group" import { LuSearch } from "react-icons/lu" import DataTable from "../../components/DataTable" -import AlertDailog from "../../components/AlertDailog" +import AlertDailog from "../../components/AlertDailog"; // import { RiDeleteBin5Line } from "react-icons/ri"; import AddModel from "./AddModel" import EditSubAdmin from "../../components/EditSubAdmin" import ViewSubAdmin from "./ViewSubAdmin" import Delete from "../../components/ActionIcons/Delete" -// import { useGetSubAdminQuery } from "../../Redux/Service/manage.subadmin.service" -// import { useEffect, useState } from "react" +import { useDeleteSubAdminPostMutation, useGetSubAdminQuery } from "../../Redux/Service/manage.subadmin.service" +import { useEffect, useState } from "react" +import { toaster } from "../../components/ui/toaster" // table data @@ -25,73 +26,110 @@ const tableHeadRow = [ "Action", ]; -const managepost: any[] = [ - ...Array.from({ length: 12 }, (_, i) => ({ - "Sr. No": i + 1, - "Id": 12565, - "First Name": "Kamlesh", - "last Name": "Pandey", - "DOB": "12/01/1987", - "Gender": "Male", +// const managepost: any[] = [ +// ...Array.from({ length: 12 }, (_, i) => ({ +// "Sr. No": i + 1, +// "Id": 12565, +// "First Name": "Kamlesh", +// "last Name": "Pandey", +// "DOB": "12/01/1987", +// "Gender": "Male", +// "Action": ( +// + +// +// + +// } +// alertText="Delete Users" +// alertIcon={} +// alertCaption="are you sure you want to delete ?" +// onConfirm={() => { +// console.log("User deleted:", i + 1); +// }} +// /> +// +// ), +// })), +// ]; + +const SubAdmin = () => { + const { data, refetch } = useGetSubAdminQuery() + const [localData, setLocalData] = useState([]); + const [deleteModal, setDeleteModal] = useState(false) + const [deleteSubAdminPost] = useDeleteSubAdminPostMutation() + + useEffect(() => { + if (data?.data.data) { + setLocalData(data?.data.data); + } + }, [data]); + + console.log('localData', localData); + + const handleDeleteFaq = async (faqId: number) => { + try { + const response = await deleteSubAdminPost(faqId).unwrap(); + if (response.success) { + toaster.create({ + title: "Success", + description: "FAQ deleted successfully", + type: "success", + }); + refetch() + console.log("FAQ deleted successfully:", response); + } + // Optionally, refetch data or update state after deletion + } catch (error) { + console.error("Error deleting FAQ:", error); + toaster.create({ + title: "Error", + description: "Something went wrong", + type: "error", + }); + } + }; + + const formatDateOfBirth = (dob: string): string => { + return new Date(dob).toLocaleDateString("en-GB", { + day: "2-digit", + month: "2-digit", + year: "numeric", + }); + }; + + const managepost = localData?.map((agency: any, index: number) => ({ + 'id': agency.id, + "Sr. No": index + 1, + "Id": agency.unique_id, + "First Name": agency.first_name, + "last Name": agency.last_name, + "DOB": formatDateOfBirth(agency.date_of_birth), + "Gender": agency.gender, + "Action": ( - - - + {/* */} + + } - alertText="Delete Users" + isOpen={deleteModal} + AltertTiggerIcon={() => setDeleteModal(prev => !prev)} />} + alertText="Delete FAQ" alertIcon={} alertCaption="are you sure you want to delete ?" + onClose={() => setDeleteModal(false)} onConfirm={() => { - console.log("User deleted:", i + 1); + // console.log("User deleted:", index + 1); + setDeleteModal(false); + handleDeleteFaq(agency.id) }} /> ), - })), -]; - -const SubAdmin = () => { - // const { data, refetch } = useGetSubAdminQuery() - // const [localData, setLocalData] = useState([]); - - // useEffect(() => { - // if (data?.data) { - // setLocalData(data?.data); - // } - // }, [data]); - - - // const managepost = localData?.map((agency: any, index: number) => ({ - // 'id': agency.id, - // "Sr. No": index + 1, - // "Id": 12565, - // "First Name": "Kamlesh", - // "last Name": "Pandey", - // "DOB": "12/01/1987", - // "Gender": "Male", - - // "Action": ( - // - // {/* */} - // - // - - // } - // alertText="Delete Users" - // alertIcon={} - // alertCaption="are you sure you want to delete ?" - // onConfirm={() => { - // // console.log("User deleted:", index + 1); - // // handleDeleteFaq(agency.id) - // }} - // /> - // - // ), - // })); + })); return ( diff --git a/src/Pages/SubAdmin/ViewSubAdmin.tsx b/src/Pages/SubAdmin/ViewSubAdmin.tsx index d928f10..55840a7 100644 --- a/src/Pages/SubAdmin/ViewSubAdmin.tsx +++ b/src/Pages/SubAdmin/ViewSubAdmin.tsx @@ -14,7 +14,6 @@ import { Grid, Heading, Input, - Span, Stack, Text, } from "@chakra-ui/react"; @@ -22,164 +21,195 @@ import { Checkbox } from "../../components/ui/checkbox"; // import { MdOutlineRemoveRedEye } from "react-icons/md"; // import { FaRegEdit } from "react-icons/fa"; import View from "../../components/ActionIcons/View"; -import { useGetSubAdminQuery } from "../../Redux/Service/manage.subadmin.service"; -function ViewSubAdmin() { - const { data} = useGetSubAdminQuery(); - console.log('data', data); - +import { Button } from "../../components/ui/button"; +import { useLazyViewSubAdminQuery } from "../../Redux/Service/manage.subadmin.service"; + +function ViewSubAdmin({ id }: { id: number }) { + const [trigger, { data }] = useLazyViewSubAdminQuery(); + + const handleView = () => { + trigger(id) + } + + const viewSubAdmin = data?.data + + const formatDateOfBirth = (dob: string): string => { + return new Date(dob).toLocaleDateString("en-GB", { + day: "2-digit", + month: "2-digit", + year: "numeric", + }); + }; + + console.log('data', data?.data); return ( - + - - - - View Sub Admin Account - - + {viewSubAdmin?.map((data: any) => ( + + + + View Sub Admin Account + + - - - - - First Name - - + + + + + First Name + + - - Last Name - - + + Last Name + + - - ID - - + + ID + + - - DOB - - + + DOB + + - - Gender - - - - Permissions - - - - - Dashboard - - - {" "} - Manage contact us - - - {" "} - manage User - - - {" "} - Manage CMS - - - {" "} - Manage Post - - - {" "} - Manage Reports - - - {" "} - manage Sub-Admin - - - {" "} - My profile - - - Manage Jobs{" "} - - - manage feedbacks - - - Manage community{" "} - - - Notification - - - - - - {/* */} - + - - + + + ))} ); } diff --git a/src/Redux/Service/manage.subadmin.service.ts b/src/Redux/Service/manage.subadmin.service.ts index 089be87..d10fbe6 100644 --- a/src/Redux/Service/manage.subadmin.service.ts +++ b/src/Redux/Service/manage.subadmin.service.ts @@ -1,17 +1,86 @@ import { createApi } from "@reduxjs/toolkit/query/react"; import { baseQueryWithReauth } from "./apiSlice"; - - -export type SubAdminPost = { - id: number; - first_name: string, - last_name: string, - unique_id: string, - date_of_birth: string, - gender: string, +interface PaginationLink { + url: string | null; + label: string; + active: boolean; } +interface UserData { + id: number; + unique_id: string; + user_name: string; + first_name: string; + last_name: string; + date_of_birth: string; + gender: string; +} + +interface PaginatedData { + current_page: number; + data: UserData[]; + first_page_url: string; + from: number; + last_page: number; + last_page_url: string; + links: PaginationLink[]; + next_page_url: string | null; + path: string; + per_page: number; + prev_page_url: string | null; + to: number; + total: number; +} + +interface ApiResponse { + status: string; + status_code: number; + message: string; + data: PaginatedData; +} + + +// export type SubAdminPost = { +// id: number; +// first_name: string, +// last_name: string, +// unique_id: string, +// date_of_birth: string, +// gender: string, +// } + +interface ResourceActionLink { + id: number; + principal_xid: number; + role_xid: number; + app_resource_xid: number; + is_active: boolean; + created_by: number | null; + modified_by: number | null; + deleted_at: string | null; + created_at: string; + updated_at: string; +} + +interface SubAdmin { + id: number; + first_name: string; + last_name: string; + unique_id: string; + date_of_birth: string; + gender: string; + get_resource_action_link: ResourceActionLink[]; +} + +interface SubAdminView { + status: string; + status_code: number; + message: string; + data: SubAdmin[]; +} + + export const manageSubAdmin = createApi({ reducerPath: "manageSubAdmin", baseQuery: baseQueryWithReauth, // Use enhanced baseQuery with error handling @@ -24,12 +93,17 @@ export const manageSubAdmin = createApi({ body: data, }), }), - getSubAdmin: builder.query({ + getSubAdmin: builder.query({ query: () => `/sub-admin` }), - updateFaq: builder.mutation({ + + viewSubAdmin: builder.query({ + query: (id) => `/sub-admin-view/${id}` + }), + + updateSubAdmin: builder.mutation({ query: (updatedData) => ({ - url: "/faq-update", + url: "/sub-admin-update", method: "POST", body: updatedData, }), @@ -43,7 +117,7 @@ export const manageSubAdmin = createApi({ }), }), - deleteFaqPost: builder.mutation<{ success: boolean }, number>({ + deleteSubAdminPost: builder.mutation<{ success: boolean }, number>({ query: (id) => ({ url: `/faq-delete/${id}`, method: "DELETE", @@ -54,6 +128,9 @@ export const manageSubAdmin = createApi({ export const { useGetSubAdminQuery, + useLazyViewSubAdminQuery, + useUpdateSubAdminMutation, + useDeleteSubAdminPostMutation, } = manageSubAdmin; export type Post = { diff --git a/src/components/ActionIcons/Delete.tsx b/src/components/ActionIcons/Delete.tsx index 49b84d1..1b209fc 100644 --- a/src/components/ActionIcons/Delete.tsx +++ b/src/components/ActionIcons/Delete.tsx @@ -2,7 +2,7 @@ import { Icon } from "@chakra-ui/react"; import { Tooltip } from "../ui/tooltip"; import { RiDeleteBin5Line } from "react-icons/ri"; -const Delete = () => { +const Delete = ({onClick}:{onClick: VoidFunction}) => { return ( { h={"24px"} w={"24px"} // color={iconColor && iconColor} + onClick={onClick} > diff --git a/src/components/AlertDailog.tsx b/src/components/AlertDailog.tsx index 40e121b..916cf99 100644 --- a/src/components/AlertDailog.tsx +++ b/src/components/AlertDailog.tsx @@ -19,6 +19,8 @@ interface DeleteConfirmationDialogProps { AltertTiggerIcon?: any; button?: any; iconColor?: string; + isOpen: boolean; + onClose: VoidFunction; } const AlertDailog: React.FC = ({ @@ -28,6 +30,8 @@ const AlertDailog: React.FC = ({ AltertTiggerIcon, button, iconColor, + isOpen, + onClose }) => { return ( = ({ motionPreset="slide-in-bottom" size={"xs"} role="alertdialog" + open={isOpen} > {button ? ( @@ -97,6 +102,7 @@ const AlertDailog: React.FC = ({ borderRadius="sm" border="1px solid black" size={"xs"} + onClick={onClose} > No @@ -120,6 +126,7 @@ const AlertDailog: React.FC = ({ _hover={{ bg: "#00000010" }} color={"#000"} colorPalette={"bg"} + onClick={onClose} /> diff --git a/src/components/EditSubAdmin.tsx b/src/components/EditSubAdmin.tsx index 1d448cd..6553271 100644 --- a/src/components/EditSubAdmin.tsx +++ b/src/components/EditSubAdmin.tsx @@ -1,4 +1,4 @@ -import { Field, Grid, Heading, Input, Span, Stack, Text } from "@chakra-ui/react"; +import { Field, Grid, Heading, Input, Stack, Text } from "@chakra-ui/react"; // import { TbEdit } from "react-icons/tb"; import { Button } from "./ui/button"; import { Checkbox } from "./ui/checkbox"; @@ -13,13 +13,143 @@ import { DialogTrigger, } from "./ui/dialog"; import Edit from "./ActionIcons/Edit"; -function EditSubAdmin() { - return ( - - - {/* */} +import { useLazyViewSubAdminQuery, useUpdateSubAdminMutation } from "../Redux/Service/manage.subadmin.service"; +import { useEffect, useState } from "react"; +import { toaster } from "./ui/toaster"; - +const resourceIdToLabel: { [key: number]: string } = { + 1: 'Dashboard', + 2: 'Manage contact us', + 3: 'Manage User', + 4: 'Manage CMS', + 5: 'Manage Post', + 6: 'Manage Reports', + 7: 'Manage Sub-Admin', + 8: 'My profile', + 9: 'Manage Jobs', + 10: 'Manage feedbacks', + 11: 'Manage community', + 12: 'Notification', +}; + + +interface ResourceActionLink { + id: number; + app_resource_xid: number; + is_active: boolean; +} + +function EditSubAdmin({ id, refetch }: { id: number, refetch: VoidFunction }) { + const [trigger, { data }] = useLazyViewSubAdminQuery(); + const [updateSubAdmin] = useUpdateSubAdminMutation() + const [isOpen, setIsOpen] = useState(false); + const [editData, setEditData] = useState<{ + id: string; + unique_id?: string, + first_name: string; + last_name: string; + date_of_birth: string; + gender?: string, + permission: ResourceActionLink[]; + }>({ + id: '', + unique_id: '', + first_name: '', + last_name: '', + date_of_birth: '', + gender: '', + permission: [], + }) + + useEffect(() => { + if (data?.data && data.data.length > 0) { + const subAdmin = data.data[0]; // Extract the first item from the array + + // Map the API response to editData + setEditData({ + id: subAdmin.id.toString(), + unique_id: subAdmin.unique_id, + first_name: subAdmin.first_name, + last_name: subAdmin.last_name, + date_of_birth: formatDateOfBirth(subAdmin.date_of_birth), + gender: subAdmin.gender, + permission: subAdmin.get_resource_action_link, + }); + } + }, [data]); + + const formatDateOfBirth = (dob: string): string => { + // Convert the date to the desired format with slashes + const formattedDate = new Date(dob).toLocaleDateString("en-GB", { + day: "2-digit", + month: "2-digit", + year: "numeric", + }); + + // Replace slashes with hyphens + return formattedDate.replace(/\//g, '-'); + }; + + const handleOpenModal = () => { + trigger(id) + setIsOpen(true); + }; + + const handleCheckboxToggle = (permissionId: number) => { + setEditData((prevData) => ({ + ...prevData, + permission: prevData.permission.map((permission) => + permission.id === permissionId + ? { ...permission, is_active: !permission.is_active } + : permission + ), + })); + }; + + + const handleSubmit = async () => { + console.log('Updated Data:', editData); + // Call your API here with the updated editData + + const payload = { + id: Number(editData.id), + unique_id: editData.unique_id, + first_name: editData.first_name, + last_name: editData.last_name, + date_of_birth: editData.date_of_birth, + gender: editData.gender, + permission: editData.permission + }; + + try { + const response = await updateSubAdmin(payload).unwrap(); + if (response?.status === "success") { + toaster.create({ + title: "Success", + description: "FAQ updated successfully", + type: "success", + }); + refetch() + setIsOpen(false); + } else { + toaster.create({ + title: "Error", + description: "Failed to update FAQ", + type: "error", + }); + } + } catch (error) { + console.error("Error updating template:", error); + // alert("Failed to update template"); + } + }; + + return ( + setIsOpen(open)}> + + {/* */} + + {/* */} @@ -42,7 +172,7 @@ function EditSubAdmin() { - First Name + ID setEditData({ ...editData, unique_id: e.target.value })} /> + First Name @@ -64,6 +197,8 @@ function EditSubAdmin() { pl={1} fontSize="12px" height="30px" + value={editData.first_name} + onChange={(e) => setEditData({ ...editData, first_name: e.target.value })} /> Last Name @@ -76,6 +211,8 @@ function EditSubAdmin() { pl={1} fontSize="12px" height="30px" + value={editData.last_name} + onChange={(e) => setEditData({ ...editData, last_name: e.target.value })} /> @@ -89,6 +226,8 @@ function EditSubAdmin() { pl={1} fontSize="12px" height="30px" + value={editData.date_of_birth} + onChange={(e) => setEditData({ ...editData, date_of_birth: e.target.value })} /> @@ -102,12 +241,14 @@ function EditSubAdmin() { pl={1} fontSize="12px" height="30px" + value={editData.gender} + onChange={(e) => setEditData({ ...editData, gender: e.target.value })} /> Permissions - + {/* Dashboard @@ -144,15 +285,31 @@ function EditSubAdmin() { Notification + */} + + {editData.permission.map((permission) => { + const label = resourceIdToLabel[permission.app_resource_xid]; + return ( + handleCheckboxToggle(permission.id)} + > + {label} + + ); + })} - - + setIsOpen(false)} /> );