Compare commits

..
14 Commits
Author SHA1 Message Date
YugonitoandClaude Opus 5.5 900f3c1d58 feat: spread an annual amount over 12 monthly entries, add Dividendes category
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:40:53 +01:00
YugonitoandClaude Opus 5.5 9fbcf12323 feat: enter a custom split in euros, other share completed automatically
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:38:00 +01:00
YugonitoandClaude Opus 5.5 c3c371aefe fix: accept euro sign and dot thousands separators in amounts, clearer loan capital error
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:31:44 +01:00
YugonitoandClaude Opus 5.5 4837a5cf22 fix: keep empty public/ dir so the Docker build can copy it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 19:16:27 +01:00
YugonitoandClaude Opus 5.5 5b402691f0 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>
2026-10-27 18:51:49 +01:00
YugonitoandClaude Opus 5.5 a0bcea4eb1 feat: production docker stack with nightly backups and README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:38:24 +01:00
YugonitoandClaude Opus 5.5 8201496bb6 feat: settings and CSV export
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:33:37 +01:00
YugonitoandClaude Opus 5.5 9cb7fe8c81 feat: loans with amortization schedule and net charges
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:31:08 +01:00
YugonitoandClaude Opus 5.5 0b9c6a11d3 feat: monthly budgets per category with history
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:28:00 +01:00
YugonitoandClaude Opus 5.5 bfaa38510b feat: recurring templates, planned and to-confirm lists
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:25:40 +01:00
YugonitoandClaude Opus 5.5 63620f8c52 feat: operations list with filters and edit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:21:56 +01:00
YugonitoandClaude Opus 5.5 1e91f38fd3 feat: monthly dashboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:20:24 +01:00
YugonitoandClaude Opus 5.5 2860f2f776 feat: quick entry form and operation/settlement actions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:17:43 +01:00
YugonitoandClaude Opus 5.5 08f23f909f feat: app shell, UI kit, data loading, recurring sync
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:14:57 +01:00
77 changed files with 5058 additions and 14 deletions

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
node_modules
.next
.git
.env
.env.*
!.env.example
.superpowers
backups
dist
tests
docs
*.log
+8 -2
View File
@@ -1,4 +1,10 @@
# Développement local (voir docker-compose.dev.yml) # --- Production (docker-compose.yml) ---
# Générer chaque secret avec : openssl rand -hex 32
MARIADB_ROOT_PASSWORD=
MARIADB_PASSWORD=
SESSION_SECRET=
APP_PORT=3000
# --- Développement local uniquement (docker-compose.dev.yml + npm run dev) ---
DATABASE_URL="mysql://root:dev@localhost:3307/finances" DATABASE_URL="mysql://root:dev@localhost:3307/finances"
TEST_DATABASE_URL="mysql://root:dev@localhost:3307/finances_test" TEST_DATABASE_URL="mysql://root:dev@localhost:3307/finances_test"
SESSION_SECRET="change-me-to-32+chars-random-string-xxxxxxxx"
+37
View File
@@ -0,0 +1,37 @@
# --- Dépendances ---
FROM node:24-alpine AS deps
WORKDIR /app
RUN apk add --no-cache openssl
COPY package.json package-lock.json ./
RUN npm ci
# --- Build Next.js (standalone) + scripts compilés ---
FROM node:24-alpine AS build
WORKDIR /app
RUN apk add --no-cache openssl
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npx prisma generate \
&& npm run build \
&& npx esbuild prisma/seed.ts scripts/reset-password.ts --bundle --platform=node --format=cjs \
--packages=external --entry-names=[name] --outdir=dist
# --- Image finale ---
FROM node:24-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production TZ=Europe/Paris PORT=3000 HOSTNAME=0.0.0.0 NEXT_TELEMETRY_DISABLED=1
RUN apk add --no-cache openssl tzdata \
&& npm install -g prisma@6.19.3 \
&& addgroup -S app && adduser -S app -G app
COPY --from=build --chown=app:app /app/.next/standalone ./
COPY --from=build --chown=app:app /app/.next/static ./.next/static
COPY --from=build --chown=app:app /app/public ./public
COPY --from=build --chown=app:app /app/prisma ./prisma
COPY --from=build --chown=app:app /app/dist ./dist
COPY --from=build --chown=app:app /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=build --chown=app:app /app/node_modules/@prisma/client ./node_modules/@prisma/client
COPY --from=build --chown=app:app /app/node_modules/bcryptjs ./node_modules/bcryptjs
COPY --chmod=755 docker/entrypoint.sh /entrypoint.sh
USER app
EXPOSE 3000
ENTRYPOINT ["/entrypoint.sh"]
+80
View File
@@ -0,0 +1,80 @@
# Finances du foyer
Suivi des entrées, dépenses et charges partagées d'un foyer de deux personnes :
répartition en %, « qui doit combien à qui », récurrents, dépenses prévues, budgets,
remboursements employeur affectés à une charge (IK, part de loyer…) et crédits.
Stack : Next.js 15 (TypeScript) + MariaDB, le tout sous Docker Compose. Accès réseau local uniquement (HTTP).
## Installation sur la VM
Prérequis : Docker et le plugin `docker compose`, git, et un accès Internet pendant le build (paquets npm, police Inter).
```bash
git clone git@git.fabout.it:hcloez/hcl-finances-manager.git
cd hcl-finances-manager
cp .env.example .env
# Renseigner les 3 secrets dans .env (un par ligne) :
openssl rand -hex 32 # → MARIADB_ROOT_PASSWORD
openssl rand -hex 32 # → MARIADB_PASSWORD
openssl rand -hex 32 # → SESSION_SECRET
docker compose up -d --build
```
Ouvrir ensuite **http://192.168.1.211:3000**. Au premier accès, un écran d'installation crée les deux comptes
(prénom, identifiant, mot de passe, couleur), la répartition par défaut et un éventuel solde d'ouverture.
Les variables `DATABASE_URL` / `TEST_DATABASE_URL` de `.env` ne servent qu'au développement local ; elles sont ignorées par la stack de production.
## Mise à jour
```bash
git pull
docker compose up -d --build
```
Les migrations de la base s'appliquent automatiquement au démarrage du conteneur `app`.
## Sauvegardes
- Le service `backup` fait un dump compressé de la base **au démarrage puis chaque nuit à 03:00** (heure de Paris)
dans `./backups/finances-AAAA-MM-JJ_HHMM.sql.gz`. Les dumps de plus de **30 jours** sont supprimés.
- La VM entière est par ailleurs sauvegardée par Proxmox Backup Server.
- Vérifier les sauvegardes : `ls -lh backups/` et `docker compose logs backup`.
### Restaurer un dump
```bash
docker compose stop app
gunzip -c backups/finances-AAAA-MM-JJ_HHMM.sql.gz \
| docker compose exec -T db sh -c 'mariadb -u root -p"$MARIADB_ROOT_PASSWORD" finances'
docker compose start app
```
## Mot de passe oublié
Chacun change son propre mot de passe dans **Réglages**. En cas d'oubli :
```bash
docker compose exec app node dist/reset-password.js <identifiant> <nouveau-mot-de-passe>
```
## Développement local
```bash
npm install
cp .env.example .env # garder les variables de la section « Développement local », ajouter SESSION_SECRET
docker compose -f docker-compose.dev.yml up -d # MariaDB sur le port 3307 (bases finances et finances_test)
npx prisma migrate dev
npm run db:seed
npm run dev # http://localhost:3000
npm test # tests unitaires + intégration (base finances_test)
```
Organisation du code :
- `src/domain/` : règles de calcul pures et testées (centimes entiers, répartitions en points de base) :
équilibre entre personnes, flux mensuels, charges nettes, budgets, amortissement, récurrences.
- `src/server/` : accès base (Prisma), authentification, services métier (`services/`) et Server Actions (`actions/`).
- `src/app/` : pages (tableau de bord, opérations, récurrents & prévu, budgets, crédits, réglages).
- `docs/superpowers/specs/` : document de conception ; `docs/superpowers/plans/` : plan d'implémentation.
+48
View File
@@ -0,0 +1,48 @@
# Stack de production : docker compose up -d --build
services:
db:
image: mariadb:latest
restart: unless-stopped
environment:
MARIADB_DATABASE: finances
MARIADB_USER: finances
MARIADB_PASSWORD: ${MARIADB_PASSWORD:?à définir dans .env}
MARIADB_ROOT_PASSWORD: ${MARIADB_ROOT_PASSWORD:?à définir dans .env}
TZ: Europe/Paris
volumes:
- db_data:/var/lib/mysql
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 10
start_period: 20s
app:
build: .
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
DATABASE_URL: mysql://finances:${MARIADB_PASSWORD}@db:3306/finances
SESSION_SECRET: ${SESSION_SECRET:?à définir dans .env (32 caractères minimum)}
ports:
- "${APP_PORT:-3000}:3000"
backup:
image: mariadb:latest
restart: unless-stopped
depends_on:
db:
condition: service_healthy
entrypoint: ["bash", "/backup.sh"]
environment:
MARIADB_ROOT_PASSWORD: ${MARIADB_ROOT_PASSWORD}
TZ: Europe/Paris
volumes:
- ./docker/backup.sh:/backup.sh:ro
- ./backups:/backups
volumes:
db_data:
+28
View File
@@ -0,0 +1,28 @@
#!/bin/bash
# Sauvegarde quotidienne de la base (03:00, heure de Paris), rétention 30 jours.
set -u -o pipefail
dump() {
local file="/backups/finances-$(date +%F_%H%M).sql.gz"
# 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
rm -f "$file.tmp"
echo "$(date '+%F %T') ÉCHEC de la sauvegarde" >&2
fi
find /backups -name 'finances-*.sql.gz' -mtime +30 -delete
}
# Attend que la base réponde, puis une première sauvegarde au démarrage.
until mariadb-admin ping -h db -u root -p"$MARIADB_ROOT_PASSWORD" --silent; do sleep 5; done
dump
while true; do
now=$(date +%s)
next=$(date -d "tomorrow 03:00" +%s)
[ "$(date +%H)" -lt 3 ] && next=$(date -d "today 03:00" +%s)
sleep $((next - now))
dump
done
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -e
# Migrations du schéma puis catégories de départ (idempotent), puis serveur Next.js.
prisma migrate deploy --schema prisma/schema.prisma
node dist/seed.js
exec node server.js
+1
View File
@@ -23,6 +23,7 @@ const CATEGORIES: { name: string; emoji: string; kind: OpKind }[] = [
{ name: "Remboursement employeur", emoji: "🧾", kind: "INCOME" }, { name: "Remboursement employeur", emoji: "🧾", kind: "INCOME" },
{ name: "IK", emoji: "🚗", kind: "INCOME" }, { name: "IK", emoji: "🚗", kind: "INCOME" },
{ name: "Prime", emoji: "💶", kind: "INCOME" }, { name: "Prime", emoji: "💶", kind: "INCOME" },
{ name: "Dividendes", emoji: "📈", kind: "INCOME" },
{ name: "Autres revenus", emoji: "➕", kind: "INCOME" }, { name: "Autres revenus", emoji: "➕", kind: "INCOME" },
]; ];
View File
Whitespace-only changes.
+100
View File
@@ -0,0 +1,100 @@
import Link from "next/link";
import { BudgetHistoryChart } from "@/components/budgets/BudgetHistoryChart";
import { BudgetInput } from "@/components/budgets/BudgetInput";
import { Card, CardLabel } from "@/components/ui/Card";
import { MonthSwitcher } from "@/components/ui/MonthSwitcher";
import { centsFromDecimal, decimalFromCents, formatEuro } from "@/domain/money";
import { budgetForMonth, budgetStatus } from "@/domain/monthly";
import { currentMonthParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { getCategories, getOpsForMonth } from "@/server/repo";
import { budgetHistory } from "@/server/services/budgets";
export default async function BudgetsPage({ searchParams }: { searchParams: Promise<{ m?: string; cat?: string }> }) {
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 [categories, ops, rows] = await Promise.all([getCategories("EXPENSE"), getOpsForMonth(month), prisma.budget.findMany()]);
const active = budgetForMonth(rows.map((b) => ({ ...b, monthlyAmount: centsFromDecimal(b.monthlyAmount) })), month);
const amountOf = new Map(active.map((b) => [b.categoryId, b.amount]));
const status = new Map(
budgetStatus(ops, month, categories.map((c) => ({ categoryId: c.id, amount: amountOf.get(c.id) ?? 0 }))).map((s) => [s.categoryId, s]),
);
const selected = categories.find((c) => c.id === sp.cat) ?? categories.find((c) => amountOf.has(c.id)) ?? categories[0];
const history = selected ? await budgetHistory(selected.id, 6, month) : [];
const totalBudget = active.reduce((t, b) => t + b.amount, 0);
const totalActual = categories.filter((c) => amountOf.has(c.id)).reduce((t, c) => t + (status.get(c.id)?.actual ?? 0), 0);
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<MonthSwitcher month={month} basePath="/budgets" params={{ cat: sp.cat }} />
{totalBudget > 0 && (
<div className="text-[13px] text-muted">
Budgété <b className="tabular text-ink">{formatEuro(totalBudget)}</b> · dépensé{" "}
<b className={`tabular ${totalActual > totalBudget ? "text-neg" : "text-ink"}`}>{formatEuro(totalActual)}</b>
</div>
)}
</div>
<Card>
<div className="mb-2 flex items-baseline justify-between gap-3">
<CardLabel>Budgets mensuels par catégorie</CardLabel>
<span className="text-right text-xs text-muted">Un montant saisi s&apos;applique à partir de ce mois</span>
</div>
<div className="divide-y divide-line-soft">
{categories.map((c) => {
const budget = amountOf.get(c.id);
const s = status.get(c.id)!;
const over = budget !== undefined && s.over;
const pct = budget ? Math.min(100, (s.actual / budget) * 100) : 0;
return (
<div key={c.id} className="flex items-center gap-3 py-2.5">
<Link href={`/budgets?m=${month}&cat=${c.id}`} className="w-36 shrink-0 truncate font-medium hover:text-accent md:w-44">
{c.emoji} {c.name}
</Link>
<div className="hidden min-w-0 flex-1 md:block">
{budget ? (
<div className="h-2 overflow-hidden rounded-full bg-line-soft">
<div className={`h-full rounded-full ${over ? "bg-neg" : "bg-accent"}`} style={{ width: `${pct}%` }} />
</div>
) : null}
</div>
<div className="tabular min-w-0 flex-1 text-right text-[13px] md:w-56 md:flex-none">
<span className={over ? "font-semibold text-neg" : ""}>{formatEuro(s.actual)}</span>
{s.plannedRemaining > 0 && <span className="text-warn"> + {formatEuro(s.plannedRemaining)} prévus</span>}
</div>
<BudgetInput
key={`${c.id}-${month}-${budget ?? 0}`}
categoryId={c.id}
month={month}
initial={budget ? decimalFromCents(budget).replace(".", ",").replace(",00", "") : ""}
/>
</div>
);
})}
</div>
</Card>
{selected && (
<Card>
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-2">
<CardLabel>
{selected.emoji} {selected.name} · 6 derniers mois
</CardLabel>
<span className="flex items-center gap-3 text-xs text-muted">
<span className="flex items-center gap-1.5">
<span className="inline-block h-2.5 w-2.5 rounded-sm bg-accent" /> Réel
</span>
<span className="flex items-center gap-1.5">
<span className="inline-block w-4 border-t-2 border-dashed border-muted" /> Budget
</span>
</span>
</div>
<BudgetHistoryChart data={history} />
</Card>
)}
</div>
);
}
@@ -0,0 +1,47 @@
import { notFound } from "next/navigation";
import { FormPage } from "@/components/FormPage";
import { LoanForm } from "@/components/credits/LoanForm";
import { centsFromDecimal, decimalFromCents } from "@/domain/money";
import { todayParis, toIsoDate } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { splitOf } from "@/server/mappers";
import { getDefaultSplit, getUsers } from "@/server/repo";
const euro = (d: { toString(): string } | null) => (d === null ? "" : decimalFromCents(centsFromDecimal(d)).replace(".", ","));
export default async function EditLoanPage({ params }: { params: Promise<{ id: string }> }) {
const user = await requireUser();
const { id } = await params;
const [loan, users, defaultSplit] = await Promise.all([
prisma.loan.findUnique({ where: { id }, include: { splits: true } }),
getUsers(),
getDefaultSplit(),
]);
if (!loan) notFound();
return (
<FormPage title={`Modifier « ${loan.name} »`} back={`/credits/${loan.id}`}>
<LoanForm
users={users}
defaultSplit={defaultSplit}
currentUserId={user.id}
today={todayParis()}
initial={{
id: loan.id,
name: loan.name,
lender: loan.lender ?? "",
principal: euro(loan.principal),
annualRate: loan.annualRate.toString().replace(".", ","),
durationMonths: loan.durationMonths,
startDate: toIsoDate(loan.startDate),
insuranceMonthly: euro(loan.insuranceMonthly),
accountUserId: loan.accountUserId,
split: splitOf(loan.splits),
paymentOverride: euro(loan.paymentOverride),
referenceDate: loan.referenceDate ? toIsoDate(loan.referenceDate) : "",
referenceRemainingCapital: euro(loan.referenceRemainingCapital),
}}
/>
</FormPage>
);
}
+131
View File
@@ -0,0 +1,131 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Card, CardLabel } from "@/components/ui/Card";
import { buildSchedule, loanSummary } from "@/domain/loan";
import { formatEuro } from "@/domain/money";
import { formatDateFr, fromIsoDate, monthOf, todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { toOp } from "@/server/mappers";
import { toLoanInput } from "@/server/services/loans";
export default async function LoanDetailPage({ params }: { params: Promise<{ id: string }> }) {
await requireUser();
const { id } = await params;
const loan = await prisma.loan.findUnique({ where: { id }, include: { recurring: true } });
if (!loan) notFound();
const today = todayParis();
const rows = buildSchedule(toLoanInput(loan));
const s = loanSummary(rows, today);
const currentIndex = rows.findIndex((r) => r.date >= today);
const month = monthOf(today);
const allocated = loan.recurring
? (
await prisma.operation.findMany({
where: {
allocatedToRecurringId: loan.recurring.id,
status: { not: "SKIPPED" },
date: { gte: fromIsoDate(`${month}-01`) },
},
include: { splits: true },
orderBy: { date: "asc" },
})
)
.map(toOp)
.filter((o) => monthOf(o.date) === month)
: [];
const reimbursed = allocated.reduce((t, o) => t + o.amount, 0);
const tiles: [string, string][] = [
["Mensualité", formatEuro(s.payment)],
["Assurance", formatEuro(s.insurance)],
["Capital restant dû", formatEuro(s.remaining)],
["Intérêts payés", formatEuro(s.interestPaid)],
["Intérêts restants", formatEuro(s.interestLeft)],
["Fin", formatDateFr(s.endDate)],
];
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-3">
<Link href="/credits" className="grid h-[30px] w-[30px] place-items-center rounded-lg border border-line bg-white text-muted" aria-label="Retour">
‹
</Link>
<h1 className="text-xl font-bold md:text-[22px]">🏦 {loan.name}</h1>
</div>
<Link href={`/credits/${loan.id}/modifier`} className="rounded-[10px] border border-line bg-white px-4 py-2.5 font-semibold">
Modifier
</Link>
</div>
<div className="grid grid-cols-2 gap-3 md:grid-cols-6">
{tiles.map(([k, v]) => (
<Card key={k} className="p-4">
<div className="text-xs text-muted">{k}</div>
<b className="tabular mt-1 block text-base">{v}</b>
</Card>
))}
</div>
<Card>
<CardLabel className="mb-1.5">Remboursements affectés ce mois-ci</CardLabel>
{allocated.length === 0 ? (
<p className="py-2 text-muted">Aucun. Saisissez une entrée (ex. IK) et affectez-la à « {loan.name} ».</p>
) : (
<>
{allocated.map((o) => (
<div key={o.id} className="flex justify-between border-b border-line-soft py-2">
<span>
{o.label} <span className="text-muted">· {formatDateFr(o.date)}</span>
</span>
<b className="tabular text-pos">{formatEuro(o.amount, { sign: true })}</b>
</div>
))}
<div className="flex justify-between pt-2.5">
<b>Coût net ce mois-ci</b>
<b className="tabular">{formatEuro(s.payment + s.insurance - reimbursed)}</b>
</div>
</>
)}
</Card>
<Card className="overflow-x-auto p-0">
<CardLabel className="px-[18px] pt-[18px]">Échéancier</CardLabel>
<table className="tabular mt-2 w-full min-w-[560px] text-right text-[13px]">
<thead className="text-xs text-muted">
<tr className="border-b border-line">
<th className="px-3 py-2 text-left font-semibold">#</th>
<th className="px-3 py-2 text-left font-semibold">Date</th>
<th className="px-3 py-2 font-semibold">Échéance</th>
<th className="px-3 py-2 font-semibold">Intérêts</th>
<th className="px-3 py-2 font-semibold">Capital</th>
<th className="px-3 py-2 font-semibold">Assurance</th>
<th className="px-3 py-2 font-semibold">Restant dû</th>
</tr>
</thead>
<tbody>
{rows.map((r, i) => (
<tr
key={r.n}
className={`border-b border-line-soft last:border-0 ${r.beforeTracking ? "text-gray-400" : ""} ${
i === currentIndex ? "bg-accent-soft font-semibold text-accent" : ""
}`}
>
<td className="px-3 py-1.5 text-left">{r.n}</td>
<td className="px-3 py-1.5 text-left">
{formatDateFr(r.date)}
{r.beforeTracking && <span className="ml-1 text-[11px]">avant suivi</span>}
</td>
<td className="px-3 py-1.5">{formatEuro(r.payment)}</td>
<td className="px-3 py-1.5">{formatEuro(r.interest)}</td>
<td className="px-3 py-1.5">{formatEuro(r.principal)}</td>
<td className="px-3 py-1.5">{formatEuro(r.insurance)}</td>
<td className="px-3 py-1.5">{formatEuro(r.remaining)}</td>
</tr>
))}
</tbody>
</table>
</Card>
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { FormPage } from "@/components/FormPage";
import { LoanForm } from "@/components/credits/LoanForm";
import { todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { getDefaultSplit, getUsers } from "@/server/repo";
export default async function NewLoanPage() {
const user = await requireUser();
const [users, defaultSplit] = await Promise.all([getUsers(), getDefaultSplit()]);
return (
<FormPage title="Nouveau crédit" back="/credits">
<LoanForm users={users} defaultSplit={defaultSplit} currentUserId={user.id} today={todayParis()} />
</FormPage>
);
}
+104
View File
@@ -0,0 +1,104 @@
import Link from "next/link";
import { Card, CardLabel } from "@/components/ui/Card";
import { Chip } from "@/components/ui/Chip";
import { buildSchedule, loanSummary } from "@/domain/loan";
import { formatEuro } from "@/domain/money";
import { currentMonthParis, formatDateFr, todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { loadDashboard } from "@/server/dashboard";
import { prisma } from "@/server/db";
import { getUsers } from "@/server/repo";
import { toLoanInput } from "@/server/services/loans";
export default async function CreditsPage() {
const user = await requireUser();
const today = todayParis();
const [loans, users, dashboard] = await Promise.all([
prisma.loan.findMany({ orderBy: { createdAt: "asc" } }),
getUsers(),
loadDashboard(currentMonthParis(), user.id, today),
]);
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-xl font-bold md:text-[22px]">Crédits & charges</h1>
<Link href="/credits/nouveau" className="rounded-[10px] bg-accent px-4 py-2.5 font-semibold text-white hover:bg-indigo-700">
+ Crédit
</Link>
</div>
{loans.length === 0 && (
<Card>
<p className="text-muted">Aucun crédit. Ajoutez le crédit voiture, un prêt immobilier…</p>
</Card>
)}
<div className="grid gap-4 md:grid-cols-2">
{loans.map((loan) => {
const input = toLoanInput(loan);
const rows = buildSchedule(input);
const s = loanSummary(rows, today);
const repaid = input.principal > 0 ? 1 - s.remaining / input.principal : 1;
const holder = users.find((u) => u.id === loan.accountUserId);
return (
<Link key={loan.id} href={`/credits/${loan.id}`} className="block">
<Card className="h-full transition hover:border-accent/40">
<div className="flex items-start justify-between gap-3">
<div>
<b className="text-base">🏦 {loan.name}</b>
<div className="text-[13px] text-muted">{loan.lender ?? "—"}</div>
</div>
{holder && <Chip color={holder.color}>{holder.firstName}</Chip>}
</div>
<div className="mt-4 grid grid-cols-3 gap-2">
<div>
<div className="text-xs text-muted">Mensualité</div>
<b className="tabular">{formatEuro(s.payment + s.insurance)}</b>
</div>
<div>
<div className="text-xs text-muted">Restant dû</div>
<b className="tabular">{formatEuro(s.remaining)}</b>
</div>
<div>
<div className="text-xs text-muted">Fin</div>
<b>{formatDateFr(s.endDate)}</b>
</div>
</div>
<div className="mt-4 h-2 overflow-hidden rounded-full bg-line-soft">
<div className="h-full rounded-full bg-accent" style={{ width: `${Math.max(0, Math.min(100, repaid * 100))}%` }} />
</div>
<div className="mt-1 text-xs text-muted">{Math.round(repaid * 100)} % remboursé</div>
</Card>
</Link>
);
})}
</div>
<Card>
<CardLabel className="mb-1.5">Charges affectées ce mois-ci</CardLabel>
{dashboard.netCharges.length === 0 ? (
<p className="py-2 text-muted">
Aucune entrée affectée ce mois-ci. Lors de la saisie d&apos;une entrée (IK, part de loyer employeur…), utilisez « Affecter à une charge ».
</p>
) : (
dashboard.netCharges.map((c) => (
<div key={c.id} className="flex items-center justify-between border-b border-line-soft py-2.5 last:border-0">
<div>
<b>{c.label}</b>
<div className="tabular text-[13px] text-muted">
{formatEuro(c.gross)} − {formatEuro(c.reimbursed)} remboursés
</div>
</div>
<div className="text-right">
<b className="tabular">{formatEuro(c.net)}</b>
<div className="text-xs text-muted">
couvert à {c.gross > 0 ? Math.round((c.reimbursed / c.gross) * 100) : 0} %
</div>
</div>
</div>
))
)}
</Card>
</div>
);
}
+18
View File
@@ -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 (
<div className="min-h-dvh md:flex">
<Sidebar user={user} />
<main className="mx-auto w-full max-w-[1200px] flex-1 px-4 pb-28 pt-5 md:px-7 md:pb-8 md:pt-6">{children}</main>
<MobileNav />
</div>
);
}
+32
View File
@@ -0,0 +1,32 @@
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 returnPath = (r?: string) => safeReturn(r, "/");
export default async function NewOperationPage({
searchParams,
}: {
searchParams: Promise<{ type?: string; prevue?: string; retour?: string }>;
}) {
const user = await requireUser();
const sp = await searchParams;
const today = todayParis();
const data = await getFormData(today);
const returnTo = returnPath(sp.retour);
return (
<FormPage title="Nouvelle opération" back={returnTo}>
<OperationForm
{...data}
currentUserId={user.id}
today={today}
initialKind={sp.type === "entree" ? "INCOME" : "EXPENSE"}
initialPlanned={sp.prevue === "1"}
returnTo={returnTo}
/>
</FormPage>
);
}
+68
View File
@@ -0,0 +1,68 @@
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";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { toOp } from "@/server/mappers";
import { getFormData } from "@/server/repo";
const returnPath = (r?: string) => safeReturn(r, "/operations");
export default async function EditOperationPage({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
searchParams: Promise<{ retour?: string }>;
}) {
const user = await requireUser();
const { id } = await params;
const row = await prisma.operation.findUnique({ where: { id }, include: { splits: true } });
if (!row || row.status === "SKIPPED") notFound();
const op = toOp(row);
const today = todayParis();
const data = await getFormData(today);
const chargeKey = op.allocatedToRecurringId
? `r:${op.allocatedToRecurringId}`
: op.allocatedToOperationId
? `o:${op.allocatedToOperationId}`
: "";
// La dépense éditée ne peut pas être sa propre cible ; une cible hors des 3 derniers mois reste sélectionnable.
const charges = data.charges.filter((c) => c.key !== `o:${op.id}`);
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={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.
</p>
)}
<OperationForm
{...data}
charges={charges}
currentUserId={user.id}
today={today}
returnTo={returnPath((await searchParams).retour)}
initial={{
id: op.id,
kind: op.kind,
amount: formatEuro(op.amount).replace(/[^\d,]/g, ""),
label: op.label,
categoryId: op.categoryId,
date: op.date,
accountUserId: op.accountUserId,
status: op.status === "PLANNED" ? "PLANNED" : "ACTUAL",
split: op.split,
note: row.note ?? "",
chargeKey,
allocationMode: op.allocationMode,
isRecurringOccurrence: op.recurringId !== null,
}}
/>
</FormPage>
);
}
+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>
);
}
+188 -7
View File
@@ -1,12 +1,193 @@
import Link from "next/link";
import { OpList } from "@/components/OpList";
import { SettlementDialog } from "@/components/dashboard/SettlementDialog";
import { Avatar } from "@/components/ui/Avatar";
import { Card, CardLabel } from "@/components/ui/Card";
import { Chip } from "@/components/ui/Chip";
import { MonthSwitcher } from "@/components/ui/MonthSwitcher";
import { formatEuro } from "@/domain/money";
import { currentMonthParis, formatDateFr, todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth"; import { requireUser } from "@/server/auth";
import { logoutAction } from "@/server/actions/auth"; import { loadDashboard } from "@/server/dashboard";
export default async function DashboardPage() { const validMonth = (m?: string) => (m && /^\d{4}-(0[1-9]|1[0-2])$/.test(m) ? m : currentMonthParis());
const user = await requireUser();
function Row({ k, v, strong, className = "" }: { k: string; v: React.ReactNode; strong?: boolean; className?: string }) {
return ( return (
<main className="p-8"> <div className={`flex justify-between border-b border-line-soft py-[7px] last:border-0 ${strong ? "pt-2.5" : ""} ${className}`}>
<p>Bonjour {user.firstName}</p> <span className={strong ? "font-semibold" : "text-muted"}>{k}</span>
<form action={logoutAction}><button>Déconnexion</button></form> <span className="tabular font-semibold">{v}</span>
</main> </div>
); );
} }
export default async function DashboardPage({ searchParams }: { searchParams: Promise<{ m?: string }> }) {
const user = await requireUser();
const month = validMonth((await searchParams).m);
const today = todayParis();
const d = await loadDashboard(month, user.id, today);
const returnTo = `/?m=${month}`;
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<MonthSwitcher month={month} basePath="/" />
<div className="flex items-center gap-2">
{d.toConfirmCount > 0 && (
<Link href="/recurrents" className="rounded-full bg-warn-soft px-3 py-1.5 text-xs font-semibold text-warn">
{d.toConfirmCount} à confirmer
</Link>
)}
<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>
</div>
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardLabel>Entrées du foyer</CardLabel>
<div className="tabular mt-1.5 text-[28px] font-bold tracking-tight text-pos">{formatEuro(d.totals.income, { sign: true })}</div>
<div className="mt-1 text-[13px] text-muted">
{d.totals.allocatedIncome > 0
? `dont ${formatEuro(d.totals.allocatedIncome)} remboursés par l'employeur`
: d.totals.plannedIncome > 0
? `dont ${formatEuro(d.totals.plannedIncome)} prévus`
: " "}
</div>
</Card>
<Card>
<CardLabel>Sorties du foyer</CardLabel>
<div className="tabular mt-1.5 text-[28px] font-bold tracking-tight text-neg">{formatEuro(-d.totals.expense)}</div>
<div className="mt-1 text-[13px] text-muted">
{d.totals.plannedExpense > 0 ? `dont ${formatEuro(d.totals.plannedExpense)} prévus, pas encore passés` : " "}
</div>
</Card>
<Card>
<CardLabel>Reste</CardLabel>
<div className="tabular mt-1.5 text-[28px] font-bold tracking-tight">{formatEuro(d.totals.remaining, { sign: true })}</div>
<div className="mt-1 text-[13px] text-muted">après les dépenses prévues</div>
</Card>
</div>
{d.balance && (
<div className="flex flex-col gap-3 rounded-card border border-warn-line bg-warn-soft px-[18px] py-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<b className="text-base">{d.balance.text}</b>
<div className="mt-1 text-[13px] text-amber-800">
Cumul des dépenses partagées
{d.lastSettlementDate ? ` depuis le dernier remboursement (${formatDateFr(d.lastSettlementDate).slice(0, 5)})` : ""}
</div>
</div>
<SettlementDialog
users={d.users}
debtorId={d.balance.debtorId}
creditorId={d.balance.creditorId}
amount={d.balance.amount}
today={today}
/>
</div>
)}
<div className="grid gap-4 md:grid-cols-2">
{d.persons.map(({ user: u, flows }) => (
<Card key={u.id}>
<div className="mb-3.5 flex items-center gap-2.5">
<Avatar user={u} />
<b>{u.firstName}</b>
</div>
<Row k="Entrées" v={<span className="text-pos">{formatEuro(flows.income, { sign: true })}</span>} />
<Row k="Payé de sa poche" v={formatEuro(-flows.paidOut)} />
<Row k="Part réelle des charges" v={formatEuro(-flows.chargesShare)} />
<Row
k="Reste"
strong
v={<span className={flows.remaining >= 0 ? "text-pos" : "text-neg"}>{formatEuro(flows.remaining, { sign: true })}</span>}
/>
</Card>
))}
</div>
<div className={`grid gap-4 ${d.netCharges.length > 0 ? "md:grid-cols-2" : ""}`}>
<Card>
<CardLabel className="mb-3.5">Budgets du mois</CardLabel>
{d.budgets.length === 0 ? (
<p className="text-muted">
Aucun budget défini.{" "}
<Link href="/budgets" className="font-semibold text-accent">
Définir des budgets
</Link>
</p>
) : (
<div className="space-y-3.5">
{d.budgets.map((b) => (
<div key={b.categoryId}>
<div className="flex justify-between font-medium">
<span>
{b.emoji} {b.name}
</span>
<span className={`tabular ${b.over ? "text-neg" : "text-muted"}`}>
{formatEuro(b.actual)} / {formatEuro(b.budget)}
</span>
</div>
<div className="mt-1.5 h-2 overflow-hidden rounded-full bg-line-soft">
<div
className={`h-full rounded-full ${b.over ? "bg-neg" : "bg-accent"}`}
style={{ width: `${Math.min(100, b.budget ? (b.actual / b.budget) * 100 : 100)}%` }}
/>
</div>
</div>
))}
</div>
)}
</Card>
{d.netCharges.length > 0 && (
<Card>
<CardLabel className="mb-1.5">Charges nettes</CardLabel>
{d.netCharges.map((c) => {
const full = d.users.find((u) => c.split[u.id] === 10000);
return (
<div key={c.id} className="flex items-center justify-between border-b border-line-soft py-2.5 last:border-0">
<div>
<b>{c.label}</b>
<div className="tabular mt-0.5 text-[13px] text-muted">
{formatEuro(c.gross)} − {formatEuro(c.reimbursed)} remboursés
</div>
</div>
<div className="text-right">
<b className="tabular">{formatEuro(c.net)}</b>
<div>
{full ? (
<Chip color={full.color}>{full.firstName} 100 %</Chip>
) : (
<Chip tone="split">{d.users.map((u) => formatEuro(Math.round((c.net * (c.split[u.id] ?? 0)) / 10000))).join(" / ")}</Chip>
)}
</div>
</div>
</div>
);
})}
</Card>
)}
</div>
<Card>
<div className="mb-1.5 flex items-center justify-between">
<CardLabel>Dernières opérations</CardLabel>
<Link href={`/operations?m=${month}`} className="text-[13px] font-semibold text-accent">
Tout voir
</Link>
</div>
{d.recent.length === 0 ? (
<p className="py-4 text-muted">Aucune opération ce mois-ci.</p>
) : (
<OpList ops={d.recent} ctx={d} returnTo={returnTo} />
)}
</Card>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
import { notFound, redirect } from "next/navigation";
import { FormPage } from "@/components/FormPage";
import { RecurringForm } from "@/components/recurrents/RecurringForm";
import { decimalFromCents } from "@/domain/money";
import { todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { getFormData, getRecurringDefs } from "@/server/repo";
export default async function EditRecurringPage({ params }: { params: Promise<{ id: string }> }) {
const user = await requireUser();
const { id } = await params;
const today = todayParis();
const [data, defs, row] = await Promise.all([
getFormData(today),
getRecurringDefs(),
prisma.recurring.findUnique({ where: { id }, select: { loanId: true } }),
]);
const def = defs.find((d) => d.id === id);
if (!def || !row) notFound();
if (row.loanId) redirect(`/credits/${row.loanId}`);
const targets = defs.filter((d) => d.kind === "EXPENSE").map((d) => ({ id: d.id, label: d.label, split: d.split }));
return (
<FormPage title="Modifier le récurrent" back="/recurrents">
<p className="mb-4 rounded-[10px] bg-accent-soft px-3 py-2 text-[13px] text-accent">
Les changements s&apos;appliquent aux prochaines échéances. Les opérations déjà passées ne bougent pas.
</p>
<RecurringForm
{...data}
targets={targets}
currentUserId={user.id}
today={today}
initial={{ ...def, amount: decimalFromCents(def.amount).replace(".", ",") }}
/>
</FormPage>
);
}
+17
View File
@@ -0,0 +1,17 @@
import { FormPage } from "@/components/FormPage";
import { RecurringForm } from "@/components/recurrents/RecurringForm";
import { todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { getFormData, getRecurringDefs } from "@/server/repo";
export default async function NewRecurringPage() {
const user = await requireUser();
const today = todayParis();
const [data, defs] = await Promise.all([getFormData(today), getRecurringDefs()]);
const targets = defs.filter((d) => d.kind === "EXPENSE").map((d) => ({ id: d.id, label: d.label, split: d.split }));
return (
<FormPage title="Nouveau récurrent" back="/recurrents">
<RecurringForm {...data} targets={targets} currentUserId={user.id} today={today} />
</FormPage>
);
}
+145
View File
@@ -0,0 +1,145 @@
import Link from "next/link";
import { OpList } from "@/components/OpList";
import { RecurringActions } from "@/components/recurrents/RecurringActions";
import { ToConfirmRow } from "@/components/recurrents/ToConfirmRow";
import { Amount } from "@/components/ui/Amount";
import { Card, CardLabel } from "@/components/ui/Card";
import { Chip } from "@/components/ui/Chip";
import { bpToPercentLabel } from "@/domain/money";
import { occurrenceDates } from "@/domain/recurrence";
import { addMonths, formatDateFr, fromIsoDate, monthOf, todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { toOp } from "@/server/mappers";
import { getCategories, getRecurringDefs, getUsers } from "@/server/repo";
const FREQ = { MONTHLY: "Mensuel", QUARTERLY: "Trimestriel", YEARLY: "Annuel" } as const;
export default async function RecurrentsPage() {
await requireUser();
const today = todayParis();
const in60 = new Date(fromIsoDate(today).getTime() + 60 * 86400000);
const [users, categories, defs, loanRecurrings, plannedRows] = await Promise.all([
getUsers(),
getCategories(undefined, true),
getRecurringDefs(),
prisma.recurring.findMany({ where: { loanId: { not: null } }, select: { id: true } }),
prisma.operation.findMany({
where: { status: "PLANNED", date: { lte: in60 } },
include: { splits: true },
orderBy: { date: "asc" },
}),
]);
const planned = plannedRows.map(toOp);
const toConfirm = planned.filter((o) => o.date <= today);
const upcoming = planned.filter((o) => o.date > today);
const cat = Object.fromEntries(categories.map((c) => [c.id, { name: c.name, emoji: c.emoji }]));
const person = (id: string) => users.find((u) => u.id === id);
const fromLoan = new Set(loanRecurrings.map((l) => l.id));
const labels = Object.fromEntries(defs.map((d) => [d.id, d.label]));
const ctx = { users, categories: cat, chargeLabels: labels };
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-xl font-bold md:text-[22px]">Récurrents & prévu</h1>
<div className="flex gap-2">
<Link href="/nouvelle?prevue=1&retour=%2Frecurrents" className="rounded-[10px] border border-line bg-white px-4 py-2.5 font-semibold">
+ Dépense prévue
</Link>
<Link href="/recurrents/nouveau" className="rounded-[10px] bg-accent px-4 py-2.5 font-semibold text-white hover:bg-indigo-700">
+ Récurrent
</Link>
</div>
</div>
<Card className={toConfirm.length ? "border-warn-line" : ""}>
<CardLabel className="mb-1 flex items-center gap-2">
À confirmer {toConfirm.length > 0 && <Chip tone="planned">{toConfirm.length}</Chip>}
</CardLabel>
{toConfirm.length === 0 ? (
<p className="py-2 text-muted">Rien à confirmer, tout est à jour ✓</p>
) : (
toConfirm.map((o) => (
<ToConfirmRow
key={o.id}
op={{
id: o.id,
label: o.label,
emoji: cat[o.categoryId]?.emoji ?? "",
amount: o.amount,
date: o.date,
kind: o.kind,
who: person(o.accountUserId)?.firstName ?? "?",
}}
/>
))
)}
</Card>
<Card>
<CardLabel className="mb-1">À venir (60 jours)</CardLabel>
{upcoming.length === 0 ? (
<p className="py-2 text-muted">Aucune opération prévue.</p>
) : (
<OpList ops={upcoming} ctx={ctx} returnTo="/recurrents" />
)}
</Card>
<div>
<CardLabel className="mb-2 px-1">Modèles récurrents</CardLabel>
{defs.length === 0 && (
<Card>
<p className="text-muted">Aucun récurrent. Ajoutez le loyer, les salaires, les abonnements…</p>
</Card>
)}
<div className="grid gap-3 md:grid-cols-2">
{defs.map((d) => {
const next = occurrenceDates(d, monthOf(today), addMonths(monthOf(today), 12)).find((x) => x >= today);
const account = person(d.accountUserId);
const full = users.find((u) => d.split[u.id] === 10000);
let status = next ? ` · prochaine le ${formatDateFr(next)}` : " · terminé";
if (d.paused) status = " · en pause";
return (
<Card key={d.id} className={d.paused ? "opacity-60" : ""}>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<b className="block truncate">
{cat[d.categoryId]?.emoji} {d.label}
</b>
<div className="text-[13px] text-muted">
{FREQ[d.frequency]} · le {d.dayOfMonth}
{status}
</div>
</div>
<Amount cents={d.amount} kind={d.kind} />
</div>
<div className="mt-2 flex flex-wrap gap-1">
{account && (
<Chip color={account.color}>
{d.kind === "EXPENSE" ? "payé par" : "reçu par"} {account.firstName}
</Chip>
)}
{d.kind === "EXPENSE" && !full && (
<Chip tone="split">{users.map((u) => bpToPercentLabel(d.split[u.id] ?? 0)).join("/")}</Chip>
)}
{d.kind === "EXPENSE" && full && full.id !== d.accountUserId && <Chip color={full.color}>pour {full.firstName}</Chip>}
{d.allocatedToRecurringId && <Chip tone="link">↳ {labels[d.allocatedToRecurringId]}</Chip>}
</div>
<div className="mt-3 border-t border-line-soft pt-2">
{fromLoan.has(d.id) ? (
<Link href="/credits" className="text-[13px] font-semibold text-muted">
Géré depuis Crédits →
</Link>
) : (
<RecurringActions id={d.id} paused={d.paused} today={today} />
)}
</div>
</Card>
);
})}
</div>
</div>
</div>
);
}
+62
View File
@@ -0,0 +1,62 @@
import { SettlementsCard } from "@/components/settings/SettlementsCard";
import { CategoriesCard, DefaultSplitCard, PersonCard } from "@/components/settings/SettingsForms";
import { Card, CardLabel } from "@/components/ui/Card";
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, 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 (
<div className="space-y-4">
<h1 className="text-xl font-bold md:text-[22px]">Réglages</h1>
<div className="grid gap-4 md:grid-cols-2">
{users.map((u) => (
<PersonCard key={u.id} user={u} isMe={u.id === me.id} />
))}
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-4">
<DefaultSplitCard users={users} split={defaultSplit} />
<Card className="space-y-3">
<CardLabel>Export CSV</CardLabel>
<p className="text-[13px] text-muted">Toutes les opérations de la période, au format Excel (séparateur « ; »).</p>
<form action="/api/export" method="get" className="flex flex-wrap items-end gap-2">
<label className="block">
<span className="mb-1.5 block text-xs font-semibold text-muted">Du mois</span>
<input type="month" name="from" defaultValue={addMonths(month, -11)} className="rounded-[10px] border border-line px-3 py-2" />
</label>
<label className="block">
<span className="mb-1.5 block text-xs font-semibold text-muted">Au mois</span>
<input type="month" name="to" defaultValue={month} className="rounded-[10px] border border-line px-3 py-2" />
</label>
<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>
</div>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { NextResponse, type NextRequest } from "next/server";
import { addMonths, currentMonthParis, fromIsoDate } from "@/lib/dates";
import { getSession } from "@/server/auth";
import { opsToCsv } from "@/server/csv";
import { prisma } from "@/server/db";
import { toOp } from "@/server/mappers";
import { getCategories, getUsers } from "@/server/repo";
const MONTH = /^\d{4}-(0[1-9]|1[0-2])$/;
export async function GET(req: NextRequest) {
const session = await getSession();
if (!session.userId || !(await prisma.user.findUnique({ where: { id: session.userId } }))) {
return NextResponse.json({ error: "Non connecté" }, { status: 401 });
}
const now = currentMonthParis();
let from = req.nextUrl.searchParams.get("from") ?? now;
let to = req.nextUrl.searchParams.get("to") ?? now;
if (!MONTH.test(from) || !MONTH.test(to)) return NextResponse.json({ error: "Mois invalide" }, { status: 400 });
if (from > to) [from, to] = [to, from];
const [rows, users, categories, recurrings] = await Promise.all([
prisma.operation.findMany({
where: { date: { gte: fromIsoDate(`${from}-01`), lt: fromIsoDate(`${addMonths(to, 1)}-01`) } },
include: { splits: true },
orderBy: [{ date: "asc" }, { createdAt: "asc" }],
}),
getUsers(),
getCategories(undefined, true),
prisma.recurring.findMany({ select: { id: true, label: true } }),
]);
const ops = rows.map((r) => ({ ...toOp(r), note: r.note }));
const chargeLabels = Object.fromEntries([...recurrings.map((r) => [r.id, r.label]), ...rows.map((r) => [r.id, r.label])]);
const csv = opsToCsv(ops, users, Object.fromEntries(categories.map((c) => [c.id, { name: c.name }])), chargeLabels);
return new NextResponse(csv, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": `attachment; filename="finances-${from}_${to}.csv"`,
},
});
}
+115
View File
@@ -0,0 +1,115 @@
"use client";
import { useEffect, useState } from "react";
import { bpToPercentLabel, formatEuro, parseEuro, percentToBp, shareAmounts, splitFromAmounts, validateSplit } from "@/domain/money";
import type { Cents, Split } from "@/domain/types";
import { Input } from "./ui/Field";
import { Pills } from "./ui/Pills";
type Unit = "pct" | "eur";
/** "600.50" → "600,50", "600.00" → "600" : valeur lisible pour un champ montant. */
const euroText = (c: Cents) => (c % 100 === 0 ? String(c / 100) : `${Math.floor(c / 100)},${String(c % 100).padStart(2, "0")}`);
/** Champ vide ou zéro → 0 ; montant valide → centimes ; sinon -1. */
const centsOrZero = (t: string): Cents => (/^[\s0.,€]*$/.test(t) ? 0 : (parseEuro(t) ?? -1));
/**
* Répartition libre, saisie en pourcentages ou en euros (quand le montant est connu).
* Avec deux personnes, la part de l'autre se complète toute seule.
*/
export function CustomSplitFields({
users,
total,
initial,
onChange,
}: {
users: { id: string; firstName: string }[];
/** undefined : pas de montant dans ce formulaire (saisie en % seulement) ; null : montant pas encore valide. */
total?: Cents | null;
initial: Split;
onChange: (s: Split) => void;
}) {
const ids = users.map((u) => u.id);
const [unit, setUnit] = useState<Unit>("pct");
const [texts, setTexts] = useState<Record<string, string>>(() =>
Object.fromEntries(ids.map((id) => [id, bpToPercentLabel(initial[id] ?? 0)])),
);
const compute = (u: Unit, t: Record<string, string>): Split => {
if (u === "pct") return Object.fromEntries(ids.map((id) => [id, percentToBp(t[id] ?? "") ?? -1]));
const parts = Object.fromEntries(ids.map((id) => [id, centsOrZero(t[id] ?? "")]));
if (Object.values(parts).some((c) => c < 0)) return Object.fromEntries(ids.map((id) => [id, -1]));
// Somme ≠ montant : tout à 0 pour que l'enregistrement refuse (« doit totaliser 100 % »).
return (total != null && splitFromAmounts(parts, total)) || Object.fromEntries(ids.map((id) => [id, 0]));
};
// En euros, la répartition dépend du montant : on la recalcule quand il change.
useEffect(() => {
if (unit === "eur") onChange(compute(unit, texts));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [total]);
const edit = (id: string, text: string) => {
const next = { ...texts, [id]: text };
const other = ids.length === 2 ? ids.find((i) => i !== id)! : null;
if (other && unit === "pct") {
const bp = percentToBp(text);
if (bp !== null) next[other] = bpToPercentLabel(10000 - bp);
} else if (other && total != null) {
const c = centsOrZero(text);
if (c >= 0 && c <= total) next[other] = euroText(total - c);
}
setTexts(next);
onChange(compute(unit, next));
};
const switchUnit = (u: Unit) => {
if (u === unit) return;
const current = compute(unit, texts);
const valid = validateSplit(current) === null;
const next = Object.fromEntries(
ids.map((id) => {
if (!valid || (u === "eur" && total == null)) return [id, ""];
if (u === "pct") return [id, bpToPercentLabel(current[id] ?? 0)];
return [id, euroText(shareAmounts(total!, current, ids[0])[id] ?? 0)];
}),
);
setUnit(u);
setTexts(next);
onChange(compute(u, next));
};
const split = compute(unit, texts);
const pctTotal = Object.values(split).reduce((t, v) => t + Math.max(v, 0), 0);
const eurTotal = ids.reduce((t, id) => t + Math.max(centsOrZero(texts[id] ?? ""), 0), 0);
const ok = unit === "pct" ? pctTotal === 10000 : total != null && eurTotal === total;
return (
<div className="space-y-3 rounded-[10px] border border-line p-3">
{total !== undefined && (
<Pills
options={[
{ value: "pct" as Unit, label: "En %" },
{ value: "eur" as Unit, label: "En €" },
]}
value={unit}
onChange={switchUnit}
/>
)}
<div className="flex flex-wrap items-center gap-3">
{users.map((u) => (
<label key={u.id} className="flex items-center gap-2">
<span className="font-medium">{u.firstName}</span>
<Input inputMode="decimal" className="w-24" value={texts[u.id] ?? ""} onChange={(e) => edit(u.id, e.target.value)} />
{unit === "pct" ? "%" : "€"}
{unit === "eur" && ok && <span className="text-xs text-muted">{bpToPercentLabel(split[u.id] ?? 0)} %</span>}
</label>
))}
<span className={`text-xs font-semibold ${ok ? "text-pos" : "text-neg"}`}>
{unit === "pct" ? `Total ${bpToPercentLabel(pctTotal)} %` : `Total ${formatEuro(eurTotal)} sur ${total == null ? "—" : formatEuro(total)}`}
</span>
</div>
</div>
);
}
+18
View File
@@ -0,0 +1,18 @@
import Link from "next/link";
import type { ReactNode } from "react";
import { Card } from "./ui/Card";
/** Page de formulaire : plein écran sur mobile, carte centrée sur ordinateur. */
export function FormPage({ title, back, children }: { title: string; back: string; children: ReactNode }) {
return (
<div className="mx-auto max-w-lg">
<div className="mb-4 flex items-center gap-3">
<Link href={back} className="grid h-[30px] w-[30px] place-items-center rounded-lg border border-line bg-white text-muted" aria-label="Retour">
‹
</Link>
<h1 className="text-lg font-bold">{title}</h1>
</div>
<Card className="p-5">{children}</Card>
</div>
);
}
+56
View File
@@ -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 && (
<div className="fixed inset-0 z-30 bg-black/20 md:hidden" onClick={() => setMore(false)}>
<div className="absolute bottom-[72px] right-3 w-56 rounded-card border border-line bg-white p-2 shadow-lg">
{[
["/budgets", "◔ Budgets"],
["/credits", "⌂ Crédits & charges"],
["/reglages", "⚙ Réglages"],
].map(([href, label]) => (
<Link key={href} href={href} className="block rounded-lg px-3 py-2.5 font-medium hover:bg-page">
{label}
</Link>
))}
<span className="block px-3 py-2.5 text-gray-400">∿ Simulateur (bientôt)</span>
<form action={logoutAction}>
<button className="w-full rounded-lg px-3 py-2.5 text-left font-medium text-neg hover:bg-neg-soft">Déconnexion</button>
</form>
</div>
</div>
)}
<nav className="fixed inset-x-0 bottom-0 z-40 flex items-end border-t border-line bg-white pb-[env(safe-area-inset-bottom)] md:hidden">
<Link href="/" className={`${tab} ${color("/")}`}>
<span className="text-lg">◧</span>Accueil
</Link>
<Link href="/operations" className={`${tab} ${color("/operations")}`}>
<span className="text-lg">≡</span>Opérations
</Link>
<Link href="/nouvelle" className="flex flex-1 justify-center py-1.5" aria-label="Nouvelle opération">
<span className="grid h-12 w-12 place-items-center rounded-full bg-accent text-2xl text-white shadow-md">+</span>
</Link>
<Link href="/recurrents" className={`${tab} ${color("/recurrents")}`}>
<span className="text-lg">↻</span>Récurrents
</Link>
<button type="button" onClick={() => setMore((v) => !v)} className={`${tab} text-muted`}>
<span className="text-lg">⋯</span>Plus
</button>
</nav>
</>
);
}
+74
View File
@@ -0,0 +1,74 @@
import Link from "next/link";
import { bpToPercentLabel } from "@/domain/money";
import type { Op } from "@/domain/types";
import { formatDateFr } from "@/lib/dates";
import { Amount } from "./ui/Amount";
import { Chip } from "./ui/Chip";
export interface OpListContext {
users: { id: string; firstName: string; color: string }[];
categories: Record<string, { name: string; emoji: string }>;
chargeLabels: Record<string, string>;
}
function splitLabel(op: Op, users: OpListContext["users"]) {
const full = users.find((u) => op.split[u.id] === 10000);
if (full) return null;
return users.map((u) => bpToPercentLabel(op.split[u.id] ?? 0)).join("/");
}
function Chips({ op, ctx }: { op: Op; ctx: OpListContext }) {
const account = ctx.users.find((u) => u.id === op.accountUserId);
const fullUser = ctx.users.find((u) => op.split[u.id] === 10000);
const split = splitLabel(op, ctx.users);
const target = op.allocatedToRecurringId ?? op.allocatedToOperationId;
return (
<div className="flex flex-wrap gap-1">
{op.status === "PLANNED" && <Chip tone="planned">prévue</Chip>}
{account && (
<Chip color={account.color}>
{op.kind === "EXPENSE" ? "payé par" : "reçu par"} {account.firstName}
</Chip>
)}
{split && <Chip tone="split">{split}</Chip>}
{!split && fullUser && fullUser.id !== op.accountUserId && <Chip color={fullUser.color}>pour {fullUser.firstName}</Chip>}
{target && <Chip tone="link">↳ {ctx.chargeLabels[target] ?? "charge"}</Chip>}
</div>
);
}
/** Liste d'opérations : tableau sur ordinateur, cartes sur mobile. Chaque ligne ouvre l'édition. */
export function OpList({ ops, ctx, returnTo }: { ops: Op[]; ctx: OpListContext; returnTo: string }) {
const href = (op: Op) => `/operations/${op.id}?retour=${encodeURIComponent(returnTo)}`;
return (
<div className="divide-y divide-line-soft">
{ops.map((op) => {
const cat = ctx.categories[op.categoryId];
return (
<Link
key={op.id}
href={href(op)}
className={`flex items-center gap-3 py-2.5 hover:bg-page/60 ${op.status === "PLANNED" ? "opacity-65" : ""}`}
>
<span className="hidden w-12 shrink-0 text-muted md:block">{formatDateFr(op.date).slice(0, 5)}</span>
<span className="grid h-[30px] w-[30px] shrink-0 place-items-center rounded-lg bg-gray-100 text-[15px]">{cat?.emoji}</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold">{op.label}</span>
<span className="block text-[13px] text-muted">
<span className="md:hidden">{formatDateFr(op.date).slice(0, 5)} · </span>
{cat?.name}
</span>
<span className="mt-1 block md:hidden">
<Chips op={op} ctx={ctx} />
</span>
</span>
<span className="hidden md:block">
<Chips op={op} ctx={ctx} />
</span>
<Amount cents={op.amount} kind={op.kind} className="w-28 shrink-0 text-right" />
</Link>
);
})}
</div>
);
}
+372
View File
@@ -0,0 +1,372 @@
"use client";
import { useRouter } from "next/navigation";
import { useMemo, useState, useTransition } from "react";
import { bpToPercentLabel, formatEuro, fullSplit, parseEuro, validateSplit } from "@/domain/money";
import type { AllocationMode, Frequency, OpKind, Split } from "@/domain/types";
import { deleteOperationAction, saveOperationAction } from "@/server/actions/operations";
import { CustomSplitFields } from "./CustomSplitFields";
import { Button } from "./ui/Button";
import { Field, FormError, Input, Select, Textarea } from "./ui/Field";
import { Pills } from "./ui/Pills";
export interface FormUser {
id: string;
firstName: string;
color: string;
}
export interface FormCategory {
id: string;
name: string;
emoji: string;
kind: OpKind;
}
export interface ChargeOption {
/** "r:<recurringId>" ou "o:<operationId>" */
key: string;
label: string;
split: Split;
}
export interface OperationInitial {
id: string;
kind: OpKind;
amount: string;
label: string;
categoryId: string;
date: string;
accountUserId: string;
status: "PLANNED" | "ACTUAL";
split: Split;
note: string;
chargeKey: string;
allocationMode: AllocationMode | null;
isRecurringOccurrence: boolean;
}
type SplitChoice = "default" | `full:${string}` | "custom";
const sameSplit = (a: Split, b: Split) => Object.keys({ ...a, ...b }).every((k) => (a[k] ?? 0) === (b[k] ?? 0));
export function OperationForm({
users,
categories,
defaultSplit,
currentUserId,
today,
charges,
initial,
initialKind = "EXPENSE",
initialPlanned = false,
returnTo = "/",
}: {
users: FormUser[];
categories: FormCategory[];
defaultSplit: Split;
currentUserId: string;
today: string;
charges: ChargeOption[];
initial?: OperationInitial;
initialKind?: OpKind;
initialPlanned?: boolean;
returnTo?: string;
}) {
const router = useRouter();
const userIds = users.map((u) => u.id);
const [pending, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
const [kind, setKind] = useState<OpKind>(initial?.kind ?? initialKind);
const [amount, setAmount] = useState(initial?.amount ?? "");
const [label, setLabel] = useState(initial?.label ?? "");
const [categoryId, setCategoryId] = useState(initial?.categoryId ?? "");
const [date, setDate] = useState(initial?.date ?? today);
const [accountUserId, setAccountUserId] = useState(initial?.accountUserId ?? currentUserId);
const [planned, setPlanned] = useState(initial ? initial.status === "PLANNED" : initialPlanned);
const [note, setNote] = useState(initial?.note ?? "");
const [chargeKey, setChargeKey] = useState(initial?.chargeKey ?? "");
const [allocationMode, setAllocationMode] = useState<AllocationMode>(initial?.allocationMode ?? "REDUCE_SHARED");
const [recurring, setRecurring] = useState(false);
const [spread, setSpread] = useState(false);
const [frequency, setFrequency] = useState<Frequency>("MONTHLY");
const [endDate, setEndDate] = useState("");
const [showMore, setShowMore] = useState(
Boolean(initial && (initial.status === "PLANNED" || initial.note || initial.chargeKey)) || initialPlanned,
);
const initialChoice = (): SplitChoice => {
if (!initial) return kind === "INCOME" ? `full:${accountUserId}` : "default";
if (sameSplit(initial.split, defaultSplit)) return "default";
const full = userIds.find((id) => initial.split[id] === 10000);
return full ? `full:${full}` : "custom";
};
const [choice, setChoice] = useState<SplitChoice>(initialChoice);
const [customSplit, setCustomSplit] = useState<Split>(initial?.split ?? defaultSplit);
const charge = charges.find((c) => c.key === chargeKey) ?? null;
const allocated = kind === "INCOME" && charge !== null;
// La répartition effective découle du choix (ou du mode d'affectation pour une entrée affectée).
const split: Split = useMemo(() => {
if (allocated) {
if (allocationMode === "REDUCE_SHARED") return charge!.split;
if (allocationMode === "BENEFICIARY_ONLY") return fullSplit(accountUserId, userIds);
return customSplit;
}
if (choice === "default") return defaultSplit;
if (choice === "custom") return customSplit;
return fullSplit(choice.slice(5), userIds);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [allocated, allocationMode, charge, accountUserId, choice, customSplit, defaultSplit]);
const changeKind = (k: OpKind) => {
setKind(k);
setCategoryId("");
if (choice !== "custom") setChoice(k === "INCOME" ? `full:${accountUserId}` : "default");
if (k === "EXPENSE") setChargeKey("");
};
const changeAccount = (id: string) => {
setAccountUserId(id);
if (kind === "INCOME" && choice.startsWith("full:")) setChoice(`full:${id}`);
};
const defaultLabel = userIds.map((id) => bpToPercentLabel(defaultSplit[id] ?? 0)).join(" / ");
const splitOptions = [
{ value: "default" as SplitChoice, label: defaultLabel },
...users.map((u) => ({ value: `full:${u.id}` as SplitChoice, label: `100 % ${u.firstName}` })),
{ value: "custom" as SplitChoice, label: "Perso…" },
];
const kindCategories = categories.filter((c) => c.kind === kind);
const showCustom = allocated ? allocationMode === "CUSTOM" : choice === "custom";
const submit = () => {
setError(null);
const splitError = validateSplit(split);
if (splitError) return setError(splitError);
startTransition(async () => {
const result = await saveOperationAction({
id: initial?.id,
kind,
amount,
label,
categoryId,
date,
accountUserId,
status: planned ? "PLANNED" : "ACTUAL",
split,
note,
allocatedToRecurringId: allocated && chargeKey.startsWith("r:") ? chargeKey.slice(2) : null,
allocatedToOperationId: allocated && chargeKey.startsWith("o:") ? chargeKey.slice(2) : null,
allocationMode: allocated ? allocationMode : null,
makeRecurring: !initial && recurring ? { frequency, endDate: endDate || null } : undefined,
spreadOverYear: !initial && spread,
});
if (!result.ok) return setError(result.error);
router.push(returnTo);
});
};
const remove = () => {
if (!initial || !confirm("Supprimer cette opération ?")) return;
startTransition(async () => {
await deleteOperationAction(initial.id);
router.push(returnTo);
});
};
return (
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<div className="flex rounded-[10px] bg-gray-100 p-1">
{(["EXPENSE", "INCOME"] as const).map((k) => (
<button
key={k}
type="button"
onClick={() => changeKind(k)}
className={`flex-1 rounded-lg py-2 font-semibold transition ${
kind === k ? `bg-white shadow-sm ${k === "EXPENSE" ? "text-neg" : "text-pos"}` : "text-muted"
}`}
>
{k === "EXPENSE" ? "Dépense" : "Entrée"}
</button>
))}
</div>
<div className="flex items-baseline justify-center gap-1 py-1">
<input
aria-label="Montant"
inputMode="decimal"
placeholder="0,00"
value={amount}
onChange={(e) => setAmount(e.target.value)}
autoFocus={!initial}
style={{ width: `${Math.max(amount.length, 4) + 0.5}ch` }}
className="max-w-full bg-transparent text-right text-4xl font-bold tracking-tight outline-none placeholder:text-gray-300"
/>
<span className="text-xl text-muted">€</span>
</div>
<Input aria-label="Libellé" placeholder="Libellé (ex. Carrefour)" value={label} onChange={(e) => setLabel(e.target.value)} />
<div>
<div className="mb-2 text-xs font-semibold text-muted">Catégorie</div>
<div className="flex flex-wrap gap-1.5">
{kindCategories.map((c) => (
<button
key={c.id}
type="button"
onClick={() => setCategoryId(c.id)}
className={`rounded-full border px-3 py-1.5 text-[13px] font-medium transition-colors ${
categoryId === c.id ? "border-accent bg-accent text-white" : "border-line bg-white hover:border-gray-300"
}`}
>
{c.emoji} {c.name}
</button>
))}
</div>
</div>
<div>
<div className="mb-2 text-xs font-semibold text-muted">{kind === "EXPENSE" ? "Payé par" : "Reçu par"}</div>
<Pills
options={users.map((u) => ({ value: u.id, label: u.firstName }))}
value={accountUserId}
onChange={changeAccount}
/>
</div>
{!allocated && (
<div>
<div className="mb-2 text-xs font-semibold text-muted">Répartition</div>
<Pills options={splitOptions} value={choice} onChange={setChoice} />
</div>
)}
{showCustom && (
<CustomSplitFields users={users} total={parseEuro(amount)} initial={customSplit} onChange={setCustomSplit} />
)}
<Field label="Date">
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} required />
</Field>
<button type="button" onClick={() => setShowMore((v) => !v)} className="text-[13px] font-semibold text-accent">
{showMore ? "− Moins d'options" : "+ Récurrent, annuel lissé, prévue, affecter à une charge"}
</button>
{showMore && (
<div className="space-y-4 rounded-card border border-line p-4">
<label className="flex items-center gap-2 font-medium">
<input type="checkbox" checked={planned} onChange={(e) => setPlanned(e.target.checked)} className="h-4 w-4 accent-accent" />
Prévue (pas encore passée)
</label>
{!initial && (
<div className="space-y-3">
<label className="flex items-center gap-2 font-medium">
<input
type="checkbox"
checked={spread}
onChange={(e) => {
setSpread(e.target.checked);
if (e.target.checked) setRecurring(false);
}}
className="h-4 w-4 accent-accent"
/>
Montant annuel : lisser sur 12 mois
</label>
{spread && (
<p className="-mt-1 text-[13px] text-muted">
{(() => {
const cents = parseEuro(amount);
return cents && cents >= 12
? `12 entrées de ${formatEuro(Math.floor(cents / 12))} par mois à partir de la date choisie, comme un revenu mensuel.`
: "Saisissez le montant de l'année : il sera réparti en 12 mois à partir de la date choisie.";
})()}
</p>
)}
<label className="flex items-center gap-2 font-medium">
<input
type="checkbox"
checked={recurring}
onChange={(e) => {
setRecurring(e.target.checked);
if (e.target.checked) setSpread(false);
}}
className="h-4 w-4 accent-accent"
/>
Rendre récurrent
</label>
{recurring && (
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Fréquence">
<Select value={frequency} onChange={(e) => setFrequency(e.target.value as Frequency)}>
<option value="MONTHLY">Mensuelle</option>
<option value="QUARTERLY">Trimestrielle</option>
<option value="YEARLY">Annuelle</option>
</Select>
</Field>
<Field label="Jusqu'au (facultatif)">
<Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
</Field>
</div>
)}
</div>
)}
{kind === "INCOME" && (
<div className="space-y-3">
<Field label="Affecter à une charge" hint="Ex. IK → crédit voiture, part loyer employeur → loyer">
<Select value={chargeKey} onChange={(e) => setChargeKey(e.target.value)}>
<option value="">Aucune</option>
{charges.map((c) => (
<option key={c.key} value={c.key}>
{c.label}
</option>
))}
</Select>
</Field>
{allocated && (
<Pills
options={[
{ value: "REDUCE_SHARED" as AllocationMode, label: "Réduit la charge pour tous" },
{ value: "BENEFICIARY_ONLY" as AllocationMode, label: "Profite au bénéficiaire" },
{ value: "CUSTOM" as AllocationMode, label: "Perso" },
]}
value={allocationMode}
onChange={setAllocationMode}
/>
)}
</div>
)}
<Field label="Note">
<Textarea rows={2} value={note} onChange={(e) => setNote(e.target.value)} />
</Field>
</div>
)}
<FormError message={error} />
<div className="flex gap-3">
{initial && (
<Button type="button" variant="danger" onClick={remove} disabled={pending}>
Supprimer
</Button>
)}
<Button type="submit" className="flex-1 py-3" disabled={pending}>
{pending ? "Enregistrement…" : "Enregistrer"}
</Button>
</div>
</form>
);
}
+60
View File
@@ -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 (
<aside className="sticky top-0 hidden h-dvh w-[210px] shrink-0 flex-col border-r border-line bg-white px-3.5 py-[22px] md:flex">
<div className="mb-[26px] px-2">
<Logo />
</div>
<nav className="space-y-0.5">
{NAV.map((n) =>
n.soon ? (
<span key={n.href} className={`${item} cursor-default text-gray-400`}>
<span className="w-[18px] text-center">{n.icon}</span>
{n.label}
<span className="ml-auto">
<Chip tone="planned">bientôt</Chip>
</span>
</span>
) : (
<Link
key={n.href}
href={n.href}
className={`${item} ${isActive(pathname, n.href) ? "bg-accent-soft text-accent" : "text-muted hover:text-ink"}`}
>
<span className="w-[18px] text-center">{n.icon}</span>
{n.label}
</Link>
),
)}
<Link
href="/reglages"
className={`${item} mt-6 ${isActive(pathname, "/reglages") ? "bg-accent-soft text-accent" : "text-muted hover:text-ink"}`}
>
<span className="w-[18px] text-center">⚙</span>
Réglages
</Link>
</nav>
<div className="mt-auto flex items-center gap-2 border-t border-line px-2 pt-4">
<Avatar user={user} size={28} />
<span className="font-semibold">{user.firstName}</span>
<form action={logoutAction} className="ml-auto">
<button className="text-xs text-muted hover:text-neg" title="Déconnexion">
Déconnexion
</button>
</form>
</div>
</aside>
);
}
+67
View File
@@ -0,0 +1,67 @@
"use client";
import { useState } from "react";
import { bpToPercentLabel, fullSplit } from "@/domain/money";
import type { Cents, Split } from "@/domain/types";
import { CustomSplitFields } from "./CustomSplitFields";
import { Pills } from "./ui/Pills";
type Choice = "default" | `full:${string}` | "custom";
const same = (a: Split, b: Split) => Object.keys({ ...a, ...b }).every((k) => (a[k] ?? 0) === (b[k] ?? 0));
/** Choix de répartition : défaut du foyer, 100 % pour une personne, ou parts libres (en % ou en €). */
export function SplitPicker({
users,
defaultSplit,
value,
onChange,
total,
}: {
users: { id: string; firstName: string }[];
defaultSplit: Split;
value: Split;
onChange: (s: Split) => void;
/** Montant de l'opération, pour pouvoir répartir en euros (voir CustomSplitFields). */
total?: Cents | null;
}) {
const ids = users.map((u) => u.id);
const [choice, setChoice] = useState<Choice>(() => {
if (same(value, defaultSplit)) return "default";
const full = ids.find((id) => value[id] === 10000);
return full ? `full:${full}` : "custom";
});
const [custom, setCustom] = useState<Split>(value);
const pick = (c: Choice) => {
setChoice(c);
if (c === "default") onChange(defaultSplit);
else if (c === "custom") onChange(custom);
else onChange(fullSplit(c.slice(5), ids));
};
return (
<div className="space-y-2">
<Pills
options={[
{ value: "default" as Choice, label: ids.map((id) => bpToPercentLabel(defaultSplit[id] ?? 0)).join(" / ") },
...users.map((u) => ({ value: `full:${u.id}` as Choice, label: `100 % ${u.firstName}` })),
{ value: "custom" as Choice, label: "Perso…" },
]}
value={choice}
onChange={pick}
/>
{choice === "custom" && (
<CustomSplitFields
users={users}
total={total}
initial={custom}
onChange={(s) => {
setCustom(s);
onChange(s);
}}
/>
)}
</div>
);
}
@@ -0,0 +1,51 @@
"use client";
import { Bar, CartesianGrid, Cell, ComposedChart, Line, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { formatEuro } from "@/domain/money";
const ACCENT = "#4f46e5";
const OVER = "#dc2626";
const MUTED = "#6b7280";
const SHORT = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."];
/** Réel (barres) face au budget (ligne en escalier pointillée), sur une catégorie. */
export function BudgetHistoryChart({ data }: { data: { month: string; budget: number | null; actual: number }[] }) {
const rows = data.map((d) => ({
month: d.month,
label: `${SHORT[Number(d.month.slice(5, 7)) - 1]} ${d.month.slice(2, 4)}`,
actual: d.actual / 100,
budget: d.budget === null ? null : d.budget / 100,
over: d.budget !== null && d.actual > d.budget,
}));
return (
<div className="h-64 w-full">
<ResponsiveContainer>
<ComposedChart data={rows} margin={{ top: 8, right: 8, bottom: 0, left: 0 }} barCategoryGap="35%">
<CartesianGrid vertical={false} stroke="#f1f2f5" />
<XAxis dataKey="label" tickLine={false} axisLine={{ stroke: "#e5e7eb" }} tick={{ fill: MUTED, fontSize: 12 }} />
<YAxis
width={56}
tickLine={false}
axisLine={false}
tick={{ fill: MUTED, fontSize: 12 }}
tickFormatter={(v: number) => `${Math.round(v)} €`}
/>
<Tooltip
cursor={{ fill: "#f5f6fa" }}
formatter={(value, name) => [
value === null || value === undefined ? "—" : formatEuro(Math.round(Number(value) * 100)),
name === "actual" ? "Réel" : "Budget",
]}
contentStyle={{ borderRadius: 10, border: "1px solid #e5e7eb", fontSize: 13 }}
/>
<Bar dataKey="actual" radius={[4, 4, 0, 0]} maxBarSize={36}>
{rows.map((r) => (
<Cell key={r.month} fill={r.over ? OVER : ACCENT} />
))}
</Bar>
<Line dataKey="budget" type="stepAfter" stroke={MUTED} strokeWidth={2} strokeDasharray="5 4" dot={{ r: 4, fill: MUTED, stroke: "#fff", strokeWidth: 2 }} connectNulls={false} />
</ComposedChart>
</ResponsiveContainer>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
"use client";
import { useState, useTransition } from "react";
import { setBudgetAction } from "@/server/actions/budgets";
/** Montant du budget, enregistré à la sortie du champ, applicable à partir du mois affiché. */
export function BudgetInput({ categoryId, month, initial }: { categoryId: string; month: string; initial: string }) {
const [value, setValue] = useState(initial);
const [saved, setSaved] = useState(initial);
const [error, setError] = useState<string | null>(null);
const [pending, start] = useTransition();
const save = () => {
if (value.trim() === saved.trim()) return;
start(async () => {
const r = await setBudgetAction(categoryId, value, month);
if (!r.ok) return setError(r.error);
setError(null);
setSaved(value);
});
};
return (
<span className="inline-flex flex-col items-end">
<span className="relative">
<input
aria-label="Budget mensuel"
inputMode="decimal"
placeholder="—"
value={value}
onChange={(e) => setValue(e.target.value)}
onBlur={save}
onKeyDown={(e) => e.key === "Enter" && (e.currentTarget as HTMLInputElement).blur()}
className={`w-28 rounded-[10px] border bg-white py-1.5 pl-3 pr-7 text-right text-sm outline-none focus:border-accent focus:ring-2 focus:ring-accent/20 ${
error ? "border-neg" : "border-line"
} ${pending ? "opacity-60" : ""}`}
/>
<span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-muted">€</span>
</span>
{error && <span className="text-xs text-neg">{error}</span>}
</span>
);
}
+138
View File
@@ -0,0 +1,138 @@
"use client";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import type { Split } from "@/domain/types";
import { deleteLoanAction, saveLoanAction } from "@/server/actions/loans";
import type { LoanFormInput } from "@/server/services/loans";
import { SplitPicker } from "../SplitPicker";
import { Button } from "../ui/Button";
import { Field, FormError, Input } from "../ui/Field";
import { Pills } from "../ui/Pills";
export function LoanForm({
users,
defaultSplit,
currentUserId,
today,
initial,
}: {
users: { id: string; firstName: string }[];
defaultSplit: Split;
currentUserId: string;
today: string;
initial?: LoanFormInput & { id: string };
}) {
const router = useRouter();
const [pending, start] = useTransition();
const [error, setError] = useState<string | null>(null);
const [f, setF] = useState<LoanFormInput>(
initial ?? {
name: "",
lender: "",
principal: "",
annualRate: "",
durationMonths: 60,
startDate: today,
insuranceMonthly: "",
accountUserId: currentUserId,
split: Object.fromEntries(users.map((u) => [u.id, u.id === currentUserId ? 10000 : 0])),
paymentOverride: "",
referenceDate: "",
referenceRemainingCapital: "",
},
);
const [running, setRunning] = useState(Boolean(initial?.referenceDate || initial?.paymentOverride));
const set = <K extends keyof LoanFormInput>(k: K, v: LoanFormInput[K]) => setF((prev) => ({ ...prev, [k]: v }));
const submit = () =>
start(async () => {
const payload = running ? f : { ...f, paymentOverride: "", referenceDate: "", referenceRemainingCapital: "" };
const r = await saveLoanAction(payload);
if (!r.ok) return setError(r.error);
router.push(`/credits/${r.id}`);
});
const remove = () => {
if (!initial || !confirm("Supprimer ce crédit ? Les mensualités déjà passées restent dans l'historique.")) return;
start(async () => {
await deleteLoanAction(initial.id);
router.push("/credits");
});
};
return (
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Nom">
<Input value={f.name} onChange={(e) => set("name", e.target.value)} placeholder="Crédit voiture" />
</Field>
<Field label="Organisme (facultatif)">
<Input value={f.lender} onChange={(e) => set("lender", e.target.value)} />
</Field>
<Field label="Capital emprunté (€)">
<Input inputMode="decimal" value={f.principal} onChange={(e) => set("principal", e.target.value)} />
</Field>
<Field label="Taux annuel (%)">
<Input inputMode="decimal" value={f.annualRate} onChange={(e) => set("annualRate", e.target.value)} placeholder="3,45" />
</Field>
<Field label="Durée (mois)">
<Input type="number" min={1} max={600} value={f.durationMonths} onChange={(e) => set("durationMonths", Number(e.target.value))} />
</Field>
<Field label="Première échéance">
<Input type="date" value={f.startDate} onChange={(e) => set("startDate", e.target.value)} />
</Field>
<Field label="Assurance mensuelle (€)">
<Input inputMode="decimal" value={f.insuranceMonthly} onChange={(e) => set("insuranceMonthly", e.target.value)} placeholder="0" />
</Field>
</div>
<div>
<div className="mb-2 text-xs font-semibold text-muted">Titulaire (compte débité)</div>
<Pills options={users.map((u) => ({ value: u.id, label: u.firstName }))} value={f.accountUserId} onChange={(v) => set("accountUserId", v)} />
</div>
<div>
<div className="mb-2 text-xs font-semibold text-muted">Répartition de la mensualité</div>
<SplitPicker users={users} defaultSplit={defaultSplit} value={f.split} onChange={(s) => set("split", s)} />
</div>
<div className="rounded-card border border-line p-4">
<label className="flex items-center gap-2 font-medium">
<input type="checkbox" checked={running} onChange={(e) => setRunning(e.target.checked)} className="h-4 w-4 accent-accent" />
Crédit déjà en cours : utiliser les chiffres de la banque
</label>
{running && (
<div className="mt-3 grid gap-3 sm:grid-cols-3">
<Field label="Mensualité réelle hors assurance (€)">
<Input inputMode="decimal" value={f.paymentOverride} onChange={(e) => set("paymentOverride", e.target.value)} />
</Field>
<Field label="Capital restant dû (€)">
<Input inputMode="decimal" value={f.referenceRemainingCapital} onChange={(e) => set("referenceRemainingCapital", e.target.value)} />
</Field>
<Field label="Au (date)">
<Input type="date" value={f.referenceDate} onChange={(e) => set("referenceDate", e.target.value)} />
</Field>
</div>
)}
</div>
<FormError message={error} />
<div className="flex gap-3">
{initial && (
<Button type="button" variant="danger" onClick={remove} disabled={pending}>
Supprimer
</Button>
)}
<Button type="submit" className="flex-1 py-3" disabled={pending}>
{pending ? "Enregistrement…" : "Enregistrer"}
</Button>
</div>
</form>
);
}
@@ -0,0 +1,87 @@
"use client";
import { useState, useTransition } from "react";
import { decimalFromCents } from "@/domain/money";
import { saveSettlementAction } from "@/server/actions/operations";
import { Button } from "../ui/Button";
import { Card } from "../ui/Card";
import { Field, FormError, Input, Select } from "../ui/Field";
export function SettlementDialog({
users,
debtorId,
creditorId,
amount,
today,
}: {
users: { id: string; firstName: string }[];
debtorId?: string;
creditorId?: string;
amount?: number;
today: string;
}) {
const [open, setOpen] = useState(false);
const [from, setFrom] = useState(debtorId ?? users[1]?.id ?? "");
const [to, setTo] = useState(creditorId ?? users[0]?.id ?? "");
const [value, setValue] = useState(amount ? decimalFromCents(amount).replace(".", ",") : "");
const [date, setDate] = useState(today);
const [error, setError] = useState<string | null>(null);
const [pending, startTransition] = useTransition();
const submit = () =>
startTransition(async () => {
const r = await saveSettlementAction({ fromUserId: from, toUserId: to, amount: value, date });
if (!r.ok) return setError(r.error);
setOpen(false);
});
return (
<>
<Button variant="ghost" onClick={() => setOpen(true)} className="shrink-0">
Enregistrer un remboursement
</Button>
{open && (
<div className="fixed inset-0 z-50 grid place-items-center bg-black/30 p-4" onClick={() => setOpen(false)}>
<Card className="w-full max-w-sm space-y-4 p-5 shadow-xl" onClick={(e) => e.stopPropagation()}>
<h2 className="text-lg font-bold">Remboursement entre vous</h2>
<div className="grid grid-cols-2 gap-3">
<Field label="De">
<Select value={from} onChange={(e) => setFrom(e.target.value)}>
{users.map((u) => (
<option key={u.id} value={u.id}>
{u.firstName}
</option>
))}
</Select>
</Field>
<Field label="À">
<Select value={to} onChange={(e) => setTo(e.target.value)}>
{users.map((u) => (
<option key={u.id} value={u.id}>
{u.firstName}
</option>
))}
</Select>
</Field>
</div>
<Field label="Montant (€)">
<Input inputMode="decimal" value={value} onChange={(e) => setValue(e.target.value)} />
</Field>
<Field label="Date">
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</Field>
<FormError message={error} />
<div className="flex gap-3">
<Button variant="ghost" onClick={() => setOpen(false)} className="flex-1">
Annuler
</Button>
<Button onClick={submit} disabled={pending} className="flex-1">
Enregistrer
</Button>
</div>
</Card>
</div>
)}
</>
);
}
+18
View File
@@ -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}/`);
@@ -0,0 +1,46 @@
"use client";
import Link from "next/link";
import { useTransition } from "react";
import { deleteRecurringAction, endRecurringAction, setRecurringPausedAction } from "@/server/actions/recurrings";
const btn = "rounded-lg px-2.5 py-1.5 text-[13px] font-semibold hover:bg-page disabled:opacity-50";
export function RecurringActions({ id, paused, today }: { id: string; paused: boolean; today: string }) {
const [pending, start] = useTransition();
const run = (fn: () => Promise<{ ok: boolean; error?: string }>) =>
start(async () => {
const r = await fn();
if (!r.ok && r.error) alert(r.error);
});
return (
<div className="flex flex-wrap gap-1">
<Link href={`/recurrents/${id}`} className={`${btn} text-accent`}>
Modifier
</Link>
<button className={`${btn} text-muted`} disabled={pending} onClick={() => run(() => setRecurringPausedAction(id, !paused))}>
{paused ? "Reprendre" : "Pause"}
</button>
<button
className={`${btn} text-muted`}
disabled={pending}
onClick={() => {
const date = prompt("Dernière échéance le (AAAA-MM-JJ) :", today);
if (date) run(() => endRecurringAction(id, date));
}}
>
Terminer
</button>
<button
className={`${btn} text-neg`}
disabled={pending}
onClick={() => {
if (confirm("Supprimer ce récurrent ? Les opérations déjà passées sont conservées.")) run(() => deleteRecurringAction(id));
}}
>
Supprimer
</button>
</div>
);
}
+193
View File
@@ -0,0 +1,193 @@
"use client";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { fullSplit, parseEuro } from "@/domain/money";
import type { AllocationMode, Frequency, OpKind, Split } from "@/domain/types";
import { saveRecurringAction } from "@/server/actions/recurrings";
import type { FormCategory, FormUser } from "../OperationForm";
import { SplitPicker } from "../SplitPicker";
import { Button } from "../ui/Button";
import { Field, FormError, Input, Select } from "../ui/Field";
import { Pills } from "../ui/Pills";
export interface RecurringInitial {
id: string;
kind: OpKind;
amount: string;
label: string;
categoryId: string;
accountUserId: string;
split: Split;
frequency: Frequency;
dayOfMonth: number;
startDate: string;
endDate: string | null;
allocatedToRecurringId: string | null;
allocationMode: AllocationMode | null;
}
export function RecurringForm({
users,
categories,
defaultSplit,
currentUserId,
today,
targets,
initial,
}: {
users: FormUser[];
categories: FormCategory[];
defaultSplit: Split;
currentUserId: string;
today: string;
targets: { id: string; label: string; split: Split }[];
initial?: RecurringInitial;
}) {
const router = useRouter();
const ids = users.map((u) => u.id);
const [pending, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
const [kind, setKind] = useState<OpKind>(initial?.kind ?? "EXPENSE");
const [amount, setAmount] = useState(initial?.amount ?? "");
const [label, setLabel] = useState(initial?.label ?? "");
const [categoryId, setCategoryId] = useState(initial?.categoryId ?? "");
const [accountUserId, setAccountUserId] = useState(initial?.accountUserId ?? currentUserId);
const [split, setSplit] = useState<Split>(initial?.split ?? defaultSplit);
const [frequency, setFrequency] = useState<Frequency>(initial?.frequency ?? "MONTHLY");
const [startDate, setStartDate] = useState(initial?.startDate ?? today);
const [dayOfMonth, setDayOfMonth] = useState(String(initial?.dayOfMonth ?? Number(today.slice(8, 10))));
const [endDate, setEndDate] = useState(initial?.endDate ?? "");
const [target, setTarget] = useState(initial?.allocatedToRecurringId ?? "");
const [mode, setMode] = useState<AllocationMode>(initial?.allocationMode ?? "REDUCE_SHARED");
const allocated = kind === "INCOME" && target !== "";
const targetOptions = targets.filter((t) => t.id !== initial?.id);
const submit = () => {
setError(null);
const effectiveSplit =
kind === "INCOME" && !(allocated && mode === "CUSTOM") ? fullSplit(accountUserId, ids) : split;
startTransition(async () => {
const r = await saveRecurringAction({
id: initial?.id,
kind,
amount,
label,
categoryId,
accountUserId,
split: effectiveSplit,
frequency,
dayOfMonth: Number(dayOfMonth),
startDate,
endDate: endDate || null,
allocatedToRecurringId: allocated ? target : null,
allocationMode: allocated ? mode : null,
});
if (!r.ok) return setError(r.error);
router.push("/recurrents");
});
};
return (
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<Pills
options={[
{ value: "EXPENSE" as OpKind, label: "Dépense" },
{ value: "INCOME" as OpKind, label: "Entrée" },
]}
value={kind}
onChange={(k) => {
setKind(k);
setCategoryId("");
}}
/>
<div className="grid gap-3 sm:grid-cols-[1fr_140px]">
<Field label="Libellé">
<Input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="Loyer, salaire, Netflix…" />
</Field>
<Field label="Montant (€)">
<Input inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="0,00" />
</Field>
</div>
<Field label="Catégorie">
<Select value={categoryId} onChange={(e) => setCategoryId(e.target.value)}>
<option value="">Choisir…</option>
{categories
.filter((c) => c.kind === kind)
.map((c) => (
<option key={c.id} value={c.id}>
{c.emoji} {c.name}
</option>
))}
</Select>
</Field>
<div>
<div className="mb-2 text-xs font-semibold text-muted">{kind === "EXPENSE" ? "Payé par" : "Reçu par"}</div>
<Pills options={users.map((u) => ({ value: u.id, label: u.firstName }))} value={accountUserId} onChange={setAccountUserId} />
</div>
{kind === "EXPENSE" && (
<div>
<div className="mb-2 text-xs font-semibold text-muted">Répartition</div>
<SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} total={parseEuro(amount)} />
</div>
)}
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Fréquence">
<Select value={frequency} onChange={(e) => setFrequency(e.target.value as Frequency)}>
<option value="MONTHLY">Mensuelle</option>
<option value="QUARTERLY">Trimestrielle</option>
<option value="YEARLY">Annuelle</option>
</Select>
</Field>
<Field label="Jour du mois" hint="31 = dernier jour des mois plus courts">
<Input type="number" min={1} max={31} value={dayOfMonth} onChange={(e) => setDayOfMonth(e.target.value)} />
</Field>
<Field label="À partir du">
<Input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
</Field>
<Field label="Jusqu'au (facultatif)">
<Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
</Field>
</div>
{kind === "INCOME" && (
<div className="space-y-3 rounded-card border border-line p-4">
<Field label="Affecter à une charge" hint="Ex. IK → crédit voiture, part loyer employeur → loyer">
<Select value={target} onChange={(e) => setTarget(e.target.value)}>
<option value="">Aucune</option>
{targetOptions.map((t) => (
<option key={t.id} value={t.id}>
{t.label}
</option>
))}
</Select>
</Field>
{allocated && (
<>
<Pills
options={[
{ value: "REDUCE_SHARED" as AllocationMode, label: "Réduit la charge pour tous" },
{ value: "BENEFICIARY_ONLY" as AllocationMode, label: "Profite au bénéficiaire" },
{ value: "CUSTOM" as AllocationMode, label: "Perso" },
]}
value={mode}
onChange={setMode}
/>
{mode === "CUSTOM" && <SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} total={parseEuro(amount)} />}
</>
)}
</div>
)}
<FormError message={error} />
<Button type="submit" className="w-full py-3" disabled={pending}>
{pending ? "Enregistrement…" : "Enregistrer"}
</Button>
</form>
);
}
@@ -0,0 +1,52 @@
"use client";
import { useState, useTransition } from "react";
import { decimalFromCents } from "@/domain/money";
import type { OpKind } from "@/domain/types";
import { formatDateFr } from "@/lib/dates";
import { confirmOperationAction, skipOperationAction } from "@/server/actions/operations";
import { Button } from "../ui/Button";
import { Input } from "../ui/Field";
export function ToConfirmRow({
op,
}: {
op: { id: string; label: string; emoji: string; amount: number; date: string; kind: OpKind; who: string };
}) {
const [amount, setAmount] = useState(decimalFromCents(op.amount).replace(".", ","));
const [date, setDate] = useState(op.date);
const [error, setError] = useState<string | null>(null);
const [pending, start] = useTransition();
return (
<div className="flex flex-col gap-2 border-b border-line-soft py-3 last:border-0 md:flex-row md:items-center">
<div className="min-w-0 flex-1">
<b>
{op.emoji} {op.label}
</b>
<div className="text-[13px] text-muted">
prévu le {formatDateFr(op.date)} · {op.kind === "EXPENSE" ? "payé par" : "reçu par"} {op.who}
</div>
{error && <div className="text-[13px] text-neg">{error}</div>}
</div>
<div className="flex flex-wrap items-center gap-2">
<Input aria-label="Montant" inputMode="decimal" className="w-28" value={amount} onChange={(e) => setAmount(e.target.value)} />
<Input aria-label="Date" type="date" className="w-40" value={date} onChange={(e) => setDate(e.target.value)} />
<Button
disabled={pending}
onClick={() =>
start(async () => {
const r = await confirmOperationAction(op.id, amount, date);
setError(r.ok ? null : r.error);
})
}
>
Confirmer
</Button>
<Button variant="ghost" disabled={pending} onClick={() => start(async () => void (await skipOperationAction(op.id)))}>
Ignorer
</Button>
</div>
</div>
);
}
+193
View File
@@ -0,0 +1,193 @@
"use client";
import { useState, useTransition } from "react";
import type { OpKind, Split } from "@/domain/types";
import {
archiveCategoryAction,
changePasswordAction,
saveCategoryAction,
setDefaultSplitAction,
updateUserAction,
} from "@/server/actions/settings";
import { SplitPicker } from "../SplitPicker";
import { Button } from "../ui/Button";
import { Card, CardLabel } from "../ui/Card";
import { Field, Input } from "../ui/Field";
function Feedback({ msg }: { msg: { ok: boolean; text: string } | null }) {
if (!msg) return null;
return <span className={`text-[13px] font-medium ${msg.ok ? "text-pos" : "text-neg"}`}>{msg.text}</span>;
}
function useSave() {
const [pending, start] = useTransition();
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const run = (fn: () => Promise<{ ok: boolean; error?: string }>, success = "Enregistré ✓") =>
start(async () => {
const r = await fn();
setMsg(r.ok ? { ok: true, text: success } : { ok: false, text: r.error ?? "Erreur" });
});
return { pending, msg, run };
}
export function PersonCard({ user, isMe }: { user: { id: string; firstName: string; login: string; color: string }; isMe: boolean }) {
const [f, setF] = useState(user);
const profile = useSave();
const password = useSave();
const [current, setCurrent] = useState("");
const [next, setNext] = useState("");
return (
<Card className="space-y-4">
<CardLabel>{isMe ? `${user.firstName} (vous)` : user.firstName}</CardLabel>
<div className="flex gap-3">
<Field label="Prénom">
<Input value={f.firstName} onChange={(e) => setF({ ...f, firstName: e.target.value })} />
</Field>
<Field label="Couleur">
<Input type="color" value={f.color} onChange={(e) => setF({ ...f, color: e.target.value })} className="h-[42px] w-16 p-1" />
</Field>
</div>
<Field label="Identifiant">
<Input value={f.login} autoCapitalize="none" onChange={(e) => setF({ ...f, login: e.target.value })} />
</Field>
<div className="flex items-center gap-3">
<Button disabled={profile.pending} onClick={() => profile.run(() => updateUserAction(user.id, f))}>
Enregistrer
</Button>
<Feedback msg={profile.msg} />
</div>
{isMe && (
<div className="space-y-3 border-t border-line pt-4">
<CardLabel>Changer mon mot de passe</CardLabel>
<Input type="password" placeholder="Mot de passe actuel" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} />
<Input type="password" placeholder="Nouveau mot de passe (8 caractères min.)" autoComplete="new-password" value={next} onChange={(e) => setNext(e.target.value)} />
<div className="flex items-center gap-3">
<Button
variant="ghost"
disabled={password.pending}
onClick={() =>
password.run(async () => {
const r = await changePasswordAction(current, next);
if (r.ok) {
setCurrent("");
setNext("");
}
return r;
}, "Mot de passe modifié ✓")
}
>
Changer
</Button>
<Feedback msg={password.msg} />
</div>
</div>
)}
</Card>
);
}
export function DefaultSplitCard({ users, split }: { users: { id: string; firstName: string }[]; split: Split }) {
const [value, setValue] = useState(split);
const save = useSave();
return (
<Card className="space-y-3">
<CardLabel>Répartition par défaut des dépenses</CardLabel>
<p className="text-[13px] text-muted">Proposée à chaque nouvelle dépense. Les entrées restent à 100 % pour la personne qui les reçoit.</p>
<SplitPicker users={users} defaultSplit={split} value={value} onChange={setValue} />
<div className="flex items-center gap-3">
<Button disabled={save.pending} onClick={() => save.run(() => setDefaultSplitAction(value))}>
Enregistrer
</Button>
<Feedback msg={save.msg} />
</div>
</Card>
);
}
interface Cat {
id: string;
name: string;
emoji: string;
kind: OpKind;
archived: boolean;
}
function CategoryRow({ cat }: { cat: Cat }) {
const [name, setName] = useState(cat.name);
const [emoji, setEmoji] = useState(cat.emoji);
const save = useSave();
const dirty = name !== cat.name || emoji !== cat.emoji;
return (
<div className={`flex items-center gap-2 py-1.5 ${cat.archived ? "opacity-50" : ""}`}>
<Input aria-label="Emoji" className="w-14 text-center" value={emoji} onChange={(e) => setEmoji(e.target.value)} />
<Input aria-label="Nom" className="min-w-0 flex-1" value={name} onChange={(e) => setName(e.target.value)} />
{dirty && (
<Button className="px-3" disabled={save.pending} onClick={() => save.run(() => saveCategoryAction({ id: cat.id, name, emoji, kind: cat.kind }))}>
OK
</Button>
)}
<button
type="button"
className="w-20 shrink-0 text-[13px] font-semibold text-muted hover:text-ink"
onClick={() => save.run(() => archiveCategoryAction(cat.id, !cat.archived), cat.archived ? "Réactivée" : "Archivée")}
>
{cat.archived ? "Réactiver" : "Archiver"}
</button>
{save.msg && !save.msg.ok && <Feedback msg={save.msg} />}
</div>
);
}
export function CategoriesCard({ categories }: { categories: Cat[] }) {
const [kind, setKind] = useState<OpKind>("EXPENSE");
const [name, setName] = useState("");
const [emoji, setEmoji] = useState("");
const add = useSave();
return (
<Card className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<CardLabel>Catégories</CardLabel>
<div className="flex rounded-[10px] bg-gray-100 p-1 text-[13px]">
{(["EXPENSE", "INCOME"] as const).map((k) => (
<button
key={k}
type="button"
onClick={() => setKind(k)}
className={`rounded-lg px-3 py-1 font-semibold ${kind === k ? "bg-white shadow-sm" : "text-muted"}`}
>
{k === "EXPENSE" ? "Dépenses" : "Entrées"}
</button>
))}
</div>
</div>
<div className="divide-y divide-line-soft">
{categories
.filter((c) => c.kind === kind)
.map((c) => (
<CategoryRow key={`${c.id}-${c.name}-${c.emoji}-${c.archived}`} cat={c} />
))}
</div>
<div className="flex items-center gap-2 border-t border-line pt-3">
<Input aria-label="Emoji" placeholder="🙂" className="w-14 text-center" value={emoji} onChange={(e) => setEmoji(e.target.value)} />
<Input aria-label="Nouvelle catégorie" placeholder="Nouvelle catégorie" className="min-w-0 flex-1" value={name} onChange={(e) => setName(e.target.value)} />
<Button
disabled={add.pending || !name.trim()}
onClick={() =>
add.run(async () => {
const r = await saveCategoryAction({ name, emoji, kind });
if (r.ok) {
setName("");
setEmoji("");
}
return r;
}, "Ajoutée ✓")
}
>
Ajouter
</Button>
</div>
<Feedback msg={add.msg} />
</Card>
);
}
@@ -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>
);
}
+13
View File
@@ -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 (
<span className={`tabular whitespace-nowrap font-semibold ${color} ${className}`}>
{formatEuro(signed, { sign: kind !== undefined })}
</span>
);
}
+10
View File
@@ -0,0 +1,10 @@
export function Avatar({ user, size = 34 }: { user: { firstName: string; color: string }; size?: number }) {
return (
<span
className="inline-grid shrink-0 place-items-center rounded-full font-bold text-white"
style={{ backgroundColor: user.color, width: size, height: size, fontSize: size * 0.38 }}
>
{user.firstName.slice(0, 1).toUpperCase()}
</span>
);
}
+24
View File
@@ -0,0 +1,24 @@
import type { ReactNode } from "react";
type Tone = "accent" | "split" | "planned" | "link" | "danger";
const TONES: Record<Tone, string> = {
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 (
<span
className={`inline-block whitespace-nowrap rounded-full px-2 py-0.5 text-[11px] font-semibold ${color ? "" : TONES[tone]}`}
style={style}
>
{children}
</span>
);
}
+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>
</>
);
}
+30
View File
@@ -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<string, string | undefined>;
}) {
const href = (m: string) => {
const q = new URLSearchParams({ ...Object.fromEntries(Object.entries(params).filter(([, v]) => v)), m } as Record<string, string>);
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 (
<div className="flex items-center gap-3">
<Link href={href(addMonths(month, -1))} className={arrow} aria-label="Mois précédent">
‹
</Link>
<h1 className="min-w-[10ch] text-center text-xl font-bold md:text-[22px]">{monthLabelFr(month)}</h1>
<Link href={href(addMonths(month, 1))} className={arrow} aria-label="Mois suivant">
›
</Link>
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
"use client";
export interface PillOption<T extends string> {
value: T;
label: string;
}
export function Pills<T extends string>({
options,
value,
onChange,
}: {
options: PillOption<T>[];
value: T | null;
onChange: (v: T) => void;
}) {
return (
<div className="flex flex-wrap gap-1.5">
{options.map((o) => (
<button
key={o.value}
type="button"
onClick={() => onChange(o.value)}
className={`rounded-full border px-3 py-1.5 text-[13px] font-medium transition-colors ${
value === o.value ? "border-accent bg-accent text-white" : "border-line bg-white text-ink hover:border-gray-300"
}`}
>
{o.label}
</button>
))}
</div>
);
}
+26 -2
View File
@@ -3,9 +3,13 @@ import type { Cents, Split, UserId } from "./types";
const euro = new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }); const euro = new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" });
const MINUS = "−"; const MINUS = "−";
/** "86,40", "1 234,56", "86.40" → centimes. null si vide, nul, négatif ou invalide. */ /** "86,40", "1 234,56", "86.40", "40.000 €" → centimes. null si vide, nul, négatif ou invalide. */
export function parseEuro(input: string): Cents | null { export function parseEuro(input: string): Cents | null {
const s = input.replace(/[\s  ]/g, "").replace(",", "."); let s = input.replace(/[\s  €]/g, "");
// Les points sont des séparateurs de milliers s'il y a une virgule décimale ("40.000,50")
// ou s'ils séparent des groupes de 3 chiffres ("40.000") ; sinon c'est la décimale ("86.40").
if (s.includes(",") || /^\d{1,3}(\.\d{3})+$/.test(s)) s = s.replace(/\./g, "");
s = s.replace(",", ".");
if (!/^\d+(\.\d{1,2})?$/.test(s)) return null; if (!/^\d+(\.\d{1,2})?$/.test(s)) return null;
const [units, decimals = ""] = s.split("."); const [units, decimals = ""] = s.split(".");
const cents = Number(units) * 100 + Number(decimals.padEnd(2, "0")); const cents = Number(units) * 100 + Number(decimals.padEnd(2, "0"));
@@ -51,6 +55,26 @@ export function shareAmounts(amount: Cents, split: Split, accountUserId: UserId)
return shares; return shares;
} }
/**
* Montant payé par chacun → répartition en points de base (plus forts restes, ex aequo au premier).
* null si la somme des montants ne fait pas le total. Précision limitée au centième de %.
*/
export function splitFromAmounts(parts: Record<UserId, Cents>, total: Cents): Split | null {
const entries = Object.entries(parts);
if (total <= 0 || entries.some(([, c]) => c < 0) || entries.reduce((t, [, c]) => t + c, 0) !== total) return null;
const split: Split = {};
const rests = entries.map(([id, c]) => {
split[id] = Math.floor((c * 10000) / total);
return { id, rest: (c * 10000) % total };
});
let missing = 10000 - Object.values(split).reduce((a, b) => a + b, 0);
for (const { id } of [...rests].sort((a, b) => b.rest - a.rest)) {
if (missing-- <= 0) break;
split[id] += 1;
}
return split;
}
/** "33,33" → 3333. null si invalide ou hors [0, 100]. */ /** "33,33" → 3333. null si invalide ou hors [0, 100]. */
export function percentToBp(input: string): number | null { export function percentToBp(input: string): number | null {
const s = input.replace(/[\s%]/g, "").replace(",", "."); const s = input.replace(/[\s%]/g, "").replace(",", ".");
+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;
}
+12
View File
@@ -0,0 +1,12 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireUser } from "@/server/auth";
import { setBudget } from "@/server/services/budgets";
export async function setBudgetAction(categoryId: string, amount: string, fromMonth: string) {
await requireUser();
const result = await setBudget(categoryId, amount, fromMonth);
if (result.ok) revalidatePath("/", "layout");
return result;
}
+19
View File
@@ -0,0 +1,19 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireUser } from "@/server/auth";
import * as loans from "@/server/services/loans";
export async function saveLoanAction(input: loans.LoanFormInput) {
await requireUser();
const result = await loans.saveLoan(input);
if (result.ok) revalidatePath("/", "layout");
return result;
}
export async function deleteLoanAction(id: string) {
await requireUser();
const result = await loans.deleteLoan(id);
revalidatePath("/", "layout");
return result;
}
+49
View File
@@ -0,0 +1,49 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireUser } from "@/server/auth";
import * as ops from "@/server/services/operations";
const refresh = () => revalidatePath("/", "layout");
export async function saveOperationAction(input: ops.OperationInput) {
const user = await requireUser();
const result = await ops.saveOperation(input, user.id);
if (result.ok) refresh();
return result;
}
export async function deleteOperationAction(id: string) {
await requireUser();
const result = await ops.deleteOperation(id);
refresh();
return result;
}
export async function confirmOperationAction(id: string, amount: string, date: string) {
await requireUser();
const result = await ops.confirmOperation(id, amount, date);
if (result.ok) refresh();
return result;
}
export async function skipOperationAction(id: string) {
await requireUser();
const result = await ops.skipOperation(id);
refresh();
return result;
}
export async function saveSettlementAction(input: Parameters<typeof ops.saveSettlement>[0]) {
await requireUser();
const result = await ops.saveSettlement(input);
if (result.ok) refresh();
return result;
}
export async function deleteSettlementAction(id: string) {
await requireUser();
const result = await ops.deleteSettlement(id);
refresh();
return result;
}
+35
View File
@@ -0,0 +1,35 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireUser } from "@/server/auth";
import * as rec from "@/server/services/recurrings";
const refresh = () => revalidatePath("/", "layout");
export async function saveRecurringAction(input: rec.RecurringInput) {
await requireUser();
const result = await rec.saveRecurring(input);
if (result.ok) refresh();
return result;
}
export async function setRecurringPausedAction(id: string, paused: boolean) {
await requireUser();
const result = await rec.setRecurringPaused(id, paused);
refresh();
return result;
}
export async function endRecurringAction(id: string, endDate: string) {
await requireUser();
const result = await rec.endRecurring(id, endDate);
if (result.ok) refresh();
return result;
}
export async function deleteRecurringAction(id: string) {
await requireUser();
const result = await rec.deleteRecurring(id);
if (result.ok) refresh();
return result;
}
+42
View File
@@ -0,0 +1,42 @@
"use server";
import { revalidatePath } from "next/cache";
import type { OpKind, Split } from "@/domain/types";
import { requireUser } from "@/server/auth";
import * as settings from "@/server/services/settings";
const refresh = () => revalidatePath("/", "layout");
export async function updateUserAction(id: string, input: { firstName: string; color: string; login: string }) {
await requireUser();
const r = await settings.updateUser(id, input);
if (r.ok) refresh();
return r;
}
/** On ne change que son propre mot de passe (l'autre passe par le script de réinitialisation). */
export async function changePasswordAction(current: string, next: string) {
const user = await requireUser();
return settings.changePassword(user.id, current, next);
}
export async function setDefaultSplitAction(split: Split) {
await requireUser();
const r = await settings.setDefaultSplit(split);
if (r.ok) refresh();
return r;
}
export async function saveCategoryAction(input: { id?: string; name: string; emoji: string; kind: OpKind }) {
await requireUser();
const r = await settings.saveCategory(input);
if (r.ok) refresh();
return r;
}
export async function archiveCategoryAction(id: string, archived: boolean) {
await requireUser();
const r = await settings.archiveCategory(id, archived);
refresh();
return r;
}
+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 } }, create: { id: 1, defaultSplit: { [users[0].id]: firstBp, [users[1].id]: 10000 - firstBp } },
}); });
if (opening !== null) { 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({ await tx.settlement.create({
data: { data: {
fromUserId: from.id, fromUserId: from.id,
+53
View File
@@ -0,0 +1,53 @@
import { bpToPercentLabel } from "@/domain/money";
import type { Op } from "@/domain/types";
import { formatDateFr } from "@/lib/dates";
const field = (v: string) => (/[;"\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v);
/** "-86,40" : virgule décimale, signe selon le type, pas de séparateur de milliers (pour Excel). */
const amount = (o: Op) => {
const cents = o.amount;
const text = `${Math.floor(cents / 100)},${String(cents % 100).padStart(2, "0")}`;
return o.kind === "EXPENSE" ? `-${text}` : text;
};
/** Export CSV pour Excel : UTF-8 avec BOM, séparateur « ; », fins de ligne CRLF. */
export function opsToCsv(
ops: (Op & { note?: string | null })[],
users: { id: string; firstName: string }[],
categories: Record<string, { name: string }>,
chargeLabels: Record<string, string>,
): string {
const header = [
"Date",
"Type",
"Libellé",
"Catégorie",
"Montant",
"Payé par",
"Statut",
...users.map((u) => `Part ${u.firstName} %`),
"Affecté à",
"Note",
];
const lines = ops
.filter((o) => o.status !== "SKIPPED")
.map((o) => {
const target = o.allocatedToRecurringId ?? o.allocatedToOperationId;
return [
formatDateFr(o.date),
o.kind === "EXPENSE" ? "Dépense" : "Entrée",
o.label,
categories[o.categoryId]?.name ?? "",
amount(o),
users.find((u) => u.id === o.accountUserId)?.firstName ?? "",
o.status === "PLANNED" ? "Prévu" : "Réel",
...users.map((u) => bpToPercentLabel(o.split[u.id] ?? 0)),
target ? (chargeLabels[target] ?? "") : "",
o.note ?? "",
]
.map(field)
.join(";");
});
return "" + [header.map(field).join(";"), ...lines].join("\r\n") + "\r\n";
}
+91
View File
@@ -0,0 +1,91 @@
import { computeBalances, describeBalance } from "@/domain/balance";
import { formatEuro, centsFromDecimal } from "@/domain/money";
import {
budgetForMonth,
budgetStatus,
householdTotals,
netCharges,
personFlows,
type BudgetLine,
type ChargeRef,
type HouseholdTotals,
type NetCharge,
type PersonFlows,
} from "@/domain/monthly";
import type { Op } from "@/domain/types";
import { fromIsoDate, todayParis } from "@/lib/dates";
import { prisma } from "./db";
import { getAllActualOps, getCategories, getOpsForMonth, getRecurringDefs, getSettlements, getUsers, type UserLite } from "./repo";
export interface DashboardData {
users: UserLite[];
totals: HouseholdTotals;
persons: { user: UserLite; flows: PersonFlows }[];
balance: { text: string; debtorId?: string; creditorId?: string; amount?: number } | null;
lastSettlementDate: string | null;
budgets: (BudgetLine & { name: string; emoji: string })[];
netCharges: NetCharge[];
recent: Op[];
toConfirmCount: number;
categories: Record<string, { name: string; emoji: string }>;
chargeLabels: Record<string, string>;
}
export async function loadDashboard(month: string, viewerId: string, today: string = todayParis()): Promise<DashboardData> {
const [users, monthOps, actualOps, settlements, recurrings, budgetRows, categories, toConfirmCount] = await Promise.all([
getUsers(),
getOpsForMonth(month),
getAllActualOps(),
getSettlements(),
getRecurringDefs(),
prisma.budget.findMany(),
getCategories(undefined, true),
prisma.operation.count({ where: { status: "PLANNED", date: { lte: fromIsoDate(today) } } }),
]);
const userIds = users.map((u) => u.id);
const name = (id: string) => users.find((u) => u.id === id)?.firstName ?? "?";
const described = describeBalance(computeBalances(actualOps, settlements, userIds));
let balance: DashboardData["balance"] = { text: "Vous êtes à l'équilibre" };
if (described) {
const amount = formatEuro(described.amount);
let text = `${name(described.debtor)} doit ${amount} à ${name(described.creditor)}`;
if (viewerId === described.creditor) text = `${name(described.debtor)} te doit ${amount}`;
if (viewerId === described.debtor) text = `Tu dois ${amount} à ${name(described.creditor)}`;
balance = { text, debtorId: described.debtor, creditorId: described.creditor, amount: described.amount };
}
const categoryMap = Object.fromEntries(categories.map((c) => [c.id, { name: c.name, emoji: c.emoji }]));
const budgets = budgetStatus(
monthOps,
month,
budgetForMonth(
budgetRows.map((b) => ({ ...b, monthlyAmount: centsFromDecimal(b.monthlyAmount) })),
month,
),
).map((b) => ({ ...b, ...(categoryMap[b.categoryId] ?? { name: "?", emoji: "" }) }));
const opTargets = new Set(monthOps.map((o) => o.allocatedToOperationId).filter((id): id is string => id !== null));
const charges: ChargeRef[] = [
...recurrings.filter((r) => r.kind === "EXPENSE").map((r) => ({ id: r.id, label: r.label, kind: "recurring" as const, split: r.split })),
...monthOps.filter((o) => opTargets.has(o.id)).map((o) => ({ id: o.id, label: o.label, kind: "operation" as const, split: o.split })),
];
const chargeLabels = Object.fromEntries([
...recurrings.map((r) => [r.id, r.label]),
...monthOps.map((o) => [o.id, o.label]),
]);
return {
users,
totals: householdTotals(monthOps, month),
persons: users.map((user) => ({ user, flows: personFlows(monthOps, month, user.id) })),
balance,
lastSettlementDate: settlements[0]?.date ?? null,
budgets,
netCharges: netCharges(monthOps, month, charges),
recent: monthOps.filter((o) => o.status !== "SKIPPED").slice(0, 8),
toConfirmCount,
categories: categoryMap,
chargeLabels,
};
}
+58
View File
@@ -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),
};
}
+122
View File
@@ -0,0 +1,122 @@
import type { OpKind } from "@prisma/client";
import { addMonths, formatDateFr, fromIsoDate } from "@/lib/dates";
import { formatEuro } from "@/domain/money";
import type { RecurringDef } from "@/domain/recurrence";
import type { Op, Settlement, Split } from "@/domain/types";
import { prisma } from "./db";
import { splitOf, toOp, toRecurringDef, toSettlement } from "./mappers";
export interface UserLite {
id: string;
firstName: string;
color: string;
}
export async function getUsers(): Promise<UserLite[]> {
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<Op[]> {
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<Op[]> {
return getOpsBetween(`${month}-01`, `${addMonths(month, 1)}-01`);
}
export async function getAllActualOps(): Promise<Op[]> {
const rows = await prisma.operation.findMany({ where: { status: "ACTUAL" }, include: { splits: true } });
return rows.map(toOp);
}
export async function getSettlements(): Promise<Settlement[]> {
const rows = await prisma.settlement.findMany({ orderBy: { date: "desc" } });
return rows.map(toSettlement);
}
export async function getRecurringDefs(): Promise<RecurringDef[]> {
const rows = await prisma.recurring.findMany({ include: { splits: true }, orderBy: { label: "asc" } });
return rows.map(toRecurringDef);
}
export async function getDefaultSplit(): Promise<Split> {
const setting = await prisma.setting.findUnique({ where: { id: 1 } });
return (setting?.defaultSplit ?? {}) as Split;
}
/** Charges auxquelles une entrée peut être affectée : récurrents de dépense et dépenses des 3 derniers mois. */
export async function getChargeOptions(today: string) {
const since = `${addMonths(today.slice(0, 7), -3)}-01`;
const [recurrings, ops] = await Promise.all([
prisma.recurring.findMany({ where: { kind: "EXPENSE" }, include: { splits: true }, orderBy: { label: "asc" } }),
prisma.operation.findMany({
where: { kind: "EXPENSE", recurringId: null, status: { not: "SKIPPED" }, date: { gte: fromIsoDate(since) } },
include: { splits: true },
orderBy: { date: "desc" },
take: 100,
}),
]);
return [
...recurrings.map((r) => ({ key: `r:${r.id}`, label: `↻ ${r.label}`, split: splitOf(r.splits) })),
...ops.map((o) => {
const op = toOp(o);
return { key: `o:${o.id}`, label: `${o.label} · ${formatDateFr(op.date)} · ${formatEuro(op.amount)}`, split: op.split };
}),
];
}
/** Données communes au formulaire de saisie. */
export async function getFormData(today: string) {
const [users, categories, defaultSplit, charges] = await Promise.all([
getUsers(),
getCategories(),
getDefaultSplit(),
getChargeOptions(today),
]);
return {
users,
categories: categories.map((c) => ({ id: c.id, name: c.name, emoji: c.emoji, kind: c.kind })),
defaultSplit,
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);
}
+49
View File
@@ -0,0 +1,49 @@
import { centsFromDecimal, decimalFromCents, parseEuro } from "@/domain/money";
import { budgetForMonth } from "@/domain/monthly";
import { addMonths } from "@/lib/dates";
import { prisma } from "../db";
import { getOpsBetween } from "../repo";
import type { Result } from "./operations";
/**
* Fixe le budget d'une catégorie à partir d'un mois (et pour la suite).
* Montant vide ou nul : plus de budget à partir de ce mois.
*/
export async function setBudget(categoryId: string, amount: string, fromMonth: string): Promise<Result> {
const blank = amount.trim() === "" || /^0+([,.]0*)?$/.test(amount.trim());
const cents = blank ? 0 : parseEuro(amount);
if (cents === null) return { ok: false, error: "Montant invalide." };
await prisma.$transaction(async (tx) => {
// Le nouveau budget remplace ceux qui démarraient à ce mois ou plus tard.
await tx.budget.deleteMany({ where: { categoryId, startMonth: { gte: fromMonth } } });
await tx.budget.updateMany({
where: { categoryId, startMonth: { lt: fromMonth }, OR: [{ endMonth: null }, { endMonth: { gte: fromMonth } }] },
data: { endMonth: addMonths(fromMonth, -1) },
});
if (cents > 0) {
await tx.budget.create({ data: { categoryId, monthlyAmount: decimalFromCents(cents), startMonth: fromMonth } });
}
});
return { ok: true };
}
export async function budgetHistory(
categoryId: string,
months: number,
untilMonth: string,
): Promise<{ month: string; budget: number | null; actual: number }[]> {
const first = addMonths(untilMonth, -(months - 1));
const [rows, ops] = await Promise.all([
prisma.budget.findMany({ where: { categoryId } }),
getOpsBetween(`${first}-01`, `${addMonths(untilMonth, 1)}-01`),
]);
const budgets = rows.map((b) => ({ ...b, monthlyAmount: centsFromDecimal(b.monthlyAmount) }));
return Array.from({ length: months }, (_, i) => {
const month = addMonths(first, i);
const actual = ops
.filter((o) => o.categoryId === categoryId && o.kind === "EXPENSE" && o.status === "ACTUAL" && o.date.startsWith(month))
.reduce((t, o) => t + o.amount, 0);
return { month, budget: budgetForMonth(budgets, month)[0]?.amount ?? null, actual };
});
}
+151
View File
@@ -0,0 +1,151 @@
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 };
}
+195
View File
@@ -0,0 +1,195 @@
import { z } from "zod";
import { decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
import type { Split } from "@/domain/types";
import { addMonths, dateInMonth, fromIsoDate, monthOf } from "@/lib/dates";
import { prisma } from "../db";
import { splitRows } from "../mappers";
export type Result<T = object> = ({ ok: true } & T) | { ok: false; error: string };
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date invalide.");
const operationSchema = z.object({
id: z.string().optional(),
kind: z.enum(["INCOME", "EXPENSE"]),
amount: z.string(),
label: z.string().trim().min(1, "Le libellé est obligatoire.").max(190),
categoryId: z.string().min(1, "Choisissez une catégorie."),
date: isoDate,
accountUserId: z.string().min(1),
status: z.enum(["PLANNED", "ACTUAL"]),
split: z.record(z.string(), z.number().int()),
note: z.string().max(2000).optional(),
allocatedToRecurringId: z.string().nullish(),
allocatedToOperationId: z.string().nullish(),
allocationMode: z.enum(["REDUCE_SHARED", "BENEFICIARY_ONLY", "CUSTOM"]).nullish(),
makeRecurring: z
.object({ frequency: z.enum(["MONTHLY", "QUARTERLY", "YEARLY"]), endDate: isoDate.nullable() })
.optional(),
/** Montant annuel lissé : 12 opérations mensuelles d'un douzième (création seulement). */
spreadOverYear: z.boolean().optional(),
});
export type OperationInput = z.input<typeof operationSchema>;
const firstError = (e: z.ZodError) => e.issues[0]?.message ?? "Données invalides.";
/** Création ou modification d'une opération (saisie rapide et édition). */
export async function saveOperation(raw: OperationInput, currentUserId: string): Promise<Result<{ id: string }>> {
const parsed = operationSchema.safeParse(raw);
if (!parsed.success) return { ok: false, error: firstError(parsed.error) };
const input = parsed.data;
const cents = parseEuro(input.amount);
if (cents === null) return { ok: false, error: "Montant invalide." };
const splitError = validateSplit(input.split as Split);
if (splitError) return { ok: false, error: splitError };
const allocatedToRecurringId = input.allocatedToRecurringId || null;
const allocatedToOperationId = input.allocatedToOperationId || null;
const allocated = allocatedToRecurringId !== null || allocatedToOperationId !== null;
if (allocated && input.kind === "EXPENSE") {
return { ok: false, error: "Seule une entrée peut être affectée à une charge." };
}
if (input.spreadOverYear && input.makeRecurring) {
return { ok: false, error: "Un montant annuel lissé ne peut pas être récurrent." };
}
if (input.spreadOverYear && cents < 12) return { ok: false, error: "Montant trop faible pour être lissé sur 12 mois." };
if (allocatedToRecurringId && allocatedToOperationId) {
return { ok: false, error: "Une entrée ne peut être affectée qu'à une seule charge." };
}
const fields = {
kind: input.kind,
amount: decimalFromCents(cents),
label: input.label,
categoryId: input.categoryId,
date: fromIsoDate(input.date),
accountUserId: input.accountUserId,
status: input.status,
note: input.note?.trim() || null,
allocatedToRecurringId,
allocatedToOperationId,
allocationMode: allocated ? (input.allocationMode ?? "REDUCE_SHARED") : null,
};
const splits = splitRows(input.split as Split);
const id = await prisma.$transaction(async (tx) => {
if (input.id) {
await tx.operationSplit.deleteMany({ where: { operationId: input.id } });
await tx.operation.update({ where: { id: input.id }, data: { ...fields, splits: { create: splits } } });
return input.id;
}
if (input.spreadOverYear) {
// Un douzième par mois, même jour (borné à la fin du mois) ; le reste d'arrondi va au premier mois.
const share = Math.floor(cents / 12);
const ids: string[] = [];
for (let i = 0; i < 12; i++) {
const op = await tx.operation.create({
data: {
...fields,
amount: decimalFromCents(i === 0 ? cents - share * 11 : share),
label: `${fields.label.slice(0, 182)} (${i + 1}/12)`,
date: fromIsoDate(dateInMonth(addMonths(monthOf(input.date), i), Number(input.date.slice(8, 10)))),
createdById: currentUserId,
splits: { create: splits },
},
});
ids.push(op.id);
}
return ids[0];
}
let recurring: { recurringId: string; occurrenceDate: Date } | object = {};
if (input.makeRecurring) {
const rec = await tx.recurring.create({
data: {
kind: fields.kind,
amount: fields.amount,
label: fields.label,
categoryId: fields.categoryId,
accountUserId: fields.accountUserId,
frequency: input.makeRecurring.frequency,
dayOfMonth: Number(input.date.slice(8, 10)),
startDate: fields.date,
endDate: input.makeRecurring.endDate ? fromIsoDate(input.makeRecurring.endDate) : null,
allocatedToRecurringId,
allocationMode: allocatedToRecurringId ? fields.allocationMode : null,
splits: { create: splits },
},
});
recurring = { recurringId: rec.id, occurrenceDate: fields.date };
}
const op = await tx.operation.create({
data: { ...fields, ...recurring, createdById: currentUserId, splits: { create: splits } },
});
return op.id;
});
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 };
}
/** Passe une opération prévue en réelle, avec montant et date ajustables. */
export async function confirmOperation(id: string, amount: string, date: string): Promise<Result> {
const cents = parseEuro(amount);
if (cents === null) return { ok: false, error: "Montant invalide." };
if (!isoDate.safeParse(date).success) return { ok: false, error: "Date invalide." };
await prisma.operation.update({
where: { id },
data: { status: "ACTUAL", amount: decimalFromCents(cents), date: fromIsoDate(date) },
});
return { ok: true };
}
/** Occurrence de récurrent : marquée ignorée (pas régénérée). Prévue ponctuelle : supprimée. */
export async function skipOperation(id: string): Promise<Result> {
const op = await prisma.operation.findUniqueOrThrow({ where: { id } });
if (op.recurringId) await prisma.operation.update({ where: { id }, data: { status: "SKIPPED" } });
else await prisma.operation.delete({ where: { id } });
return { ok: true };
}
export async function saveSettlement(input: {
fromUserId: string;
toUserId: string;
amount: string;
date: string;
note?: string;
}): Promise<Result> {
if (input.fromUserId === input.toUserId) return { ok: false, error: "Choisissez deux personnes différentes." };
const cents = parseEuro(input.amount);
if (cents === null) return { ok: false, error: "Montant invalide." };
if (!isoDate.safeParse(input.date).success) return { ok: false, error: "Date invalide." };
await prisma.settlement.create({
data: {
fromUserId: input.fromUserId,
toUserId: input.toUserId,
amount: decimalFromCents(cents),
date: fromIsoDate(input.date),
note: input.note?.trim() || null,
},
});
return { ok: true };
}
export async function deleteSettlement(id: string): Promise<Result> {
await prisma.settlement.deleteMany({ where: { id } });
return { ok: true };
}
+117
View File
@@ -0,0 +1,117 @@
import { z } from "zod";
import { decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
import type { Split } from "@/domain/types";
import { fromIsoDate, todayParis } from "@/lib/dates";
import { prisma } from "../db";
import { splitRows } from "../mappers";
import { syncRecurrings } from "../sync";
import type { Result } from "./operations";
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date invalide.");
const recurringSchema = z.object({
id: z.string().optional(),
kind: z.enum(["INCOME", "EXPENSE"]),
amount: z.string(),
label: z.string().trim().min(1, "Le libellé est obligatoire.").max(190),
categoryId: z.string().min(1, "Choisissez une catégorie."),
accountUserId: z.string().min(1),
split: z.record(z.string(), z.number().int()),
frequency: z.enum(["MONTHLY", "QUARTERLY", "YEARLY"]),
dayOfMonth: z.number().int().min(1, "Jour du mois invalide (1 à 31).").max(31, "Jour du mois invalide (1 à 31)."),
startDate: isoDate,
endDate: isoDate.nullable(),
allocatedToRecurringId: z.string().nullish(),
allocationMode: z.enum(["REDUCE_SHARED", "BENEFICIARY_ONLY", "CUSTOM"]).nullish(),
});
export type RecurringInput = z.input<typeof recurringSchema>;
/** Supprime les occurrences prévues à partir d'une date (les réelles et les prévues passées restent). */
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." };
const input = parsed.data;
const cents = parseEuro(input.amount);
if (cents === null) return { ok: false, error: "Montant invalide." };
const splitError = validateSplit(input.split as Split);
if (splitError) return { ok: false, error: splitError };
if (input.endDate && input.endDate < input.startDate) return { ok: false, error: "La date de fin précède la date de début." };
const allocatedTo = input.kind === "INCOME" ? input.allocatedToRecurringId || null : null;
if (allocatedTo && allocatedTo === input.id) return { ok: false, error: "Un récurrent ne peut pas s'affecter à lui-même." };
if (input.id) {
const existing = await prisma.recurring.findUnique({ where: { id: input.id } });
if (!existing) return { ok: false, error: "Récurrent introuvable." };
if (existing.loanId) return { ok: false, error: "Ce récurrent est géré depuis Crédits." };
}
const data = {
kind: input.kind,
amount: decimalFromCents(cents),
label: input.label,
categoryId: input.categoryId,
accountUserId: input.accountUserId,
frequency: input.frequency,
dayOfMonth: input.dayOfMonth,
startDate: fromIsoDate(input.startDate),
endDate: input.endDate ? fromIsoDate(input.endDate) : null,
allocatedToRecurringId: allocatedTo,
allocationMode: allocatedTo ? (input.allocationMode ?? "REDUCE_SHARED") : null,
};
const id = await prisma.$transaction(async (tx) => {
if (input.id) {
await tx.recurringSplit.deleteMany({ where: { recurringId: input.id } });
await tx.recurring.update({ where: { id: input.id }, data: { ...data, splits: { create: splitRows(input.split as Split) } } });
return input.id;
}
return (await tx.recurring.create({ data: { ...data, splits: { create: splitRows(input.split as Split) } } })).id;
});
await dropPlannedWithAllocations(id, today);
await syncRecurrings(today);
return { ok: true, id };
}
export async function setRecurringPaused(id: string, paused: boolean, today: string = todayParis()): Promise<Result> {
await prisma.recurring.update({ where: { id }, data: { paused } });
if (paused) await dropPlannedFrom(id, today);
else await syncRecurrings(today);
return { ok: true };
}
export async function endRecurring(id: string, endDate: string, today: string = todayParis()): Promise<Result> {
if (!isoDate.safeParse(endDate).success) return { ok: false, error: "Date invalide." };
await prisma.recurring.update({ where: { id }, data: { endDate: fromIsoDate(endDate) } });
await prisma.operation.deleteMany({ where: { recurringId: id, status: "PLANNED", date: { gt: fromIsoDate(endDate) } } });
await syncRecurrings(today);
return { ok: true };
}
export async function deleteRecurring(id: string, today: string = todayParis()): Promise<Result> {
const rec = await prisma.recurring.findUnique({ where: { id } });
if (rec?.loanId) return { ok: false, error: "Ce récurrent est géré depuis Crédits." };
await dropPlannedFrom(id, today);
await prisma.recurring.delete({ where: { id } });
return { ok: true };
}
+62
View File
@@ -0,0 +1,62 @@
import { Prisma } from "@prisma/client";
import { validateSplit } from "@/domain/money";
import type { OpKind, Split } from "@/domain/types";
import { hashPassword, validatePassword, verifyPassword } from "../auth";
import { prisma } from "../db";
import type { Result } from "./operations";
const isUniqueViolation = (e: unknown) => e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002";
export async function updateUser(id: string, input: { firstName: string; color: string; login: string }): Promise<Result> {
const firstName = input.firstName.trim();
const login = input.login.trim().toLowerCase();
if (!firstName) return { ok: false, error: "Le prénom est obligatoire." };
if (!/^[a-z0-9._-]+$/.test(login)) return { ok: false, error: "Identifiant invalide (lettres, chiffres, . _ -)." };
if (!/^#[0-9a-f]{6}$/i.test(input.color)) return { ok: false, error: "Couleur invalide." };
try {
await prisma.user.update({ where: { id }, data: { firstName, login, color: input.color } });
} catch (e) {
if (isUniqueViolation(e)) return { ok: false, error: "Cet identifiant est déjà utilisé." };
throw e;
}
return { ok: true };
}
export async function changePassword(id: string, current: string, next: string): Promise<Result> {
const user = await prisma.user.findUniqueOrThrow({ where: { id } });
if (!(await verifyPassword(current, user.passwordHash))) return { ok: false, error: "Mot de passe actuel incorrect." };
const error = validatePassword(next, next);
if (error) return { ok: false, error };
await prisma.user.update({ where: { id }, data: { passwordHash: await hashPassword(next) } });
return { ok: true };
}
export async function setDefaultSplit(split: Split): Promise<Result> {
const error = validateSplit(split);
if (error) return { ok: false, error };
await prisma.setting.upsert({ where: { id: 1 }, update: { defaultSplit: split }, create: { id: 1, defaultSplit: split } });
return { ok: true };
}
export async function saveCategory(input: { id?: string; name: string; emoji: string; kind: OpKind }): Promise<Result<{ id: string }>> {
const name = input.name.trim();
if (!name) return { ok: false, error: "Le nom est obligatoire." };
const data = { name, emoji: input.emoji.trim() || "•", kind: input.kind };
try {
if (input.id) {
await prisma.category.update({ where: { id: input.id }, data });
return { ok: true, id: input.id };
}
const last = await prisma.category.aggregate({ _max: { sortOrder: true } });
const created = await prisma.category.create({ data: { ...data, sortOrder: (last._max.sortOrder ?? 0) + 1 } });
return { ok: true, id: created.id };
} catch (e) {
if (isUniqueViolation(e)) return { ok: false, error: "Cette catégorie existe déjà." };
throw e;
}
}
export async function archiveCategory(id: string, archived: boolean): Promise<Result> {
await prisma.category.update({ where: { id }, data: { archived } });
return { ok: true };
}
+50
View File
@@ -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<number> {
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;
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { opsToCsv } from "@/server/csv";
import { op } from "./fixtures";
const users = [
{ id: "H", firstName: "H" },
{ id: "C", firstName: "C" },
];
const categories = { courses: { name: "Courses" }, salaire: { name: "Salaire" } };
describe("opsToCsv", () => {
const groceries = op({ kind: "EXPENSE", amount: 8640, accountUserId: "C", label: "Carrefour; Bio", categoryId: "courses", date: "2026-10-27" });
it("starts with a BOM and a French header", () => {
const csv = opsToCsv([groceries], users, categories, {});
expect(csv.startsWith("\uFEFFDate;Type;Libellé;Catégorie;Montant;Payé par;Statut;Part H %;Part C %;Affecté à;Note\r\n")).toBe(true);
});
it("quotes fields with separators and uses comma decimals", () => {
const lines = opsToCsv([groceries], users, categories, {}).split("\r\n");
expect(lines[1]).toBe('27/10/2026;Dépense;"Carrefour; Bio";Courses;-86,40;C;Réel;50;50;;');
});
it("writes incomes positive, planned status, allocation label and escaped notes", () => {
const refund = {
...op({ kind: "INCOME" as const, amount: 20000, accountUserId: "H", label: "Employeur", categoryId: "salaire", status: "PLANNED" as const, allocatedToRecurringId: "rent", date: "2026-10-05" }),
note: 'part "loyer"',
};
const lines = opsToCsv([refund], users, categories, { rent: "Loyer" }).split("\r\n");
expect(lines[1]).toBe('05/10/2026;Entrée;Employeur;Salaire;200,00;H;Prévu;50;50;Loyer;"part ""loyer"""');
});
it("excludes skipped operations", () => {
const skipped = op({ kind: "EXPENSE", amount: 100, accountUserId: "H", status: "SKIPPED" });
expect(opsToCsv([skipped], users, categories, {}).split("\r\n").filter(Boolean)).toHaveLength(1);
});
});
+22
View File
@@ -8,9 +8,23 @@ import {
parseEuro, parseEuro,
percentToBp, percentToBp,
shareAmounts, shareAmounts,
splitFromAmounts,
validateSplit, validateSplit,
} from "@/domain/money"; } from "@/domain/money";
describe("splitFromAmounts", () => {
it("turns the amount each person pays into basis points summing to 100 %", () => {
expect(splitFromAmounts({ h: 60000, s: 39000 }, 99000)).toEqual({ h: 6061, s: 3939 });
expect(splitFromAmounts({ a: 10000, b: 10000, c: 10000 }, 30000)).toEqual({ a: 3334, b: 3333, c: 3333 });
expect(splitFromAmounts({ h: 99000, s: 0 }, 99000)).toEqual({ h: 10000, s: 0 });
});
it("returns null when the amounts do not add up to the total", () => {
expect(splitFromAmounts({ h: 50000, s: 39000 }, 99000)).toBeNull();
expect(splitFromAmounts({ h: 0, s: 0 }, 0)).toBeNull();
});
});
const fr = (n: number) => const fr = (n: number) =>
new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(n); new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(n);
@@ -25,6 +39,14 @@ describe("parseEuro", () => {
expect(parseEuro("0,5")).toBe(50); expect(parseEuro("0,5")).toBe(50);
}); });
it("accepts a euro sign and dots as thousands separators", () => {
expect(parseEuro("40 000 €")).toBe(4000000);
expect(parseEuro("40000€")).toBe(4000000);
expect(parseEuro("40.000")).toBe(4000000);
expect(parseEuro("1.234.567")).toBe(123456700);
expect(parseEuro("40.000,50")).toBe(4000050);
});
it("rejects empty, zero, negative and malformed amounts", () => { it("rejects empty, zero, negative and malformed amounts", () => {
for (const s of ["", "0", "0,00", "-5", "abc", "12,345", "1,2,3"]) expect(parseEuro(s)).toBeNull(); for (const s of ["", "0", "0,00", "-5", "abc", "12,345", "1,2,3"]) expect(parseEuro(s)).toBeNull();
}); });
+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 { beforeEach, describe, expect, it } from "vitest";
import { computeBalances, describeBalance } from "@/domain/balance";
import { createHousehold, hashPassword, verifyPassword } from "@/server/auth"; import { createHousehold, hashPassword, verifyPassword } from "@/server/auth";
import { toSettlement } from "@/server/mappers";
import { prisma } from "@/server/db"; import { prisma } from "@/server/db";
import { resetDb } from "./helpers"; import { resetDb } from "./helpers";
@@ -33,9 +35,14 @@ describe("createHousehold", () => {
const setting = await prisma.setting.findUniqueOrThrow({ where: { id: 1 } }); const setting = await prisma.setting.findUniqueOrThrow({ where: { id: 1 } });
expect(setting.defaultSplit).toEqual({ [users[0].id]: 6000, [users[1].id]: 4000 }); expect(setting.defaultSplit).toEqual({ [users[0].id]: 6000, [users[1].id]: 4000 });
const s = await prisma.settlement.findFirstOrThrow(); 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"); 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 () => { it("skips the opening balance when empty", async () => {
+61
View File
@@ -0,0 +1,61 @@
import { beforeEach, describe, expect, it } from "vitest";
import { budgetForMonth } from "@/domain/monthly";
import { centsFromDecimal } from "@/domain/money";
import { prisma } from "@/server/db";
import { budgetHistory, setBudget } from "@/server/services/budgets";
import { saveOperation } from "@/server/services/operations";
import { categoryId, makeUsers, resetDb } from "./helpers";
let courses: string;
const active = async (month: string) => {
const rows = await prisma.budget.findMany();
return budgetForMonth(rows.map((b) => ({ ...b, monthlyAmount: centsFromDecimal(b.monthlyAmount) })), month);
};
beforeEach(async () => {
await resetDb();
courses = await categoryId("Courses");
});
describe("setBudget", () => {
it("starts a new budget from a month and keeps the previous one before it", async () => {
await setBudget(courses, "400", "2026-10");
await setBudget(courses, "450", "2027-01");
expect(await active("2026-12")).toEqual([{ categoryId: courses, amount: 40000 }]);
expect(await active("2027-01")).toEqual([{ categoryId: courses, amount: 45000 }]);
});
it("updates in place when the start month is the same", async () => {
await setBudget(courses, "400", "2026-10");
await setBudget(courses, "420", "2026-10");
expect(await prisma.budget.count()).toBe(1);
expect(await active("2026-10")).toEqual([{ categoryId: courses, amount: 42000 }]);
});
it("closes the budget with an empty or zero amount", async () => {
await setBudget(courses, "400", "2026-10");
await setBudget(courses, "0", "2027-03");
expect(await active("2027-03")).toEqual([]);
expect(await active("2027-02")).toEqual([{ categoryId: courses, amount: 40000 }]);
});
it("rejects an invalid amount", async () => {
expect(await setBudget(courses, "abc", "2026-10")).toEqual({ ok: false, error: "Montant invalide." });
});
});
describe("budgetHistory", () => {
it("returns budget and actual spending month by month, oldest first", async () => {
const { h, c } = await makeUsers();
await setBudget(courses, "400", "2026-09");
await saveOperation(
{ kind: "EXPENSE", amount: "100", label: "Courses", categoryId: courses, date: "2026-10-03", accountUserId: h.id, status: "ACTUAL", split: { [h.id]: 5000, [c.id]: 5000 } },
h.id,
);
const hist = await budgetHistory(courses, 6, "2026-10");
expect(hist.map((x) => x.month)).toEqual(["2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10"]);
expect(hist[3]).toEqual({ month: "2026-08", budget: null, actual: 0 });
expect(hist[5]).toEqual({ month: "2026-10", budget: 40000, actual: 10000 });
});
});
+87
View File
@@ -0,0 +1,87 @@
import { beforeEach, describe, expect, it } from "vitest";
import { formatEuro } from "@/domain/money";
import { loadDashboard } from "@/server/dashboard";
import { prisma } from "@/server/db";
import { saveOperation } from "@/server/services/operations";
import { categoryId, makeUsers, resetDb } from "./helpers";
let H: string;
let C: string;
async function add(input: Parameters<typeof saveOperation>[0]) {
const r = await saveOperation(input, H);
if (!r.ok) throw new Error(r.error);
return r.id;
}
beforeEach(async () => {
await resetDb();
const users = await makeUsers();
H = users.h.id;
C = users.c.id;
const half = { [H]: 5000, [C]: 5000 };
const allH = { [H]: 10000, [C]: 0 };
const base = { status: "ACTUAL" as const, date: "2026-10-15" };
await add({ ...base, kind: "INCOME", amount: "3000", label: "Salaire", categoryId: await categoryId("Salaire"), accountUserId: H, split: allH, date: "2026-10-25" });
await add({ ...base, kind: "INCOME", amount: "2000", label: "Salaire", categoryId: await categoryId("Salaire"), accountUserId: C, split: { [H]: 0, [C]: 10000 }, date: "2026-10-25" });
await add({
...base,
kind: "EXPENSE",
amount: "1000",
label: "Loyer",
categoryId: await categoryId("Logement"),
accountUserId: H,
split: half,
date: "2026-10-05",
makeRecurring: { frequency: "MONTHLY", endDate: null },
});
const rent = await prisma.recurring.findFirstOrThrow();
await add({
...base,
kind: "INCOME",
amount: "200",
label: "Part loyer employeur",
categoryId: await categoryId("Remboursement employeur"),
accountUserId: H,
split: half,
allocatedToRecurringId: rent.id,
allocationMode: "REDUCE_SHARED",
});
await add({ ...base, kind: "EXPENSE", amount: "86,40", label: "Carrefour", categoryId: await categoryId("Courses"), accountUserId: C, split: half, date: "2026-10-27" });
await add({ ...base, kind: "EXPENSE", amount: "350", label: "Révision", categoryId: await categoryId("Auto"), accountUserId: H, split: allH, status: "PLANNED", date: "2026-10-30" });
await prisma.budget.create({ data: { categoryId: await categoryId("Courses"), monthlyAmount: "400", startMonth: "2026-01" } });
});
describe("loadDashboard", () => {
it("phrases the balance from the viewer's point of view", async () => {
// H : loyer +500, employeur −100, courses payées par C −43,20 = 356,80 €
expect((await loadDashboard("2026-10", H, "2026-10-27")).balance?.text).toBe(`C te doit ${formatEuro(35680)}`);
expect((await loadDashboard("2026-10", C, "2026-10-27")).balance?.text).toBe(`Tu dois ${formatEuro(35680)} à H`);
});
it("assembles flows, totals, budgets, net charges and recent operations", async () => {
const d = await loadDashboard("2026-10", H, "2026-10-27");
expect(d.persons.map((p) => p.user.firstName)).toEqual(["H", "C"]);
// H : revenus propres 3000 − (500 + 43,20 − 100) = 2556,80
expect(d.persons[0].flows.remaining).toBe(255680);
expect(d.totals.plannedExpense).toBe(35000);
expect(d.budgets).toEqual([
expect.objectContaining({ name: "Courses", emoji: "🛒", budget: 40000, actual: 8640, over: false }),
]);
expect(d.netCharges).toEqual([expect.objectContaining({ label: "Loyer", gross: 100000, reimbursed: 20000, net: 80000 })]);
expect(d.recent[0].label).toBe("Révision");
expect(d.recent.length).toBeLessThanOrEqual(8);
expect(d.toConfirmCount).toBe(0);
expect((await loadDashboard("2026-10", H, "2026-10-31")).toConfirmCount).toBe(1);
});
it("reports a balanced household", async () => {
await prisma.settlement.create({
data: { fromUserId: C, toUserId: H, amount: "356.80", date: new Date("2026-10-28T00:00:00Z") },
});
const d = await loadDashboard("2026-10", H, "2026-10-28");
expect(d.balance?.text).toBe("Vous êtes à l'équilibre");
expect(d.lastSettlementDate).toBe("2026-10-28");
});
});
+78
View File
@@ -0,0 +1,78 @@
import { beforeEach, describe, expect, it } from "vitest";
import { prisma } from "@/server/db";
import { deleteLoan, saveLoan, type LoanFormInput } from "@/server/services/loans";
import { makeUsers, resetDb } from "./helpers";
const TODAY = "2026-10-27";
let input: LoanFormInput;
beforeEach(async () => {
await resetDb();
const { h, c } = await makeUsers();
input = {
name: "Crédit voiture",
lender: "Banque",
principal: "20000",
annualRate: "4",
durationMonths: 48,
startDate: "2026-01-05",
insuranceMonthly: "15",
accountUserId: h.id,
split: { [h.id]: 10000, [c.id]: 0 },
paymentOverride: "",
referenceDate: "",
referenceRemainingCapital: "",
};
});
describe("saveLoan", () => {
it("creates the loan's monthly recurring, without retroactive occurrences", async () => {
const r = await saveLoan(input, TODAY);
if (!r.ok) throw new Error(r.error);
const rec = await prisma.recurring.findFirstOrThrow({ where: { loanId: r.id }, include: { category: true } });
expect(rec.amount.toString()).toBe("466.58");
expect(rec.endDate?.toISOString().slice(0, 10)).toBe("2029-12-05");
expect(rec.category.name).toBe("Crédit");
const first = await prisma.operation.findFirstOrThrow({ where: { recurringId: rec.id }, orderBy: { date: "asc" } });
expect(first.date.toISOString().slice(0, 10)).toBe("2026-10-05");
});
it("follows the bank's figures for a loan already running", async () => {
const r = await saveLoan(input, TODAY);
if (!r.ok) throw new Error(r.error);
await saveLoan(
{ ...input, id: r.id, referenceDate: "2026-06-10", referenceRemainingCapital: "18000", paymentOverride: "460" },
TODAY,
);
const rec = await prisma.recurring.findFirstOrThrow({ where: { loanId: r.id } });
expect(rec.amount.toString()).toBe("475");
const future = await prisma.operation.findMany({
where: { recurringId: rec.id, status: "PLANNED", date: { gte: new Date("2026-10-27T00:00:00Z") } },
});
expect(future.length).toBeGreaterThan(0);
expect(future.every((o) => o.amount.toString() === "475")).toBe(true);
});
it("rejects a payment that cannot cover the interest", async () => {
const r = await saveLoan({ ...input, referenceDate: "2026-06-10", referenceRemainingCapital: "18000", paymentOverride: "50" }, TODAY);
expect(r).toEqual({ ok: false, error: "Mensualité insuffisante pour couvrir les intérêts" });
});
it("validates the rate and the capital", async () => {
expect(await saveLoan({ ...input, annualRate: "abc" }, TODAY)).toEqual({ ok: false, error: "Taux invalide." });
expect(await saveLoan({ ...input, principal: "0" }, TODAY)).toEqual({ ok: false, error: "Capital emprunté invalide (ex. 40000 ou 40 000,00)." });
});
});
describe("deleteLoan", () => {
it("removes the loan and its recurring but keeps actual history", async () => {
const r = await saveLoan(input, TODAY);
if (!r.ok) throw new Error(r.error);
await prisma.operation.updateMany({ where: { date: new Date("2026-10-05T00:00:00Z") }, data: { status: "ACTUAL" } });
await deleteLoan(r.id, TODAY);
expect(await prisma.loan.count()).toBe(0);
expect(await prisma.recurring.count()).toBe(0);
expect(await prisma.operation.count({ where: { status: "ACTUAL" } })).toBe(1);
expect(await prisma.operation.count({ where: { status: "PLANNED", date: { gte: new Date("2026-10-27T00:00:00Z") } } })).toBe(0);
});
});
+205
View File
@@ -0,0 +1,205 @@
import { beforeEach, describe, expect, it } from "vitest";
import { prisma } from "@/server/db";
import {
confirmOperation,
deleteOperation,
saveOperation,
deleteSettlement,
saveSettlement,
skipOperation,
type OperationInput,
} from "@/server/services/operations";
import { syncRecurrings } from "@/server/sync";
import { categoryId, makeUsers, resetDb } from "./helpers";
let H: string;
let C: string;
let courses: string;
let salaire: string;
const expense = (over: Partial<OperationInput> = {}): OperationInput => ({
kind: "EXPENSE",
amount: "86,40",
label: "Carrefour",
categoryId: courses,
date: "2026-10-27",
accountUserId: C,
status: "ACTUAL",
split: { [H]: 5000, [C]: 5000 },
...over,
});
beforeEach(async () => {
await resetDb();
const { h, c } = await makeUsers();
H = h.id;
C = c.id;
courses = await categoryId("Courses");
salaire = await categoryId("Salaire");
});
describe("saveOperation", () => {
it("stores a French amount with its split", async () => {
const r = await saveOperation(expense(), H);
expect(r).toMatchObject({ ok: true });
const op = await prisma.operation.findFirstOrThrow({ include: { splits: true } });
expect(op.amount.toString()).toBe("86.4");
expect(op.createdById).toBe(H);
expect(op.splits).toHaveLength(2);
});
it("rejects a split that does not sum to 100 %", async () => {
expect(await saveOperation(expense({ split: { [H]: 3333, [C]: 3333 } }), H)).toEqual({
ok: false,
error: "La répartition doit totaliser 100 %.",
});
});
it("rejects a zero amount", async () => {
expect(await saveOperation(expense({ amount: "0" }), H)).toEqual({ ok: false, error: "Montant invalide." });
});
it("rejects an allocation on an expense", async () => {
const r = await saveOperation(expense({ allocatedToRecurringId: "x", allocationMode: "REDUCE_SHARED" }), H);
expect(r).toEqual({ ok: false, error: "Seule une entrée peut être affectée à une charge." });
});
it("replaces splits on update", async () => {
const r = await saveOperation(expense(), H);
if (!r.ok) throw new Error(r.error);
await saveOperation(expense({ id: r.id, split: { [H]: 0, [C]: 10000 } }), H);
const splits = await prisma.operationSplit.findMany({ where: { operationId: r.id }, orderBy: { basisPoints: "asc" } });
expect(splits.map((s) => s.basisPoints)).toEqual([0, 10000]);
});
it("keeps an allocated income when its target expense is deleted", async () => {
const hotel = await saveOperation(expense({ label: "Hôtel", amount: "150" }), H);
if (!hotel.ok) throw new Error(hotel.error);
const refund = await saveOperation(
{
kind: "INCOME",
amount: "150",
label: "Note de frais",
categoryId: salaire,
date: "2026-10-28",
accountUserId: H,
status: "ACTUAL",
split: { [H]: 5000, [C]: 5000 },
allocatedToOperationId: hotel.id,
allocationMode: "REDUCE_SHARED",
},
H,
);
if (!refund.ok) throw new Error(refund.error);
await deleteOperation(hotel.id);
const kept = await prisma.operation.findUniqueOrThrow({ where: { id: refund.id } });
expect(kept.allocatedToOperationId).toBeNull();
});
it("creates a recurring template with this operation as its first occurrence", async () => {
const r = await saveOperation(expense({ makeRecurring: { frequency: "MONTHLY", endDate: null } }), H);
if (!r.ok) throw new Error(r.error);
const rec = await prisma.recurring.findFirstOrThrow({ include: { splits: true } });
expect(rec.dayOfMonth).toBe(27);
expect(rec.splits).toHaveLength(2);
const op = await prisma.operation.findUniqueOrThrow({ where: { id: r.id } });
expect(op.recurringId).toBe(rec.id);
expect(op.occurrenceDate?.toISOString().slice(0, 10)).toBe("2026-10-27");
expect(await syncRecurrings("2026-10-27")).toBe(11);
});
});
describe("saveOperation with an annual amount spread over 12 months", () => {
const dividends = (over: Partial<OperationInput> = {}): OperationInput => ({
kind: "INCOME",
amount: "1000",
label: "Dividendes",
categoryId: salaire,
date: "2026-10-31",
accountUserId: H,
status: "ACTUAL",
split: { [H]: 10000, [C]: 0 },
spreadOverYear: true,
...over,
});
it("creates 12 monthly entries summing to the annual amount", async () => {
expect(await saveOperation(dividends(), H)).toMatchObject({ ok: true });
const ops = await prisma.operation.findMany({ orderBy: { date: "asc" }, include: { splits: true } });
expect(ops).toHaveLength(12);
expect(ops.map((o) => o.date.toISOString().slice(0, 10)).slice(0, 5)).toEqual([
"2026-10-31",
"2026-11-30",
"2026-12-31",
"2027-01-31",
"2027-02-28",
]);
expect(ops[11].date.toISOString().slice(0, 10)).toBe("2027-09-30");
expect(ops.map((o) => o.amount.toString())).toEqual(["83.37", ...Array(11).fill("83.33")]);
expect(ops[0].label).toBe("Dividendes (1/12)");
expect(ops[11].label).toBe("Dividendes (12/12)");
expect(ops.every((o) => o.status === "ACTUAL" && o.splits.length === 2 && o.recurringId === null)).toBe(true);
});
it("cannot also be recurring", async () => {
expect(await saveOperation(dividends({ makeRecurring: { frequency: "MONTHLY", endDate: null } }), H)).toEqual({
ok: false,
error: "Un montant annuel lissé ne peut pas être récurrent.",
});
});
});
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);
if (!r.ok) throw new Error(r.error);
expect(await confirmOperation(r.id, "90", "2026-10-29")).toEqual({ ok: true });
const op = await prisma.operation.findUniqueOrThrow({ where: { id: r.id } });
expect(op.status).toBe("ACTUAL");
expect(op.amount.toString()).toBe("90");
expect(op.date.toISOString().slice(0, 10)).toBe("2026-10-29");
});
it("marks a recurring occurrence skipped but deletes a one-off", async () => {
const rec = await saveOperation(expense({ status: "PLANNED", makeRecurring: { frequency: "MONTHLY", endDate: null } }), H);
const oneOff = await saveOperation(expense({ status: "PLANNED" }), H);
if (!rec.ok || !oneOff.ok) throw new Error("setup");
await skipOperation(rec.id);
await skipOperation(oneOff.id);
expect((await prisma.operation.findUniqueOrThrow({ where: { id: rec.id } })).status).toBe("SKIPPED");
expect(await prisma.operation.findUnique({ where: { id: oneOff.id } })).toBeNull();
});
});
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 });
expect(await prisma.settlement.count()).toBe(1);
expect(await saveSettlement({ fromUserId: H, toUserId: H, amount: "10", date: "2026-10-27" })).toEqual({
ok: false,
error: "Choisissez deux personnes différentes.",
});
});
});
+115
View File
@@ -0,0 +1,115 @@
import { beforeEach, describe, expect, it } from "vitest";
import { fromIsoDate } from "@/lib/dates";
import { prisma } from "@/server/db";
import { deleteRecurring, endRecurring, saveRecurring, setRecurringPaused, type RecurringInput } from "@/server/services/recurrings";
import { categoryId, makeUsers, resetDb } from "./helpers";
const TODAY = "2026-10-27";
let H: string;
let C: string;
let rentInput: RecurringInput;
const planned = (recurringId: string) =>
prisma.operation.findMany({ where: { recurringId, status: "PLANNED" }, orderBy: { date: "asc" } });
beforeEach(async () => {
await resetDb();
const u = await makeUsers();
H = u.h.id;
C = u.c.id;
rentInput = {
kind: "EXPENSE",
amount: "1000",
label: "Loyer",
categoryId: await categoryId("Logement"),
accountUserId: H,
split: { [H]: 5000, [C]: 5000 },
frequency: "MONTHLY",
dayOfMonth: 5,
startDate: "2026-01-05",
endDate: null,
};
});
describe("saveRecurring", () => {
it("creates the template and its planned occurrences", async () => {
const r = await saveRecurring(rentInput, TODAY);
if (!r.ok) throw new Error(r.error);
expect(await planned(r.id)).toHaveLength(12);
});
it("applies an edit to future occurrences only", async () => {
const r = await saveRecurring(rentInput, TODAY);
if (!r.ok) throw new Error(r.error);
await prisma.operation.updateMany({ where: { recurringId: r.id, date: fromIsoDate("2026-10-05") }, data: { status: "ACTUAL" } });
await saveRecurring({ ...rentInput, id: r.id, amount: "1050" }, TODAY);
const october = await prisma.operation.findFirstOrThrow({ where: { recurringId: r.id, date: fromIsoDate("2026-10-05") } });
expect(october.amount.toString()).toBe("1000");
const future = await planned(r.id);
expect(future[0].date.toISOString().slice(0, 10)).toBe("2026-11-05");
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)." });
});
});
describe("pause / end / delete", () => {
it("pausing removes future occurrences and resuming brings them back", async () => {
const r = await saveRecurring(rentInput, TODAY);
if (!r.ok) throw new Error(r.error);
await prisma.operation.updateMany({ where: { recurringId: r.id, date: fromIsoDate("2026-10-05") }, data: { status: "ACTUAL" } });
await setRecurringPaused(r.id, true, TODAY);
expect((await planned(r.id)).filter((o) => o.date >= fromIsoDate(TODAY))).toHaveLength(0);
await setRecurringPaused(r.id, false, TODAY);
expect(await planned(r.id)).toHaveLength(11);
});
it("ending stops occurrences after the end date", async () => {
const r = await saveRecurring(rentInput, TODAY);
if (!r.ok) throw new Error(r.error);
await endRecurring(r.id, "2027-01-31", TODAY);
const rest = await planned(r.id);
expect(rest[rest.length - 1].date.toISOString().slice(0, 10)).toBe("2027-01-05");
});
it("deleting keeps actual history", async () => {
const r = await saveRecurring(rentInput, TODAY);
if (!r.ok) throw new Error(r.error);
await prisma.operation.updateMany({ where: { recurringId: r.id, date: fromIsoDate("2026-10-05") }, data: { status: "ACTUAL" } });
await deleteRecurring(r.id, TODAY);
expect(await prisma.recurring.count()).toBe(0);
expect(await prisma.operation.count({ where: { status: "ACTUAL" } })).toBe(1);
expect(await prisma.operation.count({ where: { status: "PLANNED", date: { gte: fromIsoDate(TODAY) } } })).toBe(0);
});
});
+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([]);
});
});
+51
View File
@@ -0,0 +1,51 @@
import { beforeEach, describe, expect, it } from "vitest";
import { hashPassword, verifyPassword } from "@/server/auth";
import { prisma } from "@/server/db";
import { archiveCategory, changePassword, saveCategory, setDefaultSplit, updateUser } from "@/server/services/settings";
import { 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;
});
describe("settings", () => {
it("renames a person and rejects a login already taken", async () => {
expect(await updateUser(H, { firstName: "Hugues", color: "#111111", login: "hugues" })).toEqual({ ok: true });
expect((await prisma.user.findUniqueOrThrow({ where: { id: H } })).firstName).toBe("Hugues");
expect(await updateUser(C, { firstName: "Léa", color: "#db2777", login: "hugues" })).toEqual({
ok: false,
error: "Cet identifiant est déjà utilisé.",
});
});
it("changes a password only with the current one", async () => {
await prisma.user.update({ where: { id: H }, data: { passwordHash: await hashPassword("ancien-mdp") } });
expect(await changePassword(H, "faux", "nouveau-mdp")).toEqual({ ok: false, error: "Mot de passe actuel incorrect." });
expect(await changePassword(H, "ancien-mdp", "court")).toEqual({ ok: false, error: "Le mot de passe doit faire au moins 8 caractères." });
expect(await changePassword(H, "ancien-mdp", "nouveau-mdp")).toEqual({ ok: true });
const user = await prisma.user.findUniqueOrThrow({ where: { id: H } });
expect(await verifyPassword("nouveau-mdp", user.passwordHash)).toBe(true);
});
it("stores a valid default split only", async () => {
expect(await setDefaultSplit({ [H]: 6000, [C]: 4000 })).toEqual({ ok: true });
expect((await prisma.setting.findUniqueOrThrow({ where: { id: 1 } })).defaultSplit).toEqual({ [H]: 6000, [C]: 4000 });
expect(await setDefaultSplit({ [H]: 6000, [C]: 3000 })).toEqual({ ok: false, error: "La répartition doit totaliser 100 %." });
});
it("creates, renames and archives categories", async () => {
const r = await saveCategory({ name: "Animaux", emoji: "🐶", kind: "EXPENSE" });
if (!r.ok) throw new Error(r.error);
await saveCategory({ id: r.id, name: "Chat", emoji: "🐱", kind: "EXPENSE" });
await archiveCategory(r.id, true);
const cat = await prisma.category.findUniqueOrThrow({ where: { id: r.id } });
expect([cat.name, cat.emoji, cat.archived]).toEqual(["Chat", "🐱", true]);
expect(await saveCategory({ name: "Courses", emoji: "🛒", kind: "EXPENSE" })).toEqual({ ok: false, error: "Cette catégorie existe déjà." });
});
});
+66
View File
@@ -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");
});
});