Skip to content

Commit

Permalink
matrícula em eletivas
Browse files Browse the repository at this point in the history
  • Loading branch information
yaskisoba committed Dec 13, 2023
1 parent 8ed18e2 commit 6f13fa5
Show file tree
Hide file tree
Showing 9 changed files with 276 additions and 8 deletions.
28 changes: 26 additions & 2 deletions backend/controllers/ElectiveControllers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { Electives } = require('../models/schemas')
const { Electives, ElectivesStudents } = require('../models/schemas')

exports.createElective = async(req, res) => {
const { name, description, school_year, teacher, vacancies, schedules } = req.body;
Expand Down Expand Up @@ -47,4 +47,28 @@ exports.listElectives = async (req, res) => {
} catch (err) {
res.status(400).json({ error: err.message });
}
};
};

exports.ElectivesByStudent = async(req, res) => {
const { names, student_id } = req.body
const exists = await ElectivesStudents.findOne({where:{ student_id: student_id}})

if(!exists){
try
{
await ElectivesStudents.create({
names: names,
student_id: student_id
}).then(() => {
res.status(201).json("OK")
})

}catch(err)
{
res.status(400).json({"error": err})
}
}else{
res.status(200).json("Já existe")
}

}
2 changes: 1 addition & 1 deletion backend/controllers/LearningPathsEnrolmentController.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ exports.studentEnrolment = async (req, res) => {
const existingUser = await Users.findOne({where: {id: student_id}})

if (existingEnrolment) {
return res.status(400).json({error: 'O aluno já está matriculado nesta trilha.'});
return res.status(200).json({error: 'O aluno já está matriculado nesta trilha.'});
} else {
await LearningPathsEnrolment.create({
learning_path_id: learning_path_id,
Expand Down
26 changes: 26 additions & 0 deletions backend/migrations/studentEletives.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

let electives = { schema: 'ElectivesStudents', tableName: 'tb__student_electives'}

module.exports = {
up: async (queryInterface, Sequelize) => {
const transaction = await queryInterface.sequelize.transaction();

try {
await queryInterface.createTable(electives, {
co_elective_student: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
ds_student_id: { type: Sequelize.INTEGER, allowNull: false},
ds_name: { type: Sequelize.TEXT, allowNull: false },
})

await transaction.commit()
}catch (e) {
await transaction.rollback()
throw e
}
},

down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable(electives)
}
}
22 changes: 22 additions & 0 deletions backend/models/schemas/ElectivesStudents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module.exports = (sequelize, DataTypes) => {
const ElectivesStudents = sequelize.define("ElectivesStudents", {
id: {
type: DataTypes.INTEGER,
field: "co_elective_student",
primaryKey: true,
autoIncrement: true
},
student_id: {
type: DataTypes.INTEGER,
field: "ds_student_id",
allowNull: false
},
names: {
type: DataTypes.TEXT,
field: "ds_name",
allowNull: false
}
})

return ElectivesStudents;
}
3 changes: 2 additions & 1 deletion backend/views/routes/Electives.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const electivesController = require('../../controllers/ElectiveControllers')

router.post("/createElective", electivesController.createElective);
router.delete("/deleteElective", electivesController.deleteElective);
router.get("/electives", electivesController.listElectives)
router.get("/electives", electivesController.listElectives);
router.post("/matricula-eletivas", electivesController.ElectivesByStudent)

module.exports = router;
173 changes: 173 additions & 0 deletions frontend/src/pages/NewEnrolmentElectives/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useToast } from "@chakra-ui/react";
import { Container, Flex, Text, Select, FormControl, FormLabel, Checkbox, Button, Center, Stack, CheckboxGroup } from "@chakra-ui/react";
import Header from "../../components/Header/index.js";
import Footer from "../../components/Footer/index.js";
import { ChakraProvider } from "@chakra-ui/react";
import useAuth from "../../hooks/useAuth";
import * as C from "./styles.js";
import { useFormik } from "formik";
import * as yup from "yup";
import axios from "axios";
import ButtonCadastrar from "../../components/Button";


import { Link } from "react-router-dom";

const NewEnrolmentLP = () => {
const { userId, userSy } = useAuth();
const user = userId()
const schoolYear = userSy()
const [showAlert, setShowAlert] = useState(false);
const [numElectives, setNumElectives] = useState(false);

const navigate = useNavigate();
const toast = useToast();
const [eletivas, setEletivas] = useState([]);

useEffect(() => {
const fetchEletivas = async () => {
try {
const response = await axios.get(
"http://localhost:3001/elective/electives"
);
setEletivas(response.data);
} catch (error) {
console.error("Erro ao buscar eletivas:", error);
}
};

const numElectives = async () => {
if (parseInt(schoolYear) === 1) {
setNumElectives(6)
} else if (parseInt(schoolYear) === 2 || parseInt(schoolYear) === 3) {
setNumElectives(4)
}
}

numElectives();
fetchEletivas();
}, []);

const formik = useFormik({
initialValues: {
eletivas: [],
},
validationSchema: yup.object({
eletivas: yup.array().test('conditionalExactCount', `É necessário selecionar exatamente ${numElectives} eletiva(s)`, function (value) {
let requiredCount;

if (parseInt(schoolYear) === 1) {
requiredCount = 6;
} else if (parseInt(schoolYear) === 2 || parseInt(schoolYear) === 3) {
requiredCount = 4;
}

return value.length === requiredCount;
}),
}),
onSubmit: async(values) => {
try{
const response = await axios.post("http://localhost:3001/elective/matricula-eletivas",
{
names: JSON.stringify(values.eletivas),
student_id: parseInt(user),
}
)

if (response.status === 201) {
toast({
title: "Matrícula realizada.",
description: "Matrícula realizada com sucesso!",
status: "success",
duration: 2800,
isClosable: true,
position: "top",
});


setShowAlert(true);
setTimeout(() => {
navigate("/home-student");
}, 1000);
} else if(response.status === 200){
toast({
title: "Matrícula já realizada.",
description: "Sua matrícula já foi realizada!",
status: "error",
duration: 2800,
isClosable: true,
position: "top",
});

setShowAlert(true);
setTimeout(() => {
navigate("/home-student");
}, 2000);
}
}catch(error){
console.error("Erro ao cadastrar:", error);
toast({
title: "Erro na matrícula.",
description: "Tente novamente mais tarde.",
status: "error",
duration: 2800,
isClosable: true,
position: "top",
});
}
}
})

return (
<ChakraProvider>
<Flex direction="column" minH="100vh">
<Header />
<Container flex="1" marginTop='5vh'>
<Center>
<C.titulo>
<Text
textAlign={"center"}
fontSize={"3xl"}
color={"#243A69"}
as={"b"}
>
Matricule-se em eletivas
</Text>
</C.titulo>
</Center>
<FormControl marginTop="2vh">
<FormLabel color="#243A69" fontWeight='bold'>
Selecione as eletivas
</FormLabel>

<CheckboxGroup value={formik.values.eletivas} onChange={(values) => formik.setFieldValue("eletivas", values)
}>
{eletivas.map((eletiva) =>
<Checkbox isChecked={formik.values.eletivas.includes(eletiva.name)} color="#243A69" marginLeft="1vh" value={eletiva.name} >{eletiva.name} </Checkbox>
)}
</CheckboxGroup>
{formik.touched.eletivas &&
formik.errors.eletivas && (
<Text color="red.500" fontSize="sm">
{formik.errors.eletivas}
</Text>
)}

<Center paddingBottom={5} marginTop="3vh">
<ButtonCadastrar
Text="Cadastrar"
onClick={formik.handleSubmit}
></ButtonCadastrar>
</Center>
</FormControl>
</Container>
<Footer />
</Flex>
</ChakraProvider>

);
};

export default NewEnrolmentLP;
10 changes: 10 additions & 0 deletions frontend/src/pages/NewEnrolmentElectives/styles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import styled from "styled-components";

export const titulo = styled.div`
font-size: 150%;
font-weight: 600;
color: #243A69;
margin-left: 20px;
margin-top: 20px;
align: center;
`;
11 changes: 8 additions & 3 deletions frontend/src/pages/NewEnrolmentLP/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,20 @@ const NewEnrolmentLP = () => {
setTimeout(() => {
navigate("/home-student");
}, 1000);
} else {
} else if(response.status === 200){
toast({
title: "Erro na matrícula.",
description: response.data.message || "Erro desconhecido.",
title: "Matrícula já realizada.",
description: response.data.message || "Sua matrícula já foi realizada!",
status: "error",
duration: 2800,
isClosable: true,
position: "top",
});

setShowAlert(true);
setTimeout(() => {
navigate("/home-student");
}, 2000);
}
}
}catch(error){
Expand Down
9 changes: 8 additions & 1 deletion frontend/src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import NewEnrolmentLP from "../pages/NewEnrolmentLP"
import ListLearningPath from "../pages/ListLearningPath"
import ListElectives from "../pages/ListElectives"
import StudentsLP from "../pages/StudentsLP";
import NewEnrolmentElectives from "../pages/NewEnrolmentElectives";

const RoutesApp = () => {
const { isAuthenticated, isSuperUser } = useAuth();
Expand Down Expand Up @@ -111,7 +112,13 @@ const RoutesApp = () => {
<Route
path="/matricula-trilha"
element={
!isAuthenticated() ? <Navigate to="/signin" /> : <NewEnrolmentLP />
!isAuthenticated() ? <Navigate to="/signin" /> : <NewEnrolmentLP />
}
/>
<Route
path="/matricula-eletiva"
element={
!isAuthenticated() ? <Navigate to="/signin" /> : <NewEnrolmentElectives />
}
/>
</>
Expand Down

0 comments on commit 6f13fa5

Please sign in to comment.