feat(assets): track selected indices by FIGI

Add the nullable FIGI migration, owner-scoped asset identity operations, and the explicit index search and selection flow.

Refs #4

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 22:31:52 +01:00
parent 5cb45138df
commit 8f42c30ec6
20 changed files with 1082 additions and 147 deletions

View File

@ -1,9 +1,12 @@
import { api } from './client'
export interface Asset { id: string; user_id: string; symbol: string; name: string; created_at: string }
export interface Asset { id: string; user_id: string; symbol: string; name: string; figi: string | null; created_at: string }
export interface IndexSearchResult { figi: string; name: string; symbol: string; market?: string }
export interface FollowAsset { symbol: string; name: string; figi?: string | null }
export const assetsApi = {
list: () => api.get<Asset[]>('/me/assets'),
add: (symbol: string, name: string) => api.post<Asset>('/me/assets', { symbol, name }),
remove: (symbol: string) => api.delete<void>(`/me/assets/${symbol}`),
search: (query: string, limit = 20) => api.get<IndexSearchResult[]>(`/indices/search?${new URLSearchParams({ q: query, limit: String(limit) })}`),
add: (asset: FollowAsset) => api.post<Asset>('/me/assets', asset),
remove: (id: string) => api.delete<void>(`/me/assets/${encodeURIComponent(id)}`),
}

View File

