diff --git a/docker/backup.sh b/docker/backup.sh index 3821249..1c6db80 100644 --- a/docker/backup.sh +++ b/docker/backup.sh @@ -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 diff --git a/src/app/(app)/nouvelle/page.tsx b/src/app/(app)/nouvelle/page.tsx index 107d686..2b1621f 100644 --- a/src/app/(app)/nouvelle/page.tsx +++ b/src/app/(app)/nouvelle/page.tsx @@ -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 ( (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 ( - + {op.recurringId && (

Occurrence d'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, diff --git a/src/app/(app)/reglages/page.tsx b/src/app/(app)/reglages/page.tsx index 2798366..dc559e3 100644 --- a/src/app/(app)/reglages/page.tsx +++ b/src/app/(app)/reglages/page.tsx @@ -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() { + ({ + id: s.id, + from: firstName(s.fromUserId), + to: firstName(s.toUserId), + amount: centsFromDecimal(s.amount), + date: toIsoDate(s.date), + note: s.note, + }))} + /> ({ id: c.id, name: c.name, emoji: c.emoji, kind: c.kind, archived: c.archived }))} /> diff --git a/src/components/settings/SettlementsCard.tsx b/src/components/settings/SettlementsCard.tsx new file mode 100644 index 0000000..b0f1faa --- /dev/null +++ b/src/components/settings/SettlementsCard.tsx @@ -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 ( + + Remboursements entre vous + {settlements.length === 0 ? ( +

Aucun remboursement enregistré.

+ ) : ( +
+ {settlements.map((s) => ( +
+
+ + {s.from} → {s.to} + +
+ {formatDateFr(s.date)} + {s.note ? ` · ${s.note}` : ""} +
+
+ {formatEuro(s.amount)} + +
+ ))} +
+ )} + + ); +} diff --git a/src/lib/safe-return.ts b/src/lib/safe-return.ts new file mode 100644 index 0000000..531c113 --- /dev/null +++ b/src/lib/safe-return.ts @@ -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; +} diff --git a/src/server/actions/operations.ts b/src/server/actions/operations.ts index f27eb81..60de89f 100644 --- a/src/server/actions/operations.ts +++ b/src/server/actions/operations.ts @@ -40,3 +40,10 @@ export async function saveSettlementAction(input: Parameters { - await prisma.operation.delete({ where: { id } }); + 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 { + await prisma.settlement.deleteMany({ where: { id } }); + return { ok: true }; +} diff --git a/src/server/services/recurrings.ts b/src/server/services/recurrings.ts index 3345f32..6b6ac6e 100644 --- a/src/server/services/recurrings.ts +++ b/src/server/services/recurrings.ts @@ -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> { 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 }; } diff --git a/tests/lib/safe-return.test.ts b/tests/lib/safe-return.test.ts new file mode 100644 index 0000000..40656a6 --- /dev/null +++ b/tests/lib/safe-return.test.ts @@ -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"); + } + }); +}); diff --git a/tests/server/auth.test.ts b/tests/server/auth.test.ts index 07032e1..90728b6 100644 --- a/tests/server/auth.test.ts +++ b/tests/server/auth.test.ts @@ -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 () => { diff --git a/tests/server/operations.test.ts b/tests/server/operations.test.ts index 880be48..0384e95 100644 --- a/tests/server/operations.test.ts +++ b/tests/server/operations.test.ts @@ -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 }); diff --git a/tests/server/recurrings.test.ts b/tests/server/recurrings.test.ts index a03b5e2..300c38f 100644 --- a/tests/server/recurrings.test.ts +++ b/tests/server/recurrings.test.ts @@ -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)." });