feat(sources): replace WatcherGuru with CNBC Business

Add the CNBC Business RSS source, switch supported-source wiring and reporting, and migrate existing WatcherGuru rows to disabled historical status without rewriting references.

Refs #23

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 17:17:15 +01:00
parent 1ff78a7b31
commit 64a7124889
18 changed files with 511 additions and 26 deletions

View File

@ -75,7 +75,7 @@ Laya est le moteur de classement dédié : adapter HTTP pour [Laya v0.5.2](https
Le modèle de synthèse est choisi par compte dans le catalogue admin `ai_provider_models`, indépendamment des anciens réglages globaux qui restent stockés mais inertes pour la génération. Sans sélection ou avec modèle désactivé/invalide, la génération échoue avec `summary_model_unavailable` avant source/Laya. Les nouvelles synthèses gardent un snapshot du provider et du modèle effectivement résolus ; les anciennes restent inconnues sur ces champs. Supprimer un modèle sélectionné renvoie 409. Le modèle de synthèse est choisi par compte dans le catalogue admin `ai_provider_models`, indépendamment des anciens réglages globaux qui restent stockés mais inertes pour la génération. Sans sélection ou avec modèle désactivé/invalide, la génération échoue avec `summary_model_unavailable` avant source/Laya. Les nouvelles synthèses gardent un snapshot du provider et du modèle effectivement résolus ; les anciennes restent inconnues sur ces champs. Supprimer un modèle sélectionné renvoie 409.
Tous les candidats des sources autorisées sont traités en mémoire ; sélection/ordre Laya puis plafonds source/global. Aucune nouvelle archive article. Le mode `title_content` reste enregistrable : si le contenu est absent ou égal au titre, le classement utilise explicitement le titre seul et compte ce fallback. Les synthèses et bilans agrégés sont persistés ; les anciennes archives restent intactes. Les sources exécutables sont Yahoo Finance, Bloomberg et CNBC Business ; WatcherGuru reste conservé mais désactivé et non supporté depuis la migration 000018. Tous les candidats des sources autorisées sont traités en mémoire ; sélection/ordre Laya puis plafonds source/global. Aucune nouvelle archive article. Le mode `title_content` reste enregistrable : si le contenu est absent ou égal au titre, le classement utilise explicitement le titre seul et compte ce fallback. Les synthèses et bilans agrégés sont persistés ; les anciennes archives restent intactes.
La PWA précharge les assets statiques, sans cache runtime des API privées. Son activation supprime l’ancien CacheStorage `api-cache`. Les données privées ne deviennent pas disponibles hors ligne. L’installation PWA exige un contexte sécurisé (HTTPS ou localhost). La PWA précharge les assets statiques, sans cache runtime des API privées. Son activation supprime l’ancien CacheStorage `api-cache`. Les données privées ne deviennent pas disponibles hors ligne. L’installation PWA exige un contexte sécurisé (HTTPS ou localhost).

View File

@ -13,7 +13,7 @@ import (
"github.com/tradarr/backend/internal/models" "github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper" "github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/bloomberg" "github.com/tradarr/backend/internal/scraper/bloomberg"
"github.com/tradarr/backend/internal/scraper/watcherguru" "github.com/tradarr/backend/internal/scraper/cnbcbusiness"
"github.com/tradarr/backend/internal/scraper/yahoofinance" "github.com/tradarr/backend/internal/scraper/yahoofinance"
"github.com/tradarr/backend/internal/server" "github.com/tradarr/backend/internal/server"
) )
@ -52,7 +52,7 @@ func main() {
feeds := map[string]scraper.Scraper{ feeds := map[string]scraper.Scraper{
models.SourceBloomberg: bloomberg.NewDynamic(repo, enc, cfg.ScraperURL), models.SourceBloomberg: bloomberg.NewDynamic(repo, enc, cfg.ScraperURL),
models.SourceYahooFinance: yahoofinance.New(), models.SourceYahooFinance: yahoofinance.New(),
models.SourceWatcherGuru: watcherguru.New(), models.SourceCNBCBusiness: cnbcbusiness.New(),
} }
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true}) app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})

View File

@ -0,0 +1,3 @@
-- Non-destructive retirement on downgrade: retain CNBC identity/history and
-- permissive historical constraint values. Never auto-reactivate WatcherGuru.
UPDATE sources SET enabled=false WHERE source_key='cnbc_business';

View File

@ -0,0 +1,16 @@
-- Atomic even when executed as a standalone statement. Preserve retired source
-- IDs, source keys, caps and all referencing history; never repurpose a row.
DO $migration$
BEGIN
LOCK TABLE sources IN ACCESS EXCLUSIVE MODE;
ALTER TABLE sources DROP CONSTRAINT sources_type_check;
ALTER TABLE sources ADD CONSTRAINT sources_type_check
CHECK (type IN ('bloomberg','stocktwits','reuters','watcherguru','cnbc_business'));
ALTER TABLE sources DROP CONSTRAINT sources_source_key_check;
ALTER TABLE sources ADD CONSTRAINT sources_source_key_check
CHECK (source_key IN ('yahoo_finance','bloomberg','watcher_guru','cnbc_business'));
UPDATE sources SET enabled=false WHERE source_key='watcher_guru';
INSERT INTO sources(id,name,type,enabled,article_limit,source_key)
VALUES(gen_random_uuid(),'CNBC Business','cnbc_business',true,20,'cnbc_business');
END
$migration$;

View File

@ -0,0 +1,104 @@
package migrations
import (
"os"
"regexp"
"strings"
"testing"
)
func TestCNBCMigrationRetainsWatcherIdentityAndHistoricalReferencesPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
for _, q := range []string{
`ALTER TABLE sources ADD CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','reuters','watcherguru'))`,
`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES('y','Yahoo Finance','stocktwits',true,83),('b','Bloomberg','bloomberg',false,77),('w','Watcher.Guru','watcherguru',true,64)`,
`INSERT INTO articles(id,source_id,title,url) VALUES('old-article','w','historic','https://fixture.invalid/history')`,
} {
if _, err := db.Exec(q); err != nil {
t.Fatal(err)
}
}
applyTicket13(t, db)
migration, err := os.ReadFile("000018_cnbc_business.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(migration)); err != nil {
t.Fatal(err)
}
var name, typ, key string
var enabled bool
var cap int
if err = db.QueryRow(`SELECT name,type,source_key,enabled,article_limit FROM sources WHERE id='w'`).Scan(&name, &typ, &key, &enabled, &cap); err != nil {
t.Fatal(err)
}
if name != "Watcher.Guru" || typ != "watcherguru" || key != "watcher_guru" || enabled || cap != 64 {
t.Fatal("Watcher identity/cap changed or still enabled")
}
var cnbcID string
if err = db.QueryRow(`SELECT id,enabled,article_limit FROM sources WHERE source_key='cnbc_business'`).Scan(&cnbcID, &enabled, &cap); err != nil {
t.Fatal(err)
}
if cnbcID == "w" || !regexp.MustCompile(`^[0-9a-f-]{36}$`).MatchString(cnbcID) || !enabled || cap != 20 {
t.Fatalf("new identity=%s enabled=%v cap=%d", cnbcID, enabled, cap)
}
var source string
if err = db.QueryRow(`SELECT source_id FROM articles WHERE id='old-article'`).Scan(&source); err != nil || source != "w" {
t.Fatalf("historical reference=%s err=%v", source, err)
}
if _, err = db.Exec(`UPDATE sources SET source_key='watcher_guru' WHERE id='w'`); err != nil {
t.Fatalf("legacy key no longer permitted by constraint: %v", err)
}
if _, err = db.Exec(`UPDATE sources SET source_key='unsupported' WHERE id='w'`); err == nil {
t.Fatal("unknown key accepted")
}
if _, err = db.Exec(`UPDATE sources SET type='unsupported' WHERE id='w'`); err == nil {
t.Fatal("unknown type accepted")
}
var count int
if err = db.QueryRow(`SELECT count(*) FROM sources`).Scan(&count); err != nil || count != 4 {
t.Fatalf("unexpected source count=%d %v", count, err)
}
var yahooCap, bloombergCap int
if err = db.QueryRow(`SELECT article_limit FROM sources WHERE id='y'`).Scan(&yahooCap); err != nil {
t.Fatal(err)
}
if err = db.QueryRow(`SELECT article_limit FROM sources WHERE id='b'`).Scan(&bloombergCap); err != nil || yahooCap != 83 || bloombergCap != 77 {
t.Fatal("other caps changed")
}
}
func TestCNBCMigrationFailureRollsBackWatcherAndConstraintChangesPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
for _, q := range []string{
`ALTER TABLE sources ADD CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','reuters','watcherguru'))`,
`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES('y','Yahoo Finance','stocktwits',true,83),('b','Bloomberg','bloomberg',false,77),('w','Watcher.Guru','watcherguru',true,64)`,
`ALTER TABLE sources ADD CONSTRAINT fixture_refuse_cnbc CHECK(name <> 'CNBC Business')`,
} {
if _, err := db.Exec(q); err != nil {
t.Fatal(err)
}
}
applyTicket13(t, db)
migration, err := os.ReadFile("000018_cnbc_business.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(migration)); err == nil {
t.Fatal("expected insert failure")
}
var enabled bool
var count int
var constraint string
if err = db.QueryRow(`SELECT enabled FROM sources WHERE id='w'`).Scan(&enabled); err != nil || !enabled {
t.Fatal("failed migration disabled WatcherGuru")
}
if err = db.QueryRow(`SELECT count(*) FROM sources`).Scan(&count); err != nil || count != 3 {
t.Fatal("failed migration changed source rows")
}
if err = db.QueryRow(`SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid='sources'::regclass AND conname='sources_source_key_check'`).Scan(&constraint); err != nil || strings.Contains(constraint, "cnbc_business") {
t.Fatal("failed migration changed source key constraint")
}
}

View File

@ -29,18 +29,18 @@ func (f *symbolFeed) Scrape(_ context.Context, s []string) ([]scraper.Article, e
} }
func TestPerSourceCompanyHintsDoNotChangeOtherFeeds(t *testing.T) { func TestPerSourceCompanyHintsDoNotChangeOtherFeeds(t *testing.T) {
yahoo, bloomberg, watcher := &symbolFeed{}, &symbolFeed{}, &symbolFeed{} yahoo, bloomberg, cnbc, watcher := &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")}}} input := UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 20, Assets: []models.UserAsset{{CompanyID: pointer("isin:company"), Name: "Company", Symbol: "HISTORIC INDEX", YahooSymbol: pointer("9888.HK")}}}
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceWatcherGuru} { for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceCNBCBusiness, models.SourceWatcherGuru} {
key := key key := key
input.Sources = append(input.Sources, models.Source{ID: key, SourceKey: &key, Enabled: true, ArticleLimit: 20}) 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{}} repo := &contractRepository{inputs: map[string]UserInput{"owner": input}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, LayaRanker: &contractRanker{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: yahoo, models.SourceBloomberg: bloomberg, models.SourceWatcherGuru: watcher}}) 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}})
if _, err := uc.Generate(context.Background(), "owner"); err != nil { if _, err := uc.Generate(context.Background(), "owner"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if !reflect.DeepEqual(yahoo.symbols, []string{"9888.HK"}) || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(watcher.symbols, bloomberg.symbols) { if !reflect.DeepEqual(yahoo.symbols, []string{"9888.HK"}) || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(cnbc.symbols, bloomberg.symbols) || watcher.symbols != nil {
t.Fatalf("Yahoo=%v Bloomberg=%v Watcher=%v", yahoo.symbols, bloomberg.symbols, watcher.symbols) t.Fatalf("Yahoo=%v Bloomberg=%v Watcher=%v", yahoo.symbols, bloomberg.symbols, watcher.symbols)
} }
} }

View File

@ -14,6 +14,7 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
if err := json.Unmarshal([]byte(`[ if err := json.Unmarshal([]byte(`[
{"id":"y","name":"Yahoo Finance","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":20}, {"id":"y","name":"Yahoo Finance","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":20},
{"id":"b","name":"Bloomberg","type":"bloomberg","source_key":"bloomberg","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}, {"id":"w","name":"Watcher.Guru","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":20},
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":20}, {"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":20},
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":20} {"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":20}
@ -22,7 +23,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{}} 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{} feeds := map[string]*contractScraper{}
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} { for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
feeds[key] = &contractScraper{name: key, articles: []scraper.Article{{Title: key}}} feeds[key] = &contractScraper{name: key, articles: []scraper.Article{{Title: key}}}
} }
scrapers := map[string]scraper.Scraper{} scrapers := map[string]scraper.Scraper{}
@ -33,12 +34,12 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
if err != nil || result.Summary == nil { if err != nil || result.Summary == nil {
t.Fatalf("generation result=%+v err=%v", result, err) t.Fatalf("generation result=%+v err=%v", result, err)
} }
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} { for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business"} {
if len(feeds[key].calls) != 1 { if len(feeds[key].calls) != 1 {
t.Errorf("target %s calls=%d, want one", key, len(feeds[key].calls)) t.Errorf("target %s calls=%d, want one", key, len(feeds[key].calls))
} }
} }
for _, key := range []string{"stocktwits", "reuters"} { for _, key := range []string{"watcher_guru", "stocktwits", "reuters"} {
if len(feeds[key].calls) != 0 { if len(feeds[key].calls) != 0 {
t.Errorf("unsupported enabled source %s was invoked %d times", key, len(feeds[key].calls)) t.Errorf("unsupported enabled source %s was invoked %d times", key, len(feeds[key].calls))
} }

View File

@ -149,7 +149,7 @@ func (r *Repository) ListSources() ([]Source, error) {
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) { func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
s := &Source{} s := &Source{}
err := r.db.QueryRow(` 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','watcher_guru')`, sourceType, 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')`, sourceType,
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey) ).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return nil, nil return nil, nil

View File

@ -3,12 +3,13 @@ package models
const ( const (
SourceYahooFinance = "yahoo_finance" SourceYahooFinance = "yahoo_finance"
SourceBloomberg = "bloomberg" SourceBloomberg = "bloomberg"
SourceWatcherGuru = "watcher_guru" SourceWatcherGuru = "watcher_guru" // Historical identity; no longer executable.
SourceCNBCBusiness = "cnbc_business"
) )
func SupportedSourceKey(key string) bool { func SupportedSourceKey(key string) bool {
switch key { switch key {
case SourceYahooFinance, SourceBloomberg, SourceWatcherGuru: case SourceYahooFinance, SourceBloomberg, SourceCNBCBusiness:
return true return true
} }
return false return false

View File

@ -22,3 +22,18 @@ func TestSourceSupportUsesOnlyCanonicalKeyAndPersistedEnabled(t *testing.T) {
t.Fatal("disabled target support/operational mismatch") t.Fatal("disabled target support/operational mismatch")
} }
} }
func TestCNBCReplacesWatcherGuruWithoutAliasingHistoricalIdentity(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")
}
operational := OperationalSources(sources)
if len(operational) != 1 || operational[0].ID != "new-cnbc" || operational[0].ArticleLimit != 37 {
t.Fatalf("operational=%+v", operational)
}
if *sources[1].SourceKey != "watcher_guru" || sources[1].ArticleLimit != 64 {
t.Fatal("historical identity or cap mutated")
}
}

View File

