Files
operify/app/api/forms/route.js
2025-06-16 15:53:12 +05:30

248 lines
9.0 KiB
JavaScript

import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';
// Email configuration
const emailConfig = {
from_email: process.env.EMAIL_USER || "smukeshsn2000@gmail.com",
from_email_password: process.env.EMAIL_PASS || "swoe hxko uzuc ichj",
from_email_name: process.env.EMAIL_FROM_NAME || "Operify",
to_email: process.env.EMAIL_TO || "smukesh1304@gmail.com",
to_email_name: process.env.EMAIL_TO_NAME || "Mukesh",
};
// Form configurations
const configs = {
contact: {
subject: 'Contact Form Submission',
fields: ['name', 'phone', 'service_interest', 'email', 'Organisation', 'message'],
required: ['name', 'phone', 'service_interest', 'email', 'Organisation', 'message'],
email_fields: ['email'],
successMessage: 'Thank you for your submission. Our team will contact you soon!'
},
career: {
subject: 'Career Application',
fields: ['name', 'phone', 'email', 'Education_Qualification', 'experience', 'Specify_your_interest_in_Genomics', 'message'],
required: ['name', 'phone', 'email', 'Education_Qualification', 'experience', 'Specify_your_interest_in_Genomics', 'message'],
email_fields: ['email'],
file_field: 'resume',
successMessage: 'Thank you for your application. Our team will contact you soon!'
},
sample: {
subject: 'SIF Form received for Project',
fields: [
// Customer Information
'Principal_Investigator', 'Email', 'Company_Institution', 'Contact_Number', 'Address', 'City', 'State', 'Pin',
'Secondary_Contact', 'Secondary_Email', 'Secondary_Company_Institution', 'Secondary_Contact_Number',
// Sample Information
'Project_Title', 'Number_of_Samples', 'Sample_Type', 'Sample_Type_Other', 'Sample_Source', 'Sample_Source_Other',
'Pathogenicity', 'Sample_Remarks',
// Service Information
'Service_Requested', 'Service_Requested_Other', 'Type_of_Library', 'Type_of_Library_Other',
'Required_Library_Size', 'Required_Library_Size_Other', 'Index_Information', 'Kit_Information',
'Sequencing_Platform', 'Sequencing_Platform_Other', 'Sequencing_Read_Length', 'Sequencing_Read_Length_Other',
'Total_Data_Requirement', 'Service_Remarks',
// Bioinformatics Information
'Analysis_Requested', 'Analysis_Details', 'Reference_Genome_Available', 'Genome_Size', 'Special_Consideration'
],
required: [
'Principal_Investigator', 'Email', 'Company_Institution', 'Contact_Number', 'Address', 'City', 'State', 'Pin',
'Project_Title', 'Number_of_Samples', 'Sample_Type', 'Sample_Source', 'Pathogenicity', 'Service_Requested',
'Type_of_Library', 'Required_Library_Size', 'Sequencing_Platform', 'Sequencing_Read_Length',
'Total_Data_Requirement', 'Analysis_Requested', 'Reference_Genome_Available', 'Special_Consideration'
],
email_fields: ['Email', 'Secondary_Email'],
successMessage: 'Thank you for your sample initiation form submission. Our team will contact you soon!'
}
};
// Utility functions
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function fieldName(key) {
return key.replace(/[_-]/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
}
export async function GET() {
return NextResponse.json({
message: 'Forms API is working',
timestamp: new Date().toISOString()
});
}
export async function POST(request) {
try {
// Parse form data
const formData = await request.formData();
const data = {};
const files = {};
for (const [key, value] of formData.entries()) {
if (value instanceof File) {
files[key] = value;
} else {
data[key] = value;
}
}
const form_type = data.form_type;
// Validate form type
if (!form_type || !configs[form_type]) {
return NextResponse.json({
error: 'Invalid form type: ' + (form_type || 'missing')
}, { status: 400 });
}
const config = configs[form_type];
const errors = [];
// Validate required fields
for (const required_field of config.required) {
if (!data[required_field] || String(data[required_field]).trim() === '') {
errors.push(`The "${fieldName(required_field)}" field is required.`);
} else if (config.email_fields.includes(required_field) && !isValidEmail(data[required_field])) {
errors.push(`The "${fieldName(required_field)}" email is not valid.`);
}
}
// Validate file upload for career form
if (form_type === 'career') {
const fileField = config.file_field;
const uploadedFile = files[fileField];
if (!uploadedFile || uploadedFile.size === 0) {
errors.push('Please upload your resume.');
} else {
const allowedExtensions = ['pdf', 'doc', 'docx'];
const fileName = uploadedFile.name.toLowerCase();
const fileExtension = fileName.split('.').pop();
if (!allowedExtensions.includes(fileExtension)) {
errors.push('Invalid file type. Please upload a PDF, DOC, or DOCX file.');
}
if (uploadedFile.size > 10 * 1024 * 1024) { // 10MB limit
errors.push('File is too large. Maximum size is 10MB.');
}
}
}
if (errors.length > 0) {
return NextResponse.json({
error: errors.join(' ')
}, { status: 400 });
}
// Construct email body
let emailBody = `<h2>${config.subject}</h2><table style="border: 1px solid #b5b5b5; padding: 5px;">`;
for (const [key, value] of Object.entries(data)) {
if (config.fields.includes(key) && key !== 'form_type' && key !== 'sample_details') {
emailBody += `<tr>
<td style="border: 1px solid #b5b5b5; padding: 5px;"><strong>${fieldName(key)}</strong></td>
<td style="border: 1px solid #b5b5b5; padding: 5px;">: ${String(value)}</td>
</tr>`;
}
}
// Add file info if uploaded
if (form_type === 'career' && files.resume) {
emailBody += `<tr>
<td style="border: 1px solid #b5b5b5; padding: 5px;"><strong>Resume</strong></td>
<td style="border: 1px solid #b5b5b5; padding: 5px;">: ${files.resume.name} (attached)</td>
</tr>`;
}
// Add sample details for sample form
if (form_type === 'sample' && data.sample_details) {
try {
const sampleDetails = JSON.parse(data.sample_details);
if (sampleDetails && sampleDetails.length > 0) {
emailBody += `<tr>
<td colspan="2" style="border: 1px solid #b5b5b5; padding: 10px; background-color: #e8f5f3; text-align: center;"><strong>SAMPLE DETAILS</strong></td>
</tr>`;
sampleDetails.forEach((sample, index) => {
emailBody += `<tr>
<td colspan="2" style="border: 1px solid #b5b5b5; padding: 8px; background-color: #f0f8f5; font-weight: bold;">Sample ${index + 1}</td>
</tr>`;
Object.entries(sample).forEach(([key, value]) => {
if (value && String(value).trim() !== '') {
emailBody += `<tr>
<td style="border: 1px solid #b5b5b5; padding: 5px; background-color: #f9f9f9;"><strong>${fieldName(key)}</strong></td>
<td style="border: 1px solid #b5b5b5; padding: 5px;">: ${String(value)}</td>
</tr>`;
}
});
});
}
} catch (error) {
console.error('Error parsing sample details:', error);
emailBody += `<tr>
<td colspan="2" style="border: 1px solid #b5b5b5; padding: 5px; color: red;">Error: Could not parse sample details</td>
</tr>`;
}
}
emailBody += '</table>';
// Determine reply-to email based on form type
let replyToEmail;
if (form_type === 'sample') {
replyToEmail = data.Email;
} else {
replyToEmail = data.email;
}
// Create transporter
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: emailConfig.from_email,
pass: emailConfig.from_email_password,
},
});
// Prepare email options
const mailOptions = {
from: `${emailConfig.from_email_name} <${emailConfig.from_email}>`,
to: `${emailConfig.to_email_name} <${emailConfig.to_email}>`,
replyTo: replyToEmail || emailConfig.from_email,
subject: config.subject,
html: emailBody,
text: emailBody.replace(/<[^>]*>/g, ''), // Strip HTML for text version
};
// Add attachment for career form
if (form_type === 'career' && files.resume) {
const fileBuffer = await files.resume.arrayBuffer();
mailOptions.attachments = [{
filename: files.resume.name,
content: Buffer.from(fileBuffer),
}];
}
// Send email
await transporter.sendMail(mailOptions);
return NextResponse.json({
success: true,
message: config.successMessage
});
} catch (error) {
console.error('Email sending error:', error);
return NextResponse.json({
error: 'Error sending email. Please try again later.'
}, { status: 500 });
}
}