feat(ranking): add safe article ranking and limits
Rank candidate articles using the selected preference and enforce global and per-source article limits. Refs #6 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -1,56 +1,119 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, type FormEvent } from 'react'
|
||||
import { adminApi, type Source } from '@/api/admin'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
function validLimit(value: string, max: number) {
|
||||
return /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= max
|
||||
}
|
||||
|
||||
function SourceLimit({ source }: { source: Source }) {
|
||||
const [enabled, setEnabled] = useState(source.enabled)
|
||||
const [limit, setLimit] = useState(String(source.article_limit ?? 20))
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [saved, setSaved] = useState(false)
|
||||
const valid = validLimit(limit, 200)
|
||||
|
||||
async function toggle() {
|
||||
if (saving) return
|
||||
setSaving(true); setError(''); setSaved(false)
|
||||
try {
|
||||
// Omit the limit so even a historical out-of-range value is preserved.
|
||||
await adminApi.updateSource(source.id, !enabled)
|
||||
setEnabled(!enabled); setSaved(true)
|
||||
} catch { setError('Impossible de modifier la source. Réessayez.') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
|
||||
async function save(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (!valid || saving || !enabled) return
|
||||
setSaving(true); setError(''); setSaved(false)
|
||||
try {
|
||||
await adminApi.updateSource(source.id, enabled, Number(limit))
|
||||
setSaved(true)
|
||||
} catch { setError('Impossible d’enregistrer le plafond. Votre saisie est conservée. Réessayez.') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader><CardTitle>{source.name}</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span>{enabled ? 'Activée' : 'Désactivée'}</span>
|
||||
<Button type="button" variant="outline" disabled={saving} aria-label={`${enabled ? 'Désactiver' : 'Activer'} ${source.name}`} onClick={() => void toggle()}>{enabled ? 'Désactiver' : 'Activer'}</Button>
|
||||
</div>
|
||||
<form onSubmit={save} noValidate aria-label={`Réglages de ${source.name}`} aria-busy={saving} className="space-y-3">
|
||||
<Label htmlFor={`limit-${source.id}`}>Plafond {source.name}</Label>
|
||||
<Input id={`limit-${source.id}`} type="number" min="1" max="200" step="1" required className="max-w-xs" disabled={!enabled || saving} value={limit} aria-invalid={!valid} aria-describedby={`limit-help-${source.id}`} onChange={e => { setLimit(e.target.value); setSaved(false); setError('') }} />
|
||||
<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>
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
{saved && <p role="status">Source {source.name} enregistrée.</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export function Sources() {
|
||||
const [sources, setSources] = useState<Source[]>([])
|
||||
const [limit, setLimit] = useState('50')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [toggling, setToggling] = useState<string | null>(null)
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
const valid = validLimit(limit, 500)
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
useEffect(() => { void load() }, [])
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try { setSources((await adminApi.listSources()) ?? []) } finally { setLoading(false) }
|
||||
setLoading(true); setLoadError('')
|
||||
try {
|
||||
const [sourceList, settings] = await Promise.all([adminApi.listSources(), adminApi.listSettings()])
|
||||
setSources(sourceList ?? [])
|
||||
setLimit((settings ?? []).find(s => s.key === 'summary_max_articles')?.value ?? '50')
|
||||
} catch { setLoadError('Impossible de charger les sources et plafonds. Réessayez.') }
|
||||
finally { setLoading(false) }
|
||||
}
|
||||
|
||||
async function toggle(s: Source) {
|
||||
setToggling(s.id)
|
||||
await adminApi.updateSource(s.id, !s.enabled)
|
||||
await load()
|
||||
setToggling(null)
|
||||
async function save(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (!valid || saving) return
|
||||
setSaving(true); setError(''); setSaved(false)
|
||||
try {
|
||||
await adminApi.updateSettings([{ key: 'summary_max_articles', value: limit }])
|
||||
setSaved(true)
|
||||
} catch { setError('Impossible d’enregistrer le plafond global. Votre saisie est conservée. Réessayez.') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
|
||||
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Sources de news</h1>
|
||||
<p className="text-muted-foreground text-sm">Activez ou désactivez les sources de données</p>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{sources.map(s => (
|
||||
<Card key={s.id}>
|
||||
<CardContent className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<span className="font-semibold">{s.name}</span>
|
||||
<span className="ml-2 text-xs text-muted-foreground capitalize">({s.type})</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={s.enabled ? 'default' : 'outline'}>
|
||||
{s.enabled ? 'Activée' : 'Désactivée'}
|
||||
</Badge>
|
||||
<Button variant="outline" size="sm" onClick={() => toggle(s)} disabled={toggling === s.id}>
|
||||
{toggling === s.id ? <Spinner className="h-3 w-3" /> : s.enabled ? 'Désactiver' : 'Activer'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold">Sources et plafonds</h1>
|
||||
{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>
|
||||
) : <>
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Plafond global</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={save} noValidate aria-label="Plafond global" aria-busy={saving} className="space-y-3">
|
||||
<Label htmlFor="summary-max-articles">Articles max par résumé</Label>
|
||||
<Input id="summary-max-articles" type="number" min="1" max="500" step="1" required className="max-w-xs" value={limit} disabled={saving} aria-invalid={!valid} aria-describedby="global-limit-help" onChange={e => { setLimit(e.target.value); setSaved(false); setError('') }} />
|
||||
<p id="global-limit-help" className={`text-sm ${valid ? 'text-muted-foreground' : 'text-destructive'}`}>{valid ? 'De 1 à 500 articles par génération, toutes sources confondues.' : 'Saisissez un nombre entier de 1 à 500 pour enregistrer. La valeur actuelle est conservée tant que vous ne la modifiez pas.'}</p>
|
||||
<Button type="submit" disabled={!valid || saving}>{saving ? 'Enregistrement…' : 'Enregistrer'}</Button>
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
{saved && <p role="status">Plafond global enregistré.</p>}
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{sources.length === 0 && <p>Aucune source disponible.</p>}
|
||||
{sources.map(source => <SourceLimit key={source.id} source={source} />)}
|
||||
</>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
152
frontend/tests/admin-article-limits.test.tsx
Normal file
152
frontend/tests/admin-article-limits.test.tsx
Normal file
@ -0,0 +1,152 @@
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { AdminSettings } from '../src/pages/admin/AdminSettings'
|
||||
import { Sources } from '../src/pages/admin/Sources'
|
||||
|
||||
const { listSettings, getDefaultPrompt, updateSettings, listSources, updateSource } = vi.hoisted(() => ({
|
||||
listSettings: vi.fn(),
|
||||
getDefaultPrompt: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
listSources: vi.fn(),
|
||||
updateSource: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/admin', () => ({
|
||||
adminApi: { listSettings, getDefaultPrompt, updateSettings, listSources, updateSource },
|
||||
}))
|
||||
|
||||
describe('plafonds d’articles administrateur', () => {
|
||||
afterEach(cleanup)
|
||||
beforeEach(() => {
|
||||
listSettings.mockResolvedValue([{ key: 'summary_max_articles', value: '700' }])
|
||||
getDefaultPrompt.mockResolvedValue({ prompt: 'system' })
|
||||
updateSettings.mockResolvedValue(undefined)
|
||||
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', enabled: true, article_limit: 240 }])
|
||||
updateSource.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('borne le plafond global de 1 à 500 sans écrêter une valeur historique', async () => {
|
||||
render(<Sources />)
|
||||
const input = await screen.findByLabelText('Articles max par résumé')
|
||||
expect(input).toHaveValue(700)
|
||||
expect(input).toHaveAttribute('min', '1')
|
||||
expect(input).toHaveAttribute('max', '500')
|
||||
})
|
||||
|
||||
it('sauvegarde le plafond global via les paramètres admin', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
const input = await screen.findByLabelText('Articles max par résumé')
|
||||
await user.clear(input)
|
||||
await user.type(input, '50')
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
|
||||
await waitFor(() => expect(updateSettings).toHaveBeenCalledWith([{ key: 'summary_max_articles', value: '50' }]))
|
||||
})
|
||||
|
||||
it('borne chaque plafond source de 1 à 200 et conserve une ancienne valeur hors plage', async () => {
|
||||
render(<Sources />)
|
||||
const input = await screen.findByLabelText('Plafond Yahoo Finance')
|
||||
expect(input).toHaveValue(240)
|
||||
expect(input).toHaveAttribute('min', '1')
|
||||
expect(input).toHaveAttribute('max', '200')
|
||||
})
|
||||
|
||||
it('sauvegarde le plafond de la source via l’API admin', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
const input = await screen.findByLabelText('Plafond Yahoo Finance')
|
||||
await user.clear(input)
|
||||
await user.type(input, '20')
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' }))
|
||||
await waitFor(() => expect(updateSource).toHaveBeenCalledWith('source-1', true, 20))
|
||||
})
|
||||
it('remplace l’éditeur en doublon dans Paramètres par un lien et garde le filtre séparé', async () => {
|
||||
listSettings.mockResolvedValue([{ key: 'summary_max_articles', value: '700' }, { key: 'filter_batch_size', value: '10' }])
|
||||
render(<MemoryRouter><AdminSettings /></MemoryRouter>)
|
||||
expect(await screen.findByRole('link', { name: 'Sources et plafonds' })).toHaveAttribute('href', '/admin/sources')
|
||||
expect(screen.queryByLabelText('Articles max par résumé')).not.toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Taille des batches (filtre)')).toHaveValue(10)
|
||||
})
|
||||
|
||||
it('bloque une valeur historique globale jusqu’à une correction explicite sans substitution', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
const input = await screen.findByLabelText('Articles max par résumé')
|
||||
const save = screen.getByRole('button', { name: 'Enregistrer', exact: true })
|
||||
expect(input).toHaveValue(700)
|
||||
expect(save).toBeDisabled()
|
||||
await user.click(save)
|
||||
expect(updateSettings).not.toHaveBeenCalled()
|
||||
for (const value of ['0', '501', '2.5']) {
|
||||
await user.clear(input)
|
||||
await user.type(input, value)
|
||||
expect(save).toBeDisabled()
|
||||
expect(input).toHaveValue(Number(value))
|
||||
}
|
||||
await user.clear(input)
|
||||
expect(save).toBeDisabled()
|
||||
await user.type(input, '500')
|
||||
expect(save).toBeEnabled()
|
||||
})
|
||||
|
||||
it('initialise uniquement les valeurs absentes à 50 et 20', async () => {
|
||||
listSettings.mockResolvedValue([])
|
||||
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', enabled: true }])
|
||||
render(<Sources />)
|
||||
expect(await screen.findByLabelText('Articles max par résumé')).toHaveValue(50)
|
||||
expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(20)
|
||||
})
|
||||
|
||||
it('conserve le plafond historique pendant la désactivation et la réactivation', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
const input = await screen.findByLabelText('Plafond Yahoo Finance')
|
||||
await user.click(screen.getByRole('button', { name: 'Désactiver Yahoo Finance' }))
|
||||
await waitFor(() => expect(input).toBeDisabled())
|
||||
expect(input).toHaveValue(240)
|
||||
expect(updateSource).toHaveBeenLastCalledWith('source-1', false)
|
||||
await user.click(screen.getByRole('button', { name: 'Activer Yahoo Finance' }))
|
||||
await waitFor(() => expect(input).toBeEnabled())
|
||||
expect(input).toHaveValue(240)
|
||||
expect(updateSource).toHaveBeenLastCalledWith('source-1', true)
|
||||
})
|
||||
|
||||
it('conserve les saisies après échec et annonce la réussite uniquement après sauvegarde', async () => {
|
||||
updateSettings.mockRejectedValueOnce(new Error('network'))
|
||||
updateSource.mockRejectedValueOnce(new Error('network'))
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
const global = await screen.findByLabelText('Articles max par résumé')
|
||||
await user.clear(global)
|
||||
await user.type(global, '50')
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer', exact: true }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Votre saisie est conservée.')
|
||||
expect(global).toHaveValue(50)
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer', exact: true }))
|
||||
expect(await screen.findByRole('status')).toHaveTextContent('Plafond global enregistré.')
|
||||
const source = screen.getByLabelText('Plafond Yahoo Finance')
|
||||
await user.clear(source)
|
||||
await user.type(source, '20')
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Impossible d’enregistrer le plafond.')
|
||||
expect(source).toHaveValue(20)
|
||||
})
|
||||
|
||||
it('rejette les plafonds source hors bornes et fractionnaires sans les écrêter', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
const input = await screen.findByLabelText('Plafond Yahoo Finance')
|
||||
const save = screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' })
|
||||
for (const value of ['0', '201', '1.5']) {
|
||||
await user.clear(input)
|
||||
await user.type(input, value)
|
||||
expect(input).toHaveValue(Number(value))
|
||||
expect(save).toBeDisabled()
|
||||
}
|
||||
expect(updateSource).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
})
|
||||
Reference in New Issue
Block a user