feat(watchlist): add company identity catalog

Embed a pinned FinanceDatabase equity snapshot, add authenticated company search and identity-based follows, preserve legacy assets, and map selected Yahoo symbols for collection.

Refs #19

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 15:08:22 +01:00
parent 1123360914
commit d65222169a
50 changed files with 49897 additions and 193 deletions

View File

@ -1,164 +1,191 @@
import { useState, useEffect, useRef, useCallback, type FormEvent } from 'react'
import { assetsApi, type Asset, type IndexSearchResult } from '@/api/assets'
import { assetsApi, type Asset, type CompanySearchResult } 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 { Select } from '@/components/ui/select'
const copy = {
fr: {
title: 'Entreprises suivies', intro: 'Recherchez une entreprise par son nom, choisissez le bon résultat puis suivez-la. Aucune synthèse n’est générée automatiquement.',
searchTitle: 'Rechercher une entreprise', query: "Nom de l'entreprise", search: 'Rechercher',
help: 'La recherche se lance au clic sur Rechercher ou avec Entrée. Jusqu’à 20 résultats, sans sélection automatique.',
results: 'Résultats des entreprises', before: 'Saisissez le nom d’une entreprise, puis lancez la recherche.',
searching: 'Recherche en cours…', empty: 'Aucune entreprise trouvée. Essayez un autre nom.',
quota: 'Quota de recherche atteint. Réessayez plus tard.', timeout: 'Le délai de recherche est dépassé. Vous pouvez relancer la recherche.',
unavailable: 'Le service de recherche est indisponible. Réessayez plus tard.', searchError: 'Impossible de rechercher des entreprises. Vous pouvez relancer la recherche.',
retry: 'Réessayer', follow: 'Suivre cette entreprise', tracked: 'Déjà suivie', unfollow: 'Ne plus suivre',
followed: 'Entreprise suivie.', followError: 'Impossible de suivre cette entreprise. Vos suivis sont conservés.',
conflict: 'Ce suivi ne peut pas être ajouté pour le moment. Aucun suivi existant n’a été modifié.',
removed: 'Entreprise retirée des suivis.', removeError: 'Impossible de retirer cette entreprise. Votre liste est conservée.',
undo: 'Annuler le retrait', undone: 'Retrait annulé.', undoError: 'Impossible d’annuler le retrait. Vous pouvez réessayer.',
loading: 'Chargement des entreprises suivies…', loadError: 'Impossible de charger vos entreprises suivies.', reload: 'Recharger la liste', busy: 'Mise à jour des suivis…',
noFollowed: 'Aucune entreprise suivie. Recherchez puis choisissez une entreprise pour commencer.',
legacy: 'Autres suivis existants', legacyRegion: 'Autres suivis existants — actifs historiques',
legacyHelp: 'Vos indices et autres suivis existants sont conservés sans conversion. Cette section est en lecture seule.', unknown: 'Suivi existant sans nom renseigné',
},
en: {
title: 'Followed companies', intro: 'Search for a company by name, choose the correct result, then follow it. No summary is generated automatically.',
searchTitle: 'Search for a company', query: 'Company name', search: 'Search',
help: 'Search by clicking Search or pressing Enter. Up to 20 results, with no automatic selection.',
results: 'Company results', before: 'Enter a company name, then search.', searching: 'Searching…', empty: 'No company found. Try another name.',
quota: 'Search quota reached. Please try again later.', timeout: 'The search timed out. You can search again.',
unavailable: 'The search service is unavailable. Please try again later.', searchError: 'Unable to search for companies. You can search again.',
retry: 'Try again', follow: 'Follow this company', tracked: 'Already followed', unfollow: 'Unfollow',
followed: 'Company followed.', followError: 'Unable to follow this company. Existing follows are preserved.',
conflict: 'This company cannot be followed right now. No existing follows were changed.',
removed: 'Company unfollowed.', removeError: 'Unable to unfollow this company. Your list is preserved.',
undo: 'Undo unfollow', undone: 'Unfollow undone.', undoError: 'Unable to undo. Please try again.',
loading: 'Loading followed companies…', loadError: 'Unable to load your followed companies.', reload: 'Reload list', busy: 'Updating follows…',
noFollowed: 'No followed companies. Search for and choose a company to get started.',
legacy: 'Other existing follows', legacyRegion: 'Other existing follows — historical assets',
legacyHelp: 'Your indices and other existing follows are preserved without conversion. This section is read-only.', unknown: 'Existing follow with no recorded name',
},
}
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>
}
function CompanyInfo({ company }: { company: Pick<Asset, 'name' | 'country' | 'exchange'> }) {
return <>
<p className="font-semibold break-words">{company.name}</p>
<div className="text-sm text-muted-foreground flex flex-wrap gap-x-3 gap-y-1">
{company.country && <span>{company.country}</span>}
{company.exchange && <span>{company.exchange}</span>}
</div>
</>
}
export function Watchlist() {
const [language, setLanguage] = useState<'fr' | 'en'>('fr')
const text = copy[language]
const [assets, setAssets] = useState<Asset[]>([])
const [loading, setLoading] = useState(true)
const [listError, setListError] = useState('')
const [listError, setListError] = useState(false)
const [query, setQuery] = useState('')
const [results, setResults] = useState<IndexSearchResult[] | null>(null)
const [results, setResults] = useState<CompanySearchResult[] | null>(null)
const [searching, setSearching] = useState(false)
const [searchError, setSearchError] = useState('')
const [actionError, setActionError] = useState('')
const [notice, setNotice] = useState('')
const [searchError, setSearchError] = useState<keyof typeof copy.fr | null>(null)
const [actionError, setActionError] = useState<keyof typeof copy.fr | null>(null)
const [notice, setNotice] = useState<keyof typeof copy.fr | null>(null)
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)
const legacy = assets.filter(asset => !asset.company_id)
const followed = assets.filter(asset => asset.company_id)
const load = useCallback(() => {
return assetsApi.list().then(data => setAssets(data ?? []))
.catch(() => setListError('Impossible de charger vos indices suivis.'))
.finally(() => setLoading(false))
}, [])
const load = useCallback(() => assetsApi.list().then(data => { setAssets(data ?? []); setListError(false) })
.catch(() => setListError(true)).finally(() => setLoading(false)), [])
useEffect(() => {
void load()
return () => { searchRevision.current += 1 }
}, [load])
async function search(event: FormEvent) {
event.preventDefault()
async function search(event?: FormEvent) {
event?.preventDefault()
const value = query.trim()
if (!value || value.length > 100) return
if (!value || value.length > 100 || searching) return
const revision = ++searchRevision.current
setSearching(true); setSearchError(''); setActionError(''); setResults(null)
setSearching(true); setSearchError(null); setActionError(null); setResults(null)
try {
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.')
setSearchError(status === 429 ? 'quota' : status === 504 ? 'timeout' : status === 502 ? 'unavailable' : 'searchError')
} finally { if (revision === searchRevision.current) setSearching(false) }
}
function store(asset: Asset) {
setAssets(current => [...current.filter(item => item.id !== asset.id && (!asset.figi || item.figi !== asset.figi)), asset])
// Only replace the same company follow. Never merge or convert a legacy row.
setAssets(current => [...current.filter(item => item.company_id !== asset.company_id || !item.company_id), asset])
}
async function follow(index: IndexSearchResult) {
async function follow(company: CompanySearchResult) {
if (mutationPending.current) return
mutationPending.current = true
setBusy(true); setActionError(''); setNotice('')
setBusy(true); setActionError(null); setNotice(null)
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) }
const asset = await assetsApi.add({ company_id: company.company_id })
store({ ...asset, name: company.name, company_id: company.company_id, country: company.country, exchange: company.exchange })
setNotice('followed')
} catch (error) { setActionError(errorStatus(error) === 409 ? 'conflict' : 'followError') }
finally { mutationPending.current = false; setBusy(false) }
}
async function remove(asset: Asset) {
if (mutationPending.current) return
if (!asset.company_id || mutationPending.current) return
mutationPending.current = true
setBusy(true); setActionError(''); setSearchError(''); setNotice('')
setBusy(true); setActionError(null); setSearchError(null); setNotice(null)
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.') }
setRemoved(asset); setNotice('removed')
} catch { setActionError('removeError') }
finally { mutationPending.current = false; setBusy(false) }
}
async function undo() {
if (!removed || mutationPending.current) return
if (!removed?.company_id || mutationPending.current) return
mutationPending.current = true
setBusy(true); setActionError('')
setBusy(true); setActionError(null); setNotice(null)
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.') }
const asset = await assetsApi.add({ company_id: removed.company_id })
store({ ...removed, ...asset, name: asset.name || removed.name, company_id: removed.company_id })
setRemoved(null); setNotice('undone')
} catch { setActionError('undoError') }
finally { mutationPending.current = false; setBusy(false) }
}
return (
<div className="p-4 md:p-6 space-y-6">
<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>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>
<Button type="submit" disabled={!query.trim() || searching}>Rechercher</Button>
</form>
<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>
{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>}
</>}
return <div lang={language} className="p-4 md:p-6 space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-2xl font-bold">{text.title}</h1>
<div className="space-y-1"><Label htmlFor="watchlist-language">Langue / Language</Label><Select id="watchlist-language" value={language} onChange={event => setLanguage(event.target.value as 'fr' | 'en')}>
<option value="fr">Français</option><option value="en">English</option>
</Select></div>
</div>
)
<p>{text.intro}</p>
<Card><CardHeader><CardTitle>{text.searchTitle}</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="company-query">{text.query}</Label>
<Input id="company-query" maxLength={100} required value={query} aria-describedby="company-search-help" onChange={event => {
setQuery(event.target.value); searchRevision.current += 1; setSearching(false); setResults(null); setSearchError(null)
}} />
</div>
<Button type="submit" disabled={!query.trim() || searching}>{text.search}</Button>
</form>
<p id="company-search-help" className="text-sm text-muted-foreground">{text.help}</p>
{searchError && <div className="space-y-2"><p role="alert">{text[searchError]}</p><Button variant="outline" disabled={searching || !query.trim()} onClick={() => void search()}>{text.retry}</Button></div>}
<section aria-label={text.results} aria-busy={searching} className="space-y-3">
{searching ? <p role="status">{text.searching}</p> : results === null ? <p>{text.before}</p> : results.length === 0 ? <p role="status">{text.empty}</p> : <ul className="space-y-3">{results.map(company => {
const tracked = assets.some(asset => asset.company_id === company.company_id)
return <li key={company.company_id} className="rounded-md border p-3 space-y-2 min-w-0 break-words">
<CompanyInfo company={company} />
<Button onClick={() => void follow(company)} disabled={tracked || busy || loading || listError}>{tracked ? text.tracked : text.follow}</Button>
</li>
})}</ul>}
</section>
</CardContent></Card>
{actionError && <p role="alert" className="text-destructive">{text[actionError]}</p>}
{notice && <p role="status">{text[notice]}</p>}
{busy && <p role="status">{text.busy}</p>}
{removed && <Button variant="outline" disabled={busy} onClick={() => void undo()}>{text.undo}</Button>}
{loading ? <p role="status">{text.loading}</p> : listError ? <div><p role="alert">{text.loadError}</p><Button onClick={() => { setLoading(true); setListError(false); void load() }}>{text.reload}</Button></div> : <>
<section aria-label={text.title} className="space-y-3"><h2 className="text-lg font-semibold">{text.title}</h2>
{followed.length ? <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{followed.map(asset => <li key={asset.id} className="rounded-md border p-4 space-y-2 min-w-0">
<CompanyInfo company={asset} />
<Button variant="outline" disabled={busy} onClick={() => void remove(asset)} aria-label={`${text.unfollow} ${asset.name}`}>{text.unfollow}</Button>
</li>)}</ul> : <p>{text.noFollowed}</p>}
</section>
{legacy.length > 0 && <section aria-label={text.legacyRegion} className="space-y-3"><h2 className="text-lg font-semibold">{text.legacy}</h2>
<p className="text-sm text-muted-foreground">{text.legacyHelp}</p>
<ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{legacy.map(asset => <li key={asset.id} className="rounded-md border p-4 min-w-0 break-words">{asset.name || text.unknown}</li>)}</ul>
</section>}
</>}
</div>
}