add customer

This commit is contained in:
Ken Yasue
2025-03-25 06:36:23 +01:00
parent 9aef2ad891
commit 4e9d81924a
15 changed files with 671 additions and 3 deletions

View File

@ -0,0 +1,57 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
interface DeleteButtonProps {
customerId: string;
customerName: string;
}
export default function DeleteButton({ customerId, customerName }: DeleteButtonProps) {
const [isDeleting, setIsDeleting] = useState(false);
const [error, setError] = useState<string | null>(null);
const router = useRouter();
const handleDelete = async () => {
if (!confirm(`Are you sure you want to delete customer "${customerName}"?`)) {
return;
}
setIsDeleting(true);
setError(null);
try {
const response = await fetch(`/api/customers/${customerId}`, {
method: 'DELETE',
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || 'Failed to delete customer');
}
// Refresh the page to show updated customer list
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setIsDeleting(false);
}
};
return (
<>
<button
className="text-red-600 hover:text-red-900 disabled:opacity-50"
onClick={handleDelete}
disabled={isDeleting}
>
{isDeleting ? 'Deleting...' : 'Delete'}
</button>
{error && (
<div className="text-red-500 text-xs mt-1">{error}</div>
)}
</>
);
}

View File

@ -0,0 +1,206 @@
'use client';
import { useState, useEffect, FormEvent, ChangeEvent } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
interface Customer {
id: string;
name: string;
url: string;
email: string;
createdAt: string;
modifiedAt: string;
}
interface EditCustomerProps {
id?: string; // Optional for new customer
}
export default function EditCustomer({ id }: EditCustomerProps) {
const router = useRouter();
const [formData, setFormData] = useState({
name: '',
url: '',
email: '',
});
const [isLoading, setIsLoading] = useState(!!id); // Only loading if editing
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Fetch customer data if editing
useEffect(() => {
const fetchCustomer = async () => {
if (!id) {
setIsLoading(false);
return;
}
try {
const response = await fetch(`/api/customers/${id}`);
if (!response.ok) {
throw new Error('Failed to fetch customer');
}
const customer: Customer = await response.json();
setFormData({
name: customer.name,
url: customer.url || '',
email: customer.email,
});
setIsLoading(false);
} catch (err) {
setError('Failed to load customer data');
setIsLoading(false);
}
};
fetchCustomer();
}, [id]);
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
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.name || !formData.email) {
throw new Error('Name and email are required');
}
// Determine if creating or updating
const url = id ? `/api/customers/${id}` : '/api/customers';
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'} customer`);
}
// Redirect to customers list on success
router.push('/admin/customers');
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 Customer' : 'Add New Customer'}
</h1>
<Link
href="/admin/customers"
className="text-indigo-600 hover:text-indigo-900"
>
Back to Customers
</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="name">
Name
</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="name"
type="text"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Customer Name"
required
/>
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="url">
URL
</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="url"
type="text"
name="url"
value={formData.url}
onChange={handleChange}
placeholder="Website URL (optional)"
/>
</div>
<div className="mb-6">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="email">
Email
</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="email"
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email Address"
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 Customer' : 'Create Customer')}
</button>
<Link
href="/admin/customers"
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,6 @@
import EditCustomer from '../../components/EditCustomer';
export default async function EditCustomerPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params;
return <EditCustomer id={id} />;
}

View File

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

View File

@ -0,0 +1,129 @@
import Link from 'next/link';
import { getDataSource, Customer } from '@/lib/database';
import DeleteButton from './DeleteButton';
export default async function AdminCustomers() {
// Fetch customers from the database
const dataSource = await getDataSource();
const customerRepository = dataSource.getRepository(Customer);
const customers = await customerRepository.find({
order: { createdAt: 'DESC' }
});
return (
<div>
<div className="flex justify-between items-center">
<h1 className="text-2xl font-semibold text-gray-900">Customers</h1>
<Link
href="/admin/customers/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 Customer
</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="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6"
>
Name
</th>
<th
scope="col"
className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
>
URL
</th>
<th
scope="col"
className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
>
Email
</th>
<th
scope="col"
className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
>
Created
</th>
<th
scope="col"
className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"
>
Modified
</th>
<th scope="col" className="relative py-3.5 pl-3 pr-4 sm:pr-6">
<span className="sr-only">Actions</span>
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200 bg-white">
{customers.length > 0 ? (
customers.map((customer) => (
<tr key={customer.id}>
<td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">
{customer.name}
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{customer.url ? (
<a
href={customer.url.startsWith('http') ? customer.url : `https://${customer.url}`}
target="_blank"
rel="noopener noreferrer"
className="text-indigo-600 hover:text-indigo-900"
>
{customer.url}
</a>
) : (
<span className="text-gray-400">-</span>
)}
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
<a
href={`mailto:${customer.email}`}
className="text-indigo-600 hover:text-indigo-900"
>
{customer.email}
</a>
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{new Date(customer.createdAt).toLocaleDateString()}
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{new Date(customer.modifiedAt).toLocaleDateString()}
</td>
<td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
<Link
href={`/admin/customers/edit/${customer.id}`}
className="text-indigo-600 hover:text-indigo-900 mr-4"
>
Edit
</Link>
<DeleteButton customerId={customer.id} customerName={customer.name} />
</td>
</tr>
))
) : (
<tr>
<td colSpan={6} className="py-4 pl-4 pr-3 text-sm text-gray-500 text-center">
No customers found. Create your first customer!
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
);
}

View File

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

View File

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

View File

@ -0,0 +1,57 @@
import { NextRequest, NextResponse } from 'next/server';
import { getDataSource, Customer } from '@/lib/database';
// GET /api/customers - Get all customers
export async function GET(request: NextRequest) {
try {
const dataSource = await getDataSource();
const customerRepository = dataSource.getRepository(Customer);
const customers = await customerRepository.find({
order: { createdAt: 'DESC' }
});
return NextResponse.json(customers);
} catch (error) {
console.error('Error fetching customers:', error);
return NextResponse.json(
{ error: 'Failed to fetch customers' },
{ status: 500 }
);
}
}
// POST /api/customers - Create a new customer
export async function POST(request: NextRequest) {
try {
const dataSource = await getDataSource();
const customerRepository = dataSource.getRepository(Customer);
const data = await request.json();
const { name, url, email } = data;
// Validate required fields
if (!name || !email) {
return NextResponse.json(
{ error: 'Name and email are required' },
{ status: 400 }
);
}
// Create and save the new customer
const customer = new Customer();
customer.name = name;
customer.url = url || '';
customer.email = email;
const savedCustomer = await customerRepository.save(customer);
return NextResponse.json(savedCustomer, { status: 201 });
} catch (error) {
console.error('Error creating customer:', error);
return NextResponse.json(
{ error: 'Failed to create customer' },
{ status: 500 }
);
}
}