feat: add feature to speak with the AI and create report from contexts
This commit is contained in:
20
frontend/src/api/reports.ts
Normal file
20
frontend/src/api/reports.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { api } from './client'
|
||||
|
||||
export interface Report {
|
||||
id: string
|
||||
user_id: string
|
||||
summary_id: string | null
|
||||
context_excerpt: string
|
||||
question: string
|
||||
answer: string
|
||||
status: 'generating' | 'done' | 'error'
|
||||
error_msg: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export const reportsApi = {
|
||||
list: () => api.get<Report[]>('/reports'),
|
||||
create: (data: { summary_id?: string; excerpts: string[]; question: string }) =>
|
||||
api.post<Report>('/reports', data),
|
||||
delete: (id: string) => api.delete<void>(`/reports/${id}`),
|
||||
}
|
||||
@ -11,4 +11,5 @@ export interface Summary {
|
||||
export const summariesApi = {
|
||||
list: (limit = 10) => api.get<Summary[]>(`/summaries?limit=${limit}`),
|
||||
generate: () => api.post<Summary>('/summaries/generate'),
|
||||
status: () => api.get<{ generating: boolean }>('/summaries/status'),
|
||||
}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { LayoutDashboard, Newspaper, Star, Settings, Key, Cpu, Database, ClipboardList, Users, LogOut, TrendingUp, CalendarDays } from 'lucide-react'
|
||||
import { LayoutDashboard, Newspaper, Star, Settings, Key, Cpu, Database, ClipboardList, Users, LogOut, TrendingUp, CalendarDays, FileText } from 'lucide-react'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { cn } from '@/lib/cn'
|
||||
|
||||
@ -7,6 +7,7 @@ const navItems = [
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Dashboard' },
|
||||
{ to: '/feed', icon: Newspaper, label: 'Actualités' },
|
||||
{ to: '/watchlist', icon: Star, label: 'Watchlist' },
|
||||
{ to: '/reports', icon: FileText, label: 'Rapports' },
|
||||
]
|
||||
|
||||
const adminItems = [
|
||||
|
||||
@ -12,6 +12,7 @@ import { Jobs } from '@/pages/admin/Jobs'
|
||||
import { AdminUsers } from '@/pages/admin/AdminUsers'
|
||||
import { AdminSettings } from '@/pages/admin/AdminSettings'
|
||||
import { Schedule } from '@/pages/admin/Schedule'
|
||||
import { Reports } from '@/pages/Reports'
|
||||
|
||||
export const router = createBrowserRouter([
|
||||
{ path: '/login', element: <Login /> },
|
||||
@ -21,6 +22,7 @@ export const router = createBrowserRouter([
|
||||
{ path: '/', element: <Dashboard /> },
|
||||
{ path: '/feed', element: <Feed /> },
|
||||
{ path: '/watchlist', element: <Watchlist /> },
|
||||
{ path: '/reports', element: <Reports /> },
|
||||
{
|
||||
path: '/admin',
|
||||
element: <AdminLayout />,
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { TrendingUp, Clock, Sparkles } from 'lucide-react'
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { TrendingUp, Clock, Sparkles, MessageSquarePlus, Loader2, Plus, X, Send } from 'lucide-react'
|
||||
import { summariesApi, type Summary } from '@/api/summaries'
|
||||
import { reportsApi } from '@/api/reports'
|
||||
import { assetsApi, type Asset } from '@/api/assets'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@ -8,10 +9,127 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
|
||||
// ── Text-selection floating button ─────────────────────────────────────────
|
||||
|
||||
function useTextSelection(containerRef: React.RefObject<HTMLElement>) {
|
||||
const [selection, setSelection] = useState<{ text: string; x: number; y: number } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
function onMouseUp() {
|
||||
const sel = window.getSelection()
|
||||
const text = sel?.toString().trim()
|
||||
if (!text || !containerRef.current) { setSelection(null); return }
|
||||
const range = sel!.getRangeAt(0)
|
||||
const rect = range.getBoundingClientRect()
|
||||
const containerRect = containerRef.current.getBoundingClientRect()
|
||||
setSelection({
|
||||
text,
|
||||
x: rect.left - containerRect.left + rect.width / 2,
|
||||
y: rect.top - containerRect.top - 8,
|
||||
})
|
||||
}
|
||||
function onMouseDown(e: MouseEvent) {
|
||||
if (!(e.target as Element).closest('[data-context-action]')) setSelection(null)
|
||||
}
|
||||
document.addEventListener('mouseup', onMouseUp)
|
||||
document.addEventListener('mousedown', onMouseDown)
|
||||
return () => {
|
||||
document.removeEventListener('mouseup', onMouseUp)
|
||||
document.removeEventListener('mousedown', onMouseDown)
|
||||
}
|
||||
}, [containerRef])
|
||||
|
||||
return selection
|
||||
}
|
||||
|
||||
// ── Context panel (extraits + question) ────────────────────────────────────
|
||||
|
||||
function ContextPanel({
|
||||
excerpts,
|
||||
onRemove,
|
||||
onClear,
|
||||
onSubmit,
|
||||
}: {
|
||||
excerpts: string[]
|
||||
onRemove: (i: number) => void
|
||||
onClear: () => void
|
||||
onSubmit: (question: string) => Promise<void>
|
||||
}) {
|
||||
const [question, setQuestion] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
|
||||
async function submit() {
|
||||
if (!question.trim() || submitting) return
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await onSubmit(question)
|
||||
setSubmitted(true)
|
||||
setQuestion('')
|
||||
setTimeout(() => setSubmitted(false), 2000)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-40 w-96 max-h-[70vh] flex flex-col bg-card border rounded-xl shadow-2xl overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b bg-primary/5">
|
||||
<span className="text-sm font-semibold flex items-center gap-2">
|
||||
<MessageSquarePlus className="h-4 w-4 text-primary" />
|
||||
Contexte ({excerpts.length} extrait{excerpts.length > 1 ? 's' : ''})
|
||||
</span>
|
||||
<button onClick={onClear} className="text-xs text-muted-foreground hover:text-destructive transition-colors">
|
||||
Tout effacer
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Extraits */}
|
||||
<div className="flex-1 overflow-y-auto px-4 py-3 space-y-2 min-h-0">
|
||||
{excerpts.map((e, i) => (
|
||||
<div key={i} className="flex items-start gap-2 group">
|
||||
<div className="flex-1 rounded bg-muted/60 px-2 py-1.5 text-xs text-muted-foreground italic line-clamp-3">
|
||||
« {e} »
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onRemove(i)}
|
||||
className="mt-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Question */}
|
||||
<div className="border-t px-4 py-3 space-y-2">
|
||||
<textarea
|
||||
className="w-full rounded border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring resize-none"
|
||||
rows={2}
|
||||
placeholder="Votre question…"
|
||||
value={question}
|
||||
onChange={e => setQuestion(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit() }}
|
||||
/>
|
||||
<Button size="sm" className="w-full" onClick={submit} disabled={!question.trim() || submitting || submitted}>
|
||||
{submitting
|
||||
? <><Loader2 className="h-3 w-3 animate-spin" /> Envoi…</>
|
||||
: submitted
|
||||
? 'Envoyé !'
|
||||
: <><Send className="h-3 w-3" /> Envoyer (Ctrl+Entrée)</>}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Summary content renderer ────────────────────────────────────────────────
|
||||
|
||||
function SummaryContent({ content }: { content: string }) {
|
||||
const lines = content.split('\n')
|
||||
return (
|
||||
<div className="space-y-2 text-sm leading-relaxed">
|
||||
<div className="space-y-2 text-sm leading-relaxed select-text">
|
||||
{lines.map((line, i) => {
|
||||
if (line.startsWith('## ')) return <h2 key={i} className="text-base font-semibold mt-4 first:mt-0">{line.slice(3)}</h2>
|
||||
if (line.startsWith('### ')) return <h3 key={i} className="font-medium mt-3">{line.slice(4)}</h3>
|
||||
@ -24,6 +142,8 @@ function SummaryContent({ content }: { content: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
// ── Dashboard ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function Dashboard() {
|
||||
const { user } = useAuth()
|
||||
const [summaries, setSummaries] = useState<Summary[]>([])
|
||||
@ -31,9 +151,26 @@ export function Dashboard() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [generating, setGenerating] = useState(false)
|
||||
const [current, setCurrent] = useState<Summary | null>(null)
|
||||
const [excerpts, setExcerpts] = useState<string[]>([])
|
||||
|
||||
const summaryRef = useRef<HTMLDivElement>(null)
|
||||
const textSel = useTextSelection(summaryRef as React.RefObject<HTMLElement>)
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
// Poll generating status every 5s
|
||||
useEffect(() => {
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
const status = await summariesApi.status()
|
||||
const wasGenerating = generating
|
||||
setGenerating(status.generating)
|
||||
if (wasGenerating && !status.generating) load()
|
||||
} catch { /* ignore */ }
|
||||
}, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}, [generating])
|
||||
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try {
|
||||
@ -55,8 +192,31 @@ export function Dashboard() {
|
||||
} finally { setGenerating(false) }
|
||||
}
|
||||
|
||||
const addExcerpt = useCallback(() => {
|
||||
if (!textSel) return
|
||||
setExcerpts(prev => [...prev, textSel.text])
|
||||
window.getSelection()?.removeAllRanges()
|
||||
}, [textSel])
|
||||
|
||||
async function submitQuestion(question: string) {
|
||||
await reportsApi.create({
|
||||
summary_id: current?.id,
|
||||
excerpts,
|
||||
question,
|
||||
})
|
||||
setExcerpts([])
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
{/* Generating banner */}
|
||||
{generating && (
|
||||
<div className="flex items-center gap-3 rounded-md bg-primary/10 border border-primary/20 px-4 py-3 text-sm text-primary">
|
||||
<Loader2 className="h-4 w-4 animate-spin shrink-0" />
|
||||
Génération d'un résumé IA en cours — cela peut prendre plusieurs minutes…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
@ -105,7 +265,23 @@ export function Dashboard() {
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SummaryContent content={current.content} />
|
||||
<div ref={summaryRef} className="relative">
|
||||
<SummaryContent content={current.content} />
|
||||
{textSel && (
|
||||
<button
|
||||
data-context-action
|
||||
onClick={addExcerpt}
|
||||
className="absolute z-10 flex items-center gap-1 rounded-full bg-primary text-primary-foreground text-xs px-2 py-1 shadow-lg hover:bg-primary/90 transition-colors"
|
||||
style={{ left: textSel.x, top: textSel.y, transform: 'translate(-50%, -100%)' }}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
Ajouter au contexte
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-4 italic">
|
||||
Sélectionnez du texte pour l'ajouter au contexte, puis posez une question dans le panneau qui apparaît.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
@ -141,6 +317,16 @@ export function Dashboard() {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Panneau contexte flottant */}
|
||||
{excerpts.length > 0 && (
|
||||
<ContextPanel
|
||||
excerpts={excerpts}
|
||||
onRemove={i => setExcerpts(prev => prev.filter((_, idx) => idx !== i))}
|
||||
onClear={() => setExcerpts([])}
|
||||
onSubmit={submitQuestion}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
127
frontend/src/pages/Reports.tsx
Normal file
127
frontend/src/pages/Reports.tsx
Normal file
@ -0,0 +1,127 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Trash2, FileText, Clock, Loader2, XCircle, AlertCircle } from 'lucide-react'
|
||||
import { reportsApi, type Report } from '@/api/reports'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
|
||||
function StatusBadge({ status }: { status: Report['status'] }) {
|
||||
if (status === 'generating') return (
|
||||
<Badge variant="secondary" className="gap-1 text-xs">
|
||||
<Loader2 className="h-3 w-3 animate-spin" /> En cours
|
||||
</Badge>
|
||||
)
|
||||
if (status === 'error') return (
|
||||
<Badge variant="destructive" className="gap-1 text-xs">
|
||||
<AlertCircle className="h-3 w-3" /> Erreur
|
||||
</Badge>
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
export function Reports() {
|
||||
const [reports, setReports] = useState<Report[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try { setReports((await reportsApi.list()) ?? []) }
|
||||
finally { setLoading(false) }
|
||||
}, [])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
// Poll toutes les 3s tant qu'il y a des rapports en cours
|
||||
useEffect(() => {
|
||||
const hasGenerating = reports.some(r => r.status === 'generating')
|
||||
if (!hasGenerating) return
|
||||
const interval = setInterval(load, 3000)
|
||||
return () => clearInterval(interval)
|
||||
}, [reports, load])
|
||||
|
||||
async function remove(id: string) {
|
||||
await reportsApi.delete(id)
|
||||
setReports(prev => prev.filter(r => r.id !== id))
|
||||
}
|
||||
|
||||
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Rapports IA</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Vos questions posées sur des extraits de résumés, avec les réponses de l'IA.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{reports.length === 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 text-center text-muted-foreground">
|
||||
<FileText className="h-8 w-8 mx-auto mb-3 opacity-50" />
|
||||
<p>Aucun rapport enregistré</p>
|
||||
<p className="text-xs mt-1">Sélectionnez du texte dans un résumé et posez une question à l'IA.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{reports.map(r => (
|
||||
<Card key={r.id} className={r.status === 'generating' ? 'border-primary/30' : ''}>
|
||||
<CardContent className="pt-4 pb-4 space-y-3">
|
||||
{/* Meta */}
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(r.created_at).toLocaleString('fr-FR')}
|
||||
</div>
|
||||
<StatusBadge status={r.status} />
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-destructive shrink-0"
|
||||
onClick={() => remove(r.id)}
|
||||
title={r.status === 'generating' ? 'Annuler' : 'Supprimer'}
|
||||
>
|
||||
{r.status === 'generating'
|
||||
? <XCircle className="h-3 w-3" />
|
||||
: <Trash2 className="h-3 w-3" />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Extraits de contexte */}
|
||||
{r.context_excerpt.split('\n\n---\n\n').map((excerpt, i) => (
|
||||
<div key={i} className="rounded bg-muted/60 px-3 py-2 text-xs text-muted-foreground italic">
|
||||
« {excerpt} »
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Question */}
|
||||
<p className="text-sm font-medium">{r.question}</p>
|
||||
|
||||
{/* Réponse */}
|
||||
{r.status === 'generating' && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-primary" />
|
||||
L'IA génère la réponse…
|
||||
</div>
|
||||
)}
|
||||
{r.status === 'done' && (
|
||||
<div className="text-sm text-muted-foreground whitespace-pre-wrap leading-relaxed border-t pt-3">
|
||||
{r.answer}
|
||||
</div>
|
||||
)}
|
||||
{r.status === 'error' && (
|
||||
<div className="text-sm text-destructive border-t pt-3">
|
||||
Erreur : {r.error_msg || 'Une erreur est survenue lors de la génération.'}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user