Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(#208) Página de listagem de usuário #46

Merged
merged 61 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from 59 commits
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
2da6dc3
:bulb: (#208) Criando página de listagem de usuário
lipeaaraujo Dec 7, 2023
d5744f8
:bulb: (#208) Adicionando página na navbar
lipeaaraujo Dec 7, 2023
7432e1f
:bulb: (#208) Adicionando header, pesquisa e filtro
lipeaaraujo Dec 7, 2023
de5b6ed
:bulb: (#208) Adicionando card de usuário
lipeaaraujo Dec 7, 2023
62478fd
:bulb: (#208) Adicionando requisição de unidades
lipeaaraujo Dec 7, 2023
1159fea
:bulb: (#208) Adicionando requisição dos usuários
lipeaaraujo Dec 7, 2023
c3541ae
:bulb: (#208) Adicionando dropdown na engine
lipeaaraujo Dec 7, 2023
329d6d6
:bulb: (#208) Adicionando modal
lipeaaraujo Dec 7, 2023
9909ff9
Merge branch 'dev' into 208-listagem-de-usuario
mibasFerraz Dec 7, 2023
6a93d09
:racehorse:(#208): Corrigindo rota
mibasFerraz Dec 7, 2023
06e6641
:test:(#208): adicionando pagina de teste
mibasFerraz Dec 7, 2023
b3d0550
:racehorse:(#208): renomeando paginas
mibasFerraz Dec 7, 2023
d9e5464
:bulb:(#208): adicionando rota para editar usuario
mibasFerraz Dec 7, 2023
a271a37
:bulb:(#208): criando botao de voltar
mibasFerraz Dec 7, 2023
6c89425
:bulb:(#208): adicionando fieldlabels no yupschema
mibasFerraz Dec 7, 2023
17c68a5
:bulb:(#208): adicionando valores por padrao
mibasFerraz Dec 7, 2023
ee8ef80
:bulb: (#208) Adicionando remoção de usuário
lipeaaraujo Dec 7, 2023
abe1f55
:repeat: (#208) Remoção de usuário na lista local
lipeaaraujo Dec 7, 2023
8b13265
:bug: (#208) Corrigindo requisição de usuários e unidades
lipeaaraujo Dec 8, 2023
cb13215
:bug: (#208) Arrumando deleção de usuário
lipeaaraujo Dec 8, 2023
a73d930
:bug: (#162) Corrigindo teste da Contact e Login
lipeaaraujo Dec 8, 2023
02c251b
:bug: (#208) Corrigindo teste do SignupForm
lipeaaraujo Dec 8, 2023
b1ceef4
:bulb:(#208): Conectando a pagina de listar usuarios com a edição
AntonioRangelC Dec 8, 2023
739a865
:bulb:(#208): Adicionando funcionalidade da combobox ficar marcada
AntonioRangelC Dec 8, 2023
730d90f
:bulb:(#208): corrige problemas de tratamento try/catch
guilhermedfs Dec 9, 2023
4137130
:repeat:(#191): Adicionando icone e nome do printgo
AntonioRangelC Dec 9, 2023
06f5dc3
:repeat:(#191): Refatorando tipos do yup
AntonioRangelC Dec 9, 2023
7d87a6a
:bulb(#208): ajuste no onSubmit para mandar array de cargos
vitordiniz25 Dec 9, 2023
77474bc
Merge branch 'dev' into 208-listagem-de-usuario
mibasFerraz Dec 9, 2023
2016a1c
:bug:(#208): removendo codesmell da edit user form
mibasFerraz Dec 9, 2023
1feff69
:bug:(#208): removendo codesmell da navbar
mibasFerraz Dec 9, 2023
0495aae
:bug:(#208): removendo bug da userlist
mibasFerraz Dec 9, 2023
3095559
:bulb:(#208): Adicionando proteção das rotas
AntonioRangelC Dec 10, 2023
f349260
:repeat:(#208): Modificando página de edição de usuário
AntonioRangelC Dec 10, 2023
e1fc1ba
:repeat:(#208): Modificando estilo da página de listagem de usuário
AntonioRangelC Dec 10, 2023
f6717ec
:repeat:(#208): Adicionando verificação para que somente admin acesse…
AntonioRangelC Dec 10, 2023
b75ba7b
:repeat:(#208): Modificando schema de edição
AntonioRangelC Dec 10, 2023
702e2b5
Merge branch 'dev' into 208-listagem-de-usuario
AntonioRangelC Dec 10, 2023
37215d7
Mudança na logo do favicon
Igorabreueng Dec 10, 2023
77873db
Merge branch '208-listagem-de-usuario' of https://github.com/fga-eps-…
Igorabreueng Dec 10, 2023
4551dd2
Mudança na logo do favicon
Igorabreueng Dec 10, 2023
09e70c5
:bulb:(#208): Adicionando testes para edicao de usuario
AntonioRangelC Dec 10, 2023
6e21c79
:bulb:(#208): Adicionando testes para listagem de usuario
AntonioRangelC Dec 10, 2023
2b66632
:repeat:(#208): Mudando logica do teste de url
AntonioRangelC Dec 10, 2023
cb6677e
Merge branch '208-listagem-de-usuario' of github.com:fga-eps-mds/2023…
AntonioRangelC Dec 10, 2023
e32186d
:repeat:(#208): Mudando logica do teste de url
AntonioRangelC Dec 10, 2023
532e89f
:bug:(#208): Consertando erro no teste da navbar
AntonioRangelC Dec 10, 2023
742a183
:racehorse:(#208) remove code smell
yuriAlves5 Dec 10, 2023
1833f71
:racehorse:(#208) Edit user Form refactor
yuriAlves5 Dec 10, 2023
4d3c673
:racehorse:(#208) if statement bug
yuriAlves5 Dec 10, 2023
8a4f2ba
:racehorse:(#208) complex if statement refactor
yuriAlves5 Dec 10, 2023
be09878
Revert ":racehorse:(#208) complex if statement refactor"
yuriAlves5 Dec 10, 2023
a4c0b3a
:racehorse: (#208) IF statement
yuriAlves5 Dec 10, 2023
3859b98
:racehorse: (#208) optional chain expression
yuriAlves5 Dec 10, 2023
63d4fd3
:racehorse: (#208) optional chain expression UserList
yuriAlves5 Dec 10, 2023
78c8cf4
(#208) Adding bail to test
yuriAlves5 Dec 10, 2023
77fe150
:racehorse:(#191) refactor bug in return option
yuriAlves5 Dec 10, 2023
a474970
:racehorse: (#208) unsed const removed
yuriAlves5 Dec 10, 2023
83b6079
:racehorse:(#208) codesmell bug
yuriAlves5 Dec 10, 2023
c9361f4
:bug:(#208): resolvendo conflito
mibasFerraz Dec 10, 2023
35f19ac
Merge branch 'dev' of https://github.com/fga-eps-mds/2023.2-PrintGo-F…
lipeaaraujo Dec 11, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,310 changes: 687 additions & 623 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest --coverage --passWithNoTests --no-cache --runInBand",
"test": "jest --passWithNoTests --no-cache --runInBand --bail",
"test:all": "CI=true npm run test -- --coverage",
"test:watch": "react-scripts test",
"eject": "react-scripts eject",
Expand Down
Binary file added public/Log.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified public/favicon.ico
Binary file not shown.
4 changes: 2 additions & 2 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="icon" href="favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<div id="root"></div>
Expand All @@ -28,7 +28,7 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
<title>PrintGO</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
Expand Down
Binary file added public/logo--.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed public/logo192.png
Binary file not shown.
Binary file removed public/logo512.png
Binary file not shown.
10 changes: 8 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import CreateUserPage from "./pages/CreateUser";
import EditUserPage from "./pages/EditUser";
import UsersList from "./pages/UsersList";
import Login from "./pages/Login";
import Contact from "./pages/Contact";
import AboutUs from "./pages/AboutUs";
Expand All @@ -18,22 +19,27 @@ import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import RecoverPasswordPage from "./pages/RecoverPassword";
import PrivateRoutes from "./components/utils/PrivateRoutes";
import AdminRoutes from "./components/utils/AdminRoutes";

function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route element={<PrivateRoutes />}>
<Route path="/cadastro" element={<CreateUserPage />} />
<Route path="/editarusuario" element={<EditUserPage/>}/>
<Route path="/editarusuario/:id" element={<EditUserPage/>}/>
<Route path="/mudarsenha" element={<ChangePassword />} />
<Route path="/cadastroimpressora" element={<RegisterPrinter />} />
<Route path="/editarimpressora" element={<EditPrinter />} />
<Route path="/padraoimpressora" element={<PatternPrinter />} />
<Route path="/editarpadrao" element={<EditPattern />} />
<Route path="/impressorascadastradas" element={<PrintersList />} />
<Route path="/listapadroes" element={<PatternList />} />
<Route element={<AdminRoutes/>}>
<Route path="/listausuarios" element={<UsersList />} />
<Route path="/cadastro" element={<CreateUserPage />} />
</Route>

</Route>
<Route path="/login" element={<Login />} />
<Route path="/" element={<Home />} />
Expand Down
5 changes: 5 additions & 0 deletions src/assets/Profile.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
170 changes: 123 additions & 47 deletions src/components/forms/EditUserForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,37 @@
import { useForm } from "react-hook-form";
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import * as yup from "yup";
import { getUnidades } from "../../services/unidadeService";
import { getUserById, updateUser } from "../../services/userService";
import "../../style/components/editUserForms.css";
import { ReloadIcon } from "@radix-ui/react-icons";
import { Link, useNavigate } from 'react-router-dom';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { decodeToken } from "react-jwt";
import '@testing-library/jest-dom/extend-expect';


const editUserSchema = yup.object().shape({
nome: yup.string().required('Nome é obrigatório'),
email: yup
.string()
.email('Email inválido')
.required('Email é obrigatório'),
emailConfirmar: yup
.string()
.oneOf([yup.ref('email'), null], 'Os emails devem coincidir')
.required('Email é obrigatória'),
documento: yup.string()
.matches(/^(\d{11}|\d{14})$/, 'CPF ou CNPJ inválido')
.test('cpfOrCnpj', 'CPF ou CNPJ inválido', value => {
return value.length === 11 || value.length === 14;
}),
unidade_id: yup.string().required('Lotação é obrigatória'),
unidade_pai: yup.string().strip(),
});
import { getEditUserSchema } from "../utils/YupSchema";

const fieldLabels = {
nome: 'Nome',
documento: 'CPF',
email: 'Email',
emailConfirmar: 'Email',
unidade_id: "Unidade",
};

const testObject = {
nome: 'Fulano',
documento: '01234567890',
email: 'email@email.com',
emailConfirmar: 'email@email.com',
};

export default function EditUserForm(){
const { id } = useParams();

const editUserSchema = getEditUserSchema(fieldLabels);
const { register, setValue, handleSubmit, formState: { errors, isValid, isSubmitting } } = useForm({
resolver: yupResolver(editUserSchema),
mode: "onChange"
});

let loggedUser = null;
const token = localStorage.getItem("jwt");
Expand All @@ -41,42 +42,68 @@
}

const [unidadeList, setUnidadeList] = useState();
const [isEditingAnotherAdmin, setIsEditingAnotherAdmin] = useState(); //verifica se o usuario que esta sendo editado eh admin
const [isLocadora, setIsLocadora] = useState(); //verifica se o usuario que esta sendo editado eh da locadora
const [displayLotacoes,setDisplayLotacoes] = useState ('');
const [unidadeFilhoList, setUnidadeFilhoList] = useState ();
const [userData, setUserData] = useState(null);
const [displayUserRole, setDisplayUserRole] = useState(true);

const memoUserData = useMemo(() => userData, [userData]);
const memoUnidadeList = useMemo(() => unidadeList, [unidadeList]);

const navigate = useNavigate();

const handleCheckboxLocadoraChange = (event) => {
setIsLocadora(event.target.checked);

Check warning on line 56 in src/components/forms/EditUserForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/EditUserForm.js#L56

Added line #L56 was not covered by tests
};

const {
register,
setValue,
handleSubmit,
formState: { errors, isValid, isSubmitting },
reset
} = useForm({resolver: yupResolver(editUserSchema), mode: "onChange"})
const handleCheckboxAdminChange = (event) =>{
setIsEditingAnotherAdmin(event.target.checked);

Check warning on line 60 in src/components/forms/EditUserForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/EditUserForm.js#L60

Added line #L60 was not covered by tests
}

const navigate = useNavigate();

// Puxe os dados do usuário logado.
useEffect(() => {
const fetchUserData = async () => {
try {
const data = await getUserById(loggedUser.id);
const data = await getUserById(id);

console.log(data);
if (data) {
setUserData(data);
if(data.cargos.includes("ADMIN")){
setIsEditingAnotherAdmin(true);
}
if(data.cargos.includes("LOCADORA")){
setIsLocadora(true);
}
}
} catch(error) {
console.log('Erro ao buscar dados do usuário:', error);
}
}
if(loggedUser && !userData) {
fetchUserData();

const verifyUser = async () =>{
if(loggedUser && !userData) {
await fetchUserData();

if(loggedUser.cargos.includes("ADMIN")) {
if(loggedUser.id === id){
setDisplayUserRole(false);
}
else{
return;
}
} else if(loggedUser.id != id) {
navigate("/"); // Um usuário comum não pode editar outro usuário além dele mesmo.
} else {
setDisplayUserRole(false);
}

}
}

verifyUser();

}, [loggedUser])

// Puxe os dados das unidades policiais.
Expand All @@ -99,11 +126,14 @@

useEffect(() => {
if (memoUserData && memoUnidadeList && unidadeList) {
console.log(unidadeList);

Object.keys(userData).forEach((key) => {
setValue(key, userData[key] || "");
Object.keys(editUserSchema.fields).forEach((key) => {
if (userData[key]) {
setValue(key, userData[key]);
}
})

isEditingAnotherAdmin ? setValue("isAdmin", true) : setValue("isAdmin", false);
isLocadora ? setValue("isLocadora", true) : setValue("isLocadora", false);

const unidadeFilha = unidadeList.find(unidade => unidade.id === userData.unidade_id);

Expand All @@ -119,19 +149,34 @@
}, [memoUserData, memoUnidadeList, setValue]);

const onSubmit = async (data) => {
data.id = id;

data.cargos = ["USER"]

if (data.isAdmin) {
data.cargos = data.cargos || [];
data.cargos.push("ADMIN")
}

if (data.isLocadora) {
data.cargos = data.cargos || [];
data.cargos.push("LOCADORA")
}

delete data["isAdmin"];
delete data["isLocadora"];
delete data["emailConfirmar"];
delete data["unidade_pai"];

console.log(data);

setTimeout(() => {
console.log("3 segundos se passaram.");
}, 3000); // 3000 milissegundos = 3 segundos

delete data["emailConfirmar"];
delete data["unidade_pai"];

const response = await updateUser(data, data.id);
if(response.type === 'success'){
toast.success("Usuario atualizado com sucesso!");
reset()
} else {
toast.error("Erro ao atualizar usuário");
}
Expand All @@ -153,7 +198,8 @@
};

return(
<div id="edit-user-card" data-testid="edit-user-card">
<div id="edit-user-card">
<Link id="link-back" to="/listausuarios">Voltar</Link>
<header id="edit-user-form-header">
Editar usuário
</header>
Expand Down Expand Up @@ -228,12 +274,40 @@
</div>

</div>
{displayUserRole && (
<div id="edit-user-input-line">
<div id="edit-user-input-box">
<div id="edit-user-input-checkbox" data-testid="admin-checkbox">
<input
id="checkbox"
type="checkbox"
{...register("isAdmin")}
onChange={handleCheckboxAdminChange}
/>

<label htmlFor="label-checkbox" id="label-checkbox">Usuário é administrador?</label>
</div>
</div>
<div id="edit-user-input-box">
<div id="edit-user-input-checkbox" data-testid="locadora-checkbox">
<input
id="checkbox"
type="checkbox"
{...register("isLocadora")}
onChange={handleCheckboxLocadoraChange}
/>
<label htmlFor="label-checkbox" id="label-checkbox">Usuário é da Locadora?</label>
</div>
</div>
</div>
)}


<div id="edit-user-buttons">
<button className="edit-user-form-button" type="button" id="edit-user-cancel-bnt">
<Link to="/">CANCELAR</Link>
<Link to="#">CANCELAR</Link>
</button>
<button className="edit-user-form-button" type="submit" id="edit-user-register-bnt" disabled={!isValid || isSubmitting}>
<button className="edit-user-form-button" type="submit" id="edit-user-register-bnt" disabled={isSubmitting || !isValid}>
{isSubmitting && (
<ReloadIcon id="animate-spin" data-testid="animate-spin"/>
)}
Expand All @@ -246,3 +320,5 @@
</div>
);
}

export { fieldLabels, testObject };
Loading
Loading