mjml EMail

This commit is contained in:
Andreas Knuth 2026-03-16 18:00:32 -05:00
parent b9f9df74c0
commit 5a7ba66c27
9 changed files with 3248 additions and 24 deletions

View File

@ -39,6 +39,8 @@ services:
QBO_REALM_ID: ${QBO_REALM_ID} QBO_REALM_ID: ${QBO_REALM_ID}
QBO_ACCESS_TOKEN: ${QBO_ACCESS_TOKEN} QBO_ACCESS_TOKEN: ${QBO_ACCESS_TOKEN}
QBO_REFRESH_TOKEN: ${QBO_REFRESH_TOKEN} QBO_REFRESH_TOKEN: ${QBO_REFRESH_TOKEN}
AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID}
AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY}
volumes: volumes:
- ./public/uploads:/app/public/uploads - ./public/uploads:/app/public/uploads
- ./templates:/app/templates # NEU! - ./templates:/app/templates # NEU!

2845
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -8,11 +8,14 @@
"dev": "nodemon src/index.js" "dev": "nodemon src/index.js"
}, },
"dependencies": { "dependencies": {
"@aws-sdk/client-sesv2": "^3.1009.0",
"csv-parser": "^3.2.0", "csv-parser": "^3.2.0",
"dotenv": "^17.3.1", "dotenv": "^17.3.1",
"express": "^4.21.2", "express": "^4.21.2",
"intuit-oauth": "^4.2.2", "intuit-oauth": "^4.2.2",
"mjml": "^4.18.0",
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.1",
"nodemailer": "^8.0.2",
"pg": "^8.13.1", "pg": "^8.13.1",
"puppeteer": "^23.11.1" "puppeteer": "^23.11.1"
}, },

View File

@ -22,6 +22,7 @@ import { checkCurrentLogo, initSettingsView } from './views/settings-view.js';
import { initQuoteModal } from './modals/quote-modal.js'; import { initQuoteModal } from './modals/quote-modal.js';
import { initInvoiceModal, loadLaborRate } from './modals/invoice-modal.js'; import { initInvoiceModal, loadLaborRate } from './modals/invoice-modal.js';
import './modals/payment-modal.js'; import './modals/payment-modal.js';
import './modals/email-modal.js';
import { setDefaultDate } from './utils/helpers.js'; import { setDefaultDate } from './utils/helpers.js';
// ============================================================ // ============================================================

View File

