Pay months on Charts, left this month, check-ins and onboarding

With months that start on payday, Charts groups by pay month (presets,
savings rate and month to date included, day 1 being payday). Left this
month counts bills and the usual pace up to the day before the next
salary. Check-ins read this month, budget tips and the weekly cap from
the pay month, and onboarding looks at full pay months.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
MangaValkandClaude Opus 5.5 committed 2026-11-22 18:06:51 +01:00
1 parent 9d42d52e4d
commit 943b19d743
10 files changed
+112 -55

No files matched your search

+17 -14
View File
@@ -1,8 +1,8 @@
import { ChartFilters } from "@/components/charts/ChartFilters";
import { ChartsView, type ChartsData } from "@/components/charts/ChartsView";
import { EmptyBank } from "@/components/EmptyBank";
import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periods, previousRange, rankBySpend, savingsRate, totals, type Group, type Row } from "@/lib/charts";
import { accountName, allTags, categories, displayName, getUser, isIncome, isSpend, today, transactionsSince } from "@/lib/data";
import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periods, previousRange, rankBySpend, savingsRate, totals, type Group, type Months, type Row } from "@/lib/charts";
import { accountName, allTags, categories, displayName, getUser, isIncome, isSpend, months, today, transactionsSince } from "@/lib/data";
import { ymd } from "@/lib/format";
// Charts: money over time with filters. Every number comes from lib/charts.ts over the same spend / income rule as
@@ -18,6 +18,9 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
const sp = await searchParams;
const { supabase, user } = await getUser();
const now = ymd(await today());
// Months that start on payday (profile.month): grouping by month, month presets and month to date follow them.
const mo = await months();
const pm: Months = mo.payday ? { of: mo.of, range: mo.range } : null;
const [txns, cats, tags, { data: accts }] = await Promise.all([
transactionsSince("1900-01-01"),
categories(),
@@ -39,7 +42,7 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
// Time range: a preset, or custom dates (either end open).
const range = sp.range ?? "12m";
const monthsBack = (n: number) => { const d = new Date(`${now.slice(0, 7)}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() - n + 1); return ymd(d); };
const monthsBack = (n: number) => { const d = new Date(`${pm ? pm.of(now) : now.slice(0, 7)}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() - n + 1); return pm ? pm.range(ymd(d).slice(0, 7)).start : ymd(d); };
const preset = range === "1m" ? monthsBack(1) : range === "3m" ? monthsBack(3) : range === "6m" ? monthsBack(6) : range === "ytd" ? `${now.slice(0, 4)}-01-01` : range === "all" ? first : monthsBack(12);
const from = DAY.test(sp.from ?? "") ? sp.from! : DAY.test(sp.to ?? "") ? first : preset;
const to = DAY.test(sp.to ?? "") ? sp.to! : now;
@@ -57,14 +60,14 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
.filter((r) => !q || r.text.includes(q) || r.merchant.toLowerCase().includes(q))
.map((r) => (dir === "out" ? { ...r, income: false } : dir === "in" ? { ...r, spend: false } : r));
const within = (a: string, b: string) => filtered.filter((r) => r.date >= a && r.date <= b);
const ps = periods(from, to, group);
const ps = periods(from, to, group, pm);
const rows = within(from, to);
const compare = sp.cmp === "1";
const prev = previousRange(from, to);
const before = within(prev.from, prev.to);
// The period before, lined up period by period with this one (same length, same grouping).
const psBefore = periods(prev.from, prev.to, group).slice(-ps.length);
const flowBefore = compare ? cashFlow(before, psBefore, group) : null;
const psBefore = periods(prev.from, prev.to, group, pm).slice(-ps.length);
const flowBefore = compare ? cashFlow(before, psBefore, group, pm) : null;
const pad = <T,>(xs: T[] | null) => (xs ? [...Array(Math.max(0, ps.length - xs.length)).fill(null), ...xs] : null);
// Stable colors: slots follow all-time spending, so filtering never repaints a category, merchant or account.
@@ -79,10 +82,10 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
const accounts = (accts ?? []).filter((a) => a.included !== false && ["depository", "credit", "loan"].includes(a.type) && (!acct.length || acct.includes(a.id)));
const bal = balances(
accounts.map((a) => ({ id: a.id, name: accountName(a), balance: Number((a.manual ? a.balance : a.current_balance) ?? 0), owed: a.type === "credit" || a.type === "loan" })),
all.filter((r) => r.date > from), from, to, group,
all.filter((r) => r.date > from), from, to, group, pm,
);
const flow = cashFlow(rows, ps, group);
const psMonth = periods(from, to, "month");
const flow = cashFlow(rows, ps, group, pm);
const psMonth = periods(from, to, "month", pm);
const ch = biggestChanges(rows, before, (r) => r.categoryId);
const data: ChartsData = {
@@ -93,14 +96,14 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
flow,
flowBefore: flowBefore ? (pad(flowBefore) as ChartsData["flow"]).map((f, i) => f ?? { key: ps[i].key, income: 0, spend: 0, net: 0 }) : null,
// Savings rate is per month whatever the grouping: most weeks have no pay in them, and a rate of nothing isn't 0%.
rate: { periods: psMonth, values: savingsRate(cashFlow(rows, psMonth, "month")).map((r) => r.rate) },
rateBefore: compare ? (() => { const pm = periods(prev.from, prev.to, "month").slice(-psMonth.length); const v = savingsRate(cashFlow(before, pm, "month")).map((r) => r.rate); return [...Array(Math.max(0, psMonth.length - v.length)).fill(null), ...v]; })() : null,
cats: { order: keep.map((id) => ({ id, label: label.get(id) ?? "Uncategorized", slot: catSlot.get(id)! })), values: categoriesOver(rows, ps, group, keep).map((c) => c.values) },
mtd: monthToDate(filtered, now),
rate: { periods: psMonth, values: savingsRate(cashFlow(rows, psMonth, "month", pm)).map((r) => r.rate) },
rateBefore: compare ? (() => { const pb = periods(prev.from, prev.to, "month", pm).slice(-psMonth.length); const v = savingsRate(cashFlow(before, pb, "month", pm)).map((r) => r.rate); return [...Array(Math.max(0, psMonth.length - v.length)).fill(null), ...v]; })() : null,
cats: { order: keep.map((id) => ({ id, label: label.get(id) ?? "Uncategorized", slot: catSlot.get(id)! })), values: categoriesOver(rows, ps, group, keep, pm).map((c) => c.values) },
mtd: monthToDate(filtered, now, pm),
balance: { ...bal, series: bal.series.map((s, i) => ({ ...s, slot: (i % 8) + 1 })) },
weekday: byWeekday(rows, from, to),
weekdayBefore: compare ? byWeekday(before, prev.from, prev.to) : null,
merchants: merchantsOver(rows, ps, group, topMerch).map((m) => ({ ...m, slot: merchSlot(m.name) })),
merchants: merchantsOver(rows, ps, group, topMerch, pm).map((m) => ({ ...m, slot: merchSlot(m.name) })),
changes: {
categories: { up: ch.up.map((c) => ({ ...c, label: label.get(c.id) ?? "Uncategorized" })), down: ch.down.map((c) => ({ ...c, label: label.get(c.id) ?? "Uncategorized" })) },
merchants: biggestChanges(rows, before, (r) => r.merchant),
+3 -1
View File
@@ -1,7 +1,7 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { changeLines, checkinFacts, sameDollars, type CheckinFacts } from "@/lib/checkins";
import { allRows, today as todayDate, displayName, isSpend, TXN_SELECT, typicalMonthly, type Txn } from "@/lib/data";
import { allRows, today as todayDate, displayName, isSpend, paySpan, TXN_SELECT, typicalMonthly, type Txn } from "@/lib/data";
import { runViaHelper } from "@/lib/llm/helper";
import { runCodex, runGemini, runOpencode } from "@/lib/llm/cli-snapshot";
import { AGENT_DIR, runClaudeCode } from "@/lib/llm/claude-code";
@@ -83,6 +83,7 @@ async function generate(supabase: Sb, user: User, replace: string | null) {
supabase.from("checkins").select("facts").eq("user_id", userId).lt("created_at", new Date(Date.now() - SINCE).toISOString()).order("created_at", { ascending: false }).limit(1).maybeSingle(),
loadPlan(supabase, userId).catch(() => null),
]);
const span = await paySpan(supabase, userId, today); // months that start on payday, if on
// The plan's next move by the ladder, or one marked done in the last 7 days.
type M = { title: string; why: string; status?: string; done_at?: string | null; deadline: string | null; ref: string | null; kind: Kind; step: number | null };
const moves = (plan?.moves ?? []) as unknown as M[];
@@ -108,6 +109,7 @@ async function generate(supabase: Sb, user: User, replace: string | null) {
prev: (prev?.facts as CheckinFacts | undefined) ?? null,
move: pick ? { title: pick.title, line: whyLine(pick.title, pick.why), done: pick === justDone, by: pick.deadline ?? addDays(today, 7) } : null,
today,
span,
});
// Off: no model call, the card shows the plain facts. Summary: placeholders and rounded amounts, names swapped back below.
+6 -4
View File
@@ -1,5 +1,5 @@
import { NextResponse } from "next/server";
import { allRows, getUser, moneyByMonth, today as userToday } from "@/lib/data";
import { allRows, getUser, moneyByMonth, payMonthToday, today as userToday } from "@/lib/data";
import { firstFact } from "@/lib/first-fact";
import { dateLabel, FREQ_PER_MONTH, money0, monthStart, ymd } from "@/lib/format";
import { typicalMonth } from "@/lib/insights";
@@ -17,13 +17,15 @@ export async function GET() {
const now = await userToday();
const today = ymd(now);
const since90 = ymd(new Date(now.getTime() - 90 * 864e5));
// Month logic runs on the pay month today is in when months start on payday (lib/paymonths.ts).
const monthNow = new Date(`${(await payMonthToday(supabase, uid, today)).slice(0, 7)}-01T00:00:00Z`);
const [{ data: items }, { data: accts }, { data: streams }, { data: cats }, { data: first }, rows, interest] = await Promise.all([
supabase.from("plaid_items").select("id, last_synced_at").eq("user_id", uid),
supabase.from("accounts").select("id, type, manual").eq("user_id", uid),
supabase.from("recurring").select("merchant_name, frequency, average_amount:home_average, is_income, next_date, category:categories(key)").eq("user_id", uid).eq("active", true).neq("status", "TOMBSTONED"),
supabase.from("categories").select("id, label"),
supabase.from("transactions").select("date").eq("user_id", uid).order("date").limit(1),
moneyByMonth(supabase, ymd(monthStart(now, -3))),
moneyByMonth(supabase, ymd(monthStart(monthNow, -3))),
// Card or loan interest, the For you page's rule.
allRows<{ amount: number }>((a, b) => supabase.from("transactions").select("amount").eq("user_id", uid).eq("ignored", false).gt("amount", 0).gte("date", since90)
.or("plaid_category.eq.BANK_FEES_INTEREST_CHARGE,name.ilike.*interest charge*").order("id").range(a, b)),
@@ -39,7 +41,7 @@ export async function GET() {
if ((items ?? []).some((i) => !i.last_synced_at) || !oldest) return NextResponse.json({ ...base, status: "importing" });
// The biggest category in the last full month the history covers, against its average over the full months before it.
const ym = (k: number) => ymd(monthStart(now, -k)).slice(0, 7);
const ym = (k: number) => ymd(monthStart(monthNow, -k)).slice(0, 7);
const covered = [1, 2, 3].map(ym).filter((m) => `${m}-01` >= oldest);
const spentIn = (m: string) => {
const by = new Map<string, number>();
@@ -58,7 +60,7 @@ export async function GET() {
};
}
}
const typical = typicalMonth(rows, today, oldest);
const typical = typicalMonth(rows, await payMonthToday(supabase, uid, today), oldest);
const subs = s.filter((x) => !x.is_income && !BILL.has(x.category?.key ?? "")).map((x) => ({ monthly: x.average_amount * (FREQ_PER_MONTH[x.frequency] ?? 0) }));
const fact = firstFact({ typical, interest90: interest.reduce((t, r) => t + Number(r.amount), 0), subs, top }, (n) => money0(n));
return NextResponse.json({ ...base, status: fact ? "ready" : "thin", fact });