Skip to content

Commit

Permalink
Merge branch 'development' of https://github.com/mdsreq-fga-unb/2023.…
Browse files Browse the repository at this point in the history
…2-Matriculai into development
  • Loading branch information
Algusto-RC committed Nov 23, 2023
2 parents ff82ab8 + b5a3322 commit ea11694
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 95 deletions.
4 changes: 2 additions & 2 deletions backend/config/config.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"development": {
"username": "root",
"password": "123456",
"database": "banch",
"password": "password",
"database": "matriculai_development",
"host": "localhost",
"dialect": "mysql"
},
Expand Down
1 change: 1 addition & 0 deletions backend/controllers/UserControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ exports.userLogin = async (req, res) => {
res.status(500).json({ error: 'Erro durante o login.' });
}
};

2 changes: 1 addition & 1 deletion backend/controllers/middlewares/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const createToken = (user) => {

const validateToken = (req, res, next) => {

const accessToken = req.cookies && req.cookies['access-token'];
const accessToken = req.header("accessToken");
if (!accessToken) {
return res.status(400).json({ error: 'Usuário não autenticado!' });
}
Expand Down
4 changes: 3 additions & 1 deletion backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const electiveRoute = require('./views/routes/Electives')
const learningPathRoute = require('./views/routes/LearningPaths')
const logoutRoutes = require('./views/routes/Users');
const sequelize = require('sequelize');
const deleteLearningPathsRoute = require('./views/routes/LearningPaths');

require("dotenv").config();
const app = express();
Expand All @@ -15,7 +16,8 @@ app.use(cors());

app.use('/auth', userRoute);
app.use('/elective', electiveRoute);
app.use('/learning_paths', learningPathRoute);
app.use('/learningpath', learningPathRoute);
app.use('/deleteLearningPaths', deleteLearningPathsRoute);
app.use('/api', logoutRoutes);

// sequelize
Expand Down
16 changes: 0 additions & 16 deletions backend/views/routes/Users.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,4 @@ router.get('/profile', validateToken, (req, res) => {
router.post('/register', userController.userRegister);
router.post('/login', userController.userLogin);

// Rota para logout
router.post('/logout', (req, res) => {
// Lógica para fazer logout do usuário
req.session.destroy((err) => {
if (err) {
return res.status(500).json({ message: 'Erro ao fazer logout' });
}
res.clearCookie('cookieName'); // Limpeza de cookies, se necessário
return res.status(200).json({ message: 'Logout realizado com sucesso' });
});
});

router.get('/profile', validateToken, (req, res) => {
res.json('profile');
});

module.exports = router;
68 changes: 21 additions & 47 deletions frontend/src/pages/CreateEletivas/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,55 +40,29 @@ const CreateEletivas = () => {
const [error, setError] = useState("");

const handleCadastro = async () => {
if (!nomeEletiva || !descricao || !serie || !professor || !vagas || !horario) {

setError("Preencha todos os campos");
return;
};
console.log(nomeEletiva);
console.log(descricao);
console.log(serie);
console.log(professor);
console.log(vagas);
console.log(horario);

try {
const response = await axios.post('localhost:3000', {nomeEletiva, descricao, serie, professor, vagas, horario });

if (response.status === 200) {

toast({
title: 'Account created.',
description: "We've created your account for you.",
status: 'success',
duration: 2800,
isClosable: true,
position: 'top'
})

// Sucesso, redirecionar ou realizar outras ações necessárias
navigate("/home");
} else {
// Exibir mensagem de erro
setError(response.data.message);
}
} catch (error) {
if (axios.isAxiosError(error)) {
// Imprime informações detalhadas sobre o erro Axios
console.error("Erro ao fazer cadastro - Status:", error.response?.status);
console.error("Erro ao fazer cadastro - Data:", error.response?.data);
} else {
console.error("Erro ao cadastrar:", error);
}

setError("Erro ao cadastrar. Tente novamente mais tarde.");
try{
const data = {
name: nomeEletiva,
description: descricao,
school_year: parseInt(serie),
teacher: professor,
vacancies: parseInt(vagas),
schedules: parseInt(horario)
};

const response = await axios.post('http://localhost:3001/elective/createElective', data)
console.log(response.data);
navigate('/home')

}catch(err) {
console.error('Erro no cadastro:', err);
}
};

}

return (
<ChakraProvider>


<C.Container>
<C.Content>

Expand Down Expand Up @@ -132,9 +106,9 @@ const CreateEletivas = () => {
value={serie}
onChange={(e)=>[setSerie(e.target.value), setError("")]}
>
<option value='option1'> 1</option>
<option value='option2'> 2</option>
<option value='option3'> 3</option>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
</Select>

<FormLabel color= '#243A69'>Professor Responsável</FormLabel>
Expand Down
15 changes: 6 additions & 9 deletions frontend/src/pages/CreateTrilhas/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,12 @@ const CreateTrilhas = () => {
setError("Preencha todos os campos");
return;
};
console.log(nomeTrilha);
console.log(descricao);
console.log(serie);
console.log(eletivas);

try {
const response = await axios.post('localhost:3000', {nomeTrilha, descricao, serie, eletivas });
const response = await axios.post('http://localhost:3001/learningpath/createLearningPaths', {name: nomeTrilha, description: descricao, school_year: parseInt(serie), electives: eletivas });

if (response.status === 200) {
console.log(response)
if (response.status === 201) {

toast({
title: 'Trilha cadastrada.',
Expand Down Expand Up @@ -128,9 +125,9 @@ const CreateTrilhas = () => {
value={serie}
onChange={(e)=>[setSerie(e.target.value), setError("")]}
>
<option value='option1'> 1</option>
<option value='option2'> 2</option>
<option value='option3'> 3</option>
<option value={1}> 1</option>
<option value={2}> 2</option>
<option value={3}> 3</option>
</Select>

<FormLabel color= '#243A69'>Eletivas relacionadas </FormLabel>
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/pages/Home/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import React from "react";
import Header from '../../components/Header/index.js'
import axios from "axios"
import styled from "styled-components";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { Flex, Box, Heading, Spacer, Menu, MenuButton, MenuList, MenuItem } from "@chakra-ui/react";
import { Image } from '@chakra-ui/react'
import cmtnLogo from '../../img/cmtnLogo.png'
import menuHamburguer from '../../icon/menuHamburguer.png'
import userIcon from '../../icon/usuario-do-circulo 1.png';
import settingsIcon from '../../icon/definicoes 1.png';
import helpIcon from '../../icon/interrogatorio 1.png';
import logoutIcon from '../../icon/sair-alt 1.png';

const Home = () => {

Expand Down
44 changes: 27 additions & 17 deletions frontend/src/pages/PathExclusion/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const TrilhasList = () => {
useEffect(() => {
async function fetchTrilhas() {
try {
const response = await axios.get('http://localhost:3000/api/trilhas'); // Endpoint para buscar trilhas
const response = await axios.get('http://localhost:3000/learningpath/learningpath'); // Endpoint para buscar trilhas
setTrilhas(response.data); // Define as trilhas na state 'trilhas'
} catch (error) {
console.error('Erro ao buscar trilhas:', error);
Expand All @@ -38,33 +38,43 @@ const TrilhasList = () => {
}, []);

// Função para marcar/desmarcar trilha selecionada
const toggleSelecionada = (id) => {
const handleCheckboxChange = (id) => {
const isSelected = trilhasSelecionadas.includes(id);

if (isSelected) {
const updatedSelection = trilhasSelecionadas.filter((trilhaId) => trilhaId !== id);
setTrilhasSelecionadas(updatedSelection);
// Se já estiver selecionado, remova da lista de selecionados
setTrilhasSelecionadas(trilhasSelecionadas.filter((eleId) => eleId !== id));
} else {
// Se não estiver selecionado, adicione à lista de selecionados
setTrilhasSelecionadas([...trilhasSelecionadas, id]);
}

console.log(trilhasSelecionadas)
};


// Função para excluir trilhas selecionadas
const handleExcluirTrilhas = async () => {
const handleExcluirClick = async () => {
try {
await axios.delete('http://localhost:3000/api/deleteLearningPaths', {
data: { id: trilhasSelecionadas }, // Envia os IDs das trilhas selecionadas para exclusão
});
// Atualiza a lista de trilhas após a exclusão
const updatedTrilhas = trilhas.filter((trilha) => !trilhasSelecionadas.includes(trilha.id));
setTrilhas(updatedTrilhas);
setTrilhasSelecionadas([]); // Limpa as trilhas selecionadas após a exclusão
alert('Trilhas excluídas com sucesso!');
// Enviar uma solicitação para excluir as eletivas selecionadas
trilhasSelecionadas.map(async (eletiva) => {
await axios.delete('http://localhost:3001/elective/deleteElective', {
data: { id: eletiva },
});
})

// Atualizar a lista de eletivas após a exclusão
const response = await axios.get('http://localhost:3000/learningpath/deleteLearningPaths');
setTrilhas(response.data);

// Limpar a lista de eletivas selecionadas
setTrilhasSelecionadas([]);
} catch (error) {
console.error('Erro ao excluir trilhas:', error);
}
};

const dados = [{"nomeTrilha": "teste", "anoTrilha": 2}]


return (
<ChakraProvider>
Expand All @@ -84,18 +94,18 @@ const TrilhasList = () => {
</Tr>
</Thead>
<Tbody>
{dados.map((linha, index) => (
{trilhas.map((linha, index) => (
<Tr key={index}>
<Td>{linha.nomeTrilha}</Td>
<Td>{linha.anoTrilha}</Td>
<Td><Checkbox colorScheme='red' defaultChecked></Checkbox></Td>
<Td><Checkbox colorScheme='red' onChange={() => handleCheckboxChange(linha.id)}></Checkbox></Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
<Box display="flex" justifyContent="center">
<Button color="#243A69" variant='solid' margin="2vh">Excluir</Button>
<Button color="#243A69" variant='solid' margin="2vh" onClick={handleExcluirClick}>Excluir trilha selecionadas</Button>
</Box>
</Box>
</Flex>
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/pages/Signin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@ const Signin = () => {
const response = await axios.post("http://localhost:3001/auth/login", {
email: email,
password: senha,
});
})

if (response.data.accessToken) {
signin(response.data.accessToken);
navigate("/home");
} else {
sessionStorage.setItem("accessToken", response.data.accessToken);
} else {
setError("Credenciais inválidas");
}
} catch (error) {
Expand Down

0 comments on commit ea11694

Please sign in to comment.