Merge pull request 'Get and Delete API's implemented using redux' (#4) from feature/adminList into develop

Reviewed-on: DigiMantra/digiev_frontend#4
This commit is contained in:
Mohit kalshan 2025-02-13 09:29:03 +00:00
commit 53e4f76f22
20 changed files with 30700 additions and 9055 deletions

13559
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -73,4 +73,4 @@
"@types/react-dom": "^19.0.2",
"typescript": "^5.7.3"
}
}
}

File diff suppressed because it is too large Load diff

View file

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

View file

@ -1,82 +1,149 @@
import React,{useEffect} from "react";
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField } from "@mui/material";
import React, { useEffect } from "react";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
} from "@mui/material";
import { useForm, Controller } from "react-hook-form";
interface AddEditCategoryModalProps {
open: boolean;
handleClose: () => void;
editRow:any;
open: boolean;
handleClose: () => void;
handleUpdate: (id: string, name: string, role: string) => void;
editRow: any;
}
interface FormData {
category: string;
category: string;
role: string;
name: string;
}
const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({ open, handleClose,editRow }) => {
const { control, handleSubmit, formState: { errors },setValue,reset } = useForm<FormData>({
defaultValues: {
category: "",
},
});
const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
open,
handleClose,
editRow,
handleUpdate,
}) => {
const {
control,
handleSubmit,
formState: { errors },
setValue,
reset,
} = useForm<FormData>({
defaultValues: {
category: "",
name: "",
role: "",
},
});
const onSubmit = (data: FormData) => {
console.log(data.category);
handleClose();
reset();
};
const onSubmit = (data: FormData) => {
if (editRow) {
handleUpdate(editRow.id, data.name, data.role);
}
handleClose();
reset();
};
useEffect(() => {
if (editRow) {
setValue('category', editRow.name);
} else {
reset();
}
}, [editRow, setValue, reset]);
useEffect(() => {
if (editRow) {
setValue("category", editRow.name);
setValue("name", editRow.name);
setValue("role", editRow.role);
} else {
reset();
}
}, [editRow, setValue, reset]);
return (
<>
<Dialog
open={open}
onClose={handleClose}
maxWidth="md"
fullWidth
PaperProps={{
component: 'form',
onSubmit: handleSubmit(onSubmit),
}}
>
<DialogTitle>{editRow ? "Edit" : 'Add'} Category</DialogTitle>
<DialogContent>
<Controller
name="category"
control={control}
rules={{
required: "Category Name is required",
}}
render={({ field }) => (
<TextField
{...field}
autoFocus
required
margin="dense"
label="Add Category Name"
type="text"
fullWidth
variant="standard"
error={!!errors.category}
helperText={errors.category?.message}
/>
)}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button type="submit">Save</Button>
</DialogActions>
</Dialog>
</>
);
return (
<>
<Dialog
open={open}
onClose={handleClose}
maxWidth="md"
fullWidth
PaperProps={{
component: "form",
onSubmit: handleSubmit(onSubmit),
}}
>
<DialogTitle>{editRow ? "Edit" : "Add"} Category</DialogTitle>
<DialogContent>
<Controller
name="category"
control={control}
rules={{
required: "Category Name is required",
}}
render={({ field }) => (
<TextField
{...field}
autoFocus
required
margin="dense"
label="Add Category Name"
type="text"
fullWidth
variant="standard"
error={!!errors.category}
helperText={errors.category?.message}
/>
)}
/>
<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>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button type="submit">Save</Button>
</DialogActions>
</Dialog>
</>
);
};
export default AddEditCategoryModal;

View file

