From f7b057efa3036b54a57a6a6d5684211f7bd7e0c4 Mon Sep 17 00:00:00 2001 From: Blomios Date: Sun, 22 Nov 2026 18:08:35 +0100 Subject: [PATCH] feat(search): add exact company aliases Embed a versioned local alias overlay and rank exact aliases before legal-name matches and word prefixes. Normalize Unicode consistently, deduplicate by company identity before limiting, and update bilingual search guidance and tests. Refs #24 Co-Authored-By: Claude Opus 4.8 --- backend/go.mod | 2 +- .../api/company_alias_ticket24_test.go | 47 ++++++ backend/internal/companycatalog/README.md | 13 +- .../companycatalog/aliases_ticket24_test.go | 146 ++++++++++++++++++ backend/internal/companycatalog/catalog.go | 30 ++-- .../companycatalog/data/aliases.v1.json | 13 ++ backend/internal/companycatalog/search.go | 124 +++++++++++++++ frontend/e2e/ticket12-happy-path.spec.mjs | 2 +- .../e2e/ticket19-company-watchlist.spec.mjs | 2 +- frontend/src/pages/Watchlist.tsx | 12 +- .../watchlist-alias-copy-ticket24.test.tsx | 39 +++++ ...watchlist-company-search-ticket19.test.tsx | 14 +- .../watchlist-index-search-ticket4.test.tsx | 12 +- 13 files changed, 413 insertions(+), 43 deletions(-) create mode 100644 backend/internal/api/company_alias_ticket24_test.go create mode 100644 backend/internal/companycatalog/aliases_ticket24_test.go create mode 100644 backend/internal/companycatalog/data/aliases.v1.json create mode 100644 backend/internal/companycatalog/search.go create mode 100644 frontend/tests/watchlist-alias-copy-ticket24.test.tsx diff --git a/backend/go.mod b/backend/go.mod index e5c541a..8b9e253 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -11,6 +11,7 @@ require ( github.com/robfig/cron/v3 v3.0.1 github.com/sashabaranov/go-openai v1.36.1 golang.org/x/crypto v0.32.0 + golang.org/x/text v0.21.0 ) require ( @@ -49,7 +50,6 @@ require ( golang.org/x/arch v0.8.0 // indirect golang.org/x/net v0.34.0 // indirect golang.org/x/sys v0.29.0 // indirect - golang.org/x/text v0.21.0 // indirect google.golang.org/protobuf v1.36.3 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/backend/internal/api/company_alias_ticket24_test.go b/backend/internal/api/company_alias_ticket24_test.go new file mode 100644 index 0000000..c05ba02 --- /dev/null +++ b/backend/internal/api/company_alias_ticket24_test.go @@ -0,0 +1,47 @@ +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 TestTicket24CompanyAliasKeepsCanonicalDTOAndIdentity(t *testing.T) { + old := gin.Mode() + gin.SetMode(gin.TestMode) + defer gin.SetMode(old) + const secret = "local-ticket24-secret" + handler := handlers.New(nil, &config.Config{JWTSecret: secret}, nil, nil, nil, nil) + router := SetupRouter(handler, secret) + token, err := auth.GenerateToken("owner", "owner@example.test", "user", secret) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest("GET", "/api/companies/search?q=IBM&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]["name"] != "International Business Machines Corporation" || envelope.Data[0]["company_id"] != "isin:US4592001014" { + t.Fatalf("unexpected alias DTO %+v", envelope.Data) + } + allowed := map[string]bool{"company_id": true, "name": true, "exchange": true, "country": true, "mic": true} + for key := range envelope.Data[0] { + if !allowed[key] { + t.Fatalf("DTO expanded with %q", key) + } + } +} diff --git a/backend/internal/companycatalog/README.md b/backend/internal/companycatalog/README.md index 3c4c09a..08f29ad 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") - } - out := make([]Company, 0, limit) - for _, company := range c.companies { - if strings.Contains(normalizeName(company.Name), query) { - out = append(out, company) - if len(out) == limit { - break - } - } - } - return out, nil -} func (c *Catalog) ResolveCompany(id string) (Company, error) { if company, ok := c.byID[id]; ok { return company, nil diff --git a/backend/internal/companycatalog/data/aliases.v1.json b/backend/internal/companycatalog/data/aliases.v1.json new file mode 100644 index 0000000..c94bf23 --- /dev/null +++ b/backend/internal/companycatalog/data/aliases.v1.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "aliases": [ + { + "alias": "IBM", + "company_ids": ["isin:US4592001014"] + }, + { + "alias": "Intel", + "company_ids": ["isin:US4581401001"] + } + ] +} diff --git a/backend/internal/companycatalog/search.go b/backend/internal/companycatalog/search.go new file mode 100644 index 0000000..20ce266 --- /dev/null +++ b/backend/internal/companycatalog/search.go @@ -0,0 +1,124 @@ +package companycatalog + +import ( + "encoding/json" + "errors" + "sort" + "strings" + "unicode" + + "golang.org/x/text/unicode/norm" +) + +// Normalization is shared by aliases, legal names and queries. Periods in +// initials and apostrophes are ignored; other punctuation separates words. +// Diacritics fold away; original display names and opaque IDs never change. +func normalizeName(value string) string { + var out strings.Builder + for _, r := range norm.NFKD.String(strings.ToLower(value)) { + switch { + case unicode.Is(unicode.Mn, r): + continue + case unicode.IsLetter(r) || unicode.IsNumber(r) || unicode.IsSymbol(r): + out.WriteRune(r) + case r == '.' || r == '\'' || r == '’': + continue + default: + out.WriteByte(' ') + } + } + return strings.Join(strings.Fields(out.String()), " ") +} + +// loadAliases validates the whole overlay before publishing it. Alias targets +// must resolve in this snapshot; stale IDs never cause partial alias updates. +func (c *Catalog) loadAliases(data []byte) error { + var file struct { + Version int `json:"version"` + Aliases []struct { + Alias string `json:"alias"` + CompanyIDs []string `json:"company_ids"` + } `json:"aliases"` + } + if json.Unmarshal(data, &file) != nil || file.Version != 1 { + return errors.New("invalid company alias file") + } + aliases := map[string]map[string]bool{} + for _, entry := range file.Aliases { + key := normalizeName(entry.Alias) + if key == "" || len(entry.CompanyIDs) == 0 { + return errors.New("invalid company alias entry") + } + if aliases[key] == nil { + aliases[key] = map[string]bool{} + } + for _, id := range entry.CompanyIDs { + if _, ok := c.byID[id]; !ok { + return errors.New("unresolved company alias target") + } + aliases[key][id] = true + } + } + c.aliases = aliases + return nil +} + +func legalWordPrefix(name, query string) bool { + return strings.HasPrefix(name, query) || strings.Contains(name, " "+query) +} + +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") + } + query = normalizeName(query) + if query == "" { + return []Company{}, nil + } + type match struct { + company Company + tier int + name string + } + matches := map[string]match{} + add := func(company Company, tier int) { + normalized := normalizeName(company.Name) + old, exists := matches[company.CompanyID] + if !exists || tier < old.tier || (tier == old.tier && normalized < old.name) { + matches[company.CompanyID] = match{company, tier, normalized} + } + } + for id := range c.aliases[query] { + 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) + } + } + ranked := make([]match, 0, len(matches)) + for _, candidate := range matches { + ranked = append(ranked, candidate) + } + sort.Slice(ranked, func(i, j int) bool { + a, b := ranked[i], ranked[j] + if a.tier != b.tier { + return a.tier < b.tier + } + if a.name != b.name { + return a.name < b.name + } + return a.company.CompanyID < b.company.CompanyID + }) + if len(ranked) > limit { + ranked = ranked[:limit] + } + out := make([]Company, 0, len(ranked)) + for _, candidate := range ranked { + out = append(out, candidate.company) + } + return out, nil +} diff --git a/frontend/e2e/ticket12-happy-path.spec.mjs b/frontend/e2e/ticket12-happy-path.spec.mjs index 0377416..7d144ee 100644 --- a/frontend/e2e/ticket12-happy-path.spec.mjs +++ b/frontend/e2e/ticket12-happy-path.spec.mjs @@ -83,7 +83,7 @@ test('admin creates a user who follows a fake company and generates a private su await page.goto(new URL('/assets', baseURL).href) 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" }) + const query = page.getByRole('textbox', { name: 'Nom ou nom courant de l’entreprise' }) await query.fill(fixture.companyQuery) await page.getByRole('button', { name: 'Rechercher' }).click() const results = page.getByRole('region', { name: 'Résultats des entreprises' }) diff --git a/frontend/e2e/ticket19-company-watchlist.spec.mjs b/frontend/e2e/ticket19-company-watchlist.spec.mjs index 323e34e..8540c57 100644 --- a/frontend/e2e/ticket19-company-watchlist.spec.mjs +++ b/frontend/e2e/ticket19-company-watchlist.spec.mjs @@ -43,7 +43,7 @@ test('ticket #19: search companies by name and follow by company_id while preser 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 }) + const query = page.getByRole('textbox', { name: /nom ou nom courant de l’entreprise/i }) await expect(page.getByRole('textbox')).toHaveCount(1) await query.fill('BYD') await page.getByRole('button', { name: /rechercher/i }).click() diff --git a/frontend/src/pages/Watchlist.tsx b/frontend/src/pages/Watchlist.tsx index f609280..0ed5c7d 100644 --- a/frontend/src/pages/Watchlist.tsx +++ b/frontend/src/pages/Watchlist.tsx @@ -9,10 +9,10 @@ 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.', + searchTitle: 'Rechercher une entreprise', query: 'Nom ou nom courant de l’entreprise', search: 'Rechercher', + help: 'Saisissez le nom ou le nom courant d’une entreprise, par exemple Intel ou IBM. La recherche se lance au clic sur Rechercher ou avec Entrée. Jusqu’à 20 résultats, sans sélection automatique.', results: 'Résultats des entreprises', before: 'Saisissez le nom d’une entreprise, puis lancez la recherche.', - searching: 'Recherche en cours…', empty: 'Aucune entreprise trouvée. Essayez un autre nom.', + searching: 'Recherche en cours…', empty: 'Aucune entreprise trouvée. Essayez un autre nom ou nom courant, par exemple Intel ou IBM.', quota: 'Quota de recherche atteint. Réessayez plus tard.', timeout: 'Le délai de recherche est dépassé. Vous pouvez relancer la recherche.', unavailable: 'Le service de recherche est indisponible. Réessayez plus tard.', searchError: 'Impossible de rechercher des entreprises. Vous pouvez relancer la recherche.', retry: 'Réessayer', follow: 'Suivre cette entreprise', tracked: 'Déjà suivie', unfollow: 'Ne plus suivre', @@ -27,9 +27,9 @@ 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', 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.', + searchTitle: 'Search for a company', query: 'Company name or commonly used name', search: 'Search', + help: 'Enter a company name or commonly used name, such as Intel or IBM. Search by clicking Search or pressing Enter. Up to 20 results, with no automatic selection.', + results: 'Company results', before: 'Enter a company name, then search.', searching: 'Searching…', empty: 'No company found. Try another name or commonly used name, such as Intel or IBM.', quota: 'Search quota reached. Please try again later.', timeout: 'The search timed out. You can search again.', unavailable: 'The search service is unavailable. Please try again later.', searchError: 'Unable to search for companies. You can search again.', retry: 'Try again', follow: 'Follow this company', tracked: 'Already followed', unfollow: 'Unfollow', diff --git a/frontend/tests/watchlist-alias-copy-ticket24.test.tsx b/frontend/tests/watchlist-alias-copy-ticket24.test.tsx new file mode 100644 index 0000000..2db3df8 --- /dev/null +++ b/frontend/tests/watchlist-alias-copy-ticket24.test.tsx @@ -0,0 +1,39 @@ +import { cleanup, render, screen, waitFor, within } 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 { search, list, add } = vi.hoisted(() => ({ search: vi.fn(), list: vi.fn(), add: vi.fn() })) +vi.mock('@/api/assets', () => ({ assetsApi: { search, list, add, remove: vi.fn() } })) +afterEach(cleanup) +beforeEach(() => { + vi.clearAllMocks() + list.mockResolvedValue([]) + search.mockResolvedValue([{ company_id: 'company-ibm', name: 'International Business Machines Corporation', country: 'United States', exchange: 'New York Stock Exchange', mic: 'XNYS', symbol: 'IBM' }]) +}) + +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.' }, +] 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() + if (language === 'en') await user.selectOptions(screen.getByLabelText('Langue / Language'), 'en') + const input = screen.getByRole('textbox', { name: label }) + expect(input).toHaveAccessibleDescription(help) + expect(input).toHaveAttribute('maxLength', '100') + await user.type(input, query) + expect(search).not.toHaveBeenCalled() + await user.keyboard('{Enter}') + await waitFor(() => expect(search).toHaveBeenCalledWith(query, 20)) + const region = screen.getByRole('region', { name: results }) + expect(await within(region).findByText('International Business Machines Corporation')).toBeInTheDocument() + expect(within(region).getByText('United States')).toBeInTheDocument() + expect(within(region).getByText('New York Stock Exchange')).toBeInTheDocument() + for (const value of ['IBM', 'XNYS', 'company-ibm']) expect(within(region).queryByText(value, { exact: true })).not.toBeInTheDocument() + expect(add).not.toHaveBeenCalled() + search.mockResolvedValueOnce([]) + await user.clear(input) + await user.type(input, 'Unknown{Enter}') + expect(await screen.findByText(empty)).toHaveAttribute('role', 'status') +}) diff --git a/frontend/tests/watchlist-company-search-ticket19.test.tsx b/frontend/tests/watchlist-company-search-ticket19.test.tsx index 7347809..618974a 100644 --- a/frontend/tests/watchlist-company-search-ticket19.test.tsx +++ b/frontend/tests/watchlist-company-search-ticket19.test.tsx @@ -49,7 +49,7 @@ describe('Ticket #19 — company-first watchlist search', () => { 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 }) + const query = await screen.findByRole('textbox', { name: /nom ou nom courant de l’entreprise/i }) expect(screen.getAllByRole('textbox')).toHaveLength(1) await user.type(query, 'BYD') expect(searchCompanies).not.toHaveBeenCalled() @@ -79,7 +79,7 @@ describe('Ticket #19 — company-first watchlist search', () => { 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}') + await user.type(screen.getByLabelText('Nom ou nom courant 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() @@ -95,7 +95,7 @@ describe('Ticket #19 — company-first watchlist search', () => { render() await user.selectOptions(screen.getByLabelText('Langue / Language'), 'en') await screen.findByText('BYD Company Limited') - expect(screen.getByLabelText('Company name')).toBeInTheDocument() + expect(screen.getByLabelText('Company name or commonly used 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() @@ -110,9 +110,9 @@ describe('Ticket #19 — company-first watchlist search', () => { searchCompanies.mockRejectedValueOnce(new Error('offline')) const user = userEvent.setup() render() - await user.type(screen.getByLabelText("Nom de l'entreprise"), 'BYD{Enter}') + await user.type(screen.getByLabelText('Nom ou nom courant 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(screen.getByLabelText('Nom ou nom courant 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() @@ -126,7 +126,7 @@ describe('Ticket #19 — company-first watchlist search', () => { ] satisfies CompanySearchResult[]) const user = userEvent.setup() render() - await user.type(screen.getByLabelText("Nom de l'entreprise"), 'Example{Enter}') + await user.type(screen.getByLabelText('Nom ou nom courant 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) @@ -145,7 +145,7 @@ describe('Ticket #19 — company-first watchlist search', () => { searchCompanies.mockResolvedValueOnce([{ company_id: 'company-unknown', name: 'Example Company', country: '', exchange: '', mic: 'XNAS' }] satisfies CompanySearchResult[]) const user = userEvent.setup() render() - await user.type(screen.getByLabelText("Nom de l'entreprise"), 'Example{Enter}') + await user.type(screen.getByLabelText('Nom ou nom courant de l’entreprise'), 'Example{Enter}') const name = await screen.findByText('Example Company') expect(name).toHaveClass('font-semibold') expect(screen.queryByText('XNAS')).not.toBeInTheDocument() diff --git a/frontend/tests/watchlist-index-search-ticket4.test.tsx b/frontend/tests/watchlist-index-search-ticket4.test.tsx index 59975db..79e7417 100644 --- a/frontend/tests/watchlist-index-search-ticket4.test.tsx +++ b/frontend/tests/watchlist-index-search-ticket4.test.tsx @@ -50,7 +50,7 @@ describe('Régressions Watchlist — recherche explicite et suivis d’entrepris searchIndices.mockResolvedValueOnce([indexOne]) render() - const query = await screen.findByRole('textbox', { name: "Nom de l'entreprise" }) + const query = await screen.findByRole('textbox', { name: 'Nom ou nom courant de l’entreprise' }) expect(query).toHaveAttribute('maxLength', '100') await user.type(query, 'Apple Inc.') expect(searchIndices).not.toHaveBeenCalled() @@ -74,9 +74,9 @@ describe('Régressions Watchlist — recherche explicite et suivis d’entrepris const history = await screen.findByRole('region', { name: /actifs historiques/i }) expect(within(history).queryByRole('button')).not.toBeInTheDocument() expect(within(history).getByText('Old historic asset')).toBeInTheDocument() - expect(screen.getByLabelText("Nom de l'entreprise")).toBeInTheDocument() + expect(screen.getByLabelText('Nom ou nom courant de l’entreprise')).toBeInTheDocument() - const query = screen.getByRole('textbox', { name: "Nom de l'entreprise" }) + const query = screen.getByRole('textbox', { name: 'Nom ou nom courant 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() @@ -94,7 +94,7 @@ describe('Régressions Watchlist — recherche explicite et suivis d’entrepris it('annonce aucun résultat et les erreurs quota, timeout et indisponibilité sans effacer la recherche', async () => { const user = userEvent.setup() render() - const query = await screen.findByRole('textbox', { name: "Nom de l'entreprise" }) + const query = await screen.findByRole('textbox', { name: 'Nom ou nom courant de l’entreprise' }) searchIndices.mockResolvedValueOnce([]) await user.type(query, 'No match{Enter}') @@ -122,7 +122,7 @@ describe('Régressions Watchlist — recherche explicite et suivis d’entrepris .mockReturnValueOnce(new Promise(resolve => { resolveCurrent = resolve })) const user = userEvent.setup() render() - const query = await screen.findByRole('textbox', { name: "Nom de l'entreprise" }) + const query = await screen.findByRole('textbox', { name: 'Nom ou nom courant de l’entreprise' }) await user.type(query, 'Old query{Enter}') await user.clear(query) @@ -142,7 +142,7 @@ describe('Régressions Watchlist — recherche explicite et suivis d’entrepris searchIndices.mockResolvedValueOnce([indexTwo]) render() - const query = await screen.findByRole('textbox', { name: "Nom de l'entreprise" }) + const query = await screen.findByRole('textbox', { name: 'Nom ou nom courant 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 }))