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
|
|
@ -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