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
|
|
@ -1,9 +1,10 @@
|
|||
<script lang="ts">
|
||||
import type { BlockType, ContentBlock } from '$lib/types';
|
||||
import type { ContentBlock, EmailBlock } from '$lib/types';
|
||||
import { blockLabels } from '$lib/admin/blockDefaults';
|
||||
|
||||
let { blocks = [], selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
|
||||
blocks: ContentBlock[];
|
||||
let { blocks = [], labels = blockLabels, selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
|
||||
blocks: (ContentBlock | EmailBlock)[];
|
||||
labels?: Record<string, string>;
|
||||
selectedId?: string;
|
||||
onSelect?: (id: string) => void;
|
||||
onDelete?: (id: string) => void;
|
||||
|
|
@ -17,7 +18,7 @@
|
|||
function startHold(id: string) {
|
||||
holdingId = id;
|
||||
holdTimer = setTimeout(() => {
|
||||
const idx = blocks.findIndex((b: ContentBlock) => b.id === id);
|
||||
const idx = blocks.findIndex((b: ContentBlock | EmailBlock) => b.id === id);
|
||||
onDelete(id);
|
||||
onSelect(blocks[idx + 1]?.id || blocks[idx - 1]?.id || '');
|
||||
holdingId = '';
|
||||
|
|
@ -44,7 +45,7 @@
|
|||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="cursor-grab text-xl text-base-content/40">☰</span>
|
||||
<div class="flex-1 font-semibold">{blockLabels[block.type as BlockType]}</div>
|
||||
<div class="flex-1 font-semibold">{labels[block.type] ?? block.type}</div>
|
||||
<button
|
||||
class="btn btn-xs btn-error btn-outline relative overflow-hidden"
|
||||
class:btn-disabled={holdingId && holdingId !== block.id}
|
||||
|
|
|
|||
90
app-admin/src/lib/admin/editors/EmailBlockEditor.svelte
Normal file
90
app-admin/src/lib/admin/editors/EmailBlockEditor.svelte
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
<script lang="ts">
|
||||
import type { EmailBlock, EmailBlockType } from '$lib/types';
|
||||
import { emailBlockLabels } from '$lib/admin/emailBlockDefaults';
|
||||
import RichTextEditor from './RichTextEditor.svelte';
|
||||
import ImageUploader from './ImageUploader.svelte';
|
||||
import SegmentedControl from './SegmentedControl.svelte';
|
||||
|
||||
let { block, primaryColor = '#8a9a7b', onChange = (block: EmailBlock) => {} } = $props<{
|
||||
block: EmailBlock | null;
|
||||
primaryColor?: string;
|
||||
onChange?: (block: EmailBlock) => void;
|
||||
}>();
|
||||
|
||||
function updateData(patch: Record<string, any>) {
|
||||
if (!block) return;
|
||||
block = { ...block, data: { ...block.data, ...patch } };
|
||||
onChange(block);
|
||||
}
|
||||
|
||||
function titleCase(value: string | number) {
|
||||
const text = String(value);
|
||||
return text.charAt(0).toUpperCase() + text.slice(1);
|
||||
}
|
||||
|
||||
const autoFilled: Record<string, string> = {
|
||||
booking_details: 'Filled in automatically with the booked services, date and time, prices and the total paid.',
|
||||
customer_details: "Filled in automatically with the customer's name, email, phone and checkout notes.",
|
||||
contact_info: 'Filled in automatically from the business name, address, phone and email in Globals → Footer.'
|
||||
};
|
||||
</script>
|
||||
|
||||
{#if !block}
|
||||
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">Select a block to edit.</div>
|
||||
{:else}
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<h2 class="mb-4 text-2xl font-bold">{emailBlockLabels[block.type as EmailBlockType]}</h2>
|
||||
|
||||
{#if block.type === 'text'}
|
||||
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
|
||||
<p class="mt-2 text-sm text-base-content/60">Use placeholders like <code>{'{{customer_first_name}}'}</code> — see the list above.</p>
|
||||
{:else if block.type === 'image'}
|
||||
<div class="space-y-4">
|
||||
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} />
|
||||
<SegmentedControl label="Width" options={[100, 75, 50, 25]} value={Number(block.data.width) || 100} onChange={(v) => updateData({ width: v })} formatLabel={(v) => `${v}%`} />
|
||||
<SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} formatLabel={titleCase} />
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Link (optional)</span></div>
|
||||
<input class="input input-bordered w-full" placeholder="https://… or /page" value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
|
||||
</label>
|
||||
<p class="text-sm text-base-content/60">Images load from the public media server, so they only appear in real inboxes once the site runs on a public domain.</p>
|
||||
</div>
|
||||
{:else if block.type === 'button'}
|
||||
<div class="space-y-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Button label</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">URL</span></div>
|
||||
<input class="input input-bordered w-full" placeholder={'https://…, /page or {{site_url}}'} value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
|
||||
</label>
|
||||
<SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} formatLabel={titleCase} />
|
||||
<div class="form-control">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="label-text w-24">Color</span>
|
||||
<div class="flex flex-1 items-center gap-2">
|
||||
<input class="input input-bordered h-10 w-10 cursor-pointer p-1" type="color" value={block.data.color || primaryColor} oninput={(e) => updateData({ color: e.currentTarget.value })} />
|
||||
<input class="input input-bordered flex-1" placeholder="Leave empty to use global primary" value={block.data.color || ''} oninput={(e) => updateData({ color: e.currentTarget.value })} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else if block.type === 'spacer'}
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Height (px)</span></div>
|
||||
<input type="number" min="0" class="input input-bordered w-full" value={block.data.height ?? 24} oninput={(e) => updateData({ height: parseInt(e.currentTarget.value) || 0 })} />
|
||||
</label>
|
||||
{:else if block.type === 'divider'}
|
||||
<p class="text-base-content/60">A thin horizontal line. No settings.</p>
|
||||
{:else}
|
||||
<div class="space-y-3">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Section title</span></div>
|
||||
<input class="input input-bordered w-full" placeholder="Leave empty for no title" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
|
||||
</label>
|
||||
<p class="text-sm text-base-content/60">{autoFilled[block.type]}</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
43
app-admin/src/lib/admin/emailBlockDefaults.ts
Normal file
43
app-admin/src/lib/admin/emailBlockDefaults.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { v4 as uuid } from 'uuid';
|
||||
import type { EmailBlock, EmailBlockType } from '$lib/types';
|
||||
|
||||
export const emailBlockLabels: Record<EmailBlockType, string> = {
|
||||
text: 'Text',
|
||||
image: 'Image',
|
||||
button: 'Button',
|
||||
spacer: 'Spacer',
|
||||
divider: 'Divider',
|
||||
booking_details: 'Booking details',
|
||||
customer_details: 'Customer details',
|
||||
contact_info: 'Contact info'
|
||||
};
|
||||
|
||||
export const emailBlockTypes = Object.keys(emailBlockLabels) as EmailBlockType[];
|
||||
|
||||
export function createEmailBlock(type: EmailBlockType): EmailBlock {
|
||||
const base: EmailBlock = { id: uuid(), type, data: {} };
|
||||
switch (type) {
|
||||
case 'text':
|
||||
base.data = { content: '<p>Hi {{customer_first_name}},</p><p>Add your message here.</p>' };
|
||||
break;
|
||||
case 'image':
|
||||
base.data = { url: '', alt: '', width: 100, alignment: 'center', href: '' };
|
||||
break;
|
||||
case 'button':
|
||||
base.data = { label: 'Visit our website', href: '{{site_url}}', alignment: 'center', color: '' };
|
||||
break;
|
||||
case 'spacer':
|
||||
base.data = { height: 24 };
|
||||
break;
|
||||
case 'booking_details':
|
||||
base.data = { title: 'Your booking' };
|
||||
break;
|
||||
case 'customer_details':
|
||||
base.data = { title: 'Customer' };
|
||||
break;
|
||||
case 'contact_info':
|
||||
base.data = { title: 'Where to find us' };
|
||||
break;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
1
app-admin/src/lib/email.ts
Normal file
1
app-admin/src/lib/email.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/email';
|
||||
1
app-admin/src/lib/server/email.ts
Normal file
1
app-admin/src/lib/server/email.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/server/email';
|
||||
|
|
@ -91,6 +91,7 @@
|
|||
<a class="btn btn-ghost" href="/items">Items</a>
|
||||
<a class="btn btn-ghost" href="/slots">Slots</a>
|
||||
<a class="btn btn-ghost" href="/orders">Orders</a>
|
||||
<a class="btn btn-ghost" href="/emails">Emails</a>
|
||||
<a class="btn btn-ghost" href="/globals">Globals</a>
|
||||
<div class="dropdown dropdown-end">
|
||||
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
|
||||
|
|
|
|||
21
app-admin/src/routes/emails/+page.server.ts
Normal file
21
app-admin/src/routes/emails/+page.server.ts
Normal 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() };
|
||||
};
|
||||
39
app-admin/src/routes/emails/+page.svelte
Normal file
39
app-admin/src/routes/emails/+page.svelte
Normal 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>
|
||||
116
app-admin/src/routes/emails/[key]/+page.server.ts
Normal file
116
app-admin/src/routes/emails/[key]/+page.server.ts
Normal 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);
|
||||
}
|
||||
};
|
||||
232
app-admin/src/routes/emails/[key]/+page.svelte
Normal file
232
app-admin/src/routes/emails/[key]/+page.svelte
Normal 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>
|
||||
|
|
@ -1,4 +1,6 @@
|
|||
import type { PageServerLoad } from './$types';
|
||||
import { fail } from '@sveltejs/kit';
|
||||
import { sendOrderEmails, type EmailKind } from '$lib/server/email';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
// Sort by id, not 'created' — commerce collections were imported without
|
||||
|
|
@ -9,7 +11,7 @@ export const load: PageServerLoad = async ({ locals }) => {
|
|||
for (const record of records) {
|
||||
const lineRecords = await locals.pb
|
||||
.collection('order_lines')
|
||||
.getFullList({ filter: `order = "${record.id}"` })
|
||||
.getFullList({ filter: locals.pb.filter('order = {:id}', { id: record.id }) })
|
||||
.catch(() => []);
|
||||
|
||||
orders.push({
|
||||
|
|
@ -19,6 +21,9 @@ export const load: PageServerLoad = async ({ locals }) => {
|
|||
total: Number(record.total) || 0,
|
||||
status: String(record.status || 'pending'),
|
||||
created: String(record.created || ''),
|
||||
customerEmailSentAt: String(record.customerEmailSentAt || ''),
|
||||
clientEmailSentAt: String(record.clientEmailSentAt || ''),
|
||||
emailError: String(record.emailError || ''),
|
||||
lines: lineRecords.map((line) => ({
|
||||
id: line.id,
|
||||
name: String(line.name || ''),
|
||||
|
|
@ -32,3 +37,25 @@ export const load: PageServerLoad = async ({ locals }) => {
|
|||
|
||||
return { orders };
|
||||
};
|
||||
|
||||
const OUTCOME_MESSAGES: Record<string, string> = {
|
||||
sent: 'sent',
|
||||
logged: 'not sent — SMTP is not configured (written to the server log)',
|
||||
disabled: 'not sent — this email is turned off in Emails',
|
||||
failed: 'failed — see the error on the order'
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
resend: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const orderId = String(data.get('orderId') || '');
|
||||
const kind = String(data.get('kind') || '');
|
||||
if (!orderId || (kind !== 'customer' && kind !== 'client')) {
|
||||
return fail(400, { orderId, ok: false, message: 'Invalid resend request.' });
|
||||
}
|
||||
const outcomes = await sendOrderEmails(locals.pb, orderId, [kind as EmailKind]);
|
||||
const outcome = outcomes[kind as EmailKind] ?? 'failed';
|
||||
const label = kind === 'customer' ? 'Customer confirmation' : 'Booking alert';
|
||||
return { orderId, ok: outcome === 'sent', message: `${label} ${OUTCOME_MESSAGES[outcome]}.` };
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,10 +1,37 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props();
|
||||
import { enhance } from '$app/forms';
|
||||
|
||||
let { data, form } = $props();
|
||||
let orders = $derived(data.orders || []);
|
||||
let resending = $state('');
|
||||
|
||||
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
</script>
|
||||
|
||||
{#snippet emailStatus(order: (typeof orders)[number], kind: 'customer' | 'client', label: string, sentAt: string)}
|
||||
<form
|
||||
method="POST"
|
||||
action="?/resend"
|
||||
class="flex items-center gap-2"
|
||||
use:enhance={() => {
|
||||
resending = `${order.id}-${kind}`;
|
||||
return async ({ update }) => {
|
||||
resending = '';
|
||||
await update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
<input type="hidden" name="orderId" value={order.id} />
|
||||
<input type="hidden" name="kind" value={kind} />
|
||||
<span class="badge badge-sm" class:badge-success={sentAt} class:badge-ghost={!sentAt} title={sentAt ? new Date(sentAt).toLocaleString() : 'Not sent'}>
|
||||
{label}: {sentAt ? 'sent' : 'not sent'}
|
||||
</span>
|
||||
<button class="btn btn-ghost btn-xs" type="submit" disabled={resending !== ''}>
|
||||
{resending === `${order.id}-${kind}` ? 'Sending…' : sentAt ? 'Resend' : 'Send'}
|
||||
</button>
|
||||
</form>
|
||||
{/snippet}
|
||||
|
||||
<svelte:head><title>Orders | CMS</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
|
|
@ -53,6 +80,17 @@
|
|||
{#if order.customerDetails?.notes}
|
||||
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
|
||||
{/if}
|
||||
|
||||
<div class="mt-4 flex flex-wrap gap-x-6 gap-y-2 border-t border-base-300 pt-3">
|
||||
{@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)}
|
||||
{@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)}
|
||||
</div>
|
||||
{#if order.emailError}
|
||||
<p class="mt-2 whitespace-pre-line text-sm text-error">{order.emailError}</p>
|
||||
{/if}
|
||||
{#if form?.orderId === order.id && form.message}
|
||||
<div class="alert mt-2 py-2 text-sm" class:alert-success={form.ok} class:alert-warning={!form.ok}>{form.message}</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue