feat(sources): retire Yahoo and CNBC feeds (#42)

This commit is contained in:
2026-11-25 02:00:25 +01:00
parent 7a342f240d
commit 0503c2653f
41 changed files with 603 additions and 173 deletions

View File

@ -109,7 +109,7 @@ func run(ctx context.Context) error {
if err = server.EnsureAdmin(repo, cfg); err != nil {
return err
}
feeds := map[string]scraper.Scraper{models.SourceYahooFinance: e2estack.FakeScraper{URL: fakeURL, Client: client}}
feeds := map[string]scraper.Scraper{models.SourceBloomberg: e2estack.FakeScraper{URL: fakeURL, Client: client}}
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
gin.SetMode(gin.TestMode)
gin.DefaultWriter = io.Discard
@ -226,7 +226,7 @@ func seed(db *sql.DB, fakeURL string) error {
if _, err = tx.Exec(`UPDATE sources SET enabled=false`); err != nil {
return err
}
if _, err = tx.Exec(`UPDATE sources SET enabled=true WHERE source_key='yahoo_finance'`); err != nil {
if _, err = tx.Exec(`UPDATE sources SET enabled=true WHERE source_key='bloomberg'`); err != nil {
return err
}
if _, err = tx.Exec(`INSERT INTO ai_providers(id,name,model,endpoint,is_active) VALUES('00000000-0000-0000-0000-000000001202','ollama','fake-laya',$1,true)`, fakeURL); err != nil {

View File

@ -12,9 +12,7 @@ import (
"github.com/tradarr/backend/internal/indices/openfigi"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/cnbcbusiness"
"github.com/tradarr/backend/internal/scraper/quanwenrss"
"github.com/tradarr/backend/internal/scraper/yahoofinance"
"github.com/tradarr/backend/internal/server"
)
@ -53,10 +51,8 @@ func main() {
}
feeds := map[string]scraper.Scraper{
models.SourceBloomberg: quanwenrss.New(models.SourceBloomberg, repo, nil),
models.SourceInvesting: quanwenrss.New(models.SourceInvesting, repo, nil),
models.SourceYahooFinance: yahoofinance.New(),
models.SourceCNBCBusiness: cnbcbusiness.New(),
models.SourceBloomberg: quanwenrss.New(models.SourceBloomberg, repo, nil),
models.SourceInvesting: quanwenrss.New(models.SourceInvesting, repo, nil),
}
app := server.New(repo, cfg, server.Dependencies{SummaryDiagnostics: ai.LogSummaryDiagnostic, CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})

View File

@ -0,0 +1,69 @@
package main
import (
"go/ast"
"go/parser"
"go/token"
"testing"
)
func TestTicket42ProductionCompositionContainsOnlyRSSAdapters(t *testing.T) {
file, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
if err != nil {
t.Fatal(err)
}
found := false
ast.Inspect(file, func(n ast.Node) bool {
literal, ok := n.(*ast.CompositeLit)
if !ok {
return true
}
typ, ok := literal.Type.(*ast.MapType)
if !ok {
return true
}
value, ok := typ.Value.(*ast.SelectorExpr)
if !ok || value.Sel.Name != "Scraper" {
return true
}
found = true
if len(literal.Elts) != 2 {
t.Error("production must compose exactly two source adapters")
}
keys := map[string]bool{}
for _, element := range literal.Elts {
pair, ok := element.(*ast.KeyValueExpr)
if !ok {
t.Error("unexpected source composition")
continue
}
key, ok := pair.Key.(*ast.SelectorExpr)
if !ok {
t.Error("source must have canonical identity")
continue
}
keys[key.Sel.Name] = true
call, ok := pair.Value.(*ast.CallExpr)
if !ok {
t.Error("source must be RSS adapter")
continue
}
ctor, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
t.Error("source must be RSS adapter")
continue
}
pkg, ok := ctor.X.(*ast.Ident)
if !ok || pkg.Name != "quanwenrss" || ctor.Sel.Name != "New" {
t.Error("non-RSS adapter in production composition")
}
}
if !keys["SourceBloomberg"] || !keys["SourceInvesting"] || keys["SourceYahooFinance"] || keys["SourceCNBCBusiness"] {
t.Error("production source keys do not match RSS-only policy")
}
return true
})
if !found {
t.Fatal("production source composition not found")
}
}

View File

@ -21,7 +21,7 @@ import (
type reliabilityRepo struct{ saved []generation.GenerationRecord }
func (r *reliabilityRepo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
key := models.SourceYahooFinance
key := models.SourceBloomberg
return generation.UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 1}}}, nil
}
func (r *reliabilityRepo) SaveGeneration(ctx context.Context, _ string, record generation.GenerationRecord) error {
@ -62,7 +62,7 @@ func TestTicket35HTTPProviderFailureReachesSafeGenerationOutcome(t *testing.T) {
return &http.Response{StatusCode: 503, Body: io.NopCloser(strings.NewReader("PRIVATE_BODY PRIVATE_SECRET")), Header: make(http.Header)}, nil
})}
repo := &reliabilityRepo{}
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: reliabilityDecider{}, Summarizer: generationSummarizer{providerName: "gemini", model: "gemini-2.5-flash", provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: reliabilityFeed{}}})
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: reliabilityDecider{}, Summarizer: generationSummarizer{providerName: "gemini", model: "gemini-2.5-flash", provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: reliabilityFeed{}}})
r, err := uc.Generate(ctx, "fixture")
want := map[string]string{"timeout": "summary_timeout", "canceled": "summary_canceled", "provider": "summary_failed"}[kind]
if err != nil || r.Outcome.FailureCode != want || r.Summary != nil || len(repo.saved) != 1 {

View File

@ -16,7 +16,7 @@ import (
type incident37Repo struct{ saved []generation.GenerationRecord }
func (*incident37Repo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
key := models.SourceYahooFinance
key := models.SourceBloomberg
return generation.UserInput{Language: "fr", RankingMode: "title_content", GlobalLimit: 90, Assets: []models.UserAsset{{Name: "Followed Company"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 90}}}, nil
}
func (r *incident37Repo) SaveGeneration(_ context.Context, _ string, v generation.GenerationRecord) error {
@ -89,7 +89,7 @@ func TestTicket37NinetyCandidatesSixtySelectedSummary(t *testing.T) {
repo := &incident37Repo{}
laya := &incident37Laya{}
provider := &incident37Provider{err: tc.err, empty: tc.empty}
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: laya, Summarizer: generationSummarizer{providerName: "gemini", model: "gemini-2.5-flash", provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: incident37Feed{oversized: tc.oversized}}})
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: laya, Summarizer: generationSummarizer{providerName: "gemini", model: "gemini-2.5-flash", provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: incident37Feed{oversized: tc.oversized}}})
result, err := uc.Generate(context.Background(), "fixture")
if err != nil {
t.Fatal("unexpected repository/use-case error")

View File

@ -42,7 +42,7 @@ func TestArticleCapsMigrationAndInvalidAdminUpdatesAreAtomicPostgres(t *testing.
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, source_key TEXT, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE scrape_schedules (id UUID PRIMARY KEY, day_of_week INT NOT NULL, hour INT NOT NULL, minute INT NOT NULL)`,
`INSERT INTO settings (key,value) VALUES ('summary_max_articles','733')`,
`INSERT INTO sources (id,name,type,source_key) VALUES ('00000000-0000-0000-0000-000000000001','Yahoo Finance','stocktwits','yahoo_finance')`,
`INSERT INTO sources (id,name,type,source_key) VALUES ('00000000-0000-0000-0000-000000000001','Bloomberg','bloomberg','bloomberg')`,
} {
if _, err = db.Exec(statement); err != nil {
t.Fatal(err)

View File

@ -36,7 +36,12 @@ func TestAdminSourcesExposeSupportStateAndRejectHistoricalUpdateAtomicallyPostgr
t.Fatal(err)
}
t.Cleanup(func() { _, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`); _ = db.Close() })
for _, q := range []string{`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,role TEXT,password_hash TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO users(id,email,role,password_hash) VALUES('admin-id','admin@example.test','admin','hash')`, `CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('old-id','Reuters','reuters',true,42,NULL),('y-id','Yahoo Finance','stocktwits',true,83,'yahoo_finance')`} {
for _, q := range []string{`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,role TEXT,password_hash TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO users(id,email,role,password_hash) VALUES('admin-id','admin@example.test','admin','hash')`, `CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('old-id','Reuters','reuters',true,42,NULL),('b-id','Bloomberg','bloomberg',true,83,'bloomberg')`} {
if _, err = db.Exec(q); err != nil {
t.Fatal(err)
}
}
for _, q := range []string{`CREATE TABLE source_feeds(source_id TEXT,position INT,url TEXT)`, `INSERT INTO source_feeds VALUES('b-id',0,'https://feed.quanwenrss.com/feed/bloomberg-latest.xml')`} {
if _, err = db.Exec(q); err != nil {
t.Fatal(err)
}
@ -67,7 +72,7 @@ func TestAdminSourcesExposeSupportStateAndRejectHistoricalUpdateAtomicallyPostgr
if row["id"] == "old-id" {
old = row
}
if row["id"] == "y-id" {
if row["id"] == "b-id" {
supported = row
}
}
@ -90,7 +95,7 @@ func TestAdminSourcesExposeSupportStateAndRejectHistoricalUpdateAtomicallyPostgr
if supported == nil {
t.Fatalf("GET omitted supported source: %s", get.Body.String())
}
for field, want := range map[string]any{"source_key": "yahoo_finance", "supported": true, "operational": true} {
for field, want := range map[string]any{"source_key": "bloomberg", "supported": true, "operational": true} {
if supported[field] != want {
t.Errorf("supported source %s=%v, want %v; row=%v", field, supported[field], want, supported)
}

View File

@ -40,7 +40,7 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID REFERENCES users(id),content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ,summary_model_id UUID NULL,provider_name TEXT NULL,model_name TEXT NULL)`,
`INSERT INTO users(id) VALUES('00000000-0000-0000-0000-000000000001')`,
`INSERT INTO sources(id,name,type,enabled,source_key) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true,'yahoo_finance')`,
`INSERT INTO sources(id,name,type,enabled,source_key) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true,'bloomberg')`,
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID REFERENCES summaries(id),outcome JSONB NOT NULL,created_at TIMESTAMPTZ)`,
} {
if _, err := db.Exec(statement); err != nil {
@ -48,7 +48,7 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
}
}
repo := models.NewRepository(db)
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
result, err := uc.Generate(context.Background(), "00000000-0000-0000-0000-000000000001")
if err != nil || result.Summary == nil || result.Outcome.Status != "succeeded" {
t.Fatalf("result=%+v err=%v", result, err)

View File

@ -0,0 +1,86 @@
package api_test
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/lib/pq"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
)
func TestTicket42AdminCannotReactivateOrModifyRetiredSourcesPostgres(t *testing.T) {
db, err := sql.Open("postgres", postgresTestURL(t))
if err != nil {
t.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1)
schema := fmt.Sprintf("retired42_%d", time.Now().UnixNano())
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
t.Fatal(err)
}
defer db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
t.Fatal(err)
}
for _, q := range []string{
`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,role TEXT,password_hash TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
`INSERT INTO users(id,email,role,password_hash) VALUES('admin','admin@example.test','admin','hash')`,
`CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT,type TEXT,source_key TEXT,enabled BOOLEAN,article_limit INT,created_at TIMESTAMPTZ DEFAULT NOW())`,
`INSERT INTO sources(id,name,type,source_key,enabled,article_limit) VALUES('y','Yahoo Finance','stocktwits','yahoo_finance',false,83),('c','CNBC Business','cnbc_business','cnbc_business',false,31)`,
} {
if _, err = db.Exec(q); err != nil {
t.Fatal(err)
}
}
const secret = "retired42-fixture"
token, _ := auth.GenerateToken("admin", "admin@example.test", "admin", secret)
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
request := func(method, path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, bytes.NewBufferString(body))
r.Header.Set("Authorization", "Bearer "+token)
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
return w
}
for _, id := range []string{"y", "c"} {
for _, body := range []string{`{"enabled":true}`, `{"enabled":false,"article_limit":1}`, `{"enabled":true,"feed_urls":["https://feed.quanwenrss.com/feed/bloomberg-latest.xml"]}`} {
w := request(http.MethodPut, "/api/admin/sources/"+id, body)
if w.Code != 409 || w.Body.String() != `{"error":"source_not_supported"}` {
t.Error("retired source modification/re-activation not explicitly rejected")
}
}
}
// Even a direct SQL reactivation must not make a legacy row operational.
if _, err = db.Exec(`UPDATE sources SET enabled=true`); err != nil {
t.Fatal(err)
}
w := request(http.MethodGet, "/api/admin/sources", "")
var result struct {
Data []struct {
ID, Name string
SourceKey *string `json:"source_key"`
Enabled, Supported, Operational bool
Limit int `json:"article_limit"`
}
}
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil || len(result.Data) != 2 {
t.Fatal("retired admin rows were removed")
}
for _, s := range result.Data {
if !s.Enabled || s.Supported || s.Operational || s.SourceKey == nil || (s.ID == "y" && (s.Limit != 83 || s.Name != "Yahoo Finance" || *s.SourceKey != "yahoo_finance")) || (s.ID == "c" && (s.Limit != 31 || s.Name != "CNBC Business" || *s.SourceKey != "cnbc_business")) {
t.Fatal("historical metadata was changed or source still operational")
}
}
}

View File

@ -58,7 +58,7 @@ func TestManualGenerationResolvesAccountModelsAndSnapshotsWithoutGlobalFallbackP
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
`INSERT INTO settings VALUES('summary_max_articles','50'),('ai_role_summary_provider','legacy-must-not-resolve'),('ai_role_summary_model','legacy-must-not-resolve'),('ai_role_filter_provider','legacy-must-not-resolve')`,
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,created_at TIMESTAMPTZ DEFAULT NOW(),article_limit INT,source_key TEXT)`,
`INSERT INTO sources VALUES('00000000-0000-0000-0000-000000001599','Yahoo Finance','stocktwits',true,NOW(),20,'yahoo_finance')`,
`INSERT INTO sources VALUES('00000000-0000-0000-0000-000000001599','Bloomberg','bloomberg',true,NOW(),20,'bloomberg')`,
`CREATE TABLE user_assets(id UUID PRIMARY KEY,user_id UUID,symbol TEXT,name TEXT,figi TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID,content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ,summary_model_id UUID,provider_name TEXT,model_name TEXT)`,
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID,outcome JSONB,created_at TIMESTAMPTZ)`,
@ -81,7 +81,7 @@ func TestManualGenerationResolvesAccountModelsAndSnapshotsWithoutGlobalFallbackP
return &selectionProvider{model: m.Model, calls: providerCalls}, nil
}
pipeline := ai.NewPipeline(repo, nil)
feeds := map[string]scraper.Scraper{models.SourceYahooFinance: feed}
feeds := map[string]scraper.Scraper{models.SourceBloomberg: feed}
useCase := pipeline.NewGenerationUseCaseWithFactory(feeds, laya, factory)
h := handlers.New(repo, &config.Config{}, nil, nil, pipeline, nil)
h.SetGenerationUseCase(useCase)

View File

@ -0,0 +1,2 @@
-- A downgrade must never implicitly reactivate retired sources or erase history.
UPDATE sources SET enabled=false WHERE source_key IN ('yahoo_finance','cnbc_business');

View File

@ -0,0 +1,2 @@
-- Retirement only: retain canonical/legacy keys, IDs, caps, constraints and history.
UPDATE sources SET enabled=false WHERE source_key IN ('yahoo_finance','cnbc_business');

View File

@ -0,0 +1,73 @@
package migrations
import (
"os"
"reflect"
"testing"
)
func TestTicket42RetirementPreservesIDsCapsFeedsAndHistoryPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
for _, q := range []string{
`ALTER TABLE sources ADD COLUMN source_key TEXT CHECK(source_key IN ('yahoo_finance','cnbc_business','bloomberg','investing_com'))`,
`INSERT INTO sources(id,name,type,source_key,enabled,article_limit) VALUES('y','Yahoo Finance','stocktwits','yahoo_finance',true,83),('c','CNBC Business','cnbc_business','cnbc_business',true,31),('b','Bloomberg','bloomberg','bloomberg',false,77),('i','Investing.com','investing_com','investing_com',true,20)`,
`CREATE TABLE source_feeds(source_id TEXT REFERENCES sources(id),position INT,url TEXT)`,
`INSERT INTO source_feeds VALUES('b',0,'https://feed.quanwenrss.com/feed/bloomberg-latest.xml'),('i',0,'https://feed.quanwenrss.com/feed/investing-news.xml')`,
`INSERT INTO articles(id,source_id,title,url) VALUES('old-y','y','Synthetic historical Yahoo','https://fixture.invalid/y'),('old-c','c','Synthetic historical CNBC','https://fixture.invalid/c')`,
`CREATE TABLE fixture_reports(id TEXT PRIMARY KEY,source_id TEXT REFERENCES sources(id),content TEXT)`,
`INSERT INTO fixture_reports VALUES('report-y','y','Synthetic historical report'),('report-c','c','Synthetic historical report')`,
`CREATE TABLE fixture_outcomes(payload JSONB)`,
`INSERT INTO fixture_outcomes VALUES('{"source_stats":[{"source_key":"yahoo_finance","source_name":"Yahoo Finance"},{"source_key":"cnbc_business","source_name":"CNBC Business"}]}')`,
} {
if _, err := db.Exec(q); err != nil {
t.Fatal(err)
}
}
before := ticket13ReadSources(t, db)
schema := ticket13SchemaSnapshot(t, db)
refs := ticket13ReadArticleSources(t, db)
var history, feeds, reports string
snapshots := []struct {
query string
value *string
}{
{`SELECT payload::text FROM fixture_outcomes`, &history},
{`SELECT string_agg(source_id||':'||position||':'||url,',' ORDER BY source_id,position) FROM source_feeds`, &feeds},
{`SELECT string_agg(id||':'||source_id||':'||content,',' ORDER BY id) FROM fixture_reports`, &reports},
}
for _, s := range snapshots {
if err := db.QueryRow(s.query).Scan(s.value); err != nil {
t.Fatal(err)
}
}
for _, file := range []string{"000022_retire_yahoo_cnbc.up.sql", "000022_retire_yahoo_cnbc.down.sql"} {
raw, err := os.ReadFile(file)
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(raw)); err != nil {
t.Fatal(err)
}
got := ticket13ReadSources(t, db)
expected := append([]ticket13SourceRow(nil), before...)
for n := range expected {
if expected[n].id == "y" || expected[n].id == "c" {
expected[n].enabled = false
}
}
if !reflect.DeepEqual(got, expected) || ticket13SchemaSnapshot(t, db) != schema || !reflect.DeepEqual(ticket13ReadArticleSources(t, db), refs) {
t.Fatal("retirement/rollback changed more than legacy switches")
}
for _, s := range snapshots {
var after string
if err := db.QueryRow(s.query).Scan(&after); err != nil || after != *s.value {
t.Fatal("history/feeds/report payload changed")
}
}
var keys int
if err := db.QueryRow(`SELECT count(*) FROM sources WHERE (id='y' AND source_key='yahoo_finance') OR (id='c' AND source_key='cnbc_business')`).Scan(&keys); err != nil || keys != 2 {
t.Fatal("legacy keys were removed")
}
}
}

View File

@ -29,18 +29,18 @@ func (f *symbolFeed) Scrape(_ context.Context, s []string) ([]scraper.Article, e
}
func TestPerSourceCompanyHintsDoNotChangeOtherFeeds(t *testing.T) {
yahoo, bloomberg, cnbc, watcher := &symbolFeed{}, &symbolFeed{}, &symbolFeed{}, &symbolFeed{}
yahoo, bloomberg, cnbc, watcher, investing := &symbolFeed{}, &symbolFeed{}, &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.SourceCNBCBusiness, models.SourceWatcherGuru} {
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceCNBCBusiness, models.SourceWatcherGuru, models.SourceInvesting} {
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.SourceCNBCBusiness: cnbc, models.SourceWatcherGuru: watcher}})
uc := NewUseCase(Dependencies{Repository: repo, LayaRanker: &contractRanker{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: yahoo, models.SourceBloomberg: bloomberg, models.SourceCNBCBusiness: cnbc, models.SourceWatcherGuru: watcher, models.SourceInvesting: investing}})
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(cnbc.symbols, bloomberg.symbols) || watcher.symbols != nil {
if yahoo.symbols != nil || cnbc.symbols != nil || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(investing.symbols, bloomberg.symbols) || watcher.symbols != nil {
t.Fatalf("Yahoo=%v Bloomberg=%v Watcher=%v", yahoo.symbols, bloomberg.symbols, watcher.symbols)
}
}

View File

@ -34,13 +34,13 @@ func (f *contentFeed) Enrich(_ context.Context, a []scraper.Article) ([]scraper.
func TestTicket36EnrichmentAfterPoolAndNoReordering(t *testing.T) {
for _, mode := range []string{"title_content", "title", "failure", "other_source"} {
t.Run(mode, func(t *testing.T) {
source := models.SourceBloomberg
source := models.SourceInvesting
rankingMode := mode
if mode == "failure" || mode == "other_source" {
rankingMode = "title_content"
}
if mode == "other_source" {
source = models.SourceYahooFinance
source = models.SourceBloomberg
}
feed := &contentFeed{fail: mode == "failure", contractScraper: contractScraper{articles: []scraper.Article{{Title: "Fixture first"}, {Title: "Fixture second"}, {Title: "excluded"}}}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: rankingMode, GlobalLimit: 2, Assets: []models.UserAsset{{Name: "Fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(source), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
@ -74,7 +74,7 @@ func TestTicket36EnrichmentAfterPoolAndNoReordering(t *testing.T) {
}
func TestTicket36EnrichedDateDoesNotChangeCrossSourceOrder(t *testing.T) {
keyB, keyY := models.SourceBloomberg, models.SourceYahooFinance
keyB, keyY := models.SourceInvesting, models.SourceBloomberg
feed := &contentFeed{contractScraper: contractScraper{articles: []scraper.Article{{Title: "Fixture Bloomberg"}}}}
old := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
other := &contractScraper{articles: []scraper.Article{{Title: "Fixture Yahoo", ContentState: scraper.ContentComplete, Content: "synthetic full Yahoo body", PublishedAt: &old}}}

View File

@ -20,6 +20,7 @@ type ticket40Transport func(*http.Request) (*http.Response, error)
func (f ticket40Transport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
type ticket40EvidenceFeed struct {
calls *int
source string
articles []scraper.Article
client *http.Client
@ -28,6 +29,9 @@ type ticket40EvidenceFeed struct {
func (f ticket40EvidenceFeed) Name() string { return f.source }
func (f ticket40EvidenceFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
if f.calls != nil {
*f.calls++
}
return append([]scraper.Article(nil), f.articles...), nil
}
func (f ticket40EvidenceFeed) Enrich(ctx context.Context, a []scraper.Article) ([]scraper.Article, error) {
@ -36,8 +40,8 @@ func (f ticket40EvidenceFeed) Enrich(ctx context.Context, a []scraper.Article) (
}
return articlecontent.Enrich(ctx, f.client, f.source, a)
}
func TestTicket40RealEnrichmentPortsOnlyPropagateCompleteBodiesToSummary(t *testing.T) {
for _, key := range []string{models.SourceBloomberg, models.SourceYahooFinance, models.SourceCNBCBusiness} {
func TestTicket40LegacyEnrichmentPreservedAndRetiredSourcesCannotGenerate(t *testing.T) {
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceCNBCBusiness} {
t.Run(key, func(t *testing.T) {
const full = "Synthetic full editorial body."
base, root := "https://finance.yahoo.com/news/", "caas-body"
@ -48,7 +52,8 @@ func TestTicket40RealEnrichmentPortsOnlyPropagateCompleteBodiesToSummary(t *test
if key == models.SourceBloomberg {
base = "https://www.bloomberg.com/news/articles/"
}
feed := ticket40EvidenceFeed{source: key}
calls := 0
feed := ticket40EvidenceFeed{source: key, calls: &calls}
for _, kind := range []string{"complete", "partial", "absent"} {
feed.articles = append(feed.articles, scraper.Article{Title: "Followed fixture " + kind, URL: base + kind + ".html", Content: "RSS teaser", ContentState: scraper.ContentIncomplete})
}
@ -91,10 +96,21 @@ func TestTicket40RealEnrichmentPortsOnlyPropagateCompleteBodiesToSummary(t *test
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
})}
}
// The legacy adapters remain intact for historical/diagnostic tooling.
enriched, err := feed.Enrich(context.Background(), feed.articles)
if err != nil || len(enriched) != 3 || scraper.ContentStatus(enriched[0]) != scraper.ContentComplete || scraper.ContentStatus(enriched[1]) != scraper.ContentIncomplete || scraper.ContentStatus(enriched[2]) != scraper.ContentUnavailable {
t.Fatal("legacy enrichment port was changed")
}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 3, Assets: []models.UserAsset{{Name: "Followed fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
sum := &contractSummarizer{}
result, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{key: feed}}).Generate(context.Background(), "u")
o := result.Outcome
if key == models.SourceYahooFinance || key == models.SourceCNBCBusiness {
if err != nil || result.Summary != nil || calls != 0 || len(sum.articles) != 0 || o.TotalCandidates != 0 || len(o.SourceStats) != 0 {
t.Fatal("retired source entered new generation")
}
return
}
if err != nil || result.Summary == nil || o.Status != "partial" || o.ContentComplete != 1 || o.ContentIncomplete != 1 || o.ContentUnavailable != 1 || o.Selected != 1 || len(sum.articles) != 1 || sum.articles[0][0].Article.Content != full || o.SourceStats[0].Status != "ok" || o.SourceStats[0].SourceKey != key {
t.Fatal("enrichment status lost before summary", o, err)
}

View File

@ -8,7 +8,7 @@ import (
)
func TestTicket39NoContentIsExplicit(t *testing.T) {
key := models.SourceYahooFinance
key := models.SourceBloomberg
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 2, Assets: []models.UserAsset{{Name: "Fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
sum := &contractSummarizer{}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{key: &contractScraper{articles: []scraper.Article{{Title: "Fixture", Content: "RSS teaser", ContentTruncated: true}}}}}).Generate(context.Background(), "u")
@ -42,7 +42,7 @@ func (f *ticket39ContentFeed) Enrich(_ context.Context, a []scraper.Article) ([]
return out, nil
}
func TestTicket39AllRuntimeSourcesEnrichAfterLimitAndOnlyCompleteSelectable(t *testing.T) {
for _, key := range []string{models.SourceBloomberg, models.SourceYahooFinance, models.SourceCNBCBusiness} {
for _, key := range []string{models.SourceBloomberg, models.SourceInvesting} {
t.Run(key, func(t *testing.T) {
feed := &ticket39ContentFeed{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 3, Assets: []models.UserAsset{{Name: "Followed fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}

View File

@ -92,8 +92,8 @@ func (s *contractSummarizer) Summarize(_ context.Context, language string, _ []m
func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testing.T) {
alphaID, betaID := "user-alpha", "user-beta"
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}
betaSource := models.Source{ID: "beta-feed", Type: "beta", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}
betaSource := models.Source{ID: "beta-feed", Type: "beta", SourceKey: testSourceKey(models.SourceInvesting), Enabled: true, ArticleLimit: 5}
disabled := models.Source{ID: "disabled-feed", Type: "disabled", SourceKey: testSourceKey(models.SourceWatcherGuru), Enabled: false, ArticleLimit: 5}
alphaScraper := &contractScraper{name: "alpha", articles: []scraper.Article{{Title: "alpha-only", URL: "https://private.test/alpha", ContentState: scraper.ContentComplete, Content: "alpha-secret"}}}
betaScraper := &contractScraper{name: "beta", articles: []scraper.Article{{Title: "beta-only", URL: "https://private.test/beta", ContentState: scraper.ContentComplete, Content: "beta-secret"}}}
@ -107,7 +107,7 @@ func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testin
},
saved: map[string][]GenerationRecord{},
}
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: alphaScraper, models.SourceBloomberg: betaScraper, models.SourceWatcherGuru: disabledScraper}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) }})
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: alphaScraper, models.SourceInvesting: betaScraper, models.SourceWatcherGuru: disabledScraper}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) }})
alpha, err := useCase.Generate(context.Background(), alphaID)
if err != nil || alpha.Summary == nil {
@ -148,8 +148,8 @@ func TestUseCasePreservesRecentInputOrderWithSourcePoolsAndGlobalOutputCap(t *te
feedB := &contractScraper{name: "b", articles: articles[2:]}
ranker := &contractRanker{order: []string{"a2", "b1", "a1", "b2", "a3"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 3, Assets: []models.UserAsset{{Symbol: "IDX"}}, Sources: []models.Source{{ID: "a", Type: "a", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}, {ID: "b", Type: "b", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feedA, models.SourceBloomberg: feedB}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 3, Assets: []models.UserAsset{{Symbol: "IDX"}}, Sources: []models.Source{{ID: "a", Type: "a", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 1}, {ID: "b", Type: "b", SourceKey: testSourceKey(models.SourceInvesting), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: feedA, models.SourceInvesting: feedB}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
if _, err := uc.Generate(context.Background(), "u"); err != nil {
t.Fatal(err)
}
@ -176,10 +176,10 @@ func TestUseCaseNoResultsInvalidLayaAndSummaryFailurePersistNoSummary(t *testing
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Sources: []models.Source{{ID: "s", Type: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 10}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Sources: []models.Source{{ID: "s", Type: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 10}}}}, saved: map[string][]GenerationRecord{}}
ranker := &contractRanker{err: tt.rankErr}
summarizer := &contractSummarizer{err: tt.summaryErr}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{name: "s", articles: tt.articles}}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: &contractScraper{name: "s", articles: tt.articles}}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil {
t.Fatalf("expected aggregate failure outcome, got error: %v", err)
@ -199,8 +199,8 @@ func TestUseCasePartialSourceFailureCanSummarizeRemainingSources(t *testing.T) {
bad := &contractScraper{name: "bad", err: errors.New("private error with URL https://private.test/article")}
ranker := &contractRanker{order: []string{"good-result"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "good", Type: "good", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}, {ID: "bad", Type: "bad", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: good, models.SourceBloomberg: bad}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "good", Type: "good", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}, {ID: "bad", Type: "bad", SourceKey: testSourceKey(models.SourceInvesting), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: good, models.SourceInvesting: bad}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil || result.Summary == nil || result.Outcome.Status != "partial" {
t.Fatalf("partial source failure result=%+v err=%v", result, err)
@ -221,8 +221,8 @@ func TestUseCaseOutcomeContainsAggregateCountsWithoutArticleIdentifiers(t *testi
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "candidate-title-secret", URL: "https://private.test/x", ContentState: scraper.ContentComplete, Content: "candidate-content-secret"}}}
ranker := &contractRanker{order: []string{"candidate-title-secret"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "source-id", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "source-id", Type: "source", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil {
t.Fatal(err)
@ -245,8 +245,8 @@ func TestUseCaseCountsTitleOnlyFallbackWhenContentIsUnavailable(t *testing.T) {
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "title-without-content", ContentState: scraper.ContentComplete, Content: ""}}}
ranker := &contractRanker{}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "en", RankingMode: "title_content", GlobalLimit: 4, Sources: []models.Source{{ID: "source", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "en", RankingMode: "title_content", GlobalLimit: 4, Sources: []models.Source{{ID: "source", Type: "source", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil || result.Summary != nil || result.Outcome.FailureCode != "no_complete_content" || len(summarizer.articles) != 0 {
t.Fatalf("missing content must prevent generation: result=%+v err=%v", result, err)

View File

@ -92,7 +92,7 @@ func (s *ticket14SummaryProvider) Summarize(_ context.Context, language string,
func TestGenerationInjectsLayaRankerAndSummaryProviderAsSeparatePorts(t *testing.T) {
figi := "BBG000SPX001"
key := models.SourceYahooFinance
key := models.SourceBloomberg
feed := &ticket14Feed{}
order := []string{}
ranker := &ticket14LayaRanker{selectedTitle: "Market title B", order: &order}
@ -135,7 +135,7 @@ func TestGenerationRunsTwoAccountsWithDistinctInjectedSummaryModels(t *testing.T
}
for _, account := range accounts {
t.Run(account.id, func(t *testing.T) {
figi, key := "BBG000SPX001", models.SourceYahooFinance
figi, key := "BBG000SPX001", models.SourceBloomberg
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 5}}}}
feed := &ticket14Feed{}
ranker := &ticket14LayaRanker{selectedTitle: "Market title A"}
@ -168,7 +168,7 @@ func TestGenerationInputCarriesTheUsersSelectedSummaryModel(t *testing.T) {
}
func TestGenerationWithoutSelectedSummaryProviderFailsBeforeScrapeOrLaya(t *testing.T) {
figi, key := "BBG000SPX001", models.SourceYahooFinance
figi, key := "BBG000SPX001", models.SourceBloomberg
feed := &ticket14Feed{}
ranker := &ticket14LayaRanker{selectedTitle: "Market title A"}
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 10}}}}
@ -210,7 +210,7 @@ func TestGenerationDoesNotSummarizeWhenLayaFailsOrReturnsInvalidSelectedIDs(t *t
} {
t.Run(tc.name, func(t *testing.T) {
figi := "BBG000SPX001"
key := models.SourceYahooFinance
key := models.SourceBloomberg
feed := &ticket14Feed{}
ranker := &ticket14LayaRanker{selectedTitle: "unknown"}
tc.setup(ranker)
@ -235,7 +235,7 @@ func TestGenerationDoesNotSummarizeWhenLayaFailsOrReturnsInvalidSelectedIDs(t *t
func TestGenerationRejectsDuplicateSelectedCandidateIDFromLaya(t *testing.T) {
figi := "BBG000SPX001"
key := models.SourceYahooFinance
key := models.SourceBloomberg
feed := &ticket14Feed{}
bad := ticket14DuplicateRanker{}
repo := &ticket14Repository{input: UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "stocktwits", SourceKey: &key, Enabled: true, ArticleLimit: 10}}}}

View File

@ -62,7 +62,7 @@ func TestTicket28GenerationAggregatesAllAssetsBeforeSelectionAndFailsClosed(t *t
}))
defer srv.Close()
ranker, _ := ai.NewLayaHTTPRanker(ai.LayaHTTPConfig{BaseURL: srv.URL, BatchSize: 2})
model, key := "model", models.SourceYahooFinance
model, key := "model", models.SourceBloomberg
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: "first", URL: "https://fixture.invalid/first", ContentState: scraper.ContentComplete, Content: content}, {Title: "second", URL: "https://fixture.invalid/second", ContentState: scraper.ContentComplete, Content: content}}}
summary := &ticket17HTTPSummary{}
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &model, Language: "fr", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: strings.Repeat("A", 400), Symbol: "A"}, {Name: strings.Repeat("B", 400), Symbol: "B"}}, Sources: []models.Source{{ID: "source", SourceKey: &key, Enabled: true, ArticleLimit: 2}}}}

View File

@ -91,7 +91,7 @@ func TestGenerationUsesLayaHTTPContractThenSelectedSummaryModel(t *testing.T) {
t.Fatal(err)
}
modelID := "summary-model-user-a"
key := models.SourceYahooFinance
key := models.SourceBloomberg
feed := &ticket17HTTPScraper{}
summary := &ticket17HTTPSummary{}
resolver := &ticket17HTTPResolver{provider: summary}
@ -161,7 +161,7 @@ func TestGenerationLogsSanitizedLayaFailureCause(t *testing.T) {
t.Fatal(err)
}
modelID := "summary-model-user-a"
key := models.SourceYahooFinance
key := models.SourceBloomberg
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: articleTitle, ContentState: scraper.ContentComplete, Content: articleBody, URL: articleURL}}}
summary := &ticket17HTTPSummary{}
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &modelID, Language: "en", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX"}}, Sources: []models.Source{{ID: "source-yahoo", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 5}}}}

View File

@ -59,7 +59,7 @@ func TestTicket29CompactGroupsIntegrateBeforeSelectionAndFailureIsGlobal(t *test
assets[i] = models.UserAsset{Name: fmt.Sprintf("Company %02d Incorporated", i), Symbol: fmt.Sprintf("T%02d", i)}
}
ranker, _ := ai.NewLayaHTTPRanker(ai.LayaHTTPConfig{BaseURL: srv.URL, BatchSize: 4})
model, key := "selected-model", models.SourceYahooFinance
model, key := "selected-model", models.SourceBloomberg
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: "first", URL: "https://fixture.invalid/1"}, {Title: "second", URL: "https://fixture.invalid/2"}}}
summary := &ticket17HTTPSummary{}
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &model, Language: "en", RankingMode: "title", GlobalLimit: 1, Assets: assets, Sources: []models.Source{{ID: "source", SourceKey: &key, Enabled: true, ArticleLimit: 2}}}}

View File

@ -35,7 +35,7 @@ func (r *ticket17SummaryResolver) Resolve(_ context.Context, user string, select
func TestTicket17GenerationScrapesThenLayaRanksThenUsesSelectedSummaryModel(t *testing.T) {
order := []string{}
modelID := "summary-catalog-a"
key := models.SourceYahooFinance
key := models.SourceBloomberg
feed := &ticket17Feed{order: &order}
ranker := &ticket14LayaRanker{selectedTitle: "candidate title", order: &order}
summary := &ticket14SummaryProvider{order: &order, content: "summary from selected catalogue model"}

View File

@ -56,8 +56,8 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
`INSERT INTO users(id,language,ranking_mode) VALUES ('` + userID + `','fr','title')`,
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000411','` + userID + `','LEGACY','Historic asset',NULL)`,
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20,'yahoo_finance')`,
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000422','Historic enabled','reuters',TRUE,42,NULL),('00000000-0000-0000-0000-000000000423','Disabled target','bloomberg',FALSE,77,'bloomberg')`,
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20,'bloomberg')`,
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000422','Historic enabled','reuters',TRUE,42,NULL),('00000000-0000-0000-0000-000000000423','Disabled target','bloomberg',FALSE,77,'investing_com')`,
`INSERT INTO settings(key,value) VALUES ('summary_max_articles','50'),('ai_system_prompt','Configured generation context')`,
} {
if _, err := db.Exec(statement); err != nil {
@ -72,7 +72,7 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
if input.SummaryContext != "Configured generation context" {
t.Fatal("existing generation context lost")
}
if len(input.Sources) != 1 || input.Sources[0].SourceKey == nil || *input.Sources[0].SourceKey != models.SourceYahooFinance || input.Sources[0].ArticleLimit != 20 {
if len(input.Sources) != 1 || input.Sources[0].SourceKey == nil || *input.Sources[0].SourceKey != models.SourceBloomberg || input.Sources[0].ArticleLimit != 20 {
t.Fatalf("LoadUserInput must exclude unsupported/disabled sources, preserving target caps: %+v", input.Sources)
}
if len(input.Assets) != 1 || input.Assets[0].Symbol != "LEGACY" || input.Assets[0].Name != "Historic asset" {
@ -91,7 +91,7 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
fakeRepository := &contractRepository{inputs: map[string]UserInput{userID: input}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{
Repository: fakeRepository,
Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed},
Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: feed},
Ranker: ranker,
Summarizer: summarizer,
Clock: func() time.Time { return time.Unix(1, 0).UTC() },

View File

@ -13,6 +13,7 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
var sources []models.Source
if err := json.Unmarshal([]byte(`[
{"id":"y","name":"Yahoo Finance","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":20},
{"id":"i","name":"Investing.com","type":"investing_com","source_key":"investing_com","enabled":true,"article_limit":20},
{"id":"b","name":"Bloomberg","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":20},
{"id":"c","name":"CNBC Business","type":"cnbc_business","source_key":"cnbc_business","enabled":true,"article_limit":20},
{"id":"w","name":"Watcher.Guru","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":20},
@ -23,7 +24,7 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
}
repo := &contractRepository{inputs: map[string]UserInput{"user": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, saved: map[string][]GenerationRecord{}}
feeds := map[string]*contractScraper{}
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "investing_com", "watcher_guru", "stocktwits", "reuters"} {
feeds[key] = &contractScraper{name: key, articles: []scraper.Article{{Title: key}}}
}
scrapers := map[string]scraper.Scraper{}
@ -34,17 +35,17 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
if err != nil || result.Summary == nil {
t.Fatalf("generation result=%+v err=%v", result, err)
}
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business"} {
for _, key := range []string{"bloomberg", "investing_com"} {
if len(feeds[key].calls) != 1 {
t.Errorf("target %s calls=%d, want one", key, len(feeds[key].calls))
}
}
for _, key := range []string{"watcher_guru", "stocktwits", "reuters"} {
for _, key := range []string{"yahoo_finance", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
if len(feeds[key].calls) != 0 {
t.Errorf("unsupported enabled source %s was invoked %d times", key, len(feeds[key].calls))
}
}
if result.Outcome.TotalCandidates != 3 {
t.Errorf("target candidate count=%d, want 3", result.Outcome.TotalCandidates)
if result.Outcome.TotalCandidates != 2 {
t.Errorf("target candidate count=%d, want 2", result.Outcome.TotalCandidates)
}
}

View File

@ -10,7 +10,7 @@ import (
)
func TestTicket40CanonicalSourceKeyAndReachabilitySeparateFromContent(t *testing.T) {
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceCNBCBusiness} {
for _, key := range []string{models.SourceBloomberg, models.SourceInvesting} {
t.Run(key, func(t *testing.T) {
feed := &ticket39ContentFeed{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 3, Assets: []models.UserAsset{{Name: "Followed fixture"}}, Sources: []models.Source{{ID: "s", Type: "stocktwits", SourceKey: &key, Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
@ -34,3 +34,18 @@ func TestTicket40CanonicalSourceKeyAndReachabilitySeparateFromContent(t *testing
})
}
}
func TestTicket42HistoricalSourceKeysAndTypesRemainReadable(t *testing.T) {
const payload = `{"status":"partial","source_stats":[{"source_key":"yahoo_finance","source_type":"stocktwits","source_id":"old-y","article_limit":83,"status":"ok"},{"source_key":"cnbc_business","source_type":"cnbc_business","source_id":"old-c","article_limit":31,"status":"ok"}]}`
var historical GenerationOutcome
if err := json.Unmarshal([]byte(payload), &historical); err != nil {
t.Fatal(err)
}
if historical.Status != "partial" || len(historical.SourceStats) != 2 || historical.SourceStats[0].SourceKey != models.SourceYahooFinance || historical.SourceStats[0].SourceType != "stocktwits" || historical.SourceStats[0].ArticleLimit != 83 || historical.SourceStats[1].SourceKey != models.SourceCNBCBusiness || historical.SourceStats[1].SourceType != "cnbc_business" || historical.SourceStats[1].ArticleLimit != 31 {
t.Fatal("historical outcome was reclassified")
}
raw, err := json.Marshal(historical)
if err != nil || !strings.Contains(string(raw), `"source_key":"yahoo_finance"`) || !strings.Contains(string(raw), `"source_key":"cnbc_business"`) {
t.Fatal("legacy source keys disappeared from history")
}
}

View File

@ -25,8 +25,8 @@ func TestTicket34MixedSourceUsesReceiptOrderBeforeInputLimit(t *testing.T) {
t.Fatalf("mixed source reordered before N: got %v want %v", got, want)
}
sum := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 2, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
result, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: articles}}}).Generate(context.Background(), "u")
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 2, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
result, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: &contractScraper{articles: articles}}}).Generate(context.Background(), "u")
if err != nil || result.Outcome.TotalCandidates != 2 || len(sum.articles) != 1 || !reflect.DeepEqual(candidateTitles(sum.articles[0]), want) {
t.Fatal("source mode must be chosen before N and preserved through passes", result.Outcome, err)
}
@ -38,8 +38,8 @@ func TestTicket34MergePreservesEachSourceOrderIncludingMixedDates(t *testing.T)
sum := &contractSummarizer{}
a := &contractScraper{articles: []scraper.Article{reviewDate("a-old", 1), {Title: "a-undated"}, reviewDate("a-new", 9)}}
b := &contractScraper{articles: []scraper.Article{reviewDate("b-new", 10), reviewDate("b-mid", 5)}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 5, Sources: []models.Source{{ID: "a", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 3}, {ID: "b", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: a, models.SourceBloomberg: b}}).Generate(context.Background(), "u")
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 5, Sources: []models.Source{{ID: "a", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 3}, {ID: "b", SourceKey: testSourceKey(models.SourceInvesting), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: a, models.SourceInvesting: b}}).Generate(context.Background(), "u")
if err != nil || r.Summary == nil {
t.Fatal(r, err)
}

View File

@ -29,9 +29,9 @@ func TestTicket35SummaryFailureDistinguishesTimeoutCancellationAndProvider(t *te
{"provider", errors.New("PRIVATE_BODY timeout https://PRIVATE_URL.invalid"), "summary_failed"},
} {
t.Run(tc.name, func(t *testing.T) {
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
sum := &contractSummarizer{err: tc.err}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(context.Background(), "u")
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(context.Background(), "u")
if err != nil || r.Summary != nil || r.Outcome.Status != "failed" || r.Outcome.FailureCode != tc.code {
t.Fatalf("status=%s code=%s err=%v", r.Outcome.Status, r.Outcome.FailureCode, err)
}
@ -71,11 +71,11 @@ func (r *terminalRepo) SaveGeneration(ctx context.Context, user string, record G
return r.contractRepository.SaveGeneration(ctx, user, record)
}
func TestTicket35CanceledSummaryStillPersistsSafeTerminalOutcome(t *testing.T) {
base := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
base := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
repo := &terminalRepo{contractRepository: base, expectedJob: "fixture-job"}
ctx, cancel := context.WithCancel(models.WithGenerationJob(context.Background(), repo.expectedJob))
defer cancel()
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: cancelSummary{cancel}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(ctx, "u")
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: cancelSummary{cancel}, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(ctx, "u")
if err != nil || !repo.checked || r.Summary != nil || r.Outcome.FailureCode != "summary_canceled" || len(base.saved["u"]) != 1 {
t.Fatal(r.Outcome, err)
}
@ -106,10 +106,10 @@ func TestTicket35ThreePassBudgetIsSharedAndFailureDropsAllSelection(t *testing.T
for i := 0; i < 65; i++ {
articles = append(articles, scraper.Article{Title: fmt.Sprintf("unmatched %d", i)})
}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 100, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 100}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 100, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 100}}}}, saved: map[string][]GenerationRecord{}}
gate := &budgetMention{failIndirect: true}
sum := &contractSummarizer{}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: articles}}}).Generate(context.Background(), "u")
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: &contractScraper{articles: articles}}}).Generate(context.Background(), "u")
if err != nil || r.Summary != nil || r.Outcome.FailureCode != "ranking_failed" || len(sum.articles) != 0 || gate.budgetCalls != 1 || len(gate.contexts) != 3 {
t.Fatal(r.Outcome, err)
}
@ -139,9 +139,9 @@ func TestTicket35BloombergMissingContentProducesHonestGenerationFallback(t *test
io.WriteString(w, `{"articles":[{"title":"Fixture Company","url":"https://fixture.invalid/article","published_at":null}]}`)
}))
defer server.Close()
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceInvesting), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
summary := &contractSummarizer{}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: summary, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: bloombergFixtureFeed{bloomberg.New(server.URL)}}}).Generate(context.Background(), "u")
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: summary, Scrapers: map[string]scraper.Scraper{models.SourceInvesting: bloombergFixtureFeed{bloomberg.New(server.URL)}}}).Generate(context.Background(), "u")
if err != nil || r.Summary != nil || requests != 1 || r.Outcome.ContentFallbacks != 1 || r.Outcome.SourceStats[0].ContentFallbacks != 1 || len(summary.articles) != 0 || r.Outcome.FailureCode != "no_complete_content" {
t.Fatal("inaccurate Bloomberg content availability", r.Outcome, err)
}
@ -157,10 +157,10 @@ func (s *liveContextSummary) Summarize(ctx context.Context, _ string, _ []models
return "fixture synthesis", nil
}
func TestTicket35SummaryDoesNotInheritCanceledSelectionBudget(t *testing.T) {
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
gate := &budgetMention{}
sum := &liveContextSummary{}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "unmatched"}}}}}).Generate(context.Background(), "u")
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: &contractScraper{articles: []scraper.Article{{Title: "unmatched"}}}}}).Generate(context.Background(), "u")
if err != nil || r.Summary == nil || !sum.called || gate.budgetCalls != 1 || len(gate.contexts) != 2 {
t.Fatal(r.Outcome, err)
}

View File

@ -41,8 +41,8 @@ func TestTicket34ThreePassesInputPoolPriorityAndLastBatchTrim(t *testing.T) {
b := &contractScraper{articles: []scraper.Article{{Title: "b1"}, {Title: "b2"}, {Title: "b3"}, {Title: "excluded-b"}}}
gate := &mentionFixture{yes: map[string]map[string]bool{"direct": {"a9": true, "b1": true}, "indirect": {"a8": true, "b2": true, "b3": true}}}
sum := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 4, Assets: []models.UserAsset{{Name: "Acme Holdings"}}, Sources: []models.Source{{ID: "a", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 4}, {ID: "b", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: a, models.SourceBloomberg: b}})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 4, Assets: []models.UserAsset{{Name: "Acme Holdings"}}, Sources: []models.Source{{ID: "a", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 4}, {ID: "b", SourceKey: testSourceKey(models.SourceInvesting), Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: a, models.SourceInvesting: b}})
result, err := uc.Generate(context.Background(), "u")
if err != nil || result.Summary == nil {
t.Fatalf("%+v %v", result.Outcome, err)
@ -58,10 +58,10 @@ func TestTicket34ThreePassesInputPoolPriorityAndLastBatchTrim(t *testing.T) {
}
}
func TestTicket34NoPartialSummaryOnMentionFailure(t *testing.T) {
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 5, Assets: []models.UserAsset{{Name: "Acme"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 5, Assets: []models.UserAsset{{Name: "Acme"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
sum := &contractSummarizer{}
gate := &mentionFixture{err: errors.New("private failure")}
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Acme"}, {Title: "unmatched"}}}}})
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: &contractScraper{articles: []scraper.Article{{Title: "Acme"}, {Title: "unmatched"}}}}})
r, err := uc.Generate(context.Background(), "u")
if err != nil || r.Summary != nil || r.Outcome.Status != "failed" || len(sum.articles) != 0 {
t.Fatal(r, err)
@ -89,8 +89,8 @@ func TestTicket34StopsAtReachingBatchWithoutReplacingEarlierPass(t *testing.T) {
}
old := newest.Add(-1000 * time.Hour)
articles = append(articles, scraper.Article{Title: "Acme Holdings", PublishedAt: &old})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 66, Assets: []models.UserAsset{{Name: "Acme Holdings"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 200}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: articles}}})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 66, Assets: []models.UserAsset{{Name: "Acme Holdings"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 200}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: &contractScraper{articles: articles}}})
r, err := uc.Generate(context.Background(), "u")
if err != nil || r.Outcome.Selected != 66 || !reflect.DeepEqual(gate.passes, []string{"direct", "direct"}) || !reflect.DeepEqual(gate.sizes, []int{64, 64}) {
t.Fatal(r.Outcome, gate.passes, gate.sizes, err)
@ -114,9 +114,9 @@ func TestTicket34DeterministicMentionUsesResolvedNamesAliasesAndModeOnly(t *test
id := "resolved"
gate := &mentionFixture{yes: map[string]map[string]bool{}}
sum := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: mode, GlobalLimit: 1, Assets: []models.UserAsset{{Name: "untrusted stored spelling", Symbol: "INTC", CompanyID: &id}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: mode, GlobalLimit: 1, Assets: []models.UserAsset{{Name: "untrusted stored spelling", Symbol: "INTC", CompanyID: &id}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
feed := &contractScraper{articles: []scraper.Article{{Title: "Intelligence and INTC", ContentState: scraper.ContentComplete, Content: "Intel invests."}}}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Names: fixtureNames{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}}).Generate(context.Background(), "u")
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Names: fixtureNames{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: feed}}).Generate(context.Background(), "u")
if err != nil {
t.Fatal(err)
}

View File

@ -149,7 +149,7 @@ func (r *Repository) ListSources() ([]Source, error) {
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
s := &Source{}
err := r.db.QueryRow(`
SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('yahoo_finance','bloomberg','cnbc_business','investing_com')`, sourceType,
SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('bloomberg','investing_com')`, sourceType,
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
if err == sql.ErrNoRows {
return nil, nil

View File

@ -0,0 +1,22 @@
package models
import "testing"
func TestTicket42OnlyRSSSourcesAreOperationalEvenIfLegacyRowsWereReenabled(t *testing.T) {
sources := []Source{}
for _, key := range []string{SourceYahooFinance, SourceCNBCBusiness, SourceWatcherGuru, SourceBloomberg, SourceInvesting} {
key := key
sources = append(sources, Source{ID: key, SourceKey: &key, Enabled: true, ArticleLimit: 77})
want := key == SourceBloomberg || key == SourceInvesting
if SupportedSourceKey(key) != want {
t.Errorf("source %s supported=%v, want %v", key, SupportedSourceKey(key), want)
}
}
got := OperationalSources(sources)
if len(got) != 2 || *got[0].SourceKey != SourceBloomberg || *got[1].SourceKey != SourceInvesting {
t.Fatal("legacy SQL-enabled source remained operational")
}
if !sources[0].Enabled || *sources[0].SourceKey != "yahoo_finance" || sources[0].ArticleLimit != 77 || *sources[1].SourceKey != "cnbc_business" {
t.Fatal("filter mutated historical identities/caps")
}
}

View File

@ -10,7 +10,7 @@ const (
func SupportedSourceKey(key string) bool {
switch key {
case SourceYahooFinance, SourceBloomberg, SourceCNBCBusiness, SourceInvesting:
case SourceBloomberg, SourceInvesting:
return true
}
return false

View File

@ -3,11 +3,11 @@ package models
import "testing"
func TestSourceSupportUsesOnlyCanonicalKeyAndPersistedEnabled(t *testing.T) {
yahoo := SourceYahooFinance
rss := SourceBloomberg
unknown := "reuters"
sources := []Source{
{ID: "supported", Type: "stocktwits", SourceKey: &yahoo, Enabled: true, ArticleLimit: 83},
{ID: "disabled", SourceKey: &yahoo, Enabled: false, ArticleLimit: 77},
{ID: "supported", Type: "bloomberg", SourceKey: &rss, Enabled: true, ArticleLimit: 83},
{ID: "disabled", SourceKey: &rss, Enabled: false, ArticleLimit: 77},
{ID: "legacy", Type: "stocktwits", Name: "Yahoo Finance", Enabled: true, ArticleLimit: 42},
{ID: "unknown", SourceKey: &unknown, Enabled: true, ArticleLimit: 31},
}
@ -23,17 +23,17 @@ func TestSourceSupportUsesOnlyCanonicalKeyAndPersistedEnabled(t *testing.T) {
}
}
func TestCNBCReplacesWatcherGuruWithoutAliasingHistoricalIdentity(t *testing.T) {
func TestRetiredCNBCAndWatcherKeepHistoricalIdentities(t *testing.T) {
cnbc, watcher := SourceCNBCBusiness, SourceWatcherGuru
sources := []Source{{ID: "new-cnbc", SourceKey: &cnbc, Enabled: true, ArticleLimit: 37}, {ID: "old-watcher", SourceKey: &watcher, Enabled: true, ArticleLimit: 64}}
if !sources[0].Supported() || sources[1].Supported() || sources[1].Operational() {
t.Fatal("retired WatcherGuru remains executable or CNBC unsupported")
if sources[0].Supported() || sources[0].Operational() || sources[1].Supported() || sources[1].Operational() {
t.Fatal("retired source remains executable")
}
operational := OperationalSources(sources)
if len(operational) != 1 || operational[0].ID != "new-cnbc" || operational[0].ArticleLimit != 37 {
if len(operational) != 0 {
t.Fatalf("operational=%+v", operational)
}
if *sources[1].SourceKey != "watcher_guru" || sources[1].ArticleLimit != 64 {
if *sources[0].SourceKey != "cnbc_business" || sources[0].ArticleLimit != 37 || !sources[0].Enabled || *sources[1].SourceKey != "watcher_guru" || sources[1].ArticleLimit != 64 {
t.Fatal("historical identity or cap mutated")
}
}

View File

@ -15,7 +15,7 @@ type personalInputs struct {
}
func (p *personalInputs) LoadUserInput(_ context.Context, id string) (generation.UserInput, error) {
key := models.SourceYahooFinance
key := models.SourceBloomberg
input := generation.UserInput{Language: "en", RankingMode: "title", GlobalLimit: 20, Sources: []models.Source{{ID: "source", Enabled: true, SourceKey: &key, ArticleLimit: 20}}}
if id != "account-a" {
model := "model-b"
@ -45,7 +45,7 @@ func (personalSummary) Summarize(context.Context, string, []models.UserAsset, []
func TestSchedulerActualUseCaseSkipsCollectionForUnselectedAccount(t *testing.T) {
repo := &personalInputs{saved: map[string]generation.GenerationRecord{}}
feed := &ticket13Feed{}
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, LayaRanker: ticket13Ranker{}, SummaryResolver: personalResolver{}})
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: feed}, LayaRanker: ticket13Ranker{}, SummaryResolver: personalResolver{}})
s := &Scheduler{users: twoPersonalModelUsers{}, generationUseCase: uc}
s.run()
if feed.calls != 1 || repo.saved["account-a"].Outcome.FailureCode != "summary_model_unavailable" || repo.saved["account-a"].Summary != nil {

View File

@ -41,10 +41,11 @@ func (f *ticket13Feed) Scrape(context.Context, []string) ([]scraper.Article, err
return []scraper.Article{{Title: "fixture"}}, nil
}
func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *testing.T) {
func TestScheduledGenerationUsesSameTwoRSSSourceAllowlistForEnabledLegacyRows(t *testing.T) {
var sources []models.Source
if err := json.Unmarshal([]byte(`[
{"id":"y","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":10},
{"id":"i","name":"Investing.com","type":"investing_com","source_key":"investing_com","enabled":true,"article_limit":20},
{"id":"b","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":10},
{"id":"c","name":"CNBC Business","type":"cnbc_business","source_key":"cnbc_business","enabled":true,"article_limit":20},
{"id":"w","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":10},
@ -54,7 +55,7 @@ func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *
}
feeds := map[string]*ticket13Feed{}
scrapers := map[string]scraper.Scraper{}
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "investing_com", "watcher_guru", "stocktwits", "reuters"} {
f := &ticket13Feed{}
feeds[key] = f
scrapers[key] = f
@ -62,12 +63,12 @@ func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *
uc := generation.NewUseCase(generation.Dependencies{Repository: ticket13Repository{generation.UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, Scrapers: scrapers, Ranker: ticket13Ranker{}, Summarizer: ticket13Summary{}})
s := &Scheduler{users: ticket13Users{}, generationUseCase: uc}
s.run()
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business"} {
for _, key := range []string{"bloomberg", "investing_com"} {
if feeds[key].calls != 1 {
t.Errorf("scheduled supported source %s calls=%d, want 1", key, feeds[key].calls)
}
}
for _, key := range []string{"watcher_guru", "stocktwits", "reuters"} {
for _, key := range []string{"yahoo_finance", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
if feeds[key].calls != 0 {
t.Errorf("scheduled legacy source %s was called %d times", key, feeds[key].calls)
}

View File

@ -52,7 +52,8 @@ Les snapshots `summary_model_id`, `provider_name`, `model_name` des nouvelles sy
La composition applicative utilise désormais `quanwenrss.Collector` pour Bloomberg
(`bloomberg`) et Investing.com (`investing_com`). Yahoo Finance et CNBC Business
restent enregistrés et inchangés. Les anciennes lignes, credentials et références
restaient enregistrés pendant #41 ; leur retrait opérationnel intervient en #42
(voir la section suivante). Les anciennes lignes, credentials et références
historiques Bloomberg restent conservés ; le parcours RSS n'utilise pas leurs
credentials et ne suit aucun lien d'article.
@ -122,3 +123,34 @@ sélection. Le contrat #39 demeure : titre, date nullable, source et corps inté
watchlist, contexte personnalisé, langue et budget de prompt avant synthèse.
Les candidats/GUID/corps restent en mémoire ; seules synthèse et statistiques
agrégées sont persistées.
## Retrait opérationnel Yahoo/CNBC — ticket #42
La décision utilisateur #42 remplace la période de compatibilité de #41 : les
nouvelles synthèses manuelles et planifiées utilisent exclusivement `bloomberg`
et `investing_com`. `SupportedSourceKey` et `OperationalSources` ignorent Yahoo
Finance et CNBC Business même si une écriture SQL les remet à `enabled=true`.
Le use case commun vérifie également `source.Operational()` avant tout appel de
scraper. La composition de production ne contient que les deux adapters RSS.
Les trois passes de sélection et le contrat de synthèse #39 restent inchangés.
La migration 000022 met uniquement `enabled=false` pour `yahoo_finance` et
`cnbc_business`. Elle conserve IDs, clés, types, noms, plafonds, contraintes,
credentials, références historiques, rapports et anciens bilans. Son `down` ne
réactive pas ces sources. Elle ne change pas la configuration ou l'état des deux
sources RSS. Les constantes legacy et la lecture des anciennes clés/types restent
disponibles ; aucun ancien bilan n'est recalculé ou réécrit.
`GET /api/admin/sources` conserve les lignes retirées avec `supported:false` et
`operational:false`. L'état `enabled` brut reste celui de la DB, même lors du
scénario défensif de réactivation SQL. Les demandes `PUT` valides de réactivation,
modification du plafond ou ajout de feeds sur ces lignes renvoient 409
`source_not_supported`, sans écriture. Le frontend présente Bloomberg/Investing.com
comme seules cartes configurables et les anciennes sources en lecture seule.
Les fixtures des tests de génération ont été déplacées vers les clés RSS actives.
Les tests des extracteurs historiques restent présents ; leur disponibilité ne
réintroduit aucun enregistrement dans la composition de production. La fixture
E2E utilise désormais Bloomberg comme source injectée et activée, avec transport
local factice et sans visite des articles. Les tests dédiés couvrent le refus API,
la préservation PostgreSQL, le dispatch manuel/planifié et la composition RSS seule.

View File

@ -381,7 +381,8 @@ Après migration 000021, Bloomberg utilise cinq flux QuanwenRSS et Investing.com
un flux dédié. L'administration `Sources et plafonds` permet d'enregistrer les
feeds, états et plafonds ; aucun accès réseau n'est déclenché par cet enregistrement.
Le contrat détaillé et les limites figurent dans `docs/architecture.md`, section
« Sources RSS QuanwenRSS — ticket #41 ». Yahoo et CNBC restent disponibles.
« Sources RSS QuanwenRSS — ticket #41 ». Depuis #42, Yahoo/CNBC sont retirées
des nouvelles synthèses (voir migration 000022 ci-dessous).
Le backend a uniquement besoin d'accéder aux chemins RSS approuvés sur
`feed.quanwenrss.com:443` pour ces deux sources. Il ne visite pas les articles et
@ -394,3 +395,18 @@ ont un corps complet : consulter les compteurs de feeds et de complétude du bil
En cas de changement du format réel, un `content:encoded` absent ne devient pas
complet par fallback sur `description`. Les tests et fixtures de ce lot n'effectuent
aucun contrôle live des feeds.
### Sources retirées à partir de la migration 000022 (#42)
Yahoo Finance et CNBC Business ne participent plus aux nouvelles synthèses,
manuelles ou planifiées. Seules Bloomberg RSS et Investing.com RSS sont
opérationnelles. La migration les désactive sans supprimer leurs données ; les
anciens noms, clés, IDs, plafonds, rapports et bilans restent conservés. Ne pas
utiliser une écriture SQL pour tenter de les réactiver : l'allowlist applicative
les exclut également et l'API admin refuse leur modification avec 409
`source_not_supported`. Un rollback de cette migration ne les réactive pas.
Les flux RSS et leurs réglages ne sont pas modifiés. La section « Sources
retirées » est en lecture seule ; aucune récupération ou nouvelle synthèse n'est
lancée depuis cette section. Les outils historiques ne sont pas enregistrés dans
la composition applicative.

View File

@ -22,14 +22,19 @@ test('admin source controls stay accessible and fit at 320, 375 and 390 px', asy
await expect(page.getByRole('heading', { name: 'Sources et plafonds' })).toBeVisible()
const activationControls = page.locator('button[aria-label^="Activer "], button[aria-label^="Désactiver "]')
await expect(activationControls).toHaveCount(4)
const activationNames = (await activationControls.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-label').replace(/^(Activer|Désactiver) /, '')).sort()))
expect(activationNames).toEqual(['Bloomberg', 'CNBC Business', 'Investing.com', 'Yahoo Finance'])
await expect(page.locator('form[aria-label^="Réglages de "]')).toHaveCount(4)
await expect(activationControls).toHaveCount(2)
const activationNames = await activationControls.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-label').replace(/^(Activer|Désactiver) /, '')).sort())
expect(activationNames).toEqual(['Bloomberg', 'Investing.com'])
await expect(page.locator('form[aria-label^="Réglages de "]')).toHaveCount(2)
const historical = page.getByRole('region', { name: 'Anciennes sources exclues' })
const historical = page.getByRole('region', { name: 'Sources retirées' })
await expect(historical).toBeVisible()
await historical.getByText(/^Consulter les anciennes sources/).click()
await historical.getByText(/^Consulter les sources retirées/).click()
for (const name of ['Yahoo Finance', 'CNBC Business']) {
await expect(historical.getByText(name, { exact: true })).toBeVisible()
await expect(page.getByRole('button', { name: `Activer ${name}`, exact: true })).toHaveCount(0)
await expect(page.getByRole('button', { name: `Désactiver ${name}`, exact: true })).toHaveCount(0)
}
const historicalRows = historical.locator('li')
expect(await historicalRows.count()).toBeGreaterThan(0)
await expect(historicalRows.locator('button, input, form, a')).toHaveCount(0)
@ -43,8 +48,8 @@ test('admin source controls stay accessible and fit at 320, 375 and 390 px', asy
expect(dimensions.document, `horizontal overflow at ${width}px: ${JSON.stringify(dimensions)}`).toBeLessThanOrEqual(dimensions.viewport)
await expect(page.getByRole('spinbutton', { name: 'Articles max par résumé' })).toBeVisible()
for (const name of ['Yahoo Finance', 'Bloomberg', 'CNBC Business', 'Investing.com']) {
const toggle = page.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) })
for (const name of ['Bloomberg', 'Investing.com']) {
const toggle = activationControls.filter({ hasText: /Activer|Désactiver/ }).and(page.getByRole('button', { name: new RegExp(name) }))
const cap = page.getByRole('spinbutton', { name: `Plafond ${name}` })
await expect(toggle).toBeVisible()
await expect(toggle).toBeEnabled()

View File

@ -6,7 +6,17 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
const SOURCE_KEYS = new Set(['yahoo_finance', 'bloomberg', 'cnbc_business', 'investing_com'])
const SOURCE_KEYS = new Set(['bloomberg', 'investing_com'])
function sourceName(source: Source) {
switch (source.source_key) {
case 'yahoo_finance': return 'Yahoo Finance'
case 'cnbc_business': return 'CNBC Business'
case 'bloomberg': return 'Bloomberg'
case 'investing_com': return 'Investing.com'
default: return source.name
}
}
function isSupported(source: Source) {
return source.supported === true && source.source_key !== null && SOURCE_KEYS.has(source.source_key)
@ -115,7 +125,7 @@ export function Sources() {
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Sources et plafonds</h1>
<p className="text-sm text-muted-foreground">Yahoo Finance, Bloomberg, CNBC Business et Investing.com peuvent participer aux synthèses manuelles et planifiées. Seules les sources activées sont utilisées, dans la limite de leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles ni génération immédiate.</p>
<p className="text-sm text-muted-foreground">Seules Bloomberg et Investing.com peuvent participer aux synthèses manuelles et planifiées, à partir de leurs flux RSS. Seules les sources activées sont utilisées, dans la limite de leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles ni génération immédiate.</p>
{loading ? <p role="status">Chargement des sources et plafonds…</p> : loadError ? (
<div className="space-y-3"><p role="alert">{loadError}</p><Button onClick={() => void load()}>Réessayer</Button></div>
) : <>
@ -133,16 +143,16 @@ export function Sources() {
</CardContent>
</Card>
{sources.length === 0 && <p>Aucune source disponible.</p>}
<div className="grid min-w-0 gap-4 lg:grid-cols-3">
{supported.map(source => <SourceLimit key={source.id} source={source.source_key === 'yahoo_finance' ? { ...source, name: 'Yahoo Finance' } : source.source_key === 'cnbc_business' ? { ...source, name: 'CNBC Business' } : source.source_key === 'investing_com' ? { ...source, name: 'Investing.com' } : source.source_key === 'bloomberg' ? { ...source, name: 'Bloomberg' } : source} />)}
<div className="grid min-w-0 gap-4 lg:grid-cols-2">
{supported.map(source => <SourceLimit key={source.id} source={{ ...source, name: sourceName(source) }} />)}
</div>
{historical.length > 0 && <section aria-labelledby="historical-sources-title" className="space-y-3">
<h2 id="historical-sources-title" className="text-lg font-semibold">Anciennes sources exclues</h2>
<h2 id="historical-sources-title" className="text-lg font-semibold">Sources retirées</h2>
<details className="rounded-md border p-4">
<summary className="cursor-pointer font-medium">Consulter les anciennes sources ({historical.length})</summary>
<summary className="cursor-pointer font-medium">Consulter les sources retirées ({historical.length})</summary>
<p className="mt-3 text-sm text-muted-foreground">Ces sources sont conservées en lecture seule et exclues des synthèses manuelles et planifiées. Elles ne peuvent pas être réactivées. Les bilans des générations passées restent inchangés.</p>
<ul className="mt-3 space-y-3">{historical.map(source => <li key={source.id} className="break-words">
<p className="font-medium">{source.name}</p>
<p className="font-medium">{sourceName(source)}</p>
<p className="text-sm text-muted-foreground">Exclue des synthèses · Plafond historique : {source.article_limit}</p>
</li>)}</ul>
</details>

View File

@ -23,7 +23,7 @@ describe('plafonds d’articles administrateur', () => {
listSettings.mockResolvedValue([{ key: 'summary_max_articles', value: '700' }])
getDefaultPrompt.mockResolvedValue({ prompt: 'system' })
updateSettings.mockResolvedValue(undefined)
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 240 }])
listSources.mockResolvedValue([{ id: 'source-1', name: 'Bloomberg', type: 'rss', source_key: 'bloomberg', supported: true, operational: true, enabled: true, article_limit: 240 }])
updateSource.mockResolvedValue(undefined)
})
@ -47,7 +47,7 @@ describe('plafonds d’articles administrateur', () => {
it('borne chaque plafond source de 1 à 200 et conserve une ancienne valeur hors plage', async () => {
render(<Sources />)
const input = await screen.findByLabelText('Plafond Yahoo Finance')
const input = await screen.findByLabelText('Plafond Bloomberg')
expect(input).toHaveValue(240)
expect(input).toHaveAttribute('min', '1')
expect(input).toHaveAttribute('max', '200')
@ -56,10 +56,10 @@ describe('plafonds d’articles administrateur', () => {
it('sauvegarde le plafond de la source via l’API admin', async () => {
const user = userEvent.setup()
render(<Sources />)
const input = await screen.findByLabelText('Plafond Yahoo Finance')
const input = await screen.findByLabelText('Plafond Bloomberg')
await user.clear(input)
await user.type(input, '20')
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' }))
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Bloomberg' }))
await waitFor(() => expect(updateSource).toHaveBeenCalledWith('source-1', true, 20))
})
it('remplace l’éditeur en doublon dans Paramètres par un lien et garde le filtre séparé', async () => {
@ -93,21 +93,21 @@ describe('plafonds d’articles administrateur', () => {
it('initialise uniquement les valeurs absentes à 50 et 20', async () => {
listSettings.mockResolvedValue([])
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true }])
listSources.mockResolvedValue([{ id: 'source-1', name: 'Bloomberg', type: 'rss', source_key: 'bloomberg', supported: true, operational: true, enabled: true }])
render(<Sources />)
expect(await screen.findByLabelText('Articles max par résumé')).toHaveValue(50)
expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(20)
expect(screen.getByLabelText('Plafond Bloomberg')).toHaveValue(20)
})
it('conserve le plafond historique pendant la désactivation et la réactivation', async () => {
const user = userEvent.setup()
render(<Sources />)
const input = await screen.findByLabelText('Plafond Yahoo Finance')
await user.click(screen.getByRole('button', { name: 'Désactiver Yahoo Finance' }))
const input = await screen.findByLabelText('Plafond Bloomberg')
await user.click(screen.getByRole('button', { name: 'Désactiver Bloomberg' }))
await waitFor(() => expect(input).toBeDisabled())
expect(input).toHaveValue(240)
expect(updateSource).toHaveBeenLastCalledWith('source-1', false)
await user.click(screen.getByRole('button', { name: 'Activer Yahoo Finance' }))
await user.click(screen.getByRole('button', { name: 'Activer Bloomberg' }))
await waitFor(() => expect(input).toBeEnabled())
expect(input).toHaveValue(240)
expect(updateSource).toHaveBeenLastCalledWith('source-1', true)
@ -127,10 +127,10 @@ describe('plafonds d’articles administrateur', () => {
expect(screen.queryByRole('status')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Enregistrer', exact: true }))
expect(await screen.findByRole('status')).toHaveTextContent('Plafond global enregistré.')
const source = screen.getByLabelText('Plafond Yahoo Finance')
const source = screen.getByLabelText('Plafond Bloomberg')
await user.clear(source)
await user.type(source, '20')
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' }))
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Bloomberg' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Impossible d’enregistrer le plafond.')
expect(source).toHaveValue(20)
})
@ -138,8 +138,8 @@ describe('plafonds d’articles administrateur', () => {
it('rejette les plafonds source hors bornes et fractionnaires sans les écrêter', async () => {
const user = userEvent.setup()
render(<Sources />)
const input = await screen.findByLabelText('Plafond Yahoo Finance')
const save = screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' })
const input = await screen.findByLabelText('Plafond Bloomberg')
const save = screen.getByRole('button', { name: 'Enregistrer le plafond Bloomberg' })
for (const value of ['0', '201', '1.5']) {
await user.clear(input)
await user.type(input, value)
@ -149,35 +149,31 @@ describe('plafonds d’articles administrateur', () => {
expect(updateSource).not.toHaveBeenCalled()
})
it('ne rend activables que Yahoo, Bloomberg et CNBC Business; garde Watcher Guru, StockTwits et Reuters en historique sans commandes', async () => {
it('ne rend activables que Bloomberg et Investing.com; conserve les autres sources sans commandes', async () => {
listSources.mockResolvedValue([
{ id: 'y', name: 'Yahoo Finance', type: 'stocktwits', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 83 },
{ id: 'b', name: 'Bloomberg', type: 'bloomberg', source_key: 'bloomberg', supported: true, operational: true, enabled: false, article_limit: 77 },
{ id: 'c', name: 'CNBC Business', type: 'cnbc_business', source_key: 'cnbc_business', supported: true, operational: true, enabled: true, article_limit: 20 },
{ id: 'y', name: 'Yahoo Finance', type: 'stocktwits', source_key: 'yahoo_finance', supported: false, operational: false, enabled: false, article_limit: 83 },
{ id: 'b', name: 'Bloomberg', type: 'bloomberg', source_key: 'bloomberg', supported: true, operational: false, enabled: false, article_limit: 77 },
{ id: 'i', name: 'Investing.com', type: 'rss', source_key: 'investing_com', supported: true, operational: true, enabled: true, article_limit: 20 },
{ id: 'c', name: 'CNBC Business', type: 'cnbc_business', source_key: 'cnbc_business', supported: false, operational: false, enabled: false, article_limit: 20 },
{ id: 'w', name: 'Watcher.Guru', type: 'watcherguru', source_key: 'watcher_guru', supported: false, operational: false, enabled: false, article_limit: 64 },
{ id: 's', name: 'StockTwits', type: 'stocktwits', source_key: null, supported: false, operational: false, enabled: false, article_limit: 31 },
{ id: 'r', name: 'Reuters', type: 'reuters', source_key: null, supported: false, operational: false, enabled: false, article_limit: 42 },
])
render(<Sources />)
expect(await screen.findByRole('heading', { name: 'Anciennes sources exclues' })).toBeInTheDocument()
for (const name of ['Yahoo Finance', 'Bloomberg', 'CNBC Business']) {
expect(await screen.findByRole('heading', { name: 'Sources retirées' })).toBeInTheDocument()
for (const name of ['Bloomberg', 'Investing.com']) {
expect(screen.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name}$`) })).toBeInTheDocument()
expect(screen.getByLabelText(`Plafond ${name}`)).toBeInTheDocument()
}
const historical = screen.getByRole('region', { name: 'Anciennes sources exclues' })
expect(within(historical).getByText('StockTwits')).toBeInTheDocument()
expect(within(historical).getByText('Watcher.Guru')).toBeInTheDocument()
const historical = screen.getByRole('region', { name: 'Sources retirées' })
for (const name of ['Yahoo Finance', 'CNBC Business', 'StockTwits', 'Watcher.Guru', 'Reuters']) {
expect(within(historical).getByText(name)).toBeInTheDocument()
expect(screen.queryByLabelText(`Plafond ${name}`)).not.toBeInTheDocument()
}
expect(within(historical).getByText('Exclue des synthèses · Plafond historique : 64')).toBeInTheDocument()
expect(within(historical).getByText('Reuters')).toBeInTheDocument()
expect(within(historical).queryByRole('button')).not.toBeInTheDocument()
expect(within(historical).queryByRole('spinbutton')).not.toBeInTheDocument()
const yahooCard = screen.getByRole('form', { name: 'Réglages de Yahoo Finance' }).closest('.rounded-md')
expect(yahooCard).not.toBeNull()
expect(within(yahooCard as HTMLElement).queryByText(/stocktwits/i)).not.toBeInTheDocument()
expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(83)
expect(historical.querySelectorAll('button,input,form,a')).toHaveLength(0)
expect(screen.getByLabelText('Plafond Bloomberg')).toHaveValue(77)
expect(screen.getByLabelText('Plafond CNBC Business')).toHaveValue(20)
expect(screen.queryByLabelText('Plafond Watcher.Guru')).not.toBeInTheDocument()
expect(screen.getByLabelText('Plafond Investing.com')).toHaveValue(20)
})
it('garde les anciennes sources repliées et en lecture seule même si enabled est historique', async () => {
@ -186,10 +182,10 @@ describe('plafonds d’articles administrateur', () => {
])
const user = userEvent.setup()
render(<Sources />)
const region = await screen.findByRole('region', { name: 'Anciennes sources exclues' })
const region = await screen.findByRole('region', { name: 'Sources retirées' })
const disclosure = region.querySelector('details')!
expect(disclosure).not.toHaveAttribute('open')
await user.click(within(region).getByText('Consulter les anciennes sources (1)'))
await user.click(within(region).getByText('Consulter les sources retirées (1)'))
expect(disclosure).toHaveAttribute('open')
expect(within(region).getByText('Reuters')).toBeVisible()
expect(within(region).queryByRole('button')).not.toBeInTheDocument()
@ -198,19 +194,19 @@ describe('plafonds d’articles administrateur', () => {
})
it('annonce les réglages des prochaines synthèses sans annoncer de génération lancée', async () => {
listSources.mockResolvedValue([{ id: 'y', name: 'Stocktwits', type: 'stocktwits', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 83 }])
listSources.mockResolvedValue([{ id: 'y', name: 'Stocktwits', type: 'stocktwits', source_key: 'bloomberg', supported: true, operational: true, enabled: true, article_limit: 83 }])
const user = userEvent.setup()
render(<Sources />)
const input = await screen.findByLabelText('Plafond Yahoo Finance')
const input = await screen.findByLabelText('Plafond Bloomberg')
expect(screen.queryByText('Stocktwits')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Désactiver Yahoo Finance' }))
expect(await screen.findByRole('status')).toHaveTextContent('Yahoo Finance désactivée pour les prochaines synthèses. Aucune génération n’a été lancée.')
await user.click(screen.getByRole('button', { name: 'Désactiver Bloomberg' }))
expect(await screen.findByRole('status')).toHaveTextContent('Bloomberg désactivée pour les prochaines synthèses. Aucune génération n’a été lancée.')
expect(input).toHaveValue(83)
expect(input).toBeDisabled()
await user.click(screen.getByRole('button', { name: 'Activer Yahoo Finance' }))
await user.click(screen.getByRole('button', { name: 'Activer Bloomberg' }))
await waitFor(() => expect(input).toBeEnabled())
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' }))
expect(await screen.findByRole('status')).toHaveTextContent('Plafond Yahoo Finance enregistré pour les prochaines synthèses.')
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Bloomberg' }))
expect(await screen.findByRole('status')).toHaveTextContent('Plafond Bloomberg enregistré pour les prochaines synthèses.')
expect(updateSource).toHaveBeenLastCalledWith('y', true, 83)
})
@ -221,37 +217,37 @@ describe('plafonds d’articles administrateur', () => {
expect(await screen.findByRole('alert')).toHaveTextContent('Impossible de charger')
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Réessayer' }))
expect(await screen.findByLabelText('Plafond Yahoo Finance')).toHaveValue(240)
expect(await screen.findByLabelText('Plafond Bloomberg')).toHaveValue(240)
})
it('sauvegarde le plafond CNBC et refuse toute commande Watcher Guru même avec un ancien DTO activable', async () => {
it('sauvegarde le plafond Investing.com et refuse toute commande Watcher Guru même avec un ancien DTO activable', async () => {
listSources.mockResolvedValue([
{ id: 'cnbc-new', name: 'CNBC Business', type: 'cnbc_business', source_key: 'cnbc_business', supported: true, operational: true, enabled: true, article_limit: 37 },
{ id: 'investing-new', name: 'Investing.com', type: 'rss', source_key: 'investing_com', supported: true, operational: true, enabled: true, article_limit: 37 },
{ id: 'watcher-old', name: 'Watcher.Guru', type: 'watcherguru', source_key: 'watcher_guru', supported: true, operational: true, enabled: true, article_limit: 64 },
])
const user = userEvent.setup()
render(<Sources />)
const cap = await screen.findByLabelText('Plafond CNBC Business')
const cap = await screen.findByLabelText('Plafond Investing.com')
expect(cap).toHaveValue(37)
expect(screen.queryByRole('button', { name: /^(Activer|Désactiver) Watcher/ })).not.toBeInTheDocument()
const historical = screen.getByRole('region', { name: 'Anciennes sources exclues' })
const historical = screen.getByRole('region', { name: 'Sources retirées' })
expect(within(historical).getByText('Watcher.Guru')).toBeInTheDocument()
expect(within(historical).queryByRole('spinbutton')).not.toBeInTheDocument()
expect(within(historical).queryByRole('button')).not.toBeInTheDocument()
await user.clear(cap)
await user.type(cap, '42')
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond CNBC Business' }))
await waitFor(() => expect(updateSource).toHaveBeenCalledWith('cnbc-new', true, 42))
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Investing.com' }))
await waitFor(() => expect(updateSource).toHaveBeenCalledWith('investing-new', true, 42))
expect(updateSource).toHaveBeenCalledTimes(1)
expect(await screen.findByRole('status')).toHaveTextContent('Plafond CNBC Business enregistré pour les prochaines synthèses.')
expect(screen.getByText(/Yahoo Finance, Bloomberg, CNBC Business et Investing.com/)).toBeInTheDocument()
expect(await screen.findByRole('status')).toHaveTextContent('Plafond Investing.com enregistré pour les prochaines synthèses.')
expect(screen.getByText(/Seules Bloomberg et Investing.com/)).toBeInTheDocument()
})
})
describe('ticket #41 — sources additives', () => {
describe('ticket #42 — sources RSS et sources retirées', () => {
afterEach(cleanup)
it('affiche Investing.com depuis la clé canonique backend et conserve Yahoo Finance et CNBC Business', async () => {
it('affiche Investing.com depuis la clé canonique backend et conserve Yahoo Finance et CNBC Business en lecture seule', async () => {
listSettings.mockResolvedValue([])
listSources.mockResolvedValue([
{ id: 'b', source_key: 'bloomberg', name: 'Bloomberg', type: 'rss', supported: true, operational: true, enabled: true, article_limit: 20 },
@ -263,8 +259,11 @@ describe('ticket #41 — sources additives', () => {
expect(await screen.findByRole('heading', { name: 'Investing.com' })).toBeInTheDocument()
expect(screen.getByLabelText('Plafond Investing.com')).toHaveValue(40)
expect(screen.getByRole('button', { name: 'Activer Investing.com' })).toBeEnabled()
expect(screen.getByRole('button', { name: 'Désactiver Yahoo Finance' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Désactiver CNBC Business' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /^(Activer|Désactiver) Yahoo Finance$/ })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /^(Activer|Désactiver) CNBC Business$/ })).not.toBeInTheDocument()
const retired = screen.getByRole('region', { name: 'Sources retirées' })
expect(within(retired).getByText('Yahoo Finance')).toBeInTheDocument()
expect(within(retired).getByText('CNBC Business')).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: 'Legacy RSS label' })).not.toBeInTheDocument()
})
})

View File

@ -0,0 +1,80 @@
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { Sources } from '../src/pages/admin/Sources'
import { GenerationDetails } from '../src/components/GenerationDetails'
import type { GenerationOutcome } from '../src/api/summaries'
const { listSources, listSettings, updateSource, updateSettings, updateSourceFeeds } = vi.hoisted(() => ({
listSources: vi.fn(), listSettings: vi.fn(), updateSource: vi.fn(), updateSettings: vi.fn(), updateSourceFeeds: vi.fn(),
}))
vi.mock('@/api/admin', () => ({ adminApi: { listSources, listSettings, updateSource, updateSettings, updateSourceFeeds } }))
const sources = [
{ id: 'b', source_key: 'bloomberg', name: 'Bloomberg', type: 'rss', supported: true, operational: true, enabled: true, article_limit: 20, feed_urls: ['https://feed.quanwenrss.com/feed/bloomberg-latest.xml'] },
{ id: 'i', source_key: 'investing_com', name: 'Investing.com', type: 'rss', supported: true, operational: false, enabled: false, article_limit: 40, feed_urls: ['https://feed.quanwenrss.com/feed/investing-news.xml'] },
{ id: 'y', source_key: 'yahoo_finance', name: 'Stocktwits', type: 'stocktwits', supported: false, operational: false, enabled: false, article_limit: 83 },
{ id: 'c', source_key: 'cnbc_business', name: 'legacy', type: 'cnbc_business', supported: false, operational: false, enabled: false, article_limit: 37 },
]
beforeEach(() => {
vi.clearAllMocks()
listSources.mockResolvedValue(sources)
listSettings.mockResolvedValue([{ key: 'summary_max_articles', value: '50' }])
updateSource.mockResolvedValue(undefined); updateSettings.mockResolvedValue(undefined); updateSourceFeeds.mockResolvedValue(undefined)
})
afterEach(cleanup)
it('ne propose que les deux sources RSS configurables et conserve leurs plafonds, flux et activation', async () => {
render(<Sources />)
await screen.findByRole('heading', { name: 'Bloomberg' })
expect(screen.getAllByRole('button', { name: /^(Activer|Désactiver) / })).toHaveLength(2)
for (const name of ['Bloomberg', 'Investing.com']) {
expect(screen.getByLabelText(`Plafond ${name}`)).toBeInTheDocument()
expect(screen.getByRole('form', { name: `Flux RSS ${name}` })).toBeInTheDocument()
}
expect(screen.getByLabelText('Articles max par résumé')).toHaveValue(50)
expect(screen.getByText(/Seules Bloomberg et Investing.com/)).toBeInTheDocument()
})
it('présente Yahoo/CNBC dans Sources retirées repliée et en lecture seule, avec leurs anciens plafonds', async () => {
const before = JSON.stringify(sources)
render(<Sources />)
const region = await screen.findByRole('region', { name: 'Sources retirées' })
const details = region.querySelector('details')!
expect(details).not.toHaveAttribute('open')
await userEvent.click(within(region).getByText('Consulter les sources retirées (2)'))
expect(details).toHaveAttribute('open')
expect(within(region).getByText('Yahoo Finance')).toBeVisible()
expect(within(region).getByText('CNBC Business')).toBeVisible()
expect(within(region).getByText('Exclue des synthèses · Plafond historique : 83')).toBeVisible()
expect(within(region).getByText('Exclue des synthèses · Plafond historique : 37')).toBeVisible()
expect(region.querySelectorAll('button,input,select,form,a')).toHaveLength(0)
expect(screen.queryByLabelText('Plafond Yahoo Finance')).not.toBeInTheDocument()
expect(screen.queryByLabelText('Plafond CNBC Business')).not.toBeInTheDocument()
expect(screen.queryByText('Stocktwits')).not.toBeInTheDocument()
expect(updateSource).not.toHaveBeenCalled()
expect(updateSettings).not.toHaveBeenCalled()
expect(updateSourceFeeds).not.toHaveBeenCalled()
expect(JSON.stringify(sources)).toBe(before)
})
it('ne réactive pas Yahoo/CNBC même avec un ancien DTO déclarant ces lignes activées et prises en charge', async () => {
listSources.mockResolvedValue(sources.map(source => ({ ...source, enabled: true, supported: true, operational: true })))
render(<Sources />)
await screen.findByRole('heading', { name: 'Bloomberg' })
expect(screen.queryByRole('button', { name: /^(Activer|Désactiver) (Yahoo Finance|CNBC Business)$/ })).not.toBeInTheDocument()
expect(screen.queryByRole('form', { name: /Réglages de (Yahoo Finance|CNBC Business)/ })).not.toBeInTheDocument()
const retired = screen.getByRole('region', { name: 'Sources retirées' })
expect(within(retired).getByText('Yahoo Finance')).toBeInTheDocument()
expect(within(retired).getByText('CNBC Business')).toBeInTheDocument()
})
it.each([['yahoo_finance', 'Yahoo Finance'], ['cnbc_business', 'CNBC Business']])('conserve le libellé du bilan historique %s et ses agrégats', (source_key, name) => {
const outcome: GenerationOutcome = { id: 'historic', status: 'partial', language: 'fr', ranking_mode: 'title', total_candidates: 4, selected: 2, laya_selected: 2, content_fallbacks: 0, global_limit: 50,
source_stats: [{ source_id: 'old', source_key, source_type: 'stocktwits', status: 'failed', candidates: 4, selected: 2, laya_selected: 2, article_limit: 83, content_fallbacks: 0 }] }
const before = JSON.stringify(outcome)
render(<GenerationDetails outcome={outcome} />)
expect(screen.getByText(`Cette synthèse a été générée sans ${name}, indisponible lors du traitement.`)).toBeInTheDocument()
expect(screen.getByText(name, { exact: true })).toBeInTheDocument()
expect(screen.getByText('4 articles examinés · 2 sélectionnés par Laya · 2 retenus après plafonds')).toBeInTheDocument()
expect(JSON.stringify(outcome)).toBe(before)
})