Rewrite testing

This commit is contained in:
Skylar Grant 2024-09-12 13:39:49 -04:00
parent 0c39826505
commit 73db7c0e65
2 changed files with 171 additions and 231 deletions

View File

@ -12,43 +12,92 @@ app.use(express.json());
// Print credentials // Print credentials
app.post('/print-credentials', async (req, res) => { app.post('/print-credentials', async (req, res) => {
try { try {
const { username, studentId } = req.body; const { username, studentId } = req.body;
if (!username || !studentId) { if (!username || !studentId) {
return res.status(400).json({ message: 'Username and Student ID are required.' }); return res.status(400).json({ message: 'Username and Student ID are required.' });
} }
await Thermal.printCredentials(username, studentId, req, res); // Generate the information string
} catch (error) { const infoString = Thermal.generateInfo.credentials(username, studentId);
console.error('Print Error:', error);
res.status(500).json({ message: 'Print Error', error: error.message }); // Generate the PDF, saved to disk
} Thermal.generatePdf(infoString).then(res => {
// Print the document
Thermal.print().then(res => {
res.send('PDF sent to printer successfully.');
}).catch(e => {
console.error('Failed to start printing process:', err);
res.status(500).json({ message: 'Failed to start printing process', error: err.message });
});
}).catch(e => {
console.error(e);
res.status(500).json({ message: 'Error writing PDF file', error: err.message });
});
} catch (error) {
console.error('Print Error:', error);
res.status(500).json({ message: 'Print Error', error: error.message });
}
}); });
// Print temp password // Print temp password
app.post('/print-temp-pw', async (req, res) => { app.post('/print-temp-pw', async (req, res) => {
try { try {
const { password } = req.body; // Grab the password from the request body
if (!password) { const { password } = req.body;
return res.status(400).json({ message: 'Password is required.' });
} // Check that the password is actually there
await Thermal.printTempPassword(password, req, res); if (!password) {
} catch (error) { return res.status(400).json({ message: 'Password is required.' });
console.error('Print Error:', error); }
res.status(500).json({ message: 'Print Error', error: error.message });
} // Generate the information string
const infoString = Thermal.generateInfo.tempPassword(password);
// Generate the PDF, saved to disk
Thermal.generatePdf(infoString).then(res => {
// Print the document
Thermal.print().then(res => {
res.send('PDF sent to printer successfully.');
}).catch(e => {
console.error('Failed to start printing process:', err);
res.status(500).json({ message: 'Failed to start printing process', error: err.message });
});
}).catch(e => {
console.error(e);
res.status(500).json({ message: 'Error writing PDF file', error: err.message });
});
} catch (error) {
console.error('Print Error:', error);
res.status(500).json({ message: 'Print Error', error: error.message });
}
}); });
// Print Student MaineCC Info // Print Student MaineCC Info
app.post('/print-mcc', async (req, res) => { app.post('/print-mcc', async (req, res) => {
try { try {
await Thermal.printStudentMaineCC(req, res); // Generate the information string
} catch (error) { const infoString = Thermal.generateInfo.maineCC();
console.error('Print Error:', error);
res.status(500).json({ message: 'Print Error', error: error.message }); // Generate the PDF, saved to disk
} Thermal.generatePdf(infoString).then(res => {
// Print the document
Thermal.print().then(res => {
res.send('PDF sent to printer successfully.');
}).catch(e => {
console.error('Failed to start printing process:', err);
res.status(500).json({ message: 'Failed to start printing process', error: err.message });
});
}).catch(e => {
console.error(e);
res.status(500).json({ message: 'Error writing PDF file', error: err.message });
});
} catch (error) {
console.error('Print Error:', error);
res.status(500).json({ message: 'Print Error', error: error.message });
}
}); });
// Start the server // Start the server
app.listen(port, () => { app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`); console.log(`Server running at http://localhost:${port}`);
}); });

View File

