commit new changes

This commit is contained in:
jaanvi 2025-02-19 11:59:53 +05:30
parent a105ad3ab4
commit 35d5e9d980
15 changed files with 852 additions and 485 deletions

7
package-lock.json generated
View file

@ -26,6 +26,7 @@
"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",
"highcharts": "^12.1.2",
"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",
@ -9944,6 +9945,12 @@
"he": "bin/he" "he": "bin/he"
} }
}, },
"node_modules/highcharts": {
"version": "12.1.2",
"resolved": "https://registry.npmjs.org/highcharts/-/highcharts-12.1.2.tgz",
"integrity": "sha512-paZ72q1um0zZT1sS+O/3JfXVSOLPmZ0zlo8SgRc0rEplPFPQUPc4VpkgQS8IUTueeOBgIWwVpAWyC9tBYbQ0kg==",
"license": "https://www.highcharts.com/license"
},
"node_modules/hoist-non-react-statics": { "node_modules/hoist-non-react-statics": {
"version": "3.3.2", "version": "3.3.2",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz", "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",

View file

@ -21,6 +21,7 @@
"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",
"highcharts": "^12.1.2",
"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",

View file

@ -13,14 +13,22 @@ import { useForm, Controller } from "react-hook-form";
interface AddEditCategoryModalProps { interface AddEditCategoryModalProps {
open: boolean; open: boolean;
handleClose: () => void; handleClose: () => void;
handleUpdate: (id: string, name: string, role: string) => void; handleUpdate: (
id: string,
name: string,
email: string,
phone: string,
registeredAddress: string
) => void;
editRow: any; editRow: any;
handleAdd: Function;
} }
interface FormData { interface FormData {
category: string;
role: string;
name: string; name: string;
email: string;
phone: string;
registeredAddress: string;
} }
const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
@ -28,6 +36,7 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
handleClose, handleClose,
editRow, editRow,
handleUpdate, handleUpdate,
handleAdd,
}) => { }) => {
const { const {
control, control,
@ -37,15 +46,30 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
reset, reset,
} = useForm<FormData>({ } = useForm<FormData>({
defaultValues: { defaultValues: {
category: "",
name: "", name: "",
role: "", email: "",
phone: "",
registeredAddress: "",
}, },
}); });
const onSubmit = (data: FormData) => { const onSubmit = (data: FormData) => {
if (editRow) { if (editRow) {
handleUpdate(editRow.id, data.name, data.role); handleUpdate(
editRow.id,
data.name,
data.email,
data.phone,
data.registeredAddress
);
} else {
// Call handleAdd if adding new admin
handleAdd(
data.name,
data.email,
data.phone,
data.registeredAddress
);
} }
handleClose(); handleClose();
reset(); reset();
@ -53,9 +77,11 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
useEffect(() => { useEffect(() => {
if (editRow) { if (editRow) {
setValue("category", editRow.name);
setValue("name", editRow.name); setValue("name", editRow.name);
setValue("role", editRow.role); setValue("email", editRow.role);
setValue("phone", editRow.phone);
setValue("email", editRow.email);
setValue("registeredAddress", editRow.registeredAddress);
} else { } else {
reset(); reset();
} }
@ -73,9 +99,8 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
onSubmit: handleSubmit(onSubmit), onSubmit: handleSubmit(onSubmit),
}} }}
> >
<DialogTitle>{editRow ? "Edit" : "Add"} Category</DialogTitle> <DialogTitle>{editRow ? "Edit" : "Add"} Admin</DialogTitle>
<DialogContent> <DialogContent>
<Controller <Controller
name="name" name="name"
control={control} control={control}
@ -99,22 +124,68 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
/> />
<Controller <Controller
name="role" name="email"
control={control} control={control}
rules={{ rules={{
required: "Role is required", required: "Email is required",
}} }}
render={({ field }) => ( render={({ field }) => (
<TextField <TextField
{...field} {...field}
margin="dense" margin="dense"
label="Role" label="Email"
type="text" type="text"
fullWidth fullWidth
variant="standard" variant="standard"
error={!!errors.role} error={!!errors.email}
helperText={errors.role?.message} helperText={errors.email?.message}
disabled />
)}
/>
<Controller
name="phone"
control={control}
rules={{
required: "Phone no. is required",
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: "Invalid Phone Number",
},
maxLength:{
value:10,
message:"Phone no must be 10 digits"
}
}}
render={({ field }) => (
<TextField
{...field}
margin="dense"
label="Phone"
type="tel"
fullWidth
variant="standard"
error={!!errors.phone}
helperText={errors.phone?.message}
/>
)}
/>
<Controller
name="registeredAddress"
control={control}
rules={{
required: "Address is required",
}}
render={({ field }) => (
<TextField
{...field}
margin="dense"
label="Address"
type="text"
fullWidth
variant="standard"
error={!!errors.registeredAddress}
helperText={errors.registeredAddress?.message}
/> />
)} )}
/> />

View file

@ -1,225 +1,260 @@
import * as React from "react" import * as React from "react";
import { styled } from "@mui/material/styles" import { styled } from "@mui/material/styles";
import Table from "@mui/material/Table" import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody" import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell" import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer" import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead" import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow" import TableRow from "@mui/material/TableRow";
import Paper, { paperClasses } from "@mui/material/Paper" import Paper, { paperClasses } from "@mui/material/Paper";
import { deleteAdmin } from "../../redux/slices/adminSlice" import { adminList, deleteAdmin } from "../../redux/slices/adminSlice";
import { useDispatch } from "react-redux" import { useDispatch } from "react-redux";
import { import {
Box, Box,
Button, Button,
dividerClasses, dividerClasses,
IconButton, IconButton,
listClasses, listClasses,
Menu, Menu,
} from "@mui/material" } from "@mui/material";
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded" import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
import DeleteModal from "../Modals/DeleteModal/DeleteModal" import DeleteModal from "../Modals/DeleteModal/DeleteModal";
import { AppDispatch } from "../../redux/store/store" import { AppDispatch } from "../../redux/store/store";
import ViewModal from "../Modals/ViewModal/ViewModal";
// Styled components for customization // Styled components for customization
const StyledTableCell = styled(TableCell)(({ theme }) => ({ const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: { [`&.${tableCellClasses.head}`]: {
backgroundColor: " #1565c0", backgroundColor: " #1565c0",
color: theme.palette.common.white, color: theme.palette.common.white,
}, },
[`&.${tableCellClasses.body}`]: { [`&.${tableCellClasses.body}`]: {
fontSize: 14, fontSize: 14,
}, },
})) }));
const StyledTableRow = styled(TableRow)(({ theme }) => ({ const StyledTableRow = styled(TableRow)(({ theme }) => ({
"&:nth-of-type(odd)": { "&:nth-of-type(odd)": {
backgroundColor: theme.palette.action.hover, backgroundColor: theme.palette.action.hover,
}, },
"&:last-child td, &:last-child th": { "&:last-child td, &:last-child th": {
border: 0, border: 0,
}, },
})) }));
export interface Column { export interface Column {
id: string id: string;
label: string label: string;
align?: "left" | "center" | "right" align?: "left" | "center" | "right";
} }
interface Row { interface Row {
[key: string]: any [key: string]: any;
} }
interface CustomTableProps { interface CustomTableProps {
columns: Column[] columns: Column[];
rows: Row[] rows: Row[];
setDeleteModal: Function setDeleteModal: Function;
setRowData: Function setRowData: Function;
setModalOpen: Function setModalOpen: Function;
deleteModal: boolean viewModal: boolean;
setViewModal: Function;
deleteModal: boolean;
} }
const CustomTable: React.FC<CustomTableProps> = ({ const CustomTable: React.FC<CustomTableProps> = ({
columns, columns,
rows, rows,
setDeleteModal, setDeleteModal,
deleteModal, deleteModal,
setRowData, viewModal,
setModalOpen, setRowData,
setViewModal,
setModalOpen,
}) => { }) => {
// console.log("columnsss", columns, rows) // console.log("columnsss", columns, rows)
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) => {
setAnchorEl(event.currentTarget) setAnchorEl(event.currentTarget);
setSelectedRow(row) // Ensure the row data is set setSelectedRow(row); // Ensure the row data is set
} };
const handleClose = () => { const handleClose = () => {
setAnchorEl(null) setAnchorEl(null);
} };
const isImage = (value: any) => { const isImage = (value: any) => {
if (typeof value === "string") { if (typeof value === "string") {
return value.startsWith("http") || value.startsWith("data:image") // Check for URL or base64 image return value.startsWith("http") || value.startsWith("data:image"); // Check for URL or base64 image
} }
return false return false;
} };
const handleDeleteButton = (id: string | undefined) => { const handleDeleteButton = (id: string | undefined) => {
if (!id) console.error("ID not found", id) if (!id) console.error("ID not found", id);
dispatch(deleteAdmin(id || "")) dispatch(deleteAdmin(id || ""));
setDeleteModal(false) // Close the modal only after deletion setDeleteModal(false); // Close the modal only after deletion
handleClose() handleClose();
} };
return ( const handleViewButton = (id: string | undefined) => {
<TableContainer component={Paper}> if (!id) console.error("ID not found", id);
<Table sx={{ minWidth: 700 }} aria-label="customized table"> setViewModal(false);
<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",
}}
>
<Button
variant="text"
onClick={() => setModalOpen(true)}
color="primary"
sx={{
justifyContent: "flex-start",
py: 0,
textTransform: "capitalize",
}}
>
Edit
</Button>
<Button return (
variant="text" <TableContainer component={Paper}>
onClick={(e) => { <Table sx={{ minWidth: 700 }} aria-label="customized table">
e.stopPropagation() <TableHead>
setDeleteModal(true) <TableRow>
}} {columns.map((column) => (
color="error" <StyledTableCell
sx={{ key={column.id}
justifyContent: "flex-start", align={column.align || "left"}
py: 0, >
textTransform: "capitalize", {column.label}
}} </StyledTableCell>
> ))}
Delete </TableRow>
</Button> </TableHead>
{deleteModal && ( <TableBody>
<DeleteModal {rows.map((row, rowIndex) => (
handleDelete={() => <StyledTableRow key={rowIndex}>
handleDeleteButton(selectedRow?.id) {columns.map((column) => (
} <StyledTableCell
open={deleteModal} key={column.id}
setDeleteModal={setDeleteModal} align={column.align || "left"}
id={selectedRow?.id} >
/> {isImage(row[column.id]) ? (
)} <img
</Box> src={row[column.id]}
</Menu> alt="Row "
)} style={{
</TableContainer> 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",
}}
>
<Button
variant="text"
onClick={(e) => {
e.stopPropagation();
setViewModal(true);
}}
color="primary"
sx={{
justifyContent: "flex-start",
py: 0,
textTransform: "capitalize",
}}
>
View
</Button>
{viewModal && (
<ViewModal
handleView={() =>
handleViewButton(selectedRow?.id)
}
open={viewModal}
setViewModal={setViewModal}
id={selectedRow?.id}
/>
)}
<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

@ -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/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

@ -17,11 +17,12 @@ const baseMenuItems = [
icon: <HomeRoundedIcon />, icon: <HomeRoundedIcon />,
url: "/panel/dashboard", url: "/panel/dashboard",
}, },
{
text: "Vehicles", // {
icon: <AnalyticsRoundedIcon />, // text: "Vehicles",
url: "/panel/vehicles", // icon: <AnalyticsRoundedIcon />,
}, // url: "/panel/vehicles",
// },
//created by Eknnor and Jaanvi //created by Eknnor and Jaanvi
]; ];

View file

@ -0,0 +1,80 @@
import { Box, Button, Modal, Typography } from "@mui/material";
type Props = {
open: boolean;
setLogoutModal: Function;
handlelogout: any;
};
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 LogoutModal({
open,
setLogoutModal,
handlelogout,
}: 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"
>
Logout
</Typography>
<Typography
id="modal-modal-description"
sx={{ mt: 2 }}
align="center"
>
Are you sure you want to Logout?
</Typography>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
mt: 4,
gap: 2,
}}
>
<Button
variant="contained"
color="error"
type="button"
sx={btnStyle}
onClick={() => setLogoutModal(false)}
>
Cancel
</Button>
<Button
variant="contained"
type="button"
color="primary"
sx={btnStyle}
onClick={() => handlelogout()}
>
Logout
</Button>
</Box>
</Box>
</Modal>
);
}

View file

@ -0,0 +1,82 @@
import { Box, Button, Modal, Typography } from "@mui/material";
import { AppDispatch, RootState } from "../../../redux/store/store";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
type Props = {
open: boolean;
setViewModal: Function;
handleView: (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", alignItems: "center" };
export default function ViewModal({
open,
setViewModal,
id, // Selected user's 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 || null);
}
}, [id, admins]);
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"
>
Details of {selectedAdmin?.name}
</Typography>
{selectedAdmin ? (
<>
<Typography align="center">Name: {selectedAdmin?.name}</Typography>
<Typography align="center">Email: {selectedAdmin?.email}</Typography>
<Typography align="center">Phone: {selectedAdmin?.phone}</Typography>
<Typography align="center">Address: {selectedAdmin?.registeredAddress}</Typography>
</>
) : (
<Typography align="center">No admin found with this ID</Typography>
)}
<Box sx={{ display: "flex", justifyContent: "space-between", mt: 4, gap: 2 }}>
<Button
variant="contained"
color="error"
type="button"
sx={btnStyle}
onClick={() => setViewModal(false)}
>
Close
</Button>
</Box>
</Box>
</Modal>
);
}

View file

@ -12,7 +12,7 @@ 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 { toast } from "sonner"; import Logout from "../LogOut/logOutfunc";
const MenuItem = styled(MuiMenuItem)({ const MenuItem = styled(MuiMenuItem)({
margin: "2px 0", margin: "2px 0",
@ -20,6 +20,7 @@ const MenuItem = styled(MuiMenuItem)({
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 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);
@ -32,17 +33,12 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
//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("/auth/profile"); navigate("/panel/profile");
}; };
//Eknoor singh and jaanvi //jaanvi
//date:- 13-Feb-2025 //date:- 13-Feb-2025
//Implemented logout functionality which was static previously
const handlelogout = () => {
localStorage.clear();
navigate("/auth/login");
toast.success("Logged out successfully");
};
return ( return (
<React.Fragment> <React.Fragment>
<MenuButton <MenuButton
@ -99,7 +95,20 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
{/* //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 onClick={handlelogout}>Logout</ListItemText>
<ListItemText
onClick={(e) => {
e.stopPropagation();
setLogoutModal(true);
}}
>
Logout
</ListItemText>
<Logout
setLogoutModal={setLogoutModal}
logoutModal={logoutModal}
/>
<ListItemIcon> <ListItemIcon>
<LogoutRoundedIcon fontSize="small" /> <LogoutRoundedIcon fontSize="small" />
</ListItemIcon> </ListItemIcon>

View file

@ -6,9 +6,11 @@ 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 { adminList, updateAdmin } from "../../redux/slices/adminSlice";
import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector
import ViewModal from "../../components/Modals/ViewModal/ViewModal";
export default function AdminList() { export default function AdminList() {
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen,] = useState(false);
const [viewModal, setViewOpen] = useState(false);
const { reset } = useForm(); const { reset } = useForm();
const [deleteModal, setDeleteModal] = React.useState<boolean>(false); const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
@ -26,16 +28,29 @@ export default function AdminList() {
const handleClickOpen = () => { const handleClickOpen = () => {
setModalOpen(true); setModalOpen(true);
setViewOpen(true);
}; };
const handleCloseModal = () => { const handleCloseModal = () => {
setModalOpen(false); setModalOpen(false);
setViewOpen(false)
reset(); reset();
}; };
const handleUpdate = async (id: string, name: string, role: string) => { const handleUpdate = async (
id: string,
name: string,
email: string,
phone:string,
registeredAddress:string
) => {
try { try {
await dispatch(updateAdmin({ id, name, role })); await dispatch(
updateAdmin({
id, name, email, phone, registeredAddress,
token: null
})
);
await dispatch(adminList()); // Fetch updated admins list after update await dispatch(adminList()); // Fetch updated admins list after update
} catch (error) { } catch (error) {
console.error("Update failed", error); console.error("Update failed", error);
@ -45,7 +60,10 @@ export default function AdminList() {
const categoryColumns: Column[] = [ const categoryColumns: Column[] = [
{ id: "srno", label: "Sr No" }, { id: "srno", label: "Sr No" },
{ id: "name", label: "Name" }, { id: "name", label: "Name" },
{ id: "role", label: "Role" }, { id: "email", label: "Email" },
{ id: "phone", label: "Phone No" },
{ id: "registeredAddress", label: "Address" },
{ id: "action", label: "Action", align: "center" }, { id: "action", label: "Action", align: "center" },
]; ];
@ -53,13 +71,21 @@ export default function AdminList() {
const categoryRows = admins?.length const categoryRows = admins?.length
? admins?.map( ? admins?.map(
( (
admin: { id: string; name: string; role: string }, admin: {
id: string;
name: string;
email: string;
phone: string;
registeredAddress: string;
},
index: number index: number
) => ({ ) => ({
id: admin?.id, id: admin?.id,
srno: index + 1, srno: index + 1,
name: admin?.name, name: admin?.name,
role: admin?.role, email: admin?.email,
phone: admin?.phone,
registeredAddress: admin?.registeredAddress,
}) })
) )
: []; : [];
@ -91,24 +117,28 @@ export default function AdminList() {
sx={{ textAlign: "right" }} sx={{ textAlign: "right" }}
onClick={handleClickOpen} onClick={handleClickOpen}
> >
Add Category Add Admin
</Button> </Button>
</Box> </Box>
<CustomTable <CustomTable
columns={categoryColumns} columns={categoryColumns}
rows={categoryRows} rows={categoryRows}
setDeleteModal={setDeleteModal} setDeleteModal={setDeleteModal}
deleteModal={deleteModal} deleteModal={deleteModal}
setRowData={setRowData} setRowData={setRowData}
setModalOpen={setModalOpen} setModalOpen={setModalOpen}
/> viewModal={viewModal}
setViewModal={setViewOpen}
/>
<AddEditCategoryModal <AddEditCategoryModal
open={modalOpen} open={modalOpen}
handleClose={handleCloseModal} handleClose={handleCloseModal}
editRow={rowData} editRow={rowData}
handleUpdate={handleUpdate} handleUpdate={handleUpdate}
/> />
</> </>
); );
} }

View file

@ -1,214 +1,227 @@
import * as React from 'react'; import * as React from "react";
import Box from '@mui/material/Box'; import Box from "@mui/material/Box";
import Button from '@mui/material/Button'; import Button from "@mui/material/Button";
import Checkbox from '@mui/material/Checkbox'; import Checkbox from "@mui/material/Checkbox";
import CssBaseline from '@mui/material/CssBaseline'; import CssBaseline from "@mui/material/CssBaseline";
import FormControlLabel from '@mui/material/FormControlLabel'; import FormControlLabel from "@mui/material/FormControlLabel";
import Divider from '@mui/material/Divider'; import Divider from "@mui/material/Divider";
import FormLabel from '@mui/material/FormLabel'; import FormLabel from "@mui/material/FormLabel";
import FormControl from '@mui/material/FormControl'; import FormControl from "@mui/material/FormControl";
import Link from '@mui/material/Link'; import Link from "@mui/material/Link";
import TextField from '@mui/material/TextField'; import TextField from "@mui/material/TextField";
import Typography from '@mui/material/Typography'; import Typography from "@mui/material/Typography";
import Stack from '@mui/material/Stack'; import Stack from "@mui/material/Stack";
import MuiCard from '@mui/material/Card'; import MuiCard from "@mui/material/Card";
import { styled } from '@mui/material/styles'; import { styled } from "@mui/material/styles";
import { useForm, Controller, SubmitHandler } from 'react-hook-form'; import { useForm, Controller, SubmitHandler } from "react-hook-form";
import { useDispatch } from 'react-redux'; import { useDispatch } from "react-redux";
import { loginUser } from '../../../redux/slices/authSlice.ts'; import { loginUser } from "../../../redux/slices/authSlice.ts";
import ColorModeSelect from '../../../shared-theme/ColorModeSelect.tsx'; import ColorModeSelect from "../../../shared-theme/ColorModeSelect.tsx";
import AppTheme from '../../../shared-theme/AppTheme.tsx'; import AppTheme from "../../../shared-theme/AppTheme.tsx";
import ForgotPassword from './ForgotPassword.tsx'; import ForgotPassword from "./ForgotPassword.tsx";
import { toast } from 'sonner'; import { toast } from "sonner";
import { useNavigate } from 'react-router-dom'; import { useNavigate } from "react-router-dom";
const Card = styled(MuiCard)(({ theme }) => ({ const Card = styled(MuiCard)(({ theme }) => ({
display: 'flex', display: "flex",
flexDirection: 'column', flexDirection: "column",
alignSelf: 'center', alignSelf: "center",
width: '100%', width: "100%",
padding: theme.spacing(4), padding: theme.spacing(4),
gap: theme.spacing(2), gap: theme.spacing(2),
margin: 'auto', margin: "auto",
[theme.breakpoints.up('sm')]: { [theme.breakpoints.up("sm")]: {
maxWidth: '450px', maxWidth: "450px",
}, },
boxShadow: boxShadow:
'hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px', "hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px",
...theme.applyStyles('dark', { ...theme.applyStyles("dark", {
boxShadow: boxShadow:
'hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px', "hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px",
}), }),
})); }));
const SignInContainer = styled(Stack)(({ theme }) => ({ const SignInContainer = styled(Stack)(({ theme }) => ({
height: 'calc((1 - var(--template-frame-height, 0)) * 100dvh)', height: "calc((1 - var(--template-frame-height, 0)) * 100dvh)",
minHeight: '100%', minHeight: "100%",
padding: theme.spacing(2), padding: theme.spacing(2),
[theme.breakpoints.up('sm')]: { [theme.breakpoints.up("sm")]: {
padding: theme.spacing(4), padding: theme.spacing(4),
}, },
'&::before': { "&::before": {
content: '""', content: '""',
display: 'block', display: "block",
position: 'absolute', position: "absolute",
zIndex: -1, zIndex: -1,
inset: 0, inset: 0,
backgroundImage: backgroundImage:
'radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))', "radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))",
backgroundRepeat: 'no-repeat', backgroundRepeat: "no-repeat",
...theme.applyStyles('dark', { ...theme.applyStyles("dark", {
backgroundImage: backgroundImage:
'radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))', "radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))",
}), }),
}, },
})); }));
interface ILoginForm { interface ILoginForm {
email: string; email: string;
password: string; password: string;
} }
export default function Login(props: { disableCustomTheme?: boolean }) { export default function Login(props: { disableCustomTheme?: boolean }) {
const [open, setOpen] = React.useState(false); const [open, setOpen] = React.useState(false);
const { const {
control, control,
handleSubmit, handleSubmit,
formState: { errors }, formState: { errors },
setError, setError,
} = useForm<ILoginForm>(); } = useForm<ILoginForm>();
const dispatch = useDispatch(); const dispatch = useDispatch();
const router = useNavigate(); const router = useNavigate();
const handleClickOpen = () => { const handleClickOpen = () => {
setOpen(true); setOpen(true);
}; };
const handleClose = () => { const handleClose = () => {
setOpen(false); setOpen(false);
}; };
const onSubmit: SubmitHandler<ILoginForm> = async (data: ILoginForm) => { const onSubmit: SubmitHandler<ILoginForm> = async (data: ILoginForm) => {
try { try {
const response = await dispatch(loginUser(data)).unwrap(); const response = await dispatch(loginUser(data)).unwrap();
if (response?.data?.token) { if (response?.data?.token) {
router('/panel/dashboard'); router("/panel/dashboard");
} }
} catch (error: any) { } catch (error: any) {
console.log('Login failed:', error); console.log("Login failed:", error);
toast.error('Login failed: ' + error); toast.error("Login failed: " + error);
} }
}; };
return ( return (
<AppTheme {...props}> <AppTheme {...props}>
<CssBaseline enableColorScheme /> <CssBaseline enableColorScheme />
<SignInContainer direction="column" justifyContent="space-between"> <SignInContainer direction="column" justifyContent="space-between">
<ColorModeSelect <ColorModeSelect
sx={{ position: 'fixed', top: '1rem', right: '1rem' }} sx={{ position: "fixed", top: "1rem", right: "1rem" }}
/> />
<Card variant="outlined"> <Card variant="outlined">
{/* <SitemarkIcon /> */} {/* <SitemarkIcon /> */}
Digi-EV Digi-EV
<Typography <Typography
component="h1" component="h1"
variant="h4" variant="h4"
sx={{ width: '100%', fontSize: 'clamp(2rem, 10vw, 2.15rem)' }} sx={{
> width: "100%",
Sign in fontSize: "clamp(2rem, 10vw, 2.15rem)",
</Typography> }}
<Box >
component="form" Sign in
onSubmit={handleSubmit(onSubmit)} </Typography>
noValidate <Box
sx={{ component="form"
display: 'flex', onSubmit={handleSubmit(onSubmit)}
flexDirection: 'column', noValidate
width: '100%', sx={{
gap: 2, display: "flex",
}} flexDirection: "column",
> width: "100%",
<FormControl> gap: 2,
<FormLabel htmlFor="email">Email</FormLabel> }}
<Controller >
name="email" <FormControl>
control={control} <FormLabel htmlFor="email">Email</FormLabel>
defaultValue="" <Controller
rules={{ name="email"
required: 'Email is required', control={control}
pattern: { defaultValue=""
value: /\S+@\S+\.\S+/, rules={{
message: 'Please enter a valid email address.', required: "Email is required",
}, pattern: {
}} value: /\S+@\S+\.\S+/,
render={({ field }) => ( message:
<TextField "Please enter a valid email address.",
{...field} },
error={!!errors.email} }}
helperText={errors.email?.message} render={({ field }) => (
id="email" <TextField
type="email" {...field}
placeholder="your@email.com" error={!!errors.email}
autoComplete="email" helperText={errors.email?.message}
autoFocus id="email"
required type="email"
fullWidth placeholder="your@email.com"
variant="outlined" autoComplete="email"
color={errors.email ? 'error' : 'primary'} autoFocus
/> required
)} fullWidth
/> variant="outlined"
</FormControl> color={
errors.email ? "error" : "primary"
}
/>
)}
/>
</FormControl>
<FormControl> <FormControl>
<FormLabel htmlFor="password">Password</FormLabel> <FormLabel htmlFor="password">Password</FormLabel>
<Controller <Controller
name="password" name="password"
control={control} control={control}
defaultValue="" defaultValue=""
rules={{ rules={{
required: 'Password is required', required: "Password is required",
minLength: { minLength: {
value: 6, value: 6,
message: 'Password must be at least 6 characters long.', message:
}, "Password must be at least 6 characters long.",
}} },
render={({ field }) => ( }}
<TextField render={({ field }) => (
{...field} <TextField
error={!!errors.password} {...field}
helperText={errors.password?.message} error={!!errors.password}
name="password" helperText={errors.password?.message}
placeholder="••••••" name="password"
type="password" placeholder="••••••"
id="password" type="password"
autoComplete="current-password" id="password"
autoFocus autoComplete="current-password"
required autoFocus
fullWidth required
variant="outlined" fullWidth
color={errors.password ? 'error' : 'primary'} variant="outlined"
/> color={
)} errors.password
/> ? "error"
</FormControl> : "primary"
}
/>
)}
/>
</FormControl>
<FormControlLabel <FormControlLabel
control={<Checkbox value="remember" color="primary" />} control={
label="Remember me" <Checkbox value="remember" color="primary" />
/> }
<ForgotPassword open={open} handleClose={handleClose} /> label="Remember me"
<Button type="submit" fullWidth variant="contained"> />
Sign in <ForgotPassword open={open} handleClose={handleClose} />
</Button> <Button type="submit" fullWidth variant="contained">
<Link Sign in
component="button" </Button>
type="button" {/* <Link
onClick={handleClickOpen} component="button"
variant="body2" type="button"
sx={{ alignSelf: 'center' }} onClick={handleClickOpen}
> variant="body2"
Forgot your password? sx={{ alignSelf: "center" }}
</Link> >
</Box> Forgot your password?
<Divider>or</Divider> </Link> */}
</Box>
{/* <Divider>or</Divider>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<Typography sx={{ textAlign: 'center' }}> <Typography sx={{ textAlign: 'center' }}>
Don&apos;t have an account?{' '} Don&apos;t have an account?{' '}
@ -220,9 +233,9 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
Sign up Sign up
</Link> </Link>
</Typography> </Typography>
</Box> </Box> */}
</Card> </Card>
</SignInContainer> </SignInContainer>
</AppTheme> </AppTheme>
); );
} }

View file

@ -6,17 +6,17 @@ import CustomTable from '../../components/CustomTable';
import DeleteModal from '../../components/Modals/DeleteModal/DeleteModal'; import DeleteModal from '../../components/Modals/DeleteModal/DeleteModal';
// Sample data for categories // Sample data for categories
const categoryRows = [ // const categoryRows = [
{ srno: 1, name: 'Strength', date: '01/03/2025' }, // { srno: 1, name: 'Strength', date: '01/03/2025' },
{ // {
srno: 2, // srno: 2,
name: 'HIIT (High-Intensity Interval Training)', // name: 'HIIT (High-Intensity Interval Training)',
date: '01/03/2025', // date: '01/03/2025',
}, // },
{ srno: 3, name: 'Cardio', date: '01/03/2025' }, // { srno: 3, name: 'Cardio', date: '01/03/2025' },
{ srno: 4, name: 'Combat', date: '01/03/2025' }, // { srno: 4, name: 'Combat', date: '01/03/2025' },
{ srno: 5, name: 'Yoga', date: '01/03/2025' }, // { srno: 5, name: 'Yoga', date: '01/03/2025' },
]; // ];
export default function Vehicles() { export default function Vehicles() {
const [modalOpen, setModalOpen] = useState<boolean>(false); const [modalOpen, setModalOpen] = useState<boolean>(false);
@ -66,9 +66,9 @@ export default function Vehicles() {
}} }}
> >
{/* Title and Add Category button */} {/* Title and Add Category button */}
<Typography component="h2" variant="h6" sx={{ mt: 2, fontWeight: 600 }}> {/* <Typography component="h2" variant="h6" sx={{ mt: 2, fontWeight: 600 }}>
Vehicles Vehicles
</Typography> </Typography> */}
<Button <Button
variant="contained" variant="contained"
size="medium" size="medium"

