dev-jaanvi #1

Open
jaanvi wants to merge 155 commits from dev-jaanvi into main
20 changed files with 30700 additions and 9055 deletions
Showing only changes of commit 53e4f76f22 - Show all commits

13559
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,28 +1,12 @@
import AppRouter from "./router"; import { BrowserRouter as Router} from 'react-router-dom';
import { useSelector } from "react-redux"; import AppRouter from './router';
import { useMatch, useNavigate, useSearchParams } from "react-router-dom";
import { useEffect } from "react";
import { RootState } from "./redux/store";
import { withCookies, ReactCookieProps } from "react-cookie";
const App: React.FC<ReactCookieProps> = ({ cookies }) => { function App() {
const navigate = useNavigate(); return (
const isPanel = useMatch("/auth/login"); <Router>
const isCookiePresent = !!cookies?.get("authToken"); <AppRouter />
console.log("cookies present:", isCookiePresent); </Router>
const [searchParams] = useSearchParams();
const isAuthenticated = useSelector(
(state: RootState) => state.authReducer.isAuthenticated
); );
}
useEffect(() => { export default App;
if (isPanel && isCookiePresent) {
navigate("/panel/dashboard");
}
}, [isPanel, isAuthenticated, searchParams]);
return <AppRouter />;
};
export default withCookies(App);

View file

