feat: recurring templates, planned and to-confirm lists
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
63620f8c52
commit
bfaa38510b
10 files changed
+792
No files matched your search
@@ -0,0 +1,102 @@
|
||||
import { z } from "zod";
|
||||
import { decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
|
||||
import type { Split } from "@/domain/types";
|
||||
import { fromIsoDate, todayParis } from "@/lib/dates";
|
||||
import { prisma } from "../db";
|
||||
import { splitRows } from "../mappers";
|
||||
import { syncRecurrings } from "../sync";
|
||||
import type { Result } from "./operations";
|
||||
|
||||
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date invalide.");
|
||||
|
||||
const recurringSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
kind: z.enum(["INCOME", "EXPENSE"]),
|
||||
amount: z.string(),
|
||||
label: z.string().trim().min(1, "Le libellé est obligatoire.").max(190),
|
||||
categoryId: z.string().min(1, "Choisissez une catégorie."),
|
||||
accountUserId: z.string().min(1),
|
||||
split: z.record(z.string(), z.number().int()),
|
||||
frequency: z.enum(["MONTHLY", "QUARTERLY", "YEARLY"]),
|
||||
dayOfMonth: z.number().int().min(1, "Jour du mois invalide (1 à 31).").max(31, "Jour du mois invalide (1 à 31)."),
|
||||
startDate: isoDate,
|
||||
endDate: isoDate.nullable(),
|
||||
allocatedToRecurringId: z.string().nullish(),
|
||||
allocationMode: z.enum(["REDUCE_SHARED", "BENEFICIARY_ONLY", "CUSTOM"]).nullish(),
|
||||
});
|
||||
|
||||
export type RecurringInput = z.input<typeof recurringSchema>;
|
||||
|
||||
/** Supprime les occurrences prévues à partir d'une date (les réelles et les prévues passées restent). */
|
||||
async function dropPlannedFrom(recurringId: string, from: string) {
|
||||
await prisma.operation.deleteMany({ where: { recurringId, status: "PLANNED", date: { gte: fromIsoDate(from) } } });
|
||||
}
|
||||
|
||||
export async function saveRecurring(raw: RecurringInput, today: string = todayParis()): Promise<Result<{ id: string }>> {
|
||||
const parsed = recurringSchema.safeParse(raw);
|
||||
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? "Données invalides." };
|
||||
const input = parsed.data;
|
||||
const cents = parseEuro(input.amount);
|
||||
if (cents === null) return { ok: false, error: "Montant invalide." };
|
||||
const splitError = validateSplit(input.split as Split);
|
||||
if (splitError) return { ok: false, error: splitError };
|
||||
if (input.endDate && input.endDate < input.startDate) return { ok: false, error: "La date de fin précède la date de début." };
|
||||
const allocatedTo = input.kind === "INCOME" ? input.allocatedToRecurringId || null : null;
|
||||
if (allocatedTo && allocatedTo === input.id) return { ok: false, error: "Un récurrent ne peut pas s'affecter à lui-même." };
|
||||
|
||||
if (input.id) {
|
||||
const existing = await prisma.recurring.findUnique({ where: { id: input.id } });
|
||||
if (!existing) return { ok: false, error: "Récurrent introuvable." };
|
||||
if (existing.loanId) return { ok: false, error: "Ce récurrent est géré depuis Crédits." };
|
||||
}
|
||||
|
||||
const data = {
|
||||
kind: input.kind,
|
||||
amount: decimalFromCents(cents),
|
||||
label: input.label,
|
||||
categoryId: input.categoryId,
|
||||
accountUserId: input.accountUserId,
|
||||
frequency: input.frequency,
|
||||
dayOfMonth: input.dayOfMonth,
|
||||
startDate: fromIsoDate(input.startDate),
|
||||
endDate: input.endDate ? fromIsoDate(input.endDate) : null,
|
||||
allocatedToRecurringId: allocatedTo,
|
||||
allocationMode: allocatedTo ? (input.allocationMode ?? "REDUCE_SHARED") : null,
|
||||
};
|
||||
|
||||
const id = await prisma.$transaction(async (tx) => {
|
||||
if (input.id) {
|
||||
await tx.recurringSplit.deleteMany({ where: { recurringId: input.id } });
|
||||
await tx.recurring.update({ where: { id: input.id }, data: { ...data, splits: { create: splitRows(input.split as Split) } } });
|
||||
return input.id;
|
||||
}
|
||||
return (await tx.recurring.create({ data: { ...data, splits: { create: splitRows(input.split as Split) } } })).id;
|
||||
});
|
||||
|
||||
await dropPlannedFrom(id, today);
|
||||
await syncRecurrings(today);
|
||||
return { ok: true, id };
|
||||
}
|
||||
|
||||
export async function setRecurringPaused(id: string, paused: boolean, today: string = todayParis()): Promise<Result> {
|
||||
await prisma.recurring.update({ where: { id }, data: { paused } });
|
||||
if (paused) await dropPlannedFrom(id, today);
|
||||
else await syncRecurrings(today);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export async function endRecurring(id: string, endDate: string, today: string = todayParis()): Promise<Result> {
|
||||
if (!isoDate.safeParse(endDate).success) return { ok: false, error: "Date invalide." };
|
||||
await prisma.recurring.update({ where: { id }, data: { endDate: fromIsoDate(endDate) } });
|
||||
await prisma.operation.deleteMany({ where: { recurringId: id, status: "PLANNED", date: { gt: fromIsoDate(endDate) } } });
|
||||
await syncRecurrings(today);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export async function deleteRecurring(id: string, today: string = todayParis()): Promise<Result> {
|
||||
const rec = await prisma.recurring.findUnique({ where: { id } });
|
||||
if (rec?.loanId) return { ok: false, error: "Ce récurrent est géré depuis Crédits." };
|
||||
await dropPlannedFrom(id, today);
|
||||
await prisma.recurring.delete({ where: { id } });
|
||||
return { ok: true };
|
||||
}
|
||||
Reference in new issue
Block a user