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:
@ -68,7 +68,7 @@ export function readStackManifest() {
|
||||
if (!manifest.bootstrapAdmin?.email || !manifest.bootstrapAdmin?.password) {
|
||||
throw new Error('E2E fake stack manifest must provide disposable bootstrap admin credentials.')
|
||||
}
|
||||
for (const field of ['indexQuery', 'indexName', 'indexSymbol', 'indexFIGI', 'summaryModelID', 'summarySentinel', 'articleTitle', 'articleURL', 'articleContent', 'candidateID']) {
|
||||
for (const field of ['companyQuery', 'companyID', 'companyName', 'companySymbol', 'companyFIGI', 'summaryModelID', 'summarySentinel', 'articleTitle', 'articleURL', 'articleContent', 'candidateID']) {
|
||||
if (typeof manifest.fixtures?.[field] !== 'string' || !manifest.fixtures[field]) {
|
||||
throw new Error(`E2E fake stack manifest is missing fixtures.${field}.`)
|
||||
}
|
||||
|
||||
@ -35,7 +35,7 @@ async function login(page, baseURL, email, password) {
|
||||
await expect(page).toHaveURL(new URL('/', baseURL).href)
|
||||
}
|
||||
|
||||
test('admin creates a user who follows a fake index and generates a private summary without article/job writes', async ({ page, request }) => {
|
||||
test('admin creates a user who follows a fake company and generates a private summary without article/job writes', async ({ page, request }) => {
|
||||
const stack = readStackManifest()
|
||||
await page.context().route('**/*', async route => {
|
||||
const host = new URL(route.request().url()).hostname
|
||||
@ -60,17 +60,45 @@ test('admin creates a user who follows a fake index and generates a private summ
|
||||
await page.getByRole('button', { name: 'Déconnexion' }).click()
|
||||
})
|
||||
|
||||
await test.step('new user login and explicit fake OpenFIGI selection', async () => {
|
||||
let companySearchRequest
|
||||
let companyFollowRequest
|
||||
page.on('request', request => {
|
||||
const url = new URL(request.url())
|
||||
if (url.pathname === '/api/companies/search') companySearchRequest = url
|
||||
if (url.pathname === '/api/me/assets' && request.method() === 'POST') companyFollowRequest = request.postDataJSON()
|
||||
})
|
||||
|
||||
await test.step('new user searches by company name and follows the selected local catalog company', async () => {
|
||||
await login(page, baseURL, email, password)
|
||||
|
||||
// Seed a pre-existing legacy follow through the compatibility API so the
|
||||
// real Watchlist page can prove it remains present after a company follow.
|
||||
const token = await page.evaluate(() => localStorage.getItem('token'))
|
||||
const legacy = await request.post(new URL('/api/me/assets', stack.apiUrl).href, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
data: { symbol: 'LEGACYIDX', name: 'Historic index follow' },
|
||||
})
|
||||
expect(legacy.status()).toBe(201)
|
||||
|
||||
await page.goto(new URL('/assets', baseURL).href)
|
||||
const query = page.getByRole('textbox', { name: 'Nom ou symbole' })
|
||||
await query.fill(fixture.indexQuery)
|
||||
const oldFollows = page.getByRole('region', { name: /autres suivis existants/i })
|
||||
await expect(oldFollows).toContainText('Historic index follow')
|
||||
const query = page.getByRole('textbox', { name: "Nom de l'entreprise" })
|
||||
await query.fill(fixture.companyQuery)
|
||||
await page.getByRole('button', { name: 'Rechercher' }).click()
|
||||
const results = page.getByRole('region', { name: 'Résultats de recherche' })
|
||||
await expect(results.getByText(fixture.indexName)).toBeVisible()
|
||||
await expect(results.getByText(fixture.indexSymbol)).toBeVisible()
|
||||
await results.getByRole('button', { name: 'Suivre cet indice' }).click()
|
||||
await expect(page.getByRole('region', { name: 'Indices suivis' })).toContainText(fixture.indexSymbol)
|
||||
const results = page.getByRole('region', { name: 'Résultats des entreprises' })
|
||||
await expect(results.getByText(fixture.companyName)).toBeVisible()
|
||||
await expect(results).toContainText('E2E Country')
|
||||
for (const privateValue of [fixture.companySymbol, fixture.companyFIGI, fixture.companyID]) {
|
||||
await expect(results.getByText(privateValue, { exact: false })).toHaveCount(0)
|
||||
}
|
||||
await results.getByRole('button', { name: 'Suivre cette entreprise' }).click()
|
||||
await expect(page.getByRole('region', { name: 'Entreprises suivies' })).toContainText(fixture.companyName)
|
||||
await expect(oldFollows).toContainText('Historic index follow')
|
||||
await expect(companySearchRequest?.pathname).toBe('/api/companies/search')
|
||||
await expect(companySearchRequest?.searchParams.get('q')).toBe(fixture.companyQuery)
|
||||
await expect(companySearchRequest?.searchParams.get('limit')).toBe('20')
|
||||
expect(companyFollowRequest).toEqual({ company_id: fixture.companyID })
|
||||
})
|
||||
|
||||
await test.step('user saves language and ranking preferences', async () => {
|
||||
@ -105,7 +133,9 @@ test('admin creates a user who follows a fake index and generates a private summ
|
||||
const response = await request.get(new URL(stack.fakeAuditPath, stack.fakeControlUrl).href)
|
||||
expect(response.ok()).toBeTruthy()
|
||||
const events = await response.json()
|
||||
expect(events.openfigiSearches).toBeGreaterThan(0)
|
||||
expect(events.openfigiSearches).toBe(0)
|
||||
expect(events.companySearches).toBeGreaterThan(0)
|
||||
expect(events.companyResolutions).toBeGreaterThan(0)
|
||||
expect(events.scraperCalls).toBeGreaterThan(0)
|
||||
expect(events.layaRankingCalls).toBeGreaterThan(0)
|
||||
expect(events.layaSummaryCalls).toBeGreaterThan(0)
|
||||
|
||||
67
frontend/e2e/ticket19-company-watchlist.spec.mjs
Normal file
67
frontend/e2e/ticket19-company-watchlist.spec.mjs
Normal file
@ -0,0 +1,67 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { readStackManifest } from './stack-manifest.mjs'
|
||||
|
||||
async function login(page, baseURL, email, password) {
|
||||
await page.goto(new URL('/login', baseURL).href)
|
||||
await page.getByLabel('Adresse email').fill(email)
|
||||
await page.getByLabel('Mot de passe').fill(password)
|
||||
await page.getByRole('button', { name: 'Se connecter' }).click()
|
||||
await expect(page).toHaveURL(new URL('/', baseURL).href)
|
||||
}
|
||||
|
||||
test('ticket #19: search companies by name and follow by company_id while preserving legacy assets', 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 login(page, stack.frontendUrl, stack.bootstrapAdmin.email, stack.bootstrapAdmin.password)
|
||||
|
||||
const oldAsset = {
|
||||
id: 'historical-index-19', user_id: 'ticket19-admin', symbol: 'OLDX',
|
||||
name: 'Historic S&P index', figi: null, created_at: '2025-01-01T00:00:00.000Z',
|
||||
}
|
||||
const companies = [
|
||||
{ company_id: 'isin:CNE100001526', name: 'BYD Company Limited', exchange: 'Shenzhen Stock Exchange', country: 'China', mic: 'XSHE' },
|
||||
{ company_id: 'isin:HK0285041858', name: 'BYD Electronic (International) Company Limited', exchange: 'Hong Kong Stock Exchange', country: 'China', mic: 'XHKG' },
|
||||
]
|
||||
let followedBody
|
||||
let searchURL
|
||||
await page.route('**/api/me/assets', async route => {
|
||||
if (route.request().method() === 'GET') return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: [oldAsset] }) })
|
||||
if (route.request().method() === 'POST') {
|
||||
followedBody = route.request().postDataJSON()
|
||||
return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ data: { id: 'followed-byd', user_id: oldAsset.user_id, company_id: 'isin:CNE100001526', name: 'BYD Company Limited' } }) })
|
||||
}
|
||||
return route.continue()
|
||||
})
|
||||
await page.route('**/api/companies/search?**', async route => {
|
||||
searchURL = new URL(route.request().url())
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: companies }) })
|
||||
})
|
||||
|
||||
await page.goto(new URL('/assets', stack.frontendUrl).href)
|
||||
await expect(page.getByRole('heading', { name: 'Rechercher une entreprise' })).toBeVisible({ timeout: 3000 })
|
||||
const query = page.getByRole('textbox', { name: /nom de l'entreprise/i })
|
||||
await expect(page.getByRole('textbox')).toHaveCount(1)
|
||||
await query.fill('BYD')
|
||||
await page.getByRole('button', { name: /rechercher/i }).click()
|
||||
const results = page.getByRole('region', { name: /résultats des entreprises/i })
|
||||
const byd = results.getByText('BYD Company Limited').locator('..')
|
||||
await expect(byd).toContainText('Shenzhen Stock Exchange')
|
||||
await expect(byd).toContainText('China')
|
||||
await expect(results.getByText('BYD Electronic (International) Company Limited')).toBeVisible()
|
||||
for (const privateValue of ['002594.SZ', '0285.HK', 'BBG001QVK2K1', 'BBG000JPLTR7']) {
|
||||
await expect(results.getByText(privateValue, { exact: false })).toHaveCount(0)
|
||||
}
|
||||
await expect(page.getByRole('region', { name: /actifs historiques/i })).toContainText('Historic S&P index')
|
||||
|
||||
await byd.getByRole('button', { name: /suivre/i }).click()
|
||||
await expect.poll(() => followedBody).toEqual({ company_id: 'isin:CNE100001526' })
|
||||
expect(Object.keys(followedBody)).toEqual(['company_id'])
|
||||
await expect(page.getByRole('region', { name: /actifs historiques/i })).toContainText('Historic S&P index')
|
||||
expect(searchURL?.pathname).toBe('/api/companies/search')
|
||||
expect(searchURL?.searchParams.get('q')).toBe('BYD')
|
||||
expect(searchURL?.searchParams.get('limit')).toBe('20')
|
||||
})
|
||||
@ -1,12 +1,17 @@
|
||||
import { api } from './client'
|
||||
|
||||
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 interface Asset {
|
||||
id: string; user_id: string; symbol: string; name: string; figi: string | null; created_at: string
|
||||
company_id?: string | null; country?: string; exchange?: string
|
||||
}
|
||||
export interface CompanySearchResult {
|
||||
company_id: string; name: string; exchange: string; country: string; mic: string
|
||||
}
|
||||
export interface FollowAsset { company_id: string }
|
||||
|
||||
export const assetsApi = {
|
||||
list: () => api.get<Asset[]>('/me/assets'),
|
||||
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),
|
||||
search: (query: string, limit = 20) => api.get<CompanySearchResult[]>(`/companies/search?${new URLSearchParams({ q: query, limit: String(limit) })}`),
|
||||
add: (asset: FollowAsset) => api.post<Asset>('/me/assets', { company_id: asset.company_id }),
|
||||
remove: (id: string) => api.delete<void>(`/me/assets/${encodeURIComponent(id)}`),
|
||||
}
|
||||
|
||||
@ -5,7 +5,7 @@ import { cn } from '@/lib/cn'
|
||||
|
||||
const items = [
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Synthèses' },
|
||||
{ to: '/assets', icon: Star, label: 'Indices suivis' },
|
||||
{ to: '/assets', icon: Star, label: 'Entreprises suivies' },
|
||||
{ to: '/reports', icon: FileText, label: 'Rapports' },
|
||||
{ to: '/preferences', icon: Settings, label: 'Mes préférences' },
|
||||
]
|
||||
|
||||
@ -5,7 +5,7 @@ import { cn } from '@/lib/cn'
|
||||
|
||||
const navItems = [
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Synthèses' },
|
||||
{ to: '/assets', icon: Star, label: 'Indices suivis' },
|
||||
{ to: '/assets', icon: Star, label: 'Entreprises suivies' },
|
||||
{ to: '/preferences', icon: Settings, label: 'Mes préférences' },
|
||||
{ to: '/reports', icon: FileText, label: 'Rapports' },
|
||||
]
|
||||
|
||||
@ -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>
|
||||
}
|
||||
|
||||
@ -4,21 +4,22 @@ 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 () => {
|
||||
it('recherche explicitement avec q/limit, suit une entreprise et retire par ID', async () => {
|
||||
localStorage.setItem('token', 'reader-token')
|
||||
const index = { symbol: 'SPX', name: 'S&P 500', figi: 'BBG-INDEX' }
|
||||
const index = { company_id: 'isin:US0378331005' }
|
||||
const company = { ...index, name: 'Apple Inc.', exchange: 'Nasdaq', country: 'United States', mic: 'XNAS' }
|
||||
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: [company] })))
|
||||
.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])
|
||||
expect(await assetsApi.search('Apple Inc.', 20)).toEqual([company])
|
||||
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(1, '/api/companies/search?q=Apple+Inc.&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' }))
|
||||
})
|
||||
|
||||
20
frontend/tests/company-assets-api-ticket19.test.ts
Normal file
20
frontend/tests/company-assets-api-ticket19.test.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { assetsApi } from '../src/api/assets'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('uses the company search API and submits only company_id when following a company', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ data: [{ company_id: 'isin:CNE100001526', name: 'BYD Company Limited', exchange: 'Shenzhen Stock Exchange', country: 'China', mic: 'XSHE' }] }) })
|
||||
.mockResolvedValueOnce({ ok: true, status: 201, json: async () => ({ data: { id: 'asset-1', company_id: 'isin:CNE100001526' } }) })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
expect(await assetsApi.search('BYD', 20)).toEqual([{ company_id: 'isin:CNE100001526', name: 'BYD Company Limited', exchange: 'Shenzhen Stock Exchange', country: 'China', mic: 'XSHE' }])
|
||||
await assetsApi.add({ company_id: 'isin:CNE100001526' })
|
||||
|
||||
expect.soft(fetchMock.mock.calls[0][0]).toBe('/api/companies/search?q=BYD&limit=20')
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/me/assets', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ company_id: 'isin:CNE100001526' }),
|
||||
}))
|
||||
})
|
||||
155
frontend/tests/watchlist-company-search-ticket19.test.tsx
Normal file
155
frontend/tests/watchlist-company-search-ticket19.test.tsx
Normal file
@ -0,0 +1,155 @@
|
||||
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 type { CompanySearchResult } from '../src/api/assets'
|
||||
import { Watchlist } from '../src/pages/Watchlist'
|
||||
|
||||
const { listAssets, searchCompanies, addAsset, removeAsset } = vi.hoisted(() => ({
|
||||
listAssets: vi.fn(),
|
||||
searchCompanies: vi.fn(),
|
||||
addAsset: vi.fn(),
|
||||
removeAsset: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/assets', () => ({
|
||||
assetsApi: {
|
||||
list: listAssets,
|
||||
search: searchCompanies,
|
||||
searchCompanies,
|
||||
add: addAsset,
|
||||
remove: removeAsset,
|
||||
},
|
||||
}))
|
||||
|
||||
const historicalIndex = {
|
||||
id: 'historical-index-19', user_id: 'user-19', symbol: 'SSAAPL INDEX',
|
||||
name: 'Historic S&P index', figi: null, created_at: '2025-01-01T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const companyMatches = [
|
||||
{ company_id: 'isin:CNE100001526', name: 'BYD Company Limited', exchange: 'Shenzhen Stock Exchange', country: 'China', mic: 'XSHE' },
|
||||
{ company_id: 'isin:HK0285041858', name: 'BYD Electronic (International) Company Limited', exchange: 'Hong Kong Stock Exchange', country: 'China', mic: 'XHKG' },
|
||||
] satisfies CompanySearchResult[]
|
||||
|
||||
describe('Ticket #19 — company-first watchlist search', () => {
|
||||
afterEach(cleanup)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
listAssets.mockResolvedValue([historicalIndex])
|
||||
searchCompanies.mockResolvedValue(companyMatches)
|
||||
addAsset.mockResolvedValue({ id: 'asset-company-byd', user_id: 'user-19', company_id: 'isin:CNE100001526' })
|
||||
removeAsset.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('searches by company name, shows disambiguators without private tickers, and follows by company_id only while preserving history', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Watchlist />)
|
||||
|
||||
const history = await screen.findByRole('region', { name: /actifs historiques/i })
|
||||
expect(within(history).getByText('Historic S&P index')).toBeInTheDocument()
|
||||
|
||||
const query = await screen.findByRole('textbox', { name: /nom de l'entreprise/i })
|
||||
expect(screen.getAllByRole('textbox')).toHaveLength(1)
|
||||
await user.type(query, 'BYD')
|
||||
expect(searchCompanies).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByRole('button', { name: /rechercher/i }))
|
||||
await waitFor(() => expect(searchCompanies).toHaveBeenCalledWith('BYD', 20))
|
||||
|
||||
const results = await screen.findByRole('region', { name: /résultats des entreprises/i })
|
||||
const byd = within(results).getByText('BYD Company Limited').closest('li')
|
||||
expect(byd).not.toBeNull()
|
||||
expect(within(byd!).getByText('Shenzhen Stock Exchange')).toBeInTheDocument()
|
||||
expect(within(byd!).getByText('China')).toBeInTheDocument()
|
||||
expect(within(results).getByText('BYD Electronic (International) Company Limited')).toBeInTheDocument()
|
||||
for (const privateValue of ['002594.SZ', '0285.HK', 'BBG001QVK2K1', 'BBG000JPLTR7']) {
|
||||
expect(within(results).queryByText(privateValue)).not.toBeInTheDocument()
|
||||
}
|
||||
|
||||
await user.click(within(byd!).getByRole('button', { name: /suivre/i }))
|
||||
await waitFor(() => expect(addAsset).toHaveBeenCalledWith({ company_id: 'isin:CNE100001526' }))
|
||||
expect(addAsset).toHaveBeenCalledTimes(1)
|
||||
expect(history).toHaveTextContent('Historic S&P index')
|
||||
})
|
||||
it('présente le nom officiel, le pays et la place boursière sans identifiant technique, et protège tous les anciens suivis', async () => {
|
||||
listAssets.mockResolvedValueOnce([historicalIndex, { ...historicalIndex, id: 'index-with-figi', name: 'Existing index', figi: 'BBG-OLD' }])
|
||||
searchCompanies.mockResolvedValueOnce([{ ...companyMatches[0], symbol: '002594.SZ', figi: 'BBG001QVK2K1' }])
|
||||
const user = userEvent.setup()
|
||||
render(<Watchlist />)
|
||||
const history = await screen.findByRole('region', { name: /autres suivis existants/i })
|
||||
expect(within(history).getByText('Existing index')).toBeInTheDocument()
|
||||
expect(within(history).queryByRole('button')).not.toBeInTheDocument()
|
||||
await user.type(screen.getByLabelText("Nom de l'entreprise"), 'BYD{Enter}')
|
||||
const results = await screen.findByRole('region', { name: /résultats des entreprises/i })
|
||||
expect(await within(results).findByText('Shenzhen Stock Exchange')).toBeInTheDocument()
|
||||
expect(within(results).getByText('China')).toBeInTheDocument()
|
||||
expect(within(results).getByText('BYD Company Limited')).toHaveClass('font-semibold')
|
||||
for (const value of ['002594.SZ', 'BBG001QVK2K1', 'isin:CNE100001526', 'XSHE']) expect(within(results).queryByText(value)).not.toBeInTheDocument()
|
||||
expect(addAsset).not.toHaveBeenCalled()
|
||||
expect(removeAsset).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('follows and undoes an unfollow in English using only company_id', async () => {
|
||||
listAssets.mockResolvedValueOnce([{ id: 'byd-followed', company_id: companyMatches[0].company_id, name: companyMatches[0].name, symbol: '002594.SZ', figi: 'private-figi' }])
|
||||
const user = userEvent.setup()
|
||||
render(<Watchlist />)
|
||||
await user.selectOptions(screen.getByLabelText('Langue / Language'), 'en')
|
||||
await screen.findByText('BYD Company Limited')
|
||||
expect(screen.getByLabelText('Company name')).toBeInTheDocument()
|
||||
expect(screen.queryByText('002594.SZ')).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Unfollow BYD Company Limited' }))
|
||||
expect(await screen.findByText('Company unfollowed.')).toBeInTheDocument()
|
||||
expect(removeAsset).toHaveBeenCalledWith('byd-followed')
|
||||
await user.click(screen.getByRole('button', { name: 'Undo unfollow' }))
|
||||
expect(await screen.findByText('Unfollow undone.')).toBeInTheDocument()
|
||||
expect(addAsset).toHaveBeenCalledWith({ company_id: companyMatches[0].company_id })
|
||||
expect(screen.getByText('BYD Company Limited')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('garde le nom recherché après erreur et permet une reprise explicite', async () => {
|
||||
searchCompanies.mockRejectedValueOnce(new Error('offline'))
|
||||
const user = userEvent.setup()
|
||||
render(<Watchlist />)
|
||||
await user.type(screen.getByLabelText("Nom de l'entreprise"), 'BYD{Enter}')
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Impossible de rechercher des entreprises')
|
||||
expect(screen.getByLabelText("Nom de l'entreprise")).toHaveValue('BYD')
|
||||
expect(searchCompanies).toHaveBeenCalledTimes(1)
|
||||
await user.click(screen.getByRole('button', { name: 'Réessayer' }))
|
||||
expect(await screen.findByText('BYD Company Limited')).toBeInTheDocument()
|
||||
expect(searchCompanies).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('désambiguïse deux noms identiques avec pays et place sans afficher le MIC', async () => {
|
||||
searchCompanies.mockResolvedValueOnce([
|
||||
{ company_id: 'company-us', name: 'Example Company', country: 'United States', exchange: 'Nasdaq', mic: 'XNAS' },
|
||||
{ company_id: 'company-uk', name: 'Example Company', country: 'United Kingdom', exchange: 'London Stock Exchange', mic: 'XLON' },
|
||||
] satisfies CompanySearchResult[])
|
||||
const user = userEvent.setup()
|
||||
render(<Watchlist />)
|
||||
await user.type(screen.getByLabelText("Nom de l'entreprise"), 'Example{Enter}')
|
||||
const results = screen.getByRole('region', { name: /résultats des entreprises/i })
|
||||
const names = await within(results).findAllByText('Example Company')
|
||||
expect(names).toHaveLength(2)
|
||||
const us = names[0].closest('li')!
|
||||
const uk = names[1].closest('li')!
|
||||
expect(within(us).getByText('United States')).toBeInTheDocument()
|
||||
expect(within(us).getByText('Nasdaq')).toBeInTheDocument()
|
||||
expect(within(uk).getByText('United Kingdom')).toBeInTheDocument()
|
||||
expect(within(uk).getByText('London Stock Exchange')).toBeInTheDocument()
|
||||
expect(within(results).queryByText(/XNAS|XLON|company-us|company-uk/)).not.toBeInTheDocument()
|
||||
await user.click(within(uk).getByRole('button', { name: /suivre/i }))
|
||||
expect(addAsset).toHaveBeenCalledWith({ company_id: 'company-uk' })
|
||||
})
|
||||
|
||||
it('affiche uniquement le nom si pays et place ne sont pas renseignés', async () => {
|
||||
searchCompanies.mockResolvedValueOnce([{ company_id: 'company-unknown', name: 'Example Company', country: '', exchange: '', mic: 'XNAS' }] satisfies CompanySearchResult[])
|
||||
const user = userEvent.setup()
|
||||
render(<Watchlist />)
|
||||
await user.type(screen.getByLabelText("Nom de l'entreprise"), 'Example{Enter}')
|
||||
const name = await screen.findByText('Example Company')
|
||||
expect(name).toHaveClass('font-semibold')
|
||||
expect(screen.queryByText('XNAS')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('undefined')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
})
|
||||
@ -23,18 +23,18 @@ 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' }
|
||||
const indexOne = { company_id: 'company-a', name: 'Apple Inc.', country: 'United States', exchange: 'Nasdaq', mic: 'XNAS', symbol: 'SSAAPL INDEX' }
|
||||
const indexTwo = { company_id: 'company-b', name: 'Apple Holdings', country: 'United Kingdom', exchange: 'London Stock Exchange', mic: 'XLON', symbol: 'AAPL/B' }
|
||||
|
||||
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 })
|
||||
return screen.getByRole('region', { name: /résultats des entreprises/i })
|
||||
}
|
||||
|
||||
describe('Ticket #4 — rechercher et suivre des indices', () => {
|
||||
describe('Régressions Watchlist — recherche explicite et suivis d’entreprises', () => {
|
||||
afterEach(cleanup)
|
||||
|
||||
beforeEach(() => {
|
||||
@ -50,13 +50,13 @@ describe('Ticket #4 — rechercher et suivre des indices', () => {
|
||||
searchIndices.mockResolvedValueOnce([indexOne])
|
||||
render(<Watchlist />)
|
||||
|
||||
const query = await screen.findByRole('textbox', { name: 'Nom ou symbole' })
|
||||
const query = await screen.findByRole('textbox', { name: "Nom de l'entreprise" })
|
||||
expect(query).toHaveAttribute('maxLength', '100')
|
||||
await user.type(query, 'S&P 500')
|
||||
await user.type(query, 'Apple Inc.')
|
||||
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()
|
||||
await waitFor(() => expect(searchIndices).toHaveBeenCalledWith('Apple Inc.', 20))
|
||||
expect(await within(resultRegion()).findByText('Apple Inc.')).toBeInTheDocument()
|
||||
expect(within(resultRegion()).queryByText('BBG000SPX001')).not.toBeInTheDocument()
|
||||
|
||||
await user.clear(query)
|
||||
@ -65,27 +65,27 @@ describe('Ticket #4 — rechercher et suivre des indices', () => {
|
||||
expect(searchIndices).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('exige le choix explicite, transmet le FIGI, affiche les doublons ambigus et garde les actifs legacy', async () => {
|
||||
it('exige le choix explicite, transmet company_id et garde les suivis existants', 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).queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(within(history).getByText('Old historic asset')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Nom ou symbole')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText("Nom de l'entreprise")).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]
|
||||
const query = screen.getByRole('textbox', { name: "Nom de l'entreprise" })
|
||||
await user.type(query, 'Apple Inc.{Enter}')
|
||||
const results = await screen.findByRole('region', { name: /résultats des entreprises/i })
|
||||
expect(within(results).getByText('Nasdaq')).toBeInTheDocument()
|
||||
expect(within(results).getByText('London Stock Exchange')).toBeInTheDocument()
|
||||
expect(within(results).getByRole('button', { name: /déjà suivie/i })).toBeDisabled()
|
||||
const follow = within(results).getAllByRole('button', { name: /suivre cette entreprise/i })[0]
|
||||
await user.click(follow)
|
||||
await waitFor(() => expect(addAsset).toHaveBeenCalledWith({
|
||||
symbol: 'SPX', name: 'S&P 500 alternate listing', figi: 'BBG000SPX002',
|
||||
company_id: 'company-b',
|
||||
}))
|
||||
expect(addAsset).toHaveBeenCalledTimes(1)
|
||||
expect(within(history).getByText('Old historic asset')).toBeInTheDocument()
|
||||
@ -94,16 +94,16 @@ describe('Ticket #4 — rechercher et suivre des indices', () => {
|
||||
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' })
|
||||
const query = await screen.findByRole('textbox', { name: "Nom de l'entreprise" })
|
||||
|
||||
searchIndices.mockResolvedValueOnce([])
|
||||
await user.type(query, 'No match{Enter}')
|
||||
expect(await screen.findByText(/aucun indice trouvé/i)).toBeInTheDocument()
|
||||
expect(await screen.findByText(/aucune entreprise trouvée/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],
|
||||
[apiError(502, 'provider unavailable'), /service.*indisponible/i],
|
||||
] as const) {
|
||||
searchIndices.mockRejectedValueOnce(error)
|
||||
await user.clear(query)
|
||||
@ -122,16 +122,16 @@ describe('Ticket #4 — rechercher et suivre des indices', () => {
|
||||
.mockReturnValueOnce(new Promise(resolve => { resolveCurrent = resolve }))
|
||||
const user = userEvent.setup()
|
||||
render(<Watchlist />)
|
||||
const query = await screen.findByRole('textbox', { name: 'Nom ou symbole' })
|
||||
const query = await screen.findByRole('textbox', { name: "Nom de l'entreprise" })
|
||||
|
||||
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()
|
||||
resolveCurrent([{ company_id: 'current-company', name: 'Current company', exchange: '', country: '', mic: '' }])
|
||||
expect(await screen.findByText('Current company')).toBeInTheDocument()
|
||||
resolveOld([{ company_id: 'stale-company', name: 'Stale company', exchange: '', country: '', mic: '' }])
|
||||
await waitFor(() => expect(screen.queryByText('Stale company')).not.toBeInTheDocument())
|
||||
expect(screen.getByText('Current company')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('conserve les actifs après erreur de suivi ou retrait et permet le retrait par identifiant', async () => {
|
||||
@ -142,17 +142,17 @@ describe('Ticket #4 — rechercher et suivre des indices', () => {
|
||||
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 }))
|
||||
const query = await screen.findByRole('textbox', { name: "Nom de l'entreprise" })
|
||||
await user.type(query, 'Apple Inc.{Enter}')
|
||||
const results = await screen.findByRole('region', { name: /résultats des entreprises/i })
|
||||
await user.click(within(results).getByRole('button', { name: /suivre cette entreprise/i }))
|
||||
expect(await screen.findByRole('alert')).toBeInTheDocument()
|
||||
expect(query).toHaveValue('S&P 500')
|
||||
expect(query).toHaveValue('Apple Inc.')
|
||||
|
||||
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()
|
||||
expect(screen.getByText('Apple Inc.')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user