fix: opening balance direction, safe return paths, backup failure detection, review fixes

- 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>
This commit is contained in:
YugonitoandClaude Opus 5.5 committed 2026-10-27 18:51:49 +01:00
1 parent a0bcea4eb1
commit 5b402691f0
15 files changed
+221 -14

No files matched your search

+3 -2
View File
@@ -1,10 +1,11 @@
#!/bin/bash
# Sauvegarde quotidienne de la base (03:00, heure de Paris), rétention 30 jours.
set -u
set -u -o pipefail
dump() {
local file="/backups/finances-$(date +%F_%H%M).sql.gz"
if mariadb-dump -h db -u root -p"$MARIADB_ROOT_PASSWORD" --single-transaction --routines finances | gzip > "$file.tmp"; then
# pipefail : un échec de mariadb-dump fait échouer le pipeline ; la dernière ligne confirme un dump complet.
if mariadb-dump -h db -u root -p"$MARIADB_ROOT_PASSWORD" --single-transaction --routines finances | gzip > "$file.tmp" && gunzip -c "$file.tmp" | tail -n 1 | grep -q "Dump completed"; then
mv "$file.tmp" "$file"
echo "$(date '+%F %T') sauvegarde OK : $file"
else
+3 -2
View File
@@ -1,10 +1,11 @@
import { FormPage } from "@/components/FormPage";
import { safeReturn } from "@/lib/safe-return";
import { OperationForm } from "@/components/OperationForm";
import { todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { getFormData } from "@/server/repo";
const safeReturn = (r?: string) => (r && r.startsWith("/") && !r.startsWith("//") ? r : "/");
const returnPath = (r?: string) => safeReturn(r, "/");
export default async function NewOperationPage({
searchParams,
@@ -15,7 +16,7 @@ export default async function NewOperationPage({
const sp = await searchParams;
const today = todayParis();
const data = await getFormData(today);
const returnTo = safeReturn(sp.retour);
const returnTo = returnPath(sp.retour);
return (
<FormPage title="Nouvelle opération" back={returnTo}>
<OperationForm
+4 -3
View File
@@ -1,5 +1,6 @@
import { notFound } from "next/navigation";
import { FormPage } from "@/components/FormPage";
import { safeReturn } from "@/lib/safe-return";
import { OperationForm } from "@/components/OperationForm";
import { formatEuro } from "@/domain/money";
import { todayParis } from "@/lib/dates";
@@ -8,7 +9,7 @@ import { prisma } from "@/server/db";
import { toOp } from "@/server/mappers";
import { getFormData } from "@/server/repo";
const safeReturn = (r?: string) => (r && r.startsWith("/") && !r.startsWith("//") ? r : "/operations");
const returnPath = (r?: string) => safeReturn(r, "/operations");
export default async function EditOperationPage({
params,
@@ -34,7 +35,7 @@ export default async function EditOperationPage({
if (chargeKey && !charges.some((c) => c.key === chargeKey)) charges.push({ key: chargeKey, label: "Charge actuelle", split: op.split });
return (
<FormPage title="Modifier l'opération" back={safeReturn((await searchParams).retour)}>
<FormPage title="Modifier l'opération" back={returnPath((await searchParams).retour)}>
{op.recurringId && (
<p className="mb-4 rounded-[10px] bg-accent-soft px-3 py-2 text-[13px] text-accent">
Occurrence d&apos;un récurrent : cette modification ne change que ce mois-ci.
@@ -45,7 +46,7 @@ export default async function EditOperationPage({
charges={charges}
currentUserId={user.id}
today={today}
returnTo={safeReturn((await searchParams).retour)}
returnTo={returnPath((await searchParams).retour)}
initial={{
id: op.id,
kind: op.kind,
+16 -2
View File
@@ -1,17 +1,21 @@
import { SettlementsCard } from "@/components/settings/SettlementsCard";
import { CategoriesCard, DefaultSplitCard, PersonCard } from "@/components/settings/SettingsForms";
import { Card, CardLabel } from "@/components/ui/Card";
import { addMonths, currentMonthParis } from "@/lib/dates";
import { centsFromDecimal } from "@/domain/money";
import { addMonths, currentMonthParis, toIsoDate } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { getCategories, getDefaultSplit } from "@/server/repo";
export default async function SettingsPage() {
const me = await requireUser();
const [users, categories, defaultSplit] = await Promise.all([
const [users, categories, defaultSplit, settlements] = await Promise.all([
prisma.user.findMany({ select: { id: true, firstName: true, login: true, color: true }, orderBy: { createdAt: "asc" } }),
getCategories(undefined, true),
getDefaultSplit(),
prisma.settlement.findMany({ orderBy: [{ date: "desc" }, { createdAt: "desc" }], take: 50 }),
]);
const firstName = (id: string) => users.find((u) => u.id === id)?.firstName ?? "?";
const month = currentMonthParis();
return (
@@ -40,6 +44,16 @@ export default async function SettingsPage() {
<button className="rounded-[10px] bg-accent px-4 py-2.5 font-semibold text-white hover:bg-indigo-700">Télécharger</button>
</form>
</Card>
<SettlementsCard
settlements={settlements.map((s) => ({
id: s.id,
from: firstName(s.fromUserId),
to: firstName(s.toUserId),
amount: centsFromDecimal(s.amount),
date: toIsoDate(s.date),
note: s.note,
}))}
/>
</div>
<CategoriesCard categories={categories.map((c) => ({ id: c.id, name: c.name, emoji: c.emoji, kind: c.kind, archived: c.archived }))} />
</div>
@@ -0,0 +1,58 @@
"use client";
import { useTransition } from "react";
import { formatEuro } from "@/domain/money";
import { formatDateFr } from "@/lib/dates";
import { deleteSettlementAction } from "@/server/actions/operations";
import { Card, CardLabel } from "../ui/Card";
export interface SettlementRow {
id: string;
from: string;
to: string;
amount: number;
date: string;
note: string | null;
}
/** Remboursements entre les personnes (dont le solde d'ouverture), supprimables en cas d'erreur de saisie. */
export function SettlementsCard({ settlements }: { settlements: SettlementRow[] }) {
const [pending, start] = useTransition();
return (
<Card className="space-y-2">
<CardLabel>Remboursements entre vous</CardLabel>
{settlements.length === 0 ? (
<p className="text-[13px] text-muted">Aucun remboursement enregistré.</p>
) : (
<div className="divide-y divide-line-soft">
{settlements.map((s) => (
<div key={s.id} className="flex items-center gap-3 py-2">
<div className="min-w-0 flex-1">
<b>
{s.from} → {s.to}
</b>
<div className="truncate text-[13px] text-muted">
{formatDateFr(s.date)}
{s.note ? ` · ${s.note}` : ""}
</div>
</div>
<b className="tabular">{formatEuro(s.amount)}</b>
<button
type="button"
disabled={pending}
className="text-[13px] font-semibold text-neg disabled:opacity-50"
onClick={() => {
if (confirm("Supprimer ce remboursement ? L'équilibre entre vous sera recalculé.")) {
start(async () => void (await deleteSettlementAction(s.id)));
}
}}
>
Supprimer
</button>
</div>
))}
</div>
)}
</Card>
);
}
+19
View File
@@ -0,0 +1,19 @@
// Antislash et caractères de contrôle : les navigateurs les normalisent en « // » (sortie du site).
const UNSAFE = /[\\\u0000-\u001f\u007f]/;
function decoded(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
/** Chemin de retour interne uniquement (anti-redirection ouverte), sinon `fallback`. */
export function safeReturn(value: string | undefined | null, fallback: string): string {
if (!value || !value.startsWith("/") || value.startsWith("//")) return fallback;
if (UNSAFE.test(value) || UNSAFE.test(decoded(value))) return fallback;
const url = new URL(value, "http://local.invalid");
if (url.origin !== "http://local.invalid") return fallback;
return url.pathname + url.search + url.hash;
}
+7
View File
@@ -40,3 +40,10 @@ export async function saveSettlementAction(input: Parameters<typeof ops.saveSett
if (result.ok) refresh();
return result;
}
export async function deleteSettlementAction(id: string) {
await requireUser();
const result = await ops.deleteSettlement(id);
refresh();
return result;
}
+3 -1
View File
@@ -106,7 +106,9 @@ export async function createHousehold(input: HouseholdInput) {
create: { id: 1, defaultSplit: { [users[0].id]: firstBp, [users[1].id]: 10000 - firstBp } },
});
if (opening !== null) {
const [from, to] = input.openingDirection === "second-owes-first" ? [users[1], users[0]] : [users[0], users[1]];
// Une dette de B envers A s'enregistre comme si A avait avancé l'argent à B (versement A → B).
const [debtor, creditor] = input.openingDirection === "second-owes-first" ? [users[1], users[0]] : [users[0], users[1]];
const [from, to] = [creditor, debtor];
await tx.settlement.create({
data: {
fromUserId: from.id,
+2 -1
View File
@@ -7,6 +7,7 @@ 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.");
@@ -137,7 +138,7 @@ export async function saveLoan(input: LoanFormInput, today: string = todayParis(
return { loanId, recurringId: rec.id };
});
await prisma.operation.deleteMany({ where: { recurringId, status: "PLANNED", date: { gte: fromIsoDate(today) } } });
await dropPlannedWithAllocations(recurringId, today);
await syncRecurrings(today);
return { ok: true, id: loanId };
}
+15
View File
@@ -105,8 +105,18 @@ export async function saveOperation(raw: OperationInput, currentUserId: string):
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 };
}
@@ -152,3 +162,8 @@ export async function saveSettlement(input: {
});
return { ok: true };
}
export async function deleteSettlement(id: string): Promise<Result> {
await prisma.settlement.deleteMany({ where: { id } });
return { ok: true };
}
+16 -1
View File
@@ -32,6 +32,21 @@ async function dropPlannedFrom(recurringId: string, from: string) {
await prisma.operation.deleteMany({ where: { recurringId, status: "PLANNED", date: { gte: fromIsoDate(from) } } });
}
/**
* Après modification d'une charge : ses occurrences prévues et celles des entrées qui lui sont affectées
* (dont la répartition copie celle de la charge) sont régénérées par la prochaine synchro.
*/
export async function dropPlannedWithAllocations(recurringId: string, from: string) {
const allocated = await prisma.recurring.findMany({ where: { allocatedToRecurringId: recurringId }, select: { id: true } });
await prisma.operation.deleteMany({
where: {
recurringId: { in: [recurringId, ...allocated.map((r) => r.id)] },
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." };
@@ -73,7 +88,7 @@ export async function saveRecurring(raw: RecurringInput, today: string = todayPa
return (await tx.recurring.create({ data: { ...data, splits: { create: splitRows(input.split as Split) } } })).id;
});
await dropPlannedFrom(id, today);
await dropPlannedWithAllocations(id, today);
await syncRecurrings(today);
return { ok: true, id };
}
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { safeReturn } from "@/lib/safe-return";
describe("safeReturn", () => {
it("keeps internal paths with their query string", () => {
expect(safeReturn("/operations?m=2026-10&q=a", "/")).toBe("/operations?m=2026-10&q=a");
expect(safeReturn("/", "/x")).toBe("/");
});
it("falls back for anything that could leave the site", () => {
for (const bad of [undefined, "", "https://evil.com", "//evil.com", "/\\evil.com", "/%09/evil.com", "\t//evil.com", "javascript:alert(1)", "/\t/evil.com"]) {
expect(safeReturn(bad, "/fallback")).toBe("/fallback");
}
});
});
+9 -2
View File
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it } from "vitest";
import { computeBalances, describeBalance } from "@/domain/balance";
import { createHousehold, hashPassword, verifyPassword } from "@/server/auth";
import { toSettlement } from "@/server/mappers";
import { prisma } from "@/server/db";
import { resetDb } from "./helpers";
@@ -33,9 +35,14 @@ describe("createHousehold", () => {
const setting = await prisma.setting.findUniqueOrThrow({ where: { id: 1 } });
expect(setting.defaultSplit).toEqual({ [users[0].id]: 6000, [users[1].id]: 4000 });
const s = await prisma.settlement.findFirstOrThrow();
expect(s.fromUserId).toBe(users[1].id);
expect(s.toUserId).toBe(users[0].id);
expect(s.amount.toString()).toBe("150");
// « La personne 2 doit à la personne 1 » : le tableau de bord doit l'afficher ainsi.
const ids = users.map((u) => u.id);
expect(describeBalance(computeBalances([], [toSettlement(s)], ids))).toEqual({
debtor: users[1].id,
creditor: users[0].id,
amount: 15000,
});
});
it("skips the opening balance when empty", async () => {
+23
View File
@@ -4,6 +4,7 @@ import {
confirmOperation,
deleteOperation,
saveOperation,
deleteSettlement,
saveSettlement,
skipOperation,
type OperationInput,
@@ -108,6 +109,19 @@ describe("saveOperation", () => {
});
});
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);
if (!r.ok) throw new Error(r.error);
await deleteOperation(r.id);
expect(await syncRecurrings("2026-10-27")).toBe(11);
const october = await prisma.operation.findMany({
where: { date: new Date("2026-10-27T00:00:00Z"), status: { not: "SKIPPED" } },
});
expect(october).toHaveLength(0);
});
});
describe("confirm / skip", () => {
it("confirms a planned operation with an adjusted amount and date", async () => {
const r = await saveOperation(expense({ status: "PLANNED" }), H);
@@ -130,6 +144,15 @@ describe("confirm / skip", () => {
});
});
describe("deleteSettlement", () => {
it("removes a repayment entered by mistake", async () => {
await saveSettlement({ fromUserId: C, toUserId: H, amount: "450", date: "2026-10-27" });
const s = await prisma.settlement.findFirstOrThrow();
expect(await deleteSettlement(s.id)).toEqual({ ok: true });
expect(await prisma.settlement.count()).toBe(0);
});
});
describe("saveSettlement", () => {
it("records a repayment and refuses one to oneself", async () => {
expect(await saveSettlement({ fromUserId: C, toUserId: H, amount: "450", date: "2026-10-27" })).toEqual({ ok: true });
+28
View File
@@ -50,6 +50,34 @@ describe("saveRecurring", () => {
expect(future.every((o) => o.amount.toString() === "1050")).toBe(true);
});
it("re-splits future allocated incomes when the charge's split changes", async () => {
const rent = await saveRecurring(rentInput, TODAY);
if (!rent.ok) throw new Error(rent.error);
const employer = await saveRecurring(
{
...rentInput,
kind: "INCOME",
amount: "200",
label: "Part loyer employeur",
categoryId: await categoryId("Remboursement employeur"),
split: { [H]: 10000, [C]: 0 },
allocatedToRecurringId: rent.id,
allocationMode: "REDUCE_SHARED",
},
TODAY,
);
if (!employer.ok) throw new Error(employer.error);
await saveRecurring({ ...rentInput, id: rent.id, split: { [H]: 6000, [C]: 4000 } }, TODAY);
const future = await prisma.operation.findMany({
where: { recurringId: employer.id, status: "PLANNED", date: { gte: fromIsoDate(TODAY) } },
include: { splits: true },
});
expect(future.length).toBeGreaterThan(0);
for (const o of future) {
expect(Object.fromEntries(o.splits.map((s) => [s.userId, s.basisPoints]))).toEqual({ [H]: 6000, [C]: 4000 });
}
});
it("validates the input", async () => {
expect(await saveRecurring({ ...rentInput, amount: "0" }, TODAY)).toEqual({ ok: false, error: "Montant invalide." });
expect(await saveRecurring({ ...rentInput, dayOfMonth: 32 }, TODAY)).toEqual({ ok: false, error: "Jour du mois invalide (1 à 31)." });