create active disactive feature

This commit is contained in:
jaanvi 2025-02-28 16:24:40 +05:30
parent 1c233360c4
commit 42300867a7
5 changed files with 251 additions and 232 deletions

View file

@ -172,7 +172,7 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
/> />
)} )}
/> />
<Controller {!editRow &&<Controller
name="password" name="password"
control={control} control={control}
rules={{ rules={{
@ -191,7 +191,7 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
helperText={errors.password?.message} helperText={errors.password?.message}
/> />
)} )}
/> />}
<Controller <Controller
name="phone" name="phone"
control={control} control={control}

View file

@ -7,10 +7,22 @@ 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 { Box, Button, IconButton, Menu } from "@mui/material"; import { adminList, deleteAdmin } from "../../redux/slices/adminSlice";
import { useDispatch } from "react-redux";
import {
Box,
Button,
dividerClasses,
IconButton,
listClasses,
Menu,
} from "@mui/material";
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded"; import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
import { useDispatch } from "react-redux"; // Correct the import for dispatch import DeleteModal from "../Modals/DeleteModal";
import { AppDispatch } from "../../redux/store/store"; import { AppDispatch } from "../../redux/store/store";
import ViewModal from "../Modals/ViewModal";
// Styled components for customization
const StyledTableCell = styled(TableCell)(({ theme }) => ({ const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: { [`&.${tableCellClasses.head}`]: {
backgroundColor: " #1565c0", backgroundColor: " #1565c0",
@ -38,22 +50,19 @@ export interface Column {
interface Row { interface Row {
[key: string]: any; [key: string]: any;
status: number;
statusValue: 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;
viewModal: boolean; viewModal: boolean;
setViewModal: Function; setViewModal: Function;
deleteModal: boolean; deleteModal: boolean;
setRowData: React.Dispatch<React.SetStateAction<any>>; // Adjust this type if needed
setModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
handleStatusToggle: (id: string, currentStatus: number) => void; handleStatusToggle: (id: string, currentStatus: number) => void;
tableType?: string;
} }
const CustomTable: React.FC<CustomTableProps> = ({ const CustomTable: React.FC<CustomTableProps> = ({
@ -66,27 +75,54 @@ const CustomTable: React.FC<CustomTableProps> = ({
setViewModal, setViewModal,
setModalOpen, setModalOpen,
handleStatusToggle, handleStatusToggle,
tableType,
}) => { }) => {
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 dispatch = useDispatch(); // Initialize dispatch
// Handle menu actions
const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => { const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
setAnchorEl(event.currentTarget); setAnchorEl(event.currentTarget);
setSelectedRow(row); setSelectedRow(row); // Ensure the row data is set
setRowData(row);
}; };
const handleClose = () => { const handleClose = () => {
setAnchorEl(null); setAnchorEl(null);
}; };
const dispatch = useDispatch<AppDispatch>();
// Handle status toggle logic const isImage = (value: any) => {
// const handleStatusToggle = (id: string, status: number) => { if (typeof value === "string") {
// dispatch(toggleStatus({ id, status })); // Dispatch the action to update status return value.startsWith("http") || value.startsWith("data:image"); // Check for URL or base64 image
// }; }
return false;
};
const handleDeleteButton = (id: string | undefined) => {
if (!id) console.error("ID not found", id);
dispatch(deleteAdmin(id || ""));
setDeleteModal(false); // Close the modal only after deletion
handleClose();
};
const handleViewButton = (id: string | undefined) => {
if (!id) console.error("ID not found", id);
dispatch(adminList());
setViewModal(false);
};
const handleToggleStatus = () => {
if (selectedRow) {
// Toggle the opposite of current status
const newStatus = selectedRow.statusValue === 1 ? 0 : 1;
handleStatusToggle(selectedRow.id, newStatus);
}
handleClose();
};
return ( return (
<Box sx={{ overflowX: "auto", width: "100%" }}> <Box sx={{ overflowX: "auto", width: "100%" }}>
@ -97,7 +133,11 @@ const CustomTable: React.FC<CustomTableProps> = ({
{columns.map((column) => ( {columns.map((column) => (
<StyledTableCell <StyledTableCell
key={column.id} key={column.id}
align={column.align} align={column.align || "left"}
sx={{
whiteSpace: "nowrap", // Prevent wrapping
fontSize: { xs: "12px", sm: "14px" }, // Responsively adjust font size
}}
> >
{column.label} {column.label}
</StyledTableCell> </StyledTableCell>
@ -110,15 +150,33 @@ const CustomTable: React.FC<CustomTableProps> = ({
{columns.map((column) => ( {columns.map((column) => (
<StyledTableCell <StyledTableCell
key={column.id} key={column.id}
align={column.align} align={column.align || "left"}
sx={{
whiteSpace: "nowrap", // Prevent wrapping
fontSize: {
xs: "12px",
sm: "14px",
}, // Responsively adjust font size
}}
> >
{column.id !== "action" ? ( {isImage(row[column.id]) ? (
<img
src={row[column.id]}
alt="Row "
style={{
width: "50px",
height: "50px",
objectFit: "cover",
}}
/>
) : column.id !== "action" ? (
row[column.id] row[column.id]
) : ( ) : (
<IconButton <IconButton
onClick={(e) => onClick={(e) => {
handleClick(e, row) handleClick(e, row);
} setRowData(row); // Store the selected row
}}
> >
<MoreVertRoundedIcon /> <MoreVertRoundedIcon />
</IconButton> </IconButton>
@ -132,46 +190,106 @@ const CustomTable: React.FC<CustomTableProps> = ({
</TableContainer> </TableContainer>
{/* Menu Actions */} {/* Menu Actions */}
{open && selectedRow && ( {open && (
<Menu <Menu
anchorEl={anchorEl} anchorEl={anchorEl}
id="menu"
open={open} open={open}
onClose={handleClose} onClose={handleClose}
onClick={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",
},
}}
> >
<Button <Box
variant="text" sx={{
onClick={(e) => { display: "flex",
e.stopPropagation(); flexDirection: "column",
setViewModal(true); justifyContent: "flex-start",
}} }}
> >
View <Button
</Button> variant="text"
<Button variant="text" onClick={() => setModalOpen(true)}> onClick={(e) => {
Edit e.stopPropagation();
</Button> setViewModal(true);
{/* This button now toggles the status based on the current status */} }}
<Button color="primary"
variant="text" sx={{
onClick={(e) => { justifyContent: "flex-start",
e.stopPropagation(); py: 0,
const newStatus = selectedRow?.status === 0 ? 0 : 1; textTransform: "capitalize",
handleStatusToggle(selectedRow?.id, newStatus); }}
}} >
> View
{selectedRow?.status === 1 ? "Deactivate" : "Activate"} </Button>
</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>
<Button {tableType === "roleList" && (
variant="text" <Button variant="text" onClick={handleToggleStatus}>
onClick={(e) => { {selectedRow.statusValue === 1
e.stopPropagation(); ? "Deactivate"
setDeleteModal(true); : "Activate"}
}} </Button>
> )}
Delete
</Button> <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> </Menu>
)} )}
</Box> </Box>

View file

@ -56,9 +56,7 @@ const ProfilePage = () => {
<Grid container spacing={2} alignItems="center"> <Grid container spacing={2} alignItems="center">
<Grid item> <Grid item>
<Avatar <Avatar
//Eknoor singh
//date:- 12-Feb-2025
//user is called for name and email
alt={user?.name || "User Avatar"} alt={user?.name || "User Avatar"}
src={"/static/images/avatar/7.jpg"} src={"/static/images/avatar/7.jpg"}
sx={{ width: 80, height: 80 }} sx={{ width: 80, height: 80 }}
@ -75,7 +73,7 @@ const ProfilePage = () => {
Phone: {user?.phone || "N/A"} Phone: {user?.phone || "N/A"}
</Typography> </Typography>
<Typography variant="body2" color="text.secondary"> <Typography variant="body2" color="text.secondary">
Role: <b>{user?.role || "N/A"}</b> Role: <b>{user?.userType || "N/A"}</b>
</Typography> </Typography>
</Grid> </Grid>
</Grid> </Grid>

View file

@ -43,6 +43,10 @@ export default function RoleList() {
reset(); reset();
}; };
const handleStatusToggle = (id: string, newStatus: number) => {
dispatch(toggleStatus({ id, status: newStatus }));
};
const handleCreate = async (data: { const handleCreate = async (data: {
name: string; name: string;
resource: { resource: {
@ -120,158 +124,17 @@ export default function RoleList() {
) : ( ) : (
<CustomTable <CustomTable
columns={categoryColumns} columns={categoryColumns}
rows={categoryRows} rows={categoryRows || []}
setDeleteModal={setDeleteModal} setDeleteModal={setDeleteModal}
deleteModal={deleteModal} deleteModal={deleteModal}
setViewModal={setViewModal} setViewModal={setViewModal}
viewModal={viewModal} viewModal={viewModal}
setRowData={setRowData} setRowData={setRowData}
setModalOpen={setModalOpen} setModalOpen={setModalOpen}
handleStatusToggle={(id, currentStatus) => { handleStatusToggle={handleStatusToggle}
// Correct logic to toggle between active and inactive tableType="roleList"
const updatedStatus = currentStatus === 1 ? 0 : 1;
dispatch(toggleStatus({ id, status: updatedStatus }));
}}
/> />
)} )}
</> </>
); );
} }
// import React, { useEffect, useState } from "react";
// import { Box, Button, Typography } from "@mui/material";
// import AddEditRoleModal from "../../components/AddEditRoleModal";
// import { useForm } from "react-hook-form";
// import CustomTable, { Column } from "../../components/CustomTable";
// import { useDispatch, useSelector } from "react-redux";
// import { createRole, roleList } from "../../redux/slices/roleSlice";
// import { AppDispatch, RootState } from "../../redux/store/store";
// export default function RoleList() {
// const [modalOpen, setModalOpen] = useState(false);
// const { reset } = useForm();
// const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
// const [viewModal, setViewModal] = React.useState<boolean>(false);
// const [rowData, setRowData] = React.useState<any | null>(null);
// const dispatch = useDispatch<AppDispatch>();
// const roles = useSelector((state: RootState) => state.roleReducer.roles);
// useEffect(() => {
// dispatch(roleList());
// }, [dispatch]);
// const handleClickOpen = () => {
// setRowData(null); // Reset row data when opening for new role
// setModalOpen(!modalOpen);
// };
// const handleCloseModal = () => {
// setModalOpen(false);
// setRowData(null);
// reset();
// };
// const handleCreate = async (data: {
// name: string;
// resource: {
// moduleName: string;
// moduleId: string;
// permissions: string[];
// }[];
// }) => {
// try {
// await dispatch(createRole(data));
// await dispatch(roleList()); // Refresh the list after creation
// handleCloseModal();
// } catch (error) {
// console.error("Creation failed", error);
// }
// };
// const categoryColumns: Column[] = [
// { id: "srno", label: "Sr No" },
// { id: "name", label: "Name" },
// { id: "action", label: "Action", align: "center" },
// ];
// const categoryRows = roles?.length
// ? roles?.map(function (
// role: {
// id: string;
// name: string;
// // email: string;
// // phone: string;
// // location?: string;
// // managerAssigned?: string;
// // vehicle?: string;
// },
// index: number
// ) {
// return {
// id: role?.id,
// srno: index + 1,
// name: role?.name,
// // email: user?.email,
// // phone: user?.phone,
// // location: user?.location,
// // managerAssigned: user?.managerAssigned,
// // vehicle: user?.vehicle,
// };
// })
// : [];
// console.log("Category Rows:", categoryRows);
// return (
// <>
// <Box
// sx={{
// width: "100%",
// maxWidth: {
// sm: "100%",
// display: "flex",
// justifyContent: "space-between",
// alignItems: "center",
// },
// }}
// >
// <Typography
// component="h2"
// variant="h6"
// sx={{ mt: 2, fontWeight: 600 }}
// >
// Roles
// </Typography>
// <Button
// variant="contained"
// size="medium"
// sx={{ textAlign: "right" }}
// onClick={handleClickOpen}
// >
// Add Role
// </Button>
// </Box>
// <CustomTable
// columns={categoryColumns}
// rows={categoryRows}
// setDeleteModal={setDeleteModal}
// deleteModal={deleteModal}
// setViewModal={setViewModal}
// viewModal={viewModal}
// setRowData={setRowData}
// setModalOpen={setModalOpen}
// />
// {/* <AddEditRoleModal
// open={modalOpen}
// handleClose={handleCloseModal}
// handleCreate={handleCreate}
// editRow={rowData}
// /> */}
// </>
// );
// }

View file

@ -5,7 +5,7 @@ import { toast } from "sonner";
// Define TypeScript types // Define TypeScript types
interface Role { interface Role {
id: any; id: string;
name: string; name: string;
resource: { resource: {
moduleName: string; moduleName: string;
@ -28,7 +28,7 @@ const initialState: RoleState = {
error: null, error: null,
}; };
export const roleList = createAsyncThunk<Role[], void, { rejectValue: string }>( export const roleList = createAsyncThunk<any, void, { rejectValue: string }>(
"fetchRoles", "fetchRoles",
async (_, { rejectWithValue }) => { async (_, { rejectWithValue }) => {
try { try {
@ -37,11 +37,12 @@ export const roleList = createAsyncThunk<Role[], void, { rejectValue: string }>(
const response = await http.get("get"); const response = await http.get("get");
if (!response.data?.data) throw new Error("Invalid API response"); if (!response.data) throw new Error("Invalid API response");
return response.data.data; // Return the full response to handle in the reducer
return response.data;
} catch (error: any) { } catch (error: any) {
toast.error("Error Fetching Roles" + error); toast.error("Error Fetching Roles: " + error.message);
return rejectWithValue( return rejectWithValue(
error?.response?.data?.message || "An error occurred" error?.response?.data?.message || "An error occurred"
); );
@ -51,7 +52,7 @@ export const roleList = createAsyncThunk<Role[], void, { rejectValue: string }>(
// Create Role // Create Role
export const createRole = createAsyncThunk< export const createRole = createAsyncThunk<
Role, any,
{ {
name: string; name: string;
resource: { resource: {
@ -61,11 +62,16 @@ export const createRole = createAsyncThunk<
}[]; }[];
}, },
{ rejectValue: string } { rejectValue: string }
>("/CreateRole", async (data, { rejectWithValue }) => { >("role/createRole", async (data, { rejectWithValue }) => {
try { try {
const response = await http.post("create", data); const response = await http.post("create", data);
toast.success("Role created successfully");
return response.data; return response.data;
} catch (error: any) { } catch (error: any) {
toast.error(
"Failed to create role: " +
(error.response?.data?.message || "Unknown error")
);
return rejectWithValue( return rejectWithValue(
error.response?.data?.message || "An error occurred" error.response?.data?.message || "An error occurred"
); );
@ -73,23 +79,40 @@ export const createRole = createAsyncThunk<
}); });
export const toggleStatus = createAsyncThunk< export const toggleStatus = createAsyncThunk<
Role, any,
{ id: string; status: number }, // status now expects a number (0 or 1) { id: string; status: number },
{ rejectValue: string } { rejectValue: string }
>("/toggleRoleStatus", async ({ id, status }, { rejectWithValue }) => { >("role/toggleStatus", async ({ id, status }, { rejectWithValue }) => {
try { try {
const response = await http.patch(`${id}`, { status }); const response = await http.patch(`${id}`, { status });
console.log("API Response:", response.data);
return response.data; if (response.data.statusCode === 200) {
toast.success(
response.data.message || "Status updated successfully"
);
// Return both the response data and the requested status for reliable state updates
return {
responseData: response.data,
id,
status,
};
} else {
throw new Error(response.data.message || "Failed to update status");
}
} catch (error: any) { } catch (error: any) {
toast.error(
"Error updating status: " + (error.message || "Unknown error")
);
return rejectWithValue( return rejectWithValue(
error.response?.data?.message || "An error occurred" error.response?.data?.message ||
error.message ||
"An error occurred"
); );
} }
}); });
const roleSlice = createSlice({ const roleSlice = createSlice({
name: "fetchRoles", name: "roles",
initialState, initialState,
reducers: {}, reducers: {},
extraReducers: (builder) => { extraReducers: (builder) => {
@ -102,7 +125,11 @@ const roleSlice = createSlice({
roleList.fulfilled, roleList.fulfilled,
(state, action: PayloadAction<any>) => { (state, action: PayloadAction<any>) => {
state.loading = false; state.loading = false;
state.roles = action.payload.results; // Extract results from response // Properly extract roles from the response data structure
state.roles =
action.payload.data?.results ||
action.payload.data ||
[];
} }
) )
.addCase(roleList.rejected, (state, action) => { .addCase(roleList.rejected, (state, action) => {
@ -114,9 +141,12 @@ const roleSlice = createSlice({
}) })
.addCase( .addCase(
createRole.fulfilled, createRole.fulfilled,
(state, action: PayloadAction<Role>) => { (state, action: PayloadAction<any>) => {
state.loading = false; state.loading = false;
state.roles.push(action.payload); // Add the newly created role to the state if it exists in the response
if (action.payload.data) {
state.roles.push(action.payload.data);
}
} }
) )
.addCase( .addCase(
@ -126,27 +156,37 @@ const roleSlice = createSlice({
state.error = action.payload || "Failed to create role"; state.error = action.payload || "Failed to create role";
} }
) )
.addCase(toggleStatus.pending, (state) => {
state.loading = true;
})
.addCase( .addCase(
toggleStatus.fulfilled, toggleStatus.fulfilled,
(state, action: PayloadAction<Role>) => { (state, action: PayloadAction<any>) => {
state.loading = false; state.loading = false;
const updatedRole = action.payload;
const index = state.roles.findIndex( // Get the id and updated status from the action payload
(role) => role.id === updatedRole.id const { id, status } = action.payload;
// Find and update the role with the new status
const roleIndex = state.roles.findIndex(
(role) => role.id === id
); );
if (index >= 0) { if (roleIndex !== -1) {
state.roles[index] = { state.roles[roleIndex] = {
...state.roles[index], ...state.roles[roleIndex],
status: updatedRole.status, status: status,
}; };
} }
} }
) )
.addCase(toggleStatus.rejected, (state, action) => { .addCase(
state.loading = false; toggleStatus.rejected,
state.error = action.payload || "Failed to toggle role status"; (state, action: PayloadAction<string | undefined>) => {
}); state.loading = false;
state.error =
action.payload || "Failed to toggle role status";
}
);
}, },
}); });