5 Commits

15 changed files with 635 additions and 53 deletions

View File

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

@ -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
View 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
View File

@ -19,6 +19,7 @@
"@editorjs/paragraph": "^2.11.7", "@editorjs/paragraph": "^2.11.7",
"@editorjs/quote": "^2.7.6", "@editorjs/quote": "^2.7.6",
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"csv-parse": "^5.6.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"mysql2": "^3.13.0", "mysql2": "^3.13.0",
"next": "15.2.2", "next": "15.2.2",
@ -2764,6 +2765,11 @@
"dev": true, "dev": true,
"license": "MIT" "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": { "node_modules/damerau-levenshtein": {
"version": "1.0.8", "version": "1.0.8",
"resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",

View File

@ -8,7 +8,8 @@
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "next lint",
"create-test-user": "npx ts-node -P tsconfig.scripts.json src/scripts/create-test-user.ts", "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": { "dependencies": {
"@editorjs/code": "^2.9.3", "@editorjs/code": "^2.9.3",
@ -22,6 +23,7 @@
"@editorjs/paragraph": "^2.11.7", "@editorjs/paragraph": "^2.11.7",
"@editorjs/quote": "^2.7.6", "@editorjs/quote": "^2.7.6",
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"csv-parse": "^5.6.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"mysql2": "^3.13.0", "mysql2": "^3.13.0",
"next": "15.2.2", "next": "15.2.2",

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

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

View File

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

View File

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

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