Skip to content

Commit

Permalink
Merge pull request #34 from fga-eps-mds/181-adicaoUnidadePolicia
Browse files Browse the repository at this point in the history
181 adicao unidade policia
  • Loading branch information
guilhermedfs authored Nov 24, 2023
2 parents 2ebc8b6 + ee4021d commit 8d1b503
Show file tree
Hide file tree
Showing 13 changed files with 205 additions and 135 deletions.
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module.exports = {
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
"\\.(css|less|scss)$": "identity-obj-proxy",
"axios": "axios/dist/node/axios.cjs"
},
testEnvironment: "jsdom",

Expand Down
30 changes: 30 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"dependencies": {
"@emailjs/browser": "^3.11.0",
"@hookform/resolvers": "^3.3.2",
"@radix-ui/react-icons": "^1.3.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
Expand All @@ -19,6 +20,7 @@
"react-icons": "^4.12.0",
"react-router-dom": "^6.17.0",
"react-scripts": "5.0.1",
"react-toastify": "^9.1.3",
"web-vitals": "^2.1.4",
"yup": "^1.3.2"
},
Expand Down
65 changes: 5 additions & 60 deletions src/api/api.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import axios from 'axios';

const API_URL = "https://2023-2-print-go-user-service.vercel.app";
const API_PORT = process.env.REACT_APP_API_PORT;
import { api } from "../lib/api/config";

export async function login(email, password) {
const data = {
Expand All @@ -10,17 +7,11 @@ export async function login(email, password) {
};

try {

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
const response = await axios.post(`${API_URL}:${API_PORT}/user/login`, data);
return response.data.token;
} else {
const response = await axios.post(`${API_URL}/user/login`, data);
const response = await api.post('/user/login', data);
return response.data.token;
}
} catch (error) {
console.error('Erro ao fazer login:', error);
throw error;
return {type: 'error', error};
}
}

Expand All @@ -37,56 +28,10 @@ export async function changePassword(newPassword, newPasswordConfirmation) {
}

try {

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
const response = await axios.post(`${API_URL}:${API_PORT}/user/change-password`, data, {headers});
return response;
} else {
const response = await axios.post(`${API_URL}/user/change-password`, data, {headers});
const response = await api.post('/user/change-password', data, {headers});
return response;
}
} catch(error) {
console.log('Erro ao trocar de senha', error)
throw error
}
}

export async function createUser (user) {
try {

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
const response = await axios.post(`${API_URL}:${API_PORT}/user/create`, user);
return { type: 'success', data: response.data};
} else {
const response = await axios.post(`${API_URL}/user/login`, user);
return { type: 'success', data: response.data};
}
} catch (error) {
return { type: 'error', error };
}
}

export async function createLotacao (lotacoa) {
try {
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {

const response = await axios.post(`${API_URL}:${API_PORT}/lotacao/create`, lotacoa);
return {type: 'success', data: response.data};
} else {
const response = await axios.post(`${API_URL}/lotacao/create`, lotacoa);
return {type: 'success', data: response.data};
}
} catch (error) {
return { type: 'error', error };
}
}

export async function getLotacoes() {
try {
const response = await axios.get(`${API_URL}/lotacao`);
return { type: 'success', data: response.data};
} catch (error) {
return { type: 'error', error };

return {type: 'error', error};
}
}
90 changes: 70 additions & 20 deletions src/components/forms/SignupForm.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { yupResolver } from "@hookform/resolvers/yup";
import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import * as yup from "yup";
import { getLotacoes, createUser } from "../../api/api";
import "../../style/components/signupForms.css";
import elipse6 from '../../assets/elipse6.svg';
import { getUnidades } from "../../services/unidadeService";
import { createUser } from "../../services/userService";
import "../../style/components/signupForms.css";
import { ReloadIcon } from "@radix-ui/react-icons";


