From 5ce5363f5050236025c099ab230c7708a24fea79 Mon Sep 17 00:00:00 2001 From: Yugonito Date: Tue, 27 Oct 2026 17:57:50 +0100 Subject: [PATCH] feat(domain): money parsing/formatting and splits Co-Authored-By: Claude Opus 5.5 --- src/domain/money.ts | 71 +++++++++++++++++++++++++++++++ src/domain/types.ts | 33 +++++++++++++++ tests/domain/money.test.ts | 85 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 189 insertions(+) create mode 100644 src/domain/money.ts create mode 100644 src/domain/types.ts create mode 100644 tests/domain/money.test.ts diff --git a/src/domain/money.ts b/src/domain/money.ts new file mode 100644 index 0000000..6acc932 --- /dev/null +++ b/src/domain/money.ts @@ -0,0 +1,71 @@ +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" → centimes. null si vide, nul, négatif ou invalide. */ +export function parseEuro(input: string): Cents | null { + const s = input.replace(/[\s  ]/g, "").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 { + const shares: Record = {}; + 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; +} + +/** "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])); +} diff --git a/src/domain/types.ts b/src/domain/types.ts new file mode 100644 index 0000000..0a52f2a --- /dev/null +++ b/src/domain/types.ts @@ -0,0 +1,33 @@ +export type Cents = number; +export type UserId = string; +/** Répartition en points de base : 100 % = 10000. */ +export type Split = Record; + +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; +} diff --git a/tests/domain/money.test.ts b/tests/domain/money.test.ts new file mode 100644 index 0000000..b49837f --- /dev/null +++ b/tests/domain/money.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from "vitest"; +import { + bpToPercentLabel, + centsFromDecimal, + decimalFromCents, + formatEuro, + fullSplit, + parseEuro, + percentToBp, + shareAmounts, + validateSplit, +} from "@/domain/money"; + +const fr = (n: number) => + new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(n); + +describe("parseEuro", () => { + it("accepts French and dotted inputs", () => { + expect(parseEuro("86,40")).toBe(8640); + expect(parseEuro("86.40")).toBe(8640); + expect(parseEuro("1 234,56")).toBe(123456); + expect(parseEuro("1 234,56")).toBe(123456); + expect(parseEuro("1 234,56")).toBe(123456); + expect(parseEuro("1234")).toBe(123400); + expect(parseEuro("0,5")).toBe(50); + }); + + it("rejects empty, zero, negative and malformed amounts", () => { + for (const s of ["", "0", "0,00", "-5", "abc", "12,345", "1,2,3"]) expect(parseEuro(s)).toBeNull(); + }); +}); + +describe("formatEuro", () => { + it("formats cents with Intl fr-FR", () => { + expect(formatEuro(123456)).toBe(fr(1234.56)); + }); + + it("uses a real minus sign and an explicit plus when asked", () => { + expect(formatEuro(-8640, { sign: true })).toBe("−" + fr(86.4)); + expect(formatEuro(500, { sign: true })).toBe("+" + fr(5)); + expect(formatEuro(-8640)).toBe("−" + fr(86.4)); + }); +}); + +describe("decimal conversions", () => { + it("round-trips between DB decimals and cents", () => { + expect(centsFromDecimal("86.40")).toBe(8640); + expect(centsFromDecimal("86.4")).toBe(8640); + expect(centsFromDecimal("-12.05")).toBe(-1205); + expect(centsFromDecimal({ toString: () => "1000.00" })).toBe(100000); + expect(decimalFromCents(8640)).toBe("86.40"); + expect(decimalFromCents(5)).toBe("0.05"); + }); +}); + +describe("splits", () => { + it("accepts splits summing to 100 %", () => { + expect(validateSplit({ a: 5000, b: 5000 })).toBeNull(); + expect(validateSplit({ a: 3333, b: 6667 })).toBeNull(); + }); + + it("rejects splits not summing to 100 % or with negatives", () => { + 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."); + }); + + it("gives the rounding residue to the account holder", () => { + expect(shareAmounts(1000, { a: 3333, b: 6667 }, "a")).toEqual({ a: 334, b: 666 }); + 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 }); + }); + + it("converts percentages to and from basis points", () => { + expect(percentToBp("33,33")).toBe(3333); + expect(percentToBp("50")).toBe(5000); + expect(percentToBp("abc")).toBeNull(); + expect(percentToBp("101")).toBeNull(); + expect(bpToPercentLabel(3333)).toBe("33,33"); + expect(bpToPercentLabel(5000)).toBe("50"); + }); + + it("builds a 100 % split for one person", () => { + expect(fullSplit("a", ["a", "b"])).toEqual({ a: 10000, b: 0 }); + }); +});