Files
TradarrV2/frontend/src/pages/Watchlist.tsx
Blomios f7b057efa3 feat(search): add exact company aliases
Embed a versioned local alias overlay and rank exact aliases before legal-name matches and word prefixes. Normalize Unicode consistently, deduplicate by company identity before limiting, and update bilingual search guidance and tests.

Refs #24

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-22 18:08:35 +01:00

192 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useEffect, useRef, useCallback, type FormEvent } from 'react'
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 ou nom courant de l’entreprise', search: 'Rechercher',
help: 'Saisissez le nom ou le nom courant d’une entreprise, par exemple Intel ou IBM. 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 ou nom courant, par exemple Intel ou IBM.',
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 or commonly used name', search: 'Search',
help: 'Enter a company name or commonly used name, such as Intel or IBM. 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 or commonly used name, such as Intel or IBM.',
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 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(false)
const [query, setQuery] = useState('')
const [results, setResults] = useState<CompanySearchResult[] | null>(null)
const [searching, setSearching] = useState(false)
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.company_id)
const followed = assets.filter(asset => asset.company_id)
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()
const value = query.trim()
if (!value || value.length > 100 || searching) return
const revision = ++searchRevision.current
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' : status === 504 ? 'timeout' : status === 502 ? 'unavailable' : 'searchError')
} finally { if (revision === searchRevision.current) setSearching(false) }
}
function store(asset: 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(company: CompanySearchResult) {
if (mutationPending.current) return
mutationPending.current = true
setBusy(true); setActionError(null); setNotice(null)
try {
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 (!asset.company_id || mutationPending.current) return
mutationPending.current = true
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('removed')
} catch { setActionError('removeError') }
finally { mutationPending.current = false; setBusy(false) }
}
async function undo() {
if (!removed?.company_id || mutationPending.current) return
mutationPending.current = true
setBusy(true); setActionError(null); setNotice(null)
try {
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 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>
}