Compare commits
5 Commits
42f2a30610
...
features/c
| Author | SHA1 | Date | |
|---|---|---|---|
| eb2cb72ea4 | |||
| 2a0d231597 | |||
| 705a99d415 | |||
| e1440bcea7 | |||
| 6b9e208214 |
5
doc/prompts/11. EmailTemplate CRUD
Normal file
5
doc/prompts/11. EmailTemplate CRUD
Normal 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
|
||||
11
doc/prompts/12 csv import
Normal file
11
doc/prompts/12 csv import
Normal file
@ -0,0 +1,11 @@
|
||||
Please make script to import following csv to Customer model
|
||||
|
||||
City,Name,Website URL,Email
|
||||
"Tokyo","teamLab Planets TOKYO","http://www.teamlab.art/e/planets/","null"
|
||||
"Tokyo","Tokyo National Museum","http://www.tnm.jp/","null"
|
||||
"Tokyo","Nezu Museum","http://www.nezu-muse.or.jp/","null"
|
||||
|
||||
- Name should be unique.
|
||||
- Also if there are same email address skip the row.
|
||||
|
||||
Create new branch features/csvimport and commit when you finished
|
||||
6
package-lock.json
generated
6
package-lock.json
generated
@ -19,6 +19,7 @@
|
||||
"@editorjs/paragraph": "^2.11.7",
|
||||
"@editorjs/quote": "^2.7.6",
|
||||
"bcrypt": "^5.1.1",
|
||||
"csv-parse": "^5.6.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mysql2": "^3.13.0",
|
||||
"next": "15.2.2",
|
||||
@ -2764,6 +2765,11 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/csv-parse": {
|
||||
"version": "5.6.0",
|
||||
"resolved": "https://registry.npmjs.org/csv-parse/-/csv-parse-5.6.0.tgz",
|
||||
"integrity": "sha512-l3nz3euub2QMg5ouu5U09Ew9Wf6/wQ8I++ch1loQ0ljmzhmfZYrH9fflS22i/PQEvsPvxCwxgz5q7UB8K1JO4Q=="
|
||||
},
|
||||
"node_modules/damerau-levenshtein": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",
|
||||
|
||||
@ -8,7 +8,8 @@
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"create-test-user": "npx ts-node -P tsconfig.scripts.json src/scripts/create-test-user.ts",
|
||||
"reset-database": "npx ts-node -P tsconfig.scripts.json src/scripts/reset-database.ts"
|
||||
"reset-database": "npx ts-node -P tsconfig.scripts.json src/scripts/reset-database.ts",
|
||||
"import-customers": "npx ts-node -P tsconfig.scripts.json src/scripts/import-customers.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@editorjs/code": "^2.9.3",
|
||||
@ -22,6 +23,7 @@
|
||||
"@editorjs/paragraph": "^2.11.7",
|
||||
"@editorjs/quote": "^2.7.6",
|
||||
"bcrypt": "^5.1.1",
|
||||
"csv-parse": "^5.6.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mysql2": "^3.13.0",
|
||||
"next": "15.2.2",
|
||||
|
||||
68
src/app/(admin)/admin/email-templates/DeleteButton.tsx
Normal file
68
src/app/(admin)/admin/email-templates/DeleteButton.tsx
Normal 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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
102
src/app/(admin)/admin/email-templates/detail/[id]/page.tsx
Normal file
102
src/app/(admin)/admin/email-templates/detail/[id]/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
6
src/app/(admin)/admin/email-templates/edit/[id]/page.tsx
Normal file
6
src/app/(admin)/admin/email-templates/edit/[id]/page.tsx
Normal 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} />;
|
||||
}
|
||||
5
src/app/(admin)/admin/email-templates/new/page.tsx
Normal file
5
src/app/(admin)/admin/email-templates/new/page.tsx
Normal file
@ -0,0 +1,5 @@
|
||||
import EditEmailTemplate from '../components/EditEmailTemplate';
|
||||
|
||||
export default function NewEmailTemplatePage() {
|
||||
return <EditEmailTemplate />;
|
||||
}
|
||||
106
src/app/(admin)/admin/email-templates/page.tsx
Normal file
106
src/app/(admin)/admin/email-templates/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@ -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">
|
||||
|
||||
118
src/app/api/email-templates/[id]/route.ts
Normal file
118
src/app/api/email-templates/[id]/route.ts
Normal 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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
56
src/app/api/email-templates/route.ts
Normal file
56
src/app/api/email-templates/route.ts
Normal 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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -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',
|
||||
};
|
||||
|
||||
19
src/lib/database/entities/EmailTemplate.ts
Normal file
19
src/lib/database/entities/EmailTemplate.ts
Normal 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;
|
||||
}
|
||||
@ -36,3 +36,4 @@ export * from './entities/User';
|
||||
export * from './entities/Post';
|
||||
export * from './entities/Customer';
|
||||
export * from './entities/ContactRecord';
|
||||
export * from './entities/EmailTemplate';
|
||||
|
||||
108
src/scripts/import-customers.ts
Normal file
108
src/scripts/import-customers.ts
Normal file
@ -0,0 +1,108 @@
|
||||
import 'reflect-metadata';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { parse } from 'csv-parse/sync';
|
||||
import { getDataSource } from '../lib/database';
|
||||
import { Customer } from '../lib/database/entities/Customer';
|
||||
|
||||
interface CustomerCSVRow {
|
||||
City: string;
|
||||
Name: string;
|
||||
'Website URL': string;
|
||||
Email: string;
|
||||
}
|
||||
|
||||
async function importCustomers(csvFilePath: string): Promise<void> {
|
||||
try {
|
||||
// Initialize database connection
|
||||
const dataSource = await getDataSource();
|
||||
const customerRepository = dataSource.getRepository(Customer);
|
||||
|
||||
// Read and parse CSV file
|
||||
const fileContent = fs.readFileSync(csvFilePath, 'utf-8');
|
||||
const records = parse(fileContent, {
|
||||
columns: true,
|
||||
skip_empty_lines: true,
|
||||
trim: true,
|
||||
}) as CustomerCSVRow[];
|
||||
|
||||
console.log(`Found ${records.length} records in CSV file`);
|
||||
|
||||
// Track processed emails to skip duplicates
|
||||
const processedEmails = new Set<string>();
|
||||
// Track existing names to ensure uniqueness
|
||||
const existingNames = new Set<string>(
|
||||
(await customerRepository.find()).map(customer => customer.name)
|
||||
);
|
||||
|
||||
let importedCount = 0;
|
||||
let skippedDuplicateEmail = 0;
|
||||
let skippedDuplicateName = 0;
|
||||
|
||||
for (const record of records) {
|
||||
const email = record.Email === 'null' ? '' : record.Email;
|
||||
const name = record.Name;
|
||||
|
||||
// Skip if email is already processed (not empty and already seen)
|
||||
if (email && processedEmails.has(email)) {
|
||||
console.log(`Skipping record with duplicate email: ${email}`);
|
||||
skippedDuplicateEmail++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if name already exists in database
|
||||
if (existingNames.has(name)) {
|
||||
console.log(`Skipping record with duplicate name: ${name}`);
|
||||
skippedDuplicateName++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Add to processed sets
|
||||
if (email) {
|
||||
processedEmails.add(email);
|
||||
}
|
||||
existingNames.add(name);
|
||||
|
||||
// Create new customer
|
||||
const customer = new Customer();
|
||||
customer.name = name;
|
||||
customer.url = record['Website URL'] === 'null' ? '' : record['Website URL'];
|
||||
customer.email = email;
|
||||
|
||||
// Save to database
|
||||
await customerRepository.save(customer);
|
||||
importedCount++;
|
||||
|
||||
console.log(`Imported customer: ${name}`);
|
||||
}
|
||||
|
||||
console.log('Import summary:');
|
||||
console.log(`- Total records in CSV: ${records.length}`);
|
||||
console.log(`- Successfully imported: ${importedCount}`);
|
||||
console.log(`- Skipped (duplicate email): ${skippedDuplicateEmail}`);
|
||||
console.log(`- Skipped (duplicate name): ${skippedDuplicateName}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error importing customers:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if file path is provided as command line argument
|
||||
const csvFilePath = process.argv[2];
|
||||
if (!csvFilePath) {
|
||||
console.error('Please provide the path to the CSV file as a command line argument');
|
||||
console.error('Example: npm run import-customers -- ./data/customers.csv');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Run the import function
|
||||
importCustomers(csvFilePath)
|
||||
.then(() => {
|
||||
console.log('Import completed successfully');
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Import failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user