feat(domain): monthly flows, totals, net charges, budgets
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
89bf2a821c
commit
1c7b1a53e4
3 files changed
+236
-1
No files matched your search
@@ -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 }));
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { budgetForMonth, budgetStatus, householdTotals, netCharges, personFlows } from "@/domain/monthly";
|
||||
import { op } from "./fixtures";
|
||||
|
||||
const H100 = { H: 10000, C: 0 };
|
||||
const C100 = { H: 0, C: 10000 };
|
||||
|
||||
const ops = [
|
||||
op({ kind: "INCOME", amount: 300000, accountUserId: "H", split: H100, date: "2026-10-25" }),
|
||||
op({ kind: "INCOME", amount: 200000, accountUserId: "C", split: C100, date: "2026-10-25" }),
|
||||
op({ kind: "EXPENSE", amount: 100000, accountUserId: "H", recurringId: "rent", date: "2026-10-05" }),
|
||||
op({ kind: "INCOME", amount: 20000, accountUserId: "H", allocatedToRecurringId: "rent", allocationMode: "REDUCE_SHARED" }),
|
||||
op({ kind: "EXPENSE", amount: 38000, accountUserId: "H", split: H100, recurringId: "car", date: "2026-10-10" }),
|
||||
op({ kind: "INCOME", amount: 22000, accountUserId: "H", split: H100, allocatedToRecurringId: "car", allocationMode: "REDUCE_SHARED" }),
|
||||
op({ kind: "EXPENSE", amount: 8640, accountUserId: "C", categoryId: "courses", date: "2026-10-27" }),
|
||||
op({ kind: "EXPENSE", amount: 35000, accountUserId: "H", split: H100, status: "PLANNED", date: "2026-10-30" }),
|
||||
op({ kind: "EXPENSE", amount: 99999, accountUserId: "H", date: "2026-11-01" }),
|
||||
op({ kind: "EXPENSE", amount: 77777, accountUserId: "H", status: "SKIPPED", recurringId: "rent", categoryId: "courses" }),
|
||||
];
|
||||
|
||||
describe("personFlows", () => {
|
||||
it("computes H's October flows", () => {
|
||||
expect(personFlows(ops, "2026-10", "H")).toEqual({
|
||||
income: 342000,
|
||||
paidOut: 138000,
|
||||
chargesShare: 60320,
|
||||
ownIncome: 300000,
|
||||
remaining: 239680,
|
||||
});
|
||||
});
|
||||
|
||||
it("computes C's October flows", () => {
|
||||
expect(personFlows(ops, "2026-10", "C")).toEqual({
|
||||
income: 200000,
|
||||
paidOut: 8640,
|
||||
chargesShare: 44320,
|
||||
ownIncome: 200000,
|
||||
remaining: 155680,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("householdTotals", () => {
|
||||
it("includes planned operations and excludes other months and skipped ones", () => {
|
||||
expect(householdTotals(ops, "2026-10")).toEqual({
|
||||
income: 542000,
|
||||
allocatedIncome: 42000,
|
||||
plannedIncome: 0,
|
||||
expense: 181640,
|
||||
plannedExpense: 35000,
|
||||
remaining: 360360,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("netCharges", () => {
|
||||
const charges = [
|
||||
{ id: "rent", label: "Loyer", kind: "recurring" as const, split: { H: 5000, C: 5000 } },
|
||||
{ id: "car", label: "Crédit voiture", kind: "recurring" as const, split: H100 },
|
||||
{ id: "internet", label: "Box", kind: "recurring" as const, split: { H: 5000, C: 5000 } },
|
||||
];
|
||||
|
||||
it("lists charges with reimbursements, gross minus reimbursed", () => {
|
||||
const result = netCharges(ops, "2026-10", charges);
|
||||
expect(result).toEqual([
|
||||
{ id: "rent", label: "Loyer", gross: 100000, reimbursed: 20000, net: 80000, split: { H: 5000, C: 5000 } },
|
||||
{ id: "car", label: "Crédit voiture", gross: 38000, reimbursed: 22000, net: 16000, split: H100 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles a one-off expense as a charge", () => {
|
||||
const hotel = op({ id: "hotel", kind: "EXPENSE", amount: 15000, accountUserId: "H", split: H100 });
|
||||
const refund = op({ kind: "INCOME", amount: 15000, accountUserId: "H", split: H100, allocatedToOperationId: "hotel" });
|
||||
const result = netCharges([hotel, refund], "2026-10", [{ id: "hotel", label: "Hôtel", kind: "operation", split: H100 }]);
|
||||
expect(result).toEqual([{ id: "hotel", label: "Hôtel", gross: 15000, reimbursed: 15000, net: 0, split: H100 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("budgets", () => {
|
||||
it("compares actual spending to the budget", () => {
|
||||
expect(budgetStatus(ops, "2026-10", [{ categoryId: "courses", amount: 40000 }])).toEqual([
|
||||
{ categoryId: "courses", budget: 40000, actual: 8640, plannedRemaining: 0, over: false },
|
||||
]);
|
||||
expect(budgetStatus(ops, "2026-10", [{ categoryId: "courses", amount: 5000 }])[0].over).toBe(true);
|
||||
});
|
||||
|
||||
it("picks the budget active in the month, latest start wins", () => {
|
||||
const budgets = [
|
||||
{ categoryId: "courses", monthlyAmount: 30000, startMonth: "2026-01", endMonth: null },
|
||||
{ categoryId: "courses", monthlyAmount: 40000, startMonth: "2026-09", endMonth: null },
|
||||
{ categoryId: "loisirs", monthlyAmount: 15000, startMonth: "2026-11", endMonth: null },
|
||||
{ categoryId: "auto", monthlyAmount: 10000, startMonth: "2026-01", endMonth: "2026-09" },
|
||||
];
|
||||
expect(budgetForMonth(budgets, "2026-10")).toEqual([{ categoryId: "courses", amount: 40000 }]);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import { defineConfig } from "vitest/config";
|
||||
import path from "node:path";
|
||||
|
||||
export default defineConfig({
|
||||
resolve: { alias: { "@": path.resolve(__dirname, "src") } },
|
||||
resolve: { alias: { "@": path.resolve(import.meta.dirname, "src") } },
|
||||
test: {
|
||||
environment: "node",
|
||||
include: ["tests/**/*.test.ts"],
|
||||
Reference in new issue
Block a user