Skip to content

Commit

Permalink
Merge pull request #56 from fga-eps-mds/33-attribute
Browse files Browse the repository at this point in the history
33 Atribute pages permision
  • Loading branch information
ingridSCarvalho authored Sep 8, 2024
2 parents 0db128f + b901403 commit 546596b
Show file tree
Hide file tree
Showing 56 changed files with 2,754 additions and 275 deletions.
11 changes: 0 additions & 11 deletions 2024.1-SENTINELA-FRONT.code-workspace

This file was deleted.

34 changes: 24 additions & 10 deletions src/Components/SideBar/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,42 @@ import { AiOutlineMenu } from "react-icons/ai";
import sindpol_logo from "../../assets/sindpol-logo.png";
import sentinela_logo from "../../assets/sentinela-logo.png";
import { ButtonGroup } from "@mui/material";
import { useContext, useState } from "react";
import { useEffect, useContext, useState } from "react";
import SideButton from "../SideButton";
import { AiOutlineUser } from "react-icons/ai";
import { RiLogoutCircleRLine } from "react-icons/ri";
import { useNavigate } from "react-router-dom";
import AuthContext, { useAuth } from "../../Context/auth";
import { usePermissions, checkModule } from "../../Utils/permission";
import { getRoleById } from "../../Services/RoleService/roleService";

