bulk-pdf for unique email addresses

This commit is contained in:
Harikrishnan Gopal
2025-03-09 15:34:51 +05:30
parent 27a06c3787
commit d2eeacffe7
2 changed files with 170 additions and 169 deletions

View File

@@ -90,129 +90,112 @@ const CourseConsolidated = () => {
{ key: "pwdPaperSettingTeachers", role: "PwD Paper Setter" },
];
// ✅ NEW: Group appointments by Faculty ID
const facultyMap = {};
for (const { key, role } of roles) {
if (!courseData[key] || courseData[key].length === 0) continue; // Skip empty roles
const doc = new jsPDF();
// College Logo
const logoUrl = "/logo.png";
const loadImage = async (url) => {
const response = await fetch(url);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
reader.readAsDataURL(blob);
});
};
try {
const logoBase64 = await loadImage(logoUrl);
doc.addImage(logoBase64, "PNG", 10, 10, 40, 40);
} catch (error) {
console.error("Failed to load logo:", error);
}
// Title Section
doc.setFont("times", "normal");
doc.setTextColor(0, 0, 0);
doc.setFontSize(12);
doc.text("Date: " + new Date().toLocaleDateString(), 150, 20);
doc.setFontSize(14);
doc.text("CONFIDENTIAL", 10, 60);
doc.setFontSize(10);
doc.text(`LETTER OF APPOINTMENT AS ${role.toUpperCase()}`, 105, 70, {
align: "center",
});
// Fetch Emails and Prepare Table Data
let table1Data = [];
let emails = [];
if (!courseData[key] || courseData[key].length === 0) continue;
for (const teacher of courseData[key]) {
const email = await fetchFacultyEmail(teacher.facultyId);
emails.push(email);
table1Data.push([
teacher.facultyName,
"K. J. Somaiya School of Engineering",
if (!facultyMap[teacher.facultyId]) {
facultyMap[teacher.facultyId] = {
facultyName: teacher.facultyName,
email: await fetchFacultyEmail(teacher.facultyId),
appointments: [],
};
}
facultyMap[teacher.facultyId].appointments.push({
role,
email,
]);
teacher,
});
}
}
// ✅ NEW: For each Faculty, generate PDFs & send one email
for (const facultyId in facultyMap) {
const faculty = facultyMap[facultyId];
const pdfBlobs = [];
for (const appointment of faculty.appointments) {
const { role } = appointment;
const doc = new jsPDF();
// Add Logo and Title (your original PDF content)
const logoUrl = "/logo.png";
const loadImage = async (url) => {
const response = await fetch(url);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
reader.readAsDataURL(blob);
});
};
try {
const logoBase64 = await loadImage(logoUrl);
doc.addImage(logoBase64, "PNG", 10, 10, 40, 40);
} catch (error) {
console.error("Failed to load logo:", error);
}
doc.setFont("times", "normal");
doc.text(`Date: ${new Date().toLocaleDateString()}`, 150, 20);
doc.text("CONFIDENTIAL", 10, 60);
doc.text(`LETTER OF APPOINTMENT AS ${role.toUpperCase()}`, 105, 70, { align: "center" });
autoTable(doc, {
head: [["Name", "Affiliation", "Appointment Role", "Email"]],
body: [[faculty.facultyName, "K. J. Somaiya School of Engineering", role, faculty.email]],
startY: 80,
theme: "grid",
headStyles: { fillColor: maroon, textColor: [255, 255, 255] },
});
autoTable(doc, {
body: [
["Programme:", courseData.courseName],
["Exam Category:", "Regular Examination"],
["Exam Type:", courseData.examType],
["Exam Season:", "Second Half - Winter Examination 2023"],
["Year:", courseData.year],
["Semester:", courseData.semester],
["Course Name:", courseName],
["Course Code:", courseData.courseCode],
],
startY: doc.previousAutoTable.finalY + 10,
theme: "grid",
});
const pdfBlob = doc.output("blob");
pdfBlobs.push({ blob: pdfBlob, filename: `${courseName}-${role}.pdf` });
}
// Generate Table
autoTable(doc, {
head: [["Name", "Affiliation", "Appointment Role", "Email"]],
body: table1Data,
startY: 80,
theme: "grid",
headStyles: { fillColor: maroon, textColor: [255, 255, 255] },
styles: { textColor: [0, 0, 0] },
});
// ✅ NEW: Send ONE email with ALL PDFs to the Faculty
try {
const formData = new FormData();
// Content Table
const detailsTableData = [
["Programme:", courseData.courseName],
["Exam Category:", "Regular Examination"],
["Exam Type:", courseData.examType],
["Exam Season:", "Second Half - Winter Examination 2023"],
["Number of Sets Required:", courseData.paperSettingTeachers.length],
["Year:", courseData.year],
["Semester:", courseData.semester],
["Course Name:", courseName],
["Course Code:", courseData.courseCode],
];
pdfBlobs.forEach(({ blob, filename }) => {
formData.append("pdfFiles", blob, filename); // note 'pdfFiles' is plural
});
autoTable(doc, {
body: detailsTableData,
startY: doc.previousAutoTable.finalY + 10,
theme: "grid",
styles: { textColor: [0, 0, 0] },
});
formData.append("recipientEmail", faculty.email);
formData.append("facultyName", faculty.facultyName);
formData.append("courseName", courseName);
// Footer
const footerY = doc.previousAutoTable.finalY + 10;
doc.setFontSize(12);
doc.text("Dr. S. K. Ukarande", 10, footerY);
doc.text("Principal", 10, footerY + 5);
doc.text("K. J. Somaiya School of Engineering", 10, footerY + 10);
const footerContactY = footerY + 20;
doc.setFontSize(10);
doc.text(
"Somaiya Vidyavihar, Vidyavihar (East), Mumbai-400 022, India",
10,
footerContactY
);
doc.text("Telephone: (91-22) 44444400, 44444404", 10, footerContactY + 5);
doc.text("Email: principal.tech@somaiya.edu", 10, footerContactY + 10);
doc.text("Web: www.somaiya.edu/kjsieit", 10, footerContactY + 15);
// Convert PDF to Blob
const pdfBlob = doc.output("blob");
// Send Email to Each Faculty
for (const email of emails) {
try {
const formData = new FormData();
formData.append("pdfFile", pdfBlob, `${courseName}-${role}.pdf`);
formData.append("fileName", `${courseName}-${role}.pdf`);
formData.append("recipientEmail", email);
formData.append("role", role);
formData.append("courseName", courseName);
const emailResponse = await sendEmail(formData, "pdf");
toast.success(`✅ Email sent successfully to ${email}`);
console.log("Response from server:", emailResponse);
} catch (emailError) {
toast.error(`❌ Error sending email to ${email}:`, emailError.message);
}
const emailResponse = await sendEmail(formData, "bulk-pdf");
toast.success(`✅ Email sent successfully to ${faculty.email}`);
console.log("Response:", emailResponse);
} catch (error) {
toast.error(`❌ Error sending email to ${faculty.email}: ${error.message}`);
console.error(error);
}
}
};
return (
<>