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

@ -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' }))
})

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

View 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()
})
})

View File

@ -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()
})
})