- 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>
313 lines
13 KiB
TypeScript
313 lines
13 KiB
TypeScript
"use client";
|
||
|
||
import { useActionState, useEffect, useState, useTransition } from "react";
|
||
import {
|
||
addHoldingAction,
|
||
deleteHoldingAction,
|
||
depositAction,
|
||
recordSaleAction,
|
||
savePea,
|
||
saveAccount,
|
||
searchStocks,
|
||
setCashAction,
|
||
type FormResult,
|
||
} from "@/app/actions";
|
||
import type { SearchHit } from "@/lib/market";
|
||
import type { PositionView } from "@/lib/portfolio";
|
||
import { eur, pct, price, shares as fmtShares, signedEur } from "@/lib/format";
|
||
import { Delta, Empty, inputCls, primaryBtn, secondaryBtn } from "./ui";
|
||
|
||
function Result({ r }: { r: FormResult }) {
|
||
if (!r) return null;
|
||
return <p className={`text-sm ${r.ok ? "text-accent" : "text-danger"}`}>{r.message}</p>;
|
||
}
|
||
|
||
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
|
||
return (
|
||
<label className="flex flex-col gap-1 text-sm">
|
||
<span className="font-medium">{label}</span>
|
||
{children}
|
||
{hint && <span className="text-xs text-muted">{hint}</span>}
|
||
</label>
|
||
);
|
||
}
|
||
|
||
const num = (s: string) => Number(s.replace(",", ".").replace(/\s/g, ""));
|
||
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export function AccountForm(props: { openedAt: string | null; monthly: number; day: number; auto: boolean; firstTime: boolean }) {
|
||
const [state, action, pending] = useActionState(saveAccount, null);
|
||
return (
|
||
<form action={action} className="flex flex-col gap-3">
|
||
<Field label="Compte ouvert le" hint="Laisse la date du jour si tu ne sais plus.">
|
||
<input className={inputCls} type="date" name="openedAt" defaultValue={props.openedAt ?? new Date().toISOString().slice(0, 10)} />
|
||
</Field>
|
||
{props.firstTime && (
|
||
<Field label="Argent déjà versé sur le compte-titres (€)" hint="Ce que tu as viré jusqu'ici. Mets 0 si rien encore.">
|
||
<input className={inputCls} name="alreadyDeposited" inputMode="decimal" placeholder="ex. 50" />
|
||
</Field>
|
||
)}
|
||
<div className="grid grid-cols-2 gap-2">
|
||
<Field label="Virement / mois (€)">
|
||
<input className={inputCls} name="monthlyDeposit" inputMode="decimal" defaultValue={props.monthly} />
|
||
</Field>
|
||
<Field label="Jour du virement">
|
||
<input className={inputCls} name="depositDay" inputMode="numeric" defaultValue={props.day} />
|
||
</Field>
|
||
</div>
|
||
<label className="flex items-start gap-2 text-sm">
|
||
<input type="checkbox" name="autoDeposit" defaultChecked={props.auto} className="mt-1 h-4 w-4 accent-[var(--accent)]" />
|
||
<span>
|
||
J'ai programmé ce virement chaque mois
|
||
<span className="block text-xs text-muted">L'app l'ajoutera toute seule à tes liquidités à chaque échéance.</span>
|
||
</span>
|
||
</label>
|
||
<button className={primaryBtn} disabled={pending}>
|
||
{pending ? "Enregistrement…" : "Enregistrer"}
|
||
</button>
|
||
<Result r={state} />
|
||
</form>
|
||
);
|
||
}
|
||
|
||
export function CashForms({ cash }: { cash: number }) {
|
||
const [dep, depAction, depPending] = useActionState(depositAction, null);
|
||
const [fix, fixAction, fixPending] = useActionState(setCashAction, null);
|
||
return (
|
||
<div className="grid gap-3">
|
||
<form action={depAction} className="flex flex-col gap-2">
|
||
<Field label="J'ai versé de l'argent (€)" hint="Un virement exceptionnel. Un montant négatif = un retrait.">
|
||
<div className="flex gap-2">
|
||
<input className={inputCls} name="amount" inputMode="decimal" placeholder="ex. 50" />
|
||
<button className={`${secondaryBtn} shrink-0`} disabled={depPending}>
|
||
Ajouter
|
||
</button>
|
||
</div>
|
||
</Field>
|
||
<Result r={dep} />
|
||
</form>
|
||
<form action={fixAction} className="flex flex-col gap-2">
|
||
<Field label="Liquidités affichées par Trade Republic (€)" hint="Pour corriger un petit écart (frais, dividendes, intérêts).">
|
||
<div className="flex gap-2">
|
||
<input className={inputCls} name="cash" inputMode="decimal" defaultValue={cash.toFixed(2)} />
|
||
<button className={`${secondaryBtn} shrink-0`} disabled={fixPending}>
|
||
Corriger
|
||
</button>
|
||
</div>
|
||
</Field>
|
||
<Result r={fix} />
|
||
</form>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export function AddHolding() {
|
||
const [open, setOpen] = useState(false);
|
||
const [query, setQuery] = useState("");
|
||
const [hits, setHits] = useState<SearchHit[]>([]);
|
||
const [picked, setPicked] = useState<SearchHit | null>(null);
|
||
const [qty, setQty] = useState("");
|
||
const [px, setPx] = useState("");
|
||
const [stop, setStop] = useState("7");
|
||
const [paid, setPaid] = useState(true);
|
||
const [res, setRes] = useState<FormResult>(null);
|
||
const [pending, start] = useTransition();
|
||
|
||
useEffect(() => {
|
||
if (picked || query.trim().length < 2) return;
|
||
const t = setTimeout(() => searchStocks(query).then(setHits).catch(() => setHits([])), 350);
|
||
return () => clearTimeout(t);
|
||
}, [query, picked]);
|
||
|
||
if (!open)
|
||
return (
|
||
<button className={`${secondaryBtn} w-full`} onClick={() => setOpen(true)}>
|
||
+ Ajouter une action que je détiens
|
||
</button>
|
||
);
|
||
|
||
return (
|
||
<div className="flex flex-col gap-3 rounded-xl border border-line p-3">
|
||
<p className="text-sm font-semibold">Ajouter une action détenue chez Trade Republic</p>
|
||
<input
|
||
className={inputCls}
|
||
placeholder="Rechercher l'action"
|
||
value={picked ? `${picked.name} (${picked.symbol})` : query}
|
||
onChange={(e) => {
|
||
setPicked(null);
|
||
setQuery(e.target.value);
|
||
if (e.target.value.trim().length < 2) setHits([]);
|
||
}}
|
||
/>
|
||
{!picked && hits.length > 0 && (
|
||
<ul className="overflow-hidden rounded-xl border border-line text-sm">
|
||
{hits.map((h) => (
|
||
<li key={h.symbol}>
|
||
<button className="w-full bg-surface-2 px-3 py-2.5 text-left" onClick={() => (setPicked(h), setHits([]))}>
|
||
{h.name} <span className="text-xs text-muted">· {h.symbol}</span>
|
||
</button>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
<div className="grid grid-cols-2 gap-2">
|
||
<Field label="Nombre d'actions">
|
||
<input className={inputCls} inputMode="decimal" value={qty} onChange={(e) => setQty(e.target.value)} placeholder="ex. 0,8421" />
|
||
</Field>
|
||
<Field label="Prix d'achat unitaire" hint="Dans la devise de l'action ($ ou €).">
|
||
<input className={inputCls} inputMode="decimal" value={px} onChange={(e) => setPx(e.target.value)} />
|
||
</Field>
|
||
</div>
|
||
<Field label="Stop (% sous le prix d'achat)" hint="Laisse vide si tu n'as pas mis d'ordre Stop.">
|
||
<input className={inputCls} inputMode="decimal" value={stop} onChange={(e) => setStop(e.target.value)} />
|
||
</Field>
|
||
<label className="flex items-start gap-2 text-sm">
|
||
<input type="checkbox" checked={paid} onChange={(e) => setPaid(e.target.checked)} className="mt-1 h-4 w-4" />
|
||
<span>
|
||
Retirer le coût de mes liquidités
|
||
<span className="block text-xs text-muted">Décoche si ces liquidités ne sont pas encore comptées dans l'app (achat ancien).</span>
|
||
</span>
|
||
</label>
|
||
<div className="grid grid-cols-2 gap-2">
|
||
<button
|
||
className={primaryBtn}
|
||
disabled={pending || !picked || !(num(qty) > 0) || !(num(px) > 0)}
|
||
onClick={() =>
|
||
start(async () => {
|
||
const r = await addHoldingAction({ symbol: picked!.symbol, shares: num(qty), price: num(px), stopPct: num(stop) || null, paidFromCash: paid });
|
||
setRes(r);
|
||
if (r?.ok) {
|
||
setPicked(null);
|
||
setQuery("");
|
||
setQty("");
|
||
setPx("");
|
||
setOpen(false);
|
||
}
|
||
})
|
||
}
|
||
>
|
||
Ajouter
|
||
</button>
|
||
<button className={secondaryBtn} onClick={() => setOpen(false)}>
|
||
Annuler
|
||
</button>
|
||
</div>
|
||
<Result r={res} />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function RealPositions({ positions }: { positions: PositionView[] }) {
|
||
if (!positions.length) return <Empty>Aucune action détenue pour l'instant.</Empty>;
|
||
return (
|
||
<ul className="flex flex-col gap-2">
|
||
{positions.map((p) => (
|
||
<RealPosition key={p.id} p={p} />
|
||
))}
|
||
</ul>
|
||
);
|
||
}
|
||
|
||
function RealPosition({ p }: { p: PositionView }) {
|
||
const [selling, setSelling] = useState(false);
|
||
const [px, setPx] = useState(p.price?.toFixed(2) ?? "");
|
||
const [res, setRes] = useState<FormResult>(null);
|
||
const [pending, start] = useTransition();
|
||
return (
|
||
<li className="rounded-xl bg-surface-2 p-3">
|
||
<div className="flex items-start justify-between gap-3">
|
||
<div className="min-w-0">
|
||
<p className="font-semibold">{p.name}</p>
|
||
<p className="num text-xs text-muted">
|
||
{fmtShares(p.shares)} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
|
||
</p>
|
||
{p.stopPrice && <p className="num text-xs text-muted">Stop {price(p.stopPrice, p.currency)}</p>}
|
||
</div>
|
||
<div className="text-right">
|
||
<p className="num font-semibold">{eur(p.valueEur)}</p>
|
||
<Delta value={p.pnlOpenEur}>
|
||
{signedEur(p.pnlOpenEur)} ({pct(p.pnlOpenPct)})
|
||
</Delta>
|
||
</div>
|
||
</div>
|
||
{selling ? (
|
||
<div className="mt-3 flex flex-col gap-2">
|
||
<Field label={`Prix de vente obtenu (${p.currency === "USD" ? "$" : "€"})`}>
|
||
<input className={inputCls} inputMode="decimal" value={px} onChange={(e) => setPx(e.target.value)} />
|
||
</Field>
|
||
<div className="grid grid-cols-2 gap-2">
|
||
<button className={primaryBtn} disabled={pending} onClick={() => start(async () => setRes(await recordSaleAction(p.id, num(px) || undefined)))}>
|
||
Enregistrer la vente
|
||
</button>
|
||
<button className={secondaryBtn} onClick={() => setSelling(false)}>
|
||
Annuler
|
||
</button>
|
||
</div>
|
||
</div>
|
||
) : (
|
||
<div className="mt-3 grid grid-cols-2 gap-2">
|
||
<button className={`${secondaryBtn} h-9`} onClick={() => setSelling(true)}>
|
||
J'ai vendu
|
||
</button>
|
||
<button
|
||
className={`${secondaryBtn} h-9 text-danger`}
|
||
disabled={pending}
|
||
onClick={() => {
|
||
if (confirm("Supprimer cette position (erreur de saisie) ? Tes liquidités ne changent pas.")) start(async () => setRes(await deleteHoldingAction(p.id)));
|
||
}}
|
||
>
|
||
Supprimer
|
||
</button>
|
||
</div>
|
||
)}
|
||
<Result r={res} />
|
||
</li>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export function PeaForm(props: { has: boolean; symbol: string; amount: number; day: number; start: string; calibration: number | null }) {
|
||
const [state, action, pending] = useActionState(savePea, null);
|
||
const [has, setHas] = useState(props.has);
|
||
return (
|
||
<form action={action} className="flex flex-col gap-3">
|
||
<label className="flex items-start gap-2 text-sm">
|
||
<input type="checkbox" name="hasPea" checked={has} onChange={(e) => setHas(e.target.checked)} className="mt-1 h-4 w-4" />
|
||
<span>
|
||
J'ai un PEA avec un plan d'épargne ETF
|
||
<span className="block text-xs text-muted">L'app calcule sa valeur toute seule, chaque jour, à partir du cours de l'ETF.</span>
|
||
</span>
|
||
</label>
|
||
{has && (
|
||
<>
|
||
<Field label="ETF du plan" hint="Symbole Yahoo. Par défaut : BNP Paribas Easy S&P 500 (ESE.PA), éligible PEA.">
|
||
<input className={inputCls} name="peaSymbol" defaultValue={props.symbol} autoCapitalize="characters" />
|
||
</Field>
|
||
<div className="grid grid-cols-2 gap-2">
|
||
<Field label="Montant / mois (€)">
|
||
<input className={inputCls} name="peaAmount" inputMode="decimal" defaultValue={props.amount} />
|
||
</Field>
|
||
<Field label="Jour du prélèvement">
|
||
<input className={inputCls} name="peaDay" inputMode="numeric" defaultValue={props.day} />
|
||
</Field>
|
||
</div>
|
||
<Field label="Premier prélèvement le">
|
||
<input className={inputCls} type="date" name="peaStart" defaultValue={props.start} />
|
||
</Field>
|
||
<Field label="Parts détenues aujourd'hui (facultatif)" hint="Le nombre exact affiché par Trade Republic, pour corriger un écart.">
|
||
<input className={inputCls} name="calibrationShares" inputMode="decimal" placeholder={props.calibration !== null ? String(props.calibration) : "ex. 4,2731"} />
|
||
</Field>
|
||
</>
|
||
)}
|
||
<button className={primaryBtn} disabled={pending}>
|
||
{pending ? "Enregistrement…" : "Enregistrer le PEA"}
|
||
</button>
|
||
<Result r={state} />
|
||
</form>
|
||
);
|
||
}
|