refactor(ui): retire article feed and legacy jobs surfaces
Remove obsolete article and scrape-job screens and APIs, preserve reports, and clear legacy API caches from the service worker. Refs #8 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
3
frontend/public/clear-legacy-api-cache.js
Normal file
3
frontend/public/clear-legacy-api-cache.js
Normal file
@ -0,0 +1,3 @@
|
||||
self.addEventListener('activate', event => {
|
||||
event.waitUntil(caches.delete('api-cache'))
|
||||
})
|
||||
@ -11,12 +11,6 @@ export interface OllamaModelInfo {
|
||||
details: { parameter_size: string; quantization_level: string; family: string }
|
||||
}
|
||||
export interface Source { id: string; name: string; type: string; enabled: boolean; article_limit: number }
|
||||
export interface ScrapeJob {
|
||||
id: string; source_id: string; source_name: string; status: string
|
||||
started_at: { Time: string; Valid: boolean } | null
|
||||
finished_at: { Time: string; Valid: boolean } | null
|
||||
articles_found: number; error_msg: string; created_at: string
|
||||
}
|
||||
export interface Setting { key: string; value: string }
|
||||
export interface ScheduleSlot { id?: string; day_of_week: number; hour: number; minute: number }
|
||||
export interface AdminUser { id: string; email: string; role: string; created_at: string }
|
||||
@ -54,10 +48,6 @@ export const adminApi = {
|
||||
updateSource: (id: string, enabled: boolean, article_limit?: number) =>
|
||||
api.put<void>(`/admin/sources/${id}`, { enabled, ...(article_limit === undefined ? {} : { article_limit }) }),
|
||||
|
||||
// Jobs
|
||||
listJobs: () => api.get<ScrapeJob[]>('/admin/scrape-jobs'),
|
||||
triggerJob: (source_id: string) => api.post<void>('/admin/scrape-jobs/trigger', { source_id }),
|
||||
|
||||
// Settings
|
||||
listSettings: () => api.get<Setting[]>('/admin/settings'),
|
||||
updateSettings: (settings: Setting[]) => api.put<void>('/admin/settings', { settings }),
|
||||
|
||||
@ -1,25 +0,0 @@
|
||||
import { api } from './client'
|
||||
|
||||
export interface Article {
|
||||
id: string
|
||||
source_id: string
|
||||
source_name: string
|
||||
title: string
|
||||
content: string
|
||||
url: string
|
||||
published_at: { Time: string; Valid: boolean } | null
|
||||
created_at: string
|
||||
symbols?: string[]
|
||||
}
|
||||
|
||||
export const articlesApi = {
|
||||
list: (params?: { symbol?: string; limit?: number; offset?: number }) => {
|
||||
const q = new URLSearchParams()
|
||||
if (params?.symbol) q.set('symbol', params.symbol)
|
||||
if (params?.limit) q.set('limit', String(params.limit))
|
||||
if (params?.offset) q.set('offset', String(params.offset))
|
||||
const qs = q.toString()
|
||||
return api.get<Article[]>(`/articles${qs ? `?${qs}` : ''}`)
|
||||
},
|
||||
get: (id: string) => api.get<Article>(`/articles/${id}`),
|
||||
}
|
||||
@ -1,10 +1,12 @@
|
||||
import { Outlet, Navigate } from 'react-router-dom'
|
||||
import { Outlet, Navigate, useLocation } from 'react-router-dom'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { Sidebar } from './Sidebar'
|
||||
import { MobileNav } from './MobileNav'
|
||||
|
||||
export function AppLayout() {
|
||||
const { token } = useAuth()
|
||||
const location = useLocation()
|
||||
const notice = typeof location.state?.notice === 'string' ? location.state.notice : null
|
||||
if (!token) return <Navigate to="/login" replace />
|
||||
|
||||
return (
|
||||
@ -15,7 +17,8 @@ export function AppLayout() {
|
||||
</div>
|
||||
|
||||
{/* Main content */}
|
||||
<main className="flex-1 overflow-y-auto pb-16 md:pb-0">
|
||||
<main className="min-w-0 flex-1 overflow-y-auto pb-16 md:pb-0">
|
||||
{notice && <p role="status" className="m-4 rounded-md border bg-muted p-3 text-sm">{notice}</p>}
|
||||
<Outlet />
|
||||
</main>
|
||||
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { LayoutDashboard, Newspaper, Star, Settings, FileText } from 'lucide-react'
|
||||
import { LayoutDashboard, Star, Settings, FileText } from 'lucide-react'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { cn } from '@/lib/cn'
|
||||
|
||||
const items = [
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Dashboard' },
|
||||
{ to: '/feed', icon: Newspaper, label: 'Actus' },
|
||||
{ to: '/watchlist', icon: Star, label: 'Watchlist' },
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Synthèses' },
|
||||
{ to: '/assets', icon: Star, label: 'Indices suivis' },
|
||||
{ to: '/reports', icon: FileText, label: 'Rapports' },
|
||||
{ to: '/preferences', icon: Settings, label: 'Mes préférences' },
|
||||
]
|
||||
|
||||
@ -1,21 +1,19 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { LayoutDashboard, Newspaper, Star, Settings, Key, Cpu, Database, ClipboardList, Users, LogOut, CalendarDays, FileText } from 'lucide-react'
|
||||
import { LayoutDashboard, Star, Settings, Key, Cpu, Database, Users, LogOut, CalendarDays, FileText } from 'lucide-react'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { cn } from '@/lib/cn'
|
||||
|
||||
const navItems = [
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Dashboard' },
|
||||
{ to: '/feed', icon: Newspaper, label: 'Actualités' },
|
||||
{ to: '/watchlist', icon: Star, label: 'Watchlist' },
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Synthèses' },
|
||||
{ to: '/assets', icon: Star, label: 'Indices suivis' },
|
||||
{ to: '/preferences', icon: Settings, label: 'Mes préférences' },
|
||||
{ to: '/reports', icon: FileText, label: 'Rapports' },
|
||||
]
|
||||
|
||||
const adminItems = [
|
||||
{ to: '/admin/ai', icon: Cpu, label: 'Fournisseurs IA' },
|
||||
{ to: '/admin/credentials', icon: Key, label: 'Identifiants' },
|
||||
{ to: '/admin/credentials', icon: Key, label: 'Accès aux sources' },
|
||||
{ to: '/admin/sources', icon: Database, label: 'Sources et plafonds' },
|
||||
{ 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' },
|
||||
|
||||
@ -1,14 +1,12 @@
|
||||
import { createBrowserRouter } from 'react-router-dom'
|
||||
import { createBrowserRouter, Navigate } from 'react-router-dom'
|
||||
import { AppLayout } from '@/components/layout/AppLayout'
|
||||
import { Login } from '@/pages/Login'
|
||||
import { Dashboard } from '@/pages/Dashboard'
|
||||
import { Feed } from '@/pages/Feed'
|
||||
import { Watchlist } from '@/pages/Watchlist'
|
||||
import { AdminLayout } from '@/pages/admin/AdminLayout'
|
||||
import { AIProviders } from '@/pages/admin/AIProviders'
|
||||
import { Credentials } from '@/pages/admin/Credentials'
|
||||
import { Sources } from '@/pages/admin/Sources'
|
||||
import { Jobs } from '@/pages/admin/Jobs'
|
||||
import { AdminUsers } from '@/pages/admin/AdminUsers'
|
||||
import { AdminSettings } from '@/pages/admin/AdminSettings'
|
||||
import { Schedule } from '@/pages/admin/Schedule'
|
||||
@ -21,7 +19,8 @@ export const router = createBrowserRouter([
|
||||
element: <AppLayout />,
|
||||
children: [
|
||||
{ path: '/', element: <Dashboard /> },
|
||||
{ path: '/feed', element: <Feed /> },
|
||||
{ path: '/feed', element: <Navigate to="/" replace state={{ notice: 'Le fil d’articles a été retiré. Retrouvez vos synthèses et leurs bilans ici.' }} /> },
|
||||
{ path: '/assets', element: <Watchlist /> },
|
||||
{ path: '/watchlist', element: <Watchlist /> },
|
||||
{ path: '/preferences', element: <Preferences /> },
|
||||
{ path: '/reports', element: <Reports /> },
|
||||
@ -33,7 +32,7 @@ export const router = createBrowserRouter([
|
||||
{ path: 'ai', element: <AIProviders /> },
|
||||
{ path: 'credentials', element: <Credentials /> },
|
||||
{ path: 'sources', element: <Sources /> },
|
||||
{ path: 'jobs', element: <Jobs /> },
|
||||
{ path: 'jobs', element: <Navigate to="/admin/sources" replace /> },
|
||||
{ path: 'users', element: <AdminUsers /> },
|
||||
{ path: 'settings', element: <AdminSettings /> },
|
||||
{ path: 'schedule', element: <Schedule /> },
|
||||
|
||||
@ -1,115 +0,0 @@
|
||||
import { useState, useEffect, useCallback } 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 ?? []))
|
||||
}, [])
|
||||
|
||||
const load = useCallback(async (newOffset = 0) => {
|
||||
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) }
|
||||
}, [filterSymbol])
|
||||
|
||||
useEffect(() => { void load(0) }, [load])
|
||||
|
||||
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={() => { setLoading(true); void 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 => { setLoading(true); 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={() => { setLoading(true); void load(offset) }} disabled={loading}>
|
||||
{loading ? <Spinner className="h-4 w-4" /> : 'Charger plus'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,13 +1,12 @@
|
||||
import { NavLink, Outlet, Navigate } from 'react-router-dom'
|
||||
import { Cpu, Key, Database, ClipboardList, Users, CalendarDays, Settings } from 'lucide-react'
|
||||
import { Cpu, Key, Database, 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/credentials', icon: Key, label: 'Accès aux sources' },
|
||||
{ to: '/admin/sources', icon: Database, label: 'Sources et plafonds' },
|
||||
{ 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' },
|
||||
|
||||
@ -98,7 +98,7 @@ export function AdminSettings() {
|
||||
<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
|
||||
Utilisé pour le planning de génération et l’horodatage des synthèses
|
||||
</p>
|
||||
<div className="flex gap-2 max-w-sm">
|
||||
<Input
|
||||
|
||||
@ -52,8 +52,8 @@ export function Credentials() {
|
||||
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>
|
||||
<h1 className="text-2xl font-bold">Accès aux sources</h1>
|
||||
<p className="text-muted-foreground text-sm">Ces accès sont utilisés par le mécanisme de récupération existant. Les enregistrer ne lance aucune récupération. Les mots de passe sont chiffrés côté serveur.</p>
|
||||
</div>
|
||||
|
||||
{creds.length === 0 && (
|
||||
|
||||
@ -1,109 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@ -68,11 +68,11 @@ export function Schedule() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<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
|
||||
Définissez les créneaux de génération des synthèses pour chaque jour.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={save} disabled={saving}>
|
||||
@ -137,7 +137,7 @@ export function Schedule() {
|
||||
</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.
|
||||
Le planning est utilisé par le service de génération existant. Enregistrer ces créneaux ne lance aucune récupération ni génération immédiate.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
@ -95,6 +95,7 @@ export function Sources() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold">Sources et plafonds</h1>
|
||||
<p className="text-sm text-muted-foreground">Choisissez les sources utilisées pour les synthèses et leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles.</p>
|
||||
{loading ? <p role="status">Chargement des sources et plafonds…</p> : loadError ? (
|
||||
<div className="space-y-3"><p role="alert">{loadError}</p><Button onClick={() => void load()}>Réessayer</Button></div>
|
||||
) : <>
|
||||
|
||||
83
frontend/tests/ticket8-legacy-routes.test.tsx
Normal file
83
frontend/tests/ticket8-legacy-routes.test.tsx
Normal file
@ -0,0 +1,83 @@
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { RouterProvider } from 'react-router-dom'
|
||||
import { router } from '../src/lib/router'
|
||||
import { Sidebar } from '../src/components/layout/Sidebar'
|
||||
import { MobileNav } from '../src/components/layout/MobileNav'
|
||||
|
||||
const authState = vi.hoisted(() => ({ role: 'admin' as 'admin' | 'user' }))
|
||||
|
||||
vi.mock('@/lib/auth', () => ({
|
||||
useAuth: () => ({
|
||||
token: 'ticket-8-token',
|
||||
user: { email: 'ticket8@example.test', role: authState.role },
|
||||
isAdmin: authState.role === 'admin',
|
||||
logout: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/pages/Dashboard', () => ({ Dashboard: () => <h1>Synthèses conservées</h1> }))
|
||||
vi.mock('@/pages/Feed', () => ({ Feed: () => <h1>Ancien fil d’actualités</h1> }))
|
||||
vi.mock('@/pages/admin/Jobs', () => ({ Jobs: () => <h1>Ancien historique des jobs</h1> }))
|
||||
vi.mock('@/pages/admin/Sources', () => ({ Sources: () => <h1>Sources et plafonds</h1> }))
|
||||
|
||||
describe('Ticket #8 — anciennes routes et navigation', () => {
|
||||
afterEach(() => cleanup())
|
||||
|
||||
beforeEach(async () => {
|
||||
authState.role = 'admin'
|
||||
await router.navigate('/')
|
||||
})
|
||||
|
||||
it('redirige /feed vers les synthèses avec remplacement et notice', async () => {
|
||||
render(<RouterProvider router={router} />)
|
||||
await router.navigate('/feed')
|
||||
|
||||
await waitFor(() => {
|
||||
if (router.state.location.pathname !== '/') throw new Error(`route remained ${router.state.location.pathname}`)
|
||||
})
|
||||
expect(router.state.historyAction).toBe('REPLACE')
|
||||
expect(router.state.location.state).toMatchObject({ notice: expect.any(String) })
|
||||
expect(screen.getByRole('heading', { name: 'Synthèses conservées' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: 'Ancien fil d’actualités' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('redirige /admin/jobs vers les sources pour un admin', async () => {
|
||||
authState.role = 'admin'
|
||||
render(<RouterProvider router={router} />)
|
||||
await router.navigate('/admin/jobs')
|
||||
|
||||
await waitFor(() => {
|
||||
if (router.state.location.pathname !== '/admin/sources') throw new Error(`route remained ${router.state.location.pathname}`)
|
||||
})
|
||||
expect(router.state.historyAction).toBe('REPLACE')
|
||||
expect(screen.getByRole('heading', { name: 'Sources et plafonds' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: 'Ancien historique des jobs' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('garde la protection admin sur /admin/jobs pour un utilisateur', async () => {
|
||||
authState.role = 'user'
|
||||
render(<RouterProvider router={router} />)
|
||||
await router.navigate('/admin/jobs')
|
||||
|
||||
await waitFor(() => {
|
||||
if (router.state.location.pathname !== '/') throw new Error(`route remained ${router.state.location.pathname}`)
|
||||
})
|
||||
expect(screen.queryByRole('heading', { name: 'Ancien historique des jobs' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('retire Feed et Jobs de la navigation desktop tout en gardant Rapports et Sources', () => {
|
||||
render(<MemoryRouter><Sidebar /><MobileNav /></MemoryRouter>)
|
||||
|
||||
expect(screen.queryByRole('link', { name: 'Actualités' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: 'Jobs' })).not.toBeInTheDocument()
|
||||
expect(screen.getAllByRole('link', { name: 'Rapports' }).length).toBeGreaterThan(0)
|
||||
expect(screen.getByRole('link', { name: 'Sources et plafonds' })).toHaveAttribute('href', '/admin/sources')
|
||||
})
|
||||
|
||||
it('retire Actus de la navigation mobile', () => {
|
||||
render(<MemoryRouter><MobileNav /></MemoryRouter>)
|
||||
expect(screen.queryByRole('link', { name: 'Actus' })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
35
frontend/tests/ticket8-preserved-reports.test.tsx
Normal file
35
frontend/tests/ticket8-preserved-reports.test.tsx
Normal file
@ -0,0 +1,35 @@
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { Reports } from '../src/pages/Reports'
|
||||
|
||||
const { listReports, listMessages } = vi.hoisted(() => ({ listReports: vi.fn(), listMessages: vi.fn() }))
|
||||
|
||||
vi.mock('@/api/reports', () => ({
|
||||
reportsApi: { list: listReports, listMessages, delete: vi.fn(), createMessage: vi.fn() },
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
listReports.mockResolvedValue([{
|
||||
id: 'historical-report-1',
|
||||
user_id: 'user-1',
|
||||
summary_id: 'historical-summary-1',
|
||||
context_excerpt: 'Extrait issu de la synthèse historique.',
|
||||
question: 'Que signifiait ce mouvement ?',
|
||||
answer: 'La réponse historique reste disponible.',
|
||||
status: 'done',
|
||||
error_msg: '',
|
||||
created_at: '2026-11-19T10:00:00.000Z',
|
||||
}])
|
||||
listMessages.mockResolvedValue([])
|
||||
})
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
it('conserve et affiche les rapports historiques avec leur synthèse et leur réponse', async () => {
|
||||
render(<Reports />)
|
||||
|
||||
expect(await screen.findByText('Que signifiait ce mouvement ?')).toBeInTheDocument()
|
||||
expect(screen.getByText(/Extrait issu de la synthèse historique/)).toBeInTheDocument()
|
||||
expect(screen.getByText('La réponse historique reste disponible.')).toBeInTheDocument()
|
||||
expect(listReports).toHaveBeenCalledOnce()
|
||||
})
|
||||
44
frontend/tests/ticket8-service-worker-cache.test.ts
Normal file
44
frontend/tests/ticket8-service-worker-cache.test.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
|
||||
const workerPath = resolve(process.cwd(), 'public/clear-legacy-api-cache.js')
|
||||
const config = readFileSync(resolve(process.cwd(), 'vite.config.ts'), 'utf8')
|
||||
|
||||
it('exécute le vrai handler activate et supprime uniquement api-cache de CacheStorage', async () => {
|
||||
expect(existsSync(workerPath), `service worker import attendu: ${workerPath}`).toBe(true)
|
||||
const source = readFileSync(workerPath, 'utf8')
|
||||
const cacheNames = new Set(['api-cache', 'workbox-precache', 'user-data-cache'])
|
||||
const cacheStorage = {
|
||||
delete: vi.fn(async (name: string) => cacheNames.delete(name)),
|
||||
}
|
||||
let activateHandler: ((event: { waitUntil: (promise: Promise<unknown>) => void }) => void) | undefined
|
||||
const self = {
|
||||
addEventListener: vi.fn((name: string, handler: typeof activateHandler) => {
|
||||
if (name === 'activate') activateHandler = handler
|
||||
}),
|
||||
}
|
||||
|
||||
runInNewContext(source, { self, caches: cacheStorage })
|
||||
expect(activateHandler, 'le script doit enregistrer son handler activate').toBeTypeOf('function')
|
||||
const pending: Promise<unknown>[] = []
|
||||
activateHandler!({ waitUntil: promise => pending.push(promise) })
|
||||
expect(pending, 'la purge doit être attachée à event.waitUntil').toHaveLength(1)
|
||||
await Promise.all(pending)
|
||||
|
||||
expect(cacheStorage.delete).toHaveBeenCalledOnce()
|
||||
expect(cacheStorage.delete).toHaveBeenCalledWith('api-cache')
|
||||
expect([...cacheNames].sort()).toEqual(['user-data-cache', 'workbox-precache'])
|
||||
})
|
||||
|
||||
it('garde GenerateSW, le precache, autoUpdate et importe le nettoyage legacy', () => {
|
||||
expect(config).toContain('VitePWA(')
|
||||
expect(config).toContain("registerType: 'autoUpdate'")
|
||||
expect(config).toContain("globPatterns: ['**/*.{js,css,html,ico,png,svg}']")
|
||||
expect(config).toMatch(/importScripts:\s*\[\s*['"]clear-legacy-api-cache\.js['"]\s*\]/)
|
||||
})
|
||||
|
||||
it('ne configure aucun runtime cache pour les réponses /api/', () => {
|
||||
expect(config).not.toMatch(/urlPattern:\s*\/\^\\\/api\\\//)
|
||||
})
|
||||
@ -12,7 +12,7 @@ export default defineConfig({
|
||||
manifest: {
|
||||
name: 'Tradarr',
|
||||
short_name: 'Tradarr',
|
||||
description: 'Agrégateur de news financières avec résumés IA',
|
||||
description: 'Synthèses financières personnalisées',
|
||||
theme_color: '#0f172a',
|
||||
background_color: '#0f172a',
|
||||
display: 'standalone',
|
||||
@ -24,13 +24,7 @@ export default defineConfig({
|
||||
},
|
||||
workbox: {
|
||||
globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
|
||||
runtimeCaching: [
|
||||
{
|
||||
urlPattern: /^\/api\//,
|
||||
handler: 'NetworkFirst',
|
||||
options: { cacheName: 'api-cache', expiration: { maxEntries: 50, maxAgeSeconds: 300 } },
|
||||
},
|
||||
],
|
||||
importScripts: ['clear-legacy-api-cache.js'],
|
||||
},
|
||||
}),
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user