feat: spread an annual amount over 12 monthly entries, add Dividendes category
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9fbcf12323
commit
900f3c1d58
4 files changed
+98
-4
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" },
|
||||
];
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import { bpToPercentLabel, fullSplit, parseEuro, 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";
|
||||
@@ -89,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(
|
||||
@@ -162,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);
|
||||
@@ -258,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 && (
|
||||
@@ -270,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,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({
|
||||
|
||||
@@ -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