feat(search): find companies by stock symbol

Index exact symbols from selected primary listings, preserve canonical company identities, and add BABA as an explicit alias for Alibaba's primary identity. Update bilingual help and cover symbol collisions, aliases, and DTO stability.

Refs #25

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 18:31:46 +01:00
parent f7b057efa3
commit f97ae18d6c
10 changed files with 354 additions and 19 deletions

View File

@ -0,0 +1,54 @@
package api
import (
"encoding/json"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
)
func TestTicket25BABAAndAMZNKeepPrimaryCompanyDTO(t *testing.T) {
previous := gin.Mode()
gin.SetMode(gin.TestMode)
defer gin.SetMode(previous)
const secret = "local-ticket25-baba-secret"
h := handlers.New(nil, &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
router := SetupRouter(h, secret)
token, err := auth.GenerateToken("owner", "owner@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct{ query, id, name string }{{"BABA", "isin:KYG017191142", "Alibaba Group Holding Limited"}, {"amzn", "isin:US0231351067", "Amazon.com, Inc."}} {
t.Run(tc.query, func(t *testing.T) {
request := httptest.NewRequest("GET", "/api/companies/search?q="+tc.query+"&limit=1", nil)
request.Header.Set("Authorization", "Bearer "+token)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != 200 {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
var envelope struct {
Data []map[string]any `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
if len(envelope.Data) != 1 || envelope.Data[0]["company_id"] != tc.id || envelope.Data[0]["name"] != tc.name {
t.Fatalf("DTO=%+v", envelope.Data)
}
expected := []string{"company_id", "name", "exchange", "country", "mic"}
if len(envelope.Data[0]) != len(expected) {
t.Fatalf("DTO fields changed: %+v", envelope.Data[0])
}
for _, key := range expected {
if _, ok := envelope.Data[0][key]; !ok {
t.Fatalf("DTO missing %s", key)
}
}
})
}
}

View File

@ -6,7 +6,7 @@ Source officielle : <https://github.com/JerBouma/FinanceDatabase/tree/93b872f0e4
Le fichier est complet, mais ne représente pas 47 735 sociétés identifiables distinctes : 2 423 lignes n'ont ni ISIN ni FIGI et 2 184 identités ont plusieurs lignes déjà classées primaires par l'amont. Le port expose **43 126 identités** (`isin:` en priorité, sinon `figi:`). Pour une identité répétée, il retient le meilleur `listing_score` amont ; une égalité entre primaires est départagée par symbole dans un ordre stable, uniquement pour choisir un représentant déterministe. Les lignes sans identité restent dans le snapshot mais sont exclues de la recherche et de la résolution. Aucune identité artificielle n'est inventée. Les valeurs exactes NVDA, AAPL, 9888.HK, 002594.SZ et 0285.HK sont vérifiées, avec BYD Company et BYD Electronic distincts.
Le manifeste précise provenance, champs, décompte, SHA-256 du parquet amont et du CSV, empreintes des sources Python utilisées et politique de résolution. Le chargement embarqué vérifie son empreinte avant utilisation. La recherche locale classe les alias exacts en premier, les noms légaux exacts ensuite, puis les préfixes de mots du nom légal. Les alias ne sont jamais recherchés par sous-chaîne ou préfixe. La déduplication par `company_id` précède la limite (maximum 20), et les collisions d’alias retournent tous les candidats dans cette limite, sans choix arbitraire d’identité. À rang égal, le tri utilise le nom légal normalisé puis `company_id`. Aucun appel fournisseur n’est nécessaire. Le DTO de recherche ne projette que `company_id`, `name`, `exchange`, `country`, `mic`.
Le manifeste précise provenance, champs, décompte, SHA-256 du parquet amont et du CSV, empreintes des sources Python utilisées et politique de résolution. Le chargement embarqué vérifie son empreinte avant utilisation. La recherche locale classe les symboles exacts du catalogue en premier, puis les alias exacts, les noms légaux exacts et les préfixes de mots du nom légal. Les alias ne sont jamais recherchés par sous-chaîne ou préfixe. La déduplication par `company_id` précède la limite (maximum 20), et les collisions d’alias retournent tous les candidats dans cette limite, sans choix arbitraire d’identité. À rang égal, le tri utilise le nom légal normalisé puis `company_id`. Aucun appel fournisseur n’est nécessaire. Le DTO de recherche ne projette que `company_id`, `name`, `exchange`, `country`, `mic`.
## Reproduire ou mettre à jour explicitement
@ -39,3 +39,24 @@ Les deux associations initiales sont vérifiées dans le CSV réel : IBM → `is
La normalisation commune aux requêtes, alias et noms légaux applique la casse minuscule, la décomposition Unicode NFKD, le retrait des accents combinants et la réduction des espaces. Les points d’abréviation et apostrophes sont retirés (`I.B.M.` → `ibm`), les autres ponctuations séparent les mots (`Intel-Corporation` → `intel corporation`). Les symboles mathématiques/monétaires restent littéraux : `ES=F` ne doit pas devenir une requête générique « es f ». La chaîne originale d’affichage est conservée. Un préfixe légal commence à une frontière de mot ; il ne cherche pas à l’intérieur d’un mot et ne réordonne pas les mots.
Pour maintenir les alias, modifier uniquement l’overlay et ses tests après vérification des identités locales. Après mise à jour du snapshot, valider toutes les références d’alias avant livraison. Les chargements de petits CSV de test via `NewFinanceDatabaseCatalogFromSnapshot` n’appliquent pas automatiquement l’overlay de production : ils ne contiennent pas nécessairement ses identités cibles.
## Symboles exacts locaux — ticket 25
Les symboles internes deviennent aussi des clés de recherche exactes, sans être ajoutés au DTO. Leur normalisation est séparée de celle des noms/alias : retrait des espaces extérieurs et casse majuscule uniquement. Les ponctuations, accents, espaces intérieurs et suffixes sont conservés (`BRK-B` est distinct de `BRK.B`/`BRKB`, `9888.HK` de `9888`). Aucune recherche par préfixe de symbole, traduction de format ou inférence de place n'est effectuée. Les alias #24 gardent leur normalisation et leur comportement.
L'index couvre tous les symboles des lignes primaires identifiables du snapshot, y compris les différentes lignes primaires partageant un `company_id`. Une recherche renvoie toujours la société canonique déjà résolue et ne remplace pas son ticker Yahoo interne. Si un symbole appartient à plusieurs IDs, tous restent candidats, triés par nom légal normalisé puis ID. La déduplication par ID intervient avant la limite et conserve le meilleur rang : symbole exact, alias exact, nom légal exact, préfixe légal. Aucun ID ni affichage n'est modifié.
Exemples vérifiés localement : `AMZN` → Amazon.com, Inc. (`isin:US0231351067`), `INTC` → Intel Corporation, `9888.HK` → Baidu et `9988.HK` → Alibaba Group Holding Limited (`isin:KYG017191142`). La ligne `BABA` reste absente du snapshot primaire embarqué ; un alias explicite, approuvé par Architect, résout cette saisie vers l’identité primaire Alibaba, sans admettre le listing non primaire. Aucun enrichissement réseau n'est effectué.
### Alias BABA approuvé : provenance et respect de `primary_only`
L’overlay `data/aliases.v1.json` ajoute explicitement `BABA` → `isin:KYG017191142`. La justification provient de `compression/equities.parquet` au commit FinanceDatabase `93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1`, SHA-256 `decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f`, vérifié localement avec les empreintes des sources. Le nom commun est **Alibaba Group Holding Limited** ; le rattachement utilise l’ISIN identique, sans inférence par nom.
| Ligne amont | ISIN | FIGI | Place / devise | Radiée | Primaire amont |
| --- | --- | --- | --- | --- | --- |
| BABA | KYG017191142 | BBG006G2JVQ7 | NYQ / XNYS / USD | Non | Non |
| 9988.HK | KYG017191142 | BBG00QV37ZP9 | HKG / XHKG / HKD | Non | Oui |
La décision Architect autorise uniquement cet alias versionné : aucun index générique des listings secondaires n’est ajouté. Le filtre Equities/primaire/non-radié, le CSV et son manifeste restent inchangés. `BABA` n’entre pas dans l’index des symboles primaires. La recherche par alias renvoie le `company_id` primaire et la résolution serveur conserve `9988.HK`/`BBG00QV37ZP9`, jamais les champs du listing BABA. Les autres symboles secondaires (BABAF, BABAN.MX, BABA.BA) ne sont pas admis implicitement. `amzn` conserve sa résolution par symbole exact vers Amazon. Les tests catalogue et HTTP vérifient la priorité, les champs canoniques et le DTO existant, sans accès réseau.

View File

@ -0,0 +1,70 @@
package companycatalog
import (
"bytes"
"encoding/csv"
"testing"
)
func TestTicket25BABAExplicitAliasResolvesPrimaryAlibaba(t *testing.T) {
catalog, err := Default()
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct{ query, id, name, symbol, figi string }{
{"BABA", "isin:KYG017191142", "Alibaba Group Holding Limited", "9988.HK", "BBG00QV37ZP9"},
{" baba ", "isin:KYG017191142", "Alibaba Group Holding Limited", "9988.HK", "BBG00QV37ZP9"},
{"amzn", "isin:US0231351067", "Amazon.com, Inc.", "AMZN", "BBG000BVQ4Z3"},
} {
t.Run(tc.query, func(t *testing.T) {
got, err := catalog.SearchCompanies(tc.query, 1)
if err != nil || len(got) != 1 || got[0].CompanyID != tc.id || got[0].Name != tc.name || got[0].YahooSymbol != tc.symbol || got[0].FIGI != tc.figi {
t.Fatalf("query=%q result=%+v err=%v", tc.query, got, err)
}
resolved, err := catalog.ResolveCompany(got[0].CompanyID)
if err != nil || resolved != got[0] {
t.Fatalf("resolution differs: %+v %v", resolved, err)
}
})
}
}
func TestTicket25BABAOverlayDoesNotAdmitNonPrimaryRowsOrSecondarySymbols(t *testing.T) {
catalog, err := Default()
if err != nil {
t.Fatal(err)
}
if len(catalog.symbolIDs["BABA"]) != 0 {
t.Fatal("BABA was admitted to the primary symbol index")
}
if len(catalog.companies) != 43126 {
t.Fatal("company identities changed")
}
rows, err := csv.NewReader(bytes.NewReader(embeddedSnapshot)).ReadAll()
if err != nil {
t.Fatal(err)
}
columns := map[string]int{}
for i, key := range rows[0] {
columns[key] = i
}
if len(rows)-1 != 47735 {
t.Fatal("snapshot size changed")
}
for _, row := range rows[1:] {
if row[columns["symbol"]] == "BABA" || row[columns["primary_listing"]] != "true" || row[columns["delisted"]] != "false" {
t.Fatalf("non-primary/delisted row admitted: %s", row[columns["symbol"]])
}
}
for _, query := range []string{"BABAF", "BABAN.MX", "BABA.BA"} {
got, err := catalog.SearchCompanies(query, 20)
if err != nil {
t.Fatal(err)
}
for _, company := range got {
if company.CompanyID == "isin:KYG017191142" {
t.Fatalf("unapproved secondary symbol %q admitted", query)
}
}
}
}

View File

@ -28,6 +28,7 @@ type CompanyCatalog interface {
var ErrUnknownCompany = errors.New("unknown company")
type Catalog struct {
symbolIDs map[string][]string
aliases map[string]map[string]bool
companies []Company
byID map[string]Company
@ -94,7 +95,7 @@ func readCatalog(input io.Reader) (*Catalog, error) {
return nil, errors.New("invalid company snapshot columns")
}
}
c := &Catalog{byID: map[string]Company{}}
c := &Catalog{byID: map[string]Company{}, symbolIDs: map[string][]string{}}
scores := map[string]float64{}
for {
row, err := r.Read()
@ -126,6 +127,10 @@ func readCatalog(input io.Reader) (*Catalog, error) {
return nil, errors.New("invalid listing score")
}
}
// Index every locally selected primary symbol, before grouping identities.
// Search still returns the existing canonical Company and Yahoo listing.
key := normalizeExactSymbol(company.YahooSymbol)
c.symbolIDs[key] = append(c.symbolIDs[key], company.CompanyID)
if old, exists := c.byID[company.CompanyID]; exists {
// The upstream primary selector can keep multiple equally primary venues
// for one ISIN. Prefer its score, then a stable representative among those

View File

@ -3,11 +3,21 @@
"aliases": [
{
"alias": "IBM",
"company_ids": ["isin:US4592001014"]
"company_ids": [
"isin:US4592001014"
]
},
{
"alias": "Intel",
"company_ids": ["isin:US4581401001"]
"company_ids": [
"isin:US4581401001"
]
},
{
"alias": "BABA",
"company_ids": [
"isin:KYG017191142"
]
}
]
}

View File

@ -63,6 +63,10 @@ func (c *Catalog) loadAliases(data []byte) error {
return nil
}
// Symbol lookup has its own exact normalization: punctuation, accents,
// internal whitespace and exchange suffixes are never folded or inferred.
func normalizeExactSymbol(value string) string { return strings.ToUpper(strings.TrimSpace(value)) }
func legalWordPrefix(name, query string) bool {
return strings.HasPrefix(name, query) || strings.Contains(name, " "+query)
}
@ -71,10 +75,8 @@ func (c *Catalog) SearchCompanies(query string, limit int) ([]Company, error) {
if strings.TrimSpace(query) == "" || limit < 1 || limit > 20 {
return nil, errors.New("invalid company search")
}
symbol := normalizeExactSymbol(query)
query = normalizeName(query)
if query == "" {
return []Company{}, nil
}
type match struct {
company Company
tier int
@ -88,17 +90,28 @@ func (c *Catalog) SearchCompanies(query string, limit int) ([]Company, error) {
matches[company.CompanyID] = match{company, tier, normalized}
}
}
for id := range c.aliases[query] {
for _, id := range c.symbolIDs[symbol] {
add(c.byID[id], 0)
}
for _, company := range c.companies {
name := normalizeName(company.Name)
if name == query {
add(company, 1)
} else if legalWordPrefix(name, query) {
add(company, 2)
if normalizeExactSymbol(company.YahooSymbol) == symbol {
add(company, 0)
}
}
if query != "" {
for id := range c.aliases[query] {
add(c.byID[id], 1)
}
for _, company := range c.companies {
name := normalizeName(company.Name)
if name == query {
add(company, 2)
} else if legalWordPrefix(name, query) {
add(company, 3)
}
}
}
ranked := make([]match, 0, len(matches))
for _, candidate := range matches {
ranked = append(ranked, candidate)

View File

@ -0,0 +1,118 @@
package companycatalog
import (
"reflect"
"strings"
"testing"
)
func TestTicket25RealCatalogExactSymbols(t *testing.T) {
catalog, err := Default()
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct{ query, id, name string }{
{" amzn ", "isin:US0231351067", "Amazon.com, Inc."},
{"INTC", "isin:US4581401001", "Intel Corporation"},
{"9888.hk", "isin:KYG070341048", "Baidu, Inc."},
{"BRK-B", "isin:US0846707026", "Berkshire Hathaway Inc."},
{"9988.HK", "isin:KYG017191142", "Alibaba Group Holding Limited"},
} {
t.Run(tc.query, func(t *testing.T) {
canonical, err := catalog.ResolveCompany(tc.id)
if err != nil || canonical.Name != tc.name {
t.Fatalf("real snapshot identity=%+v err=%v", canonical, err)
}
got, err := catalog.SearchCompanies(tc.query, 1)
if err != nil || len(got) != 1 || got[0].CompanyID != tc.id || got[0].Name != tc.name {
t.Fatalf("query=%q got=%+v err=%v", tc.query, got, err)
}
})
}
}
func TestTicket25SymbolExactnessPreservesPunctuationSuffixAndInnerSpaces(t *testing.T) {
c := &Catalog{companies: []Company{{CompanyID: "isin:brk", Name: "Berkshire Hathaway", YahooSymbol: "BRK-B"}, {CompanyID: "isin:baidu", Name: "Baidu", YahooSymbol: "9888.HK"}, {CompanyID: "isin:accent", Name: "Other Company", YahooSymbol: "ECO"}}}
for _, query := range []string{"brkb", "BRK B", "BRK.B", "BRK- B", "BRK", "9888", "9888-HK", "9888 HK", "9888.HK.EXTRA", "ÉCO", "E.C.O."} {
got, err := c.SearchCompanies(query, 20)
if err != nil || len(got) != 0 {
t.Fatalf("non-exact symbol %q matched %+v err=%v", query, got, err)
}
}
for _, query := range []string{"BRK-B", " \tbrk-b\n"} {
got, err := c.SearchCompanies(query, 20)
if err != nil || len(got) != 1 || got[0].CompanyID != "isin:brk" {
t.Fatalf("trim/case exact %q got=%+v err=%v", query, got, err)
}
}
}
func TestTicket25SymbolCollisionsPrecedeAliasesAndNamesAndDeduplicateBeforeLimit(t *testing.T) {
companies := []Company{
{CompanyID: "isin:s-z", Name: "Zed Company", YahooSymbol: "DUP.X"},
{CompanyID: "isin:s-a", Name: "Alpha Company", YahooSymbol: "dup.x"},
{CompanyID: "isin:alias", Name: "Alias Company", YahooSymbol: "OTHER"},
{CompanyID: "isin:legal", Name: "DUP.X", YahooSymbol: "LEGAL"},
{CompanyID: "isin:prefix", Name: "DUP.X Services", YahooSymbol: "PREFIX"},
}
c := &Catalog{byID: map[string]Company{}}
for _, company := range companies {
c.companies = append(c.companies, company, company)
c.byID[company.CompanyID] = company
}
if err := c.loadAliases([]byte(`{"version":1,"aliases":[{"alias":"DUP.X","company_ids":["isin:alias","isin:s-a","isin:s-a"]}]}`)); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
limit int
want []string
}{
{1, []string{"isin:s-a"}}, {2, []string{"isin:s-a", "isin:s-z"}}, {3, []string{"isin:s-a", "isin:s-z", "isin:alias"}},
{20, []string{"isin:s-a", "isin:s-z", "isin:alias", "isin:legal", "isin:prefix"}},
} {
for run := 0; run < 3; run++ {
got, err := c.SearchCompanies(" DuP.X ", tc.limit)
if err != nil {
t.Fatal(err)
}
ids := []string{}
for _, company := range got {
ids = append(ids, company.CompanyID)
}
if !reflect.DeepEqual(ids, tc.want) {
t.Fatalf("limit=%d ids=%v want=%v", tc.limit, ids, tc.want)
}
}
}
}
func TestTicket25AllPrimarySymbolsRemainSearchableWithoutChangingCanonicalListing(t *testing.T) {
data := "symbol,name,exchange,mic,country,isin,figi,delisted,primary_listing,listing_score\n" +
"ONE.A,Legal Company,Venue A,XAAA,Country,US1234567890,BBG000AAAAAA,false,true,4\n" +
"TWO.B,Legal Company,Venue B,XBBB,Country,US1234567890,BBG000BBBBBB,false,true,3\n"
catalog, err := readCatalog(strings.NewReader(data))
if err != nil {
t.Fatal(err)
}
got, err := catalog.SearchCompanies("TWO.B", 20)
if err != nil || len(got) != 1 || got[0].CompanyID != "isin:US1234567890" || got[0].YahooSymbol != "ONE.A" {
t.Fatalf("symbol lookup changed canonical company: %+v %v", got, err)
}
}
func TestTicket25DoesNotInventMissingSymbolOrBroadenItToPrefix(t *testing.T) {
catalog, err := Default()
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct{ query, excluded string }{{"BABAF", "isin:KYG017191142"}, {"AMZ", "isin:US0231351067"}, {"9888", "isin:KYG070341048"}} {
got, err := catalog.SearchCompanies(tc.query, 20)
if err != nil {
t.Fatal(err)
}
for _, company := range got {
if company.CompanyID == tc.excluded {
t.Fatalf("invented symbol/prefix %q for %s", tc.query, tc.excluded)
}
}
}
}

View File

@ -10,9 +10,9 @@ 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.',
help: 'Saisissez le nom, le sigle courant ou le symbole boursier d’une entreprise, par exemple Intel, IBM, AMZN ou BABA. 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.',
searching: 'Recherche en cours…', empty: 'Aucune entreprise trouvée. Essayez un autre nom, sigle courant ou symbole boursier.',
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',
@ -28,8 +28,8 @@ const copy = {
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.',
help: 'Enter a company name, commonly used acronym or stock symbol, such as Intel, IBM, AMZN or BABA. 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, commonly used acronym or stock symbol.',
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',

View File

@ -13,8 +13,8 @@ beforeEach(() => {
})
it.each([
{ language: 'fr', label: 'Nom ou nom courant de l’entreprise', help: /Intel.*IBM/, results: 'Résultats des entreprises', query: 'Intel', empty: 'Aucune entreprise trouvée. Essayez un autre nom ou nom courant, par exemple Intel ou IBM.' },
{ language: 'en', label: 'Company name or commonly used name', help: /Intel.*IBM/, results: 'Company results', query: 'IBM', empty: 'No company found. Try another name or commonly used name, such as Intel or IBM.' },
{ language: 'fr', label: 'Nom ou nom courant de l’entreprise', help: /Intel.*IBM/, results: 'Résultats des entreprises', query: 'Intel', empty: 'Aucune entreprise trouvée. Essayez un autre nom, sigle courant ou symbole boursier.' },
{ language: 'en', label: 'Company name or commonly used name', help: /Intel.*IBM/, results: 'Company results', query: 'IBM', empty: 'No company found. Try another name, commonly used acronym or stock symbol.' },
] as const)('affiche les textes accessibles $language et garde la recherche explicite au clavier', async ({ language, label, help, results, query, empty }) => {
const user = userEvent.setup()
render(<Watchlist />)

View File

@ -0,0 +1,44 @@
import { cleanup, render, screen, within, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { Watchlist } from '../src/pages/Watchlist'
const { list, search, add } = vi.hoisted(() => ({ list: vi.fn(), search: vi.fn(), add: vi.fn() }))
vi.mock('@/api/assets', () => ({ assetsApi: { list, search, add, remove: vi.fn() } }))
afterEach(cleanup)
beforeEach(() => { vi.clearAllMocks(); list.mockResolvedValue([]) })
it.each([
{ language: 'fr', symbol: 'AMZN', name: 'Amazon.com, Inc.' },
{ language: 'fr', symbol: 'BABA', name: 'Alibaba Group Holding Limited' },
{ language: 'en', symbol: 'AMZN', name: 'Amazon.com, Inc.' },
{ language: 'en', symbol: 'BABA', name: 'Alibaba Group Holding Limited' },
] as const)('$language explique la recherche par symbole $symbol sans le rendre dans les résultats', async ({ language, symbol, name }) => {
const company = { company_id: `company-${symbol}`, name, country: 'United States', exchange: 'Nasdaq', mic: 'XNAS', symbol }
search.mockResolvedValueOnce([company]).mockResolvedValueOnce([])
add.mockResolvedValueOnce({ id: 'followed-company', ...company })
const user = userEvent.setup()
render(<Watchlist />)
if (language === 'en') await user.selectOptions(screen.getByLabelText('Langue / Language'), 'en')
const input = screen.getByRole('textbox')
expect(input).toHaveAccessibleDescription(language === 'fr' ? /nom,.*sigle courant.*symbole boursier/ : /name,.*commonly used acronym.*stock symbol/)
await user.type(input, symbol)
expect(search).not.toHaveBeenCalled()
await user.keyboard('{Enter}')
await waitFor(() => expect(search).toHaveBeenCalledWith(symbol, 20))
const results = screen.getByRole('region', { name: language === 'fr' ? 'Résultats des entreprises' : 'Company results' })
expect(await within(results).findByText(name)).toBeInTheDocument()
for (const hidden of [symbol, company.company_id, company.mic]) expect(within(results).queryByText(hidden, { exact: true })).not.toBeInTheDocument()
expect(add).not.toHaveBeenCalled()
await user.click(within(results).getByRole('button', { name: language === 'fr' ? 'Suivre cette entreprise' : 'Follow this company' }))
await waitFor(() => expect(add).toHaveBeenCalledWith({ company_id: company.company_id }))
const followed = screen.getByRole('region', { name: language === 'fr' ? 'Entreprises suivies' : 'Followed companies' })
expect(within(followed).getByText(name)).toBeInTheDocument()
expect(within(followed).queryByText(symbol, { exact: true })).not.toBeInTheDocument()
expect(within(followed).queryByText(company.mic)).not.toBeInTheDocument()
await user.clear(input)
await user.type(input, 'Unknown{Enter}')
expect(await screen.findByText(language === 'fr'
? 'Aucune entreprise trouvée. Essayez un autre nom, sigle courant ou symbole boursier.'
: 'No company found. Try another name, commonly used acronym or stock symbol.')).toHaveAttribute('role', 'status')
})