From 9fbcf12323df5d815c636ed07440451691a581f5 Mon Sep 17 00:00:00 2001 From: Yugonito Date: Tue, 27 Oct 2026 21:38:00 +0100 Subject: [PATCH] feat: enter a custom split in euros, other share completed automatically Co-Authored-By: Claude Opus 5.5 --- src/components/CustomSplitFields.tsx | 115 ++++++++++++++++++++ src/components/OperationForm.tsx | 30 +---- src/components/SplitPicker.tsx | 47 +++----- src/components/recurrents/RecurringForm.tsx | 6 +- src/domain/money.ts | 20 ++++ tests/domain/money.test.ts | 14 +++ 6 files changed, 175 insertions(+), 57 deletions(-) create mode 100644 src/components/CustomSplitFields.tsx diff --git a/src/components/CustomSplitFields.tsx b/src/components/CustomSplitFields.tsx new file mode 100644 index 0000000..545daaa --- /dev/null +++ b/src/components/CustomSplitFields.tsx @@ -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("pct"); + const [texts, setTexts] = useState>(() => + Object.fromEntries(ids.map((id) => [id, bpToPercentLabel(initial[id] ?? 0)])), + ); + + const compute = (u: Unit, t: Record): 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 ( +
+ {total !== undefined && ( + + )} +
+ {users.map((u) => ( + + ))} + + {unit === "pct" ? `Total ${bpToPercentLabel(pctTotal)} %` : `Total ${formatEuro(eurTotal)} sur ${total == null ? "—" : formatEuro(total)}`} + +
+
+ ); +} diff --git a/src/components/OperationForm.tsx b/src/components/OperationForm.tsx index 19075ab..86a8f68 100644 --- a/src/components/OperationForm.tsx +++ b/src/components/OperationForm.tsx @@ -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(initialChoice); - const [custom, setCustom] = useState>(() => - Object.fromEntries(userIds.map((id) => [id, bpToPercentLabel((initial?.split ?? defaultSplit)[id] ?? 0)])), - ); + const [customSplit, setCustomSplit] = useState(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 && ( -
- {users.map((u) => ( - - ))} - - Total {bpToPercentLabel(customTotal)} % - -
+ )} diff --git a/src/components/SplitPicker.tsx b/src/components/SplitPicker.tsx index 0ee06f6..e41abe3 100644 --- a/src/components/SplitPicker.tsx +++ b/src/components/SplitPicker.tsx @@ -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(() => { @@ -28,18 +31,14 @@ export function SplitPicker({ const full = ids.find((id) => value[id] === 10000); return full ? `full:${full}` : "custom"; }); - const [custom, setCustom] = useState>(() => - Object.fromEntries(ids.map((id) => [id, bpToPercentLabel(value[id] ?? 0)])), - ); + const [custom, setCustom] = useState(value); - const fromCustom = (c: Record): 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 (
@@ -53,25 +52,15 @@ export function SplitPicker({ onChange={pick} /> {choice === "custom" && ( -
- {users.map((u) => ( - - ))} - Total {bpToPercentLabel(total)} % -
+ { + setCustom(s); + onChange(s); + }} + /> )}
); diff --git a/src/components/recurrents/RecurringForm.tsx b/src/components/recurrents/RecurringForm.tsx index db6ccbd..2bf29e1 100644 --- a/src/components/recurrents/RecurringForm.tsx +++ b/src/components/recurrents/RecurringForm.tsx @@ -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" && (
Répartition
- +
)}
@@ -179,7 +179,7 @@ export function RecurringForm({ value={mode} onChange={setMode} /> - {mode === "CUSTOM" && } + {mode === "CUSTOM" && } )}
diff --git a/src/domain/money.ts b/src/domain/money.ts index 428aef4..7119370 100644 --- a/src/domain/money.ts +++ b/src/domain/money.ts @@ -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, 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(",", "."); diff --git a/tests/domain/money.test.ts b/tests/domain/money.test.ts index 3fcca8b..46406ad 100644 --- a/tests/domain/money.test.ts +++ b/tests/domain/money.test.ts @@ -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);