60 lines
2.0 KiB
TypeScript
60 lines
2.0 KiB
TypeScript
|
|
'use server';
|
|
|
|
import { z } from 'zod';
|
|
import db from '@/lib/db';
|
|
import { revalidatePath } from 'next/cache';
|
|
|
|
const emailTemplateSchema = z.object({
|
|
subject: z.string().min(1, 'Subject is required.'),
|
|
body: z.string().min(1, 'Body is required.'),
|
|
});
|
|
|
|
/**
|
|
* Gets the email template from the database.
|
|
*/
|
|
export async function getEmailTemplate(): Promise<{ subject: string; body: string } | null> {
|
|
try {
|
|
const stmt = db.prepare('SELECT subject, body FROM email_templates WHERE id = ?');
|
|
// We assume there is only one template with id = 1
|
|
const template = stmt.get(1) as { subject: string; body: string } | undefined;
|
|
if (!template) {
|
|
return null;
|
|
}
|
|
return template;
|
|
} catch (error) {
|
|
console.error('Failed to get email template:', error);
|
|
// Propagate the error to be handled by the caller
|
|
throw new Error('Database error while fetching email template.');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Updates the email template in the database.
|
|
*/
|
|
export async function updateEmailTemplate(data: { subject: string; body: string }): Promise<{ success: boolean; message: string }> {
|
|
const validation = emailTemplateSchema.safeParse(data);
|
|
if (!validation.success) {
|
|
const errorMessages = validation.error.issues.map(issue => issue.message).join(' ');
|
|
return { success: false, message: `Invalid data provided: ${errorMessages}` };
|
|
}
|
|
|
|
const { subject, body } = validation.data;
|
|
|
|
try {
|
|
const stmt = db.prepare('UPDATE email_templates SET subject = ?, body = ? WHERE id = ?');
|
|
// We assume we're updating the template with id = 1
|
|
const info = stmt.run(subject, body, 1);
|
|
|
|
if (info.changes === 0) {
|
|
return { success: false, message: 'Could not find the template to update. No changes were made.' };
|
|
}
|
|
|
|
revalidatePath('/admin/settings/email-templates');
|
|
return { success: true, message: 'Email template updated successfully!' };
|
|
} catch (error: any) {
|
|
console.error('Failed to update email template:', error);
|
|
return { success: false, message: error.message || 'An unexpected database error occurred.' };
|
|
}
|
|
}
|