@ -46,6 +46,7 @@ func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *
if err := json.Unmarshal([]byte(`[ if err := json.Unmarshal([]byte(`[
{"id":"y","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":10}, {"id":"y","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":10},
{"id":"b","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":10}, {"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}, {"id":"w","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":10},
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":10}, {"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":10},
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":10}]`), &sources); err != nil { {"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":10}]`), &sources); err != nil {
@ -53,7 +54,7 @@ func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *
} }
feeds := map[string]*ticket13Feed{} feeds := map[string]*ticket13Feed{}
scrapers := map[string]scraper.Scraper{} scrapers := map[string]scraper.Scraper{}
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} { for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
f := &ticket13Feed{} f := &ticket13Feed{}
feeds[key] = f feeds[key] = f
scrapers[key] = f scrapers[key] = f
@ -61,12 +62,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{}}) 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 := &Scheduler{users: ticket13Users{}, generationUseCase: uc}
s.run() s.run()
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} { for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business"} {
if feeds[key].calls != 1 { if feeds[key].calls != 1 {
t.Errorf("scheduled supported source %s calls=%d, want 1", key, feeds[key].calls) t.Errorf("scheduled supported source %s calls=%d, want 1", key, feeds[key].calls)
} }
} }
for _, key := range []string{"stocktwits", "reuters"} { for _, key := range []string{"watcher_guru", "stocktwits", "reuters"} {
if feeds[key].calls != 0 { if feeds[key].calls != 0 {
t.Errorf("scheduled legacy source %s was called %d times", key, feeds[key].calls) t.Errorf("scheduled legacy source %s was called %d times", key, feeds[key].calls)
} }

View File

@ -0,0 +1,166 @@
// Package cnbcbusiness reads only CNBC's configured Business RSS feed.
// Article URLs are returned as metadata and are never fetched.
package cnbcbusiness
import (
"bytes"
"context"
"encoding/xml"
"errors"
"io"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/tradarr/backend/internal/scraper"
"golang.org/x/net/html"
)
const feedURL = "https://www.cnbc.com/id/10001147/device/rss/rss.html"
const maxFeedBytes = 2 * 1024 * 1024
type CNBCBusiness struct{ client *http.Client }
func New() *CNBCBusiness {
return &CNBCBusiness{client: &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
}
func (*CNBCBusiness) Name() string { return "cnbc_business" }
type rssItem struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
PubDate string `xml:"pubDate"`
}
type rssChannel struct {
Items []rssItem `xml:"item"`
}
type rssFeed struct {
XMLName xml.Name `xml:"rss"`
Channel *rssChannel `xml:"channel"`
}
func (c *CNBCBusiness) Scrape(ctx context.Context, _ []string) (articles []scraper.Article, resultErr error) {
status := 0
cause := "none"
defer func() {
outcome := "ok"
if resultErr != nil {
outcome = "failed"
}
log.Printf("source=cnbc_business rss status=%d articles=%d outcome=%s cause=%s", status, len(articles), outcome, cause)
}()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, feedURL, nil)
if err != nil {
cause = "request"
return nil, errors.New("cnbc_business: request failed")
}
req.Header.Set("User-Agent", "Tradarr/1.0")
req.Header.Set("Accept", "application/rss+xml, application/xml, text/xml")
response, err := c.client.Do(req)
if err != nil {
cause = "transport"
if ctx.Err() != nil {
cause = "canceled_or_timeout"
}
return nil, errors.New("cnbc_business: transport or timeout failure")
}
defer response.Body.Close()
status = response.StatusCode
if status != http.StatusOK {
cause = "http_status"
return nil, errors.New("cnbc_business: unexpected HTTP status")
}
body, err := io.ReadAll(io.LimitReader(response.Body, maxFeedBytes+1))
if err != nil {
cause = "read"
return nil, errors.New("cnbc_business: feed read failed")
}
if len(body) > maxFeedBytes {
cause = "too_large"
return nil, errors.New("cnbc_business: feed exceeds size limit")
}
decoder := xml.NewDecoder(bytes.NewReader(body))
var feed rssFeed
if decoder.Decode(&feed) != nil || feed.Channel == nil {
cause = "parse"
return nil, errors.New("cnbc_business: invalid RSS feed")
}
// Allow trailing XML whitespace/comments, but never a second document or text.
for {
token, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
cause = "parse"
return nil, errors.New("cnbc_business: invalid RSS framing")
}
switch value := token.(type) {
case xml.CharData:
if strings.TrimSpace(string(value)) == "" {
continue
}
case xml.Comment:
continue
}
cause = "parse"
return nil, errors.New("cnbc_business: invalid RSS framing")
}
seen := map[string]bool{}
articles = make([]scraper.Article, 0, len(feed.Channel.Items))
for _, item := range feed.Channel.Items {
title := plainText(item.Title)
link, err := url.Parse(strings.TrimSpace(item.Link))
if title == "" || err != nil || link.Host == "" || link.User != nil || (link.Scheme != "https" && link.Scheme != "http") {
continue
}
link.Fragment = ""
canonical := link.String()
if seen[canonical] {
continue
}
seen[canonical] = true
var published *time.Time
for _, format := range []string{time.RFC1123Z, time.RFC1123, "Mon, 02 Jan 2006 15:04:05 -0700", time.RFC3339} {
if parsed, err := time.Parse(format, strings.TrimSpace(item.PubDate)); err == nil {
published = &parsed
break
}
}
articles = append(articles, scraper.Article{Title: title, URL: canonical, Content: plainText(item.Description), PublishedAt: published})
}
return articles, nil
}
// Parse description markup locally. Scripts/styles and comments are not evidence;
// no missing description, date or article body is fabricated.
func plainText(value string) string {
document, err := html.Parse(strings.NewReader(value))
if err != nil {
return ""
}
var text strings.Builder
var walk func(*html.Node)
walk = func(node *html.Node) {
if node.Type == html.ElementNode && (node.Data == "script" || node.Data == "style") {
return
}
if node.Type == html.TextNode {
text.WriteString(node.Data)
}
if node.Type == html.ElementNode && (node.Data == "p" || node.Data == "div" || node.Data == "br" || node.Data == "li") {
text.WriteByte(' ')
}
for child := node.FirstChild; child != nil; child = child.NextSibling {
walk(child)
}
if node.Type == html.ElementNode && (node.Data == "p" || node.Data == "div" || node.Data == "li") {
text.WriteByte(' ')
}
}
walk(document)
return strings.Join(strings.Fields(text.String()), " ")
}

