From 9d42d52e4d6383ef1698df1738c81a3990f780d2 Mon Sep 17 00:00:00 2001 From: MangaValk Date: Sun, 22 Nov 2026 18:02:23 +0100 Subject: [PATCH] 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 --- src/app/(app)/budgets/page.tsx | 19 ++++--- src/app/(app)/page.tsx | 12 +++-- src/app/(app)/spending/page.tsx | 31 +++++++---- src/app/api/clear-data/route.ts | 2 +- src/components/BudgetEditor.tsx | 9 ++-- src/components/ProfileForm.tsx | 12 +++++ src/lib/budget.ts | 8 +-- src/lib/data.ts | 66 +++++++++++++++++++++-- src/lib/paymonths.test.ts | 42 +++++++++++++++ src/lib/paymonths.ts | 67 ++++++++++++++++++++++++ src/lib/plan-facts.ts | 12 +++-- supabase/migrations/0035_pay_periods.sql | 28 ++++++++++ 12 files changed, 269 insertions(+), 39 deletions(-) create mode 100644 src/lib/paymonths.test.ts create mode 100644 src/lib/paymonths.ts create mode 100644 supabase/migrations/0035_pay_periods.sql diff --git a/src/app/(app)/budgets/page.tsx b/src/app/(app)/budgets/page.tsx index 82825c7..5c7f830 100644 --- a/src/app/(app)/budgets/page.tsx +++ b/src/app/(app)/budgets/page.tsx @@ -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 = {}; 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. - 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/app/(app)/page.tsx b/src/app/(app)/page.tsx index 78f9521..57c7354 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -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).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 (
diff --git a/src/app/(app)/spending/page.tsx b/src/app/(app)/spending/page.tsx index 70e448a..e302946 100644 --- a/src/app/(app)/spending/page.tsx +++ b/src/app/(app)/spending/page.tsx @@ -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 ; 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 ; @@ -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) => "/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 ? ( ) : } - {dateLabel(month, { month: "long", year: "numeric" })} + + {dateLabel(month, { month: "long", year: "numeric" })} + {mo.payday && {dateLabel(mo.range(ymOf(month)).start, { month: "short", day: "numeric" })} to {dateLabel(lastDay, { month: "short", day: "numeric" })}} + {offset < 0 ? ( ) : } {offset < -1 && This month}
- +