@ -1,187 +1,225 @@
import * as React from 'react';
import { styled } from '@mui/material/styles';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper, { paperClasses } from '@mui/material/Paper';
import * as React from "react"
import { styled } from "@mui/material/styles"
import Table from "@mui/material/Table"
import TableBody from "@mui/material/TableBody"
import TableCell, { tableCellClasses } from "@mui/material/TableCell"
import TableContainer from "@mui/material/TableContainer"
import TableHead from "@mui/material/TableHead"
import TableRow from "@mui/material/TableRow"
import Paper, { paperClasses } from "@mui/material/Paper"
import { deleteAdmin } from "../../redux/slices/authSlice"
import { useDispatch } from "react-redux"
import {
Box,
Button,
dividerClasses,
IconButton,
listClasses,
Menu,
} from '@mui/material';
import MoreVertRoundedIcon from '@mui/icons-material/MoreVertRounded';
Box,
Button,
dividerClasses,
IconButton,
listClasses,
Menu,
} from "@mui/material"
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded"
import DeleteModal from "../Modals/DeleteModal/DeleteModal"
import { AppDispatch } from "../../redux/store/store"
// Styled components for customization
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: ' #1565c0',
color: theme.palette.common.white,
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
},
}));
[`&.${tableCellClasses.head}`]: {
backgroundColor: " #1565c0",
color: theme.palette.common.white,
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
},
}))
const StyledTableRow = styled(TableRow)(({ theme }) => ({
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
'&:last-child td, &:last-child th': {
border: 0,
},
}));
"&:nth-of-type(odd)": {
backgroundColor: theme.palette.action.hover,
},
"&:last-child td, &:last-child th": {
border: 0,
},
}))
interface Column {
id: string;
label: string;
align?: 'left' | 'center' | 'right';
export interface Column {
id: string
label: string
align?: "left" | "center" | "right"
}
interface Row {
[key: string]: any;
[key: string]: any
}
interface CustomTableProps {
columns: Column[];
rows: Row[];
setDeleteModal: Function;
setRowData: Function;
setModalOpen: Function;
columns: Column[]
rows: Row[]
setDeleteModal: Function
setRowData: Function
setModalOpen: Function
deleteModal: boolean
}
const CustomTable: React.FC<CustomTableProps> = ({
columns,
rows,
setDeleteModal,
setRowData,
setModalOpen,
columns,
rows,
setDeleteModal,
deleteModal,
setRowData,
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 [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const isImage = (value: any) => {
if (typeof value === 'string') {
return value.startsWith('http') || value.startsWith('data:image'); // Check for URL or base64 image
const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
setAnchorEl(event.currentTarget)
setSelectedRow(row) // Ensure the row data is set
}
return false;
};
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<TableRow>
{columns.map((column) => (
<StyledTableCell key={column.id} align={column.align || 'left'}>
{column.label}
</StyledTableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, rowIndex) => (
<StyledTableRow key={rowIndex}>
{columns.map((column) => (
<StyledTableCell key={column.id} align={column.align || 'left'}>
{isImage(row[column.id]) ? (
<img
src={row[column.id]}
alt="Row "
style={{
width: '50px',
height: '50px',
objectFit: 'cover',
}}
/>
) : column.id !== 'action' ? (
row[column.id]
) : (
<IconButton
onClick={(e) => {
handleClick(e);
setRowData(row);
}}
const handleClose = () => {
setAnchorEl(null)
}
const isImage = (value: any) => {
if (typeof value === "string") {
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 (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<TableRow>
{columns.map((column) => (
<StyledTableCell
key={column.id}
align={column.align || "left"}
>
{column.label}
</StyledTableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, rowIndex) => (
<StyledTableRow key={rowIndex}>
{columns.map((column) => (
<StyledTableCell
key={column.id}
align={column.align || "left"}
>
{isImage(row[column.id]) ? (
<img
src={row[column.id]}
alt="Row "
style={{
width: "50px",
height: "50px",
objectFit: "cover",
}}
/>
) : column.id !== "action" ? (
row[column.id]
) : (
<IconButton
onClick={(e) => {
handleClick(e, row)
setRowData(row) // Store the selected row
}}
>
<MoreVertRoundedIcon />
</IconButton>
)}
</StyledTableCell>
))}
</StyledTableRow>
))}
</TableBody>
</Table>
{open && (
<Menu
anchorEl={anchorEl}
id="menu"
open={open}
onClose={handleClose}
onClick={handleClose}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
sx={{
[`& .${listClasses.root}`]: {
padding: "4px",
},
[`& .${paperClasses.root}`]: {
padding: 0,
},
[`& .${dividerClasses.root}`]: {
margin: "4px -4px",
},
}}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "flex-start",
}}
>
<MoreVertRoundedIcon />
</IconButton>
)}
</StyledTableCell>
))}
</StyledTableRow>
))}
</TableBody>
</Table>
{open && (
<Menu
anchorEl={anchorEl}
id="menu"
open={open}
onClose={handleClose}
onClick={handleClose}
transformOrigin={{ horizontal: 'right', vertical: 'top' }}
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
sx={{
[`& .${listClasses.root}`]: {
padding: '4px',
},
[`& .${paperClasses.root}`]: {
padding: 0,
},
[`& .${dividerClasses.root}`]: {
margin: '4px -4px',
},
}}
>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
}}
>
<Button
variant="text"
onClick={() => setModalOpen(true)}
color="primary"
sx={{
justifyContent: 'flex-start',
py: 0,
textTransform: 'capitalize',
}}
>
Edit
</Button>
<Button
variant="text"
onClick={() => setDeleteModal(true)}
color="error"
sx={{
justifyContent: 'flex-start',
py: 0,
textTransform: 'capitalize',
}}
>
Delete
</Button>
</Box>
</Menu>
)}
</TableContainer>
);
};
<Button
variant="text"
onClick={() => setModalOpen(true)}
color="primary"
sx={{
justifyContent: "flex-start",
py: 0,
textTransform: "capitalize",
}}
>
Edit
</Button>
export default CustomTable;
<Button
variant="text"
onClick={(e) => {
e.stopPropagation()
setDeleteModal(true)
}}
color="error"
sx={{
justifyContent: "flex-start",
py: 0,
textTransform: "capitalize",
}}
>
Delete
</Button>
{deleteModal && (
<DeleteModal
handleDelete={() =>
handleDeleteButton(selectedRow?.id)
}
open={deleteModal}
setDeleteModal={setDeleteModal}
id={selectedRow?.id}
/>
)}
</Box>
</Menu>
)}
</TableContainer>
)
}
export default CustomTable

View file

@ -1,69 +1,95 @@
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import Stack from '@mui/material/Stack';
import HomeRoundedIcon from '@mui/icons-material/HomeRounded';
import AnalyticsRoundedIcon from '@mui/icons-material/AnalyticsRounded';
import { Link, useLocation } from 'react-router-dom';
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Stack from "@mui/material/Stack";
import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
import AnalyticsRoundedIcon from "@mui/icons-material/AnalyticsRounded";
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 = [
{
text: 'Home',
icon: <HomeRoundedIcon />,
url: '/panel/dashboard',
},
{
text: 'Vehicles',
icon: <AnalyticsRoundedIcon />,
url: '/panel/vehicles',
},
const baseMenuItems = [
{
text: "Home",
icon: <HomeRoundedIcon />,
url: "/panel/dashboard",
},
{
text: "Vehicles",
icon: <AnalyticsRoundedIcon />,
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",
},
];
type PropType = {
hidden: boolean;
hidden: boolean;
};
export default function MenuContent({ hidden }: PropType) {
const location = useLocation();
const location = useLocation();
const userRole = useSelector((state: RootState) => state.auth.user?.role);
return (
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: 'space-between' }}>
<List dense>
{mainListItems.map((item, index) => (
<ListItem key={index} disablePadding sx={{ display: 'block', py: 1 }}>
{/* Wrap ListItemButton with Link to enable routing */}
<ListItemButton
component={Link}
to={item.url}
selected={item.url === location.pathname}
sx={{ alignItems: 'center', columnGap: 1 }}
>
<ListItemIcon
sx={{
minWidth: 'fit-content',
'.MuiSvgIcon-root': {
fontSize: 24,
},
}}
>
{item.icon}
</ListItemIcon>
<ListItemText
sx={{
display: !hidden ? 'none' : '',
transition: 'all 0.5s ease',
'.MuiListItemText-primary': {
fontSize: '16px',
},
}}
primary={item.text}
/>
</ListItemButton>
</ListItem>
))}
</List>
</Stack>
);
const mainListItems = [
...baseMenuItems,
...(userRole === "superadmin" ? superAdminOnlyItems : []),
];
return (
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: "space-between" }}>
<List dense>
{mainListItems.map((item, index) => (
<ListItem
key={index}
disablePadding
sx={{ display: "block", py: 1 }}
>
{/* Wrap ListItemButton with Link to enable routing */}
<ListItemButton
component={Link}
to={item.url}
selected={item.url === location.pathname}
sx={{ alignItems: "center", columnGap: 1 }}
>
<ListItemIcon
sx={{
minWidth: "fit-content",
".MuiSvgIcon-root": {
fontSize: 24,
},
}}
>
{item.icon}
</ListItemIcon>
<ListItemText
sx={{
display: !hidden ? "none" : "",
transition: "all 0.5s ease",
".MuiListItemText-primary": {
fontSize: "16px",
},
}}
primary={item.text}
/>
</ListItemButton>
</ListItem>
))}
</List>
</Stack>
);
}