@ -19,222 +19,113 @@ const mccContractor = {
}; };
module.exports = { module.exports = {
printCredentials(username, studentId, req, res) { generateInfo: {
// Create the output text credentials(username, studentId) {
const infoArray = [ // Create the output text
`Username: ${username}`, const infoArray = [
'', `Username: ${username}`,
'Email:', '',
`${username}@kvcc.me.edu`, 'Email:',
'', `${username}@kvcc.me.edu`,
`Student ID: ${studentId}`, '',
'', `Student ID: ${studentId}`,
'Note: the MyKV Portal uses your username to sign in, not email.', '',
receiptFooter 'Note: the MyKV Portal uses your username to sign in, not email.',
]; receiptFooter
const infoString = infoArray.join('\n'); ];
return infoArray.join('\n');
// Define the path for the PDF file },
const pdfFilePath = path.join(__dirname, 'output.pdf'); maineCC() {
// Create the output text
// Create a new PDF document const infoArray = [
const doc = new PDFDocument({ 'Kennebec Valley Community College is migrating email domains from @kvcc.me.edu to @mainecc.edu.\n',
size: [204, 400], `For support with this transition, please contact:\n${mccContractor.name}`,
margin: 5 `${mccContractor.phone}`,
}); `${mccContractor.email}`,
`${mccContractor.site}\n`,
// Create a writable stream to save the PDF to a file receiptFooter
const writeStream = fs.createWriteStream(pdfFilePath); ];
doc.pipe(writeStream); return infoArray.join('\n');
},
// Add content (image, text) to the PDF tempPassword(password) {
doc.image('./public/itslogo.jpg', { // Create the output text
fit: [196, 100], const infoArray = [
align: 'center', 'We have changed your password to a temporary password, shown below. Next time you log into Microsoft you will be prompted to change your password.\n',
valign: 'top', 'Password requirements:\n8+ characters\n1+ Uppercase\n1+ Lowercase\n1+ Special (!/_=.,?)\n',
}); 'Temporary Password:',
`${password}\n`,
doc.moveDown(); receiptFooter
doc.moveDown(); ];
doc.moveDown(); return infoArray.join('\n');
doc.moveDown(); }
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.fontSize(12).text(infoString, {
align: 'left',
});
// Finalize the PDF
doc.end();
writeStream.on('finish', () => {
// PDF file has been saved, now print it using lp command
const printer = spawn('lp', ['-d', 'ITThermal', pdfFilePath]); // Replace 'ITThermal' with your actual printer name
// Handle error if the printing process fails
printer.on('error', (err) => {
console.error('Failed to start printing process:', err);
res.status(500).json({ message: 'Failed to start printing process', error: err.message });
});
// Handle the process exit event
printer.on('close', (code) => {
if (code === 0) {
res.send('PDF sent to printer successfully.');
} else {
res.status(500).json({ message: 'Failed to print PDF' });
}
});
});
// Handle any errors during file writing
writeStream.on('error', (err) => {
console.error('Error writing PDF file:', err);
res.status(500).json({ message: 'Error writing PDF file', error: err.message });
});
}, },
printStudentMaineCC(req, res) { generatePdf(infoString) {
// Create the output text return new Promise((resolve, reject) => {
const infoArray = [ // Define the path for the PDF file
'Kennebec Valley Community College is migrating email domains from @kvcc.me.edu to @mainecc.edu.\n', const pdfFilePath = path.join(__dirname, 'output.pdf');
`For support with this transition, please contact:\n${mccContractor.name}`,
`${mccContractor.phone}`,
`${mccContractor.email}`,
`${mccContractor.site}\n`,
receiptFooter
];
const infoString = infoArray.join('\n');
// Define the path for the PDF file // Create a new PDF document
const pdfFilePath = path.join(__dirname, 'output.pdf'); const doc = new PDFDocument({
size: [204, 400],
margin: 5
});
// Create a new PDF document // Create a writable stream to save the PDF to a file
const doc = new PDFDocument({ const writeStream = fs.createWriteStream(pdfFilePath);
size: [204, 400], doc.pipe(writeStream);
margin: 5
});
// Create a writable stream to save the PDF to a file // Add content (image, text) to the PDF
const writeStream = fs.createWriteStream(pdfFilePath); doc.image('./public/itslogo.jpg', {
doc.pipe(writeStream); fit: [196, 100],
align: 'center',
valign: 'top',
});
// Add content (image, text) to the PDF // Move down below the Logo/Banner image
doc.image('./public/itslogo.jpg', { doc.moveDown();
fit: [196, 100], doc.moveDown();
align: 'center', doc.moveDown();
valign: 'top', doc.moveDown();
}); doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown(); // Write the text from infoString
doc.moveDown(); doc.fontSize(12).text(infoString, {
doc.moveDown(); align: 'left',
doc.moveDown(); });
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.fontSize(12).text(infoString, {
align: 'left',
});
// Finalize the PDF // Finalize the PDF
doc.end(); doc.end();
writeStream.on('finish', () => { writeStream.on('finish', () => {
// PDF file has been saved, now print it using lp command resolve();
});
// Handle any errors during file writing
writeStream.on('error', (err) => {
reject(err);
});
})
},
print() {
return new Promise((resolve, reject) => {
// Start the print command
const printer = spawn('lp', ['-d', 'ITThermal', pdfFilePath]); const printer = spawn('lp', ['-d', 'ITThermal', pdfFilePath]);
// Handle error if the printing process fails // Handle error if the printing process fails
printer.on('error', (err) => { printer.on('error', (err) => {
console.error('Failed to start printing process:', err); reject(err);
res.status(500).json({ message: 'Failed to start printing process', error: err.message });
}); });
// Handle the process exit event // Handle the process exit event
printer.on('close', (code) => { printer.on('close', (code) => {
if (code === 0) { if (code === 0) {
res.send('PDF sent to printer successfully.'); resolve()
} else { } else {
res.status(500).json({ message: 'Failed to print PDF' }); reject("lp process exited with non-zero result.");
} }
}); });
}); })
// Handle any errors during file writing
writeStream.on('error', (err) => {
console.error('Error writing PDF file:', err);
res.status(500).json({ message: 'Error writing PDF file', error: err.message });
});
},
printTempPassword(password, req, res) {
// Create the output text
const infoArray = [
'We have changed your password to a temporary password, shown below. Next time you log into Microsoft you will be prompted to change your password.\n',
'Password requirements:\n8+ characters\n1+ Uppercase\n1+ Lowercase\n1+ Special (!/_=.,?)\n',
'Temporary Password:',
`${password}\n`,
receiptFooter
];
const infoString = infoArray.join('\n');
// Define the path for the PDF file
const pdfFilePath = path.join(__dirname, 'output.pdf');
// Create a new PDF document
const doc = new PDFDocument({
size: [204, 400],
margin: 5
});
// Create a writable stream to save the PDF to a file
const writeStream = fs.createWriteStream(pdfFilePath);
doc.pipe(writeStream);
// Add content (image, text) to the PDF
doc.image('./public/itslogo.jpg', {
fit: [196, 100],
align: 'center',
valign: 'top',
});
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.fontSize(12).text(infoString, {
align: 'left',
});
// Finalize the PDF
doc.end();
writeStream.on('finish', () => {
// PDF file has been saved, now print it using lp command
const printer = spawn('lp', ['-d', 'ITThermal', pdfFilePath]);
// Handle error if the printing process fails
printer.on('error', (err) => {
console.error('Failed to start printing process:', err);
res.status(500).json({ message: 'Failed to start printing process', error: err.message });
});
// Handle the process exit event
printer.on('close', (code) => {
if (code === 0) {
res.send('PDF sent to printer successfully.');
} else {
res.status(500).json({ message: 'Failed to print PDF' });
}
});
});
// Handle any errors during file writing
writeStream.on('error', (err) => {
console.error('Error writing PDF file:', err);
res.status(500).json({ message: 'Error writing PDF file', error: err.message });
});
} }
} }