trading-app/src/lib/news.ts
David 234efda586 Fix trade proposals, speed, Trade Republic setup and stock UI
- Buy by EUR amount (fractional shares, like Trade Republic): 200 EUR can
  now reach every large cap; risk engine sizes in whole euros
- No-AI screener (pullback in uptrend) feeds training cards and AI candidates
- Auto-update on app open via after(); "find ideas now" button (3/day)
- New Actions tab: stock list, stock page with chart, news, AI opinion,
  sandbox buy by amount or shares
- "Mon compte" tab: declare deposits, cash, holdings and PEA plan
  (no broker credentials, no PEA invented by default)
- Yahoo data cached and deduplicated, pages stream per section
- Tests: fractional sizing, screener, no-AI idea flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:05:20 +01:00

90 lines
3.1 KiB
TypeScript

import "server-only";
import { desc, eq, gte, isNull } from "drizzle-orm";
import { aiEnabled, triageNews } from "./ai";
import { getDb, schema } from "./db";
import { getNews } from "./market";
import { findStock } from "./universe";
const MAX_AGE_HOURS = 48;
/** Récupère les actus récentes des actions données (6 requêtes en parallèle au maximum). */
export async function collectNews(symbols: string[]): Promise<number> {
const db = await getDb();
const cutoff = Date.now() - MAX_AGE_HOURS * 3_600_000;
let inserted = 0;
for (let i = 0; i < symbols.length; i += 6) {
const chunk = symbols.slice(i, i + 6);
const results = await Promise.allSettled(chunk.map((s) => getNews(s)));
const rows = results
.flatMap((r) => (r.status === "fulfilled" ? r.value : []))
.filter((n) => n.publishedAt.getTime() >= cutoff);
if (!rows.length) continue;
const res = await db
.insert(schema.news)
.values(rows.map((n) => ({ ...n, id: `${n.symbol}:${n.id}` })))
.onConflictDoNothing()
.returning({ id: schema.news.id });
inserted += res.length;
}
return inserted;
}
/** Fait trier par Haiku toutes les actus pas encore notées, par paquets de 40. */
export async function triagePending(): Promise<number> {
if (!aiEnabled()) return 0;
const db = await getDb();
const pending = await db.select().from(schema.news).where(isNull(schema.news.triagedAt));
let done = 0;
for (let i = 0; i < pending.length; i += 40) {
const batch = pending.slice(i, i + 40);
const out = await triageNews(
batch.map((n) => ({
id: n.id,
symbol: n.symbol,
company: findStock(n.symbol)?.name ?? n.symbol,
title: n.title,
publisher: n.publisher,
})),
);
const byId = new Map(out.map((o) => [o.id, o]));
const now = new Date();
for (const n of batch) {
const t = byId.get(n.id);
await db
.update(schema.news)
.set({
triagedAt: now,
triage: t
? { relevance: t.relevance, direction: t.direction, eventType: t.eventType, severity: t.severity, reason: t.reason }
: { relevance: 0, direction: "neutral", eventType: "other", severity: "low", reason: "Non évaluée." },
})
.where(eq(schema.news.id, n.id));
done++;
}
}
return done;
}
export type NewsRow = typeof schema.news.$inferSelect;
/** Nombre d'actus récentes par action (pour la liste des actions). */
export async function newsCounts(hours = 48): Promise<Map<string, number>> {
const db = await getDb();
const rows = await db
.select({ symbol: schema.news.symbol })
.from(schema.news)
.where(gte(schema.news.publishedAt, new Date(Date.now() - hours * 3_600_000)));
const out = new Map<string, number>();
for (const r of rows) out.set(r.symbol, (out.get(r.symbol) ?? 0) + 1);
return out;
}
export async function recentNews(hours = 36): Promise<NewsRow[]> {
const db = await getDb();
return db
.select()
.from(schema.news)
.where(gte(schema.news.publishedAt, new Date(Date.now() - hours * 3_600_000)))
.orderBy(desc(schema.news.publishedAt));
}