feat: operations list with filters and edit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
YugonitoandClaude Opus 5.5 committed 2026-10-27 18:21:56 +01:00
1 parent 1e91f38fd3
commit 63620f8c52
4 files changed
+210

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
import Link from "next/link";
import { OpList } from "@/components/OpList";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { Input, Select } from "@/components/ui/Field";
import { MobileCollapse } from "@/components/ui/MobileCollapse";
import { MonthSwitcher } from "@/components/ui/MonthSwitcher";
import { formatEuro } from "@/domain/money";
import { currentMonthParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { getCategories, getRecurringDefs, getUsers, searchOps } from "@/server/repo";
type Params = { m?: string; p?: string; c?: string; t?: string; s?: string; q?: string };
export default async function OperationsPage({ searchParams }: { searchParams: Promise<Params> }) {
await requireUser();
const sp = await searchParams;
const month = sp.m && /^\d{4}-(0[1-9]|1[0-2])$/.test(sp.m) ? sp.m : currentMonthParis();
const kind = sp.t === "INCOME" || sp.t === "EXPENSE" ? sp.t : undefined;
const status = sp.s === "PLANNED" || sp.s === "ACTUAL" ? sp.s : undefined;
const [ops, users, categories, recurrings] = await Promise.all([
searchOps({ month, userId: sp.p || undefined, categoryId: sp.c || undefined, kind, status, q: sp.q }),
getUsers(),
getCategories(undefined, true),
getRecurringDefs(),
]);
const ctx = {
users,
categories: Object.fromEntries(categories.map((c) => [c.id, { name: c.name, emoji: c.emoji }])),
chargeLabels: Object.fromEntries([...recurrings.map((r) => [r.id, r.label]), ...ops.map((o) => [o.id, o.label])]),
};
const income = ops.filter((o) => o.kind === "INCOME").reduce((t, o) => t + o.amount, 0);
const expense = ops.filter((o) => o.kind === "EXPENSE").reduce((t, o) => t + o.amount, 0);
const filters = { p: sp.p, c: sp.c, t: sp.t, s: sp.s, q: sp.q };
const activeFilters = Object.values(filters).filter(Boolean).length;
const returnTo = `/operations?${new URLSearchParams({ m: month, ...Object.fromEntries(Object.entries(filters).filter(([, v]) => v)) } as Record<string, string>)}`;
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<MonthSwitcher month={month} basePath="/operations" params={filters} />
<Link
href={`/nouvelle?retour=${encodeURIComponent(returnTo)}`}
className="hidden rounded-[10px] bg-accent px-4 py-2.5 font-semibold text-white hover:bg-indigo-700 md:inline-block"
>
+ Nouvelle opération
</Link>
</div>
<Card className="p-3">
<MobileCollapse label={`Filtres${activeFilters > 0 ? ` (${activeFilters})` : ""}`} defaultOpen={activeFilters > 0}>
<form className="mt-2 grid gap-2 md:mt-0 md:grid-cols-[1fr_repeat(4,auto)_auto]">
<input type="hidden" name="m" value={month} />
<Input name="q" placeholder="Rechercher un libellé…" defaultValue={sp.q} />
<Select name="p" defaultValue={sp.p ?? ""} className="md:w-auto">
<option value="">Tout le monde</option>
{users.map((u) => (
<option key={u.id} value={u.id}>
{u.firstName}
</option>
))}
</Select>
<Select name="c" defaultValue={sp.c ?? ""} className="md:w-auto">
<option value="">Toutes catégories</option>
{categories.map((c) => (
<option key={c.id} value={c.id}>
{c.emoji} {c.name}
</option>
))}
</Select>
<Select name="t" defaultValue={sp.t ?? ""} className="md:w-auto">
<option value="">Entrées et dépenses</option>
<option value="INCOME">Entrées</option>
<option value="EXPENSE">Dépenses</option>
</Select>
<Select name="s" defaultValue={sp.s ?? ""} className="md:w-auto">
<option value="">Réel et prévu</option>
<option value="ACTUAL">Réel</option>
<option value="PLANNED">Prévu</option>
</Select>
<div className="flex gap-2">
<Button type="submit">Filtrer</Button>
{activeFilters > 0 && (
<Link href={`/operations?m=${month}`} className="grid place-items-center px-2 text-[13px] font-semibold text-muted">
Effacer
</Link>
)}
</div>
</form>
</MobileCollapse>
</Card>
<Card>
{ops.length === 0 ? (
<p className="py-6 text-center text-muted">Aucune opération ne correspond.</p>
) : (
<OpList ops={ops} ctx={ctx} returnTo={returnTo} />
)}
<div className="mt-3 flex flex-wrap justify-end gap-x-6 gap-y-1 border-t border-line pt-3 text-[13px]">
<span className="text-muted">
{ops.length} opération{ops.length > 1 ? "s" : ""}
</span>
<span>
Entrées <b className="tabular text-pos">{formatEuro(income, { sign: true })}</b>
</span>
<span>
Dépenses <b className="tabular text-neg">{formatEuro(-expense)}</b>
</span>
</div>
</Card>
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
"use client";
import { useState, type ReactNode } from "react";
/** Contenu toujours visible sur ordinateur, repliable derrière un bouton sur mobile. */
export function MobileCollapse({ label, defaultOpen, children }: { label: string; defaultOpen: boolean; children: ReactNode }) {
const [open, setOpen] = useState(defaultOpen);
return (
<>
<button type="button" onClick={() => setOpen((v) => !v)} className="px-1 py-1 font-semibold text-accent md:hidden">
{open ? "− " : "+ "}
{label}
</button>
<div className={`${open ? "block" : "hidden"} md:block`}>{children}</div>
</>
);
}
+28
View File
@@ -92,3 +92,31 @@ export async function getFormData(today: string) {
charges,
};
}
export interface OpsFilter {
month: string;
userId?: string;
categoryId?: string;
kind?: OpKind;
status?: "PLANNED" | "ACTUAL";
q?: string;
}
/** Recherche de la page Opérations. La collation MariaDB rend la recherche insensible à la casse. */
export async function searchOps(f: OpsFilter): Promise<Op[]> {
const rows = await prisma.operation.findMany({
where: {
date: { gte: fromIsoDate(`${f.month}-01`), lt: fromIsoDate(`${addMonths(f.month, 1)}-01`) },
status: f.status ?? { not: "SKIPPED" },
...(f.kind ? { kind: f.kind } : {}),
...(f.categoryId ? { categoryId: f.categoryId } : {}),
...(f.q?.trim() ? { label: { contains: f.q.trim() } } : {}),
...(f.userId
? { OR: [{ accountUserId: f.userId }, { splits: { some: { userId: f.userId, basisPoints: { gt: 0 } } } }] }
: {}),
},
include: { splits: true },
orderBy: [{ date: "desc" }, { createdAt: "desc" }],
});
return rows.map(toOp);
}
+50
View File
@@ -0,0 +1,50 @@
import { beforeEach, describe, expect, it } from "vitest";
import { prisma } from "@/server/db";
import { searchOps } from "@/server/repo";
import { saveOperation } from "@/server/services/operations";
import { categoryId, makeUsers, resetDb } from "./helpers";
let H: string;
let C: string;
beforeEach(async () => {
await resetDb();
const u = await makeUsers();
H = u.h.id;
C = u.c.id;
const base = { status: "ACTUAL" as const, date: "2026-10-15", categoryId: await categoryId("Courses") };
for (const input of [
{ ...base, kind: "EXPENSE" as const, amount: "86,40", label: "Carrefour Market", accountUserId: C, split: { [H]: 5000, [C]: 5000 } },
{ ...base, kind: "EXPENSE" as const, amount: "1000", label: "Loyer", accountUserId: H, split: { [H]: 5000, [C]: 5000 }, categoryId: await categoryId("Logement") },
{ ...base, kind: "EXPENSE" as const, amount: "40", label: "Coiffeur", accountUserId: H, split: { [H]: 10000, [C]: 0 } },
{ ...base, kind: "EXPENSE" as const, amount: "350", label: "Révision", accountUserId: H, split: { [H]: 10000, [C]: 0 }, status: "PLANNED" as const },
{ ...base, kind: "EXPENSE" as const, amount: "20", label: "Ignorée", accountUserId: H, split: { [H]: 10000, [C]: 0 } },
{ ...base, kind: "EXPENSE" as const, amount: "20", label: "Novembre", accountUserId: H, split: { [H]: 10000, [C]: 0 }, date: "2026-11-02" },
]) {
const r = await saveOperation(input, H);
if (!r.ok) throw new Error(r.error);
}
await prisma.operation.updateMany({ where: { label: "Ignorée" }, data: { status: "SKIPPED" } });
});
const labels = async (f: Parameters<typeof searchOps>[0]) => (await searchOps(f)).map((o) => o.label).sort();
describe("searchOps", () => {
it("searches labels case-insensitively within the month", async () => {
expect(await labels({ month: "2026-10", q: "carre" })).toEqual(["Carrefour Market"]);
});
it("filters by person: account holder or anyone with a share", async () => {
expect(await labels({ month: "2026-10", userId: C })).toEqual(["Carrefour Market", "Loyer"]);
});
it("filters by status and never returns skipped operations", async () => {
expect(await labels({ month: "2026-10", status: "PLANNED" })).toEqual(["Révision"]);
expect(await labels({ month: "2026-10" })).toEqual(["Carrefour Market", "Coiffeur", "Loyer", "Révision"]);
});
it("filters by category and kind", async () => {
expect(await labels({ month: "2026-10", categoryId: await categoryId("Logement") })).toEqual(["Loyer"]);
expect(await labels({ month: "2026-10", kind: "INCOME" })).toEqual([]);
});
});