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

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