@ -0,0 +1,225 @@
// email-modal.js — ES Module
// Modal to review and send invoice emails via AWS SES
import { showSpinner, hideSpinner } from '../utils/helpers.js';
let currentInvoice = null;
let quillInstance = null;
// ============================================================
// DOM & Render
// ============================================================
function ensureModalElement() {
let modal = document.getElementById('email-modal');
if (!modal) {
modal = document.createElement('div');
modal.id = 'email-modal';
modal.className = 'modal fixed inset-0 bg-black bg-opacity-50 z-50 justify-center items-start pt-10 overflow-y-auto hidden';
document.body.appendChild(modal);
}
}
function renderModalContent() {
const modal = document.getElementById('email-modal');
if (!modal) return;
const defaultEmail = currentInvoice.email || '';
// Editor-Container hat jetzt eine feste, kompaktere Höhe (h-48 = 12rem/192px) und scrollt bei viel Text
modal.innerHTML = `
<div class="bg-white rounded-lg shadow-2xl w-full max-w-3xl mx-auto p-8">
<div class="flex justify-between items-center mb-6">
<h2 class="text-2xl font-bold text-gray-800">📤 Send Invoice #${currentInvoice.invoice_number || currentInvoice.id}</h2>
<button onclick="window.emailModal.close()" class="text-gray-400 hover:text-gray-600">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<form id="email-send-form" class="space-y-5">
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Recipient Email *</label>
<input type="email" id="email-recipient" value="${defaultEmail}" required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
<p class="text-xs text-gray-400 mt-1">You can override this for testing.</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Melio Payment Link (Optional)</label>
<input type="url" id="email-melio-link" placeholder="https://melio.me/..."
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Message Body</label>
<div id="email-message-editor" class="border border-gray-300 rounded-md bg-white h-48 overflow-y-auto"></div>
</div>
<div class="bg-blue-50 border border-blue-200 p-4 rounded-md flex items-center gap-3">
<span class="text-2xl">📎</span>
<div class="text-sm text-blue-800">
<strong>Invoice_${currentInvoice.invoice_number || currentInvoice.id}.pdf</strong> will be generated and attached automatically.
</div>
</div>
<div class="flex justify-end space-x-3 pt-4">
<button type="button" onclick="window.emailModal.close()"
class="px-6 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300">Cancel</button>
<button type="submit" id="email-submit-btn"
class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 font-semibold">
Send via AWS SES
</button>
</div>
</form>
</div>`;
// Initialize Quill
const editorDiv = document.getElementById('email-message-editor');
quillInstance = new Quill(editorDiv, {
theme: 'snow',
modules: {
toolbar: [
['bold', 'italic', 'underline'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
['clean']
]
}
});
// Variablen für den Text aufbereiten
const invoiceNum = currentInvoice.invoice_number || currentInvoice.id;
const totalDue = parseFloat(currentInvoice.balance ?? currentInvoice.total).toFixed(2);
// Datum formatieren
let dueDateStr = 'Upon Receipt';
if (currentInvoice.due_date) {
const d = new Date(currentInvoice.due_date);
dueDateStr = d.toLocaleDateString('en-US', { timeZone: 'UTC' });
}
// Dynamischer Text für die Fälligkeit (Löst das "payable by Upon Receipt" Problem)
let paymentText = '';
if (currentInvoice.terms && currentInvoice.terms.toLowerCase().includes('receipt')) {
paymentText = 'which is due upon receipt.';
} else if (dueDateStr !== 'Upon Receipt') {
paymentText = `payable by <strong>${dueDateStr}</strong>.`;
} else {
paymentText = 'which is due upon receipt.';
}
// Der neue Standard-Text
const defaultHtml = `
<p>Good afternoon,</p>
<p>Attached is invoice <strong>#${invoiceNum}</strong> for service performed at your location. The total amount due is <strong>$${totalDue}</strong>, ${paymentText}</p>
<p>Please pay at your earliest convenience. We appreciate your continued business.</p>
<p>If you have any questions about the invoice, feel free to reply to this email.</p>
<p>Best regards,</p>
<p><strong>Claudia Knuth</strong></p>
<p>Bay Area Affiliates, Inc.</p>
<p>accounting@bayarea-cc.com</p>
`;
quillInstance.root.innerHTML = defaultHtml;
// Bind Submit Handler
document.getElementById('email-send-form').addEventListener('submit', submitEmail);
}
// ============================================================
// Logic & API
// ============================================================
export async function openEmailModal(invoiceId) {
ensureModalElement();
if (typeof showSpinner === 'function') showSpinner('Loading invoice data...');
try {
const res = await fetch(`/api/invoices/${invoiceId}`);
const data = await res.json();
if (!data.invoice) throw new Error('Invoice not found');
currentInvoice = data.invoice;
renderModalContent();
// Tailwind hidden toggle
document.getElementById('email-modal').classList.remove('hidden');
document.getElementById('email-modal').classList.add('flex');
} catch (e) {
console.error('Error loading invoice for email:', e);
alert('Could not load invoice details.');
} finally {
if (typeof hideSpinner === 'function') hideSpinner();
}
}
export function closeEmailModal() {
const modal = document.getElementById('email-modal');
if (modal) {
modal.classList.add('hidden');
modal.classList.remove('flex');
}
currentInvoice = null;
quillInstance = null;
}
async function submitEmail(e) {
e.preventDefault();
const recipientEmail = document.getElementById('email-recipient').value.trim();
const melioLink = document.getElementById('email-melio-link').value.trim();
const customText = quillInstance.root.innerHTML;
if (!recipientEmail) {
alert('Please enter a recipient email.');
return;
}
const submitBtn = document.getElementById('email-submit-btn');
submitBtn.innerHTML = '⏳ Sending...';
submitBtn.disabled = true;
if (typeof showSpinner === 'function') showSpinner('Generating PDF and sending email...');
try {
const response = await fetch(`/api/invoices/${currentInvoice.id}/send-email`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
recipientEmail,
melioLink,
customText
})
});
const result = await response.json();
if (response.ok) {
alert('✅ Invoice sent successfully!');
closeEmailModal();
// Reload the invoice view so the "Sent" badge updates
if (window.invoiceView) window.invoiceView.loadInvoices();
} else {
alert(`❌ Error: ${result.error}`);
}
} catch (e) {
console.error('Send email error:', e);
alert('Network error while sending email.');
} finally {
submitBtn.innerHTML = 'Send via AWS SES';
submitBtn.disabled = false;
if (typeof hideSpinner === 'function') hideSpinner();
}
}
// ============================================================
// Expose
// ============================================================
window.emailModal = {
open: openEmailModal,
close: closeEmailModal
};