@ -21,7 +21,7 @@ export const router = createBrowserRouter([
{ path: '/', element: <Dashboard /> },
{ path: '/feed', element: <Navigate to="/" replace state={{ notice: 'Le fil d’articles a été retiré. Retrouvez vos synthèses et leurs bilans ici.' }} /> },
{ path: '/assets', element: <Watchlist /> },
{ path: '/watchlist', element: <Watchlist /> },
{ path: '/watchlist', element: <Navigate to="/assets" replace /> },
{ path: '/preferences', element: <Preferences /> },
{ path: '/reports', element: <Reports /> },
{

View File

@ -1,117 +1,164 @@
import { useState, useEffect, type FormEvent } from 'react'
import { Plus, Trash2, TrendingUp } from 'lucide-react'
import { assetsApi, type Asset } from '@/api/assets'
import { useState, useEffect, useRef, useCallback, type FormEvent } from 'react'
import { assetsApi, type Asset, type IndexSearchResult } from '@/api/assets'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner'
function errorStatus(error: unknown) {
return error && typeof error === 'object' && 'status' in error ? error.status : undefined
}
function AssetList({ items, busy, onRemove }: { items: Asset[]; busy: boolean; onRemove: (asset: Asset) => void }) {
return <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{items.map(asset => (
<li key={asset.id} className="rounded-md border p-4 space-y-2 min-w-0">
<p className="font-medium break-words">{asset.name || asset.symbol}</p>
<p className="font-mono break-all">{asset.symbol}</p>
{!asset.figi && <p className="text-sm text-muted-foreground">Type non vérifié</p>}
<Button variant="outline" disabled={busy} onClick={() => onRemove(asset)} aria-label={`Ne plus suivre ${asset.name || asset.symbol}`}>Ne plus suivre</Button>
</li>
))}</ul>
}
export function Watchlist() {
const [assets, setAssets] = useState<Asset[]>([])
const [loading, setLoading] = useState(true)
const [symbol, setSymbol] = useState('')
const [name, setName] = useState('')
const [adding, setAdding] = useState(false)
const [removing, setRemoving] = useState<string | null>(null)
const [error, setError] = useState('')
const [listError, setListError] = useState('')
const [query, setQuery] = useState('')
const [results, setResults] = useState<IndexSearchResult[] | null>(null)
const [searching, setSearching] = useState(false)
const [searchError, setSearchError] = useState('')
const [actionError, setActionError] = useState('')
const [notice, setNotice] = useState('')
const [busy, setBusy] = useState(false)
const [removed, setRemoved] = useState<Asset | null>(null)
const searchRevision = useRef(0)
const mutationPending = useRef(false)
const legacy = assets.filter(asset => !asset.figi)
const followed = assets.filter(asset => asset.figi)
useEffect(() => { load() }, [])
const load = useCallback(() => {
return assetsApi.list().then(data => setAssets(data ?? []))
.catch(() => setListError('Impossible de charger vos indices suivis.'))
.finally(() => setLoading(false))
}, [])
async function load() {
setLoading(true)
try { setAssets(await assetsApi.list() ?? []) } finally { setLoading(false) }
}
useEffect(() => {
void load()
return () => { searchRevision.current += 1 }
}, [load])
async function add(e: FormEvent) {
e.preventDefault()
if (!symbol) return
setAdding(true); setError('')
async function search(event: FormEvent) {
event.preventDefault()
const value = query.trim()
if (!value || value.length > 100) return
const revision = ++searchRevision.current
setSearching(true); setSearchError(''); setActionError(''); setResults(null)
try {
await assetsApi.add(symbol.toUpperCase(), name)
setSymbol(''); setName('')
await load()
} catch (err) { setError(err instanceof Error ? err.message : 'Erreur') } finally { setAdding(false) }
const data = await assetsApi.search(value, 20)
if (revision === searchRevision.current) setResults((data ?? []).slice(0, 20))
} catch (error) {
if (revision !== searchRevision.current) return
const status = errorStatus(error)
setSearchError(status === 429 ? 'Quota de recherche atteint. Réessayez plus tard.'
: status === 504 ? 'Le délai de recherche est dépassé. Vous pouvez relancer la recherche.'
: status === 502 ? 'Le fournisseur de recherche est indisponible. Réessayez plus tard.'
: 'Impossible de rechercher des indices. Vous pouvez relancer la recherche.')
} finally { if (revision === searchRevision.current) setSearching(false) }
}
async function remove(sym: string) {
setRemoving(sym)
await assetsApi.remove(sym)
await load()
setRemoving(null)
function store(asset: Asset) {
setAssets(current => [...current.filter(item => item.id !== asset.id && (!asset.figi || item.figi !== asset.figi)), asset])
}
async function follow(index: IndexSearchResult) {
if (mutationPending.current) return
mutationPending.current = true
setBusy(true); setActionError(''); setNotice('')
try {
store(await assetsApi.add({ symbol: index.symbol, name: index.name, figi: index.figi }))
setNotice(`${index.name} est maintenant suivi.`)
} catch (error) {
setActionError(errorStatus(error) === 409
? 'Cet indice correspond à un actif historique ambigu. Aucun suivi n’a été modifié.'
: 'Impossible de suivre cet indice. Vos indices suivis sont conservés.')
} finally { mutationPending.current = false; setBusy(false) }
}
async function remove(asset: Asset) {
if (mutationPending.current) return
mutationPending.current = true
setBusy(true); setActionError(''); setSearchError(''); setNotice('')
try {
await assetsApi.remove(asset.id)
setAssets(current => current.filter(item => item.id !== asset.id))
setRemoved(asset); setNotice(`${asset.name || asset.symbol} n’est plus suivi.`)
} catch { setActionError('Impossible de retirer cet actif. Votre liste est conservée.') }
finally { mutationPending.current = false; setBusy(false) }
}
async function undo() {
if (!removed || mutationPending.current) return
mutationPending.current = true
setBusy(true); setActionError('')
try {
store(await assetsApi.add({ symbol: removed.symbol, name: removed.name, ...(removed.figi ? { figi: removed.figi } : {}) }))
setRemoved(null); setNotice('Retrait annulé.')
} catch { setActionError('Impossible d’annuler le retrait. Vous pouvez réessayer.') }
finally { mutationPending.current = false; setBusy(false) }
}
return (
<div className="p-4 md:p-6 space-y-6">
<div>
<h1 className="text-2xl font-bold">Watchlist</h1>
<p className="text-muted-foreground text-sm">Les symboles suivis seront utilisés pour personnaliser vos résumés IA</p>
</div>
{/* Formulaire d'ajout */}
<h1 className="text-2xl font-bold">Indices suivis</h1>
<p>Recherchez un indice avec OpenFIGI, choisissez le résultat puis suivez-le. Aucune génération de synthèse n’est lancée automatiquement.</p>
<Card>
<CardHeader><CardTitle className="text-base">Ajouter un actif</CardTitle></CardHeader>
<CardContent>
<form onSubmit={add} className="flex flex-wrap gap-3 items-end">
<div className="space-y-1 flex-1 min-w-32">
<Label>Symbole</Label>
<Input
placeholder="AAPL, TSLA, BTC…"
value={symbol}
onChange={e => setSymbol(e.target.value.toUpperCase())}
className="font-mono"
required
/>
<CardHeader><CardTitle>Rechercher un indice</CardTitle></CardHeader>
<CardContent className="space-y-4">
<form onSubmit={search} className="flex flex-wrap items-end gap-3">
<div className="flex-1 min-w-0 space-y-1.5">
<Label htmlFor="index-query">Nom ou symbole</Label>
<Input id="index-query" maxLength={100} required value={query} aria-describedby="index-search-help" onChange={event => {
setQuery(event.target.value); searchRevision.current += 1; setSearching(false); setResults(null); setSearchError('')
}} />
</div>
<div className="space-y-1 flex-1 min-w-40">
<Label>Nom <span className="text-muted-foreground">(optionnel)</span></Label>
<Input
placeholder="Apple Inc."
value={name}
onChange={e => setName(e.target.value)}
/>
</div>
<Button type="submit" disabled={adding || !symbol}>
{adding ? <Spinner className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
Ajouter
</Button>
<Button type="submit" disabled={!query.trim() || searching}>Rechercher</Button>
</form>
{error && <p className="mt-2 text-sm text-destructive">{error}</p>}
<p id="index-search-help" className="text-sm text-muted-foreground">La recherche utilise le quota OpenFIGI uniquement au clic sur Rechercher ou avec Entrée. Choisissez explicitement parmi les 20 résultats maximum.</p>
{searchError && <p role="alert">{searchError}</p>}
<section aria-label="Résultats de recherche" aria-busy={searching} className="space-y-3">
{searching ? <p role="status">Recherche en cours…</p> : results === null ? <p>Saisissez un nom ou un symbole, puis lancez la recherche.</p> : results.length === 0 ? <p role="status">Aucun indice trouvé. Essayez un autre nom ou symbole.</p> : (
<ul className="space-y-3">{results.map(index => {
const tracked = assets.some(asset => asset.figi === index.figi)
const ambiguous = results.some(other => other.figi !== index.figi && other.symbol === index.symbol)
return <li key={index.figi} className="rounded-md border p-3 space-y-2 break-words">
<p className="font-medium">{index.name}</p><p>{index.symbol}</p>
{index.market && <p>{index.market}</p>}
{ambiguous && <p className="font-mono break-all">{index.figi}</p>}
<Button onClick={() => void follow(index)} disabled={tracked || busy || loading || !!listError}>{tracked ? 'Déjà suivi' : 'Suivre cet indice'}</Button>
</li>
})}</ul>
)}
</section>
</CardContent>
</Card>
{/* Liste */}
{loading ? (
<div className="flex justify-center py-12"><Spinner /></div>
) : assets.length === 0 ? (
<Card className="border-dashed">
<CardContent className="py-12 text-center">
<TrendingUp className="h-10 w-10 mx-auto text-muted-foreground mb-3 opacity-50" />
<p className="text-muted-foreground">Aucun actif dans votre watchlist</p>
</CardContent>
</Card>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{assets.map(a => (
<Card key={a.id} className="flex items-center justify-between p-4">
<div className="flex items-center gap-3 min-w-0">
<Badge variant="secondary" className="font-mono shrink-0">{a.symbol}</Badge>
{a.name && <span className="text-sm text-muted-foreground truncate">{a.name}</span>}
</div>
<Button
variant="ghost"
size="icon"
className="shrink-0 h-7 w-7 text-muted-foreground hover:text-destructive"
onClick={() => remove(a.symbol)}
disabled={removing === a.symbol}
>
{removing === a.symbol ? <Spinner className="h-3 w-3" /> : <Trash2 className="h-3 w-3" />}
</Button>
</Card>
))}
</div>
)}
{actionError && <p role="alert" className="text-destructive">{actionError}</p>}
{notice && <p role="status">{notice}</p>}
{busy && <p role="status">Mise à jour des indices suivis…</p>}
{removed && <Button variant="outline" disabled={busy} onClick={() => void undo()}>Annuler le retrait</Button>}
{loading ? <p role="status">Chargement des indices suivis…</p> : listError ? <div><p role="alert">{listError}</p><Button onClick={() => { setLoading(true); setListError(''); void load() }}>Recharger la liste</Button></div> : <>
<section aria-label="Indices suivis" className="space-y-3">
<h2 className="text-lg font-semibold">Indices suivis</h2>
{followed.length ? <AssetList items={followed} busy={busy} onRemove={remove} /> : <p>Aucun indice suivi. Recherchez puis choisissez un indice pour commencer.</p>}
</section>
{legacy.length > 0 && <section aria-label="Actifs historiques" className="space-y-3">
<h2 className="text-lg font-semibold">Actifs historiques</h2>
<p className="text-sm text-muted-foreground">Ces actifs restent utilisés dans vos synthèses. Leur type n’a pas été vérifié ; ils ne sont ni convertis ni retirés automatiquement.</p>
{<AssetList items={legacy} busy={busy} onRemove={remove} />}
</section>}
</>}
</div>
)
}

View File

@ -0,0 +1,32 @@
import { afterEach, expect, it, vi } from 'vitest'
import { assetsApi } from '../src/api/assets'
import { ApiError } from '../src/api/client'
afterEach(() => { vi.unstubAllGlobals(); localStorage.clear() })
it('recherche explicitement avec q/limit, suit le FIGI et retire par ID', async () => {
localStorage.setItem('token', 'reader-token')
const index = { symbol: 'SPX', name: 'S&P 500', figi: 'BBG-INDEX' }
const legacy = { id: 'legacy-id', symbol: 'OLD', name: 'Historic', figi: null }
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [index] })))
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'asset-id', ...index } }), { status: 201 }))
.mockResolvedValueOnce(new Response(null, { status: 204 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [legacy] })))
vi.stubGlobal('fetch', fetchMock)
expect(await assetsApi.search('S&P 500', 20)).toEqual([index])
await assetsApi.add(index)
await assetsApi.remove('asset/id')
expect(await assetsApi.list()).toEqual([legacy])
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/indices/search?q=S%26P+500&limit=20', expect.objectContaining({ headers: expect.objectContaining({ Authorization: 'Bearer reader-token' }) }))
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/me/assets', expect.objectContaining({ method: 'POST', body: JSON.stringify(index) }))
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/me/assets/asset%2Fid', expect.objectContaining({ method: 'DELETE' }))
})
it('conserve le statut HTTP pour les messages quota et indisponibilité', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'rate limited' }), { status: 429 })))
const error = await assetsApi.search('NASDAQ', 20).catch(error => error)
expect(error).toBeInstanceOf(ApiError)
expect(error.status).toBe(429)
expect(error.message).toBe('rate limited')
})

