diff --git a/src/components/AddEditCategoryModal/index.tsx b/src/components/AddEditCategoryModal/index.tsx index ecf4fa9..2033bbc 100644 --- a/src/components/AddEditCategoryModal/index.tsx +++ b/src/components/AddEditCategoryModal/index.tsx @@ -172,7 +172,7 @@ const AddEditCategoryModal: React.FC = ({ /> )} /> - = ({ helperText={errors.password?.message} /> )} - /> + />} ({ [`&.${tableCellClasses.head}`]: { backgroundColor: " #1565c0", @@ -38,22 +50,19 @@ export interface Column { interface Row { [key: string]: any; - status: number; - statusValue: any; } interface CustomTableProps { columns: Column[]; rows: Row[]; setDeleteModal: Function; - // setRowData: Function; - // setModalOpen: Function; + setRowData: Function; + setModalOpen: Function; viewModal: boolean; setViewModal: Function; deleteModal: boolean; - setRowData: React.Dispatch>; // Adjust this type if needed - setModalOpen: React.Dispatch>; handleStatusToggle: (id: string, currentStatus: number) => void; + tableType?: string; } const CustomTable: React.FC = ({ @@ -66,27 +75,54 @@ const CustomTable: React.FC = ({ setViewModal, setModalOpen, handleStatusToggle, + tableType, }) => { + const dispatch = useDispatch(); const [anchorEl, setAnchorEl] = React.useState(null); const [selectedRow, setSelectedRow] = React.useState(null); const open = Boolean(anchorEl); - ///const dispatch = useDispatch(); // Initialize dispatch - // Handle menu actions const handleClick = (event: React.MouseEvent, row: Row) => { setAnchorEl(event.currentTarget); - setSelectedRow(row); + setSelectedRow(row); // Ensure the row data is set + setRowData(row); }; const handleClose = () => { setAnchorEl(null); }; - const dispatch = useDispatch(); - // Handle status toggle logic - // const handleStatusToggle = (id: string, status: number) => { - // dispatch(toggleStatus({ id, status })); // Dispatch the action to update status - // }; + + const isImage = (value: any) => { + if (typeof value === "string") { + return value.startsWith("http") || value.startsWith("data:image"); // Check for URL or base64 image + } + return false; + }; + + const handleDeleteButton = (id: string | undefined) => { + if (!id) console.error("ID not found", id); + + dispatch(deleteAdmin(id || "")); + setDeleteModal(false); // Close the modal only after deletion + handleClose(); + }; + + 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 ( @@ -97,7 +133,11 @@ const CustomTable: React.FC = ({ {columns.map((column) => ( {column.label} @@ -110,15 +150,33 @@ const CustomTable: React.FC = ({ {columns.map((column) => ( - {column.id !== "action" ? ( + {isImage(row[column.id]) ? ( + Row + ) : column.id !== "action" ? ( row[column.id] ) : ( - handleClick(e, row) - } + onClick={(e) => { + handleClick(e, row); + setRowData(row); // Store the selected row + }} > @@ -132,46 +190,106 @@ const CustomTable: React.FC = ({ {/* Menu Actions */} - {open && selectedRow && ( + {open && ( - - - {/* This button now toggles the status based on the current status */} - + + {viewModal && ( + + handleViewButton(selectedRow?.id) + } + open={viewModal} + setViewModal={setViewModal} + id={selectedRow?.id} + /> + )} + - + {tableType === "roleList" && ( + + )} + + + {deleteModal && ( + + handleDeleteButton(selectedRow?.id) + } + open={deleteModal} + setDeleteModal={setDeleteModal} + id={selectedRow?.id} + /> + )} + )} diff --git a/src/pages/ProfilePage/index.tsx b/src/pages/ProfilePage/index.tsx index 86488a8..1bebb78 100644 --- a/src/pages/ProfilePage/index.tsx +++ b/src/pages/ProfilePage/index.tsx @@ -56,9 +56,7 @@ const ProfilePage = () => { { Phone: {user?.phone || "N/A"} - Role: {user?.role || "N/A"} + Role: {user?.userType || "N/A"} diff --git a/src/pages/RoleList/index.tsx b/src/pages/RoleList/index.tsx index 0feeb32..58344bf 100644 --- a/src/pages/RoleList/index.tsx +++ b/src/pages/RoleList/index.tsx @@ -43,6 +43,10 @@ export default function RoleList() { reset(); }; + const handleStatusToggle = (id: string, newStatus: number) => { + dispatch(toggleStatus({ id, status: newStatus })); + }; + const handleCreate = async (data: { name: string; resource: { @@ -120,158 +124,17 @@ export default function RoleList() { ) : ( { - // Correct logic to toggle between active and inactive - const updatedStatus = currentStatus === 1 ? 0 : 1; - dispatch(toggleStatus({ id, status: updatedStatus })); - }} + handleStatusToggle={handleStatusToggle} + tableType="roleList" /> )} ); } - -// 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(false); -// const [viewModal, setViewModal] = React.useState(false); -// const [rowData, setRowData] = React.useState(null); - -// const dispatch = useDispatch(); - -// 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 ( -// <> -// -// -// Roles -// -// -// - -// -// {/* */} -// -// ); -// } diff --git a/src/redux/slices/roleSlice.ts b/src/redux/slices/roleSlice.ts index 797014c..9c20808 100644 --- a/src/redux/slices/roleSlice.ts +++ b/src/redux/slices/roleSlice.ts @@ -5,7 +5,7 @@ import { toast } from "sonner"; // Define TypeScript types interface Role { - id: any; + id: string; name: string; resource: { moduleName: string; @@ -28,7 +28,7 @@ const initialState: RoleState = { error: null, }; -export const roleList = createAsyncThunk( +export const roleList = createAsyncThunk( "fetchRoles", async (_, { rejectWithValue }) => { try { @@ -37,11 +37,12 @@ export const roleList = createAsyncThunk( 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) { - toast.error("Error Fetching Roles" + error); + toast.error("Error Fetching Roles: " + error.message); return rejectWithValue( error?.response?.data?.message || "An error occurred" ); @@ -51,7 +52,7 @@ export const roleList = createAsyncThunk( // Create Role export const createRole = createAsyncThunk< - Role, + any, { name: string; resource: { @@ -61,11 +62,16 @@ export const createRole = createAsyncThunk< }[]; }, { rejectValue: string } ->("/CreateRole", async (data, { rejectWithValue }) => { +>("role/createRole", async (data, { rejectWithValue }) => { try { const response = await http.post("create", data); + toast.success("Role created successfully"); return response.data; } catch (error: any) { + toast.error( + "Failed to create role: " + + (error.response?.data?.message || "Unknown error") + ); return rejectWithValue( error.response?.data?.message || "An error occurred" ); @@ -73,23 +79,40 @@ export const createRole = createAsyncThunk< }); export const toggleStatus = createAsyncThunk< - Role, - { id: string; status: number }, // status now expects a number (0 or 1) + any, + { id: string; status: number }, { rejectValue: string } ->("/toggleRoleStatus", async ({ id, status }, { rejectWithValue }) => { +>("role/toggleStatus", async ({ id, status }, { rejectWithValue }) => { try { 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) { + toast.error( + "Error updating status: " + (error.message || "Unknown error") + ); return rejectWithValue( - error.response?.data?.message || "An error occurred" + error.response?.data?.message || + error.message || + "An error occurred" ); } }); const roleSlice = createSlice({ - name: "fetchRoles", + name: "roles", initialState, reducers: {}, extraReducers: (builder) => { @@ -102,7 +125,11 @@ const roleSlice = createSlice({ roleList.fulfilled, (state, action: PayloadAction) => { 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) => { @@ -114,9 +141,12 @@ const roleSlice = createSlice({ }) .addCase( createRole.fulfilled, - (state, action: PayloadAction) => { + (state, action: PayloadAction) => { 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( @@ -126,27 +156,37 @@ const roleSlice = createSlice({ state.error = action.payload || "Failed to create role"; } ) + .addCase(toggleStatus.pending, (state) => { + state.loading = true; + }) .addCase( toggleStatus.fulfilled, - (state, action: PayloadAction) => { + (state, action: PayloadAction) => { state.loading = false; - const updatedRole = action.payload; - const index = state.roles.findIndex( - (role) => role.id === updatedRole.id + // Get the id and updated status from the action payload + 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) { - state.roles[index] = { - ...state.roles[index], - status: updatedRole.status, + if (roleIndex !== -1) { + state.roles[roleIndex] = { + ...state.roles[roleIndex], + status: status, }; } } ) - .addCase(toggleStatus.rejected, (state, action) => { - state.loading = false; - state.error = action.payload || "Failed to toggle role status"; - }); + .addCase( + toggleStatus.rejected, + (state, action: PayloadAction) => { + state.loading = false; + state.error = + action.payload || "Failed to toggle role status"; + } + ); }, });