feat: add annotation types management system

- Created annotation_types table with name, display_name, color, category, icon
- Implemented CRUD API endpoints for annotation types management
- Built annotation types management UI page at /annotation-types
- Updated Toolbox component to dynamically load and display annotation types
- Updated CandleChart component to use dynamic annotation types for markers
- Added seed functionality for default types (break_up, break_down, line)
- Cleaned up duplicate migration files
This commit is contained in:
Marko Djordjevic 2026-02-12 18:16:09 +01:00
parent 50229e2ccf
commit 974d9f5598
13 changed files with 942 additions and 79 deletions

View file

@ -0,0 +1,390 @@
'use client';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
type AnnotationType = {
id: number;
name: string;
display_name: string;
color: string;
category: string;
icon: string | null;
is_active: number;
created_at: number;
};
export default function AnnotationTypesPage() {
const [types, setTypes] = useState<AnnotationType[]>([]);
const [loading, setLoading] = useState(true);
const [editingId, setEditingId] = useState<number | null>(null);
const [showAddForm, setShowAddForm] = useState(false);
// Form state
const [formData, setFormData] = useState({
name: '',
display_name: '',
color: '#3b82f6',
category: 'marker',
icon: '',
});
const fetchTypes = async () => {
try {
const res = await fetch('/api/annotation-types');
if (res.ok) {
const data = await res.json();
setTypes(data);
}
} catch (error) {
console.error('Error fetching annotation types:', error);
} finally {
setLoading(false);
}
};
const seedDefaultTypes = async () => {
try {
const res = await fetch('/api/annotation-types', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'seed' }),
});
if (res.ok) {
fetchTypes();
}
} catch (error) {
console.error('Error seeding types:', error);
}
};
useEffect(() => {
fetchTypes();
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
if (editingId !== null) {
// Update existing type
const res = await fetch(`/api/annotation-types/${editingId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
if (res.ok) {
setEditingId(null);
resetForm();
fetchTypes();
} else {
const error = await res.json();
alert(error.error || 'Failed to update type');
}
} else {
// Create new type
const res = await fetch('/api/annotation-types', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
if (res.ok) {
setShowAddForm(false);
resetForm();
fetchTypes();
} else {
const error = await res.json();
alert(error.error || 'Failed to create type');
}
}
} catch (error) {
console.error('Error saving type:', error);
alert('Failed to save type');
}
};
const handleEdit = (type: AnnotationType) => {
setFormData({
name: type.name,
display_name: type.display_name,
color: type.color,
category: type.category,
icon: type.icon || '',
});
setEditingId(type.id);
setShowAddForm(true);
};
const handleDelete = async (id: number) => {
if (!confirm('Are you sure you want to delete this annotation type?')) {
return;
}
try {
const res = await fetch(`/api/annotation-types?id=${id}`, {
method: 'DELETE',
});
if (res.ok) {
fetchTypes();
} else {
const error = await res.json();
alert(error.error || 'Failed to delete type');
}
} catch (error) {
console.error('Error deleting type:', error);
alert('Failed to delete type');
}
};
const resetForm = () => {
setFormData({
name: '',
display_name: '',
color: '#3b82f6',
category: 'marker',
icon: '',
});
setEditingId(null);
};
const handleCancel = () => {
setShowAddForm(false);
resetForm();
};
if (loading) {
return (
<div className="min-h-screen bg-gray-50 p-8">
<div className="max-w-6xl mx-auto">
<p>Loading...</p>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 p-8">
<div className="max-w-6xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Annotation Types</h1>
<p className="text-gray-600 mt-1">Manage annotation types for your charts</p>
</div>
<div className="flex gap-2">
<Button onClick={() => window.location.href = '/'} variant="outline">
Back to Chart
</Button>
{types.length === 0 && (
<Button onClick={seedDefaultTypes}>
Seed Default Types
</Button>
)}
{!showAddForm && (
<Button onClick={() => setShowAddForm(true)}>
Add New Type
</Button>
)}
</div>
</div>
{showAddForm && (
<div className="bg-white p-6 rounded-lg shadow mb-6">
<h2 className="text-xl font-semibold mb-4">
{editingId !== null ? 'Edit Annotation Type' : 'Add New Annotation Type'}
</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Internal Name *
</label>
<Input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="e.g., break_up"
required
disabled={editingId !== null}
/>
<p className="text-xs text-gray-500 mt-1">
Used internally (cannot be changed after creation)
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Display Name *
</label>
<Input
type="text"
value={formData.display_name}
onChange={(e) => setFormData({ ...formData, display_name: e.target.value })}
placeholder="e.g., Break Up"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Color *
</label>
<div className="flex gap-2">
<Input
type="color"
value={formData.color}
onChange={(e) => setFormData({ ...formData, color: e.target.value })}
className="w-20"
required
/>
<Input
type="text"
value={formData.color}
onChange={(e) => setFormData({ ...formData, color: e.target.value })}
placeholder="#3b82f6"
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Category *
</label>
<select
value={formData.category}
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-md"
required
>
<option value="marker">Marker</option>
<option value="line">Line</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Icon
</label>
<Input
type="text"
value={formData.icon}
onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
placeholder="e.g., arrowUp"
/>
</div>
</div>
<div className="flex gap-2">
<Button type="submit">
{editingId !== null ? 'Update' : 'Create'}
</Button>
<Button type="button" variant="outline" onClick={handleCancel}>
Cancel
</Button>
</div>
</form>
</div>
)}
<div className="bg-white rounded-lg shadow overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Display Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Color
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Category
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Icon
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Status
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{types.length === 0 ? (
<tr>
<td colSpan={7} className="px-6 py-8 text-center text-gray-500">
No annotation types found. Click "Seed Default Types" to get started.
</td>
</tr>
) : (
types.map((type) => (
<tr key={type.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{type.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{type.display_name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex items-center gap-2">
<div
className="w-6 h-6 rounded border border-gray-300"
style={{ backgroundColor: type.color }}
/>
<span className="text-gray-600">{type.color}</span>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
<span className="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">
{type.category}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
{type.icon || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<span
className={`px-2 py-1 text-xs font-medium rounded-full ${
type.is_active
? 'bg-green-100 text-green-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{type.is_active ? 'Active' : 'Inactive'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<div className="flex justify-end gap-2">
<Button
size="sm"
variant="outline"
onClick={() => handleEdit(type)}
>
Edit
</Button>
<Button
size="sm"
variant="outline"
onClick={() => handleDelete(type.id)}
>
Delete
</Button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,65 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { annotationTypes } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
type RouteContext = {
params: Promise<{ id: string }>;
};
// PATCH - Update annotation type
export async function PATCH(
request: NextRequest,
context: RouteContext
) {
try {
const { id } = await context.params;
const body = await request.json();
const { name, display_name, color, category, icon, is_active } = body;
const updateData: any = {};
if (name !== undefined) updateData.name = name;
if (display_name !== undefined) updateData.display_name = display_name;
if (color !== undefined) updateData.color = color;
if (category !== undefined) updateData.category = category;
if (icon !== undefined) updateData.icon = icon;
if (is_active !== undefined) updateData.is_active = is_active;
if (Object.keys(updateData).length === 0) {
return NextResponse.json(
{ error: 'No fields to update' },
{ status: 400 }
);
}
const result = await db
.update(annotationTypes)
.set(updateData)
.where(eq(annotationTypes.id, parseInt(id)))
.returning();
if (result.length === 0) {
return NextResponse.json(
{ error: 'Annotation type not found' },
{ status: 404 }
);
}
return NextResponse.json(result[0]);
} catch (error: any) {
console.error('Error updating annotation type:', error);
if (error.message?.includes('UNIQUE constraint failed')) {
return NextResponse.json(
{ error: 'Annotation type with this name already exists' },
{ status: 409 }
);
}
return NextResponse.json(
{ error: 'Failed to update annotation type' },
{ status: 500 }
);
}
}

View file

@ -0,0 +1,160 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { annotationTypes, annotations } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
// GET - List all annotation types
export async function GET() {
try {
const types = await db.select().from(annotationTypes);
return NextResponse.json(types);
} catch (error) {
console.error('Error fetching annotation types:', error);
return NextResponse.json(
{ error: 'Failed to fetch annotation types' },
{ status: 500 }
);
}
}
// POST - Create new annotation type or seed defaults
export async function POST(request: NextRequest) {
try {
const body = await request.json();
// Special case: seed default types
if (body.action === 'seed') {
const existing = await db.select().from(annotationTypes);
if (existing.length > 0) {
return NextResponse.json({ message: 'Types already seeded' });
}
const now = Math.floor(Date.now() / 1000);
const defaultTypes = [
{
name: 'break_up',
display_name: 'Break Up',
color: '#10b981',
category: 'marker',
icon: 'arrowUp',
is_active: 1,
created_at: now,
},
{
name: 'break_down',
display_name: 'Break Down',
color: '#ef4444',
category: 'marker',
icon: 'arrowDown',
is_active: 1,
created_at: now,
},
{
name: 'line',
display_name: 'Line',
color: '#3b82f6',
category: 'line',
icon: 'line',
is_active: 1,
created_at: now,
},
];
await db.insert(annotationTypes).values(defaultTypes);
return NextResponse.json({ message: 'Default types seeded successfully' });
}
// Regular create
const { name, display_name, color, category, icon } = body;
if (!name || !display_name || !color || !category) {
return NextResponse.json(
{ error: 'name, display_name, color, and category are required' },
{ status: 400 }
);
}
const result = await db
.insert(annotationTypes)
.values({
name,
display_name,
color,
category,
icon: icon || null,
is_active: 1,
created_at: Math.floor(Date.now() / 1000),
})
.returning();
return NextResponse.json(result[0], { status: 201 });
} catch (error: any) {
console.error('Error creating annotation type:', error);
if (error.message?.includes('UNIQUE constraint failed')) {
return NextResponse.json(
{ error: 'Annotation type with this name already exists' },
{ status: 409 }
);
}
return NextResponse.json(
{ error: 'Failed to create annotation type' },
{ status: 500 }
);
}
}
// DELETE - Delete annotation type (only if no annotations use it)
export async function DELETE(request: NextRequest) {
try {
const { searchParams } = request.nextUrl;
const id = searchParams.get('id');
if (!id) {
return NextResponse.json(
{ error: 'id parameter is required' },
{ status: 400 }
);
}
// Check if the type exists
const type = await db
.select()
.from(annotationTypes)
.where(eq(annotationTypes.id, parseInt(id)))
.limit(1);
if (type.length === 0) {
return NextResponse.json(
{ error: 'Annotation type not found' },
{ status: 404 }
);
}
// Check if any annotations use this type
const existingAnnotations = await db
.select()
.from(annotations)
.where(eq(annotations.label_type, type[0].name))
.limit(1);
if (existingAnnotations.length > 0) {
return NextResponse.json(
{ error: 'Cannot delete annotation type: annotations exist with this type' },
{ status: 409 }
);
}
await db.delete(annotationTypes).where(eq(annotationTypes.id, parseInt(id)));
return NextResponse.json({ message: 'Annotation type deleted successfully' });
} catch (error) {
console.error('Error deleting annotation type:', error);
return NextResponse.json(
{ error: 'Failed to delete annotation type' },
{ status: 500 }
);
}
}

View file

@ -93,6 +93,12 @@ export default function Home() {
<div className="p-6 border-b border-border">
<h1 className="text-2xl font-semibold text-foreground">Candle Annotator</h1>
<p className="text-sm text-muted-foreground mt-1">Chart annotation tool</p>
<a
href="/annotation-types"
className="mt-3 inline-block text-sm text-blue-600 hover:text-blue-800 underline"
>
Manage Annotation Types
</a>
</div>
<div className="p-6">
<FileUpload onUploadSuccess={handleUploadSuccess} />