Skip to content

Commit

Permalink
Updated registration (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
samnotfound404 authored Jul 12, 2024
1 parent 4f81c1d commit ce5e242
Show file tree
Hide file tree
Showing 6 changed files with 229 additions and 52 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@reduxjs/toolkit": "^2.0.1",
"@tanstack/react-table": "^8.11.2",
"@types/qs": "^6.9.14",
"antd": "^5.13.1",
"antd": "^5.19.1",
"axios": "^1.6.3",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
Expand Down
48 changes: 30 additions & 18 deletions src/app/(routes)/admin/students/page.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,49 @@
"use client";
import { fetchStudentData } from "@/helpers/api";
import { useState, useEffect } from 'react';
import { fetchStudentData, } from "@/helpers/api";
import Cookies from "js-cookie";
import Table from "@/components/NewTableComponent/Table";
import type {DTO} from '@/dto/StudentDto'
import {
MaterialReactTable,
useMaterialReactTable,
type MRT_Row,
createMRTColumnHelper,
} from 'material-react-table';
import type { DTO } from '@/dto/StudentDto';
import { createMRTColumnHelper } from 'material-react-table';
import generateColumns from "@/components/NewTableComponent/ColumnMapping";
import { jsondto } from "@/dto/StudentDto";
import { Form } from 'antd';
import { cookies } from 'next/headers';
const hiddenColumns = ['userId', 'programId','id'];

const StudentPage = () => {
const [students, setStudents] = useState<DTO[]>([]);
const columnHelper = createMRTColumnHelper<DTO>();
const columns = generateColumns(jsondto);

const hiddenColumns = ['userId', 'programId', 'id'];


const StudentPage = async () => {
const columnHelper = createMRTColumnHelper<DTO>();
const columns = generateColumns(jsondto)
console.log(columns)
const AllStudents = await fetchStudentData(Cookies.get("accessToken"),null);



const visibleColumns = columns.filter(
(column:any) => !hiddenColumns.includes(column?.accessorKey)
(column: any) => !hiddenColumns.includes(column?.accessorKey)
);


useEffect(() => {
const fetchData = async () => {
const data = await fetchStudentData(Cookies.get("accessToken"), null);
setStudents(data);
console.log(data);
};


fetchData();
}, []);


return (
<div className="m-10">
<h1 className="text-center font-bold text-3xl my-5 py-5">Students</h1>
<div>
{AllStudents && (
{students.length > 0 && (
<Table
data={AllStudents}
data={students}
columns={visibleColumns}
type={"student"}
/>
Expand Down
180 changes: 153 additions & 27 deletions src/components/NewTableComponent/StudentModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ import CircularProgress from '@mui/material/CircularProgress';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { grey } from '@mui/material/colors';
import { Button } from '@mui/material';

import Cookies from 'js-cookie';
import Loader from '@/components/Loader/loader';
const redirect = () => {};
const theme = createTheme({
palette: {
primary: {
Expand Down Expand Up @@ -49,32 +52,122 @@ const style = {

const baseUrl = process.env.NEXT_PUBLIC_BACKEND_URL;

const handleRegistration = async (accessToken, studentId, seasonId, currentStatus) => {
if (!accessToken) {
console.error('No access token provided');
return;
}

try {
const res = await fetch(`${baseUrl}/api/v1/registrations`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify([{
studentId,
seasonId,
registered: !currentStatus
}]),
});

if (!res.ok) {
const errorDetails = await res.json();
console.error(`Failed to update registration status: ${errorDetails.message}`);
throw new Error(`Failed to update registration status: ${errorDetails.message}`);
//Will change it in a separate console removal PR
}

console.log('Registration status updated successfully');
return true;
} catch (error) {
console.error('Error updating registration status:', error.message);
alert(`Error updating registration status: ${error.message}`);
return false;
}
};

export default function StudentModal({ open, setOpen, id }) {
const [studentData, setStudentData] = useState(null);
const [loading, setLoading] = useState(false);
const [registrationData, setRegistrationData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
const fetchStudentData = async () => {
setLoading(true);
try {
const response = await fetch(`${baseUrl}/api/v1/students/${id}`);
const data = await response.json();
setStudentData(data);
} catch (error) {
console.error('Error fetching student data:', error);
const fetchStudentData = async (accessToken, id) => {
if (!accessToken) {
console.error('No access token provided');
return;
}

setLoading(true);
try {
const response = await fetch(`${baseUrl}/api/v1/students/${id}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
if (!response.ok) {
throw new Error(`Error fetching student data: ${response.statusText}`);
}
const data = await response.json();
setStudentData(data);
} catch (error) {
console.error('Error fetching student data:', error);
} finally {
setLoading(false);
};
}
};

const fetchRegistrationData = async (accessToken, studentId) => {
if (!accessToken) {
console.error('No access token provided');
return;
}

setLoading(true);
try {
const response = await fetch(`${baseUrl}/api/v1/registrations`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
});

if (!response.ok) {
throw new Error(`Error fetching registration data: ${response.statusText}`);
}
const allData = await response.json();
const filteredData = allData.filter((registration) => registration.student.id === studentId);
setRegistrationData(filteredData);
} catch (error) {

} finally {
setLoading(false);
}
};

useEffect(() => {
if (open && id) {
fetchStudentData();
const accessToken = Cookies.get("accessToken");
fetchStudentData(accessToken, id);
fetchRegistrationData(accessToken, id);
}
}, [open, id]);

const handleClose = () => setOpen(false);

const handleStatusChange = async (studentId, seasonId, currentStatus) => {
const success = await handleRegistration(Cookies.get("accessToken"), studentId, seasonId, currentStatus);
if (success) {
setRegistrationData((prevData) =>
prevData.map((registration) =>
registration.season.id === seasonId ? { ...registration, registered: !currentStatus } : registration
)
);
}
};

return (
<ThemeProvider theme={theme} >
<ThemeProvider theme={theme}>
<Modal
open={open}
onClose={handleClose}
Expand Down Expand Up @@ -160,19 +253,19 @@ export default function StudentModal({ open, setOpen, id }) {
<TableCell component="th" scope="row" sx={{ fontWeight: 'bold' }}>
Name
</TableCell>
<TableCell>{studentData.user.name}</TableCell>
<TableCell>{studentData.user ? studentData.user.name : 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row" sx={{ fontWeight: 'bold' }}>
Email
</TableCell>
<TableCell>{studentData.user.email}</TableCell>
<TableCell>{studentData.user ? studentData.user.email : 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row" sx={{ fontWeight: 'bold' }}>
Contact
</TableCell>
<TableCell>{studentData.user.contact}</TableCell>
<TableCell>{studentData.user ? studentData.user.contact : 'N/A'}</TableCell>
</TableRow>
</TableBody>
</Table>
Expand All @@ -187,24 +280,24 @@ export default function StudentModal({ open, setOpen, id }) {
<TableCell component="th" scope="row" sx={{ fontWeight: 'bold' }}>
Branch
</TableCell>
<TableCell>{studentData.program.branch}</TableCell>
<TableCell>{studentData.program ? studentData.program.branch : 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row" sx={{ fontWeight: 'bold' }}>
Course
</TableCell><TableCell>{studentData.program.course}</TableCell>
</TableCell><TableCell>{studentData.program ? studentData.program.course : 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row" sx={{ fontWeight: 'bold' }}>
Year
</TableCell>
<TableCell>{studentData.program.year}</TableCell>
<TableCell>{studentData.program ? studentData.program.year : 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row" sx={{ fontWeight: 'bold' }}>
Department
</TableCell>
<TableCell>{studentData.program.department}</TableCell>
<TableCell>{studentData.program ? studentData.program.department : 'N/A'}</TableCell>
</TableRow>
</TableBody>
</Table>
Expand All @@ -222,7 +315,7 @@ export default function StudentModal({ open, setOpen, id }) {
</TableRow>
</TableHead>
<TableBody>
{studentData.resumes.map((resume) => (
{studentData.resumes ? studentData.resumes.map((resume) => (
<TableRow key={resume.id}>
<TableCell>{resume.id}</TableCell>
<TableCell>
Expand All @@ -238,7 +331,7 @@ export default function StudentModal({ open, setOpen, id }) {
</TableCell>
<TableCell>{resume.verified.toString()}</TableCell>
</TableRow>
))}
)) : 'N/A'}
</TableBody>
</Table>
</TableContainer>
Expand All @@ -249,19 +342,52 @@ export default function StudentModal({ open, setOpen, id }) {
<Table>
<TableHead>
<TableRow>
<TableCell sx={{ fontWeight: 'bold' }}>ID</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Penalty</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Reason</TableCell>
</TableRow>
</TableHead>
<TableBody>
{studentData.penalties.map((penalty) => (
{studentData.penalties ? studentData.penalties.map((penalty) => (
<TableRow key={penalty.id}>
<TableCell>{penalty.id}</TableCell>
<TableCell>{penalty.penalty}</TableCell>
<TableCell>{penalty.reason}</TableCell>
</TableRow>
))}
)) : 'N/A'}
</TableBody>
</Table>
</TableContainer>
<Typography variant="h5" component="h3" gutterBottom sx={{ mt: 2,mb:2}}>
Registration
</Typography>
<TableContainer component={Paper} elevation={3} sx={{ mb: 2 }} >
<Table>
<TableHead>
<TableRow>

<TableCell sx={{ fontWeight: 'bold' }}>Year</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Type</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Status</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{registrationData ? registrationData.map((registration) => (
<TableRow key={registration.id}>

<TableCell>{registration.season.year}</TableCell>
<TableCell>{registration.season.type}</TableCell>
<TableCell>{registration.registered ? "Registered" : "Not Registered"}</TableCell>
<TableCell>
<Button
variant="contained"
color={registration.registered ? "secondary" : "primary"}
onClick={() => handleStatusChange(studentData.id, registration.season.id, registration.registered)}
>
{registration.registered ? "Deregister" : "Register"}
</Button>
</TableCell>
</TableRow>
)) : 'N/A'}
</TableBody>
</Table>
</TableContainer>
Expand All @@ -273,4 +399,4 @@ export default function StudentModal({ open, setOpen, id }) {
</Modal>
</ThemeProvider>
);
}
}
22 changes: 22 additions & 0 deletions src/helpers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,27 @@ export const fetchStudentData = async (
return json;
};

export const fetchSeasonData = async (
accessToken: string | undefined,
filter: string | undefined
) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}
const res = await fetch(
filter ? url(`/registrations?${filter}`) : url("/registrations"),
{
next: { tags: ["AllStudents"] },
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const json = await res.json();
return json;
};

export const fetchCompanyRecruiters = async (
accessToken: string | undefined,
companyId: string | undefined
Expand Down Expand Up @@ -300,6 +321,7 @@ export const fetchRecruiterData = async (
redirect();
return;
}

const res = await fetch(
filter ? url(`/recruiters?${filter}`) : url("/recruiters"),
{
Expand Down
Loading

0 comments on commit ce5e242

Please sign in to comment.