View File

@ -0,0 +1,158 @@
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 { Watchlist } from '../src/pages/Watchlist'
const { listAssets, searchIndices, addAsset, removeAsset } = vi.hoisted(() => ({
listAssets: vi.fn(),
searchIndices: vi.fn(),
addAsset: vi.fn(),
removeAsset: vi.fn(),
}))
vi.mock('@/api/assets', () => ({
assetsApi: {
list: listAssets,
search: searchIndices,
add: addAsset,
remove: removeAsset,
},
}))
const legacyAsset = {
id: 'legacy-asset-1', user_id: 'reader-1', symbol: 'OLDX', name: 'Old historic asset',
figi: null, created_at: '2025-01-01T00:00:00.000Z',
}
const indexOne = { figi: 'BBG000SPX001', name: 'S&P 500', symbol: 'SPX', market: 'US' }
const indexTwo = { figi: 'BBG000SPX002', name: 'S&P 500 alternate listing', symbol: 'SPX', market: 'US' }
function apiError(status: number, message: string) {
return Object.assign(new Error(message), { status })
}
function resultRegion() {
return screen.getByRole('region', { name: /résultats de recherche/i })
}
describe('Ticket #4 — rechercher et suivre des indices', () => {
afterEach(cleanup)
beforeEach(() => {
vi.clearAllMocks()
listAssets.mockResolvedValue([legacyAsset])
searchIndices.mockResolvedValue([])
addAsset.mockResolvedValue({ id: 'new-index-1', ...indexOne, user_id: 'reader-1' })
removeAsset.mockResolvedValue(undefined)
})
it('déclenche la recherche explicitement au clic ou à Entrée et limite la demande à 20 résultats', async () => {
const user = userEvent.setup()
searchIndices.mockResolvedValueOnce([indexOne])
render(<Watchlist />)
const query = await screen.findByRole('textbox', { name: 'Nom ou symbole' })
expect(query).toHaveAttribute('maxLength', '100')
await user.type(query, 'S&P 500')
expect(searchIndices).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Rechercher' }))
await waitFor(() => expect(searchIndices).toHaveBeenCalledWith('S&P 500', 20))
expect(await within(resultRegion()).findByText('S&P 500')).toBeInTheDocument()
expect(within(resultRegion()).queryByText('BBG000SPX001')).not.toBeInTheDocument()
await user.clear(query)
await user.type(query, 'NASDAQ{Enter}')
await waitFor(() => expect(searchIndices).toHaveBeenLastCalledWith('NASDAQ', 20))
expect(searchIndices).toHaveBeenCalledTimes(2)
})
it('exige le choix explicite, transmet le FIGI, affiche les doublons ambigus et garde les actifs legacy', async () => {
const user = userEvent.setup()
listAssets.mockResolvedValueOnce([legacyAsset, { id: 'followed-1', ...indexOne, user_id: 'reader-1' }])
searchIndices.mockResolvedValueOnce([indexOne, indexTwo])
render(<Watchlist />)
const history = await screen.findByRole('region', { name: /actifs historiques/i })
expect(within(history).getByText('Type non vérifié')).toBeInTheDocument()
expect(within(history).getByText('Old historic asset')).toBeInTheDocument()
expect(screen.getByLabelText('Nom ou symbole')).toBeInTheDocument()
const query = screen.getByRole('textbox', { name: 'Nom ou symbole' })
await user.type(query, 'S&P 500{Enter}')
const results = await screen.findByRole('region', { name: /résultats de recherche/i })
expect(within(results).getByText('BBG000SPX001')).toBeInTheDocument()
expect(within(results).getByText('BBG000SPX002')).toBeInTheDocument()
expect(within(results).getByRole('button', { name: /déjà suivi/i })).toBeDisabled()
const follow = within(results).getAllByRole('button', { name: /suivre cet indice/i })[0]
await user.click(follow)
await waitFor(() => expect(addAsset).toHaveBeenCalledWith({
symbol: 'SPX', name: 'S&P 500 alternate listing', figi: 'BBG000SPX002',
}))
expect(addAsset).toHaveBeenCalledTimes(1)
expect(within(history).getByText('Old historic asset')).toBeInTheDocument()
})
it('annonce aucun résultat et les erreurs quota, timeout et indisponibilité sans effacer la recherche', async () => {
const user = userEvent.setup()
render(<Watchlist />)
const query = await screen.findByRole('textbox', { name: 'Nom ou symbole' })
searchIndices.mockResolvedValueOnce([])
await user.type(query, 'No match{Enter}')
expect(await screen.findByText(/aucun indice trouvé/i)).toBeInTheDocument()
for (const [error, message] of [
[apiError(429, 'rate limited'), /quota de recherche/i],
[apiError(504, 'timeout'), /délai.*dépassé|timeout/i],
[apiError(502, 'provider unavailable'), /fournisseur.*indisponible/i],
] as const) {
searchIndices.mockRejectedValueOnce(error)
await user.clear(query)
await user.type(query, 'NASDAQ{Enter}')
expect(await screen.findByRole('alert')).toHaveTextContent(message)
expect(query).toHaveValue('NASDAQ')
}
expect(searchIndices).toHaveBeenCalledTimes(4)
})
it('ignore les réponses de recherches obsolètes sans remplacer les résultats courants', async () => {
let resolveOld!: (value: unknown) => void
let resolveCurrent!: (value: unknown) => void
searchIndices
.mockReturnValueOnce(new Promise(resolve => { resolveOld = resolve }))
.mockReturnValueOnce(new Promise(resolve => { resolveCurrent = resolve }))
const user = userEvent.setup()
render(<Watchlist />)
const query = await screen.findByRole('textbox', { name: 'Nom ou symbole' })
await user.type(query, 'Old query{Enter}')
await user.clear(query)
await user.type(query, 'Current query{Enter}')
resolveCurrent([{ figi: 'BBG-CURRENT', name: 'Current index', symbol: 'CUR' }])
expect(await screen.findByText('Current index')).toBeInTheDocument()
resolveOld([{ figi: 'BBG-STALE', name: 'Stale index', symbol: 'OLD' }])
await waitFor(() => expect(screen.queryByText('Stale index')).not.toBeInTheDocument())
expect(screen.getByText('Current index')).toBeInTheDocument()
})
it('conserve les actifs après erreur de suivi ou retrait et permet le retrait par identifiant', async () => {
const user = userEvent.setup()
listAssets.mockResolvedValueOnce([{ id: 'tracked-1', ...indexOne, user_id: 'reader-1' }])
addAsset.mockRejectedValueOnce(apiError(409, 'ambiguous legacy asset'))
removeAsset.mockRejectedValueOnce(new Error('network unavailable'))
searchIndices.mockResolvedValueOnce([indexTwo])
render(<Watchlist />)
const query = await screen.findByRole('textbox', { name: 'Nom ou symbole' })
await user.type(query, 'S&P 500{Enter}')
const results = await screen.findByRole('region', { name: /résultats de recherche/i })
await user.click(within(results).getByRole('button', { name: /suivre cet indice/i }))
expect(await screen.findByRole('alert')).toBeInTheDocument()
expect(query).toHaveValue('S&P 500')
await user.click(screen.getByRole('button', { name: /ne plus suivre/i }))
expect(await screen.findByRole('alert')).toBeInTheDocument()
expect(removeAsset).toHaveBeenCalledWith('tracked-1')
expect(screen.getByText('S&P 500')).toBeInTheDocument()
})
})