Months that start on payday

A profile setting ("A month starts: on payday") runs each month from one
salary to the day before the next, named after the calendar month it
mostly covers. Salary is money in under Income of at least half a usual
paycheck, found within 12 days of the usual pay day; until it arrives the
running month goes on. The months are worked out on each request and kept
in pay_periods, which money_by_month now groups by, so every monthly
total follows. Spending, Home, Budgets, the typical month and the plan
use them; Charts, check-ins and onboarding stay on calendar 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:02:23 +01:00
1 parent 1bdcc57c2f
commit 9d42d52e4d
12 files changed
+269 -39

No files matched your search

+11 -8
View File
@@ -3,7 +3,7 @@ import { AskButton } from "@/components/Assistant";
import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor";
import { EmptyBank } from "@/components/EmptyBank";
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, months, 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 full months of data (up to 3, the
@@ -16,16 +16,19 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
const from = DAY.test(sp.from ?? "") ? sp.from! : "", to = DAY.test(sp.to ?? "") ? sp.to! : "";
const { supabase, user } = await getUser();
const now = await today();
const thisMonth = ymd(monthStart(now)).slice(0, 7);
const lastMonth = ymd(monthStart(now, -1)).slice(0, 7);
// Pay months on: this month is the pay month today is in (named after the calendar month it mostly covers).
const mo = await months();
const thisMonth = await mo.current();
const cur = new Date(`${thisMonth}-01T00:00:00Z`);
const lastMonth = ymd(monthStart(cur, -1)).slice(0, 7);
const [txns, cats, saved, typical] = await Promise.all([
moneyByMonth(supabase, ymd(monthStart(now, -Math.max(3, now.getUTCMonth())))), // own rows, totalled in SQL: 3 months, or back to January
moneyByMonth(supabase, ymd(monthStart(cur, -Math.max(3, cur.getUTCMonth())))), // own rows, totalled in SQL: 3 months, or back to January
categories(),
supabase.from("budgets").select("category_id, amount"),
typicalMonthly(supabase, user!.id, ymd(now)),
]);
const threeMonthsAgo = ymd(monthStart(now, -3)).slice(0, 7);
const threeMonthsAgo = ymd(monthStart(cur, -3)).slice(0, 7);
const past = txns.filter((r) => !r.month.startsWith(thisMonth) && r.month.slice(0, 7) >= threeMonthsAgo);
const monthsOfData = Math.max(1, new Set(past.map((r) => r.month.slice(0, 7))).size);
const sum = (catId: string, month?: string) =>
@@ -44,8 +47,8 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
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 };
});
// Each month of this year, spend by category, for the year view.
const year = String(now.getUTCFullYear());
const yearMonths: MonthSpend[] = Array.from({ length: now.getUTCMonth() + 1 }, (_, i) => {
const year = String(cur.getUTCFullYear());
const yearMonths: MonthSpend[] = Array.from({ length: cur.getUTCMonth() + 1 }, (_, i) => {
const month = `${year}-${String(i + 1).padStart(2, "0")}`;
const cats: Record<string, number> = {};
for (const r of txns) if (r.month.startsWith(month) && r.spend > 0) cats[r.category_id] = (cats[r.category_id] ?? 0) + r.spend;
@@ -65,7 +68,7 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
return (
// The key takes in saved changes from elsewhere (the AI's Apply) on refresh.
<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={
<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} {...(mo.payday ? { span: mo.range(thisMonth), label: `${thisMonth}-01` } : {})} aside={
<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]]))}`}
className="card-link w-full p-5 text-left flex items-center gap-4"
+7 -5
View File
@@ -11,8 +11,8 @@ import { PayQuestion } from "@/components/PayQuestion";
import { SyncButton } from "@/components/PlaidButtons";
import { TxnList } from "@/components/TxnList";
import { WeekCard } from "@/components/WeekCard";
import { categories, getUser, moneyByMonth, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
import { dateLabel, money0, monthStart, ymd } from "@/lib/format";
import { categories, getUser, moneyByMonth, months, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
import { dateLabel, money0, ymd } from "@/lib/format";
import { deterministicMoves, ladder } from "@/lib/plan";
import { myPlanFacts } from "@/lib/plan-facts";
import { payGuess } from "@/lib/pay";
@@ -66,6 +66,8 @@ export default async function Dashboard() {
const now = await today(); // the user's date at UTC midnight: read it with getUTC* and ymd
const day = ymd(now), soon = ymd(new Date(now.getTime() + 14 * 864e5));
const checks = (fetchChecks(supabase, uid, day) as Promise<Checks>).catch(() => ({ rows: [], total: 0 })); // starts now, beside the queries below
// Pay months on: "this month" is the pay month today is in, named after the calendar month it mostly covers.
const thisMonth = await (await months()).current();
// Own rows only: an account a partner shares is on the Accounts page, not in your totals.
const [{ data: recent }, { data: accounts }, { data: noRate }, { data: bills }, rows, cats] = await Promise.all([
@@ -73,7 +75,7 @@ export default async function Dashboard() {
supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", uid),
supabase.rpc("fx_missing"),
supabase.from("recurring").select("id, merchant_name, logo_url, average_amount:home_average, next_date").eq("user_id", uid).eq("active", true).eq("is_income", false).neq("status", "TOMBSTONED").gte("next_date", day).lte("next_date", soon).order("next_date").limit(4),
moneyByMonth(supabase, ymd(monthStart(now))),
moneyByMonth(supabase, `${thisMonth}-01`),
categories(),
]);
@@ -93,8 +95,8 @@ export default async function Dashboard() {
{ label: "You owe", value: owed == null ? null : Math.abs(owed), href: "/debt" },
].filter((t) => t.value != null);
const pic = moneyPicture(rows, cats, ymd(monthStart(now)).slice(0, 7), null);
const monthName = dateLabel(day, { month: "long" });
const pic = moneyPicture(rows, cats, thisMonth, null);
const monthName = dateLabel(`${thisMonth}-01`, { month: "long" });
return (
<div className="space-y-4 max-w-4xl">
+22 -9
View File
@@ -5,7 +5,7 @@ import { EmptyBank } from "@/components/EmptyBank";
import { MonthBars } from "@/components/MonthBars";
import { PageDates } from "@/components/PageDates";
import { Merchant } from "@/components/Merchant";
import { categories, displayName, getUser, isIncome, isSpend, loanPayments, moneyByMonth, savedByMonth, sumOf, today, transactionsSince, type MonthRow, type Txn } from "@/lib/data";
import { categories, displayName, getUser, isIncome, isSpend, loanPayments, moneyByMonth, months as monthsOf, savedByMonth, sumOf, today, transactionsSince, type MonthRow, type Txn } from "@/lib/data";
import { dateLabel, money, money0, monthLabel, monthStart, ymd } from "@/lib/format";
const DAY = /^\d{4}-\d{2}-\d{2}$/;
@@ -108,13 +108,21 @@ export default async function Spending({ searchParams }: { searchParams: Promise
const { m, bills, from: rawFrom, to: rawTo, span } = await searchParams;
const from = DAY.test(rawFrom ?? "") ? rawFrom! : "", to = DAY.test(rawTo ?? "") ? rawTo! : "";
const includeBills = bills !== "0";
const now = await today();
let now = await today();
if (from || to) return <CustomRange from={from} to={to} today={ymd(now)} />;
const { supabase, user } = await getUser();
// Pay months on (profile.month = "payday"): "now" is the pay month today is in, so after salary on the 24th it's
// already next month. Calendar months otherwise. Month arithmetic runs on the month's name, its dates come from mo.range.
const mo = await monthsOf();
const curYm = await mo.current();
const daysIn = Math.round((now.getTime() - Date.parse(`${mo.range(curYm).start}T00:00:00Z`)) / 864e5) + 1;
const real = now;
now = new Date(`${curYm}-01T00:00:00Z`);
const ymOf = (d: Date) => ymd(d).slice(0, 7);
// m = "YYYY-MM" (the arrows or a bar), "last" or "now"; anything else = this month. Up to 5 years back.
const ym = /^\d{4}-\d{2}$/.test(m ?? "") ? m!.split("-").map(Number) : null;
// The first days of a month open on last month: this one is still empty. m=now asks for this month anyway.
const offset = m === "last" || (!m && now.getUTCDate() <= 3) ? -1 : ym ? Math.max(-59, Math.min(0, (ym[0] - now.getUTCFullYear()) * 12 + ym[1] - 1 - now.getUTCMonth())) : 0;
const offset = m === "last" || (!m && daysIn <= 3) ? -1 : ym ? Math.max(-59, Math.min(0, (ym[0] - now.getUTCFullYear()) * 12 + ym[1] - 1 - now.getUTCMonth())) : 0;
const month = monthStart(now, offset);
const prevMonth = monthStart(now, offset - 1);
// The chart and table: the picked month's whole year by default, or the last 12 or 6 months (the 6 or 12 ending at the
@@ -130,9 +138,9 @@ export default async function Spending({ searchParams }: { searchParams: Promise
const [rows, allCats, monthTxns, loans, savedMonths] = await Promise.all([
moneyByMonth(supabase, ymd(first)),
categories(),
transactionsSince(ymd(month), ymd(monthStart(now, offset + 1))),
loanPayments(supabase, user!.id, ymd(first)),
savedByMonth(supabase, user!.id, ymd(first)),
transactionsSince(mo.range(ymOf(month)).start, mo.range(ymOf(month)).end),
loanPayments(supabase, user!.id, mo.range(ymOf(first)).start, undefined, mo.of),
savedByMonth(supabase, user!.id, mo.range(ymOf(first)).start, undefined, mo.of),
]);
// ponytail: "no transactions in 6 months" is treated as "no bank yet"; split the copy if linked-but-quiet accounts show up.
if (!rows.length) return <EmptyBank title="See where your money goes" body="Link a bank to get a monthly breakdown by category." />;
@@ -183,6 +191,8 @@ export default async function Spending({ searchParams }: { searchParams: Promise
const change = prevTotal ? Math.round(((total - prevTotal) / prevTotal) * 100) : null;
const vs = (a: number, b: number) => (Math.abs(a - b) < 1 ? `Same as ${monthLabel(prevMonth)}` : `${money0(Math.abs(a - b))} ${a > b ? "more" : "less"} than ${monthLabel(prevMonth)}`);
// The month's last day: the day before the next salary, or the day before its usual date while it's running.
const lastDay = new Date(Date.parse(`${mo.range(ymOf(month)).end}T00:00:00Z`) - 864e5).toISOString().slice(0, 10);
const qs = (o: Record<string, string | undefined>) => "/spending?" + new URLSearchParams(Object.entries({ m, bills, span, ...o }).filter(([, v]) => v) as [string, string][]);
return (
@@ -191,14 +201,17 @@ export default async function Spending({ searchParams }: { searchParams: Promise
{offset > -59 ? (
<Link scroll={false} href={qs({ m: ymd(prevMonth).slice(0, 7) })} aria-label="Earlier month" className="size-9 rounded-full border border-line grid place-items-center text-muted hover:text-ink row-hover"><ChevronLeft size={18} /></Link>
) : <span className="size-9" />}
<span className="min-w-36 text-center font-medium tabular-nums">{dateLabel(month, { month: "long", year: "numeric" })}</span>
<span className="min-w-36 text-center">
<span className="block font-medium tabular-nums">{dateLabel(month, { month: "long", year: "numeric" })}</span>
{mo.payday && <span className="block text-xs text-muted tabular-nums">{dateLabel(mo.range(ymOf(month)).start, { month: "short", day: "numeric" })} to {dateLabel(lastDay, { month: "short", day: "numeric" })}</span>}
</span>
{offset < 0 ? (
<Link scroll={false} href={qs({ m: offset === -1 ? "now" : ymd(monthStart(now, offset + 1)).slice(0, 7) })} aria-label="Later month" className="size-9 rounded-full border border-line grid place-items-center text-muted hover:text-ink row-hover"><ChevronRight size={18} /></Link>
) : <span className="size-9" />}
{offset < -1 && <Link scroll={false} href={qs({ m: "now" })} className="text-sm text-muted hover:text-ink underline underline-offset-4 ml-1">This month</Link>}
</div>
<PageDates path="/spending" from="" to="" today={ymd(now)} />
<PageDates path="/spending" from="" to="" today={ymd(real)} />
<nav aria-label="How much to show" className="pill-tabs max-w-full overflow-x-auto">
{[
@@ -289,7 +302,7 @@ export default async function Spending({ searchParams }: { searchParams: Promise
)}
</section>
</div>
<IncomeSources txns={monthTxns} range={`&from=${ymd(month)}&to=${ymd(new Date(monthStart(now, offset + 1).getTime() - 864e5))}`} />
<IncomeSources txns={monthTxns} range={`&from=${mo.range(ymOf(month)).start}&to=${lastDay}`} />
</div>
<div className="space-y-6">
+1 -1
View File
@@ -7,7 +7,7 @@ import { createClient } from "@/utils/supabase/server";
// Settings, Database, "Clear my data": the signed-in user's money data, and nobody else's. Bank connections are revoked
// at Plaid first, then deleted (accounts, transactions, bills and holdings cascade). Sign-in, profile answers, categories
// and the AI connection stay, so they can link again or use a test bank straight away.
const TABLES = ["accounts", "transactions", "recurring", "budgets", "rules", "plans", "checkins", "chat_threads", "bookmarks"];
const TABLES = ["accounts", "transactions", "recurring", "budgets", "rules", "plans", "checkins", "chat_threads", "bookmarks", "pay_periods"];
export async function POST(request: Request) {
const { data: { user } } = await (await createClient()).auth.getUser();