feat(sources): enforce supported source allowlist

Assign stable keys to the three supported sources, preserve excluded historical rows, and expose history read-only in admin. Add migration, coverage, and responsive browser spec.

Refs #13

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 00:11:26 +01:00
parent 4459a81206
commit ac17d27f51
26 changed files with 924 additions and 61 deletions

View File

@ -0,0 +1,59 @@
import { test, expect } from '@playwright/test'
import { readStackManifest } from './stack-manifest.mjs'
async function loginAsBootstrapAdmin(page, stack) {
await page.goto(new URL('/login', stack.frontendUrl).href)
await page.getByLabel('Adresse email').fill(stack.bootstrapAdmin.email)
await page.getByLabel('Mot de passe').fill(stack.bootstrapAdmin.password)
await page.getByRole('button', { name: 'Se connecter' }).click()
await expect(page).toHaveURL(new URL('/', stack.frontendUrl).href)
}
test('admin source controls stay accessible and fit at 320, 375 and 390 px', async ({ page }) => {
const stack = readStackManifest()
await page.context().route('**/*', async route => {
const host = new URL(route.request().url()).hostname
if (host !== '127.0.0.1' && host !== '[::1]') return route.abort('blockedbyclient')
return route.continue()
})
await loginAsBootstrapAdmin(page, stack)
await page.goto(new URL('/admin/sources', stack.frontendUrl).href)
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)
const activationNames = (await activationControls.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-label').replace(/^(Activer|Désactiver) /, '')).sort()))
expect(activationNames).toEqual(['Bloomberg', 'Watcher.Guru', 'Yahoo Finance'])
await expect(page.locator('form[aria-label^="Réglages de "]')).toHaveCount(3)
const historical = page.getByRole('region', { name: 'Anciennes sources exclues' })
await expect(historical).toBeVisible()
await historical.getByText(/^Consulter les anciennes sources/).click()
const historicalRows = historical.locator('li')
expect(await historicalRows.count()).toBeGreaterThan(0)
await expect(historicalRows.locator('button, input, form, a')).toHaveCount(0)
for (const width of [320, 375, 390]) {
await page.setViewportSize({ width, height: 844 })
const dimensions = await page.evaluate(() => ({
viewport: window.innerWidth,
document: document.documentElement.scrollWidth,
}))
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', 'Watcher.Guru']) {
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()
await expect(toggle).toBeEnabled()
await expect(cap).toBeVisible()
await expect(cap).toHaveAttribute('min', '1')
await expect(cap).toHaveAttribute('max', '200')
await expect(page.getByRole('button', { name: `Enregistrer le plafond ${name}` })).toBeVisible()
}
await expect(historical).toBeVisible()
await expect(historicalRows.locator('button, input, form, a')).toHaveCount(0)
}
})

View File

@ -10,7 +10,10 @@ export interface OllamaModelInfo {
name: string; size: number; modified_at: string
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 Source {
id: string; name: string; type: string; enabled: boolean; article_limit: number
source_key: string | null; supported: boolean; operational: boolean
}
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 }

View File

