feat(sources): add managed RSS feeds (#41)

This commit is contained in:
2026-11-25 01:42:27 +01:00
parent 12acb36612
commit 136d9b3b59
38 changed files with 2103 additions and 67 deletions

View File

@ -22,10 +22,10 @@ test('admin source controls stay accessible and fit at 320, 375 and 390 px', asy
await expect(page.getByRole('heading', { name: 'Sources et plafonds' })).toBeVisible()
const activationControls = page.locator('button[aria-label^="Activer "], button[aria-label^="Désactiver "]')
await expect(activationControls).toHaveCount(3)
await expect(activationControls).toHaveCount(4)
const activationNames = (await activationControls.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-label').replace(/^(Activer|Désactiver) /, '')).sort()))
expect(activationNames).toEqual(['Bloomberg', 'CNBC Business', 'Yahoo Finance'])
await expect(page.locator('form[aria-label^="Réglages de "]')).toHaveCount(3)
expect(activationNames).toEqual(['Bloomberg', 'CNBC Business', 'Investing.com', 'Yahoo Finance'])
await expect(page.locator('form[aria-label^="Réglages de "]')).toHaveCount(4)
const historical = page.getByRole('region', { name: 'Anciennes sources exclues' })
await expect(historical).toBeVisible()
@ -43,7 +43,7 @@ test('admin source controls stay accessible and fit at 320, 375 and 390 px', asy
expect(dimensions.document, `horizontal overflow at ${width}px: ${JSON.stringify(dimensions)}`).toBeLessThanOrEqual(dimensions.viewport)
await expect(page.getByRole('spinbutton', { name: 'Articles max par résumé' })).toBeVisible()
for (const name of ['Yahoo Finance', 'Bloomberg', 'CNBC Business']) {
for (const name of ['Yahoo Finance', 'Bloomberg', 'CNBC Business', 'Investing.com']) {
const toggle = page.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) })
const cap = page.getByRole('spinbutton', { name: `Plafond ${name}` })
await expect(toggle).toBeVisible()

View File

@ -13,6 +13,7 @@ export interface OllamaModelInfo {
}
export interface Source {
id: string; name: string; type: string; enabled: boolean; article_limit: number
feed_urls?: string[]
source_key: string | null; supported: boolean; operational: boolean
}
export interface Setting { key: string; value: string }
@ -55,6 +56,9 @@ export const adminApi = {
updateSource: (id: string, enabled: boolean, article_limit?: number) =>
api.put<void>(`/admin/sources/${id}`, { enabled, ...(article_limit === undefined ? {} : { article_limit }) }),
updateSourceFeeds: (id: string, enabled: boolean, feed_urls: string[]) =>
api.put<void>(`/admin/sources/${encodeURIComponent(id)}`, { enabled, feed_urls }),
// Settings
listSettings: () => api.get<Setting[]>('/admin/settings'),
updateSettings: (settings: Setting[]) => api.put<void>('/admin/settings', { settings }),

View File

@ -26,6 +26,7 @@ export interface PromptBudgetUsage {
}
export interface SourceGenerationStat extends ContentCompleteness {
feeds?: { attempted: number; succeeded: number; failed: number } | null
source_id: string
source_key?: string | null
source_type: string

View File

@ -4,6 +4,7 @@ function sourceLabel(key?: string | null) {
switch (key) {
case 'yahoo_finance': return 'Yahoo Finance'
case 'bloomberg': return 'Bloomberg'
case 'investing_com': return 'Investing.com'
case 'cnbc_business': return 'CNBC Business'
default: return 'Source non identifiée'
}
@ -11,20 +12,23 @@ function sourceLabel(key?: string | null) {
function sourceState(source: SourceGenerationStat, mode: GenerationOutcome['ranking_mode']) {
if (source.status === 'failed') return 'Récupération impossible'
if (source.status !== 'ok') return 'État de collecte non renseigné'
if (mode === 'title') return 'Source joignable · contenu non évalué'
if (source.status !== 'ok' && source.status !== 'partial') return 'État de collecte non renseigné'
const collection = source.status === 'partial' ? 'Récupération partielle' : 'Source joignable'
if (mode === 'title') return `${collection} · contenu non évalué`
const counts = [source.content_complete, source.content_incomplete, source.content_unavailable]
if (counts.some(count => count === undefined)) return 'Source joignable · complétude non renseignée'
if (source.candidates === 0) return 'Source joignable · aucun article examiné'
if (counts.filter(count => (count ?? 0) > 0).length > 1) return 'Source joignable · contenus de complétude variable'
if ((source.content_complete ?? 0) > 0) return 'Source joignable · contenus complets'
if ((source.content_incomplete ?? 0) > 0) return 'Source joignable · contenu partiel'
if ((source.content_unavailable ?? 0) > 0) return 'Source joignable · contenu absent'
return 'Source joignable · complétude non renseignée'
if (counts.some(count => count === undefined)) return `${collection} · complétude non renseignée`
if (source.candidates === 0) return `${collection} · aucun article examiné`
if (counts.filter(count => (count ?? 0) > 0).length > 1) return `${collection} · contenus de complétude variable`
if ((source.content_complete ?? 0) > 0) return `${collection} · contenus complets`
if ((source.content_incomplete ?? 0) > 0) return `${collection} · contenu partiel`
if ((source.content_unavailable ?? 0) > 0) return `${collection} · contenu absent`
return `${collection} · complétude non renseignée`
}
export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => sourceLabel(source.source_key))
const partialFeeds = outcome.source_stats.filter(source => source.status === 'partial').map(source => sourceLabel(source.source_key))
const hasFeedCounts = outcome.source_stats.some(source => source.feeds != null)
const hasCompleteness = outcome.content_complete !== undefined && outcome.content_incomplete !== undefined && outcome.content_unavailable !== undefined
const usage = outcome.prompt_budget
const number = (value: number) => value.toLocaleString('fr-FR')
@ -36,6 +40,7 @@ export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
{unavailable.length > 0 && <p>Cette synthèse a été générée sans {unavailable.join(', ')}, indisponible lors du traitement.</p>}
</div>
)}
{partialFeeds.length > 0 && <p>Certains flux RSS de {partialFeeds.join(', ')} n’ont pas pu être récupérés. Les articles des autres flux restent pris en compte.</p>}
<p>{outcome.total_candidates} articles examinés · {outcome.laya_selected} sélectionnés par Laya · {outcome.selected} retenus après plafonds</p>
<div className="space-y-1" aria-label="Complétude des articles">
<p>Les compteurs portent sur les articles examinés après plafonds par source, avant sélection et plafond global.</p>
@ -66,12 +71,13 @@ export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
<div className="overflow-x-auto">
<table className="w-full text-sm text-left">
<caption className="text-left font-medium">Bilan par source</caption>
<thead><tr><th scope="col">Source</th><th scope="col">Collecte et complétude</th><th scope="col">Articles examinés</th><th scope="col">Sélectionnés par Laya</th><th scope="col">Retenus</th><th scope="col">Plafond</th><th scope="col">Dates disponibles</th>{outcome.ranking_mode === 'title_content' && <><th scope="col">Contenus complets</th><th scope="col">Contenus partiels</th><th scope="col">Contenus absents</th></>}</tr></thead>
<thead><tr><th scope="col">Source</th><th scope="col">Collecte et complétude</th><th scope="col">Articles examinés</th><th scope="col">Sélectionnés par Laya</th><th scope="col">Retenus</th><th scope="col">Plafond</th><th scope="col">Dates disponibles</th>{hasFeedCounts && <th scope="col">Récupération des flux RSS</th>}{outcome.ranking_mode === 'title_content' && <><th scope="col">Contenus complets</th><th scope="col">Contenus partiels</th><th scope="col">Contenus absents</th></>}</tr></thead>
<tbody>{outcome.source_stats.map(source => (
<tr key={source.source_id}>
<th scope="row">{sourceLabel(source.source_key)}</th>
<td>{sourceState(source, outcome.ranking_mode)}</td>
<td>{source.candidates}</td><td>{source.laya_selected}</td><td>{source.selected}</td><td>{source.article_limit}</td><td>{source.dates_available ?? 'Non renseigné'}</td>
{hasFeedCounts && <td>{source.feeds ? `Tentés : ${source.feeds.attempted} · récupérés : ${source.feeds.succeeded} · en échec : ${source.feeds.failed}` : 'Non renseigné'}</td>}
{outcome.ranking_mode === 'title_content' && <><td>{source.content_complete ?? 'Non renseigné'}</td><td>{source.content_incomplete ?? 'Non renseigné'}</td><td>{source.content_unavailable ?? 'Non renseigné'}</td></>}
</tr>
))}</tbody>

View File

@ -0,0 +1,112 @@
import { useRef, useState, type FormEvent } from 'react'
import { ApiError } from '@/api/client'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
interface SourceFeedsEditorProps {
sourceId: string
sourceKey: string
sourceName: string
urls: string[]
disabled?: boolean
onSave: (urls: string[]) => Promise<void>
}
const FEED_PATHS: Record<string, readonly string[]> = {
bloomberg: ['bloomberg-latest', 'bloomberg-economics', 'bloomberg-technology', 'bloomberg-politics', 'bloomberg-technology-ai'],
investing_com: ['investing-news'],
}
function validateUrl(value: string, sourceKey: string): string | null {
try {
if (value !== value.trim() || value.length > 256) return null
const path = /^https:\/\/[^/?#]+(\/[^?#]*)$/.exec(value)?.[1]
const url = new URL(value)
if (url.protocol !== 'https:' || url.hostname !== 'feed.quanwenrss.com' || url.port ||
url.username || url.password || value.includes('#') || value.includes('?') ||
!Object.prototype.hasOwnProperty.call(FEED_PATHS, sourceKey) || !FEED_PATHS[sourceKey].some(name => path === `/feed/${name}.xml` && url.pathname === path)) return null
return url.href
} catch { return null }
}
export function SourceFeedsEditor({ sourceId, sourceKey, sourceName, urls, onSave, disabled = false }: SourceFeedsEditorProps) {
const [rows, setRows] = useState(() => urls.map((url, id) => ({ id, url })))
const [errors, setErrors] = useState<Record<number, string>>({})
const [error, setError] = useState('')
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const nextId = useRef(urls.length)
const fields = useRef(new Map<number, HTMLInputElement>())
const addButton = useRef<HTMLButtonElement>(null)
function clearMessages() { setErrors({}); setError(''); setSaved(false) }
function focusRow(id?: number) {
setTimeout(() => {
const field = id === undefined ? undefined : fields.current.get(id)
if (field) field.focus()
else addButton.current?.focus()
}, 0)
}
function add() {
const id = nextId.current++
setRows(current => [...current, { id, url: '' }]); clearMessages(); focusRow(id)
}
function remove(id: number, index: number) {
const remaining = rows.filter(row => row.id !== id)
setRows(remaining); clearMessages(); focusRow(remaining[Math.min(index, remaining.length - 1)]?.id)
}
async function save(event: FormEvent) {
event.preventDefault()
if (saving || disabled) return
clearMessages()
if (!rows.length) { setError('Ajoutez au moins un flux RSS pour enregistrer.'); return }
const invalid: Record<number, string> = {}
const normalized: string[] = []
for (const row of rows) {
const url = validateUrl(row.url, sourceKey)
if (!row.url.trim()) invalid[row.id] = 'Saisissez une URL de flux RSS.'
else if (!url) invalid[row.id] = 'Utilisez une URL RSS HTTPS autorisée pour cette source, sans identifiants, paramètres ni fragment.'
else if (normalized.includes(url)) invalid[row.id] = 'Ce flux RSS est déjà présent. Retirez le doublon ou modifiez son URL.'
if (url) normalized.push(url)
}
if (Object.keys(invalid).length) {
setErrors(invalid); focusRow(rows.find(row => invalid[row.id])?.id); return
}
setSaving(true)
try { await onSave(normalized); setSaved(true) }
catch (error) {
if (error instanceof ApiError && error.status === 400 && ['source_feeds_invalid', 'source_feeds_not_supported', 'source_configuration_invalid'].includes(error.message)) {
setError('Les flux RSS ont été refusés. Vérifiez les adresses autorisées et les doublons. Votre saisie est conservée.')
} else { setError('Impossible d’enregistrer les flux RSS. Votre saisie est conservée. Réessayez.') }
}
finally { setSaving(false) }
}
return (
<form onSubmit={save} noValidate aria-label={`Flux RSS ${sourceName}`} aria-busy={saving} className="space-y-3 min-w-0">
<p id={`feeds-help-${sourceId}`} className="text-sm text-muted-foreground">Une URL par ligne. Seuls les flux QuanwenRSS autorisés pour cette source sont acceptés. Les modifications s’appliquent aux prochaines synthèses, sans récupération ni génération immédiate. Un flux accessible ne garantit pas un contenu complet.</p>
{Object.keys(errors).length > 1 && <p role="alert" className="text-sm text-destructive">Plusieurs flux RSS sont invalides. Corrigez les champs signalés ci-dessous.</p>}
{rows.map((row, index) => (
<div key={row.id} className="space-y-2 min-w-0">
<Label htmlFor={`feed-${sourceId}-${row.id}`}>URL du flux RSS {sourceName} {index + 1}</Label>
<div className="flex flex-wrap gap-2 min-w-0">
<Input id={`feed-${sourceId}-${row.id}`} type="url" required maxLength={256} autoComplete="off" spellCheck={false}
ref={element => { if (element) fields.current.set(row.id, element); else fields.current.delete(row.id) }}
className="min-w-0 flex-1 basis-48" disabled={saving || disabled} value={row.url}
aria-invalid={!!errors[row.id]} aria-describedby={`feeds-help-${sourceId}${errors[row.id] ? ` feed-error-${sourceId}-${row.id}` : ''}`}
onChange={event => { const url = event.target.value; setRows(current => current.map(item => item.id === row.id ? { ...item, url } : item)); clearMessages() }} />
<Button type="button" variant="outline" disabled={saving} aria-label={`Retirer le flux RSS ${sourceName} ${index + 1}`} onClick={() => remove(row.id, index)}>Retirer</Button>
</div>
{errors[row.id] && <p id={`feed-error-${sourceId}-${row.id}`} role="alert" className="text-sm text-destructive">{errors[row.id]}</p>}
</div>
))}
<div className="flex flex-wrap gap-2">
<Button ref={addButton} type="button" variant="outline" disabled={saving} aria-label={`Ajouter un flux RSS ${sourceName}`} onClick={add}>Ajouter un flux RSS</Button>
<Button type="submit" disabled={saving} aria-label={`Enregistrer les flux RSS ${sourceName}`}>{saving ? 'Enregistrement…' : 'Enregistrer les flux RSS'}</Button>
</div>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{(saving || saved) && <p role="status">{saving ? 'Enregistrement des flux RSS…' : 'Flux RSS enregistrés pour les prochaines synthèses. Aucune récupération ni génération n’a été lancée.'}</p>}
</form>
)
}

View File

@ -1,11 +1,12 @@
import { useState, useEffect, type FormEvent } from 'react'
import { adminApi, type Source } from '@/api/admin'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { SourceFeedsEditor } from '@/components/SourceFeedsEditor'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
const SOURCE_KEYS = new Set(['yahoo_finance', 'bloomberg', 'cnbc_business'])
const SOURCE_KEYS = new Set(['yahoo_finance', 'bloomberg', 'cnbc_business', 'investing_com'])
function isSupported(source: Source) {
return source.supported === true && source.source_key !== null && SOURCE_KEYS.has(source.source_key)
@ -24,6 +25,12 @@ function SourceLimit({ source }: { source: Source }) {
const [saved, setSaved] = useState('')
const valid = validLimit(limit, 200)
async function saveFeeds(urls: string[]) {
setSaving(true); setSaved(''); setError('')
try { await adminApi.updateSourceFeeds(source.id, enabled, urls) }
finally { setSaving(false) }
}
async function toggle() {
if (saving) return
setSaving(true); setError(''); setSaved('')
@ -61,6 +68,9 @@ function SourceLimit({ source }: { source: Source }) {
<p id={`limit-help-${source.id}`} className={`text-sm ${valid ? 'text-muted-foreground' : 'text-destructive'}`}>{valid ? 'De 1 à 200 articles par génération. Le plafond est conservé quand la source est désactivée.' : 'Saisissez un nombre entier de 1 à 200. La valeur actuelle est conservée tant que vous ne la modifiez pas.'}</p>
<Button type="submit" disabled={!valid || !enabled || saving} aria-label={`Enregistrer le plafond ${source.name}`}>{saving ? 'Enregistrement…' : 'Enregistrer le plafond'}</Button>
</form>
{(source.source_key === 'bloomberg' || source.source_key === 'investing_com') && (Array.isArray(source.feed_urls)
? <SourceFeedsEditor sourceId={source.id} sourceKey={source.source_key} sourceName={source.name} urls={source.feed_urls} onSave={saveFeeds} disabled={saving} />
: <p>Configuration des flux RSS indisponible. Rechargez la page ou contactez votre administrateur.</p>)}
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{saved && <p role="status">{saved}</p>}
</CardContent>
@ -105,7 +115,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">Seules Yahoo Finance, Bloomberg et CNBC Business peuvent participer aux synthèses manuelles et planifiées. Seules les sources activées sont utilisées, dans la limite de leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles ni génération immédiate.</p>
<p className="text-sm text-muted-foreground">Yahoo Finance, Bloomberg, CNBC Business et Investing.com peuvent participer aux synthèses manuelles et planifiées. Seules les sources activées sont utilisées, dans la limite de leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles ni génération immédiate.</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>
) : <>
@ -124,7 +134,7 @@ export function Sources() {
</Card>
{sources.length === 0 && <p>Aucune source disponible.</p>}
<div className="grid min-w-0 gap-4 lg:grid-cols-3">
{supported.map(source => <SourceLimit key={source.id} source={source.source_key === 'yahoo_finance' ? { ...source, name: 'Yahoo Finance' } : source.source_key === 'cnbc_business' ? { ...source, name: 'CNBC Business' } : source} />)}
{supported.map(source => <SourceLimit key={source.id} source={source.source_key === 'yahoo_finance' ? { ...source, name: 'Yahoo Finance' } : source.source_key === 'cnbc_business' ? { ...source, name: 'CNBC Business' } : source.source_key === 'investing_com' ? { ...source, name: 'Investing.com' } : source.source_key === 'bloomberg' ? { ...source, name: 'Bloomberg' } : source} />)}
</div>
{historical.length > 0 && <section aria-labelledby="historical-sources-title" className="space-y-3">
<h2 id="historical-sources-title" className="text-lg font-semibold">Anciennes sources exclues</h2>

View File

@ -38,3 +38,11 @@ it('envoie les plafonds via les endpoints admin et préserve le plafond lors du
method: 'PUT', body: JSON.stringify({ enabled: false }),
}))
})
it('remplace les flux RSS par PUT sans modifier le plafond et sans appeler les feeds', async () => {
const urls = ['https://feed.quanwenrss.com/feed/bloomberg-latest.xml']
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ok: true } }), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
await adminApi.updateSourceFeeds('source-b', false, urls)
expect(fetchMock).toHaveBeenCalledExactlyOnceWith('/api/admin/sources/source-b', expect.objectContaining({ method: 'PUT', body: JSON.stringify({ enabled: false, feed_urls: urls }) }))
})

View File

@ -244,7 +244,27 @@ describe('plafonds d’articles administrateur', () => {
await waitFor(() => expect(updateSource).toHaveBeenCalledWith('cnbc-new', true, 42))
expect(updateSource).toHaveBeenCalledTimes(1)
expect(await screen.findByRole('status')).toHaveTextContent('Plafond CNBC Business enregistré pour les prochaines synthèses.')
expect(screen.getByText(/Seules Yahoo Finance, Bloomberg et CNBC Business/)).toBeInTheDocument()
expect(screen.getByText(/Yahoo Finance, Bloomberg, CNBC Business et Investing.com/)).toBeInTheDocument()
})
})
describe('ticket #41 — sources additives', () => {
afterEach(cleanup)
it('affiche Investing.com depuis la clé canonique backend et conserve Yahoo Finance et CNBC Business', async () => {
listSettings.mockResolvedValue([])
listSources.mockResolvedValue([
{ id: 'b', source_key: 'bloomberg', name: 'Bloomberg', type: 'rss', supported: true, operational: true, enabled: true, article_limit: 20 },
{ id: 'i', source_key: 'investing_com', name: 'Legacy RSS label', type: 'rss', supported: true, operational: false, enabled: false, article_limit: 40 },
{ id: 'y', source_key: 'yahoo_finance', name: 'legacy', type: 'stocktwits', supported: true, operational: true, enabled: true, article_limit: 20 },
{ id: 'c', source_key: 'cnbc_business', name: 'legacy', type: 'rss', supported: true, operational: true, enabled: true, article_limit: 20 },
])
render(<Sources />)
expect(await screen.findByRole('heading', { name: 'Investing.com' })).toBeInTheDocument()
expect(screen.getByLabelText('Plafond Investing.com')).toHaveValue(40)
expect(screen.getByRole('button', { name: 'Activer Investing.com' })).toBeEnabled()
expect(screen.getByRole('button', { name: 'Désactiver Yahoo Finance' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Désactiver CNBC Business' })).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: 'Legacy RSS label' })).not.toBeInTheDocument()
})
})

View File

@ -0,0 +1,72 @@
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { Sources } from '../src/pages/admin/Sources'
const latest = 'https://feed.quanwenrss.com/feed/bloomberg-latest.xml'
const economics = 'https://feed.quanwenrss.com/feed/bloomberg-economics.xml'
const investing = 'https://feed.quanwenrss.com/feed/investing-news.xml'
const fetchMock = vi.fn()
let sources: object[]
beforeEach(() => {
sources = [
{ id: 'b', source_key: 'bloomberg', name: 'Bloomberg', supported: true, operational: true, enabled: true, article_limit: 20, feed_urls: [latest] },
{ id: 'i', source_key: 'investing_com', name: 'Investing.com', supported: true, operational: false, enabled: false, article_limit: 40, feed_urls: [investing] },
]
vi.stubGlobal('fetch', fetchMock)
fetchMock.mockReset().mockImplementation((url: string) => Promise.resolve(new Response(JSON.stringify({ data: url === '/api/admin/sources' ? sources : [] }), { status: 200 })))
})
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
it('charge et sauvegarde plusieurs flux Bloomberg sans déclencher de récupération ni génération', async () => {
render(<Sources />)
const form = await screen.findByRole('form', { name: 'Flux RSS Bloomberg' })
await userEvent.click(within(form).getByRole('button', { name: 'Ajouter un flux RSS Bloomberg' }))
await userEvent.type(within(form).getByLabelText('URL du flux RSS Bloomberg 2'), economics)
await userEvent.click(within(form).getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(fetchMock).toHaveBeenLastCalledWith('/api/admin/sources/b', expect.objectContaining({ method: 'PUT', body: JSON.stringify({ enabled: true, feed_urls: [latest, economics] }) }))
expect(within(form).getByRole('status')).toHaveTextContent('Aucune récupération ni génération n’a été lancée.')
expect(fetchMock).toHaveBeenCalledTimes(3)
})
it('enregistre les flux d’une source désactivée sans l’activer et sans modifier son plafond', async () => {
render(<Sources />)
const form = await screen.findByRole('form', { name: 'Flux RSS Investing.com' })
expect(within(form).getByLabelText('URL du flux RSS Investing.com 1')).toHaveValue(investing)
await userEvent.click(within(form).getByRole('button', { name: 'Enregistrer les flux RSS Investing.com' }))
expect(fetchMock).toHaveBeenLastCalledWith('/api/admin/sources/i', expect.objectContaining({ method: 'PUT', body: JSON.stringify({ enabled: false, feed_urls: [investing] }) }))
expect(screen.getByRole('button', { name: 'Activer Investing.com' })).toBeEnabled()
expect(screen.getByLabelText('Plafond Investing.com')).toHaveValue(40)
})
it('ne propose pas de configuration supposée quand le DTO ne fournit pas de feeds', async () => {
sources = [{ id: 'b', source_key: 'bloomberg', name: 'Bloomberg', supported: true, operational: true, enabled: true, article_limit: 20 }]
render(<Sources />)
await screen.findByRole('heading', { name: 'Bloomberg' })
expect(screen.queryByRole('form', { name: 'Flux RSS Bloomberg' })).not.toBeInTheDocument()
expect(screen.getByText(/Configuration des flux RSS indisponible/)).toBeInTheDocument()
})
it('relie les rejets de validation serveur à un message assaini et conserve les saisies', async () => {
render(<Sources />)
const form = await screen.findByRole('form', { name: 'Flux RSS Bloomberg' })
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ error: 'source_feeds_invalid', url: 'PRIVATE_URL', content: 'PRIVATE_CONTENT' }), { status: 400 }))
await userEvent.click(within(form).getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(within(form).getByRole('alert')).toHaveTextContent('Les flux RSS ont été refusés.')
expect(within(form).getByRole('alert')).not.toHaveTextContent(/PRIVATE_/)
expect(within(form).getByLabelText('URL du flux RSS Bloomberg 1')).toHaveValue(latest)
})
it('verrouille activation et plafond pendant la sauvegarde des flux de la même source', async () => {
render(<Sources />)
const form = await screen.findByRole('form', { name: 'Flux RSS Bloomberg' })
let complete!: (value: Response) => void
fetchMock.mockImplementationOnce(() => new Promise<Response>(resolve => { complete = resolve }))
await userEvent.click(within(form).getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(screen.getByRole('button', { name: 'Désactiver Bloomberg' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Enregistrer le plafond Bloomberg' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Activer Investing.com' })).toBeEnabled()
complete(new Response(JSON.stringify({ data: { ok: true } }), { status: 200 }))
expect(await within(form).findByText(/Flux RSS enregistrés pour les prochaines synthèses/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Désactiver Bloomberg' })).toBeEnabled()
})

View File

@ -0,0 +1,38 @@
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import { afterEach, expect, it } from 'vitest'
import { GenerationDetails } from '../src/components/GenerationDetails'
import type { GenerationOutcome } from '../src/api/summaries'
afterEach(cleanup)
const outcome = (status: string, sourceKey = 'bloomberg'): GenerationOutcome => ({
id: 'g', status: 'partial', language: 'fr', ranking_mode: 'title_content', failure_code: 'content_incomplete',
total_candidates: 6, laya_selected: 2, selected: 2, global_limit: 50, content_fallbacks: 1,
content_complete: 3, content_incomplete: 2, content_unavailable: 1,
source_stats: [{ source_id: 'b', source_key: sourceKey, source_type: 'stocktwits', status, candidates: 6, laya_selected: 2, selected: 2, article_limit: 20, content_fallbacks: 1,
content_complete: 3, content_incomplete: 2, content_unavailable: 1,
feeds: { attempted: 5, succeeded: status === 'failed' ? 0 : 4, failed: status === 'failed' ? 5 : 1 },
}],
})
function show(value: GenerationOutcome) {
const result = render(<GenerationDetails outcome={value} />)
fireEvent.click(screen.getByText('Détails de la génération'))
return result
}
it('annonce une récupération partielle de feeds distincte de la complétude, sans perdre les agrégats', () => {
show(outcome('partial'))
expect(screen.getByText(/Certains flux RSS de Bloomberg n’ont pas pu être récupérés/)).toBeInTheDocument()
const row = screen.getByRole('row', { name: /Bloomberg/ })
expect(within(row).getByRole('cell', { name: 'Récupération partielle · contenus de complétude variable' })).toBeInTheDocument()
expect(within(row).getByText('Tentés : 5 · récupérés : 4 · en échec : 1')).toBeInTheDocument()
expect(screen.getByText('Contenus complets : 3')).toBeInTheDocument()
expect(screen.getByText(/Seuls les contenus complets sont éligibles/)).toBeInTheDocument()
})
it('nomme Investing.com et rend une indisponibilité complète des feeds sans diagnostic brut', () => {
const { container } = show(outcome('failed', 'investing_com'))
expect(screen.getByRole('rowheader', { name: 'Investing.com' })).toBeInTheDocument()
expect(screen.getByRole('cell', { name: 'Récupération impossible' })).toBeInTheDocument()
expect(screen.getByText('Tentés : 5 · récupérés : 0 · en échec : 5')).toBeInTheDocument()
expect(container.innerHTML).not.toMatch(/stocktwits|https?:|abonnement|authentification|challenge/i)
})

View File

@ -0,0 +1,105 @@
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { SourceFeedsEditor } from '../src/components/SourceFeedsEditor'
const latest = 'https://feed.quanwenrss.com/feed/bloomberg-latest.xml'
const economics = 'https://feed.quanwenrss.com/feed/bloomberg-economics.xml'
const save = vi.fn()
const fetchMock = vi.fn()
function show(urls = [latest]) {
return render(<SourceFeedsEditor sourceId="b" sourceKey="bloomberg" sourceName="Bloomberg" urls={urls} onSave={save} />)
}
beforeEach(() => { save.mockReset().mockResolvedValue(undefined); vi.stubGlobal('fetch', fetchMock.mockReset()) })
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
it('ajoute et retire des lignes identifiées puis sauvegarde toutes les URLs sans récupération', async () => {
show()
expect(screen.getByLabelText('URL du flux RSS Bloomberg 1')).toHaveValue(latest)
await userEvent.click(screen.getByRole('button', { name: 'Ajouter un flux RSS Bloomberg' }))
await userEvent.type(screen.getByLabelText('URL du flux RSS Bloomberg 2'), economics)
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(save).toHaveBeenLastCalledWith([latest, economics])
expect(screen.getByRole('status')).toHaveTextContent('Flux RSS enregistrés pour les prochaines synthèses. Aucune récupération ni génération n’a été lancée.')
await userEvent.click(screen.getByRole('button', { name: 'Retirer le flux RSS Bloomberg 1' }))
expect(screen.getByLabelText('URL du flux RSS Bloomberg 1')).toHaveValue(economics)
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(save).toHaveBeenLastCalledWith([economics])
expect(fetchMock).not.toHaveBeenCalled()
})
it.each([
'', 'bad-url', 'http://feed.quanwenrss.com/feed/bloomberg-latest.xml',
'https://feed.quanwenrss.com.evil.invalid/feed/bloomberg-latest.xml',
'https://127.0.0.1/feed/bloomberg-latest.xml',
'https://feed.quanwenrss.com:8443/feed/bloomberg-latest.xml',
'https://user:PRIVATE_SECRET@feed.quanwenrss.com/feed/bloomberg-latest.xml',
`${latest}#fragment`, `${latest}?secret=PRIVATE_SECRET`,
'https://feed.quanwenrss.com/feed/investing-news.xml',
'https://feed.quanwenrss.com/feed/unknown.xml',
])('refuse une URL non autorisée sans requête (%s)', async url => {
show([url])
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
const input = screen.getByLabelText('URL du flux RSS Bloomberg 1')
expect(input).toHaveAttribute('aria-invalid', 'true')
expect(input).toHaveAccessibleDescription(/URL|adresse/i)
const alert = screen.getByRole('alert')
expect(alert).not.toHaveTextContent(/PRIVATE_SECRET|127\.0\.0\.1|https?:/)
expect(save).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
it('refuse les doublons et une liste vidée puis permet de corriger', async () => {
show([latest, latest])
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(screen.getAllByRole('alert')[0]).toHaveTextContent(/déjà présent/)
await userEvent.clear(screen.getByLabelText('URL du flux RSS Bloomberg 2'))
await userEvent.type(screen.getByLabelText('URL du flux RSS Bloomberg 2'), economics)
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(save).toHaveBeenCalledWith([latest, economics])
await userEvent.click(screen.getByRole('button', { name: 'Retirer le flux RSS Bloomberg 2' }))
await userEvent.click(screen.getByRole('button', { name: 'Retirer le flux RSS Bloomberg 1' }))
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(screen.getByRole('alert')).toHaveTextContent(/Ajoutez au moins un flux RSS/)
expect(save).toHaveBeenCalledTimes(1)
})
it('garde les saisies après une erreur de sauvegarde, sans exposer le détail brut, et permet de réessayer', async () => {
save.mockRejectedValueOnce(new Error('PRIVATE_SECRET https://private.invalid'))
show([latest, economics])
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(screen.getByRole('alert')).toHaveTextContent('Impossible d’enregistrer les flux RSS. Votre saisie est conservée. Réessayez.')
expect(screen.getByRole('alert')).not.toHaveTextContent(/PRIVATE_SECRET|private.invalid/)
expect(screen.getByLabelText('URL du flux RSS Bloomberg 2')).toHaveValue(economics)
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(save).toHaveBeenCalledTimes(2)
expect(screen.getByRole('status')).toBeInTheDocument()
})
it('annonce l’enregistrement en cours et empêche les soumissions concurrentes', async () => {
let complete!: () => void
save.mockImplementationOnce(() => new Promise<void>(resolve => { complete = resolve }))
show()
const button = screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' })
await userEvent.click(button)
expect(screen.getByRole('form', { name: 'Flux RSS Bloomberg' })).toHaveAttribute('aria-busy', 'true')
expect(button).toBeDisabled()
expect(screen.getByRole('button', { name: 'Ajouter un flux RSS Bloomberg' })).toBeDisabled()
expect(screen.getByRole('status')).toHaveTextContent('Enregistrement des flux RSS…')
complete()
expect(await screen.findByText(/Flux RSS enregistrés pour les prochaines synthèses/)).toBeInTheDocument()
})
it.each([` ${latest}`, `${latest} `, 'https://feed.quanwenrss.com/feed/../feed/bloomberg-latest.xml'])('refuse une normalisation qui masquerait une URL non conforme au serveur (%s)', async url => {
show([url])
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(screen.getByRole('alert')).toBeInTheDocument()
expect(save).not.toHaveBeenCalled()
})
it('normalise le port HTTPS standard et refuse les doublons normalisés', async () => {
show([latest, 'https://FEED.QUANWENRSS.COM:443/feed/bloomberg-latest.xml'])
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
expect(screen.getByRole('alert')).toHaveTextContent('déjà présent')
expect(save).not.toHaveBeenCalled()
})