Implementation-of-Profile-Api-And-SuperAdmin-Specification

This commit is contained in:
jaanvi 2025-02-13 10:11:14 +05:30
parent 7de0799b02
commit ba2945a3e5
11 changed files with 806 additions and 463 deletions

View file

@ -1,12 +1,14 @@
import * as React from "react"; import * as React from "react"
import { styled } from "@mui/material/styles"; import { styled } from "@mui/material/styles"
import Table from "@mui/material/Table"; import Table from "@mui/material/Table"
import TableBody from "@mui/material/TableBody"; import TableBody from "@mui/material/TableBody"
import TableCell, { tableCellClasses } from "@mui/material/TableCell"; import TableCell, { tableCellClasses } from "@mui/material/TableCell"
import TableContainer from "@mui/material/TableContainer"; import TableContainer from "@mui/material/TableContainer"
import TableHead from "@mui/material/TableHead"; import TableHead from "@mui/material/TableHead"
import TableRow from "@mui/material/TableRow"; import TableRow from "@mui/material/TableRow"
import Paper, { paperClasses } from "@mui/material/Paper"; import Paper, { paperClasses } from "@mui/material/Paper"
import { deleteAdmin } from "../../redux/slices/authSlice"
import { useDispatch } from "react-redux"
import { import {
Box, Box,
Button, Button,
@ -14,8 +16,10 @@ import {
IconButton, IconButton,
listClasses, listClasses,
Menu, Menu,
} from "@mui/material"; } from "@mui/material"
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded"; import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded"
import DeleteModal from "../Modals/DeleteModal/DeleteModal"
import { AppDispatch } from "../../redux/store/store"
// Styled components for customization // Styled components for customization
const StyledTableCell = styled(TableCell)(({ theme }) => ({ const StyledTableCell = styled(TableCell)(({ theme }) => ({
@ -26,7 +30,7 @@ const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.body}`]: { [`&.${tableCellClasses.body}`]: {
fontSize: 14, fontSize: 14,
}, },
})); }))
const StyledTableRow = styled(TableRow)(({ theme }) => ({ const StyledTableRow = styled(TableRow)(({ theme }) => ({
"&:nth-of-type(odd)": { "&:nth-of-type(odd)": {
@ -35,50 +39,64 @@ const StyledTableRow = styled(TableRow)(({ theme }) => ({
"&:last-child td, &:last-child th": { "&:last-child td, &:last-child th": {
border: 0, border: 0,
}, },
})); }))
interface Column { export interface Column {
id: string; id: string
label: string; label: string
align?: "left" | "center" | "right"; align?: "left" | "center" | "right"
} }
interface Row { interface Row {
[key: string]: any; [key: string]: any
} }
interface CustomTableProps { interface CustomTableProps {
columns: Column[]; columns: Column[]
rows: Row[]; rows: Row[]
setDeleteModal: Function; setDeleteModal: Function
setRowData: Function; setRowData: Function
setModalOpen: Function; setModalOpen: Function
deleteModal: boolean
} }
const CustomTable: React.FC<CustomTableProps> = ({ const CustomTable: React.FC<CustomTableProps> = ({
columns, columns,
rows, rows,
setDeleteModal, setDeleteModal,
deleteModal,
setRowData, setRowData,
setModalOpen, setModalOpen,
}) => { }) => {
console.log("columnsss", columns, rows); // console.log("columnsss", columns, rows)
const dispatch = useDispatch<AppDispatch>()
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)
const [selectedRow, setSelectedRow] = React.useState<Row | null>(null)
const open = Boolean(anchorEl)
const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
setAnchorEl(event.currentTarget)
setSelectedRow(row) // Ensure the row data is set
}
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => { const handleClose = () => {
setAnchorEl(null); setAnchorEl(null)
}; }
const isImage = (value: any) => { const isImage = (value: any) => {
if (typeof value === "string") { if (typeof value === "string") {
return value.startsWith("http") || value.startsWith("data:image"); // Check for URL or base64 image return value.startsWith("http") || value.startsWith("data:image") // Check for URL or base64 image
}
return false
}
const handleDeleteButton = (id: string | undefined) => {
if (!id) console.error("ID not found", id)
dispatch(deleteAdmin(id || ""))
setDeleteModal(false) // Close the modal only after deletion
handleClose()
} }
return false;
};
return ( return (
<TableContainer component={Paper}> <TableContainer component={Paper}>
@ -118,8 +136,8 @@ const CustomTable: React.FC<CustomTableProps> = ({
) : ( ) : (
<IconButton <IconButton
onClick={(e) => { onClick={(e) => {
handleClick(e); handleClick(e, row)
setRowData(row); setRowData(row) // Store the selected row
}} }}
> >
<MoreVertRoundedIcon /> <MoreVertRoundedIcon />
@ -171,9 +189,13 @@ const CustomTable: React.FC<CustomTableProps> = ({
> >
Edit Edit
</Button> </Button>
<Button <Button
variant="text" variant="text"
onClick={() => setDeleteModal(true)} onClick={(e) => {
e.stopPropagation()
setDeleteModal(true)
}}
color="error" color="error"
sx={{ sx={{
justifyContent: "flex-start", justifyContent: "flex-start",
@ -183,11 +205,21 @@ const CustomTable: React.FC<CustomTableProps> = ({
> >
Delete Delete
</Button> </Button>
{deleteModal && (
<DeleteModal
handleDelete={() =>
handleDeleteButton(selectedRow?.id)
}
open={deleteModal}
setDeleteModal={setDeleteModal}
id={selectedRow?.id}
/>
)}
</Box> </Box>
</Menu> </Menu>
)} )}
</TableContainer> </TableContainer>
); )
}; }
export default CustomTable; export default CustomTable

View file

@ -1,30 +1,39 @@
import List from '@mui/material/List'; import List from "@mui/material/List";
import ListItem from '@mui/material/ListItem'; import ListItem from "@mui/material/ListItem";
import ListItemButton from '@mui/material/ListItemButton'; import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from '@mui/material/ListItemText'; import ListItemText from "@mui/material/ListItemText";
import Stack from '@mui/material/Stack'; import Stack from "@mui/material/Stack";
import HomeRoundedIcon from '@mui/icons-material/HomeRounded'; import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
import AnalyticsRoundedIcon from '@mui/icons-material/AnalyticsRounded'; import AnalyticsRoundedIcon from "@mui/icons-material/AnalyticsRounded";
import FormatListBulletedIcon from '@mui/icons-material/FormatListBulleted'; import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted";
import { Link, useLocation } from 'react-router-dom'; import { Link, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store/store";
const mainListItems = [ const baseMenuItems = [
{ {
text: 'Home', text: "Home",
icon: <HomeRoundedIcon />, icon: <HomeRoundedIcon />,
url: '/panel/dashboard', url: "/panel/dashboard",
}, },
{ {
text: 'Vehicles', text: "Vehicles",
icon: <AnalyticsRoundedIcon />, icon: <AnalyticsRoundedIcon />,
url: '/panel/vehicles', url: "/panel/vehicles",
}, },
//created by Eknnor and Jaanvi //created by Eknnor and Jaanvi
];
//Eknoor singh and Jaanvi
//date:- 12-Feb-2025
//Made a different variable for super admin to access all the details.
const superAdminOnlyItems = [
{ {
text: 'Admin List', text: "Admin List",
icon: <FormatListBulletedIcon />, icon: <FormatListBulletedIcon />,
url: '/panel/adminlist', url: "/panel/adminlist",
}, },
]; ];
@ -34,23 +43,33 @@ type PropType = {
export default function MenuContent({ hidden }: PropType) { export default function MenuContent({ hidden }: PropType) {
const location = useLocation(); const location = useLocation();
const userRole = useSelector((state: RootState) => state.auth.user?.role);
const mainListItems = [
...baseMenuItems,
...(userRole === "superadmin" ? superAdminOnlyItems : []),
];
return ( return (
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: 'space-between' }}> <Stack sx={{ flexGrow: 1, p: 1, justifyContent: "space-between" }}>
<List dense> <List dense>
{mainListItems.map((item, index) => ( {mainListItems.map((item, index) => (
<ListItem key={index} disablePadding sx={{ display: 'block', py: 1 }}> <ListItem
key={index}
disablePadding
sx={{ display: "block", py: 1 }}
>
{/* Wrap ListItemButton with Link to enable routing */} {/* Wrap ListItemButton with Link to enable routing */}
<ListItemButton <ListItemButton
component={Link} component={Link}
to={item.url} to={item.url}
selected={item.url === location.pathname} selected={item.url === location.pathname}
sx={{ alignItems: 'center', columnGap: 1 }} sx={{ alignItems: "center", columnGap: 1 }}
> >
<ListItemIcon <ListItemIcon
sx={{ sx={{
minWidth: 'fit-content', minWidth: "fit-content",
'.MuiSvgIcon-root': { ".MuiSvgIcon-root": {
fontSize: 24, fontSize: 24,
}, },
}} }}
@ -59,10 +78,10 @@ export default function MenuContent({ hidden }: PropType) {
</ListItemIcon> </ListItemIcon>
<ListItemText <ListItemText
sx={{ sx={{
display: !hidden ? 'none' : '', display: !hidden ? "none" : "",
transition: 'all 0.5s ease', transition: "all 0.5s ease",
'.MuiListItemText-primary': { ".MuiListItemText-primary": {
fontSize: '16px', fontSize: "16px",
}, },
}} }}
primary={item.text} primary={item.text}

View file

@ -1,31 +1,34 @@
import { Box, Button, Modal, Typography } from '@mui/material'; import { Box, Button, Modal, Typography } from "@mui/material";
import { MouseEventHandler } from 'react';
type Props = { type Props = {
open: boolean; open: boolean;
setDeleteModal: Function; setDeleteModal: Function;
handleDelete: MouseEventHandler; handleDelete: (id: string | undefined) => void;
id?: string | undefined;
}; };
const style = { const style = {
position: 'absolute', position: "absolute",
top: '50%', top: "50%",
left: '50%', left: "50%",
transform: 'translate(-50%, -50%)', transform: "translate(-50%, -50%)",
width: 330, width: 330,
bgcolor: 'background.paper', bgcolor: "background.paper",
borderRadius: 1.5, borderRadius: 1.5,
boxShadow: 24, boxShadow: 24,
p: 3, p: 3,
}; };
const btnStyle = { py: 1, px: 5, width: '50%', textTransform: 'capitalize' }; const btnStyle = { py: 1, px: 5, width: "50%", textTransform: "capitalize" };
export default function DeleteModal({ export default function DeleteModal({
open, open,
setDeleteModal, setDeleteModal,
handleDelete, handleDelete,
id,
}: Props) { }: Props) {
// console.log("DeleteModal opened with ID:", id)
return ( return (
<Modal <Modal
open={open} open={open}
@ -41,13 +44,17 @@ export default function DeleteModal({
> >
Delete Record Delete Record
</Typography> </Typography>
<Typography id="modal-modal-description" sx={{ mt: 2 }} align="center"> <Typography
id="modal-modal-description"
sx={{ mt: 2 }}
align="center"
>
Are you sure you want to delete this record? Are you sure you want to delete this record?
</Typography> </Typography>
<Box <Box
sx={{ sx={{
display: 'flex', display: "flex",
justifyContent: 'space-between', justifyContent: "space-between",
mt: 4, mt: 4,
gap: 2, gap: 2,
}} }}
@ -66,7 +73,7 @@ export default function DeleteModal({
type="button" type="button"
color="primary" color="primary"
sx={btnStyle} sx={btnStyle}
onClick={handleDelete} onClick={() => handleDelete(id || "")}
> >
Delete Delete
</Button> </Button>

View file

@ -11,11 +11,13 @@ import LogoutRoundedIcon from "@mui/icons-material/LogoutRounded";
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded"; import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
import MenuButton from "../MenuButton"; import MenuButton from "../MenuButton";
import { Avatar } from "@mui/material"; import { Avatar } from "@mui/material";
import { useNavigate } from "react-router-dom";
const MenuItem = styled(MuiMenuItem)({ const MenuItem = styled(MuiMenuItem)({
margin: "2px 0", margin: "2px 0",
}); });
export default function OptionsMenu({ avatar }: { avatar?: boolean }) { export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null); const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl); const open = Boolean(anchorEl);
@ -25,6 +27,10 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
const handleClose = () => { const handleClose = () => {
setAnchorEl(null); setAnchorEl(null);
}; };
const navigate = useNavigate();
const handleProfile = () =>{
navigate("/auth/profile");
}
return ( return (
<React.Fragment> <React.Fragment>
<MenuButton <MenuButton
@ -63,7 +69,9 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
}, },
}} }}
> >
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleProfile}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem> <MenuItem onClick={handleClose}>My account</MenuItem>
<Divider /> <Divider />
<MenuItem onClick={handleClose}>Add another account</MenuItem> <MenuItem onClick={handleClose}>Add another account</MenuItem>

View file

@ -1,30 +1,47 @@
import { styled } from '@mui/material/styles'; import { styled } from "@mui/material/styles";
import Avatar from '@mui/material/Avatar'; import Avatar from "@mui/material/Avatar";
import MuiDrawer, { drawerClasses } from '@mui/material/Drawer'; import MuiDrawer, { drawerClasses } from "@mui/material/Drawer";
import Box from '@mui/material/Box'; import Box from "@mui/material/Box";
import Stack from '@mui/material/Stack'; import Stack from "@mui/material/Stack";
import Typography from '@mui/material/Typography'; import Typography from "@mui/material/Typography";
import MenuContent from '../MenuContent'; import MenuContent from "../MenuContent";
import OptionsMenu from '../OptionsMenu'; import OptionsMenu from "../OptionsMenu";
import React from 'react'; import React, { useEffect } from "react";
import { ArrowLeftIcon, ArrowRightIcon } from '@mui/x-date-pickers'; import { ArrowLeftIcon, ArrowRightIcon } from "@mui/x-date-pickers";
import { Button } from '@mui/material'; import { Button } from "@mui/material";
import { fetchProfile } from "../../redux/slices/authSlice";
import { AppDispatch } from "../../redux/store/store";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../redux/reducers";
const drawerWidth = 240; const drawerWidth = 240;
const Drawer = styled(MuiDrawer)({ const Drawer = styled(MuiDrawer)({
width: drawerWidth, width: drawerWidth,
flexShrink: 0, flexShrink: 0,
boxSizing: 'border-box', boxSizing: "border-box",
mt: 10, mt: 10,
[`& .${drawerClasses.paper}`]: { [`& .${drawerClasses.paper}`]: {
width: drawerWidth, width: drawerWidth,
boxSizing: 'border-box', boxSizing: "border-box",
}, },
}); });
export default function SideMenu() { export default function SideMenu() {
const [open, setOpen] = React.useState(true); const [open, setOpen] = React.useState(true);
const dispatch = useDispatch<AppDispatch>();
//Created by : jaanvi and Eknoor
//date: 12-feb-25
//Extract user profile data from Auth
const { user } = useSelector((state: RootState) => state.auth);
useEffect(() => {
// Dispatch the fetchProfile thunk to fetch user profile data
dispatch(fetchProfile());
}, [dispatch]);
return ( return (
<Drawer <Drawer
open={open} open={open}
@ -32,25 +49,25 @@ export default function SideMenu() {
anchor="left" anchor="left"
sx={{ sx={{
display: { display: {
xs: 'none', xs: "none",
md: 'block', md: "block",
width: open ? 220 : 80, width: open ? 250 : 80,
transition: 'all 0.5s ease', transition: "all 0.5s ease",
}, },
[`& .${drawerClasses.paper}`]: { [`& .${drawerClasses.paper}`]: {
backgroundColor: 'background.paper', backgroundColor: "background.paper",
width: open ? 220 : 80, width: open ? 250 : 80,
transition: 'all 0.5s ease', transition: "all 0.5s ease",
}, },
}} }}
> >
<Box <Box
sx={{ sx={{
display: 'flex', display: "flex",
justifyContent: open ? 'flex-end' : 'center', justifyContent: open ? "flex-end" : "center",
alignItems: 'center', alignItems: "center",
pt: 1.5, pt: 1.5,
textAlign: 'center', textAlign: "center",
}} }}
> >
<Button variant="text" onClick={() => setOpen(!open)}> <Button variant="text" onClick={() => setOpen(!open)}>
@ -64,9 +81,9 @@ export default function SideMenu() {
sx={{ sx={{
p: 2, p: 2,
gap: 1, gap: 1,
alignItems: 'center', alignItems: "center",
borderTop: '1px solid', borderTop: "1px solid",
borderColor: 'divider', borderColor: "divider",
}} }}
> >
<Avatar <Avatar
@ -75,15 +92,18 @@ export default function SideMenu() {
src="/static/images/avatar/7.jpg" src="/static/images/avatar/7.jpg"
sx={{ width: open ? 36 : 0, height: open ? 36 : 0 }} sx={{ width: open ? 36 : 0, height: open ? 36 : 0 }}
/> />
<Box sx={{ mr: 'auto', display: !open ? 'none' : 'block' }}> <Box sx={{ mr: "auto", display: !open ? "none" : "block" }}>
<Typography <Typography
variant="body2" variant="body2"
sx={{ fontWeight: 500, lineHeight: '16px' }} sx={{ fontWeight: 500, lineHeight: "16px" }}
> >
Riley Carter {user?.name}
</Typography> </Typography>
<Typography variant="caption" sx={{ color: 'text.secondary' }}> <Typography
riley@email.com variant="caption"
sx={{ color: "text.secondary" }}
>
{user?.email}
</Typography> </Typography>
</Box> </Box>
<OptionsMenu avatar={open} /> <OptionsMenu avatar={open} />

View file

@ -15,7 +15,7 @@
// export default http; // export default http;
import axios, { AxiosInstance } from 'axios'; import axios, { AxiosInstance } from "axios";
// Axios instance for the production backend // Axios instance for the production backend
const backendHttp = axios.create({ const backendHttp = axios.create({
@ -27,13 +27,15 @@ const apiHttp = axios.create({
baseURL: "http://localhost:5000/api", baseURL: "http://localhost:5000/api",
}); });
// Add interceptors to both instances // Add interceptors to both instances
const addAuthInterceptor = (instance: AxiosInstance) => { const addAuthInterceptor = (instance: AxiosInstance) => {
instance.interceptors.request.use((config) => { instance.interceptors.request.use((config) => {
const authToken = localStorage.getItem('authToken'); const authToken = localStorage.getItem("authToken");
if (authToken) { if (authToken) {
config.headers.Authorization = authToken; //Created by : jaanvi and Eknoor
//date: 12-feb-25
//changes in token fetching
config.headers.Authorization = `Bearer ${authToken}`;
} }
return config; return config;
}); });

View file

@ -1,19 +1,14 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { Box, Button, Typography } from "@mui/material"; import { Box, Button, Typography } from "@mui/material";
import AddEditCategoryModal from "../../components/AddEditCategoryModal"; import AddEditCategoryModal from "../../components/AddEditCategoryModal";
// import { useForm } from "react-hook-form";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import CustomTable from "../../components/CustomTable"; import CustomTable, { Column } from "../../components/CustomTable";
import DeleteModal from "../../components/Modals/DeleteModal/DeleteModal";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { adminList, updateAdmin } from "../../redux/slices/authSlice"; import { adminList, updateAdmin } from "../../redux/slices/authSlice";
import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector
// Sample data for categories
export default function AdminList() { export default function AdminList() {
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [editRow, setEditRow] = useState<any>(null);
const { reset } = useForm(); const { reset } = useForm();
const [deleteModal, setDeleteModal] = React.useState<boolean>(false); const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
@ -31,7 +26,6 @@ export default function AdminList() {
const handleClickOpen = () => { const handleClickOpen = () => {
setModalOpen(true); setModalOpen(true);
setEditRow(null);
}; };
const handleCloseModal = () => { const handleCloseModal = () => {
@ -39,20 +33,16 @@ export default function AdminList() {
reset(); reset();
}; };
const handleDelete = () => {
setDeleteModal(false);
};
//By Jaanvi : Edit feature :: 11-feb-25
const handleUpdate = async (id: string, name: string, role: string) => { const handleUpdate = async (id: string, name: string, role: string) => {
try { try {
await dispatch(updateAdmin({ id, name, role })); await dispatch(updateAdmin({ id, name, role }));
dispatch(adminList()); // Fetch updated admins list after update await dispatch(adminList()); // Fetch updated admins list after update
} catch (error) { } catch (error) {
console.error("Update failed", error); console.error("Update failed", error);
} }
}; };
const categoryColumns = [ const categoryColumns: Column[] = [
{ id: "srno", label: "Sr No" }, { id: "srno", label: "Sr No" },
{ id: "name", label: "Name" }, { id: "name", label: "Name" },
{ id: "role", label: "Role" }, { id: "role", label: "Role" },
@ -66,10 +56,10 @@ export default function AdminList() {
admin: { id: string; name: string; role: string }, admin: { id: string; name: string; role: string },
index: number index: number
) => ({ ) => ({
srno: index + 1,
id: admin?.id, id: admin?.id,
srno: index + 1,
name: admin?.name, name: admin?.name,
role: admin?.role || "N/A", role: admin?.role,
}) })
) )
: []; : [];
@ -108,8 +98,8 @@ export default function AdminList() {
<CustomTable <CustomTable
columns={categoryColumns} columns={categoryColumns}
rows={categoryRows} rows={categoryRows}
editRow={editRow}
setDeleteModal={setDeleteModal} setDeleteModal={setDeleteModal}
deleteModal={deleteModal}
setRowData={setRowData} setRowData={setRowData}
setModalOpen={setModalOpen} setModalOpen={setModalOpen}
/> />
@ -119,11 +109,6 @@ export default function AdminList() {
editRow={rowData} editRow={rowData}
handleUpdate={handleUpdate} handleUpdate={handleUpdate}
/> />
<DeleteModal
open={deleteModal}
setDeleteModal={setDeleteModal}
handleDelete={handleDelete}
/>
</> </>
); );
} }

View file

@ -0,0 +1,103 @@
import React, { useEffect } from "react";
import {
Container,
Typography,
CircularProgress,
Card,
CardContent,
Grid,
Avatar,
Box,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "../../redux/store/store";
import { fetchProfile } from "../../redux/slices/authSlice";
const ProfilePage = () => {
// const dispatch = useDispatch();
const dispatch = useDispatch<AppDispatch>();
//Created by : jaanvi and Eknoor
//date: 12-feb-25
//Extract user profile data from Auth
// Extract profile, loading, and error state from Redux
const { user, isLoading, error } = useSelector(
(state: RootState) => state.auth
);
useEffect(() => {
// Dispatch the getProfile thunk to fetch user profile data
dispatch(fetchProfile());
}, [dispatch]);
if (isLoading) {
return (
<Box
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh",
}}
>
<CircularProgress />
</Box>
);
}
if (error) {
return (
<Container>
<Typography variant="h5" color="error" gutterBottom>
Error: {error}
</Typography>
</Container>
);
}
if (!user) {
return (
<Container>
<Typography variant="h5">No profile data available</Typography>
</Container>
);
}
return (
<Container sx={{ py: 4 }}>
<Typography variant="h4" gutterBottom>
Profile
</Typography>
<Card sx={{ maxWidth: 600, margin: "0 auto" }}>
<CardContent>
<Grid container spacing={2} alignItems="center">
<Grid item>
<Avatar
alt={user?.name || "User Avatar"}
src={"/static/images/avatar/7.jpg"}
sx={{ width: 80, height: 80 }}
/>
</Grid>
<Grid item xs>
<Typography variant="h6">
{user?.name || "N/A"}
</Typography>
<Typography variant="body2" color="text.secondary">
Email: {user?.email || "N/A"}
</Typography>
<Typography variant="body2" color="text.secondary">
Phone: {user?.phone || "N/A"}
</Typography>
<Typography variant="body2" color="text.secondary">
Role: {user?.role || "N/A"}
</Typography>
</Grid>
</Grid>
</CardContent>
</Card>
</Container>
);
};
export default ProfilePage;

View file

@ -4,25 +4,49 @@ import { backendHttp, apiHttp } from "../../lib/https";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
// Define types for state // Define types for state
//By jaanvi:: 12-feb-25
interface User { interface User {
token: string | null;
map(
arg0: (
admin: { name: any; role: any; email: any; phone: any },
index: number
) => { srno: number; name: any; role: any; email: any; phone: any }
): unknown;
id: string; id: string;
name: string;
email: string; email: string;
role: string;
phone: string;
} }
interface Admin { interface Admin {
id: string; id: string;
name: string; name: string;
role: string; role: string;
} }
interface AuthState { interface AuthState {
user: User | null; user: User | null;
admins: Admin[]; admins: Admin[];
isAuthenticated: boolean; isAuthenticated: boolean;
isLoading: boolean; isLoading: boolean;
error: string | null; error: object | string | null;
token: string | null; // Store token in Redux state
} }
const initialState: AuthState = {
user: null,
admins: [],
isAuthenticated: false,
isLoading: false,
error: null,
token: null, //Intialize token
};
// Async thunk for login // Async thunk for login
export const loginUser = createAsyncThunk< export const loginUser = createAsyncThunk<
User, User,
@ -30,11 +54,14 @@ export const loginUser = createAsyncThunk<
{ rejectValue: string } { rejectValue: string }
>("auth/login", async ({ email, password }, { rejectWithValue }) => { >("auth/login", async ({ email, password }, { rejectWithValue }) => {
try { try {
const response = await backendHttp.post("admin/login", { const response = await apiHttp.post("auth/login", {
email, email,
password, password,
}); });
localStorage.setItem("authToken", response.data?.data?.token); // Save token //changes By Jaanvi
//Store token
localStorage.setItem("authToken", response.data?.data?.token);
toast.success(response.data?.message); toast.success(response.data?.message);
return response.data; return response.data;
} catch (error: any) { } catch (error: any) {
@ -44,6 +71,41 @@ export const loginUser = createAsyncThunk<
} }
}); });
//created by jaanvi
//date: 12-feb-25
//function for fetching Profile data function
export const fetchProfile = createAsyncThunk<
User,
void,
{ rejectValue: string }
>("auth/fetchProfile", async (_, { rejectWithValue }) => {
try {
//Get the token from localStorage
const token = localStorage.getItem("authToken");
if (!token) throw new Error("No token found");
const response = await apiHttp.get("/auth/profile", {
headers: { Authorization: `Bearer ${token}` }, // Ensuring 'Bearer' prefix
});
console.log("API Response:", response.data); // Debugging
if (!response.data?.data) {
throw new Error("Invalid API response");
}
return response.data.data;
} catch (error: any) {
console.error(
"Profile Fetch Error:",
error.response?.data || error.message
);
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
// Async thunk for register // Async thunk for register
export const registerUser = createAsyncThunk< export const registerUser = createAsyncThunk<
User, User,
@ -63,6 +125,10 @@ export const registerUser = createAsyncThunk<
} }
}); });
//created by Eknoor and jaanvi
//date: 10-Feb-2025
//Fetching list of admins
export const adminList = createAsyncThunk< export const adminList = createAsyncThunk<
Admin[], Admin[],
void, void,
@ -70,11 +136,12 @@ export const adminList = createAsyncThunk<
>("/auth", async (_, { rejectWithValue }) => { >("/auth", async (_, { rejectWithValue }) => {
try { try {
const response = await apiHttp.get("/auth"); const response = await apiHttp.get("/auth");
console.log(response?.data?.data);
return response?.data?.data?.map( return response?.data?.data?.map(
(admin: { id: string; name: string; role: string }) => ({ (admin: { id: string; name: string; role: string }) => ({
id: admin.id, id: admin.id,
name: admin.name, name: admin?.name,
role: admin.role || "N/A", role: admin?.role || "N/A",
}) })
); );
} catch (error: any) { } catch (error: any) {
@ -84,8 +151,26 @@ export const adminList = createAsyncThunk<
} }
}); });
//By Jaanvi : Edit feature :: 11-feb-25 //created by Eknoor
// updateAdmin Action //date: 11-Feb-2025
//function for deleting admin
export const deleteAdmin = createAsyncThunk<
string,
string,
{ rejectValue: string }
>("deleteAdmin", async (id, { rejectWithValue }) => {
try {
const response = await apiHttp.delete(`/auth/${id}`);
toast.success(response.data?.message);
return id;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
export const updateAdmin = createAsyncThunk( export const updateAdmin = createAsyncThunk(
"/auth/id", "/auth/id",
async ( async (
@ -105,14 +190,6 @@ export const updateAdmin = createAsyncThunk(
} }
); );
const initialState: AuthState = {
user: null,
admins: [],
isAuthenticated: false,
isLoading: false,
error: null,
};
const authSlice = createSlice({ const authSlice = createSlice({
name: "auth", name: "auth",
initialState, initialState,
@ -120,6 +197,8 @@ const authSlice = createSlice({
logout: (state) => { logout: (state) => {
state.user = null; state.user = null;
state.isAuthenticated = false; state.isAuthenticated = false;
state.token = null;
localStorage.removeItem("authToken");
}, },
}, },
extraReducers: (builder) => { extraReducers: (builder) => {
@ -129,14 +208,12 @@ const authSlice = createSlice({
state.isLoading = true; state.isLoading = true;
state.error = null; state.error = null;
}) })
.addCase( .addCase(loginUser.fulfilled, (state, action) => {
loginUser.fulfilled,
(state, action: PayloadAction<User>) => {
state.isLoading = false; state.isLoading = false;
state.isAuthenticated = true; state.isAuthenticated = true;
state.user = action.payload; state.user = action.payload;
} state.token = action.payload.token; // Store token in Redux
) })
.addCase( .addCase(
loginUser.rejected, loginUser.rejected,
(state, action: PayloadAction<string | undefined>) => { (state, action: PayloadAction<string | undefined>) => {
@ -164,7 +241,9 @@ const authSlice = createSlice({
state.error = action.payload || "An error occurred"; state.error = action.payload || "An error occurred";
} }
) )
// Fetch admin list
// created by Jaanvi and Eknoor
//AdminList
.addCase(adminList.pending, (state) => { .addCase(adminList.pending, (state) => {
state.isLoading = true; state.isLoading = true;
state.error = null; state.error = null;
@ -176,6 +255,7 @@ const authSlice = createSlice({
state.admins = action.payload; state.admins = action.payload;
} }
) )
.addCase( .addCase(
adminList.rejected, adminList.rejected,
(state, action: PayloadAction<string | undefined>) => { (state, action: PayloadAction<string | undefined>) => {
@ -183,16 +263,57 @@ const authSlice = createSlice({
state.error = action.payload || "An error occurred"; state.error = action.payload || "An error occurred";
} }
) )
// update admin cases
//created by Eknoor
//date: 11-Feb-2025
//cases for deleting admin
.addCase(deleteAdmin.pending, (state) => {
state.isLoading = true;
})
.addCase(deleteAdmin.fulfilled, (state, action) => {
state.isLoading = false;
state.admins = state.admins.filter(
(admin) => String(admin.id) !== String(action.payload)
);
})
.addCase(deleteAdmin.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload || "Failed to delete admin";
})
.addCase(updateAdmin.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(updateAdmin.fulfilled, (state, action) => { .addCase(updateAdmin.fulfilled, (state, action) => {
const updatedAdmin = action.payload; const updatedAdmin = action.payload;
state.admins = state.admins.map((admin) => state.admins = state.admins.map((admin) =>
admin.id === updatedAdmin.id ? updatedAdmin : admin admin.id === updatedAdmin.id ? updatedAdmin : admin
); );
})
.addCase(updateAdmin.rejected, (state) => {
state.isLoading = false; state.isLoading = false;
})
.addCase(updateAdmin.rejected, (state, action) => {
state.isLoading = false;
state.error =
action.payload ||
"Something went wrong while updating Admin!!";
})
//Adding Cases for Profile Slice
//Pending state
.addCase(fetchProfile.pending, (state) => {
state.isLoading = true;
state.error = null; state.error = null;
})
//Fullfilled state
.addCase(fetchProfile.fulfilled, (state, action) => {
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
//Failed to load state
.addCase(fetchProfile.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload || "Failed to fetch admin profile";
}); });
}, },
}); });

View file

@ -1,5 +1,4 @@
import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom"; import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom";
// import useAuth from "./hooks/useAuth";
import React, { Suspense } from "react"; import React, { Suspense } from "react";
import LoadingComponent from "./components/Loading"; import LoadingComponent from "./components/Loading";
import DashboardLayout from "./layouts/DashboardLayout"; import DashboardLayout from "./layouts/DashboardLayout";
@ -8,6 +7,11 @@ import SignUp from "./pages/Auth/SignUp";
import Dashboard from "./pages/Dashboard"; import Dashboard from "./pages/Dashboard";
import Vehicles from "./pages/Vehicles"; import Vehicles from "./pages/Vehicles";
import AdminList from "./pages/AdminList"; import AdminList from "./pages/AdminList";
import ProfilePage from "./pages/ProfilePage";
// import SuperAdminRouter from "./components/SuperAdminRoute";
// SuperAdminRouter // Fix: single import with correct path
import SuperAdminRouter from "./superAdminRouter";
function ProtectedRoute({ function ProtectedRoute({
caps, caps,
@ -37,6 +41,7 @@ export default function AppRouter() {
<Route path="login" element={<Login />} /> <Route path="login" element={<Login />} />
<Route path="signup" element={<SignUp />} /> <Route path="signup" element={<SignUp />} />
</Route> </Route>
<Route path="/panel" element={<DashboardLayout />}> <Route path="/panel" element={<DashboardLayout />}>
<Route <Route
path="dashboard" path="dashboard"
@ -61,12 +66,27 @@ export default function AppRouter() {
element={ element={
<ProtectedRoute <ProtectedRoute
caps={[]} caps={[]}
component={<AdminList />} component={
//Eknoor singh and jaanvi
//date:- 12-Feb-2025
//Admin list put under protected route for specific use
<SuperAdminRouter>
<AdminList />
</SuperAdminRouter>
}
/> />
} }
/> />
<Route path="*" element={<>404</>} /> <Route path="*" element={<>404</>} />
</Route> </Route>
<Route
path="/auth/profile"
element={
<ProtectedRoute caps={[]} component={<ProfilePage />} />
}
/>
<Route path="*" element={<>404</>} /> <Route path="*" element={<>404</>} />
</BaseRoutes> </BaseRoutes>
</Suspense> </Suspense>

26
src/superAdminRouter.tsx Normal file
View file

@ -0,0 +1,26 @@
//Eknoor singh and jaanvi
//date:- 12-Feb-2025
//seperate route for super admin implemented
import React from "react";
import { useSelector } from "react-redux";
import { Navigate } from "react-router-dom";
import { RootState } from "./redux/store/store";
interface SuperAdminRouteProps {
children: React.ReactNode;
}
const SuperAdminRouter: React.FC<SuperAdminRouteProps> = ({ children }) => {
const userRole = useSelector((state: RootState) => state.auth.user?.role);
if (userRole !== 'superadmin') {
// Redirect to dashboard if user is not a superadmin
return <Navigate to="/panel/dashboard" replace />;
}
return <>{children}</>;
};
export default SuperAdminRouter;