added mailing through Brevo and node mailer, also a email editor, with
their custom blocks and renderers
This commit is contained in:
parent
43db707e34
commit
96828994e1
34 changed files with 2035 additions and 323 deletions
|
|
@ -6,13 +6,25 @@
|
|||
"name": "@eva/shared",
|
||||
"dependencies": {
|
||||
"@stripe/stripe-js": "^9.12.1",
|
||||
"nodemailer": "^10.0.12",
|
||||
"pocketbase": "^0.26.9",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/nodemailer": "^8.0.2",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@stripe/stripe-js": ["@stripe/stripe-js@9.13.0", "", {}, "sha512-/0c72BUgzzVkVTlsw5uBn8x3waTdVJ/PZGfQ6jY1eu6K7olUPf4d9lgDPA9/0sIdsR8j7o3QIG8fOCO6ItcL7A=="],
|
||||
|
||||
"@types/node": ["@types/node@26.6.3", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg=="],
|
||||
|
||||
"@types/nodemailer": ["@types/nodemailer@8.0.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA=="],
|
||||
|
||||
"nodemailer": ["nodemailer@10.0.12", "", {}, "sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg=="],
|
||||
|
||||
"pocketbase": ["pocketbase@0.26.9", "", {}, "sha512-Tiv1/hNuUzRdvT0d8hF03dfzuefQ1WdSRp1A1q3wzFC/WYhQcbU/Qlaubl/3ZDo6xvFXBS8JAgBS/L+ms7nkVQ=="],
|
||||
|
||||
"undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,10 +12,16 @@
|
|||
"./basket.svelte": "./src/basket.svelte.ts",
|
||||
"./blocks/BlockRenderer.svelte": "./src/blocks/BlockRenderer.svelte",
|
||||
"./server/pb-admin": "./src/server/pb-admin.ts",
|
||||
"./server/basket": "./src/server/basket.ts"
|
||||
"./server/basket": "./src/server/basket.ts",
|
||||
"./email": "./src/email/index.ts",
|
||||
"./server/email": "./src/server/email/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"pocketbase": "^0.26.9",
|
||||
"@stripe/stripe-js": "^9.12.1"
|
||||
"@stripe/stripe-js": "^9.12.1",
|
||||
"nodemailer": "^10.0.12",
|
||||
"pocketbase": "^0.26.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/nodemailer": "^8.0.2"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
86
packages/shared/src/email/defaults.ts
Normal file
86
packages/shared/src/email/defaults.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import type { EmailBlock, EmailTemplate, EmailTemplateKey } from '../types';
|
||||
|
||||
export const emailTemplateKeys: EmailTemplateKey[] = ['customer_confirmation', 'client_alert'];
|
||||
|
||||
export const emailTemplateMeta: Record<EmailTemplateKey, { label: string; description: string }> = {
|
||||
customer_confirmation: {
|
||||
label: 'Booking confirmation',
|
||||
description: 'Sent to the customer after a successful payment. Includes a calendar (.ics) attachment for booked time slots.'
|
||||
},
|
||||
client_alert: {
|
||||
label: 'New booking alert',
|
||||
description: 'Sent to you after a successful payment. Replying goes straight to the customer.'
|
||||
}
|
||||
};
|
||||
|
||||
// Used whenever no email_templates record exists for a key, so booking emails
|
||||
// work before anyone has opened the email editor.
|
||||
export const defaultEmailTemplates: Record<EmailTemplateKey, EmailTemplate> = {
|
||||
customer_confirmation: {
|
||||
key: 'customer_confirmation',
|
||||
subject: 'Your booking is confirmed – {{service}}',
|
||||
recipients: '',
|
||||
enabled: true,
|
||||
blocks: [
|
||||
{
|
||||
id: 'default-cc-intro',
|
||||
type: 'text',
|
||||
data: {
|
||||
content:
|
||||
'<h2>Thank you, {{customer_first_name}}!</h2><p>Your booking is confirmed and paid. Here are the details:</p>'
|
||||
}
|
||||
},
|
||||
{ id: 'default-cc-booking', type: 'booking_details', data: { title: 'Your booking' } },
|
||||
{
|
||||
id: 'default-cc-outro',
|
||||
type: 'text',
|
||||
data: {
|
||||
content:
|
||||
'<p>A calendar file is attached — open it to add the appointment to your calendar.</p><p>If you need to change or cancel your booking, simply reply to this email.</p><p>Looking forward to seeing you,<br>{{business_name}}</p>'
|
||||
}
|
||||
},
|
||||
{ id: 'default-cc-divider', type: 'divider', data: {} },
|
||||
{ id: 'default-cc-contact', type: 'contact_info', data: { title: 'Where to find us' } }
|
||||
] satisfies EmailBlock[]
|
||||
},
|
||||
client_alert: {
|
||||
key: 'client_alert',
|
||||
subject: 'New booking: {{service}} – {{customer_name}}',
|
||||
recipients: '',
|
||||
enabled: true,
|
||||
blocks: [
|
||||
{
|
||||
id: 'default-ca-intro',
|
||||
type: 'text',
|
||||
data: {
|
||||
content:
|
||||
'<h2>New booking</h2><p>{{customer_name}} just booked and paid {{order_total}}.</p>'
|
||||
}
|
||||
},
|
||||
{ id: 'default-ca-booking', type: 'booking_details', data: { title: 'Booking' } },
|
||||
{ id: 'default-ca-customer', type: 'customer_details', data: { title: 'Customer' } },
|
||||
{
|
||||
id: 'default-ca-outro',
|
||||
type: 'text',
|
||||
data: { content: '<p>Reply to this email to contact {{customer_first_name}} directly.</p>' }
|
||||
}
|
||||
] satisfies EmailBlock[]
|
||||
}
|
||||
};
|
||||
|
||||
export function isEmailTemplateKey(value: string): value is EmailTemplateKey {
|
||||
return (emailTemplateKeys as string[]).includes(value);
|
||||
}
|
||||
|
||||
/** Merge a PocketBase record (or partial data) over the default for its key. */
|
||||
export function normalizeEmailTemplate(key: EmailTemplateKey, record?: Record<string, any> | null): EmailTemplate {
|
||||
const fallback = defaultEmailTemplates[key];
|
||||
if (!record) return structuredClone(fallback);
|
||||
return {
|
||||
key,
|
||||
subject: typeof record.subject === 'string' && record.subject.trim() ? record.subject : fallback.subject,
|
||||
blocks: Array.isArray(record.blocks) ? record.blocks : structuredClone(fallback.blocks),
|
||||
recipients: typeof record.recipients === 'string' ? record.recipients : '',
|
||||
enabled: typeof record.enabled === 'boolean' ? record.enabled : true
|
||||
};
|
||||
}
|
||||
2
packages/shared/src/email/index.ts
Normal file
2
packages/shared/src/email/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from './render';
|
||||
export * from './defaults';
|
||||
424
packages/shared/src/email/render.ts
Normal file
424
packages/shared/src/email/render.ts
Normal file
|
|
@ -0,0 +1,424 @@
|
|||
import type { ColorsGlobal, CustomerDetails, EmailBlock, EmailTemplate, FooterGlobal } from '../types';
|
||||
|
||||
// Pure email rendering — no server or browser APIs, so the admin editor can
|
||||
// render its live preview client-side with exactly the code that sends.
|
||||
//
|
||||
// Email clients (Gmail, Outlook, Apple Mail) strip <style> tags and ignore
|
||||
// most modern CSS, so everything here is table-based with inline styles.
|
||||
|
||||
export type EmailLine = {
|
||||
name: string;
|
||||
price: number;
|
||||
quantity: number;
|
||||
start: string | null;
|
||||
end: string | null;
|
||||
};
|
||||
|
||||
export type EmailContext = {
|
||||
orderId: string;
|
||||
total: number;
|
||||
currency: string;
|
||||
customer: CustomerDetails;
|
||||
lines: EmailLine[];
|
||||
business: FooterGlobal;
|
||||
colors: ColorsGlobal;
|
||||
siteUrl: string;
|
||||
timezone: string;
|
||||
};
|
||||
|
||||
export type RenderedEmail = { subject: string; html: string; text: string };
|
||||
|
||||
export const emailPlaceholders: { key: string; description: string }[] = [
|
||||
{ key: 'customer_name', description: 'Customer full name' },
|
||||
{ key: 'customer_first_name', description: 'Customer first name' },
|
||||
{ key: 'customer_email', description: 'Customer email' },
|
||||
{ key: 'customer_phone', description: 'Customer phone' },
|
||||
{ key: 'customer_notes', description: 'Notes left at checkout' },
|
||||
{ key: 'service', description: 'Booked service(s)' },
|
||||
{ key: 'booking_date', description: 'Date and time of the first booking' },
|
||||
{ key: 'order_total', description: 'Total paid' },
|
||||
{ key: 'order_id', description: 'Order reference' },
|
||||
{ key: 'business_name', description: 'Business name (footer settings)' },
|
||||
{ key: 'business_email', description: 'Business email (footer settings)' },
|
||||
{ key: 'business_phone', description: 'Business phone (footer settings)' },
|
||||
{ key: 'site_url', description: 'Website address' }
|
||||
];
|
||||
|
||||
const CONTENT_WIDTH = 536; // 600px card minus 2×32px padding
|
||||
const FONT_BODY = "'DM Sans', Helvetica, Arial, sans-serif";
|
||||
const FONT_HEADING = "'Playfair Display', Georgia, 'Times New Roman', serif";
|
||||
const BORDER = '#e7e1d8';
|
||||
|
||||
// ── Formatting ────────────────────────────────────────────────────────
|
||||
|
||||
export function escapeHtml(value: unknown): string {
|
||||
return String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
export function formatMoney(amount: number, currency: string): string {
|
||||
try {
|
||||
return new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency.toUpperCase() }).format(amount);
|
||||
} catch {
|
||||
return `${amount.toFixed(2)} ${currency.toUpperCase()}`;
|
||||
}
|
||||
}
|
||||
|
||||
function safeTimeZone(timezone: string): string {
|
||||
try {
|
||||
new Intl.DateTimeFormat('en-GB', { timeZone: timezone });
|
||||
return timezone;
|
||||
} catch {
|
||||
return 'UTC';
|
||||
}
|
||||
}
|
||||
|
||||
export function formatDateTime(iso: string, timezone: string): string {
|
||||
return new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone: safeTimeZone(timezone),
|
||||
weekday: 'long',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(new Date(iso));
|
||||
}
|
||||
|
||||
function formatTime(iso: string, timezone: string): string {
|
||||
return new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone: safeTimeZone(timezone),
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(new Date(iso));
|
||||
}
|
||||
|
||||
/** "Monday 6 October 2026 at 10:00 – 11:00" (end omitted when unknown). */
|
||||
export function formatLineWhen(line: EmailLine, timezone: string): string {
|
||||
if (!line.start) return '';
|
||||
const start = formatDateTime(line.start, timezone);
|
||||
return line.end ? `${start} – ${formatTime(line.end, timezone)}` : start;
|
||||
}
|
||||
|
||||
export function absoluteUrl(url: string, siteUrl: string): string {
|
||||
if (url.startsWith('/') && !url.startsWith('//')) return siteUrl.replace(/\/$/, '') + url;
|
||||
return url;
|
||||
}
|
||||
|
||||
// ── Placeholders ──────────────────────────────────────────────────────
|
||||
|
||||
export function placeholderValues(ctx: EmailContext): Record<string, string> {
|
||||
const firstBooking = ctx.lines.find((line) => line.start);
|
||||
return {
|
||||
customer_name: ctx.customer.name,
|
||||
customer_first_name: (ctx.customer.name || '').trim().split(/\s+/)[0] || '',
|
||||
customer_email: ctx.customer.email,
|
||||
customer_phone: ctx.customer.phone,
|
||||
customer_notes: ctx.customer.notes,
|
||||
service: ctx.lines.map((line) => line.name).join(', '),
|
||||
booking_date: firstBooking ? formatLineWhen(firstBooking, ctx.timezone) : '',
|
||||
order_total: formatMoney(ctx.total, ctx.currency),
|
||||
order_id: ctx.orderId,
|
||||
business_name: ctx.business.businessName,
|
||||
business_email: ctx.business.email,
|
||||
business_phone: ctx.business.phone,
|
||||
site_url: ctx.siteUrl
|
||||
};
|
||||
}
|
||||
|
||||
/** Replace {{key}} tokens; unknown keys are left untouched so typos stay visible. */
|
||||
export function fillPlaceholders(input: string, values: Record<string, string>, escape: boolean): string {
|
||||
return String(input ?? '').replace(/\{\{\s*([a-z_]+)\s*\}\}/g, (match, key: string) =>
|
||||
key in values ? (escape ? escapeHtml(values[key]) : values[key]) : match
|
||||
);
|
||||
}
|
||||
|
||||
// ── Rich text → inline-styled HTML ────────────────────────────────────
|
||||
|
||||
function richTextStyles(colors: ColorsGlobal): Record<string, string> {
|
||||
const heading = `font-family:${FONT_HEADING};color:${colors.heading};font-weight:600;line-height:1.3;`;
|
||||
const body = `font-family:${FONT_BODY};color:${colors.text};font-size:16px;line-height:1.6;`;
|
||||
return {
|
||||
h1: `${heading}font-size:28px;margin:0 0 16px;`,
|
||||
h2: `${heading}font-size:24px;margin:0 0 14px;`,
|
||||
h3: `${heading}font-size:19px;margin:0 0 10px;color:${colors.subheading};`,
|
||||
p: `${body}margin:0 0 14px;`,
|
||||
ul: `${body}margin:0 0 14px;padding-left:24px;`,
|
||||
ol: `${body}margin:0 0 14px;padding-left:24px;`,
|
||||
li: `${body}margin:0 0 4px;`,
|
||||
blockquote: `${body}margin:0 0 14px;padding-left:14px;border-left:3px solid ${colors.primary};color:${colors.subheading};font-style:italic;`,
|
||||
a: `color:${colors.accent};text-decoration:underline;`
|
||||
};
|
||||
}
|
||||
|
||||
function styleRichText(html: string, ctx: EmailContext): string {
|
||||
const styles = richTextStyles(ctx.colors);
|
||||
return html
|
||||
.replace(/<(h1|h2|h3|p|ul|ol|li|blockquote|a)(\s[^>]*)?>/gi, (_match, rawTag: string, rawAttrs = '') => {
|
||||
const tag = rawTag.toLowerCase();
|
||||
let attrs = String(rawAttrs);
|
||||
const existing = attrs.match(/\sstyle\s*=\s*"([^"]*)"/i);
|
||||
if (existing) {
|
||||
attrs = attrs.replace(existing[0], ` style="${styles[tag]}${existing[1]}"`);
|
||||
} else {
|
||||
attrs += ` style="${styles[tag]}"`;
|
||||
}
|
||||
return `<${tag}${attrs}>`;
|
||||
})
|
||||
.replace(/\shref\s*=\s*"(\/[^"]*)"/gi, (_m, href: string) => ` href="${escapeHtml(absoluteUrl(href, ctx.siteUrl))}"`);
|
||||
}
|
||||
|
||||
function decodeEntities(text: string): string {
|
||||
return text
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
|
||||
export function htmlToText(html: string, siteUrl = ''): string {
|
||||
return decodeEntities(
|
||||
html
|
||||
.replace(/<br\s*\/?>/gi, '\n')
|
||||
.replace(/<li[^>]*>/gi, '- ')
|
||||
.replace(/<\/(p|h1|h2|h3|ul|ol|blockquote|div)>/gi, '\n\n')
|
||||
.replace(/<\/li>/gi, '\n')
|
||||
.replace(/<a\s[^>]*href\s*=\s*"([^"]*)"[^>]*>(.*?)<\/a>/gi, (_m, href: string, label: string) => {
|
||||
const url = absoluteUrl(href, siteUrl);
|
||||
const text = label.replace(/<[^>]+>/g, '');
|
||||
return text && text !== url ? `${text} (${url})` : url;
|
||||
})
|
||||
.replace(/<[^>]+>/g, '')
|
||||
)
|
||||
.replace(/[ \t]+\n/g, '\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
// ── Blocks ────────────────────────────────────────────────────────────
|
||||
|
||||
function row(content: string, padding = '8px 32px', align = 'left'): string {
|
||||
return `<tr><td align="${align}" style="padding:${padding};text-align:${align};">${content}</td></tr>`;
|
||||
}
|
||||
|
||||
function sectionTitle(title: string, ctx: EmailContext): string {
|
||||
if (!title) return '';
|
||||
return `<h3 style="font-family:${FONT_HEADING};color:${ctx.colors.heading};font-size:19px;font-weight:600;line-height:1.3;margin:0 0 12px;">${escapeHtml(title)}</h3>`;
|
||||
}
|
||||
|
||||
function detailTable(rows: [string, string][], ctx: EmailContext): string {
|
||||
const cells = rows
|
||||
.map(
|
||||
([label, value]) =>
|
||||
`<tr><td valign="top" style="padding:6px 12px 6px 0;font-family:${FONT_BODY};font-size:14px;line-height:1.5;color:${ctx.colors.subheading};white-space:nowrap;">${escapeHtml(label)}</td><td valign="top" style="padding:6px 0;font-family:${FONT_BODY};font-size:15px;line-height:1.5;color:${ctx.colors.text};">${value}</td></tr>`
|
||||
)
|
||||
.join('');
|
||||
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">${cells}</table>`;
|
||||
}
|
||||
|
||||
function boxed(inner: string, ctx: EmailContext): string {
|
||||
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background:${ctx.colors.background};border:1px solid ${BORDER};border-radius:8px;"><tr><td style="padding:20px 22px;">${inner}</td></tr></table>`;
|
||||
}
|
||||
|
||||
function renderBookingDetails(block: EmailBlock, ctx: EmailContext): string {
|
||||
const cell = `font-family:${FONT_BODY};color:${ctx.colors.text};`;
|
||||
const lines = ctx.lines
|
||||
.map((line) => {
|
||||
const when = formatLineWhen(line, ctx.timezone);
|
||||
const qty = line.quantity > 1 ? `${line.quantity}× ` : '';
|
||||
return `<tr>
|
||||
<td valign="top" style="${cell}padding:10px 12px 10px 0;border-bottom:1px solid ${BORDER};">
|
||||
<div style="font-size:16px;font-weight:600;line-height:1.4;">${escapeHtml(qty + line.name)}</div>
|
||||
${when ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheading};">${escapeHtml(when)}</div>` : ''}
|
||||
</td>
|
||||
<td valign="top" align="right" style="${cell}padding:10px 0;border-bottom:1px solid ${BORDER};font-size:15px;white-space:nowrap;">${escapeHtml(formatMoney(line.price * line.quantity, ctx.currency))}</td>
|
||||
</tr>`;
|
||||
})
|
||||
.join('');
|
||||
const total = `<tr><td style="${cell}padding:12px 12px 0 0;font-size:16px;font-weight:700;">Total paid</td><td align="right" style="${cell}padding:12px 0 0;font-size:16px;font-weight:700;white-space:nowrap;">${escapeHtml(formatMoney(ctx.total, ctx.currency))}</td></tr>`;
|
||||
const table = `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">${lines}${total}</table>`;
|
||||
return boxed(sectionTitle(block.data.title ?? '', ctx) + table, ctx);
|
||||
}
|
||||
|
||||
function renderCustomerDetails(block: EmailBlock, ctx: EmailContext): string {
|
||||
const link = `color:${ctx.colors.accent};text-decoration:underline;`;
|
||||
const { name, email, phone, notes } = ctx.customer;
|
||||
const rows: [string, string][] = [['Name', escapeHtml(name)]];
|
||||
if (email) rows.push(['Email', `<a href="mailto:${escapeHtml(email)}" style="${link}">${escapeHtml(email)}</a>`]);
|
||||
if (phone) rows.push(['Phone', `<a href="tel:${escapeHtml(phone.replace(/\s+/g, ''))}" style="${link}">${escapeHtml(phone)}</a>`]);
|
||||
if (notes) rows.push(['Notes', escapeHtml(notes).replace(/\n/g, '<br>')]);
|
||||
return boxed(sectionTitle(block.data.title ?? '', ctx) + detailTable(rows, ctx), ctx);
|
||||
}
|
||||
|
||||
function renderContactInfo(block: EmailBlock, ctx: EmailContext): string {
|
||||
const link = `color:${ctx.colors.accent};text-decoration:underline;`;
|
||||
const { businessName, address, phone, email } = ctx.business;
|
||||
const parts: string[] = [];
|
||||
if (businessName) parts.push(`<strong>${escapeHtml(businessName)}</strong>`);
|
||||
if (address) parts.push(escapeHtml(address).replace(/\n/g, '<br>'));
|
||||
if (phone) parts.push(`<a href="tel:${escapeHtml(phone.replace(/\s+/g, ''))}" style="${link}">${escapeHtml(phone)}</a>`);
|
||||
if (email) parts.push(`<a href="mailto:${escapeHtml(email)}" style="${link}">${escapeHtml(email)}</a>`);
|
||||
if (ctx.siteUrl) parts.push(`<a href="${escapeHtml(ctx.siteUrl)}" style="${link}">${escapeHtml(ctx.siteUrl.replace(/^https?:\/\//, ''))}</a>`);
|
||||
const body = `<p style="font-family:${FONT_BODY};color:${ctx.colors.text};font-size:15px;line-height:1.7;margin:0;">${parts.join('<br>')}</p>`;
|
||||
return sectionTitle(block.data.title ?? '', ctx) + body;
|
||||
}
|
||||
|
||||
function renderBlockHtml(block: EmailBlock, ctx: EmailContext, values: Record<string, string>): string {
|
||||
const data = block.data || {};
|
||||
switch (block.type) {
|
||||
case 'text':
|
||||
return row(styleRichText(fillPlaceholders(data.content || '', values, true), ctx));
|
||||
case 'image': {
|
||||
if (!data.url) return '';
|
||||
const width = Math.round((CONTENT_WIDTH * (Number(data.width) || 100)) / 100);
|
||||
const align = data.alignment || 'center';
|
||||
const img = `<img src="${escapeHtml(absoluteUrl(data.url, ctx.siteUrl))}" alt="${escapeHtml(data.alt || '')}" width="${width}" style="display:inline-block;width:100%;max-width:${width}px;height:auto;border:0;border-radius:6px;">`;
|
||||
const href = fillPlaceholders(data.href || '', values, false);
|
||||
return row(href ? `<a href="${escapeHtml(absoluteUrl(href, ctx.siteUrl))}">${img}</a>` : img, '8px 32px', align);
|
||||
}
|
||||
case 'button': {
|
||||
const color = data.color || ctx.colors.primary;
|
||||
const href = escapeHtml(absoluteUrl(fillPlaceholders(data.href || '', values, false), ctx.siteUrl));
|
||||
const label = fillPlaceholders(data.label || '', values, true);
|
||||
const button = `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="display:inline-table;"><tr><td bgcolor="${escapeHtml(color)}" style="background:${escapeHtml(color)};border-radius:6px;"><a href="${href}" style="display:inline-block;padding:13px 28px;font-family:${FONT_BODY};font-size:16px;font-weight:600;line-height:1.2;color:#ffffff;text-decoration:none;border-radius:6px;">${label}</a></td></tr></table>`;
|
||||
return row(button, '12px 32px', data.alignment || 'center');
|
||||
}
|
||||
case 'spacer': {
|
||||
const height = Math.max(0, Number(data.height) || 24);
|
||||
return `<tr><td style="height:${height}px;line-height:${height}px;font-size:0;"> </td></tr>`;
|
||||
}
|
||||
case 'divider':
|
||||
return row(`<div style="border-top:1px solid ${BORDER};font-size:0;line-height:0;"> </div>`, '16px 32px');
|
||||
case 'booking_details':
|
||||
return row(renderBookingDetails(block, ctx), '12px 32px');
|
||||
case 'customer_details':
|
||||
return row(renderCustomerDetails(block, ctx), '12px 32px');
|
||||
case 'contact_info':
|
||||
return row(renderContactInfo(block, ctx), '12px 32px');
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function renderBlockText(block: EmailBlock, ctx: EmailContext, values: Record<string, string>): string {
|
||||
const data = block.data || {};
|
||||
const title = data.title ? `${String(data.title).toUpperCase()}\n` : '';
|
||||
switch (block.type) {
|
||||
case 'text':
|
||||
// Escape so values survive tag stripping; htmlToText decodes them again.
|
||||
return htmlToText(fillPlaceholders(data.content || '', values, true), ctx.siteUrl);
|
||||
case 'button': {
|
||||
const href = absoluteUrl(fillPlaceholders(data.href || '', values, false), ctx.siteUrl);
|
||||
return `${fillPlaceholders(data.label || '', values, false)}: ${href}`;
|
||||
}
|
||||
case 'divider':
|
||||
return '----------------------------------------';
|
||||
case 'booking_details': {
|
||||
const lines = ctx.lines.map((line) => {
|
||||
const when = formatLineWhen(line, ctx.timezone);
|
||||
const qty = line.quantity > 1 ? `${line.quantity}× ` : '';
|
||||
return `- ${qty}${line.name} — ${formatMoney(line.price * line.quantity, ctx.currency)}${when ? `\n ${when}` : ''}`;
|
||||
});
|
||||
return `${title}${lines.join('\n')}\nTotal paid: ${formatMoney(ctx.total, ctx.currency)}`;
|
||||
}
|
||||
case 'customer_details': {
|
||||
const { name, email, phone, notes } = ctx.customer;
|
||||
return [
|
||||
`${title}Name: ${name}`,
|
||||
email && `Email: ${email}`,
|
||||
phone && `Phone: ${phone}`,
|
||||
notes && `Notes: ${notes}`
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
case 'contact_info': {
|
||||
const { businessName, address, phone, email } = ctx.business;
|
||||
return title + [businessName, address, phone, email, ctx.siteUrl].filter(Boolean).join('\n');
|
||||
}
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// ── Document ──────────────────────────────────────────────────────────
|
||||
|
||||
export function renderEmail(template: Pick<EmailTemplate, 'subject' | 'blocks'>, ctx: EmailContext): RenderedEmail {
|
||||
const values = placeholderValues(ctx);
|
||||
const subject = fillPlaceholders(template.subject, values, false).replace(/\s+/g, ' ').trim();
|
||||
const blocks = template.blocks || [];
|
||||
|
||||
const body = blocks.map((block) => renderBlockHtml(block, ctx, values)).join('\n');
|
||||
const footerParts = [ctx.business.businessName, (ctx.business.address || '').replace(/\n/g, ', ')].filter(Boolean);
|
||||
const footer = footerParts.length
|
||||
? `<p style="font-family:${FONT_BODY};font-size:12px;line-height:1.6;color:${ctx.colors.subheading};margin:16px 0 0;">${footerParts.map(escapeHtml).join(' · ')}</p>`
|
||||
: '';
|
||||
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light">
|
||||
<meta name="supported-color-schemes" content="light">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background:${ctx.colors.background};">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background:${ctx.colors.background};">
|
||||
<tr><td align="center" style="padding:32px 12px;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="600" style="width:100%;max-width:600px;background:#ffffff;border:1px solid ${BORDER};border-radius:10px;">
|
||||
<tr><td style="height:24px;line-height:24px;font-size:0;"> </td></tr>
|
||||
${body}
|
||||
<tr><td style="height:24px;line-height:24px;font-size:0;"> </td></tr>
|
||||
</table>
|
||||
${footer}
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
const text = blocks
|
||||
.map((block) => renderBlockText(block, ctx, values))
|
||||
.filter((part) => part.trim())
|
||||
.join('\n\n');
|
||||
|
||||
return { subject, html, text };
|
||||
}
|
||||
|
||||
/** Realistic fake data for the admin preview and "send test email". */
|
||||
export function sampleEmailContext(options: {
|
||||
business: FooterGlobal;
|
||||
colors: ColorsGlobal;
|
||||
siteUrl: string;
|
||||
timezone: string;
|
||||
currency: string;
|
||||
service?: { name: string; price: number; duration: number | null };
|
||||
}): EmailContext {
|
||||
const service = options.service ?? { name: 'Relaxing full-body massage', price: 90, duration: 60 };
|
||||
const start = new Date();
|
||||
start.setUTCDate(start.getUTCDate() + 3);
|
||||
start.setUTCHours(9, 0, 0, 0);
|
||||
const end = new Date(start.getTime() + (service.duration || 60) * 60_000);
|
||||
return {
|
||||
orderId: 'SAMPLE123',
|
||||
total: service.price,
|
||||
currency: options.currency,
|
||||
customer: {
|
||||
name: 'Jane Example',
|
||||
email: 'jane@example.com',
|
||||
phone: '+47 400 00 000',
|
||||
notes: 'First visit — slight lower back tension.'
|
||||
},
|
||||
lines: [{ name: service.name, price: service.price, quantity: 1, start: start.toISOString(), end: end.toISOString() }],
|
||||
business: options.business,
|
||||
colors: options.colors,
|
||||
siteUrl: options.siteUrl,
|
||||
timezone: options.timezone
|
||||
};
|
||||
}
|
||||
69
packages/shared/src/server/email/ics.ts
Normal file
69
packages/shared/src/server/email/ics.ts
Normal 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';
|
||||
}
|
||||
236
packages/shared/src/server/email/index.ts
Normal file
236
packages/shared/src/server/email/index.ts
Normal 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
|
||||
});
|
||||
}
|
||||
70
packages/shared/src/server/email/transport.ts
Normal file
70
packages/shared/src/server/email/transport.ts
Normal 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 };
|
||||
}
|
||||
|
|
@ -170,6 +170,9 @@ export type OrderRecord = {
|
|||
stripePaymentIntentId: string;
|
||||
createdAt: string;
|
||||
lines?: OrderLine[];
|
||||
customerEmailSentAt?: string;
|
||||
clientEmailSentAt?: string;
|
||||
emailError?: string;
|
||||
};
|
||||
|
||||
export type OrderLine = {
|
||||
|
|
@ -199,6 +202,38 @@ export type CheckoutBlockData = {
|
|||
notesLabel?: string;
|
||||
};
|
||||
|
||||
// ── Email types ───────────────────────────────────────────────────────
|
||||
|
||||
// Email blocks are a separate, smaller set than page blocks: email clients
|
||||
// only render table layouts with inline styles, so each type has its own
|
||||
// renderer in $shared/email/render.
|
||||
export type EmailBlockType =
|
||||
| 'text'
|
||||
| 'image'
|
||||
| 'button'
|
||||
| 'spacer'
|
||||
| 'divider'
|
||||
| 'booking_details'
|
||||
| 'customer_details'
|
||||
| 'contact_info';
|
||||
|
||||
export type EmailBlock = {
|
||||
id: string;
|
||||
type: EmailBlockType;
|
||||
data: Record<string, any>;
|
||||
};
|
||||
|
||||
export type EmailTemplateKey = 'customer_confirmation' | 'client_alert';
|
||||
|
||||
export type EmailTemplate = {
|
||||
key: EmailTemplateKey;
|
||||
subject: string;
|
||||
blocks: EmailBlock[];
|
||||
// Comma-separated addresses; only used by client_alert (falls back to the footer email).
|
||||
recipients: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
export type ColorsGlobal = {
|
||||
background: string;
|
||||
heading: string;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue