diff --git a/docs/superpowers/plans/2026-10-27-finances-foyer-v1.md b/docs/superpowers/plans/2026-10-27-finances-foyer-v1.md new file mode 100644 index 0000000..1406f52 --- /dev/null +++ b/docs/superpowers/plans/2026-10-27-finances-foyer-v1.md @@ -0,0 +1,737 @@ +# Finances du foyer v1 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build a self-hosted household finance tracker for two people, with shared expenses split in %, a running "who owes whom" balance, recurring and planned operations, budgets, employer reimbursements linked to the charge they offset, and loans. It is deployed with docker compose (Next.js + MariaDB) on a LAN VM. + +**Architecture:** A single Next.js App Router project in TypeScript. All financial logic lives in a pure, unit-tested `src/domain/` layer that works in integer cents, basis points and ISO date strings. `src/server/` holds the thin Prisma repositories, auth, and the Server Actions that map DB rows to domain types. `src/app/` holds the pages, built with Tailwind in the visual language of the validated mockup. Recurring occurrences are created idempotently when a page loads, so there is no cron job. + +**Tech Stack:** +- Node 24, Next.js 15 (App Router, `output: 'standalone'`), React 19, TypeScript strict, Tailwind CSS 4 +- Prisma 6 (provider `mysql`) on `mariadb:latest` +- Vitest, `iron-session`, `bcryptjs`, `zod`, `recharts` +- Docker compose + +**Spec:** `docs/superpowers/specs/2026-10-27-finances-foyer-design.md`. Read it before any task, because section numbers (§) below refer to it. Visual reference: `.superpowers/brainstorm/250-1793118883/content/dashboard-v2.html`. + +## Global Constraints + +- The UI is in French. Amounts display as `1 234,56 €` (`Intl.NumberFormat('fr-FR',{style:'currency',currency:'EUR'})`) and dates as `JJ/MM/AAAA`. The timezone is `Europe/Paris`. +- Amounts are `DECIMAL(12,2)` in the DB. The domain works in **integer cents**. No float arithmetic on money, anywhere. +- Splits are integer **basis points** (100 % = 10000). A split is valid only if it sums to exactly 10000 and every value is ≥ 0. +- Dates in the domain are `YYYY-MM-DD` strings and months are `YYYY-MM` strings. Never use a JS `Date` for day or month logic, so UTC/Paris drift is impossible. +- Colors: bg `#f5f6fa`, card `#ffffff`, line `#e5e7eb`, text `#111827`, muted `#6b7280`, accent `#4f46e5`, green `#059669`, red `#dc2626`, amber `#d97706`. Default person colors are `#4f46e5` and `#db2777`. Font is Inter, card radius is 14px. +- The DB is `mariadb:latest`. The app is reachable on port `3000` and the DB is not exposed on the host. +- First names replace "Toi/Conjointe" everywhere. +- Status `SKIPPED` exists only to stop a recurring occurrence from regenerating. Every calculation ignores it. +- Commit messages end with `Co-Authored-By: Claude Opus 5.5 `. + +## Review Focus + +1. **Splits that don't sum to 100 %, or are uneven.** 33.33/66.67 must be accepted, 33.33/33.33 rejected with a French error message, and the cent residue assigned to the account holder. Tests are in Task 2. +2. **French amount input.** `86,40`, `86.40`, `1 234,56` and `1 234,56` (narrow nbsp) must all parse to cents. `0`, `-5` and `abc` must be rejected. Tests are in Task 2. +3. **Recurring day 31 or 29.** It must fall on the last day of short months (2027-02-28). Quarterly and yearly items step from the start date's month. Tests are in Task 6. +4. **Deleting things that other things point to.** Deleting a recurring template or an allocation target must not delete ACTUAL history or crash. The references are set to NULL. Tests are in Task 9 (repository integration test) and Task 6 (pure planning ignores a missing target). +5. **Month boundaries.** An operation dated `2026-10-31` belongs to October whatever the server timezone. The default month is computed in Europe/Paris. Tests are in Task 4 (`monthOf`) and Task 1 (`todayParis`). + +--- + +## File Structure + +``` +package.json, tsconfig.json, next.config.ts, vitest.config.ts, postcss.config.mjs, .env.example +prisma/schema.prisma # full schema (Task 1) +prisma/seed.ts # categories + settings singleton (Task 1) +src/lib/dates.ts # ISO date helpers, todayParis, month math (Task 1) +src/domain/types.ts # domain types (Task 2) +src/domain/money.ts # parse/format cents, splits (Task 2) +src/domain/balance.ts # who owes whom (Task 3) +src/domain/monthly.ts # per-person flows, household totals, net charges, budgets (Task 4) +src/domain/loan.ts # amortization (Task 5) +src/domain/recurrence.ts # occurrence dates + planning (Task 6) +src/server/db.ts # Prisma singleton (Task 1) +src/server/auth.ts # session, requireUser, password hashing (Task 7) +src/server/mappers.ts # Prisma row -> domain (Task 8) +src/server/repo.ts # data loading used by pages (Task 8) +src/server/sync.ts # syncRecurrings() (Task 8) +src/server/actions/*.ts # setup/auth, operations, settlements, recurrings, budgets, loans, settings +src/app/(public)/setup, login # Task 7 +src/app/(app)/layout.tsx # shell with sidebar + mobile nav (Task 8) +src/app/(app)/page.tsx # dashboard (Task 10) +src/app/(app)/operations, recurrents, budgets, credits, credits/[id], reglages # Tasks 11-15 +src/app/api/export/route.ts # CSV (Task 15) +src/components/ui/*.tsx # Card, Chip, Avatar, Button, MonthSwitcher, Field, Pills (Task 8) +src/components/OperationForm.tsx # quick entry (Task 9) +tests/domain/*.test.ts # unit tests +tests/server/*.test.ts # integration tests against local MariaDB (TEST_DATABASE_URL) +Dockerfile, docker-compose.yml, docker-compose.dev.yml, docker/entrypoint.sh, docker/backup.sh +scripts/reset-password.ts, README.md +``` + +--- + +### Task 1: Project scaffold, schema, local DB + +**Files:** +- Create: everything under "scaffold" in File Structure, plus `prisma/schema.prisma`, `prisma/seed.ts`, `src/lib/dates.ts`, `src/server/db.ts`, `docker-compose.dev.yml`, `.env.example` +- Test: `tests/lib/dates.test.ts` + +**Interfaces:** +- Produces: + - `src/lib/dates.ts`: + - `todayParis(now?: Date): string` returns YYYY-MM-DD + - `currentMonthParis(now?: Date): string` returns YYYY-MM + - `monthOf(iso: string): string` + - `addMonths(month: string, n: number): string` + - `daysInMonth(month: string): number` + - `toIsoDate(d: Date): string` (reads UTC parts, for Prisma `@db.Date` values) + - `fromIsoDate(iso: string): Date` (UTC midnight) + - `formatDateFr(iso: string): string` returns JJ/MM/AAAA + - `monthLabelFr(month: string): string` returns "Octobre 2026" + - The Prisma client `prisma` from `src/server/db.ts`. + - The DB schema below. + +- [ ] **Step 1: Scaffold.** Run `npx create-next-app@15 . --ts --tailwind --eslint --app --src-dir --import-alias "@/*" --use-npm --no-turbopack` (keep the existing `docs/` and `.gitignore`). Then: + - install `prisma@6 @prisma/client@6 iron-session bcryptjs zod recharts`; + - install as dev dependencies `vitest @types/bcryptjs tsx`; + - set `output: 'standalone'` in `next.config.ts`; + - add the scripts `"test": "vitest run"`, `"db:migrate": "prisma migrate dev"` and `"db:seed": "tsx prisma/seed.ts"`, and `"prisma": {"seed": "tsx prisma/seed.ts"}`; + - in `vitest.config.ts`, use the alias `@` → `src` and the environment `node`. + +- [ ] **Step 2: Dev DB.** In `docker-compose.dev.yml`, add a `mariadb:latest` service on host port `3307`. Use the env vars `MARIADB_ROOT_PASSWORD=dev` and `MARIADB_DATABASE=finances`, and an init SQL that also creates `finances_test`. In `.env.example`, put: + ``` + DATABASE_URL="mysql://root:dev@localhost:3307/finances" + TEST_DATABASE_URL="mysql://root:dev@localhost:3307/finances_test" + SESSION_SECRET="change-me-to-32+chars-random-string-xxxxxxxx" + ``` + Copy it to `.env`, then run `docker compose -f docker-compose.dev.yml up -d`. + +- [ ] **Step 3: Write `prisma/schema.prisma`.** + - Enums: + - `OpKind {INCOME EXPENSE}` + - `OpStatus {PLANNED ACTUAL SKIPPED}` + - `AllocationMode {REDUCE_SHARED BENEFICIARY_ONLY CUSTOM}` + - `Frequency {MONTHLY QUARTERLY YEARLY}` + - Models: ids are `String @id @default(cuid())` unless stated. Money fields are `Decimal @db.Decimal(12,2)`, date fields are `DateTime @db.Date`, and splits use `basisPoints Int`. + - `User`: firstName, login @unique, passwordHash, color, createdAt. + - `Setting`: `id Int @id @default(1)`, `defaultSplit Json` (a map userId→bp). + - `Category`: name, emoji, kind OpKind, archived Bool default false, sortOrder Int default 0. + - `Operation`: + - kind, amount, date, label, note `String? @db.Text`, categoryId → Category (onDelete Restrict), accountUserId → User, status ; + - recurringId? → Recurring (**onDelete SetNull**), occurrenceDate? (Date) ; + - allocatedToRecurringId? → Recurring (**SetNull**), allocatedToOperationId? → Operation (self relation, **SetNull**, NoAction on update), allocationMode? ; + - createdById → User, createdAt, updatedAt ; + - `@@unique([recurringId, occurrenceDate])`, `@@index([date])`. + - `OperationSplit`: operationId (onDelete **Cascade**), userId, basisPoints, `@@id([operationId,userId])`. + - `Recurring`: + - kind, amount, label, categoryId, accountUserId, frequency, dayOfMonth Int, startDate, endDate?, paused Bool default false ; + - loanId? @unique → Loan (onDelete **Cascade**) ; + - allocatedToRecurringId? → Recurring (self, SetNull), allocationMode? ; + - splits `RecurringSplit[]`. + - `RecurringSplit`: recurringId (Cascade), userId, basisPoints, `@@id([recurringId,userId])`. + - `Settlement`: fromUserId, toUserId, amount, date, note?, createdAt. + - `Budget`: categoryId (Cascade), monthlyAmount, `startMonth String @db.Char(7)`, `endMonth String? @db.Char(7)`. + - `Loan`: name, lender?, principal, `annualRate Decimal @db.Decimal(6,3)`, durationMonths Int, startDate, insuranceMonthly default 0, accountUserId, paymentOverride?, referenceDate?, referenceRemainingCapital?, splits `LoanSplit[]`, recurring `Recurring?`. + - `LoanSplit`: loanId (Cascade), userId, basisPoints, `@@id([loanId,userId])`. + +- [ ] **Step 4: Seed.** `prisma/seed.ts` upserts the categories of spec §10 (exact names and emojis, kind EXPENSE or INCOME, with sortOrder in list order) by name+kind. It also upserts `Setting{id:1, defaultSplit:{}}`, which gets filled at setup. It creates no users. Run `npx prisma migrate dev --name init`, then `npm run db:seed`. + Expected: the migration applies and `SELECT COUNT(*) FROM Category` returns 22. + +- [ ] **Step 5: Write the failing tests** in `tests/lib/dates.test.ts`: + ```ts + expect(todayParis(new Date('2026-10-31T23:30:00Z'))).toBe('2026-11-01'); // Paris is UTC+1 after DST ends + expect(todayParis(new Date('2026-10-31T22:30:00Z'))).toBe('2026-10-31'); + expect(monthOf('2026-10-31')).toBe('2026-10'); + expect(addMonths('2026-11', 3)).toBe('2027-02'); + expect(addMonths('2026-01', -1)).toBe('2025-12'); + expect(daysInMonth('2028-02')).toBe(29); + expect(toIsoDate(new Date('2026-10-31T00:00:00Z'))).toBe('2026-10-31'); + expect(formatDateFr('2026-10-05')).toBe('05/10/2026'); + expect(monthLabelFr('2026-10')).toBe('Octobre 2026'); + ``` + +- [ ] **Step 6: Run** `npx vitest run tests/lib`. Expected: FAIL (module missing). + +- [ ] **Step 7: Implement `src/lib/dates.ts`.** Use `Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Paris'})` for `todayParis`. Everything else is string arithmetic. + +- [ ] **Step 8: Run** `npx vitest run tests/lib` and `npm run build`. Expected: both PASS. + +- [ ] **Step 9: Commit** with `chore: scaffold Next.js + Prisma schema + dev MariaDB`. + +--- + +### Task 2: Domain types, money and splits + +**Files:** +- Create: `src/domain/types.ts`, `src/domain/money.ts` +- Test: `tests/domain/money.test.ts` + +**Interfaces:** +- Produces `src/domain/types.ts`: + ```ts + export type Cents = number; export type UserId = string; + export type Split = Record; // basis points, sum 10000 + export type OpKind = 'INCOME' | 'EXPENSE'; + export type OpStatus = 'PLANNED' | 'ACTUAL' | 'SKIPPED'; + export type AllocationMode = 'REDUCE_SHARED' | 'BENEFICIARY_ONLY' | 'CUSTOM'; + 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; } + ``` +- Produces `src/domain/money.ts`: + - `parseEuro(input: string): Cents | null`: returns null for empty, ≤0 or invalid input. + - `formatEuro(c: Cents, opts?: {sign?: boolean}): string` + - `centsFromDecimal(d: {toString(): string} | string | number): Cents` + - `decimalFromCents(c: Cents): string` (for example `"86.40"`) + - `validateSplit(s: Split): string | null`: returns the French error message or null. + - `shareAmounts(amount: Cents, split: Split, accountUserId: UserId): Record` + - `percentToBp(input: string): number | null` (`"33,33"` gives 3333) + - `bpToPercentLabel(bp: number): string` (5000 gives `"50"`, 3333 gives `"33,33"`) + - `fullSplit(userId: UserId, userIds: UserId[]): Split`: 10000 for one user, 0 for the others. + +- [ ] **Step 1: Write the failing tests.** + ```ts + for (const s of ['86,40','86.40','1 234,56','1 234,56','1234']) expect(parseEuro(s)).not.toBeNull(); + expect(parseEuro('86,40')).toBe(8640); expect(parseEuro('1 234,56')).toBe(123456); expect(parseEuro('1234')).toBe(123400); + for (const s of ['','0','-5','abc','12,345']) expect(parseEuro(s)).toBeNull(); + expect(formatEuro(123456)).toBe('1 234,56 €'); // Intl fr-FR output + expect(formatEuro(-8640, {sign:true})).toBe('−86,40 €'); expect(formatEuro(500, {sign:true})).toBe('+5,00 €'); + expect(centsFromDecimal('86.40')).toBe(8640); expect(decimalFromCents(8640)).toBe('86.40'); + expect(validateSplit({a:5000,b:5000})).toBeNull(); + expect(validateSplit({a:3333,b:6667})).toBeNull(); + expect(validateSplit({a:3333,b:3333})).toBe('La répartition doit totaliser 100 %.'); + expect(validateSplit({a:-100,b:10100})).toBe('Les pourcentages doivent être positifs.'); + expect(shareAmounts(1000, {a:3333,b:6667}, 'a')).toEqual({a:334, b:666}); // residue to account holder + expect(shareAmounts(8640, {a:5000,b:5000}, 'b')).toEqual({a:4320, b:4320}); + expect(shareAmounts(1, {a:5000,b:5000}, 'b')).toEqual({a:0, b:1}); + expect(percentToBp('33,33')).toBe(3333); expect(bpToPercentLabel(3333)).toBe('33,33'); expect(bpToPercentLabel(5000)).toBe('50'); + expect(fullSplit('a',['a','b'])).toEqual({a:10000,b:0}); + ``` + If `Intl` emits a different space character for `formatEuro`, assert against the `Intl` output instead. The sign must be the real minus `−` (U+2212), as in the mockup. + +- [ ] **Step 2: Run** `npx vitest run tests/domain/money.test.ts`. Expected: FAIL. +- [ ] **Step 3: Implement.** In `shareAmounts`, round each share with `Math.floor(amount*bp/10000)` on integers, then add `amount − Σ` to `accountUserId`. In `parseEuro`, strip the spaces (`\s`, U+00A0, U+202F), replace `,` with `.`, and match `/^\d+(\.\d{1,2})?$/`. +- [ ] **Step 4: Run** the tests. Expected: PASS. +- [ ] **Step 5: Commit** with `feat(domain): money parsing/formatting and splits`. + +--- + +### Task 3: Balance between people (spec §7.1) + +**Files:** +- Create: `src/domain/balance.ts` +- Test: `tests/domain/balance.test.ts` + +**Interfaces:** +- Consumes: `Op`, `Settlement`, `shareAmounts`. +- Produces: + - `computeBalances(ops: Op[], settlements: Settlement[], userIds: UserId[]): Record`: only ACTUAL ops count. A positive value means P is owed. + - `describeBalance(b: Record): {debtor: UserId; creditor: UserId; amount: Cents} | null`: built for two people, returns null when every value is 0. + +- [ ] **Step 1: Write the failing tests.** Use a helper `op(partial)` that builds an `Op` with defaults (status ACTUAL, split 50/50, allocation null). + - Spec control example: rent EXPENSE 100000, acc H, split 50/50, plus INCOME 20000 acc H, split 50/50 (REDUCE_SHARED copy). Expect `computeBalances(...)` to equal `{H: 40000, C: -40000}`, and `describeBalance` to return `{debtor:'C', creditor:'H', amount:40000}`. + - Salary INCOME 300000, acc H, split `{H:10000,C:0}` gives `{H:0,C:0}`, and `describeBalance` returns null. + - A PLANNED or SKIPPED expense is ignored. + - Settlement C→H 40000 on top of the control example gives `{H:0, C:0}`. + - An uneven split of 1000 at 3333/6667, acc H, gives `{H:666, C:-666}`. This uses `shareAmounts`, so the shares are a:334 and b:666. +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement** with the formulas of §7.1, using the `shareAmounts` cents (not float). +- [ ] **Step 4: Run** the tests. Expected: PASS. +- [ ] **Step 5: Commit** with `feat(domain): balance between people`. + +--- + +### Task 4: Monthly flows, household totals, net charges, budgets (spec §7.2–7.4) + +**Files:** +- Create: `src/domain/monthly.ts` +- Test: `tests/domain/monthly.test.ts` + +**Interfaces:** +- Consumes: `Op`, `shareAmounts`, `monthOf`. +- Produces: + - `personFlows(ops: Op[], month: string, userId: UserId): {income: Cents; paidOut: Cents; chargesShare: Cents; ownIncome: Cents; remaining: Cents}`. It uses ACTUAL ops of the month only. An "allocated" income is an INCOME with `allocatedToRecurringId` or `allocatedToOperationId` set. + - `householdTotals(ops: Op[], month: string): {income: Cents; allocatedIncome: Cents; plannedIncome: Cents; expense: Cents; plannedExpense: Cents; remaining: Cents}`. Here `income` and `expense` cover ACTUAL + PLANNED, and `remaining = income − expense`. + - `netCharges(ops: Op[], month: string, charges: {id: string; label: string; kind: 'recurring'|'operation'; split: Split}[]): {id; label; gross: Cents; reimbursed: Cents; net: Cents; split: Split}[]`. It lists only the charges that have at least one allocated income in the month. + - For a recurring charge, gross = Σ non-SKIPPED occurrences (ACTUAL + PLANNED) with that `recurringId` in the month. + - For an operation charge, gross = that op's amount when it falls in the month. + - reimbursed = Σ non-SKIPPED incomes allocated to the charge in the month. + - `budgetStatus(ops: Op[], month: string, budgets: {categoryId: string; amount: Cents}[]): {categoryId; budget: Cents; actual: Cents; plannedRemaining: Cents; over: boolean}[]`. + - `budgetForMonth(budgets: {categoryId; monthlyAmount: Cents; startMonth; endMonth: string|null}[], month: string): {categoryId; amount: Cents}[]`. When several budgets match, the latest `startMonth` wins. + +- [ ] **Step 1: Write the failing tests.** The fixture is October 2026 with users H and C. The figures reproduce the mockup's structure with simple numbers. + - Ops: + - salary H +300000 (100 % H) on 10-25 ; + - salary C +200000 (100 % C) ; + - rent −100000 acc H 50/50 (recurringId `rent`) ; + - employer rent +20000 acc H, allocated to `rent`, split 50/50 ; + - car loan −38000 acc H 100 % H (recurringId `car`) ; + - IK +22000 acc H, allocated to `car`, 100 % H ; + - groceries −8640 acc C 50/50 ACTUAL ; + - PLANNED car service −35000 acc H 100 % H on 10-30 ; + - an op dated `2026-11-01`, which is excluded. + - `personFlows(ops,'2026-10','H')`: + - income = 300000+20000+22000 = 342000 ; + - paidOut = 100000+38000 = 138000 ; + - chargesShare = 50000+38000+4320 − 10000 − 22000 = 60320 ; + - ownIncome = 300000 ; + - remaining = 239680. + - `personFlows(...,'C')`: income 200000, paidOut 8640, chargesShare 50000+4320−10000 = 44320, ownIncome 200000, remaining 155680. + - `householdTotals`: income 542000, allocatedIncome 42000, plannedIncome 0, expense 100000+38000+8640+35000 = 181640, plannedExpense 35000, remaining 360360. + - `netCharges` with the charges rent (50/50) and car (100 % H) returns rent `{gross:100000, reimbursed:20000, net:80000}` and car `{gross:38000, reimbursed:22000, net:16000}`. A charge without allocation is not returned. + - `budgetStatus` with the Courses budget 40000 returns `{actual:8640, plannedRemaining:0, over:false}`. A budget of 5000 returns `over:true`. + - `budgetForMonth`: a budget starting `2026-11` is absent in `2026-10`. Of two budgets (from `2026-01` and from `2026-09`), October uses the September one. + - SKIPPED ops are absent from every result. +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement** per §7.2–7.4. Filter by `monthOf(op.date) === month`. +- [ ] **Step 4: Run** the tests. Expected: PASS. +- [ ] **Step 5: Commit** with `feat(domain): monthly flows, totals, net charges, budgets`. + +--- + +### Task 5: Loan amortization (spec §7.5 + Loan "crédit en cours") + +**Files:** +- Create: `src/domain/loan.ts` +- Test: `tests/domain/loan.test.ts` + +**Interfaces:** +- Produces: + ```ts + 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; beforeTracking: boolean; } + export function monthlyPayment(principal: Cents, annualRatePct: number, months: number): Cents; + export function buildSchedule(l: LoanInput): ScheduleRow[]; + export function remainingAt(rows: ScheduleRow[], date: string): Cents; + export function loanSummary(rows: ScheduleRow[], today: string): { payment: Cents; insurance: Cents; endDate: string; remaining: Cents; interestPaid: Cents; interestLeft: Cents; }; + ``` + - `payment` excludes insurance. Row dates are `startDate` + (n−1) months, clamped to the end of the month. + - `remainingAt` returns the remaining capital after the last row whose date is ≤ the given date (or the principal if there is none). + +- [ ] **Step 1: Write the failing tests.** + - `monthlyPayment(2000000, 4, 48)` returns `45158`, and `monthlyPayment(1200000, 0, 12)` returns `100000`. + - `buildSchedule({principal:2000000, annualRatePct:4, durationMonths:48, startDate:'2026-01-05', insuranceMonthly:1500, paymentOverride:null, referenceDate:null, referenceRemainingCapital:null})`: + - 48 rows ; + - row 1 is `{date:'2026-01-05', interest:6667, principal:38491, insurance:1500, remaining:1961509}` ; + - the last row has `remaining: 0`, and its principal equals the previous row's remaining (the last payment absorbs the residue) ; + - Σ principal = 2000000. + - Reference mode: same loan with `referenceDate:'2026-06-10'`, `referenceRemainingCapital:1800000`, `paymentOverride:46000`. The rows dated ≤ 2026-06-10 have `beforeTracking:true`. The first row after (`2026-07-05`) has interest `round(1800000*0.04/12)=6000` and principal `40000`. Rows continue until remaining is 0. The final payment is ≤ 46000, and the row count may differ from 48. + - With `startDate` on day 31 (`'2026-01-31'`), row 2's date is `'2026-02-28'`. + - `remainingAt(rows,'2026-01-04')` returns 2000000, and `remainingAt(rows,'2026-01-05')` returns 1961509. +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement.** Use `interest = Math.round(remaining * rate/100/12)` and `principal = payment − interest`; on the last row (`principal ≥ remaining`), set `principal = remaining` and `payment = principal + interest`. + - In reference mode, the rows before `referenceDate` are computed from the original loan only for display (`beforeTracking:true`). From the first date > `referenceDate`, restart with remaining = `referenceRemainingCapital` and payment = `paymentOverride ?? monthlyPayment(refCapital, rate, durationMonths − rowsBefore)`. + - Guard: if payment ≤ interest, throw `Error('Mensualité insuffisante pour couvrir les intérêts')`. +- [ ] **Step 4: Run** the tests. Expected: PASS. +- [ ] **Step 5: Commit** with `feat(domain): loan amortization schedule`. + +--- + +### Task 6: Recurrence dates and occurrence planning (spec §9, §8) + +**Files:** +- Create: `src/domain/recurrence.ts` +- Test: `tests/domain/recurrence.test.ts` + +**Interfaces:** +- Consumes: `Split`, `AllocationMode`, `fullSplit`, date helpers. +- Produces: + ```ts + export interface RecurringDef { id: string; kind: OpKind; amount: Cents; label: string; categoryId: string; + accountUserId: UserId; split: Split; frequency: 'MONTHLY'|'QUARTERLY'|'YEARLY'; dayOfMonth: number; + startDate: string; endDate: string | null; paused: boolean; + allocatedToRecurringId: string | null; allocationMode: AllocationMode | null; } + export function occurrenceDates(r: RecurringDef, fromMonth: string, toMonth: string): string[]; + export function splitForAllocation(mode: AllocationMode, accountUserId: UserId, targetSplit: Split | null, custom: Split, userIds: UserId[]): Split; + export function planOccurrences(recs: RecurringDef[], existingKeys: Set, today: string, userIds: UserId[], horizonMonths?: number): PlannedOccurrence[]; + // PlannedOccurrence = Omit & { status: 'PLANNED'; occurrenceDate: string }; key = `${recurringId}|${occurrenceDate}` + ``` +- Rules: + - The months included are those `m` with `m ≥ monthOf(startDate)` and `(monthsBetween(start, m) % step === 0)`, where step is 1, 3 or 12. + - The day is `min(dayOfMonth, daysInMonth)`. + - Dates must satisfy `startDate ≤ date ≤ endDate` (when `endDate` is set). + - `planOccurrences` covers the months from `monthOf(today)` to `+horizonMonths−1` (default 12), skips paused recurrings and existing keys, and sets the allocation split with `splitForAllocation`. + - An income recurring with no allocation gets `fullSplit(accountUserId)`. An expense gets `r.split`. + - If the allocation target is missing from `recs`, it falls back to `fullSplit(accountUserId)` and keeps the allocation null. + +- [ ] **Step 1: Write the failing tests.** + - A monthly recurring on day 31 from `2026-10-31`, over `2026-10`..`2027-03`, gives `['2026-10-31','2026-11-30','2026-12-31','2027-01-31','2027-02-28','2027-03-31']`. + - A quarterly recurring from `2026-11-15` over `2026-10`..`2027-12` gives `['2026-11-15','2027-02-15','2027-05-15','2027-08-15','2027-11-15']`. + - A yearly recurring from `2025-03-01` over `2026-01`..`2027-12` gives `['2026-03-01','2027-03-01']`. + - A recurring with `endDate:'2026-12-15'`, monthly on day 20, over `2026-10`..`2027-02` gives `['2026-10-20','2026-11-20']`. + - `splitForAllocation('REDUCE_SHARED','H',{H:5000,C:5000},{},['H','C'])` returns the 50/50 split, `'BENEFICIARY_ONLY'` returns `{H:10000,C:0}`, and `'CUSTOM'` returns the custom split. + - `planOccurrences` with today `2026-10-27` and a monthly rent from `2024-01-05` gives 12 occurrences, starting at `2026-10-05` (no retroactive months before the current month) and ending at `2027-09-05`. + - With `existingKeys` holding `rent|2026-10-05`, it gives 11 occurrences. + - A paused recurring gives 0. + - An IK income recurring allocated to `car` (REDUCE_SHARED, car split 100 % H) gets the split `{H:10000,C:0}` and `allocatedToRecurringId:'car'`. + - A dangling target gives `allocatedToRecurringId:null` and the full split for the account holder. +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** the tests. Expected: PASS. +- [ ] **Step 5: Commit** with `feat(domain): recurrence dates and occurrence planning`. + +--- + +### Task 7: Auth, first-run setup, login + +**Files:** +- Create: `src/server/auth.ts`, `src/server/actions/auth.ts`, `src/middleware.ts`, `src/app/(public)/setup/page.tsx`, `src/app/(public)/login/page.tsx`, `src/app/(public)/layout.tsx`, `scripts/reset-password.ts` +- Test: `tests/server/auth.test.ts` + +**Interfaces:** +- Consumes: `prisma`, `parseEuro`, `percentToBp`, `validateSplit`. +- Produces: + - `hashPassword(p: string): Promise` and `verifyPassword(p: string, h: string): Promise`, using bcryptjs with cost 10. + - `getSession()`: an iron-session with cookie `hcl_fin`, `secure:false` (LAN HTTP) and `maxAge` 90 days, storing `{userId?: string}`. + - `requireUser(): Promise`: redirects to `/login` if there is no user, and to `/setup` if no users exist. + - `isSetupDone(): Promise`. + - Actions: + - `setupAction(formData)` creates both users. Each user's fields are firstName, login, password (≥ 8 chars), confirmation and color. + - It writes `Setting.defaultSplit` from the default split percent for user 1 (user 2 gets the remainder). + - It takes an optional opening balance amount + direction and creates a Settlement dated `todayParis()`. + - It logs in user 1 and redirects to `/`. + - It refuses to run if users already exist. + - `loginAction(formData)` and `logoutAction()`. + - `scripts/reset-password.ts `, run inside the container as `node scripts/reset-password.js` after build. Compile it with tsx in the Dockerfile or ship it via `npx tsx`, whichever works in the standalone image. + +- [ ] **Step 1: Write the failing test.** It runs against `TEST_DATABASE_URL`: a `beforeAll` runs `prisma migrate reset --force --skip-seed` with `DATABASE_URL` pointing at the test DB, then truncates. Test `hashPassword`/`verifyPassword` (round-trip true, wrong password false). Test that a `createHousehold({...})` helper (extracted from `setupAction`, pure DB without cookies) creates 2 users, the Setting defaultSplit `{u1:6000,u2:4000}` for an input of 60 %, and a Settlement when the opening balance is `"150"` with direction `u2→u1`. A second call throws `Error('Installation déjà effectuée')`. +- [ ] **Step 2: Run** `npx vitest run tests/server/auth.test.ts`. Expected: FAIL. +- [ ] **Step 3: Implement** the auth helpers and `createHousehold`, then the setup and login pages. + - The pages use a centered white card on the `#f5f6fa` background, with the logo (indigo square "€" + "Finances"). + - The setup form has two side-by-side person blocks (stacked on mobile), each with a color picker defaulting to `#4f46e5` / `#db2777`. Below them come the default split (one % input, default 50) and the "Solde d'ouverture (facultatif)" section. + - Errors show as French inline messages. + - `middleware.ts` only redirects unauthenticated requests (no cookie) to `/login`, except `/login`, `/setup` and `/_next`. The pages enforce the full check with `requireUser`. +- [ ] **Step 4: Run** the tests. Expected: PASS. Then run `npm run dev` and check by hand that `/` redirects to `/setup`, that setup redirects to `/`, and that after logout `/login` works. +- [ ] **Step 5: Commit** with `feat: auth, first-run setup, login`. + +--- + +### Task 8: App shell, UI kit, data loading, recurring sync + +**Files:** +- Create: + - `src/server/mappers.ts`, `src/server/repo.ts`, `src/server/sync.ts` + - `src/app/(app)/layout.tsx`, `src/components/Sidebar.tsx`, `src/components/MobileNav.tsx` + - `src/components/ui/{Card,Chip,Avatar,Button,MonthSwitcher,Field,Pills,Amount}.tsx` +- Modify: `src/app/globals.css` (Inter font via `next/font/google`, color tokens as CSS variables) +- Test: `tests/server/sync.test.ts` + +**Interfaces:** +- Consumes: `planOccurrences`, `toIsoDate`, `fromIsoDate`, `centsFromDecimal`, `requireUser`. +- Produces: + - `mappers.ts`: `toOp(row with splits): Op`, `toRecurringDef(row with splits): RecurringDef`, `toSettlement(row): Settlement`. + - `repo.ts`: + - `getUsers(): Promise<{id, firstName, color}[]>` (order by createdAt) ; + - `getCategories(kind?: OpKind)` ; + - `getOpsForMonth(month: string): Promise` ; + - `getAllActualOps(): Promise` ; + - `getSettlements(): Promise` ; + - `getRecurringDefs(): Promise` ; + - `getDefaultSplit(): Promise`. + - `sync.ts`: `syncRecurrings(today?: string): Promise` loads the defs and existing keys, then runs `prisma.operation.createMany({skipDuplicates:true})` plus the split rows. It returns the count created. It is called once at the top of `(app)/layout.tsx`. + - UI kit: + - ``: white, 1px `#e5e7eb` border, radius 14, padding 18. + - `` + - `` + - ``: green for income, red for expense, tabular-nums. + - ``: ‹ › links using `?m=YYYY-MM`. + - `` + - Layout: + - desktop sidebar at 210px as in the mockup, with the items Tableau de bord, Opérations, Récurrents & prévu, Budgets, Crédits & charges, Simulateur (disabled, "bientôt" chip), Réglages, and Déconnexion ; + - on mobile (<768px), a bottom tab bar with Accueil, Opérations, a central **+** button that opens the quick entry, Récurrents and Plus (a menu with the rest). + +- [ ] **Step 1: Write the failing test** (`TEST_DATABASE_URL`). Seed 2 users, a category, and a monthly recurring rent from `2026-01-05`. `syncRecurrings('2026-10-27')` returns 12, and a second call returns 0. Then: + - mark the `2026-10-05` occurrence SKIPPED, delete the `2026-11-05` one, and call sync again: it returns 1 (November is recreated, the skipped October is not) ; + - delete the Recurring: the ACTUAL operations that pointed at it still exist with `recurringId` null (Review Focus 4). +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement** the repo, mappers and sync, then the layout and UI kit. Match the mockup (`dashboard-v2.html`) for the spacing, colors and typography. +- [ ] **Step 4: Run** the tests. Expected: PASS. In `npm run dev`, the shell renders at 1280px and 390px wide without horizontal scroll. +- [ ] **Step 5: Commit** with `feat: app shell, UI kit, data loading, recurring sync`. + +--- + +### Task 9: Quick entry form, operation and settlement actions + +**Files:** +- Create: `src/components/OperationForm.tsx`, `src/components/QuickAddButton.tsx`, `src/server/actions/operations.ts`, `src/server/actions/settlements.ts`, `src/components/SettlementDialog.tsx` +- Test: `tests/server/operations.test.ts` + +**Interfaces:** +- Consumes: `parseEuro`, `validateSplit`, `splitForAllocation`, `fullSplit`, `getDefaultSplit`, the UI kit. +- Produces: + - `saveOperation(input: OperationInput): Promise<{ok: true} | {ok: false; error: string}>`, where: + ```ts + OperationInput = { id?: string; kind: OpKind; amount: string; label: string; categoryId: string; date: string; + accountUserId: string; status: 'PLANNED'|'ACTUAL'; split: Split; note?: string; + allocatedToRecurringId?: string|null; allocatedToOperationId?: string|null; allocationMode?: AllocationMode|null; + makeRecurring?: { frequency: Frequency; endDate: string|null } } + ``` + - It validates with zod, `parseEuro` and `validateSplit`, and rejects allocation fields on an EXPENSE. + - With `makeRecurring`, it creates a Recurring (dayOfMonth = the day of `date`, startDate = `date`) **and** the operation as its first occurrence, with `recurringId` and `occurrenceDate` set. + - On update, it replaces the splits. + - `deleteOperation(id)`. + - `confirmOperation(id, amount: string, date: string)` sets the status to ACTUAL. + - `skipOperation(id)`: for a recurring occurrence it sets status SKIPPED, otherwise it deletes the operation. + - `saveSettlement({fromUserId,toUserId,amount,date,note})`. + - All of them call `revalidatePath('/', 'layout')`. + - The form's behavior: + - **Defaults**: the type is Dépense, the date is `todayParis()`, the payer is the logged-in user, the split is the household default for an expense and 100 % of the receiver for an income (switching the type or payer recomputes it unless the user picked "Perso…"). + - **Split pills**: the household default ("50 / 50" label from the bp), "100 % {prénom1}", "100 % {prénom2}" and "Perso…", which shows one % input per person with a live total. + - **Advanced section** (collapsed "+ Récurrent, prévue, affecter à une charge"): + - a "Prévue" toggle ; + - "Rendre récurrent" (frequency and optional end date) ; + - for an income only, "Affecter à une charge": a select listing the expense recurrings and the expense ops of the last 3 months, plus the mode pills "Réduit la charge pour tous" (REDUCE_SHARED, default), "Profite au bénéficiaire" and "Perso", which prefill the split ; + - a note. + - **Presentation**: on mobile it is a full-screen sheet, on desktop a centered modal. The layout follows the mockup's phone screen (the big amount input uses `inputMode="decimal"`). + +- [ ] **Step 1: Write the failing tests** (`TEST_DATABASE_URL`). These cover `saveOperation`: + - The amount `"86,40"` with a 50/50 split is stored as 86.40 with two split rows. + - A split of 3333/3333 returns `{ok:false, error:'La répartition doit totaliser 100 %.'}`. + - The amount `"0"` returns `{ok:false, error:'Montant invalide.'}`. + - An income allocated to an expense op, then deletion of that expense op: the income still exists with `allocatedToOperationId` null (Review Focus 4). + - `makeRecurring` monthly from `2026-10-27` creates 1 Recurring and an op whose `occurrenceDate` is `2026-10-27`. A following `syncRecurrings('2026-10-27')` creates 11 more, not 12. + - `skipOperation` on a recurring occurrence sets SKIPPED, and on a one-off op deletes it. + - `saveSettlement` with from === to returns an error. +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement** the actions, then the form and the `QuickAddButton` (used in the dashboard header, the mobile **+** tab and the Opérations page). +- [ ] **Step 4: Run** the tests. Expected: PASS. Then in the browser at 390px, enter "86,40 Carrefour" with the payer set to person 2 and a 50/50 split: it saves and shows a success toast. +- [ ] **Step 5: Commit** with `feat: quick entry form and operation/settlement actions`. + +--- + +### Task 10: Dashboard + +**Files:** +- Create: `src/app/(app)/page.tsx`, `src/components/dashboard/{HouseholdCards,BalanceBanner,PersonCard,BudgetsCard,NetChargesCard,RecentOps,ToConfirmBadge}.tsx` +- Test: `tests/server/dashboard.test.ts` (data assembly) + +**Interfaces:** +- Consumes: `getOpsForMonth`, `getAllActualOps`, `getSettlements`, `getUsers`, `computeBalances`, `describeBalance`, `personFlows`, `householdTotals`, `netCharges`, `budgetStatus`, `budgetForMonth`, `SettlementDialog`. +- Produces: `loadDashboard(month: string, viewerId: string, today: string = todayParis()): Promise` in `src/server/repo.ts`. `DashboardData` holds: + - `totals` and `persons: {user, flows}[]` ; + - `balance: {text: string; debtor?; creditor?; amount?} | null` and `lastSettlementDate: string|null` ; + - `budgets` (with category name/emoji) and `netCharges` ; + - `recent: Op[]` (the 8 most recent of the month by date desc, PLANNED included) ; + - `toConfirmCount` (PLANNED with date ≤ today, all months). + + The balance text is computed from the viewer's point of view: + - viewer is the creditor: `"{débiteur} te doit {montant}"` ; + - viewer is the debtor: `"Tu dois {montant} à {créancier}"` ; + - balanced: `"Vous êtes à l'équilibre"`. + +- [ ] **Step 1: Write the failing test.** Insert the Task 4 fixture in the test DB, with users whose firstName is "H" and "C". The balance for H is: rent +50000, employer −10000, groceries paid by C −4320, car loan and IK 0, so H = 35680. Assert: + - `loadDashboard('2026-10', H.id).balance.text === 'C te doit ' + formatEuro(35680)` ; + - `loadDashboard('2026-10', C.id).balance.text === 'Tu dois ' + formatEuro(35680) + ' à H'` ; + - `persons[0].flows.remaining === 239680` ; + - `toConfirmCount === 0` when today is `2026-10-27`, because the planned op is dated 10-30. +- [ ] **Step 2: Run** the test. Expected: FAIL. +- [ ] **Step 3: Implement** `loadDashboard` and the page, laid out as in the mockup: + - header (MonthSwitcher + "+ Nouvelle opération") ; + - 3 household cards (Entrées with "dont X € remboursés par l'employeur", Sorties with "dont X € prévus, pas encore passés", Reste with "après les dépenses prévues") ; + - amber balance banner with the "Enregistrer un remboursement" button (prefilled from debtor to creditor with the amount) and "depuis le dernier remboursement (JJ/MM)" ; + - 2 person cards ; + - budgets and net charges side by side (stacked on mobile) ; + - the recent operations table (PLANNED rows at 65 % opacity with the amber "prévue" chip, the "payé par {prénom}" chip in the person's color, the split chip, and the "↳ {charge}" link chip) ; + - a small amber pill "N à confirmer" linking to `/recurrents`, shown when `toConfirmCount > 0`. + + Empty states: + - no budget: "Aucun budget défini" with a link to Budgets ; + - no net charge: hide the card ; + - no operation: "Aucune opération ce mois-ci". +- [ ] **Step 4: Run** the tests. Expected: PASS. Check visually at 1280px and 390px against the mockup. +- [ ] **Step 5: Commit** with `feat: monthly dashboard`. + +--- + +### Task 11: Operations page + +**Files:** +- Create: `src/app/(app)/operations/page.tsx`, `src/components/operations/{OpsFilters,OpsTable,EditOperationDialog}.tsx` +- Modify: `src/server/repo.ts` (add `searchOps`) +- Test: `tests/server/search.test.ts` + +**Interfaces:** +- Produces: `searchOps(f: {month: string; userId?: string; categoryId?: string; kind?: OpKind; status?: 'PLANNED'|'ACTUAL'; q?: string}): Promise`. + - `userId` matches the account holder **or** anyone with a share > 0. + - `q` is a case-insensitive `contains` on the label. + - SKIPPED ops are always excluded, and results are sorted by date desc. + +- [ ] **Step 1: Write the failing test.** On a fixture, filtering by `q:'carre'` finds "Carrefour". `userId:C` finds the rent split 50/50 that H paid. `status:'PLANNED'` returns only planned ops. SKIPPED ops never appear. +- [ ] **Step 2: Run** the test. Expected: FAIL. +- [ ] **Step 3: Implement.** + - The filters are a URL search-params form (MonthSwitcher, person, category, type, status, search). + - The table matches the mockup's table style. On mobile it becomes a list of cards. + - Clicking a row opens `OperationForm` in edit mode with a "Supprimer" button, behind a confirm dialog. + - The month footer totals entries and expenses. +- [ ] **Step 4: Run** the tests. Expected: PASS. Then edit an op's split in the browser and check that the dashboard reflects it. +- [ ] **Step 5: Commit** with `feat: operations list with filters and edit`. + +--- + +### Task 12: Récurrents & prévu + +**Files:** +- Create: `src/app/(app)/recurrents/page.tsx`, `src/components/recurrents/{RecurringList,RecurringForm,ToConfirmList,UpcomingList}.tsx`, `src/server/actions/recurrings.ts` +- Test: `tests/server/recurrings.test.ts` + +**Interfaces:** +- Produces: + - `saveRecurring(input)`, where the input matches the `Recurring` fields with `amount: string` and `split`, plus the allocation fields for income. + - On update, it deletes the PLANNED occurrences of this recurring with `date ≥ todayParis()`, then runs `syncRecurrings()`. + - Past PLANNED and ACTUAL occurrences stay untouched (§9). + - `setRecurringPaused(id, paused)`: pausing deletes the future PLANNED occurrences, resuming runs sync. + - `endRecurring(id, endDate)`: sets `endDate` and deletes the PLANNED occurrences after it. + - `deleteRecurring(id)`: deletes the future PLANNED occurrences, then the template (ACTUAL history is kept via SetNull). + - Loan-linked recurrings are read-only here, with the hint "Géré depuis Crédits". + +- [ ] **Step 1: Write the failing tests.** + - A rent recurring is synced from `2026-10-27`. The 2026-10-05 occurrence is confirmed (ACTUAL). Then `saveRecurring` changes the amount to 105000 with today `2026-10-27`: the 2026-10-05 ACTUAL keeps the old amount, and the occurrences from 2026-11-05 onward have 105000. + - Pausing leaves 0 PLANNED occurrences ≥ today. Resuming brings back 11. + - `endRecurring(id,'2027-01-31')` leaves the last PLANNED occurrence at `2027-01-05`. +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement.** The page has three sections, in this order: + - **"À confirmer"**: PLANNED with date ≤ today. Each row has an inline amount and date that can be edited, plus "Confirmer" and "Ignorer" buttons. + - **"À venir"**: PLANNED in the next 60 days. This includes one-off planned ops, and has a "+ Dépense prévue" button that opens `OperationForm` with Prévue on. + - **"Modèles récurrents"**: cards showing the label, amount, frequency, next date, payer chip, split chip and allocation chip, with the actions edit / pause / end / delete. +- [ ] **Step 4: Run** the tests. Expected: PASS. Then confirm an occurrence in the browser and check that the dashboard moves it from planned to actual. +- [ ] **Step 5: Commit** with `feat: recurring templates, planned and to-confirm lists`. + +--- + +### Task 13: Budgets + +**Files:** +- Create: `src/app/(app)/budgets/page.tsx`, `src/components/budgets/{BudgetEditor,BudgetHistoryChart}.tsx`, `src/server/actions/budgets.ts` +- Test: `tests/server/budgets.test.ts` + +**Interfaces:** +- Produces: + - `setBudget(categoryId, amount: string, fromMonth: string)`: + - if a budget for that category exists with `startMonth === fromMonth`, it updates it ; + - otherwise it closes the current one (`endMonth = addMonths(fromMonth,-1)`) and creates a new one from `fromMonth` ; + - an empty amount or `"0"` closes the budget without creating a new one. + - `budgetHistory(categoryId, months: number, untilMonth: string): {month; budget: Cents|null; actual: Cents}[]`. + +- [ ] **Step 1: Write the failing tests.** `setBudget(courses,'400','2026-10')` and then `setBudget(courses,'450','2027-01')` give `budgetForMonth` 40000 for `2026-12` and 45000 for `2027-01`. `setBudget(courses,'0','2027-03')` leaves no budget for `2027-03`. `budgetHistory` returns 6 entries in chronological order. +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement.** The page shows the MonthSwitcher, then one row per expense category with the budget input (saved on blur, "applies from this month"), a progress bar (red if over), "réel / budget" and the planned remaining. Below it, a Recharts bar chart compares budget and actual for the selected category over the last 6 months, in the mockup's colors. +- [ ] **Step 4: Run** the tests. Expected: PASS. Then check in the browser. +- [ ] **Step 5: Commit** with `feat: monthly budgets per category with history`. + +--- + +### Task 14: Crédits & charges + +**Files:** +- Create: `src/app/(app)/credits/page.tsx`, `src/app/(app)/credits/[id]/page.tsx`, `src/components/credits/{LoanForm,ScheduleTable,LoanSummaryCards}.tsx`, `src/server/actions/loans.ts` +- Test: `tests/server/loans.test.ts` + +**Interfaces:** +- Consumes: `buildSchedule`, `loanSummary`, `syncRecurrings`, `netCharges`. +- Produces: + - `saveLoan(input)`: + - It creates or updates the Loan and its splits. + - It upserts the linked Recurring: EXPENSE, category "Crédit", label = loan name, amount = schedule payment + insurance, dayOfMonth = the startDate day, startDate = first schedule row not `beforeTracking`, endDate = last row date, and accountUserId and split copied from the loan. + - It then deletes the future PLANNED occurrences of that recurring and runs sync. + - `deleteLoan(id)`: the Recurring cascades and ACTUAL history is kept via SetNull. + +- [ ] **Step 1: Write the failing tests.** `saveLoan` with the Task 5 loan (20000 €, 4 %, 48 months, start `2026-01-05`, insurance 15 €) and today `2026-10-27`: + - creates a Recurring with amount 46658 (45158+1500) and endDate `2029-12-05` ; + - creates occurrences only from `2026-10-05` (no retroactive ones). + + Updating with `referenceDate:'2026-06-10'`, `referenceRemainingCapital:'18000'` and `paymentOverride:'460'` changes the Recurring amount to 47500, and the future PLANNED occurrences follow it. +- [ ] **Step 2: Run** the tests. Expected: FAIL. +- [ ] **Step 3: Implement.** + - **List page**: one card per loan with the name, lender, holder chip, monthly payment incl. insurance, remaining capital today, end date and a progress bar of the % repaid. Below it, the **"Charges affectées"** section shows `netCharges` for the current month (gross − reimbursements = net, as in the mockup). + - **Detail page**: summary cards (mensualité, assurance, capital restant dû, intérêts payés / restants, fin), the affectations this month, and the full schedule table. Rows marked `beforeTracking` are greyed out with the label "avant suivi", and the current row is highlighted. + - **Form fields**: name, lender, capital, rate %, duration in months, first payment date, monthly insurance, holder, split, and the collapsed section "Crédit déjà en cours" (mensualité réelle, capital restant dû au, date). +- [ ] **Step 4: Run** the tests. Expected: PASS. Then in the browser, create the car loan and assign an IK income to it: it shows up in net charges. +- [ ] **Step 5: Commit** with `feat: loans with amortization schedule and net charges`. + +--- + +### Task 15: Settings and CSV export + +**Files:** +- Create: `src/app/(app)/reglages/page.tsx`, `src/components/settings/{UsersSettings,DefaultSplitSettings,CategoriesSettings,ExportForm}.tsx`, `src/server/actions/settings.ts`, `src/app/api/export/route.ts`, `src/server/csv.ts` +- Test: `tests/domain/csv.test.ts` + +**Interfaces:** +- Produces: + - `updateUser(id,{firstName,color,login})` and `changePassword(id,current,next)`, where `next` must have ≥ 8 chars. + - `setDefaultSplit(split)`. + - `saveCategory({id?,name,emoji,kind})` and `archiveCategory(id, archived)`. Archived categories are hidden from the form pickers but still shown on existing ops. + - `opsToCsv(ops, users, categories): string`: + - UTF-8 with BOM, `;` separator, CRLF line endings ; + - header `Date;Type;Libellé;Catégorie;Montant;Payé par;Statut;Part {prénom1} %;Part {prénom2} %;Affecté à;Note` ; + - dates in JJ/MM/AAAA, amounts like `-86,40` (comma decimal, sign by type), statut `Réel`/`Prévu`, SKIPPED excluded ; + - fields containing `;`, `"` or a newline are quoted and their `"` escaped. + - `GET /api/export?from=YYYY-MM&to=YYYY-MM` (auth required) returns `text/csv` with `Content-Disposition: attachment; filename="finances-{from}_{to}.csv"`. + +- [ ] **Step 1: Write the failing test.** + - `opsToCsv` with one expense "Carrefour; Bio" of 8640, 50/50, paid by C, starts with `'Date;Type;'`. + - Its line is `27/10/2026;Dépense;"Carrefour; Bio";Courses;-86,40;C;Réel;50;50;;`. + - A SKIPPED op is absent. +- [ ] **Step 2: Run** the test. Expected: FAIL. +- [ ] **Step 3: Implement** `opsToCsv`, the route and the settings page. The page has four cards: Personnes (prénom, identifiant, couleur, mot de passe), Répartition par défaut, Catégories (list grouped by type with emoji + name inline edit, add, archive toggle) and Export (from/to month pickers + button). +- [ ] **Step 4: Run** `npm test`. Expected: all PASS. Then rename a person in the browser and check that the dashboard uses the new name. +- [ ] **Step 5: Commit** with `feat: settings and CSV export`. + +--- + +### Task 16: Production Docker stack, backups, README + +**Files:** +- Create: `Dockerfile`, `docker-compose.yml`, `docker/entrypoint.sh`, `docker/backup.sh`, `README.md` +- Modify: `.env.example` (production vars), `.dockerignore` + +**Interfaces:** +- Produces: + - `docker compose up -d --build` serves the app on `:3000`. + - The services `app`, `db` and `backup`. + - Env: + - `MARIADB_ROOT_PASSWORD`, `MARIADB_PASSWORD`, `SESSION_SECRET`, `APP_PORT=3000` ; + - `DATABASE_URL` is assembled in compose as `mysql://finances:${MARIADB_PASSWORD}@db:3306/finances`. + +- [ ] **Step 1: Dockerfile.** Use a multi-stage build on `node:24-alpine`: + - deps: `npm ci` ; + - build: `npx prisma generate && npm run build` ; + - runner: copy `.next/standalone`, `.next/static`, `public`, `prisma/`, `node_modules/.prisma` and `node_modules/prisma` (CLI for migrate deploy), plus a tsx-free compiled seed (`npx tsc prisma/seed.ts --outDir dist` or esbuild) and the compiled `scripts/reset-password` ; + - `ENTRYPOINT docker/entrypoint.sh`, which runs `prisma migrate deploy`, then `node dist/seed.js` (idempotent upserts), then `node server.js`. + - The image runs as a non-root user and sets `ENV TZ=Europe/Paris`. +- [ ] **Step 2: Compose.** + - `db`: `mariadb:latest`, with `MARIADB_DATABASE=finances`, `MARIADB_USER=finances`, `MARIADB_PASSWORD` and `MARIADB_ROOT_PASSWORD` ; volume `db_data:/var/lib/mysql` ; healthcheck `healthcheck.sh --connect --innodb_initialized` ; no published ports ; `restart: unless-stopped`. + - `app`: depends on db (healthy), `ports: ["${APP_PORT:-3000}:3000"]`, restart unless-stopped. + - `backup`: `mariadb:latest` running `docker/backup.sh`, mounted read-only, with `./backups:/backups`. The script loops forever: + - sleep until 03:00 Europe/Paris ; + - `mariadb-dump -h db -u root -p$MARIADB_ROOT_PASSWORD --single-transaction finances | gzip > /backups/finances-$(date +%F_%H%M).sql.gz` ; + - `find /backups -name '*.sql.gz' -mtime +30 -delete`. + - It also runs one dump at container start. +- [ ] **Step 3: README** (in French). It covers: + - prerequisites ; + - installation (`git clone git@git.fabout.it:hcloez/hcl-finances-manager.git`, `cp .env.example .env`, generate secrets with `openssl rand -hex 32`, `docker compose up -d --build`, open `http://192.168.1.211:3000`) ; + - updating (`git pull && docker compose up -d --build`) ; + - backups (location, retention, PBS note) ; + - restoring (`gunzip -c backups/X.sql.gz | docker compose exec -T db mariadb -u root -p"$MARIADB_ROOT_PASSWORD" finances`) ; + - resetting a password (`docker compose exec app node dist/reset-password.js `) ; + - local development (dev compose, `npm run dev`, `npm test`). +- [ ] **Step 4: Verify locally.** + - Run `docker compose -p finprod up -d --build` with a temporary `.env` and `APP_PORT=3010`. Expected: all 3 services are up, `curl -s -o /dev/null -w '%{http_code}' localhost:3010/login` prints 200, and `ls backups/` shows one `.sql.gz`. + - Smoke test in the browser: setup → add an expense → dashboard shows it → restart the stack → the data is still there. + - Then run `docker compose -p finprod down -v`. +- [ ] **Step 5: Commit** with `feat: production docker stack with nightly backups and README`. + +--- + +### Task 17: Deploy to 192.168.1.211 + +This needs SSH access to the VM. If it is not available, stop and give the user the README commands. + +- [ ] **Step 1:** Push the branch to `origin` and merge it to `main`, per the finishing-a-development-branch choice. +- [ ] **Step 2:** On the VM, run the README "Installation" steps. +- [ ] **Step 3:** From the workstation, `curl -s -o /dev/null -w '%{http_code}' http://192.168.1.211:3000/login` prints 200. `docker compose ps` on the VM shows the 3 services running and `db` healthy.