bulk-email/src/redux/slices/roleSlice.ts
2025-02-28 14:53:24 +05:30

154 lines
3.6 KiB
TypeScript

import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";
import http from "../../lib/https";
import { toast } from "sonner";
// Define TypeScript types
interface Role {
id: any;
name: string;
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
status: number;
}
interface RoleState {
roles: Role[];
loading: boolean;
error: string | null;
}
// Initial state
const initialState: RoleState = {
roles: [],
loading: false,
error: null,
};
export const roleList = createAsyncThunk<Role[], void, { rejectValue: string }>(
"fetchRoles",
async (_, { rejectWithValue }) => {
try {
const token = localStorage?.getItem("authToken");
if (!token) throw new Error("No token found");
const response = await http.get("get");
if (!response.data?.data) throw new Error("Invalid API response");
return response.data.data;
} catch (error: any) {
toast.error("Error Fetching Roles" + error);
return rejectWithValue(
error?.response?.data?.message || "An error occurred"
);
}
}
);
// Create Role
export const createRole = createAsyncThunk<
Role,
{
name: string;
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
},
{ rejectValue: string }
>("/CreateRole", async (data, { rejectWithValue }) => {
try {
const response = await http.post("create", data);
return response.data;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
export const toggleStatus = createAsyncThunk<
Role,
{ id: string; status: number }, // status now expects a number (0 or 1)
{ rejectValue: string }
>("/toggleRoleStatus", async ({ id, status }, { rejectWithValue }) => {
try {
const response = await http.patch(`${id}`, { status });
console.log("API Response:", response.data);
return response.data;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
const roleSlice = createSlice({
name: "fetchRoles",
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(roleList.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(
roleList.fulfilled,
(state, action: PayloadAction<any>) => {
state.loading = false;
state.roles = action.payload.results; // Extract results from response
}
)
.addCase(roleList.rejected, (state, action) => {
state.loading = false;
state.error = action.payload || "Failed to fetch roles";
})
.addCase(createRole.pending, (state) => {
state.loading = true;
})
.addCase(
createRole.fulfilled,
(state, action: PayloadAction<Role>) => {
state.loading = false;
state.roles.push(action.payload);
}
)
.addCase(
createRole.rejected,
(state, action: PayloadAction<string | undefined>) => {
state.loading = false;
state.error = action.payload || "Failed to create role";
}
)
.addCase(
toggleStatus.fulfilled,
(state, action: PayloadAction<Role>) => {
state.loading = false;
const updatedRole = action.payload;
const index = state.roles.findIndex(
(role) => role.id === updatedRole.id
);
if (index >= 0) {
state.roles[index] = {
...state.roles[index],
status: updatedRole.status,
};
}
}
)
.addCase(toggleStatus.rejected, (state, action) => {
state.loading = false;
state.error = action.payload || "Failed to toggle role status";
});
},
});
export default roleSlice.reducer;