feat: Rapport de Cycle — auto-généré à chaque run avec contexte IA, delta, PnL/VaR snapshot
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -15,7 +15,7 @@ const nav = [
|
||||
{ to: '/patterns', icon: Zap, label: 'Patterns' },
|
||||
{ to: '/portfolio', icon: DollarSign, label: 'Portefeuille' },
|
||||
{ to: '/journal', icon: BookOpen, label: 'Journal de Bord' },
|
||||
{ to: '/rapport', icon: FileBarChart, label: 'Rapport IA' },
|
||||
{ to: '/rapport', icon: FileBarChart, label: 'Rapport de Cycle' },
|
||||
{ to: '/super-contexte', icon: Brain, label: 'Super Contexte' },
|
||||
{ to: '/analytics', icon: FlaskConical, label: 'Analytics' },
|
||||
{ to: '/analytics-advanced', icon: Microscope, label: 'Analytics Avancées' },
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useState } from 'react'
|
||||
import { Brain, TrendingUp, TrendingDown, RefreshCw, Zap, AlertTriangle, BookOpen, Target, Eye, Clock, ChevronRight, Trash2 } from 'lucide-react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import clsx from 'clsx'
|
||||
import { usePortfolioReportData, useGeneratePortfolioReport, useAiReportsList, useAiReport, useDeleteAiReport } from '../hooks/useApi'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Brain, TrendingUp, TrendingDown, RefreshCw, ShieldAlert,
|
||||
GitCompare, Layers, Zap, BookOpen, Clock, ChevronRight,
|
||||
} from 'lucide-react'
|
||||
|
||||
const SCENARIO_META: Record<string, { label: string; color: string; emoji: string }> = {
|
||||
goldilocks: { label: 'Goldilocks', color: '#22c55e', emoji: '🌟' },
|
||||
@@ -16,11 +18,12 @@ const SCENARIO_META: Record<string, { label: string; color: string; emoji: strin
|
||||
incertain: { label: 'Incertain', color: '#64748b', emoji: '❓' },
|
||||
}
|
||||
|
||||
function ScenarioBadge({ dominant }: { dominant: string }) {
|
||||
function RegimeBadge({ dominant }: { dominant?: string }) {
|
||||
if (!dominant) return null
|
||||
const m = SCENARIO_META[dominant] ?? SCENARIO_META.incertain
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] font-semibold"
|
||||
className="inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-semibold"
|
||||
style={{ background: `${m.color}22`, color: m.color, border: `1px solid ${m.color}44` }}
|
||||
>
|
||||
{m.emoji} {m.label}
|
||||
@@ -28,499 +31,415 @@ function ScenarioBadge({ dominant }: { dominant: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
function PnlBar({ pnl }: { pnl: number }) {
|
||||
const pos = pnl >= 0
|
||||
const width = Math.min(Math.abs(pnl), 200) / 2 // cap at 100% width
|
||||
function Section({ icon, title, children }: { icon: React.ReactNode; title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={clsx('font-bold font-mono text-sm w-16 text-right', pos ? 'text-emerald-400' : 'text-red-400')}>
|
||||
{pos ? '+' : ''}{pnl.toFixed(1)}%
|
||||
</span>
|
||||
<div className="flex-1 h-1.5 bg-dark-700 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full rounded-full"
|
||||
style={{ width: `${width}%`, background: pos ? '#22c55e' : '#ef4444' }}
|
||||
/>
|
||||
<div className="card mb-4">
|
||||
<div className="flex items-center gap-2 mb-3 pb-2 border-b border-slate-700/40">
|
||||
<span className="text-slate-400">{icon}</span>
|
||||
<span className="text-sm font-semibold text-slate-200">{title}</span>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ScoreTrend({ trend }: { trend: number[] }) {
|
||||
if (!trend || trend.length === 0) return <span className="text-slate-700 text-xs">—</span>
|
||||
return (
|
||||
<div className="flex items-end gap-0.5 h-6">
|
||||
{trend.map((s, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="w-2 rounded-sm"
|
||||
style={{
|
||||
height: `${Math.max(3, (s ?? 0) / 100 * 24)}px`,
|
||||
background: (s ?? 0) >= 60 ? '#22c55e' : (s ?? 0) >= 40 ? '#eab308' : '#64748b',
|
||||
}}
|
||||
title={`${s}/100`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MoverCard({ trade, rank, type }: { trade: any; rank: number; type: 'winner' | 'loser' }) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const pnl = trade.pnl_pct ?? 0
|
||||
const sc = trade.scoring_context ?? {}
|
||||
const scOut = sc.output ?? {}
|
||||
const sg = trade.suggestion_context ?? {}
|
||||
const sgOut = sg.output ?? {}
|
||||
const buckets: any[] = scOut.buckets ?? []
|
||||
const isWinner = type === 'winner'
|
||||
|
||||
return (
|
||||
<div className={clsx(
|
||||
'card border',
|
||||
isWinner ? 'border-emerald-700/20' : 'border-red-700/20'
|
||||
)}>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Rank */}
|
||||
<div className={clsx(
|
||||
'w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0',
|
||||
isWinner ? 'bg-emerald-900/40 text-emerald-400' : 'bg-red-900/40 text-red-400'
|
||||
)}>
|
||||
{rank}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-2 mb-1">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="font-semibold text-slate-200 truncate">{trade.pattern_name || trade.pattern_id}</span>
|
||||
<span className={clsx('text-[10px] font-semibold px-1.5 py-0.5 rounded',
|
||||
trade.direction === 'bearish' ? 'bg-red-900/30 text-red-400' : 'bg-emerald-900/30 text-emerald-400')}>
|
||||
{trade.direction === 'bearish' ? '🐻' : '🐂'} {trade.strategy}
|
||||
</span>
|
||||
<span className="font-mono text-slate-400 text-xs">{trade.underlying}</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setExpanded(v => !v)}
|
||||
className="text-slate-600 hover:text-slate-400 shrink-0"
|
||||
>
|
||||
<Eye className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<PnlBar pnl={pnl} />
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 mt-2 text-[11px] text-slate-500">
|
||||
<span>Score entrée : <span className="font-mono text-slate-300">{trade.score_at_entry ?? '?'}/100</span></span>
|
||||
<span>EV : <span className={clsx('font-mono', (trade.ev_net ?? 0) > 0 ? 'text-emerald-400' : 'text-red-400')}>
|
||||
{trade.ev_net != null ? `${(trade.ev_net * 100).toFixed(0)}%` : '—'}
|
||||
</span></span>
|
||||
{sc.macro_dominant && <ScenarioBadge dominant={sc.macro_dominant} />}
|
||||
{sc.geo_score != null && <span>Géo <span className="font-mono text-slate-300">{sc.geo_score}/100</span></span>}
|
||||
<span className="ml-auto text-slate-700">{trade.entry_date}</span>
|
||||
</div>
|
||||
|
||||
{scOut.key_catalyst && (
|
||||
<p className="mt-1.5 text-[11px] text-slate-500 italic">
|
||||
Catalyseur : {scOut.key_catalyst}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{trade.score_trend?.length > 0 && (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<span className="text-[10px] text-slate-600">Score trend :</span>
|
||||
<ScoreTrend trend={trade.score_trend} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{expanded && (
|
||||
<div className="mt-3 space-y-2 border-t border-slate-800 pt-3 text-xs">
|
||||
{/* Thèse d'origine */}
|
||||
{(sgOut.macro_fit || sgOut.description) && (
|
||||
<div>
|
||||
<span className="text-slate-600 font-medium">Thèse initiale : </span>
|
||||
<span className="text-slate-400">{sgOut.macro_fit || sgOut.description}</span>
|
||||
</div>
|
||||
)}
|
||||
{/* Piliers */}
|
||||
{buckets.length > 0 && (
|
||||
<div className="grid grid-cols-2 gap-1.5 mt-2">
|
||||
{buckets.map((b: any, i: number) => {
|
||||
const pct = b.max ? Math.round((b.score / b.max) * 100) : 0
|
||||
const color = pct >= 66 ? '#22c55e' : pct >= 33 ? '#eab308' : '#ef4444'
|
||||
return (
|
||||
<div key={i} className="flex items-center gap-2 bg-dark-800 rounded px-2 py-1">
|
||||
<div className="w-10 h-1 bg-dark-700 rounded-full overflow-hidden shrink-0">
|
||||
<div className="h-full rounded-full" style={{ width: `${pct}%`, background: color }} />
|
||||
</div>
|
||||
<span className="text-slate-500 truncate">{b.label ?? b.id}</span>
|
||||
<span className="font-mono ml-auto shrink-0" style={{ color }}>{b.score}/{b.max}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{scOut.summary && (
|
||||
<p className="text-slate-600 italic mt-1">{scOut.summary}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ReportSection({ icon: Icon, title, content, color = 'text-slate-300' }: {
|
||||
icon: any; title: string; content: string | string[]; color?: string
|
||||
function DeltaRow({ emoji, label, count, items, colorClass }: {
|
||||
emoji: string; label: string; count: number;
|
||||
items: any[]; colorClass: string;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-slate-400">
|
||||
<Icon className="w-4 h-4" />
|
||||
{title}
|
||||
</div>
|
||||
{Array.isArray(content) ? (
|
||||
<ul className="space-y-1 pl-4">
|
||||
{content.map((item, i) => (
|
||||
<li key={i} className={clsx('text-sm', color)}>• {item}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className={clsx('text-sm leading-relaxed', color)}>{content}</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function RapportIA() {
|
||||
const [days, setDays] = useState(30)
|
||||
const [selectedHistoryId, setSelectedHistoryId] = useState<number | null>(null)
|
||||
const [showHistory, setShowHistory] = useState(false)
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const { data: rawData, isLoading: loadingRaw, refetch } = usePortfolioReportData(days)
|
||||
const { mutate: generate, isPending: generating, data: freshReportData, reset: resetFresh } = useGeneratePortfolioReport()
|
||||
const { data: historyList } = useAiReportsList()
|
||||
const { data: historicReport } = useAiReport(selectedHistoryId)
|
||||
const { mutate: deleteReport } = useDeleteAiReport()
|
||||
|
||||
const history: any[] = (historyList as any)?.reports ?? []
|
||||
|
||||
// Active report: either a loaded historic one, or the freshly generated one
|
||||
const activeHistoric = historicReport as any
|
||||
const fresh = freshReportData as any
|
||||
const raw = rawData as any
|
||||
|
||||
const rep = selectedHistoryId && activeHistoric ? activeHistoric : fresh
|
||||
const report = rep?.report ?? null
|
||||
const stats = rep?.stats ?? raw
|
||||
const winners = rep?.winners ?? raw?.winners ?? []
|
||||
const losers = rep?.losers ?? raw?.losers ?? []
|
||||
const avgPnl = stats?.avg_pnl_pct ?? null
|
||||
|
||||
function handleGenerate() {
|
||||
setSelectedHistoryId(null)
|
||||
resetFresh()
|
||||
generate(days, {
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-reports-list'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
{/* History sidebar */}
|
||||
{showHistory && (
|
||||
<aside className="w-64 shrink-0 border-r border-slate-700/40 bg-dark-800 flex flex-col h-screen sticky top-0 overflow-y-auto">
|
||||
<div className="p-3 border-b border-slate-700/40 flex items-center justify-between">
|
||||
<span className="text-xs font-semibold text-slate-400 uppercase tracking-wide">Rapports archivés</span>
|
||||
<button onClick={() => setShowHistory(false)} className="text-slate-600 hover:text-slate-400 text-xs">✕</button>
|
||||
</div>
|
||||
{history.length === 0 ? (
|
||||
<div className="p-4 text-xs text-slate-600 text-center mt-4">
|
||||
Aucun rapport archivé.<br />Générez votre premier rapport.
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col divide-y divide-slate-800">
|
||||
{history.map((r: any) => {
|
||||
const avg = r.stats?.avg_pnl_pct
|
||||
const date = r.created_at?.slice(0, 16).replace('T', ' ') ?? ''
|
||||
const isActive = selectedHistoryId === r.id
|
||||
return (
|
||||
<div
|
||||
key={r.id}
|
||||
className={clsx(
|
||||
'group relative text-left hover:bg-dark-700/50 transition-colors',
|
||||
isActive && 'bg-blue-900/20 border-l-2 border-blue-500'
|
||||
)}
|
||||
>
|
||||
<button
|
||||
onClick={() => { setSelectedHistoryId(r.id) }}
|
||||
className="w-full text-left px-3 py-2.5 pr-8"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-0.5">
|
||||
<span className="text-[11px] font-mono text-slate-500">{date}</span>
|
||||
<span className="text-[10px] text-slate-600">{r.days}j</span>
|
||||
</div>
|
||||
{r.report?.headline && (
|
||||
<p className="text-xs text-slate-400 line-clamp-2 leading-snug">{r.report.headline}</p>
|
||||
)}
|
||||
{avg != null && (
|
||||
<span className={clsx('text-[11px] font-mono font-bold mt-1 block',
|
||||
avg >= 0 ? 'text-emerald-400' : 'text-red-400')}>
|
||||
{avg >= 0 ? '+' : ''}{avg.toFixed(1)}% moy.
|
||||
</span>
|
||||
)}
|
||||
{isActive && <ChevronRight className="w-3 h-3 text-blue-400 mt-1" />}
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (confirm('Supprimer ce rapport ?')) {
|
||||
if (selectedHistoryId === r.id) setSelectedHistoryId(null)
|
||||
deleteReport(r.id)
|
||||
}
|
||||
}}
|
||||
className="absolute top-2 right-2 p-1 rounded opacity-0 group-hover:opacity-100 text-slate-600 hover:text-red-400 hover:bg-red-400/10 transition-all"
|
||||
title="Supprimer ce rapport"
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
)}
|
||||
|
||||
<div className="flex-1 p-6 space-y-6 max-w-5xl overflow-auto">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
{!showHistory && (
|
||||
<button
|
||||
onClick={() => setShowHistory(true)}
|
||||
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded border border-slate-700/40 text-slate-500 hover:text-slate-300 text-xs"
|
||||
title={`${history.length} rapport${history.length !== 1 ? 's' : ''} archivé${history.length !== 1 ? 's' : ''}`}
|
||||
>
|
||||
<Clock className="w-3.5 h-3.5" />
|
||||
{history.length > 0 && <span className="font-mono">{history.length}</span>}
|
||||
</button>
|
||||
)}
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-white flex items-center gap-2">
|
||||
<Brain className="w-6 h-6 text-blue-400" />
|
||||
Rapport IA — Performance & Analyse
|
||||
{selectedHistoryId && activeHistoric && (
|
||||
<span className="text-xs font-normal text-slate-500 ml-2">
|
||||
archivé · {activeHistoric.created_at?.slice(0, 10)}
|
||||
<div className="mb-2">
|
||||
<button
|
||||
onClick={() => setExpanded(e => !e)}
|
||||
className="flex items-center gap-2 w-full text-left"
|
||||
>
|
||||
<span className="text-base">{emoji}</span>
|
||||
<span className={clsx('text-sm font-bold', colorClass)}>{count}</span>
|
||||
<span className="text-xs text-slate-400">{label}</span>
|
||||
{items.length > 0 && (
|
||||
<ChevronRight className={clsx('w-3 h-3 text-slate-600 ml-auto transition-transform', expanded && 'rotate-90')} />
|
||||
)}
|
||||
</button>
|
||||
{expanded && items.length > 0 && (
|
||||
<div className="mt-1.5 ml-6 space-y-1">
|
||||
{items.map((item: any, i: number) => (
|
||||
<div key={i} className="text-xs text-slate-400 flex items-start gap-2">
|
||||
<span className="text-slate-600 shrink-0 mt-0.5">—</span>
|
||||
<div>
|
||||
<span className="text-slate-200 font-medium">
|
||||
{item.name ?? item.underlying ?? '?'}
|
||||
{item.underlying && item.strategy ? ` · ${item.strategy}` : ''}
|
||||
</span>
|
||||
{item.description && (
|
||||
<div className="text-slate-600 text-[10px] mt-0.5 line-clamp-2">{item.description}</div>
|
||||
)}
|
||||
{item.triggers?.length > 0 && (
|
||||
<div className="text-slate-700 text-[10px]">Déclencheurs: {item.triggers.join(', ')}</div>
|
||||
)}
|
||||
{item.pnl_pct != null && (
|
||||
<span className={clsx('font-mono text-[10px] ml-1', item.pnl_pct >= 0 ? 'text-emerald-400' : 'text-red-400')}>
|
||||
{item.pnl_pct >= 0 ? '+' : ''}{item.pnl_pct.toFixed(1)}%
|
||||
</span>
|
||||
)}
|
||||
</h1>
|
||||
<p className="text-sm text-slate-500 mt-0.5">
|
||||
Synthèse des top mouvements + explication GPT-4o basée sur les traces de raisonnement
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{selectedHistoryId && (
|
||||
<button
|
||||
onClick={() => setSelectedHistoryId(null)}
|
||||
className="text-xs text-slate-500 hover:text-slate-300 px-2.5 py-1.5 rounded border border-slate-700/40"
|
||||
>
|
||||
← Nouveau
|
||||
</button>
|
||||
)}
|
||||
{/* Période — only relevant for new generation */}
|
||||
{!selectedHistoryId && (
|
||||
<div className="flex items-center gap-2 text-sm text-slate-400">
|
||||
<span>Période :</span>
|
||||
{[7, 14, 30, 90].map(d => (
|
||||
<button
|
||||
key={d}
|
||||
onClick={() => setDays(d)}
|
||||
className={clsx(
|
||||
'px-2.5 py-1 rounded text-xs font-medium transition-colors',
|
||||
days === d
|
||||
? 'bg-blue-900/40 text-blue-300 border border-blue-700/40'
|
||||
: 'bg-dark-700 text-slate-500 hover:text-slate-300'
|
||||
)}
|
||||
>
|
||||
{d}j
|
||||
</button>
|
||||
))}
|
||||
{item.macro_fit && (
|
||||
<div className="text-slate-600 text-[10px] italic">{item.macro_fit}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!selectedHistoryId && (
|
||||
<button
|
||||
onClick={() => refetch()}
|
||||
disabled={loadingRaw}
|
||||
className="text-slate-600 hover:text-slate-400 disabled:opacity-40"
|
||||
>
|
||||
<RefreshCw className={clsx('w-4 h-4', loadingRaw && 'animate-spin')} />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleGenerate}
|
||||
disabled={generating}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-medium transition-colors"
|
||||
>
|
||||
<Zap className={clsx('w-4 h-4', generating && 'animate-pulse')} />
|
||||
{generating ? 'Génération GPT-4o…' : 'Générer rapport IA'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats bar */}
|
||||
{(loadingRaw || stats) && (
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{[
|
||||
{ label: 'Trades total', value: stats?.total_trades ?? '…' },
|
||||
{ label: 'Trades pricés', value: stats?.priced_count ?? '…' },
|
||||
{
|
||||
label: 'P&L moyen',
|
||||
value: avgPnl != null
|
||||
? <span className={clsx('font-bold', avgPnl >= 0 ? 'text-emerald-400' : 'text-red-400')}>
|
||||
{avgPnl >= 0 ? '+' : ''}{avgPnl.toFixed(1)}%
|
||||
</span>
|
||||
: '—'
|
||||
},
|
||||
].map(({ label, value }) => (
|
||||
<div key={label} className="card text-center">
|
||||
<div className="text-2xl font-bold text-white">{value}</div>
|
||||
<div className="text-xs text-slate-500 mt-0.5">{label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
{/* GPT-4o report */}
|
||||
{report && (
|
||||
<div className="card border border-blue-700/30 space-y-5">
|
||||
<div className="flex items-center gap-2 text-blue-400 font-semibold">
|
||||
<Brain className="w-4 h-4" />
|
||||
Analyse GPT-4o
|
||||
export default function RapportCycle() {
|
||||
const [selectedRunId, setSelectedRunId] = useState<string | null>(null)
|
||||
|
||||
const { data: listData, isLoading: listLoading } = useQuery({
|
||||
queryKey: ['cycle-reports-list'],
|
||||
queryFn: () => fetch('/api/reports/cycle/list?limit=20').then(r => r.ok ? r.json() : { reports: [] }),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const { data: latestReport, isLoading: latestLoading } = useQuery({
|
||||
queryKey: ['cycle-report-latest'],
|
||||
queryFn: () => fetch('/api/reports/cycle/latest').then(r => r.ok ? r.json() : { report: null }),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const { data: selectedReport, isLoading: selectedLoading } = useQuery({
|
||||
queryKey: ['cycle-report', selectedRunId],
|
||||
queryFn: () => fetch(`/api/reports/cycle/${selectedRunId}`).then(r => r.ok ? r.json() : null),
|
||||
enabled: !!selectedRunId,
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const reports: any[] = listData?.reports ?? []
|
||||
const report: any = selectedRunId ? selectedReport : latestReport?.report
|
||||
const isLoading = selectedRunId ? selectedLoading : latestLoading
|
||||
|
||||
return (
|
||||
<div className="p-6 flex gap-4 h-full min-h-screen">
|
||||
{/* Left panel — history list */}
|
||||
<div className="w-56 shrink-0">
|
||||
<div className="section-title flex items-center gap-1 mb-3">
|
||||
<BookOpen className="w-3.5 h-3.5" /> Historique
|
||||
</div>
|
||||
{listLoading ? (
|
||||
<div className="text-xs text-slate-600">Chargement…</div>
|
||||
) : reports.length === 0 ? (
|
||||
<div className="text-xs text-slate-600">Aucun rapport. Le premier sera généré au prochain cycle.</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{reports.map((r: any) => {
|
||||
const dt = r.generated_at ? new Date(r.generated_at.endsWith('Z') ? r.generated_at : r.generated_at + 'Z') : null
|
||||
const dateStr = dt
|
||||
? dt.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
|
||||
: '—'
|
||||
const isActive = selectedRunId === r.run_id || (!selectedRunId && r === reports[0])
|
||||
const m = SCENARIO_META[r.macro_dominant] ?? SCENARIO_META.incertain
|
||||
return (
|
||||
<button
|
||||
key={r.run_id}
|
||||
onClick={() => setSelectedRunId(r.run_id)}
|
||||
className={clsx(
|
||||
'w-full text-left px-2.5 py-2 rounded border text-xs transition-all',
|
||||
isActive
|
||||
? 'border-blue-600/60 bg-blue-900/20 text-slate-200'
|
||||
: 'border-slate-700/30 bg-dark-800 text-slate-500 hover:border-slate-600/40 hover:text-slate-300'
|
||||
)}
|
||||
>
|
||||
<div className="font-mono text-[10px] text-slate-600 mb-0.5">{dateStr}</div>
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<span>{m.emoji}</span>
|
||||
<span className="font-medium truncate" style={{ color: isActive ? m.color : undefined }}>{m.label}</span>
|
||||
</div>
|
||||
<div className="flex gap-2 text-[10px] text-slate-600">
|
||||
<span className="text-blue-400">+{r.patterns_added ?? 0} pat.</span>
|
||||
<span className="text-emerald-500">{r.trades_logged ?? 0} log.</span>
|
||||
{(r.trades_closed ?? 0) > 0 && <span className="text-slate-400">{r.trades_closed} clos</span>}
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{report.headline && (
|
||||
<p className="text-base font-medium text-white border-l-2 border-blue-500 pl-3">
|
||||
{report.headline}
|
||||
</p>
|
||||
)}
|
||||
{/* Right panel — report */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 text-slate-500 text-sm mt-12 justify-center">
|
||||
<RefreshCw className="w-4 h-4 animate-spin" /> Chargement…
|
||||
</div>
|
||||
) : !report ? (
|
||||
<div className="card text-center py-12">
|
||||
<Brain className="w-10 h-10 text-slate-700 mx-auto mb-3" />
|
||||
<div className="text-slate-500 text-sm mb-1">Aucun rapport de cycle disponible</div>
|
||||
<div className="text-xs text-slate-600">Les rapports sont générés automatiquement à la fin de chaque cycle.</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Header */}
|
||||
<div className="card mb-4">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<RegimeBadge dominant={report.macro_dominant} />
|
||||
<span className="text-xs text-slate-500 font-mono">
|
||||
Géo {report.geo_score ?? '—'}/100
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[10px] text-slate-600 font-mono">
|
||||
Cycle du {report.generated_at
|
||||
? new Date(report.generated_at.endsWith('Z') ? report.generated_at : report.generated_at + 'Z')
|
||||
.toLocaleString('fr-FR')
|
||||
: '—'}
|
||||
{report.prev_cycle_at && (
|
||||
<span className="ml-2 text-slate-700">
|
||||
· vs cycle du {new Date(report.prev_cycle_at.endsWith('Z') ? report.prev_cycle_at : report.prev_cycle_at + 'Z')
|
||||
.toLocaleDateString('fr-FR')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* Macro scores mini */}
|
||||
{report.macro_scores && (
|
||||
<div className="flex gap-1.5 flex-wrap justify-end max-w-[220px]">
|
||||
{Object.entries(report.macro_scores as Record<string, number>)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.slice(0, 4)
|
||||
.map(([k, v]: [string, number]) => {
|
||||
const m = SCENARIO_META[k] ?? SCENARIO_META.incertain
|
||||
return (
|
||||
<span key={k}
|
||||
className="text-[9px] px-1.5 py-0.5 rounded font-mono"
|
||||
style={{ background: `${m.color}18`, color: m.color }}>
|
||||
{m.label} {v}%
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* PnL + VaR summary row */}
|
||||
<div className="grid grid-cols-2 gap-3 mt-2">
|
||||
{report.pnl_summary && Object.keys(report.pnl_summary).length > 0 && (
|
||||
<div className="bg-dark-700/50 rounded px-3 py-2">
|
||||
<div className="text-[9px] text-slate-600 mb-1 uppercase tracking-wide">PnL au moment du cycle</div>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className={clsx('text-lg font-bold font-mono',
|
||||
(report.pnl_summary.total_pnl_pct ?? 0) >= 0 ? 'text-emerald-400' : 'text-red-400')}>
|
||||
{report.pnl_summary.total_pnl_pct != null
|
||||
? `${report.pnl_summary.total_pnl_pct >= 0 ? '+' : ''}${report.pnl_summary.total_pnl_pct.toFixed(2)}%`
|
||||
: '—'}
|
||||
</span>
|
||||
{report.pnl_summary.total_pnl_eur != null && (
|
||||
<span className="text-xs text-slate-500 font-mono">
|
||||
{report.pnl_summary.total_pnl_eur >= 0 ? '+' : ''}
|
||||
{report.pnl_summary.total_pnl_eur.toFixed(0)}€
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[9px] text-slate-600 mt-0.5">
|
||||
{report.pnl_summary.n_open ?? 0} ouvertes · {report.pnl_summary.n_closed ?? 0} fermées
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{report.var_summary && Object.keys(report.var_summary).length > 0 && (
|
||||
<div className="bg-dark-700/50 rounded px-3 py-2">
|
||||
<div className="text-[9px] text-slate-600 mb-1 uppercase tracking-wide">VaR 95% au moment du cycle</div>
|
||||
<div className="grid grid-cols-3 gap-1">
|
||||
{[
|
||||
{ label: 'Hist.', val: report.var_summary.hist_var_1d_pct, color: 'text-blue-400' },
|
||||
{ label: 'CVaR', val: report.var_summary.hist_cvar_pct, color: 'text-orange-400' },
|
||||
{ label: 'MC', val: report.var_summary.mc_var_1d_pct, color: 'text-red-400' },
|
||||
].map(({ label, val, color }) => (
|
||||
<div key={label} className="text-center">
|
||||
<div className="text-[8px] text-slate-700">{label}</div>
|
||||
<div className={clsx('text-xs font-mono font-bold', color)}>
|
||||
{val != null ? `${val >= 0 ? '+' : ''}${val.toFixed(2)}%` : '—'}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-5">
|
||||
{report.winners_analysis && (
|
||||
<ReportSection
|
||||
icon={TrendingUp}
|
||||
title="Pourquoi les gains"
|
||||
content={report.winners_analysis}
|
||||
color="text-emerald-300"
|
||||
{/* Delta section */}
|
||||
<Section icon={<GitCompare className="w-4 h-4" />} title="Changements du cycle">
|
||||
<DeltaRow
|
||||
emoji="⭐" label="patterns ajoutés"
|
||||
count={report.patterns_added ?? 0}
|
||||
items={report.patterns_added_list ?? []}
|
||||
colorClass="text-blue-400"
|
||||
/>
|
||||
)}
|
||||
{report.losers_analysis && (
|
||||
<ReportSection
|
||||
icon={TrendingDown}
|
||||
title="Pourquoi les pertes"
|
||||
content={report.losers_analysis}
|
||||
color="text-red-300"
|
||||
<DeltaRow
|
||||
emoji="📥" label="trades loggés"
|
||||
count={report.trades_logged ?? 0}
|
||||
items={(report.trades_logged_list ?? []).map((t: any) => ({
|
||||
underlying: t.underlying, strategy: t.strategy,
|
||||
pnl_pct: t.pnl_pct, description: t.pattern_name
|
||||
}))}
|
||||
colorClass="text-emerald-400"
|
||||
/>
|
||||
<DeltaRow
|
||||
emoji="✅" label="trades fermés depuis le cycle précédent"
|
||||
count={report.trades_closed ?? 0}
|
||||
items={(report.trades_closed_list ?? []).map((t: any) => ({
|
||||
underlying: t.underlying, strategy: t.strategy,
|
||||
pnl_pct: t.pnl_pct, description: t.pattern_name
|
||||
}))}
|
||||
colorClass={report.trades_closed > 0 ? 'text-slate-300' : 'text-slate-600'}
|
||||
/>
|
||||
{/* Top scored */}
|
||||
{(report.top_scored ?? []).length > 0 && (
|
||||
<div className="mt-3 pt-3 border-t border-slate-700/30">
|
||||
<div className="text-xs text-slate-500 mb-2">Top patterns scorés ce cycle</div>
|
||||
<div className="space-y-1.5">
|
||||
{(report.top_scored as any[]).map((p: any, i: number) => (
|
||||
<div key={i} className="flex items-start gap-2 text-xs">
|
||||
<span className="text-slate-700 font-mono w-4 shrink-0">{i + 1}</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<span className="text-slate-300">{p.name ?? '—'}</span>
|
||||
{p.key_catalyst && (
|
||||
<div className="text-[10px] text-slate-600 truncate">{p.key_catalyst}</div>
|
||||
)}
|
||||
</div>
|
||||
<span className={clsx('font-mono font-bold shrink-0',
|
||||
(p.score ?? 0) >= 60 ? 'text-emerald-400' : (p.score ?? 0) >= 40 ? 'text-yellow-400' : 'text-slate-500')}>
|
||||
{p.score ?? '—'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{/* Context narrative */}
|
||||
{report.context_narrative?.narrative && (
|
||||
<Section icon={<Brain className="w-4 h-4" />} title="Raisonnement IA — ce cycle">
|
||||
<p className="text-sm text-slate-300 leading-relaxed mb-4">
|
||||
{report.context_narrative.narrative}
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{(report.context_narrative.context_driven ?? []).length > 0 && (
|
||||
<div>
|
||||
<div className="text-[10px] text-emerald-400 font-semibold uppercase tracking-wide mb-2">
|
||||
📡 Du contexte transmis
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
{(report.context_narrative.context_driven as string[]).map((s, i) => (
|
||||
<li key={i} className="text-xs text-slate-400 flex items-start gap-1.5">
|
||||
<span className="text-emerald-600 shrink-0 mt-0.5">•</span> {s}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{(report.context_narrative.general_knowledge ?? []).length > 0 && (
|
||||
<div>
|
||||
<div className="text-[10px] text-blue-400 font-semibold uppercase tracking-wide mb-2">
|
||||
🧠 Connaissance générale
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
{(report.context_narrative.general_knowledge as string[]).map((s, i) => (
|
||||
<li key={i} className="text-xs text-slate-400 flex items-start gap-1.5">
|
||||
<span className="text-blue-600 shrink-0 mt-0.5">•</span> {s}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{(report.context_narrative.key_signals ?? []).length > 0 && (
|
||||
<div className="mt-3 pt-3 border-t border-slate-700/30">
|
||||
<div className="text-[10px] text-slate-500 mb-2">Signaux déterminants</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{(report.context_narrative.key_signals as string[]).map((s, i) => (
|
||||
<span key={i} className="text-[10px] bg-slate-800 text-slate-300 border border-slate-700/50 px-2 py-0.5 rounded">
|
||||
<Zap className="w-2.5 h-2.5 inline mr-1 text-yellow-500" />{s}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Context log */}
|
||||
{report.context_narrative.context_log && (
|
||||
<div className="mt-3 pt-3 border-t border-slate-700/30">
|
||||
<div className="text-[10px] text-slate-500 mb-2">Log contexte — état transmis à l'IA</div>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-1 text-[10px]">
|
||||
{Object.entries(report.context_narrative.context_log.key_gauges ?? {}).map(([k, v]: [string, any]) => (
|
||||
<div key={k} className="flex items-center gap-1.5">
|
||||
<span className="text-slate-600 w-20">{k}</span>
|
||||
<span className="font-mono text-slate-400">{v}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{(report.context_narrative.context_log.dominant_news ?? []).length > 0 && (
|
||||
<div className="mt-2">
|
||||
<div className="text-[9px] text-slate-700 mb-1">News transmises (top impact)</div>
|
||||
{(report.context_narrative.context_log.dominant_news as string[]).map((n, i) => (
|
||||
<div key={i} className="text-[9px] text-slate-600 truncate">· {n}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{report.regime_assessment && (
|
||||
<ReportSection
|
||||
icon={Eye}
|
||||
title="Alignement régime macro"
|
||||
content={report.regime_assessment}
|
||||
/>
|
||||
)}
|
||||
|
||||
{report.key_lessons?.length > 0 && (
|
||||
<ReportSection
|
||||
icon={BookOpen}
|
||||
title="Leçons clés"
|
||||
content={report.key_lessons}
|
||||
color="text-blue-300"
|
||||
/>
|
||||
)}
|
||||
|
||||
{report.blind_spots && (
|
||||
<ReportSection
|
||||
icon={AlertTriangle}
|
||||
title="Angles morts du scoring"
|
||||
content={report.blind_spots}
|
||||
color="text-yellow-300"
|
||||
/>
|
||||
)}
|
||||
|
||||
{report.next_cycle_priorities && (
|
||||
<ReportSection
|
||||
icon={Target}
|
||||
title="Priorités prochain cycle"
|
||||
content={report.next_cycle_priorities}
|
||||
color="text-purple-300"
|
||||
/>
|
||||
)}
|
||||
|
||||
{report.risk_watch && (
|
||||
<ReportSection
|
||||
icon={AlertTriangle}
|
||||
title="Risques à surveiller"
|
||||
content={report.risk_watch}
|
||||
color="text-orange-300"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Top movers */}
|
||||
{(winners.length > 0 || losers.length > 0) && (
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
{/* Winners */}
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-emerald-400 uppercase tracking-wide flex items-center gap-2">
|
||||
<TrendingUp className="w-4 h-4" /> Top Gains
|
||||
</h2>
|
||||
{winners.length === 0 ? (
|
||||
<div className="card text-center py-8 text-slate-600 text-sm">Aucun trade pricé</div>
|
||||
) : (
|
||||
winners.map((t: any, i: number) => (
|
||||
<MoverCard key={t.id ?? i} trade={t} rank={i + 1} type="winner" />
|
||||
))
|
||||
{/* Cycle commentary */}
|
||||
{report.commentary?.commentary && (
|
||||
<Section icon={<Layers className="w-4 h-4" />} title="Analyse macro du cycle">
|
||||
<p className="text-sm text-slate-300 leading-relaxed mb-3">{report.commentary.commentary}</p>
|
||||
{report.commentary.key_risk && (
|
||||
<div className="flex items-start gap-2 text-xs text-orange-400 bg-orange-900/10 border border-orange-800/20 rounded px-3 py-2">
|
||||
<ShieldAlert className="w-3.5 h-3.5 shrink-0 mt-0.5" />
|
||||
<span>{report.commentary.key_risk}</span>
|
||||
</div>
|
||||
)}
|
||||
{report.commentary.top_pattern && (
|
||||
<div className="mt-2 text-xs text-slate-500">
|
||||
Pattern le plus pertinent : <span className="text-blue-400 font-medium">{report.commentary.top_pattern}</span>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Losers */}
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-red-400 uppercase tracking-wide flex items-center gap-2">
|
||||
<TrendingDown className="w-4 h-4" /> Top Pertes
|
||||
</h2>
|
||||
{losers.length === 0 ? (
|
||||
<div className="card text-center py-8 text-slate-600 text-sm">Aucun trade pricé</div>
|
||||
) : (
|
||||
losers.map((t: any, i: number) => (
|
||||
<MoverCard key={t.id ?? i} trade={t} rank={i + 1} type="loser" />
|
||||
))
|
||||
{/* Risk / portfolio monitor */}
|
||||
{report.portfolio_monitor && (
|
||||
<Section icon={<ShieldAlert className="w-4 h-4" />} title="Risque & Alertes portefeuille">
|
||||
<p className="text-sm text-slate-400 mb-3">{report.portfolio_monitor.assessment}</p>
|
||||
{(report.portfolio_monitor.actions ?? []).length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{(report.portfolio_monitor.actions as any[]).map((a: any, i: number) => (
|
||||
<div key={i} className={clsx(
|
||||
'flex items-start gap-2 text-xs px-2.5 py-2 rounded border',
|
||||
a.priority === 'high'
|
||||
? 'border-red-700/30 bg-red-900/10 text-red-300'
|
||||
: 'border-yellow-700/30 bg-yellow-900/10 text-yellow-300'
|
||||
)}>
|
||||
<span className="shrink-0 font-mono font-bold">{a.priority === 'high' ? '⚠️' : '👁'}</span>
|
||||
<span>{a.underlying && <strong>{a.underlying} </strong>}{a.reason}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{report.portfolio_monitor.rebalance_suggestion && (
|
||||
<div className="mt-2 text-[11px] text-slate-500 italic">
|
||||
💡 {report.portfolio_monitor.rebalance_suggestion}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loadingRaw && !raw && !report && (
|
||||
<div className="card text-center py-16 text-slate-600">
|
||||
<Brain className="w-12 h-12 mx-auto mb-3 opacity-20" />
|
||||
<p className="text-sm">Cliquer "Générer rapport IA" pour lancer l'analyse GPT-4o</p>
|
||||
<p className="text-xs mt-1 text-slate-700">
|
||||
Le rapport compare les trades gagnants et perdants, identifie les patterns récurrents
|
||||
et génère des recommandations pour le prochain cycle.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user