View file

@ -1,77 +1,84 @@
import { Box, Button, Modal, Typography } from '@mui/material';
import { MouseEventHandler } from 'react';
import { Box, Button, Modal, Typography } from "@mui/material"
type Props = {
open: boolean;
setDeleteModal: Function;
handleDelete: MouseEventHandler;
};
open: boolean
setDeleteModal: Function
handleDelete: (id: string | undefined) => void
id?: string | undefined
}
const style = {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 330,
bgcolor: 'background.paper',
borderRadius: 1.5,
boxShadow: 24,
p: 3,
};
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 330,
bgcolor: "background.paper",
borderRadius: 1.5,
boxShadow: 24,
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({
open,
setDeleteModal,
handleDelete,
open,
setDeleteModal,
handleDelete,
id,
}: Props) {
return (
<Modal
open={open}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<Typography
id="modal-modal-title"
variant="h6"
component="h2"
align="center"
// console.log("DeleteModal opened with ID:", id)
return (
<Modal
open={open}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
Delete Record
</Typography>
<Typography id="modal-modal-description" sx={{ mt: 2 }} align="center">
Are you sure you want to delete this record?
</Typography>
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
mt: 4,
gap: 2,
}}
>
<Button
variant="contained"
color="error"
type="button"
sx={btnStyle}
onClick={() => setDeleteModal(false)}
>
Cancel
</Button>
<Button
variant="contained"
type="button"
color="primary"
sx={btnStyle}
onClick={handleDelete}
>
Delete
</Button>
</Box>
</Box>
</Modal>
);
<Box sx={style}>
<Typography
id="modal-modal-title"
variant="h6"
component="h2"
align="center"
>
Delete Record
</Typography>
<Typography
id="modal-modal-description"
sx={{ mt: 2 }}
align="center"
>
Are you sure you want to delete this record?
</Typography>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
mt: 4,
gap: 2,
}}
>
<Button
variant="contained"
color="error"
type="button"
sx={btnStyle}
onClick={() => setDeleteModal(false)}
>
Cancel
</Button>
<Button
variant="contained"
type="button"
color="primary"
sx={btnStyle}
onClick={() => handleDelete(id || "")}
>
Delete
</Button>
</Box>
</Box>
</Modal>
)
}

View file

