Files
TradarrV2/backend/internal/companycatalog/search.go
Blomios f7b057efa3 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 <noreply@anthropic.com>
2026-11-22 18:08:35 +01:00

125 lines
3.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}