import nodemailer from 'nodemailer' /** * Email the (client-generated) Fulfillment Earnings PDF report as attachment. * * Body: { * toEmail: string (required) * ccEmail?: string * subject?: string * message?: string (plain text, becomes the mail body) * base64: string (required — the pdfmake-generated PDF) * fileName?: string * dateRange?: string (cosmetic — used in default subject) * } */ const isValidEmail = (s: any) => typeof s === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()) const escapeHtml = (s: string) => s .replace(/&/g, '&') .replace(//g, '>') const buildHtml = (message: string, dateRange: string) => { const bodyText = escapeHtml(message || '').replace(/\n/g, '
') return `

Fulfillment Earnings Report${dateRange ? ` — ${escapeHtml(dateRange)}` : ''}

${bodyText || 'Attached you\'ll find the fulfillment earnings report.'}

Sent automatically by LogShip ERP.

` } export default defineEventHandler(async (event) => { try { const body = await readBody(event) const toEmail = String(body.toEmail || '').trim() const ccEmail = body.ccEmail ? String(body.ccEmail).trim() : '' const base64 = String(body.base64 || '') const dateRange = String(body.dateRange || '').trim() if (!isValidEmail(toEmail)) { return { status: 400, message: 'A valid recipient email is required' } } if (ccEmail && !isValidEmail(ccEmail)) { return { status: 400, message: 'CC email is not valid' } } if (!base64) { return { status: 400, message: 'No PDF provided' } } const fileName = String(body.fileName || '').trim() || 'fulfillment-earnings-report.pdf' const subject = String(body.subject || '').trim() || `Fulfillment Earnings Report${dateRange ? ` — ${dateRange}` : ''}` const transporter = nodemailer.createTransport({ host: 'localhost', port: 25, secure: false, tls: { rejectUnauthorized: false } }) const emailOptions: any = { from: 'no-reply@logyou.de', to: toEmail, subject, html: buildHtml(String(body.message || ''), dateRange), attachments: [{ filename: fileName, content: Buffer.from(base64, 'base64'), contentType: 'application/pdf' }] } if (ccEmail) emailOptions.cc = ccEmail try { const info = await transporter.sendMail(emailOptions) return { status: 200, message: 'Report email sent', messageId: info?.messageId } } catch (err: any) { console.error('[Earnings Report Email] Send error:', err) return { status: 500, message: `Failed to send email: ${err.message || err}` } } } catch (err: any) { console.error('[Earnings Report Email] Error:', err) return { status: 500, message: err.message || 'Failed to send report email' } } })