@ -1,100 +1,97 @@
import * as React from 'react';
import { styled } from '@mui/material/styles';
import Divider, { dividerClasses } from '@mui/material/Divider';
import Menu from '@mui/material/Menu';
import MuiMenuItem from '@mui/material/MenuItem';
import { paperClasses } from '@mui/material/Paper';
import { listClasses } from '@mui/material/List';
import ListItemText from '@mui/material/ListItemText';
import ListItemIcon, { listItemIconClasses } from '@mui/material/ListItemIcon';
import LogoutRoundedIcon from '@mui/icons-material/LogoutRounded';
import MoreVertRoundedIcon from '@mui/icons-material/MoreVertRounded';
import MenuButton from '../MenuButton';
import { Avatar } from '@mui/material';
import { useDispatch } from 'react-redux';
import { logoutUser } from '../../redux/slices/authSlice';
import { useCookies } from 'react-cookie';
import * as React from "react";
import { styled } from "@mui/material/styles";
import Divider, { dividerClasses } from "@mui/material/Divider";
import Menu from "@mui/material/Menu";
import MuiMenuItem from "@mui/material/MenuItem";
import { paperClasses } from "@mui/material/Paper";
import { listClasses } from "@mui/material/List";
import ListItemText from "@mui/material/ListItemText";
import ListItemIcon, { listItemIconClasses } from "@mui/material/ListItemIcon";
import LogoutRoundedIcon from "@mui/icons-material/LogoutRounded";
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
import MenuButton from "../MenuButton";
import { Avatar } from "@mui/material";
import { useNavigate } from "react-router-dom";
const MenuItem = styled(MuiMenuItem)({
margin: '2px 0',
margin: "2px 0",
});
export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const dispatch = useDispatch();
const [cookies, setCookie, removeCookie] = useCookies(['authToken']);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const handleLogout = () => {
dispatch(logoutUser({ removeCookie }));
console.log('click')
handleClose();
};
return (
<React.Fragment>
<MenuButton
aria-label="Open menu"
onClick={handleClick}
sx={{ borderColor: 'transparent' }}
>
{avatar ? (
<MoreVertRoundedIcon />
) : (
<Avatar
sizes="small"
alt="Riley Carter"
src="/static/images/avatar/7.jpg"
sx={{ width: 36, height: 36 }}
/>
)}
</MenuButton>
<Menu
anchorEl={anchorEl}
id="menu"
open={open}
onClose={handleClose}
onClick={handleClose}
transformOrigin={{ horizontal: 'right', vertical: 'top' }}
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
sx={{
[`& .${listClasses.root}`]: {
padding: '4px',
},
[`& .${paperClasses.root}`]: {
padding: 0,
},
[`& .${dividerClasses.root}`]: {
margin: '4px -4px',
},
}}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<Divider />
<MenuItem onClick={handleClose}>Add another account</MenuItem>
<MenuItem onClick={handleClose}>Settings</MenuItem>
<Divider />
<MenuItem
onClick={handleLogout}
sx={{
[`& .${listItemIconClasses.root}`]: {
ml: 'auto',
minWidth: 0,
},
}}
>
<ListItemText>Logout</ListItemText>
<ListItemIcon>
<LogoutRoundedIcon fontSize="small" />
</ListItemIcon>
</MenuItem>
</Menu>
</React.Fragment>
);
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event?.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
//Eknoor singh and jaanvi
//date:- 12-Feb-2025
//Made a navigation page for the profile page
const navigate = useNavigate();
const handleProfile = () => {
navigate("/auth/profile");
};
return (
<React.Fragment>
<MenuButton
aria-label="Open menu"
onClick={handleClick}
sx={{ borderColor: "transparent" }}
>
{avatar ? (
<MoreVertRoundedIcon />
) : (
<Avatar
sizes="small"
alt="Riley Carter"
src="/static/images/avatar/7.jpg"
sx={{ width: 36, height: 36 }}
/>
)}
</MenuButton>
<Menu
anchorEl={anchorEl}
id="menu"
open={open}
onClose={handleClose}
onClick={handleClose}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
sx={{
[`& .${listClasses.root}`]: {
padding: "4px",
},
[`& .${paperClasses.root}`]: {
padding: 0,
},
[`& .${dividerClasses.root}`]: {
margin: "4px -4px",
},
}}
>
<MenuItem onClick={handleProfile}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<Divider />
<MenuItem onClick={handleClose}>Add another account</MenuItem>
<MenuItem onClick={handleClose}>Settings</MenuItem>
<Divider />
<MenuItem
onClick={handleClose}
sx={{
[`& .${listItemIconClasses.root}`]: {
ml: "auto",
minWidth: 0,
},
}}
>
<ListItemText>Logout</ListItemText>
<ListItemIcon>
<LogoutRoundedIcon fontSize="small" />
</ListItemIcon>
</MenuItem>
</Menu>
</React.Fragment>
);
}

View file

