Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions src/components/BudgetEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { PageDates } from "@/components/PageDates";
import { CATEGORY_ICON_KEYS, CategoryIcon } from "@/components/Icons";
import { CountUp, EASE, firstVisit, reduced } from "@/components/motion";
import { toast } from "@/components/Toast";
import { budgetContext, daysBetween, merge, month, perDay, scaleBudget, startPeriod, step, tone, yearView, type MonthSpend } from "@/lib/budget";
import { budgetContext, daysBetween, merge, month, perDay, retune, scaleBudget, startPeriod, step, tone, yearView, type MonthSpend } from "@/lib/budget";
import { useMoney } from "@/components/Money";

export type BudgetRange = { from: string; to: string; start: string; end: string; spent: Record<string, number> };
Expand Down Expand Up @@ -93,10 +93,13 @@ export function BudgetEditor({ basis, cats: all, initial, year, range, today, in

// Fills main categories that have no budget yet; amounts you set stay.
const suggestion = cats.filter((c) => c.main && !(c.id in budgets)).sort((a, b) => b.suggested - a.suggested);
// The Suggest sheet: budgets well off from real spending, plus main categories with none yet.
const retuned = retune(cats, budgets);
// Saves exactly what the suggestion list shows after any edits.
const useSuggested = (picked: Record<string, number>) => {
const saveSuggested = (picked: Record<string, number>, verb = "Added") => {
setSheet(null);
apply(picked, `Added ${Object.keys(picked).length} budgets`);
const n = Object.keys(picked).length;
apply(picked, `${verb} ${n} ${n === 1 ? "budget" : "budgets"}`);
};

const sheets = (
Expand All @@ -123,7 +126,10 @@ export function BudgetEditor({ basis, cats: all, initial, year, range, today, in
<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 open={sheet === "suggest"} onClose={() => setSheet(null)} title="Suggested budgets">
<Suggest key={suggestion.map((c) => c.id).join()} cats={suggestion} open={open} income={0} basis={basis} onUse={useSuggested} disabled={error === SETUP} sticky />
{/* Each open starts from the latest numbers. The AI button closes the sheet so the assistant isn't behind it. */}
<Suggest key={`${sheet}${retuned.map((c) => c.id).join()}`} cats={retuned} open={open} current={budgets} income={0} basis={basis} onUse={(p) => saveSuggested(p, "Updated")} disabled={error === SETUP} sticky
empty="Your budgets are close to what you really spend."
alt={aside && <div className="basis-full" onClickCapture={() => setSheet(null)}>{aside}</div>} />
</Sheet>
</>
);
Expand All @@ -136,7 +142,7 @@ export function BudgetEditor({ basis, cats: all, initial, year, range, today, in
<h2 className="text-2xl font-semibold">Set a budget from how you really spend</h2>
<p className="text-sm text-muted">{basis} Press an amount to change it. Remove any you don&apos;t want, or add another.</p>
</div>
<Suggest cats={suggestion} open={open} income={income} basis={basis} onUse={useSuggested} disabled={error === SETUP} alt={<button className="btn" onClick={() => setSheet("add")}>Add one at a time</button>} />
<Suggest cats={suggestion} open={open} income={income} basis={basis} onUse={saveSuggested} 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>}
{sheets}
</div>
Expand Down Expand Up @@ -561,20 +567,22 @@ function Editor({ label, value, onSave, onCancel, onDelete }: { label: string; v

// The suggested budgets, the usual month per category, as a draft: change an amount, remove a row or add a category
// before saving. Nothing saves until Use these, which saves exactly the rows shown.
function Suggest({ cats, open, income, basis, onUse, disabled, alt, sticky }: { cats: BudgetCat[]; open: BudgetCat[]; income: number; basis: string; onUse: (picked: Record<string, number>) => void; disabled: boolean; alt?: React.ReactNode; sticky?: boolean }) {
// With `current` (budgets you already have), a row with a budget shows the change: $650 → $350.
function Suggest({ cats, open, current, income, basis, onUse, disabled, alt, sticky, empty = "Nothing to suggest right now." }: { cats: BudgetCat[]; open: BudgetCat[]; current?: Record<string, number>; income: number; basis: string; onUse: (picked: Record<string, number>) => void; disabled: boolean; alt?: React.ReactNode; sticky?: boolean; empty?: string }) {
const { money0, symbol } = useMoney();
const [draft, setDraft] = useState<Record<string, number>>(() => Object.fromEntries(cats.map((c) => [c.id, c.suggested])));
const set = (id: string, n: number | null) => setDraft((d) => merge(d, { [id]: n }));
const rows = Object.keys(draft).map((id) => open.find((c) => c.id === id)).filter((c) => !!c);
const rows = Object.keys(draft).map((id) => cats.find((c) => c.id === id) ?? open.find((c) => c.id === id)).filter((c) => !!c);
const total = Object.values(draft).reduce((s, n) => s + n, 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">{empty}</p>{alt}</div>;
return (
<>
<ul className="grid @2xl:grid-cols-2 gap-x-8 px-5 md:px-8">
{rows.map((c) => (
<li key={c.id} className="flex items-center gap-3 py-1.5 border-b border-line">
<CategoryIcon icon={c.icon} color={c.color} size={30} />
<span className="flex-1 min-w-0 truncate">{c.label}</span>
{current && c.id in current && <span className="text-sm text-muted tabular whitespace-nowrap">{money0(current[c.id])} →</span>}
<span className="text-sm font-medium"><AmountCell label={c.label} value={draft[c.id]} symbol={symbol} onSave={(n) => set(c.id, n)} onType={(n) => set(c.id, n)} /></span>
<button onClick={() => set(c.id, null)} aria-label={`Remove ${c.label}`} className="size-8 grid place-items-center rounded-full text-muted hover:text-bad hover:bg-[var(--hover-strong)] shrink-0"><X size={15} /></button>
</li>
Expand All @@ -585,7 +593,7 @@ function Suggest({ cats, open, income, basis, onUse, disabled, alt, sticky }: {
<p className="text-xs text-muted">{basis} Never less than you&apos;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>}
<div className="flex flex-wrap items-center gap-3">
<button className="btn-primary" onClick={() => onUse(draft)} disabled={disabled || !rows.length}>Use these · {money0(total)}/mo</button>
<button className="btn-primary" onClick={() => onUse(draft)} disabled={disabled || !rows.length}>{current ? `Apply ${rows.length === 1 ? "it" : `all ${rows.length}`}` : `Use these · ${money0(total)}/mo`}</button>
{alt}
</div>
</div>
Expand Down
15 changes: 14 additions & 1 deletion src/lib/budget.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Run: node src/lib/budget.test.ts
import assert from "node:assert/strict";
import { budgetChanges, daysBetween, scaleBudget, startPeriod, yearView, merge, month, perDay, roundUp, step, suggest, tone } from "./budget.ts";
import { budgetChanges, retune, wellOff, daysBetween, scaleBudget, startPeriod, yearView, merge, month, perDay, roundUp, step, suggest, tone } from "./budget.ts";

assert.equal(roundUp(0), 0);
assert.equal(roundUp(42.1), 50);
Expand Down Expand Up @@ -68,3 +68,16 @@ 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");

assert.equal(wellOff(650, 350), true);
assert.equal(wellOff(100, 110), false); // $10 gap
assert.equal(wellOff(1600, 1650), false); // $50 is under a fifth
assert.equal(wellOff(100, 0), false); // nothing spent: leave it
{
const cats = [
{ id: "a", suggested: 350, main: true }, { id: "b", suggested: 300, main: true }, { id: "c", suggested: 100, main: true },
{ id: "d", suggested: 80, main: true }, { id: "e", suggested: 200, main: true }, { id: "f", suggested: 5, main: false },
];
assert.deepEqual(retune(cats, { a: 650, b: 100, c: 105 }).map((c) => c.id), ["a", "b", "e", "d"]);
assert.deepEqual(retune(cats, { a: 350, b: 300, c: 100, d: 80, e: 200 }), []);
}
10 changes: 10 additions & 0 deletions src/lib/budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ export function monthList(months: string[]) {
// "Use these" never puts the user over budget on day one.
export const suggest = (avg: number, spentThisMonth: number) => roundUp(Math.max(avg, spentThisMonth));

// A budget is "well off" when it is $25 and a fifth or more away from the suggested amount. Small gaps are noise.
export const wellOff = (budget: number, suggested: number) => suggested > 0 && Math.abs(budget - suggested) >= Math.max(25, budget * 0.2);

// What the Suggest sheet offers: budgets well off from real spending (biggest gap first), then main categories with no budget.
export function retune<C extends { id: string; suggested: number; main: boolean }>(cats: C[], budgets: Record<string, number>): C[] {
const off = cats.filter((c) => c.id in budgets && wellOff(budgets[c.id], c.suggested)).sort((a, b) => Math.abs(b.suggested - budgets[b.id]) - Math.abs(a.suggested - budgets[a.id]));
const fresh = cats.filter((c) => c.main && !(c.id in budgets)).sort((a, b) => b.suggested - a.suggested);
return [...off, ...fresh];
}

// Where the month is: today counts as a day left.
export function month(now: Date) {
const day = now.getUTCDate();
Expand Down
Loading