@ -5,25 +5,33 @@ 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', 'watcher_guru'])
function isSupported(source: Source) {
return source.supported === true && source.source_key !== null && SOURCE_KEYS.has(source.source_key)
}
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 [operational, setOperational] = useState(source.operational)
const [limit, setLimit] = useState(String(source.article_limit ?? 20))
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [saved, setSaved] = useState(false)
const [saved, setSaved] = useState('')
const valid = validLimit(limit, 200)
async function toggle() {
if (saving) return
setSaving(true); setError(''); setSaved(false)
setSaving(true); setError(''); setSaved('')
try {
// Omit the limit so even a historical out-of-range value is preserved.
await adminApi.updateSource(source.id, !enabled)
setEnabled(!enabled); setSaved(true)
setEnabled(!enabled); setOperational(!enabled)
setSaved(`${source.name} ${enabled ? 'désactivée' : 'activée'} pour les prochaines synthèses. Aucune génération n’a été lancée.`)
} catch { setError('Impossible de modifier la source. Réessayez.') }
finally { setSaving(false) }
}
@ -31,10 +39,10 @@ function SourceLimit({ source }: { source: Source }) {
async function save(event: FormEvent) {
event.preventDefault()
if (!valid || saving || !enabled) return
setSaving(true); setError(''); setSaved(false)
setSaving(true); setError(''); setSaved('')
try {
await adminApi.updateSource(source.id, enabled, Number(limit))
setSaved(true)
setSaved(`Plafond ${source.name} enregistré pour les prochaines synthèses. Aucune génération n’a été lancée.`)
} catch { setError('Impossible d’enregistrer le plafond. Votre saisie est conservée. Réessayez.') }
finally { setSaving(false) }
}
@ -42,19 +50,19 @@ function SourceLimit({ source }: { source: Source }) {
return (
<Card>
<CardHeader><CardTitle>{source.name}</CardTitle></CardHeader>
<CardContent className="space-y-4">
<CardContent className="space-y-4 min-w-0 break-words">
<div className="flex flex-wrap items-center gap-3">
<span>{enabled ? 'Activée' : 'Désactivée'}</span>
<span>{enabled && operational ? 'Activée pour les synthèses' : 'Désactivée pour les synthèses'}</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('') }} />
<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(''); 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>}
{saved && <p role="status">{saved}</p>}
</CardContent>
</Card>
)
@ -69,6 +77,8 @@ export function Sources() {
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const valid = validLimit(limit, 500)
const supported = sources.filter(isSupported)
const historical = sources.filter(source => !isSupported(source))
useEffect(() => { void load() }, [])
async function load() {
@ -95,7 +105,7 @@ export function Sources() {
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Sources et plafonds</h1>
<p className="text-sm text-muted-foreground">Choisissez les sources utilisées pour les synthèses et leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles.</p>
<p className="text-sm text-muted-foreground">Seules Yahoo Finance, Bloomberg et Watcher Guru 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>
) : <>
@ -105,15 +115,28 @@ export function Sources() {
<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>
<p id="global-limit-help" className={`text-sm ${valid ? 'text-muted-foreground' : 'text-destructive'}`}>{valid ? 'De 1 à 500 articles par génération, parmi les sources autorisées et activées, après sélection par Laya et application des plafonds par source.' : '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>}
{saved && <div role="status"><p>Plafond global enregistré.</p><p>Il s’appliquera aux prochaines synthèses. Aucune génération n’a été lancée.</p></div>}
</form>
</CardContent>
</Card>
{sources.length === 0 && <p>Aucune source disponible.</p>}
{sources.map(source => <SourceLimit key={source.id} source={source} />)}
<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} />)}
</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>
<details className="rounded-md border p-4">
<summary className="cursor-pointer font-medium">Consulter les anciennes sources ({historical.length})</summary>
<p className="mt-3 text-sm text-muted-foreground">Ces sources sont conservées en lecture seule et exclues des synthèses manuelles et planifiées. Elles ne peuvent pas être réactivées. Les bilans des générations passées restent inchangés.</p>
<ul className="mt-3 space-y-3">{historical.map(source => <li key={source.id} className="break-words">
<p className="font-medium">{source.name}</p>
<p className="text-sm text-muted-foreground">Exclue des synthèses · Plafond historique : {source.article_limit}</p>
</li>)}</ul>
</details>
</section>}
</>}
</div>
)

View File