@ -1,93 +1,111 @@
import { styled } from '@mui/material/styles';
import Avatar from '@mui/material/Avatar';
import MuiDrawer, { drawerClasses } from '@mui/material/Drawer';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import MenuContent from '../MenuContent';
import OptionsMenu from '../OptionsMenu';
import React from 'react';
import { ArrowLeftIcon, ArrowRightIcon } from '@mui/x-date-pickers';
import { Button } from '@mui/material';
import { styled } from "@mui/material/styles";
import Avatar from "@mui/material/Avatar";
import MuiDrawer, { drawerClasses } from "@mui/material/Drawer";
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import MenuContent from "../MenuContent";
import OptionsMenu from "../OptionsMenu";
import { useDispatch, useSelector } from "react-redux";
import React, { useEffect } from "react";
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 Drawer = styled(MuiDrawer)({
width: drawerWidth,
flexShrink: 0,
boxSizing: 'border-box',
mt: 10,
[`& .${drawerClasses.paper}`]: {
width: drawerWidth,
boxSizing: 'border-box',
},
width: drawerWidth,
flexShrink: 0,
boxSizing: "border-box",
mt: 10,
[`& .${drawerClasses.paper}`]: {
width: drawerWidth,
boxSizing: "border-box",
},
});
export default function SideMenu() {
const [open, setOpen] = React.useState(true);
return (
<Drawer
open={open}
variant="permanent"
anchor="left"
sx={{
display: {
xs: 'none',
md: 'block',
width: open ? 220 : 80,
transition: 'all 0.5s ease',
},
[`& .${drawerClasses.paper}`]: {
backgroundColor: 'background.paper',
width: open ? 220 : 80,
transition: 'all 0.5s ease',
},
}}
>
<Box
sx={{
display: 'flex',
justifyContent: open ? 'flex-end' : 'center',
alignItems: 'center',
pt: 1.5,
textAlign: 'center',
}}
>
<Button variant="text" onClick={() => setOpen(!open)}>
{open ? <ArrowLeftIcon /> : <ArrowRightIcon />}
</Button>
</Box>
<MenuContent hidden={open} />
{/* <CardAlert /> */}
<Stack
direction="row"
sx={{
p: 2,
gap: 1,
alignItems: 'center',
borderTop: '1px solid',
borderColor: 'divider',
}}
>
<Avatar
sizes="small"
alt="Riley Carter"
src="/static/images/avatar/7.jpg"
sx={{ width: open ? 36 : 0, height: open ? 36 : 0 }}
/>
<Box sx={{ mr: 'auto', display: !open ? 'none' : 'block' }}>
<Typography
variant="body2"
sx={{ fontWeight: 500, lineHeight: '16px' }}
>
Riley Carter
</Typography>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
riley@email.com
</Typography>
</Box>
<OptionsMenu avatar={open} />
</Stack>
</Drawer>
);
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 (
<Drawer
open={open}
variant="permanent"
anchor="left"
sx={{
display: {
xs: "none",
md: "block",
width: open ? 250 : 80,
transition: "all 0.5s ease",
},
[`& .${drawerClasses.paper}`]: {
backgroundColor: "background.paper",
width: open ? 250 : 80,
transition: "all 0.5s ease",
},
}}
>
<Box
sx={{
display: "flex",
justifyContent: open ? "flex-end" : "center",
alignItems: "center",
pt: 1.5,
textAlign: "center",
}}
>
<Button variant="text" onClick={() => setOpen(!open)}>
{open ? <ArrowLeftIcon /> : <ArrowRightIcon />}
</Button>
</Box>
<MenuContent hidden={open} />
{/* <CardAlert /> */}
<Stack
direction="row"
sx={{
p: 2,
gap: 1,
alignItems: "center",
borderTop: "1px solid",
borderColor: "divider",
}}
>
<Avatar
sizes="small"
alt={user?.name || "User Avatar"}
src={"/static/images/avatar/7.jpg"}
sx={{ width: open ? 36 : 0, height: open ? 36 : 0 }}
/>
<Box sx={{ mr: "auto", display: !open ? "none" : "block" }}>
<Typography
variant="body2"
sx={{ fontWeight: 500, lineHeight: "16px" }}
>
{user?.name || "No Admin"}
</Typography>
<Typography
variant="caption"
sx={{ color: "text.secondary" }}
>
{user?.email || "No Email"}
</Typography>
</Box>
<OptionsMenu avatar={open} />
</Stack>
</Drawer>
);
}

View file

