Skip to content

Commit

Permalink
added export all data component
Browse files Browse the repository at this point in the history
  • Loading branch information
sangam2109 committed Jul 3, 2024
1 parent 72c86b4 commit b54f713
Show file tree
Hide file tree
Showing 12 changed files with 698 additions and 161 deletions.
3 changes: 3 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ const tr104 = require("./routes/UserProfileData/Training4");
const placementData = require("./routes/UserProfileData/PlacementData");
const adminControl = require("./routes/adminControlRoutes/adminControl");
const test = require("./routes/test.js");
const certificate = require('./routes/getCertificate.js')


app.use("/api/userprofiles", userProfileRoutes);
app.use("/api/tr101", tr101);
Expand All @@ -40,6 +42,7 @@ app.use("/api/validate", validateRoute);
app.use("/api/password", passwordResetRoute);
app.use("/api/admin", adminControl);
app.use("/api/test", test);
app.use("/api/certificate", certificate);
// Start the server
const port = process.env.PORT;
app.listen(port, () => {
Expand Down
185 changes: 185 additions & 0 deletions backend/routes/getCertificate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
const express = require('express');
const router = express.Router();
const SignUp = require('../models/UserInfo').SignUp;

router.get('/tr101/:id', async (req, res) => {
try {
const id = req.params.id;

// Assuming SignUp model has a method to fetch certificates, adjust as per your actual model
const user = await SignUp.findById(id);

if (!user) {
return res.status(404).json({ success: false, message: 'User not found or certificate not available' });
}

const base64Certificate = user.tr101.certificate.replace(/^.+,/, ''); // Adjust this based on your schema

// Convert base64 to buffer
const certificateBuffer = Buffer.from(base64Certificate, 'base64');
const fileName = `${user.userInfo.Name}_${user.userInfo.urn}_tr101.pdf`.replace(/[^a-zA-Z0-9-_\.]/g, '_');

// Set response headers for file download
res.set({
'Content-Type': 'application/pdf', // Adjust the content type as per your file type
'Content-Disposition': 'inline; certificate.pdf', // Adjust filename as per your requirement
});

res.send(certificateBuffer);

} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});
router.get('/tr102/:id', async (req, res) => {
try {
const id = req.params.id;

// Assuming SignUp model has a method to fetch certificates, adjust as per your actual model
const user = await SignUp.findById(id);

if (!user) {
return res.status(404).json({ success: false, message: 'User not found or certificate not available' });
}

const base64Certificate = user.tr102.certificate.replace(/^.+,/, ''); // Adjust this based on your schema

// Convert base64 to buffer
const certificateBuffer = Buffer.from(base64Certificate, 'base64');
const fileName = `${user.userInfo.Name}_${user.userInfo.urn}_tr101.pdf`.replace(/[^a-zA-Z0-9-_\.]/g, '_');

// Set response headers for file download
res.set({
'Content-Type': 'application/pdf', // Adjust the content type as per your file type
'Content-Disposition': 'inline; certificate.pdf', // Adjust filename as per your requirement
});

res.send(certificateBuffer);

} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});
router.get('/tr103/:id', async (req, res) => {
try {
const id = req.params.id;

// Assuming SignUp model has a method to fetch certificates, adjust as per your actual model
const user = await SignUp.findById(id);

if (!user) {
return res.status(404).json({ success: false, message: 'User not found or certificate not available' });
}

const base64Certificate = user.tr103.certificate.replace(/^.+,/, ''); // Adjust this based on your schema

// Convert base64 to buffer
const certificateBuffer = Buffer.from(base64Certificate, 'base64');
const fileName = `${user.userInfo.Name}_${user.userInfo.urn}_tr101.pdf`.replace(/[^a-zA-Z0-9-_\.]/g, '_');

// Set response headers for file download
res.set({
'Content-Type': 'application/pdf', // Adjust the content type as per your file type
'Content-Disposition': 'inline; certificate.pdf', // Adjust filename as per your requirement
});

res.send(certificateBuffer);

} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});
router.get('/tr104/:id', async (req, res) => {
try {
const id = req.params.id;

// Assuming SignUp model has a method to fetch certificates, adjust as per your actual model
const user = await SignUp.findById(id);

if (!user) {
return res.status(404).json({ success: false, message: 'User not found or certificate not available' });
}

const base64Certificate = user.tr101.certificate.replace(/^.+,/, ''); // Adjust this based on your schema

// Convert base64 to buffer
const certificateBuffer = Buffer.from(base64Certificate, 'base64');
const fileName = `${user.userInfo.Name}_${user.userInfo.urn}_tr101.pdf`.replace(/[^a-zA-Z0-9-_\.]/g, '_');

// Set response headers for file download
res.set({
'Content-Type': 'application/pdf', // Adjust the content type as per your file type
'Content-Disposition': 'inline; certificate.pdf', // Adjust filename as per your requirement
});

res.send(certificateBuffer);

} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});
router.get('/appointmentLetter/:id', async (req, res) => {
try {
const id = req.params.id;

// Assuming SignUp model has a method to fetch certificates, adjust as per your actual model
const user = await SignUp.findById(id);

if (!user) {
return res.status(404).json({ success: false, message: 'User not found or certificate not available' });
}

const base64Certificate = user.placementData.appointmentLetter.replace(/^.+,/, ''); // Adjust this based on your schema

// Convert base64 to buffer
const certificateBuffer = Buffer.from(base64Certificate, 'base64');
const fileName = `${user.userInfo.Name}_${user.userInfo.urn}_tr101.pdf`.replace(/[^a-zA-Z0-9-_\.]/g, '_');

// Set response headers for file download
res.set({
'Content-Type': 'application/pdf', // Adjust the content type as per your file type
'Content-Disposition': 'inline; certificate.pdf', // Adjust filename as per your requirement
});

res.send(certificateBuffer);

} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});
router.get('/gateCertificate/:id', async (req, res) => {
try {
const id = req.params.id;

// Assuming SignUp model has a method to fetch certificates, adjust as per your actual model
const user = await SignUp.findById(id);

if (!user) {
return res.status(404).json({ success: false, message: 'User not found or certificate not available' });
}

const base64Certificate = user.placementData.gateCertificate.replace(/^.+,/, ''); // Adjust this based on your schema

// Convert base64 to buffer
const certificateBuffer = Buffer.from(base64Certificate, 'base64');
const fileName = `${user.userInfo.Name}_${user.userInfo.urn}_tr101.pdf`.replace(/[^a-zA-Z0-9-_\.]/g, '_');

// Set response headers for file download
res.set({
'Content-Type': 'application/pdf', // Adjust the content type as per your file type
'Content-Disposition': 'inline; certificate.pdf', // Adjust filename as per your requirement
});

res.send(certificateBuffer);

} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});
module.exports = router;
31 changes: 16 additions & 15 deletions backend/routes/getUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const SignUp = require('../models/UserInfo').SignUp;
const fetchuser = require('../middleware/fetchUser');
const isAdmin = require('../middleware/isAdmin');


router.get('/getuser/:crn', fetchuser, async (req, res) => {
try {
const crn = req.params.crn;
Expand All @@ -23,7 +22,7 @@ router.get('/getuser/:crn', fetchuser, async (req, res) => {
router.get('/getallusers', fetchuser, isAdmin, async (req, res) => {
try {
// Fetch all users
const users = await SignUp.find({}).select('-password');
const users = await SignUp.find({ role: 'user' }).select('-password');

// Return the list of users
return res.status(200).json({ success: true, data: users });
Expand All @@ -36,7 +35,7 @@ router.put('/updateUser/:crn', fetchuser, isAdmin, async (req, res) => {
const { crn } = req.params; // Get CRN from request parameters
const updatedFormData = req.body.updatedFormData; // Get updated user data from request body
try {
// Find user by CRN and update with updatedFormData

const updatedUser = await SignUp.findOneAndUpdate(
{ crn: crn }, // Filter condition: find user by CRN
{
Expand Down Expand Up @@ -75,23 +74,28 @@ router.put('/updateUser/:crn', fetchuser, isAdmin, async (req, res) => {
router.get('/getUsersByBatch', fetchuser, isAdmin, async (req, res) => {
try {
const { batch, trainingType } = req.query;

if (!batch || !trainingType) {
return res.status(400).json({ success: false, message: 'Batch and training type are required' });
}

const allowedTrainingTypes = ['tr101', 'tr102', 'tr103', 'tr104', 'placementData'];
const allowedTrainingTypes = ['tr101', 'tr102', 'tr103', 'tr104', 'placementData', 'all'];
if (!allowedTrainingTypes.includes(trainingType)) {
return res.status(400).json({ success: false, message: 'Invalid training type' });
}



// Fetch users with the specified batch and role 'user'
const users = await SignUp.find({
'userInfo.batch': batch,
role: 'user'
}).select(`crn email ${trainingType} userInfo`);
let users;
if (trainingType === 'all') {
users = await SignUp.find({
'userInfo.batch': batch,
role: 'user'
}).select(`crn email tr101.certificate tr102.certificate tr103.certificate tr104.certificate placementData userInfo`);
} else {
users = await SignUp.find({
'userInfo.batch': batch,
role: 'user'
}).select(`crn email ${trainingType} userInfo`);
}


// Return the list of users with the specified training type and user data
return res.status(200).json({ success: true, data: users });
Expand All @@ -100,8 +104,6 @@ router.get('/getUsersByBatch', fetchuser, isAdmin, async (req, res) => {
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});


router.get('/getUsersByPreviousBatches', fetchuser, isAdmin, async (req, res) => {
try {
const { years, trainingType } = req.query; // Add trainingType to destructuring
Expand Down Expand Up @@ -136,5 +138,4 @@ router.get('/getUsersByPreviousBatches', fetchuser, isAdmin, async (req, res) =>
}
});


module.exports = router;
23 changes: 14 additions & 9 deletions client/src/Components/ExportCsvData.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import React from 'react';
import { Button, Box } from '@mui/material';
import { mkConfig, generateCsv, download } from 'export-to-csv';
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import { base64toBlob } from '../utils/base64topdf'
const API_URL =
import.meta.env.VITE_ENV === "production"
? import.meta.env.VITE_PROD_BASE_URL
: import.meta.env.VITE_DEV_BASE_URL;

const ExportCsvComponent = ({ data, selectedTraining }) => {
const csvConfig = mkConfig({
fieldSeparator: ',',
Expand Down Expand Up @@ -34,9 +38,10 @@ const ExportCsvComponent = ({ data, selectedTraining }) => {
filteredRow['Project Name'] = trainingData.projectName;
filteredRow['Technology Used'] = trainingData.technology.join(', ');
if (trainingData.certificate) {
const certifiateBlob = base64toBlob(trainingData.certificate);
const certificateUrl = URL.createObjectURL(certifiateBlob);
filteredRow['Training Certificate'] = certificateUrl;
const certifiateUrl = `${API_URL}certificate/${selectedTraining}/${row._id}`;

filteredRow['Training Certificate'] = certifiateUrl;

} else {
filteredRow['Training Certificate'] = '';
}
Expand All @@ -56,8 +61,8 @@ const ExportCsvComponent = ({ data, selectedTraining }) => {

// Convert appointment letter to data URL
if (trainingData.appointmentLetter) {
const appointmentLetterBlob = base64toBlob(trainingData.appointmentLetter);
filteredRow['Appointment Letter'] = URL.createObjectURL(appointmentLetterBlob);
const certificateURL = `${API_URL}certificate/appointmentLetter/${row._id}`;
filteredRow['Appointment Letter'] = certificateURL;

} else {
filteredRow['Appointment Letter'] = '';
Expand All @@ -66,8 +71,8 @@ const ExportCsvComponent = ({ data, selectedTraining }) => {
filteredRow['Higher Study Place'] = trainingData.highStudyplace;
filteredRow['Gate Appeared Status'] = trainingData.gateStatus;
if (trainingData.gateCertificate) {
const gateCertificateBlob = base64toBlob(trainingData.gateCertificate);
filteredRow['Gate Admit Card/ ScoreCard'] = URL.createObjectURL(gateCertificateBlob);
const certificateURL = `${API_URL}certificate/gateCertificate/${row._id}`; // Replace with actual URL
filteredRow['Gate Admit Card/ ScoreCard'] = certificateURL

} else {
filteredRow['Gate Admit Card/ ScoreCard'] = '';
Expand All @@ -81,7 +86,7 @@ const ExportCsvComponent = ({ data, selectedTraining }) => {
}).filter(row => Object.keys(row).length > 0);

const csv = generateCsv(csvConfig)(filteredData);

download(csvConfig)(csv);
};

Expand Down
Loading

0 comments on commit b54f713

Please sign in to comment.