diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx new file mode 100644 index 0000000..4579321 --- /dev/null +++ b/src/app/(app)/layout.tsx @@ -0,0 +1,18 @@ +import { MobileNav } from "@/components/MobileNav"; +import { Sidebar } from "@/components/Sidebar"; +import { requireUser } from "@/server/auth"; +import { syncRecurrings } from "@/server/sync"; + +export const dynamic = "force-dynamic"; + +export default async function AppLayout({ children }: { children: React.ReactNode }) { + const user = await requireUser(); + await syncRecurrings(); + return ( +
+ +
{children}
+ +
+ ); +} diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index 9d9a93c..0ca2a00 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -1,12 +1,6 @@ import { requireUser } from "@/server/auth"; -import { logoutAction } from "@/server/actions/auth"; export default async function DashboardPage() { const user = await requireUser(); - return ( -
-

Bonjour {user.firstName}

-
-
- ); + return

Bonjour {user.firstName}

; } diff --git a/src/components/MobileNav.tsx b/src/components/MobileNav.tsx new file mode 100644 index 0000000..1d38473 --- /dev/null +++ b/src/components/MobileNav.tsx @@ -0,0 +1,56 @@ +"use client"; + +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { useState } from "react"; +import { logoutAction } from "@/server/actions/auth"; +import { isActive } from "./nav"; + +const tab = "flex flex-1 flex-col items-center gap-0.5 py-2 text-[11px] font-medium"; + +export function MobileNav() { + const pathname = usePathname(); + const [more, setMore] = useState(false); + const color = (href: string) => (isActive(pathname, href) ? "text-accent" : "text-muted"); + + return ( + <> + {more && ( +
setMore(false)}> +
+ {[ + ["/budgets", "◔ Budgets"], + ["/credits", "⌂ Crédits & charges"], + ["/reglages", "⚙ Réglages"], + ].map(([href, label]) => ( + + {label} + + ))} + ∿ Simulateur (bientôt) +
+ +
+
+
+ )} + + + ); +} diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx new file mode 100644 index 0000000..1c1362e --- /dev/null +++ b/src/components/Sidebar.tsx @@ -0,0 +1,60 @@ +"use client"; + +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { logoutAction } from "@/server/actions/auth"; +import { Logo } from "./Logo"; +import { Avatar } from "./ui/Avatar"; +import { Chip } from "./ui/Chip"; +import { NAV, isActive } from "./nav"; + +const item = "flex items-center gap-2.5 rounded-lg px-2.5 py-2 font-medium"; + +export function Sidebar({ user }: { user: { firstName: string; color: string } }) { + const pathname = usePathname(); + return ( + + ); +} diff --git a/src/components/nav.ts b/src/components/nav.ts new file mode 100644 index 0000000..1baf22e --- /dev/null +++ b/src/components/nav.ts @@ -0,0 +1,18 @@ +export interface NavItem { + href: string; + label: string; + icon: string; + soon?: boolean; +} + +export const NAV: NavItem[] = [ + { href: "/", label: "Tableau de bord", icon: "◧" }, + { href: "/operations", label: "Opérations", icon: "≡" }, + { href: "/recurrents", label: "Récurrents & prévu", icon: "↻" }, + { href: "/budgets", label: "Budgets", icon: "◔" }, + { href: "/credits", label: "Crédits & charges", icon: "⌂" }, + { href: "/simulateur", label: "Simulateur", icon: "∿", soon: true }, +]; + +export const isActive = (pathname: string, href: string) => + href === "/" ? pathname === "/" : pathname === href || pathname.startsWith(`${href}/`); diff --git a/src/components/ui/Amount.tsx b/src/components/ui/Amount.tsx new file mode 100644 index 0000000..e2f321d --- /dev/null +++ b/src/components/ui/Amount.tsx @@ -0,0 +1,13 @@ +import { formatEuro } from "@/domain/money"; +import type { OpKind } from "@/domain/types"; + +/** Montant en vert (entrée) ou rouge (dépense), chiffres tabulaires. */ +export function Amount({ cents, kind, className = "" }: { cents: number; kind?: OpKind; className?: string }) { + const signed = kind === "EXPENSE" ? -cents : cents; + const color = kind === "INCOME" ? "text-pos" : kind === "EXPENSE" ? "text-neg" : ""; + return ( + + {formatEuro(signed, { sign: kind !== undefined })} + + ); +} diff --git a/src/components/ui/Avatar.tsx b/src/components/ui/Avatar.tsx new file mode 100644 index 0000000..586096b --- /dev/null +++ b/src/components/ui/Avatar.tsx @@ -0,0 +1,10 @@ +export function Avatar({ user, size = 34 }: { user: { firstName: string; color: string }; size?: number }) { + return ( + + {user.firstName.slice(0, 1).toUpperCase()} + + ); +} diff --git a/src/components/ui/Chip.tsx b/src/components/ui/Chip.tsx new file mode 100644 index 0000000..86e8572 --- /dev/null +++ b/src/components/ui/Chip.tsx @@ -0,0 +1,24 @@ +import type { ReactNode } from "react"; + +type Tone = "accent" | "split" | "planned" | "link" | "danger"; + +const TONES: Record = { + accent: "bg-accent-soft text-accent", + split: "bg-gray-100 text-gray-700", + planned: "bg-warn-soft text-warn", + link: "bg-pos-soft text-pos", + danger: "bg-neg-soft text-neg", +}; + +/** Pastille ; `color` (couleur d'une personne) remplace le ton. */ +export function Chip({ tone = "accent", color, children }: { tone?: Tone; color?: string; children: ReactNode }) { + const style = color ? { backgroundColor: `${color}1a`, color } : undefined; + return ( + + {children} + + ); +} diff --git a/src/components/ui/MonthSwitcher.tsx b/src/components/ui/MonthSwitcher.tsx new file mode 100644 index 0000000..c03a4f0 --- /dev/null +++ b/src/components/ui/MonthSwitcher.tsx @@ -0,0 +1,30 @@ +import Link from "next/link"; +import { addMonths, monthLabelFr } from "@/lib/dates"; + +/** ‹ Mois › : navigation par le paramètre ?m=YYYY-MM, en conservant les autres filtres. */ +export function MonthSwitcher({ + month, + basePath, + params = {}, +}: { + month: string; + basePath: string; + params?: Record; +}) { + const href = (m: string) => { + const q = new URLSearchParams({ ...Object.fromEntries(Object.entries(params).filter(([, v]) => v)), m } as Record); + return `${basePath}?${q}`; + }; + const arrow = "grid h-[30px] w-[30px] place-items-center rounded-lg border border-line bg-white text-muted hover:text-ink"; + return ( +
+ + ‹ + +

{monthLabelFr(month)}

+ + › + +
+ ); +} diff --git a/src/components/ui/Pills.tsx b/src/components/ui/Pills.tsx new file mode 100644 index 0000000..3c08b92 --- /dev/null +++ b/src/components/ui/Pills.tsx @@ -0,0 +1,33 @@ +"use client"; + +export interface PillOption { + value: T; + label: string; +} + +export function Pills({ + options, + value, + onChange, +}: { + options: PillOption[]; + value: T | null; + onChange: (v: T) => void; +}) { + return ( +
+ {options.map((o) => ( + + ))} +
+ ); +} diff --git a/src/server/mappers.ts b/src/server/mappers.ts new file mode 100644 index 0000000..429c141 --- /dev/null +++ b/src/server/mappers.ts @@ -0,0 +1,58 @@ +import type { Operation, OperationSplit, Recurring, RecurringSplit, Settlement as SettlementRow } from "@prisma/client"; +import { centsFromDecimal } from "@/domain/money"; +import type { RecurringDef } from "@/domain/recurrence"; +import type { Op, Settlement, Split } from "@/domain/types"; +import { toIsoDate } from "@/lib/dates"; + +export const splitOf = (rows: { userId: string; basisPoints: number }[]): Split => + Object.fromEntries(rows.map((s) => [s.userId, s.basisPoints])); + +export const splitRows = (split: Split) => + Object.entries(split).map(([userId, basisPoints]) => ({ userId, basisPoints })); + +export function toOp(row: Operation & { splits: OperationSplit[] }): Op { + return { + id: row.id, + kind: row.kind, + amount: centsFromDecimal(row.amount), + date: toIsoDate(row.date), + label: row.label, + categoryId: row.categoryId, + accountUserId: row.accountUserId, + status: row.status, + split: splitOf(row.splits), + recurringId: row.recurringId, + allocatedToRecurringId: row.allocatedToRecurringId, + allocatedToOperationId: row.allocatedToOperationId, + allocationMode: row.allocationMode, + }; +} + +export function toRecurringDef(row: Recurring & { splits: RecurringSplit[] }): RecurringDef { + return { + id: row.id, + kind: row.kind, + amount: centsFromDecimal(row.amount), + label: row.label, + categoryId: row.categoryId, + accountUserId: row.accountUserId, + split: splitOf(row.splits), + frequency: row.frequency, + dayOfMonth: row.dayOfMonth, + startDate: toIsoDate(row.startDate), + endDate: row.endDate ? toIsoDate(row.endDate) : null, + paused: row.paused, + allocatedToRecurringId: row.allocatedToRecurringId, + allocationMode: row.allocationMode, + }; +} + +export function toSettlement(row: SettlementRow): Settlement { + return { + id: row.id, + fromUserId: row.fromUserId, + toUserId: row.toUserId, + amount: centsFromDecimal(row.amount), + date: toIsoDate(row.date), + }; +} diff --git a/src/server/repo.ts b/src/server/repo.ts new file mode 100644 index 0000000..4959111 --- /dev/null +++ b/src/server/repo.ts @@ -0,0 +1,56 @@ +import type { OpKind } from "@prisma/client"; +import { addMonths, fromIsoDate } from "@/lib/dates"; +import type { RecurringDef } from "@/domain/recurrence"; +import type { Op, Settlement, Split } from "@/domain/types"; +import { prisma } from "./db"; +import { toOp, toRecurringDef, toSettlement } from "./mappers"; + +export interface UserLite { + id: string; + firstName: string; + color: string; +} + +export async function getUsers(): Promise { + return prisma.user.findMany({ select: { id: true, firstName: true, color: true }, orderBy: { createdAt: "asc" } }); +} + +export async function getCategories(kind?: OpKind, includeArchived = false) { + return prisma.category.findMany({ + where: { ...(kind ? { kind } : {}), ...(includeArchived ? {} : { archived: false }) }, + orderBy: [{ kind: "desc" }, { sortOrder: "asc" }, { name: "asc" }], + }); +} + +export async function getOpsBetween(from: string, toExclusive: string): Promise { + const rows = await prisma.operation.findMany({ + where: { date: { gte: fromIsoDate(from), lt: fromIsoDate(toExclusive) } }, + include: { splits: true }, + orderBy: [{ date: "desc" }, { createdAt: "desc" }], + }); + return rows.map(toOp); +} + +export async function getOpsForMonth(month: string): Promise { + return getOpsBetween(`${month}-01`, `${addMonths(month, 1)}-01`); +} + +export async function getAllActualOps(): Promise { + const rows = await prisma.operation.findMany({ where: { status: "ACTUAL" }, include: { splits: true } }); + return rows.map(toOp); +} + +export async function getSettlements(): Promise { + const rows = await prisma.settlement.findMany({ orderBy: { date: "desc" } }); + return rows.map(toSettlement); +} + +export async function getRecurringDefs(): Promise { + const rows = await prisma.recurring.findMany({ include: { splits: true }, orderBy: { label: "asc" } }); + return rows.map(toRecurringDef); +} + +export async function getDefaultSplit(): Promise { + const setting = await prisma.setting.findUnique({ where: { id: 1 } }); + return (setting?.defaultSplit ?? {}) as Split; +} diff --git a/src/server/sync.ts b/src/server/sync.ts new file mode 100644 index 0000000..70b6403 --- /dev/null +++ b/src/server/sync.ts @@ -0,0 +1,50 @@ +import { Prisma } from "@prisma/client"; +import { occurrenceKey, planOccurrences } from "@/domain/recurrence"; +import { decimalFromCents } from "@/domain/money"; +import { fromIsoDate, todayParis, toIsoDate } from "@/lib/dates"; +import { prisma } from "./db"; +import { splitRows } from "./mappers"; +import { getRecurringDefs, getUsers } from "./repo"; + +/** + * Matérialise les occurrences prévues des récurrents sur 12 mois glissants (spec §9). + * Idempotent : appelé à chaque chargement de page, sans cron. + */ +export async function syncRecurrings(today: string = todayParis()): Promise { + const [defs, users] = await Promise.all([getRecurringDefs(), getUsers()]); + if (defs.length === 0) return 0; + + const existing = await prisma.operation.findMany({ + where: { recurringId: { not: null }, occurrenceDate: { not: null } }, + select: { recurringId: true, occurrenceDate: true }, + }); + const keys = new Set(existing.map((e) => occurrenceKey(e.recurringId!, toIsoDate(e.occurrenceDate!)))); + + let created = 0; + for (const p of planOccurrences(defs, keys, today, users.map((u) => u.id))) { + try { + await prisma.operation.create({ + data: { + kind: p.kind, + amount: decimalFromCents(p.amount), + date: fromIsoDate(p.date), + occurrenceDate: fromIsoDate(p.occurrenceDate), + label: p.label, + categoryId: p.categoryId, + accountUserId: p.accountUserId, + createdById: p.accountUserId, + status: "PLANNED", + recurringId: p.recurringId, + allocatedToRecurringId: p.allocatedToRecurringId, + allocationMode: p.allocationMode, + splits: { create: splitRows(p.split) }, + }, + }); + created += 1; + } catch (e) { + // Deux chargements simultanés : l'occurrence existe déjà, on ignore. + if (!(e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002")) throw e; + } + } + return created; +} diff --git a/tests/server/sync.test.ts b/tests/server/sync.test.ts new file mode 100644 index 0000000..88d7481 --- /dev/null +++ b/tests/server/sync.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { fromIsoDate } from "@/lib/dates"; +import { prisma } from "@/server/db"; +import { syncRecurrings } from "@/server/sync"; +import { categoryId, makeUsers, resetDb } from "./helpers"; + +async function makeRent() { + const { h, c } = await makeUsers(); + const rent = await prisma.recurring.create({ + data: { + kind: "EXPENSE", + amount: "1000.00", + label: "Loyer", + categoryId: await categoryId("Logement"), + accountUserId: h.id, + frequency: "MONTHLY", + dayOfMonth: 5, + startDate: fromIsoDate("2026-01-05"), + splits: { create: [{ userId: h.id, basisPoints: 5000 }, { userId: c.id, basisPoints: 5000 }] }, + }, + }); + return { h, c, rent }; +} + +describe("syncRecurrings", () => { + beforeEach(resetDb); + + it("creates 12 months of planned occurrences with splits, idempotently", async () => { + const { rent } = await makeRent(); + expect(await syncRecurrings("2026-10-27")).toBe(12); + expect(await syncRecurrings("2026-10-27")).toBe(0); + const first = await prisma.operation.findFirstOrThrow({ + where: { recurringId: rent.id }, + orderBy: { date: "asc" }, + include: { splits: true }, + }); + expect(first.date.toISOString().slice(0, 10)).toBe("2026-10-05"); + expect(first.status).toBe("PLANNED"); + expect(first.splits.map((s) => s.basisPoints)).toEqual([5000, 5000]); + }); + + it("recreates deleted occurrences but never skipped ones", async () => { + const { rent } = await makeRent(); + await syncRecurrings("2026-10-27"); + await prisma.operation.updateMany({ + where: { recurringId: rent.id, date: fromIsoDate("2026-10-05") }, + data: { status: "SKIPPED" }, + }); + await prisma.operation.deleteMany({ where: { recurringId: rent.id, date: fromIsoDate("2026-11-05") } }); + expect(await syncRecurrings("2026-10-27")).toBe(1); + const october = await prisma.operation.findFirstOrThrow({ where: { recurringId: rent.id, date: fromIsoDate("2026-10-05") } }); + expect(october.status).toBe("SKIPPED"); + }); + + it("keeps actual history when the recurring template is deleted", async () => { + const { rent } = await makeRent(); + await syncRecurrings("2026-10-27"); + const october = await prisma.operation.findFirstOrThrow({ where: { recurringId: rent.id, date: fromIsoDate("2026-10-05") } }); + await prisma.operation.update({ where: { id: october.id }, data: { status: "ACTUAL" } }); + await prisma.operation.deleteMany({ where: { recurringId: rent.id, status: "PLANNED" } }); + await prisma.recurring.delete({ where: { id: rent.id } }); + const kept = await prisma.operation.findUniqueOrThrow({ where: { id: october.id } }); + expect(kept.recurringId).toBeNull(); + expect(kept.status).toBe("ACTUAL"); + }); +});