trading-app/src/lib/app.integration.test.ts
David 469e46d306 Fix double executions, missed deposits, holidays; AI pot deposits; faster market data
- Orders, position closes, card answers and deposits are claimed atomically
  (one tick at a time, one evening at a time); cash updated in SQL
- Each tick step is isolated: an AI or Yahoo failure no longer stops the rest
- Missed monthly deposits are caught up; Trade Republic holidays handled
- Gap opens fill at the open (target included); limit orders valid one
  trading day; stale sell orders cancelled; old cards expire (PEA transfer kept)
- News queries bounded to 48 h, news older than 30 days purged
- AI sim pot receives the same monthly deposit as the real account;
  performance measured on money contributed vs S&P 500 with the same flows;
  reset action
- Yahoo data cached in the database (stale-while-revalidate); the order
  engine still requires fresh quotes; client router keeps tabs for 60 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:54:17 +01:00

235 lines
10 KiB
TypeScript

/**
* Test d'intégration : vraie base (PGlite temporaire) + vrais cours Yahoo.
* Lancer avec : pnpm test:integration
*/
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { eq } from "drizzle-orm";
import { beforeAll, describe, expect, it } from "vitest";
process.env.PGLITE_DIR = mkdtempSync(path.join(tmpdir(), "cagnotte-test-"));
delete process.env.DATABASE_URL;
delete process.env.ANTHROPIC_API_KEY;
const { getDb, schema } = await import("./db");
const { defaultPeaPlan, ensureSetup } = await import("./settings");
const { collectNews } = await import("./news");
const { getPortfolioState, placeOrder, processAll } = await import("./portfolio");
const { getQuote } = await import("./market");
const { respondToCard } = await import("./cards");
const { runEvening } = await import("./jobs");
const { getGateStatus, getPea, getLeaderboard } = await import("./stats");
const { addDays, parisDate } = await import("./time");
describe("intégration", () => {
beforeAll(async () => {
await ensureSetup();
});
it("crée les trois portefeuilles", async () => {
const s = await getPortfolioState("sandbox");
expect(s.cash).toBe(200);
expect((await getPortfolioState("real")).cash).toBe(0);
});
it("collecte des actus réelles", async () => {
const n = await collectNews(["AAPL", "AIR.PA"]);
expect(n).toBeGreaterThan(0);
});
it("exécute un ordre limite à partir des barres journalières, puis déclenche le stop", async () => {
const db = await getDb();
const quote = (await getQuote("KO"))!;
const { order } = await placeOrder({
portfolioId: "sandbox",
symbol: "KO",
name: "Coca-Cola",
currency: quote.currency,
side: "buy",
type: "limit",
shares: 2,
limitPrice: quote.price * 1.2,
stopPrice: quote.price * 0.5,
validUntil: addDays(parisDate(), 5),
});
// On antidate l'ordre de 5 jours : les barres suivantes passent forcément sous la limite.
await db
.update(schema.orders)
.set({ status: "pending", createdAt: new Date(Date.now() - 5 * 86_400_000) })
.where(eq(schema.orders.id, order.id));
await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
await db.update(schema.portfolios).set({ cash: 200 }).where(eq(schema.portfolios.id, "sandbox"));
const log = await processAll();
expect(log.join(" ")).toContain("Ordre exécuté");
let s = await getPortfolioState("sandbox");
expect(s.positions).toHaveLength(1);
expect(s.cash).toBeLessThan(200);
// Stop au-dessus du cours, position antidatée : le stop doit partir.
await db
.update(schema.positions)
.set({ stopPrice: quote.price * 2, openedAt: new Date(Date.now() - 5 * 86_400_000) })
.where(eq(schema.positions.id, s.positions[0].id));
const log2 = await processAll();
expect(log2.join(" ")).toContain("stop");
s = await getPortfolioState("sandbox");
expect(s.positions).toHaveLength(0);
const [closed] = await db.select().from(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
expect(closed.exitReason).toBe("stop");
expect(closed.feesEur).toBe(2);
});
it("enregistre un achat réel confirmé puis sa vente", async () => {
const db = await getDb();
await db.update(schema.portfolios).set({ cash: 300 }).where(eq(schema.portfolios.id, "real"));
const [card] = await db
.insert(schema.actions)
.values({
rendezvousId: 0,
kind: "buy",
training: false,
symbol: "KO",
payload: { title: "Acheter", why: "", steps: [], name: "Coca-Cola", currency: "USD", shares: 3, limitPrice: 60, stopPrice: 55 },
})
.returning();
await respondToCard(card.id, "done", { price: 61, shares: 3 });
const real = await getPortfolioState("real");
expect(real.positions).toHaveLength(1);
expect(real.positions[0].entryPrice).toBe(61);
expect(real.cash).toBeLessThan(300 - 3 * 61 * 0.8);
const [sell] = await db
.insert(schema.actions)
.values({
rendezvousId: 0,
kind: "sell",
training: false,
symbol: "KO",
payload: { title: "Vendre", why: "", steps: [], positionId: real.positions[0].id },
})
.returning();
await respondToCard(sell.id, "done", { price: 65 });
const after = await getPortfolioState("real");
expect(after.positions).toHaveLength(0);
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.portfolioId, "real"));
expect(pos.pnlEur).toBeGreaterThan(0);
});
it("prépare un rendez-vous même sans IA, et calcule PEA, classement et critères", async () => {
const log = await runEvening({ force: true });
expect(log.join(" ")).toContain("Rendez-vous créé");
const db = await getDb();
const [rdv] = await db.select().from(schema.rendezvous);
expect(rdv.summary).toContain("Anthropic");
const settings = await ensureSetup();
expect(settings.peaPlan).toBeNull(); // pas de PEA inventé tant que tu ne l'as pas déclaré
const pea = await getPea({ ...settings, peaPlan: defaultPeaPlan(addDays(parisDate(), -120)) });
expect(pea!.invested).toBeGreaterThanOrEqual(150);
expect(pea!.value).toBeGreaterThan(0);
const gate = await getGateStatus();
expect(gate.criteria).toHaveLength(5);
expect(gate.unlocked).toBe(false);
const board = await getLeaderboard(settings, await getPortfolioState("ai_sim"), await getPortfolioState("sandbox"));
expect(board.map((b) => b.label).sort()).toEqual(["L'IA", "S&P 500", "Toi"]);
});
it("n'exécute un ordre qu'une fois même si deux mises à jour tournent en même temps", async () => {
const db = await getDb();
await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
await db.delete(schema.orders).where(eq(schema.orders.portfolioId, "sandbox"));
await db.update(schema.portfolios).set({ cash: 200 }).where(eq(schema.portfolios.id, "sandbox"));
const quote = (await getQuote("KO"))!;
const [order] = await db
.insert(schema.orders)
.values({
portfolioId: "sandbox",
symbol: "KO",
name: "Coca-Cola",
currency: quote.currency,
side: "buy",
type: "limit",
shares: 1,
limitPrice: quote.price * 1.2,
validUntil: addDays(parisDate(), 5),
createdAt: new Date(Date.now() - 5 * 86_400_000),
})
.returning();
await Promise.all([processAll(), processAll(), processAll()]);
const positions = await db.select().from(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
expect(positions).toHaveLength(1);
const [o] = await db.select().from(schema.orders).where(eq(schema.orders.id, order.id));
expect(o.status).toBe("filled");
const s = await getPortfolioState("sandbox");
expect(s.cash).toBeCloseTo(200 - positions[0].shares * positions[0].entryPrice * positions[0].entryFx - 1, 6);
// Vente : la position ne peut être clôturée qu'une fois.
const { closePosition } = await import("./portfolio");
const results = await Promise.all([closePosition(positions[0], 70, 1, "manual"), closePosition(positions[0], 70, 1, "manual")]);
expect(results.filter(Boolean)).toHaveLength(1);
});
it("un double appui sur « C'est fait » n'enregistre l'achat réel qu'une fois", async () => {
const db = await getDb();
await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "real"));
const [card] = await db
.insert(schema.actions)
.values({
rendezvousId: 0,
kind: "buy",
training: false,
symbol: "KO",
payload: { title: "Acheter", why: "", steps: [], name: "Coca-Cola", currency: "USD", shares: 1, limitPrice: 60, stopPrice: 55 },
})
.returning();
const r = await Promise.allSettled([respondToCard(card.id, "done"), respondToCard(card.id, "done")]);
expect(r.filter((x) => x.status === "fulfilled")).toHaveLength(1);
const real = await getPortfolioState("real");
expect(real.positions).toHaveLength(1);
});
it("verrous : une seule mise à jour à la fois, une chose par jour", async () => {
const { claimKv, claimLock, releaseLock } = await import("./settings");
expect(await claimLock("testLock", 60_000)).toBe(true);
expect(await claimLock("testLock", 60_000)).toBe(false);
await releaseLock("testLock");
expect(await claimLock("testLock", 60_000)).toBe(true);
expect(await claimKv("testDay", "2026-11-18")).toBe(true);
expect(await claimKv("testDay", "2026-11-18")).toBe(false);
expect(await claimKv("testDay", "2026-11-19")).toBe(true);
});
it("remet la cagnotte de l'IA à zéro et relance la simulation", async () => {
const db = await getDb();
const { resetAiSim } = await import("./jobs");
await db.update(schema.portfolios).set({ cash: 120 }).where(eq(schema.portfolios.id, "ai_sim"));
await db.insert(schema.cashFlows).values({ portfolioId: "ai_sim", amount: 50, kind: "deposit", date: "2026-10-05" });
await resetAiSim();
const ai = await getPortfolioState("ai_sim");
expect(ai.cash).toBe(200);
const flows = await db.select().from(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "ai_sim"));
expect(flows).toHaveLength(0);
expect((await ensureSetup()).simStartDate).toBe(parisDate());
});
it("sans IA, propose une idée du filtre et permet un achat fractionné", async () => {
const { refreshIdeas } = await import("./ideas");
const ideas = await refreshIdeas(true);
await runEvening({ force: true });
const db = await getDb();
const cards = await db.select().from(schema.actions).where(eq(schema.actions.status, "pending"));
// Le marché ne donne pas toujours d'idée : la fiche n'existe que s'il y en a une.
if (ideas.items.length) expect(cards.some((c) => c.training && c.payload.source === "screen")).toBe(true);
// Une fraction d'une action chère, comme « Montant » chez Trade Republic.
const s = await getPortfolioState("sandbox");
const q = (await getQuote("MC.PA"))!;
const r = await placeOrder({ portfolioId: "sandbox", symbol: "MC.PA", name: q.name, currency: "EUR", side: "buy", type: "limit", shares: 0.25, limitPrice: q.price * 2 });
expect(r.order.shares).toBe(0.25);
expect(s.cash).toBeGreaterThan(0);
});
});