const signupSchema = yup.object().shape({
Expand All @@ -31,44 +35,70 @@ const signupSchema = yup.object().shape({
.test('cpfOrCnpj', 'CPF ou CNPJ inválido', value => {
return value.length === 11 || value.length === 14;
}),
lotacao_id: yup.string().required('Lotação é obrigatória'),
unidade_id: yup.string().required('Lotação é obrigatória'),
isAdmin: yup.boolean(),
});

export default function SignupForm(){
const [lotacao, setLotacao] = useState([]);
const [unidade, setUnidade] = useState([]);
const [unidadeInList, setUnidadeInList] = useState([]);
const [displayLotacoes, setDisplayLotacoes] = useState(false);

useEffect( () => {
async function setLotacoes() {
async function setData() {
try {
const data = await getLotacoes();
if (data.type ==='success' && data.data) {
setLotacao(data.data);
const dataUnidades = await getUnidades();

if (dataUnidades.type ==='success' && dataUnidades.data) {
setUnidade(dataUnidades.data);

Check warning on line 53 in src/components/forms/SignupForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/SignupForm.js#L53

Added line #L53 was not covered by tests
}

} catch (error) {
console.error('Erro ao obter opções do serviço:', error);
}
}
setLotacoes();
setData();
}, []);


const {
register,
handleSubmit,
formState: { errors, isValid },
formState: { errors, isValid, isSubmitting },
reset
} = useForm({resolver: yupResolver(signupSchema), mode: "onChange"})

const onSubmit = async (data) => {

setTimeout(() => {
console.log("3 segundos se passaram.");

Check warning on line 74 in src/components/forms/SignupForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/SignupForm.js#L73-L74

Added lines #L73 - L74 were not covered by tests
}, 3000); // 3000 milissegundos = 3 segundos

data.cargos = ["USER"];
if (data.isAdmin) {
data.cargos.push("ADMIN");
}
await createUser(data);
reset()
const response = await createUser(data);

Check warning on line 81 in src/components/forms/SignupForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/SignupForm.js#L81

Added line #L81 was not covered by tests
if(response.type === 'success'){
toast.success("Usuario cadastrado com sucesso!")
reset()
} else {
toast.error("Erro ao cadastrar usuario")

Check warning on line 86 in src/components/forms/SignupForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/SignupForm.js#L83-L86

Added lines #L83 - L86 were not covered by tests
}
}

const handleWorkstationChange = (event) => {

if(event.target.value) {
const listChildWorkstations = unidade.find(uni => uni.id === event.target.value).child_workstations;
setDisplayLotacoes(true);
setUnidadeInList(listChildWorkstations);
}else {
setDisplayLotacoes(false);

Check warning on line 97 in src/components/forms/SignupForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/SignupForm.js#L93-L97

Added lines #L93 - L97 were not covered by tests
}
};


return(
<div id="signup-card">
<header id="form-header">
Expand Down Expand Up @@ -118,17 +148,30 @@ export default function SignupForm(){
</div>
<div id="input-line">
<div id="input-box">
<label>Lotação <span>*</span></label>
<select {...register("lotacao_id", {required: "Lotação é obrigatória"})}>
<option value="">Selecione a Lotação</option>
{lotacao?.map((lotacao) => (
<option key={lotacao.id} value={lotacao.id}>
{lotacao.nome}
<label>Unidade de pai<span>*</span></label>
<select onChange={handleWorkstationChange}>
<option value="">Selecione a Unidade de policia</option>
{unidade?.map((unit) => (
<option key={unit.id} value={unit.id}>

Check warning on line 155 in src/components/forms/SignupForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/SignupForm.js#L155

Added line #L155 was not covered by tests
{unit.name}
</option>
))}
</select>
<span>{errors.lotacao_id?.message}</span>
</div>
{displayLotacoes && (
<div id="input-box">

Check warning on line 162 in src/components/forms/SignupForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/SignupForm.js#L162

Added line #L162 was not covered by tests
<label>Unidade Filha <span>*</span></label>
<select {...register("unidade_id", {required: "Lotação é obrigatória"})}>
<option value="">Selecione a Lotação</option>
{unidadeInList?.map((unidade) => (
<option key={unidade.id} value={unidade.id}>

Check warning on line 167 in src/components/forms/SignupForm.js

View check run for this annotation

Codecov / codecov/patch

src/components/forms/SignupForm.js#L167

Added line #L167 was not covered by tests
{unidade.name}
</option>
))}
</select>
<span>{errors.unidade_id?.message}</span>
</div>
)}
</div>
<div id="input-line">
<div id="input-box">
Expand All @@ -146,12 +189,19 @@ export default function SignupForm(){

<div id="buttons">
<button className="form-button" type="button" id="cancel-bnt" >CANCELAR</button>
<button className="form-button" type="submit" id="register-bnt" disabled={!isValid}>REGISTRAR</button>
<button className="form-button" type="submit" id="register-bnt" disabled={!isValid || isSubmitting}>
{isSubmitting && (
<ReloadIcon id="animate-spin"/>
)}

{!isSubmitting ? 'REGISTRAR': "CADASTRANDO"}
</button>
</div>
</form>
<div className="elipse-signup">
<img alt= "elipse" src={elipse6}></img>
</div>
<ToastContainer />
</div>
);
}
2 changes: 1 addition & 1 deletion src/lib/api/config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';

export const api = axios.create({
baseURL: process.env.API_URL || 'http://localhost:8000',
baseURL: process.env.REACT_APP_API_URL,
timeout: 5000,
headers: {
'Content-Type': 'application/json',
Expand Down
32 changes: 9 additions & 23 deletions src/pages/Contact.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,36 +10,22 @@ export default function Contact() {
const [email, setEmail] = useState("");
const [assunto, setAssunto] = useState("");

function handleEnviar() {
// Here you can handle the data such as validating and sending it to a server
console.log("Nome:", nome);
console.log("E-mail:", email);
console.log("Assunto:", assunto);
function handleEnviar(){

const templateParams = {
from_name: nome,
email: email,
message: assunto,
};

emailjs
.send(
"service_amwcg9n",
"template_5l6g71s",
templateParams,
"az5Vq1c-iMacr4p-z"
)
.then(
(response) => {
console.log("SUCCESS!", response.status, response.text);
setAssunto("");
setEmail("");
setNome("");
},
(err) => {
console.log("FAILED...", err);
}
);
emailjs.send("service_amwcg9n","template_5l6g71s",templateParams,"az5Vq1c-iMacr4p-z")
.then((response) => {
setAssunto('');
setEmail('');
setNome('');
}, (err) => {

Check warning on line 26 in src/pages/Contact.js

View check run for this annotation

Codecov / codecov/patch

src/pages/Contact.js#L26

Added line #L26 was not covered by tests

})
}

return (
Expand Down
Loading

0 comments on commit 8d1b503

Please sign in to comment.