import { getDocumesoDocument, checkDocumentSignatureStatus, formatRecipientName } from '~/server/utils/documeso'; import { getInterestById } from '~/server/utils/nocodb'; import { sendEmail } from '~/server/utils/email'; interface ReminderEmail { to: string; subject: string; html: string; } export default defineEventHandler(async (event) => { const xTagHeader = getRequestHeader(event, "x-tag"); if (!xTagHeader || (xTagHeader !== "094ut234" && xTagHeader !== "pjnvü1230")) { throw createError({ statusCode: 401, statusMessage: "unauthenticated" }); } try { const body = await readBody(event); const { interestId, documentId } = body; if (!interestId || !documentId) { throw createError({ statusCode: 400, statusMessage: 'Interest ID and Document ID are required', }); } // Get interest details const interest = await getInterestById(interestId); if (!interest) { throw createError({ statusCode: 404, statusMessage: 'Interest not found', }); } // Check if reminders are enabled for this interest // For now, we'll assume they're always enabled unless explicitly disabled const remindersEnabled = (interest as any)['reminder_enabled'] !== false; if (!remindersEnabled) { return { success: false, message: 'Reminders are disabled for this interest' }; } // Get document and check signature status const document = await getDocumesoDocument(parseInt(documentId)); const status = await checkDocumentSignatureStatus(parseInt(documentId)); const emailsToSend: ReminderEmail[] = []; const currentHour = new Date().getHours(); // Determine if we should send reminders based on time const shouldSendMorningReminder = currentHour === 9; const shouldSendAfternoonReminder = currentHour === 16; if (!shouldSendMorningReminder && !shouldSendAfternoonReminder) { return { success: false, message: 'Reminders are only sent at 9am and 4pm' }; } // If client hasn't signed, send reminder to sales (4pm only) if (!status.clientSigned && shouldSendAfternoonReminder) { const salesEmail = generateSalesReminderEmail(interest, document); emailsToSend.push(salesEmail); } // If client has signed but others haven't, send reminders to them if (status.clientSigned && !status.allSigned) { for (const recipient of status.unsignedRecipients) { if (recipient.signingOrder > 1) { // Skip client const reminderEmail = generateRecipientReminderEmail( recipient, interest['Full Name'] || 'Client', recipient.signingUrl ); emailsToSend.push(reminderEmail); } } } // Send all emails const results = []; for (const email of emailsToSend) { try { await sendReminderEmail(email); results.push({ to: email.to, success: true }); } catch (error) { console.error(`Failed to send reminder to ${email.to}:`, error); results.push({ to: email.to, success: false, error: error instanceof Error ? error.message : String(error) }); } } // Update last reminder sent timestamp await $fetch('/api/update-interest', { method: 'POST', headers: { 'x-tag': xTagHeader, }, body: { id: interestId, data: { 'last_reminder_sent': new Date().toISOString() } } }); return { success: true, remindersSent: results.length, results }; } catch (error: any) { console.error('Failed to send reminders:', error); throw createError({ statusCode: error.statusCode || 500, statusMessage: error.statusMessage || 'Failed to send reminders', }); } }); function generateRecipientReminderEmail( recipient: any, clientName: string, signUrl: string ): ReminderEmail { const recipientFirst = formatRecipientName(recipient); const clientFormatted = clientName; const html = ` Port Nimara EOI Signature Request
Port Nimara Logo

Dear ${recipientFirst},

There is an EOI from ${clientFormatted} waiting to be signed. Please click the button below to review and sign the document. If you need any assistance, please reach out to the sales team.

Sign Your EOI

Thank you,
- The Port Nimara CRM

`; // For testing, send to matt@portnimara.com return { to: 'matt@portnimara.com', // TODO: Change to recipient.email after testing subject: `EOI Signature Reminder - ${clientName}`, html }; } function generateSalesReminderEmail(interest: any, document: any): ReminderEmail { const clientName = interest['Full Name'] || 'Client'; const html = ` Port Nimara EOI Signature Reminder
Port Nimara Logo

Dear Sales Team,

The EOI for ${clientName} has not been signed by the client yet. Please follow up with them to ensure the document is signed. Document: ${document.title}

Thank you,
- The Port Nimara CRM

`; return { to: 'sales@portnimara.com', subject: `Action Required: EOI Not Signed - ${clientName}`, html }; } async function sendReminderEmail(email: ReminderEmail) { // Use noreply@portnimara.com credentials with correct mail server const credentials = { host: 'mail.portnimara.com', port: 465, secure: true, auth: { user: 'noreply@portnimara.com', pass: 'sJw6GW5G5bCI1EtBIq3J2hVm8xCOMw1kQs1puS6g0yABqkrwj' } }; // Send email using the existing email utility await sendEmail({ from: 'Port Nimara CRM ', to: email.to, subject: email.subject, html: email.html }, credentials); }