Compare commits
3
Commits
4837a5cf22
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
900f3c1d58 | ||
|
|
9fbcf12323 | ||
|
|
c3c371aefe |
No files matched your search
@@ -23,6 +23,7 @@ const CATEGORIES: { name: string; emoji: string; kind: OpKind }[] = [
|
||||
{ name: "Remboursement employeur", emoji: "🧾", kind: "INCOME" },
|
||||
{ name: "IK", emoji: "🚗", kind: "INCOME" },
|
||||
{ name: "Prime", emoji: "💶", kind: "INCOME" },
|
||||
{ name: "Dividendes", emoji: "📈", kind: "INCOME" },
|
||||
{ name: "Autres revenus", emoji: "➕", kind: "INCOME" },
|
||||
];
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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, formatEuro, 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";
|
||||
@@ -88,6 +89,7 @@ export function OperationForm({
|
||||
const [chargeKey, setChargeKey] = useState(initial?.chargeKey ?? "");
|
||||
const [allocationMode, setAllocationMode] = useState<AllocationMode>(initial?.allocationMode ?? "REDUCE_SHARED");
|
||||
const [recurring, setRecurring] = useState(false);
|
||||
const [spread, setSpread] = useState(false);
|
||||
const [frequency, setFrequency] = useState<Frequency>("MONTHLY");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
const [showMore, setShowMore] = useState(
|
||||
@@ -101,16 +103,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 +119,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);
|
||||
@@ -166,6 +163,7 @@ export function OperationForm({
|
||||
allocatedToOperationId: allocated && chargeKey.startsWith("o:") ? chargeKey.slice(2) : null,
|
||||
allocationMode: allocated ? allocationMode : null,
|
||||
makeRecurring: !initial && recurring ? { frequency, endDate: endDate || null } : undefined,
|
||||
spreadOverYear: !initial && spread,
|
||||
});
|
||||
if (!result.ok) return setError(result.error);
|
||||
router.push(returnTo);
|
||||
@@ -254,23 +252,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">
|
||||
@@ -278,7 +260,7 @@ export function OperationForm({
|
||||
</Field>
|
||||
|
||||
<button type="button" onClick={() => setShowMore((v) => !v)} className="text-[13px] font-semibold text-accent">
|
||||
{showMore ? "− Moins d'options" : "+ Récurrent, prévue, affecter à une charge"}
|
||||
{showMore ? "− Moins d'options" : "+ Récurrent, annuel lissé, prévue, affecter à une charge"}
|
||||
</button>
|
||||
|
||||
{showMore && (
|
||||
@@ -290,11 +272,36 @@ export function OperationForm({
|
||||
|
||||
{!initial && (
|
||||
<div className="space-y-3">
|
||||
<label className="flex items-center gap-2 font-medium">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={spread}
|
||||
onChange={(e) => {
|
||||
setSpread(e.target.checked);
|
||||
if (e.target.checked) setRecurring(false);
|
||||
}}
|
||||
className="h-4 w-4 accent-accent"
|
||||
/>
|
||||
Montant annuel : lisser sur 12 mois
|
||||
</label>
|
||||
{spread && (
|
||||
<p className="-mt-1 text-[13px] text-muted">
|
||||
{(() => {
|
||||
const cents = parseEuro(amount);
|
||||
return cents && cents >= 12
|
||||
? `12 entrées de ${formatEuro(Math.floor(cents / 12))} par mois à partir de la date choisie, comme un revenu mensuel.`
|
||||
: "Saisissez le montant de l'année : il sera réparti en 12 mois à partir de la date choisie.";
|
||||
})()}
|
||||
</p>
|
||||
)}
|
||||
<label className="flex items-center gap-2 font-medium">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={recurring}
|
||||
onChange={(e) => setRecurring(e.target.checked)}
|
||||
onChange={(e) => {
|
||||
setRecurring(e.target.checked);
|
||||
if (e.target.checked) setSpread(false);
|
||||
}}
|
||||
className="h-4 w-4 accent-accent"
|
||||
/>
|
||||
Rendre récurrent
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
|
||||
+26
-2
@@ -3,9 +3,13 @@ import type { Cents, Split, UserId } from "./types";
|
||||
const euro = new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" });
|
||||
const MINUS = "−";
|
||||
|
||||
/** "86,40", "1 234,56", "86.40" → centimes. null si vide, nul, négatif ou invalide. */
|
||||
/** "86,40", "1 234,56", "86.40", "40.000 €" → centimes. null si vide, nul, négatif ou invalide. */
|
||||
export function parseEuro(input: string): Cents | null {
|
||||
const s = input.replace(/[\s ]/g, "").replace(",", ".");
|
||||
let s = input.replace(/[\s €]/g, "");
|
||||
// Les points sont des séparateurs de milliers s'il y a une virgule décimale ("40.000,50")
|
||||
// ou s'ils séparent des groupes de 3 chiffres ("40.000") ; sinon c'est la décimale ("86.40").
|
||||
if (s.includes(",") || /^\d{1,3}(\.\d{3})+$/.test(s)) s = s.replace(/\./g, "");
|
||||
s = s.replace(",", ".");
|
||||
if (!/^\d+(\.\d{1,2})?$/.test(s)) return null;
|
||||
const [units, decimals = ""] = s.split(".");
|
||||
const cents = Number(units) * 100 + Number(decimals.padEnd(2, "0"));
|
||||
@@ -51,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(",", ".");
|
||||
|
||||
@@ -50,7 +50,7 @@ const optionalEuro = (s: string) => (s.trim() === "" ? null : (parseEuro(s) ?? u
|
||||
export async function saveLoan(input: LoanFormInput, today: string = todayParis()): Promise<Result<{ id: string }>> {
|
||||
if (!input.name.trim()) return { ok: false, error: "Le nom est obligatoire." };
|
||||
const principal = parseEuro(input.principal);
|
||||
if (principal === null) return { ok: false, error: "Capital invalide." };
|
||||
if (principal === null) return { ok: false, error: "Capital emprunté invalide (ex. 40000 ou 40 000,00)." };
|
||||
const rateText = input.annualRate.trim().replace(",", ".");
|
||||
const rate = /^\d+(\.\d{1,3})?$/.test(rateText) ? Number(rateText) : NaN;
|
||||
if (!(rate >= 0 && rate < 100)) return { ok: false, error: "Taux invalide." };
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import { decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
|
||||
import type { Split } from "@/domain/types";
|
||||
import { fromIsoDate } from "@/lib/dates";
|
||||
import { addMonths, dateInMonth, fromIsoDate, monthOf } from "@/lib/dates";
|
||||
import { prisma } from "../db";
|
||||
import { splitRows } from "../mappers";
|
||||
|
||||
@@ -26,6 +26,8 @@ const operationSchema = z.object({
|
||||
makeRecurring: z
|
||||
.object({ frequency: z.enum(["MONTHLY", "QUARTERLY", "YEARLY"]), endDate: isoDate.nullable() })
|
||||
.optional(),
|
||||
/** Montant annuel lissé : 12 opérations mensuelles d'un douzième (création seulement). */
|
||||
spreadOverYear: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type OperationInput = z.input<typeof operationSchema>;
|
||||
@@ -49,6 +51,10 @@ export async function saveOperation(raw: OperationInput, currentUserId: string):
|
||||
if (allocated && input.kind === "EXPENSE") {
|
||||
return { ok: false, error: "Seule une entrée peut être affectée à une charge." };
|
||||
}
|
||||
if (input.spreadOverYear && input.makeRecurring) {
|
||||
return { ok: false, error: "Un montant annuel lissé ne peut pas être récurrent." };
|
||||
}
|
||||
if (input.spreadOverYear && cents < 12) return { ok: false, error: "Montant trop faible pour être lissé sur 12 mois." };
|
||||
if (allocatedToRecurringId && allocatedToOperationId) {
|
||||
return { ok: false, error: "Une entrée ne peut être affectée qu'à une seule charge." };
|
||||
}
|
||||
@@ -75,6 +81,26 @@ export async function saveOperation(raw: OperationInput, currentUserId: string):
|
||||
return input.id;
|
||||
}
|
||||
|
||||
if (input.spreadOverYear) {
|
||||
// Un douzième par mois, même jour (borné à la fin du mois) ; le reste d'arrondi va au premier mois.
|
||||
const share = Math.floor(cents / 12);
|
||||
const ids: string[] = [];
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const op = await tx.operation.create({
|
||||
data: {
|
||||
...fields,
|
||||
amount: decimalFromCents(i === 0 ? cents - share * 11 : share),
|
||||
label: `${fields.label.slice(0, 182)} (${i + 1}/12)`,
|
||||
date: fromIsoDate(dateInMonth(addMonths(monthOf(input.date), i), Number(input.date.slice(8, 10)))),
|
||||
createdById: currentUserId,
|
||||
splits: { create: splits },
|
||||
},
|
||||
});
|
||||
ids.push(op.id);
|
||||
}
|
||||
return ids[0];
|
||||
}
|
||||
|
||||
let recurring: { recurringId: string; occurrenceDate: Date } | object = {};
|
||||
if (input.makeRecurring) {
|
||||
const rec = await tx.recurring.create({
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -25,6 +39,14 @@ describe("parseEuro", () => {
|
||||
expect(parseEuro("0,5")).toBe(50);
|
||||
});
|
||||
|
||||
it("accepts a euro sign and dots as thousands separators", () => {
|
||||
expect(parseEuro("40 000 €")).toBe(4000000);
|
||||
expect(parseEuro("40000€")).toBe(4000000);
|
||||
expect(parseEuro("40.000")).toBe(4000000);
|
||||
expect(parseEuro("1.234.567")).toBe(123456700);
|
||||
expect(parseEuro("40.000,50")).toBe(4000050);
|
||||
});
|
||||
|
||||
it("rejects empty, zero, negative and malformed amounts", () => {
|
||||
for (const s of ["", "0", "0,00", "-5", "abc", "12,345", "1,2,3"]) expect(parseEuro(s)).toBeNull();
|
||||
});
|
||||
|
||||
@@ -60,7 +60,7 @@ describe("saveLoan", () => {
|
||||
|
||||
it("validates the rate and the capital", async () => {
|
||||
expect(await saveLoan({ ...input, annualRate: "abc" }, TODAY)).toEqual({ ok: false, error: "Taux invalide." });
|
||||
expect(await saveLoan({ ...input, principal: "0" }, TODAY)).toEqual({ ok: false, error: "Capital invalide." });
|
||||
expect(await saveLoan({ ...input, principal: "0" }, TODAY)).toEqual({ ok: false, error: "Capital emprunté invalide (ex. 40000 ou 40 000,00)." });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -109,6 +109,46 @@ describe("saveOperation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveOperation with an annual amount spread over 12 months", () => {
|
||||
const dividends = (over: Partial<OperationInput> = {}): OperationInput => ({
|
||||
kind: "INCOME",
|
||||
amount: "1000",
|
||||
label: "Dividendes",
|
||||
categoryId: salaire,
|
||||
date: "2026-10-31",
|
||||
accountUserId: H,
|
||||
status: "ACTUAL",
|
||||
split: { [H]: 10000, [C]: 0 },
|
||||
spreadOverYear: true,
|
||||
...over,
|
||||
});
|
||||
|
||||
it("creates 12 monthly entries summing to the annual amount", async () => {
|
||||
expect(await saveOperation(dividends(), H)).toMatchObject({ ok: true });
|
||||
const ops = await prisma.operation.findMany({ orderBy: { date: "asc" }, include: { splits: true } });
|
||||
expect(ops).toHaveLength(12);
|
||||
expect(ops.map((o) => o.date.toISOString().slice(0, 10)).slice(0, 5)).toEqual([
|
||||
"2026-10-31",
|
||||
"2026-11-30",
|
||||
"2026-12-31",
|
||||
"2027-01-31",
|
||||
"2027-02-28",
|
||||
]);
|
||||
expect(ops[11].date.toISOString().slice(0, 10)).toBe("2027-09-30");
|
||||
expect(ops.map((o) => o.amount.toString())).toEqual(["83.37", ...Array(11).fill("83.33")]);
|
||||
expect(ops[0].label).toBe("Dividendes (1/12)");
|
||||
expect(ops[11].label).toBe("Dividendes (12/12)");
|
||||
expect(ops.every((o) => o.status === "ACTUAL" && o.splits.length === 2 && o.recurringId === null)).toBe(true);
|
||||
});
|
||||
|
||||
it("cannot also be recurring", async () => {
|
||||
expect(await saveOperation(dividends({ makeRecurring: { frequency: "MONTHLY", endDate: null } }), H)).toEqual({
|
||||
ok: false,
|
||||
error: "Un montant annuel lissé ne peut pas être récurrent.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteOperation on a recurring occurrence", () => {
|
||||
it("does not come back at the next sync", async () => {
|
||||
const r = await saveOperation(expense({ makeRecurring: { frequency: "MONTHLY", endDate: null } }), H);
|
||||
|
||||
Reference in new issue
Block a user