import React, { useState, useEffect } from "react";
import axios from "axios";
import * as XLSX from "xlsx-js-style";
import { sendEmail, createExcelBook } from "../api";
import Navbar from "./Navbar";
const styles = {
header: {
background: '#003366',
color: 'white',
padding: '20px 0',
textAlign: 'center',
fontSize: '24px',
marginBottom: '0',
},
buttonRow: {
display: 'flex',
justifyContent: 'space-around',
alignItems: 'center',
padding: '10px 0',
margin: '0',
backgroundColor: '#003366',
boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)'
},
button: {
padding: '10px 20px',
borderRadius: '5px',
color: 'white',
border: 'none',
cursor: 'pointer',
fontSize: '16px',
flex: '1',
},
bulkDownloadButton: {
backgroundColor: '#3fb5a3',
},
downloadButton: {
backgroundColor: '#28a745',
},
emailButton: {
backgroundColor: '#ff6f61',
},
tableContainer: {
maxHeight: "70vh",
overflowY: "auto",
border: "1px solid #ccc",
padding: "10px",
borderRadius: "5px",
backgroundColor: "#f9f9f9",
marginBottom: "20px",
},
table: {
width: "100%",
marginTop: "20px",
borderCollapse: "collapse",
},
th: {
backgroundColor: "#333",
color: "white",
padding: "10px 15px",
},
td: {
padding: "10px",
textAlign: "left",
borderBottom: "1px solid #ddd",
},
paginationContainer: {
textAlign: "center",
marginTop: "20px",
},
paginationButton: {
padding: "10px 15px",
backgroundColor: "#007bff",
color: "white",
borderRadius: "5px",
border: "none",
},
main: {
width: "100%",
}
};
const ConsolidatedTable = () => {
const [searchQuery, setSearchQuery] = useState(""); // State for search input
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [currentPage, setCurrentPage] = useState(1);
const tablesPerPage = 5;
const [expandedTeacher, setExpandedTeacher] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(
"http://localhost:8080/api/table/consolidated-table"
);
setData(response.data);
setLoading(false);
} catch (error) {
console.error("Error fetching table data:", error);
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return
Loading...
;
}
// Extract unique faculty names and filter based on the search query
const filteredTeachers = [...new Set(data.map((row) => row.Name))].filter(
(teacher) =>
teacher.toLowerCase().includes(searchQuery.toLowerCase()) // Filter by search query
);
// Pagination logic applied to filtered teachers
const indexOfLastTable = currentPage * tablesPerPage;
const indexOfFirstTable = indexOfLastTable - tablesPerPage;
const currentTeachers = filteredTeachers.slice(
indexOfFirstTable,
indexOfLastTable
);
const totalPages = Math.ceil(filteredTeachers.length / tablesPerPage);
const handleNextPage = () => {
if (currentPage < totalPages) setCurrentPage((prevPage) => prevPage + 1);
};
const handlePrevPage = () => {
if (currentPage > 1) setCurrentPage((prevPage) => prevPage - 1);
};
const createExcelFile = (teacherData, teacherName) => {
const workbook = createExcelBook(teacherData, teacherName);
XLSX.writeFile(workbook, `${teacherName.replace(/\s+/g, "_")}_Table.xlsx`);
};
const bulkDownload = () => {
filteredTeachers.forEach((teacher) => {
const teacherData = data.filter((row) => row.Name === teacher);
createExcelFile(teacherData, teacher);
});
};
const handleSendEmail = async (teacher, teacherData) => {
const facultyId = teacherData[0].facultyId;
try {
const response = await axios.get(
`http://localhost:8080/api/faculty/${facultyId}`
);
const facultyEmail = response.data.email;
const workbook = createExcelBook(teacherData, teacher);
const fileName = `${teacher.replace(/\s+/g, "_")}_table.xlsx`;
const excelBlob = XLSX.write(workbook, {
bookType: "xlsx",
type: "array",
});
const file = new File([excelBlob], fileName, {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const formData = new FormData();
formData.append("teacher", teacher);
formData.append("fileName", fileName);
formData.append("recipientEmail", facultyEmail);
formData.append("file", file);
try {
const emailResponse = await sendEmail(formData);
alert(`Email sent successfully to ${facultyEmail}`);
console.log("Response from server:", emailResponse);
} catch (emailError) {
console.error("Error sending email:", emailError);
alert("Failed to send email.");
}
} catch (facultyError) {
console.error("Error fetching Faculty data:", facultyError);
alert("Failed to fetch faculty data.");
}
};
const sendEmailsToAllTeachers = async () => {
for (let teacher of filteredTeachers) {
const teacherData = data.filter((row) => row.Name === teacher);
await handleSendEmail(teacher, teacherData); // Wait for each email to be sent before proceeding to the next
}
alert("Emails sent to all teachers.");
};
return (
<>
Faculty Tables with Download Options
{/* Search Bar */}
setSearchQuery(e.target.value)}
placeholder="Search for a faculty..."
style={{
width: "100%",
padding: "10px",
borderRadius: "5px",
border: "1px solid #ccc",
fontSize: "16px",
}}
/>
{currentTeachers.map((teacher, index) => {
const teacherData = data.filter((row) => row.Name === teacher);
return (
setExpandedTeacher(
expandedTeacher === teacher ? null : teacher
)
}
>
{teacher}'s Table
{expandedTeacher === teacher && (
| Semester |
Course Code |
Course Name |
Exam Type |
Year |
Marks |
Name |
Affiliation/College |
Highest Qualification |
Career Experience |
Oral/Practical |
Assessment |
Reassessment |
Paper Setting |
Moderation |
PwD Paper Setting |
{teacherData.map((row, idx) => (
| {row.semester} |
{row.courseCode} |
{row.courseName} |
{row.examType} |
{row.year} |
{row.marks} |
{row.Name} |
{row.affiliation} |
{row.qualification} |
{row.experience} |
{row.oralPractical} |
{row.assessment} |
{row.reassessment} |
{row.paperSetting} |
{row.moderation} |
{row.pwdPaperSetting} |
))}
)}
);
})}
{/* Pagination controls */}
Page {currentPage} of {totalPages}
>
);
};
export default ConsolidatedTable;