@ -1,33 +1,60 @@
import React,{useEffect} from "react"; import React, { useEffect } from "react";
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField } from "@mui/material"; import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
} from "@mui/material";
import { useForm, Controller } from "react-hook-form"; import { useForm, Controller } from "react-hook-form";
interface AddEditCategoryModalProps { interface AddEditCategoryModalProps {
open: boolean; open: boolean;
handleClose: () => void; handleClose: () => void;
editRow:any; handleUpdate: (id: string, name: string, role: string) => void;
editRow: any;
} }
interface FormData { interface FormData {
category: string; category: string;
role: string;
name: string;
} }
const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({ open, handleClose,editRow }) => { const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
const { control, handleSubmit, formState: { errors },setValue,reset } = useForm<FormData>({ open,
handleClose,
editRow,
handleUpdate,
}) => {
const {
control,
handleSubmit,
formState: { errors },
setValue,
reset,
} = useForm<FormData>({
defaultValues: { defaultValues: {
category: "", category: "",
name: "",
role: "",
}, },
}); });
const onSubmit = (data: FormData) => { const onSubmit = (data: FormData) => {
console.log(data.category); if (editRow) {
handleUpdate(editRow.id, data.name, data.role);
}
handleClose(); handleClose();
reset(); reset();
}; };
useEffect(() => { useEffect(() => {
if (editRow) { if (editRow) {
setValue('category', editRow.name); setValue("category", editRow.name);
setValue("name", editRow.name);
setValue("role", editRow.role);
} else { } else {
reset(); reset();
} }
@ -41,18 +68,17 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({ open, handl
maxWidth="md" maxWidth="md"
fullWidth fullWidth
PaperProps={{ PaperProps={{
component: 'form', component: "form",
onSubmit: handleSubmit(onSubmit), onSubmit: handleSubmit(onSubmit),
}} }}
> >
<DialogTitle>{editRow ? "Edit" : 'Add'} Category</DialogTitle> <DialogTitle>{editRow ? "Edit" : "Add"} Category</DialogTitle>
<DialogContent> <DialogContent>
<Controller <Controller
name="category" name="category"
control={control} control={control}
rules={{ rules={{
required: "Category Name is required", required: "Category Name is required",
}} }}
render={({ field }) => ( render={({ field }) => (
<TextField <TextField
@ -69,6 +95,47 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({ open, handl
/> />
)} )}
/> />
<Controller
name="name"
control={control}
rules={{
required: "Admin Name is required",
}}
render={({ field }) => (
<TextField
{...field}
autoFocus
required
margin="dense"
label="Admin Name"
type="text"
fullWidth
variant="standard"
error={!!errors.name}
helperText={errors.name?.message}
/>
)}
/>
<Controller
name="role"
control={control}
rules={{
required: "Role is required",
}}
render={({ field }) => (
<TextField
{...field}
margin="dense"
label="Role"
type="text"
fullWidth
variant="standard"
error={!!errors.role}
helperText={errors.role?.message}
/>
)}
/>
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={handleClose}>Cancel</Button> <Button onClick={handleClose}>Cancel</Button>

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,71 +16,87 @@ 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 }) => ({
[`&.${tableCellClasses.head}`]: { [`&.${tableCellClasses.head}`]: {
backgroundColor: ' #1565c0', backgroundColor: " #1565c0",
color: theme.palette.common.white, color: theme.palette.common.white,
}, },
[`&.${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)": {
backgroundColor: theme.palette.action.hover, backgroundColor: theme.palette.action.hover,
}, },
'&: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}>
@ -86,7 +104,10 @@ const CustomTable: React.FC<CustomTableProps> = ({
<TableHead> <TableHead>
<TableRow> <TableRow>
{columns.map((column) => ( {columns.map((column) => (
<StyledTableCell key={column.id} align={column.align || 'left'}> <StyledTableCell
key={column.id}
align={column.align || "left"}
>
{column.label} {column.label}
</StyledTableCell> </StyledTableCell>
))} ))}
@ -96,24 +117,27 @@ const CustomTable: React.FC<CustomTableProps> = ({
{rows.map((row, rowIndex) => ( {rows.map((row, rowIndex) => (
<StyledTableRow key={rowIndex}> <StyledTableRow key={rowIndex}>
{columns.map((column) => ( {columns.map((column) => (
<StyledTableCell key={column.id} align={column.align || 'left'}> <StyledTableCell
key={column.id}
align={column.align || "left"}
>
{isImage(row[column.id]) ? ( {isImage(row[column.id]) ? (
<img <img
src={row[column.id]} src={row[column.id]}
alt="Row " alt="Row "
style={{ style={{
width: '50px', width: "50px",
height: '50px', height: "50px",
objectFit: 'cover', objectFit: "cover",
}} }}
/> />
) : column.id !== 'action' ? ( ) : column.id !== "action" ? (
row[column.id] row[column.id]
) : ( ) : (
<IconButton <IconButton
onClick={(e) => { onClick={(e) => {
handleClick(e); handleClick(e, row)
setRowData(row); setRowData(row) // Store the selected row
}} }}
> >
<MoreVertRoundedIcon /> <MoreVertRoundedIcon />
@ -132,25 +156,25 @@ const CustomTable: React.FC<CustomTableProps> = ({
open={open} open={open}
onClose={handleClose} onClose={handleClose}
onClick={handleClose} onClick={handleClose}
transformOrigin={{ horizontal: 'right', vertical: 'top' }} transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }} anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
sx={{ sx={{
[`& .${listClasses.root}`]: { [`& .${listClasses.root}`]: {
padding: '4px', padding: "4px",
}, },
[`& .${paperClasses.root}`]: { [`& .${paperClasses.root}`]: {
padding: 0, padding: 0,
}, },
[`& .${dividerClasses.root}`]: { [`& .${dividerClasses.root}`]: {
margin: '4px -4px', margin: "4px -4px",
}, },
}} }}
> >
<Box <Box
sx={{ sx={{
display: 'flex', display: "flex",
flexDirection: 'column', flexDirection: "column",
justifyContent: 'flex-start', justifyContent: "flex-start",
}} }}
> >
<Button <Button
@ -158,30 +182,44 @@ const CustomTable: React.FC<CustomTableProps> = ({
onClick={() => setModalOpen(true)} onClick={() => setModalOpen(true)}
color="primary" color="primary"
sx={{ sx={{
justifyContent: 'flex-start', justifyContent: "flex-start",
py: 0, py: 0,
textTransform: 'capitalize', textTransform: "capitalize",
}} }}
> >
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",
py: 0, py: 0,
textTransform: 'capitalize', textTransform: "capitalize",
}} }}
> >
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,23 +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 { Link, useLocation } from 'react-router-dom'; import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted";
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
];
//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",
icon: <FormatListBulletedIcon />,
url: "/panel/adminlist",
}, },
]; ];
@ -27,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,
}, },
}} }}
@ -52,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,12 +73,12 @@ 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>
</Box> </Box>
</Box> </Box>
</Modal> </Modal>
); )
} }

View file

@ -1,47 +1,44 @@
import * as React from 'react'; import * as React from "react";
import { styled } from '@mui/material/styles'; import { styled } from "@mui/material/styles";
import Divider, { dividerClasses } from '@mui/material/Divider'; import Divider, { dividerClasses } from "@mui/material/Divider";
import Menu from '@mui/material/Menu'; import Menu from "@mui/material/Menu";
import MuiMenuItem from '@mui/material/MenuItem'; import MuiMenuItem from "@mui/material/MenuItem";
import { paperClasses } from '@mui/material/Paper'; import { paperClasses } from "@mui/material/Paper";
import { listClasses } from '@mui/material/List'; import { listClasses } from "@mui/material/List";
import ListItemText from '@mui/material/ListItemText'; import ListItemText from "@mui/material/ListItemText";
import ListItemIcon, { listItemIconClasses } from '@mui/material/ListItemIcon'; import ListItemIcon, { listItemIconClasses } from "@mui/material/ListItemIcon";
import LogoutRoundedIcon from '@mui/icons-material/LogoutRounded'; 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 { useDispatch } from 'react-redux'; import { useNavigate } from "react-router-dom";
import { logoutUser } from '../../redux/slices/authSlice';
import { useCookies } from 'react-cookie';
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);
const dispatch = useDispatch();
const [cookies, setCookie, removeCookie] = useCookies(['authToken']);
const handleClick = (event: React.MouseEvent<HTMLElement>) => { const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget); setAnchorEl(event?.currentTarget);
}; };
const handleClose = () => { const handleClose = () => {
setAnchorEl(null); setAnchorEl(null);
}; };
//Eknoor singh and jaanvi
const handleLogout = () => { //date:- 12-Feb-2025
dispatch(logoutUser({ removeCookie })); //Made a navigation page for the profile page
console.log('click') const navigate = useNavigate();
handleClose(); const handleProfile = () => {
navigate("/auth/profile");
}; };
return ( return (
<React.Fragment> <React.Fragment>
<MenuButton <MenuButton
aria-label="Open menu" aria-label="Open menu"
onClick={handleClick} onClick={handleClick}
sx={{ borderColor: 'transparent' }} sx={{ borderColor: "transparent" }}
> >
{avatar ? ( {avatar ? (
<MoreVertRoundedIcon /> <MoreVertRoundedIcon />
@ -60,31 +57,31 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
open={open} open={open}
onClose={handleClose} onClose={handleClose}
onClick={handleClose} onClick={handleClose}
transformOrigin={{ horizontal: 'right', vertical: 'top' }} transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }} anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
sx={{ sx={{
[`& .${listClasses.root}`]: { [`& .${listClasses.root}`]: {
padding: '4px', padding: "4px",
}, },
[`& .${paperClasses.root}`]: { [`& .${paperClasses.root}`]: {
padding: 0, padding: 0,
}, },
[`& .${dividerClasses.root}`]: { [`& .${dividerClasses.root}`]: {
margin: '4px -4px', margin: "4px -4px",
}, },
}} }}
> >
<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>
<MenuItem onClick={handleClose}>Settings</MenuItem> <MenuItem onClick={handleClose}>Settings</MenuItem>
<Divider /> <Divider />
<MenuItem <MenuItem
onClick={handleLogout} onClick={handleClose}
sx={{ sx={{
[`& .${listItemIconClasses.root}`]: { [`& .${listItemIconClasses.root}`]: {
ml: 'auto', ml: "auto",
minWidth: 0, minWidth: 0,
}, },
}} }}

View file

@ -1,30 +1,45 @@
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 { useDispatch, useSelector } from "react-redux";
import { ArrowLeftIcon, ArrowRightIcon } from '@mui/x-date-pickers'; import React, { useEffect } from "react";
import { Button } from '@mui/material'; import { ArrowLeftIcon, ArrowRightIcon } from "@mui/x-date-pickers";
import { AppDispatch, RootState } from "../../redux/store/store";
import { Button } from "@mui/material";
import { fetchAdminProfile } from "../../redux/slices/authSlice";
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);
//Eknoor singh
//date:- 12-Feb-2025
//Dispatch is called with user from Authstate Interface
const dispatch = useDispatch<AppDispatch>();
const { user } = useSelector((state: RootState) => state?.auth);
useEffect(() => {
dispatch(fetchAdminProfile());
}, [dispatch]);
return ( return (
<Drawer <Drawer
open={open} open={open}
@ -32,25 +47,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,26 +79,29 @@ 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
sizes="small" sizes="small"
alt="Riley Carter" alt={user?.name || "User Avatar"}
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 || "No Admin"}
</Typography> </Typography>
<Typography variant="caption" sx={{ color: 'text.secondary' }}> <Typography
riley@email.com variant="caption"
sx={{ color: "text.secondary" }}
>
{user?.email || "No Email"}
</Typography> </Typography>
</Box> </Box>
<OptionsMenu avatar={open} /> <OptionsMenu avatar={open} />

View file

@ -1,32 +1,29 @@
import React from "react"; import React from 'react';
import ReactDOM from "react-dom/client"; import ReactDOM from 'react-dom/client';
import "./index.css"; import './index.css';
import App from "./App"; import reportWebVitals from './reportWebVitals';
import { Provider } from "react-redux"; import App from './App';
import store from "./redux/store"; import { Provider } from 'react-redux';
import { Slide, ToastContainer } from "react-toastify"; import store from './redux/store/store.ts';
import { BrowserRouter as Router } from "react-router-dom"; import { Slide, ToastContainer } from 'react-toastify';
import { CookiesProvider } from "react-cookie";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( root.render(
<React.StrictMode> <React.StrictMode>
<CookiesProvider defaultSetOptions={{ path: "/" }}>
<Provider store={store}> <Provider store={store}>
<Router>
<App /> <App />
</Router>
<ToastContainer <ToastContainer
autoClose={2000} autoClose={2000}
hideProgressBar hideProgressBar
theme="dark" theme="dark"
transition={Slide} transition={Slide}
toastStyle={{ border: "1px solid dimgray" }} toastStyle={{ border: '1px solid dimgray' }}
/> />
</Provider> </Provider>
</CookiesProvider>
</React.StrictMode> </React.StrictMode>
); );
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View file

@ -1,36 +1,47 @@
import axios from "axios"; // import axios from 'axios';
import { Cookies } from "react-cookie";
const cookies = new Cookies(); // const http = axios.create({
// baseURL: process.env.REACT_APP_BACKEND_URL,
// });
// console.log(process.env.REACT_APP_BACKEND_URL);
// http.interceptors.request.use((config) => {
// const authToken = localStorage.getItem('authToken');
// if (authToken) {
// config.headers.Authorization = authToken;
// }
const http = axios.create({ // return config;
// });
// export default http;
//Eknoor singh
//date:- 10-Feb-2025
//Made different functions for calling different backends and sent them in a function for clarity
import axios, { AxiosInstance } from "axios";
const backendHttp = axios.create({
baseURL: process.env.REACT_APP_BACKEND_URL, baseURL: process.env.REACT_APP_BACKEND_URL,
}); });
http.interceptors.request.use((config) => { // Axios instance for the local API
const authToken = cookies.get("authToken"); const apiHttp = axios.create({
console.log(authToken); baseURL: "http://localhost:5000/api",
if (authToken) {
config.headers.Authorization = authToken;
}
return config;
}); });
http.interceptors.response.use( // Add interceptors to both instances
(response) => response, const addAuthInterceptor = (instance: AxiosInstance) => {
(error) => { instance.interceptors.request.use((config) => {
const isCookiePresent = cookies.get("authToken"); const authToken = localStorage.getItem("authToken");
console.log(isCookiePresent,"jkk") if (authToken) {
if ( config.headers.Authorization = `Bearer ${authToken}`; // <-- Add "Bearer "
error.response &&
isCookiePresent &&
(error.response.status === 403 || error.response.status === 401)
) {
cookies.remove("authToken", { path: "/" });
window.location.href = "/";
} }
return Promise.reject(error); return config;
} });
); };
export default http; addAuthInterceptor(backendHttp);
addAuthInterceptor(apiHttp);
export { backendHttp, apiHttp };

View file

@ -0,0 +1,114 @@
import React, { useEffect, useState } from "react";
import { Box, Button, Typography } from "@mui/material";
import AddEditCategoryModal from "../../components/AddEditCategoryModal";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable";
import { useDispatch, useSelector } from "react-redux";
import { adminList, updateAdmin } from "../../redux/slices/authSlice";
import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector
export default function AdminList() {
const [modalOpen, setModalOpen] = useState(false);
const { reset } = useForm();
const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
const [rowData, setRowData] = React.useState<any | null>(null);
const dispatch = useDispatch<AppDispatch>();
// Fetching admin data from the Redux store
const admins = useSelector((state: RootState) => state.auth.admins);
// Dispatching the API call when the component mounts
useEffect(() => {
dispatch(adminList());
}, [dispatch]);
const handleClickOpen = () => {
setModalOpen(true);
};
const handleCloseModal = () => {
setModalOpen(false);
reset();
};
const handleUpdate = async (id: string, name: string, role: string) => {
try {
await dispatch(updateAdmin({ id, name, role }));
await dispatch(adminList()); // Fetch updated admins list after update
} catch (error) {
console.error("Update failed", error);
}
};
const categoryColumns: Column[] = [
{ id: "srno", label: "Sr No" },
{ id: "name", label: "Name" },
{ id: "role", label: "Role" },
{ id: "action", label: "Action", align: "center" },
];
// If no admins are available, display the sample data
const categoryRows = admins?.length
? admins?.map(
(
admin: { id: string; name: string; role: string },
index: number
) => ({
id: admin?.id,
srno: index + 1,
name: admin?.name,
role: admin?.role,
})
)
: [];
return (
<>
<Box
sx={{
width: "100%",
maxWidth: {
sm: "100%",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
},
}}
>
{/* Title and Add Category button */}
<Typography
component="h2"
variant="h6"
sx={{ mt: 2, fontWeight: 600 }}
>
Admins
</Typography>
<Button
variant="contained"
size="medium"
sx={{ textAlign: "right" }}
onClick={handleClickOpen}
>
Add Category
</Button>
</Box>
<CustomTable
columns={categoryColumns}
rows={categoryRows}
setDeleteModal={setDeleteModal}
deleteModal={deleteModal}
setRowData={setRowData}
setModalOpen={setModalOpen}
/>
<AddEditCategoryModal
open={modalOpen}
handleClose={handleCloseModal}
editRow={rowData}
handleUpdate={handleUpdate}
/>
</>
);
}

View file

@ -84,7 +84,7 @@ const dispatch = useDispatch();
const [countryCode, setCountryCode] = React.useState(''); const [countryCode, setCountryCode] = React.useState('');
const [phoneNumber, setPhoneNumber] = React.useState(''); const [phoneNumber, setPhoneNumber] = React.useState('');
const extractCountryCodeAndNumber = (phone) => { const extractCountryCodeAndNumber = (phone: string) => {
// Match the country code (e.g., +91) and the rest of the number // Match the country code (e.g., +91) and the rest of the number
const match = phone.match(/^(\+\d{1,3})\s*(\d+.*)/); const match = phone.match(/^(\+\d{1,3})\s*(\d+.*)/);
if (match) { if (match) {
@ -92,7 +92,7 @@ const dispatch = useDispatch();
} }
return { countryCode: '', numberWithoutCountryCode: phone }; return { countryCode: '', numberWithoutCountryCode: phone };
}; };
const handleOnChange = (newPhone) => { const handleOnChange = (newPhone: string) => {
const { countryCode, numberWithoutCountryCode } = extractCountryCodeAndNumber(newPhone); const { countryCode, numberWithoutCountryCode } = extractCountryCodeAndNumber(newPhone);
console.log("numberWithoutCountryCode",numberWithoutCountryCode); console.log("numberWithoutCountryCode",numberWithoutCountryCode);
setPhoneNumber(numberWithoutCountryCode) setPhoneNumber(numberWithoutCountryCode)

View file

@ -0,0 +1,102 @@
//Eknoor singh
//date:- 12-Feb-2025
//Made a special page for showing the profile details
import { 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 { fetchAdminProfile } from "../../redux/slices/authSlice";
const ProfilePage = () => {
//Eknoor singh
//date:- 12-Feb-2025
//Dispatch is called and user, isLoading, and error from Authstate Interface
const dispatch = useDispatch<AppDispatch>();
const { user, isLoading, error } = useSelector(
(state: RootState) => state?.auth
);
useEffect(() => {
dispatch(fetchAdminProfile());
}, [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>
<h2>An error occurred while loading profile</h2>
</Typography>
</Container>
);
}
console.log(user?.name);
console.log(user?.email);
console.log(user?.role);
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
//Eknoor singh
//date:- 12-Feb-2025
//user is called for name and email
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: <b>{user?.role || "N/A"}</b>
</Typography>
</Grid>
</Grid>
</CardContent>
</Card>
</Container>
);
};
export default ProfilePage;

View file

@ -1,37 +1,43 @@
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit"; import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios"; import axios from "axios";
import http from "../../lib/https"; import { backendHttp, apiHttp } from "../../lib/https";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
import { Cookies } from "react-cookie";
const cookies = new Cookies();
// Define types for state // Define types for state
//Eknoor singh
//date:- 12-Feb-2025
//Token for the user has been declared
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;
role: string;
phone: string;
}
interface Admin {
id: string;
name: string;
role: string;
email: string; email: string;
} }
interface AuthState { interface AuthState {
user: User | null; user: User | null;
admins: Admin[];
isAuthenticated: boolean; isAuthenticated: boolean;
isLoading: boolean; isLoading: boolean;
error: string | null; error: object | string | null;
token: string | null;
} }
export const checkUserAuth = createAsyncThunk<
boolean,
void,
{ rejectValue: any }
>("application/checkUserAuth", async (_, thunkAPI) => {
try {
const isCookiePresent = cookies.get("authToken");
if (!isCookiePresent) return thunkAPI.rejectWithValue(null);
return thunkAPI.fulfillWithValue(true);
} catch (error) {
console.log(error);
return thunkAPI.rejectWithValue(error);
}
});
// Async thunk for login // Async thunk for login
export const loginUser = createAsyncThunk< export const loginUser = createAsyncThunk<
User, User,
@ -39,8 +45,11 @@ 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 http.post("admin/login", { email, password }); const response = await apiHttp.post("auth/login", {
cookies.set("authToken", response.data?.data?.token); email,
password,
});
localStorage.setItem("authToken", response.data?.data?.token); // Save token
toast.success(response.data?.message); toast.success(response.data?.message);
return response.data; return response.data;
} catch (error: any) { } catch (error: any) {
@ -53,14 +62,17 @@ export const loginUser = createAsyncThunk<
// Async thunk for register // Async thunk for register
export const registerUser = createAsyncThunk< export const registerUser = createAsyncThunk<
User, User,
{ email: string; password: string }, {
name: string;
email: string;
password: string;
phone: string;
role: string;
},
{ rejectValue: string } { rejectValue: string }
>("auth/register", async (data, { rejectWithValue }) => { >("auth/signup", async (data, { rejectWithValue }) => {
try { try {
const response = await axios.post( const response = await apiHttp.post("auth/signup", data);
"https://health-digi.dmlabs.in/auth/register",
data
);
return response.data; return response.data;
} catch (error: any) { } catch (error: any) {
return rejectWithValue( return rejectWithValue(
@ -69,26 +81,121 @@ export const registerUser = createAsyncThunk<
} }
}); });
export const logoutUser = createAsyncThunk< //created by Eknoor and jaanvi
//date: 10-Feb-2025
//Fetching list of admins
export const adminList = createAsyncThunk<
Admin[],
void, void,
{ removeCookie: any },
{ rejectValue: string } { rejectValue: string }
>("auth/logout", async ({ removeCookie }, { rejectWithValue }) => { >("/auth", async (_, { rejectWithValue }) => {
try { try {
removeCookie("authToken", { path: "/auth" }); const response = await apiHttp.get("/auth");
toast.success("You have been logged out successfully."); console.log(response?.data?.data);
return response?.data?.data?.map(
(admin: {
id: string;
name: string;
role: string;
email: string;
}) => ({
id: admin?.id,
name: admin?.name,
role: admin?.role || "N/A",
email: admin?.email,
})
);
} catch (error: any) { } catch (error: any) {
return rejectWithValue( return rejectWithValue(
error.response?.data?.message || "Failed to log out." error.response?.data?.message || "An error occurred"
);
}
});
//created by Eknoor
//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(
"/auth/id",
async (
{ id, name, role }: { id: any; name: string; role: string },
{ rejectWithValue }
) => {
try {
const response = await apiHttp.put(`/auth/${id}`, { name, role });
toast.success("Admin updated successfully");
console.log(response?.data);
return response?.data;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
}
);
//Eknoor singh
//date:- 12-Feb-2025
//Function for fetching profile of a particular user has been implemented with Redux.
export const fetchAdminProfile = createAsyncThunk<
User,
void,
{ rejectValue: string }
>("auth/fetchAdminProfile", async (_, { rejectWithValue }) => {
try {
const token = localStorage?.getItem("authToken");
if (!token) throw new Error("No token found");
const response = await apiHttp?.get("/auth/profile", {
headers: { Authorization: `Bearer ${token}` }, // Ensure 'Bearer' prefix
});
console.log("API Response:", response?.data); // Debugging
if (!response.data?.data) {
throw new Error("Invalid API response");
}
return response?.data?.data; // Fix: Return only `data`, assuming it contains user info.
} catch (error: any) {
console.error(
"Profile Fetch Error:",
error?.response?.data || error?.message
);
return rejectWithValue(
error?.response?.data?.message || "An error occurred"
); );
} }
}); });
const initialState: AuthState = { const initialState: AuthState = {
user: null, user: null,
admins: [],
isAuthenticated: false, isAuthenticated: false,
isLoading: false, isLoading: false,
error: null, error: null,
//Eknoor singh
//date:- 12-Feb-2025
//initial state of token set to null
token: null,
}; };
const authSlice = createSlice({ const authSlice = createSlice({
@ -98,6 +205,11 @@ const authSlice = createSlice({
logout: (state) => { logout: (state) => {
state.user = null; state.user = null;
state.isAuthenticated = false; state.isAuthenticated = false;
//Eknoor singh
//date:- 12-Feb-2025
//Token is removed from local storage and set to null
state.token = null;
localStorage.removeItem("authToken");
}, },
}, },
extraReducers: (builder) => { extraReducers: (builder) => {
@ -107,14 +219,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; // Fix: Extract correct 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>) => {
@ -142,19 +252,82 @@ const authSlice = createSlice({
state.error = action.payload || "An error occurred"; state.error = action.payload || "An error occurred";
} }
) )
// Logout
.addCase(logoutUser.fulfilled, (state) => { // created by Jaanvi and Eknoor
state.user = null; //AdminList
state.isAuthenticated = false; .addCase(adminList.pending, (state) => {
state.isLoading = true;
state.error = null;
}) })
.addCase( .addCase(
logoutUser.rejected, adminList.fulfilled,
(state, action: PayloadAction<string | undefined>) => { (state, action: PayloadAction<Admin[]>) => {
state.error = state.isLoading = false;
action.payload || "An error occurred during logout"; state.admins = action.payload;
} }
)
.addCase(
adminList.rejected,
(state, action: PayloadAction<string | undefined>) => {
state.isLoading = false;
state.error = action.payload || "An error occurred";
}
)
//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) => {
const updatedAdmin = action.payload;
state.admins = state?.admins?.map((admin) =>
admin?.id === updatedAdmin?.id ? updatedAdmin : admin
);
state.isLoading = false;
})
.addCase(updateAdmin.rejected, (state, action) => {
state.isLoading = false;
state.error =
action.payload ||
"Something went wrong while updating Admin!!";
})
//Eknoor singh
//date:- 12-Feb-2025
//Reducers for fetching profiles has been implemented
.addCase(fetchAdminProfile.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(fetchAdminProfile.fulfilled, (state, action) => {
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
.addCase(fetchAdminProfile.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload || "Failed to fetch admin profile";
});
}, },
}); });
export const { logout } = authSlice.actions;
export default authSlice.reducer; export default authSlice.reducer;

View file

@ -1,10 +1,13 @@
import { configureStore } from '@reduxjs/toolkit'; import { configureStore } from '@reduxjs/toolkit';
import authReducer from '../slices/authSlice.ts'
const store = configureStore({
reducer: {
auth: authReducer,
},
});
import rootReducer from './reducers';
export const store = configureStore({
reducer: rootReducer,
})
export type RootState = ReturnType<typeof store.getState>; export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch; export type AppDispatch = typeof store.dispatch;
export default store; export default store;

View file

@ -1,29 +1,25 @@
import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom"; import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom";
import { 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";
import Login from "./pages/Auth/Login"; import Login from "./pages/Auth/Login";
import SignUp from "./pages/Auth/SignUp"; 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 { useSelector } from "react-redux"; import AdminList from "./pages/AdminList";
import { RootState } from "./redux/reducers"; import ProfilePage from "./pages/ProfilePage";
import { useCookies } from "react-cookie";
interface ProtectedRouteProps { import SuperAdminRouter from "./superAdminRouter";
component: JSX.Element;
cookies?: { get: (key: string) => string | null };
}
function ProtectedRoute({ component }: ProtectedRouteProps): JSX.Element {
const [cookies] = useCookies(["authToken"]);
const isCookiePresent = !!cookies?.authToken;
const isAuthenticated = useSelector(
(state: RootState) => state.authReducer.isAuthenticated
);
if (!isAuthenticated && !isCookiePresent) { function ProtectedRoute({
return <Navigate to="/auth/login" replace />; caps,
} component,
}: {
caps: string[];
component: React.ReactNode;
}) {
if (!localStorage.getItem("authToken"))
return <Navigate to={`/auth/login`} replace />;
return component; return component;
} }
@ -43,17 +39,52 @@ 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"
element={<ProtectedRoute component={<Dashboard />} />} element={
<ProtectedRoute
caps={[]}
component={<Dashboard />}
/>
}
/> />
<Route <Route
path="vehicles" path="vehicles"
element={<ProtectedRoute component={<Vehicles />} />} element={
<ProtectedRoute
caps={[]}
component={<Vehicles />}
/> />
}
/>
<Route
path="adminlist"
element={
<ProtectedRoute
caps={[]}
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>

25
src/superAdminRouter.tsx Normal file
View file

@ -0,0 +1,25 @@
//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;

View file

@ -1,10 +1,9 @@
{ {
"compilerOptions": { "compilerOptions": {
"jsx": "react",
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022", "target": "ES2022",
"lib": [ "lib": ["ES2023"],
"ES2023"
],
"module": "ESNext", "module": "ESNext",
"skipLibCheck": true, "skipLibCheck": true,
/* Bundler mode */ /* Bundler mode */