View file

@ -2,14 +2,16 @@ 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; 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;
} }
interface Admin { interface Admin {
@ -18,6 +20,7 @@ interface Admin {
role: string; role: string;
email: string; email: string;
phone: string; phone: string;
registeredAddress: string;
} }
interface AuthState { interface AuthState {
@ -64,19 +67,17 @@ export const deleteAdmin = createAsyncThunk<
// Update Admin // Update Admin
export const updateAdmin = createAsyncThunk( export const updateAdmin = createAsyncThunk(
"UpdateAdmin", "updateAdmin",
async ( async ({ id, ...data}: User, { rejectWithValue }) => {
{ id, name, role }: { id: any; name: string; role: string },
{ rejectWithValue }
) => {
try { try {
const response = await http.put(`auth/${id}/update-admin`, { const response = await http.put(
name, `auth/${id}/update-admin`,
role, data
}); );
toast.success("Admin updated successfully"); toast.success("Admin updated successfully");
return response?.data; return response?.data;
} catch (error: any) { } catch (error: any) {
toast.error("Error updating the user: " + error);
return rejectWithValue( return rejectWithValue(
error.response?.data?.message || "An error occurred" error.response?.data?.message || "An error occurred"
); );
@ -84,6 +85,8 @@ export const updateAdmin = createAsyncThunk(
} }
); );
const initialState: AuthState = { const initialState: AuthState = {
user: null, user: null,
admins: [], admins: [],
@ -96,8 +99,7 @@ const initialState: AuthState = {
const adminSlice = createSlice({ const adminSlice = createSlice({
name: "admin", name: "admin",
initialState, initialState,
reducers: { reducers: {},
},
extraReducers: (builder) => { extraReducers: (builder) => {
builder builder
.addCase(adminList.pending, (state) => { .addCase(adminList.pending, (state) => {

View file

@ -64,6 +64,7 @@ export const registerUser = createAsyncThunk<
email: string; email: string;
password: string; password: string;
phone: string; phone: string;
// registeredAddress:string;
role: string; role: string;
}, },
{ rejectValue: string } { rejectValue: string }

View file

@ -64,15 +64,6 @@ export default function AppRouter() {
/> />
<Route path="login" element={<Login />} /> <Route path="login" element={<Login />} />
<Route path="signup" element={<SignUp />} /> <Route path="signup" element={<SignUp />} />
<Route
path="profile"
element={
<ProtectedRoute
caps={[]}
component={<ProfilePage />}
/>
}
/>
</Route> </Route>
{/* Dashboard Routes */} {/* Dashboard Routes */}
@ -108,6 +99,15 @@ export default function AppRouter() {
/> />
} }
/> />
<Route
path="profile"
element={
<ProtectedRoute
caps={[]}
component={<ProfilePage />}
/>
}
/>
<Route path="*" element={<>404</>} /> <Route path="*" element={<>404</>} />
</Route> </Route>