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:
1 parent
1bdcc57c2f
commit
9d42d52e4d
12 files changed
+269
-39
No files matched your search
@@ -3,7 +3,7 @@ import { AskButton } from "@/components/Assistant";
|
|||||||
import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor";
|
import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor";
|
||||||
import { EmptyBank } from "@/components/EmptyBank";
|
import { EmptyBank } from "@/components/EmptyBank";
|
||||||
import { budgetContext, median, monthList, suggest, type MonthSpend } from "@/lib/budget";
|
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";
|
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
|
// 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 from = DAY.test(sp.from ?? "") ? sp.from! : "", to = DAY.test(sp.to ?? "") ? sp.to! : "";
|
||||||
const { supabase, user } = await getUser();
|
const { supabase, user } = await getUser();
|
||||||
const now = await today();
|
const now = await today();
|
||||||
const thisMonth = ymd(monthStart(now)).slice(0, 7);
|
// Pay months on: this month is the pay month today is in (named after the calendar month it mostly covers).
|
||||||
const lastMonth = ymd(monthStart(now, -1)).slice(0, 7);
|
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([
|
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(),
|
categories(),
|
||||||
supabase.from("budgets").select("category_id, amount"),
|
supabase.from("budgets").select("category_id, amount"),
|
||||||
typicalMonthly(supabase, user!.id, ymd(now)),
|
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 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 monthsOfData = Math.max(1, new Set(past.map((r) => r.month.slice(0, 7))).size);
|
||||||
const sum = (catId: string, month?: string) =>
|
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 };
|
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.
|
// Each month of this year, spend by category, for the year view.
|
||||||
const year = String(now.getUTCFullYear());
|
const year = String(cur.getUTCFullYear());
|
||||||
const yearMonths: MonthSpend[] = Array.from({ length: now.getUTCMonth() + 1 }, (_, i) => {
|
const yearMonths: MonthSpend[] = Array.from({ length: cur.getUTCMonth() + 1 }, (_, i) => {
|
||||||
const month = `${year}-${String(i + 1).padStart(2, "0")}`;
|
const month = `${year}-${String(i + 1).padStart(2, "0")}`;
|
||||||
const cats: Record<string, number> = {};
|
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;
|
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 (
|
return (
|
||||||
// The key takes in saved changes from elsewhere (the AI's Apply) on refresh.
|
// 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
|
<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]]))}`}
|
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"
|
className="card-link w-full p-5 text-left flex items-center gap-4"
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ import { PayQuestion } from "@/components/PayQuestion";
|
|||||||
import { SyncButton } from "@/components/PlaidButtons";
|
import { SyncButton } from "@/components/PlaidButtons";
|
||||||
import { TxnList } from "@/components/TxnList";
|
import { TxnList } from "@/components/TxnList";
|
||||||
import { WeekCard } from "@/components/WeekCard";
|
import { WeekCard } from "@/components/WeekCard";
|
||||||
import { categories, getUser, moneyByMonth, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
|
import { categories, getUser, moneyByMonth, months, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
|
||||||
import { dateLabel, money0, monthStart, ymd } from "@/lib/format";
|
import { dateLabel, money0, ymd } from "@/lib/format";
|
||||||
import { deterministicMoves, ladder } from "@/lib/plan";
|
import { deterministicMoves, ladder } from "@/lib/plan";
|
||||||
import { myPlanFacts } from "@/lib/plan-facts";
|
import { myPlanFacts } from "@/lib/plan-facts";
|
||||||
import { payGuess } from "@/lib/pay";
|
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 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 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
|
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.
|
// 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([
|
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.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", uid),
|
||||||
supabase.rpc("fx_missing"),
|
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),
|
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(),
|
categories(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -93,8 +95,8 @@ export default async function Dashboard() {
|
|||||||
{ label: "You owe", value: owed == null ? null : Math.abs(owed), href: "/debt" },
|
{ label: "You owe", value: owed == null ? null : Math.abs(owed), href: "/debt" },
|
||||||
].filter((t) => t.value != null);
|
].filter((t) => t.value != null);
|
||||||
|
|
||||||
const pic = moneyPicture(rows, cats, ymd(monthStart(now)).slice(0, 7), null);
|
const pic = moneyPicture(rows, cats, thisMonth, null);
|
||||||
const monthName = dateLabel(day, { month: "long" });
|
const monthName = dateLabel(`${thisMonth}-01`, { month: "long" });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4 max-w-4xl">
|
<div className="space-y-4 max-w-4xl">
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { EmptyBank } from "@/components/EmptyBank";
|
|||||||
import { MonthBars } from "@/components/MonthBars";
|
import { MonthBars } from "@/components/MonthBars";
|
||||||
import { PageDates } from "@/components/PageDates";
|
import { PageDates } from "@/components/PageDates";
|
||||||
import { Merchant } from "@/components/Merchant";
|
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";
|
import { dateLabel, money, money0, monthLabel, monthStart, ymd } from "@/lib/format";
|
||||||
|
|
||||||
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
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 { m, bills, from: rawFrom, to: rawTo, span } = await searchParams;
|
||||||
const from = DAY.test(rawFrom ?? "") ? rawFrom! : "", to = DAY.test(rawTo ?? "") ? rawTo! : "";
|
const from = DAY.test(rawFrom ?? "") ? rawFrom! : "", to = DAY.test(rawTo ?? "") ? rawTo! : "";
|
||||||
const includeBills = bills !== "0";
|
const includeBills = bills !== "0";
|
||||||
const now = await today();
|
let now = await today();
|
||||||
if (from || to) return <CustomRange from={from} to={to} today={ymd(now)} />;
|
if (from || to) return <CustomRange from={from} to={to} today={ymd(now)} />;
|
||||||
const { supabase, user } = await getUser();
|
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.
|
// 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;
|
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.
|
// 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 month = monthStart(now, offset);
|
||||||
const prevMonth = monthStart(now, offset - 1);
|
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
|
// 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([
|
const [rows, allCats, monthTxns, loans, savedMonths] = await Promise.all([
|
||||||
moneyByMonth(supabase, ymd(first)),
|
moneyByMonth(supabase, ymd(first)),
|
||||||
categories(),
|
categories(),
|
||||||
transactionsSince(ymd(month), ymd(monthStart(now, offset + 1))),
|
transactionsSince(mo.range(ymOf(month)).start, mo.range(ymOf(month)).end),
|
||||||
loanPayments(supabase, user!.id, ymd(first)),
|
loanPayments(supabase, user!.id, mo.range(ymOf(first)).start, undefined, mo.of),
|
||||||
savedByMonth(supabase, user!.id, ymd(first)),
|
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.
|
// 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." />;
|
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 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)}`);
|
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][]);
|
const qs = (o: Record<string, string | undefined>) => "/spending?" + new URLSearchParams(Object.entries({ m, bills, span, ...o }).filter(([, v]) => v) as [string, string][]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -191,14 +201,17 @@ export default async function Spending({ searchParams }: { searchParams: Promise
|
|||||||
{offset > -59 ? (
|
{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>
|
<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="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 ? (
|
{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>
|
<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" />}
|
) : <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>}
|
{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>
|
</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">
|
<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>
|
</section>
|
||||||
</div>
|
</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>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
|||||||
@@ -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
|
// 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
|
// 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.
|
// 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) {
|
export async function POST(request: Request) {
|
||||||
const { data: { user } } = await (await createClient()).auth.getUser();
|
const { data: { user } } = await (await createClient()).auth.getUser();
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ export type BudgetCat = { id: string; label: string; icon: string; color: string
|
|||||||
// Bars use the app's chart blue, like the rest of the app; only an overspend turns red.
|
// Bars use the app's chart blue, like the rest of the app; only an overspend turns red.
|
||||||
const TEXT = { ok: "text-muted", near: "text-ink", over: "text-bad" };
|
const TEXT = { ok: "text-muted", near: "text-ink", over: "text-bad" };
|
||||||
|
|
||||||
export function BudgetEditor({ basis, cats: all, initial, year, range, today, income, now, tableMissing, aside }: { basis: string; cats: BudgetCat[]; initial: Record<string, number>; year: MonthSpend[]; range: BudgetRange | null; today: string; income: number; now: string; tableMissing: boolean; aside?: React.ReactNode }) {
|
// span and label: with pay months on, this month's dates and the calendar month it's named after ("YYYY-MM-01").
|
||||||
|
export function BudgetEditor({ basis, cats: all, initial, year, range, today, income, now, tableMissing, aside, span, label }: { basis: string; cats: BudgetCat[]; initial: Record<string, number>; year: MonthSpend[]; range: BudgetRange | null; today: string; income: number; now: string; tableMissing: boolean; aside?: React.ReactNode; span?: { start: string; end: string }; label?: string }) {
|
||||||
const { money0, dateLabel } = useMoney();
|
const { money0, dateLabel } = useMoney();
|
||||||
const root = useRef<HTMLDivElement>(null);
|
const root = useRef<HTMLDivElement>(null);
|
||||||
const [budgets, setBudgets] = useState(initial);
|
const [budgets, setBudgets] = useState(initial);
|
||||||
@@ -41,8 +42,8 @@ export function BudgetEditor({ basis, cats: all, initial, year, range, today, in
|
|||||||
try { localStorage.setItem("budget-view", v); } catch {}
|
try { localStorage.setItem("budget-view", v); } catch {}
|
||||||
};
|
};
|
||||||
|
|
||||||
const m = month(new Date(now));
|
const m = month(new Date(now), span);
|
||||||
const d = new Date(now);
|
const d = new Date(label ? `${label}T00:00:00Z` : now);
|
||||||
const lastMonth = dateLabel(new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - 1, 1)).toISOString().slice(0, 10), { month: "long" });
|
const lastMonth = dateLabel(new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - 1, 1)).toISOString().slice(0, 10), { month: "long" });
|
||||||
// This month or last: the same rows with "spent" swapped, so the list, table and summary all follow.
|
// This month or last: the same rows with "spent" swapped, so the list, table and summary all follow.
|
||||||
const [period, setPeriod] = useState<"this" | "last" | "year" | "custom">(() => range ? "custom" : startPeriod(m.day, all.filter((c) => c.id in initial).reduce((s, c) => s + c.last, 0)));
|
const [period, setPeriod] = useState<"this" | "last" | "year" | "custom">(() => range ? "custom" : startPeriod(m.day, all.filter((c) => c.id in initial).reduce((s, c) => s + c.last, 0)));
|
||||||
@@ -227,7 +228,7 @@ export function BudgetEditor({ basis, cats: all, initial, year, range, today, in
|
|||||||
<div className="section-label px-1">Summary</div>
|
<div className="section-label px-1">Summary</div>
|
||||||
<section className="card p-6 space-y-5">
|
<section className="card p-6 space-y-5">
|
||||||
<div>
|
<div>
|
||||||
<div className="card-title">{past ? lastMonth : dateLabel(now.slice(0, 10), { month: "long" })}</div>
|
<div className="card-title">{past ? lastMonth : dateLabel(label ?? now.slice(0, 10), { month: "long" })}</div>
|
||||||
<div className="figure mt-1">
|
<div className="figure mt-1">
|
||||||
{left >= 0 ? <CountUp value={left} format="money0" /> : money0(-left)}{" "}
|
{left >= 0 ? <CountUp value={left} format="money0" /> : money0(-left)}{" "}
|
||||||
<span className={`text-base font-medium tracking-normal ${left >= 0 ? "text-muted" : "text-bad"}`}>{left >= 0 ? (past ? "under" : "left") : "over"}</span>
|
<span className={`text-base font-medium tracking-normal ${left >= 0 ? "text-muted" : "text-bad"}`}>{left >= 0 ? (past ? "under" : "left") : "over"}</span>
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export type Profile = {
|
|||||||
alsoBanksIn?: string[]; // countries besides their own: only "NZ" changes anything today (wantsAkahu)
|
alsoBanksIn?: string[]; // countries besides their own: only "NZ" changes anything today (wantsAkahu)
|
||||||
credit?: string; creditAsOf?: string; // a credit.ts Band and a "YYYY-MM" month
|
credit?: string; creditAsOf?: string; // a credit.ts Band and a "YYYY-MM" month
|
||||||
pay?: { amount: number; every: string }; // take-home pay per check; every: a Plaid frequency (WEEKLY ... MONTHLY)
|
pay?: { amount: number; every: string }; // take-home pay per check; every: a Plaid frequency (WEEKLY ... MONTHLY)
|
||||||
|
month?: "payday"; // months start on payday (lib/paymonths.ts); absent = on the 1st
|
||||||
onboarding?: string; // the first-run step to resume at (Onboarding.tsx); absent or "done" = finished
|
onboarding?: string; // the first-run step to resume at (Onboarding.tsx); absent or "done" = finished
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -117,6 +118,17 @@ export function ProfileForm({ initial }: { initial: Profile }) {
|
|||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted -mt-2">Your credit range picks which cards fit you on the Cards page.</p>
|
<p className="text-xs text-muted -mt-2">Your credit range picks which cards fit you on the Cards page.</p>
|
||||||
|
|
||||||
|
<Field label="A month starts">
|
||||||
|
<Dropdown
|
||||||
|
label="A month starts"
|
||||||
|
value={p.month ?? "calendar"}
|
||||||
|
options={[{ value: "calendar", label: "On the 1st" }, { value: "payday", label: "On payday" }]}
|
||||||
|
onChange={(v) => { setP({ ...p, month: v === "payday" ? "payday" : undefined }); setSaved(false); }}
|
||||||
|
placeholder="On the 1st"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted pt-1">On payday: each month runs from one salary to the day before the next, and is named after the month it mostly covers. Salary is money in under Income.</p>
|
||||||
|
</Field>
|
||||||
|
|
||||||
<Field label="Goals">
|
<Field label="Goals">
|
||||||
<GoalPicker goals={p.goals ?? []} plans={p.goalPlans ?? []} onChange={(goals, goalPlans) => { setP({ ...p, goals, goalPlans: goalPlans as GoalPlan[] }); setSaved(false); }} />
|
<GoalPicker goals={p.goals ?? []} plans={p.goalPlans ?? []} onChange={(goals, goalPlans) => { setP({ ...p, goals, goalPlans: goalPlans as GoalPlan[] }); setSaved(false); }} />
|
||||||
</Field>
|
</Field>
|
||||||
|
|||||||
+5
-3
@@ -34,9 +34,11 @@ export function retune<C extends { id: string; suggested: number; main: boolean
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Where the month is: today counts as a day left.
|
// Where the month is: today counts as a day left.
|
||||||
export function month(now: Date) {
|
// span: a pay month's first day and the day after its last (lib/paymonths.ts), else the calendar month.
|
||||||
const day = now.getUTCDate();
|
export function month(now: Date, span?: { start: string; end: string }) {
|
||||||
const days = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();
|
const at = (d: string) => Date.parse(`${d}T00:00:00Z`);
|
||||||
|
const day = span ? Math.round((now.getTime() - at(span.start)) / 864e5) + 1 : now.getUTCDate();
|
||||||
|
const days = span ? Math.round((at(span.end) - at(span.start)) / 864e5) : new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();
|
||||||
return { day, days, left: days - day + 1, pace: day / days };
|
return { day, days, left: days - day + 1, pace: day / days };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+62
-4
@@ -5,6 +5,7 @@ import { cache } from "react";
|
|||||||
import { dayIn, fmtFor, setFmtScope, US_FMT, type Fmt } from "@/lib/format";
|
import { dayIn, fmtFor, setFmtScope, US_FMT, type Fmt } from "@/lib/format";
|
||||||
import { ensureRates } from "@/lib/fx";
|
import { ensureRates } from "@/lib/fx";
|
||||||
import { typicalMonth } from "@/lib/insights";
|
import { typicalMonth } from "@/lib/insights";
|
||||||
|
import { detectPeriods, monthOf, rangeOf, type Pay, type Period } from "@/lib/paymonths";
|
||||||
import { createAdminClient } from "@/utils/supabase/admin";
|
import { createAdminClient } from "@/utils/supabase/admin";
|
||||||
import { createClient } from "@/utils/supabase/server";
|
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.
|
// 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.
|
// 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 };
|
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) {
|
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 });
|
const { data, error } = await supabase.rpc("money_by_month", { start_date: start, end_date: end ?? null });
|
||||||
if (error) throw new Error(error.message);
|
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) }));
|
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 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.
|
// 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) {
|
export async function typicalMonthly(supabase: SupabaseClient, userId: string, today: string) {
|
||||||
|
today = await payMonthToday(supabase, userId, today);
|
||||||
const [y, m] = today.split("-").map(Number);
|
const [y, m] = today.split("-").map(Number);
|
||||||
const [rows, { data }] = await Promise.all([
|
const [rows, { data }] = await Promise.all([
|
||||||
moneyByMonth(supabase, new Date(Date.UTC(y, m - 4, 1)).toISOString().slice(0, 10)),
|
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);
|
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),
|
// 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:
|
// 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.
|
// 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) =>
|
const rows = await allRows<{ date: string; amount: number }>((a, b) =>
|
||||||
supabase.from("transactions").select("date, amount, category:categories!inner(key), account:accounts!inner(type)")
|
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("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));
|
.eq("category.key", "LOAN_PAYMENTS").neq("account.type", "loan").order("id").range(a, b));
|
||||||
const by = new Map<string, number>();
|
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;
|
return by;
|
||||||
}
|
}
|
||||||
// Money going into savings and investment accounts per "YYYY-MM": what arrives on a savings account (net of what leaves it)
|
// 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.
|
// 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 { 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 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 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)
|
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));
|
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) {
|
if (invest.length) {
|
||||||
@@ -161,3 +176,46 @@ export async function allTags() {
|
|||||||
if (!seen.has(tag.toLowerCase())) seen.set(tag.toLowerCase(), tag);
|
if (!seen.has(tag.toLowerCase())) seen.set(tag.toLowerCase(), tag);
|
||||||
return [...seen.values()].sort((a, b) => a.localeCompare(b));
|
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)),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Run: node src/lib/paymonths.test.ts
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { detectPeriods, monthOf, paychecks, rangeOf } from "./paymonths.ts";
|
||||||
|
|
||||||
|
// Salary around the 24th or 25th, early when that's a weekend. A tax refund and student finance are no paychecks.
|
||||||
|
const pays = [
|
||||||
|
{ date: "2026-07-24", amount: 2700 }, { date: "2026-08-25", amount: 2700 }, { date: "2026-09-04", amount: 310 },
|
||||||
|
{ date: "2026-09-24", amount: 2750 }, { date: "2026-10-23", amount: 2760 }, { date: "2026-10-30", amount: 64 },
|
||||||
|
];
|
||||||
|
assert.deepEqual(paychecks(pays).map((p) => p.date), ["2026-07-24", "2026-08-25", "2026-09-24", "2026-10-23"]);
|
||||||
|
|
||||||
|
let ps = detectPeriods(pays, "2026-07-02", "2026-11-22")!;
|
||||||
|
assert.deepEqual(ps, [
|
||||||
|
{ month: "2026-08-01", start: "2026-07-24" },
|
||||||
|
{ month: "2026-09-01", start: "2026-08-25" },
|
||||||
|
{ month: "2026-10-01", start: "2026-09-24" },
|
||||||
|
{ month: "2026-11-01", start: "2026-10-23" },
|
||||||
|
], "December has not started: no salary yet and it isn't the 24th");
|
||||||
|
assert.equal(monthOf(ps, "2026-10-22"), "2026-10");
|
||||||
|
assert.equal(monthOf(ps, "2026-10-23"), "2026-11", "salary day opens the month");
|
||||||
|
assert.equal(monthOf(ps, "2026-07-10"), "2026-07", "before the first salary: calendar");
|
||||||
|
assert.deepEqual(rangeOf(ps, "2026-10"), { start: "2026-09-24", end: "2026-10-23" });
|
||||||
|
assert.deepEqual(rangeOf(ps, "2026-11"), { start: "2026-10-23", end: "2026-11-23" }, "running month: a month on");
|
||||||
|
assert.deepEqual(rangeOf(ps, "2026-07"), { start: "2026-07-01", end: "2026-07-24" }, "the month before the first salary");
|
||||||
|
assert.deepEqual(rangeOf(null, "2026-02"), { start: "2026-02-01", end: "2026-03-01" });
|
||||||
|
|
||||||
|
// Salary late: past the usual day the month waits for it, a day at a time.
|
||||||
|
ps = detectPeriods(pays, "2026-07-02", "2026-11-26")!;
|
||||||
|
assert.equal(ps.at(-1)!.month, "2026-11-01", "the 26th, still no salary: November runs on");
|
||||||
|
// It comes on the 27th.
|
||||||
|
ps = detectPeriods([...pays, { date: "2026-11-27", amount: 2780 }], "2026-07-02", "2026-11-27")!;
|
||||||
|
assert.deepEqual(ps.at(-1), { month: "2026-12-01", start: "2026-11-27" });
|
||||||
|
// No salary at all for 12 days after the usual day (the 25th here): the usual day stands in.
|
||||||
|
ps = detectPeriods(pays.slice(0, 2), "2026-07-02", "2026-10-30")!;
|
||||||
|
assert.deepEqual(ps.map((p) => p.start), ["2026-07-24", "2026-08-25", "2026-09-25"]);
|
||||||
|
|
||||||
|
// Paid on the 1st: each month starts on its own payday.
|
||||||
|
ps = detectPeriods([{ date: "2026-09-01", amount: 2000 }, { date: "2026-09-30", amount: 2000 }, { date: "2026-11-02", amount: 2000 }], "2026-09-01", "2026-11-05")!;
|
||||||
|
assert.deepEqual(ps, [{ month: "2026-09-01", start: "2026-09-01" }, { month: "2026-10-01", start: "2026-09-30" }, { month: "2026-11-01", start: "2026-11-02" }]);
|
||||||
|
|
||||||
|
assert.equal(detectPeriods([], "2026-01-01", "2026-11-22"), null);
|
||||||
|
console.log("paymonths ok");
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// Months that start on payday (profile.month = "payday"): each month runs from one salary to the day before the next.
|
||||||
|
// A month is named after the calendar month it mostly covers, so salary on 24 October starts "November".
|
||||||
|
// Salary: money in under the Income category, at least half a usual paycheck, so a small refund never starts a month.
|
||||||
|
// Before the first salary, or for a month whose salary hasn't come yet, the usual pay day stands in.
|
||||||
|
// Pure: `node src/lib/paymonths.test.ts` runs it.
|
||||||
|
|
||||||
|
export type Pay = { date: string; amount: number }; // amount: money in, positive
|
||||||
|
export type Period = { month: string; start: string }; // month: "YYYY-MM-01", start: "YYYY-MM-DD"
|
||||||
|
|
||||||
|
const DAY = 864e5;
|
||||||
|
const at = (iso: string) => Date.parse(`${iso}T00:00:00Z`);
|
||||||
|
const iso = (t: number) => new Date(t).toISOString().slice(0, 10);
|
||||||
|
const addMonths = (ym: string, n: number) => iso(Date.UTC(+ym.slice(0, 4), +ym.slice(5, 7) - 1 + n, 1)).slice(0, 7);
|
||||||
|
const median = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : 0; };
|
||||||
|
const dayIn = (ym: string, d: number) => {
|
||||||
|
const last = new Date(Date.UTC(+ym.slice(0, 4), +ym.slice(5, 7), 0)).getUTCDate();
|
||||||
|
return `${ym}-${String(Math.min(d, last)).padStart(2, "0")}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The paychecks among money in: per calendar month the biggest one sets a usual size, and anything at least half
|
||||||
|
* of that counts. */
|
||||||
|
export function paychecks(pays: Pay[]) {
|
||||||
|
const top = new Map<string, number>();
|
||||||
|
for (const p of pays) top.set(p.date.slice(0, 7), Math.max(top.get(p.date.slice(0, 7)) ?? 0, p.amount));
|
||||||
|
const usual = median([...top.values()]);
|
||||||
|
return usual > 0 ? pays.filter((p) => p.amount >= usual / 2).sort((a, b) => a.date.localeCompare(b.date)) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every month from the one holding `first` up to the one today is in. Null with no salary to go by. */
|
||||||
|
export function detectPeriods(pays: Pay[], first: string, today: string): Period[] | null {
|
||||||
|
const checks = paychecks(pays);
|
||||||
|
if (!checks.length) return null;
|
||||||
|
const usualDay = median(checks.map((p) => +p.date.slice(8, 10)));
|
||||||
|
// Pay late in the month starts the next month's period; pay early in the month starts its own.
|
||||||
|
const lead = usualDay >= 15 ? 1 : 0;
|
||||||
|
const out: Period[] = [];
|
||||||
|
for (let ym = addMonths(first.slice(0, 7), lead); ; ym = addMonths(ym, 1)) {
|
||||||
|
const expected = dayIn(addMonths(ym, -lead), usualDay);
|
||||||
|
const prev = out.at(-1)?.start;
|
||||||
|
// Salary up to 12 days either side of the usual day (weekends, holidays, a late employer), at least 20 days after
|
||||||
|
// the last start, so one paycheck never starts two months.
|
||||||
|
const found = checks.find((p) => Math.abs(at(p.date) - at(expected)) <= 12 * DAY && (!prev || at(p.date) - at(prev) >= 20 * DAY));
|
||||||
|
const waiting = !found && at(expected) + 12 * DAY > at(today);
|
||||||
|
// Not paid yet: the month can't start before tomorrow, so today stays in the month that's running.
|
||||||
|
const start = found ? found.date : waiting ? iso(Math.max(at(expected), at(today) + DAY)) : expected;
|
||||||
|
if (start > today) break;
|
||||||
|
out.push({ month: `${ym}-01`, start });
|
||||||
|
}
|
||||||
|
return out.length ? out : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "YYYY-MM" of the month a date is in. Without pay months (or before the first one): its calendar month. */
|
||||||
|
export function monthOf(periods: Period[] | null, date: string) {
|
||||||
|
if (periods) for (let i = periods.length - 1; i >= 0; i--) if (periods[i].start <= date) return periods[i].month.slice(0, 7);
|
||||||
|
return date.slice(0, 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** First day and the day after the last day of a month ("YYYY-MM"). */
|
||||||
|
export function rangeOf(periods: Period[] | null, ym: string) {
|
||||||
|
const cal = { start: `${ym}-01`, end: `${addMonths(ym, 1)}-01` };
|
||||||
|
if (!periods?.length) return cal;
|
||||||
|
const i = periods.findIndex((p) => p.month.startsWith(ym));
|
||||||
|
if (i < 0) return ym < periods[0].month ? { start: cal.start, end: ym === addMonths(periods[0].month, -1) ? periods[0].start : cal.end } : cal;
|
||||||
|
// The running month: its end is a guess, the same day a month on (the next salary decides).
|
||||||
|
const s = periods[i].start;
|
||||||
|
return { start: s, end: periods[i + 1]?.start ?? dayIn(addMonths(s.slice(0, 7), 1), +s.slice(8, 10)) };
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import { cardMatches } from "@/lib/cards-data";
|
|||||||
import { cashInsights, myCashInsights } from "@/lib/cash";
|
import { cashInsights, myCashInsights } from "@/lib/cash";
|
||||||
import { countryOf } from "@/lib/countries";
|
import { countryOf } from "@/lib/countries";
|
||||||
import { cache } from "react";
|
import { cache } from "react";
|
||||||
import { allRows, displayName, getUser, isIncome, isSpend, moneyByMonth, today as userToday, TXN_SELECT, type Txn, loanPayments } from "@/lib/data";
|
import { allRows, displayName, getUser, isIncome, isSpend, moneyByMonth, payMonthToday, today as userToday, TXN_SELECT, type Txn, loanPayments } from "@/lib/data";
|
||||||
import { dateLabel, fmtFor, money0, ymd } from "@/lib/format";
|
import { dateLabel, fmtFor, money0, ymd } from "@/lib/format";
|
||||||
import { addDays, toldMonthly } from "@/lib/insights";
|
import { addDays, toldMonthly } from "@/lib/insights";
|
||||||
import { contributionRoom } from "@/lib/invest";
|
import { contributionRoom } from "@/lib/invest";
|
||||||
@@ -52,6 +52,8 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
|
|||||||
const country = countryOf(profile.country);
|
const country = countryOf(profile.country);
|
||||||
const since = addDays(today, -90);
|
const since = addDays(today, -90);
|
||||||
const usTax = country.code === "US" && Number(today.slice(0, 4)) === TAX_YEAR;
|
const usTax = country.code === "US" && Number(today.slice(0, 4)) === TAX_YEAR;
|
||||||
|
// Month logic runs on the pay month today is in when months start on payday (lib/paymonths.ts).
|
||||||
|
const monthToday = await payMonthToday(supabase, userId, today);
|
||||||
// US tax rows load in the same batch: they only depend on usTax.
|
// US tax rows load in the same batch: they only depend on usTax.
|
||||||
const [cash, { streams, txns: charges }, { data: rec }, months, txns, { data: cats }, room, cards, byMonth, { data: accts }, [taxTxns, { data: held }]] = await Promise.all([
|
const [cash, { streams, txns: charges }, { data: rec }, months, txns, { data: cats }, room, cards, byMonth, { data: accts }, [taxTxns, { data: held }]] = await Promise.all([
|
||||||
cash0 ?? cashInsights(supabase, profile, { userId, today }),
|
cash0 ?? cashInsights(supabase, profile, { userId, today }),
|
||||||
@@ -62,7 +64,7 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
|
|||||||
supabase.from("categories").select("id, label, key"),
|
supabase.from("categories").select("id, label, key"),
|
||||||
contributionRoom(supabase, profile, { tax: country.tax, today, locale: country.locale, mine: profile.contributed as Record<string, number> | undefined }).catch(() => []),
|
contributionRoom(supabase, profile, { tax: country.tax, today, locale: country.locale, mine: profile.contributed as Record<string, number> | undefined }).catch(() => []),
|
||||||
country.cards ? cardMatches(supabase, userId, creditOf(profile)?.band) : Promise.resolve(null),
|
country.cards ? cardMatches(supabase, userId, creditOf(profile)?.band) : Promise.resolve(null),
|
||||||
moneyByMonth(supabase, monthStart(today, -3)),
|
moneyByMonth(supabase, monthStart(monthToday, -3)),
|
||||||
supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", userId),
|
supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", userId),
|
||||||
usTax
|
usTax
|
||||||
? Promise.all([
|
? Promise.all([
|
||||||
@@ -160,7 +162,7 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
|
|||||||
// The affordability gate's numbers: monthly income and spending over the last full months with data (up to 3),
|
// The affordability gate's numbers: monthly income and spending over the last full months with data (up to 3),
|
||||||
// essentials from the same months, and cash available now (the same figure as safe to spend).
|
// essentials from the same months, and cash available now (the same figure as safe to spend).
|
||||||
const key = new Map((cats ?? []).map((c) => [c.id as string, c.key as string]));
|
const key = new Map((cats ?? []).map((c) => [c.id as string, c.key as string]));
|
||||||
const thisMonth = today.slice(0, 7);
|
const thisMonth = monthToday.slice(0, 7);
|
||||||
const perMonth = new Map<string, { income: number; spend: number; essentials: number; cats: Map<string, number> }>();
|
const perMonth = new Map<string, { income: number; spend: number; essentials: number; cats: Map<string, number> }>();
|
||||||
for (const row of byMonth) {
|
for (const row of byMonth) {
|
||||||
const m = row.month.slice(0, 7);
|
const m = row.month.slice(0, 7);
|
||||||
@@ -178,11 +180,11 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
|
|||||||
// No paycheck found (typicalMonth has no income): the take-home pay they told us in onboarding, flagged. Never mixed in.
|
// No paycheck found (typicalMonth has no income): the take-home pay they told us in onboarding, flagged. Never mixed in.
|
||||||
const told = cash.typical && cash.typical.income > 0 ? null : toldMonthly(profile.pay as { amount?: number; every?: string } | undefined);
|
const told = cash.typical && cash.typical.income > 0 ? null : toldMonthly(profile.pay as { amount?: number; every?: string } | undefined);
|
||||||
// Loan payments aren't spending in the totals, but the money is gone and they can't be skipped: count them as essentials.
|
// Loan payments aren't spending in the totals, but the money is gone and they can't be skipped: count them as essentials.
|
||||||
const paid = await loanPayments(supabase, userId, monthStart(today, -3));
|
const paid = await loanPayments(supabase, userId, monthStart(monthToday, -3));
|
||||||
const baseMonths = [...perMonth].filter(([, x]) => base.includes(x)).map(([m]) => m);
|
const baseMonths = [...perMonth].filter(([, x]) => base.includes(x)).map(([m]) => m);
|
||||||
const loanAvg = baseMonths.length ? baseMonths.reduce((s, m) => s + (paid.get(m) ?? 0), 0) / baseMonths.length : 0;
|
const loanAvg = baseMonths.length ? baseMonths.reduce((s, m) => s + (paid.get(m) ?? 0), 0) / baseMonths.length : 0;
|
||||||
const budget = { income: r2(told ?? avg((x) => x.income)), ...(told ? { incomeTold: true } : {}), spend: r2(spendAvg + loanAvg), cash: r2(cash.safe.cash), essentials: r2((essentials > 0 ? essentials : spendAvg) + loanAvg), essentialsAll: !(essentials > 0) };
|
const budget = { income: r2(told ?? avg((x) => x.income)), ...(told ? { incomeTold: true } : {}), spend: r2(spendAvg + loanAvg), cash: r2(cash.safe.cash), essentials: r2((essentials > 0 ? essentials : spendAvg) + loanAvg), essentialsAll: !(essentials > 0) };
|
||||||
const last = monthStart(today, -1).slice(0, 7);
|
const last = monthStart(monthToday, -1).slice(0, 7);
|
||||||
const monthRows = [last, thisMonth].flatMap((m) => { const x = perMonth.get(m); return x && (x.spend || x.income) ? [{ month: m, income: r2(x.income), spend: r2(x.spend) }] : []; });
|
const monthRows = [last, thisMonth].flatMap((m) => { const x = perMonth.get(m); return x && (x.spend || x.income) ? [{ month: m, income: r2(x.income), spend: r2(x.spend) }] : []; });
|
||||||
const now = perMonth.get(thisMonth);
|
const now = perMonth.get(thisMonth);
|
||||||
const spikes = earlier.length && now
|
const spikes = earlier.length && now
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-- Months that start on payday (profile.month = "payday", src/lib/paymonths.ts): one row per month with the day it starts.
|
||||||
|
-- The server writes them (lib/data.ts payPeriods) whenever they change; with no rows, months are calendar months.
|
||||||
|
create table if not exists public.pay_periods (
|
||||||
|
user_id uuid not null references auth.users on delete cascade,
|
||||||
|
month date not null, -- the calendar month it's named after, first day
|
||||||
|
start_date date not null,
|
||||||
|
primary key (user_id, month)
|
||||||
|
);
|
||||||
|
create index if not exists pay_periods_start on public.pay_periods (user_id, start_date);
|
||||||
|
alter table public.pay_periods enable row level security;
|
||||||
|
drop policy if exists "own" on public.pay_periods;
|
||||||
|
create policy "own" on public.pay_periods for select to authenticated using (user_id = (select auth.uid()));
|
||||||
|
grant select on public.pay_periods to authenticated;
|
||||||
|
|
||||||
|
-- By month and category, the month being the pay month a day falls in (the latest start on or before it), else the
|
||||||
|
-- calendar month. n counts every own row in the group, counted or not (pages use it for "months of data").
|
||||||
|
create or replace function public.money_by_month(start_date date, end_date date default null)
|
||||||
|
returns table (month date, category_id uuid, spend numeric, income numeric, n bigint)
|
||||||
|
language sql stable set search_path = '' as $$
|
||||||
|
with x as (
|
||||||
|
select coalesce(
|
||||||
|
(select p.month from public.pay_periods p where p.user_id = (select auth.uid()) and p.start_date <= r.date order by p.start_date desc limit 1),
|
||||||
|
date_trunc('month', r.date)::date) as month,
|
||||||
|
r.category_id, r.spend, r.income
|
||||||
|
from public.money_rows(start_date, end_date) r
|
||||||
|
)
|
||||||
|
select x.month, x.category_id, sum(x.spend), sum(x.income), count(*) from x group by 1, 2
|
||||||
|
$$;
|
||||||
Reference in new issue
Block a user