Implemented Notification feature and made changes in ui of view modal

This commit is contained in:
jaanvi 2025-02-20 10:24:49 +05:30
commit cadad61747
30 changed files with 2251 additions and 10647 deletions

26
package-lock.json generated
View file

@ -11,13 +11,14 @@
"@emotion/react": "^11.14.0", "@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0", "@emotion/styled": "^11.14.0",
"@mui/icons-material": "^6.3.0", "@mui/icons-material": "^6.3.0",
"@mui/material": "^6.3.0", "@mui/material": "^6.4.4",
"@mui/x-charts": "^7.23.2", "@mui/x-charts": "^7.23.2",
"@mui/x-data-grid": "^7.23.5", "@mui/x-data-grid": "^7.23.5",
"@mui/x-date-pickers": "^7.23.3", "@mui/x-date-pickers": "^7.27.0",
"@mui/x-tree-view": "^7.23.2", "@mui/x-tree-view": "^7.23.2",
"@react-spring/web": "^9.7.5", "@react-spring/web": "^9.7.5",
"@reduxjs/toolkit": "^2.5.0", "@reduxjs/toolkit": "^2.5.0",
"@types/babel__core": "^7.20.5",
"AdapterDayjs": "file:@mui/x-date-pickers/AdapterDayjs", "AdapterDayjs": "file:@mui/x-date-pickers/AdapterDayjs",
"add": "^2.0.6", "add": "^2.0.6",
"AppBar": "file:@mui/material/AppBar", "AppBar": "file:@mui/material/AppBar",
@ -40,7 +41,6 @@
"react-redux": "^9.2.0", "react-redux": "^9.2.0",
"react-router-dom": "^7.1.1", "react-router-dom": "^7.1.1",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"react-toastify": "^11.0.2",
"RichTreeView": "file:@mui/x-tree-view/RichTreeView", "RichTreeView": "file:@mui/x-tree-view/RichTreeView",
"sonner": "^1.7.4", "sonner": "^1.7.4",
"Stack": "file:@mui/material/Stack", "Stack": "file:@mui/material/Stack",
@ -3545,9 +3545,9 @@
} }
}, },
"node_modules/@mui/x-date-pickers": { "node_modules/@mui/x-date-pickers": {
"version": "7.26.0", "version": "7.27.0",
"resolved": "https://registry.npmjs.org/@mui/x-date-pickers/-/x-date-pickers-7.26.0.tgz", "resolved": "https://registry.npmjs.org/@mui/x-date-pickers/-/x-date-pickers-7.27.0.tgz",
"integrity": "sha512-bhSDce1b5MBYYlCdHQJBThe10LGTE3D/u53TDQ41+IRj+iiNCun8jivw3DxKhmoBxlB+hVdkcltpTtIGlPjQZQ==", "integrity": "sha512-wSx8JGk4WQ2hTObfQITc+zlmUKNleQYoH1hGocaQlpWpo1HhauDtcQfX6sDN0J0dPT2eeyxDWGj4uJmiSfQKcw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.25.7", "@babel/runtime": "^7.25.7",
@ -15299,19 +15299,6 @@
} }
} }
}, },
"node_modules/react-toastify": {
"version": "11.0.3",
"resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-11.0.3.tgz",
"integrity": "sha512-cbPtHJPfc0sGqVwozBwaTrTu1ogB9+BLLjd4dDXd863qYLj7DGrQ2sg5RAChjFUB4yc3w8iXOtWcJqPK/6xqRQ==",
"license": "MIT",
"dependencies": {
"clsx": "^2.1.1"
},
"peerDependencies": {
"react": "^18 || ^19",
"react-dom": "^18 || ^19"
}
},
"node_modules/react-transition-group": { "node_modules/react-transition-group": {
"version": "4.4.5", "version": "4.4.5",
"resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
@ -17703,6 +17690,7 @@
"version": "5.7.3", "version": "5.7.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz",
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
"dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",

View file

@ -6,18 +6,25 @@
"@emotion/react": "^11.14.0", "@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0", "@emotion/styled": "^11.14.0",
"@mui/icons-material": "^6.3.0", "@mui/icons-material": "^6.3.0",
"@mui/material": "^6.3.0", "@mui/material": "^6.4.4",
"@mui/x-charts": "^7.23.2", "@mui/x-charts": "^7.23.2",
"@mui/x-data-grid": "^7.23.5", "@mui/x-data-grid": "^7.23.5",
"@mui/x-date-pickers": "^7.23.3", "@mui/x-date-pickers": "^7.27.0",
"@mui/x-tree-view": "^7.23.2", "@mui/x-tree-view": "^7.23.2",
"@react-spring/web": "^9.7.5", "@react-spring/web": "^9.7.5",
"@reduxjs/toolkit": "^2.5.0", "@reduxjs/toolkit": "^2.5.0",
"@types/babel__core": "^7.20.5",
"AdapterDayjs": "file:@mui/x-date-pickers/AdapterDayjs", "AdapterDayjs": "file:@mui/x-date-pickers/AdapterDayjs",
"add": "^2.0.6",
"AppBar": "file:@mui/material/AppBar", "AppBar": "file:@mui/material/AppBar",
"axios": "^1.7.9",
"Box": "file:@mui/material/Box", "Box": "file:@mui/material/Box",
"PieChart": "file:@mui/x-charts/PieChart",
"RichTreeView": "file:@mui/x-tree-view/RichTreeView",
"Stack": "file:@mui/material/Stack",
"Tabs": "file:@mui/material/Tabs",
"Toolbar": "file:@mui/material/Toolbar",
"Typography": "file:@mui/material/Typography",
"add": "^2.0.6",
"axios": "^1.7.9",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cra-template-typescript": "1.2.0", "cra-template-typescript": "1.2.0",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
@ -25,7 +32,6 @@
"hooks": "file:@mui/x-charts/hooks", "hooks": "file:@mui/x-charts/hooks",
"mui-phone-number": "^3.0.3", "mui-phone-number": "^3.0.3",
"mui-tel-input": "^7.0.0", "mui-tel-input": "^7.0.0",
"PieChart": "file:@mui/x-charts/PieChart",
"prop-types": "^15.8.1", "prop-types": "^15.8.1",
"react": "^18.0.0", "react": "^18.0.0",
"react-cookie": "^7.2.2", "react-cookie": "^7.2.2",
@ -35,14 +41,8 @@
"react-redux": "^9.2.0", "react-redux": "^9.2.0",
"react-router-dom": "^7.1.1", "react-router-dom": "^7.1.1",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"react-toastify": "^11.0.2",
"RichTreeView": "file:@mui/x-tree-view/RichTreeView",
"sonner": "^1.7.4", "sonner": "^1.7.4",
"Stack": "file:@mui/material/Stack",
"styles": "file:@mui/material/styles", "styles": "file:@mui/material/styles",
"Tabs": "file:@mui/material/Tabs",
"Toolbar": "file:@mui/material/Toolbar",
"Typography": "file:@mui/material/Typography",
"web-vitals": "^4.2.4" "web-vitals": "^4.2.4"
}, },
"scripts": { "scripts": {

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,139 @@
// import React from "react";
// import {
// Button,
// Dialog,
// DialogActions,
// DialogContent,
// DialogTitle,
// TextField,
// } from "@mui/material";
// import { useForm, Controller } from "react-hook-form";
// interface AddAdminModalProps {
// open: boolean;
// handleClose: () => void;
// handleAdd: (name: string, email: string, phone: string, registeredAddress: string) => void;
// }
// interface FormData {
// name: string;
// email: string;
// phone: string;
// registeredAddress: string;
// }
// const AddAdminModal: React.FC<AddAdminModalProps> = ({ open, handleClose, handleAdd }) => {
// const { control, handleSubmit, reset, formState: { errors } } = useForm<FormData>({
// defaultValues: {
// name: "",
// email: "",
// phone: "",
// registeredAddress: "",
// },
// });
// const onSubmit = (data: FormData) => {
// handleAdd(data.name, data.email, data.phone, data.registeredAddress);
// handleClose();
// reset();
// };
// return (
// <Dialog
// open={open}
// onClose={handleClose}
// maxWidth="md"
// fullWidth
// PaperProps={{
// component: "form",
// onSubmit: handleSubmit(onSubmit),
// }}
// >
// <DialogTitle>Add Admin</DialogTitle>
// <DialogContent>
// <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="email"
// control={control}
// rules={{ required: "Email is required" }}
// render={({ field }) => (
// <TextField
// {...field}
// required
// margin="dense"
// label="Email"
// type="text"
// fullWidth
// variant="standard"
// error={!!errors.email}
// helperText={errors.email?.message}
// />
// )}
// />
// <Controller
// name="phone"
// control={control}
// rules={{ required: "Phone number is required" }}
// render={({ field }) => (
// <TextField
// {...field}
// required
// margin="dense"
// label="Phone Number"
// type="text"
// fullWidth
// variant="standard"
// error={!!errors.phone}
// helperText={errors.phone?.message}
// />
// )}
// />
// <Controller
// name="registeredAddress"
// control={control}
// rules={{ required: "Address is required" }}
// render={({ field }) => (
// <TextField
// {...field}
// required
// margin="dense"
// label="Address"
// type="text"
// fullWidth
// variant="standard"
// error={!!errors.registeredAddress}
// helperText={errors.registeredAddress?.message}
// />
// )}
// />
// </DialogContent>
// <DialogActions>
// <Button onClick={handleClose}>Cancel</Button>
// <Button type="submit">Save</Button>
// </DialogActions>
// </Dialog>
// );
// };
// export default AddAdminModal;

View file

@ -1,5 +1,6 @@
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import { import {
Box,
Button, Button,
Dialog, Dialog,
DialogActions, DialogActions,
@ -7,12 +8,14 @@ import {
DialogTitle, DialogTitle,
TextField, TextField,
} from "@mui/material"; } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form"; import { useForm, Controller } from "react-hook-form";
//By Jaanvi : Edit Model :: 11-feb-25 //By Jaanvi : Edit Model :: 11-feb-25
interface AddEditCategoryModalProps { interface AddEditCategoryModalProps {
open: boolean; open: boolean;
handleClose: () => void; handleClose: () => void;
handleCreate: (data: FormData) => void;
handleUpdate: ( handleUpdate: (
id: string, id: string,
name: string, name: string,
@ -21,7 +24,6 @@ interface AddEditCategoryModalProps {
registeredAddress: string registeredAddress: string
) => void; ) => void;
editRow: any; editRow: any;
handleAdd: Function;
} }
interface FormData { interface FormData {
@ -34,9 +36,9 @@ interface FormData {
const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
open, open,
handleClose, handleClose,
editRow, handleCreate,
handleUpdate, handleUpdate,
handleAdd, editRow,
}) => { }) => {
const { const {
control, control,
@ -63,13 +65,7 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
data.registeredAddress data.registeredAddress
); );
} else { } else {
// Call handleAdd if adding new admin handleCreate(data);
handleAdd(
data.name,
data.email,
data.phone,
data.registeredAddress
);
} }
handleClose(); handleClose();
reset(); reset();
@ -78,9 +74,8 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
useEffect(() => { useEffect(() => {
if (editRow) { if (editRow) {
setValue("name", editRow.name); setValue("name", editRow.name);
setValue("email", editRow.role);
setValue("phone", editRow.phone);
setValue("email", editRow.email); setValue("email", editRow.email);
setValue("phone", editRow.phone);
setValue("registeredAddress", editRow.registeredAddress); setValue("registeredAddress", editRow.registeredAddress);
} else { } else {
reset(); reset();
@ -88,114 +83,156 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
}, [editRow, setValue, reset]); }, [editRow, setValue, reset]);
return ( return (
<> <Dialog
<Dialog open={open}
open={open} onClose={handleClose}
onClose={handleClose} maxWidth="md"
maxWidth="md" fullWidth
fullWidth PaperProps={{
PaperProps={{ component: "form",
component: "form", onSubmit: handleSubmit(onSubmit),
onSubmit: handleSubmit(onSubmit), }}
>
<DialogTitle
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}} }}
> >
<DialogTitle>{editRow ? "Edit" : "Add"} Admin</DialogTitle> {editRow ? "Edit Admin" : "Add Admin"}
<DialogContent> <Box
<Controller onClick={handleClose}
name="name" sx={{
control={control} cursor: "pointer",
rules={{ display: "flex",
required: "Admin Name is required", alignItems: "center",
}} }}
render={({ field }) => ( >
<TextField <CloseIcon />
{...field} </Box>
autoFocus </DialogTitle>
required
margin="dense"
label="Admin Name"
type="text"
fullWidth
variant="standard"
error={!!errors.name}
helperText={errors.name?.message}
/>
)}
/>
<Controller <DialogContent>
name="email" <Controller
control={control} name="name"
rules={{ control={control}
required: "Email is required", rules={{
}} required: "Admin Name is required",
render={({ field }) => ( minLength: {
<TextField value: 3,
{...field} message: "Minimum 3 characters required",
margin="dense" },
label="Email" maxLength: {
type="text" value: 30,
fullWidth message: "Maximum 30 characters allowed",
variant="standard" },
error={!!errors.email} }}
helperText={errors.email?.message} render={({ field }) => (
/> <TextField
)} {...field}
/> autoFocus
<Controller required
name="phone" margin="dense"
control={control} label="Admin Name"
rules={{ type="text"
required: "Phone no. is required", fullWidth
pattern: { variant="standard"
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i, error={!!errors.name}
message: "Invalid Phone Number", helperText={errors.name?.message}
}, />
maxLength:{ )}
value:10, />
message:"Phone no must be 10 digits"
} <Controller
name="email"
}} control={control}
render={({ field }) => ( rules={{
<TextField required: "Email is required",
{...field} pattern: {
margin="dense" value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
label="Phone" message: "Invalid email address",
type="tel" },
fullWidth }}
variant="standard" render={({ field }) => (
error={!!errors.phone} <TextField
helperText={errors.phone?.message} {...field}
/> required
)} margin="dense"
/> label="Email"
<Controller type="email"
name="registeredAddress" fullWidth
control={control} variant="standard"
rules={{ error={!!errors.email}
required: "Address is required", helperText={errors.email?.message}
}} />
render={({ field }) => ( )}
<TextField />
{...field}
margin="dense" <Controller
label="Address" name="phone"
type="text" control={control}
fullWidth rules={{
variant="standard" required: "Phone number is required",
error={!!errors.registeredAddress} pattern: {
helperText={errors.registeredAddress?.message} value: /^[0-9]*$/,
/> message: "Only numbers are allowed",
)} },
/> minLength: {
</DialogContent> value: 6,
<DialogActions> message: "Phone number must be exactly 6 digits",
<Button onClick={handleClose}>Cancel</Button> },
<Button type="submit">Save</Button> maxLength: {
</DialogActions> value: 14,
</Dialog> message: "Phone number must be exactly 14 digits",
</> },
}}
render={({ field }) => (
<TextField
{...field}
required
margin="dense"
label="Phone Number"
type="tel"
fullWidth
variant="standard"
error={!!errors.phone}
helperText={errors.phone?.message}
/>
)}
/>
<Controller
name="registeredAddress"
control={control}
rules={{
required: "Address is required",
maxLength: {
value: 100,
message: "Address cannot exceed 100 characters",
},
}}
render={({ field }) => (
<TextField
{...field}
required
margin="dense"
label="Address"
type="text"
fullWidth
variant="standard"
error={!!errors.registeredAddress}
helperText={errors.registeredAddress?.message}
/>
)}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button type="submit">{editRow ? "Update" : "Create"}</Button>
</DialogActions>
</Dialog>
); );
}; };

View file

@ -1,105 +1,112 @@
import * as React from 'react'; import * as React from "react";
import { styled } from '@mui/material/styles'; import { styled } from "@mui/material/styles";
import AppBar from '@mui/material/AppBar'; import AppBar from "@mui/material/AppBar";
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 MuiToolbar from '@mui/material/Toolbar'; import MuiToolbar from "@mui/material/Toolbar";
import { tabsClasses } from '@mui/material/Tabs'; import { tabsClasses } from "@mui/material/Tabs";
import Typography from '@mui/material/Typography'; import Typography from "@mui/material/Typography";
import MenuRoundedIcon from '@mui/icons-material/MenuRounded'; import MenuRoundedIcon from "@mui/icons-material/MenuRounded";
import DashboardRoundedIcon from '@mui/icons-material/DashboardRounded'; import DashboardRoundedIcon from "@mui/icons-material/DashboardRounded";
import ColorModeIconDropdown from '../../shared-theme/ColorModeIconDropdown'; import ColorModeIconDropdown from "../../shared-theme/ColorModeIconDropdown";
import MenuButton from '../MenuButton'; import MenuButton from "../MenuButton";
import SideMenuMobile from '../SideMenuMobile'; import SideMenuMobile from "../SideMenuMobile";
import NotificationsRoundedIcon from "@mui/icons-material/NotificationsRounded";
const Toolbar = styled(MuiToolbar)({ const Toolbar = styled(MuiToolbar)({
width: '100%', width: "100%",
padding: '12px', padding: "12px",
display: 'flex', display: "flex",
flexDirection: 'column', flexDirection: "column",
alignItems: 'start', alignItems: "start",
justifyContent: 'center', justifyContent: "center",
gap: '12px', gap: "12px",
flexShrink: 0, flexShrink: 0,
[`& ${tabsClasses.flexContainer}`]: { [`& ${tabsClasses.flexContainer}`]: {
gap: '8px', gap: "8px",
p: '8px', p: "8px",
pb: 0, pb: 0,
}, },
}); });
export default function AppNavbar() { export default function AppNavbar() {
const [open, setOpen] = React.useState(false); const [open, setOpen] = React.useState(false);
const toggleDrawer = (newOpen: boolean) => () => { const toggleDrawer = (newOpen: boolean) => () => {
setOpen(newOpen); setOpen(newOpen);
}; };
return ( return (
<AppBar <AppBar
position="fixed" position="fixed"
sx={{ sx={{
display: { xs: 'auto', md: 'none' }, display: { xs: "auto", md: "none" },
boxShadow: 0, boxShadow: 0,
bgcolor: 'background.paper', bgcolor: "background.paper",
backgroundImage: 'none', backgroundImage: "none",
borderBottom: '1px solid', borderBottom: "1px solid",
borderColor: 'divider', borderColor: "divider",
top: 'var(--template-frame-height, 0px)', top: "var(--template-frame-height, 0px)",
}} }}
> >
<Toolbar variant="regular"> <Toolbar variant="regular">
<Stack <Stack
direction="row" direction="row"
sx={{ sx={{
alignItems: 'center', alignItems: "center",
flexGrow: 1, flexGrow: 1,
width: '100%', width: "100%",
gap: 1, gap: 1,
}} }}
> >
<Stack <Stack
direction="row" direction="row"
spacing={1} spacing={1}
sx={{ justifyContent: 'center', mr: 'auto' }} sx={{ justifyContent: "center", mr: "auto" }}
> >
<CustomIcon /> <CustomIcon />
<Typography variant="h4" component="h1" sx={{ color: 'text.primary' }}> <Typography
Dashboard variant="h4"
</Typography> component="h1"
</Stack> sx={{ color: "text.primary" }}
<ColorModeIconDropdown /> >
<MenuButton aria-label="menu" onClick={toggleDrawer(true)}> Dashboard
<MenuRoundedIcon /> </Typography>
</MenuButton> </Stack>
<SideMenuMobile open={open} toggleDrawer={toggleDrawer} /> <ColorModeIconDropdown />
</Stack> <MenuButton aria-label="menu" onClick={toggleDrawer(true)}>
</Toolbar> <MenuRoundedIcon />
</AppBar> </MenuButton>
);
<SideMenuMobile open={open} toggleDrawer={toggleDrawer} />
</Stack>
</Toolbar>
</AppBar>
);
} }
export function CustomIcon() { export function CustomIcon() {
return ( return (
<Box <Box
sx={{ sx={{
width: '1.5rem', width: "1.5rem",
height: '1.5rem', height: "1.5rem",
bgcolor: 'black', bgcolor: "black",
borderRadius: '999px', borderRadius: "999px",
display: 'flex', display: "flex",
justifyContent: 'center', justifyContent: "center",
alignItems: 'center', alignItems: "center",
alignSelf: 'center', alignSelf: "center",
backgroundImage: backgroundImage:
'linear-gradient(135deg, hsl(210, 98%, 60%) 0%, hsl(210, 100%, 35%) 100%)', "linear-gradient(135deg, hsl(210, 98%, 60%) 0%, hsl(210, 100%, 35%) 100%)",
color: 'hsla(210, 100%, 95%, 0.9)', color: "hsla(210, 100%, 95%, 0.9)",
border: '1px solid', border: "1px solid",
borderColor: 'hsl(210, 100%, 55%)', borderColor: "hsl(210, 100%, 55%)",
boxShadow: 'inset 0 2px 5px rgba(255, 255, 255, 0.3)', boxShadow: "inset 0 2px 5px rgba(255, 255, 255, 0.3)",
}} }}
> >
<DashboardRoundedIcon color="inherit" sx={{ fontSize: '1rem' }} /> <DashboardRoundedIcon color="inherit" sx={{ fontSize: "1rem" }} />
</Box> </Box>
); );
} }

View file

@ -34,21 +34,21 @@ function ButtonField(props: ButtonFieldProps) {
inputProps: { 'aria-label': ariaLabel } = {}, inputProps: { 'aria-label': ariaLabel } = {},
} = props; } = props;
return ( // return (
<Button // // <Button
variant="outlined" // // variant="outlined"
id={id} // // id={id}
disabled={disabled} // // disabled={disabled}
ref={ref} // // ref={ref}
aria-label={ariaLabel} // // aria-label={ariaLabel}
size="small" // // size="small"
onClick={() => setOpen?.((prev) => !prev)} // // onClick={() => setOpen?.((prev) => !prev)}
startIcon={<CalendarTodayRoundedIcon fontSize="small" />} // // startIcon={<CalendarTodayRoundedIcon fontSize="small" />}
sx={{ minWidth: 'fit-content' }} // // sx={{ minWidth: 'fit-content' }}
> // // >
{label ? `${label}` : 'Pick a date'} // // {label ? `${label}` : 'Pick a date'}
</Button> // // </Button>
); // );
} }
export default function CustomDatePicker() { export default function CustomDatePicker() {

View file

@ -18,9 +18,9 @@ import {
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 DeleteModal from "../Modals/DeleteModal";
import { AppDispatch } from "../../redux/store/store"; import { AppDispatch } from "../../redux/store/store";
import ViewModal from "../Modals/ViewModal/ViewModal"; import ViewModal from "../Modals/ViewModal";
// Styled components for customization // Styled components for customization
const StyledTableCell = styled(TableCell)(({ theme }) => ({ const StyledTableCell = styled(TableCell)(({ theme }) => ({
@ -77,6 +77,7 @@ const CustomTable: React.FC<CustomTableProps> = ({
const dispatch = useDispatch<AppDispatch>(); const dispatch = useDispatch<AppDispatch>();
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null); const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const [selectedRow, setSelectedRow] = React.useState<Row | null>(null); const [selectedRow, setSelectedRow] = React.useState<Row | null>(null);
const open = Boolean(anchorEl); const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => { const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
@ -105,6 +106,8 @@ const CustomTable: React.FC<CustomTableProps> = ({
const handleViewButton = (id: string | undefined) => { const handleViewButton = (id: string | undefined) => {
if (!id) console.error("ID not found", id); if (!id) console.error("ID not found", id);
dispatch(adminList());
setViewModal(false); setViewModal(false);
}; };

View file

@ -0,0 +1,153 @@
// import React, { useEffect } from "react";
// import {
// Button,
// Dialog,
// DialogActions,
// DialogContent,
// DialogTitle,
// TextField,
// } from "@mui/material";
// import { useForm, Controller } from "react-hook-form";
// interface EditAdminModalProps {
// open: boolean;
// handleClose: () => void;
// handleUpdate: (id: string, name: string, email: string, phone: string, registeredAddress: string) => void;
// editRow: any;
// }
// interface FormData {
// name: string;
// email: string;
// phone: string;
// registeredAddress: string;
// }
// const EditAdminModal: React.FC<EditAdminModalProps> = ({ open, handleClose, editRow, handleUpdate }) => {
// const { control, handleSubmit, setValue, reset, formState: { errors } } = useForm<FormData>({
// defaultValues: {
// name: "",
// email: "",
// phone: "",
// registeredAddress: "",
// },
// });
// useEffect(() => {
// if (editRow) {
// setValue("name", editRow.name);
// setValue("email", editRow.email);
// setValue("phone", editRow.phone);
// setValue("registeredAddress", editRow.registeredAddress);
// } else {
// reset();
// }
// }, [editRow, setValue, reset]);
// const onSubmit = (data: FormData) => {
// if (editRow) {
// handleUpdate(editRow.id, data.name, data.email, data.phone, data.registeredAddress);
// handleClose();
// reset();
// }
// };
// return (
// <Dialog
// open={open}
// onClose={handleClose}
// maxWidth="md"
// fullWidth
// PaperProps={{
// component: "form",
// onSubmit: handleSubmit(onSubmit),
// }}
// >
// <DialogTitle>Edit Admin</DialogTitle>
// <DialogContent>
// <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="email"
// control={control}
// rules={{ required: "Email is required" }}
// render={({ field }) => (
// <TextField
// {...field}
// required
// margin="dense"
// label="Email"
// type="text"
// fullWidth
// variant="standard"
// error={!!errors.email}
// helperText={errors.email?.message}
// />
// )}
// />
// <Controller
// name="phone"
// control={control}
// rules={{ required: "Phone number is required" }}
// render={({ field }) => (
// <TextField
// {...field}
// required
// margin="dense"
// label="Phone Number"
// type="text"
// fullWidth
// variant="standard"
// error={!!errors.phone}
// helperText={errors.phone?.message}
// />
// )}
// />
// <Controller
// name="registeredAddress"
// control={control}
// rules={{ required: "Address is required" }}
// render={({ field }) => (
// <TextField
// {...field}
// required
// margin="dense"
// label="Address"
// type="text"
// fullWidth
// variant="standard"
// error={!!errors.registeredAddress}
// helperText={errors.registeredAddress?.message}
// />
// )}
// />
// </DialogContent>
// <DialogActions>
// <Button onClick={handleClose}>Cancel</Button>
// <Button type="submit">Save</Button>
// </DialogActions>
// </Dialog>
// );
// };
// export default EditAdminModal;

View file

@ -1,36 +1,63 @@
import * as React from 'react'; import * as React from "react";
import Stack from '@mui/material/Stack'; import Stack from "@mui/material/Stack";
import NotificationsRoundedIcon from '@mui/icons-material/NotificationsRounded'; import NotificationsRoundedIcon from "@mui/icons-material/NotificationsRounded";
import CustomDatePicker from '../CustomDatePicker'; import CustomDatePicker from "../CustomDatePicker";
import NavbarBreadcrumbs from '../NavbarBreadcrumbs'; import NavbarBreadcrumbs from "../NavbarBreadcrumbs";
import MenuButton from '../MenuButton'; import MenuButton from "../MenuButton";
import ColorModeIconDropdown from '../../shared-theme/ColorModeIconDropdown'; import ColorModeIconDropdown from "../../shared-theme/ColorModeIconDropdown";
import Box from "@mui/material/Box";
import Search from '../Search'; import Typography from "@mui/material/Typography";
import Search from "../Search";
export default function Header() { export default function Header() {
return ( const [showNotifications, setShowNotifications] = React.useState(false);
<Stack const toggleNotifications = () => {
direction="row" setShowNotifications((prev) => !prev);
sx={{ };
display: { xs: 'none', md: 'flex' }, return (
width: '100%', <Stack
alignItems: { xs: 'flex-start', md: 'center' }, direction="row"
justifyContent: 'space-between', sx={{
maxWidth: { sm: '100%', md: '1700px' }, display: { xs: "none", md: "flex" },
pt: 1.5, width: "100%",
}} alignItems: { xs: "flex-start", md: "center" },
spacing={2} justifyContent: "space-between",
> maxWidth: { sm: "100%", md: "1700px" },
<NavbarBreadcrumbs /> pt: 1.5,
<Stack direction="row" sx={{ gap: 1 }}> }}
<Search /> spacing={2}
<CustomDatePicker /> >
<MenuButton showBadge aria-label="Open notifications"> <NavbarBreadcrumbs />
<NotificationsRoundedIcon /> <Stack direction="row" sx={{ gap: 1 }}>
</MenuButton> <Search />
<ColorModeIconDropdown /> <CustomDatePicker />
</Stack> <MenuButton
</Stack> showBadge
); aria-label="Open notifications"
onClick={toggleNotifications}
>
<NotificationsRoundedIcon />
</MenuButton>
<ColorModeIconDropdown />
</Stack>
{showNotifications && (
<Box
sx={{
p: 2,
position: "absolute",
top: "55px", // Adjust this value according to your AppBar height
right: "66px",
bgcolor: "lightblue",
boxShadow: 1,
borderRadius: 1,
zIndex: 1300,
}}
>
<Typography variant="body2" color="text.secondary">
No notifications yet
</Typography>
</Box>
)}
</Stack>
);
} }

View file

@ -0,0 +1,35 @@
// Logout.tsx
import React from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import LogoutModal from "../Modals/LogOutModal";
interface LogoutProps {
setLogoutModal: React.Dispatch<React.SetStateAction<boolean>>;
logoutModal: boolean;
}
const Logout: React.FC<LogoutProps> = ({ setLogoutModal, logoutModal }) => {
const navigate = useNavigate();
const handlelogout = () => {
localStorage.clear();
navigate("/auth/login");
toast.success("Logged out successfully");
setLogoutModal(false);
};
return (
<>
{logoutModal && (
<LogoutModal
handlelogout={handlelogout}
open={logoutModal}
setLogoutModal={setLogoutModal}
/>
)}
</>
);
};
export default Logout;

View file

@ -74,21 +74,6 @@ export default function MainGrid() {
<PageViewsBarChart /> <PageViewsBarChart />
</Grid> </Grid>
</Grid> </Grid>
<Typography component="h2" variant="h6" sx={{ mb: 2 }}>
Details
</Typography>
<Grid container spacing={2} columns={12}>
<Grid size={{ xs: 12, lg: 9 }}>
<CustomizedDataGrid />
</Grid>
<Grid size={{ xs: 12, lg: 3 }}>
<Stack gap={2} direction={{ xs: 'column', sm: 'row', lg: 'column' }}>
<CustomizedTreeView />
<ChartUserByCountry />
</Stack>
</Grid>
</Grid>
<Copyright sx={{ my: 4 }} />
</Box> </Box>
); );
} }

View file

@ -1,23 +1,23 @@
import * as React from 'react'; import * as React from "react";
import Badge, { badgeClasses } from '@mui/material/Badge'; import Badge, { badgeClasses } from "@mui/material/Badge";
import IconButton, { IconButtonProps } from '@mui/material/IconButton'; import IconButton, { IconButtonProps } from "@mui/material/IconButton";
export interface MenuButtonProps extends IconButtonProps { export interface MenuButtonProps extends IconButtonProps {
showBadge?: boolean; showBadge?: boolean;
} }
export default function MenuButton({ export default function MenuButton({
showBadge = false, showBadge = false,
...props ...props
}: MenuButtonProps) { }: MenuButtonProps) {
return ( return (
<Badge <Badge
color="error" color="error"
variant="dot" variant="dot"
invisible={!showBadge} invisible={!showBadge}
sx={{ [`& .${badgeClasses.badge}`]: { right: 2, top: 2 } }} sx={{ [`& .${badgeClasses.badge}`]: { right: 2, top: 2 } }}
> >
<IconButton size="small" {...props} /> <IconButton size="small" {...props} />
</Badge> </Badge>
); );
} }

View file

@ -5,7 +5,7 @@ import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText"; import ListItemText from "@mui/material/ListItemText";
import Stack from "@mui/material/Stack"; import Stack from "@mui/material/Stack";
import HomeRoundedIcon from "@mui/icons-material/HomeRounded"; import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
import AnalyticsRoundedIcon from "@mui/icons-material/AnalyticsRounded"; // import AnalyticsRoundedIcon from "@mui/icons-material/AnalyticsRounded";
import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted"; import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted";
import { Link, useLocation } from "react-router-dom"; import { Link, useLocation } from "react-router-dom";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
@ -17,7 +17,6 @@ const baseMenuItems = [
icon: <HomeRoundedIcon />, icon: <HomeRoundedIcon />,
url: "/panel/dashboard", url: "/panel/dashboard",
}, },
// { // {
// text: "Vehicles", // text: "Vehicles",
// icon: <AnalyticsRoundedIcon />, // icon: <AnalyticsRoundedIcon />,

View file

@ -0,0 +1,98 @@
import { Box, Button, Modal, Typography } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
type Props = {
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,
};
const btnStyle = { py: 1, px: 5, width: "50%", textTransform: "capitalize" };
export default function DeleteModal({
open,
setDeleteModal,
handleDelete,
id,
}: Props) {
// console.log("DeleteModal opened with ID:", id)
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"
sx={{ flexGrow: 1 }} // This ensures the title takes up available space
>
Delete Record
</Typography>
<Box
onClick={() => setDeleteModal(false)}
sx={{
cursor: "pointer",
display: "flex",
alignItems: "center",
justifyContent: "flex-end", // Aligns the close icon to the right
marginTop: -3.5
}}
>
<CloseIcon />
</Box>
<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,12 +1,12 @@
import { Box, Button, Modal, Typography } from "@mui/material" import { Box, Button, Modal, Typography } from "@mui/material";
import CloseIcon from '@mui/icons-material/Close';
type Props = { type Props = {
open: boolean open: boolean;
setDeleteModal: Function setLogoutModal: Function;
handleDelete: (id: string | undefined) => void handlelogout: any;
id?: string | undefined };
}
const style = { const style = {
position: "absolute", position: "absolute",
top: "50%", top: "50%",
@ -17,18 +17,15 @@ const style = {
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 LogoutModal({
open, open,
setDeleteModal, setLogoutModal,
handleDelete, handlelogout,
id,
}: Props) { }: Props) {
// console.log("DeleteModal opened with ID:", id)
return ( return (
<Modal <Modal
open={open} open={open}
@ -36,20 +33,20 @@ export default function DeleteModal({
aria-describedby="modal-modal-description" aria-describedby="modal-modal-description"
> >
<Box sx={style}> <Box sx={style}>
<Typography <Typography id="modal-title" variant="h5" fontWeight="bold" sx={{ width: "100%" }}>
id="modal-modal-title" <Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%" }}>
variant="h6" <Box sx={{ flex: 1, textAlign: "center" }}>Logout</Box>
component="h2" <Box onClick={() => setLogoutModal(false)} sx={{ cursor: "pointer", display: "flex", alignItems: "center" }}>
align="center" <CloseIcon />
> </Box>
Delete Record </Box>
</Typography> </Typography>
<Typography <Typography
id="modal-modal-description" id="modal-modal-description"
sx={{ mt: 2 }} sx={{ mt: 2 }}
align="center" align="center"
> >
Are you sure you want to delete this record? Are you sure you want to Logout?
</Typography> </Typography>
<Box <Box
sx={{ sx={{
@ -64,7 +61,7 @@ export default function DeleteModal({
color="error" color="error"
type="button" type="button"
sx={btnStyle} sx={btnStyle}
onClick={() => setDeleteModal(false)} onClick={() => setLogoutModal(false)}
> >
Cancel Cancel
</Button> </Button>
@ -73,12 +70,12 @@ export default function DeleteModal({
type="button" type="button"
color="primary" color="primary"
sx={btnStyle} sx={btnStyle}
onClick={() => handleDelete(id || "")} onClick={() => handlelogout()}
> >
Delete Logout
</Button> </Button>
</Box> </Box>
</Box> </Box>
</Modal> </Modal>
) );
} }

View file

@ -0,0 +1,126 @@
import { Box, Button, Modal, Typography, Divider } from "@mui/material";
import { RootState } from "../../../redux/store/store";
import { useSelector } from "react-redux";
import { useEffect, useState } from "react";
import CloseIcon from "@mui/icons-material/Close";
type Props = {
open: boolean;
setViewModal: Function;
id?: string;
};
const style = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "background.paper",
borderRadius: 2,
boxShadow: "0px 4px 20px rgba(0, 0, 0, 0.15)",
p: 4,
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 2,
};
const btnStyle = {
mt: 2,
px: 5,
py: 1.2,
width: "100%",
textTransform: "capitalize",
};
export default function ViewModal({ open, setViewModal, id }: Props) {
const { admins } = useSelector((state: RootState) => state.adminReducer);
const [selectedAdmin, setSelectedAdmin] = useState<any>(null);
useEffect(() => {
if (id) {
const admin = admins.find((admin) => admin.id === id);
setSelectedAdmin(admin);
}
}, [id, admins]);
return (
<Modal
open={open}
aria-labelledby="modal-title"
aria-describedby="modal-description"
>
<Box sx={style}>
<Typography
id="modal-title"
variant="h5"
fontWeight="bold"
sx={{ width: "100%" }}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
width: "100%",
}}
>
<Box sx={{ flex: 1, textAlign: "center" }}>
{selectedAdmin?.name}'s Details
</Box>
<Box
onClick={() => setViewModal(false)}
sx={{
cursor: "pointer",
display: "flex",
alignItems: "center",
}}
>
<CloseIcon />
</Box>
</Box>
</Typography>
<Divider sx={{ width: "100%" }} />
{selectedAdmin ? (
<Box
sx={{
width: "80%",
textAlign: "left",
display: "flex",
flexDirection: "column",
gap: 1.5,
whiteSpace: "pre-wrap", // the text wraps properly
wordBreak: "break-word",
overflowWrap: "break-word",
}}
>
<Typography variant="body1">
<b>Name:</b> {selectedAdmin.name}
</Typography>
<Typography variant="body1">
<strong>Email:</strong> {selectedAdmin.email}
</Typography>
<Typography variant="body1">
<strong>Phone:</strong> {selectedAdmin.phone}
</Typography>
<Typography variant="body1">
<strong>Address:</strong>{" "}
{selectedAdmin.registeredAddress ?? "N/A"}
</Typography>
</Box>
) : (
<Typography align="center">
No admin found with this ID
</Typography>
)}
{/* <Button variant="contained" color="error" sx={btnStyle} onClick={() => setViewModal(false)}>
Close
</Button> */}
</Box>
</Modal>
);
}

View file

@ -12,108 +12,109 @@ import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
import MenuButton from "../MenuButton"; import MenuButton from "../MenuButton";
import { Avatar } from "@mui/material"; import { Avatar } from "@mui/material";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import Logout from "../LogOut/logOutfunc"; import Logout from "../LogOutFunction/LogOutFunction";
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 [logoutModal, setLogoutModal] = React.useState<boolean>(false); const [logoutModal, setLogoutModal] = React.useState<boolean>(false);
const open = Boolean(anchorEl); const open = Boolean(anchorEl);
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 //Eknoor singh and jaanvi
//date:- 12-Feb-2025 //date:- 12-Feb-2025
//Made a navigation page for the profile page //Made a navigation page for the profile page
const navigate = useNavigate(); const navigate = useNavigate();
const handleProfile = () => { const handleProfile = () => {
navigate("/panel/profile"); navigate("/panel/profile");
}; };
//jaanvi //jaanvi
//date:- 13-Feb-2025 //date:- 13-Feb-2025
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 />
) : ( ) : (
<Avatar <Avatar
sizes="small" sizes="small"
alt="Riley Carter" alt="Riley Carter"
src="/static/images/avatar/7.jpg" src="/static/images/avatar/7.jpg"
sx={{ width: 36, height: 36 }} sx={{ width: 36, height: 36 }}
/> />
)} )}
</MenuButton> </MenuButton>
<Menu <Menu
anchorEl={anchorEl} anchorEl={anchorEl}
id="menu" id="menu"
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={handleProfile}>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={handleClose} onClick={handleClose}
sx={{ sx={{
[`& .${listItemIconClasses.root}`]: { [`& .${listItemIconClasses.root}`]: {
ml: "auto", ml: "auto",
minWidth: 0, minWidth: 0,
}, },
}} }}
> >
{/* //Eknoor singh and jaanvi {/* //Eknoor singh and jaanvi
//date:- 13-Feb-2025 //date:- 13-Feb-2025
//Implemented logout functionality which was static previously */} //Implemented logout functionality which was static previously */}
<ListItemText <ListItemText
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
setLogoutModal(true); setLogoutModal(true);
}} }}
> >
Logout Logout
</ListItemText> </ListItemText>
<Logout <Logout
setLogoutModal={setLogoutModal} setLogoutModal={setLogoutModal}
logoutModal={logoutModal} logoutModal={logoutModal}
/> />
<ListItemIcon> <ListItemIcon>
<LogoutRoundedIcon fontSize="small" /> <LogoutRoundedIcon fontSize="small" />
</ListItemIcon> </ListItemIcon>
</MenuItem> </MenuItem>
</Menu> </Menu>
</React.Fragment> </React.Fragment>
); );
} }

View file

@ -1,73 +1,80 @@
import * as React from 'react'; import * as React from "react";
import Avatar from '@mui/material/Avatar'; import Avatar from "@mui/material/Avatar";
import Button from '@mui/material/Button'; import Button from "@mui/material/Button";
import Divider from '@mui/material/Divider'; import Divider from "@mui/material/Divider";
import Drawer, { drawerClasses } from '@mui/material/Drawer'; import Drawer, { drawerClasses } from "@mui/material/Drawer";
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 LogoutRoundedIcon from '@mui/icons-material/LogoutRounded'; import LogoutRoundedIcon from "@mui/icons-material/LogoutRounded";
import NotificationsRoundedIcon from '@mui/icons-material/NotificationsRounded'; import NotificationsRoundedIcon from "@mui/icons-material/NotificationsRounded";
import MenuButton from '../MenuButton'; import MenuButton from "../MenuButton";
import MenuContent from '../MenuContent'; import MenuContent from "../MenuContent";
import CardAlert from '../CardAlert/CardAlert'; import CardAlert from "../CardAlert/CardAlert";
interface SideMenuMobileProps { interface SideMenuMobileProps {
open: boolean | undefined; open: boolean | undefined;
toggleDrawer: (newOpen: boolean) => () => void; toggleDrawer: (newOpen: boolean) => () => void;
} }
export default function SideMenuMobile({ open, toggleDrawer }: SideMenuMobileProps) { export default function SideMenuMobile({
return ( open,
<Drawer toggleDrawer,
anchor="right" }: SideMenuMobileProps) {
open={open} return (
onClose={toggleDrawer(false)} <Drawer
sx={{ anchor="right"
zIndex: (theme) => theme.zIndex.drawer + 1, open={open}
[`& .${drawerClasses.paper}`]: { onClose={toggleDrawer(false)}
backgroundImage: 'none', sx={{
backgroundColor: 'background.paper', zIndex: (theme) => theme.zIndex.drawer + 1,
}, [`& .${drawerClasses.paper}`]: {
}} backgroundImage: "none",
> backgroundColor: "background.paper",
<Stack },
sx={{ }}
maxWidth: '70dvw', >
height: '100%', <Stack
}} sx={{
> maxWidth: "70dvw",
<Stack direction="row" sx={{ p: 2, pb: 0, gap: 1 }}> height: "100%",
<Stack }}
direction="row" >
sx={{ gap: 1, alignItems: 'center', flexGrow: 1, p: 1 }} <Stack direction="row" sx={{ p: 2, pb: 0, gap: 1 }}>
> <Stack
<Avatar direction="row"
sizes="small" sx={{ gap: 1, alignItems: "center", flexGrow: 1, p: 1 }}
alt="Riley Carter" >
src="/static/images/avatar/7.jpg" <Avatar
sx={{ width: 24, height: 24 }} sizes="small"
/> alt="Riley Carter"
<Typography component="p" variant="h6"> src="/static/images/avatar/7.jpg"
Riley Carter sx={{ width: 24, height: 24 }}
</Typography> />
</Stack> <Typography component="p" variant="h6">
<MenuButton showBadge> Riley Carter
<NotificationsRoundedIcon /> </Typography>
</MenuButton> </Stack>
</Stack> <MenuButton showBadge>
<Divider /> <NotificationsRoundedIcon />
<Stack sx={{ flexGrow: 1 }}> </MenuButton>
<MenuContent /> </Stack>
<Divider /> <Divider />
</Stack> <Stack sx={{ flexGrow: 1 }}>
<CardAlert /> <MenuContent />
<Stack sx={{ p: 2 }}> <Divider />
<Button variant="outlined" fullWidth startIcon={<LogoutRoundedIcon />}> </Stack>
Logout <CardAlert />
</Button> <Stack sx={{ p: 2 }}>
</Stack> <Button
</Stack> variant="outlined"
</Drawer> fullWidth
); startIcon={<LogoutRoundedIcon />}
>
Logout
</Button>
</Stack>
</Stack>
</Drawer>
);
} }

View file

@ -12,7 +12,12 @@ root.render(
<React.StrictMode> <React.StrictMode>
<Provider store={store}> <Provider store={store}>
<App /> <App />
<Toaster position="top-right" richColors /> <Toaster
position="top-right"
richColors
closeButton
duration={6000}
/>
</Provider> </Provider>
</React.StrictMode> </React.StrictMode>
); );

View file

@ -21,6 +21,8 @@ const DashboardLayout: React.FC<LayoutProps> = ({ customStyles }) => {
<Box <Box
component="main" component="main"
sx={(theme) => ({ sx={(theme) => ({
display: "flex",
height: '100vh',
flexGrow: 1, flexGrow: 1,
backgroundColor: theme.vars backgroundColor: theme.vars
? `rgba(${theme.vars.palette.background.defaultChannel} / 1)` ? `rgba(${theme.vars.palette.background.defaultChannel} / 1)`
@ -32,6 +34,10 @@ const DashboardLayout: React.FC<LayoutProps> = ({ customStyles }) => {
<Stack <Stack
spacing={2} spacing={2}
sx={{ sx={{
display: "flex",
flex: 1,
justifyItems: "center",
alignItems: 'center', alignItems: 'center',
mx: 3, mx: 3,
pb: 5, pb: 5,

View file

@ -4,54 +4,73 @@ import AddEditCategoryModal from "../../components/AddEditCategoryModal";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable"; import CustomTable, { Column } from "../../components/CustomTable";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { adminList, updateAdmin } from "../../redux/slices/adminSlice"; import {
import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector adminList,
import ViewModal from "../../components/Modals/ViewModal/ViewModal"; updateAdmin,
export default function AdminList() { createAdmin,
const [modalOpen, setModalOpen,] = useState(false); } from "../../redux/slices/adminSlice";
const [viewModal, setViewOpen] = useState(false); import { AppDispatch, RootState } from "../../redux/store/store";
export default function AdminList() {
const [modalOpen, setModalOpen] = useState(false);
const { reset } = useForm(); const { reset } = useForm();
const [deleteModal, setDeleteModal] = React.useState<boolean>(false); const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
const [viewModal, setViewModal] = React.useState<boolean>(false);
const [rowData, setRowData] = React.useState<any | null>(null); const [rowData, setRowData] = React.useState<any | null>(null);
const dispatch = useDispatch<AppDispatch>(); const dispatch = useDispatch<AppDispatch>();
// Fetching admin data from the Redux store
const admins = useSelector((state: RootState) => state.adminReducer.admins); const admins = useSelector((state: RootState) => state.adminReducer.admins);
// Dispatching the API call when the component mounts
useEffect(() => { useEffect(() => {
dispatch(adminList()); dispatch(adminList());
}, [dispatch]); }, [dispatch]);
const handleClickOpen = () => { const handleClickOpen = () => {
setRowData(null); // Reset row data when opening for new admin
setModalOpen(true); setModalOpen(true);
setViewOpen(true);
}; };
const handleCloseModal = () => { const handleCloseModal = () => {
setModalOpen(false); setModalOpen(false);
setViewOpen(false) setRowData(null);
reset(); reset();
}; };
const handleCreate = async (data: {
name: string;
email: string;
phone: string;
registeredAddress: string;
}) => {
try {
await dispatch(createAdmin(data));
await dispatch(adminList()); // Refresh the list after creation
handleCloseModal();
} catch (error) {
console.error("Creation failed", error);
}
};
const handleUpdate = async ( const handleUpdate = async (
id: string, id: string,
name: string, name: string,
email: string, email: string,
phone:string, phone: string,
registeredAddress:string registeredAddress: string
) => { ) => {
try { try {
await dispatch( await dispatch(
updateAdmin({ updateAdmin({
id, name, email, phone, registeredAddress, id,
token: null name,
email,
phone,
registeredAddress,
}) })
); );
await dispatch(adminList()); // Fetch updated admins list after update await dispatch(adminList());
} catch (error) { } catch (error) {
console.error("Update failed", error); console.error("Update failed", error);
} }
@ -61,13 +80,11 @@ export default function AdminList() {
{ id: "srno", label: "Sr No" }, { id: "srno", label: "Sr No" },
{ id: "name", label: "Name" }, { id: "name", label: "Name" },
{ id: "email", label: "Email" }, { id: "email", label: "Email" },
{ id: "phone", label: "Phone No" }, { id: "phone", label: "Phone" },
{ id: "registeredAddress", label: "Address" }, { id: "registeredAddress", label: "Address" },
{ id: "action", label: "Action", align: "center" }, { id: "action", label: "Action", align: "center" },
]; ];
// If no admins are available, display the sample data
const categoryRows = admins?.length const categoryRows = admins?.length
? admins?.map( ? admins?.map(
( (
@ -103,7 +120,6 @@ export default function AdminList() {
}, },
}} }}
> >
{/* Title and Add Category button */}
<Typography <Typography
component="h2" component="h2"
variant="h6" variant="h6"
@ -121,24 +137,23 @@ export default function AdminList() {
</Button> </Button>
</Box> </Box>
<CustomTable <CustomTable
columns={categoryColumns} columns={categoryColumns}
rows={categoryRows} rows={categoryRows}
setDeleteModal={setDeleteModal} setDeleteModal={setDeleteModal}
deleteModal={deleteModal} deleteModal={deleteModal}
setRowData={setRowData} setViewModal={setViewModal}
setModalOpen={setModalOpen} viewModal={viewModal}
viewModal={viewModal} setRowData={setRowData}
setViewModal={setViewOpen} setModalOpen={setModalOpen}
/> />
<AddEditCategoryModal <AddEditCategoryModal
open={modalOpen} open={modalOpen}
handleClose={handleCloseModal} handleClose={handleCloseModal}
editRow={rowData} handleCreate={handleCreate}
handleUpdate={handleUpdate} handleUpdate={handleUpdate}
editRow={rowData}
/> />
</> </>
); );
} }

View file

@ -222,18 +222,24 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
</Link> */} </Link> */}
</Box> </Box>
{/* <Divider>or</Divider> {/* <Divider>or</Divider>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <Box
<Typography sx={{ textAlign: 'center' }}> sx={{
Don&apos;t have an account?{' '} display: "flex",
<Link flexDirection: "column",
href="/auth/signup" gap: 2,
variant="body2" }}
sx={{ alignSelf: 'center' }} >
> <Typography sx={{ textAlign: "center" }}>
Sign up Don&apos;t have an account?{" "}
</Link> <Link
</Typography> href="/auth/signup"
</Box> */} variant="body2"
sx={{ alignSelf: "center" }}
>
Sign up
</Link>
</Typography>
</Box> */}
</Card> </Card>
</SignInContainer> </SignInContainer>
</AppTheme> </AppTheme>

View file

@ -98,8 +98,8 @@ export default function SignUp(props: { disableCustomTheme?: boolean }) {
const roleOptions = [ const roleOptions = [
{ value: "admin", label: "Admin" }, { value: "admin", label: "Admin" },
{ value: "user", label: "User" } { value: "user", label: "User" },
]; ];
// Enhanced email validation regex // Enhanced email validation regex
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
@ -133,8 +133,8 @@ export default function SignUp(props: { disableCustomTheme?: boolean }) {
}; };
await dispatch(registerUser(payload)).unwrap(); await dispatch(registerUser(payload)).unwrap();
toast.success("Registration successful!");
navigate("/auth/login"); navigate("/auth/login");
toast.success("Registration successful!");
} catch (error: any) { } catch (error: any) {
toast.error(error?.message || "Registration failed"); toast.error(error?.message || "Registration failed");
console.error("Registration error:", error); console.error("Registration error:", error);

View file

@ -1,17 +1,17 @@
// src/pages/Dashboard // src/pages/Dashboard
import * as React from 'react'; import * as React from 'react';
import { CssBaseline } from '@mui/material'; import { Box, CssBaseline, Typography } from '@mui/material';
import { import {
chartsCustomizations, chartsCustomizations,
dataGridCustomizations, dataGridCustomizations,
datePickersCustomizations, datePickersCustomizations,
treeViewCustomizations, treeViewCustomizations,
} from './theme/customizations/index.ts'; } from './theme/customizations';
import DashboardLayout from '../../layouts/DashboardLayout'; import DashboardLayout from '../../layouts/DashboardLayout';
import AppTheme from '../../shared-theme/AppTheme'; import AppTheme from '../../shared-theme/AppTheme';
import MainGrid from '../../components/MainGrid/index.tsx'; import MainGrid from '../../components/MainGrid';
const xThemeComponents = { const xThemeComponents = {
...chartsCustomizations, ...chartsCustomizations,
@ -20,18 +20,39 @@ const xThemeComponents = {
...treeViewCustomizations, ...treeViewCustomizations,
}; };
export default function Dashboard(props: { disableCustomTheme?: boolean }) { interface DashboardProps {
const disable = true; disableCustomTheme?: boolean;
}
const Dashboard: React.FC<DashboardProps> = ({ disableCustomTheme = false }) => {
return ( return (
<AppTheme {...props} themeComponents={xThemeComponents}> <AppTheme {...{ disableCustomTheme }} themeComponents={xThemeComponents}>
{!disable ? ( <CssBaseline enableColorScheme />
<> {!disableCustomTheme ? (
<CssBaseline enableColorScheme /> <MainGrid />
<MainGrid />
</>
) : ( ) : (
'Dashboard' <Box
sx={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
textAlign: 'center',
padding: 2,
}}
>
<Box>
<Typography variant="h6" component="h1" gutterBottom>
Dashboard
</Typography>
<Typography variant="body1" sx={{ marginTop: 2 }}>
No content available on the Dashboard yet.
</Typography>
</Box>
</Box>
)} )}
</AppTheme> </AppTheme>
); );
} };
export default Dashboard;

View file

@ -3,7 +3,7 @@ import { Box, Button, Typography } from '@mui/material';
import AddEditCategoryModal from '../../components/AddEditCategoryModal'; import AddEditCategoryModal from '../../components/AddEditCategoryModal';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import CustomTable from '../../components/CustomTable'; import CustomTable from '../../components/CustomTable';
import DeleteModal from '../../components/Modals/DeleteModal/DeleteModal'; import DeleteModal from '../../components/Modals/DeleteModal';
// Sample data for categories // Sample data for categories
// const categoryRows = [ // const categoryRows = [
@ -75,7 +75,7 @@ export default function Vehicles() {
sx={{ textAlign: 'right' }} sx={{ textAlign: 'right' }}
onClick={handleClickOpen} onClick={handleClickOpen}
> >
Add Category Add Categorywewfw
</Button> </Button>
</Box> </Box>

View file

@ -2,14 +2,12 @@ import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import http from "../../lib/https"; import http from "../../lib/https";
import { toast } from "sonner"; import { toast } from "sonner";
// Interfaces // Interfaces
interface User { interface User {
token: string | null;
id: string; id: string;
name: string; name: string;
email: string; email: string;
// role: string; role: string;
phone: string; phone: string;
registeredAddress: string; registeredAddress: string;
} }
@ -28,7 +26,7 @@ interface AuthState {
admins: Admin[]; admins: Admin[];
isAuthenticated: boolean; isAuthenticated: boolean;
isLoading: boolean; isLoading: boolean;
error: string | null; // error: string | null;
token: string | null; token: string | null;
} }
@ -42,6 +40,8 @@ export const adminList = createAsyncThunk<
const response = await http.get("auth/admin-list"); const response = await http.get("auth/admin-list");
return response?.data?.data; return response?.data?.data;
} catch (error: any) { } catch (error: any) {
toast.error("Error fetching users list" + error);
return rejectWithValue( return rejectWithValue(
error.response?.data?.message || "An error occurred" error.response?.data?.message || "An error occurred"
); );
@ -58,6 +58,28 @@ export const deleteAdmin = createAsyncThunk<
const response = await http.delete(`auth/${id}/delete-admin`); const response = await http.delete(`auth/${id}/delete-admin`);
toast.success(response.data?.message); toast.success(response.data?.message);
return id; return id;
} catch (error: any) {
toast.error("Error deleting the user" + error);
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
export const createAdmin = createAsyncThunk<
User,
{
name: string;
email: string;
phone: string;
registeredAddress: string;
},
{ rejectValue: string }
>("auth/signup", async (data, { rejectWithValue }) => {
try {
const response = await http.post("auth/create-admin", data);
return response.data;
} catch (error: any) { } catch (error: any) {
return rejectWithValue( return rejectWithValue(
error.response?.data?.message || "An error occurred" error.response?.data?.message || "An error occurred"
@ -68,11 +90,11 @@ export const deleteAdmin = createAsyncThunk<
// Update Admin // Update Admin
export const updateAdmin = createAsyncThunk( export const updateAdmin = createAsyncThunk(
"updateAdmin", "updateAdmin",
async ({ id, ...data}: User, { rejectWithValue }) => { async ({ id, ...userData }: User, { rejectWithValue }) => {
try { try {
const response = await http.put( const response = await http.put(
`auth/${id}/update-admin`, `auth/${id}/update-admin`,
data userData
); );
toast.success("Admin updated successfully"); toast.success("Admin updated successfully");
return response?.data; return response?.data;
@ -85,14 +107,12 @@ export const updateAdmin = createAsyncThunk(
} }
); );
const initialState: AuthState = { const initialState: AuthState = {
user: null, user: null,
admins: [], admins: [],
isAuthenticated: false, isAuthenticated: false,
isLoading: false, isLoading: false,
error: null, // error: null,
token: null, token: null,
}; };
@ -104,7 +124,7 @@ const adminSlice = createSlice({
builder builder
.addCase(adminList.pending, (state) => { .addCase(adminList.pending, (state) => {
state.isLoading = true; state.isLoading = true;
state.error = null; // state.error = null;
}) })
.addCase( .addCase(
adminList.fulfilled, adminList.fulfilled,
@ -113,13 +133,10 @@ const adminSlice = createSlice({
state.admins = action.payload; state.admins = action.payload;
} }
) )
.addCase( .addCase(adminList.rejected, (state) => {
adminList.rejected, state.isLoading = false;
(state, action: PayloadAction<string | undefined>) => { // state.error = action.payload || "An error occurred";
state.isLoading = false; })
state.error = action.payload || "An error occurred";
}
)
.addCase(deleteAdmin.pending, (state) => { .addCase(deleteAdmin.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
@ -129,13 +146,11 @@ const adminSlice = createSlice({
(admin) => String(admin.id) !== String(action.payload) (admin) => String(admin.id) !== String(action.payload)
); );
}) })
.addCase(deleteAdmin.rejected, (state, action) => { .addCase(deleteAdmin.rejected, (state) => {
state.isLoading = false; state.isLoading = false;
state.error = action.payload || "Failed to delete admin";
}) })
.addCase(updateAdmin.pending, (state) => { .addCase(updateAdmin.pending, (state) => {
state.isLoading = true; state.isLoading = true;
state.error = null;
}) })
.addCase(updateAdmin.fulfilled, (state, action) => { .addCase(updateAdmin.fulfilled, (state, action) => {
const updatedAdmin = action.payload; const updatedAdmin = action.payload;
@ -144,13 +159,26 @@ const adminSlice = createSlice({
); );
state.isLoading = false; state.isLoading = false;
}) })
.addCase(updateAdmin.rejected, (state, action) => { .addCase(updateAdmin.rejected, (state) => {
state.isLoading = false; state.isLoading = false;
state.error = })
typeof action.payload === "string" .addCase(createAdmin.pending, (state) => {
? action.payload state.isLoading = true;
: "Something went wrong while updating Admin!"; // state.error = null;
}); })
.addCase(
createAdmin.fulfilled,
(state, action: PayloadAction<User>) => {
state.isLoading = false;
state.admins.push(action.payload);
}
)
.addCase(
createAdmin.rejected,
(state, action: PayloadAction<string | undefined>) => {
state.isLoading = false;
}
);
}, },
}); });

View file

@ -1,6 +1,5 @@
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit"; import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import http from "../../lib/https"; import http from "../../lib/https";
// import { toast } from "react-toastify";
import { toast } from "sonner"; import { toast } from "sonner";
// Define types for state // Define types for state
@ -30,8 +29,9 @@ interface AuthState {
admins: Admin[]; admins: Admin[];
isAuthenticated: boolean; isAuthenticated: boolean;
isLoading: boolean; isLoading: boolean;
error: object | string | null; // error: object | string | null;
token: string | null; token: string | null;
role: string | null;
} }
// Async thunk for login // Async thunk for login
@ -42,6 +42,9 @@ export const loginUser = createAsyncThunk<
>("LoginUser", async ({ email, password }, { rejectWithValue }) => { >("LoginUser", async ({ email, password }, { rejectWithValue }) => {
try { try {
// this is endpoint not action name // this is endpoint not action name
//use below commented endpoint if using deployed backend........
// const response = await http.post("admin/login", {
const response = await http.post("auth/login", { const response = await http.post("auth/login", {
email, email,
password, password,
@ -50,6 +53,8 @@ export const loginUser = createAsyncThunk<
toast.success(response.data?.message); toast.success(response.data?.message);
return response.data; return response.data;
} catch (error: any) { } catch (error: any) {
toast.error("Error logging in the user" + error);
return rejectWithValue( return rejectWithValue(
error.response?.data?.message || "An error occurred" error.response?.data?.message || "An error occurred"
); );
@ -84,11 +89,12 @@ const initialState: AuthState = {
admins: [], admins: [],
isAuthenticated: false, isAuthenticated: false,
isLoading: false, isLoading: false,
error: null, // error: null,
//Eknoor singh //Eknoor singh
//date:- 12-Feb-2025 //date:- 12-Feb-2025
//initial state of token set to null //initial state of token set to null
token: null, token: null,
role: null, // New field for role
}; };
const authSlice = createSlice({ const authSlice = createSlice({
@ -100,7 +106,7 @@ const authSlice = createSlice({
// Login // Login
.addCase(loginUser.pending, (state) => { .addCase(loginUser.pending, (state) => {
state.isLoading = true; state.isLoading = true;
state.error = null; // state.error = null;
}) })
.addCase(loginUser.fulfilled, (state, action) => { .addCase(loginUser.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
@ -111,15 +117,16 @@ const authSlice = createSlice({
.addCase( .addCase(
loginUser.rejected, loginUser.rejected,
(state, action: PayloadAction<string | undefined>) => { // (state, action: PayloadAction<string | undefined>) => {
(state) => {
state.isLoading = false; state.isLoading = false;
state.error = action.payload || "An error occurred"; // state.error = action.payload || "An error occurred";
} }
) )
// Register // Register
.addCase(registerUser.pending, (state) => { .addCase(registerUser.pending, (state) => {
state.isLoading = true; state.isLoading = true;
state.error = null; // state.error = null;
}) })
.addCase( .addCase(
registerUser.fulfilled, registerUser.fulfilled,
@ -133,7 +140,7 @@ const authSlice = createSlice({
registerUser.rejected, registerUser.rejected,
(state, action: PayloadAction<string | undefined>) => { (state, action: PayloadAction<string | undefined>) => {
state.isLoading = false; state.isLoading = false;
state.error = action.payload || "An error occurred"; // state.error = action.payload || "An error occurred";
} }
); );

View file

@ -15,7 +15,6 @@ interface AuthState {
user: User | null; user: User | null;
isAuthenticated: boolean; isAuthenticated: boolean;
isLoading: boolean; isLoading: boolean;
error: string | null;
} }
export const fetchAdminProfile = createAsyncThunk< export const fetchAdminProfile = createAsyncThunk<
@ -27,15 +26,13 @@ export const fetchAdminProfile = createAsyncThunk<
const token = localStorage?.getItem("authToken"); const token = localStorage?.getItem("authToken");
if (!token) throw new Error("No token found"); if (!token) throw new Error("No token found");
const response = await http.get("/auth/profile", { const response = await http.get("/auth/profile");
headers: { Authorization: `Bearer ${token}` },
});
if (!response.data?.data) throw new Error("Invalid API response"); if (!response.data?.data) throw new Error("Invalid API response");
return response.data.data; return response.data.data;
} catch (error: any) { } catch (error: any) {
toast.error("Error fetching Profile"); toast.error("Error Fetching Profile" + error);
return rejectWithValue( return rejectWithValue(
error?.response?.data?.message || "An error occurred" error?.response?.data?.message || "An error occurred"
); );
@ -46,7 +43,6 @@ const initialState: AuthState = {
user: null, user: null,
isAuthenticated: false, isAuthenticated: false,
isLoading: false, isLoading: false,
error: null,
}; };
const profileSlice = createSlice({ const profileSlice = createSlice({
@ -57,16 +53,14 @@ const profileSlice = createSlice({
builder builder
.addCase(fetchAdminProfile.pending, (state) => { .addCase(fetchAdminProfile.pending, (state) => {
state.isLoading = true; state.isLoading = true;
state.error = null;
}) })
.addCase(fetchAdminProfile.fulfilled, (state, action) => { .addCase(fetchAdminProfile.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.user = action.payload; state.user = action.payload;
state.isAuthenticated = true; state.isAuthenticated = true;
}) })
.addCase(fetchAdminProfile.rejected, (state, action) => { .addCase(fetchAdminProfile.rejected, (state) => {
state.isLoading = false; state.isLoading = false;
state.error = action.payload || "Failed to fetch admin profile";
}); });
}, },
}); });

View file

@ -99,6 +99,7 @@ export default function AppRouter() {
/> />
} }
/> />
<Route <Route
path="profile" path="profile"
element={ element={