1 Commits

Author SHA1 Message Date
ba479a671c save work 2025-03-25 11:29:54 +01:00
11 changed files with 52 additions and 507 deletions

View File

@ -0,0 +1,7 @@
I want add EmailTemplate Model
Tablename: EmailTemplate
id, content, modifiedAt, createdAt
Create branch features/emailtemplate
Make CRUD operation UI in Admin console
Then commit changes

View File

@ -1,5 +0,0 @@
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

@ -1,68 +0,0 @@
'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

@ -1,188 +0,0 @@
'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

@ -1,102 +0,0 @@
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

@ -1,6 +0,0 @@
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

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

View File

@ -1,106 +0,0 @@
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

@ -1,18 +1,18 @@
import { NextRequest, NextResponse } from 'next/server';
import { getDataSource, EmailTemplate } from '@/lib/database';
// GET /api/email-templates/[id] - Get a specific email template
// GET /api/email-templates/[id] - Get a single email template by ID
export async function GET(
request: NextRequest,
props: { params: Promise<{ id: string }> }
{ params }: { params: { id: string } }
) {
try {
const { id } = await props.params;
const { id } = params;
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
const emailTemplate = await emailTemplateRepository.findOne({
where: { id: id }
where: { id }
});
if (!emailTemplate) {
@ -35,16 +35,16 @@ export async function GET(
// PUT /api/email-templates/[id] - Update an email template
export async function PUT(
request: NextRequest,
props: { params: Promise<{ id: string }> }
{ params }: { params: { id: string } }
) {
try {
const { id } = await props.params;
const { id } = params;
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
// Find the email template to update
// Check if email template exists
const emailTemplate = await emailTemplateRepository.findOne({
where: { id: id }
where: { id }
});
if (!emailTemplate) {
@ -54,22 +54,23 @@ export async function PUT(
);
}
// Get update data
const data = await request.json();
const { title, content } = data;
const { name, content } = data;
// Validate required fields
if (!title || !content) {
if (!name && !content) {
return NextResponse.json(
{ error: 'Title and content are required' },
{ error: 'At least one field (name or content) must be provided' },
{ status: 400 }
);
}
// Update email template fields
emailTemplate.title = title;
emailTemplate.content = content;
// Update fields
if (name) emailTemplate.name = name;
if (content) emailTemplate.content = content;
// Save the updated email template
// Save updated email template
const updatedEmailTemplate = await emailTemplateRepository.save(emailTemplate);
return NextResponse.json(updatedEmailTemplate);
@ -85,16 +86,16 @@ export async function PUT(
// DELETE /api/email-templates/[id] - Delete an email template
export async function DELETE(
request: NextRequest,
props: { params: Promise<{ id: string }> }
{ params }: { params: { id: string } }
) {
try {
const { id } = await props.params;
const { id } = params;
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
// Find the email template to delete
// Check if email template exists
const emailTemplate = await emailTemplateRepository.findOne({
where: { id: id }
where: { id }
});
if (!emailTemplate) {
@ -107,7 +108,10 @@ export async function DELETE(
// Delete the email template
await emailTemplateRepository.remove(emailTemplate);
return NextResponse.json({ success: true });
return NextResponse.json(
{ message: 'Email template deleted successfully' },
{ status: 200 }
);
} catch (error) {
console.error('Error deleting email template:', error);
return NextResponse.json(

View File

@ -7,9 +7,23 @@ export async function GET(request: NextRequest) {
const dataSource = await getDataSource();
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
const emailTemplates = await emailTemplateRepository.find({
// Get query parameters
const url = new URL(request.url);
const search = url.searchParams.get('search');
// Build query
const queryOptions: any = {
order: { createdAt: 'DESC' }
});
};
// Add search filter if provided
if (search) {
queryOptions.where = [
{ name: search ? { contains: search } : undefined }
];
}
const emailTemplates = await emailTemplateRepository.find(queryOptions);
return NextResponse.json(emailTemplates);
} catch (error) {
@ -28,19 +42,19 @@ export async function POST(request: NextRequest) {
const emailTemplateRepository = dataSource.getRepository(EmailTemplate);
const data = await request.json();
const { title, content } = data;
const { name, content } = data;
// Validate required fields
if (!title || !content) {
if (!name || !content) {
return NextResponse.json(
{ error: 'Title and content are required' },
{ error: 'Name and content are required' },
{ status: 400 }
);
}
// Create and save the new email template
const emailTemplate = new EmailTemplate();
emailTemplate.title = title;
emailTemplate.name = name;
emailTemplate.content = content;
const savedEmailTemplate = await emailTemplateRepository.save(emailTemplate);

View File

@ -6,7 +6,7 @@ export class EmailTemplate {
id: string;
@Column()
title: string;
name: string;
@Column('text')
content: string;