Files
TradarrV2/frontend/src/pages/Dashboard.tsx

262 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useEffect, useRef, useCallback } from 'react'
import { TrendingUp, Clock, Sparkles, Loader2 } from 'lucide-react'
import { summariesApi, type Summary, type GenerationOutcome, type GenerationHistory, type GenerationJob } from '@/api/summaries'
import { preferencesApi, type UserPreferences, type SummaryModelOption } from '@/api/preferences'
import { assetsApi, type Asset } from '@/api/assets'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { SummaryQA } from '@/components/SummaryQA'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import { useAuth } from '@/lib/auth'
import { generationCopy, generationLimitMessage, generationFailureMessage } from '@/i18n/generation'
// ── Summary content renderer ────────────────────────────────────────────────
function PromptBudgetRemoval({ outcome }: { outcome?: GenerationOutcome | null }) {
const count = outcome?.articles_removed_for_prompt_budget
if (!outcome || !Number.isSafeInteger(count) || !count || count < 1) return null
return <p className="text-xs text-muted-foreground mt-1">{count === 1
? '1 article ancien a été retiré pour respecter le plafond du prompt.'
: `${count} articles parmi les plus anciens ont été retirés pour respecter le plafond du prompt.`}</p>
}
// ── Dashboard ───────────────────────────────────────────────────────────────
export function Dashboard() {
const { user } = useAuth()
const copy = generationCopy[document.documentElement.lang.startsWith('en') ? 'en' : 'fr']
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 [models, setModels] = useState<SummaryModelOption[]>([])
const [preferences, setPreferences] = useState<UserPreferences | null>(null)
const [history, setHistory] = useState<GenerationHistory[]>([])
const [outcomeSummaryId, setOutcomeSummaryId] = useState<string | null>(null)
const [outcome, setOutcome] = useState<GenerationOutcome | null>(null)
const [completedJob, setCompletedJob] = useState<GenerationJob | null>(null)
const [loadError, setLoadError] = useState('')
const requestPending = useRef(false)
const jobRef = useRef<GenerationJob | null>(null)
const [checking, setChecking] = useState(true)
const [uncertain, setUncertain] = useState(false)
const acceptRef = useRef<(job: GenerationJob) => void>(() => {})
const verifyRef = useRef<() => void>(() => {})
const load = useCallback(() => {
return Promise.allSettled([
summariesApi.list(5), assetsApi.list(), preferencesApi.get(), summariesApi.generations(), preferencesApi.listSummaryModels(),
]).then(results => {
const [summaryResult, assetResult, preferenceResult, historyResult, modelResult] = results
if (summaryResult.status === 'fulfilled') {
setSummaries(summaryResult.value ?? [])
setCurrent(previous => summaryResult.value?.[0] ?? previous)
}
if (assetResult.status === 'fulfilled') setAssets(assetResult.value ?? [])
if (preferenceResult.status === 'fulfilled') setPreferences(preferenceResult.value)
if (modelResult.status === 'fulfilled') setModels(modelResult.value ?? [])
if (historyResult.status === 'fulfilled') setHistory(historyResult.value ?? [])
setLoadError(results.some(result => result.status === 'rejected') ? 'Certaines données n’ont pas pu être chargées. Réessayez.' : '')
setLoading(false)
})
}, [])
useEffect(() => { void load() }, [load])
useEffect(() => {
let disposed = false
let busy = false
let timer: ReturnType<typeof setTimeout> | undefined
const apply = async (job: GenerationJob | null) => {
jobRef.current = job
setUncertain(false)
setGenerating(job?.status === 'running')
setOutcome(job?.outcome ?? null)
setOutcomeSummaryId(job?.summary_id ?? null)
if (job?.status !== 'running') setCompletedJob(job)
if (job && job.status !== 'running') await load()
}
const verify = async (accepted?: GenerationJob) => {
if (busy || disposed || requestPending.current) return
busy = true
clearTimeout(timer)
setChecking(true)
try {
const job = accepted ?? await (jobRef.current?.status === 'running'
? summariesApi.getJob(jobRef.current.id) : summariesApi.recentJob())
if (!disposed) await apply(job)
} catch {
if (!disposed) { setUncertain(true); setGenerating(false) }
} finally {
busy = false
if (!disposed) {
setChecking(false)
if (jobRef.current?.status === 'running') timer = setTimeout(() => void verify(), 5000)
}
}
}
verifyRef.current = () => { void verify() }
const visible = () => { if (document.visibilityState === 'visible') { void load(); void verify() } }
acceptRef.current = job => { void verify(job) }
window.addEventListener('focus', visible)
document.addEventListener('visibilitychange', visible)
void verify()
return () => {
disposed = true
clearTimeout(timer)
acceptRef.current = () => {}
window.removeEventListener('focus', visible)
document.removeEventListener('visibilitychange', visible)
}
}, [load, copy])
async function generate() {
if (requestPending.current || generating || checking || uncertain || assets.length === 0 || !selectedModel) return
requestPending.current = true
setGenerating(true); setOutcome(null)
try {
const job = await summariesApi.generate()
requestPending.current = false
acceptRef.current(job)
} catch {
setGenerating(false)
setUncertain(true)
} finally { requestPending.current = false }
}
const currentOutcome = history.find(item => item.summary_id === current?.id)?.outcome
?? (current && outcomeSummaryId === current.id ? outcome : null)
const newestHistory = history[0]
const historyIsNewer = newestHistory && (!completedJob ||
Date.parse(newestHistory.created_at) > Date.parse(completedJob.finished_at ?? completedJob.created_at))
const latest = historyIsNewer ? newestHistory.outcome : completedJob
const latestOutcome = historyIsNewer ? newestHistory.outcome : completedJob?.outcome
const latestSummaryId = historyIsNewer ? newestHistory.summary_id : completedJob?.summary_id
const failureCode = latest?.failure_code ?? latestOutcome?.failure_code
const failed = latest?.status === 'failed'
const lastFailure = failed ? failureCode ?? '' : null
const message = !latest || generating || uncertain ? '' : generationLimitMessage(failureCode)
?? (latest.status === 'no_results' ? copy.empty : copy.succeeded)
const selectedModel = models.find(model => model.id === preferences?.summary_model_id)
return (
<div className="p-4 md:p-6 space-y-6">
{lastFailure !== null && <p role="alert">{generationFailureMessage(lastFailure)}</p>}
{(lastFailure === 'ranking_model_unavailable' || lastFailure === 'ranking_model_incompatible') && <a href="/preferences" className="text-primary underline">Mes préférences</a>}
{latestOutcome && latestSummaryId && latestSummaryId !== current?.id && <PromptBudgetRemoval outcome={latestOutcome} />}
{/* Generating banner */}
{generating && !uncertain && (
<div role="status" 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" />
{copy.running}
</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 || checking || uncertain || loading || assets.length === 0 || !selectedModel}>
{generating && !uncertain ? <><Spinner className="h-4 w-4" /> {copy.pending}</> : <><Sparkles className="h-4 w-4" /> {copy.generate}</>}
</Button>
</div>
{loadError && <div role="alert"><p>{loadError}</p><Button onClick={() => void load()}>Recharger</Button></div>}
{uncertain && <div role="status"><p>{copy.uncertain}</p><Button onClick={() => verifyRef.current()} disabled={checking}>{copy.verify}</Button></div>}
{message && !failed && <p role="status">{message}</p>}
{(failed || latest?.status === 'no_results') && !['summary_capacity_unknown', 'summary_prompt_budget_exceeded'].includes(failureCode ?? '') && <Button onClick={generate} disabled={generating || checking || uncertain || !selectedModel || assets.length === 0}>{copy.retry}</Button>}
{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">Aucun indice suivi</p>
<p className="text-sm text-muted-foreground mt-1">Ajoutez des indices pour obtenir des synthèses personnalisées.</p>
<a href="/assets" className="text-primary underline">Gérer mes indices</a>
</CardContent>
</Card>
)}
{/* 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" /> Synthèse
</CardTitle>
<div>
<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>
<PromptBudgetRemoval outcome={currentOutcome} />
</div>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-3">Langue de cette synthèse : {currentOutcome ? (currentOutcome.language === 'fr' ? 'Français' : 'English') : 'non renseignée'}</p>
<SummaryQA summaryId={current.id} content={current.content} />
<p className="mt-3 text-sm text-muted-foreground">Modèle utilisé : {current.provider_name && current.model_name ? `${current.provider_name} · ${current.model_name}` : 'non renseigné pour cette synthèse historique'}</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>Aucune synthèse disponible</p>
<p className="text-xs mt-1">Cliquez sur &quot;Générer une synthèse&quot; pour commencer</p>
</CardContent>
</Card>
)}
</div>
{/* Historique résumés */}
{(summaries.length > 1 || history.some(item => !item.summary_id)) && (
<div className="space-y-3">
<h2 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">Historique</h2>
{history.filter(item => !item.summary_id).map(item => (
<Card key={item.id}>
<CardContent className="py-3">
<div className="text-xs text-muted-foreground">{new Date(item.created_at).toLocaleString('fr-FR')}</div>
<PromptBudgetRemoval outcome={item.outcome} />
<p className="text-sm">{item.outcome.status === 'failed'
? generationFailureMessage(item.outcome.failure_code)
: generationLimitMessage(item.outcome.failure_code) ?? copy.empty}</p>
</CardContent>
</Card>
))}
{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' : ''}`}
>
<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>
<PromptBudgetRemoval outcome={history.find(item => item.summary_id === s.id)?.outcome} />
<button className="text-sm text-left line-clamp-3" onClick={() => { setCurrent(s) }}>{s.content.slice(0, 120)}…</button>
</CardContent>
</Card>
))}
</div>
)}
</div>
</div>
)
}