5 Commits

Author SHA1 Message Date
705a99d415 update list ui 2025-03-25 12:04:39 +01:00
e1440bcea7 Add title field to EmailTemplate model and update UI 2025-03-25 11:43:47 +01:00
6b9e208214 Add EmailTemplate model and CRUD UI in admin console 2025-03-25 11:40:45 +01:00
42f2a30610 contact recoreds done 2025-03-25 08:12:33 +01:00
c9751b058f contact recoed list 2025-03-25 07:08:43 +01:00
19 changed files with 1077 additions and 23 deletions

View File

@ -0,0 +1,5 @@
I want add list page for Contact Recored.
- Add link to contact recored list page to admin console headder
- Users can see customer name, contact type, and notes
- Users can click on customer name then opens the customer detail
- Users can filter by customer, date ( from - to )

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

@ -3,6 +3,7 @@
import { useState, useEffect, FormEvent, ChangeEvent } from 'react'; import { useState, useEffect, FormEvent, ChangeEvent } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { CONTACT_TYPES } from '@/lib/constants';
interface ContactRecord { interface ContactRecord {
id: string; id: string;
@ -125,7 +126,7 @@ export default function EditContactRecord({ id }: EditContactRecordProps) {
return ( return (
<div> <div>
<div className="flex justify-between items-center mb-6"> <div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-semibold text-gray-900">Edit Contact Record</h1> <h1 className="text-2xl font-semibold text-gray-900 dark:text-gray-100">Edit Contact Record</h1>
<Link <Link
href={`/admin/customers/detail/${customerId}`} href={`/admin/customers/detail/${customerId}`}
className="text-indigo-600 hover:text-indigo-900" className="text-indigo-600 hover:text-indigo-900"
@ -135,33 +136,33 @@ export default function EditContactRecord({ id }: EditContactRecordProps) {
</div> </div>
{error && ( {error && (
<div className="bg-red-50 border-l-4 border-red-400 p-4 mb-6"> <div className="bg-red-50 border-l-4 border-red-400 p-4 mb-6 dark:bg-red-900/20 dark:border-red-500">
<div className="flex"> <div className="flex">
<div className="flex-shrink-0"> <div className="flex-shrink-0">
<svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor"> <svg className="h-5 w-5 text-red-400 dark:text-red-300" 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" /> <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> </svg>
</div> </div>
<div className="ml-3"> <div className="ml-3">
<p className="text-sm text-red-700">{error}</p> <p className="text-sm text-red-700 dark:text-red-300">{error}</p>
</div> </div>
</div> </div>
</div> </div>
)} )}
<div className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"> <div className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4 dark:bg-gray-800">
<div className="mb-6"> <div className="mb-6">
<label className="block text-gray-700 text-sm font-bold mb-2"> <label className="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2">
Customer Customer
</label> </label>
<div className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight"> <div className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 dark:text-gray-200 dark:bg-gray-700 dark:border-gray-600 leading-tight">
{customerName} {customerName}
</div> </div>
</div> </div>
<form onSubmit={handleSubmit} className="space-y-4"> <form onSubmit={handleSubmit} className="space-y-4">
<div> <div>
<label htmlFor="contactType" className="block text-gray-700 text-sm font-bold mb-2"> <label htmlFor="contactType" className="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2">
Contact Type Contact Type
</label> </label>
<select <select
@ -169,19 +170,20 @@ export default function EditContactRecord({ id }: EditContactRecordProps) {
name="contactType" name="contactType"
value={formData.contactType} value={formData.contactType}
onChange={handleChange} onChange={handleChange}
className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md" className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
required required
> >
<option value="">Select a contact type</option> <option value="">Select a contact type</option>
<option value="Email">Email</option> {CONTACT_TYPES.map((type) => (
<option value="Phone">Phone</option> <option key={type.value} value={type.value}>
<option value="Meeting">Meeting</option> {type.label}
<option value="Other">Other</option> </option>
))}
</select> </select>
</div> </div>
<div> <div>
<label htmlFor="notes" className="block text-gray-700 text-sm font-bold mb-2"> <label htmlFor="notes" className="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2">
Notes Notes
</label> </label>
<textarea <textarea
@ -190,7 +192,7 @@ export default function EditContactRecord({ id }: EditContactRecordProps) {
rows={4} rows={4}
value={formData.notes} value={formData.notes}
onChange={handleChange} onChange={handleChange}
className="mt-1 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md" className="mt-1 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
placeholder="Enter notes about the contact" placeholder="Enter notes about the contact"
></textarea> ></textarea>
</div> </div>

View File

@ -0,0 +1,317 @@
'use client';
import { useState, useEffect, FormEvent } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { CONTACT_TYPES } from '@/lib/constants';
interface Customer {
id: string;
name: string;
}
interface ContactRecord {
id: string;
customerId: string;
contactType: string;
notes: string;
createdAt: string;
customer: Customer;
}
export default function ContactRecordsList() {
const router = useRouter();
const searchParams = useSearchParams();
// Get filter values from URL params
const initialCustomerId = searchParams.get('customerId') || '';
const initialContactType = searchParams.get('contactType') || '';
const initialDateFrom = searchParams.get('dateFrom') || '';
const initialDateTo = searchParams.get('dateTo') || '';
// State for filters
const [customerId, setCustomerId] = useState(initialCustomerId);
const [contactType, setContactType] = useState(initialContactType);
const [dateFrom, setDateFrom] = useState(initialDateFrom);
const [dateTo, setDateTo] = useState(initialDateTo);
// State for data
const [contactRecords, setContactRecords] = useState<ContactRecord[]>([]);
const [customers, setCustomers] = useState<Customer[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Fetch customers for the filter dropdown
useEffect(() => {
const fetchCustomers = async () => {
try {
const response = await fetch('/api/customers');
if (!response.ok) {
throw new Error('Failed to fetch customers');
}
const data = await response.json();
setCustomers(data);
} catch (err) {
console.error('Error fetching customers:', err);
setError(err instanceof Error ? err.message : 'An error occurred');
}
};
fetchCustomers();
}, []);
// Fetch contact records with filters
useEffect(() => {
const fetchContactRecords = async () => {
setIsLoading(true);
setError(null);
try {
// Build query string with filters
const params = new URLSearchParams();
if (customerId) params.append('customerId', customerId);
if (contactType) params.append('contactType', contactType);
if (dateFrom) params.append('dateFrom', dateFrom);
if (dateTo) params.append('dateTo', dateTo);
const response = await fetch(`/api/contact-records?${params.toString()}`);
if (!response.ok) {
throw new Error('Failed to fetch contact records');
}
const data = await response.json();
setContactRecords(data);
} catch (err) {
console.error('Error fetching contact records:', err);
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setIsLoading(false);
}
};
// Only fetch if we have URL parameters or if this is the initial load
if (initialCustomerId || initialContactType || initialDateFrom || initialDateTo || isLoading) {
fetchContactRecords();
}
}, [initialCustomerId, initialContactType, initialDateFrom, initialDateTo]);
// Handle filter form submission
const handleFilterSubmit = (e: FormEvent) => {
e.preventDefault();
// Build query string with filters
const params = new URLSearchParams();
if (customerId) params.append('customerId', customerId);
if (contactType) params.append('contactType', contactType);
if (dateFrom) params.append('dateFrom', dateFrom);
if (dateTo) params.append('dateTo', dateTo);
// Update URL with filters
router.push(`/admin/contact-records?${params.toString()}`);
};
// Handle filter reset
const handleReset = () => {
setCustomerId('');
setContactType('');
setDateFrom('');
setDateTo('');
router.push('/admin/contact-records');
};
return (
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-semibold text-gray-900 dark:text-gray-100">Contact Records</h1>
</div>
{/* Filter Form */}
<div className="bg-white dark:bg-gray-800 shadow overflow-hidden sm:rounded-lg mb-8">
<div className="px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-gray-700">
<h3 className="text-lg leading-6 font-medium text-gray-900 dark:text-gray-100">Filter Contact Records</h3>
</div>
<div className="px-4 py-5 sm:p-6">
<form onSubmit={handleFilterSubmit} className="space-y-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-4">
<div>
<label htmlFor="customerId" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Customer
</label>
<select
id="customerId"
name="customerId"
value={customerId}
onChange={(e) => setCustomerId(e.target.value)}
className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:bg-gray-800 dark:border-gray-700 dark:text-gray-200"
>
<option value="">All Customers</option>
{customers.map((customer) => (
<option key={customer.id} value={customer.id}>
{customer.name}
</option>
))}
</select>
</div>
<div>
<label htmlFor="contactType" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Contact Type
</label>
<select
id="contactType"
name="contactType"
value={contactType}
onChange={(e) => setContactType(e.target.value)}
className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:bg-gray-800 dark:border-gray-700 dark:text-gray-200"
>
<option value="">All Contact Types</option>
{CONTACT_TYPES.map((type) => (
<option key={type.value} value={type.value}>
{type.label}
</option>
))}
</select>
</div>
<div>
<label htmlFor="dateFrom" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Date From
</label>
<input
type="date"
id="dateFrom"
name="dateFrom"
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:bg-gray-800 dark:border-gray-700 dark:text-gray-200"
/>
</div>
<div>
<label htmlFor="dateTo" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Date To
</label>
<input
type="date"
id="dateTo"
name="dateTo"
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:bg-gray-800 dark:border-gray-700 dark:text-gray-200"
/>
</div>
</div>
<div className="flex justify-end space-x-3">
<button
type="button"
onClick={handleReset}
className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600 dark:hover:bg-gray-600"
>
Reset
</button>
<button
type="submit"
className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
Filter
</button>
</div>
</form>
</div>
</div>
{/* Error Message */}
{error && (
<div className="bg-red-50 border-l-4 border-red-400 p-4 mb-4 dark:bg-red-900/20 dark:border-red-500">
<div className="flex">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-red-400 dark:text-red-300" 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 dark:text-red-300">{error}</p>
</div>
</div>
</div>
)}
{/* Loading State */}
{isLoading ? (
<div className="text-center py-8">
<p className="text-gray-500 dark:text-gray-400">Loading contact records...</p>
</div>
) : (
<>
{/* Contact Records Table */}
{contactRecords.length === 0 ? (
<div className="bg-white dark:bg-gray-800 shadow overflow-hidden sm:rounded-lg">
<div className="px-4 py-5 sm:p-6 text-center">
<p className="text-gray-500 dark:text-gray-400">No contact records found.</p>
</div>
</div>
) : (
<div className="bg-white dark:bg-gray-800 shadow overflow-hidden sm:rounded-lg">
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-700">
<tr>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
Customer
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
Contact Type
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
Notes
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
Date
</th>
<th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{contactRecords.map((record) => (
<tr key={record.id}>
<td className="px-6 py-4 whitespace-nowrap">
<Link
href={`/admin/customers/detail/${record.customerId}`}
className="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300"
>
{record.customer?.name || 'Unknown Customer'}
</Link>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">
{record.contactType}
</span>
</td>
<td className="px-6 py-4">
<div className="text-sm text-gray-900 dark:text-gray-200 max-w-xs truncate">
{record.notes || <span className="text-gray-400 dark:text-gray-500 italic">No notes</span>}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{new Date(record.createdAt).toLocaleString()}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<Link
href={`/admin/contact-records/edit/${record.id}`}
className="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 mr-4"
>
Edit
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</>
)}
</div>
);
}

View File

@ -2,6 +2,7 @@
import { useState, FormEvent, ChangeEvent } from 'react'; import { useState, FormEvent, ChangeEvent } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { CONTACT_TYPES } from '@/lib/constants';
interface NewContactRecordFormProps { interface NewContactRecordFormProps {
customerId: string; customerId: string;
@ -119,10 +120,11 @@ export default function NewContactRecordForm({ customerId }: NewContactRecordFor
required required
> >
<option value="">Select a contact type</option> <option value="">Select a contact type</option>
<option value="Email">Email</option> {CONTACT_TYPES.map((type) => (
<option value="Phone">Phone</option> <option key={type.value} value={type.value}>
<option value="Meeting">Meeting</option> {type.label}
<option value="Other">Other</option> </option>
))}
</select> </select>
</div> </div>

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

@ -106,6 +106,18 @@ export default function RootLayout({
> >
Customers Customers
</Link> </Link>
<Link
href="/admin/contact-records"
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"
>
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> </div>
<div className="hidden sm:ml-6 sm:flex sm:items-center"> <div className="hidden sm:ml-6 sm:flex sm:items-center">

View File

@ -10,6 +10,9 @@ export async function GET(request: NextRequest) {
// Get query parameters // Get query parameters
const url = new URL(request.url); const url = new URL(request.url);
const customerId = url.searchParams.get('customerId'); const customerId = url.searchParams.get('customerId');
const contactType = url.searchParams.get('contactType');
const dateFrom = url.searchParams.get('dateFrom');
const dateTo = url.searchParams.get('dateTo');
// Build query // Build query
const queryOptions: any = { const queryOptions: any = {
@ -17,9 +20,38 @@ export async function GET(request: NextRequest) {
relations: ['customer'] relations: ['customer']
}; };
// Build where clause
let whereClause: any = {};
// Filter by customer if customerId is provided // Filter by customer if customerId is provided
if (customerId) { if (customerId) {
queryOptions.where = { customerId }; whereClause.customerId = customerId;
}
// Filter by contact type if provided
if (contactType) {
whereClause.contactType = contactType;
}
// Filter by date range if provided
if (dateFrom || dateTo) {
whereClause.createdAt = {};
if (dateFrom) {
whereClause.createdAt.gte = new Date(dateFrom);
}
if (dateTo) {
// Set the date to the end of the day for inclusive filtering
const endDate = new Date(dateTo);
endDate.setHours(23, 59, 59, 999);
whereClause.createdAt.lte = endDate;
}
}
// Add where clause to query options if not empty
if (Object.keys(whereClause).length > 0) {
queryOptions.where = whereClause;
} }
const contactRecords = await contactRecordRepository.find(queryOptions); const contactRecords = await contactRecordRepository.find(queryOptions);

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 }
);
}
}

9
src/lib/constants.ts Normal file
View File

@ -0,0 +1,9 @@
// Contact record types
export const CONTACT_TYPES = [
{ value: 'Email', label: 'Email' },
{ value: 'EmailSent', label: 'Email sent' },
{ value: 'EmailReceived', label: 'Email received' },
{ value: 'Phone', label: 'Phone' },
{ value: 'Meeting', label: 'Meeting' },
{ value: 'Other', label: 'Other' }
];

View File

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