added mailing through Brevo and node mailer, also a email editor, with

their custom blocks and renderers
This commit is contained in:
Jakub Dorfman 2026-09-28 19:25:19 +02:00
parent 43db707e34
commit 96828994e1
34 changed files with 2035 additions and 323 deletions

View file

@ -0,0 +1,69 @@
// Minimal RFC 5545 calendar file for booking confirmations.
// METHOD:PUBLISH (not REQUEST) so mail clients offer "Add to calendar"
// rather than treating it as a meeting invite that expects an RSVP.
export type IcsEvent = {
uid: string;
start: string; // ISO
end: string; // ISO
summary: string;
description?: string;
location?: string;
url?: string;
};
function formatUtc(iso: string): string {
return new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
}
function escapeText(value: string): string {
return value.replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,').replace(/\r?\n/g, '\\n');
}
/** Fold lines to 75 octets as the spec requires (continuations start with a space). */
function fold(line: string): string {
const encoder = new TextEncoder();
const parts: string[] = [];
let current = '';
let bytes = 0;
for (const char of line) {
const size = encoder.encode(char).length;
const limit = parts.length === 0 ? 75 : 74;
if (bytes + size > limit) {
parts.push(current);
current = '';
bytes = 0;
}
current += char;
bytes += size;
}
parts.push(current);
return parts.join('\r\n ');
}
export function buildIcs(events: IcsEvent[], productName: string): string {
const stamp = formatUtc(new Date().toISOString());
const lines = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
`PRODID:-//${escapeText(productName)}//Booking//EN`,
'CALSCALE:GREGORIAN',
'METHOD:PUBLISH'
];
for (const event of events) {
lines.push(
'BEGIN:VEVENT',
`UID:${event.uid}`,
`DTSTAMP:${stamp}`,
`DTSTART:${formatUtc(event.start)}`,
`DTEND:${formatUtc(event.end)}`,
`SUMMARY:${escapeText(event.summary)}`
);
if (event.description) lines.push(`DESCRIPTION:${escapeText(event.description)}`);
if (event.location) lines.push(`LOCATION:${escapeText(event.location)}`);
if (event.url) lines.push(`URL:${event.url}`);
lines.push('STATUS:CONFIRMED', 'END:VEVENT');
}
lines.push('END:VCALENDAR');
return lines.map(fold).join('\r\n') + '\r\n';
}

View file

