feat: enter a custom split in euros, other share completed automatically

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
YugonitoandClaude Opus 5.5 committed 2026-10-27 21:38:00 +01:00
1 parent c3c371aefe
commit 9fbcf12323
6 files changed
+173 -55

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
"use client";
import { useEffect, useState } from "react";
import { bpToPercentLabel, formatEuro, parseEuro, percentToBp, shareAmounts, splitFromAmounts, validateSplit } from "@/domain/money";
import type { Cents, Split } from "@/domain/types";
import { Input } from "./ui/Field";
import { Pills } from "./ui/Pills";
type Unit = "pct" | "eur";
/** "600.50" → "600,50", "600.00" → "600" : valeur lisible pour un champ montant. */
const euroText = (c: Cents) => (c % 100 === 0 ? String(c / 100) : `${Math.floor(c / 100)},${String(c % 100).padStart(2, "0")}`);
/** Champ vide ou zéro → 0 ; montant valide → centimes ; sinon -1. */
const centsOrZero = (t: string): Cents => (/^[\s0.,€]*$/.test(t) ? 0 : (parseEuro(t) ?? -1));
/**
* Répartition libre, saisie en pourcentages ou en euros (quand le montant est connu).
* Avec deux personnes, la part de l'autre se complète toute seule.
*/
export function CustomSplitFields({
users,
total,
initial,
onChange,
}: {
users: { id: string; firstName: string }[];
/** undefined : pas de montant dans ce formulaire (saisie en % seulement) ; null : montant pas encore valide. */
total?: Cents | null;
initial: Split;
onChange: (s: Split) => void;
}) {
const ids = users.map((u) => u.id);
const [unit, setUnit] = useState<Unit>("pct");
const [texts, setTexts] = useState<Record<string, string>>(() =>
Object.fromEntries(ids.map((id) => [id, bpToPercentLabel(initial[id] ?? 0)])),
);
const compute = (u: Unit, t: Record<string, string>): Split => {
if (u === "pct") return Object.fromEntries(ids.map((id) => [id, percentToBp(t[id] ?? "") ?? -1]));
const parts = Object.fromEntries(ids.map((id) => [id, centsOrZero(t[id] ?? "")]));
if (Object.values(parts).some((c) => c < 0)) return Object.fromEntries(ids.map((id) => [id, -1]));
// Somme ≠ montant : tout à 0 pour que l'enregistrement refuse (« doit totaliser 100 % »).
return (total != null && splitFromAmounts(parts, total)) || Object.fromEntries(ids.map((id) => [id, 0]));
};
// En euros, la répartition dépend du montant : on la recalcule quand il change.
useEffect(() => {
if (unit === "eur") onChange(compute(unit, texts));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [total]);
const edit = (id: string, text: string) => {
const next = { ...texts, [id]: text };
const other = ids.length === 2 ? ids.find((i) => i !== id)! : null;
if (other && unit === "pct") {
const bp = percentToBp(text);
if (bp !== null) next[other] = bpToPercentLabel(10000 - bp);
} else if (other && total != null) {
const c = centsOrZero(text);
if (c >= 0 && c <= total) next[other] = euroText(total - c);
}
setTexts(next);
onChange(compute(unit, next));
};
const switchUnit = (u: Unit) => {
if (u === unit) return;
const current = compute(unit, texts);
const valid = validateSplit(current) === null;
const next = Object.fromEntries(
ids.map((id) => {
if (!valid || (u === "eur" && total == null)) return [id, ""];
if (u === "pct") return [id, bpToPercentLabel(current[id] ?? 0)];
return [id, euroText(shareAmounts(total!, current, ids[0])[id] ?? 0)];
}),
);
setUnit(u);
setTexts(next);
onChange(compute(u, next));
};
const split = compute(unit, texts);
const pctTotal = Object.values(split).reduce((t, v) => t + Math.max(v, 0), 0);
const eurTotal = ids.reduce((t, id) => t + Math.max(centsOrZero(texts[id] ?? ""), 0), 0);
const ok = unit === "pct" ? pctTotal === 10000 : total != null && eurTotal === total;
return (
<div className="space-y-3 rounded-[10px] border border-line p-3">
{total !== undefined && (
<Pills
options={[
{ value: "pct" as Unit, label: "En %" },
{ value: "eur" as Unit, label: "En €" },
]}
value={unit}
onChange={switchUnit}
/>
)}
<div className="flex flex-wrap items-center gap-3">
{users.map((u) => (
<label key={u.id} className="flex items-center gap-2">
<span className="font-medium">{u.firstName}</span>
<Input inputMode="decimal" className="w-24" value={texts[u.id] ?? ""} onChange={(e) => edit(u.id, e.target.value)} />
{unit === "pct" ? "%" : "€"}
{unit === "eur" && ok && <span className="text-xs text-muted">{bpToPercentLabel(split[u.id] ?? 0)} %</span>}
</label>
))}
<span className={`text-xs font-semibold ${ok ? "text-pos" : "text-neg"}`}>
{unit === "pct" ? `Total ${bpToPercentLabel(pctTotal)} %` : `Total ${formatEuro(eurTotal)} sur ${total == null ? "—" : formatEuro(total)}`}
</span>
</div>
</div>
);
}
+5 -25
View File
@@ -2,9 +2,10 @@
import { useRouter } from "next/navigation";
import { useMemo, useState, useTransition } from "react";
import { bpToPercentLabel, fullSplit, percentToBp, validateSplit } from "@/domain/money";
import { bpToPercentLabel, fullSplit, parseEuro, validateSplit } from "@/domain/money";
import type { AllocationMode, Frequency, OpKind, Split } from "@/domain/types";
import { deleteOperationAction, saveOperationAction } from "@/server/actions/operations";
import { CustomSplitFields } from "./CustomSplitFields";
import { Button } from "./ui/Button";
import { Field, FormError, Input, Select, Textarea } from "./ui/Field";
import { Pills } from "./ui/Pills";
@@ -101,16 +102,11 @@ export function OperationForm({
return full ? `full:${full}` : "custom";
};
const [choice, setChoice] = useState<SplitChoice>(initialChoice);
const [custom, setCustom] = useState<Record<string, string>>(() =>
Object.fromEntries(userIds.map((id) => [id, bpToPercentLabel((initial?.split ?? defaultSplit)[id] ?? 0)])),
);
const [customSplit, setCustomSplit] = useState<Split>(initial?.split ?? defaultSplit);
const charge = charges.find((c) => c.key === chargeKey) ?? null;
const allocated = kind === "INCOME" && charge !== null;
const customSplit: Split = Object.fromEntries(userIds.map((id) => [id, percentToBp(custom[id] ?? "") ?? -1]));
const customTotal = Object.values(customSplit).reduce((t, v) => t + Math.max(v, 0), 0);
// La répartition effective découle du choix (ou du mode d'affectation pour une entrée affectée).
const split: Split = useMemo(() => {
if (allocated) {
@@ -122,7 +118,7 @@ export function OperationForm({
if (choice === "custom") return customSplit;
return fullSplit(choice.slice(5), userIds);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [allocated, allocationMode, charge, accountUserId, choice, custom, defaultSplit]);
}, [allocated, allocationMode, charge, accountUserId, choice, customSplit, defaultSplit]);
const changeKind = (k: OpKind) => {
setKind(k);
@@ -254,23 +250,7 @@ export function OperationForm({
)}
{showCustom && (
<div className="flex flex-wrap items-center gap-3 rounded-[10px] border border-line p-3">
{users.map((u) => (
<label key={u.id} className="flex items-center gap-2">
<span className="font-medium">{u.firstName}</span>
<Input
inputMode="decimal"
className="w-20"
value={custom[u.id] ?? ""}
onChange={(e) => setCustom({ ...custom, [u.id]: e.target.value })}
/>
%
</label>
))}
<span className={`text-xs font-semibold ${customTotal === 10000 ? "text-pos" : "text-neg"}`}>
Total {bpToPercentLabel(customTotal)} %
</span>
</div>
<CustomSplitFields users={users} total={parseEuro(amount)} initial={customSplit} onChange={setCustomSplit} />
)}
<Field label="Date">
+16 -27
View File
@@ -1,26 +1,29 @@
"use client";
import { useState } from "react";
import { bpToPercentLabel, fullSplit, percentToBp } from "@/domain/money";
import type { Split } from "@/domain/types";
import { Input } from "./ui/Field";
import { bpToPercentLabel, fullSplit } from "@/domain/money";
import type { Cents, Split } from "@/domain/types";
import { CustomSplitFields } from "./CustomSplitFields";
import { Pills } from "./ui/Pills";
type Choice = "default" | `full:${string}` | "custom";
const same = (a: Split, b: Split) => Object.keys({ ...a, ...b }).every((k) => (a[k] ?? 0) === (b[k] ?? 0));
/** Choix de répartition : défaut du foyer, 100 % pour une personne, ou pourcentages libres. */
/** Choix de répartition : défaut du foyer, 100 % pour une personne, ou parts libres (en % ou en €). */
export function SplitPicker({
users,
defaultSplit,
value,
onChange,
total,
}: {
users: { id: string; firstName: string }[];
defaultSplit: Split;
value: Split;
onChange: (s: Split) => void;
/** Montant de l'opération, pour pouvoir répartir en euros (voir CustomSplitFields). */
total?: Cents | null;
}) {
const ids = users.map((u) => u.id);
const [choice, setChoice] = useState<Choice>(() => {
@@ -28,18 +31,14 @@ export function SplitPicker({
const full = ids.find((id) => value[id] === 10000);
return full ? `full:${full}` : "custom";
});
const [custom, setCustom] = useState<Record<string, string>>(() =>
Object.fromEntries(ids.map((id) => [id, bpToPercentLabel(value[id] ?? 0)])),
);
const [custom, setCustom] = useState<Split>(value);
const fromCustom = (c: Record<string, string>): Split => Object.fromEntries(ids.map((id) => [id, percentToBp(c[id] ?? "") ?? -1]));
const pick = (c: Choice) => {
setChoice(c);
if (c === "default") onChange(defaultSplit);
else if (c === "custom") onChange(fromCustom(custom));
else if (c === "custom") onChange(custom);
else onChange(fullSplit(c.slice(5), ids));
};
const total = Object.values(fromCustom(custom)).reduce((t, v) => t + Math.max(v, 0), 0);
return (
<div className="space-y-2">
@@ -53,25 +52,15 @@ export function SplitPicker({
onChange={pick}
/>
{choice === "custom" && (
<div className="flex flex-wrap items-center gap-3 rounded-[10px] border border-line p-3">
{users.map((u) => (
<label key={u.id} className="flex items-center gap-2">
<span className="font-medium">{u.firstName}</span>
<Input
inputMode="decimal"
className="w-20"
value={custom[u.id] ?? ""}
onChange={(e) => {
const next = { ...custom, [u.id]: e.target.value };
setCustom(next);
onChange(fromCustom(next));
<CustomSplitFields
users={users}
total={total}
initial={custom}
onChange={(s) => {
setCustom(s);
onChange(s);
}}
/>
%
</label>
))}
<span className={`text-xs font-semibold ${total === 10000 ? "text-pos" : "text-neg"}`}>Total {bpToPercentLabel(total)} %</span>
</div>
)}
</div>
);
+3 -3
View File
@@ -2,7 +2,7 @@
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { fullSplit } from "@/domain/money";
import { fullSplit, parseEuro } from "@/domain/money";
import type { AllocationMode, Frequency, OpKind, Split } from "@/domain/types";
import { saveRecurringAction } from "@/server/actions/recurrings";
import type { FormCategory, FormUser } from "../OperationForm";
@@ -135,7 +135,7 @@ export function RecurringForm({
{kind === "EXPENSE" && (
<div>
<div className="mb-2 text-xs font-semibold text-muted">Répartition</div>
<SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} />
<SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} total={parseEuro(amount)} />
</div>
)}
<div className="grid gap-3 sm:grid-cols-2">
@@ -179,7 +179,7 @@ export function RecurringForm({
value={mode}
onChange={setMode}
/>
{mode === "CUSTOM" && <SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} />}
{mode === "CUSTOM" && <SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} total={parseEuro(amount)} />}
</>
)}
</div>
+20
View File
@@ -55,6 +55,26 @@ export function shareAmounts(amount: Cents, split: Split, accountUserId: UserId)
return shares;
}
/**
* Montant payé par chacun → répartition en points de base (plus forts restes, ex aequo au premier).
* null si la somme des montants ne fait pas le total. Précision limitée au centième de %.
*/
export function splitFromAmounts(parts: Record<UserId, Cents>, total: Cents): Split | null {
const entries = Object.entries(parts);
if (total <= 0 || entries.some(([, c]) => c < 0) || entries.reduce((t, [, c]) => t + c, 0) !== total) return null;
const split: Split = {};
const rests = entries.map(([id, c]) => {
split[id] = Math.floor((c * 10000) / total);
return { id, rest: (c * 10000) % total };
});
let missing = 10000 - Object.values(split).reduce((a, b) => a + b, 0);
for (const { id } of [...rests].sort((a, b) => b.rest - a.rest)) {
if (missing-- <= 0) break;
split[id] += 1;
}
return split;
}
/** "33,33" → 3333. null si invalide ou hors [0, 100]. */
export function percentToBp(input: string): number | null {
const s = input.replace(/[\s%]/g, "").replace(",", ".");
+14
View File
@@ -8,9 +8,23 @@ import {
parseEuro,
percentToBp,
shareAmounts,
splitFromAmounts,
validateSplit,
} from "@/domain/money";
describe("splitFromAmounts", () => {
it("turns the amount each person pays into basis points summing to 100 %", () => {
expect(splitFromAmounts({ h: 60000, s: 39000 }, 99000)).toEqual({ h: 6061, s: 3939 });
expect(splitFromAmounts({ a: 10000, b: 10000, c: 10000 }, 30000)).toEqual({ a: 3334, b: 3333, c: 3333 });
expect(splitFromAmounts({ h: 99000, s: 0 }, 99000)).toEqual({ h: 10000, s: 0 });
});
it("returns null when the amounts do not add up to the total", () => {
expect(splitFromAmounts({ h: 50000, s: 39000 }, 99000)).toBeNull();
expect(splitFromAmounts({ h: 0, s: 0 }, 0)).toBeNull();
});
});
const fr = (n: number) =>
new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(n);