View File

@ -258,10 +258,18 @@ function renderInvoiceRow(invoice) {
// Mark Sent button (right side) — only when open, not paid/partial // Mark Sent button (right side) — only when open, not paid/partial
let sendBtn = ''; let sendBtn = '';
if (hasQbo && !paid && !overdue && invoice.email_status !== 'sent') { // if (hasQbo && !paid && !overdue && invoice.email_status !== 'sent') {
sendBtn = `<button onclick="window.invoiceView.setEmailStatus(${invoice.id}, 'sent')" class="text-indigo-600 hover:text-indigo-800 text-xs font-medium" title="Mark as sent to customer">📤 Mark Sent</button>`; // sendBtn = `<button onclick="window.invoiceView.setEmailStatus(${invoice.id}, 'sent')" class="text-indigo-600 hover:text-indigo-800 text-xs font-medium" title="Mark as sent to customer">📤 Mark Sent</button>`;
} // }
if (hasQbo && !paid && !overdue) {
sendBtn = `
<button onclick="window.invoiceView.setEmailStatus(${invoice.id}, 'sent')" class="text-gray-600 hover:text-gray-900 text-xs font-medium mr-4" title="Nur Status ändern">
Mark Sent
</button>
<button onclick="window.emailModal.open(${invoice.id})" class="text-indigo-600 hover:text-indigo-800 text-xs font-medium" title="E-Mail via SES versenden">
📧 Send Email
</button>
`; }
const delBtn = `<button onclick="window.invoiceView.remove(${invoice.id})" class="text-red-600 hover:text-red-900">Del</button>`; const delBtn = `<button onclick="window.invoiceView.remove(${invoice.id})" class="text-red-600 hover:text-red-900">Del</button>`;
const rowClass = paid ? (invoice.payment_status === 'Deposited' ? 'bg-blue-50/50' : 'bg-green-50/50') : partial ? 'bg-yellow-50/30' : overdue ? 'bg-red-50/50' : ''; const rowClass = paid ? (invoice.payment_status === 'Deposited' ? 'bg-blue-50/50' : 'bg-green-50/50') : partial ? 'bg-yellow-50/30' : overdue ? 'bg-red-50/50' : '';

View File

@ -12,6 +12,7 @@ const { formatDate, formatMoney } = require('../utils/helpers');
const { getBrowser, generatePdfFromHtml, getLogoHtml, renderInvoiceItems, formatAddressLines } = require('../services/pdf-service'); const { getBrowser, generatePdfFromHtml, getLogoHtml, renderInvoiceItems, formatAddressLines } = require('../services/pdf-service');
const { exportInvoiceToQbo, syncInvoiceToQbo } = require('../services/qbo-service'); const { exportInvoiceToQbo, syncInvoiceToQbo } = require('../services/qbo-service');
const { getOAuthClient, getQboBaseUrl, makeQboApiCall } = require('../config/qbo'); const { getOAuthClient, getQboBaseUrl, makeQboApiCall } = require('../config/qbo');
const { sendInvoiceEmail } = require('../services/email-service');
function calculateNextRecurringDate(invoiceDate, interval) { function calculateNextRecurringDate(invoiceDate, interval) {
const d = new Date(invoiceDate); const d = new Date(invoiceDate);
@ -816,5 +817,65 @@ router.get('/:id/html', async (req, res) => {
res.status(500).json({ error: 'Error generating HTML' }); res.status(500).json({ error: 'Error generating HTML' });
} }
}); });
router.post('/:id/send-email', async (req, res) => {
const { id } = req.params;
const { recipientEmail, customText, melioLink } = req.body;
if (!recipientEmail) {
return res.status(400).json({ error: 'Recipient email is required.' });
}
try {
// 1. Rechnungsdaten und Items laden (analog zu deiner PDF-Route)
const invoiceResult = await pool.query(`
SELECT i.*, c.name as customer_name, c.line1, c.line2, c.line3, c.line4, c.city, c.state, c.zip_code, c.account_number,
COALESCE((SELECT SUM(pi.amount) FROM payment_invoices pi WHERE pi.invoice_id = i.id), 0) as amount_paid
FROM invoices i
LEFT JOIN customers c ON i.customer_id = c.id
WHERE i.id = $1
`, [id]);
if (invoiceResult.rows.length === 0) return res.status(404).json({ error: 'Invoice not found' });
const invoice = invoiceResult.rows[0];
const itemsResult = await pool.query('SELECT * FROM invoice_items WHERE invoice_id = $1 ORDER BY item_order', [id]);
// 2. PDF generieren, aber nur im Speicher halten
const templatePath = path.join(__dirname, '..', '..', 'templates', 'invoice-template.html');
let html = await fs.readFile(templatePath, 'utf-8');
const logoHTML = await getLogoHtml();
const itemsHTML = renderInvoiceItems(itemsResult.rows, invoice);
const authHTML = invoice.auth_code ? `<p style="margin-bottom: 20px; font-size: 13px;"><strong>Authorization:</strong> ${invoice.auth_code}</p>` : '';
const streetBlock = formatAddressLines(invoice.line1, invoice.line2, invoice.line3, invoice.line4, invoice.customer_name);
html = html
.replace('{{LOGO_HTML}}', logoHTML)
.replace('{{CUSTOMER_NAME}}', invoice.bill_to_name || invoice.customer_name || '')
.replace('{{CUSTOMER_STREET}}', streetBlock)
.replace('{{CUSTOMER_CITY}}', invoice.city || '')
.replace('{{CUSTOMER_STATE}}', invoice.state || '')
.replace('{{CUSTOMER_ZIP}}', invoice.zip_code || '')
.replace('{{INVOICE_NUMBER}}', invoice.invoice_number || '')
.replace('{{ACCOUNT_NUMBER}}', invoice.account_number || '')
.replace('{{INVOICE_DATE}}', formatDate(invoice.invoice_date))
.replace('{{TERMS}}', invoice.terms)
.replace('{{AUTHORIZATION}}', authHTML)
.replace('{{ITEMS}}', itemsHTML);
const pdfBuffer = await generatePdfFromHtml(html);
// 3. E-Mail über SES versenden
const info = await sendInvoiceEmail(invoice, recipientEmail, customText, melioLink, pdfBuffer);
// 4. (Optional) Status in der DB aktualisieren
//await pool.query('UPDATE invoices SET email_status = $1 WHERE id = $2', ['sent', id]);
res.json({ success: true, messageId: info.messageId });
} catch (error) {
console.error('Error sending invoice email:', error);
res.status(500).json({ error: 'Failed to send email: ' + error.message });
}
});
module.exports = router; module.exports = router;

