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,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>
)
}