@ -1,32 +1,29 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import store from "./redux/store";
import { Slide, ToastContainer } from "react-toastify";
import { BrowserRouter as Router } from "react-router-dom";
import { CookiesProvider } from "react-cookie";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store/store.ts';
import { Slide, ToastContainer } from 'react-toastify';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<CookiesProvider defaultSetOptions={{ path: "/" }}>
<Provider store={store}>
<Router>
<App />
</Router>
<ToastContainer
autoClose={2000}
hideProgressBar
theme="dark"
transition={Slide}
toastStyle={{ border: "1px solid dimgray" }}
/>
</Provider>
</CookiesProvider>
</React.StrictMode>
<React.StrictMode>
<Provider store={store}>
<App />
<ToastContainer
autoClose={2000}
hideProgressBar
theme="dark"
transition={Slide}
toastStyle={{ border: '1px solid dimgray' }}
/>
</Provider>
</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 { Cookies } from "react-cookie";
// import axios from 'axios';
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,
});
http.interceptors.request.use((config) => {
const authToken = cookies.get("authToken");
console.log(authToken);
if (authToken) {
config.headers.Authorization = authToken;
}
return config;
// Axios instance for the local API
const apiHttp = axios.create({
baseURL: "http://localhost:5000/api",
});
http.interceptors.response.use(
(response) => response,
(error) => {
const isCookiePresent = cookies.get("authToken");
console.log(isCookiePresent,"jkk")
if (
error.response &&
isCookiePresent &&
(error.response.status === 403 || error.response.status === 401)
) {
cookies.remove("authToken", { path: "/" });
window.location.href = "/";
// Add interceptors to both instances
const addAuthInterceptor = (instance: AxiosInstance) => {
instance.interceptors.request.use((config) => {
const authToken = localStorage.getItem("authToken");
if (authToken) {
config.headers.Authorization = `Bearer ${authToken}`; // <-- Add "Bearer "
}
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 [phoneNumber, setPhoneNumber] = React.useState('');
const extractCountryCodeAndNumber = (phone) => {
const extractCountryCodeAndNumber = (phone: string) => {
// Match the country code (e.g., +91) and the rest of the number
const match = phone.match(/^(\+\d{1,3})\s*(\d+.*)/);
if (match) {
@ -92,7 +92,7 @@ const dispatch = useDispatch();
}
return { countryCode: '', numberWithoutCountryCode: phone };
};
const handleOnChange = (newPhone) => {
const handleOnChange = (newPhone: string) => {
const { countryCode, numberWithoutCountryCode } = extractCountryCodeAndNumber(newPhone);
console.log("numberWithoutCountryCode",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 axios from "axios";
import http from "../../lib/https";
import { backendHttp, apiHttp } from "../../lib/https";
import { toast } from "react-toastify";
import { Cookies } from "react-cookie";
const cookies = new Cookies();
// Define types for state
//Eknoor singh
//date:- 12-Feb-2025
//Token for the user has been declared
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;
name: string;
email: string;
role: string;
phone: string;
}
interface Admin {
id: string;
name: string;
role: string;
email: string;
}
interface AuthState {
user: User | null;
admins: Admin[];
isAuthenticated: 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
export const loginUser = createAsyncThunk<
User,
@ -39,8 +45,11 @@ export const loginUser = createAsyncThunk<
{ rejectValue: string }
>("auth/login", async ({ email, password }, { rejectWithValue }) => {
try {
const response = await http.post("admin/login", { email, password });
cookies.set("authToken", response.data?.data?.token);
const response = await apiHttp.post("auth/login", {
email,
password,
});
localStorage.setItem("authToken", response.data?.data?.token); // Save token
toast.success(response.data?.message);
return response.data;
} catch (error: any) {
@ -53,14 +62,17 @@ export const loginUser = createAsyncThunk<
// Async thunk for register
export const registerUser = createAsyncThunk<
User,
{ email: string; password: string },
{
name: string;
email: string;
password: string;
phone: string;
role: string;
},
{ rejectValue: string }
>("auth/register", async (data, { rejectWithValue }) => {
>("auth/signup", async (data, { rejectWithValue }) => {
try {
const response = await axios.post(
"https://health-digi.dmlabs.in/auth/register",
data
);
const response = await apiHttp.post("auth/signup", data);
return response.data;
} catch (error: any) {
return rejectWithValue(
@ -69,26 +81,121 @@ export const registerUser = createAsyncThunk<
}
});
export const logoutUser = createAsyncThunk<
void,
{ removeCookie: any },
{ rejectValue: string }
>("auth/logout", async ({ removeCookie }, { rejectWithValue }) => {
try {
removeCookie("authToken", { path: "/auth" });
toast.success("You have been logged out successfully.");
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "Failed to log out."
);
}
//created by Eknoor and jaanvi
//date: 10-Feb-2025
//Fetching list of admins
export const adminList = createAsyncThunk<
Admin[],
void,
{ rejectValue: string }
>("/auth", async (_, { rejectWithValue }) => {
try {
const response = await apiHttp.get("/auth");
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) {
return rejectWithValue(
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 = {
user: null,
admins: [],
isAuthenticated: false,
isLoading: false,
error: null,
//Eknoor singh
//date:- 12-Feb-2025
//initial state of token set to null
token: null,
};
const authSlice = createSlice({
@ -98,6 +205,11 @@ const authSlice = createSlice({
logout: (state) => {
state.user = null;
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) => {
@ -107,14 +219,12 @@ const authSlice = createSlice({
state.isLoading = true;
state.error = null;
})
.addCase(
loginUser.fulfilled,
(state, action: PayloadAction<User>) => {
state.isLoading = false;
state.isAuthenticated = true;
state.user = action.payload;
}
)
.addCase(loginUser.fulfilled, (state, action) => {
state.isLoading = false;
state.isAuthenticated = true;
state.user = action.payload; // Fix: Extract correct payload
state.token = action.payload.token; // Store token in Redux
})
.addCase(
loginUser.rejected,
(state, action: PayloadAction<string | undefined>) => {
@ -142,19 +252,82 @@ const authSlice = createSlice({
state.error = action.payload || "An error occurred";
}
)
// Logout
.addCase(logoutUser.fulfilled, (state) => {
state.user = null;
state.isAuthenticated = false;
// created by Jaanvi and Eknoor
//AdminList
.addCase(adminList.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(
logoutUser.rejected,
(state, action: PayloadAction<string | undefined>) => {
state.error =
action.payload || "An error occurred during logout";
adminList.fulfilled,
(state, action: PayloadAction<Admin[]>) => {
state.isLoading = false;
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;

View file

@ -1,10 +1,13 @@
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 AppDispatch = typeof store.dispatch;
export default store;

View file

@ -1,29 +1,25 @@
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 DashboardLayout from "./layouts/DashboardLayout";
import Login from "./pages/Auth/Login";
import SignUp from "./pages/Auth/SignUp";
import Dashboard from "./pages/Dashboard";
import Vehicles from "./pages/Vehicles";
import { useSelector } from "react-redux";
import { RootState } from "./redux/reducers";
import { useCookies } from "react-cookie";
import AdminList from "./pages/AdminList";
import ProfilePage from "./pages/ProfilePage";
interface ProtectedRouteProps {
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
);
import SuperAdminRouter from "./superAdminRouter";
if (!isAuthenticated && !isCookiePresent) {
return <Navigate to="/auth/login" replace />;
}
function ProtectedRoute({
caps,
component,
}: {
caps: string[];
component: React.ReactNode;
}) {
if (!localStorage.getItem("authToken"))
return <Navigate to={`/auth/login`} replace />;
return component;
}
@ -43,17 +39,52 @@ export default function AppRouter() {
<Route path="login" element={<Login />} />
<Route path="signup" element={<SignUp />} />
</Route>
<Route path="/panel" element={<DashboardLayout />}>
<Route
path="dashboard"
element={<ProtectedRoute component={<Dashboard />} />}
element={
<ProtectedRoute
caps={[]}
component={<Dashboard />}
/>
}
/>
<Route
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>
<Route
path="/auth/profile"
element={
<ProtectedRoute caps={[]} component={<ProfilePage />} />
}
/>
<Route path="*" element={<>404</>} />
</BaseRoutes>
</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,23 +1,22 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": [
"ES2023"
],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
}
}
"compilerOptions": {
"jsx": "react",
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
}
}