From 0ebc53112441fd4e81561be6ecaa6964ffe168e3 Mon Sep 17 00:00:00 2001 From: Blomios Date: Fri, 20 Nov 2026 21:20:51 +0100 Subject: [PATCH] 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 --- backend/internal/api/handlers/admin.go | 28 ---- backend/internal/api/handlers/articles.go | 36 ----- .../api/retired_surfaces_ticket8_test.go | 123 ++++++++++++++++++ frontend/public/clear-legacy-api-cache.js | 3 + frontend/src/api/admin.ts | 10 -- frontend/src/api/articles.ts | 25 ---- frontend/src/components/layout/AppLayout.tsx | 7 +- frontend/src/components/layout/MobileNav.tsx | 7 +- frontend/src/components/layout/Sidebar.tsx | 10 +- frontend/src/lib/router.tsx | 9 +- frontend/src/pages/Feed.tsx | 115 ---------------- frontend/src/pages/admin/AdminLayout.tsx | 5 +- frontend/src/pages/admin/AdminSettings.tsx | 2 +- frontend/src/pages/admin/Credentials.tsx | 4 +- frontend/src/pages/admin/Jobs.tsx | 109 ---------------- frontend/src/pages/admin/Schedule.tsx | 6 +- frontend/src/pages/admin/Sources.tsx | 1 + frontend/tests/ticket8-legacy-routes.test.tsx | 83 ++++++++++++ .../tests/ticket8-preserved-reports.test.tsx | 35 +++++ .../ticket8-service-worker-cache.test.ts | 44 +++++++ frontend/vite.config.ts | 10 +- 21 files changed, 315 insertions(+), 357 deletions(-) delete mode 100644 backend/internal/api/handlers/articles.go create mode 100644 backend/internal/api/retired_surfaces_ticket8_test.go create mode 100644 frontend/public/clear-legacy-api-cache.js delete mode 100644 frontend/src/api/articles.ts delete mode 100644 frontend/src/pages/Feed.tsx delete mode 100644 frontend/src/pages/admin/Jobs.tsx create mode 100644 frontend/tests/ticket8-legacy-routes.test.tsx create mode 100644 frontend/tests/ticket8-preserved-reports.test.tsx create mode 100644 frontend/tests/ticket8-service-worker-cache.test.ts diff --git a/backend/internal/api/handlers/admin.go b/backend/internal/api/handlers/admin.go index ba2c8f0..4ca399b 100644 --- a/backend/internal/api/handlers/admin.go +++ b/backend/internal/api/handlers/admin.go @@ -254,34 +254,6 @@ func (h *Handler) UpdateSource(c *gin.Context) { httputil.OK(c, gin.H{"ok": true}) } -// ── Scrape Jobs ──────────────────────────────────────────────────────────── - -func (h *Handler) ListScrapeJobs(c *gin.Context) { - jobs, err := h.repo.ListScrapeJobs(100) - if err != nil { - httputil.InternalError(c, err) - return - } - httputil.OK(c, jobs) -} - -func (h *Handler) TriggerScrapeJob(c *gin.Context) { - type triggerRequest struct { - SourceID string `json:"source_id" binding:"required"` - } - var req triggerRequest - if err := c.ShouldBindJSON(&req); err != nil { - httputil.BadRequest(c, err) - return - } - go func() { - if err := h.registry.Run(req.SourceID); err != nil { - fmt.Printf("scrape job error: %v\n", err) - } - }() - c.JSON(http.StatusAccepted, gin.H{"ok": true, "message": "job started"}) -} - // ── Settings ─────────────────────────────────────────────────────────────── func (h *Handler) ListSettings(c *gin.Context) { diff --git a/backend/internal/api/handlers/articles.go b/backend/internal/api/handlers/articles.go deleted file mode 100644 index b9a89f9..0000000 --- a/backend/internal/api/handlers/articles.go +++ /dev/null @@ -1,36 +0,0 @@ -package handlers - -import ( - "strconv" - - "github.com/gin-gonic/gin" - "github.com/tradarr/backend/internal/httputil" -) - -func (h *Handler) ListArticles(c *gin.Context) { - symbol := c.Query("symbol") - limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50")) - offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0")) - if limit > 100 { - limit = 100 - } - articles, err := h.repo.ListArticles(symbol, limit, offset) - if err != nil { - httputil.InternalError(c, err) - return - } - httputil.OK(c, articles) -} - -func (h *Handler) GetArticle(c *gin.Context) { - article, err := h.repo.GetArticleByID(c.Param("id")) - if err != nil { - httputil.InternalError(c, err) - return - } - if article == nil { - httputil.NotFound(c) - return - } - httputil.OK(c, article) -} diff --git a/backend/internal/api/retired_surfaces_ticket8_test.go b/backend/internal/api/retired_surfaces_ticket8_test.go new file mode 100644 index 0000000..8cd5c51 --- /dev/null +++ b/backend/internal/api/retired_surfaces_ticket8_test.go @@ -0,0 +1,123 @@ +package api_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/tradarr/backend/internal/api" + "github.com/tradarr/backend/internal/api/handlers" + "github.com/tradarr/backend/internal/auth" + "github.com/tradarr/backend/internal/config" + "github.com/tradarr/backend/internal/models" +) + +func TestRetiredArticleAndScrapeJobEndpointsReturnNotFound(t *testing.T) { + db, _ := ticket7DB(t) + for _, statement := range []string{ + `CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL)`, + `CREATE TABLE articles (id UUID PRIMARY KEY, source_id UUID NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL, url TEXT NOT NULL, published_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL)`, + `CREATE TABLE scrape_jobs (id UUID PRIMARY KEY, source_id UUID NOT NULL, status TEXT NOT NULL, started_at TIMESTAMPTZ, finished_at TIMESTAMPTZ, articles_found INT NOT NULL, error_msg TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL)`, + `INSERT INTO sources (id,name) VALUES ('00000000-0000-0000-0000-000000000010','Fixture source')`, + `INSERT INTO articles (id,source_id,title,content,url,created_at) VALUES ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000010','private-title','private-body','https://private.test/article',NOW())`, + `INSERT INTO scrape_jobs (id,source_id,status,articles_found,error_msg,created_at) VALUES ('00000000-0000-0000-0000-000000000020','00000000-0000-0000-0000-000000000010','done',1,'',NOW())`, + } { + if _, err := db.Exec(statement); err != nil { + t.Fatal(err) + } + } + // Snapshot every stored field, so an UPDATE cannot pass a row-count check. + const snapshotSQL = `SELECT jsonb_build_object('articles',(SELECT jsonb_agg(to_jsonb(a) ORDER BY id) FROM articles a),'jobs',(SELECT jsonb_agg(to_jsonb(j) ORDER BY id) FROM scrape_jobs j))::text` + var before, after string + if err := db.QueryRow(snapshotSQL).Scan(&before); err != nil { + t.Fatal(err) + } + for _, statement := range []string{ + `CREATE FUNCTION forbid_legacy_write() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'legacy write prohibited'; END $$`, + `CREATE TRIGGER article_write_guard BEFORE INSERT OR UPDATE OR DELETE ON articles FOR EACH STATEMENT EXECUTE FUNCTION forbid_legacy_write()`, + `CREATE TRIGGER job_write_guard BEFORE INSERT OR UPDATE OR DELETE ON scrape_jobs FOR EACH STATEMENT EXECUTE FUNCTION forbid_legacy_write()`, + } { + if _, err := db.Exec(statement); err != nil { + t.Fatal(err) + } + } + var articlesBefore, jobsBefore int + if err := db.QueryRow(`SELECT COUNT(*) FROM articles`).Scan(&articlesBefore); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT COUNT(*) FROM scrape_jobs`).Scan(&jobsBefore); err != nil { + t.Fatal(err) + } + router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret) + userToken, err := auth.GenerateToken("00000000-0000-0000-0000-000000000001", "reader@example.test", "user", ticket7JWTSecret) + if err != nil { + t.Fatal(err) + } + adminToken, err := auth.GenerateToken("00000000-0000-0000-0000-000000000002", "admin@example.test", "admin", ticket7JWTSecret) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + path string + role string + method string + }{ + {name: "article collection", path: "/api/articles", role: userToken, method: http.MethodGet}, + {name: "article detail", path: "/api/articles/00000000-0000-0000-0000-000000000001", role: userToken, method: http.MethodGet}, + {name: "admin scrape jobs", path: "/api/admin/scrape-jobs", role: adminToken, method: http.MethodGet}, + {name: "scrape trigger", path: "/api/admin/scrape-jobs/trigger", role: adminToken, method: http.MethodPost}, + } { + t.Run(tc.name, func(t *testing.T) { + request := httptest.NewRequest(tc.method, tc.path, nil) + request.Header.Set("Authorization", "Bearer "+tc.role) + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if response.Code != http.StatusNotFound { + t.Fatalf("%s %s: got %d, want 404; body=%s", tc.method, tc.path, response.Code, response.Body.String()) + } + }) + } + for _, route := range router.Routes() { + if route.Path == "/api/articles" || route.Path == "/api/articles/:id" || route.Path == "/api/admin/scrape-jobs" || route.Path == "/api/admin/scrape-jobs/trigger" { + t.Errorf("retired route remains callable: %s %s", route.Method, route.Path) + } + } + var articlesAfter, jobsAfter int + if err := db.QueryRow(`SELECT COUNT(*) FROM articles`).Scan(&articlesAfter); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT COUNT(*) FROM scrape_jobs`).Scan(&jobsAfter); err != nil { + t.Fatal(err) + } + if articlesAfter != articlesBefore || jobsAfter != jobsBefore { + t.Fatalf("retired requests changed persisted data: articles %d→%d, scrape jobs %d→%d", articlesBefore, articlesAfter, jobsBefore, jobsAfter) + } + if err := db.QueryRow(snapshotSQL).Scan(&after); err != nil { + t.Fatal(err) + } + if before != after { + t.Fatalf("historical records changed: before=%s after=%s", before, after) + } + t.Logf("no writes from retired requests: articles=%d, scrape_jobs=%d before and after", articlesAfter, jobsAfter) +} + +// Route retirement must also hold without a database or retrieval adapters. +func TestRetiredSurfacesAreAbsentWithoutDatabase(t *testing.T) { + router := api.SetupRouter(handlers.New(nil, &config.Config{}, nil, nil, nil, nil), ticket7JWTSecret) + token, err := auth.GenerateToken("admin", "admin@example.test", "admin", ticket7JWTSecret) + if err != nil { + t.Fatal(err) + } + for _, path := range []string{"/api/articles", "/api/articles/legacy-id", "/api/admin/scrape-jobs", "/api/admin/scrape-jobs/trigger"} { + for _, method := range []string{http.MethodGet, http.MethodPost} { + request := httptest.NewRequest(method, path, nil) + request.Header.Set("Authorization", "Bearer "+token) + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if response.Code != http.StatusNotFound { + t.Fatalf("%s %s: status=%d", method, path, response.Code) + } + } + } +} diff --git a/frontend/public/clear-legacy-api-cache.js b/frontend/public/clear-legacy-api-cache.js new file mode 100644 index 0000000..25fe0db --- /dev/null +++ b/frontend/public/clear-legacy-api-cache.js @@ -0,0 +1,3 @@ +self.addEventListener('activate', event => { + event.waitUntil(caches.delete('api-cache')) +}) diff --git a/frontend/src/api/admin.ts b/frontend/src/api/admin.ts index 8d6a3a8..0dd6c91 100644 --- a/frontend/src/api/admin.ts +++ b/frontend/src/api/admin.ts @@ -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(`/admin/sources/${id}`, { enabled, ...(article_limit === undefined ? {} : { article_limit }) }), - // Jobs - listJobs: () => api.get('/admin/scrape-jobs'), - triggerJob: (source_id: string) => api.post('/admin/scrape-jobs/trigger', { source_id }), - // Settings listSettings: () => api.get('/admin/settings'), updateSettings: (settings: Setting[]) => api.put('/admin/settings', { settings }), diff --git a/frontend/src/api/articles.ts b/frontend/src/api/articles.ts deleted file mode 100644 index db44f63..0000000 --- a/frontend/src/api/articles.ts +++ /dev/null @@ -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(`/articles${qs ? `?${qs}` : ''}`) - }, - get: (id: string) => api.get
(`/articles/${id}`), -} diff --git a/frontend/src/components/layout/AppLayout.tsx b/frontend/src/components/layout/AppLayout.tsx index fdacb6c..1366f0c 100644 --- a/frontend/src/components/layout/AppLayout.tsx +++ b/frontend/src/components/layout/AppLayout.tsx @@ -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 return ( @@ -15,7 +17,8 @@ export function AppLayout() { {/* Main content */} -
+
+ {notice &&

{notice}

}
diff --git a/frontend/src/components/layout/MobileNav.tsx b/frontend/src/components/layout/MobileNav.tsx index 5284b47..de48e40 100644 --- a/frontend/src/components/layout/MobileNav.tsx +++ b/frontend/src/components/layout/MobileNav.tsx @@ -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' }, ] diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index 54694e2..b3a9971 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -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' }, diff --git a/frontend/src/lib/router.tsx b/frontend/src/lib/router.tsx index 30c5998..3c2c7eb 100644 --- a/frontend/src/lib/router.tsx +++ b/frontend/src/lib/router.tsx @@ -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: , children: [ { path: '/', element: }, - { path: '/feed', element: }, + { path: '/feed', element: }, + { path: '/assets', element: }, { path: '/watchlist', element: }, { path: '/preferences', element: }, { path: '/reports', element: }, @@ -33,7 +32,7 @@ export const router = createBrowserRouter([ { path: 'ai', element: }, { path: 'credentials', element: }, { path: 'sources', element: }, - { path: 'jobs', element: }, + { path: 'jobs', element: }, { path: 'users', element: }, { path: 'settings', element: }, { path: 'schedule', element: }, diff --git a/frontend/src/pages/Feed.tsx b/frontend/src/pages/Feed.tsx deleted file mode 100644 index 9ab963f..0000000 --- a/frontend/src/pages/Feed.tsx +++ /dev/null @@ -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([]) - const [assets, setAssets] = useState([]) - 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 ( -
-
-

Actualités

- -
- - {/* Filtres */} -
-
- - setSearch(e.target.value)} /> -
- -
- - {loading && articles.length === 0 ? ( -
- ) : ( - <> -
- {filtered.map(a => ( - - -
-
-
- {a.source_name} - {fmtDate(a)} -
-

{a.title}

- {a.content && ( -

{a.content}

- )} -
- - - -
-
-
- ))} - {filtered.length === 0 && ( - Aucun article - )} -
- - {filtered.length >= limit && ( -
- -
- )} - - )} -
- ) -} diff --git a/frontend/src/pages/admin/AdminLayout.tsx b/frontend/src/pages/admin/AdminLayout.tsx index db6c494..d4e2388 100644 --- a/frontend/src/pages/admin/AdminLayout.tsx +++ b/frontend/src/pages/admin/AdminLayout.tsx @@ -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' }, diff --git a/frontend/src/pages/admin/AdminSettings.tsx b/frontend/src/pages/admin/AdminSettings.tsx index d4d3cfc..be215c1 100644 --- a/frontend/src/pages/admin/AdminSettings.tsx +++ b/frontend/src/pages/admin/AdminSettings.tsx @@ -98,7 +98,7 @@ export function AdminSettings() {

- 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

-

Identifiants de scraping

-

Les mots de passe sont chiffrés en AES-256-GCM côté serveur

+

Accès aux sources

+

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.

{creds.length === 0 && ( diff --git a/frontend/src/pages/admin/Jobs.tsx b/frontend/src/pages/admin/Jobs.tsx deleted file mode 100644 index bf7a07b..0000000 --- a/frontend/src/pages/admin/Jobs.tsx +++ /dev/null @@ -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([]) - const [sources, setSources] = useState([]) - 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 ( -
-
-
-

Jobs de scraping

-

Historique et déclenchement manuel

-
-
- - - -
-
- - {loading ? ( -
- ) : ( - - Historique - -
- - - - - - - - - - - - - {jobs.map(j => ( - - - - - - - - - ))} - {jobs.length === 0 && ( - - )} - -
SourceStatutDébutFinArticlesErreur
{j.source_name} - {j.status} - {fmtDate(j.started_at)}{fmtDate(j.finished_at)}{j.articles_found}{j.error_msg || '—'}
Aucun job
-
-
-
- )} -
- ) -} diff --git a/frontend/src/pages/admin/Schedule.tsx b/frontend/src/pages/admin/Schedule.tsx index a0d559c..2450573 100644 --- a/frontend/src/pages/admin/Schedule.tsx +++ b/frontend/src/pages/admin/Schedule.tsx @@ -68,11 +68,11 @@ export function Schedule() { return (
-
+

Planning hebdomadaire

- 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.

- À 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.

) diff --git a/frontend/src/pages/admin/Sources.tsx b/frontend/src/pages/admin/Sources.tsx index 0ee923f..4365915 100644 --- a/frontend/src/pages/admin/Sources.tsx +++ b/frontend/src/pages/admin/Sources.tsx @@ -95,6 +95,7 @@ export function Sources() { return (

Sources et plafonds

+

Choisissez les sources utilisées pour les synthèses et leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles.

{loading ?

Chargement des sources et plafonds…

: loadError ? (

{loadError}

) : <> diff --git a/frontend/tests/ticket8-legacy-routes.test.tsx b/frontend/tests/ticket8-legacy-routes.test.tsx new file mode 100644 index 0000000..1079f98 --- /dev/null +++ b/frontend/tests/ticket8-legacy-routes.test.tsx @@ -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: () =>

Synthèses conservées

})) +vi.mock('@/pages/Feed', () => ({ Feed: () =>

Ancien fil d’actualités

})) +vi.mock('@/pages/admin/Jobs', () => ({ Jobs: () =>

Ancien historique des jobs

})) +vi.mock('@/pages/admin/Sources', () => ({ Sources: () =>

Sources et plafonds

})) + +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() + 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() + 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() + 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() + + 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() + expect(screen.queryByRole('link', { name: 'Actus' })).not.toBeInTheDocument() + }) +}) diff --git a/frontend/tests/ticket8-preserved-reports.test.tsx b/frontend/tests/ticket8-preserved-reports.test.tsx new file mode 100644 index 0000000..a969de9 --- /dev/null +++ b/frontend/tests/ticket8-preserved-reports.test.tsx @@ -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() + + 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() +}) diff --git a/frontend/tests/ticket8-service-worker-cache.test.ts b/frontend/tests/ticket8-service-worker-cache.test.ts new file mode 100644 index 0000000..0c5743d --- /dev/null +++ b/frontend/tests/ticket8-service-worker-cache.test.ts @@ -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) => 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[] = [] + 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\\\//) +}) diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index ea4897c..d92d050 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -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'], }, }), ],