88 lines
3.0 KiB
JavaScript
88 lines
3.0 KiB
JavaScript
module.exports = (pool, transporter) => {
|
|
const submitForm = async (req, res) => {
|
|
const {
|
|
firstName,
|
|
lastName,
|
|
organization,
|
|
email,
|
|
phone,
|
|
contactMethod,
|
|
message,
|
|
} = req.body;
|
|
|
|
if (
|
|
!firstName || !lastName || !email || !message ||
|
|
typeof contactMethod === 'undefined'
|
|
) {
|
|
console.error('Missing required fields in submission:', req.body);
|
|
return res.status(400).json({ message: 'Missing required form fields.' });
|
|
}
|
|
|
|
try {
|
|
const result = await pool.query(
|
|
`INSERT INTO submissions(
|
|
first_name,
|
|
last_name,
|
|
organization,
|
|
email,
|
|
phone,
|
|
contact_method,
|
|
message,
|
|
time_submitted
|
|
) VALUES($1, $2, $3, $4, $5, $6, $7, $8, NOW())
|
|
RETURNING *`,
|
|
[
|
|
firstName,
|
|
lastName,
|
|
organization,
|
|
email,
|
|
phone,
|
|
contactMethod,
|
|
message,
|
|
]
|
|
);
|
|
|
|
console.log('Successfully saved submission to the database:', result.rows[0]);
|
|
|
|
const mailOptions = {
|
|
from: `"Contact Form" <contact@dlseitz.dev>`,
|
|
to: process.env.EMAIL_RCPT,
|
|
subject: 'New Contact Form Submission',
|
|
html: `
|
|
<h3>New Submission</h3>
|
|
<ul>
|
|
<li><strong>First Name:</strong> ${firstName}</li>
|
|
<li><strong>Last Name:</strong> ${lastName}</li>
|
|
<li><strong>Organization:</strong> ${organization}</li>
|
|
<li><strong>Email:</strong> ${email}</li>
|
|
<li><strong>Phone:</strong> ${phone}</li>
|
|
<li><strong>Contact Method:</strong> ${contactMethod}</li>
|
|
<li><strong>Submission Time:</strong> ${result.rows[0].time_submitted}</li>
|
|
</ul>
|
|
<p><strong>Message:</strong></p>
|
|
<p>${message}</p>
|
|
`,
|
|
};
|
|
|
|
const emailInfo = await transporter.sendMail(mailOptions);
|
|
console.log('Message sent: %s', emailInfo.messageId);
|
|
|
|
res.status(200).json({
|
|
message: 'Form submitted successfully and saved to the database!',
|
|
dataReceived: req.body
|
|
});
|
|
|
|
} catch (err) {
|
|
console.error('Error occurred during form submission:', err.stack || err);
|
|
res.status(500).json({
|
|
message: 'An error occurred while submitting the form.',
|
|
error: err.message || 'Unknown error'
|
|
});
|
|
}
|
|
};
|
|
|
|
return {
|
|
submitForm,
|
|
};
|
|
};
|