247 lines
12 KiB
TypeScript
247 lines
12 KiB
TypeScript
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 { GenerationDetails } from '@/components/GenerationDetails'
|
||
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'
|
||
import { generationCopy } from '@/i18n/generation'
|
||
|
||
// ── Summary content renderer ────────────────────────────────────────────────
|
||
|
||
function SummaryContent({ content }: { content: string }) {
|
||
return <Markdown content={content} />
|
||
}
|
||
|
||
// ── 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 [outcome, setOutcome] = useState<GenerationOutcome | null>(null)
|
||
const [message, setMessage] = useState('')
|
||
const [failed, setFailed] = useState(false)
|
||
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)
|
||
setFailed(job?.status === 'failed')
|
||
setMessage(!job || job.status === 'running' ? '' : job.status === 'failed'
|
||
? copy.failed
|
||
: job.status === 'no_results' ? copy.empty
|
||
: copy.succeeded)
|
||
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); setMessage('') }
|
||
} 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 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); setMessage(''); setFailed(false); 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
|
||
|
||
const selectedModel = models.find(model => model.id === preferences?.summary_model_id)
|
||
|
||
return (
|
||
<div className="p-4 md:p-6 space-y-6">
|
||
{/* 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>
|
||
|
||
<div className="space-y-2">
|
||
{preferences ? <p>Prochaine synthèse : {preferences.language === 'fr' ? 'Français' : 'English'} · Classement par {preferences.ranking_mode === 'title_content' ? 'titre et contenu disponible' : 'titre uniquement'}</p> : <p>Chargement des préférences…</p>}
|
||
{selectedModel ? <p>Modèle de synthèse : {selectedModel.provider} · {selectedModel.model}</p> : <p>Aucun modèle de synthèse disponible sélectionné. Choisissez un modèle dans Mes préférences avant de générer.</p>}
|
||
<a href="/preferences" className="text-primary underline">Modifier mes préférences</a>
|
||
</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 && <p role={failed ? 'alert' : 'status'}>{message}</p>}
|
||
{(failed || outcome?.status === 'no_results') && <Button onClick={generate} disabled={generating || checking || uncertain || !selectedModel || assets.length === 0}>{copy.retry}</Button>}
|
||
{outcome && <GenerationDetails outcome={outcome} />}
|
||
|
||
{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>
|
||
)}
|
||
|
||
{assets.length > 0 && (
|
||
<div aria-label="Indices actuellement suivis" className="flex flex-wrap gap-2">
|
||
{assets.map(a => (
|
||
<Badge key={a.id} variant="secondary"><span>{a.name}</span><span className="ml-2 font-mono">{a.symbol}</span></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" /> Synthèse
|
||
</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>
|
||
<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>
|
||
<SummaryContent 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 "Générer une synthèse" 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' : ''}`}
|
||
>
|
||
<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>
|
||
<button className="text-sm text-left line-clamp-3" onClick={() => { setCurrent(s); setOutcome(null); setMessage('') }}>{s.content.slice(0, 120)}…</button>
|
||
</CardContent>
|
||
</Card>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
{!outcome && currentOutcome && <GenerationDetails outcome={currentOutcome} />}
|
||
|
||
</div>
|
||
)
|
||
}
|