@ -0,0 +1,236 @@
import type PocketBase from 'pocketbase';
import { env } from '$env/dynamic/private';
import { env as publicEnv } from '$env/dynamic/public';
import {
defaultColors,
defaultFooter,
type ColorsGlobal,
type CustomerDetails,
type EmailTemplate,
type EmailTemplateKey,
type FooterGlobal
} from '../../types';
import { normalizeEmailTemplate } from '../../email/defaults';
import { renderEmail, sampleEmailContext, type EmailContext, type EmailLine } from '../../email/render';
import { buildIcs } from './ics';
import { sendEmail, type SendResult } from './transport';
export { sendEmail, isEmailConfigured, emailSender, type SendResult, type OutgoingEmail } from './transport';
export { buildIcs, type IcsEvent } from './ics';
export type EmailKind = 'customer' | 'client';
const TEMPLATE_KEY: Record<EmailKind, EmailTemplateKey> = {
customer: 'customer_confirmation',
client: 'client_alert'
};
const SENT_AT_FIELD: Record<EmailKind, string> = {
customer: 'customerEmailSentAt',
client: 'clientEmailSentAt'
};
// Prefixes for per-kind lines in orders.emailError, so resending one email
// only replaces that email's error line.
const ERROR_PREFIX: Record<EmailKind, string> = {
customer: 'Customer email',
client: 'Alert email'
};
export type EmailOutcome = 'sent' | 'logged' | 'disabled' | 'failed';
export type EmailSettings = {
business: FooterGlobal;
colors: ColorsGlobal;
siteUrl: string;
timezone: string;
currency: string;
};
async function getGlobalData<T extends object>(pb: PocketBase, key: string, fallback: T): Promise<T> {
try {
const record = await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key }));
return { ...fallback, ...(record.data || {}) };
} catch {
return fallback;
}
}
/** Public site URL — the admin app's ORIGIN is the admin subdomain, so prefer PUBLIC_SITE_URL. */
export function emailSiteUrl(): string {
return (publicEnv.PUBLIC_SITE_URL || env.ORIGIN || '').replace(/\/$/, '');
}
export async function loadEmailSettings(pb: PocketBase): Promise<EmailSettings> {
const [business, colors] = await Promise.all([
getGlobalData(pb, 'footer', defaultFooter),
getGlobalData(pb, 'colors', defaultColors)
]);
return {
business,
colors,
siteUrl: emailSiteUrl(),
timezone: env.SITE_TIMEZONE || 'Europe/Oslo',
currency: env.STRIPE_CURRENCY || 'eur'
};
}
/** The saved template for `key`, or the built-in default if none was saved (or the collection is missing). */
export async function loadEmailTemplate(pb: PocketBase, key: EmailTemplateKey): Promise<EmailTemplate & { id?: string }> {
const record = await pb
.collection('email_templates')
.getFirstListItem(pb.filter('key = {:key}', { key }))
.catch(() => null);
return { ...normalizeEmailTemplate(key, record), id: record?.id };
}
function bookingIcs(ctx: EmailContext, lineIds: string[], settings: EmailSettings): string | null {
const host = settings.siteUrl.replace(/^https?:\/\//, '').replace(/[:/].*$/, '') || 'localhost';
const events = ctx.lines.flatMap((line, i) =>
line.start
? [
{
uid: `${ctx.orderId}-${lineIds[i] ?? i}@${host}`,
start: line.start,
end: line.end || new Date(new Date(line.start).getTime() + 60 * 60_000).toISOString(),
summary: `${line.name} – ${settings.business.businessName}`.replace(/ – $/, ''),
description: `Booking reference: ${ctx.orderId}`,
location: (settings.business.address || '').replace(/\n/g, ', '),
url: settings.siteUrl || undefined
}
]
: []
);
return events.length ? buildIcs(events, settings.business.businessName || 'Booking') : null;
}
async function loadOrderContext(pb: PocketBase, orderId: string, settings: EmailSettings) {
const order = await pb.collection('orders').getOne(orderId);
const lineRecords = await pb
.collection('order_lines')
.getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item', sort: 'start' });
const lines: EmailLine[] = lineRecords.map((line) => {
const start = line.start ? new Date(line.start).toISOString() : null;
const slotEnd = line.expand?.slot?.end;
const duration = Number(line.expand?.item?.duration) || 0;
const end = slotEnd
? new Date(slotEnd).toISOString()
: start && duration
? new Date(new Date(start).getTime() + duration * 60_000).toISOString()
: null;
return {
name: String(line.name || 'Item'),
price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1,
start,
end
};
});
const details = (order.customerDetails || {}) as Partial<CustomerDetails>;
const customer: CustomerDetails = {
name: String(details.name || ''),
email: String(details.email || order.email || ''),
phone: String(details.phone || ''),
notes: String(details.notes || '')
};
const ctx: EmailContext = {
orderId: order.id,
total: Number(order.total) || 0,
customer,
lines,
...settings
};
return { order, ctx, lineIds: lineRecords.map((line) => line.id) };
}
/**
* Render and send the booking emails for a paid order, then record the
* outcome on the order (customerEmailSentAt / clientEmailSentAt / emailError).
* Never throws — a failed email must not fail the Stripe webhook; the admin
* can resend from /orders.
*/
export async function sendOrderEmails(
pb: PocketBase,
orderId: string,
kinds: EmailKind[] = ['customer', 'client']
): Promise<Partial<Record<EmailKind, EmailOutcome>>> {
const outcomes: Partial<Record<EmailKind, EmailOutcome>> = {};
try {
const settings = await loadEmailSettings(pb);
const { order, ctx, lineIds } = await loadOrderContext(pb, orderId, settings);
const patch: Record<string, string> = {};
const errorLines = String(order.emailError || '')
.split('\n')
.filter((line) => line && !kinds.some((kind) => line.startsWith(ERROR_PREFIX[kind])));
for (const kind of kinds) {
const template = await loadEmailTemplate(pb, TEMPLATE_KEY[kind]);
if (!template.enabled) {
outcomes[kind] = 'disabled';
continue;
}
try {
const rendered = renderEmail(template, ctx);
const to = kind === 'customer' ? ctx.customer.email : template.recipients.trim() || settings.business.email;
if (!to) {
throw new Error(
kind === 'customer'
? 'the order has no customer email'
: 'no recipient — set one on the email template or add an email to the footer settings'
);
}
const ics = kind === 'customer' ? bookingIcs(ctx, lineIds, settings) : null;
const result = await sendEmail({
to,
...rendered,
replyTo: kind === 'customer' ? settings.business.email || undefined : ctx.customer.email || undefined,
attachments: ics ? [{ filename: 'booking.ics', content: ics, contentType: 'text/calendar; charset=utf-8; method=PUBLISH' }] : undefined
});
outcomes[kind] = result.status;
if (result.status === 'sent') {
patch[SENT_AT_FIELD[kind]] = new Date().toISOString();
} else {
errorLines.push(`${ERROR_PREFIX[kind]}: not sent — SMTP is not configured (written to the server log instead)`);
}
} catch (e) {
outcomes[kind] = 'failed';
const message = e instanceof Error ? e.message : String(e);
errorLines.push(`${ERROR_PREFIX[kind]}: ${message}`);
console.error(`[email] ${kind} email for order ${orderId} failed:`, e);
}
}
patch.emailError = errorLines.join('\n').slice(0, 2000);
await pb
.collection('orders')
.update(orderId, patch)
.catch((e) => console.error(`[email] could not record email status on order ${orderId}:`, e));
} catch (e) {
console.error(`[email] could not prepare emails for order ${orderId}:`, e);
for (const kind of kinds) outcomes[kind] ??= 'failed';
}
return outcomes;
}
/** Render `template` with sample booking data and send it to `to` (admin "Send test email"). */
export async function sendTestEmail(
pb: PocketBase,
template: Pick<EmailTemplate, 'key' | 'subject' | 'blocks'>,
to: string,
service?: { name: string; price: number; duration: number | null }
): Promise<SendResult> {
const settings = await loadEmailSettings(pb);
const ctx = sampleEmailContext({ ...settings, service });
const rendered = renderEmail(template, ctx);
const ics = template.key === 'customer_confirmation' ? bookingIcs(ctx, ['test'], settings) : null;
return sendEmail({
to,
...rendered,
subject: `[Test] ${rendered.subject}`,
attachments: ics ? [{ filename: 'booking.ics', content: ics, contentType: 'text/calendar; charset=utf-8; method=PUBLISH' }] : undefined
});
}

View file

@ -0,0 +1,70 @@
import nodemailer, { type Transporter } from 'nodemailer';
import { env } from '$env/dynamic/private';
export type OutgoingEmail = {
to: string;
subject: string;
html: string;
text: string;
replyTo?: string;
attachments?: { filename: string; content: string; contentType: string }[];
};
// 'logged' = SMTP isn't configured (local dev), so the email was printed to
// the server log instead of being sent.
export type SendResult = { status: 'sent'; messageId: string } | { status: 'logged' };
let transporter: Transporter | null = null;
export function isEmailConfigured(): boolean {
return Boolean(env.SMTP_HOST);
}
export function emailSender(): string {
return env.EMAIL_FROM ? `${env.EMAIL_FROM_NAME || ''} <${env.EMAIL_FROM}>`.trim() : '';
}
function getTransporter(): Transporter {
if (!transporter) {
const port = Number(env.SMTP_PORT) || 587;
transporter = nodemailer.createTransport({
host: env.SMTP_HOST,
port,
// 465 is implicit TLS; 587/2525 upgrade via STARTTLS.
secure: port === 465,
auth: env.SMTP_USER ? { user: env.SMTP_USER, pass: env.SMTP_PASS || '' } : undefined,
// Fail fast — nodemailer's defaults wait up to two minutes.
connectionTimeout: 10_000,
greetingTimeout: 10_000,
socketTimeout: 30_000
});
}
return transporter;
}
/**
* Send one email through the configured SMTP relay (Brevo in production).
* Throws on SMTP errors; callers decide how to record the failure.
*/
export async function sendEmail(email: OutgoingEmail): Promise<SendResult> {
if (!isEmailConfigured()) {
console.info(
`[email] SMTP_HOST is not set — logging instead of sending.\n` +
` To: ${email.to}\n Reply-To: ${email.replyTo || '-'}\n Subject: ${email.subject}\n` +
` Attachments: ${email.attachments?.map((a) => a.filename).join(', ') || '-'}\n\n${email.text}\n`
);
return { status: 'logged' };
}
if (!env.EMAIL_FROM) throw new Error('EMAIL_FROM is not set');
const info = await getTransporter().sendMail({
from: { name: env.EMAIL_FROM_NAME || '', address: env.EMAIL_FROM },
to: email.to,
replyTo: email.replyTo || undefined,
subject: email.subject,
html: email.html,
text: email.text,
attachments: email.attachments
});
return { status: 'sent', messageId: info.messageId };
}