chore(repo): initialize Tradarr repository
Add the existing application baseline and repository documentation/ignore rules. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
349
frontend/src/pages/Dashboard.tsx
Normal file
349
frontend/src/pages/Dashboard.tsx
Normal file
@ -0,0 +1,349 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { TrendingUp, Clock, Sparkles, MessageSquarePlus, Loader2, Plus, X, Send, ChevronDown, ChevronUp } 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 { Markdown } from '@/components/ui/markdown'
|
||||
import { Button } from '@/components/ui/button'
|
||||
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 readSelection() {
|
||||
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 onMouseUp() { readSelection() }
|
||||
// On mobile, selectionchange fires after the user lifts their finger
|
||||
function onSelectionChange() {
|
||||
const sel = window.getSelection()
|
||||
if (!sel?.toString().trim()) setSelection(null)
|
||||
else readSelection()
|
||||
}
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (!(e.target as Element).closest('[data-context-action]')) setSelection(null)
|
||||
}
|
||||
document.addEventListener('mouseup', onMouseUp)
|
||||
document.addEventListener('selectionchange', onSelectionChange)
|
||||
document.addEventListener('pointerdown', onPointerDown)
|
||||
return () => {
|
||||
document.removeEventListener('mouseup', onMouseUp)
|
||||
document.removeEventListener('selectionchange', onSelectionChange)
|
||||
document.removeEventListener('pointerdown', onPointerDown)
|
||||
}
|
||||
}, [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)
|
||||
const [showExcerpts, setShowExcerpts] = 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-16 left-0 right-0 z-40 flex flex-col bg-card border-t shadow-2xl overflow-hidden md:bottom-4 md:left-auto md:right-4 md:w-96 md:rounded-xl md:border">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b bg-primary/5">
|
||||
<button
|
||||
className="text-sm font-semibold flex items-center gap-2 hover:text-primary transition-colors"
|
||||
onClick={() => setShowExcerpts(v => !v)}
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4 text-primary" />
|
||||
Contexte ({excerpts.length} extrait{excerpts.length > 1 ? 's' : ''})
|
||||
<span className="md:hidden">{showExcerpts ? <ChevronDown className="h-3 w-3" /> : <ChevronUp className="h-3 w-3" />}</span>
|
||||
</button>
|
||||
<button onClick={onClear} className="text-xs text-muted-foreground hover:text-destructive transition-colors">
|
||||
Tout effacer
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Extraits — toujours visible sur desktop, togglable sur mobile */}
|
||||
<div className={`flex-1 overflow-y-auto px-4 py-3 space-y-2 min-h-0 max-h-[25vh] ${showExcerpts ? 'block' : 'hidden'} md:block`}>
|
||||
{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 text-muted-foreground hover:text-destructive md:opacity-0 md:group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<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 }) {
|
||||
return <Markdown content={content} />
|
||||
}
|
||||
|
||||
// ── Dashboard ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function Dashboard() {
|
||||
const { user } = useAuth()
|
||||
const [summaries, setSummaries] = useState<Summary[]>([])
|
||||
const [assets, setAssets] = useState<Asset[]>([])
|
||||
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 {
|
||||
const [s, a] = await Promise.all([summariesApi.list(5), assetsApi.list()])
|
||||
setSummaries(s ?? [])
|
||||
setAssets(a ?? [])
|
||||
setCurrent(s?.[0] ?? null)
|
||||
} finally { setLoading(false) }
|
||||
}
|
||||
|
||||
async function generate() {
|
||||
setGenerating(true)
|
||||
try {
|
||||
const s = await summariesApi.generate()
|
||||
setSummaries(prev => [s, ...prev])
|
||||
setCurrent(s)
|
||||
} catch (e) {
|
||||
alert(e instanceof Error ? e.message : 'Erreur lors de la génération')
|
||||
} 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>
|
||||
<h1 className="text-2xl font-bold">Bonjour 👋</h1>
|
||||
<p className="text-muted-foreground text-sm">{user?.email}</p>
|
||||
</div>
|
||||
<Button onClick={generate} disabled={generating || assets.length === 0}>
|
||||
{generating ? <><Spinner className="h-4 w-4" /> Génération…</> : <><Sparkles className="h-4 w-4" /> Générer un résumé</>}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{assets.length === 0 && !loading && (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-8 text-center">
|
||||
<TrendingUp className="h-10 w-10 mx-auto text-muted-foreground mb-3" />
|
||||
<p className="font-medium">Votre watchlist est vide</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">Ajoutez des symboles dans la section Watchlist pour obtenir des résumés personnalisés</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{assets.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assets.map(a => (
|
||||
<Badge key={a.id} variant="secondary" className="font-mono">{a.symbol}</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Résumé actuel */}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<div className="lg:col-span-2 space-y-4">
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-20"><Spinner /></div>
|
||||
) : current ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Sparkles className="h-5 w-5 text-primary" /> Résumé IA
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(current.generated_at).toLocaleString('fr-FR')}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div ref={summaryRef} className="relative">
|
||||
<SummaryContent content={current.content} />
|
||||
{/* Desktop: floating button above selection */}
|
||||
{textSel && (
|
||||
<button
|
||||
data-context-action
|
||||
onClick={addExcerpt}
|
||||
className="absolute z-10 hidden md: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>
|
||||
{/* Mobile: fixed bottom bar — avoids conflict with native selection menu */}
|
||||
{textSel && (
|
||||
<div className="md:hidden fixed bottom-16 left-0 right-0 z-50 flex justify-center px-4 pointer-events-none">
|
||||
<button
|
||||
data-context-action
|
||||
onClick={addExcerpt}
|
||||
className="pointer-events-auto flex items-center gap-2 rounded-full bg-primary text-primary-foreground text-sm px-4 py-2.5 shadow-xl"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
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>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 text-center text-muted-foreground">
|
||||
<Sparkles className="h-8 w-8 mx-auto mb-3 opacity-50" />
|
||||
<p>Aucun résumé disponible</p>
|
||||
<p className="text-xs mt-1">Cliquez sur "Générer un résumé" pour commencer</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Historique résumés */}
|
||||
{summaries.length > 1 && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">Historique</h2>
|
||||
{summaries.slice(1).map(s => (
|
||||
<Card
|
||||
key={s.id}
|
||||
className={`cursor-pointer transition-colors hover:border-primary/50 ${current?.id === s.id ? 'border-primary/50' : ''}`}
|
||||
onClick={() => setCurrent(s)}
|
||||
>
|
||||
<CardContent className="py-3">
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground mb-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(s.generated_at).toLocaleString('fr-FR')}
|
||||
</div>
|
||||
<p className="text-sm line-clamp-3">{s.content.slice(0, 120)}…</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</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>
|
||||
)
|
||||
}
|
||||
116
frontend/src/pages/Feed.tsx
Normal file
116
frontend/src/pages/Feed.tsx
Normal file
@ -0,0 +1,116 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { ExternalLink, RefreshCw, Search } from 'lucide-react'
|
||||
import { articlesApi, type Article } from '@/api/articles'
|
||||
import { assetsApi, type Asset } from '@/api/assets'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select } from '@/components/ui/select'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
|
||||
function fmtDate(a: Article) {
|
||||
const d = a.published_at?.Valid ? new Date(a.published_at.Time) : new Date(a.created_at)
|
||||
const now = Date.now()
|
||||
const diff = now - d.getTime()
|
||||
if (diff < 3600000) return `Il y a ${Math.floor(diff / 60000)} min`
|
||||
if (diff < 86400000) return `Il y a ${Math.floor(diff / 3600000)} h`
|
||||
return d.toLocaleDateString('fr-FR')
|
||||
}
|
||||
|
||||
export function Feed() {
|
||||
const [articles, setArticles] = useState<Article[]>([])
|
||||
const [assets, setAssets] = useState<Asset[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState('')
|
||||
const [filterSymbol, setFilterSymbol] = useState('')
|
||||
const [offset, setOffset] = useState(0)
|
||||
const limit = 30
|
||||
|
||||
useEffect(() => {
|
||||
assetsApi.list().then(a => setAssets(a ?? []))
|
||||
}, [])
|
||||
|
||||
useEffect(() => { load(0) }, [filterSymbol])
|
||||
|
||||
async function load(newOffset = 0) {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await articlesApi.list({ symbol: filterSymbol || undefined, limit, offset: newOffset })
|
||||
if (newOffset === 0) setArticles(data ?? [])
|
||||
else setArticles(prev => [...prev, ...(data ?? [])])
|
||||
setOffset(newOffset + limit)
|
||||
} finally { setLoading(false) }
|
||||
}
|
||||
|
||||
const filtered = search
|
||||
? articles.filter(a => a.title.toLowerCase().includes(search.toLowerCase()) || a.source_name?.toLowerCase().includes(search.toLowerCase()))
|
||||
: articles
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<h1 className="text-2xl font-bold flex-1">Actualités</h1>
|
||||
<Button variant="outline" size="icon" onClick={() => load(0)}><RefreshCw className="h-4 w-4" /></Button>
|
||||
</div>
|
||||
|
||||
{/* Filtres */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<div className="relative flex-1 min-w-48">
|
||||
<Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input className="pl-8" placeholder="Rechercher…" value={search} onChange={e => setSearch(e.target.value)} />
|
||||
</div>
|
||||
<Select value={filterSymbol} onChange={e => setFilterSymbol(e.target.value)} className="w-40">
|
||||
<option value="">Tous les symboles</option>
|
||||
{assets.map(a => <option key={a.id} value={a.symbol}>{a.symbol}</option>)}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{loading && articles.length === 0 ? (
|
||||
<div className="flex justify-center py-20"><Spinner /></div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
{filtered.map(a => (
|
||||
<Card key={a.id} className="hover:border-border/80 transition-colors">
|
||||
<CardContent className="py-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap mb-1">
|
||||
<Badge variant="outline" className="text-xs">{a.source_name}</Badge>
|
||||
<span className="text-xs text-muted-foreground">{fmtDate(a)}</span>
|
||||
</div>
|
||||
<h3 className="font-medium leading-snug mb-2">{a.title}</h3>
|
||||
{a.content && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">{a.content}</p>
|
||||
)}
|
||||
</div>
|
||||
<a
|
||||
href={a.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="shrink-0 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</a>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
{filtered.length === 0 && (
|
||||
<Card><CardContent className="py-12 text-center text-muted-foreground">Aucun article</CardContent></Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{filtered.length >= limit && (
|
||||
<div className="flex justify-center pt-2">
|
||||
<Button variant="outline" onClick={() => load(offset)} disabled={loading}>
|
||||
{loading ? <Spinner className="h-4 w-4" /> : 'Charger plus'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
94
frontend/src/pages/Login.tsx
Normal file
94
frontend/src/pages/Login.tsx
Normal file
@ -0,0 +1,94 @@
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
export function Login() {
|
||||
const { token, login } = useAuth()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
if (token) return <Navigate to="/" replace />
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
const { token: t, user } = await authApi.login(email, password)
|
||||
login(t, user)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Erreur de connexion')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background p-4">
|
||||
{/* Motif de fond discret */}
|
||||
<div className="absolute inset-0 opacity-[0.03] pointer-events-none"
|
||||
style={{ backgroundImage: 'repeating-linear-gradient(0deg, hsl(20 15% 9%), hsl(20 15% 9%) 1px, transparent 1px, transparent 40px), repeating-linear-gradient(90deg, hsl(20 15% 9%), hsl(20 15% 9%) 1px, transparent 1px, transparent 40px)' }}
|
||||
/>
|
||||
|
||||
<div className="relative w-full max-w-sm">
|
||||
{/* En-tête */}
|
||||
<div className="mb-8 text-center">
|
||||
<h1 className="font-serif text-4xl font-bold text-foreground">
|
||||
Financ<span className="text-primary">IA</span>l
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-muted-foreground tracking-wide">
|
||||
Votre journal financier augmenté par l'IA
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Carte formulaire */}
|
||||
<div className="rounded-lg border bg-card shadow-sm p-6">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="email">Adresse email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={e => setEmail(e.target.value)}
|
||||
required
|
||||
autoComplete="email"
|
||||
placeholder="vous@exemple.com"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="password">Mot de passe</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
autoComplete="current-password"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm text-destructive border border-destructive/20 bg-destructive/5 rounded px-3 py-2">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" className="w-full mt-2" disabled={loading}>
|
||||
{loading ? 'Connexion…' : 'Se connecter'}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-center text-xs text-muted-foreground">
|
||||
© {new Date().getFullYear()} FinancIAl — Accès restreint
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
252
frontend/src/pages/Reports.tsx
Normal file
252
frontend/src/pages/Reports.tsx
Normal file
@ -0,0 +1,252 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { Trash2, FileText, Clock, Loader2, XCircle, AlertCircle, Send } from 'lucide-react'
|
||||
import { reportsApi, type Report, type ReportMessage } from '@/api/reports'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Markdown } from '@/components/ui/markdown'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
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
|
||||
}
|
||||
|
||||
function MessageBubble({ msg }: { msg: ReportMessage }) {
|
||||
const isUser = msg.role === 'user'
|
||||
return (
|
||||
<div className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
|
||||
<div className={`max-w-[85%] rounded-lg px-3 py-2 text-sm ${
|
||||
isUser
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted'
|
||||
}`}>
|
||||
{msg.status === 'generating' ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
<span className="text-xs">Génération…</span>
|
||||
</div>
|
||||
) : msg.status === 'error' ? (
|
||||
<span className="text-destructive text-xs">{msg.content || 'Erreur lors de la génération.'}</span>
|
||||
) : isUser ? (
|
||||
<p>{msg.content}</p>
|
||||
) : (
|
||||
<Markdown content={msg.content} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ReportChat({ report }: { report: Report }) {
|
||||
const [messages, setMessages] = useState<ReportMessage[]>([])
|
||||
const [input, setInput] = useState('')
|
||||
const [sending, setSending] = useState(false)
|
||||
const bottomRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const loadMessages = useCallback(async () => {
|
||||
const msgs = await reportsApi.listMessages(report.id)
|
||||
setMessages(msgs ?? [])
|
||||
}, [report.id])
|
||||
|
||||
useEffect(() => { loadMessages() }, [loadMessages])
|
||||
|
||||
// Poll tant qu'un message assistant est en cours de génération
|
||||
useEffect(() => {
|
||||
const hasGenerating = messages.some(m => m.status === 'generating')
|
||||
if (!hasGenerating) return
|
||||
const interval = setInterval(loadMessages, 2000)
|
||||
return () => clearInterval(interval)
|
||||
}, [messages, loadMessages])
|
||||
|
||||
// Scroll vers le bas à chaque nouveau message
|
||||
useEffect(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
}, [messages])
|
||||
|
||||
async function send() {
|
||||
const content = input.trim()
|
||||
if (!content || sending) return
|
||||
setInput('')
|
||||
setSending(true)
|
||||
try {
|
||||
// Optimistic: ajouter le message user immédiatement
|
||||
const optimisticUser: ReportMessage = {
|
||||
id: `tmp-${Date.now()}`,
|
||||
report_id: report.id,
|
||||
role: 'user',
|
||||
content,
|
||||
status: 'done',
|
||||
created_at: new Date().toISOString(),
|
||||
}
|
||||
const optimisticAssistant: ReportMessage = {
|
||||
id: `tmp-assistant-${Date.now()}`,
|
||||
report_id: report.id,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
status: 'generating',
|
||||
created_at: new Date().toISOString(),
|
||||
}
|
||||
setMessages(prev => [...prev, optimisticUser, optimisticAssistant])
|
||||
await reportsApi.createMessage(report.id, content)
|
||||
await loadMessages()
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
const hasGenerating = messages.some(m => m.status === 'generating')
|
||||
|
||||
return (
|
||||
<div className="border-t pt-3 space-y-3">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Conversation</p>
|
||||
|
||||
{messages.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{messages.map(msg => (
|
||||
<MessageBubble key={msg.id} msg={msg} />
|
||||
))}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={input}
|
||||
onChange={e => setInput(e.target.value)}
|
||||
onKeyDown={e => e.key === 'Enter' && !e.shiftKey && send()}
|
||||
placeholder="Posez une question sur cette réponse…"
|
||||
disabled={hasGenerating || sending}
|
||||
className="text-sm"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={send}
|
||||
disabled={!input.trim() || hasGenerating || sending}
|
||||
className="shrink-0"
|
||||
>
|
||||
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 initiale */}
|
||||
{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="border-t pt-3">
|
||||
<Markdown content={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>
|
||||
)}
|
||||
|
||||
{/* Chat de suivi (uniquement quand le rapport est terminé) */}
|
||||
{r.status === 'done' && <ReportChat report={r} />}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
117
frontend/src/pages/Watchlist.tsx
Normal file
117
frontend/src/pages/Watchlist.tsx
Normal file
@ -0,0 +1,117 @@
|
||||
import { useState, useEffect, type FormEvent } from 'react'
|
||||
import { Plus, Trash2, TrendingUp } from 'lucide-react'
|
||||
import { assetsApi, type Asset } from '@/api/assets'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
|
||||
export function Watchlist() {
|
||||
const [assets, setAssets] = useState<Asset[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [symbol, setSymbol] = useState('')
|
||||
const [name, setName] = useState('')
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [removing, setRemoving] = useState<string | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try { setAssets(await assetsApi.list() ?? []) } finally { setLoading(false) }
|
||||
}
|
||||
|
||||
async function add(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!symbol) return
|
||||
setAdding(true); setError('')
|
||||
try {
|
||||
await assetsApi.add(symbol.toUpperCase(), name)
|
||||
setSymbol(''); setName('')
|
||||
await load()
|
||||
} catch (err) { setError(err instanceof Error ? err.message : 'Erreur') } finally { setAdding(false) }
|
||||
}
|
||||
|
||||
async function remove(sym: string) {
|
||||
setRemoving(sym)
|
||||
await assetsApi.remove(sym)
|
||||
await load()
|
||||
setRemoving(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Watchlist</h1>
|
||||
<p className="text-muted-foreground text-sm">Les symboles suivis seront utilisés pour personnaliser vos résumés IA</p>
|
||||
</div>
|
||||
|
||||
{/* Formulaire d'ajout */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">Ajouter un actif</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={add} className="flex flex-wrap gap-3 items-end">
|
||||
<div className="space-y-1 flex-1 min-w-32">
|
||||
<Label>Symbole</Label>
|
||||
<Input
|
||||
placeholder="AAPL, TSLA, BTC…"
|
||||
value={symbol}
|
||||
onChange={e => setSymbol(e.target.value.toUpperCase())}
|
||||
className="font-mono"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1 flex-1 min-w-40">
|
||||
<Label>Nom <span className="text-muted-foreground">(optionnel)</span></Label>
|
||||
<Input
|
||||
placeholder="Apple Inc."
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={adding || !symbol}>
|
||||
{adding ? <Spinner className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
|
||||
Ajouter
|
||||
</Button>
|
||||
</form>
|
||||
{error && <p className="mt-2 text-sm text-destructive">{error}</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Liste */}
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-12"><Spinner /></div>
|
||||
) : assets.length === 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 text-center">
|
||||
<TrendingUp className="h-10 w-10 mx-auto text-muted-foreground mb-3 opacity-50" />
|
||||
<p className="text-muted-foreground">Aucun actif dans votre watchlist</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{assets.map(a => (
|
||||
<Card key={a.id} className="flex items-center justify-between p-4">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<Badge variant="secondary" className="font-mono shrink-0">{a.symbol}</Badge>
|
||||
{a.name && <span className="text-sm text-muted-foreground truncate">{a.name}</span>}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="shrink-0 h-7 w-7 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => remove(a.symbol)}
|
||||
disabled={removing === a.symbol}
|
||||
>
|
||||
{removing === a.symbol ? <Spinner className="h-3 w-3" /> : <Trash2 className="h-3 w-3" />}
|
||||
</Button>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
652
frontend/src/pages/admin/AIProviders.tsx
Normal file
652
frontend/src/pages/admin/AIProviders.tsx
Normal file
@ -0,0 +1,652 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Plus, Trash2, Star, Download, HardDrive, Cpu, ChevronDown, ChevronUp, X } from 'lucide-react'
|
||||
import { adminApi, type AIProvider, type AIRoles, type OllamaModelInfo } from '@/api/admin'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Select } from '@/components/ui/select'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
|
||||
const PROVIDER_NAMES = ['openai', 'anthropic', 'gemini', 'ollama', 'claudecode'] as const
|
||||
|
||||
const CUSTOM_MODELS_KEY = 'ollama_custom_models'
|
||||
|
||||
const KNOWN_OLLAMA_MODELS: { name: string; family: string; tags: { tag: string; size: string }[] }[] = [
|
||||
{ name: 'qwen3', family: 'Qwen3', tags: [{ tag: '0.6b', size: '~0.4 GB' }, { tag: '1.7b', size: '~1.1 GB' }, { tag: '4b', size: '~2.6 GB' }, { tag: '8b', size: '~5.2 GB' }, { tag: '14b', size: '~9.3 GB' }, { tag: '32b', size: '~20 GB' }] },
|
||||
{ name: 'qwen2.5', family: 'Qwen2.5', tags: [{ tag: '0.5b', size: '~0.4 GB' }, { tag: '1.5b', size: '~1 GB' }, { tag: '3b', size: '~2 GB' }, { tag: '7b', size: '~4.7 GB' }, { tag: '14b', size: '~9 GB' }, { tag: '32b', size: '~20 GB' }] },
|
||||
{ name: 'llama3.2', family: 'Llama 3.2', tags: [{ tag: '1b', size: '~1.3 GB' }, { tag: '3b', size: '~2 GB' }] },
|
||||
{ name: 'llama3.1', family: 'Llama 3.1', tags: [{ tag: '8b', size: '~4.9 GB' }, { tag: '70b', size: '~40 GB' }] },
|
||||
{ name: 'gemma3', family: 'Gemma 3', tags: [{ tag: '1b', size: '~0.8 GB' }, { tag: '4b', size: '~3.3 GB' }, { tag: '12b', size: '~8 GB' }, { tag: '27b', size: '~17 GB' }] },
|
||||
{ name: 'mistral', family: 'Mistral', tags: [{ tag: '7b', size: '~4.1 GB' }] },
|
||||
{ name: 'phi4', family: 'Phi-4', tags: [{ tag: 'latest', size: '~9 GB' }] },
|
||||
{ name: 'phi4-mini', family: 'Phi-4 Mini', tags: [{ tag: 'latest', size: '~2.5 GB' }] },
|
||||
{ name: 'deepseek-r1', family: 'DeepSeek-R1', tags: [{ tag: '1.5b', size: '~1.1 GB' }, { tag: '7b', size: '~4.7 GB' }, { tag: '8b', size: '~4.9 GB' }, { tag: '14b', size: '~9 GB' }, { tag: '32b', size: '~20 GB' }] },
|
||||
]
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`
|
||||
if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB`
|
||||
return `${bytes} B`
|
||||
}
|
||||
|
||||
function loadCustomModels(): string[] {
|
||||
try { return JSON.parse(localStorage.getItem(CUSTOM_MODELS_KEY) ?? '[]') } catch { return [] }
|
||||
}
|
||||
function saveCustomModels(models: string[]) {
|
||||
localStorage.setItem(CUSTOM_MODELS_KEY, JSON.stringify(models))
|
||||
}
|
||||
|
||||
// ── Confirmation dialog ────────────────────────────────────────────────────
|
||||
|
||||
function ConfirmDownloadDialog({ modelName, onConfirm, onCancel }: {
|
||||
modelName: string
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
|
||||
<div className="bg-card border rounded-xl shadow-2xl p-6 w-full max-w-sm mx-4 space-y-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<p className="font-semibold">Télécharger ce modèle ?</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
<span className="font-mono text-foreground">{modelName}</span> sera téléchargé depuis Ollama Hub.
|
||||
Le téléchargement peut prendre plusieurs minutes.
|
||||
</p>
|
||||
</div>
|
||||
<button onClick={onCancel} className="text-muted-foreground hover:text-foreground ml-3 shrink-0">
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button variant="outline" size="sm" onClick={onCancel}>Annuler</Button>
|
||||
<Button size="sm" onClick={onConfirm}>
|
||||
<Download className="h-3 w-3 mr-1" /> Télécharger
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Shared model catalogue ─────────────────────────────────────────────────
|
||||
|
||||
function ModelCatalogue({
|
||||
installedNames,
|
||||
pulling,
|
||||
onPull,
|
||||
}: {
|
||||
installedNames: Set<string>
|
||||
pulling: string | null
|
||||
onPull: (name: string) => void
|
||||
}) {
|
||||
const [customName, setCustomName] = useState('')
|
||||
const [pendingModel, setPendingModel] = useState<string | null>(null)
|
||||
const [customModels, setCustomModels] = useState<string[]>(loadCustomModels)
|
||||
|
||||
// All model names in the hardcoded catalogue
|
||||
const knownNames = new Set(
|
||||
KNOWN_OLLAMA_MODELS.flatMap(f => f.tags.map(t => `${f.name}:${t.tag}`))
|
||||
)
|
||||
|
||||
function requestPull(name: string) {
|
||||
setPendingModel(name)
|
||||
}
|
||||
|
||||
function confirmPull() {
|
||||
if (!pendingModel) return
|
||||
// If not in hardcoded catalogue, add to custom list
|
||||
if (!knownNames.has(pendingModel)) {
|
||||
const updated = [...new Set([...customModels, pendingModel])]
|
||||
setCustomModels(updated)
|
||||
saveCustomModels(updated)
|
||||
}
|
||||
onPull(pendingModel)
|
||||
setPendingModel(null)
|
||||
}
|
||||
|
||||
function submitCustom() {
|
||||
const name = customName.trim()
|
||||
if (!name) return
|
||||
const fullName = name.includes(':') ? name : `${name}:latest`
|
||||
setCustomName('')
|
||||
requestPull(fullName)
|
||||
}
|
||||
|
||||
// Families to display: hardcoded + custom entries
|
||||
const customEntries = customModels.filter(m => !knownNames.has(m))
|
||||
|
||||
return (
|
||||
<>
|
||||
{pendingModel && (
|
||||
<ConfirmDownloadDialog
|
||||
modelName={pendingModel}
|
||||
onConfirm={confirmPull}
|
||||
onCancel={() => setPendingModel(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Free-text input */}
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-1.5">Nom personnalisé</p>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
className="h-8 text-sm font-mono"
|
||||
placeholder="ex: llama3.2:3b, mymodel:latest…"
|
||||
value={customName}
|
||||
onChange={e => setCustomName(e.target.value)}
|
||||
onKeyDown={e => e.key === 'Enter' && submitCustom()}
|
||||
disabled={pulling !== null}
|
||||
/>
|
||||
<Button size="sm" className="h-8 shrink-0" onClick={submitCustom}
|
||||
disabled={!customName.trim() || pulling !== null}>
|
||||
<Download className="h-3 w-3" /> Installer
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom models section */}
|
||||
{customEntries.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-1.5">Personnalisés</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{customEntries.map(fullName => {
|
||||
const installed = installedNames.has(fullName)
|
||||
const isPulling = pulling === fullName
|
||||
return <ModelTag key={fullName} fullName={fullName} size="?" installed={installed} isPulling={isPulling} pulling={pulling} onRequest={requestPull} />
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Hardcoded catalogue */}
|
||||
<div className="space-y-3">
|
||||
{KNOWN_OLLAMA_MODELS.map(family => (
|
||||
<div key={family.name}>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-1.5">{family.family}</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{family.tags.map(({ tag, size }) => {
|
||||
const fullName = `${family.name}:${tag}`
|
||||
const installed = installedNames.has(fullName)
|
||||
const isPulling = pulling === fullName
|
||||
return <ModelTag key={fullName} fullName={fullName} size={size} installed={installed} isPulling={isPulling} pulling={pulling} onRequest={requestPull} />
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ModelTag({ fullName, size, installed, isPulling, pulling, onRequest }: {
|
||||
fullName: string; size: string
|
||||
installed: boolean; isPulling: boolean; pulling: string | null
|
||||
onRequest: (name: string) => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
disabled={installed || pulling !== null}
|
||||
onClick={() => !installed && !isPulling && onRequest(fullName)}
|
||||
className={[
|
||||
'flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors',
|
||||
installed
|
||||
? 'border-primary/40 bg-primary/5 text-primary cursor-default'
|
||||
: isPulling
|
||||
? 'border-border bg-muted text-muted-foreground cursor-wait'
|
||||
: pulling !== null
|
||||
? 'border-border bg-background text-muted-foreground opacity-50 cursor-not-allowed'
|
||||
: 'border-border bg-background hover:border-primary/60 hover:bg-primary/5 cursor-pointer',
|
||||
].join(' ')}
|
||||
>
|
||||
{isPulling
|
||||
? <><Spinner className="h-2.5 w-2.5" /> Téléchargement…</>
|
||||
: installed
|
||||
? <><span className="text-[10px]">✓</span> {fullName}</>
|
||||
: <><Download className="h-2.5 w-2.5" /> {fullName} {size !== '?' && <span className="text-muted-foreground">{size}</span>}</>
|
||||
}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Cloud model picker (OpenAI / Anthropic / Gemini / …) ──────────────────
|
||||
|
||||
function CloudModelPicker({ value, providerName, apiKey, endpoint, onChange }: {
|
||||
value: string; providerName: string; apiKey: string; endpoint: string
|
||||
onChange: (model: string) => void
|
||||
}) {
|
||||
const [models, setModels] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const noKeyNeeded = providerName === 'claudecode'
|
||||
|
||||
useEffect(() => {
|
||||
if (noKeyNeeded) loadModels()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [providerName])
|
||||
|
||||
async function loadModels() {
|
||||
if (!noKeyNeeded && !apiKey) { setLoadError('Renseigne la clé API d\'abord'); return }
|
||||
setLoading(true); setLoadError('')
|
||||
try {
|
||||
const list = await adminApi.probeModels({ name: providerName, api_key: apiKey, endpoint })
|
||||
setModels(list ?? [])
|
||||
if ((list ?? []).length === 0) setLoadError('Aucun modèle trouvé')
|
||||
} catch (e) {
|
||||
setLoadError(e instanceof Error ? e.message : 'Erreur')
|
||||
} finally { setLoading(false) }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="gpt-4o-mini, claude-sonnet-4-6…"
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
list="cloud-models-list"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button type="button" variant="outline" size="sm" className="shrink-0" onClick={loadModels} disabled={loading}>
|
||||
{loading ? <Spinner className="h-3 w-3" /> : 'Charger'}
|
||||
</Button>
|
||||
</div>
|
||||
{models.length > 0 && (
|
||||
<datalist id="cloud-models-list">
|
||||
{models.map(m => <option key={m} value={m} />)}
|
||||
</datalist>
|
||||
)}
|
||||
{models.length > 0 && (
|
||||
<Select value={value} onChange={e => onChange(e.target.value)}>
|
||||
<option value="">— Sélectionner un modèle —</option>
|
||||
{models.map(m => <option key={m} value={m}>{m}</option>)}
|
||||
</Select>
|
||||
)}
|
||||
{loadError && <p className="text-xs text-destructive">{loadError}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Ollama model picker (inside provider form) ─────────────────────────────
|
||||
|
||||
function OllamaModelPicker({ value, installedModels, onSelect, onRefresh }: {
|
||||
value: string
|
||||
installedModels: OllamaModelInfo[]
|
||||
onSelect: (name: string) => void
|
||||
onRefresh: () => Promise<OllamaModelInfo[]>
|
||||
}) {
|
||||
const [showCatalogue, setShowCatalogue] = useState(installedModels.length === 0)
|
||||
const [pulling, setPulling] = useState<string | null>(null)
|
||||
const installedNames = new Set(installedModels.map(m => m.name))
|
||||
|
||||
async function pull(fullName: string) {
|
||||
setPulling(fullName)
|
||||
try {
|
||||
await adminApi.pullOllamaModel(fullName)
|
||||
await new Promise<void>(resolve => {
|
||||
const iv = setInterval(async () => {
|
||||
try {
|
||||
const updated = await onRefresh()
|
||||
if (updated.some(m => m.name === fullName)) { clearInterval(iv); onSelect(fullName); setShowCatalogue(false); resolve() }
|
||||
} catch { /* ignore */ }
|
||||
}, 4000)
|
||||
setTimeout(() => { clearInterval(iv); resolve() }, 1800000)
|
||||
})
|
||||
} finally { setPulling(null) }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Select value={value} onChange={e => onSelect(e.target.value)}>
|
||||
<option value="">— Choisir un modèle installé —</option>
|
||||
{installedModels.map(m => (
|
||||
<option key={m.name} value={m.name}>
|
||||
{m.name}{m.details.parameter_size ? ` (${m.details.parameter_size})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<button type="button" className="flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
onClick={() => setShowCatalogue(v => !v)}>
|
||||
{showCatalogue ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
{showCatalogue ? 'Masquer le catalogue' : 'Installer un nouveau modèle'}
|
||||
</button>
|
||||
{showCatalogue && (
|
||||
<div className="rounded-lg border bg-muted/30 p-3 max-h-72 overflow-y-auto">
|
||||
<ModelCatalogue installedNames={installedNames} pulling={pulling} onPull={pull} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Role Assignment ────────────────────────────────────────────────────────
|
||||
|
||||
const ROLE_LABELS: Record<string, { label: string; desc: string }> = {
|
||||
summary: { label: 'Résumés', desc: 'Génération du résumé quotidien (passe 2)' },
|
||||
report: { label: 'Rapports', desc: 'Réponses aux questions sur les résumés' },
|
||||
filter: { label: 'Filtre articles', desc: 'Sélection des articles pertinents (passe 1)' },
|
||||
}
|
||||
|
||||
function RoleCard({ role, providers, currentProviderID, onSave }: {
|
||||
role: string; providers: AIProvider[]; currentProviderID: string
|
||||
onSave: (providerID: string) => Promise<void>
|
||||
}) {
|
||||
const [providerID, setProviderID] = useState(currentProviderID)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
useEffect(() => { setProviderID(currentProviderID) }, [currentProviderID])
|
||||
const { label, desc } = ROLE_LABELS[role]
|
||||
async function save() {
|
||||
setSaving(true)
|
||||
try { await onSave(providerID); setSaved(true); setTimeout(() => setSaved(false), 2000) }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_auto] items-end">
|
||||
<div>
|
||||
<Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{label}</Label>
|
||||
<p className="text-xs text-muted-foreground mb-2">{desc}</p>
|
||||
<Select value={providerID} onChange={e => setProviderID(e.target.value)}>
|
||||
<option value="">— Fournisseur par défaut —</option>
|
||||
{providers.map(p => <option key={p.id} value={p.id}>{p.name}{p.model ? ` — ${p.model}` : ''}</option>)}
|
||||
</Select>
|
||||
</div>
|
||||
<Button size="sm" onClick={save} disabled={saving} className="whitespace-nowrap">
|
||||
{saving ? <Spinner className="h-3 w-3" /> : saved ? '✓ Sauvegardé' : 'Appliquer'}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Ollama model manager card ──────────────────────────────────────────────
|
||||
|
||||
function OllamaModelsCard({ installedModels, onRefresh, onDelete }: {
|
||||
installedModels: OllamaModelInfo[]
|
||||
onRefresh: () => Promise<OllamaModelInfo[]>
|
||||
onDelete: (name: string) => Promise<void>
|
||||
}) {
|
||||
const [showCatalogue, setShowCatalogue] = useState(false)
|
||||
const [pulling, setPulling] = useState<string | null>(null)
|
||||
const [deleting, setDeleting] = useState<string | null>(null)
|
||||
const installedNames = new Set(installedModels.map(m => m.name))
|
||||
|
||||
async function pull(fullName: string) {
|
||||
setPulling(fullName)
|
||||
try {
|
||||
await adminApi.pullOllamaModel(fullName)
|
||||
await new Promise<void>(resolve => {
|
||||
const iv = setInterval(async () => {
|
||||
try {
|
||||
const updated = await onRefresh()
|
||||
if (updated.some(m => m.name === fullName)) { clearInterval(iv); resolve() }
|
||||
} catch { /* ignore */ }
|
||||
}, 4000)
|
||||
setTimeout(() => { clearInterval(iv); resolve() }, 1800000)
|
||||
})
|
||||
} finally { setPulling(null) }
|
||||
}
|
||||
|
||||
async function remove(name: string) {
|
||||
setDeleting(name)
|
||||
try { await onDelete(name) } finally { setDeleting(null) }
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<HardDrive className="h-4 w-4" /> Modèles Ollama
|
||||
</CardTitle>
|
||||
<Button variant="outline" size="sm" onClick={() => setShowCatalogue(v => !v)}>
|
||||
{showCatalogue ? <><ChevronUp className="h-3.5 w-3.5" /> Masquer</> : <><Download className="h-3.5 w-3.5" /> Installer</>}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold mb-2 flex items-center gap-1.5">
|
||||
<Cpu className="h-3.5 w-3.5" /> Installés ({installedModels.length})
|
||||
</h3>
|
||||
{installedModels.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground italic">Aucun modèle installé</p>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{installedModels.map(m => (
|
||||
<div key={m.name} className="flex items-center justify-between rounded-md border bg-muted/30 px-3 py-2">
|
||||
<div>
|
||||
<span className="font-mono text-sm font-medium">{m.name}</span>
|
||||
<span className="ml-3 text-xs text-muted-foreground">
|
||||
{formatSize(m.size)}
|
||||
{m.details.parameter_size && <> · {m.details.parameter_size}</>}
|
||||
{m.details.quantization_level && <> · {m.details.quantization_level}</>}
|
||||
</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm"
|
||||
className="text-destructive hover:text-destructive h-7 w-7 p-0"
|
||||
onClick={() => remove(m.name)} disabled={deleting === m.name}>
|
||||
{deleting === m.name ? <Spinner className="h-3 w-3" /> : <Trash2 className="h-3 w-3" />}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{showCatalogue && (
|
||||
<div className="rounded-lg border bg-muted/30 p-4">
|
||||
<p className="text-sm font-semibold mb-3">Catalogue</p>
|
||||
<ModelCatalogue installedNames={installedNames} pulling={pulling} onPull={pull} />
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Main Page ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function AIProviders() {
|
||||
const [providers, setProviders] = useState<AIProvider[]>([])
|
||||
const [roles, setRoles] = useState<AIRoles | null>(null)
|
||||
const [ollamaModels, setOllamaModels] = useState<OllamaModelInfo[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [form, setForm] = useState({ name: 'openai', api_key: '', model: '', endpoint: '' })
|
||||
const [editId, setEditId] = useState<string | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const isOllamaForm = form.name === 'ollama'
|
||||
const isClaudeCodeForm = form.name === 'claudecode'
|
||||
|
||||
const loadOllamaModels = useCallback(async (): Promise<OllamaModelInfo[]> => {
|
||||
try {
|
||||
console.log('[ollama] fetching installed models…')
|
||||
const m = await adminApi.listOllamaModels()
|
||||
const list = m ?? []
|
||||
console.log(`[ollama] ${list.length} model(s):`, list.map(x => x.name))
|
||||
setOllamaModels(list)
|
||||
return list
|
||||
} catch (e) {
|
||||
console.error('[ollama] error:', e)
|
||||
return []
|
||||
}
|
||||
}, [])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [p, r] = await Promise.all([adminApi.listProviders(), adminApi.getRoles()])
|
||||
setProviders(p ?? [])
|
||||
setRoles(r)
|
||||
await loadOllamaModels()
|
||||
} finally { setLoading(false) }
|
||||
}, [loadOllamaModels])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
async function save() {
|
||||
setSaving(true); setError('')
|
||||
try {
|
||||
if (editId) { await adminApi.updateProvider(editId, form) }
|
||||
else { await adminApi.createProvider(form) }
|
||||
setShowForm(false); setEditId(null)
|
||||
setForm({ name: 'openai', api_key: '', model: '', endpoint: '' })
|
||||
await load()
|
||||
} catch (e) { setError(e instanceof Error ? e.message : 'Erreur') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
|
||||
async function setDefault(id: string) { await adminApi.activateProvider(id); await load() }
|
||||
async function remove(id: string) {
|
||||
if (!confirm('Supprimer ce fournisseur ?')) return
|
||||
await adminApi.deleteProvider(id); await load()
|
||||
}
|
||||
function startEdit(p: AIProvider) {
|
||||
setEditId(p.id); setForm({ name: p.name, api_key: '', model: p.model, endpoint: p.endpoint }); setShowForm(true)
|
||||
}
|
||||
async function saveRole(role: string, providerID: string) {
|
||||
await adminApi.updateRole(role, { provider_id: providerID, model: '' }); await load()
|
||||
}
|
||||
async function deleteOllamaModel(name: string) {
|
||||
await adminApi.deleteOllamaModel(name); await loadOllamaModels()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Fournisseurs IA</h1>
|
||||
<p className="text-muted-foreground text-sm">Configurez les fournisseurs et assignez un modèle à chaque tâche</p>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-12"><Spinner /></div>
|
||||
) : (
|
||||
<>
|
||||
{/* Role assignments */}
|
||||
{roles && providers.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">Assignation des tâches</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-5 divide-y">
|
||||
{(['summary', 'report', 'filter'] as const).map(role => (
|
||||
<div key={role} className={role !== 'summary' ? 'pt-5' : ''}>
|
||||
<RoleCard role={role} providers={providers}
|
||||
currentProviderID={roles[role].provider_id}
|
||||
onSave={pid => saveRole(role, pid)} />
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Providers list */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">Fournisseurs configurés</CardTitle>
|
||||
<Button size="sm" onClick={() => { setShowForm(true); setEditId(null); setForm({ name: 'openai', api_key: '', model: '', endpoint: '' }) }}>
|
||||
<Plus className="h-4 w-4" /> Ajouter
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{showForm && (
|
||||
<div className="rounded-lg border p-4 space-y-4 bg-muted/30">
|
||||
<p className="font-medium text-sm">{editId ? 'Modifier le fournisseur' : 'Nouveau fournisseur'}</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label>Fournisseur</Label>
|
||||
<Select value={form.name} disabled={!!editId}
|
||||
onChange={e => {
|
||||
const name = e.target.value
|
||||
setForm(f => ({ ...f, name, model: '', api_key: '', endpoint: name === 'ollama' ? 'http://ollama:11434' : '' }))
|
||||
}}>
|
||||
{PROVIDER_NAMES.map(n => <option key={n} value={n}>{n}</option>)}
|
||||
</Select>
|
||||
</div>
|
||||
{!isOllamaForm && !isClaudeCodeForm && (
|
||||
<div className="space-y-1">
|
||||
<Label>Clé API {editId && <span className="text-muted-foreground text-xs">(vide = conserver)</span>}</Label>
|
||||
<Input type="password" placeholder="sk-…" value={form.api_key} onChange={e => setForm(f => ({ ...f, api_key: e.target.value }))} />
|
||||
</div>
|
||||
)}
|
||||
{isOllamaForm && (
|
||||
<div className="space-y-1">
|
||||
<Label>Endpoint</Label>
|
||||
<Input value={form.endpoint || 'http://ollama:11434'} onChange={e => setForm(f => ({ ...f, endpoint: e.target.value }))} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>Modèle par défaut</Label>
|
||||
{isOllamaForm ? (
|
||||
<OllamaModelPicker value={form.model} installedModels={ollamaModels}
|
||||
onSelect={m => setForm(f => ({ ...f, model: m }))}
|
||||
onRefresh={loadOllamaModels} />
|
||||
) : (
|
||||
<CloudModelPicker
|
||||
value={form.model}
|
||||
providerName={form.name}
|
||||
apiKey={form.api_key}
|
||||
endpoint={form.endpoint}
|
||||
onChange={m => setForm(f => ({ ...f, model: m }))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={save} disabled={saving}>{saving ? <Spinner className="h-4 w-4" /> : 'Enregistrer'}</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => { setShowForm(false); setEditId(null) }}>Annuler</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{providers.length === 0 && !showForm && (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">Aucun fournisseur configuré</p>
|
||||
)}
|
||||
|
||||
{providers.map(p => (
|
||||
<div key={p.id} className={`flex flex-wrap items-center gap-3 rounded-md border px-3 py-2.5 ${p.is_active ? 'border-primary/50 bg-primary/5' : ''}`}>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-semibold capitalize text-sm">{p.name}</span>
|
||||
{p.is_active && <Badge variant="default" className="text-xs">Défaut</Badge>}
|
||||
{!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode' && <Badge variant="outline" className="text-yellow-500 border-yellow-500 text-xs">Sans clé</Badge>}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground flex gap-3 mt-0.5">
|
||||
{p.model && <span>Modèle : <strong>{p.model}</strong></span>}
|
||||
{p.endpoint && <span>{p.endpoint}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={() => startEdit(p)}>Modifier</Button>
|
||||
{!p.is_active && (
|
||||
<Button size="sm" variant="outline" className="h-7 px-2 text-xs" onClick={() => setDefault(p.id)}>
|
||||
<Star className="h-3 w-3 mr-1" /> Défaut
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive hover:text-destructive" onClick={() => remove(p.id)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Ollama model manager — always shown so user can install even without provider configured */}
|
||||
<OllamaModelsCard
|
||||
installedModels={ollamaModels}
|
||||
onRefresh={loadOllamaModels}
|
||||
onDelete={deleteOllamaModel}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
47
frontend/src/pages/admin/AdminLayout.tsx
Normal file
47
frontend/src/pages/admin/AdminLayout.tsx
Normal file
@ -0,0 +1,47 @@
|
||||
import { NavLink, Outlet, Navigate } from 'react-router-dom'
|
||||
import { Cpu, Key, Database, ClipboardList, Users, CalendarDays, Settings } from 'lucide-react'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { cn } from '@/lib/cn'
|
||||
|
||||
const adminItems = [
|
||||
{ to: '/admin/ai', icon: Cpu, label: 'Fournisseurs IA' },
|
||||
{ to: '/admin/credentials', icon: Key, label: 'Identifiants' },
|
||||
{ to: '/admin/sources', icon: Database, label: 'Sources' },
|
||||
{ to: '/admin/jobs', icon: ClipboardList,label: 'Jobs' },
|
||||
{ to: '/admin/users', icon: Users, label: 'Utilisateurs' },
|
||||
{ to: '/admin/schedule', icon: CalendarDays, label: 'Planning' },
|
||||
{ to: '/admin/settings', icon: Settings, label: 'Paramètres' },
|
||||
]
|
||||
|
||||
export function AdminLayout() {
|
||||
const { isAdmin } = useAuth()
|
||||
if (!isAdmin) return <Navigate to="/" replace />
|
||||
return (
|
||||
<div>
|
||||
{/* Mobile sub-nav — scrollable horizontal tabs */}
|
||||
<nav className="md:hidden flex overflow-x-auto border-b bg-card scrollbar-none sticky top-0 z-10">
|
||||
{adminItems.map(({ to, icon: Icon, label }) => (
|
||||
<NavLink
|
||||
key={to}
|
||||
to={to}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
'flex shrink-0 flex-col items-center gap-1 px-4 py-3 text-xs font-medium transition-colors border-b-2',
|
||||
isActive
|
||||
? 'border-primary text-primary'
|
||||
: 'border-transparent text-muted-foreground'
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
{label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="p-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
209
frontend/src/pages/admin/AdminSettings.tsx
Normal file
209
frontend/src/pages/admin/AdminSettings.tsx
Normal file
@ -0,0 +1,209 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Save, RotateCcw, Sun, Moon } from 'lucide-react'
|
||||
import { adminApi, type Setting } from '@/api/admin'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { useTheme } from '@/lib/theme'
|
||||
|
||||
const NUMERIC_SETTINGS: Record<string, { label: string; description: string }> = {
|
||||
summary_max_articles: { label: 'Articles max par résumé', description: 'Nombre maximum d\'articles envoyés à l\'IA pour la passe 2 (résumé)' },
|
||||
filter_batch_size: { label: 'Taille des batches (filtre)', description: 'Nombre d\'articles par appel IA lors de la passe 1 (filtrage). Réduire pour des réponses plus rapides.' },
|
||||
}
|
||||
|
||||
const COMMON_TIMEZONES = [
|
||||
'Europe/Paris', 'Europe/London', 'Europe/Berlin', 'Europe/Madrid', 'Europe/Rome',
|
||||
'America/New_York', 'America/Chicago', 'America/Los_Angeles',
|
||||
'Asia/Tokyo', 'Asia/Hong_Kong', 'Asia/Singapore',
|
||||
'UTC',
|
||||
]
|
||||
|
||||
export function AdminSettings() {
|
||||
const { theme, setTheme } = useTheme()
|
||||
const [settings, setSettings] = useState<Setting[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [values, setValues] = useState<Record<string, string>>({})
|
||||
const [defaultPrompt, setDefaultPrompt] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [savingTz, setSavingTz] = useState(false)
|
||||
const [savingPrompt, setSavingPrompt] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
const [savedTz, setSavedTz] = useState(false)
|
||||
const [savedPrompt, setSavedPrompt] = useState(false)
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [s, d] = await Promise.all([
|
||||
adminApi.listSettings(),
|
||||
adminApi.getDefaultPrompt(),
|
||||
])
|
||||
const settled = s ?? []
|
||||
setSettings(settled)
|
||||
setDefaultPrompt(d?.prompt ?? '')
|
||||
const v: Record<string, string> = {}
|
||||
for (const setting of settled) v[setting.key] = setting.value
|
||||
setValues(v)
|
||||
} finally { setLoading(false) }
|
||||
}
|
||||
|
||||
async function saveNumeric() {
|
||||
setSaving(true); setSaved(false)
|
||||
const numericKeys = Object.keys(NUMERIC_SETTINGS)
|
||||
await adminApi.updateSettings(
|
||||
settings
|
||||
.filter(s => numericKeys.includes(s.key))
|
||||
.map(s => ({ key: s.key, value: values[s.key] ?? s.value }))
|
||||
)
|
||||
setSaving(false); setSaved(true)
|
||||
setTimeout(() => setSaved(false), 2000)
|
||||
}
|
||||
|
||||
async function saveTimezone() {
|
||||
setSavingTz(true); setSavedTz(false)
|
||||
await adminApi.updateSettings([{ key: 'timezone', value: values['timezone'] ?? 'Europe/Paris' }])
|
||||
setSavingTz(false); setSavedTz(true)
|
||||
setTimeout(() => setSavedTz(false), 2000)
|
||||
}
|
||||
|
||||
async function savePrompt() {
|
||||
setSavingPrompt(true); setSavedPrompt(false)
|
||||
await adminApi.updateSettings([{ key: 'ai_system_prompt', value: values['ai_system_prompt'] ?? '' }])
|
||||
setSavingPrompt(false); setSavedPrompt(true)
|
||||
setTimeout(() => setSavedPrompt(false), 2000)
|
||||
}
|
||||
|
||||
function resetPrompt() {
|
||||
setValues(v => ({ ...v, ai_system_prompt: defaultPrompt }))
|
||||
}
|
||||
|
||||
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
|
||||
|
||||
const currentPrompt = values['ai_system_prompt'] ?? defaultPrompt
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Paramètres</h1>
|
||||
<p className="text-muted-foreground text-sm">Configuration globale du service</p>
|
||||
</div>
|
||||
|
||||
{/* Apparence */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Apparence</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => setTheme('light')}
|
||||
className={`flex items-center gap-2 px-4 py-2 rounded-md border text-sm font-medium transition-colors ${
|
||||
theme === 'light'
|
||||
? 'bg-primary text-primary-foreground border-primary'
|
||||
: 'bg-transparent text-muted-foreground border-border hover:bg-accent hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
<Sun className="h-4 w-4" />
|
||||
Clair
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTheme('dark')}
|
||||
className={`flex items-center gap-2 px-4 py-2 rounded-md border text-sm font-medium transition-colors ${
|
||||
theme === 'dark'
|
||||
? 'bg-primary text-primary-foreground border-primary'
|
||||
: 'bg-transparent text-muted-foreground border-border hover:bg-accent hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
<Moon className="h-4 w-4" />
|
||||
Sombre
|
||||
</button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Fuseau horaire */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Fuseau horaire</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<Label>Timezone (IANA)</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Utilisé pour le planning de scraping et l'horodatage des résumés
|
||||
</p>
|
||||
<div className="flex gap-2 max-w-sm">
|
||||
<Input
|
||||
list="tz-list"
|
||||
value={values['timezone'] ?? 'Europe/Paris'}
|
||||
onChange={e => setValues(v => ({ ...v, timezone: e.target.value }))}
|
||||
placeholder="Europe/Paris"
|
||||
/>
|
||||
<datalist id="tz-list">
|
||||
{COMMON_TIMEZONES.map(tz => <option key={tz} value={tz} />)}
|
||||
</datalist>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={saveTimezone} disabled={savingTz}>
|
||||
{savingTz ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
|
||||
{savedTz ? 'Enregistré !' : 'Enregistrer'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Paramètres généraux */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Paramètres généraux</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{settings.filter(s => NUMERIC_SETTINGS[s.key]).map(s => {
|
||||
const meta = NUMERIC_SETTINGS[s.key]
|
||||
return (
|
||||
<div key={s.key} className="space-y-1">
|
||||
<Label>{meta.label}</Label>
|
||||
<p className="text-xs text-muted-foreground">{meta.description}</p>
|
||||
<Input
|
||||
value={values[s.key] ?? ''}
|
||||
onChange={e => setValues(v => ({ ...v, [s.key]: e.target.value }))}
|
||||
className="max-w-xs"
|
||||
type="number"
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<Button onClick={saveNumeric} disabled={saving}>
|
||||
{saving ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
|
||||
{saved ? 'Enregistré !' : 'Enregistrer'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Contexte IA */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Contexte IA</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Instructions envoyées à l'IA avant les articles. Les actifs de ta watchlist et les articles sont ajoutés automatiquement après ce texte.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<textarea
|
||||
className="w-full min-h-[280px] rounded-md border border-input bg-background px-3 py-2 text-sm font-mono resize-y focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
value={currentPrompt}
|
||||
onChange={e => setValues(v => ({ ...v, ai_system_prompt: e.target.value }))}
|
||||
spellCheck={false}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={savePrompt} disabled={savingPrompt}>
|
||||
{savingPrompt ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
|
||||
{savedPrompt ? 'Enregistré !' : 'Enregistrer le contexte'}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={resetPrompt} title="Remettre le contexte par défaut">
|
||||
<RotateCcw className="h-4 w-4" /> Réinitialiser
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
113
frontend/src/pages/admin/AdminUsers.tsx
Normal file
113
frontend/src/pages/admin/AdminUsers.tsx
Normal file
@ -0,0 +1,113 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Trash2, Pencil } from 'lucide-react'
|
||||
import { adminApi, type AdminUser } from '@/api/admin'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select } from '@/components/ui/select'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
|
||||
export function AdminUsers() {
|
||||
const { user: me } = useAuth()
|
||||
const [users, setUsers] = useState<AdminUser[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [editId, setEditId] = useState<string | null>(null)
|
||||
const [editForm, setEditForm] = useState({ email: '', role: 'user' })
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try { setUsers((await adminApi.listUsers()) ?? []) } finally { setLoading(false) }
|
||||
}
|
||||
|
||||
function startEdit(u: AdminUser) {
|
||||
setEditId(u.id); setEditForm({ email: u.email, role: u.role }); setError('')
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!editId) return
|
||||
setSaving(true); setError('')
|
||||
try {
|
||||
await adminApi.updateUser(editId, editForm.email, editForm.role)
|
||||
setEditId(null); await load()
|
||||
} catch (e) { setError(e instanceof Error ? e.message : 'Erreur') } finally { setSaving(false) }
|
||||
}
|
||||
|
||||
async function remove(id: string) {
|
||||
if (!confirm('Supprimer cet utilisateur ?')) return
|
||||
await adminApi.deleteUser(id)
|
||||
await load()
|
||||
}
|
||||
|
||||
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Utilisateurs</h1>
|
||||
<p className="text-muted-foreground text-sm">{users.length} utilisateur(s)</p>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Liste</CardTitle></CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b">
|
||||
<tr className="text-left text-muted-foreground">
|
||||
<th className="px-4 py-3">Email</th>
|
||||
<th className="px-4 py-3">Rôle</th>
|
||||
<th className="px-4 py-3">Inscrit le</th>
|
||||
<th className="px-4 py-3">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map(u => (
|
||||
<tr key={u.id} className="border-b last:border-0 hover:bg-muted/30">
|
||||
<td className="px-4 py-3">
|
||||
{editId === u.id ? (
|
||||
<Input value={editForm.email} onChange={e => setEditForm(f => ({ ...f, email: e.target.value }))} className="h-7" />
|
||||
) : (
|
||||
<span className={u.id === me?.id ? 'font-medium' : ''}>{u.email}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
{editId === u.id ? (
|
||||
<Select value={editForm.role} onChange={e => setEditForm(f => ({ ...f, role: e.target.value }))} className="h-7 w-28">
|
||||
<option value="user">user</option>
|
||||
<option value="admin">admin</option>
|
||||
</Select>
|
||||
) : (
|
||||
<Badge variant={u.role === 'admin' ? 'default' : 'secondary'}>{u.role}</Badge>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{new Date(u.created_at).toLocaleDateString('fr-FR')}</td>
|
||||
<td className="px-4 py-3">
|
||||
{editId === u.id ? (
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={save} disabled={saving}>{saving ? <Spinner className="h-3 w-3" /> : 'OK'}</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => setEditId(null)}>Annuler</Button>
|
||||
{error && <span className="text-destructive text-xs">{error}</span>}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="icon" className="h-7 w-7" onClick={() => startEdit(u)}><Pencil className="h-3 w-3" /></Button>
|
||||
{u.id !== me?.id && (
|
||||
<Button variant="destructive" size="icon" className="h-7 w-7" onClick={() => remove(u.id)}><Trash2 className="h-3 w-3" /></Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
114
frontend/src/pages/admin/Credentials.tsx
Normal file
114
frontend/src/pages/admin/Credentials.tsx
Normal file
@ -0,0 +1,114 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Eye, EyeOff, Save } from 'lucide-react'
|
||||
import { adminApi, type Credential } from '@/api/admin'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
|
||||
export function Credentials() {
|
||||
const [creds, setCreds] = useState<Credential[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [forms, setForms] = useState<Record<string, { username: string; password: string; show: boolean }>>({})
|
||||
const [saving, setSaving] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await adminApi.getCredentials()
|
||||
setCreds(data ?? [])
|
||||
const init: typeof forms = {}
|
||||
for (const c of data ?? []) {
|
||||
init[c.source_id] = { username: c.username, password: '', show: false }
|
||||
}
|
||||
setForms(init)
|
||||
} finally { setLoading(false) }
|
||||
}
|
||||
|
||||
function update(sourceId: string, field: string, value: string | boolean) {
|
||||
setForms(f => ({ ...f, [sourceId]: { ...f[sourceId], [field]: value } }))
|
||||
}
|
||||
|
||||
async function save(sourceId: string) {
|
||||
setSaving(sourceId); setSuccess(null)
|
||||
const f = forms[sourceId]
|
||||
await adminApi.updateCredentials({
|
||||
source_id: sourceId,
|
||||
username: f.username,
|
||||
...(f.password ? { password: f.password } : {}),
|
||||
})
|
||||
setSaving(null)
|
||||
setSuccess(sourceId)
|
||||
setTimeout(() => setSuccess(null), 2000)
|
||||
await load()
|
||||
}
|
||||
|
||||
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Identifiants de scraping</h1>
|
||||
<p className="text-muted-foreground text-sm">Les mots de passe sont chiffrés en AES-256-GCM côté serveur</p>
|
||||
</div>
|
||||
|
||||
{creds.length === 0 && (
|
||||
<Card><CardContent className="py-8 text-center text-muted-foreground">Aucune source nécessitant des identifiants</CardContent></Card>
|
||||
)}
|
||||
|
||||
{creds.map(cred => {
|
||||
const f = forms[cred.source_id] ?? { username: '', password: '', show: false }
|
||||
return (
|
||||
<Card key={cred.source_id}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">{cred.source_name}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`user-${cred.source_id}`}>Identifiant / Email</Label>
|
||||
<Input
|
||||
id={`user-${cred.source_id}`}
|
||||
value={f.username}
|
||||
onChange={e => update(cred.source_id, 'username', e.target.value)}
|
||||
placeholder="votre@email.com"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`pwd-${cred.source_id}`}>
|
||||
Mot de passe {cred.has_password && <span className="text-muted-foreground">(déjà défini — laisser vide pour ne pas changer)</span>}
|
||||
</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={`pwd-${cred.source_id}`}
|
||||
type={f.show ? 'text' : 'password'}
|
||||
value={f.password}
|
||||
onChange={e => update(cred.source_id, 'password', e.target.value)}
|
||||
placeholder={cred.has_password ? '••••••••' : 'Nouveau mot de passe'}
|
||||
className="pr-10"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => update(cred.source_id, 'show', !f.show)}
|
||||
>
|
||||
{f.show ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={() => save(cred.source_id)} disabled={saving === cred.source_id}>
|
||||
{saving === cred.source_id ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
|
||||
{success === cred.source_id ? 'Enregistré !' : 'Enregistrer'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
109
frontend/src/pages/admin/Jobs.tsx
Normal file
109
frontend/src/pages/admin/Jobs.tsx
Normal file
@ -0,0 +1,109 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Play, RefreshCw } from 'lucide-react'
|
||||
import { adminApi, type ScrapeJob, type Source } from '@/api/admin'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Select } from '@/components/ui/select'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
|
||||
function jobStatusVariant(status: string) {
|
||||
if (status === 'done') return 'bullish'
|
||||
if (status === 'error') return 'bearish'
|
||||
if (status === 'running') return 'default'
|
||||
return 'outline'
|
||||
}
|
||||
|
||||
function fmtDate(t: { Time: string; Valid: boolean } | null) {
|
||||
if (!t?.Valid) return '—'
|
||||
return new Date(t.Time).toLocaleString('fr-FR')
|
||||
}
|
||||
|
||||
export function Jobs() {
|
||||
const [jobs, setJobs] = useState<ScrapeJob[]>([])
|
||||
const [sources, setSources] = useState<Source[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [triggering, setTriggering] = useState(false)
|
||||
const [selectedSource, setSelectedSource] = useState('')
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [j, s] = await Promise.all([adminApi.listJobs(), adminApi.listSources()])
|
||||
setJobs(j ?? [])
|
||||
setSources(s ?? [])
|
||||
if (s?.[0]) setSelectedSource(s[0].id)
|
||||
} finally { setLoading(false) }
|
||||
}
|
||||
|
||||
async function trigger() {
|
||||
if (!selectedSource) return
|
||||
setTriggering(true)
|
||||
await adminApi.triggerJob(selectedSource)
|
||||
setTimeout(() => { load(); setTriggering(false) }, 1000)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Jobs de scraping</h1>
|
||||
<p className="text-muted-foreground text-sm">Historique et déclenchement manuel</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Select value={selectedSource} onChange={e => setSelectedSource(e.target.value)} className="w-40">
|
||||
{sources.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||||
</Select>
|
||||
<Button onClick={trigger} disabled={triggering || !selectedSource}>
|
||||
{triggering ? <Spinner className="h-4 w-4" /> : <Play className="h-4 w-4" />}
|
||||
Lancer
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" onClick={load}><RefreshCw className="h-4 w-4" /></Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-12"><Spinner /></div>
|
||||
) : (
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Historique</CardTitle></CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b">
|
||||
<tr className="text-left text-muted-foreground">
|
||||
<th className="px-4 py-3">Source</th>
|
||||
<th className="px-4 py-3">Statut</th>
|
||||
<th className="px-4 py-3">Début</th>
|
||||
<th className="px-4 py-3">Fin</th>
|
||||
<th className="px-4 py-3">Articles</th>
|
||||
<th className="px-4 py-3">Erreur</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{jobs.map(j => (
|
||||
<tr key={j.id} className="border-b last:border-0 hover:bg-muted/30">
|
||||
<td className="px-4 py-3 font-medium">{j.source_name}</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={jobStatusVariant(j.status) as 'bullish' | 'bearish' | 'default' | 'outline'}>{j.status}</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{fmtDate(j.started_at)}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{fmtDate(j.finished_at)}</td>
|
||||
<td className="px-4 py-3">{j.articles_found}</td>
|
||||
<td className="px-4 py-3 text-destructive max-w-xs truncate">{j.error_msg || '—'}</td>
|
||||
</tr>
|
||||
))}
|
||||
{jobs.length === 0 && (
|
||||
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">Aucun job</td></tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
145
frontend/src/pages/admin/Schedule.tsx
Normal file
145
frontend/src/pages/admin/Schedule.tsx
Normal file
@ -0,0 +1,145 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Plus, Trash2, Save } from 'lucide-react'
|
||||
import { adminApi, type ScheduleSlot } from '@/api/admin'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
|
||||
const DAYS = [
|
||||
{ label: 'Lundi', short: 'LUN', value: 1 },
|
||||
{ label: 'Mardi', short: 'MAR', value: 2 },
|
||||
{ label: 'Mercredi', short: 'MER', value: 3 },
|
||||
{ label: 'Jeudi', short: 'JEU', value: 4 },
|
||||
{ label: 'Vendredi', short: 'VEN', value: 5 },
|
||||
{ label: 'Samedi', short: 'SAM', value: 6 },
|
||||
{ label: 'Dimanche', short: 'DIM', value: 0 },
|
||||
]
|
||||
|
||||
type SlotKey = `${number}-${number}-${number}`
|
||||
|
||||
function toKey(s: ScheduleSlot): SlotKey {
|
||||
return `${s.day_of_week}-${s.hour}-${s.minute}`
|
||||
}
|
||||
|
||||
function fmt(h: number, m: number) {
|
||||
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function Schedule() {
|
||||
const [slots, setSlots] = useState<ScheduleSlot[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
const [newTimes, setNewTimes] = useState<Record<number, string>>({})
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try { setSlots((await adminApi.getSchedule()) ?? []) } finally { setLoading(false) }
|
||||
}
|
||||
|
||||
function slotsForDay(day: number) {
|
||||
return slots
|
||||
.filter(s => s.day_of_week === day)
|
||||
.sort((a, b) => a.hour !== b.hour ? a.hour - b.hour : a.minute - b.minute)
|
||||
}
|
||||
|
||||
function addSlot(day: number) {
|
||||
const time = newTimes[day] || '06:00'
|
||||
const [h, m] = time.split(':').map(Number)
|
||||
const newSlot: ScheduleSlot = { day_of_week: day, hour: h, minute: m }
|
||||
if (slots.some(s => toKey(s) === toKey(newSlot))) return
|
||||
setSlots(prev => [...prev, newSlot])
|
||||
setNewTimes(p => ({ ...p, [day]: '06:00' }))
|
||||
}
|
||||
|
||||
function removeSlot(slot: ScheduleSlot) {
|
||||
setSlots(prev => prev.filter(s => toKey(s) !== toKey(slot)))
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setSaving(true); setSaved(false)
|
||||
await adminApi.updateSchedule(slots)
|
||||
setSaving(false); setSaved(true)
|
||||
setTimeout(() => setSaved(false), 2000)
|
||||
}
|
||||
|
||||
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Planning hebdomadaire</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Définissez les créneaux de scraping + résumé IA pour chaque jour
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={save} disabled={saving}>
|
||||
{saving ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
|
||||
{saved ? 'Enregistré !' : 'Enregistrer'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-7 gap-3">
|
||||
{DAYS.map(day => {
|
||||
const daySlots = slotsForDay(day.value)
|
||||
const isWeekend = day.value === 0 || day.value === 6
|
||||
return (
|
||||
<Card key={day.value} className={isWeekend ? 'border-muted' : ''}>
|
||||
<CardHeader className="pb-2 pt-4 px-4">
|
||||
<CardTitle className="text-sm font-semibold">
|
||||
<span className="hidden xl:block">{day.label}</span>
|
||||
<span className="xl:hidden">{day.short}</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="px-4 pb-4 space-y-2">
|
||||
{/* Créneaux existants */}
|
||||
{daySlots.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground italic">Aucun créneau</p>
|
||||
)}
|
||||
{daySlots.map(slot => (
|
||||
<div
|
||||
key={toKey(slot)}
|
||||
className="flex items-center justify-between rounded bg-primary/10 px-2 py-1"
|
||||
>
|
||||
<span className="text-sm font-mono font-medium">
|
||||
{fmt(slot.hour, slot.minute)}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => removeSlot(slot)}
|
||||
className="text-muted-foreground hover:text-destructive transition-colors ml-2"
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Ajout d'un créneau */}
|
||||
<div className="flex items-center gap-1 pt-1">
|
||||
<input
|
||||
type="time"
|
||||
value={newTimes[day.value] ?? '06:00'}
|
||||
onChange={e => setNewTimes(p => ({ ...p, [day.value]: e.target.value }))}
|
||||
className="flex-1 min-w-0 rounded border border-input bg-background px-2 py-1 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
<button
|
||||
onClick={() => addSlot(day.value)}
|
||||
className="rounded bg-primary/10 p-1 hover:bg-primary/20 transition-colors"
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
À chaque créneau, le service lance le scraping de toutes les sources actives puis génère les résumés IA.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
56
frontend/src/pages/admin/Sources.tsx
Normal file
56
frontend/src/pages/admin/Sources.tsx
Normal file
@ -0,0 +1,56 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { adminApi, type Source } from '@/api/admin'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
export function Sources() {
|
||||
const [sources, setSources] = useState<Source[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [toggling, setToggling] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try { setSources((await adminApi.listSources()) ?? []) } finally { setLoading(false) }
|
||||
}
|
||||
|
||||
async function toggle(s: Source) {
|
||||
setToggling(s.id)
|
||||
await adminApi.updateSource(s.id, !s.enabled)
|
||||
await load()
|
||||
setToggling(null)
|
||||
}
|
||||
|
||||
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Sources de news</h1>
|
||||
<p className="text-muted-foreground text-sm">Activez ou désactivez les sources de données</p>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{sources.map(s => (
|
||||
<Card key={s.id}>
|
||||
<CardContent className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<span className="font-semibold">{s.name}</span>
|
||||
<span className="ml-2 text-xs text-muted-foreground capitalize">({s.type})</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={s.enabled ? 'default' : 'outline'}>
|
||||
{s.enabled ? 'Activée' : 'Désactivée'}
|
||||
</Badge>
|
||||
<Button variant="outline" size="sm" onClick={() => toggle(s)} disabled={toggling === s.id}>
|
||||
{toggling === s.id ? <Spinner className="h-3 w-3" /> : s.enabled ? 'Désactiver' : 'Activer'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user