export default function SideBar({ fullHeight = true }) {
const [isSideBarOpen, setIsSideBarOpen] = useState(false);
const handleSideBar = () => setIsSideBarOpen(!isSideBarOpen);
const navigate = useNavigate();
const context = useContext(AuthContext);
const { user } = useAuth();
const permissions = usePermissions();
const [role, setRole] = useState("");

const handleItemClick = (user) => {
if (user?.role?.name == "sindicalizado") {
navigate(`/filiados/${user.name}`, {
state: { membershipId: user._id },
});
} else {
useEffect(() => {}, [navigate]);

const handleItemClick = async (user) => {
if (user) {
try {
const result = await getRoleById(user.role);
setRole(result.name);
} catch (error) {
console.error(error);
}
}

if (role == "administrador") {
navigate(`/usuarios/editar/${user.name}`, {
state: { userId: user._id },
});
} else {
navigate("/perfil");
}
};

Expand All @@ -40,23 +53,23 @@ export default function SideBar({ fullHeight = true }) {
}}
/>,
<SideButton
hidden={user ? "flex" : "none"}
hidden={checkModule(permissions, "users") ? "flex" : "none"}
key="filiacao"
text="CADASTROS"
onClick={() => {
navigate("/usuarios/hub");
}}
/>,
<SideButton
hidden={user ? "flex" : "none"}
hidden={checkModule(permissions, "finance") ? "flex" : "none"}
key="financeiro"
text="FINANCEIRO"
onClick={() => {
navigate("/finance/hub");
}}
/>,
<SideButton
hidden={user ? "flex" : "none"}
hidden={checkModule(permissions, "benefits") ? "flex" : "none"}
key="beneficios"
text="BENEFÍCIOS"
onClick={() => {
Expand Down Expand Up @@ -144,6 +157,7 @@ export default function SideBar({ fullHeight = true }) {
onClick={() => {
context.Logout();
navigate("/");
window.location.reload();
}}
>
LOGOUT <RiLogoutCircleRLine className="logout-icon" />
Expand Down
6 changes: 4 additions & 2 deletions src/Context/auth.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,23 @@ const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);

const [flag, setFlag] = useState(true);
useEffect(() => {
const storagedUser = localStorage.getItem("@App:user");
const storagedToken = localStorage.getItem("@App:token");

if (storagedToken && storagedUser) {
setUser(JSON.parse(storagedUser));
}
}, []);
}, [flag]);

const Login = async (email, password) => {
try {
const response = await userLogin(email, password);
setUser(response.data);
localStorage.setItem("@App:user", JSON.stringify(response.data.user));
localStorage.setItem("@App:token", JSON.stringify(response.data.token));
setFlag(!flag);
return false;
} catch (err) {
return true;
Expand All @@ -33,6 +34,7 @@ export const AuthProvider = ({ children }) => {

localStorage.removeItem("@App:user");
localStorage.removeItem("App:token");
setFlag(!flag);
};

// ### Auth return
Expand Down
13 changes: 9 additions & 4 deletions src/Pages/Protected/Benefit/Benefits/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import SecondaryButton from "../../../../Components/SecondaryButton";
import sindpol_logo from "../../../../assets/sindpol-logo.png";
import sentinela_logo from "../../../../assets/sentinela-logo.png";
import "./index.css";
import { checkAction, usePermissions } from "../../../../Utils/permission";

const Benefits = () => {
const navigate = useNavigate();
const { user } = useAuth();
const permissions = usePermissions();
const canCreate = checkAction(permissions, "benefits", "create");

const handleBenefitsList = () => {
navigate("/beneficios/lista");
Expand All @@ -29,10 +32,12 @@ const Benefits = () => {
alt="Sentinela Logo"
/>
<div className="hub-btn">
<SecondaryButton
text="CADASTRO DE BENEFÍCIOS"
onClick={handleBenefitsCreate}
/>
{canCreate && (
<SecondaryButton
text="CADASTRO DE BENEFÍCIOS"
onClick={handleBenefitsCreate}
/>
)}
<SecondaryButton
text="LISTA DE BENEFÍCIOS"
onClick={handleBenefitsList}
Expand Down
54 changes: 53 additions & 1 deletion src/Pages/Protected/Benefit/Benefits/index.test.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { BrowserRouter as Router } from "react-router-dom";
import Benefits from "./index";
import "@testing-library/jest-dom";

let canCreatePermission = true;

vi.mock("../../../../Utils/permission", () => ({
usePermissions: () => ({
somePermission: true,
}),
checkAction: () => canCreatePermission,
}));

vi.mock("../../../../Context/auth", () => ({
useAuth: () => ({
user: { name: "Test User" }, // Mocking a user
}),
}));

describe("Benefits", () => {
it("renders buttons correctly", () => {
render(
Expand Down Expand Up @@ -49,4 +64,41 @@ describe("Benefits", () => {
expect(window.location.pathname).toBe("/beneficios/lista");
});
});

it("does not render the 'CADASTRO DE BENEFÍCIOS' button when canCreate is false", async () => {
// Ajustar a variável global para simular ausência de permissão de criação
canCreatePermission = false;

render(
<Router>
<Benefits />
</Router>
);

await waitFor(() => {
// Verificar que o botão CADASTRO DE BENEFÍCIOS não está presente
expect(
screen.queryByText("CADASTRO DE BENEFÍCIOS")
).not.toBeInTheDocument();

// O botão LISTA DE BENEFÍCIOS ainda deve estar presente
expect(screen.getByText("LISTA DE BENEFÍCIOS")).toBeInTheDocument();
});
});

it("renders buttons correctly when user has create permission", async () => {
// Ajustar a variável global para simular permissão de criação
canCreatePermission = true;

render(
<Router>
<Benefits />
</Router>
);

await waitFor(() => {
// Verificar se o botão de CADASTRO DE BENEFÍCIOS está presente
expect(screen.getByText("CADASTRO DE BENEFÍCIOS")).toBeInTheDocument();
});
});
});
7 changes: 6 additions & 1 deletion src/Pages/Protected/Benefit/BenefitsList/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ import ListItemText from "@mui/material/ListItemText";
import Divider from "@mui/material/Divider";
import "./index.css";
import { getBenefitsForm } from "../../../../Services/benefitsService";
import { checkAction, usePermissions } from "../../../../Utils/permission";

export default function BenefitsList() {
const [search, setSearch] = useState("");
const [benefits, setBenefits] = useState([]);
const navigate = useNavigate();
const permissions = usePermissions();
const canCreate = checkAction(permissions, "benefits", "create");

const handleSubmit = () => {
navigate("/beneficios/criar");
Expand Down Expand Up @@ -43,7 +46,9 @@ export default function BenefitsList() {
<div className="forms-container-list-benefits">
<div className="double-box-list-benefits">
<h1> Lista de benefícios</h1>
<PrimaryButton text="Cadastrar benefício" onClick={handleSubmit} />
{canCreate && (
<PrimaryButton text="Cadastrar benefício" onClick={handleSubmit} />
)}
</div>
<div className="search-box-benefits">
<FieldText
Expand Down
6 changes: 6 additions & 0 deletions src/Pages/Protected/Benefit/BenefitsList/index.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import { getBenefitsForm } from "../../../../Services/benefitsService";
import "@testing-library/jest-dom";

vi.mock("../../../../Services/benefitsService");
vi.mock("../../../../Utils/permission", () => ({
usePermissions: () => ({
somePermission: true,
}),
checkAction: () => true,
}));

describe("BenefitsList", () => {
beforeEach(() => {
Expand Down
20 changes: 14 additions & 6 deletions src/Pages/Protected/Benefit/BenefitsUpdate/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
} from "../../../../Utils/validators";
import { Snackbar } from "@mui/material";
import Alert from "@mui/material/Alert";
import { checkAction, usePermissions } from "../../../../Utils/permission";

export default function BenefitsUpdate() {
const navigate = useNavigate();
Expand Down Expand Up @@ -53,6 +54,9 @@ export default function BenefitsUpdate() {
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showDeletedModal, setShowDeletedModal] = useState(false);
const [openError, setOpenError] = useState(false);
const permissions = usePermissions();
const canUpdate = checkAction(permissions, "benefits", "update");
const canDelete = checkAction(permissions, "benefits", "delete");

const tipoPessoaList = ["Jurídica", "Física"];
const categoriaList = [
Expand Down Expand Up @@ -392,12 +396,16 @@ export default function BenefitsUpdate() {
/>

<div className="double-buttons">
<SecondaryButton text="Deletar" onClick={handleDeleteModal} />

<PrimaryButton
text="Salvar"
onClick={() => handleUpdateBenefitsButton()}
/>
{canDelete && (
<SecondaryButton text="Deletar" onClick={handleDeleteModal} />
)}

{canUpdate && (
<PrimaryButton
text="Salvar"
onClick={() => handleUpdateBenefitsButton()}
/>
)}
</div>

<Snackbar
Expand Down
7 changes: 7 additions & 0 deletions src/Pages/Protected/Benefit/BenefitsUpdate/index.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ import {
updateBenefitsFormById,
} from "../../../../Services/benefitsService";

vi.mock("../../../../Utils/permission", () => ({
usePermissions: () => ({
somePermission: true,
}),
checkAction: () => true,
}));

function mockValidators() {
// mocka funções de validação do service
vi.mock("../../../../Utils/validators", () => {
Expand Down
13 changes: 9 additions & 4 deletions src/Pages/Protected/Finance/BankAccountList/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ import ListItemButton from "@mui/material/ListItemButton";
import ListItemText from "@mui/material/ListItemText";
import FieldText from "../../../../Components/FieldText";
import { getAll } from "../../../../../src/Services/bankAccountService";
import { checkAction, usePermissions } from "../../../../Utils/permission";

export default function ListBankAccount() {
const [busca, setBusca] = useState("");
const navigate = useNavigate();
const { user } = useAuth();
const [bankAccounts, setBankAccounts] = useState([]);
const permissions = usePermissions();
const canCreate = checkAction(permissions, "finance", "create");

useEffect(() => {
const fetchBankAccounts = async () => {
Expand Down Expand Up @@ -48,10 +51,12 @@ export default function ListBankAccount() {
<div className="forms-container-list-bankAccount">
<div className="double-box-list-bankAccount">
<h1>Lista de Contas Bancárias</h1>
<PrimaryButtom
text="Cadastrar contas bancárias"
onClick={handleRegisterClick}
/>
{canCreate && (
<PrimaryButtom
text="Cadastrar contas bancárias"
onClick={handleRegisterClick}
/>
)}
</div>
<div className="search-box-bankAccount">
<FieldText
Expand Down
8 changes: 7 additions & 1 deletion src/Pages/Protected/Finance/BankAccountList/index.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ import { MemoryRouter, Route, Routes } from "react-router-dom";
import ListBankAccount from "./index";
import { getAll } from "../../../../../src/Services/bankAccountService";
import "@testing-library/jest-dom";

// Mockar o serviço getAll
vi.mock("../../../../../src/Services/bankAccountService", () => ({
getAll: vi.fn(),
}));

vi.mock("../../../../Utils/permission", () => ({
usePermissions: () => ({
somePermission: true,
}),
checkAction: () => true,
}));

// Mockar o contexto de autenticação
vi.mock("../../../../Context/auth", () => ({
useAuth: () => ({
Expand Down
Loading

0 comments on commit 546596b

Please sign in to comment.