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,21 @@
import { emailTemplateKeys, emailTemplateMeta } from '$lib/email';
import { emailSender, isEmailConfigured, loadEmailSettings, loadEmailTemplate } from '$lib/server/email';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
const settings = await loadEmailSettings(locals.pb);
const templates = await Promise.all(
emailTemplateKeys.map(async (key) => {
const template = await loadEmailTemplate(locals.pb, key);
return {
key,
...emailTemplateMeta[key],
subject: template.subject,
enabled: template.enabled,
customised: Boolean(template.id),
recipients: key === 'customer_confirmation' ? 'The customer' : template.recipients || settings.business.email || ''
};
})
);
return { templates, smtpConfigured: isEmailConfigured(), sender: emailSender() };
};

View file

@ -0,0 +1,39 @@
<script lang="ts">
let { data } = $props();
</script>
<svelte:head><title>Emails | CMS</title></svelte:head>
<div class="space-y-6">
<div>
<h1 class="text-3xl font-bold">Emails</h1>
<p class="text-base-content/60">Automatic emails sent after a successful booking.</p>
</div>
{#if !data.smtpConfigured}
<div class="alert alert-warning">
<span>Email sending is not configured (<code>SMTP_HOST</code> is empty), so emails are only written to the server log. See the README for the Brevo setup.</span>
</div>
{:else}
<p class="text-sm text-base-content/60">Sending as <strong>{data.sender || 'EMAIL_FROM is not set!'}</strong></p>
{/if}
<div class="grid gap-4 md:grid-cols-2">
{#each data.templates as template}
<a class="rounded-box bg-base-100 p-5 shadow transition hover:shadow-md" href="/emails/{template.key}">
<div class="flex items-start justify-between gap-3">
<h2 class="text-xl font-bold">{template.label}</h2>
<div class="flex gap-2">
{#if !template.customised}<span class="badge badge-ghost">Default</span>{/if}
<span class="badge" class:badge-success={template.enabled} class:badge-error={!template.enabled}>{template.enabled ? 'On' : 'Off'}</span>
</div>
</div>
<p class="mt-2 text-sm text-base-content/60">{template.description}</p>
<dl class="mt-4 space-y-1 text-sm">
<div><dt class="inline font-semibold">To:</dt> <dd class="inline">{template.recipients || '— no recipient set —'}</dd></div>
<div><dt class="inline font-semibold">Subject:</dt> <dd class="inline">{template.subject}</dd></div>
</dl>
</a>
{/each}
</div>
</div>

View file

@ -0,0 +1,116 @@
import { error, fail, redirect } from '@sveltejs/kit';
import { emailTemplateMeta, isEmailTemplateKey } from '$lib/email';
import { isEmailConfigured, loadEmailSettings, loadEmailTemplate, sendTestEmail } from '$lib/server/email';
import type { EmailBlock } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
function parseBlocks(raw: FormDataEntryValue | null): EmailBlock[] | null {
try {
const blocks = JSON.parse(String(raw || '[]'));
return Array.isArray(blocks) ? blocks : null;
} catch {
return null;
}
}
/** A real bookable service for the sample booking in previews and test emails. */
async function findSampleService(pb: App.Locals['pb']) {
return pb
.collection('items')
.getFirstListItem("type = 'item_with_time' && active = true", { sort: 'name' })
.then((item) => ({ name: String(item.name), price: Number(item.price) || 0, duration: Number(item.duration) || null }))
.catch(() => undefined);
}
export const load: PageServerLoad = async ({ params, locals }) => {
if (!isEmailTemplateKey(params.key)) throw error(404, 'Unknown email template');
const key = params.key;
const [template, settings, service] = await Promise.all([
loadEmailTemplate(locals.pb, key),
loadEmailSettings(locals.pb),
findSampleService(locals.pb)
]);
return {
key,
meta: emailTemplateMeta[key],
template: { subject: template.subject, blocks: template.blocks, recipients: template.recipients, enabled: template.enabled },
customised: Boolean(template.id),
settings,
service,
smtpConfigured: isEmailConfigured(),
userEmail: String(locals.user?.email || '')
};
};
export const actions: Actions = {
save: async ({ params, request, locals }) => {
if (!isEmailTemplateKey(params.key)) throw error(404, 'Unknown email template');
const data = await request.formData();
const blocks = parseBlocks(data.get('blocks'));
if (!blocks) return fail(400, { action: 'save', ok: false, message: 'Invalid blocks data.' });
const subject = String(data.get('subject') || '').trim();
if (!subject) return fail(400, { action: 'save', ok: false, message: 'Subject is required.' });
const recipients = String(data.get('recipients') || '').trim();
const invalid = recipients
.split(',')
.map((address) => address.trim())
.filter((address) => address && !EMAIL_RE.test(address));
if (invalid.length) return fail(400, { action: 'save', ok: false, message: `Invalid recipient address: ${invalid.join(', ')}` });
const payload = { key: params.key, subject, blocks, recipients, enabled: data.get('enabled') === 'true' };
const existing = await loadEmailTemplate(locals.pb, params.key);
try {
if (existing.id) await locals.pb.collection('email_templates').update(existing.id, payload);
else await locals.pb.collection('email_templates').create(payload);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
return fail(500, {
action: 'save',
ok: false,
message: `Could not save: ${message}. Has the email_templates collection been imported from pb_schema.json?`
});
}
return { action: 'save', ok: true, message: 'Saved.' };
},
test: async ({ params, request, locals }) => {
if (!isEmailTemplateKey(params.key)) throw error(404, 'Unknown email template');
const data = await request.formData();
const to = String(data.get('to') || '').trim();
if (!EMAIL_RE.test(to)) return fail(400, { action: 'test', ok: false, message: 'Enter a valid email address.' });
const blocks = parseBlocks(data.get('blocks'));
if (!blocks) return fail(400, { action: 'test', ok: false, message: 'Invalid blocks data.' });
try {
const result = await sendTestEmail(
locals.pb,
{ key: params.key, subject: String(data.get('subject') || ''), blocks },
to,
await findSampleService(locals.pb)
);
return {
action: 'test',
ok: true,
message:
result.status === 'sent'
? `Test email sent to ${to}.`
: 'SMTP is not configured — the email was written to the app-admin log instead of being sent.'
};
} catch (e) {
return fail(502, { action: 'test', ok: false, message: `Sending failed: ${e instanceof Error ? e.message : String(e)}` });
}
},
reset: async ({ params, locals, url }) => {
if (!isEmailTemplateKey(params.key)) throw error(404, 'Unknown email template');
const existing = await loadEmailTemplate(locals.pb, params.key);
if (existing.id) await locals.pb.collection('email_templates').delete(existing.id);
throw redirect(303, url.pathname);
}
};

View file

@ -0,0 +1,232 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { beforeNavigate } from '$app/navigation';
import BlockList from '$lib/admin/BlockList.svelte';
import EmailBlockEditor from '$lib/admin/editors/EmailBlockEditor.svelte';
import { createEmailBlock, emailBlockLabels, emailBlockTypes } from '$lib/admin/emailBlockDefaults';
import { emailPlaceholders, renderEmail, sampleEmailContext } from '$lib/email';
import type { EmailBlock, EmailBlockType } from '$lib/types';
let { data, form } = $props();
let subject = $state(data.template.subject);
let recipients = $state(data.template.recipients);
let enabled = $state(data.template.enabled);
let blocks = $state<EmailBlock[]>(structuredClone(data.template.blocks));
let selectedId = $state(blocks[0]?.id || '');
let previewMode = $state<'desktop' | 'mobile'>('desktop');
let previewFormat = $state<'html' | 'text'>('html');
let testTo = $state(data.userEmail);
let saving = $state(false);
let testing = $state(false);
let copied = $state('');
const serialize = () => JSON.stringify({ subject, recipients, enabled, blocks });
let savedSnapshot = $state(serialize());
let dirty = $derived(serialize() !== savedSnapshot);
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
let context = $derived(sampleEmailContext({ ...data.settings, service: data.service }));
let rendered = $derived(renderEmail({ subject, blocks }, context));
let isAlert = $derived(data.key === 'client_alert');
beforeNavigate(({ cancel, type }) => {
if (dirty && type !== 'form' && !confirm('You have unsaved changes. Leave anyway?')) cancel();
});
function addBlock(type: EmailBlockType) {
const block = createEmailBlock(type);
blocks = [...blocks, block];
selectedId = block.id;
}
function updateBlock(updated: EmailBlock) {
blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
}
function deleteBlock(id: string) {
blocks = blocks.filter((block) => block.id !== id);
if (selectedId === id) selectedId = blocks[0]?.id || '';
}
function moveBlock(from: number, to: number) {
const copy = [...blocks];
const [item] = copy.splice(from, 1);
copy.splice(to, 0, item);
blocks = copy;
}
async function copyPlaceholder(key: string) {
await navigator.clipboard?.writeText(`{{${key}}}`).catch(() => {});
copied = key;
setTimeout(() => (copied = ''), 1200);
}
</script>
<svelte:head><title>{data.meta.label} | Emails | CMS</title></svelte:head>
<div class="space-y-6">
<form
method="POST"
action="?/save"
class="space-y-6"
use:enhance={() => {
saving = true;
const snapshot = serialize();
return async ({ result, update }) => {
saving = false;
if (result.type === 'success') savedSnapshot = snapshot;
await update({ reset: false });
};
}}
>
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<input type="hidden" name="enabled" value={String(enabled)} />
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<a class="link link-hover text-sm text-base-content/60" href="/emails">← Emails</a>
<h1 class="text-3xl font-bold">{data.meta.label}</h1>
<p class="text-base-content/60">{data.meta.description}</p>
</div>
<div class="flex flex-wrap items-center gap-2">
{#if dirty}<span class="badge badge-warning">Unsaved changes</span>{/if}
<button class="btn btn-primary" type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save'}</button>
</div>
</div>
{#if form?.action === 'save' && form.message}
<div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div>
{/if}
<div class="rounded-box space-y-4 bg-base-100 p-5 shadow">
<label class="label cursor-pointer justify-start gap-3">
<input type="checkbox" class="toggle toggle-primary" bind:checked={enabled} />
<span class="label-text">{enabled ? 'This email is sent automatically' : 'This email is turned off'}</span>
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Subject</span></div>
<input class="input input-bordered w-full" name="subject" bind:value={subject} />
</label>
{#if isAlert}
<label class="form-control w-full">
<div class="label"><span class="label-text">Send to (comma-separated)</span></div>
<input class="input input-bordered w-full" name="recipients" placeholder={data.settings.business.email || 'you@example.com'} bind:value={recipients} />
<div class="label">
<span class="label-text-alt text-base-content/60">
{#if data.settings.business.email}Leave empty to use the footer email ({data.settings.business.email}).{:else}No footer email is set — enter at least one address.{/if}
</span>
</div>
</label>
{:else}
<input type="hidden" name="recipients" value="" />
<p class="text-sm text-base-content/60">Sent to the email address the customer entered at checkout. Replies go to {data.settings.business.email || 'the footer email (not set yet)'}.</p>
{/if}
<details class="collapse collapse-arrow border border-base-300">
<summary class="collapse-title font-semibold">Placeholders</summary>
<div class="collapse-content">
<p class="mb-3 text-sm text-base-content/60">Type these into the subject or any text block; they're replaced with the booking's details. Click one to copy it.</p>
<div class="grid gap-2 sm:grid-cols-2">
{#each emailPlaceholders as placeholder}
<button type="button" class="btn btn-ghost btn-sm justify-start font-normal" onclick={() => copyPlaceholder(placeholder.key)}>
<code class="text-primary">{`{{${placeholder.key}}}`}</code>
<span class="text-base-content/60">{copied === placeholder.key ? 'Copied!' : placeholder.description}</span>
</button>
{/each}
</div>
</div>
</details>
</div>
<div class="grid gap-6 lg:grid-cols-[22rem_1fr]">
<aside class="space-y-4">
<div class="rounded-box bg-base-100 p-4 shadow">
<div class="dropdown w-full">
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
{#each emailBlockTypes as type}
<li><button type="button" onclick={() => addBlock(type)}>{emailBlockLabels[type]}</button></li>
{/each}
</ul>
</div>
</div>
<BlockList {blocks} labels={emailBlockLabels} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
</aside>
<EmailBlockEditor block={selectedBlock} primaryColor={data.settings.colors.primary} onChange={updateBlock} />
</div>
</form>
<div class="rounded-box bg-base-100 p-5 shadow">
<div class="mb-3 flex flex-col justify-between gap-3 md:flex-row md:items-center">
<div>
<h2 class="text-xl font-bold">Preview</h2>
<p class="text-sm text-base-content/60">With a sample booking. <strong>Subject:</strong> {rendered.subject}</p>
</div>
<div class="flex gap-2">
<div class="join">
<button type="button" class="btn btn-sm join-item" class:btn-active={previewFormat === 'html'} onclick={() => (previewFormat = 'html')}>Formatted</button>
<button type="button" class="btn btn-sm join-item" class:btn-active={previewFormat === 'text'} onclick={() => (previewFormat = 'text')}>Plain text</button>
</div>
<div class="join">
<button type="button" class="btn btn-sm join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button>
<button type="button" class="btn btn-sm join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button>
</div>
</div>
</div>
{#if previewFormat === 'html'}
<iframe
class="mx-auto block h-[48rem] rounded-box border border-base-300 bg-white"
class:w-full={previewMode === 'desktop'}
style={previewMode === 'mobile' ? 'width: 390px;' : ''}
sandbox=""
srcdoc={rendered.html}
title="Email preview"
></iframe>
{:else}
<pre class="max-h-[48rem] overflow-auto whitespace-pre-wrap rounded-box border border-base-300 bg-base-200 p-4 text-sm">{rendered.text}</pre>
{/if}
</div>
<form
method="POST"
action="?/test"
class="rounded-box space-y-3 bg-base-100 p-5 shadow"
use:enhance={() => {
testing = true;
return async ({ update }) => {
testing = false;
await update({ reset: false, invalidateAll: false });
};
}}
>
<h2 class="text-xl font-bold">Send a test email</h2>
<p class="text-sm text-base-content/60">Sends the current (unsaved) version with the sample booking{data.key === 'customer_confirmation' ? ', including the calendar attachment' : ''}.</p>
{#if !data.smtpConfigured}
<div class="alert alert-warning text-sm">SMTP is not configured, so the test email will only be written to the server log.</div>
{/if}
<input type="hidden" name="subject" value={subject} />
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<div class="flex flex-col gap-2 sm:flex-row">
<input class="input input-bordered flex-1" type="email" name="to" placeholder="you@example.com" bind:value={testTo} required />
<button class="btn" type="submit" disabled={testing}>{testing ? 'Sending…' : 'Send test'}</button>
</div>
{#if form?.action === 'test' && form.message}
<div class="alert text-sm" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div>
{/if}
</form>
{#if data.customised}
<form
method="POST"
action="?/reset"
class="text-right"
onsubmit={(e) => {
if (!confirm('Replace this email with the built-in default? Your changes will be lost.')) e.preventDefault();
}}
>
<button class="btn btn-ghost btn-sm text-error" type="submit">Reset to default</button>
</form>
{/if}
</div>