View File

@ -0,0 +1,105 @@
package cnbcbusiness
import (
"bytes"
"context"
"errors"
"io"
"log"
"net/http"
"strings"
"testing"
)
type fakeTransport func(*http.Request) (*http.Response, error)
func (f fakeTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestCNBCBusinessRSSMapsMetadataWithoutArticleRequests(t *testing.T) {
calls := 0
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(r *http.Request) (*http.Response, error) {
calls++
if r.Method != "GET" || r.URL.String() != "https://www.cnbc.com/id/10001147/device/rss/rss.html" {
t.Fatalf("unexpected request %s %s", r.Method, r.URL)
}
body := `<rss version="2.0"><channel><item><title> Business &amp; markets </title><link>https://www.cnbc.com/fixture.html</link><description><![CDATA[<p>Available <b>RSS</b> evidence.</p><script>PRIVATE_SCRIPT</script>]]></description><pubDate>Mon, 02 Jan 2006 15:04:05 -0700</pubDate></item><item><title>Duplicate</title><link>https://www.cnbc.com/fixture.html</link></item><item><title>No description</title><link>https://www.cnbc.com/empty.html</link><pubDate>invalid</pubDate></item><item><title>Unsafe</title><link>javascript:alert(1)</link></item><item><title>Missing link</title></item></channel></rss>`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
})}}
got, err := feed.Scrape(context.Background(), []string{"IGNORED"})
if err != nil || len(got) != 2 || calls != 1 {
t.Fatalf("articles=%+v calls=%d err=%v", got, calls, err)
}
if feed.Name() != "cnbc_business" || got[0].Title != "Business & markets" || got[0].Content != "Available RSS evidence." || got[0].PublishedAt == nil || got[0].PublishedAt.Year() != 2006 {
t.Fatalf("mapping=%+v", got[0])
}
if got[1].Content != "" || got[1].PublishedAt != nil {
t.Fatalf("invented missing data=%+v", got[1])
}
}
func TestCNBCBusinessFailsSafelyAndLogsOnlyDiagnostics(t *testing.T) {
for _, tc := range []struct {
name string
status int
body string
}{
{"http", 503, "PRIVATE_RESPONSE https://secret.invalid/?key=PRIVATE_SECRET"},
{"malformed", 200, "<rss><PRIVATE_ARTICLE"}, {"html", 200, "<html>PRIVATE_TITLE</html>"},
{"trailing", 200, "<rss><channel/></rss>PRIVATE_PROMPT"}, {"oversize", 200, strings.Repeat("x", 2*1024*1024+1)},
} {
t.Run(tc.name, func(t *testing.T) {
var logs bytes.Buffer
old := log.Writer()
log.SetOutput(&logs)
defer log.SetOutput(old)
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil
})}}
got, err := feed.Scrape(context.Background(), nil)
if err == nil || len(got) != 0 {
t.Fatalf("not fail-closed: %d %v", len(got), err)
}
if !strings.Contains(logs.String(), "cnbc_business") || !strings.Contains(logs.String(), "status=") || !strings.Contains(logs.String(), "articles=0") {
t.Fatalf("missing diagnostics: %q", logs.String())
}
if strings.Contains(logs.String(), "PRIVATE_") || strings.Contains(logs.String(), "https://") || strings.Contains(err.Error(), "PRIVATE_") || strings.Contains(err.Error(), "https://") {
t.Fatal("sensitive response leaked")
}
})
}
}
func TestCNBCBusinessDoesNotFollowRedirectOrLeakTransportError(t *testing.T) {
for _, redirect := range []bool{false, true} {
var logs bytes.Buffer
previous := log.Writer()
log.SetOutput(&logs)
feed := New()
calls := 0
feed.client.Transport = fakeTransport(func(r *http.Request) (*http.Response, error) {
calls++
if r.URL.String() != feedURL {
t.Errorf("followed redirect to an article")
}
if !redirect {
return nil, errors.New("PRIVATE_TRANSPORT https://private.invalid/article?key=secret")
}
return &http.Response{StatusCode: 302, Header: http.Header{"Location": []string{"https://private.invalid/article?key=secret"}}, Body: io.NopCloser(strings.NewReader("PRIVATE_RESPONSE"))}, nil
})
got, err := feed.Scrape(context.Background(), nil)
log.SetOutput(previous)
if err == nil || len(got) != 0 || calls != 1 {
t.Fatalf("calls=%d err=%v", calls, err)
}
if strings.Contains(logs.String(), "PRIVATE_") || strings.Contains(logs.String(), "https://") || strings.Contains(err.Error(), "https://") {
t.Fatal("transport/redirect data leaked")
}
}
}
func TestCNBCBusinessEmptyRSSIsNoResults(t *testing.T) {
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("<rss><channel/></rss>"))}, nil
})}}
got, err := feed.Scrape(context.Background(), nil)
if err != nil || len(got) != 0 {
t.Fatalf("empty RSS: %v %v", got, err)
}
}

View File

@ -94,3 +94,12 @@ Le catalogue FinanceDatabase Equity/primary est embarqué dans le binaire : aucu
La migration 000017 transactionnelle ajoute des colonnes nullable (`company_id`, `yahoo_symbol`, désambiguïsation) et une unicité propriétaire/société ; elle sépare les index uniques legacy afin de conserver un ancien suivi indépendamment du nouveau. Aucun ancien actif n'est converti, effacé ou renommé. Le rollback automatique est refusé pour éviter de perdre cette identité ou fusionner des lignes : une réconciliation explicite/sauvegarde est nécessaire. Yahoo reçoit le listing Yahoo résolu pour les nouveaux suivis ; les labels Bloomberg et FIGI sont filtrés dans les anciens hints Yahoo, sans conversion inventée. Les entrées transmises aux récupérateurs Bloomberg et WatcherGuru restent inchangées. La migration 000017 transactionnelle ajoute des colonnes nullable (`company_id`, `yahoo_symbol`, désambiguïsation) et une unicité propriétaire/société ; elle sépare les index uniques legacy afin de conserver un ancien suivi indépendamment du nouveau. Aucun ancien actif n'est converti, effacé ou renommé. Le rollback automatique est refusé pour éviter de perdre cette identité ou fusionner des lignes : une réconciliation explicite/sauvegarde est nécessaire. Yahoo reçoit le listing Yahoo résolu pour les nouveaux suivis ; les labels Bloomberg et FIGI sont filtrés dans les anciens hints Yahoo, sans conversion inventée. Les entrées transmises aux récupérateurs Bloomberg et WatcherGuru restent inchangées.
Les diagnostics Yahoo et WatcherGuru ne journalisent plus de corps HTTP. Yahoo indique symbole/hint assaini, statut, nombre d'articles et résultat ; WatcherGuru indique chaque tentative RSS (étiquette de chemin fixe) et HTML, statut, nombre d'articles et résultat. Les échecs avant réception portent statut 0. Aucun titre, contenu, URL complète ou secret n'est ajouté aux logs. Les tests injectent exclusivement des transports factices ; l'extraction et la séquence de fallback existantes restent inchangées. Les diagnostics Yahoo et WatcherGuru ne journalisent plus de corps HTTP. Yahoo indique symbole/hint assaini, statut, nombre d'articles et résultat ; WatcherGuru indique chaque tentative RSS (étiquette de chemin fixe) et HTML, statut, nombre d'articles et résultat. Les échecs avant réception portent statut 0. Aucun titre, contenu, URL complète ou secret n'est ajouté aux logs. Les tests injectent exclusivement des transports factices ; l'extraction et la séquence de fallback existantes restent inchangées.
## CNBC Business et migration 000018
Le backend utilise désormais Yahoo Finance, Bloomberg et **CNBC Business** (`cnbc_business`). Le nouvel adapter lit exclusivement le flux configuré `https://www.cnbc.com/id/10001147/device/rss/rss.html` : un GET RSS, sans visite des liens d'articles, navigateur, HTML de fallback ou appel API supplémentaire. Ce flux a été recommandé à l'utilisateur ; sa disponibilité réelle et sa forme actuelle n'ont pas été vérifiées par les tests synthétiques.
Le parseur vérifie RSS/channel et le document entier, borne le corps à 2 Mio, retire les balises/scripts/styles des descriptions, ignore les entrées sans titre ou URL HTTP(S) absolue sans credentials, déduplique les liens et parse `pubDate` quand possible. Un contenu absent reste vide ; une date absente/invalide reste NULL. La description RSS ne constitue pas un article complet. Les redirections ne sont pas suivies. Les diagnostics ne contiennent que source, statut, nombre d'articles, résultat et catégorie d'erreur ; aucun corps, titre, prompt, URL ou secret. Les tests utilisent uniquement un RoundTripper synthétique.
La migration 000018 est atomique : elle étend les contraintes de type et de clé en conservant `watcherguru`/`watcher_guru`, désactive la ligne WatcherGuru existante et ajoute une ligne CNBC Business avec UUID neuf, activée, cap initial 20. Les IDs, noms, caps et références historiques WatcherGuru sont préservés ; aucune ligne d'article/job/outcome n'est réattribuée ou purgée. Les caps/configurations Yahoo/Bloomberg restent inchangés. WatcherGuru devient non supporté/non opérationnel côté application, même si une écriture externe le réactive ; l'API admin refuse sa modification. Les anciennes migrations ne changent pas. Le downgrade désactive seulement CNBC et conserve sa ligne ainsi que les valeurs historiques admises par les contraintes ; il ne réactive pas automatiquement WatcherGuru.

