Budgets from your full months, the middle value per category, and say which months
A half month at the start of your history or one unusual month no longer sets the budget. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c3276ab5c1
commit
37a97fe20a
6 files changed
+40
-15
No files matched your search
@@ -2,12 +2,12 @@ import { SlidersHorizontal } from "lucide-react";
|
|||||||
import { AskButton } from "@/components/Assistant";
|
import { AskButton } from "@/components/Assistant";
|
||||||
import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor";
|
import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor";
|
||||||
import { EmptyBank } from "@/components/EmptyBank";
|
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 { categories, getUser, isSpend, moneyByMonth, sumOf, today, transactionsSince, typicalMonthly } from "@/lib/data";
|
||||||
import { monthStart, ymd } from "@/lib/format";
|
import { monthStart, ymd } from "@/lib/format";
|
||||||
|
|
||||||
// Budgets: tracked against this month with a pace marker; suggestions come from the last 3 full months,
|
// Budgets: tracked against this month with a pace marker. Suggestions come from the full months of data (up to 3, the
|
||||||
// never below this month's spending so far. Income is the typical month every page shows (typicalMonthly).
|
// 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 DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
const nextDay = (d: string) => new Date(Date.parse(`${d}T00:00:00Z`) + 864e5).toISOString().slice(0, 10);
|
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) =>
|
const sum = (catId: string, month?: string) =>
|
||||||
sumOf((month ? txns : past).filter((r) => r.category_id === catId && (!month || r.month.startsWith(month))), (r) => r.spend);
|
sumOf((month ? txns : past).filter((r) => r.category_id === catId && (!month || r.month.startsWith(month))), (r) => r.spend);
|
||||||
const income = typical?.income ?? 0;
|
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
|
const rows: BudgetCat[] = cats
|
||||||
.filter((c) => c.kind === "spend")
|
.filter((c) => c.kind === "spend")
|
||||||
.map((c) => {
|
.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);
|
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 };
|
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 (
|
return (
|
||||||
// The key takes in saved changes from elsewhere (the AI's Apply) on refresh.
|
// The key takes in saved changes from elsewhere (the AI's Apply) on refresh.
|
||||||
<BudgetEditor key={JSON.stringify(budgets) + (range ? `${from}|${to}` : "")} cats={rows} initial={budgets} year={yearMonths} range={range} today={ymd(now)} income={Math.round(income)} now={now.toISOString()} tableMissing={!!saved.error} aside={
|
<BudgetEditor key={JSON.stringify(budgets) + (range ? `${from}|${to}` : "")} basis={basis} cats={rows} initial={budgets} year={yearMonths} range={range} today={ymd(now)} income={Math.round(income)} now={now.toISOString()} tableMissing={!!saved.error} aside={
|
||||||
<AskButton
|
<AskButton
|
||||||
q={`Look at my budget, my income and my last 3 months of spending. Which categories should I lower, by how much, and what would that free up each month?${budgetContext(rows.filter((c) => c.id in budgets).map((c) => [c.label, budgets[c.id]]))}`}
|
q={`Look at my budget, my income and my last 3 months of spending. Which categories should I lower, by how much, and what would that free up each month?${budgetContext(rows.filter((c) => 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"
|
className="card-link w-full p-5 text-left flex items-center gap-4"
|
||||||
|
|||||||
@@ -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.
|
// 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" };
|
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<string, number>; 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<string, number>; year: MonthSpend[]; range: BudgetRange | null; today: string; income: number; now: string; tableMissing: boolean; aside?: React.ReactNode }) {
|
||||||
const { money0, dateLabel } = useMoney();
|
const { money0, dateLabel } = useMoney();
|
||||||
const root = useRef<HTMLDivElement>(null);
|
const root = useRef<HTMLDivElement>(null);
|
||||||
const [budgets, setBudgets] = useState(initial);
|
const [budgets, setBudgets] = useState(initial);
|
||||||
@@ -122,7 +122,7 @@ export function BudgetEditor({ cats: all, initial, year, range, today, income, n
|
|||||||
<NewCategory taken={cats.map((c) => c.label)} onDone={(id, label, amount) => { setSheet(null); setBudgets((x) => ({ ...x, [id]: amount })); setFresh(id); toast(`Added ${label}`); }} />
|
<NewCategory taken={cats.map((c) => c.label)} onDone={(id, label, amount) => { setSheet(null); setBudgets((x) => ({ ...x, [id]: amount })); setFresh(id); toast(`Added ${label}`); }} />
|
||||||
</Sheet>
|
</Sheet>
|
||||||
<Sheet open={sheet === "suggest"} onClose={() => setSheet(null)} title="Suggested budgets">
|
<Sheet open={sheet === "suggest"} onClose={() => setSheet(null)} title="Suggested budgets">
|
||||||
<Suggest cats={suggestion} income={0} onUse={useSuggested} disabled={error === SETUP} sticky />
|
<Suggest cats={suggestion} income={0} basis={basis} onUse={useSuggested} disabled={error === SETUP} sticky />
|
||||||
</Sheet>
|
</Sheet>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -133,9 +133,9 @@ export function BudgetEditor({ cats: all, initial, year, range, today, income, n
|
|||||||
<div className="card overflow-hidden">
|
<div className="card overflow-hidden">
|
||||||
<div className="p-6 md:p-8 pb-4 md:pb-4 max-w-xl space-y-2">
|
<div className="p-6 md:p-8 pb-4 md:pb-4 max-w-xl space-y-2">
|
||||||
<h2 className="text-2xl font-semibold">Set a budget from how you really spend</h2>
|
<h2 className="text-2xl font-semibold">Set a budget from how you really spend</h2>
|
||||||
<p className="text-sm text-muted">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.</p>
|
<p className="text-sm text-muted">{basis} Use them as they are, or change any one after.</p>
|
||||||
</div>
|
</div>
|
||||||
<Suggest cats={suggestion} income={income} onUse={useSuggested} disabled={error === SETUP} alt={<button className="btn" onClick={() => setSheet("add")}>Add one at a time</button>} />
|
<Suggest cats={suggestion} income={income} basis={basis} onUse={useSuggested} disabled={error === SETUP} alt={<button className="btn" onClick={() => setSheet("add")}>Add one at a time</button>} />
|
||||||
{error && <div className="px-6 md:px-8 pb-6"><ErrorNote error={error} /></div>}
|
{error && <div className="px-6 md:px-8 pb-6"><ErrorNote error={error} /></div>}
|
||||||
{sheets}
|
{sheets}
|
||||||
</div>
|
</div>
|
||||||
@@ -547,8 +547,8 @@ function Editor({ label, value, onSave, onCancel, onDelete }: { label: string; v
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Preview of budgets from the 3-month average.
|
// Preview of the suggested budgets: the usual month per category.
|
||||||
function Suggest({ cats, income, onUse, disabled, alt, sticky }: { cats: BudgetCat[]; income: number; onUse: () => void; disabled: boolean; alt?: React.ReactNode; sticky?: boolean }) {
|
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 { money0 } = useMoney();
|
||||||
const total = cats.reduce((s, c) => s + c.suggested, 0);
|
const total = cats.reduce((s, c) => s + c.suggested, 0);
|
||||||
if (!cats.length) return <div className="px-6 md:px-8 pb-6 space-y-4"><p className="text-sm text-muted">Nothing to suggest right now.</p>{alt}</div>;
|
if (!cats.length) return <div className="px-6 md:px-8 pb-6 space-y-4"><p className="text-sm text-muted">Nothing to suggest right now.</p>{alt}</div>;
|
||||||
@@ -566,7 +566,7 @@ function Suggest({ cats, income, onUse, disabled, alt, sticky }: { cats: BudgetC
|
|||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
<div className={`${sticky ? "sticky bottom-0" : ""} bg-surface px-5 md:px-8 py-5 space-y-3`}>
|
<div className={`${sticky ? "sticky bottom-0" : ""} bg-surface px-5 md:px-8 py-5 space-y-3`}>
|
||||||
<p className="text-xs text-muted">Each one is your 3-month average, rounded up, and never less than you've spent this month.</p>
|
<p className="text-xs text-muted">{basis} Never less than you've already spent this month.</p>
|
||||||
{income > 0 && <p className="text-sm text-muted">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.`}</p>}
|
{income > 0 && <p className="text-sm text-muted">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.`}</p>}
|
||||||
<div className="flex flex-wrap items-center gap-3">
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
<button className="btn-primary" onClick={onUse} disabled={disabled}>Use these · {money0(total)}/mo</button>
|
<button className="btn-primary" onClick={onUse} disabled={disabled}>Use these · {money0(total)}/mo</button>
|
||||||
|
|||||||
@@ -60,3 +60,11 @@ console.log("budget: ok");
|
|||||||
]);
|
]);
|
||||||
assert.deepEqual(budgetChanges({ Coffee: null }, cats, {}), []); // nothing to remove
|
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");
|
||||||
@@ -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.
|
// 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);
|
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.
|
// 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.
|
// "Use these" never puts the user over budget on day one.
|
||||||
export const suggest = (avg: number, spentThisMonth: number) => roundUp(Math.max(avg, spentThisMonth));
|
export const suggest = (avg: number, spentThisMonth: number) => roundUp(Math.max(avg, spentThisMonth));
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ const rows = [
|
|||||||
{ month: "2026-09-01", income: 3240, spend: 1800 },
|
{ month: "2026-09-01", income: 3240, spend: 1800 },
|
||||||
{ month: "2026-10-01", income: 3240, spend: 7000 },
|
{ 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");
|
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:
|
// 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.
|
// October so far (2,835.92 over 23 days) scaled to a month.
|
||||||
|
|||||||
+2
-2
@@ -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 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 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));
|
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 seen = [...new Set(rows.map((r) => r.month.slice(0, 7)))].sort();
|
||||||
const first = seen.find(paid);
|
const first = seen.find(paid);
|
||||||
if (!first) return null;
|
if (!first) return null;
|
||||||
@@ -48,7 +48,7 @@ export function typicalMonth(rows: { month: string; income: number; spend: numbe
|
|||||||
if (days < 14) return null;
|
if (days < 14) return null;
|
||||||
const since = seen.filter((ym) => ym >= start.slice(0, 7));
|
const since = seen.filter((ym) => ym >= start.slice(0, 7));
|
||||||
const scale = 365 / 12 / days;
|
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.
|
// The take-home pay typed in onboarding (profile.pay), as a month. Used only when no paycheck is found, never added to one.
|
||||||
|
|||||||
Reference in new issue
Block a user