View File

@ -0,0 +1,112 @@
// src/services/email-service.js
const { SESv2Client, SendEmailCommand } = require('@aws-sdk/client-sesv2');
const nodemailer = require('nodemailer');
const mjml2html = require('mjml');
const sesClient = new SESv2Client({
region: process.env.AWS_REGION || 'us-east-2'
});
const transporter = nodemailer.createTransport({
SES: {
sesClient,
SendEmailCommand
}
});
function generateInvoiceEmailHtml(invoice, customText, melioLink) {
const formattedText = customText || '';
const buttonMjml = melioLink
? `<mj-button background-color="#2563eb" color="white" border-radius="6px" href="${melioLink}" font-weight="600" font-size="16px" padding-top="25px">
Pay Now (Free ACH)
</mj-button>`
: '';
const template = `
<mjml>
<mj-head>
<mj-attributes>
<mj-all font-family="ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif" />
</mj-attributes>
<mj-style inline="inline">
.email-body p {
margin: 0 0 14px 0 !important;
}
.email-body p:last-child {
margin-bottom: 0 !important;
}
</mj-style>
</mj-head>
<mj-body background-color="#f4f4f5">
<mj-section padding="0">
<mj-column>
<mj-spacer height="20px" />
</mj-column>
</mj-section>
<mj-section background-color="#ffffff" padding="30px" border-radius="8px 8px 0 0">
<mj-column>
<mj-text font-size="22px" font-weight="700" color="#1e3a8a" padding="0">
Bay Area Affiliates, Inc.
</mj-text>
<mj-text font-size="15px" color="#64748b" padding="5px 0 0 0">
Invoice #${invoice.invoice_number || invoice.id}
</mj-text>
</mj-column>
</mj-section>
<mj-section background-color="#ffffff" padding="0 30px 30px 30px">
<mj-column>
<mj-text css-class="email-body" font-size="15px" color="#334155" line-height="1.5" padding="0">
${formattedText}
</mj-text>
${buttonMjml}
<mj-divider border-color="#e2e8f0" border-width="1px" padding-top="30px" padding-bottom="20px" />
<mj-text font-size="14px" color="#64748b" line-height="1.5" padding="0">
<strong>Prefer to pay by check?</strong><br/>
Please make checks payable to Bay Area Affiliates, Inc. and mail to:<br/>
1001 Blucher Street<br/>
Corpus Christi, Texas 78401
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
`;
// validationLevel: 'strict' fängt falsche Attribute ab, bevor sie an den Kunden gehen
const result = mjml2html(template, { validationLevel: 'strict' });
if (result.errors && result.errors.length > 0) {
console.error('MJML Parse Errors:', result.errors);
}
return result.html;
}
async function sendInvoiceEmail(invoice, recipientEmail, customText, melioLink, pdfBuffer) {
const htmlContent = generateInvoiceEmailHtml(invoice, customText, melioLink);
const mailOptions = {
from: '"Bay Area Affiliates Inc. Accounting" <accounting@bayarea-cc.com>',
to: recipientEmail,
subject: `Invoice #${invoice.invoice_number || invoice.id} from Bay Area Affiliates, Inc.`,
html: htmlContent,
attachments: [
{
filename: `Invoice_${invoice.invoice_number || invoice.id}_BayAreaAffiliates.pdf`,
content: pdfBuffer,
contentType: 'application/pdf'
}
]
};
return await transporter.sendMail(mailOptions);
}
module.exports = { sendInvoiceEmail };

View File

@ -33,7 +33,8 @@ async function generatePdfFromHtml(html, options = {}) {
} }
const page = await browser.newPage(); const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0', timeout: 60000 }); //await page.setContent(html, { waitUntil: 'networkidle0', timeout: 60000 });
await page.setContent(html, { waitUntil: 'load', timeout: 5000 });
const pdf = await page.pdf({ const pdf = await page.pdf({
format, format,