the email template itself has to be able to get modified by admin

This commit is contained in:
Leon Serfaty G
2025-07-18 03:21:13 +00:00
parent c56316c740
commit 4cf4c0ccbe
3 changed files with 210 additions and 22 deletions
+54
View File
@@ -0,0 +1,54 @@
'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);
return null;
}
}
/**
* 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
stmt.run(subject, body, 1);
revalidatePath('/admin/settings/email-templates');
return { success: true, message: 'Email template updated successfully!' };
} catch (error) {
console.error('Failed to update email template:', error);
return { success: false, message: 'An unexpected error occurred.' };
}
}