diff --git a/backend/internal/api/company_baba_ticket25_test.go b/backend/internal/api/company_baba_ticket25_test.go new file mode 100644 index 0000000..c18e82b --- /dev/null +++ b/backend/internal/api/company_baba_ticket25_test.go @@ -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) + } + } + }) + } +} diff --git a/backend/internal/companycatalog/README.md b/backend/internal/companycatalog/README.md index 08f29ad..2eb2548 100644 --- a/backend/internal/companycatalog/README.md +++ b/backend/internal/companycatalog/README.md @@ -6,7 +6,7 @@ Source officielle : 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) diff --git a/backend/internal/companycatalog/symbols_ticket25_test.go b/backend/internal/companycatalog/symbols_ticket25_test.go new file mode 100644 index 0000000..4e0cb66 --- /dev/null +++ b/backend/internal/companycatalog/symbols_ticket25_test.go @@ -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) + } + } + } +} diff --git a/frontend/src/pages/Watchlist.tsx b/frontend/src/pages/Watchlist.tsx index 0ed5c7d..46586c8 100644 --- a/frontend/src/pages/Watchlist.tsx +++ b/frontend/src/pages/Watchlist.tsx @@ -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', diff --git a/frontend/tests/watchlist-alias-copy-ticket24.test.tsx b/frontend/tests/watchlist-alias-copy-ticket24.test.tsx index 2db3df8..e5c4ebb 100644 --- a/frontend/tests/watchlist-alias-copy-ticket24.test.tsx +++ b/frontend/tests/watchlist-alias-copy-ticket24.test.tsx @@ -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() diff --git a/frontend/tests/watchlist-symbol-copy-ticket25.test.tsx b/frontend/tests/watchlist-symbol-copy-ticket25.test.tsx new file mode 100644 index 0000000..e83bc5b --- /dev/null +++ b/frontend/tests/watchlist-symbol-copy-ticket25.test.tsx @@ -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() + 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') +})