feat(ai): implement intelligent auto-tagging system

- Added multi-provider AI infrastructure (OpenAI/Ollama)
- Implemented real-time tag suggestions with debounced analysis
- Created AI diagnostics and database maintenance tools in Settings
- Added automated garbage collection for orphan labels
- Refined UX with deterministic color hashing and interactive ghost tags
This commit is contained in:
2026-01-08 22:59:52 +01:00
parent 6f4d758e5c
commit 3c4b9d6176
27 changed files with 1336 additions and 138 deletions

View File

@@ -170,6 +170,39 @@ export async function createNote(data: {
}
}
// Helper to cleanup orphan labels
async function cleanupOrphanLabels(userId: string, candidateLabels: string[]) {
if (!candidateLabels || candidateLabels.length === 0) return
for (const labelName of candidateLabels) {
// Check if label is used in any other note
// Note: We search for the label name within the JSON string array
// This is a rough check but effective for JSON arrays like ["Label1","Label2"]
const count = await prisma.note.count({
where: {
userId,
labels: {
contains: `"${labelName}"`
}
}
})
if (count === 0) {
console.log(`Cleaning up orphan label: ${labelName}`)
try {
await prisma.label.deleteMany({
where: {
userId,
name: labelName
}
})
} catch (e) {
console.error(`Failed to delete orphan label ${labelName}:`, e)
}
}
}
}
// Update a note
export async function updateNote(id: string, data: {
title?: string | null
@@ -189,6 +222,14 @@ export async function updateNote(id: string, data: {
if (!session?.user?.id) throw new Error('Unauthorized');
try {
// Get old note state to compare labels
const oldNote = await prisma.note.findUnique({
where: { id, userId: session.user.id },
select: { labels: true }
})
const oldLabels: string[] = oldNote?.labels ? JSON.parse(oldNote.labels) : []
// Stringify JSON fields if they exist
const updateData: any = { ...data }
if ('checkItems' in data) {
@@ -213,6 +254,15 @@ export async function updateNote(id: string, data: {
data: updateData
})
// Cleanup orphan labels if labels changed
if (data.labels && oldLabels.length > 0) {
const removedLabels = oldLabels.filter(l => !data.labels?.includes(l))
if (removedLabels.length > 0) {
// Execute async without awaiting to not block response
cleanupOrphanLabels(session.user.id, removedLabels)
}
}
revalidatePath('/')
return parseNote(note)
} catch (error) {
@@ -227,6 +277,13 @@ export async function deleteNote(id: string) {
if (!session?.user?.id) throw new Error('Unauthorized');
try {
// Get labels before delete
const note = await prisma.note.findUnique({
where: { id, userId: session.user.id },
select: { labels: true }
})
const labels: string[] = note?.labels ? JSON.parse(note.labels) : []
await prisma.note.delete({
where: {
id,
@@ -234,6 +291,11 @@ export async function deleteNote(id: string) {
}
})
// Cleanup potential orphans
if (labels.length > 0) {
cleanupOrphanLabels(session.user.id, labels)
}
revalidatePath('/')
return { success: true }
} catch (error) {
@@ -344,6 +406,61 @@ export async function reorderNotes(draggedId: string, targetId: string) {
}
}
// Public action to manually trigger cleanup
export async function cleanupAllOrphans() {
const session = await auth();
if (!session?.user?.id) throw new Error('Unauthorized');
const userId = session.user.id;
let deletedCount = 0;
try {
// 1. Get all labels defined in Label table
const allDefinedLabels = await prisma.label.findMany({
where: { userId },
select: { id: true, name: true }
})
// 2. Get all used labels from Notes (fetch only labels column)
const allNotes = await prisma.note.findMany({
where: { userId },
select: { labels: true }
})
// 3. Build a Set of all used label names
const usedLabelsSet = new Set<string>();
allNotes.forEach(note => {
if (note.labels) {
try {
const parsedLabels: string[] = JSON.parse(note.labels);
if (Array.isArray(parsedLabels)) {
parsedLabels.forEach(l => usedLabelsSet.add(l.toLowerCase())); // Normalize to lowercase for comparison
}
} catch (e) {
// Ignore parse errors
}
}
});
// 4. Identify orphans
const orphans = allDefinedLabels.filter(label => !usedLabelsSet.has(label.name.toLowerCase()));
// 5. Delete orphans
for (const orphan of orphans) {
console.log(`Deleting orphan label: ${orphan.name}`);
await prisma.label.delete({ where: { id: orphan.id } });
deletedCount++;
}
revalidatePath('/')
return { success: true, count: deletedCount }
} catch (error) {
console.error('Error cleaning up orphans:', error)
throw new Error('Failed to cleanup database')
}
}
// Update full order of notes
export async function updateFullOrder(ids: string[]) {
const session = await auth();

View File

@@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAIProvider } from '@/lib/ai/factory';
import { z } from 'zod';
const requestSchema = z.object({
content: z.string().min(1, "Le contenu ne peut pas être vide"),
});
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const { content } = requestSchema.parse(body);
const provider = getAIProvider();
const tags = await provider.generateTags(content);
console.log('[API Tags] Generated tags:', tags);
return NextResponse.json({ tags });
} catch (error: any) {
console.error('Erreur API tags:', error);
if (error instanceof z.ZodError) {
return NextResponse.json({ error: error.errors }, { status: 400 });
}
return NextResponse.json(
{ error: error.message || 'Erreur lors de la génération des tags' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,27 @@
import { NextResponse } from 'next/server';
import { getAIProvider } from '@/lib/ai/factory';
export async function GET() {
try {
const provider = getAIProvider();
const providerName = process.env.AI_PROVIDER || 'openai';
// Test simple de génération de tags sur un texte bidon
const testContent = "J'adore cuisiner des pâtes le dimanche soir avec ma famille.";
const tags = await provider.generateTags(testContent);
return NextResponse.json({
status: 'success',
provider: providerName,
test_tags: tags,
message: 'Infrastructure IA opérationnelle'
});
} catch (error: any) {
console.error('Erreur test IA détaillée:', error);
return NextResponse.json({
status: 'error',
message: error.message,
stack: error.stack
}, { status: 500 });
}
}

View File

@@ -0,0 +1,152 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader2, CheckCircle, XCircle, RefreshCw, Trash2, Database } from 'lucide-react';
import { cleanupAllOrphans } from '@/app/actions/notes';
import { useToast } from '@/components/ui/toast';
export default function SettingsPage() {
const { addToast } = useToast();
const [loading, setLoading] = useState(false);
const [cleanupLoading, setCleanupLoading] = useState(false);
const [status, setStatus] = useState<'idle' | 'success' | 'error'>('idle');
const [result, setResult] = useState<any>(null);
const [config, setConfig] = useState<any>(null);
const checkConnection = async () => {
setLoading(true);
setStatus('idle');
setResult(null);
try {
const res = await fetch('/api/ai/test');
const data = await res.json();
setConfig({
provider: data.provider,
status: res.ok ? 'connected' : 'disconnected'
});
if (res.ok) {
setStatus('success');
setResult(data);
} else {
setStatus('error');
setResult(data);
}
} catch (error: any) {
console.error(error);
setStatus('error');
setResult({ message: error.message, stack: error.stack });
} finally {
setLoading(false);
}
};
const handleCleanup = async () => {
setCleanupLoading(true);
try {
const result = await cleanupAllOrphans();
if (result.success) {
addToast(`Nettoyage terminé : ${result.count} tags supprimés`, 'success');
}
} catch (error) {
console.error(error);
addToast("Erreur lors du nettoyage", "error");
} finally {
setCleanupLoading(false);
}
};
useEffect(() => {
checkConnection();
}, []);
return (
<div className="container mx-auto py-10 px-4 max-w-4xl space-y-8">
<h1 className="text-3xl font-bold mb-8">Paramètres</h1>
<Card>
<CardHeader>
<div className="flex justify-between items-center">
<div>
<CardTitle className="flex items-center gap-2">
Diagnostic IA
{status === 'success' && <CheckCircle className="text-green-500 w-5 h-5" />}
{status === 'error' && <XCircle className="text-red-500 w-5 h-5" />}
</CardTitle>
<CardDescription>Vérifiez la connexion avec votre fournisseur d'intelligence artificielle.</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={checkConnection} disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <RefreshCw className="w-4 h-4 mr-2" />}
Tester la connexion
</Button>
</div>
</CardHeader>
<CardContent className="space-y-6">
{/* Configuration Actuelle */}
<div className="grid grid-cols-2 gap-4">
<div className="p-4 rounded-lg bg-secondary/50">
<p className="text-sm font-medium text-muted-foreground mb-1">Provider Configuré</p>
<p className="text-lg font-mono">{config?.provider || '...'}</p>
</div>
<div className="p-4 rounded-lg bg-secondary/50">
<p className="text-sm font-medium text-muted-foreground mb-1">État API</p>
<Badge variant={status === 'success' ? 'default' : 'destructive'}>
{status === 'success' ? 'Opérationnel' : 'Erreur'}
</Badge>
</div>
</div>
{/* Résultat du Test */}
{result && (
<div className="space-y-2">
<h3 className="text-sm font-medium">Détails du test :</h3>
<div className={`p-4 rounded-md font-mono text-xs overflow-x-auto ${status === 'error' ? 'bg-red-50 text-red-900 border border-red-200' : 'bg-slate-950 text-slate-50'}`}>
<pre>{JSON.stringify(result, null, 2)}</pre>
</div>
{status === 'error' && (
<div className="text-sm text-red-600 mt-2">
<p className="font-bold">Conseil de dépannage :</p>
<ul className="list-disc list-inside mt-1">
<li>Vérifiez que Ollama tourne (<code>ollama list</code>)</li>
<li>Vérifiez l'URL (http://localhost:11434)</li>
<li>Vérifiez que le modèle (ex: granite4:latest) est bien téléchargé</li>
<li>Regardez le terminal du serveur Next.js pour plus de logs</li>
</ul>
</div>
)}
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="w-5 h-5" />
Maintenance
</CardTitle>
<CardDescription>Outils pour maintenir la santé de votre base de données.</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center justify-between p-4 border rounded-lg">
<div>
<h3 className="font-medium">Nettoyage des tags orphelins</h3>
<p className="text-sm text-muted-foreground">Supprime les tags qui ne sont plus utilisés par aucune note.</p>
</div>
<Button variant="secondary" onClick={handleCleanup} disabled={cleanupLoading}>
{cleanupLoading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Trash2 className="w-4 h-4 mr-2" />}
Nettoyer
</Button>
</div>
</CardContent>
</Card>
</div>
);
}