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

Feat update #7

Merged
merged 9 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion src/Components/SideBar/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default function SideBar() {
state: { userId: user._id },
});
} else {
navigate("/perfil");
navigate("/user");
}
};

Expand Down
63 changes: 63 additions & 0 deletions src/Pages/Protected/Users/userUpdate/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
@media screen and (max-width: 1080px) {
.double-box-user {
display: contents;
grid-template-columns: 0.5fr 0.5fr;
}

.double-buttons-user {
display: flex;
flex-direction: column;
gap: 15px;
margin-top: 20px;
}

.container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
min-height: 100vh; /* Para que o conteúdo ocupe toda a altura da tela */
padding: 20px; /* Um pouco de padding para dar espaço interno */
}

.forms-container-user {
width: 100%;
max-width: 500px; /* Limite máximo da largura do formulário */
padding: 10px;
border-radius: 10px;
}

.password-edit {
display: flex;
flex-direction: column;
align-items: center;
gap: 15px;
margin-top: 20px;
}

#addDependentBttn {
cursor: pointer;
}
}

@media screen and (min-width: 1080px) {
.double-buttons-user {
display: flex;
justify-content: space-between; /* Distribui os botões igualmente no espaço disponível */
align-items: end; /* Alinha os botões verticalmente */
gap: 20px;
}

.double-buttons-user button {
flex: 1; /* Faz com que os botões ocupem o espaço disponível igualmente */
height: 40px;
}

.forms-container-user {
padding-bottom: 40px; /* Garante um espaçamento ao final da página */
}

#addDependentBttn {
cursor: pointer;
}
}
254 changes: 254 additions & 0 deletions src/Pages/Protected/Users/userUpdate/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
import { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import FieldSelect from "../../../../Components/FieldSelect";
import FieldText from "../../../../Components/FieldText";
import Modal from "../../../../Components/Modal";
import PrimaryButton from "../../../../Components/PrimaryButton";
import SecondaryButton from "../../../../Components/SecondaryButton";
import {
getRoles,
getLoggedUser,
updateLogged,
changePasswordInProfile,
} from "../../../../Services/userService";
import "./index.css";
import {
isValidCelular,
isValidEmail,
mascaraTelefone,
} from "../../../../Utils/validators";

export default function UserUpdatePage() {
const { state } = useLocation();
const navigate = useNavigate();
const userId = state?.userId;
const [showPasswords] = useState(false);

const [nomeCompleto, setNomeCompleto] = useState("");
const [celular, setCelular] = useState("");
const [login, setLogin] = useState("Ativo");
const [email, setEmail] = useState("");
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmNewPassword] = useState("");

const [perfilSelecionado, setPerfilSelecionado] = useState("");
const [, setRoles] = useState([]);
const [showSaveModal, setShowSaveModal] = useState(false);
const [showPasswordSaveModal, setShowPasswordSaveModal] = useState(false);
const [isEmailValid, setIsEmailValid] = useState(true);
const [isCelularValid, setIsCelularValid] = useState(true);
const [isUserVisible, setIsUserVisible] = useState(true);
const [isNewPasswordValid] = useState(true);

const passwordsMatch = newPassword === confirmPassword;

useEffect(() => {
const loadRoles = async () => {
try {
const roles = await getRoles();
setRoles(roles);
} catch (error) {
console.error("Erro ao carregar roles:", error);
}
};
loadRoles();
}, []);

useEffect(() => {
const fetchUser = async () => {
try {
const user = await getLoggedUser();
if (user) {
setNomeCompleto(user.name || "");
setCelular(mascaraTelefone(user.phone || ""));
setLogin(user.status ? "Ativo" : "Inativo");
setEmail(user.email || "");
setPerfilSelecionado(user.role._id || "");
}
} catch (error) {
console.error("Erro ao buscar usuário:", error);
}
};

fetchUser();
}, [userId]);

console.log(userId);

const handleSave = async () => {
const trimmedCelular = celular.replace(/\D/g, "");
const { isValid: isValidNumber, message: celularMessage } =
isValidCelular(trimmedCelular);
const { isValid: isValidEmailAddress, message: emailMessage } =
isValidEmail(email);

setIsCelularValid(isValidNumber);
setIsEmailValid(isValidEmailAddress);

if (!isValidNumber || !isValidEmailAddress) {
if (!isValidNumber) {
console.error(celularMessage);
}
if (!isValidEmailAddress) {
console.error(emailMessage);
}
return;
}

const updatedUser = {
name: nomeCompleto,
email: email,
phone: trimmedCelular,
status: login === "Ativo",
role: perfilSelecionado,
};
try {
await updateLogged(updatedUser);
handleSaveModal();
} catch (error) {
console.error(`Erro ao atualizar usuário com ID ${userId}:`, error);
}
};

const handleSavePassword = async () => {
const updatedUserPassword = {
old_password: oldPassword,
new_password: newPassword,
};
try {
await changePasswordInProfile(updatedUserPassword).then((data) => {
console.log("caraleo", data);
if (data && data.response.status != 200) {
alert(data.response.data.mensagem);
}
});
handleSavePasswordModal();
} catch (error) {
console.error(
`Erro ao atualizar senha do usuário com ID ${userId}:`,
error
);
}
};

const handleChangeLogin = (event) => setLogin(event.target.value);

const handleSaveModal = () => setShowSaveModal(true);
const handleSavePasswordModal = () => setShowPasswordSaveModal(true);

const handleSaveCloseDialog = () => {
setShowSaveModal(false);
setShowPasswordSaveModal(false);
navigate("/user");
};

const showUserDiv = () => setIsUserVisible(true);
const showPasswordDiv = () => setIsUserVisible(false);

return (
<section className="container">
<div className="forms-container-user">
<div className="double-buttons-user">
<PrimaryButton text="Editar usuário" onClick={showUserDiv} />
<PrimaryButton text="Editar senha" onClick={showPasswordDiv} />
</div>

{isUserVisible && (
<div>
<h3>Dados Pessoais</h3>
<div className="double-box-user">
<FieldText
label="Nome Completo"
value={nomeCompleto}
onChange={(e) =>
setNomeCompleto(e.target.value.replace(/[^a-zA-ZÀ-ÿ\s]/g, ""))
}
/>
<FieldText
label="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
{!isEmailValid && (
<label className="isValid">*Insira um email válido</label>
)}
</div>
<div className="double-box-user">
<FieldText
label="Celular"
value={celular}
onChange={(e) => setCelular(mascaraTelefone(e.target.value))}
/>
<FieldSelect
label="Status"
value={login}
onChange={handleChangeLogin}
options={["Ativo", "Inativo"]}
/>
</div>
{!isCelularValid && (
<label className="isValid">
*Verifique se o número de celular inserido está completo
</label>
)}

<PrimaryButton text="Salvar" onClick={handleSave} />

<Modal alertTitle="Alterações Salvas" show={showSaveModal}>
<SecondaryButton
text="OK"
onClick={handleSaveCloseDialog}
width="338px"
/>
</Modal>
</div>
)}

{!isUserVisible && (
<div>
<h3>Alterar Senha</h3>
<FieldText
label="Senha atual"
type={showPasswords ? "text" : "password"}
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
/>

<FieldText
label="Nova senha"
value={newPassword}
type={showPasswords ? "text" : "password"}
onChange={(e) => setNewPassword(e.target.value)}
/>
{!isNewPasswordValid && (
<label className="isValid">*Insira uma senha válida</label>
)}

<FieldText
label="Repetir nova senha"
type={showPasswords ? "text" : "password"}
onChange={(e) => setConfirmNewPassword(e.target.value)}
/>

<br />
{!passwordsMatch && confirmPassword && (
<span style={{ color: "red" }}>As senhas não coincidem</span>
)}
<br />

<PrimaryButton text="Alterar senha" onClick={handleSavePassword} />

<Modal alertTitle="Alterações Salvas" show={showPasswordSaveModal}>
<SecondaryButton
text="OK"
onClick={handleSaveCloseDialog}
width="338px"
/>
</Modal>
</div>
)}
</div>
</section>
);
}
Loading
Loading