Compare commits

..
21 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
YugonitoandClaude Opus 5.5 23f3192cd0 feat: auth, first-run setup, login
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:12:41 +01:00
YugonitoandClaude Opus 5.5 d722c0034c feat(domain): recurrence dates and occurrence planning
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:00:51 +01:00
YugonitoandClaude Opus 5.5 9fb4aab887 feat(domain): loan amortization schedule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:00:07 +01:00
YugonitoandClaude Opus 5.5 1c7b1a53e4 feat(domain): monthly flows, totals, net charges, budgets
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:59:12 +01:00
YugonitoandClaude Opus 5.5 89bf2a821c feat(domain): balance between people
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:58:21 +01:00
YugonitoandClaude Opus 5.5 5ce5363f50 feat(domain): money parsing/formatting and splits
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:57:50 +01:00
YugonitoandClaude Opus 5.5 8d41c2fffe chore: scaffold Next.js + Prisma schema + dev MariaDB
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:57:05 +01:00
121 changed files with 16101 additions and 0 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
+10
View File
@@ -0,0 +1,10 @@
# --- 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"
TEST_DATABASE_URL="mysql://root:dev@localhost:3307/finances_test"
+3
View File
@@ -0,0 +1,3 @@
* text=auto eol=lf
*.ico binary
*.png binary
+3
View File
@@ -4,3 +4,6 @@ node_modules/
.env
backups/
*.log
next-env.d.ts
*.tsbuildinfo
/dist
+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.
+14
View File
@@ -0,0 +1,14 @@
# Base MariaDB locale pour le développement et les tests (port 3307).
services:
db:
image: mariadb:latest
environment:
MARIADB_ROOT_PASSWORD: dev
MARIADB_DATABASE: finances
ports:
- "3307:3306"
volumes:
- ./docker/dev-init.sql:/docker-entrypoint-initdb.d/dev-init.sql:ro
- dev_db:/var/lib/mysql
volumes:
dev_db:
+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
+1
View File
@@ -0,0 +1 @@
CREATE DATABASE IF NOT EXISTS finances_test;
+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
+25
View File
@@ -0,0 +1,25 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
{
ignores: [
"node_modules/**",
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
],
},
];
export default eslintConfig;
+7
View File
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;
+8765
View File
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
{
"name": "hcl-finances-manager",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
"test": "vitest run",
"db:migrate": "prisma migrate dev",
"db:seed": "tsx prisma/seed.ts"
},
"dependencies": {
"@prisma/client": "^6.19.3",
"bcryptjs": "^3.0.3",
"iron-session": "^9.0.1",
"next": "15.5.28",
"prisma": "^6.19.3",
"react": "19.1.0",
"react-dom": "19.1.0",
"recharts": "^3.10.1",
"zod": "^4.6.7"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/bcryptjs": "^2.4.6",
"@types/node": "^24.19.2",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.5.28",
"playwright": "^1.64.1",
"tailwindcss": "^4",
"tsx": "^4.23.15",
"typescript": "^5",
"vitest": "^5.0.5"
},
"prisma": {
"seed": "tsx prisma/seed.ts"
}
}
+5
View File
@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;
@@ -0,0 +1,210 @@
-- CreateTable
CREATE TABLE `User` (
`id` VARCHAR(191) NOT NULL,
`firstName` VARCHAR(191) NOT NULL,
`login` VARCHAR(191) NOT NULL,
`passwordHash` VARCHAR(191) NOT NULL,
`color` VARCHAR(191) NOT NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE INDEX `User_login_key`(`login`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Setting` (
`id` INTEGER NOT NULL DEFAULT 1,
`defaultSplit` JSON NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Category` (
`id` VARCHAR(191) NOT NULL,
`name` VARCHAR(191) NOT NULL,
`emoji` VARCHAR(191) NOT NULL,
`kind` ENUM('INCOME', 'EXPENSE') NOT NULL,
`archived` BOOLEAN NOT NULL DEFAULT false,
`sortOrder` INTEGER NOT NULL DEFAULT 0,
UNIQUE INDEX `Category_name_kind_key`(`name`, `kind`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Operation` (
`id` VARCHAR(191) NOT NULL,
`kind` ENUM('INCOME', 'EXPENSE') NOT NULL,
`amount` DECIMAL(12, 2) NOT NULL,
`date` DATE NOT NULL,
`label` VARCHAR(191) NOT NULL,
`note` TEXT NULL,
`categoryId` VARCHAR(191) NOT NULL,
`accountUserId` VARCHAR(191) NOT NULL,
`status` ENUM('PLANNED', 'ACTUAL', 'SKIPPED') NOT NULL,
`recurringId` VARCHAR(191) NULL,
`occurrenceDate` DATE NULL,
`allocatedToRecurringId` VARCHAR(191) NULL,
`allocatedToOperationId` VARCHAR(191) NULL,
`allocationMode` ENUM('REDUCE_SHARED', 'BENEFICIARY_ONLY', 'CUSTOM') NULL,
`createdById` VARCHAR(191) NOT NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updatedAt` DATETIME(3) NOT NULL,
INDEX `Operation_date_idx`(`date`),
UNIQUE INDEX `Operation_recurringId_occurrenceDate_key`(`recurringId`, `occurrenceDate`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `OperationSplit` (
`operationId` VARCHAR(191) NOT NULL,
`userId` VARCHAR(191) NOT NULL,
`basisPoints` INTEGER NOT NULL,
PRIMARY KEY (`operationId`, `userId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Recurring` (
`id` VARCHAR(191) NOT NULL,
`kind` ENUM('INCOME', 'EXPENSE') NOT NULL,
`amount` DECIMAL(12, 2) NOT NULL,
`label` VARCHAR(191) NOT NULL,
`categoryId` VARCHAR(191) NOT NULL,
`accountUserId` VARCHAR(191) NOT NULL,
`frequency` ENUM('MONTHLY', 'QUARTERLY', 'YEARLY') NOT NULL,
`dayOfMonth` INTEGER NOT NULL,
`startDate` DATE NOT NULL,
`endDate` DATE NULL,
`paused` BOOLEAN NOT NULL DEFAULT false,
`loanId` VARCHAR(191) NULL,
`allocatedToRecurringId` VARCHAR(191) NULL,
`allocationMode` ENUM('REDUCE_SHARED', 'BENEFICIARY_ONLY', 'CUSTOM') NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE INDEX `Recurring_loanId_key`(`loanId`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `RecurringSplit` (
`recurringId` VARCHAR(191) NOT NULL,
`userId` VARCHAR(191) NOT NULL,
`basisPoints` INTEGER NOT NULL,
PRIMARY KEY (`recurringId`, `userId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Settlement` (
`id` VARCHAR(191) NOT NULL,
`fromUserId` VARCHAR(191) NOT NULL,
`toUserId` VARCHAR(191) NOT NULL,
`amount` DECIMAL(12, 2) NOT NULL,
`date` DATE NOT NULL,
`note` VARCHAR(191) NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Budget` (
`id` VARCHAR(191) NOT NULL,
`categoryId` VARCHAR(191) NOT NULL,
`monthlyAmount` DECIMAL(12, 2) NOT NULL,
`startMonth` CHAR(7) NOT NULL,
`endMonth` CHAR(7) NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Loan` (
`id` VARCHAR(191) NOT NULL,
`name` VARCHAR(191) NOT NULL,
`lender` VARCHAR(191) NULL,
`principal` DECIMAL(12, 2) NOT NULL,
`annualRate` DECIMAL(6, 3) NOT NULL,
`durationMonths` INTEGER NOT NULL,
`startDate` DATE NOT NULL,
`insuranceMonthly` DECIMAL(12, 2) NOT NULL DEFAULT 0,
`accountUserId` VARCHAR(191) NOT NULL,
`paymentOverride` DECIMAL(12, 2) NULL,
`referenceDate` DATE NULL,
`referenceRemainingCapital` DECIMAL(12, 2) NULL,
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `LoanSplit` (
`loanId` VARCHAR(191) NOT NULL,
`userId` VARCHAR(191) NOT NULL,
`basisPoints` INTEGER NOT NULL,
PRIMARY KEY (`loanId`, `userId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `Operation` ADD CONSTRAINT `Operation_categoryId_fkey` FOREIGN KEY (`categoryId`) REFERENCES `Category`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Operation` ADD CONSTRAINT `Operation_accountUserId_fkey` FOREIGN KEY (`accountUserId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Operation` ADD CONSTRAINT `Operation_recurringId_fkey` FOREIGN KEY (`recurringId`) REFERENCES `Recurring`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Operation` ADD CONSTRAINT `Operation_allocatedToRecurringId_fkey` FOREIGN KEY (`allocatedToRecurringId`) REFERENCES `Recurring`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Operation` ADD CONSTRAINT `Operation_allocatedToOperationId_fkey` FOREIGN KEY (`allocatedToOperationId`) REFERENCES `Operation`(`id`) ON DELETE SET NULL ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `Operation` ADD CONSTRAINT `Operation_createdById_fkey` FOREIGN KEY (`createdById`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `OperationSplit` ADD CONSTRAINT `OperationSplit_operationId_fkey` FOREIGN KEY (`operationId`) REFERENCES `Operation`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `OperationSplit` ADD CONSTRAINT `OperationSplit_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Recurring` ADD CONSTRAINT `Recurring_categoryId_fkey` FOREIGN KEY (`categoryId`) REFERENCES `Category`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Recurring` ADD CONSTRAINT `Recurring_accountUserId_fkey` FOREIGN KEY (`accountUserId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Recurring` ADD CONSTRAINT `Recurring_loanId_fkey` FOREIGN KEY (`loanId`) REFERENCES `Loan`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Recurring` ADD CONSTRAINT `Recurring_allocatedToRecurringId_fkey` FOREIGN KEY (`allocatedToRecurringId`) REFERENCES `Recurring`(`id`) ON DELETE SET NULL ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `RecurringSplit` ADD CONSTRAINT `RecurringSplit_recurringId_fkey` FOREIGN KEY (`recurringId`) REFERENCES `Recurring`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `RecurringSplit` ADD CONSTRAINT `RecurringSplit_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Settlement` ADD CONSTRAINT `Settlement_fromUserId_fkey` FOREIGN KEY (`fromUserId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Settlement` ADD CONSTRAINT `Settlement_toUserId_fkey` FOREIGN KEY (`toUserId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Budget` ADD CONSTRAINT `Budget_categoryId_fkey` FOREIGN KEY (`categoryId`) REFERENCES `Category`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Loan` ADD CONSTRAINT `Loan_accountUserId_fkey` FOREIGN KEY (`accountUserId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `LoanSplit` ADD CONSTRAINT `LoanSplit_loanId_fkey` FOREIGN KEY (`loanId`) REFERENCES `Loan`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `LoanSplit` ADD CONSTRAINT `LoanSplit_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "mysql"
+201
View File
@@ -0,0 +1,201 @@
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
enum OpKind {
INCOME
EXPENSE
}
enum OpStatus {
PLANNED
ACTUAL
SKIPPED
}
enum AllocationMode {
REDUCE_SHARED
BENEFICIARY_ONLY
CUSTOM
}
enum Frequency {
MONTHLY
QUARTERLY
YEARLY
}
model User {
id String @id @default(cuid())
firstName String
login String @unique
passwordHash String
color String
createdAt DateTime @default(now())
accountOperations Operation[] @relation("OperationAccount")
createdOperations Operation[] @relation("OperationCreator")
operationSplits OperationSplit[]
recurrings Recurring[]
recurringSplits RecurringSplit[]
settlementsFrom Settlement[] @relation("SettlementFrom")
settlementsTo Settlement[] @relation("SettlementTo")
loans Loan[]
loanSplits LoanSplit[]
}
model Setting {
id Int @id @default(1)
defaultSplit Json
}
model Category {
id String @id @default(cuid())
name String
emoji String
kind OpKind
archived Boolean @default(false)
sortOrder Int @default(0)
operations Operation[]
recurrings Recurring[]
budgets Budget[]
@@unique([name, kind])
}
model Operation {
id String @id @default(cuid())
kind OpKind
amount Decimal @db.Decimal(12, 2)
date DateTime @db.Date
label String
note String? @db.Text
categoryId String
category Category @relation(fields: [categoryId], references: [id], onDelete: Restrict)
accountUserId String
accountUser User @relation("OperationAccount", fields: [accountUserId], references: [id])
status OpStatus
recurringId String?
recurring Recurring? @relation("RecurringOccurrences", fields: [recurringId], references: [id], onDelete: SetNull)
occurrenceDate DateTime? @db.Date
allocatedToRecurringId String?
allocatedToRecurring Recurring? @relation("OperationAllocatedToRecurring", fields: [allocatedToRecurringId], references: [id], onDelete: SetNull)
allocatedToOperationId String?
allocatedToOperation Operation? @relation("OperationAllocatedToOperation", fields: [allocatedToOperationId], references: [id], onDelete: SetNull, onUpdate: NoAction)
allocatedFrom Operation[] @relation("OperationAllocatedToOperation")
allocationMode AllocationMode?
splits OperationSplit[]
createdById String
createdBy User @relation("OperationCreator", fields: [createdById], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([recurringId, occurrenceDate])
@@index([date])
}
model OperationSplit {
operationId String
operation Operation @relation(fields: [operationId], references: [id], onDelete: Cascade)
userId String
user User @relation(fields: [userId], references: [id])
basisPoints Int
@@id([operationId, userId])
}
model Recurring {
id String @id @default(cuid())
kind OpKind
amount Decimal @db.Decimal(12, 2)
label String
categoryId String
category Category @relation(fields: [categoryId], references: [id], onDelete: Restrict)
accountUserId String
accountUser User @relation(fields: [accountUserId], references: [id])
frequency Frequency
dayOfMonth Int
startDate DateTime @db.Date
endDate DateTime? @db.Date
paused Boolean @default(false)
loanId String? @unique
loan Loan? @relation(fields: [loanId], references: [id], onDelete: Cascade)
allocatedToRecurringId String?
allocatedToRecurring Recurring? @relation("RecurringAllocatedToRecurring", fields: [allocatedToRecurringId], references: [id], onDelete: SetNull, onUpdate: NoAction)
allocatedFrom Recurring[] @relation("RecurringAllocatedToRecurring")
allocationMode AllocationMode?
splits RecurringSplit[]
occurrences Operation[] @relation("RecurringOccurrences")
allocatedOperations Operation[] @relation("OperationAllocatedToRecurring")
createdAt DateTime @default(now())
}
model RecurringSplit {
recurringId String
recurring Recurring @relation(fields: [recurringId], references: [id], onDelete: Cascade)
userId String
user User @relation(fields: [userId], references: [id])
basisPoints Int
@@id([recurringId, userId])
}
model Settlement {
id String @id @default(cuid())
fromUserId String
fromUser User @relation("SettlementFrom", fields: [fromUserId], references: [id])
toUserId String
toUser User @relation("SettlementTo", fields: [toUserId], references: [id])
amount Decimal @db.Decimal(12, 2)
date DateTime @db.Date
note String?
createdAt DateTime @default(now())
}
model Budget {
id String @id @default(cuid())
categoryId String
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
monthlyAmount Decimal @db.Decimal(12, 2)
startMonth String @db.Char(7)
endMonth String? @db.Char(7)
}
model Loan {
id String @id @default(cuid())
name String
lender String?
principal Decimal @db.Decimal(12, 2)
annualRate Decimal @db.Decimal(6, 3)
durationMonths Int
startDate DateTime @db.Date
insuranceMonthly Decimal @default(0) @db.Decimal(12, 2)
accountUserId String
accountUser User @relation(fields: [accountUserId], references: [id])
paymentOverride Decimal? @db.Decimal(12, 2)
referenceDate DateTime? @db.Date
referenceRemainingCapital Decimal? @db.Decimal(12, 2)
splits LoanSplit[]
recurring Recurring?
createdAt DateTime @default(now())
}
model LoanSplit {
loanId String
loan Loan @relation(fields: [loanId], references: [id], onDelete: Cascade)
userId String
user User @relation(fields: [userId], references: [id])
basisPoints Int
@@id([loanId, userId])
}
+46
View File
@@ -0,0 +1,46 @@
import { PrismaClient, type OpKind } from "@prisma/client";
// Catégories de départ (spec §10). Upsert idempotent : relancé à chaque démarrage du conteneur.
const CATEGORIES: { name: string; emoji: string; kind: OpKind }[] = [
{ name: "Logement", emoji: "🏠", kind: "EXPENSE" },
{ name: "Courses", emoji: "🛒", kind: "EXPENSE" },
{ name: "Restaurants", emoji: "🍽", kind: "EXPENSE" },
{ name: "Transport", emoji: "⛽", kind: "EXPENSE" },
{ name: "Auto", emoji: "🚗", kind: "EXPENSE" },
{ name: "Crédit", emoji: "🏦", kind: "EXPENSE" },
{ name: "Énergie", emoji: "⚡", kind: "EXPENSE" },
{ name: "Télécom", emoji: "📱", kind: "EXPENSE" },
{ name: "Abonnements", emoji: "📺", kind: "EXPENSE" },
{ name: "Santé", emoji: "💊", kind: "EXPENSE" },
{ name: "Loisirs", emoji: "🎉", kind: "EXPENSE" },
{ name: "Vacances", emoji: "✈️", kind: "EXPENSE" },
{ name: "Vêtements", emoji: "👕", kind: "EXPENSE" },
{ name: "Cadeaux", emoji: "🎁", kind: "EXPENSE" },
{ name: "Maison", emoji: "🛋", kind: "EXPENSE" },
{ name: "Impôts", emoji: "🧾", kind: "EXPENSE" },
{ name: "Divers", emoji: "📦", kind: "EXPENSE" },
{ name: "Salaire", emoji: "💼", kind: "INCOME" },
{ name: "Remboursement employeur", emoji: "🧾", kind: "INCOME" },
{ name: "IK", emoji: "🚗", kind: "INCOME" },
{ name: "Prime", emoji: "💶", kind: "INCOME" },
{ name: "Dividendes", emoji: "📈", kind: "INCOME" },
{ name: "Autres revenus", emoji: "➕", kind: "INCOME" },
];
export async function seed(prisma: PrismaClient) {
for (const [i, c] of CATEGORIES.entries()) {
await prisma.category.upsert({
where: { name_kind: { name: c.name, kind: c.kind } },
update: {},
create: { ...c, sortOrder: i },
});
}
await prisma.setting.upsert({ where: { id: 1 }, update: {}, create: { id: 1, defaultSplit: {} } });
}
if (require.main === module) {
const prisma = new PrismaClient();
seed(prisma)
.then(() => console.log(`Seed OK (${CATEGORIES.length} catégories)`))
.finally(() => prisma.$disconnect());
}
View File
Whitespace-only changes.
+26
View File
@@ -0,0 +1,26 @@
// Réinitialise le mot de passe d'un compte : node dist/reset-password.js <identifiant> <nouveau mot de passe>
import bcrypt from "bcryptjs";
import { PrismaClient } from "@prisma/client";
async function main() {
const [login, password] = process.argv.slice(2);
if (!login || !password || password.length < 8) {
console.error("Usage : reset-password <identifiant> <nouveau mot de passe (8 caractères min.)>");
process.exit(1);
}
const prisma = new PrismaClient();
try {
const user = await prisma.user.update({
where: { login: login.toLowerCase() },
data: { passwordHash: await bcrypt.hash(password, 10) },
});
console.log(`Mot de passe de ${user.firstName} (${user.login}) mis à jour.`);
} catch {
console.error(`Aucun compte avec l'identifiant « ${login} ».`);
process.exitCode = 1;
} finally {
await prisma.$disconnect();
}
}
main();
+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>
);
}
+193
View File
@@ -0,0 +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 { loadDashboard } from "@/server/dashboard";
const validMonth = (m?: string) => (m && /^\d{4}-(0[1-9]|1[0-2])$/.test(m) ? m : currentMonthParis());
function Row({ k, v, strong, className = "" }: { k: string; v: React.ReactNode; strong?: boolean; className?: string }) {
return (
<div className={`flex justify-between border-b border-line-soft py-[7px] last:border-0 ${strong ? "pt-2.5" : ""} ${className}`}>
<span className={strong ? "font-semibold" : "text-muted"}>{k}</span>
<span className="tabular font-semibold">{v}</span>
</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>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { Logo } from "@/components/Logo";
export default function PublicLayout({ children }: { children: React.ReactNode }) {
return (
<main className="flex min-h-dvh flex-col items-center justify-center px-4 py-10">
<div className="mb-6">
<Logo />
</div>
{children}
</main>
);
}
+28
View File
@@ -0,0 +1,28 @@
"use client";
import { useActionState } from "react";
import { loginAction } from "@/server/actions/auth";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { Field, FormError, Input } from "@/components/ui/Field";
export function LoginForm() {
const [state, action, pending] = useActionState(loginAction, { error: null });
return (
<Card className="w-full max-w-sm p-6 shadow-sm">
<h1 className="mb-5 text-xl font-bold">Connexion</h1>
<form action={action} className="space-y-4">
<Field label="Identifiant">
<Input name="login" defaultValue={state.values?.login} autoComplete="username" autoCapitalize="none" required autoFocus />
</Field>
<Field label="Mot de passe">
<Input name="password" type="password" autoComplete="current-password" required />
</Field>
<FormError message={state.error} />
<Button type="submit" className="w-full" disabled={pending}>
{pending ? "Connexion…" : "Se connecter"}
</Button>
</form>
</Card>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { redirect } from "next/navigation";
import { isSetupDone } from "@/server/auth";
import { LoginForm } from "./LoginForm";
export const dynamic = "force-dynamic";
export default async function LoginPage() {
if (!(await isSetupDone())) redirect("/setup");
return <LoginForm />;
}
+82
View File
@@ -0,0 +1,82 @@
"use client";
import { useActionState, useState } from "react";
import { setupAction } from "@/server/actions/auth";
import { Button } from "@/components/ui/Button";
import { Card, CardLabel } from "@/components/ui/Card";
import { Field, FormError, Input, Select } from "@/components/ui/Field";
function PersonBlock({ i, defaultColor, title, values }: { i: number; defaultColor: string; title: string; values?: Record<string, string> }) {
return (
<div className="space-y-3 rounded-card border border-line p-4">
<CardLabel>{title}</CardLabel>
<div className="flex gap-3">
<Field label="Prénom">
<Input name={`firstName${i}`} defaultValue={values?.[`firstName${i}`]} required />
</Field>
<Field label="Couleur">
<Input name={`color${i}`} type="color" defaultValue={values?.[`color${i}`] ?? defaultColor} className="h-[42px] w-16 p-1" />
</Field>
</div>
<Field label="Identifiant">
<Input name={`login${i}`} defaultValue={values?.[`login${i}`]} autoCapitalize="none" required />
</Field>
<Field label="Mot de passe" hint="8 caractères minimum">
<Input name={`password${i}`} type="password" autoComplete="new-password" required minLength={8} />
</Field>
<Field label="Confirmation">
<Input name={`passwordConfirm${i}`} type="password" autoComplete="new-password" required minLength={8} />
</Field>
</div>
);
}
export function SetupForm() {
const [state, action, pending] = useActionState(setupAction, { error: null });
const [percent, setPercent] = useState("50");
return (
<Card className="w-full max-w-3xl p-6 shadow-sm">
<h1 className="text-xl font-bold">Bienvenue 👋</h1>
<p className="mb-6 mt-1 text-muted">Créons vos deux comptes. Tout reste modifiable ensuite dans les Réglages.</p>
<form action={action} className="space-y-6">
<div className="grid gap-4 md:grid-cols-2">
<PersonBlock i={0} defaultColor="#4f46e5" title="Personne 1" values={state.values} />
<PersonBlock i={1} defaultColor="#db2777" title="Personne 2" values={state.values} />
</div>
<div className="space-y-3 rounded-card border border-line p-4">
<CardLabel>Répartition par défaut des dépenses</CardLabel>
<div className="flex items-center gap-3">
<Input
name="defaultPercentFirst"
value={percent}
onChange={(e) => setPercent(e.target.value)}
inputMode="decimal"
className="w-24"
/>
<span className="text-muted">
% pour la personne 1, {Math.max(0, 100 - (Number(percent.replace(",", ".")) || 0))} % pour la personne 2
</span>
</div>
</div>
<div className="space-y-3 rounded-card border border-line p-4">
<CardLabel>Solde d&apos;ouverture (facultatif)</CardLabel>
<p className="text-muted">Si l&apos;un doit déjà de l&apos;argent à l&apos;autre au démarrage.</p>
<div className="flex flex-wrap gap-3">
<Select name="openingDirection" defaultValue={state.values?.openingDirection} className="w-auto">
<option value="second-owes-first">La personne 2 doit à la personne 1</option>
<option value="first-owes-second">La personne 1 doit à la personne 2</option>
</Select>
<Input name="openingAmount" defaultValue={state.values?.openingAmount} placeholder="0,00 €" inputMode="decimal" className="w-32" />
</div>
</div>
<FormError message={state.error} />
<Button type="submit" className="w-full md:w-auto" disabled={pending}>
{pending ? "Création…" : "Créer le foyer"}
</Button>
</form>
</Card>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { redirect } from "next/navigation";
import { isSetupDone } from "@/server/auth";
import { SetupForm } from "./SetupForm";
export const dynamic = "force-dynamic";
export default async function SetupPage() {
if (await isSetupDone()) redirect("/login");
return <SetupForm />;
}
+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"`,
},
});
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+32
View File
@@ -0,0 +1,32 @@
@import "tailwindcss";
/* Langage visuel de la maquette validée (dashboard-v2.html). */
@theme {
--font-sans: var(--font-inter), system-ui, sans-serif;
--color-page: #f5f6fa;
--color-card: #ffffff;
--color-line: #e5e7eb;
--color-line-soft: #f1f2f5;
--color-ink: #111827;
--color-muted: #6b7280;
--color-accent: #4f46e5;
--color-accent-soft: #eef2ff;
--color-pos: #059669;
--color-pos-soft: #ecfdf5;
--color-neg: #dc2626;
--color-neg-soft: #fef2f2;
--color-warn: #d97706;
--color-warn-soft: #fffbeb;
--color-warn-line: #fde68a;
--radius-card: 14px;
}
body {
background: var(--color-page);
color: var(--color-ink);
font-size: 14px;
}
.tabular {
font-variant-numeric: tabular-nums;
}
+20
View File
@@ -0,0 +1,20 @@
import type { Metadata, Viewport } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ variable: "--font-inter", subsets: ["latin"] });
export const metadata: Metadata = {
title: "Finances du foyer",
description: "Suivi des entrées, dépenses et charges partagées du foyer",
};
export const viewport: Viewport = { width: "device-width", initialScale: 1, themeColor: "#f5f6fa" };
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="fr">
<body className={`${inter.variable} font-sans antialiased`}>{children}</body>
</html>
);
}
+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>
);
}
+8
View File
@@ -0,0 +1,8 @@
export function Logo() {
return (
<div className="flex items-center gap-2 text-base font-bold">
<span className="grid h-7 w-7 place-items-center rounded-lg bg-accent text-sm text-white">€</span>
Finances
</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>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { ButtonHTMLAttributes } from "react";
type Variant = "primary" | "ghost" | "danger" | "subtle";
const VARIANTS: Record<Variant, string> = {
primary: "bg-accent text-white hover:bg-indigo-700",
ghost: "border border-line bg-white text-ink hover:bg-gray-50",
danger: "border border-red-200 bg-white text-neg hover:bg-neg-soft",
subtle: "text-accent hover:bg-accent-soft",
};
export function Button({
variant = "primary",
className = "",
...props
}: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: Variant }) {
return (
<button
className={`inline-flex items-center justify-center gap-2 rounded-[10px] px-4 py-2.5 text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${VARIANTS[variant]} ${className}`}
{...props}
/>
);
}
+9
View File
@@ -0,0 +1,9 @@
import type { HTMLAttributes } from "react";
export function Card({ className = "", ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={`rounded-card border border-line bg-card p-[18px] ${className}`} {...props} />;
}
export function CardLabel({ className = "", ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={`text-xs font-semibold uppercase tracking-wide text-muted ${className}`} {...props} />;
}
+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>
);
}
+34
View File
@@ -0,0 +1,34 @@
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes, TextareaHTMLAttributes } from "react";
/** Largeur pleine par défaut, sauf si l'appelant fixe une largeur. */
const width = (className: string) => (/(^|\s)w-/.test(className) ? "" : "w-full");
const control =
"rounded-[10px] border border-line bg-white px-3 py-2.5 text-sm text-ink outline-none transition focus:border-accent focus:ring-2 focus:ring-accent/20";
export function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
return (
<label className="block">
<span className="mb-1.5 block text-xs font-semibold text-muted">{label}</span>
{children}
{hint && <span className="mt-1 block text-xs text-muted">{hint}</span>}
</label>
);
}
export function Input({ className = "", ...props }: InputHTMLAttributes<HTMLInputElement>) {
return <input className={`${control} ${width(className)} ${className}`} {...props} />;
}
export function Select({ className = "", ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
return <select className={`${control} ${width(className)} ${className}`} {...props} />;
}
export function Textarea({ className = "", ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
return <textarea className={`${control} ${width(className)} ${className}`} {...props} />;
}
export function FormError({ message }: { message?: string | null }) {
if (!message) return null;
return <p className="rounded-[10px] border border-red-200 bg-neg-soft px-3 py-2 text-sm text-neg">{message}</p>;
}
+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>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { shareAmounts } from "./money";
import type { Cents, Op, Settlement, UserId } from "./types";
/**
* Équilibre entre personnes (spec §7.1), sur toutes les opérations réelles.
* Positif : on doit de l'argent à cette personne.
*/
export function computeBalances(ops: Op[], settlements: Settlement[], userIds: UserId[]): Record<UserId, Cents> {
const balance: Record<UserId, Cents> = Object.fromEntries(userIds.map((id) => [id, 0]));
for (const o of ops) {
if (o.status !== "ACTUAL") continue;
const shares = shareAmounts(o.amount, o.split, o.accountUserId);
for (const userId of userIds) {
const share = shares[userId] ?? 0;
const held = userId === o.accountUserId ? o.amount : 0;
// Dépense : avoir payé pour les autres rend créancier.
// Entrée : avoir reçu ce qui revient aux autres rend débiteur.
balance[userId] += o.kind === "EXPENSE" ? held - share : share - held;
}
}
for (const s of settlements) {
balance[s.fromUserId] = (balance[s.fromUserId] ?? 0) + s.amount;
balance[s.toUserId] = (balance[s.toUserId] ?? 0) - s.amount;
}
return balance;
}
/** Pour deux personnes : qui doit combien à qui, ou null à l'équilibre. */
export function describeBalance(
b: Record<UserId, Cents>,
): { debtor: UserId; creditor: UserId; amount: Cents } | null {
const entries = Object.entries(b);
const creditor = entries.find(([, v]) => v > 0);
const debtor = entries.find(([, v]) => v < 0);
if (!creditor || !debtor) return null;
return { debtor: debtor[0], creditor: creditor[0], amount: creditor[1] };
}
+133
View File
@@ -0,0 +1,133 @@
import { addMonths, dateInMonth, monthOf } from "@/lib/dates";
import type { Cents } from "./types";
export interface LoanInput {
principal: Cents;
annualRatePct: number;
durationMonths: number;
startDate: string;
insuranceMonthly: Cents;
paymentOverride: Cents | null;
referenceDate: string | null;
referenceRemainingCapital: Cents | null;
}
export interface ScheduleRow {
n: number;
date: string;
payment: Cents;
interest: Cents;
principal: Cents;
insurance: Cents;
remaining: Cents;
/** Échéance antérieure au capital de référence saisi (affichée « avant suivi »). */
beforeTracking: boolean;
}
export interface LoanSummary {
payment: Cents;
insurance: Cents;
endDate: string;
remaining: Cents;
interestPaid: Cents;
interestLeft: Cents;
}
const MAX_ROWS = 1200;
/** Mensualité constante hors assurance (amortissement à la française). */
export function monthlyPayment(principal: Cents, annualRatePct: number, months: number): Cents {
if (months <= 0) return principal;
const r = annualRatePct / 100 / 12;
if (r === 0) return Math.round(principal / months);
return Math.round((principal * r) / (1 - Math.pow(1 + r, -months)));
}
function rowDate(startDate: string, n: number): string {
return dateInMonth(addMonths(monthOf(startDate), n - 1), Number(startDate.slice(8, 10)));
}
/**
* Lignes d'amortissement à partir de `remaining`. Si `lastN` est fourni, la ligne `lastN`
* solde le capital ; sinon on continue jusqu'à remboursement complet.
*/
function amortize(
l: LoanInput,
firstN: number,
remaining: Cents,
payment: Cents,
lastN: number | null,
): ScheduleRow[] {
const rows: ScheduleRow[] = [];
const rate = l.annualRatePct / 100 / 12;
for (let n = firstN; remaining > 0 && rows.length < MAX_ROWS; n++) {
const interest = Math.round(remaining * rate);
let principal = payment - interest;
if (principal <= 0) throw new Error("Mensualité insuffisante pour couvrir les intérêts");
if (principal >= remaining || n === lastN) principal = remaining;
remaining -= principal;
rows.push({
n,
date: rowDate(l.startDate, n),
payment: principal + interest,
interest,
principal,
insurance: l.insuranceMonthly,
remaining,
beforeTracking: false,
});
}
return rows;
}
export function buildSchedule(l: LoanInput): ScheduleRow[] {
const standardPayment = l.paymentOverride ?? monthlyPayment(l.principal, l.annualRatePct, l.durationMonths);
if (l.referenceDate === null || l.referenceRemainingCapital === null) {
return amortize(l, 1, l.principal, standardPayment, l.paymentOverride === null ? l.durationMonths : null);
}
// Crédit en cours : l'historique théorique sert seulement à l'affichage,
// le suivi repart du capital constaté à la date de référence.
const original = amortize(
l,
1,
l.principal,
monthlyPayment(l.principal, l.annualRatePct, l.durationMonths),
l.durationMonths,
);
const before = original
.filter((r) => r.date <= l.referenceDate!)
.map((r) => ({ ...r, beforeTracking: true }));
const payment =
l.paymentOverride ??
monthlyPayment(l.referenceRemainingCapital, l.annualRatePct, l.durationMonths - before.length);
const after = amortize(
l,
before.length + 1,
l.referenceRemainingCapital,
payment,
l.paymentOverride === null ? l.durationMonths : null,
);
return [...before, ...after];
}
/** Capital restant dû après la dernière échéance passée à `date`. */
export function remainingAt(rows: ScheduleRow[], date: string): Cents {
let remaining: Cents | null = null;
for (const r of rows) if (r.date <= date) remaining = r.remaining;
if (remaining !== null) return remaining;
const first = rows[0];
return first ? first.remaining + first.principal : 0;
}
export function loanSummary(rows: ScheduleRow[], today: string): LoanSummary {
const tracked = rows.filter((r) => !r.beforeTracking);
return {
payment: tracked[0]?.payment ?? 0,
insurance: rows[0]?.insurance ?? 0,
endDate: rows[rows.length - 1]?.date ?? "",
remaining: remainingAt(rows, today),
interestPaid: rows.filter((r) => r.date <= today).reduce((t, r) => t + r.interest, 0),
interestLeft: rows.filter((r) => r.date > today).reduce((t, r) => t + r.interest, 0),
};
}
+95
View File
@@ -0,0 +1,95 @@
import type { Cents, Split, UserId } from "./types";
const euro = new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" });
const MINUS = "−";
/** "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 {
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;
const [units, decimals = ""] = s.split(".");
const cents = Number(units) * 100 + Number(decimals.padEnd(2, "0"));
return cents > 0 ? cents : null;
}
export function formatEuro(c: Cents, opts: { sign?: boolean } = {}): string {
const text = euro.format(Math.abs(c) / 100);
if (c < 0) return MINUS + text;
return opts.sign && c > 0 ? "+" + text : text;
}
/** Decimal Prisma (ou chaîne/nombre) → centimes, sans passer par un float. */
export function centsFromDecimal(d: { toString(): string } | string | number): Cents {
const s = d.toString();
const negative = s.startsWith("-");
const [units, decimals = ""] = s.replace("-", "").split(".");
const cents = Number(units) * 100 + Number(decimals.padEnd(2, "0").slice(0, 2));
return negative ? -cents : cents;
}
export function decimalFromCents(c: Cents): string {
const abs = Math.abs(c);
return `${c < 0 ? "-" : ""}${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, "0")}`;
}
export function validateSplit(s: Split): string | null {
const values = Object.values(s);
if (values.some((v) => v < 0 || !Number.isInteger(v))) return "Les pourcentages doivent être positifs.";
if (values.reduce((a, b) => a + b, 0) !== 10000) return "La répartition doit totaliser 100 %.";
return null;
}
/** Part de chacun en centimes ; le résidu d'arrondi va au titulaire du compte. */
export function shareAmounts(amount: Cents, split: Split, accountUserId: UserId): Record<UserId, Cents> {
const shares: Record<UserId, Cents> = {};
let total = 0;
for (const [userId, bp] of Object.entries(split)) {
shares[userId] = Math.floor((amount * bp) / 10000);
total += shares[userId];
}
shares[accountUserId] = (shares[accountUserId] ?? 0) + amount - total;
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]. */
export function percentToBp(input: string): number | null {
const s = input.replace(/[\s%]/g, "").replace(",", ".");
if (!/^\d+(\.\d{1,2})?$/.test(s)) return null;
const [units, decimals = ""] = s.split(".");
const bp = Number(units) * 100 + Number(decimals.padEnd(2, "0"));
return bp <= 10000 ? bp : null;
}
export function bpToPercentLabel(bp: number): string {
const units = Math.floor(bp / 100);
const rest = bp % 100;
return rest === 0 ? String(units) : `${units},${String(rest).padStart(2, "0").replace(/0$/, "")}`;
}
export function fullSplit(userId: UserId, userIds: UserId[]): Split {
return Object.fromEntries(userIds.map((id) => [id, id === userId ? 10000 : 0]));
}
+139
View File
@@ -0,0 +1,139 @@
import { monthOf } from "@/lib/dates";
import { shareAmounts } from "./money";
import type { Cents, Op, Split, UserId } from "./types";
export interface PersonFlows {
income: Cents;
paidOut: Cents;
chargesShare: Cents;
ownIncome: Cents;
remaining: Cents;
}
export interface HouseholdTotals {
income: Cents;
allocatedIncome: Cents;
plannedIncome: Cents;
expense: Cents;
plannedExpense: Cents;
remaining: Cents;
}
export interface ChargeRef {
id: string;
label: string;
kind: "recurring" | "operation";
split: Split;
}
export interface NetCharge {
id: string;
label: string;
gross: Cents;
reimbursed: Cents;
net: Cents;
split: Split;
}
export interface BudgetLine {
categoryId: string;
budget: Cents;
actual: Cents;
plannedRemaining: Cents;
over: boolean;
}
export const isAllocated = (o: Op) => o.allocatedToRecurringId !== null || o.allocatedToOperationId !== null;
const inMonth = (ops: Op[], month: string) => ops.filter((o) => o.status !== "SKIPPED" && monthOf(o.date) === month);
const sum = (ops: Op[]) => ops.reduce((t, o) => t + o.amount, 0);
/** Flux d'une personne sur le mois, opérations réelles uniquement (spec §7.2). */
export function personFlows(ops: Op[], month: string, userId: UserId): PersonFlows {
const flows: PersonFlows = { income: 0, paidOut: 0, chargesShare: 0, ownIncome: 0, remaining: 0 };
for (const o of inMonth(ops, month)) {
if (o.status !== "ACTUAL") continue;
const share = shareAmounts(o.amount, o.split, o.accountUserId)[userId] ?? 0;
const isAccount = o.accountUserId === userId;
if (o.kind === "EXPENSE") {
if (isAccount) flows.paidOut += o.amount;
flows.chargesShare += share;
} else {
if (isAccount) flows.income += o.amount;
if (isAllocated(o)) flows.chargesShare -= share;
else flows.ownIncome += share;
}
}
flows.remaining = flows.ownIncome - flows.chargesShare;
return flows;
}
/** Totaux du foyer sur le mois, prévues incluses. */
export function householdTotals(ops: Op[], month: string): HouseholdTotals {
const monthOps = inMonth(ops, month);
const incomes = monthOps.filter((o) => o.kind === "INCOME");
const expenses = monthOps.filter((o) => o.kind === "EXPENSE");
const income = sum(incomes);
const expense = sum(expenses);
return {
income,
allocatedIncome: sum(incomes.filter(isAllocated)),
plannedIncome: sum(incomes.filter((o) => o.status === "PLANNED")),
expense,
plannedExpense: sum(expenses.filter((o) => o.status === "PLANNED")),
remaining: income - expense,
};
}
/** Charges ayant au moins un remboursement affecté dans le mois (spec §7.3). */
export function netCharges(ops: Op[], month: string, charges: ChargeRef[]): NetCharge[] {
const monthOps = inMonth(ops, month);
const result: NetCharge[] = [];
for (const c of charges) {
const refunds = monthOps.filter(
(o) =>
o.kind === "INCOME" &&
(c.kind === "recurring" ? o.allocatedToRecurringId === c.id : o.allocatedToOperationId === c.id),
);
if (refunds.length === 0) continue;
const gross =
c.kind === "recurring"
? sum(monthOps.filter((o) => o.kind === "EXPENSE" && o.recurringId === c.id))
: sum(monthOps.filter((o) => o.id === c.id));
const reimbursed = sum(refunds);
result.push({ id: c.id, label: c.label, gross, reimbursed, net: gross - reimbursed, split: c.split });
}
return result;
}
/** Réel et prévu restant par catégorie budgétée (montants totaux du foyer). */
export function budgetStatus(ops: Op[], month: string, budgets: { categoryId: string; amount: Cents }[]): BudgetLine[] {
const expenses = inMonth(ops, month).filter((o) => o.kind === "EXPENSE");
return budgets.map((b) => {
const inCategory = expenses.filter((o) => o.categoryId === b.categoryId);
const actual = sum(inCategory.filter((o) => o.status === "ACTUAL"));
return {
categoryId: b.categoryId,
budget: b.amount,
actual,
plannedRemaining: sum(inCategory.filter((o) => o.status === "PLANNED")),
over: actual > b.amount,
};
});
}
export function budgetForMonth(
budgets: { categoryId: string; monthlyAmount: Cents; startMonth: string; endMonth: string | null }[],
month: string,
): { categoryId: string; amount: Cents }[] {
const active = new Map<string, { startMonth: string; amount: Cents }>();
for (const b of budgets) {
if (b.startMonth > month || (b.endMonth !== null && b.endMonth < month)) continue;
const current = active.get(b.categoryId);
if (!current || b.startMonth > current.startMonth) {
active.set(b.categoryId, { startMonth: b.startMonth, amount: b.monthlyAmount });
}
}
return [...active].map(([categoryId, { amount }]) => ({ categoryId, amount }));
}
+97
View File
@@ -0,0 +1,97 @@
import { addMonths, dateInMonth, monthOf, monthsBetween } from "@/lib/dates";
import { fullSplit } from "./money";
import type { AllocationMode, Cents, Frequency, Op, OpKind, Split, UserId } from "./types";
export interface RecurringDef {
id: string;
kind: OpKind;
amount: Cents;
label: string;
categoryId: string;
accountUserId: UserId;
split: Split;
frequency: Frequency;
dayOfMonth: number;
startDate: string;
endDate: string | null;
paused: boolean;
allocatedToRecurringId: string | null;
allocationMode: AllocationMode | null;
}
export type PlannedOccurrence = Omit<Op, "id" | "status"> & { status: "PLANNED"; occurrenceDate: string };
const STEP: Record<Frequency, number> = { MONTHLY: 1, QUARTERLY: 3, YEARLY: 12 };
export const occurrenceKey = (recurringId: string, occurrenceDate: string) => `${recurringId}|${occurrenceDate}`;
/** Dates d'occurrence entre deux mois inclus (spec §9). */
export function occurrenceDates(r: RecurringDef, fromMonth: string, toMonth: string): string[] {
const startMonth = monthOf(r.startDate);
const dates: string[] = [];
for (let m = fromMonth < startMonth ? startMonth : fromMonth; m <= toMonth; m = addMonths(m, 1)) {
if (monthsBetween(startMonth, m) % STEP[r.frequency] !== 0) continue;
const date = dateInMonth(m, r.dayOfMonth);
if (date < r.startDate) continue;
if (r.endDate !== null && date > r.endDate) break;
dates.push(date);
}
return dates;
}
export function splitForAllocation(
mode: AllocationMode,
accountUserId: UserId,
targetSplit: Split | null,
custom: Split,
userIds: UserId[],
): Split {
if (mode === "REDUCE_SHARED" && targetSplit) return { ...targetSplit };
if (mode === "CUSTOM") return { ...custom };
return fullSplit(accountUserId, userIds);
}
/** Occurrences manquantes sur l'horizon glissant, à partir du mois courant. */
export function planOccurrences(
recs: RecurringDef[],
existingKeys: Set<string>,
today: string,
userIds: UserId[],
horizonMonths = 12,
): PlannedOccurrence[] {
const fromMonth = monthOf(today);
const toMonth = addMonths(fromMonth, horizonMonths - 1);
const byId = new Map(recs.map((r) => [r.id, r]));
const planned: PlannedOccurrence[] = [];
for (const r of recs) {
if (r.paused) continue;
const target = r.allocatedToRecurringId ? byId.get(r.allocatedToRecurringId) : undefined;
const allocated = r.kind === "INCOME" && target !== undefined && r.allocationMode !== null;
let split: Split;
if (r.kind === "EXPENSE") split = r.split;
else if (allocated) split = splitForAllocation(r.allocationMode!, r.accountUserId, target!.split, r.split, userIds);
else split = fullSplit(r.accountUserId, userIds);
for (const date of occurrenceDates(r, fromMonth, toMonth)) {
if (existingKeys.has(occurrenceKey(r.id, date))) continue;
planned.push({
kind: r.kind,
amount: r.amount,
date,
occurrenceDate: date,
label: r.label,
categoryId: r.categoryId,
accountUserId: r.accountUserId,
status: "PLANNED",
split,
recurringId: r.id,
allocatedToRecurringId: allocated ? target!.id : null,
allocatedToOperationId: null,
allocationMode: allocated ? r.allocationMode : null,
});
}
}
return planned;
}
+33
View File
@@ -0,0 +1,33 @@
export type Cents = number;
export type UserId = string;
/** Répartition en points de base : 100 % = 10000. */
export type Split = Record<UserId, number>;
export type OpKind = "INCOME" | "EXPENSE";
export type OpStatus = "PLANNED" | "ACTUAL" | "SKIPPED";
export type AllocationMode = "REDUCE_SHARED" | "BENEFICIARY_ONLY" | "CUSTOM";
export type Frequency = "MONTHLY" | "QUARTERLY" | "YEARLY";
export interface Op {
id: string;
kind: OpKind;
amount: Cents;
date: string;
label: string;
categoryId: string;
accountUserId: UserId;
status: OpStatus;
split: Split;
recurringId: string | null;
allocatedToRecurringId: string | null;
allocatedToOperationId: string | null;
allocationMode: AllocationMode | null;
}
export interface Settlement {
id: string;
fromUserId: UserId;
toUserId: UserId;
amount: Cents;
date: string;
}
+69
View File
@@ -0,0 +1,69 @@
// Les dates métier sont des chaînes "YYYY-MM-DD" et les mois "YYYY-MM" :
// aucune logique jour/mois ne passe par un Date JS, pour éviter tout décalage UTC/Paris.
const parisDay = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Paris",
year: "numeric",
month: "2-digit",
day: "2-digit",
});
const MONTHS_FR = [
"Janvier", "Février", "Mars", "Avril", "Mai", "Juin",
"Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre",
];
const pad = (n: number, len = 2) => String(n).padStart(len, "0");
export function todayParis(now: Date = new Date()): string {
return parisDay.format(now);
}
export function currentMonthParis(now: Date = new Date()): string {
return monthOf(todayParis(now));
}
export function monthOf(iso: string): string {
return iso.slice(0, 7);
}
export function addMonths(month: string, n: number): string {
const [y, m] = month.split("-").map(Number);
const index = y * 12 + (m - 1) + n;
return `${pad(Math.floor(index / 12), 4)}-${pad((index % 12) + 1)}`;
}
/** Nombre de mois de `from` à `to` (positif si `to` est après). */
export function monthsBetween(from: string, to: string): number {
const [fy, fm] = from.split("-").map(Number);
const [ty, tm] = to.split("-").map(Number);
return ty * 12 + tm - (fy * 12 + fm);
}
export function daysInMonth(month: string): number {
const [y, m] = month.split("-").map(Number);
return new Date(Date.UTC(y, m, 0)).getUTCDate();
}
/** Jour `day` du mois, ramené au dernier jour si le mois est plus court. */
export function dateInMonth(month: string, day: number): string {
return `${month}-${pad(Math.min(day, daysInMonth(month)))}`;
}
export function toIsoDate(d: Date): string {
return `${pad(d.getUTCFullYear(), 4)}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
}
export function fromIsoDate(iso: string): Date {
return new Date(`${iso}T00:00:00.000Z`);
}
export function formatDateFr(iso: string): string {
const [y, m, d] = iso.split("-");
return `${d}/${m}/${y}`;
}
export function monthLabelFr(month: string): string {
const [y, m] = month.split("-").map(Number);
return `${MONTHS_FR[m - 1]} ${y}`;
}
+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 @@
import { NextResponse, type NextRequest } from "next/server";
// Garde légère : sans cookie de session, on renvoie vers /login.
// La vérification complète (session valide, installation faite) se fait dans requireUser().
export function middleware(req: NextRequest) {
if (!req.cookies.has("hcl_fin")) return NextResponse.redirect(new URL("/login", req.url));
return NextResponse.next();
}
export const config = {
matcher: ["/((?!login|setup|_next|favicon.ico).*)"],
};
+60
View File
@@ -0,0 +1,60 @@
"use server";
import { redirect } from "next/navigation";
import { createHousehold, getSession, isSetupDone, verifyPassword, type PersonInput } from "@/server/auth";
import { prisma } from "@/server/db";
export type FormState = { error: string | null; values?: Record<string, string> };
/** Valeurs renvoyées au formulaire après une erreur (React réinitialise le formulaire), sans les mots de passe. */
const keepValues = (fd: FormData) =>
Object.fromEntries([...fd.entries()].filter(([k, v]) => typeof v === "string" && !k.startsWith("$") && !k.startsWith("password")).map(([k, v]) => [k, String(v)]));
const str = (fd: FormData, key: string) => String(fd.get(key) ?? "");
function person(fd: FormData, i: number): PersonInput {
return {
firstName: str(fd, `firstName${i}`),
login: str(fd, `login${i}`),
password: str(fd, `password${i}`),
passwordConfirm: str(fd, `passwordConfirm${i}`),
color: str(fd, `color${i}`) || (i === 0 ? "#4f46e5" : "#db2777"),
};
}
export async function setupAction(_prev: FormState, fd: FormData): Promise<FormState> {
if (await isSetupDone()) redirect("/login");
let firstUserId: string;
try {
const { users } = await createHousehold({
people: [person(fd, 0), person(fd, 1)],
defaultPercentFirst: str(fd, "defaultPercentFirst") || "50",
openingAmount: str(fd, "openingAmount"),
openingDirection: str(fd, "openingDirection") === "first-owes-second" ? "first-owes-second" : "second-owes-first",
});
firstUserId = users[0].id;
} catch (e) {
return { error: e instanceof Error ? e.message : "Erreur inattendue.", values: keepValues(fd) };
}
const session = await getSession();
session.userId = firstUserId;
await session.save();
redirect("/");
}
export async function loginAction(_prev: FormState, fd: FormData): Promise<FormState> {
const user = await prisma.user.findUnique({ where: { login: str(fd, "login").trim().toLowerCase() } });
if (!user || !(await verifyPassword(str(fd, "password"), user.passwordHash))) {
return { error: "Identifiant ou mot de passe incorrect.", values: keepValues(fd) };
}
const session = await getSession();
session.userId = user.id;
await session.save();
redirect("/");
}
export async function logoutAction() {
const session = await getSession();
session.destroy();
redirect("/login");
}
+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;
}
+124
View File
@@ -0,0 +1,124 @@
import bcrypt from "bcryptjs";
import { getIronSession, type SessionOptions } from "iron-session";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { cache } from "react";
import { todayParis, fromIsoDate } from "@/lib/dates";
import { decimalFromCents, parseEuro, percentToBp } from "@/domain/money";
import { prisma } from "./db";
export interface SessionData {
userId?: string;
}
const sessionOptions = (): SessionOptions => ({
password: process.env.SESSION_SECRET ?? "",
cookieName: "hcl_fin",
// Accès LAN en HTTP : pas de cookie "secure".
cookieOptions: { secure: false, httpOnly: true, sameSite: "lax", maxAge: 60 * 60 * 24 * 90 },
ttl: 60 * 60 * 24 * 90,
});
export function hashPassword(p: string): Promise<string> {
return bcrypt.hash(p, 10);
}
export function verifyPassword(p: string, h: string): Promise<boolean> {
return bcrypt.compare(p, h);
}
export async function getSession() {
return getIronSession<SessionData>(await cookies(), sessionOptions());
}
export async function isSetupDone(): Promise<boolean> {
return (await prisma.user.count()) > 0;
}
/** Utilisateur connecté, sinon redirection vers l'installation ou la connexion. */
export const requireUser = cache(async () => {
const session = await getSession();
const user = session.userId ? await prisma.user.findUnique({ where: { id: session.userId } }) : null;
if (user) return user;
redirect((await isSetupDone()) ? "/login" : "/setup");
});
export interface PersonInput {
firstName: string;
login: string;
password: string;
passwordConfirm: string;
color: string;
}
export interface HouseholdInput {
people: [PersonInput, PersonInput];
defaultPercentFirst: string;
openingAmount: string;
openingDirection: "second-owes-first" | "first-owes-second";
}
export function validatePassword(password: string, confirm: string): string | null {
if (password.length < 8) return "Le mot de passe doit faire au moins 8 caractères.";
if (password !== confirm) return "Les mots de passe ne correspondent pas.";
return null;
}
/** Création du foyer au premier lancement (comptes, répartition par défaut, solde d'ouverture). */
export async function createHousehold(input: HouseholdInput) {
if (await isSetupDone()) throw new Error("Installation déjà effectuée");
for (const p of input.people) {
if (!p.firstName.trim()) throw new Error("Le prénom est obligatoire.");
if (!/^[a-z0-9._-]+$/i.test(p.login.trim())) throw new Error("Identifiant invalide (lettres, chiffres, . _ -).");
const pwError = validatePassword(p.password, p.passwordConfirm);
if (pwError) throw new Error(pwError);
}
if (input.people[0].login.trim().toLowerCase() === input.people[1].login.trim().toLowerCase()) {
throw new Error("Les deux identifiants doivent être différents.");
}
const firstBp = percentToBp(input.defaultPercentFirst);
if (firstBp === null) throw new Error("Répartition par défaut invalide.");
const opening = input.openingAmount.trim() ? parseEuro(input.openingAmount) : null;
if (input.openingAmount.trim() && opening === null) throw new Error("Montant du solde d'ouverture invalide.");
const hashes = await Promise.all(input.people.map((p) => hashPassword(p.password)));
return prisma.$transaction(async (tx) => {
const users = [];
for (const [i, p] of input.people.entries()) {
users.push(
await tx.user.create({
data: {
firstName: p.firstName.trim(),
login: p.login.trim().toLowerCase(),
passwordHash: hashes[i],
color: p.color,
// createdAt distincts pour garder l'ordre des personnes.
createdAt: new Date(Date.now() + i),
},
}),
);
}
await tx.setting.upsert({
where: { id: 1 },
update: { 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) {
// Une dette de B envers A s'enregistre comme si A avait avancé l'argent à B (versement A → B).
const [debtor, creditor] = input.openingDirection === "second-owes-first" ? [users[1], users[0]] : [users[0], users[1]];
const [from, to] = [creditor, debtor];
await tx.settlement.create({
data: {
fromUserId: from.id,
toUserId: to.id,
amount: decimalFromCents(opening),
date: fromIsoDate(todayParis()),
note: "Solde d'ouverture",
},
});
}
return { users };
});
}
+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,
};
}
+7
View File
@@ -0,0 +1,7 @@
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
+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;
}
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { computeBalances, describeBalance } from "@/domain/balance";
import { op } from "./fixtures";
const users = ["H", "C"];
const rent = op({ kind: "EXPENSE", amount: 100000, accountUserId: "H" });
const employerRent = op({
kind: "INCOME",
amount: 20000,
accountUserId: "H",
allocatedToRecurringId: "rent",
allocationMode: "REDUCE_SHARED",
});
describe("computeBalances", () => {
it("matches the spec control example: net rent 800 split 400/400", () => {
const b = computeBalances([rent, employerRent], [], users);
expect(b).toEqual({ H: 40000, C: -40000 });
expect(describeBalance(b)).toEqual({ debtor: "C", creditor: "H", amount: 40000 });
});
it("does not create a debt for an income kept 100 % by its receiver", () => {
const salary = op({ kind: "INCOME", amount: 300000, accountUserId: "H", split: { H: 10000, C: 0 } });
const b = computeBalances([salary], [], users);
expect(b).toEqual({ H: 0, C: 0 });
expect(describeBalance(b)).toBeNull();
});
it("ignores planned and skipped operations", () => {
const planned = op({ kind: "EXPENSE", amount: 5000, accountUserId: "H", status: "PLANNED" });
const skipped = op({ kind: "EXPENSE", amount: 5000, accountUserId: "H", status: "SKIPPED" });
expect(computeBalances([planned, skipped], [], users)).toEqual({ H: 0, C: 0 });
});
it("settles debts with person-to-person repayments", () => {
const settlement = { id: "s1", fromUserId: "C", toUserId: "H", amount: 40000, date: "2026-10-20" };
expect(computeBalances([rent, employerRent], [settlement], users)).toEqual({ H: 0, C: 0 });
});
it("uses cent-exact shares for uneven splits", () => {
const uneven = op({ kind: "EXPENSE", amount: 1000, accountUserId: "H", split: { H: 3333, C: 6667 } });
expect(computeBalances([uneven], [], users)).toEqual({ H: 666, C: -666 });
});
});
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more