152 lines
6.8 KiB
TypeScript
152 lines
6.8 KiB
TypeScript
import type { Loan, LoanSplit } from "@prisma/client";
|
|
import { z } from "zod";
|
|
import { buildSchedule, type LoanInput } from "@/domain/loan";
|
|
import { centsFromDecimal, decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
|
|
import type { Split } from "@/domain/types";
|
|
import { fromIsoDate, todayParis, toIsoDate } from "@/lib/dates";
|
|
import { prisma } from "../db";
|
|
import { splitRows } from "../mappers";
|
|
import { syncRecurrings } from "../sync";
|
|
import { dropPlannedWithAllocations } from "./recurrings";
|
|
import type { Result } from "./operations";
|
|
|
|
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date invalide.");
|
|
|
|
export interface LoanFormInput {
|
|
id?: string;
|
|
name: string;
|
|
lender: string;
|
|
principal: string;
|
|
annualRate: string;
|
|
durationMonths: number;
|
|
startDate: string;
|
|
insuranceMonthly: string;
|
|
accountUserId: string;
|
|
split: Split;
|
|
paymentOverride: string;
|
|
referenceDate: string;
|
|
referenceRemainingCapital: string;
|
|
}
|
|
|
|
export function toLoanInput(row: Loan): LoanInput {
|
|
return {
|
|
principal: centsFromDecimal(row.principal),
|
|
annualRatePct: Number(row.annualRate.toString()),
|
|
durationMonths: row.durationMonths,
|
|
startDate: toIsoDate(row.startDate),
|
|
insuranceMonthly: centsFromDecimal(row.insuranceMonthly),
|
|
paymentOverride: row.paymentOverride ? centsFromDecimal(row.paymentOverride) : null,
|
|
referenceDate: row.referenceDate ? toIsoDate(row.referenceDate) : null,
|
|
referenceRemainingCapital: row.referenceRemainingCapital ? centsFromDecimal(row.referenceRemainingCapital) : null,
|
|
};
|
|
}
|
|
|
|
export type LoanWithSplits = Loan & { splits: LoanSplit[] };
|
|
|
|
/** Montant facultatif : vide → null ; invalide → undefined. */
|
|
const optionalEuro = (s: string) => (s.trim() === "" ? null : (parseEuro(s) ?? undefined));
|
|
|
|
/** Création ou modification d'un crédit et de son récurrent de mensualité. */
|
|
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 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." };
|
|
if (!Number.isInteger(input.durationMonths) || input.durationMonths < 1 || input.durationMonths > 600) {
|
|
return { ok: false, error: "Durée invalide (en mois)." };
|
|
}
|
|
if (!isoDate.safeParse(input.startDate).success) return { ok: false, error: "Date de première échéance invalide." };
|
|
const insurance = input.insuranceMonthly.trim() === "" ? 0 : parseEuro(input.insuranceMonthly);
|
|
if (insurance === null) return { ok: false, error: "Assurance invalide." };
|
|
const paymentOverride = optionalEuro(input.paymentOverride);
|
|
const refCapital = optionalEuro(input.referenceRemainingCapital);
|
|
if (paymentOverride === undefined) return { ok: false, error: "Mensualité invalide." };
|
|
if (refCapital === undefined) return { ok: false, error: "Capital restant dû invalide." };
|
|
const refDate = input.referenceDate.trim() || null;
|
|
if (refDate && !isoDate.safeParse(refDate).success) return { ok: false, error: "Date de référence invalide." };
|
|
if ((refDate === null) !== (refCapital === null)) {
|
|
return { ok: false, error: "Renseignez à la fois le capital restant dû et sa date." };
|
|
}
|
|
const splitError = validateSplit(input.split);
|
|
if (splitError) return { ok: false, error: splitError };
|
|
|
|
const loanInput: LoanInput = {
|
|
principal,
|
|
annualRatePct: rate,
|
|
durationMonths: input.durationMonths,
|
|
startDate: input.startDate,
|
|
insuranceMonthly: insurance,
|
|
paymentOverride,
|
|
referenceDate: refDate,
|
|
referenceRemainingCapital: refCapital,
|
|
};
|
|
let schedule;
|
|
try {
|
|
schedule = buildSchedule(loanInput);
|
|
} catch (e) {
|
|
return { ok: false, error: e instanceof Error ? e.message : "Échéancier impossible." };
|
|
}
|
|
const tracked = schedule.filter((r) => !r.beforeTracking);
|
|
if (tracked.length === 0) return { ok: false, error: "Ce crédit est déjà entièrement remboursé." };
|
|
|
|
const category =
|
|
(await prisma.category.findFirst({ where: { name: "Crédit", kind: "EXPENSE" } })) ??
|
|
(await prisma.category.findFirstOrThrow({ where: { kind: "EXPENSE" }, orderBy: { sortOrder: "asc" } }));
|
|
|
|
const loanData = {
|
|
name: input.name.trim(),
|
|
lender: input.lender.trim() || null,
|
|
principal: decimalFromCents(principal),
|
|
annualRate: rateText,
|
|
durationMonths: input.durationMonths,
|
|
startDate: fromIsoDate(input.startDate),
|
|
insuranceMonthly: decimalFromCents(insurance),
|
|
accountUserId: input.accountUserId,
|
|
paymentOverride: paymentOverride === null ? null : decimalFromCents(paymentOverride),
|
|
referenceDate: refDate ? fromIsoDate(refDate) : null,
|
|
referenceRemainingCapital: refCapital === null ? null : decimalFromCents(refCapital),
|
|
};
|
|
const recurringData = {
|
|
kind: "EXPENSE" as const,
|
|
amount: decimalFromCents(tracked[0].payment + insurance),
|
|
label: loanData.name,
|
|
categoryId: category.id,
|
|
accountUserId: input.accountUserId,
|
|
frequency: "MONTHLY" as const,
|
|
dayOfMonth: Number(input.startDate.slice(8, 10)),
|
|
startDate: fromIsoDate(tracked[0].date),
|
|
endDate: fromIsoDate(schedule[schedule.length - 1].date),
|
|
};
|
|
|
|
const { loanId, recurringId } = await prisma.$transaction(async (tx) => {
|
|
let loanId = input.id;
|
|
if (loanId) {
|
|
await tx.loanSplit.deleteMany({ where: { loanId } });
|
|
await tx.loan.update({ where: { id: loanId }, data: { ...loanData, splits: { create: splitRows(input.split) } } });
|
|
} else {
|
|
loanId = (await tx.loan.create({ data: { ...loanData, splits: { create: splitRows(input.split) } } })).id;
|
|
}
|
|
const existing = await tx.recurring.findUnique({ where: { loanId } });
|
|
if (existing) {
|
|
await tx.recurringSplit.deleteMany({ where: { recurringId: existing.id } });
|
|
await tx.recurring.update({ where: { id: existing.id }, data: { ...recurringData, splits: { create: splitRows(input.split) } } });
|
|
return { loanId, recurringId: existing.id };
|
|
}
|
|
const rec = await tx.recurring.create({ data: { ...recurringData, loanId, splits: { create: splitRows(input.split) } } });
|
|
return { loanId, recurringId: rec.id };
|
|
});
|
|
|
|
await dropPlannedWithAllocations(recurringId, today);
|
|
await syncRecurrings(today);
|
|
return { ok: true, id: loanId };
|
|
}
|
|
|
|
export async function deleteLoan(id: string, today: string = todayParis()): Promise<Result> {
|
|
const rec = await prisma.recurring.findUnique({ where: { loanId: id } });
|
|
if (rec) await prisma.operation.deleteMany({ where: { recurringId: rec.id, status: "PLANNED", date: { gte: fromIsoDate(today) } } });
|
|
await prisma.loan.delete({ where: { id } });
|
|
return { ok: true };
|
|
}
|