diff --git a/src/domain/recurrence.ts b/src/domain/recurrence.ts new file mode 100644 index 0000000..b63be44 --- /dev/null +++ b/src/domain/recurrence.ts @@ -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 & { status: "PLANNED"; occurrenceDate: string }; + +const STEP: Record = { 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, + 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; +} diff --git a/tests/domain/recurrence.test.ts b/tests/domain/recurrence.test.ts new file mode 100644 index 0000000..0f370c2 --- /dev/null +++ b/tests/domain/recurrence.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; +import { occurrenceDates, planOccurrences, splitForAllocation, type RecurringDef } from "@/domain/recurrence"; + +const users = ["H", "C"]; + +function rec(partial: Partial): RecurringDef { + return { + id: "r", + kind: "EXPENSE", + amount: 100000, + label: "Loyer", + categoryId: "logement", + accountUserId: "H", + split: { H: 5000, C: 5000 }, + frequency: "MONTHLY", + dayOfMonth: 5, + startDate: "2026-01-05", + endDate: null, + paused: false, + allocatedToRecurringId: null, + allocationMode: null, + ...partial, + }; +} + +describe("occurrenceDates", () => { + it("clamps day 31 to the end of short months", () => { + expect(occurrenceDates(rec({ dayOfMonth: 31, startDate: "2026-10-31" }), "2026-10", "2027-03")).toEqual([ + "2026-10-31", "2026-11-30", "2026-12-31", "2027-01-31", "2027-02-28", "2027-03-31", + ]); + }); + + it("steps quarterly from the start month", () => { + expect( + occurrenceDates(rec({ frequency: "QUARTERLY", dayOfMonth: 15, startDate: "2026-11-15" }), "2026-10", "2027-12"), + ).toEqual(["2026-11-15", "2027-02-15", "2027-05-15", "2027-08-15", "2027-11-15"]); + }); + + it("steps yearly from the start month", () => { + expect( + occurrenceDates(rec({ frequency: "YEARLY", dayOfMonth: 1, startDate: "2025-03-01" }), "2026-01", "2027-12"), + ).toEqual(["2026-03-01", "2027-03-01"]); + }); + + it("stops at the end date", () => { + expect( + occurrenceDates(rec({ dayOfMonth: 20, startDate: "2026-10-20", endDate: "2026-12-15" }), "2026-10", "2027-02"), + ).toEqual(["2026-10-20", "2026-11-20"]); + }); + + it("does not produce a date before the start date in the start month", () => { + expect(occurrenceDates(rec({ dayOfMonth: 5, startDate: "2026-10-27" }), "2026-10", "2026-11")).toEqual(["2026-11-05"]); + }); +}); + +describe("splitForAllocation", () => { + it("copies the charge split, gives all to the beneficiary, or uses the custom split", () => { + expect(splitForAllocation("REDUCE_SHARED", "H", { H: 5000, C: 5000 }, {}, users)).toEqual({ H: 5000, C: 5000 }); + expect(splitForAllocation("BENEFICIARY_ONLY", "H", { H: 5000, C: 5000 }, {}, users)).toEqual({ H: 10000, C: 0 }); + expect(splitForAllocation("CUSTOM", "H", { H: 5000, C: 5000 }, { H: 7000, C: 3000 }, users)).toEqual({ H: 7000, C: 3000 }); + }); +}); + +describe("planOccurrences", () => { + const rent = rec({ id: "rent", startDate: "2024-01-05" }); + + it("plans 12 months from the current month, never retroactively", () => { + const planned = planOccurrences([rent], new Set(), "2026-10-27", users); + expect(planned).toHaveLength(12); + expect(planned[0]).toMatchObject({ occurrenceDate: "2026-10-05", date: "2026-10-05", status: "PLANNED", recurringId: "rent", amount: 100000 }); + expect(planned[11].occurrenceDate).toBe("2027-09-05"); + }); + + it("skips existing occurrences and paused recurrings", () => { + expect(planOccurrences([rent], new Set(["rent|2026-10-05"]), "2026-10-27", users)).toHaveLength(11); + expect(planOccurrences([{ ...rent, paused: true }], new Set(), "2026-10-27", users)).toHaveLength(0); + }); + + it("gives an unallocated income entirely to its receiver", () => { + const salary = rec({ id: "salary", kind: "INCOME", split: { H: 5000, C: 5000 } }); + expect(planOccurrences([salary], new Set(), "2026-10-27", users)[0].split).toEqual({ H: 10000, C: 0 }); + }); + + it("splits an allocated income like its target charge", () => { + const car = rec({ id: "car", split: { H: 10000, C: 0 } }); + const ik = rec({ id: "ik", kind: "INCOME", allocatedToRecurringId: "car", allocationMode: "REDUCE_SHARED" }); + const planned = planOccurrences([car, ik], new Set(), "2026-10-27", users).filter((p) => p.recurringId === "ik"); + expect(planned[0]).toMatchObject({ split: { H: 10000, C: 0 }, allocatedToRecurringId: "car", allocationMode: "REDUCE_SHARED" }); + }); + + it("drops a dangling allocation target", () => { + const ik = rec({ id: "ik", kind: "INCOME", allocatedToRecurringId: "gone", allocationMode: "REDUCE_SHARED" }); + const planned = planOccurrences([ik], new Set(), "2026-10-27", users); + expect(planned[0]).toMatchObject({ split: { H: 10000, C: 0 }, allocatedToRecurringId: null, allocationMode: null }); + }); +});