- opening balance: "person 2 owes person 1" was stored the wrong way round - retour param: reject backslash/control chars (open redirect) - backup: pipefail + check dump completeness, failed dumps no longer logged OK - deleting a recurring occurrence marks it skipped so sync does not recreate it - editing a charge regenerates future occurrences of incomes allocated to it - settlements (incl. opening balance) listed in settings and deletable Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
170 lines
6.6 KiB
TypeScript
170 lines
6.6 KiB
TypeScript
import { z } from "zod";
|
|
import { decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
|
|
import type { Split } from "@/domain/types";
|
|
import { fromIsoDate } from "@/lib/dates";
|
|
import { prisma } from "../db";
|
|
import { splitRows } from "../mappers";
|
|
|
|
export type Result<T = object> = ({ ok: true } & T) | { ok: false; error: string };
|
|
|
|
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date invalide.");
|
|
|
|
const operationSchema = 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."),
|
|
date: isoDate,
|
|
accountUserId: z.string().min(1),
|
|
status: z.enum(["PLANNED", "ACTUAL"]),
|
|
split: z.record(z.string(), z.number().int()),
|
|
note: z.string().max(2000).optional(),
|
|
allocatedToRecurringId: z.string().nullish(),
|
|
allocatedToOperationId: z.string().nullish(),
|
|
allocationMode: z.enum(["REDUCE_SHARED", "BENEFICIARY_ONLY", "CUSTOM"]).nullish(),
|
|
makeRecurring: z
|
|
.object({ frequency: z.enum(["MONTHLY", "QUARTERLY", "YEARLY"]), endDate: isoDate.nullable() })
|
|
.optional(),
|
|
});
|
|
|
|
export type OperationInput = z.input<typeof operationSchema>;
|
|
|
|
const firstError = (e: z.ZodError) => e.issues[0]?.message ?? "Données invalides.";
|
|
|
|
/** Création ou modification d'une opération (saisie rapide et édition). */
|
|
export async function saveOperation(raw: OperationInput, currentUserId: string): Promise<Result<{ id: string }>> {
|
|
const parsed = operationSchema.safeParse(raw);
|
|
if (!parsed.success) return { ok: false, error: firstError(parsed.error) };
|
|
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 };
|
|
|
|
const allocatedToRecurringId = input.allocatedToRecurringId || null;
|
|
const allocatedToOperationId = input.allocatedToOperationId || null;
|
|
const allocated = allocatedToRecurringId !== null || allocatedToOperationId !== null;
|
|
if (allocated && input.kind === "EXPENSE") {
|
|
return { ok: false, error: "Seule une entrée peut être affectée à une charge." };
|
|
}
|
|
if (allocatedToRecurringId && allocatedToOperationId) {
|
|
return { ok: false, error: "Une entrée ne peut être affectée qu'à une seule charge." };
|
|
}
|
|
|
|
const fields = {
|
|
kind: input.kind,
|
|
amount: decimalFromCents(cents),
|
|
label: input.label,
|
|
categoryId: input.categoryId,
|
|
date: fromIsoDate(input.date),
|
|
accountUserId: input.accountUserId,
|
|
status: input.status,
|
|
note: input.note?.trim() || null,
|
|
allocatedToRecurringId,
|
|
allocatedToOperationId,
|
|
allocationMode: allocated ? (input.allocationMode ?? "REDUCE_SHARED") : null,
|
|
};
|
|
const splits = splitRows(input.split as Split);
|
|
|
|
const id = await prisma.$transaction(async (tx) => {
|
|
if (input.id) {
|
|
await tx.operationSplit.deleteMany({ where: { operationId: input.id } });
|
|
await tx.operation.update({ where: { id: input.id }, data: { ...fields, splits: { create: splits } } });
|
|
return input.id;
|
|
}
|
|
|
|
let recurring: { recurringId: string; occurrenceDate: Date } | object = {};
|
|
if (input.makeRecurring) {
|
|
const rec = await tx.recurring.create({
|
|
data: {
|
|
kind: fields.kind,
|
|
amount: fields.amount,
|
|
label: fields.label,
|
|
categoryId: fields.categoryId,
|
|
accountUserId: fields.accountUserId,
|
|
frequency: input.makeRecurring.frequency,
|
|
dayOfMonth: Number(input.date.slice(8, 10)),
|
|
startDate: fields.date,
|
|
endDate: input.makeRecurring.endDate ? fromIsoDate(input.makeRecurring.endDate) : null,
|
|
allocatedToRecurringId,
|
|
allocationMode: allocatedToRecurringId ? fields.allocationMode : null,
|
|
splits: { create: splits },
|
|
},
|
|
});
|
|
recurring = { recurringId: rec.id, occurrenceDate: fields.date };
|
|
}
|
|
|
|
const op = await tx.operation.create({
|
|
data: { ...fields, ...recurring, createdById: currentUserId, splits: { create: splits } },
|
|
});
|
|
return op.id;
|
|
});
|
|
|
|
return { ok: true, id };
|
|
}
|
|
|
|
/** Une occurrence de récurrent est marquée ignorée (sinon la synchro la recréerait) ; le reste est supprimé. */
|
|
export async function deleteOperation(id: string): Promise<Result> {
|
|
const op = await prisma.operation.findUnique({ where: { id } });
|
|
if (!op) return { ok: true };
|
|
if (op.recurringId) {
|
|
await prisma.$transaction([
|
|
prisma.operation.updateMany({ where: { allocatedToOperationId: id }, data: { allocatedToOperationId: null } }),
|
|
prisma.operation.update({ where: { id }, data: { status: "SKIPPED" } }),
|
|
]);
|
|
} else {
|
|
await prisma.operation.delete({ where: { id } });
|
|
}
|
|
return { ok: true };
|
|
}
|
|
|
|
/** Passe une opération prévue en réelle, avec montant et date ajustables. */
|
|
export async function confirmOperation(id: string, amount: string, date: string): Promise<Result> {
|
|
const cents = parseEuro(amount);
|
|
if (cents === null) return { ok: false, error: "Montant invalide." };
|
|
if (!isoDate.safeParse(date).success) return { ok: false, error: "Date invalide." };
|
|
await prisma.operation.update({
|
|
where: { id },
|
|
data: { status: "ACTUAL", amount: decimalFromCents(cents), date: fromIsoDate(date) },
|
|
});
|
|
return { ok: true };
|
|
}
|
|
|
|
/** Occurrence de récurrent : marquée ignorée (pas régénérée). Prévue ponctuelle : supprimée. */
|
|
export async function skipOperation(id: string): Promise<Result> {
|
|
const op = await prisma.operation.findUniqueOrThrow({ where: { id } });
|
|
if (op.recurringId) await prisma.operation.update({ where: { id }, data: { status: "SKIPPED" } });
|
|
else await prisma.operation.delete({ where: { id } });
|
|
return { ok: true };
|
|
}
|
|
|
|
export async function saveSettlement(input: {
|
|
fromUserId: string;
|
|
toUserId: string;
|
|
amount: string;
|
|
date: string;
|
|
note?: string;
|
|
}): Promise<Result> {
|
|
if (input.fromUserId === input.toUserId) return { ok: false, error: "Choisissez deux personnes différentes." };
|
|
const cents = parseEuro(input.amount);
|
|
if (cents === null) return { ok: false, error: "Montant invalide." };
|
|
if (!isoDate.safeParse(input.date).success) return { ok: false, error: "Date invalide." };
|
|
await prisma.settlement.create({
|
|
data: {
|
|
fromUserId: input.fromUserId,
|
|
toUserId: input.toUserId,
|
|
amount: decimalFromCents(cents),
|
|
date: fromIsoDate(input.date),
|
|
note: input.note?.trim() || null,
|
|
},
|
|
});
|
|
return { ok: true };
|
|
}
|
|
|
|
export async function deleteSettlement(id: string): Promise<Result> {
|
|
await prisma.settlement.deleteMany({ where: { id } });
|
|
return { ok: true };
|
|
}
|