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:
@ -57,7 +57,8 @@ Toutes les routes ci-dessous, sauf login, exigent un JWT. Les routes admin recha
|
||||
| Surface | API principale |
|
||||
| --- | --- |
|
||||
| Connexion | `POST /api/auth/login` |
|
||||
| Recherche d’indices authentifiée | `GET /api/indices/search?q=NASDAQ&limit=10` (1–100 caractères Unicode, limite 1–20) |
|
||||
| Recherche locale de sociétés | `GET /api/companies/search?q=NVIDIA&limit=10`, nom et désambiguïsation uniquement, catalogue embarqué FinanceDatabase Equity/primary/MIT ; [provenance et maintenance](backend/internal/companycatalog/README.md). |
|
||||
| Recherche d’indices authentifiée (legacy) | `GET /api/indices/search?q=NASDAQ&limit=10` (1–100 caractères Unicode, limite 1–20) |
|
||||
| Compte et indices suivis | `GET /api/me`, `GET/POST /api/me/assets`, `DELETE /api/me/assets/:symbol` |
|
||||
| Préférences | `GET/PUT /api/me/preferences`, `{language,ranking_mode,summary_model_id}`, défaut `fr/title/null` pour un nouveau compte |
|
||||
| Modèles de synthèse disponibles | `GET /api/me/summary-models`, uniquement id/provider/model/label |
|
||||
|
||||
@ -26,6 +26,8 @@ WORKDIR /app
|
||||
COPY --from=builder /app/tradarr .
|
||||
COPY --from=builder /app/internal/database/migrations ./internal/database/migrations
|
||||
|
||||
COPY --from=builder /app/internal/companycatalog/data/FINANCEDATABASE_LICENSE /usr/share/licenses/tradarr/FinanceDatabase-MIT.txt
|
||||
|
||||
ENV CHROME_PATH=/usr/bin/chromium
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
@ -113,7 +113,7 @@ func run(ctx context.Context) error {
|
||||
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
|
||||
gin.SetMode(gin.TestMode)
|
||||
gin.DefaultWriter = io.Discard
|
||||
app := server.New(repo, cfg, server.Dependencies{Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
|
||||
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: e2estack.FakeCompanyCatalog{Fakes: fakes}, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
|
||||
return p.NewGenerationUseCaseWithFactory(feeds, e2estack.FakeLayaRanker{Provider: provider}, func(m models.ResolvedSummaryModel) (ai.Provider, error) {
|
||||
selected := provider
|
||||
selected.Model = m.Model
|
||||
|
||||
@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/companycatalog"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"github.com/tradarr/backend/internal/database"
|
||||
@ -27,6 +28,10 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatalf("config: %v", err)
|
||||
}
|
||||
catalog, err := companycatalog.Default()
|
||||
if err != nil {
|
||||
log.Fatal("company catalog: invalid embedded snapshot")
|
||||
}
|
||||
db, err := database.Connect(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
log.Fatalf("database: %v", err)
|
||||
@ -50,7 +55,7 @@ func main() {
|
||||
models.SourceWatcherGuru: watcherguru.New(),
|
||||
}
|
||||
|
||||
app := server.New(repo, cfg, server.Dependencies{LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
|
||||
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
|
||||
defer app.Close()
|
||||
|
||||
addr := fmt.Sprintf(":%s", cfg.Port)
|
||||
|
||||
54
backend/internal/ai/company_identity_ticket19_test.go
Normal file
54
backend/internal/ai/company_identity_ticket19_test.go
Normal file
@ -0,0 +1,54 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
func TestTicket19LayaReceivesCompanyNameAndSelectedInternalIdentity(t *testing.T) {
|
||||
figi := "BBG00ZMFX1S5"
|
||||
var request struct {
|
||||
States []struct {
|
||||
Indices []map[string]string `json:"indices"`
|
||||
} `json:"states"`
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/systemone/batch" {
|
||||
t.Errorf("Laya path=%s", r.URL.Path)
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Errorf("decode Laya payload: %v", err)
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"results":[{"answers":{"relevance":{"type":"score","score":0.1,"answer_confidence":0.9}},"usage":{"truncated":false,"state_tokens_dropped":0,"truncated_questions":[]}}],"total_usage":{"input_tokens":10,"output_tokens":0}}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL, Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = ranker.Rank(context.Background(), "title", []models.UserAsset{{Name: "Baidu, Inc.", Symbol: "9888.HK", FIGI: &figi}}, []generation.Candidate{{ID: "candidate", Article: scraper.Article{Title: "synthetic market headline"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(request.States) != 1 || len(request.States[0].Indices) != 1 {
|
||||
t.Fatalf("Laya indices payload=%+v", request.States)
|
||||
}
|
||||
index := request.States[0].Indices[0]
|
||||
if index["name"] != "Baidu, Inc." || index["symbol"] != "9888.HK" || index["figi"] != figi {
|
||||
t.Fatalf("Laya received wrong company identity: %+v", index)
|
||||
}
|
||||
if index["symbol"] == "SSAAPL INDEX" {
|
||||
t.Fatalf("Bloomberg identifier was sent to Laya as ticker: %+v", index)
|
||||
}
|
||||
}
|
||||
@ -102,6 +102,12 @@ func (r *LayaHTTPRanker) Rank(ctx context.Context, mode string, assets []models.
|
||||
indices := make([]map[string]string, 0, len(assets))
|
||||
for _, a := range assets {
|
||||
index := map[string]string{"name": a.Name, "symbol": a.Symbol}
|
||||
if a.CompanyID != nil {
|
||||
index["company_id"] = *a.CompanyID
|
||||
}
|
||||
if a.YahooSymbol != nil {
|
||||
index["yahoo_symbol"] = *a.YahooSymbol
|
||||
}
|
||||
if a.FIGI != nil {
|
||||
index["figi"] = *a.FIGI
|
||||
}
|
||||
|
||||
82
backend/internal/api/company_search_ticket19_test.go
Normal file
82
backend/internal/api/company_search_ticket19_test.go
Normal file
@ -0,0 +1,82 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"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 TestTicket19CompanySearchIsAuthenticatedBoundedAndReturnsSafeCompanyDTO(t *testing.T) {
|
||||
previousMode := gin.Mode()
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Cleanup(func() { gin.SetMode(previousMode) })
|
||||
const secret = "ticket-19-company-search-test-secret"
|
||||
const userID = "00000000-0000-0000-0000-000000000019"
|
||||
h := handlers.New(nil, &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
|
||||
router := SetupRouter(h, secret)
|
||||
|
||||
call := func(token, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, req)
|
||||
return response
|
||||
}
|
||||
unauthenticated := call("", "/api/companies/search?q=BYD&limit=2")
|
||||
if unauthenticated.Code != http.StatusUnauthorized {
|
||||
t.Errorf("anonymous company search status=%d, want 401 (body=%s)", unauthenticated.Code, unauthenticated.Body.String())
|
||||
}
|
||||
token, err := auth.GenerateToken(userID, "ticket19@example.test", "user", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
valid := call(token, "/api/companies/search?q=BYD&limit=2")
|
||||
if valid.Code != http.StatusOK {
|
||||
t.Errorf("authenticated company search status=%d, want 200 (body=%s)", valid.Code, valid.Body.String())
|
||||
} else {
|
||||
var envelope struct {
|
||||
Data []map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(valid.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode company results: %v", err)
|
||||
}
|
||||
if len(envelope.Data) == 0 {
|
||||
t.Fatal("company search returned no local results for BYD")
|
||||
}
|
||||
for i, result := range envelope.Data {
|
||||
var name, companyID string
|
||||
if err := json.Unmarshal(result["name"], &name); err != nil || strings.TrimSpace(name) == "" {
|
||||
t.Errorf("result %d lacks display name: %s", i, valid.Body.String())
|
||||
}
|
||||
if err := json.Unmarshal(result["company_id"], &companyID); err != nil || strings.TrimSpace(companyID) == "" {
|
||||
t.Errorf("result %d lacks resolved company_id: %s", i, valid.Body.String())
|
||||
}
|
||||
if len(result["exchange"]) == 0 && len(result["country"]) == 0 {
|
||||
t.Errorf("result %d lacks a company disambiguator: %s", i, valid.Body.String())
|
||||
}
|
||||
}
|
||||
for _, privateKey := range []string{`"symbol":`, `"ticker":`, `"figi":`, `"composite_figi":`} {
|
||||
if strings.Contains(valid.Body.String(), privateKey) {
|
||||
t.Errorf("search DTO exposes private identity field %s: %s", privateKey, valid.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
maxValidLimit := call(token, "/api/companies/search?q=BYD&limit=20")
|
||||
if maxValidLimit.Code != http.StatusOK {
|
||||
t.Errorf("company search limit=20 status=%d, want 200 (body=%s)", maxValidLimit.Code, maxValidLimit.Body.String())
|
||||
}
|
||||
invalidLimit := call(token, "/api/companies/search?q=BYD&limit=21")
|
||||
if invalidLimit.Code != http.StatusBadRequest {
|
||||
t.Errorf("company search limit=21 status=%d, want 400 (body=%s)", invalidLimit.Code, invalidLimit.Body.String())
|
||||
}
|
||||
}
|
||||
59
backend/internal/api/handlers/companies.go
Normal file
59
backend/internal/api/handlers/companies.go
Normal file
@ -0,0 +1,59 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/companycatalog"
|
||||
"github.com/tradarr/backend/internal/httputil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type CompanyCatalog = companycatalog.CompanyCatalog
|
||||
|
||||
func (h *Handler) SetCompanyCatalog(c CompanyCatalog) { h.companyCatalog = c }
|
||||
|
||||
type companyDTO struct {
|
||||
CompanyID string `json:"company_id"`
|
||||
Name string `json:"name"`
|
||||
Exchange string `json:"exchange"`
|
||||
Country string `json:"country"`
|
||||
MIC string `json:"mic"`
|
||||
}
|
||||
|
||||
func (h *Handler) SearchCompanies(c *gin.Context) {
|
||||
query := strings.TrimSpace(c.Query("q"))
|
||||
limit := 10
|
||||
params := c.Request.URL.Query()
|
||||
if values, ok := params["limit"]; ok {
|
||||
if len(values) != 1 {
|
||||
c.JSON(400, gin.H{"error": "invalid search parameters"})
|
||||
return
|
||||
}
|
||||
v, err := strconv.Atoi(values[0])
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"error": "invalid search parameters"})
|
||||
return
|
||||
}
|
||||
limit = v
|
||||
}
|
||||
if len(params["q"]) != 1 || !utf8.ValidString(query) || utf8.RuneCountInString(query) < 1 || utf8.RuneCountInString(query) > 100 || limit < 1 || limit > 20 {
|
||||
c.JSON(400, gin.H{"error": "invalid search parameters"})
|
||||
return
|
||||
}
|
||||
if h.companyCatalog == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "company catalog unavailable"})
|
||||
return
|
||||
}
|
||||
companies, err := h.companyCatalog.SearchCompanies(query, limit)
|
||||
if err != nil {
|
||||
c.JSON(503, gin.H{"error": "company catalog unavailable"})
|
||||
return
|
||||
}
|
||||
results := make([]companyDTO, 0, len(companies))
|
||||
for _, company := range companies {
|
||||
results = append(results, companyDTO{company.CompanyID, company.Name, company.Exchange, company.Country, company.MIC})
|
||||
}
|
||||
httputil.OK(c, results)
|
||||
}
|
||||
164
backend/internal/api/handlers/company_asset_ticket19_test.go
Normal file
164
backend/internal/api/handlers/company_asset_ticket19_test.go
Normal file
@ -0,0 +1,164 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/companycatalog"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
const (
|
||||
ticket19OwnerA = "00000000-0000-0000-0000-000000000191"
|
||||
ticket19OwnerB = "00000000-0000-0000-0000-000000000192"
|
||||
ticket19BaiduCompany = "isin:KYG070341048"
|
||||
ticket19NVDACompany = "figi:BBG000BBJQV0"
|
||||
ticket19SpoofFIGI = "BBG-CLIENT-SPOOF"
|
||||
)
|
||||
|
||||
// ticket19CompanyCatalogFake models the injected, local catalog. It supplies
|
||||
// canonical domain records; the HTTP DTO remains outside this test contract.
|
||||
type ticket19CompanyCatalogFake struct {
|
||||
companies map[string]companycatalog.Company
|
||||
}
|
||||
|
||||
func (f ticket19CompanyCatalogFake) SearchCompanies(query string, limit int) ([]companycatalog.Company, error) {
|
||||
result := make([]companycatalog.Company, 0, limit)
|
||||
for _, company := range f.companies {
|
||||
if query != "" && containsFold(company.Name, query) {
|
||||
result = append(result, company)
|
||||
}
|
||||
}
|
||||
if len(result) > limit {
|
||||
result = result[:limit]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (f ticket19CompanyCatalogFake) ResolveCompany(companyID string) (companycatalog.Company, error) {
|
||||
company, ok := f.companies[companyID]
|
||||
if !ok {
|
||||
return companycatalog.Company{}, fmt.Errorf("unknown company id")
|
||||
}
|
||||
return company, nil
|
||||
}
|
||||
|
||||
func TestTicket19FollowCompanyResolvesOpaqueIdentityIdempotentlyPerOwnerPostgres(t *testing.T) {
|
||||
previousMode := gin.Mode()
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Cleanup(func() { gin.SetMode(previousMode) })
|
||||
db := ticket4AssetDB(t)
|
||||
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog := ticket19CompanyCatalogFake{companies: map[string]companycatalog.Company{
|
||||
ticket19BaiduCompany: {
|
||||
CompanyID: ticket19BaiduCompany, ISIN: "KYG070341048", Name: "Baidu, Inc.",
|
||||
YahooSymbol: "9888.HK", FIGI: "BBG00ZMFX1S5", Exchange: "Hong Kong Stock Exchange", Country: "China",
|
||||
},
|
||||
ticket19NVDACompany: {
|
||||
CompanyID: ticket19NVDACompany, Name: "NVIDIA Corporation",
|
||||
YahooSymbol: "NVDA", FIGI: "BBG000BBJQV0", Exchange: "Nasdaq", Country: "United States",
|
||||
},
|
||||
}}
|
||||
const secret = "ticket-19-company-follow-test-secret"
|
||||
tokenA, err := auth.GenerateToken(ticket19OwnerA, "owner-a@example.test", "user", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tokenB, err := auth.GenerateToken(ticket19OwnerB, "owner-b@example.test", "user", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
|
||||
h.SetCompanyCatalog(catalog)
|
||||
router := gin.New()
|
||||
authed := router.Group("/api")
|
||||
authed.Use(auth.Middleware(secret))
|
||||
authed.POST("/me/assets", h.AddMyAsset)
|
||||
post := func(token, companyID, symbol, name, figi string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
requestBody := map[string]string{"company_id": companyID}
|
||||
// The client may send old or hostile values; the injected catalog wins.
|
||||
if symbol != "" {
|
||||
requestBody["symbol"] = symbol
|
||||
}
|
||||
if name != "" {
|
||||
requestBody["name"] = name
|
||||
}
|
||||
if figi != "" {
|
||||
requestBody["figi"] = figi
|
||||
}
|
||||
payload, err := json.Marshal(requestBody)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/me/assets", bytes.NewReader(payload))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, req)
|
||||
return response
|
||||
}
|
||||
|
||||
first := post(tokenA, ticket19BaiduCompany, "CLIENT-SPOOF-A", "Client supplied name A", ticket19SpoofFIGI)
|
||||
if first.Code != http.StatusCreated {
|
||||
t.Fatalf("follow company status=%d body=%s, want 201", first.Code, first.Body.String())
|
||||
}
|
||||
duplicate := post(tokenA, ticket19BaiduCompany, "", "", "")
|
||||
if duplicate.Code != http.StatusCreated {
|
||||
t.Fatalf("repeat follow by company identity status=%d body=%s, want idempotent success", duplicate.Code, duplicate.Body.String())
|
||||
}
|
||||
otherOwner := post(tokenB, ticket19BaiduCompany, "CLIENT-SPOOF-C", "Client supplied name C", "BBG-CLIENT-SPOOF-3")
|
||||
if otherOwner.Code != http.StatusCreated {
|
||||
t.Fatalf("other owner's same-company follow status=%d body=%s", otherOwner.Code, otherOwner.Body.String())
|
||||
}
|
||||
fallback := post(tokenB, ticket19NVDACompany, "", "", "")
|
||||
if fallback.Code != http.StatusCreated {
|
||||
t.Fatalf("FIGI-fallback company follow status=%d body=%s", fallback.Code, fallback.Body.String())
|
||||
}
|
||||
|
||||
for _, tc := range []struct{ owner, companyID string }{
|
||||
{ticket19OwnerA, ticket19BaiduCompany},
|
||||
{ticket19OwnerB, ticket19BaiduCompany},
|
||||
{ticket19OwnerB, ticket19NVDACompany},
|
||||
} {
|
||||
var count int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM user_assets WHERE user_id=$1 AND company_id=$2`, tc.owner, tc.companyID).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("owner %s company %s rows=%d; want one", tc.owner, tc.companyID, count)
|
||||
}
|
||||
}
|
||||
var userID, companyID, symbol, name string
|
||||
var figi sql.NullString
|
||||
err = db.QueryRow(`SELECT user_id::text,company_id,symbol,name,figi FROM user_assets WHERE company_id=$1 AND user_id=$2`, ticket19BaiduCompany, ticket19OwnerA).Scan(&userID, &companyID, &symbol, &name, &figi)
|
||||
if err != nil {
|
||||
t.Fatalf("read resolved Baidu asset: %v", err)
|
||||
}
|
||||
if userID != ticket19OwnerA || companyID != ticket19BaiduCompany || symbol != "9888.HK" || name != "Baidu, Inc." || !figi.Valid || figi.String != "BBG00ZMFX1S5" {
|
||||
t.Errorf("persisted identity did not come from CompanyCatalog: owner=%s id=%q symbol=%q name=%q figi=%v", userID, companyID, symbol, name, figi)
|
||||
}
|
||||
if bytes.Contains(first.Body.Bytes(), []byte("Client supplied")) || bytes.Contains(first.Body.Bytes(), []byte("CLIENT-SPOOF")) || bytes.Contains(first.Body.Bytes(), []byte(ticket19SpoofFIGI)) {
|
||||
t.Errorf("POST response leaked client-controlled identity: %s", first.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func containsFold(value, query string) bool {
|
||||
return len(query) == 0 || strings.Contains(strings.ToLower(value), strings.ToLower(query))
|
||||
}
|
||||
98
backend/internal/api/handlers/company_repository_test.go
Normal file
98
backend/internal/api/handlers/company_repository_test.go
Normal file
@ -0,0 +1,98 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/companycatalog"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCompanyRepositoryPreservesLegacyAndReturnsHintsPostgres(t *testing.T) {
|
||||
db := ticket4AssetDB(t)
|
||||
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
figi := "BBG00ZMFX1S5"
|
||||
legacy, err := repo.UpsertUserAsset(ticket4OwnerA, "LEGACY INDEX", "legacy retained", &figi)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
company := companycatalog.Company{CompanyID: "isin:KYG070341048", Name: "Baidu, Inc.", YahooSymbol: "9888.HK", FIGI: figi, Country: "China", Exchange: "HKG"}
|
||||
first, err := repo.UpsertCompanyAsset(ticket4OwnerA, company)
|
||||
if err != nil {
|
||||
t.Fatalf("company upsert: %v", err)
|
||||
}
|
||||
again, err := repo.UpsertCompanyAsset(ticket4OwnerA, company)
|
||||
if err != nil || again.ID != first.ID {
|
||||
t.Fatalf("non-idempotent: %v", err)
|
||||
}
|
||||
other, err := repo.UpsertCompanyAsset(ticket4OwnerB, company)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assets, err := repo.GetUserAssets(ticket4OwnerA)
|
||||
if err != nil || len(assets) != 2 {
|
||||
t.Fatalf("assets=%+v err=%v", assets, err)
|
||||
}
|
||||
for _, a := range assets {
|
||||
if a.ID == legacy.ID && (a.Name != "legacy retained" || a.Symbol != "LEGACY INDEX" || a.CompanyID != nil || a.YahooSymbol != nil) {
|
||||
t.Fatal("legacy row changed")
|
||||
}
|
||||
if a.ID == first.ID && (a.YahooSymbol == nil || *a.YahooSymbol != "9888.HK" || a.CompanyID == nil || *a.CompanyID != company.CompanyID) {
|
||||
t.Fatal("lost company hints")
|
||||
}
|
||||
}
|
||||
if err := repo.RemoveUserAssetByID(ticket4OwnerA, other.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
theirs, err := repo.GetUserAssets(ticket4OwnerB)
|
||||
if err != nil || len(theirs) != 1 {
|
||||
t.Fatal("foreign delete changed data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompanyFollowIgnoresEvenMalformedSpoofFieldsPostgres(t *testing.T) {
|
||||
db := ticket4AssetDB(t)
|
||||
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
h := New(repo, &config.Config{}, nil, nil, nil, nil)
|
||||
company := companycatalog.Company{CompanyID: "isin:KYG070341048", Name: "Baidu, Inc.", YahooSymbol: "9888.HK"}
|
||||
h.SetCompanyCatalog(ticket19CompanyCatalogFake{companies: map[string]companycatalog.Company{company.CompanyID: company}})
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) { c.Set("userID", ticket4OwnerA) })
|
||||
router.POST("/assets", h.AddMyAsset)
|
||||
for _, tc := range []struct {
|
||||
body string
|
||||
status int
|
||||
}{
|
||||
{`{"company_id":"isin:KYG070341048","name":{"private":"spoof"},"symbol":["SSAAPL INDEX"],"figi":123,"user_id":"foreign"}`, 201},
|
||||
{`{"company_id":"isin:unknown","symbol":"CLIENT-SPOOF"}`, 400},
|
||||
} {
|
||||
req := httptest.NewRequest("POST", "/assets", strings.NewReader(tc.body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, req)
|
||||
if response.Code != tc.status {
|
||||
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
assets, err := repo.GetUserAssets(ticket4OwnerA)
|
||||
if err != nil || len(assets) != 1 || assets[0].Name != company.Name {
|
||||
t.Fatalf("assets=%+v err=%v", assets, err)
|
||||
}
|
||||
}
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/companycatalog"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
@ -14,6 +15,7 @@ import (
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
companyCatalog CompanyCatalog
|
||||
indexSearcher indices.IndexSearcher
|
||||
generationUseCase generation.UseCase
|
||||
repo *models.Repository
|
||||
@ -33,7 +35,12 @@ func New(
|
||||
pipeline *ai.Pipeline,
|
||||
sched *scheduler.Scheduler,
|
||||
) *Handler {
|
||||
var catalog CompanyCatalog
|
||||
if embedded, err := companycatalog.Default(); err == nil {
|
||||
catalog = embedded
|
||||
}
|
||||
return &Handler{
|
||||
companyCatalog: catalog,
|
||||
repo: repo,
|
||||
cfg: cfg,
|
||||
enc: enc,
|
||||
|
||||
@ -3,6 +3,7 @@ package handlers
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/tradarr/backend/internal/httputil"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"net/http"
|
||||
@ -33,14 +34,39 @@ func (h *Handler) GetMyAssets(c *gin.Context) {
|
||||
|
||||
type addAssetRequest struct {
|
||||
FIGI *string `json:"figi"`
|
||||
Symbol string `json:"symbol" binding:"required"`
|
||||
Symbol string `json:"symbol"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (h *Handler) AddMyAsset(c *gin.Context) {
|
||||
userID := c.GetString("userID")
|
||||
var identity struct {
|
||||
CompanyID *string `json:"company_id"`
|
||||
}
|
||||
if err := c.ShouldBindBodyWith(&identity, binding.JSON); err != nil {
|
||||
httputil.BadRequest(c, err)
|
||||
return
|
||||
}
|
||||
if identity.CompanyID != nil {
|
||||
if h.companyCatalog == nil {
|
||||
c.JSON(503, gin.H{"error": "company catalog unavailable"})
|
||||
return
|
||||
}
|
||||
company, err := h.companyCatalog.ResolveCompany(strings.TrimSpace(*identity.CompanyID))
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"error": "unknown company_id"})
|
||||
return
|
||||
}
|
||||
asset, err := h.repo.UpsertCompanyAsset(userID, company)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"error": "asset operation failed"})
|
||||
return
|
||||
}
|
||||
httputil.Created(c, asset)
|
||||
return
|
||||
}
|
||||
var req addAssetRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
|
||||
httputil.BadRequest(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@ -34,6 +34,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
authed.Use(auth.Middleware(jwtSecret))
|
||||
|
||||
authed.GET("/indices/search", h.SearchIndices)
|
||||
authed.GET("/companies/search", h.SearchCompanies)
|
||||
authed.GET("/me", h.GetMe)
|
||||
authed.GET("/me/preferences", h.GetMyPreferences)
|
||||
authed.GET("/me/summary-models", h.ListMySummaryModels)
|
||||
|
||||
30
backend/internal/companycatalog/README.md
Normal file
30
backend/internal/companycatalog/README.md
Normal file
@ -0,0 +1,30 @@
|
||||
# Catalogue local FinanceDatabase
|
||||
|
||||
Source officielle : <https://github.com/JerBouma/FinanceDatabase/tree/93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1>, version 2.5.2, commit du 17 novembre 2026. Copyright (c) 2023 Jeroen Bouma ; licence MIT reproduite intégralement dans `data/FINANCEDATABASE_LICENSE`.
|
||||
|
||||
`data/equities_primary.csv` embarque les **47 735 lignes** produites par `Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True)` au commit épinglé. Les scores et indicateurs proviennent de `get_listing_ranks()` sur le jeu complet, sans heuristique maison pour promouvoir un listing secondaire. Aucune partition ETF, fonds, indices, futures ou options n'est chargée par l'exporteur : la classification est celle du partitionnement Equities amont, sans prétendre auditer individuellement chaque instrument. Aucun prix, article ou résultat d'API n'est inclus. Le serveur n'effectue aucun téléchargement, y compris au démarrage.
|
||||
|
||||
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 porte sur le nom (casse et espaces normalisés), avec ordre nom/identité stable et limite après déduplication ; 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
|
||||
|
||||
Les dépendances Python sont réservées à la maintenance ; elles ne sont requises ni dans l'image backend ni pour les tests Go. Python 3.11+ avec prise en charge `tarfile` du filtre `data` est nécessaire. Installer les versions du lockfile dans un environnement virtuel sous un temporaire accessible :
|
||||
|
||||
```sh
|
||||
python3 -E -m venv "$TMPDIR/company-catalog-venv"
|
||||
"$TMPDIR/company-catalog-venv/bin/python" -E -m pip install -r backend/scripts/company-catalog-requirements.txt
|
||||
"$TMPDIR/company-catalog-venv/bin/python" -E backend/scripts/update-company-catalog.py --download
|
||||
```
|
||||
|
||||
`--download` contacte uniquement l'archive source GitHub officielle au commit épinglé. Il ne contacte aucun site financier/API et ne lance aucune récupération d'articles. Pour une reproduction complètement hors réseau, fournir une archive préalablement extraite :
|
||||
|
||||
```sh
|
||||
"$TMPDIR/company-catalog-venv/bin/python" -E backend/scripts/update-company-catalog.py \
|
||||
--source-dir /chemin/FinanceDatabase-93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1 \
|
||||
--output "$TMPDIR/company-catalog-reproduction"
|
||||
cmp backend/internal/companycatalog/data/equities_primary.csv "$TMPDIR/company-catalog-reproduction/equities_primary.csv"
|
||||
```
|
||||
|
||||
Le sélectionneur utilise uniquement les fichiers locaux et refuse les connexions Python pendant la sélection. Les sources et le parquet sont vérifiés avant export. Pour changer de commit, revoir explicitement les empreintes attendues (`company-catalog-upstream.json`), les versions Python, constantes, effectifs, identités cibles et tests ; puis régénérer et faire valider par QA. Il n'existe aucun rafraîchissement automatique. Ne pas lancer cet outil pendant les tests ou au démarrage de l'application.
|
||||
168
backend/internal/companycatalog/catalog.go
Normal file
168
backend/internal/companycatalog/catalog.go
Normal file
@ -0,0 +1,168 @@
|
||||
// Package companycatalog provides a local, immutable catalogue of primary equities.
|
||||
package companycatalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
_ "embed"
|
||||
"encoding/csv"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Company struct {
|
||||
CompanyID, Name, YahooSymbol, ISIN, FIGI, Exchange, MIC, Country string
|
||||
}
|
||||
type CompanyCatalog interface {
|
||||
SearchCompanies(string, int) ([]Company, error)
|
||||
ResolveCompany(string) (Company, error)
|
||||
}
|
||||
|
||||
var ErrUnknownCompany = errors.New("unknown company")
|
||||
|
||||
type Catalog struct {
|
||||
companies []Company
|
||||
byID map[string]Company
|
||||
}
|
||||
|
||||
//go:embed data/equities_primary.csv
|
||||
var embeddedSnapshot []byte
|
||||
|
||||
//go:embed data/manifest.json
|
||||
var embeddedManifest []byte
|
||||
|
||||
//go:embed data/FINANCEDATABASE_LICENSE
|
||||
var embeddedLicense []byte
|
||||
var defaultOnce sync.Once
|
||||
var defaultCatalog *Catalog
|
||||
var defaultError error
|
||||
|
||||
func Default() (*Catalog, error) {
|
||||
defaultOnce.Do(func() {
|
||||
var manifest struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
Records int `json:"records"`
|
||||
LicenseSHA256 string `json:"license_sha256"`
|
||||
}
|
||||
sum := sha256.Sum256(embeddedSnapshot)
|
||||
licenseSum := sha256.Sum256(embeddedLicense)
|
||||
if json.Unmarshal(embeddedManifest, &manifest) != nil || manifest.Records != 47735 || hex.EncodeToString(sum[:]) != manifest.SHA256 || hex.EncodeToString(licenseSum[:]) != manifest.LicenseSHA256 {
|
||||
defaultError = errors.New("invalid embedded company snapshot checksum")
|
||||
return
|
||||
}
|
||||
defaultCatalog, defaultError = readCatalog(bytes.NewReader(embeddedSnapshot))
|
||||
})
|
||||
return defaultCatalog, defaultError
|
||||
}
|
||||
func NewFinanceDatabaseCatalogFromSnapshot(path string) (*Catalog, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return readCatalog(f)
|
||||
}
|
||||
func readCatalog(input io.Reader) (*Catalog, error) {
|
||||
r := csv.NewReader(input)
|
||||
header, err := r.Read()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
columns := map[string]int{}
|
||||
for i, h := range header {
|
||||
columns[h] = i
|
||||
}
|
||||
for _, key := range []string{"symbol", "name", "isin", "figi", "exchange", "country", "mic", "delisted", "primary_listing"} {
|
||||
if _, ok := columns[key]; !ok {
|
||||
return nil, errors.New("invalid company snapshot columns")
|
||||
}
|
||||
}
|
||||
c := &Catalog{byID: map[string]Company{}}
|
||||
scores := map[string]float64{}
|
||||
for {
|
||||
row, err := r.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid company snapshot row")
|
||||
}
|
||||
value := func(key string) string { return strings.TrimSpace(row[columns[key]]) }
|
||||
if !strings.EqualFold(value("delisted"), "false") || !strings.EqualFold(value("primary_listing"), "true") {
|
||||
continue
|
||||
}
|
||||
company := Company{Name: value("name"), YahooSymbol: value("symbol"), ISIN: value("isin"), FIGI: value("figi"), Exchange: value("exchange"), MIC: value("mic"), Country: value("country")}
|
||||
if company.ISIN != "" {
|
||||
company.CompanyID = "isin:" + company.ISIN
|
||||
} else if company.FIGI != "" {
|
||||
company.CompanyID = "figi:" + company.FIGI
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
if company.Name == "" || company.YahooSymbol == "" || strings.ContainsAny(company.YahooSymbol, " \r\n\t") {
|
||||
return nil, errors.New("invalid company snapshot identity")
|
||||
}
|
||||
score := 0.0
|
||||
if column, ok := columns["listing_score"]; ok {
|
||||
score, err = strconv.ParseFloat(row[column], 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid listing score")
|
||||
}
|
||||
}
|
||||
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
|
||||
// already-primary rows. Never promote a non-primary listing.
|
||||
if score < scores[company.CompanyID] || (score == scores[company.CompanyID] && company.YahooSymbol >= old.YahooSymbol) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
c.byID[company.CompanyID] = company
|
||||
scores[company.CompanyID] = score
|
||||
}
|
||||
for _, company := range c.byID {
|
||||
c.companies = append(c.companies, company)
|
||||
}
|
||||
sort.Slice(c.companies, func(i, j int) bool {
|
||||
a, b := c.companies[i], c.companies[j]
|
||||
if strings.ToLower(a.Name) == strings.ToLower(b.Name) {
|
||||
return a.CompanyID < b.CompanyID
|
||||
}
|
||||
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
|
||||
})
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Name search folds case/spacing only: punctuation from a derivative ticker
|
||||
// (for example ES=F) must not become unrelated fragments of company names.
|
||||
func normalizeName(s string) string { return strings.Join(strings.Fields(strings.ToLower(s)), " ") }
|
||||
|
||||
func (c *Catalog) SearchCompanies(query string, limit int) ([]Company, error) {
|
||||
query = normalizeName(query)
|
||||
if query == "" || limit < 1 || limit > 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
|
||||
}
|
||||
return Company{}, ErrUnknownCompany
|
||||
}
|
||||
72
backend/internal/companycatalog/catalog_ticket19_test.go
Normal file
72
backend/internal/companycatalog/catalog_ticket19_test.go
Normal file
@ -0,0 +1,72 @@
|
||||
package companycatalog
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// This checks the internal catalog result only; it intentionally does not fix
|
||||
// an HTTP/public DTO shape. The snapshot is local and pinned, with no network.
|
||||
func TestSearchReturnsOneCompanyNameAndPrimaryYahooSymbol(t *testing.T) {
|
||||
catalog, err := NewFinanceDatabaseCatalogFromSnapshot(filepath.Join("testdata", "finance_database_equities_primary_2026-11-22.csv"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct{ query, name, companyID, yahoo string }{
|
||||
{"NVIDIA", "NVIDIA Corporation", "isin:US67066G1040", "NVDA"},
|
||||
{"Apple", "Apple Inc.", "isin:US0378331005", "AAPL"},
|
||||
{"Baidu", "Baidu, Inc.", "isin:KYG070341048", "9888.HK"},
|
||||
{"BYD Company", "BYD Company Limited", "isin:CNE100001526", "002594.SZ"},
|
||||
{"BYD Electronic", "BYD Electronic (International) Company Limited", "isin:HK0285041858", "0285.HK"},
|
||||
} {
|
||||
t.Run(tc.query, func(t *testing.T) {
|
||||
got, err := catalog.SearchCompanies(tc.query, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("results=%+v; want one company for %q", got, tc.query)
|
||||
}
|
||||
if got[0].Name != tc.name || got[0].CompanyID != tc.companyID || got[0].YahooSymbol != tc.yahoo {
|
||||
t.Fatalf("company=%+v; want name=%q company_id=%q yahoo=%q", got[0], tc.name, tc.companyID, tc.yahoo)
|
||||
}
|
||||
if strings.Contains(got[0].YahooSymbol, " ") || strings.Contains(got[0].YahooSymbol, "INDEX") {
|
||||
t.Fatalf("non-Yahoo security label leaked as Yahoo symbol %q", got[0].YahooSymbol)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompanyCatalogUsesFIGIFallbackWhenISINIsMissing(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "local-figi-fallback.csv")
|
||||
fixture := "symbol,name,exchange,mic,country,isin,figi,composite_figi,delisted,listing_score,primary_listing,main_venue,listings,usual_currency,home_known\n" +
|
||||
"FALLBACK,Example Company,NMS,XNAS,United States,,BBG000FALLBK,BBG000FALLBK,false,1,true,true,1,true,true\n"
|
||||
if err := os.WriteFile(path, []byte(fixture), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog, err := NewFinanceDatabaseCatalogFromSnapshot(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := catalog.SearchCompanies("Example Company", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].CompanyID != "figi:BBG000FALLBK" {
|
||||
t.Fatalf("company fallback identity=%+v; want figi:BBG000FALLBK", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchExcludesNonEquityAssetClasses(t *testing.T) {
|
||||
catalog, err := NewFinanceDatabaseCatalogFromSnapshot(filepath.Join("testdata", "finance_database_equities_primary_2026-11-22.csv"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, symbol := range []string{"QQQ", "ES=F", "AAPL260117C00200000"} {
|
||||
if got, err := catalog.SearchCompanies(symbol, 10); err != nil || len(got) != 0 {
|
||||
t.Errorf("non-equity %q returned %+v, err=%v", symbol, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
21
backend/internal/companycatalog/data/FINANCEDATABASE_LICENSE
Normal file
21
backend/internal/companycatalog/data/FINANCEDATABASE_LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Jeroen Bouma
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
47736
backend/internal/companycatalog/data/equities_primary.csv
Normal file
47736
backend/internal/companycatalog/data/equities_primary.csv
Normal file
File diff suppressed because it is too large
Load Diff
76
backend/internal/companycatalog/data/manifest.json
Normal file
76
backend/internal/companycatalog/data/manifest.json
Normal file
@ -0,0 +1,76 @@
|
||||
{
|
||||
"fields": [
|
||||
"symbol",
|
||||
"name",
|
||||
"exchange",
|
||||
"mic",
|
||||
"country",
|
||||
"isin",
|
||||
"figi",
|
||||
"composite_figi",
|
||||
"delisted",
|
||||
"listing_score",
|
||||
"primary_listing",
|
||||
"main_venue",
|
||||
"listings",
|
||||
"usual_currency",
|
||||
"home_known"
|
||||
],
|
||||
"identities_with_multiple_primary_rows": 2184,
|
||||
"license": "MIT",
|
||||
"license_sha256": "dea317ce7193c52174ebb0def6df1a2f762f75b60e5bc026176fea6cf3ede4ff",
|
||||
"package_version": "2.5.2",
|
||||
"primary_listing_evidence": "Unmodified commit-pinned upstream listings_model over the complete local Equities data; no ticker heuristic or provider API.",
|
||||
"records": 47735,
|
||||
"rows_without_stable_identity": 2423,
|
||||
"runtime_identity_policy": "ISIN else FIGI; group identical identity; highest upstream listing_score; equal-score primary rows use symbol lexical tie-break for a deterministic representative; unidentified rows remain embedded but are not searchable/followable.",
|
||||
"runtime_resolvable_identities": 43126,
|
||||
"selection": "Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True, as_pandas=False); join get_listing_ranks(); sort symbol",
|
||||
"sha256": "2b340b0834cef9ac8a3c4baea3eb4428466581211c3fdaa0bdf36481749b70ba",
|
||||
"snapshot": "equities_primary.csv",
|
||||
"upstream_commit": "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1",
|
||||
"upstream_commit_date_utc": "2026-11-17T13:27:37Z",
|
||||
"upstream_equities_data_file": "compression/equities.parquet",
|
||||
"upstream_equities_data_sha256": "decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f",
|
||||
"upstream_repository": "https://github.com/JerBouma/FinanceDatabase",
|
||||
"upstream_source_sha256": {
|
||||
"financedatabase/__init__.py": "607e4c1f0f772d2f51f6004b06fe4a905441d29142fa1f06988f549ce5c8e794",
|
||||
"financedatabase/cache_model.py": "1372be4459874b7494c82a9ca8b869803bb843ef6ee5132df67f9f0a710a1e88",
|
||||
"financedatabase/categories_model.py": "f4f47fd5d90edc476f7ce2cf524977a0dc4115dfacfe2f914c6b3566900648f4",
|
||||
"financedatabase/cryptos/__init__.py": "896a0c2f55ea897a3f6c136c0e0e33118de0ff9274edccd9ae0bb29b26770d74",
|
||||
"financedatabase/cryptos/cryptos_controller.py": "953ff91ef8a8043987e2cf1d552332e6cb511f69aa85483186301fee0bb79fc2",
|
||||
"financedatabase/currencies/__init__.py": "c1884f7dbcc322ea64d210696fec6ed6508e05e63614f35523d8ea44fdc23adc",
|
||||
"financedatabase/currencies/currencies_controller.py": "a427110863e835e99ecd153d9b5d960520d6052e22aacff7ef0ad994c09b311d",
|
||||
"financedatabase/database_controller.py": "56b9db9cd3363a8993f13a19bb1530d3d77fef9c945acb75df4ca4c853d6e1d7",
|
||||
"financedatabase/equities/__init__.py": "55b8e55b48cf515b1ec3e3d1266550e3cf00f21fba584e4394cd2264dc4a84df",
|
||||
"financedatabase/equities/equities_controller.py": "0fd7d859fa2f43f7c3d43484a21a8d5ccfcdcb2276e2a4a1d1c94eb838b88bc5",
|
||||
"financedatabase/etfs/__init__.py": "5cb9a938a8130ed8a3af1c19095a5d896f809ca24c50f66586a67b31937304b9",
|
||||
"financedatabase/etfs/etfs_controller.py": "2944bb089470bafc149b94e6f1719081849be1aec62e702df59fe482a5fc51f0",
|
||||
"financedatabase/frame_model.py": "1e36264d193952a8ddd51ccd5ccc3b6ad1dea55b3c5041ad68112f2c29210386",
|
||||
"financedatabase/funds/__init__.py": "e67772c33f8130fa8867723f7b41efe7e9b776ea4107db81e399eaec136e369e",
|
||||
"financedatabase/funds/funds_controller.py": "9a282674b0ac1c5d925fd65955ac7d66899cd788c1dfc74379aacd2c12bf72a6",
|
||||
"financedatabase/helpers.py": "87946e2257254b6d6700716c27f6edc964bdb4aeba847cf958f0ec70a9f9bb49",
|
||||
"financedatabase/indices/__init__.py": "5f5915ef8e0d5e5ef4efe04139db3397ec2a59fc2b8c08e370685959aff51733",
|
||||
"financedatabase/indices/indices_controller.py": "d67f8b26b3d72de503fc62ae987021a6a9bed78a99bd30a6be203d742a7a514c",
|
||||
"financedatabase/listings_model.py": "44f9b99fda44019e09c37be241d2fd1cdcf52afd1a6b1d33eb7ac54b7132b48d",
|
||||
"financedatabase/mcp_server/__init__.py": "9df6de1448fd4d659e8463d6548c90b40b6c47f5492dffc5ceb2b585d3993c18",
|
||||
"financedatabase/mcp_server/__main__.py": "51796c03ba817474a84161ccbb3900838651acee63a47dec7e95a59d4815363a",
|
||||
"financedatabase/mcp_server/analytics_model.py": "426775e4d6c8d140b4cc009139ad5ce5e24b31bf32f8cb3dc1620676b8d418f5",
|
||||
"financedatabase/mcp_server/coercion_model.py": "c309112cd0e76c70e777613a9b9d0bd0c09f0f8522d24a72c1d2dcb0a4e9cdc7",
|
||||
"financedatabase/mcp_server/formatting_model.py": "2c3d32ec961352782894993b336c4ee58d47bf0ee25b762f5f5bd22688fde546",
|
||||
"financedatabase/mcp_server/mcp_controller.py": "fe1ebab3086b54855aeecffd4f43bd60257f5ae24fe0dbfdc0e3ea0242431dd7",
|
||||
"financedatabase/mcp_server/provider_model.py": "22bb45c6f192abbb29cf6aea8ee6b901a204d5960765ae7c10e575f002e9af55",
|
||||
"financedatabase/mcp_server/ranking_model.py": "f03e03de04fc719a0a4ec6beeeaadb261b403a1ad5b3abf057977af6cc924faa",
|
||||
"financedatabase/mcp_server/registry_model.py": "a4d4844268ef84fbcae1c82aa16e1ba4be34b0a295936661df13220dd3b4dd46",
|
||||
"financedatabase/mcp_server/setup_model.py": "69508873479ceacfbdb92a8bacfd988968c773b9adb67193dbcfee2d7acc92be",
|
||||
"financedatabase/mcp_server/site_model.py": "0cf95f37479086d6753653e382029ec8f2806e654e6d35e6dc611f75cb0e6a2f",
|
||||
"financedatabase/mcp_server/stats_page_model.py": "c53f4ee51851feb4050b8fb9724ea973c0b95305a205ee78456eb818dff6a9ca",
|
||||
"financedatabase/mcp_server/tools_model.py": "81cadc7360a3512503d0e126437fde168c7043e4578d7d7214bbba5c38d2cfd1",
|
||||
"financedatabase/moneymarkets/__init__.py": "d6e552766b18c4c577f730e23e622847f327d71cc0c8009140bdcd6384829cc8",
|
||||
"financedatabase/moneymarkets/moneymarkets_controller.py": "516f6db36f3cd5195cdbab70bda810575e0b875ce7b43e66087b5be6d336971f",
|
||||
"financedatabase/query_model.py": "a24ff8c88ffb4f5c4dcf7607e057e8b549b3d5f403539a821ca62935fd54e54b",
|
||||
"financedatabase/utilities/__init__.py": "8ae00bf057b5f6315fac4999e7a813d4b21696017b76246e44a08e20dc9dc282",
|
||||
"financedatabase/utilities/dataframe_model.py": "814cab4fca135b5c7b6f50818052c0a318f6bd8466338a8bead0c66270066aee",
|
||||
"financedatabase/utilities/logger_model.py": "9dcf03c9dca815a1d6a2d0b694f5937f98b4ede2a5e03abf36a19575b4387d92"
|
||||
}
|
||||
}
|
||||
53
backend/internal/companycatalog/embedded_test.go
Normal file
53
backend/internal/companycatalog/embedded_test.go
Normal file
@ -0,0 +1,53 @@
|
||||
package companycatalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/csv"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEmbeddedSnapshotIsCompletePinnedAndResolvable(t *testing.T) {
|
||||
data, err := os.ReadFile("data/manifest.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var manifest struct {
|
||||
Records int `json:"records"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Commit string `json:"upstream_commit"`
|
||||
}
|
||||
if err = json.Unmarshal(data, &manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := sha256.Sum256(embeddedSnapshot)
|
||||
rows, err := csv.NewReader(bytes.NewReader(embeddedSnapshot)).ReadAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if manifest.Records != 47735 || len(rows)-1 != manifest.Records || hex.EncodeToString(sum[:]) != manifest.SHA256 || manifest.Commit != "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1" {
|
||||
t.Fatal("incomplete or unpinned embedded snapshot")
|
||||
}
|
||||
catalog, err := Default()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(catalog.companies) != 43126 {
|
||||
t.Fatalf("resolved identities=%d", len(catalog.companies))
|
||||
}
|
||||
for id, want := range map[string]string{"isin:US67066G1040": "NVDA", "isin:US0378331005": "AAPL", "isin:KYG070341048": "9888.HK", "isin:CNE100001526": "002594.SZ", "isin:HK0285041858": "0285.HK"} {
|
||||
company, err := catalog.ResolveCompany(id)
|
||||
if err != nil || company.YahooSymbol != want {
|
||||
t.Fatalf("%s resolved to %+v, %v", id, company, err)
|
||||
}
|
||||
}
|
||||
for _, query := range []string{"QQQ", "ES=F", "AAPL260117C00200000"} {
|
||||
result, err := catalog.SearchCompanies(query, 20)
|
||||
if err != nil || len(result) != 0 {
|
||||
t.Fatalf("unexpected non-company search result %q: %+v", query, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,191 @@
|
||||
package companycatalog
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/csv"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const testdataDir = "testdata"
|
||||
|
||||
type financeDatabaseManifest struct {
|
||||
UpstreamRepository string `json:"upstream_repository"`
|
||||
UpstreamCommit string `json:"upstream_commit"`
|
||||
CommitDate string `json:"upstream_commit_date_utc"`
|
||||
PackageVersion string `json:"package_version"`
|
||||
License string `json:"license"`
|
||||
UpstreamDataFile string `json:"upstream_equities_data_file"`
|
||||
UpstreamDataSHA256 string `json:"upstream_equities_data_sha256"`
|
||||
SnapshotDate string `json:"snapshot_date"`
|
||||
Selection string `json:"selection"`
|
||||
Evidence string `json:"primary_listing_evidence"`
|
||||
Fixtures map[string]struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
Records int `json:"records"`
|
||||
} `json:"fixtures"`
|
||||
}
|
||||
|
||||
type financeDatabaseRow struct {
|
||||
Symbol string
|
||||
Name string
|
||||
Exchange string
|
||||
MIC string
|
||||
Country string
|
||||
ISIN string
|
||||
FIGI string
|
||||
CompositeFIGI string
|
||||
Delisted string
|
||||
ListingScore string
|
||||
PrimaryListing string
|
||||
MainVenue string
|
||||
Listings string
|
||||
UsualCurrency string
|
||||
HomeKnown string
|
||||
}
|
||||
|
||||
func readFinanceDatabaseRows(t *testing.T, filename string) []financeDatabaseRow {
|
||||
t.Helper()
|
||||
file, err := os.Open(filepath.Join(testdataDir, filename))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
reader := csv.NewReader(file)
|
||||
reader.FieldsPerRecord = -1
|
||||
rows, err := reader.ReadAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) < 2 {
|
||||
t.Fatalf("%s has only %d records", filename, len(rows)-1)
|
||||
}
|
||||
columns := make(map[string]int, len(rows[0]))
|
||||
for i, name := range rows[0] {
|
||||
columns[name] = i
|
||||
}
|
||||
for _, column := range []string{"symbol", "name", "exchange", "mic", "country", "isin", "figi", "composite_figi", "delisted", "listing_score", "primary_listing", "main_venue", "listings", "usual_currency", "home_known"} {
|
||||
if _, ok := columns[column]; !ok {
|
||||
t.Fatalf("%s lacks %q column", filename, column)
|
||||
}
|
||||
}
|
||||
out := make([]financeDatabaseRow, 0, len(rows)-1)
|
||||
for _, values := range rows[1:] {
|
||||
if len(values) != len(rows[0]) {
|
||||
t.Fatalf("malformed row in %s: %v", filename, values)
|
||||
}
|
||||
value := func(column string) string { return values[columns[column]] }
|
||||
out = append(out, financeDatabaseRow{
|
||||
Symbol: value("symbol"), Name: value("name"), Exchange: value("exchange"), MIC: value("mic"),
|
||||
Country: value("country"), ISIN: value("isin"), FIGI: value("figi"), CompositeFIGI: value("composite_figi"),
|
||||
Delisted: value("delisted"), ListingScore: value("listing_score"), PrimaryListing: value("primary_listing"),
|
||||
MainVenue: value("main_venue"), Listings: value("listings"), UsualCurrency: value("usual_currency"), HomeKnown: value("home_known"),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestFinanceDatabaseSnapshotHasPinnedRuntimeProvenanceAndChecksums(t *testing.T) {
|
||||
manifestBytes, err := os.ReadFile(filepath.Join(testdataDir, "finance_database_manifest_2026-11-22.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var manifest financeDatabaseManifest
|
||||
if err := json.Unmarshal(manifestBytes, &manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if manifest.UpstreamRepository != "https://github.com/JerBouma/FinanceDatabase" || manifest.UpstreamCommit != "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1" || manifest.CommitDate != "2026-11-17T13:27:37Z" {
|
||||
t.Fatalf("unexpected upstream provenance: %+v", manifest)
|
||||
}
|
||||
if manifest.PackageVersion != "2.5.2" || manifest.License != "MIT" || manifest.SnapshotDate != "2026-11-22" {
|
||||
t.Fatalf("unexpected version/license/date: %+v", manifest)
|
||||
}
|
||||
if manifest.UpstreamDataFile != "compression/equities.parquet" || len(manifest.UpstreamDataSHA256) != 64 {
|
||||
t.Fatalf("manifest lacks the pinned upstream dataset digest: %+v", manifest)
|
||||
}
|
||||
if !strings.Contains(manifest.Selection, "Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True)") || manifest.Evidence == "" {
|
||||
t.Fatal("manifest must state the actual primary-listing selection and its evidence")
|
||||
}
|
||||
for name, want := range manifest.Fixtures {
|
||||
content, err := os.ReadFile(filepath.Join(testdataDir, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := sha256.Sum256(content)
|
||||
if got := hex.EncodeToString(sum[:]); got != want.SHA256 {
|
||||
t.Errorf("%s sha256=%s, manifest says %s", name, got, want.SHA256)
|
||||
}
|
||||
rows := readFinanceDatabaseRows(t, name)
|
||||
if len(rows) != want.Records {
|
||||
t.Errorf("%s records=%d, manifest says %d", name, len(rows), want.Records)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinanceDatabaseRawMultiListingsAndPrimaryRuntimeSnapshot(t *testing.T) {
|
||||
raw := readFinanceDatabaseRows(t, "finance_database_raw_multilistings_2026-11-22.csv")
|
||||
primary := readFinanceDatabaseRows(t, "finance_database_equities_primary_2026-11-22.csv")
|
||||
rawBySymbol := make(map[string]financeDatabaseRow, len(raw))
|
||||
for _, row := range raw {
|
||||
if _, exists := rawBySymbol[row.Symbol]; exists {
|
||||
t.Fatalf("raw fixture repeats symbol %s", row.Symbol)
|
||||
}
|
||||
rawBySymbol[row.Symbol] = row
|
||||
}
|
||||
// Keep both the requested Baidu ADR (BIDU) and the two Hong Kong listings in
|
||||
// the raw data. The upstream selector chooses 9888.HK as primary for Baidu.
|
||||
for _, symbol := range []string{"NVDA", "AAPL", "BIDU", "9888.HK", "89888.HK", "1211.HK", "002594.SZ", "0285.HK", "BYDIF", "BYDIY"} {
|
||||
if _, ok := rawBySymbol[symbol]; !ok {
|
||||
t.Errorf("raw multi-listing fixture lacks %s", symbol)
|
||||
}
|
||||
}
|
||||
if !strings.EqualFold(rawBySymbol["BIDU"].PrimaryListing, "false") || !strings.EqualFold(rawBySymbol["9888.HK"].PrimaryListing, "true") {
|
||||
t.Errorf("FinanceDatabase primary-listing result for Baidu: BIDU=%s 9888.HK=%s", rawBySymbol["BIDU"].PrimaryListing, rawBySymbol["9888.HK"].PrimaryListing)
|
||||
}
|
||||
if !strings.EqualFold(rawBySymbol["1211.HK"].PrimaryListing, "false") || !strings.EqualFold(rawBySymbol["002594.SZ"].PrimaryListing, "true") {
|
||||
t.Errorf("FinanceDatabase primary-listing result for BYD Co: 1211.HK=%s 002594.SZ=%s", rawBySymbol["1211.HK"].PrimaryListing, rawBySymbol["002594.SZ"].PrimaryListing)
|
||||
}
|
||||
if !strings.EqualFold(rawBySymbol["0285.HK"].PrimaryListing, "true") || !strings.EqualFold(rawBySymbol["BYDIF"].PrimaryListing, "false") {
|
||||
t.Errorf("FinanceDatabase primary-listing result for BYD Electronic: 0285.HK=%s BYDIF=%s", rawBySymbol["0285.HK"].PrimaryListing, rawBySymbol["BYDIF"].PrimaryListing)
|
||||
}
|
||||
|
||||
want := map[string]string{
|
||||
"NVDA": "NVIDIA Corporation",
|
||||
"AAPL": "Apple Inc.",
|
||||
"9888.HK": "Baidu, Inc.",
|
||||
"002594.SZ": "BYD Company Limited",
|
||||
"0285.HK": "BYD Electronic (International) Company Limited",
|
||||
}
|
||||
got := make(map[string]financeDatabaseRow, len(primary))
|
||||
nameCounts := make(map[string]int)
|
||||
for _, row := range primary {
|
||||
if !strings.EqualFold(row.Delisted, "false") || !strings.EqualFold(row.PrimaryListing, "true") {
|
||||
t.Errorf("runtime snapshot contains non-primary or delisted row: %+v", row)
|
||||
}
|
||||
got[row.Symbol] = row
|
||||
nameCounts[row.Name]++
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("runtime selector snapshot has %d target rows; want %d: %+v", len(got), len(want), got)
|
||||
}
|
||||
for symbol, name := range want {
|
||||
row, ok := got[symbol]
|
||||
if !ok || row.Name != name {
|
||||
t.Errorf("runtime primary row %s=%+v; want company %q", symbol, row, name)
|
||||
}
|
||||
if nameCounts[name] != 1 {
|
||||
t.Errorf("runtime snapshot has %d rows for %q; want one", nameCounts[name], name)
|
||||
}
|
||||
}
|
||||
if got["002594.SZ"].Name == got["0285.HK"].Name || got["002594.SZ"].ISIN == got["0285.HK"].ISIN {
|
||||
t.Fatal("FinanceDatabase runtime snapshot collapsed BYD Co and BYD Electronic")
|
||||
}
|
||||
if got["002594.SZ"].ListingScore == "" || got["0285.HK"].ListingScore == "" {
|
||||
t.Fatal("runtime snapshot lacks selector ranking evidence")
|
||||
}
|
||||
}
|
||||
6
backend/internal/companycatalog/testdata/finance_database_equities_primary_2026-11-22.csv
vendored
Normal file
6
backend/internal/companycatalog/testdata/finance_database_equities_primary_2026-11-22.csv
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
symbol,name,exchange,mic,country,isin,figi,composite_figi,delisted,listing_score,primary_listing,main_venue,listings,usual_currency,home_known
|
||||
002594.SZ,BYD Company Limited,SHZ,XSHE,China,CNE100001526,BBG001QVK2K1,BBG000G44NQ0,False,3.999605988967691,True,True,11,True,True
|
||||
0285.HK,BYD Electronic (International) Company Limited,HKG,XHKG,China,HK0285041858,BBG000JPLTR7,BBG000JPKS36,False,2.4508226691042045,True,True,2,True,True
|
||||
9888.HK,"Baidu, Inc.",HKG,XHKG,China,KYG070341048,BBG00ZMFX1S5,BBG000Q1VPS8,False,2.4508226691042045,True,True,15,True,True
|
||||
AAPL,Apple Inc.,NMS,XNAS,United States,US0378331005,BBG000B9Y5X2,BBG000B9XRY4,False,3.7479016786570742,True,True,18,True,True
|
||||
NVDA,NVIDIA Corporation,NMS,XNAS,United States,US67066G1040,BBG000BBJQV0,BBG000BBJQV0,False,3.7479016786570742,True,True,18,True,True
|
||||
|
40
backend/internal/companycatalog/testdata/finance_database_manifest_2026-11-22.json
vendored
Normal file
40
backend/internal/companycatalog/testdata/finance_database_manifest_2026-11-22.json
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
{
|
||||
"source": "FinanceDatabase Equities",
|
||||
"upstream_repository": "https://github.com/JerBouma/FinanceDatabase",
|
||||
"upstream_commit": "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1",
|
||||
"upstream_commit_date_utc": "2026-11-17T13:27:37Z",
|
||||
"package_version": "2.5.2",
|
||||
"license": "MIT",
|
||||
"upstream_equities_data_file": "compression/equities.parquet",
|
||||
"upstream_equities_data_sha256": "decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f",
|
||||
"snapshot_date": "2026-11-22",
|
||||
"selection": "Ran pinned source with its commit-pinned local compression data: Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True). The raw fixture contains symbols NVDA, AAPL, BIDU, 9888.HK, 89888.HK, 1211.HK, 002594.SZ, 0285.HK, BYDIF, BYDIY, BYDDF and BYDDY before primary filtering. The runtime fixture contains rows produced by the selector; it was sorted by symbol only after selection for deterministic file ordering.",
|
||||
"primary_listing_evidence": "Runtime primary_listing flags and listing_score are from upstream listings_model.get_listing_ranks() over the full pinned Equities dataset. Ranking considers exchanges, country/home-market shares, main venues, currency, number of listings, and linked names; not random choice or ticker sorting.",
|
||||
"fields": [
|
||||
"symbol",
|
||||
"name",
|
||||
"exchange",
|
||||
"mic",
|
||||
"country",
|
||||
"isin",
|
||||
"figi",
|
||||
"composite_figi",
|
||||
"delisted",
|
||||
"listing_score",
|
||||
"primary_listing",
|
||||
"main_venue",
|
||||
"listings",
|
||||
"usual_currency",
|
||||
"home_known"
|
||||
],
|
||||
"fixtures": {
|
||||
"finance_database_raw_multilistings_2026-11-22.csv": {
|
||||
"sha256": "2ae92b90ba9ec2797d7c27c46b46cff423d6968b36e91576ae488b53fdba19cd",
|
||||
"records": 12
|
||||
},
|
||||
"finance_database_equities_primary_2026-11-22.csv": {
|
||||
"sha256": "977d473bd05658406631b9fac829ac628ab057ff240868b9fd38314fd7848732",
|
||||
"records": 5
|
||||
}
|
||||
}
|
||||
}
|
||||
13
backend/internal/companycatalog/testdata/finance_database_raw_multilistings_2026-11-22.csv
vendored
Normal file
13
backend/internal/companycatalog/testdata/finance_database_raw_multilistings_2026-11-22.csv
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
symbol,name,exchange,mic,country,isin,figi,composite_figi,delisted,listing_score,primary_listing,main_venue,listings,usual_currency,home_known
|
||||
002594.SZ,BYD Company Limited,SHZ,XSHE,China,CNE100001526,BBG001QVK2K1,BBG000G44NQ0,False,3.999605988967691,True,True,11,True,True
|
||||
0285.HK,BYD Electronic (International) Company Limited,HKG,XHKG,China,HK0285041858,BBG000JPLTR7,BBG000JPKS36,False,2.4508226691042045,True,True,2,True,True
|
||||
1211.HK,"BYD Co., Ltd.",HKG,XHKG,China,CNE100000296,BBG000G6RLL9,BBG000G6RL93,False,2.4508226691042045,False,True,11,True,True
|
||||
89888.HK,"Baidu, Inc.",HKG,XHKG,China,KYG070341048,BBG01GXJWMV7,BBG01GXJWMT0,False,2.4508226691042045,False,True,15,False,True
|
||||
9888.HK,"Baidu, Inc.",HKG,XHKG,China,KYG070341048,BBG00ZMFX1S5,BBG000Q1VPS8,False,2.4508226691042045,True,True,15,True,True
|
||||
AAPL,Apple Inc.,NMS,XNAS,United States,US0378331005,BBG000B9Y5X2,BBG000B9XRY4,False,3.7479016786570742,True,True,18,True,True
|
||||
BIDU,"Baidu, Inc.",NMS,XNAS,China,KYG070341048,BBG000QXWHD1,BBG000QXWHD1,False,1.0584459696877415,False,True,15,True,True
|
||||
BYDDF,"BYD Co., Ltd.",PNK,OTCM,China,CNE100000296,BBG000NZG2R5,BBG000NZG2R5,False,0.0,False,False,11,True,True
|
||||
BYDDY,"BYD Co., Ltd.",PNK,OTCM,China,US05606L1008,BBG000SFXPB1,BBG000SFXPB1,False,0.0,False,False,11,True,True
|
||||
BYDIF,BYD Electronic (International) Company Limited,PNK,OTCM,China,HK0285041858,BBG000VKK8W5,BBG000VKK8W5,False,0.0,False,False,2,True,True
|
||||
BYDIY,BYD Electronic (International) Company Limited,PNK,OTCM,China,US1243121092,BBG004WFYQV3,BBG004WFYQV3,False,0.0,False,False,2,True,True
|
||||
NVDA,NVIDIA Corporation,NMS,XNAS,United States,US67066G1040,BBG000BBJQV0,BBG000BBJQV0,False,3.7479016786570742,True,True,18,True,True
|
||||
|
@ -0,0 +1,3 @@
|
||||
-- No destructive downgrade: removing company identity would collapse independent
|
||||
-- catalogue and legacy follows. Restore a backup or explicitly reconcile first.
|
||||
DO $$ BEGIN RAISE EXCEPTION '000017 cannot be reverted without explicit company/legacy reconciliation'; END $$;
|
||||
@ -0,0 +1,13 @@
|
||||
BEGIN;
|
||||
ALTER TABLE user_assets ADD COLUMN company_id TEXT NULL,
|
||||
ADD COLUMN yahoo_symbol TEXT NULL,
|
||||
ADD COLUMN company_exchange TEXT NULL,
|
||||
ADD COLUMN company_country TEXT NULL,
|
||||
ADD COLUMN company_mic TEXT NULL;
|
||||
CREATE UNIQUE INDEX user_assets_company_unique ON user_assets(user_id,company_id) WHERE company_id IS NOT NULL;
|
||||
-- Legacy identities remain independent of catalogue follows, even for the same FIGI.
|
||||
DROP INDEX IF EXISTS user_assets_legacy_symbol_unique;
|
||||
DROP INDEX IF EXISTS user_assets_figi_unique;
|
||||
CREATE UNIQUE INDEX user_assets_legacy_symbol_unique ON user_assets(user_id,symbol) WHERE figi IS NULL AND company_id IS NULL;
|
||||
CREATE UNIQUE INDEX user_assets_figi_unique ON user_assets(user_id,figi) WHERE figi IS NOT NULL AND company_id IS NULL;
|
||||
COMMIT;
|
||||
@ -0,0 +1,126 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
func TestTicket19CompanyCatalogMigrationIsAdditiveAndKeepsLegacyIndexAssetsPostgres(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
if os.Getenv("TEST_DATABASE_REQUIRED") == "1" {
|
||||
t.Fatal("TEST_DATABASE_REQUIRED=1 but TEST_DATABASE_URL is empty")
|
||||
}
|
||||
t.Skip("TEST_DATABASE_URL absent: isolated PostgreSQL required")
|
||||
}
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("ticket19_company_migration_%d", time.Now().UnixNano())
|
||||
if _, err := db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||
_ = db.Close()
|
||||
})
|
||||
|
||||
const owner = "00000000-0000-0000-0000-000000000191"
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users (id UUID PRIMARY KEY)`,
|
||||
`CREATE TABLE user_assets (id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, symbol VARCHAR(20) NOT NULL, name TEXT NOT NULL DEFAULT '', figi TEXT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE UNIQUE INDEX user_assets_legacy_symbol_unique ON user_assets(user_id,symbol) WHERE figi IS NULL`,
|
||||
`CREATE UNIQUE INDEX user_assets_figi_unique ON user_assets(user_id,figi) WHERE figi IS NOT NULL`,
|
||||
`INSERT INTO users(id) VALUES ('` + owner + `')`,
|
||||
`INSERT INTO users(id) VALUES ('00000000-0000-0000-0000-000000000193')`,
|
||||
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000191','` + owner + `','LEGACY','Historic company asset',NULL)`,
|
||||
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000192','` + owner + `','SPX','Historic index asset','BBG000SPX001')`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
up, err := os.ReadFile("000017_company_catalog.up.sql")
|
||||
if err != nil {
|
||||
t.Fatalf("read additive company-catalog migration 000017: %v", err)
|
||||
}
|
||||
upSQL := strings.ToLower(string(up))
|
||||
if !strings.Contains(upSQL, "company_id") {
|
||||
t.Fatalf("migration must add string company_id for new catalog-backed follow rows: %s", upSQL)
|
||||
}
|
||||
for _, destructive := range []string{"delete from user_assets", "truncate user_assets", "drop table user_assets", "create table companies"} {
|
||||
if strings.Contains(upSQL, destructive) {
|
||||
t.Errorf("company-catalog migration must preserve assets and avoid a dynamic companies table; found %q", destructive)
|
||||
}
|
||||
}
|
||||
if _, err := db.Exec(string(up)); err != nil {
|
||||
t.Fatalf("apply company-catalog migration to legacy schema: %v", err)
|
||||
}
|
||||
|
||||
var companyIDType string
|
||||
if err := db.QueryRow(`SELECT data_type FROM information_schema.columns WHERE table_schema=$1 AND table_name='user_assets' AND column_name='company_id'`, schema).Scan(&companyIDType); err != nil {
|
||||
t.Fatalf("read company_id column type: %v", err)
|
||||
}
|
||||
if companyIDType != "text" && companyIDType != "character varying" {
|
||||
t.Fatalf("company_id data type=%q; want an opaque string, not UUID", companyIDType)
|
||||
}
|
||||
rows, err := db.Query(`SELECT id::text,user_id::text,symbol,name,figi,company_id FROM user_assets ORDER BY id`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type assetRow struct {
|
||||
id, userID, symbol, name string
|
||||
figi, companyID sql.NullString
|
||||
}
|
||||
var got []assetRow
|
||||
for rows.Next() {
|
||||
var row assetRow
|
||||
if err := rows.Scan(&row.id, &row.userID, &row.symbol, &row.name, &row.figi, &row.companyID); err != nil {
|
||||
rows.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, row)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows.Close()
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("legacy/index asset rows=%d, want both rows preserved: %+v", len(got), got)
|
||||
}
|
||||
if got[0].id != "00000000-0000-0000-0000-000000000191" || got[0].userID != owner || got[0].symbol != "LEGACY" || got[0].name != "Historic company asset" || got[0].figi.Valid || got[0].companyID.Valid {
|
||||
t.Errorf("legacy asset was changed by migration: %+v", got[0])
|
||||
}
|
||||
if got[1].id != "00000000-0000-0000-0000-000000000192" || got[1].userID != owner || got[1].symbol != "SPX" || got[1].name != "Historic index asset" || !got[1].figi.Valid || got[1].figi.String != "BBG000SPX001" || got[1].companyID.Valid {
|
||||
t.Errorf("historical index asset was changed or converted by migration: %+v", got[1])
|
||||
}
|
||||
for i, identity := range []string{"isin:KYG070341048", "figi:BBG000BBJQV0"} {
|
||||
id := fmt.Sprintf("00000000-0000-0000-0000-00000000019%d", 3+i)
|
||||
symbol := fmt.Sprintf("catalog-%d", i)
|
||||
if _, err := db.Exec(`INSERT INTO user_assets(id,user_id,symbol,name,figi,company_id) VALUES ($1,$2,$3,'catalog asset',NULL,$4)`, id, owner, symbol, identity); err != nil {
|
||||
t.Fatalf("insert opaque company identity %q: %v", identity, err)
|
||||
}
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO user_assets(id,user_id,symbol,name,figi,company_id) VALUES ('00000000-0000-0000-0000-000000000195',$1,'duplicate','duplicate catalog identity',NULL,'isin:KYG070341048')`, owner); err == nil {
|
||||
t.Fatal("duplicate owner/company_id must be rejected for idempotent application upserts")
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO user_assets(id,user_id,symbol,name,figi,company_id) VALUES ('00000000-0000-0000-0000-000000000196','00000000-0000-0000-0000-000000000193','other-owner','same company other owner',NULL,'isin:KYG070341048')`); err != nil {
|
||||
t.Fatalf("same company identity should be allowed for another owner: %v", err)
|
||||
}
|
||||
}
|
||||
@ -11,6 +11,7 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/companycatalog"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
@ -18,10 +19,11 @@ import (
|
||||
|
||||
type Fixtures struct {
|
||||
SummaryModelID string `json:"summaryModelID"`
|
||||
IndexQuery string `json:"indexQuery"`
|
||||
IndexName string `json:"indexName"`
|
||||
IndexSymbol string `json:"indexSymbol"`
|
||||
IndexFIGI string `json:"indexFIGI"`
|
||||
CompanyQuery string `json:"companyQuery"`
|
||||
CompanyID string `json:"companyID"`
|
||||
CompanyName string `json:"companyName"`
|
||||
CompanySymbol string `json:"companySymbol"`
|
||||
CompanyFIGI string `json:"companyFIGI"`
|
||||
SummarySentinel string `json:"summarySentinel"`
|
||||
ArticleTitle string `json:"articleTitle"`
|
||||
ArticleURL string `json:"articleURL"`
|
||||
@ -30,15 +32,44 @@ type Fixtures struct {
|
||||
}
|
||||
|
||||
func DefaultFixtures() Fixtures {
|
||||
return Fixtures{"00000000-0000-0000-0000-000000001203", "E2E index", "E2E Financial Index", "E2EIDX", "BBG000E2E001", "E2E synthesized financial summary", "E2E private article title", "https://fixture.invalid/private-article", "E2E private article body", "pending-candidate-id"}
|
||||
return Fixtures{"00000000-0000-0000-0000-000000001203", "E2E Company", "isin:US0000000001", "E2E Company Inc.", "E2ECO", "BBG000E2E001", "E2E synthesized financial summary", "E2E private article title", "https://fixture.invalid/private-article", "E2E private article body", "pending-candidate-id"}
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
Model string `json:"model,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
Query string `json:"query,omitempty"`
|
||||
CompanyID string `json:"company_id,omitempty"`
|
||||
Symbols []string `json:"symbols,omitempty"`
|
||||
CandidateID string `json:"candidate_id,omitempty"`
|
||||
}
|
||||
|
||||
// FakeCompanyCatalog keeps the browser journey deterministic and entirely
|
||||
// local. It exercises the production catalog port without OpenFIGI traffic.
|
||||
type FakeCompanyCatalog struct{ Fakes *Fakes }
|
||||
|
||||
func (c FakeCompanyCatalog) SearchCompanies(query string, limit int) ([]companycatalog.Company, error) {
|
||||
company := c.Fakes.company()
|
||||
c.Fakes.record(Event{Kind: "companySearches", Query: query})
|
||||
if limit < 1 || !strings.Contains(strings.ToLower(company.Name), strings.ToLower(strings.TrimSpace(query))) {
|
||||
return []companycatalog.Company{}, nil
|
||||
}
|
||||
return []companycatalog.Company{company}, nil
|
||||
}
|
||||
|
||||
func (c FakeCompanyCatalog) ResolveCompany(companyID string) (companycatalog.Company, error) {
|
||||
company := c.Fakes.company()
|
||||
c.Fakes.record(Event{Kind: "companyResolutions", CompanyID: companyID})
|
||||
if companyID != company.CompanyID {
|
||||
return companycatalog.Company{}, companycatalog.ErrUnknownCompany
|
||||
}
|
||||
return company, nil
|
||||
}
|
||||
|
||||
func (f *Fakes) company() companycatalog.Company {
|
||||
return companycatalog.Company{CompanyID: f.Fixture.CompanyID, Name: f.Fixture.CompanyName, YahooSymbol: f.Fixture.CompanySymbol, FIGI: f.Fixture.CompanyFIGI, Exchange: "E2E Exchange", MIC: "XEEE", Country: "E2E Country"}
|
||||
}
|
||||
|
||||
type Fakes struct {
|
||||
mu sync.Mutex
|
||||
Fixture Fixtures
|
||||
@ -60,7 +91,7 @@ func (f *Fakes) Handler() http.Handler {
|
||||
mux.HandleFunc("/audit", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"openfigiSearches": f.counts["openfigiSearches"], "scraperCalls": f.counts["scraperCalls"], "layaRankingCalls": f.counts["layaRankingCalls"], "layaSummaryCalls": f.counts["layaSummaryCalls"], "events": f.Events})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"openfigiSearches": f.counts["openfigiSearches"], "companySearches": f.counts["companySearches"], "companyResolutions": f.counts["companyResolutions"], "scraperCalls": f.counts["scraperCalls"], "layaRankingCalls": f.counts["layaRankingCalls"], "layaSummaryCalls": f.counts["layaSummaryCalls"], "events": f.Events})
|
||||
})
|
||||
mux.HandleFunc("/v3/search", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
@ -72,7 +103,7 @@ func (f *Fakes) Handler() http.Handler {
|
||||
return
|
||||
}
|
||||
f.record(Event{Kind: "openfigiSearches"})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]string{{"name": f.Fixture.IndexName, "ticker": f.Fixture.IndexSymbol, "figi": f.Fixture.IndexFIGI, "marketSector": "Index"}}})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]string{{"name": f.Fixture.CompanyName, "ticker": f.Fixture.CompanySymbol, "figi": f.Fixture.CompanyFIGI, "marketSector": "Index"}}})
|
||||
})
|
||||
mux.HandleFunc("/scrape", func(w http.ResponseWriter, r *http.Request) {
|
||||
var symbols []string
|
||||
|
||||
32
backend/internal/generation/company_symbols.go
Normal file
32
backend/internal/generation/company_symbols.go
Normal file
@ -0,0 +1,32 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var yahooTicker = regexp.MustCompile(`^[A-Za-z0-9^][A-Za-z0-9.^=\-]{0,31}$`)
|
||||
var figiIdentity = regexp.MustCompile(`^BBG[A-Z0-9]{9}$`)
|
||||
|
||||
// Only the Yahoo source gets the catalogue's Yahoo listing hint. Other feeds
|
||||
// retain the exact historical Symbol input. No guesses or Bloomberg conversion.
|
||||
func yahooSymbols(assets []models.UserAsset) []string {
|
||||
out := []string{}
|
||||
seen := map[string]bool{}
|
||||
for _, a := range assets {
|
||||
symbol := a.Symbol
|
||||
if a.CompanyID != nil {
|
||||
if a.YahooSymbol == nil {
|
||||
continue
|
||||
}
|
||||
symbol = *a.YahooSymbol
|
||||
}
|
||||
if !yahooTicker.MatchString(symbol) || figiIdentity.MatchString(strings.ToUpper(symbol)) || seen[symbol] {
|
||||
continue
|
||||
}
|
||||
seen[symbol] = true
|
||||
out = append(out, symbol)
|
||||
}
|
||||
return out
|
||||
}
|
||||
46
backend/internal/generation/company_symbols_test.go
Normal file
46
backend/internal/generation/company_symbols_test.go
Normal file
@ -0,0 +1,46 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func pointer(s string) *string { return &s }
|
||||
func TestYahooSymbolsUseResolvedPrimaryWithoutBloombergOrFIGI(t *testing.T) {
|
||||
assets := []models.UserAsset{
|
||||
{CompanyID: pointer("isin:KYG070341048"), Name: "Baidu, Inc.", Symbol: "OLD_BLOOMBERG", YahooSymbol: pointer("9888.HK")},
|
||||
{Symbol: "SSAAPL INDEX"}, {Symbol: "BBG000BBJQV0"}, {Symbol: "NVDA"}, {Symbol: "NVDA"},
|
||||
{CompanyID: pointer("isin:unknown"), Symbol: "CLIENT-SPOOF"},
|
||||
}
|
||||
if got := yahooSymbols(assets); !reflect.DeepEqual(got, []string{"9888.HK", "NVDA"}) {
|
||||
t.Fatalf("Yahoo input=%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
type symbolFeed struct{ symbols []string }
|
||||
|
||||
func (f *symbolFeed) Name() string { return "fake" }
|
||||
func (f *symbolFeed) Scrape(_ context.Context, s []string) ([]scraper.Article, error) {
|
||||
f.symbols = s
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestPerSourceCompanyHintsDoNotChangeOtherFeeds(t *testing.T) {
|
||||
yahoo, bloomberg, watcher := &symbolFeed{}, &symbolFeed{}, &symbolFeed{}
|
||||
input := UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 20, Assets: []models.UserAsset{{CompanyID: pointer("isin:company"), Name: "Company", Symbol: "HISTORIC INDEX", YahooSymbol: pointer("9888.HK")}}}
|
||||
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceWatcherGuru} {
|
||||
key := key
|
||||
input.Sources = append(input.Sources, models.Source{ID: key, SourceKey: &key, Enabled: true, ArticleLimit: 20})
|
||||
}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"owner": input}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, LayaRanker: &contractRanker{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: yahoo, models.SourceBloomberg: bloomberg, models.SourceWatcherGuru: watcher}})
|
||||
if _, err := uc.Generate(context.Background(), "owner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(yahoo.symbols, []string{"9888.HK"}) || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(watcher.symbols, bloomberg.symbols) {
|
||||
t.Fatalf("Yahoo=%v Bloomberg=%v Watcher=%v", yahoo.symbols, bloomberg.symbols, watcher.symbols)
|
||||
}
|
||||
}
|
||||
@ -168,7 +168,11 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
if feed == nil {
|
||||
err = fmt.Errorf("unavailable")
|
||||
} else {
|
||||
articles, err = feed.Scrape(ctx, append([]string(nil), symbols...))
|
||||
sourceSymbols := symbols
|
||||
if *source.SourceKey == models.SourceYahooFinance {
|
||||
sourceSymbols = yahooSymbols(input.Assets)
|
||||
}
|
||||
articles, err = feed.Scrape(ctx, append([]string(nil), sourceSymbols...))
|
||||
}
|
||||
if err != nil {
|
||||
stat.Status = "failed"
|
||||
|
||||
33
backend/internal/models/company_assets.go
Normal file
33
backend/internal/models/company_assets.go
Normal file
@ -0,0 +1,33 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/tradarr/backend/internal/companycatalog"
|
||||
)
|
||||
|
||||
// UpsertCompanyAsset never converts legacy rows. Each owner/company identity
|
||||
// has an independent follow, resolved from the trusted local catalogue.
|
||||
func (r *Repository) UpsertCompanyAsset(owner string, company companycatalog.Company) (*UserAsset, error) {
|
||||
tx, err := r.db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.Exec(`SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, owner); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a := &UserAsset{}
|
||||
err = tx.QueryRow(`INSERT INTO user_assets(user_id,symbol,name,figi,company_id,yahoo_symbol,company_exchange,company_country,company_mic)
|
||||
VALUES($1,$2::text,$3,NULLIF($4,''),$5,$2::text,$6,$7,$8)
|
||||
ON CONFLICT(user_id,company_id) WHERE company_id IS NOT NULL DO UPDATE SET
|
||||
symbol=EXCLUDED.symbol,name=EXCLUDED.name,figi=EXCLUDED.figi,yahoo_symbol=EXCLUDED.yahoo_symbol,
|
||||
company_exchange=EXCLUDED.company_exchange,company_country=EXCLUDED.company_country,company_mic=EXCLUDED.company_mic
|
||||
RETURNING id,user_id,symbol,name,figi,created_at,company_id,yahoo_symbol,company_exchange,company_country,company_mic`,
|
||||
owner, company.YahooSymbol, company.Name, company.FIGI, company.CompanyID, company.Exchange, company.Country, company.MIC).Scan(&a.ID, &a.UserID, &a.Symbol, &a.Name, &a.FIGI, &a.CreatedAt, &a.CompanyID, &a.YahooSymbol, &a.CompanyExchange, &a.CompanyCountry, &a.CompanyMIC)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
@ -22,6 +22,11 @@ type User struct {
|
||||
}
|
||||
|
||||
type UserAsset struct {
|
||||
CompanyID *string `json:"company_id"`
|
||||
YahooSymbol *string `json:"-"`
|
||||
CompanyExchange *string `json:"exchange,omitempty"`
|
||||
CompanyCountry *string `json:"country,omitempty"`
|
||||
CompanyMIC *string `json:"mic,omitempty"`
|
||||
FIGI *string `json:"figi"`
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
|
||||
@ -17,14 +17,18 @@ func scanAsset(row assetScanner) (*UserAsset, error) {
|
||||
}
|
||||
|
||||
func (r *Repository) GetUserAssets(userID string) ([]UserAsset, error) {
|
||||
rows, err := r.db.Query(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 ORDER BY symbol,created_at,id`, userID)
|
||||
rows, err := r.db.Query(`SELECT id,user_id,symbol,name,figi,created_at,
|
||||
to_jsonb(user_assets)->>'company_id',to_jsonb(user_assets)->>'yahoo_symbol',
|
||||
to_jsonb(user_assets)->>'company_exchange',to_jsonb(user_assets)->>'company_country',to_jsonb(user_assets)->>'company_mic'
|
||||
FROM user_assets WHERE user_id=$1 ORDER BY symbol,created_at,id`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
assets := []UserAsset{}
|
||||
for rows.Next() {
|
||||
a, err := scanAsset(rows)
|
||||
a := &UserAsset{}
|
||||
err := rows.Scan(&a.ID, &a.UserID, &a.Symbol, &a.Name, &a.FIGI, &a.CreatedAt, &a.CompanyID, &a.YahooSymbol, &a.CompanyExchange, &a.CompanyCountry, &a.CompanyMIC)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -62,19 +66,24 @@ func (r *Repository) UpsertUserAsset(userID, symbol, name string, figi *string)
|
||||
return a, tx.Commit()
|
||||
}
|
||||
if figi == nil {
|
||||
return finish(scanAsset(tx.QueryRow(`INSERT INTO user_assets(user_id,symbol,name,figi) VALUES($1,$2,$3,NULL)
|
||||
ON CONFLICT(user_id,symbol) WHERE figi IS NULL DO UPDATE SET name=EXCLUDED.name
|
||||
RETURNING id,user_id,symbol,name,figi,created_at`, userID, symbol, name)))
|
||||
existing, lookupErr := scanAsset(tx.QueryRow(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND symbol=$2 AND figi IS NULL AND to_jsonb(user_assets)->>'company_id' IS NULL`, userID, symbol))
|
||||
if lookupErr == nil {
|
||||
return finish(scanAsset(tx.QueryRow(`UPDATE user_assets SET name=$1 WHERE id=$2 AND user_id=$3 RETURNING id,user_id,symbol,name,figi,created_at`, name, existing.ID, userID)))
|
||||
}
|
||||
if lookupErr != sql.ErrNoRows {
|
||||
return nil, lookupErr
|
||||
}
|
||||
return finish(scanAsset(tx.QueryRow(`INSERT INTO user_assets(user_id,symbol,name,figi) VALUES($1,$2,$3,NULL) RETURNING id,user_id,symbol,name,figi,created_at`, userID, symbol, name)))
|
||||
}
|
||||
// A known FIGI remains canonical even when other rows share its symbol.
|
||||
a, err := scanAsset(tx.QueryRow(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND figi=$2`, userID, *figi))
|
||||
a, err := scanAsset(tx.QueryRow(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND figi=$2 AND to_jsonb(user_assets)->>'company_id' IS NULL`, userID, *figi))
|
||||
if err == nil {
|
||||
return finish(scanAsset(tx.QueryRow(`UPDATE user_assets SET symbol=$1,name=$2 WHERE id=$3 AND user_id=$4 RETURNING id,user_id,symbol,name,figi,created_at`, symbol, name, a.ID, userID)))
|
||||
}
|
||||
if err != sql.ErrNoRows {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := tx.Query(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND UPPER(BTRIM(symbol))=$2 FOR UPDATE`, userID, symbol)
|
||||
rows, err := tx.Query(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND UPPER(BTRIM(symbol))=$2 AND to_jsonb(user_assets)->>'company_id' IS NULL FOR UPDATE`, userID, symbol)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -107,7 +116,7 @@ func (r *Repository) UpsertUserAsset(userID, symbol, name string, figi *string)
|
||||
}
|
||||
|
||||
func (r *Repository) RemoveUserAsset(userID, symbol string) error {
|
||||
_, err := r.db.Exec(`DELETE FROM user_assets WHERE user_id=$1 AND symbol=$2 AND figi IS NULL`, userID, strings.ToUpper(strings.TrimSpace(symbol)))
|
||||
_, err := r.db.Exec(`DELETE FROM user_assets WHERE user_id=$1 AND symbol=$2 AND figi IS NULL AND to_jsonb(user_assets)->>'company_id' IS NULL`, userID, strings.ToUpper(strings.TrimSpace(symbol)))
|
||||
return err
|
||||
}
|
||||
func (r *Repository) RemoveUserAssetByID(userID, id string) error {
|
||||
|
||||
@ -7,6 +7,7 @@ import (
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/companycatalog"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
@ -18,6 +19,7 @@ import (
|
||||
)
|
||||
|
||||
type Dependencies struct {
|
||||
CompanyCatalog companycatalog.CompanyCatalog
|
||||
LayaRanker generation.LayaRanker
|
||||
Feeds map[string]scraper.Scraper
|
||||
IndexSearcher indices.IndexSearcher
|
||||
@ -47,6 +49,9 @@ func New(repo *models.Repository, cfg *config.Config, deps Dependencies) *App {
|
||||
h := handlers.New(repo, cfg, enc, registry, pipeline, sched)
|
||||
h.SetGenerationUseCase(uc)
|
||||
h.SetIndexSearcher(deps.IndexSearcher)
|
||||
if deps.CompanyCatalog != nil {
|
||||
h.SetCompanyCatalog(deps.CompanyCatalog)
|
||||
}
|
||||
return &App{Router: api.SetupRouter(h, cfg.JWTSecret), scheduler: sched}
|
||||
}
|
||||
func (a *App) Close() { a.scheduler.Stop() }
|
||||
|
||||
11
backend/scripts/company-catalog-requirements.txt
Normal file
11
backend/scripts/company-catalog-requirements.txt
Normal file
@ -0,0 +1,11 @@
|
||||
certifi==2026.11.20
|
||||
charset-normalizer==3.5.2
|
||||
idna==3.20
|
||||
numpy==2.4.6
|
||||
pandas==3.0.3
|
||||
polars==2.1.0
|
||||
polars-runtime-32==2.1.0
|
||||
python-dateutil==4.0.0
|
||||
requests==2.34.2
|
||||
tzdata==2026.6
|
||||
urllib3==2.8.0
|
||||
45
backend/scripts/company-catalog-upstream.json
Normal file
45
backend/scripts/company-catalog-upstream.json
Normal file
@ -0,0 +1,45 @@
|
||||
{
|
||||
"license_sha256": "dea317ce7193c52174ebb0def6df1a2f762f75b60e5bc026176fea6cf3ede4ff",
|
||||
"upstream_commit": "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1",
|
||||
"upstream_equities_data_sha256": "decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f",
|
||||
"upstream_source_sha256": {
|
||||
"financedatabase/__init__.py": "607e4c1f0f772d2f51f6004b06fe4a905441d29142fa1f06988f549ce5c8e794",
|
||||
"financedatabase/cache_model.py": "1372be4459874b7494c82a9ca8b869803bb843ef6ee5132df67f9f0a710a1e88",
|
||||
"financedatabase/categories_model.py": "f4f47fd5d90edc476f7ce2cf524977a0dc4115dfacfe2f914c6b3566900648f4",
|
||||
"financedatabase/cryptos/__init__.py": "896a0c2f55ea897a3f6c136c0e0e33118de0ff9274edccd9ae0bb29b26770d74",
|
||||
"financedatabase/cryptos/cryptos_controller.py": "953ff91ef8a8043987e2cf1d552332e6cb511f69aa85483186301fee0bb79fc2",
|
||||
"financedatabase/currencies/__init__.py": "c1884f7dbcc322ea64d210696fec6ed6508e05e63614f35523d8ea44fdc23adc",
|
||||
"financedatabase/currencies/currencies_controller.py": "a427110863e835e99ecd153d9b5d960520d6052e22aacff7ef0ad994c09b311d",
|
||||
"financedatabase/database_controller.py": "56b9db9cd3363a8993f13a19bb1530d3d77fef9c945acb75df4ca4c853d6e1d7",
|
||||
"financedatabase/equities/__init__.py": "55b8e55b48cf515b1ec3e3d1266550e3cf00f21fba584e4394cd2264dc4a84df",
|
||||
"financedatabase/equities/equities_controller.py": "0fd7d859fa2f43f7c3d43484a21a8d5ccfcdcb2276e2a4a1d1c94eb838b88bc5",
|
||||
"financedatabase/etfs/__init__.py": "5cb9a938a8130ed8a3af1c19095a5d896f809ca24c50f66586a67b31937304b9",
|
||||
"financedatabase/etfs/etfs_controller.py": "2944bb089470bafc149b94e6f1719081849be1aec62e702df59fe482a5fc51f0",
|
||||
"financedatabase/frame_model.py": "1e36264d193952a8ddd51ccd5ccc3b6ad1dea55b3c5041ad68112f2c29210386",
|
||||
"financedatabase/funds/__init__.py": "e67772c33f8130fa8867723f7b41efe7e9b776ea4107db81e399eaec136e369e",
|
||||
"financedatabase/funds/funds_controller.py": "9a282674b0ac1c5d925fd65955ac7d66899cd788c1dfc74379aacd2c12bf72a6",
|
||||
"financedatabase/helpers.py": "87946e2257254b6d6700716c27f6edc964bdb4aeba847cf958f0ec70a9f9bb49",
|
||||
"financedatabase/indices/__init__.py": "5f5915ef8e0d5e5ef4efe04139db3397ec2a59fc2b8c08e370685959aff51733",
|
||||
"financedatabase/indices/indices_controller.py": "d67f8b26b3d72de503fc62ae987021a6a9bed78a99bd30a6be203d742a7a514c",
|
||||
"financedatabase/listings_model.py": "44f9b99fda44019e09c37be241d2fd1cdcf52afd1a6b1d33eb7ac54b7132b48d",
|
||||
"financedatabase/mcp_server/__init__.py": "9df6de1448fd4d659e8463d6548c90b40b6c47f5492dffc5ceb2b585d3993c18",
|
||||
"financedatabase/mcp_server/__main__.py": "51796c03ba817474a84161ccbb3900838651acee63a47dec7e95a59d4815363a",
|
||||
"financedatabase/mcp_server/analytics_model.py": "426775e4d6c8d140b4cc009139ad5ce5e24b31bf32f8cb3dc1620676b8d418f5",
|
||||
"financedatabase/mcp_server/coercion_model.py": "c309112cd0e76c70e777613a9b9d0bd0c09f0f8522d24a72c1d2dcb0a4e9cdc7",
|
||||
"financedatabase/mcp_server/formatting_model.py": "2c3d32ec961352782894993b336c4ee58d47bf0ee25b762f5f5bd22688fde546",
|
||||
"financedatabase/mcp_server/mcp_controller.py": "fe1ebab3086b54855aeecffd4f43bd60257f5ae24fe0dbfdc0e3ea0242431dd7",
|
||||
"financedatabase/mcp_server/provider_model.py": "22bb45c6f192abbb29cf6aea8ee6b901a204d5960765ae7c10e575f002e9af55",
|
||||
"financedatabase/mcp_server/ranking_model.py": "f03e03de04fc719a0a4ec6beeeaadb261b403a1ad5b3abf057977af6cc924faa",
|
||||
"financedatabase/mcp_server/registry_model.py": "a4d4844268ef84fbcae1c82aa16e1ba4be34b0a295936661df13220dd3b4dd46",
|
||||
"financedatabase/mcp_server/setup_model.py": "69508873479ceacfbdb92a8bacfd988968c773b9adb67193dbcfee2d7acc92be",
|
||||
"financedatabase/mcp_server/site_model.py": "0cf95f37479086d6753653e382029ec8f2806e654e6d35e6dc611f75cb0e6a2f",
|
||||
"financedatabase/mcp_server/stats_page_model.py": "c53f4ee51851feb4050b8fb9724ea973c0b95305a205ee78456eb818dff6a9ca",
|
||||
"financedatabase/mcp_server/tools_model.py": "81cadc7360a3512503d0e126437fde168c7043e4578d7d7214bbba5c38d2cfd1",
|
||||
"financedatabase/moneymarkets/__init__.py": "d6e552766b18c4c577f730e23e622847f327d71cc0c8009140bdcd6384829cc8",
|
||||
"financedatabase/moneymarkets/moneymarkets_controller.py": "516f6db36f3cd5195cdbab70bda810575e0b875ce7b43e66087b5be6d336971f",
|
||||
"financedatabase/query_model.py": "a24ff8c88ffb4f5c4dcf7607e057e8b549b3d5f403539a821ca62935fd54e54b",
|
||||
"financedatabase/utilities/__init__.py": "8ae00bf057b5f6315fac4999e7a813d4b21696017b76246e44a08e20dc9dc282",
|
||||
"financedatabase/utilities/dataframe_model.py": "814cab4fca135b5c7b6f50818052c0a318f6bd8466338a8bead0c66270066aee",
|
||||
"financedatabase/utilities/logger_model.py": "9dcf03c9dca815a1d6a2d0b694f5937f98b4ede2a5e03abf36a19575b4387d92"
|
||||
}
|
||||
}
|
||||
114
backend/scripts/update-company-catalog.py
Normal file
114
backend/scripts/update-company-catalog.py
Normal file
@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit maintenance only. Never imported/called by the application.
|
||||
Run with pinned dependencies in company-catalog-requirements.txt and -E.
|
||||
--source-dir uses an already downloaded upstream checkout completely offline.
|
||||
--download explicitly downloads only the pinned official source archive.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import urllib.request
|
||||
|
||||
COMMIT = "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1"
|
||||
DATA_HASH = "decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f"
|
||||
FIELDS = "symbol name exchange mic country isin figi composite_figi delisted listing_score primary_listing main_venue listings usual_currency home_known".split()
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def digest(content):
|
||||
return hashlib.sha256(content).hexdigest()
|
||||
|
||||
def generate(source, destination):
|
||||
parquet = source / "compression/equities.parquet"
|
||||
if digest(parquet.read_bytes()) != DATA_HASH:
|
||||
raise SystemExit("Pinned equities parquet hash mismatch")
|
||||
lock = json.loads((ROOT / "scripts/company-catalog-upstream.json").read_text())
|
||||
if lock["upstream_commit"] != COMMIT or lock["upstream_equities_data_sha256"] != DATA_HASH:
|
||||
raise SystemExit("Upstream lock and generator constants disagree")
|
||||
for name, expected in lock["upstream_source_sha256"].items():
|
||||
if digest((source / name).read_bytes()) != expected:
|
||||
raise SystemExit("Pinned upstream source hash mismatch")
|
||||
if digest((source / "LICENSE").read_bytes()) != lock["license_sha256"]:
|
||||
raise SystemExit("Pinned upstream license hash mismatch")
|
||||
# The upstream selector is run over local data; refuse Python network access.
|
||||
def deny(*args, **kwargs):
|
||||
raise RuntimeError("Network forbidden while selecting the local snapshot")
|
||||
socket.socket.connect = deny
|
||||
socket.create_connection = deny
|
||||
os.environ.setdefault("POLARS_MAX_THREADS", "4")
|
||||
sys.path.insert(0, str(source))
|
||||
import financedatabase as fd
|
||||
import polars as pl
|
||||
equities = fd.Equities(use_local_location=True)
|
||||
selected = equities.select(only_primary_listing=True, exclude_delisted=True, as_pandas=False)
|
||||
rows = selected.join(equities.get_listing_ranks(), on="symbol", how="left").select(FIELDS).sort("symbol")
|
||||
if rows.height != 47735:
|
||||
raise SystemExit(f"Unexpected primary equity count {rows.height}, expected 47735")
|
||||
targets = {"NVDA": "NVIDIA Corporation", "AAPL": "Apple Inc.", "9888.HK": "Baidu, Inc.", "002594.SZ": "BYD Company Limited", "0285.HK": "BYD Electronic (International) Company Limited"}
|
||||
for symbol, name in targets.items():
|
||||
match = rows.filter(pl.col("symbol") == symbol)
|
||||
if match.height != 1 or match["name"][0] != name:
|
||||
raise SystemExit("Pinned primary target mismatch")
|
||||
content = rows.write_csv().encode("utf-8")
|
||||
identities = {}
|
||||
unidentified = 0
|
||||
for row in rows.iter_rows(named=True):
|
||||
identity = "isin:" + row["isin"] if row["isin"] else ("figi:" + row["figi"] if row["figi"] else None)
|
||||
if identity:
|
||||
identities[identity] = identities.get(identity, 0) + 1
|
||||
else:
|
||||
unidentified += 1
|
||||
manifest = {
|
||||
"runtime_resolvable_identities": len(identities),
|
||||
"rows_without_stable_identity": unidentified,
|
||||
"identities_with_multiple_primary_rows": sum(count > 1 for count in identities.values()),
|
||||
"runtime_identity_policy": "ISIN else FIGI; group identical identity; highest upstream listing_score; equal-score primary rows use symbol lexical tie-break for a deterministic representative; unidentified rows remain embedded but are not searchable/followable.",
|
||||
"upstream_repository": "https://github.com/JerBouma/FinanceDatabase",
|
||||
"upstream_commit": COMMIT,
|
||||
"upstream_commit_date_utc": "2026-11-17T13:27:37Z",
|
||||
"package_version": "2.5.2", "license": "MIT",
|
||||
"upstream_equities_data_file": "compression/equities.parquet",
|
||||
"upstream_equities_data_sha256": DATA_HASH,
|
||||
"selection": "Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True, as_pandas=False); join get_listing_ranks(); sort symbol",
|
||||
"primary_listing_evidence": "Unmodified commit-pinned upstream listings_model over the complete local Equities data; no ticker heuristic or provider API.",
|
||||
"records": rows.height, "snapshot": "equities_primary.csv", "sha256": digest(content),
|
||||
"fields": FIELDS,
|
||||
"upstream_source_sha256": {str(p.relative_to(source)): digest(p.read_bytes()) for p in sorted((source / "financedatabase").rglob("*.py"))},
|
||||
"license_sha256": digest((source / "LICENSE").read_bytes()),
|
||||
}
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
# Generate everything before replacing existing artifacts; no cache purge.
|
||||
with tempfile.TemporaryDirectory(dir=destination) as staging:
|
||||
stage = Path(staging)
|
||||
(stage / "equities_primary.csv").write_bytes(content)
|
||||
(stage / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
shutil.copyfile(source / "LICENSE", stage / "FINANCEDATABASE_LICENSE")
|
||||
for name in ("equities_primary.csv", "manifest.json", "FINANCEDATABASE_LICENSE"):
|
||||
os.replace(stage / name, destination / name)
|
||||
print(f"Equity primary snapshot: {rows.height} records; sha256={digest(content)}")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
group = parser.add_mutually_exclusive_group(required=True)
|
||||
group.add_argument("--source-dir", type=Path)
|
||||
group.add_argument("--download", action="store_true")
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "internal/companycatalog/data")
|
||||
args = parser.parse_args()
|
||||
if args.source_dir:
|
||||
generate(args.source_dir.resolve(), args.output)
|
||||
else:
|
||||
with tempfile.TemporaryDirectory(prefix="company-catalog-", dir=os.environ.get("IDEA_MANAGED_TMP") or os.environ.get("TMPDIR")) as work:
|
||||
archive = urllib.request.urlopen(f"https://codeload.github.com/JerBouma/FinanceDatabase/tar.gz/{COMMIT}", timeout=120).read()
|
||||
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar:
|
||||
tar.extractall(work, filter="data")
|
||||
generate(Path(work) / f"FinanceDatabase-{COMMIT}", args.output)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -83,3 +83,14 @@ Les quotas Search/Filter sont partagés par clé ou IP : 5/minute sans clé, 20/
|
||||
La migration 000016 crée `ai_provider_models`, la préférence nullable et les colonnes de snapshot. Elle backfille les comptes existants selon la configuration autrefois effective : provider summary explicite valide, sinon provider actif unique ; override modèle, sinon modèle configuré. Les anciens defaults de constructeurs sont matérialisés une seule fois si le champ modèle était vide. Aucune telle résolution globale n’a lieu après migration. Une configuration active ambiguë échoue atomiquement. Sans provider effectif, les comptes restent sans sélection. Les providers, clés, paramètres historiques et anciens contenus ne sont pas réécrits. Les nouvelles synthèses snapshotent la paire réellement résolue ; les anciennes gardent des snapshots NULL.
|
||||
|
||||
Les POST `/api/reports` et `/api/reports/:id/messages` renvoient 410 sans lecture du corps ni écriture. GET/list/delete restent owner-scoped. Les anciennes tâches `generating`, qui ne peuvent plus reprendre, sont projetées en état d’erreur/interruption dans les réponses de lecture, sans mise à jour de la base. Aucune purge de rapports/conversations et aucun appel provider report.
|
||||
|
||||
|
||||
## Catalogue sociétés et migration 000017
|
||||
|
||||
Le catalogue FinanceDatabase Equity/primary est embarqué dans le binaire : aucune clé, API, requête fournisseur ou tâche de rafraîchissement au runtime. Voir [la provenance, licence MIT, limites et procédure reproductible](../backend/internal/companycatalog/README.md). Le snapshot complet contient 47 735 lignes ; 43 126 identités sont résolubles après exclusion des lignes sans ISIN/FIGI et regroupement des listings primaires d'une même identité. Les deux sociétés BYD restent distinctes. Les anciennes routes indices et l'ajout legacy sont conservés.
|
||||
|
||||
`GET /api/companies/search` nécessite un JWT : `q` est un nom de 1 à 100 caractères, limite 1–20 (défaut 10). La réponse contient `company_id`, nom, pays, place et MIC, sans ticker/symbole/FIGI séparé. `POST /api/me/assets` avec `company_id` résout nom et identité localement ; les champs d'identité client sont ignorés. Une identité inconnue renvoie 400 sans écriture, un catalogue indisponible 503. L'ajout répété renvoie 201 avec le même suivi pour le même propriétaire.
|
||||
|
||||
La migration 000017 transactionnelle ajoute des colonnes nullable (`company_id`, `yahoo_symbol`, désambiguïsation) et une unicité propriétaire/société ; elle sépare les index uniques legacy afin de conserver un ancien suivi indépendamment du nouveau. Aucun ancien actif n'est converti, effacé ou renommé. Le rollback automatique est refusé pour éviter de perdre cette identité ou fusionner des lignes : une réconciliation explicite/sauvegarde est nécessaire. Yahoo reçoit le listing Yahoo résolu pour les nouveaux suivis ; les labels Bloomberg et FIGI sont filtrés dans les anciens hints Yahoo, sans conversion inventée. Les entrées transmises aux récupérateurs Bloomberg et WatcherGuru restent inchangées.
|
||||
|
||||
Les diagnostics Yahoo et WatcherGuru ne journalisent plus de corps HTTP. Yahoo indique symbole/hint assaini, statut, nombre d'articles et résultat ; WatcherGuru indique chaque tentative RSS (étiquette de chemin fixe) et HTML, statut, nombre d'articles et résultat. Les échecs avant réception portent statut 0. Aucun titre, contenu, URL complète ou secret n'est ajouté aux logs. Les tests injectent exclusivement des transports factices ; l'extraction et la séquence de fallback existantes restent inchangées.
|
||||
|
||||
@ -68,7 +68,7 @@ export function readStackManifest() {
|
||||
if (!manifest.bootstrapAdmin?.email || !manifest.bootstrapAdmin?.password) {
|
||||
throw new Error('E2E fake stack manifest must provide disposable bootstrap admin credentials.')
|
||||
}
|
||||
for (const field of ['indexQuery', 'indexName', 'indexSymbol', 'indexFIGI', 'summaryModelID', 'summarySentinel', 'articleTitle', 'articleURL', 'articleContent', 'candidateID']) {
|
||||
for (const field of ['companyQuery', 'companyID', 'companyName', 'companySymbol', 'companyFIGI', 'summaryModelID', 'summarySentinel', 'articleTitle', 'articleURL', 'articleContent', 'candidateID']) {
|
||||
if (typeof manifest.fixtures?.[field] !== 'string' || !manifest.fixtures[field]) {
|
||||
throw new Error(`E2E fake stack manifest is missing fixtures.${field}.`)
|
||||
}
|
||||
|
||||
@ -35,7 +35,7 @@ async function login(page, baseURL, email, password) {
|
||||
await expect(page).toHaveURL(new URL('/', baseURL).href)
|
||||
}
|
||||
|
||||
test('admin creates a user who follows a fake index and generates a private summary without article/job writes', async ({ page, request }) => {
|
||||
test('admin creates a user who follows a fake company and generates a private summary without article/job writes', async ({ page, request }) => {
|
||||
const stack = readStackManifest()
|
||||
await page.context().route('**/*', async route => {
|
||||
const host = new URL(route.request().url()).hostname
|
||||
@ -60,17 +60,45 @@ test('admin creates a user who follows a fake index and generates a private summ
|
||||
await page.getByRole('button', { name: 'Déconnexion' }).click()
|
||||
})
|
||||
|
||||
await test.step('new user login and explicit fake OpenFIGI selection', async () => {
|
||||
let companySearchRequest
|
||||
let companyFollowRequest
|
||||
page.on('request', request => {
|
||||
const url = new URL(request.url())
|
||||
if (url.pathname === '/api/companies/search') companySearchRequest = url
|
||||
if (url.pathname === '/api/me/assets' && request.method() === 'POST') companyFollowRequest = request.postDataJSON()
|
||||
})
|
||||
|
||||
await test.step('new user searches by company name and follows the selected local catalog company', async () => {
|
||||
await login(page, baseURL, email, password)
|
||||
|
||||
// Seed a pre-existing legacy follow through the compatibility API so the
|
||||
// real Watchlist page can prove it remains present after a company follow.
|
||||
const token = await page.evaluate(() => localStorage.getItem('token'))
|
||||
const legacy = await request.post(new URL('/api/me/assets', stack.apiUrl).href, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
data: { symbol: 'LEGACYIDX', name: 'Historic index follow' },
|
||||
})
|
||||
expect(legacy.status()).toBe(201)
|
||||
|
||||
await page.goto(new URL('/assets', baseURL).href)
|
||||
const query = page.getByRole('textbox', { name: 'Nom ou symbole' })
|
||||
await query.fill(fixture.indexQuery)
|
||||
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" })
|
||||
await query.fill(fixture.companyQuery)
|
||||
await page.getByRole('button', { name: 'Rechercher' }).click()
|
||||
const results = page.getByRole('region', { name: 'Résultats de recherche' })
|
||||
await expect(results.getByText(fixture.indexName)).toBeVisible()
|
||||
await expect(results.getByText(fixture.indexSymbol)).toBeVisible()
|
||||
await results.getByRole('button', { name: 'Suivre cet indice' }).click()
|
||||
await expect(page.getByRole('region', { name: 'Indices suivis' })).toContainText(fixture.indexSymbol)
|
||||
const results = page.getByRole('region', { name: 'Résultats des entreprises' })
|
||||
await expect(results.getByText(fixture.companyName)).toBeVisible()
|
||||
await expect(results).toContainText('E2E Country')
|
||||
for (const privateValue of [fixture.companySymbol, fixture.companyFIGI, fixture.companyID]) {
|
||||
await expect(results.getByText(privateValue, { exact: false })).toHaveCount(0)
|
||||
}
|
||||
await results.getByRole('button', { name: 'Suivre cette entreprise' }).click()
|
||||
await expect(page.getByRole('region', { name: 'Entreprises suivies' })).toContainText(fixture.companyName)
|
||||
await expect(oldFollows).toContainText('Historic index follow')
|
||||
await expect(companySearchRequest?.pathname).toBe('/api/companies/search')
|
||||
await expect(companySearchRequest?.searchParams.get('q')).toBe(fixture.companyQuery)
|
||||
await expect(companySearchRequest?.searchParams.get('limit')).toBe('20')
|
||||
expect(companyFollowRequest).toEqual({ company_id: fixture.companyID })
|
||||
})
|
||||
|
||||
await test.step('user saves language and ranking preferences', async () => {
|
||||
@ -105,7 +133,9 @@ test('admin creates a user who follows a fake index and generates a private summ
|
||||
const response = await request.get(new URL(stack.fakeAuditPath, stack.fakeControlUrl).href)
|
||||
expect(response.ok()).toBeTruthy()
|
||||
const events = await response.json()
|
||||
expect(events.openfigiSearches).toBeGreaterThan(0)
|
||||
expect(events.openfigiSearches).toBe(0)
|
||||
expect(events.companySearches).toBeGreaterThan(0)
|
||||
expect(events.companyResolutions).toBeGreaterThan(0)
|
||||
expect(events.scraperCalls).toBeGreaterThan(0)
|
||||
expect(events.layaRankingCalls).toBeGreaterThan(0)
|
||||
expect(events.layaSummaryCalls).toBeGreaterThan(0)
|
||||
|
||||
67
frontend/e2e/ticket19-company-watchlist.spec.mjs
Normal file
67
frontend/e2e/ticket19-company-watchlist.spec.mjs
Normal file
@ -0,0 +1,67 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { readStackManifest } from './stack-manifest.mjs'
|
||||
|
||||
async function login(page, baseURL, email, password) {
|
||||
await page.goto(new URL('/login', baseURL).href)
|
||||
await page.getByLabel('Adresse email').fill(email)
|
||||
await page.getByLabel('Mot de passe').fill(password)
|
||||
await page.getByRole('button', { name: 'Se connecter' }).click()
|
||||
await expect(page).toHaveURL(new URL('/', baseURL).href)
|
||||
}
|
||||
|
||||
test('ticket #19: search companies by name and follow by company_id while preserving legacy assets', async ({ page }) => {
|
||||
const stack = readStackManifest()
|
||||
await page.context().route('**/*', async route => {
|
||||
const host = new URL(route.request().url()).hostname
|
||||
if (host !== '127.0.0.1' && host !== '[::1]') return route.abort('blockedbyclient')
|
||||
return route.continue()
|
||||
})
|
||||
await login(page, stack.frontendUrl, stack.bootstrapAdmin.email, stack.bootstrapAdmin.password)
|
||||
|
||||
const oldAsset = {
|
||||
id: 'historical-index-19', user_id: 'ticket19-admin', symbol: 'OLDX',
|
||||
name: 'Historic S&P index', figi: null, created_at: '2025-01-01T00:00:00.000Z',
|
||||
}
|
||||
const companies = [
|
||||
{ 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' },
|
||||
]
|
||||
let followedBody
|
||||
let searchURL
|
||||
await page.route('**/api/me/assets', async route => {
|
||||
if (route.request().method() === 'GET') return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: [oldAsset] }) })
|
||||
if (route.request().method() === 'POST') {
|
||||
followedBody = route.request().postDataJSON()
|
||||
return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ data: { id: 'followed-byd', user_id: oldAsset.user_id, company_id: 'isin:CNE100001526', name: 'BYD Company Limited' } }) })
|
||||
}
|
||||
return route.continue()
|
||||
})
|
||||
await page.route('**/api/companies/search?**', async route => {
|
||||
searchURL = new URL(route.request().url())
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: companies }) })
|
||||
})
|
||||
|
||||
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 })
|
||||
await expect(page.getByRole('textbox')).toHaveCount(1)
|
||||
await query.fill('BYD')
|
||||
await page.getByRole('button', { name: /rechercher/i }).click()
|
||||
const results = page.getByRole('region', { name: /résultats des entreprises/i })
|
||||
const byd = results.getByText('BYD Company Limited').locator('..')
|
||||
await expect(byd).toContainText('Shenzhen Stock Exchange')
|
||||
await expect(byd).toContainText('China')
|
||||
await expect(results.getByText('BYD Electronic (International) Company Limited')).toBeVisible()
|
||||
for (const privateValue of ['002594.SZ', '0285.HK', 'BBG001QVK2K1', 'BBG000JPLTR7']) {
|
||||
await expect(results.getByText(privateValue, { exact: false })).toHaveCount(0)
|
||||
}
|
||||
await expect(page.getByRole('region', { name: /actifs historiques/i })).toContainText('Historic S&P index')
|
||||
|
||||
await byd.getByRole('button', { name: /suivre/i }).click()
|
||||
await expect.poll(() => followedBody).toEqual({ company_id: 'isin:CNE100001526' })
|
||||
expect(Object.keys(followedBody)).toEqual(['company_id'])
|
||||
await expect(page.getByRole('region', { name: /actifs historiques/i })).toContainText('Historic S&P index')
|
||||
expect(searchURL?.pathname).toBe('/api/companies/search')
|
||||
expect(searchURL?.searchParams.get('q')).toBe('BYD')
|
||||
expect(searchURL?.searchParams.get('limit')).toBe('20')
|
||||
})
|
||||
@ -1,12 +1,17 @@
|
||||
import { api } from './client'
|
||||
|
||||
export interface Asset { id: string; user_id: string; symbol: string; name: string; figi: string | null; created_at: string }
|
||||
export interface IndexSearchResult { figi: string; name: string; symbol: string; market?: string }
|
||||
export interface FollowAsset { symbol: string; name: string; figi?: string | null }
|
||||
export interface Asset {
|
||||
id: string; user_id: string; symbol: string; name: string; figi: string | null; created_at: string
|
||||
company_id?: string | null; country?: string; exchange?: string
|
||||
}
|
||||
export interface CompanySearchResult {
|
||||
company_id: string; name: string; exchange: string; country: string; mic: string
|
||||
}
|
||||
export interface FollowAsset { company_id: string }
|
||||
|
||||
export const assetsApi = {
|
||||
list: () => api.get<Asset[]>('/me/assets'),
|
||||
search: (query: string, limit = 20) => api.get<IndexSearchResult[]>(`/indices/search?${new URLSearchParams({ q: query, limit: String(limit) })}`),
|
||||
add: (asset: FollowAsset) => api.post<Asset>('/me/assets', asset),
|
||||
search: (query: string, limit = 20) => api.get<CompanySearchResult[]>(`/companies/search?${new URLSearchParams({ q: query, limit: String(limit) })}`),
|
||||
add: (asset: FollowAsset) => api.post<Asset>('/me/assets', { company_id: asset.company_id }),
|
||||
remove: (id: string) => api.delete<void>(`/me/assets/${encodeURIComponent(id)}`),
|
||||
}
|
||||
|
||||
@ -5,7 +5,7 @@ import { cn } from '@/lib/cn'
|
||||
|
||||
const items = [
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Synthèses' },
|
||||
{ to: '/assets', icon: Star, label: 'Indices suivis' },
|
||||
{ to: '/assets', icon: Star, label: 'Entreprises suivies' },
|
||||
{ to: '/reports', icon: FileText, label: 'Rapports' },
|
||||
{ to: '/preferences', icon: Settings, label: 'Mes préférences' },
|
||||
]
|
||||
|
||||
@ -5,7 +5,7 @@ import { cn } from '@/lib/cn'
|
||||
|
||||
const navItems = [
|
||||
{ to: '/', icon: LayoutDashboard, label: 'Synthèses' },
|
||||
{ to: '/assets', icon: Star, label: 'Indices suivis' },
|
||||
{ to: '/assets', icon: Star, label: 'Entreprises suivies' },
|
||||
{ to: '/preferences', icon: Settings, label: 'Mes préférences' },
|
||||
{ to: '/reports', icon: FileText, label: 'Rapports' },
|
||||
]
|
||||
|
||||
@ -1,164 +1,191 @@
|
||||
import { useState, useEffect, useRef, useCallback, type FormEvent } from 'react'
|
||||
import { assetsApi, type Asset, type IndexSearchResult } from '@/api/assets'
|
||||
import { assetsApi, type Asset, type CompanySearchResult } from '@/api/assets'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
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.',
|
||||
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.',
|
||||
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',
|
||||
followed: 'Entreprise suivie.', followError: 'Impossible de suivre cette entreprise. Vos suivis sont conservés.',
|
||||
conflict: 'Ce suivi ne peut pas être ajouté pour le moment. Aucun suivi existant n’a été modifié.',
|
||||
removed: 'Entreprise retirée des suivis.', removeError: 'Impossible de retirer cette entreprise. Votre liste est conservée.',
|
||||
undo: 'Annuler le retrait', undone: 'Retrait annulé.', undoError: 'Impossible d’annuler le retrait. Vous pouvez réessayer.',
|
||||
loading: 'Chargement des entreprises suivies…', loadError: 'Impossible de charger vos entreprises suivies.', reload: 'Recharger la liste', busy: 'Mise à jour des suivis…',
|
||||
noFollowed: 'Aucune entreprise suivie. Recherchez puis choisissez une entreprise pour commencer.',
|
||||
legacy: 'Autres suivis existants', legacyRegion: 'Autres suivis existants — actifs historiques',
|
||||
legacyHelp: 'Vos indices et autres suivis existants sont conservés sans conversion. Cette section est en lecture seule.', unknown: 'Suivi existant sans nom renseigné',
|
||||
},
|
||||
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.',
|
||||
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',
|
||||
followed: 'Company followed.', followError: 'Unable to follow this company. Existing follows are preserved.',
|
||||
conflict: 'This company cannot be followed right now. No existing follows were changed.',
|
||||
removed: 'Company unfollowed.', removeError: 'Unable to unfollow this company. Your list is preserved.',
|
||||
undo: 'Undo unfollow', undone: 'Unfollow undone.', undoError: 'Unable to undo. Please try again.',
|
||||
loading: 'Loading followed companies…', loadError: 'Unable to load your followed companies.', reload: 'Reload list', busy: 'Updating follows…',
|
||||
noFollowed: 'No followed companies. Search for and choose a company to get started.',
|
||||
legacy: 'Other existing follows', legacyRegion: 'Other existing follows — historical assets',
|
||||
legacyHelp: 'Your indices and other existing follows are preserved without conversion. This section is read-only.', unknown: 'Existing follow with no recorded name',
|
||||
},
|
||||
}
|
||||
|
||||
function errorStatus(error: unknown) {
|
||||
return error && typeof error === 'object' && 'status' in error ? error.status : undefined
|
||||
}
|
||||
|
||||
function AssetList({ items, busy, onRemove }: { items: Asset[]; busy: boolean; onRemove: (asset: Asset) => void }) {
|
||||
return <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{items.map(asset => (
|
||||
<li key={asset.id} className="rounded-md border p-4 space-y-2 min-w-0">
|
||||
<p className="font-medium break-words">{asset.name || asset.symbol}</p>
|
||||
<p className="font-mono break-all">{asset.symbol}</p>
|
||||
{!asset.figi && <p className="text-sm text-muted-foreground">Type non vérifié</p>}
|
||||
<Button variant="outline" disabled={busy} onClick={() => onRemove(asset)} aria-label={`Ne plus suivre ${asset.name || asset.symbol}`}>Ne plus suivre</Button>
|
||||
</li>
|
||||
))}</ul>
|
||||
function CompanyInfo({ company }: { company: Pick<Asset, 'name' | 'country' | 'exchange'> }) {
|
||||
return <>
|
||||
<p className="font-semibold break-words">{company.name}</p>
|
||||
<div className="text-sm text-muted-foreground flex flex-wrap gap-x-3 gap-y-1">
|
||||
{company.country && <span>{company.country}</span>}
|
||||
{company.exchange && <span>{company.exchange}</span>}
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
|
||||
|
||||
export function Watchlist() {
|
||||
const [language, setLanguage] = useState<'fr' | 'en'>('fr')
|
||||
const text = copy[language]
|
||||
const [assets, setAssets] = useState<Asset[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [listError, setListError] = useState('')
|
||||
const [listError, setListError] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState<IndexSearchResult[] | null>(null)
|
||||
const [results, setResults] = useState<CompanySearchResult[] | null>(null)
|
||||
const [searching, setSearching] = useState(false)
|
||||
const [searchError, setSearchError] = useState('')
|
||||
const [actionError, setActionError] = useState('')
|
||||
const [notice, setNotice] = useState('')
|
||||
const [searchError, setSearchError] = useState<keyof typeof copy.fr | null>(null)
|
||||
const [actionError, setActionError] = useState<keyof typeof copy.fr | null>(null)
|
||||
const [notice, setNotice] = useState<keyof typeof copy.fr | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [removed, setRemoved] = useState<Asset | null>(null)
|
||||
const searchRevision = useRef(0)
|
||||
const mutationPending = useRef(false)
|
||||
const legacy = assets.filter(asset => !asset.figi)
|
||||
const followed = assets.filter(asset => asset.figi)
|
||||
const legacy = assets.filter(asset => !asset.company_id)
|
||||
const followed = assets.filter(asset => asset.company_id)
|
||||
|
||||
const load = useCallback(() => {
|
||||
return assetsApi.list().then(data => setAssets(data ?? []))
|
||||
.catch(() => setListError('Impossible de charger vos indices suivis.'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
const load = useCallback(() => assetsApi.list().then(data => { setAssets(data ?? []); setListError(false) })
|
||||
.catch(() => setListError(true)).finally(() => setLoading(false)), [])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
return () => { searchRevision.current += 1 }
|
||||
}, [load])
|
||||
|
||||
async function search(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
async function search(event?: FormEvent) {
|
||||
event?.preventDefault()
|
||||
const value = query.trim()
|
||||
if (!value || value.length > 100) return
|
||||
if (!value || value.length > 100 || searching) return
|
||||
const revision = ++searchRevision.current
|
||||
setSearching(true); setSearchError(''); setActionError(''); setResults(null)
|
||||
setSearching(true); setSearchError(null); setActionError(null); setResults(null)
|
||||
try {
|
||||
const data = await assetsApi.search(value, 20)
|
||||
if (revision === searchRevision.current) setResults((data ?? []).slice(0, 20))
|
||||
} catch (error) {
|
||||
if (revision !== searchRevision.current) return
|
||||
const status = errorStatus(error)
|
||||
setSearchError(status === 429 ? 'Quota de recherche atteint. Réessayez plus tard.'
|
||||
: status === 504 ? 'Le délai de recherche est dépassé. Vous pouvez relancer la recherche.'
|
||||
: status === 502 ? 'Le fournisseur de recherche est indisponible. Réessayez plus tard.'
|
||||
: 'Impossible de rechercher des indices. Vous pouvez relancer la recherche.')
|
||||
setSearchError(status === 429 ? 'quota' : status === 504 ? 'timeout' : status === 502 ? 'unavailable' : 'searchError')
|
||||
} finally { if (revision === searchRevision.current) setSearching(false) }
|
||||
}
|
||||
|
||||
function store(asset: Asset) {
|
||||
setAssets(current => [...current.filter(item => item.id !== asset.id && (!asset.figi || item.figi !== asset.figi)), asset])
|
||||
// Only replace the same company follow. Never merge or convert a legacy row.
|
||||
setAssets(current => [...current.filter(item => item.company_id !== asset.company_id || !item.company_id), asset])
|
||||
}
|
||||
|
||||
async function follow(index: IndexSearchResult) {
|
||||
async function follow(company: CompanySearchResult) {
|
||||
if (mutationPending.current) return
|
||||
mutationPending.current = true
|
||||
setBusy(true); setActionError(''); setNotice('')
|
||||
setBusy(true); setActionError(null); setNotice(null)
|
||||
try {
|
||||
store(await assetsApi.add({ symbol: index.symbol, name: index.name, figi: index.figi }))
|
||||
setNotice(`${index.name} est maintenant suivi.`)
|
||||
} catch (error) {
|
||||
setActionError(errorStatus(error) === 409
|
||||
? 'Cet indice correspond à un actif historique ambigu. Aucun suivi n’a été modifié.'
|
||||
: 'Impossible de suivre cet indice. Vos indices suivis sont conservés.')
|
||||
} finally { mutationPending.current = false; setBusy(false) }
|
||||
const asset = await assetsApi.add({ company_id: company.company_id })
|
||||
store({ ...asset, name: company.name, company_id: company.company_id, country: company.country, exchange: company.exchange })
|
||||
setNotice('followed')
|
||||
} catch (error) { setActionError(errorStatus(error) === 409 ? 'conflict' : 'followError') }
|
||||
finally { mutationPending.current = false; setBusy(false) }
|
||||
}
|
||||
|
||||
async function remove(asset: Asset) {
|
||||
if (mutationPending.current) return
|
||||
if (!asset.company_id || mutationPending.current) return
|
||||
mutationPending.current = true
|
||||
setBusy(true); setActionError(''); setSearchError(''); setNotice('')
|
||||
setBusy(true); setActionError(null); setSearchError(null); setNotice(null)
|
||||
try {
|
||||
await assetsApi.remove(asset.id)
|
||||
setAssets(current => current.filter(item => item.id !== asset.id))
|
||||
setRemoved(asset); setNotice(`${asset.name || asset.symbol} n’est plus suivi.`)
|
||||
} catch { setActionError('Impossible de retirer cet actif. Votre liste est conservée.') }
|
||||
setRemoved(asset); setNotice('removed')
|
||||
} catch { setActionError('removeError') }
|
||||
finally { mutationPending.current = false; setBusy(false) }
|
||||
}
|
||||
|
||||
async function undo() {
|
||||
if (!removed || mutationPending.current) return
|
||||
if (!removed?.company_id || mutationPending.current) return
|
||||
mutationPending.current = true
|
||||
setBusy(true); setActionError('')
|
||||
setBusy(true); setActionError(null); setNotice(null)
|
||||
try {
|
||||
store(await assetsApi.add({ symbol: removed.symbol, name: removed.name, ...(removed.figi ? { figi: removed.figi } : {}) }))
|
||||
setRemoved(null); setNotice('Retrait annulé.')
|
||||
} catch { setActionError('Impossible d’annuler le retrait. Vous pouvez réessayer.') }
|
||||
const asset = await assetsApi.add({ company_id: removed.company_id })
|
||||
store({ ...removed, ...asset, name: asset.name || removed.name, company_id: removed.company_id })
|
||||
setRemoved(null); setNotice('undone')
|
||||
} catch { setActionError('undoError') }
|
||||
finally { mutationPending.current = false; setBusy(false) }
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
<h1 className="text-2xl font-bold">Indices suivis</h1>
|
||||
<p>Recherchez un indice avec OpenFIGI, choisissez le résultat puis suivez-le. Aucune génération de synthèse n’est lancée automatiquement.</p>
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Rechercher un indice</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
return <div lang={language} className="p-4 md:p-6 space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-2xl font-bold">{text.title}</h1>
|
||||
<div className="space-y-1"><Label htmlFor="watchlist-language">Langue / Language</Label><Select id="watchlist-language" value={language} onChange={event => setLanguage(event.target.value as 'fr' | 'en')}>
|
||||
<option value="fr">Français</option><option value="en">English</option>
|
||||
</Select></div>
|
||||
</div>
|
||||
<p>{text.intro}</p>
|
||||
<Card><CardHeader><CardTitle>{text.searchTitle}</CardTitle></CardHeader><CardContent className="space-y-4">
|
||||
<form onSubmit={search} className="flex flex-wrap items-end gap-3">
|
||||
<div className="flex-1 min-w-0 space-y-1.5">
|
||||
<Label htmlFor="index-query">Nom ou symbole</Label>
|
||||
<Input id="index-query" maxLength={100} required value={query} aria-describedby="index-search-help" onChange={event => {
|
||||
setQuery(event.target.value); searchRevision.current += 1; setSearching(false); setResults(null); setSearchError('')
|
||||
<div className="flex-1 min-w-0 space-y-1.5"><Label htmlFor="company-query">{text.query}</Label>
|
||||
<Input id="company-query" maxLength={100} required value={query} aria-describedby="company-search-help" onChange={event => {
|
||||
setQuery(event.target.value); searchRevision.current += 1; setSearching(false); setResults(null); setSearchError(null)
|
||||
}} />
|
||||
</div>
|
||||
<Button type="submit" disabled={!query.trim() || searching}>Rechercher</Button>
|
||||
<Button type="submit" disabled={!query.trim() || searching}>{text.search}</Button>
|
||||
</form>
|
||||
<p id="index-search-help" className="text-sm text-muted-foreground">La recherche utilise le quota OpenFIGI uniquement au clic sur Rechercher ou avec Entrée. Choisissez explicitement parmi les 20 résultats maximum.</p>
|
||||
{searchError && <p role="alert">{searchError}</p>}
|
||||
<section aria-label="Résultats de recherche" aria-busy={searching} className="space-y-3">
|
||||
{searching ? <p role="status">Recherche en cours…</p> : results === null ? <p>Saisissez un nom ou un symbole, puis lancez la recherche.</p> : results.length === 0 ? <p role="status">Aucun indice trouvé. Essayez un autre nom ou symbole.</p> : (
|
||||
<ul className="space-y-3">{results.map(index => {
|
||||
const tracked = assets.some(asset => asset.figi === index.figi)
|
||||
const ambiguous = results.some(other => other.figi !== index.figi && other.symbol === index.symbol)
|
||||
return <li key={index.figi} className="rounded-md border p-3 space-y-2 break-words">
|
||||
<p className="font-medium">{index.name}</p><p>{index.symbol}</p>
|
||||
{index.market && <p>{index.market}</p>}
|
||||
{ambiguous && <p className="font-mono break-all">{index.figi}</p>}
|
||||
<Button onClick={() => void follow(index)} disabled={tracked || busy || loading || !!listError}>{tracked ? 'Déjà suivi' : 'Suivre cet indice'}</Button>
|
||||
<p id="company-search-help" className="text-sm text-muted-foreground">{text.help}</p>
|
||||
{searchError && <div className="space-y-2"><p role="alert">{text[searchError]}</p><Button variant="outline" disabled={searching || !query.trim()} onClick={() => void search()}>{text.retry}</Button></div>}
|
||||
<section aria-label={text.results} aria-busy={searching} className="space-y-3">
|
||||
{searching ? <p role="status">{text.searching}</p> : results === null ? <p>{text.before}</p> : results.length === 0 ? <p role="status">{text.empty}</p> : <ul className="space-y-3">{results.map(company => {
|
||||
const tracked = assets.some(asset => asset.company_id === company.company_id)
|
||||
return <li key={company.company_id} className="rounded-md border p-3 space-y-2 min-w-0 break-words">
|
||||
<CompanyInfo company={company} />
|
||||
<Button onClick={() => void follow(company)} disabled={tracked || busy || loading || listError}>{tracked ? text.tracked : text.follow}</Button>
|
||||
</li>
|
||||
})}</ul>
|
||||
)}
|
||||
})}</ul>}
|
||||
</section>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{actionError && <p role="alert" className="text-destructive">{actionError}</p>}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{busy && <p role="status">Mise à jour des indices suivis…</p>}
|
||||
{removed && <Button variant="outline" disabled={busy} onClick={() => void undo()}>Annuler le retrait</Button>}
|
||||
{loading ? <p role="status">Chargement des indices suivis…</p> : listError ? <div><p role="alert">{listError}</p><Button onClick={() => { setLoading(true); setListError(''); void load() }}>Recharger la liste</Button></div> : <>
|
||||
<section aria-label="Indices suivis" className="space-y-3">
|
||||
<h2 className="text-lg font-semibold">Indices suivis</h2>
|
||||
{followed.length ? <AssetList items={followed} busy={busy} onRemove={remove} /> : <p>Aucun indice suivi. Recherchez puis choisissez un indice pour commencer.</p>}
|
||||
</CardContent></Card>
|
||||
{actionError && <p role="alert" className="text-destructive">{text[actionError]}</p>}
|
||||
{notice && <p role="status">{text[notice]}</p>}
|
||||
{busy && <p role="status">{text.busy}</p>}
|
||||
{removed && <Button variant="outline" disabled={busy} onClick={() => void undo()}>{text.undo}</Button>}
|
||||
{loading ? <p role="status">{text.loading}</p> : listError ? <div><p role="alert">{text.loadError}</p><Button onClick={() => { setLoading(true); setListError(false); void load() }}>{text.reload}</Button></div> : <>
|
||||
<section aria-label={text.title} className="space-y-3"><h2 className="text-lg font-semibold">{text.title}</h2>
|
||||
{followed.length ? <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{followed.map(asset => <li key={asset.id} className="rounded-md border p-4 space-y-2 min-w-0">
|
||||
<CompanyInfo company={asset} />
|
||||
<Button variant="outline" disabled={busy} onClick={() => void remove(asset)} aria-label={`${text.unfollow} ${asset.name}`}>{text.unfollow}</Button>
|
||||
</li>)}</ul> : <p>{text.noFollowed}</p>}
|
||||
</section>
|
||||
{legacy.length > 0 && <section aria-label="Actifs historiques" className="space-y-3">
|
||||
<h2 className="text-lg font-semibold">Actifs historiques</h2>
|
||||
<p className="text-sm text-muted-foreground">Ces actifs restent utilisés dans vos synthèses. Leur type n’a pas été vérifié ; ils ne sont ni convertis ni retirés automatiquement.</p>
|
||||
{<AssetList items={legacy} busy={busy} onRemove={remove} />}
|
||||
{legacy.length > 0 && <section aria-label={text.legacyRegion} className="space-y-3"><h2 className="text-lg font-semibold">{text.legacy}</h2>
|
||||
<p className="text-sm text-muted-foreground">{text.legacyHelp}</p>
|
||||
<ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{legacy.map(asset => <li key={asset.id} className="rounded-md border p-4 min-w-0 break-words">{asset.name || text.unknown}</li>)}</ul>
|
||||
</section>}
|
||||
</>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@ -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' }))
|
||||
})
|
||||
|
||||
20
frontend/tests/company-assets-api-ticket19.test.ts
Normal file
20
frontend/tests/company-assets-api-ticket19.test.ts
Normal 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' }),
|
||||
}))
|
||||
})
|
||||
155
frontend/tests/watchlist-company-search-ticket19.test.tsx
Normal file
155
frontend/tests/watchlist-company-search-ticket19.test.tsx
Normal 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()
|
||||
})
|
||||
|
||||
})
|
||||
@ -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()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user