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

+62 -4
View File
@@ -5,6 +5,7 @@ import { cache } from "react";
import { dayIn, fmtFor, setFmtScope, US_FMT, type Fmt } from "@/lib/format";
import { ensureRates } from "@/lib/fx";
import { typicalMonth } from "@/lib/insights";
import { detectPeriods, monthOf, rangeOf, type Pay, type Period } from "@/lib/paymonths";
import { createAdminClient } from "@/utils/supabase/admin";
import { createClient } from "@/utils/supabase/server";
@@ -94,7 +95,12 @@ export async function transactionsSince(gte: string, lt?: string) {
// Totals from SQL (migration 0014), own rows only, same rules as isSpend / isIncome. income is money in, positive.
// Take the client so the AI tools can call them with theirs.
export type MonthRow = { month: string; category_id: string; spend: number; income: number; n: number };
// With pay months on, a month's first day is its payday, so a start on the 1st moves back to that day.
export async function moneyByMonth(supabase: SupabaseClient, start: string, end?: string) {
if (start.endsWith("-01")) {
const { data: p } = await supabase.from("pay_periods").select("start_date").eq("month", start).maybeSingle();
if (p?.start_date && p.start_date < start) start = p.start_date as string;
}
const { data, error } = await supabase.rpc("money_by_month", { start_date: start, end_date: end ?? null });
if (error) throw new Error(error.message);
return ((data ?? []) as MonthRow[]).map((r) => ({ ...r, spend: Number(r.spend), income: Number(r.income), n: Number(r.n) }));
@@ -107,6 +113,7 @@ export async function spendByDay(supabase: SupabaseClient, start: string, end?:
// The user's typical month: income and spend averaged over the last 3 full months (typicalMonth in insights.ts has
// the rule). The one source for "about $X a month" income on every page. Null until there is a full month.
export async function typicalMonthly(supabase: SupabaseClient, userId: string, today: string) {
today = await payMonthToday(supabase, userId, today);
const [y, m] = today.split("-").map(Number);
const [rows, { data }] = await Promise.all([
moneyByMonth(supabase, new Date(Date.UTC(y, m - 4, 1)).toISOString().slice(0, 10)),
@@ -114,25 +121,33 @@ export async function typicalMonthly(supabase: SupabaseClient, userId: string, t
]);
return typicalMonth(rows, today, (data?.[0]?.date as string | undefined) ?? null);
}
/** With pay months on, today as seen by month logic: the first day of the pay month it's in (after salary on the
* 24th it's already next month). Else today itself. */
export async function payMonthToday(supabase: SupabaseClient, userId: string, today: string) {
const { data } = await supabase.from("pay_periods").select("month").eq("user_id", userId).lte("start_date", today).order("start_date", { ascending: false }).limit(1);
const m = data?.[0]?.month as string | undefined;
return m && m.slice(0, 7) !== today.slice(0, 7) ? m : today;
}
// Loan payments per "YYYY-MM": car, student, mortgage and so on. They're transfers in the spending totals (migration 0022),
// but the money still leaves, so anything saying what's left over must count them. Only the row leaving a bank account:
// the same payment arriving on a linked loan is negative, and a loan account's own rows don't count. Card payments have their own category.
export async function loanPayments(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31") {
// key: the month a date is in (months().of with pay months on), calendar by default. Same for savedByMonth.
export async function loanPayments(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31", key = (d: string) => d.slice(0, 7)) {
const rows = await allRows<{ date: string; amount: number }>((a, b) =>
supabase.from("transactions").select("date, amount, category:categories!inner(key), account:accounts!inner(type)")
.eq("user_id", userId).eq("ignored", false).gt("amount", 0).gte("date", start).lte("date", end)
.eq("category.key", "LOAN_PAYMENTS").neq("account.type", "loan").order("id").range(a, b));
const by = new Map<string, number>();
for (const r of rows) by.set(r.date.slice(0, 7), (by.get(r.date.slice(0, 7)) ?? 0) + Number(r.amount));
for (const r of rows) by.set(key(r.date), (by.get(key(r.date)) ?? 0) + Number(r.amount));
return by;
}
// Money going into savings and investment accounts per "YYYY-MM": what arrives on a savings account (net of what leaves it)
// and contributions to investment accounts. Only accounts broke can see.
export async function savedByMonth(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31") {
export async function savedByMonth(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31", key = (d: string) => d.slice(0, 7)) {
const { data: accts } = await supabase.from("accounts").select("id, type, subtype").eq("user_id", userId).or("type.eq.investment,subtype.eq.savings");
const by = new Map<string, number>();
const savings = (accts ?? []).filter((a) => a.type !== "investment").map((a) => a.id), invest = (accts ?? []).filter((a) => a.type === "investment").map((a) => a.id);
const add = (date: string, n: number) => by.set(date.slice(0, 7), (by.get(date.slice(0, 7)) ?? 0) + n);
const add = (date: string, n: number) => by.set(key(date), (by.get(key(date)) ?? 0) + n);
if (savings.length)
for (const t of await allRows<{ date: string; amount: number }>((a, b) => supabase.from("transactions").select("date, amount").eq("ignored", false).gte("date", start).lte("date", end).in("account_id", savings).order("id").range(a, b))) add(t.date, -Number(t.amount));
if (invest.length) {
@@ -161,3 +176,46 @@ export async function allTags() {
if (!seen.has(tag.toLowerCase())) seen.set(tag.toLowerCase(), tag);
return [...seen.values()].sort((a, b) => a.localeCompare(b));
}
// Months that start on payday (profile.month = "payday", lib/paymonths.ts), worked out from the salary in the
// transactions on every request, so a new paycheck or a category change shows at once. money_by_month (migration 0035)
// reads the same months from pay_periods, which is rewritten here only when they change. Null: calendar months.
export const payPeriods = cache(async (): Promise<Period[] | null> => {
const { supabase, user } = await getUser();
if (!user) return null;
const on = (user.user_metadata?.profile as { month?: string } | undefined)?.month === "payday";
const [{ data: stored }, periods] = await Promise.all([
supabase.from("pay_periods").select("month, start_date").order("month"),
on ? findPeriods(supabase, user.id) : Promise.resolve(null),
]);
const want = periods ?? [];
const same = (stored ?? []).length === want.length && want.every((p, i) => stored![i].month === p.month && stored![i].start_date === p.start);
if (!same) {
const db = createAdminClient();
await db.from("pay_periods").delete().eq("user_id", user.id);
if (want.length) await db.from("pay_periods").insert(want.map((p) => ({ user_id: user.id, month: p.month, start_date: p.start })));
}
return periods;
});
async function findPeriods(supabase: SupabaseClient, userId: string) {
const [pays, { data: first }, now] = await Promise.all([
allRows<{ date: string; amount: number }>((a, b) => supabase.from("transactions").select("date, amount, category:categories!inner(key), account:accounts!inner(included)")
.eq("user_id", userId).eq("ignored", false).lt("amount", 0).eq("category.key", "INCOME").eq("account.included", true).order("id").range(a, b)),
supabase.from("transactions").select("date").eq("user_id", userId).order("date").limit(1),
today(),
]);
if (!first?.length) return null;
return detectPeriods(pays.map((p): Pay => ({ date: p.date, amount: -Number(p.amount) })), first[0].date as string, now.toISOString().slice(0, 10));
}
/** This request's months: what month a date is in, a month's dates, and the month today is in. */
export async function months() {
const periods = await payPeriods();
return {
payday: !!periods,
of: (date: string) => monthOf(periods, date),
range: (ym: string) => rangeOf(periods, ym),
current: async () => monthOf(periods, (await today()).toISOString().slice(0, 10)),
};
}