3 Commits

13 changed files with 684 additions and 3 deletions

View File

@ -0,0 +1,5 @@
Please add model EmailTemplate and make CRUD UI in admin console.
ModelName: EmailTamplate
id, content, modifiedAt, createdAt
create branch features/emailtemplate first and commit changes in the end

View File

@ -0,0 +1,68 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
interface DeleteButtonProps {
templateId: string;
}
export default function DeleteButton({ templateId }: DeleteButtonProps) {
const router = useRouter();
const [isDeleting, setIsDeleting] = useState(false);
const [showConfirm, setShowConfirm] = useState(false);
const handleDelete = async () => {
if (isDeleting) return;
setIsDeleting(true);
try {
const response = await fetch(`/api/email-templates/${templateId}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Failed to delete email template');
}
// Refresh the page to show updated list
router.refresh();
} catch (error) {
console.error('Error deleting email template:', error);
alert('Failed to delete email template');
} finally {
setIsDeleting(false);
setShowConfirm(false);
}
};
return (
<>
{showConfirm ? (
<span className="inline-flex items-center">
<button
onClick={handleDelete}
className="text-red-600 hover:text-red-900 mr-2"
disabled={isDeleting}
>
{isDeleting ? 'Deleting...' : 'Confirm'}
</button>
<button
onClick={() => setShowConfirm(false)}
className="text-gray-600 hover:text-gray-900"
disabled={isDeleting}
>
Cancel
</button>
</span>
) : (
<button
onClick={() => setShowConfirm(true)}
className="text-red-600 hover:text-red-900"
>
Delete
</button>
)}
</>
);
}

View File

@ -0,0 +1,188 @@
'use client';
import { useState, useEffect, FormEvent, ChangeEvent } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
interface EmailTemplate {
id: string;
title: string;
content: string;
createdAt: string;
modifiedAt: string;
}
interface EditEmailTemplateProps {
id?: string; // Optional for new template
}
export default function EditEmailTemplate({ id }: EditEmailTemplateProps) {
const router = useRouter();
const [formData, setFormData] = useState({
title: '',
content: '',
});
const [isLoading, setIsLoading] = useState(!!id); // Only loading if editing
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Fetch email template data if editing
useEffect(() => {
const fetchEmailTemplate = async () => {
if (!id) {
setIsLoading(false);
return;
}
try {
const response = await fetch(`/api/email-templates/${id}`);
if (!response.ok) {
throw new Error('Failed to fetch email template');
}
const template: EmailTemplate = await response.json();
setFormData({
title: template.title,
content: template.content,
});
setIsLoading(false);
} catch (err) {
setError('Failed to load email template data');
setIsLoading(false);
}
};
fetchEmailTemplate();
}, [id]);
const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setFormData((prev) => ({ ...prev, [name]: value }));
};
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
setError(null);
try {
// Validate form
if (!formData.title || !formData.content) {
throw new Error('Title and content are required');
}
// Determine if creating or updating
const url = id ? `/api/email-templates/${id}` : '/api/email-templates';
const method = id ? 'PUT' : 'POST';
// Submit the form
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || `Failed to ${id ? 'update' : 'create'} email template`);
}
// Redirect to email templates list on success
router.push('/admin/email-templates');
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
setIsSubmitting(false);
}
};
if (isLoading) {
return <div className="text-center py-10">Loading...</div>;
}
return (
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-semibold text-gray-900">
{id ? 'Edit Email Template' : 'Add New Email Template'}
</h1>
<Link
href="/admin/email-templates"
className="text-indigo-600 hover:text-indigo-900"
>
Back to Email Templates
</Link>
</div>
{error && (
<div className="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
<div className="flex">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
</div>
<div className="ml-3">
<p className="text-sm text-red-700">{error}</p>
</div>
</div>
</div>
)}
<form onSubmit={handleSubmit} className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="title">
Title
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="title"
type="text"
name="title"
value={formData.title}
onChange={handleChange}
placeholder="Email template title"
required
/>
</div>
<div className="mb-6">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="content">
Content
</label>
<textarea
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="content"
name="content"
value={formData.content}
onChange={handleChange}
placeholder="Email template content"
rows={10}
required
/>
</div>
<div className="flex items-center justify-between">
<button
className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline disabled:opacity-50"
type="submit"
disabled={isSubmitting}
>
{isSubmitting ? (id ? 'Updating...' : 'Creating...') : (id ? 'Update Template' : 'Create Template')}
</button>
<Link
href="/admin/email-templates"
className="inline-block align-baseline font-bold text-sm text-indigo-600 hover:text-indigo-800"
>
Cancel
</Link>
</div>
</form>
</div>
);
}

View File

@ -0,0 +1,102 @@
import Link from 'next/link';
import { getDataSource, EmailTemplate } from '@/lib/database';
export default async function EmailTemplateDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params;
// Fetch email template from the database
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
const emailTemplate = await emailTemplateRepository.findOne({
where: { id }
});
if (!emailTemplate) {
return (
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-semibold text-gray-900">Email Template Not Found</h1>
<Link
href="/admin/email-templates"
className="text-indigo-600 hover:text-indigo-900"
>
Back to Email Templates
</Link>
</div>
<div className="bg-red-50 border-l-4 border-red-400 p-4">
<div className="flex">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
</div>
<div className="ml-3">
<p className="text-sm text-red-700">The requested email template could not be found.</p>
</div>
</div>
</div>
</div>
);
}
return (
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-semibold text-gray-900">Email Template Details</h1>
<div className="flex space-x-4">
<Link
href={`/admin/email-templates/edit/${emailTemplate.id}`}
className="text-indigo-600 hover:text-indigo-900"
>
Edit
</Link>
<Link
href="/admin/email-templates"
className="text-indigo-600 hover:text-indigo-900"
>
Back to Email Templates
</Link>
</div>
</div>
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
<div className="px-4 py-5 sm:px-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">Template Information</h3>
</div>
<div className="border-t border-gray-200">
<dl>
<div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">ID</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{emailTemplate.id}</dd>
</div>
<div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Created At</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{new Date(emailTemplate.createdAt).toLocaleString()}
</dd>
</div>
<div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Modified At</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{new Date(emailTemplate.modifiedAt).toLocaleString()}
</dd>
</div>
<div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Title</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{emailTemplate.title}
</dd>
</div>
<div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Content</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2 whitespace-pre-wrap">
{emailTemplate.content}
</dd>
</div>
</dl>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,6 @@
import EditEmailTemplate from '../../components/EditEmailTemplate';
export default async function EditEmailTemplatePage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params;
return <EditEmailTemplate id={id} />;
}

View File

@ -0,0 +1,5 @@
import EditEmailTemplate from '../components/EditEmailTemplate';
export default function NewEmailTemplatePage() {
return <EditEmailTemplate />;
}

View File

@ -0,0 +1,106 @@
import Link from 'next/link';
import { getDataSource, EmailTemplate } from '@/lib/database';
import DeleteButton from './DeleteButton';
export default async function AdminEmailTemplates() {
// Fetch email templates from the database
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
const emailTemplates = await emailTemplateRepository.find({
order: { createdAt: 'DESC' }
});
return (
<div>
<div className="flex justify-between items-center">
<h1 className="text-2xl font-semibold text-gray-900">Email Templates</h1>
<Link
href="/admin/email-templates/new"
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
Add New Template
</Link>
</div>
<div className="mt-8 flex flex-col">
<div className="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
<div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
<table className="min-w-full divide-y divide-gray-300">
<thead className="bg-gray-50">
<tr>
<th
scope="col"
className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
style={{ width: "60%" }}
>
Title
</th>
<th
scope="col"
className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
style={{ width: "10%" }}
>
Created
</th>
<th
scope="col"
className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
style={{ width: "10%" }}
>
Modified
</th>
<th scope="col" className="relative py-3.5 pl-3 pr-4 sm:pr-6" style={{ width: "15%" }}>
<span className="sr-only">Actions</span>
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200 bg-white">
{emailTemplates.length > 0 ? (
emailTemplates.map((template) => (
<tr key={template.id}>
<td className="py-4 px-3 text-sm text-gray-500">
<Link
href={`/admin/email-templates/detail/${template.id}`}
className="text-indigo-600 hover:text-indigo-900"
>
{template.title}
</Link>
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{new Date(template.createdAt).toLocaleDateString()}
{new Date(template.createdAt).toLocaleTimeString()}
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{new Date(template.modifiedAt).toLocaleDateString()}
{new Date(template.modifiedAt).toLocaleTimeString()}
</td>
<td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
<Link
href={`/admin/email-templates/edit/${template.id}`}
className="text-indigo-600 hover:text-indigo-900 mr-4"
>
Edit
</Link>
<DeleteButton templateId={template.id} />
</td>
</tr>
))
) : (
<tr>
<td colSpan={5} className="py-4 pl-4 pr-3 text-sm text-gray-500 text-center">
No email templates found. Create your first template!
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@ -112,6 +112,12 @@ export default function RootLayout({
>
Contact Records
</Link>
<Link
href="/admin/email-templates"
className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
>
Email Templates
</Link>
</div>
</div>
<div className="hidden sm:ml-6 sm:flex sm:items-center">

View File

@ -0,0 +1,118 @@
import { NextRequest, NextResponse } from 'next/server';
import { getDataSource, EmailTemplate } from '@/lib/database';
// GET /api/email-templates/[id] - Get a specific email template
export async function GET(
request: NextRequest,
props: { params: Promise<{ id: string }> }
) {
try {
const { id } = await props.params;
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
const emailTemplate = await emailTemplateRepository.findOne({
where: { id: id }
});
if (!emailTemplate) {
return NextResponse.json(
{ error: 'Email template not found' },
{ status: 404 }
);
}
return NextResponse.json(emailTemplate);
} catch (error) {
console.error('Error fetching email template:', error);
return NextResponse.json(
{ error: 'Failed to fetch email template' },
{ status: 500 }
);
}
}
// PUT /api/email-templates/[id] - Update an email template
export async function PUT(
request: NextRequest,
props: { params: Promise<{ id: string }> }
) {
try {
const { id } = await props.params;
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
// Find the email template to update
const emailTemplate = await emailTemplateRepository.findOne({
where: { id: id }
});
if (!emailTemplate) {
return NextResponse.json(
{ error: 'Email template not found' },
{ status: 404 }
);
}
const data = await request.json();
const { title, content } = data;
// Validate required fields
if (!title || !content) {
return NextResponse.json(
{ error: 'Title and content are required' },
{ status: 400 }
);
}
// Update email template fields
emailTemplate.title = title;
emailTemplate.content = content;
// Save the updated email template
const updatedEmailTemplate = await emailTemplateRepository.save(emailTemplate);
return NextResponse.json(updatedEmailTemplate);
} catch (error) {
console.error('Error updating email template:', error);
return NextResponse.json(
{ error: 'Failed to update email template' },
{ status: 500 }
);
}
}
// DELETE /api/email-templates/[id] - Delete an email template
export async function DELETE(
request: NextRequest,
props: { params: Promise<{ id: string }> }
) {
try {
const { id } = await props.params;
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
// Find the email template to delete
const emailTemplate = await emailTemplateRepository.findOne({
where: { id: id }
});
if (!emailTemplate) {
return NextResponse.json(
{ error: 'Email template not found' },
{ status: 404 }
);
}
// Delete the email template
await emailTemplateRepository.remove(emailTemplate);
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting email template:', error);
return NextResponse.json(
{ error: 'Failed to delete email template' },
{ status: 500 }
);
}
}

View File

@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from 'next/server';
import { getDataSource, EmailTemplate } from '@/lib/database';
// GET /api/email-templates - Get all email templates
export async function GET(request: NextRequest) {
try {
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
const emailTemplates = await emailTemplateRepository.find({
order: { createdAt: 'DESC' }
});
return NextResponse.json(emailTemplates);
} catch (error) {
console.error('Error fetching email templates:', error);
return NextResponse.json(
{ error: 'Failed to fetch email templates' },
{ status: 500 }
);
}
}
// POST /api/email-templates - Create a new email template
export async function POST(request: NextRequest) {
try {
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
const data = await request.json();
const { title, content } = data;
// Validate required fields
if (!title || !content) {
return NextResponse.json(
{ error: 'Title and content are required' },
{ status: 400 }
);
}
// Create and save the new email template
const emailTemplate = new EmailTemplate();
emailTemplate.title = title;
emailTemplate.content = content;
const savedEmailTemplate = await emailTemplateRepository.save(emailTemplate);
return NextResponse.json(savedEmailTemplate, { status: 201 });
} catch (error) {
console.error('Error creating email template:', error);
return NextResponse.json(
{ error: 'Failed to create email template' },
{ status: 500 }
);
}
}

View File

@ -3,13 +3,14 @@ import { User } from './entities/User';
import { Post } from './entities/Post';
import { Customer } from './entities/Customer';
import { ContactRecord } from './entities/ContactRecord';
import { EmailTemplate } from './entities/EmailTemplate';
import path from 'path';
// Default configuration for SQLite (development/testing)
const sqliteConfig: DataSourceOptions = {
type: 'sqlite',
database: path.join(process.cwd(), 'data', 'database.sqlite'),
entities: [User, Post, Customer, ContactRecord],
entities: [User, Post, Customer, ContactRecord, EmailTemplate],
synchronize: true, // Set to false in production
logging: process.env.NODE_ENV === 'development',
};
@ -22,7 +23,7 @@ const mysqlConfig: DataSourceOptions = {
username: process.env.DB_USERNAME || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_DATABASE || 'kantancms',
entities: [User, Post, Customer, ContactRecord],
entities: [User, Post, Customer, ContactRecord, EmailTemplate],
synchronize: false, // Always false in production
logging: process.env.NODE_ENV === 'development',
};
@ -35,7 +36,7 @@ const postgresConfig: DataSourceOptions = {
username: process.env.DB_USERNAME || 'postgres',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_DATABASE || 'kantancms',
entities: [User, Post, Customer, ContactRecord],
entities: [User, Post, Customer, ContactRecord, EmailTemplate],
synchronize: false, // Always false in production
logging: process.env.NODE_ENV === 'development',
};

View File

@ -0,0 +1,19 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
@Entity('email_templates')
export class EmailTemplate {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
title: string;
@Column('text')
content: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
modifiedAt: Date;
}

View File

@ -36,3 +36,4 @@ export * from './entities/User';
export * from './entities/Post';
export * from './entities/Customer';
export * from './entities/ContactRecord';
export * from './entities/EmailTemplate';