@ -1,4 +1,4 @@
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import { cleanup, render, screen, waitFor, within } 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'
@ -23,7 +23,7 @@ describe('plafonds d’articles administrateur', () => {
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 }])
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 240 }])
updateSource.mockResolvedValue(undefined)
})
@ -93,7 +93,7 @@ describe('plafonds d’articles administrateur', () => {
it('initialise uniquement les valeurs absentes à 50 et 20', async () => {
listSettings.mockResolvedValue([])
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', enabled: true }])
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true }])
render(<Sources />)
expect(await screen.findByLabelText('Articles max par résumé')).toHaveValue(50)
expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(20)
@ -149,4 +149,75 @@ describe('plafonds d’articles administrateur', () => {
expect(updateSource).not.toHaveBeenCalled()
})
it('ne rend activables que Yahoo, Bloomberg et Watcher Guru; garde StockTwits et Reuters en historique sans commandes', async () => {
listSources.mockResolvedValue([
{ id: 'y', name: 'Yahoo Finance', type: 'stocktwits', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 83 },
{ id: 'b', name: 'Bloomberg', type: 'bloomberg', source_key: 'bloomberg', supported: true, operational: true, enabled: false, article_limit: 77 },
{ id: 'w', name: 'Watcher.Guru', type: 'watcherguru', source_key: 'watcher_guru', supported: true, operational: true, enabled: true, article_limit: 64 },
{ id: 's', name: 'StockTwits', type: 'stocktwits', source_key: null, supported: false, operational: false, enabled: false, article_limit: 31 },
{ id: 'r', name: 'Reuters', type: 'reuters', source_key: null, supported: false, operational: false, enabled: false, article_limit: 42 },
])
render(<Sources />)
expect(await screen.findByRole('heading', { name: 'Anciennes sources exclues' })).toBeInTheDocument()
for (const name of ['Yahoo Finance', 'Bloomberg', 'Watcher.Guru']) {
expect(screen.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name}$`) })).toBeInTheDocument()
expect(screen.getByLabelText(`Plafond ${name}`)).toBeInTheDocument()
}
const historical = screen.getByRole('region', { name: 'Anciennes sources exclues' })
expect(within(historical).getByText('StockTwits')).toBeInTheDocument()
expect(within(historical).getByText('Reuters')).toBeInTheDocument()
expect(within(historical).queryByRole('button')).not.toBeInTheDocument()
expect(within(historical).queryByRole('spinbutton')).not.toBeInTheDocument()
const yahooCard = screen.getByRole('form', { name: 'Réglages de Yahoo Finance' }).closest('.rounded-md')
expect(yahooCard).not.toBeNull()
expect(within(yahooCard as HTMLElement).queryByText(/stocktwits/i)).not.toBeInTheDocument()
expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(83)
expect(screen.getByLabelText('Plafond Bloomberg')).toHaveValue(77)
expect(screen.getByLabelText('Plafond Watcher.Guru')).toHaveValue(64)
})
it('garde les anciennes sources repliées et en lecture seule même si enabled est historique', async () => {
listSources.mockResolvedValue([
{ id: 'old', name: 'Reuters', type: 'reuters', source_key: null, supported: false, operational: false, enabled: true, article_limit: 42 },
])
const user = userEvent.setup()
render(<Sources />)
const region = await screen.findByRole('region', { name: 'Anciennes sources exclues' })
const disclosure = region.querySelector('details')!
expect(disclosure).not.toHaveAttribute('open')
await user.click(within(region).getByText('Consulter les anciennes sources (1)'))
expect(disclosure).toHaveAttribute('open')
expect(within(region).getByText('Reuters')).toBeVisible()
expect(within(region).queryByRole('button')).not.toBeInTheDocument()
expect(within(region).queryByRole('spinbutton')).not.toBeInTheDocument()
expect(updateSource).not.toHaveBeenCalled()
})
it('annonce les réglages des prochaines synthèses sans annoncer de génération lancée', async () => {
listSources.mockResolvedValue([{ id: 'y', name: 'Stocktwits', type: 'stocktwits', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 83 }])
const user = userEvent.setup()
render(<Sources />)
const input = await screen.findByLabelText('Plafond Yahoo Finance')
expect(screen.queryByText('Stocktwits')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Désactiver Yahoo Finance' }))
expect(await screen.findByRole('status')).toHaveTextContent('Yahoo Finance désactivée pour les prochaines synthèses. Aucune génération n’a été lancée.')
expect(input).toHaveValue(83)
expect(input).toBeDisabled()
await user.click(screen.getByRole('button', { name: 'Activer Yahoo Finance' }))
await waitFor(() => expect(input).toBeEnabled())
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' }))
expect(await screen.findByRole('status')).toHaveTextContent('Plafond Yahoo Finance enregistré pour les prochaines synthèses.')
expect(updateSource).toHaveBeenLastCalledWith('y', true, 83)
})
it('permet de recharger après un échec sans afficher de commandes pour des sources supposées', async () => {
listSources.mockRejectedValueOnce(new Error('network'))
const user = userEvent.setup()
render(<Sources />)
expect(await screen.findByRole('alert')).toHaveTextContent('Impossible de charger')
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Réessayer' }))
expect(await screen.findByLabelText('Plafond Yahoo Finance')).toHaveValue(240)
})
})