diff --git a/src/app/(app)/budgets/page.tsx b/src/app/(app)/budgets/page.tsx index b11ab0e..82825c7 100644 --- a/src/app/(app)/budgets/page.tsx +++ b/src/app/(app)/budgets/page.tsx @@ -2,12 +2,12 @@ import { SlidersHorizontal } from "lucide-react"; import { AskButton } from "@/components/Assistant"; import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor"; import { EmptyBank } from "@/components/EmptyBank"; -import { budgetContext, suggest, type MonthSpend } from "@/lib/budget"; +import { budgetContext, median, monthList, suggest, type MonthSpend } from "@/lib/budget"; import { categories, getUser, isSpend, moneyByMonth, sumOf, today, transactionsSince, typicalMonthly } from "@/lib/data"; import { monthStart, ymd } from "@/lib/format"; -// Budgets: tracked against this month with a pace marker; suggestions come from the last 3 full months, -// never below this month's spending so far. Income is the typical month every page shows (typicalMonthly). +// Budgets: tracked against this month with a pace marker. Suggestions come from the full months of data (up to 3, the +// ones the typical month uses), the middle value per category, never below this month's spending so far. Income is the typical month every page shows (typicalMonthly). const DAY = /^\d{4}-\d{2}-\d{2}$/; const nextDay = (d: string) => new Date(Date.parse(`${d}T00:00:00Z`) + 864e5).toISOString().slice(0, 10); @@ -31,11 +31,15 @@ export default async function Budgets({ searchParams }: { searchParams: Promise< const sum = (catId: string, month?: string) => sumOf((month ? txns : past).filter((r) => r.category_id === catId && (!month || r.month.startsWith(month))), (r) => r.spend); const income = typical?.income ?? 0; + const clean = typical?.list ?? []; + const basis = clean.length ? `Built from ${monthList(clean)}, your full months of data: what you usually spend in each category, rounded up.` : "Built from the spending broke has so far, rounded up. It gets sharper after your first full month."; const rows: BudgetCat[] = cats .filter((c) => c.kind === "spend") .map((c) => { - const avg = sum(c.id) / monthsOfData; + // The full months broke has (the ones the typical month uses), middle value per category. Without one full month yet, + // the average of what there is. + const avg = clean.length ? median(clean.map((m) => sum(c.id, m))) : sum(c.id) / monthsOfData; const spent = sum(c.id, thisMonth); return { id: c.id, label: c.label, icon: c.icon, color: c.color, spent, last: sum(c.id, lastMonth), avg, suggested: suggest(avg, spent), main: c.key !== "BANK_FEES" && Math.max(avg, spent) >= 10 }; }); @@ -61,7 +65,7 @@ export default async function Budgets({ searchParams }: { searchParams: Promise< return ( // The key takes in saved changes from elsewhere (the AI's Apply) on refresh. - c.id in budgets).map((c) => [c.label, budgets[c.id]]))}`} className="card-link w-full p-5 text-left flex items-center gap-4" diff --git a/src/components/BudgetEditor.tsx b/src/components/BudgetEditor.tsx index 5b50388..64fe9f1 100644 --- a/src/components/BudgetEditor.tsx +++ b/src/components/BudgetEditor.tsx @@ -23,7 +23,7 @@ export type BudgetCat = { id: string; label: string; icon: string; color: string // Bars use the app's chart blue, like the rest of the app; only an overspend turns red. const TEXT = { ok: "text-muted", near: "text-ink", over: "text-bad" }; -export function BudgetEditor({ cats: all, initial, year, range, today, income, now, tableMissing, aside }: { cats: BudgetCat[]; initial: Record; year: MonthSpend[]; range: BudgetRange | null; today: string; income: number; now: string; tableMissing: boolean; aside?: React.ReactNode }) { +export function BudgetEditor({ basis, cats: all, initial, year, range, today, income, now, tableMissing, aside }: { basis: string; cats: BudgetCat[]; initial: Record; year: MonthSpend[]; range: BudgetRange | null; today: string; income: number; now: string; tableMissing: boolean; aside?: React.ReactNode }) { const { money0, dateLabel } = useMoney(); const root = useRef(null); const [budgets, setBudgets] = useState(initial); @@ -122,7 +122,7 @@ export function BudgetEditor({ cats: all, initial, year, range, today, income, n c.label)} onDone={(id, label, amount) => { setSheet(null); setBudgets((x) => ({ ...x, [id]: amount })); setFresh(id); toast(`Added ${label}`); }} /> setSheet(null)} title="Suggested budgets"> - + ); @@ -133,9 +133,9 @@ export function BudgetEditor({ cats: all, initial, year, range, today, income, n

Set a budget from how you really spend

-

These are your averages for the last 3 months, rounded up, and never less than you've spent this month. Use them as they are, or add one category at a time.

+

{basis} Use them as they are, or change any one after.

- setSheet("add")}>Add one at a time} /> + setSheet("add")}>Add one at a time} /> {error &&
} {sheets}
@@ -547,8 +547,8 @@ function Editor({ label, value, onSave, onCancel, onDelete }: { label: string; v ); } -// Preview of budgets from the 3-month average. -function Suggest({ cats, income, onUse, disabled, alt, sticky }: { cats: BudgetCat[]; income: number; onUse: () => void; disabled: boolean; alt?: React.ReactNode; sticky?: boolean }) { +// Preview of the suggested budgets: the usual month per category. +function Suggest({ cats, income, basis, onUse, disabled, alt, sticky }: { cats: BudgetCat[]; income: number; basis: string; onUse: () => void; disabled: boolean; alt?: React.ReactNode; sticky?: boolean }) { const { money0 } = useMoney(); const total = cats.reduce((s, c) => s + c.suggested, 0); if (!cats.length) return

Nothing to suggest right now.

{alt}
; @@ -566,7 +566,7 @@ function Suggest({ cats, income, onUse, disabled, alt, sticky }: { cats: BudgetC ))}
-

Each one is your 3-month average, rounded up, and never less than you've spent this month.

+

{basis} Never less than you've already spent this month.

{income > 0 &&

You bring in about {money0(income)} a month. {income >= total ? `This leaves ${money0(income - total)} to save.` : `You're spending ${money0(total - income)} more than you earn.`}

}
diff --git a/src/lib/budget.test.ts b/src/lib/budget.test.ts index b5c5250..1215bc7 100644 --- a/src/lib/budget.test.ts +++ b/src/lib/budget.test.ts @@ -60,3 +60,11 @@ console.log("budget: ok"); ]); assert.deepEqual(budgetChanges({ Coffee: null }, cats, {}), []); // nothing to remove } + +// The usual month: one big month doesn't set the budget. +import { median as med, monthList as ml } from "./budget.ts"; +assert.equal(med([120, 900, 140]), 140); +assert.equal(med([100, 200]), 150); +assert.equal(med([]), 0); +assert.equal(ml(["2026-10", "2026-08", "2026-09"]), "August, September and October"); +assert.equal(ml(["2026-10"]), "October"); diff --git a/src/lib/budget.ts b/src/lib/budget.ts index 74dc86e..66a1a18 100644 --- a/src/lib/budget.ts +++ b/src/lib/budget.ts @@ -6,6 +6,19 @@ export const step = (n: number) => (n < 200 ? 10 : n < 1000 ? 25 : 50); // A suggested budget: the average rounded up to the next step. export const roundUp = (n: number) => (n > 0 ? Math.ceil(n / step(n)) * step(n) : 0); +// The middle value: one unusual month (a holiday, a big repair) doesn't set the budget. Averages the middle two when even. +export function median(ns: number[]) { + if (!ns.length) return 0; + const s = [...ns].sort((a, b) => a - b), mid = Math.floor(s.length / 2); + return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2; +} + +// "August, September and October" from ["2026-10", "2026-08", "2026-09"]. +export function monthList(months: string[]) { + const names = [...months].sort().map((m) => new Date(`${m}-01T00:00:00Z`).toLocaleDateString("en-US", { month: "long", timeZone: "UTC" })); + return names.length <= 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`; +} + // A suggested budget for a category: the 3-month average, but never below what is already spent this month, rounded up. // "Use these" never puts the user over budget on day one. export const suggest = (avg: number, spentThisMonth: number) => roundUp(Math.max(avg, spentThisMonth)); diff --git a/src/lib/insights.test.ts b/src/lib/insights.test.ts index 57a6be9..9e20b5e 100644 --- a/src/lib/insights.test.ts +++ b/src/lib/insights.test.ts @@ -86,7 +86,7 @@ const rows = [ { month: "2026-09-01", income: 3240, spend: 1800 }, { month: "2026-10-01", income: 3240, spend: 7000 }, ]; -assert.deepEqual(typicalMonth(rows, "2026-10-23", "2026-07-30"), { income: 3240, spend: 1000, months: 2 }); +assert.deepEqual(typicalMonth(rows, "2026-10-23", "2026-07-30"), { income: 3240, spend: 1000, months: 2, list: ["2026-09", "2026-08"] }, "the partial July is left out"); assert.equal(typicalMonth(rows, "2026-10-23", "2026-06-01")!.income, (810 + 3240 + 3240) / 3, "3 full months"); // The e2e user: history from Jul 30 but only cents of interest until October's paychecks. Not $0.12 a month: // October so far (2,835.92 over 23 days) scaled to a month. diff --git a/src/lib/insights.ts b/src/lib/insights.ts index 967eb17..a958f7d 100644 --- a/src/lib/insights.ts +++ b/src/lib/insights.ts @@ -39,7 +39,7 @@ export function typicalMonth(rows: { month: string; income: number; spend: numbe const of = (months: string[], f: (r: (typeof rows)[number]) => number) => sum(rows.filter((r) => months.includes(r.month.slice(0, 7))).map(f)); const paid = (ym: string) => of([ym], (r) => r.income) >= 100; const full = [1, 2, 3].map((k) => new Date(Date.UTC(y, m - 1 - k, 1)).toISOString().slice(0, 7)).filter((ym) => `${ym}-01` >= oldest && paid(ym)); - if (full.length) return { income: of(full, (r) => r.income) / full.length, spend: of(full, (r) => r.spend) / full.length, months: full.length }; + if (full.length) return { income: of(full, (r) => r.income) / full.length, spend: of(full, (r) => r.spend) / full.length, months: full.length, list: full }; const seen = [...new Set(rows.map((r) => r.month.slice(0, 7)))].sort(); const first = seen.find(paid); if (!first) return null; @@ -48,7 +48,7 @@ export function typicalMonth(rows: { month: string; income: number; spend: numbe if (days < 14) return null; const since = seen.filter((ym) => ym >= start.slice(0, 7)); const scale = 365 / 12 / days; - return { income: of(since, (r) => r.income) * scale, spend: of(since, (r) => r.spend) * scale, months: 0 }; + return { income: of(since, (r) => r.income) * scale, spend: of(since, (r) => r.spend) * scale, months: 0, list: [] as string[] }; } // The take-home pay typed in onboarding (profile.pay), as a month. Used only when no paycheck is found, never added to one.