View File

@ -1,7 +1,11 @@
import type { GenerationOutcome } from '@/api/summaries' import type { GenerationOutcome } from '@/api/summaries'
function sourceLabel(type: string) {
return type === 'cnbc_business' ? 'CNBC Business' : type
}
export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) { export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => source.source_type) const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => sourceLabel(source.source_type))
return ( return (
<section className="space-y-3" aria-label="Bilan de la génération"> <section className="space-y-3" aria-label="Bilan de la génération">
{outcome.status === 'partial' && ( {outcome.status === 'partial' && (
@ -23,7 +27,7 @@ export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
<thead><tr><th scope="col">Source</th><th scope="col">État</th><th scope="col">Examinés</th><th scope="col">Sélectionnés par Laya</th><th scope="col">Retenus</th><th scope="col">Plafond</th></tr></thead> <thead><tr><th scope="col">Source</th><th scope="col">État</th><th scope="col">Examinés</th><th scope="col">Sélectionnés par Laya</th><th scope="col">Retenus</th><th scope="col">Plafond</th></tr></thead>
<tbody>{outcome.source_stats.map(source => ( <tbody>{outcome.source_stats.map(source => (
<tr key={source.source_id}> <tr key={source.source_id}>
<th scope="row">{source.source_type}</th> <th scope="row">{sourceLabel(source.source_type)}</th>
<td>{source.status === 'failed' ? 'Indisponible' : 'Disponible'}</td> <td>{source.status === 'failed' ? 'Indisponible' : 'Disponible'}</td>
<td>{source.candidates}</td><td>{source.laya_selected}</td><td>{source.selected}</td><td>{source.article_limit}</td> <td>{source.candidates}</td><td>{source.laya_selected}</td><td>{source.selected}</td><td>{source.article_limit}</td>
</tr> </tr>

View File

@ -5,7 +5,7 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label' import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
const SOURCE_KEYS = new Set(['yahoo_finance', 'bloomberg', 'watcher_guru']) const SOURCE_KEYS = new Set(['yahoo_finance', 'bloomberg', 'cnbc_business'])
function isSupported(source: Source) { function isSupported(source: Source) {
return source.supported === true && source.source_key !== null && SOURCE_KEYS.has(source.source_key) return source.supported === true && source.source_key !== null && SOURCE_KEYS.has(source.source_key)
@ -105,7 +105,7 @@ export function Sources() {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<h1 className="text-2xl font-bold">Sources et plafonds</h1> <h1 className="text-2xl font-bold">Sources et plafonds</h1>
<p className="text-sm text-muted-foreground">Seules Yahoo Finance, Bloomberg et Watcher Guru 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 Yahoo Finance, Bloomberg et CNBC Business 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>
{loading ? <p role="status">Chargement des sources et plafonds…</p> : loadError ? ( {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> <div className="space-y-3"><p role="alert">{loadError}</p><Button onClick={() => void load()}>Réessayer</Button></div>
) : <> ) : <>
@ -124,7 +124,7 @@ export function Sources() {
</Card> </Card>
{sources.length === 0 && <p>Aucune source disponible.</p>} {sources.length === 0 && <p>Aucune source disponible.</p>}
<div className="grid min-w-0 gap-4 lg:grid-cols-3"> <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} />)} {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} />)}
</div> </div>
{historical.length > 0 && <section aria-labelledby="historical-sources-title" className="space-y-3"> {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">Anciennes sources exclues</h2>

View File

@ -149,22 +149,25 @@ describe('plafonds d’articles administrateur', () => {
expect(updateSource).not.toHaveBeenCalled() expect(updateSource).not.toHaveBeenCalled()
}) })
it('ne rend activables que Yahoo, Bloomberg et Watcher Guru; garde StockTwits et Reuters en historique sans commandes', async () => { it('ne rend activables que Yahoo, Bloomberg et CNBC Business; garde Watcher Guru, StockTwits et Reuters en historique sans commandes', async () => {
listSources.mockResolvedValue([ listSources.mockResolvedValue([
{ id: 'y', name: 'Yahoo Finance', type: 'stocktwits', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 83 }, { 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: 'b', name: 'Bloomberg', type: 'bloomberg', source_key: 'bloomberg', supported: true, operational: true, enabled: false, article_limit: 77 },
{ id: 'w', name: 'Watcher.Guru', type: 'watcherguru', source_key: 'watcher_guru', supported: true, operational: true, enabled: true, article_limit: 64 }, { id: 'c', name: 'CNBC Business', type: 'cnbc_business', source_key: 'cnbc_business', supported: true, operational: true, enabled: true, 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: '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 }, { id: 'r', name: 'Reuters', type: 'reuters', source_key: null, supported: false, operational: false, enabled: false, article_limit: 42 },
]) ])
render(<Sources />) render(<Sources />)
expect(await screen.findByRole('heading', { name: 'Anciennes sources exclues' })).toBeInTheDocument() expect(await screen.findByRole('heading', { name: 'Anciennes sources exclues' })).toBeInTheDocument()
for (const name of ['Yahoo Finance', 'Bloomberg', 'Watcher.Guru']) { for (const name of ['Yahoo Finance', 'Bloomberg', 'CNBC Business']) {
expect(screen.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name}$`) })).toBeInTheDocument() expect(screen.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name}$`) })).toBeInTheDocument()
expect(screen.getByLabelText(`Plafond ${name}`)).toBeInTheDocument() expect(screen.getByLabelText(`Plafond ${name}`)).toBeInTheDocument()
} }
const historical = screen.getByRole('region', { name: 'Anciennes sources exclues' }) const historical = screen.getByRole('region', { name: 'Anciennes sources exclues' })
expect(within(historical).getByText('StockTwits')).toBeInTheDocument() expect(within(historical).getByText('StockTwits')).toBeInTheDocument()
expect(within(historical).getByText('Watcher.Guru')).toBeInTheDocument()
expect(within(historical).getByText('Exclue des synthèses · Plafond historique : 64')).toBeInTheDocument()
expect(within(historical).getByText('Reuters')).toBeInTheDocument() expect(within(historical).getByText('Reuters')).toBeInTheDocument()
expect(within(historical).queryByRole('button')).not.toBeInTheDocument() expect(within(historical).queryByRole('button')).not.toBeInTheDocument()
expect(within(historical).queryByRole('spinbutton')).not.toBeInTheDocument() expect(within(historical).queryByRole('spinbutton')).not.toBeInTheDocument()
@ -173,7 +176,8 @@ describe('plafonds d’articles administrateur', () => {
expect(within(yahooCard as HTMLElement).queryByText(/stocktwits/i)).not.toBeInTheDocument() expect(within(yahooCard as HTMLElement).queryByText(/stocktwits/i)).not.toBeInTheDocument()
expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(83) expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(83)
expect(screen.getByLabelText('Plafond Bloomberg')).toHaveValue(77) expect(screen.getByLabelText('Plafond Bloomberg')).toHaveValue(77)
expect(screen.getByLabelText('Plafond Watcher.Guru')).toHaveValue(64) expect(screen.getByLabelText('Plafond CNBC Business')).toHaveValue(20)
expect(screen.queryByLabelText('Plafond Watcher.Guru')).not.toBeInTheDocument()
}) })
it('garde les anciennes sources repliées et en lecture seule même si enabled est historique', async () => { it('garde les anciennes sources repliées et en lecture seule même si enabled est historique', async () => {
@ -220,4 +224,27 @@ describe('plafonds d’articles administrateur', () => {
expect(await screen.findByLabelText('Plafond Yahoo Finance')).toHaveValue(240) expect(await screen.findByLabelText('Plafond Yahoo Finance')).toHaveValue(240)
}) })
it('sauvegarde le plafond CNBC 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: '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')
expect(cap).toHaveValue(37)
expect(screen.queryByRole('button', { name: /^(Activer|Désactiver) Watcher/ })).not.toBeInTheDocument()
const historical = screen.getByRole('region', { name: 'Anciennes sources exclues' })
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))
expect(updateSource).toHaveBeenCalledTimes(1)
expect(await screen.findByRole('status')).toHaveTextContent('Plafond CNBC Business enregistré pour les prochaines synthèses.')
expect(screen.getByText(/Seules Yahoo Finance, Bloomberg et CNBC Business/)).toBeInTheDocument()
})
}) })

View File

@ -0,0 +1,33 @@
import { cleanup, render, screen, within } from '@testing-library/react'
import { afterEach, expect, it } from 'vitest'
import { GenerationDetails } from '../src/components/GenerationDetails'
import type { GenerationOutcome } from '../src/api/summaries'
afterEach(cleanup)
function outcome(sourceType: string): GenerationOutcome {
return {
id: 'generation-23', status: 'partial', language: 'fr', ranking_mode: 'title',
total_candidates: 0, content_fallbacks: 0, laya_selected: 0, selected: 0, global_limit: 50,
source_stats: [{ source_id: 'source-23', source_type: sourceType, status: 'failed', candidates: 0, laya_selected: 0, selected: 0, article_limit: 20, content_fallbacks: 0, failure_code: 'source_unavailable' }],
}
}
it('nomme CNBC Business dans le diagnostic agrégé sans exposer de détails de récupération', () => {
const result = outcome('cnbc_business')
render(<GenerationDetails outcome={result} />)
expect(screen.getByText('Cette synthèse a été générée sans CNBC Business, indisponible lors du traitement.')).toBeInTheDocument()
const row = screen.getByText('CNBC Business').closest('tr')!
expect(within(row).getByText('Indisponible')).toBeInTheDocument()
expect(screen.queryByText('source_unavailable')).not.toBeInTheDocument()
expect(screen.queryByRole('link')).not.toBeInTheDocument()
})
it.each(['watcherguru', 'Watcher.Guru', 'Watcher Guru'])('garde le bilan historique %s sans réécrire son identité', sourceType => {
const result = outcome(sourceType)
const before = JSON.stringify(result)
render(<GenerationDetails outcome={result} />)
expect(screen.getByText(sourceType, { exact: true })).toBeInTheDocument()
expect(screen.queryByText(/CNBC Business/)).not.toBeInTheDocument()
expect(JSON.stringify(result)).toBe(before)
})