diff --git a/src/app/(app)/charts/page.tsx b/src/app/(app)/charts/page.tsx index ab215aa..2c663f2 100644 --- a/src/app/(app)/charts/page.tsx +++ b/src/app/(app)/charts/page.tsx @@ -1,8 +1,8 @@ import { ChartFilters } from "@/components/charts/ChartFilters"; import { ChartsView, type ChartsData } from "@/components/charts/ChartsView"; import { EmptyBank } from "@/components/EmptyBank"; -import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periods, previousRange, rankBySpend, savingsRate, totals, type Group, type Row } from "@/lib/charts"; -import { accountName, allTags, categories, displayName, getUser, isIncome, isSpend, today, transactionsSince } from "@/lib/data"; +import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periods, previousRange, rankBySpend, savingsRate, totals, type Group, type Months, type Row } from "@/lib/charts"; +import { accountName, allTags, categories, displayName, getUser, isIncome, isSpend, months, today, transactionsSince } from "@/lib/data"; import { ymd } from "@/lib/format"; // Charts: money over time with filters. Every number comes from lib/charts.ts over the same spend / income rule as @@ -18,6 +18,9 @@ export default async function Charts({ searchParams }: { searchParams: Promise { const d = new Date(`${now.slice(0, 7)}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() - n + 1); return ymd(d); }; + const monthsBack = (n: number) => { const d = new Date(`${pm ? pm.of(now) : now.slice(0, 7)}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() - n + 1); return pm ? pm.range(ymd(d).slice(0, 7)).start : ymd(d); }; const preset = range === "1m" ? monthsBack(1) : range === "3m" ? monthsBack(3) : range === "6m" ? monthsBack(6) : range === "ytd" ? `${now.slice(0, 4)}-01-01` : range === "all" ? first : monthsBack(12); const from = DAY.test(sp.from ?? "") ? sp.from! : DAY.test(sp.to ?? "") ? first : preset; const to = DAY.test(sp.to ?? "") ? sp.to! : now; @@ -57,14 +60,14 @@ export default async function Charts({ searchParams }: { searchParams: Promise !q || r.text.includes(q) || r.merchant.toLowerCase().includes(q)) .map((r) => (dir === "out" ? { ...r, income: false } : dir === "in" ? { ...r, spend: false } : r)); const within = (a: string, b: string) => filtered.filter((r) => r.date >= a && r.date <= b); - const ps = periods(from, to, group); + const ps = periods(from, to, group, pm); const rows = within(from, to); const compare = sp.cmp === "1"; const prev = previousRange(from, to); const before = within(prev.from, prev.to); // The period before, lined up period by period with this one (same length, same grouping). - const psBefore = periods(prev.from, prev.to, group).slice(-ps.length); - const flowBefore = compare ? cashFlow(before, psBefore, group) : null; + const psBefore = periods(prev.from, prev.to, group, pm).slice(-ps.length); + const flowBefore = compare ? cashFlow(before, psBefore, group, pm) : null; const pad = (xs: T[] | null) => (xs ? [...Array(Math.max(0, ps.length - xs.length)).fill(null), ...xs] : null); // Stable colors: slots follow all-time spending, so filtering never repaints a category, merchant or account. @@ -79,10 +82,10 @@ export default async function Charts({ searchParams }: { searchParams: Promise a.included !== false && ["depository", "credit", "loan"].includes(a.type) && (!acct.length || acct.includes(a.id))); const bal = balances( accounts.map((a) => ({ id: a.id, name: accountName(a), balance: Number((a.manual ? a.balance : a.current_balance) ?? 0), owed: a.type === "credit" || a.type === "loan" })), - all.filter((r) => r.date > from), from, to, group, + all.filter((r) => r.date > from), from, to, group, pm, ); - const flow = cashFlow(rows, ps, group); - const psMonth = periods(from, to, "month"); + const flow = cashFlow(rows, ps, group, pm); + const psMonth = periods(from, to, "month", pm); const ch = biggestChanges(rows, before, (r) => r.categoryId); const data: ChartsData = { @@ -93,14 +96,14 @@ export default async function Charts({ searchParams }: { searchParams: Promise f ?? { key: ps[i].key, income: 0, spend: 0, net: 0 }) : null, // Savings rate is per month whatever the grouping: most weeks have no pay in them, and a rate of nothing isn't 0%. - rate: { periods: psMonth, values: savingsRate(cashFlow(rows, psMonth, "month")).map((r) => r.rate) }, - rateBefore: compare ? (() => { const pm = periods(prev.from, prev.to, "month").slice(-psMonth.length); const v = savingsRate(cashFlow(before, pm, "month")).map((r) => r.rate); return [...Array(Math.max(0, psMonth.length - v.length)).fill(null), ...v]; })() : null, - cats: { order: keep.map((id) => ({ id, label: label.get(id) ?? "Uncategorized", slot: catSlot.get(id)! })), values: categoriesOver(rows, ps, group, keep).map((c) => c.values) }, - mtd: monthToDate(filtered, now), + rate: { periods: psMonth, values: savingsRate(cashFlow(rows, psMonth, "month", pm)).map((r) => r.rate) }, + rateBefore: compare ? (() => { const pb = periods(prev.from, prev.to, "month", pm).slice(-psMonth.length); const v = savingsRate(cashFlow(before, pb, "month", pm)).map((r) => r.rate); return [...Array(Math.max(0, psMonth.length - v.length)).fill(null), ...v]; })() : null, + cats: { order: keep.map((id) => ({ id, label: label.get(id) ?? "Uncategorized", slot: catSlot.get(id)! })), values: categoriesOver(rows, ps, group, keep, pm).map((c) => c.values) }, + mtd: monthToDate(filtered, now, pm), balance: { ...bal, series: bal.series.map((s, i) => ({ ...s, slot: (i % 8) + 1 })) }, weekday: byWeekday(rows, from, to), weekdayBefore: compare ? byWeekday(before, prev.from, prev.to) : null, - merchants: merchantsOver(rows, ps, group, topMerch).map((m) => ({ ...m, slot: merchSlot(m.name) })), + merchants: merchantsOver(rows, ps, group, topMerch, pm).map((m) => ({ ...m, slot: merchSlot(m.name) })), changes: { categories: { up: ch.up.map((c) => ({ ...c, label: label.get(c.id) ?? "Uncategorized" })), down: ch.down.map((c) => ({ ...c, label: label.get(c.id) ?? "Uncategorized" })) }, merchants: biggestChanges(rows, before, (r) => r.merchant), diff --git a/src/app/api/checkins/route.ts b/src/app/api/checkins/route.ts index e6d719e..529303d 100644 --- a/src/app/api/checkins/route.ts +++ b/src/app/api/checkins/route.ts @@ -1,7 +1,7 @@ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { changeLines, checkinFacts, sameDollars, type CheckinFacts } from "@/lib/checkins"; -import { allRows, today as todayDate, displayName, isSpend, TXN_SELECT, typicalMonthly, type Txn } from "@/lib/data"; +import { allRows, today as todayDate, displayName, isSpend, paySpan, TXN_SELECT, typicalMonthly, type Txn } from "@/lib/data"; import { runViaHelper } from "@/lib/llm/helper"; import { runCodex, runGemini, runOpencode } from "@/lib/llm/cli-snapshot"; import { AGENT_DIR, runClaudeCode } from "@/lib/llm/claude-code"; @@ -83,6 +83,7 @@ async function generate(supabase: Sb, user: User, replace: string | null) { supabase.from("checkins").select("facts").eq("user_id", userId).lt("created_at", new Date(Date.now() - SINCE).toISOString()).order("created_at", { ascending: false }).limit(1).maybeSingle(), loadPlan(supabase, userId).catch(() => null), ]); + const span = await paySpan(supabase, userId, today); // months that start on payday, if on // The plan's next move by the ladder, or one marked done in the last 7 days. type M = { title: string; why: string; status?: string; done_at?: string | null; deadline: string | null; ref: string | null; kind: Kind; step: number | null }; const moves = (plan?.moves ?? []) as unknown as M[]; @@ -108,6 +109,7 @@ async function generate(supabase: Sb, user: User, replace: string | null) { prev: (prev?.facts as CheckinFacts | undefined) ?? null, move: pick ? { title: pick.title, line: whyLine(pick.title, pick.why), done: pick === justDone, by: pick.deadline ?? addDays(today, 7) } : null, today, + span, }); // Off: no model call, the card shows the plain facts. Summary: placeholders and rounded amounts, names swapped back below. diff --git a/src/app/api/onboarding/route.ts b/src/app/api/onboarding/route.ts index d6b6e68..fec6bc1 100644 --- a/src/app/api/onboarding/route.ts +++ b/src/app/api/onboarding/route.ts @@ -1,5 +1,5 @@ import { NextResponse } from "next/server"; -import { allRows, getUser, moneyByMonth, today as userToday } from "@/lib/data"; +import { allRows, getUser, moneyByMonth, payMonthToday, today as userToday } from "@/lib/data"; import { firstFact } from "@/lib/first-fact"; import { dateLabel, FREQ_PER_MONTH, money0, monthStart, ymd } from "@/lib/format"; import { typicalMonth } from "@/lib/insights"; @@ -17,13 +17,15 @@ export async function GET() { const now = await userToday(); const today = ymd(now); const since90 = ymd(new Date(now.getTime() - 90 * 864e5)); + // Month logic runs on the pay month today is in when months start on payday (lib/paymonths.ts). + const monthNow = new Date(`${(await payMonthToday(supabase, uid, today)).slice(0, 7)}-01T00:00:00Z`); const [{ data: items }, { data: accts }, { data: streams }, { data: cats }, { data: first }, rows, interest] = await Promise.all([ supabase.from("plaid_items").select("id, last_synced_at").eq("user_id", uid), supabase.from("accounts").select("id, type, manual").eq("user_id", uid), supabase.from("recurring").select("merchant_name, frequency, average_amount:home_average, is_income, next_date, category:categories(key)").eq("user_id", uid).eq("active", true).neq("status", "TOMBSTONED"), supabase.from("categories").select("id, label"), supabase.from("transactions").select("date").eq("user_id", uid).order("date").limit(1), - moneyByMonth(supabase, ymd(monthStart(now, -3))), + moneyByMonth(supabase, ymd(monthStart(monthNow, -3))), // Card or loan interest, the For you page's rule. allRows<{ amount: number }>((a, b) => supabase.from("transactions").select("amount").eq("user_id", uid).eq("ignored", false).gt("amount", 0).gte("date", since90) .or("plaid_category.eq.BANK_FEES_INTEREST_CHARGE,name.ilike.*interest charge*").order("id").range(a, b)), @@ -39,7 +41,7 @@ export async function GET() { if ((items ?? []).some((i) => !i.last_synced_at) || !oldest) return NextResponse.json({ ...base, status: "importing" }); // The biggest category in the last full month the history covers, against its average over the full months before it. - const ym = (k: number) => ymd(monthStart(now, -k)).slice(0, 7); + const ym = (k: number) => ymd(monthStart(monthNow, -k)).slice(0, 7); const covered = [1, 2, 3].map(ym).filter((m) => `${m}-01` >= oldest); const spentIn = (m: string) => { const by = new Map(); @@ -58,7 +60,7 @@ export async function GET() { }; } } - const typical = typicalMonth(rows, today, oldest); + const typical = typicalMonth(rows, await payMonthToday(supabase, uid, today), oldest); const subs = s.filter((x) => !x.is_income && !BILL.has(x.category?.key ?? "")).map((x) => ({ monthly: x.average_amount * (FREQ_PER_MONTH[x.frequency] ?? 0) })); const fact = firstFact({ typical, interest90: interest.reduce((t, r) => t + Number(r.amount), 0), subs, top }, (n) => money0(n)); return NextResponse.json({ ...base, status: fact ? "ready" : "thin", fact }); diff --git a/src/components/charts/ChartsView.tsx b/src/components/charts/ChartsView.tsx index 1835a58..f22dc56 100644 --- a/src/components/charts/ChartsView.tsx +++ b/src/components/charts/ChartsView.tsx @@ -20,7 +20,7 @@ export type ChartsData = { rate: { periods: Period[]; values: (number | null)[] }; rateBefore: (number | null)[] | null; cats: { order: { id: string; label: string; slot: number }[]; values: Record[] }; - mtd: { thisMonth: string; lastMonth: string; current: number[]; last: number[]; average: number[] }; + mtd: { thisMonth: string; lastMonth: string; start: string; current: number[]; last: number[]; average: number[] }; // start: day 1 (payday with pay months) balance: { days: string[]; series: { id: string; name: string; owed: boolean; slot: number; values: number[] }[]; total: number[] }; weekday: number[]; weekdayBefore: number[] | null; @@ -99,7 +99,7 @@ export function ChartsView({ d }: { d: ChartsData }) { [l, d.mtd.current[i] !== undefined ? money0(d.mtd.current[i]) : "–", d.mtd.last[i] !== undefined ? money0(d.mtd.last[i]) : "–", money0(d.mtd.average[i])]) }}> - activity({ from: `${d.mtd.thisMonth}-01`, to: `${d.mtd.thisMonth}-${String(i + 1).padStart(2, "0")}` })} series={[ + activity({ from: d.mtd.start, to: new Date(Date.parse(`${d.mtd.start}T00:00:00Z`) + i * 864e5).toISOString().slice(0, 10) })} series={[ { name: "3-month average", color: "var(--series-other)", values: d.mtd.average, width: 1.5 }, { name: "Last month", color: "var(--muted)", values: mtdDays.map((_, i) => d.mtd.last[i] ?? null), dashed: true, width: 1.5 }, { name: "This month", color: "var(--chart)", values: mtdDays.map((_, i) => d.mtd.current[i] ?? null), width: 2.5 }, diff --git a/src/lib/charts.test.ts b/src/lib/charts.test.ts index b4d50ed..7c2d8da 100644 --- a/src/lib/charts.test.ts +++ b/src/lib/charts.test.ts @@ -1,5 +1,6 @@ // node src/lib/charts.test.ts import assert from "node:assert/strict"; +import { monthOf, rangeOf } from "./paymonths.ts"; import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periodKey, periods, previousRange, rankBySpend, savingsRate, totals, type Row } from "./charts.ts"; const r = (date: string, amount: number, extra: Partial = {}): Row => ({ @@ -58,4 +59,17 @@ assert.equal(byWeekday([r("2026-11-02", 30)], "2026-11-02", "2026-11-15")[0], 15 const ch = biggestChanges([r("2026-11-02", 300, { categoryId: "fun" }), r("2026-11-03", 20)], [r("2026-10-02", 100, { categoryId: "fun" }), r("2026-10-03", 90)], (x) => x.categoryId); assert.deepEqual(ch.up, [{ id: "fun", now: 300, before: 100, delta: 200 }]); assert.deepEqual(ch.down, [{ id: "food", now: 20, before: 90, delta: -70 }]); + +// Months that start on payday: salary on 24 Sep and 23 Oct, so "October" is 24 Sep to 22 Oct. +const pays = [{ month: "2026-10-01", start: "2026-09-24" }, { month: "2026-11-01", start: "2026-10-23" }]; +const pm = { of: (d: string) => monthOf(pays, d), range: (ym: string) => rangeOf(pays, ym) }; +assert.equal(periodKey("2026-10-23", "month", pm), "2026-11"); +assert.deepEqual(periods("2026-09-24", "2026-11-03", "month", pm).map((p) => [p.key, p.from, p.to]), [["2026-10", "2026-09-24", "2026-10-22"], ["2026-11", "2026-10-23", "2026-11-22"]]); +const flowPm = cashFlow([r("2026-10-22", 10), r("2026-10-23", 7)], periods("2026-09-24", "2026-11-03", "month", pm), "month", pm); +assert.deepEqual(flowPm.map((f) => f.spend), [10, 7], "the 23rd is already November"); +const mtdPm = monthToDate([r("2026-10-23", 5), r("2026-10-25", 2), r("2026-09-24", 4)], "2026-10-25", pm); +assert.equal(mtdPm.thisMonth, "2026-11"); +assert.equal(mtdPm.start, "2026-10-23"); +assert.deepEqual(mtdPm.current, [5, 5, 7], "day 1 is payday"); +assert.equal(mtdPm.last[0], 4); console.log("charts ok"); diff --git a/src/lib/charts.ts b/src/lib/charts.ts index 2cfc15e..c15c67c 100644 --- a/src/lib/charts.ts +++ b/src/lib/charts.ts @@ -13,6 +13,9 @@ export type Row = { accountId: string | null; }; export type Period = { key: string; label: string; from: string; to: string }; +/** Months that start on payday (lib/paymonths.ts): the month ("YYYY-MM") a day is in, and a month's first day and the + * day after its last. Null: calendar months. Only grouping by month changes. */ +export type Months = { of: (d: string) => string; range: (ym: string) => { start: string; end: string } } | null; const DAY = 864e5; const iso = (t: number) => new Date(t).toISOString().slice(0, 10); @@ -21,23 +24,24 @@ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", " const round2 = (n: number) => Math.round(n * 100) / 100; /** The period a day falls in: the day itself, the Monday of its week, or its month. */ -export function periodKey(d: string, g: Group) { +export function periodKey(d: string, g: Group, pm: Months = null) { if (g === "day") return d; - if (g === "month") return d.slice(0, 7); + if (g === "month") return pm ? pm.of(d) : d.slice(0, 7); const t = at(d), wd = (new Date(t).getUTCDay() + 6) % 7; // Monday = 0 return iso(t - wd * DAY); } /** Every period from `from` to `to` (inclusive), so empty ones still show as zero. */ -export function periods(from: string, to: string, g: Group): Period[] { +export function periods(from: string, to: string, g: Group, pm: Months = null): Period[] { const out: Period[] = []; - let key = periodKey(from, g); - const last = periodKey(to, g); + let key = periodKey(from, g, pm); + const last = periodKey(to, g, pm); for (let guard = 0; key <= last && guard < 4000; guard++) { if (g === "month") { const [y, m] = key.split("-").map(Number); const next = m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, "0")}`; - out.push({ key, label: `${MONTHS[m - 1]}${m === 1 || !out.length ? ` '${String(y).slice(2)}` : ""}`, from: `${key}-01`, to: iso(at(`${next}-01`) - DAY) }); + const r = pm ? pm.range(key) : { start: `${key}-01`, end: `${next}-01` }; + out.push({ key, label: `${MONTHS[m - 1]}${m === 1 || !out.length ? ` '${String(y).slice(2)}` : ""}`, from: r.start, to: iso(at(r.end) - DAY) }); key = next; } else { const span = g === "day" ? 1 : 7, d = new Date(at(key)); @@ -55,10 +59,10 @@ export function previousRange(from: string, to: string) { } export type Flow = { key: string; income: number; spend: number; net: number }; -export function cashFlow(rows: Row[], ps: Period[], g: Group): Flow[] { +export function cashFlow(rows: Row[], ps: Period[], g: Group, pm: Months = null): Flow[] { const by = new Map(ps.map((p) => [p.key, { key: p.key, income: 0, spend: 0, net: 0 }])); for (const r of rows) { - const f = by.get(periodKey(r.date, g)); + const f = by.get(periodKey(r.date, g, pm)); if (!f) continue; if (r.spend) f.spend += r.amount; else if (r.income) f.income -= r.amount; // money in is negative in the app's sign @@ -70,11 +74,11 @@ export function cashFlow(rows: Row[], ps: Period[], g: Group): Flow[] { export const savingsRate = (flows: Flow[]) => flows.map((f) => ({ key: f.key, rate: f.income > 0 ? Math.round(((f.income - f.spend) / f.income) * 1000) / 10 : null })); /** Spending per period per category: the `keep` categories by name, everything else summed as "other". */ -export function categoriesOver(rows: Row[], ps: Period[], g: Group, keep: string[]) { +export function categoriesOver(rows: Row[], ps: Period[], g: Group, keep: string[], pm: Months = null) { const by = new Map(ps.map((p) => [p.key, Object.fromEntries([...keep, "other"].map((k) => [k, 0])) as Record])); for (const r of rows) { if (!r.spend) continue; - const b = by.get(periodKey(r.date, g)); + const b = by.get(periodKey(r.date, g, pm)); if (!b) continue; const k = r.categoryId && keep.includes(r.categoryId) ? r.categoryId : "other"; b[k] = round2(b[k] + r.amount); @@ -92,26 +96,37 @@ export function rankBySpend(rows: Row[], of: (r: Row) => string | null) { return [...sum.entries()].sort((a, b) => b[1] - a[1]).map(([k]) => k); } -/** Running total of spending day by day through a month, for this month, last month and the average of the three before. */ -export function monthToDate(rows: Row[], today: string) { +/** Running total of spending day by day through a month, for this month, last month and the average of the three before. + * With pay months, day 1 is payday and a month is as long as its pay month. */ +export function monthToDate(rows: Row[], today: string, pm: Months = null) { + const cur = pm ? pm.of(today) : today.slice(0, 7); const month = (offset: number) => { - const [y, m] = today.slice(0, 7).split("-").map(Number); - const d = new Date(Date.UTC(y, m - 1 + offset, 1)); - return iso(d.getTime()).slice(0, 7); + const [y, m] = cur.split("-").map(Number); + return iso(Date.UTC(y, m - 1 + offset, 1)).slice(0, 7); + }; + const span = (key: string) => pm!.range(key); // only with pay months + const days = (key: string) => { + if (!pm) return new Date(Date.UTC(Number(key.slice(0, 4)), Number(key.slice(5, 7)), 0)).getUTCDate(); + const r = span(key); + return Math.round((at(r.end) - at(r.start)) / DAY); }; - const days = (key: string) => new Date(Date.UTC(Number(key.slice(0, 4)), Number(key.slice(5, 7)), 0)).getUTCDate(); const daily = (key: string) => { const out = new Array(days(key)).fill(0) as number[]; - for (const r of rows) if (r.spend && r.date.startsWith(key)) out[Number(r.date.slice(8, 10)) - 1] += r.amount; + const start = pm ? at(span(key).start) : 0; + for (const r of rows) { + if (!r.spend) continue; + const i = pm ? Math.round((at(r.date) - start) / DAY) : r.date.startsWith(key) ? Number(r.date.slice(8, 10)) - 1 : -1; + if (i >= 0 && i < out.length) out[i] += r.amount; + } let run = 0; return out.map((v) => (run = round2(run + v))); }; const thisKey = month(0), lastKey = month(-1); - const upTo = Number(today.slice(8, 10)); + const upTo = pm ? Math.round((at(today) - at(span(thisKey).start)) / DAY) + 1 : Number(today.slice(8, 10)); const avgOf = [month(-1), month(-2), month(-3)].map(daily); - const avg = Array.from({ length: 31 }, (_, i) => round2(avgOf.reduce((s, m) => s + (m[Math.min(i, m.length - 1)] ?? 0), 0) / avgOf.length)); + const avg = Array.from({ length: 40 }, (_, i) => round2(avgOf.reduce((s, m) => s + (m[Math.min(i, m.length - 1)] ?? 0), 0) / avgOf.length)); return { - thisMonth: thisKey, lastMonth: lastKey, + thisMonth: thisKey, lastMonth: lastKey, start: pm ? span(thisKey).start : `${thisKey}-01`, current: daily(thisKey).slice(0, upTo), last: daily(lastKey), average: avg.slice(0, days(thisKey)), @@ -121,10 +136,10 @@ export function monthToDate(rows: Row[], today: string) { export type Balance = { id: string; name: string; balance: number; owed: boolean }; /** Each account's balance at the end of every day in [from, to], worked back from today's balance: a day's balance is * today's plus what went out since (minus what came in). A card or loan counts what's owed; the total subtracts it. */ -export function balances(accounts: Balance[], rows: Row[], from: string, to: string, step: Group) { +export function balances(accounts: Balance[], rows: Row[], from: string, to: string, step: Group, pm: Months = null) { const ds: string[] = []; for (let t = at(from); t <= at(to); t += DAY) ds.push(iso(t)); - const marks = step === "day" ? ds : ds.filter((d, i) => i === ds.length - 1 || periodKey(ds[i + 1], step) !== periodKey(d, step)); // last day of each period + const marks = step === "day" ? ds : ds.filter((d, i) => i === ds.length - 1 || periodKey(ds[i + 1], step, pm) !== periodKey(d, step, pm)); // last day of each period const series = accounts.map((a) => { const mine = rows.filter((r) => r.accountId === a.id).sort((x, y) => y.date.localeCompare(x.date)); let i = 0, after = 0; // sum of amounts dated after the mark @@ -147,11 +162,11 @@ export function byWeekday(rows: Row[], from: string, to: string) { } /** Spending per period for each of the given merchants. */ -export function merchantsOver(rows: Row[], ps: Period[], g: Group, names: string[]) { +export function merchantsOver(rows: Row[], ps: Period[], g: Group, names: string[], pm: Months = null) { const by = new Map(names.map((n) => [n, new Map(ps.map((p) => [p.key, 0]))])); for (const r of rows) { const m = r.spend ? by.get(r.merchant) : undefined; - const k = periodKey(r.date, g); + const k = periodKey(r.date, g, pm); if (m?.has(k)) m.set(k, round2(m.get(k)! + r.amount)); } return names.map((n) => ({ name: n, values: ps.map((p) => by.get(n)!.get(p.key)!) })); diff --git a/src/lib/checkins.ts b/src/lib/checkins.ts index b002571..61f20fb 100644 --- a/src/lib/checkins.ts +++ b/src/lib/checkins.ts @@ -53,6 +53,7 @@ const same = (a: string, b: string) => a.toLowerCase().includes(b.toLowerCase()) export function checkinFacts(o: { txns: CheckinTxn[]; streams: CheckinStream[]; cash: number | null; available?: number | null; spendable?: number | null; spendableIn?: string; income?: number | null; today: string; usualSpend?: number | null; budgets?: { category: string; amount: number }[]; prev?: CheckinFacts | null; move?: CheckinFacts["move"]; + span?: { start: string; end: string }; // with pay months on: this month's first day and the day after its last (lib/paymonths.ts) }): CheckinFacts { const weekAgo = shift(o.today, -7); const unusual: CheckinFacts["unusual"] = []; @@ -91,7 +92,7 @@ export function checkinFacts(o: { const upcomingTotal = r2(upcoming.reduce((s, u) => s + u.amount, 0)); const sum = (xs: CheckinTxn[]) => r2(xs.reduce((s, t) => s + t.amount, 0)); - const month = o.txns.filter((t) => t.date >= o.today.slice(0, 8) + "01"); + const month = o.txns.filter((t) => t.date >= (o.span?.start ?? o.today.slice(0, 8) + "01")); const monthSpend = sum(month); const byCat = new Map(); for (const t of month) byCat.set(t.category ?? "Other", (byCat.get(t.category ?? "Other") ?? 0) + t.amount); @@ -119,10 +120,10 @@ const monthEnd = (today: string) => today.slice(0, 8) + String(new Date(Date.UTC function reviewOf(o: Parameters[0] & { weekSpend: number; monthSpend: number; month: CheckinTxn[]; bills: CheckinStream[]; newSubs: CheckinFacts["newSubs"]; priceUps: CheckinFacts["priceUps"]; }) { - const end = monthEnd(o.today), daysLeft = Number(end.slice(8)) - Number(o.today.slice(8)); + const end = o.span ? shift(o.span.end, -1) : monthEnd(o.today), daysLeft = Math.round((Date.parse(end) - Date.parse(o.today)) / DAY); const subs = [...new Set(o.bills.map((s) => s.merchant_name))].sort(); const prev = o.prev?.subs ? o.prev : null; - const left = leftThisMonth({ income: o.income ?? null, spend: o.usualSpend ?? null, streams: o.streams, spent: o.monthSpend, today: o.today }); + const left = leftThisMonth({ income: o.income ?? null, spend: o.usualSpend ?? null, streams: o.streams, spent: o.monthSpend, today: o.today, span: o.span }); const byCat = (c: string) => r2(o.month.filter((t) => (t.category ?? "Other") === c).reduce((s, t) => s + t.amount, 0)); const budgets = (o.budgets ?? []).filter((b) => b.amount > 0).map((b) => ({ category: b.category, budget: b.amount, spent: byCat(b.category) })); @@ -144,7 +145,7 @@ function reviewOf(o: Parameters[0] & { // A budget tip from last month has nothing to check against in a new month. const checks: Check[] = (prev?.tips ?? []).flatMap((t): Check[] => { if (t.kind === "pace") return [{ tip: t, now: o.weekSpend, ok: o.weekSpend <= t.amount }]; - if (t.kind === "budget") return t.by.slice(0, 7) === o.today.slice(0, 7) ? [{ tip: t, now: byCat(t.key), ok: byCat(t.key) <= t.amount }] : []; + if (t.kind === "budget") return (o.span ? t.by >= o.span.start : t.by.slice(0, 7) === o.today.slice(0, 7)) ? [{ tip: t, now: byCat(t.key), ok: byCat(t.key) <= t.amount }] : []; if (t.kind === "hike") { const now = o.streams.find((s) => s.merchant_name === t.key)?.last_amount ?? t.last ?? 0; return [{ tip: t, now, ok: now <= t.amount * 1.05 }]; } const charged = o.txns.filter((x) => x.date > t.on && same(x.merchant, t.key)).reduce((s, x) => s + x.amount, 0); return [{ tip: t, now: r2(charged), ok: charged === 0 }]; diff --git a/src/lib/data.ts b/src/lib/data.ts index a2035c7..caa1615 100644 --- a/src/lib/data.ts +++ b/src/lib/data.ts @@ -128,6 +128,14 @@ export async function payMonthToday(supabase: SupabaseClient, userId: string, to const m = data?.[0]?.month as string | undefined; return m && m.slice(0, 7) !== today.slice(0, 7) ? m : today; } +/** With pay months on, the pay month today is in: its first day and the day after its last (a guess while it runs). + * Undefined with calendar months. Reads the stored months, so it works outside a page request too. */ +export async function paySpan(supabase: SupabaseClient, userId: string, today: string) { + const { data } = await supabase.from("pay_periods").select("month, start_date").eq("user_id", userId).order("start_date"); + const ps = ((data ?? []) as { month: string; start_date: string }[]).map((p): Period => ({ month: p.month, start: p.start_date })); + if (!ps.length || ps[0].start > today) return undefined; + return rangeOf(ps, monthOf(ps, 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. diff --git a/src/lib/insights.test.ts b/src/lib/insights.test.ts index 9e20b5e..07ebcec 100644 --- a/src/lib/insights.test.ts +++ b/src/lib/insights.test.ts @@ -113,6 +113,12 @@ assert.equal(Math.round(left.left), Math.round(5200 - 1820 - 2100 - pace * 8)); assert.equal(leftThisMonth({ income: null, spend: 4000, streams: lm, spent: 2100, today: "2026-10-23" }), null, "no income: no guess"); assert.equal(leftThisMonth({ income: 3000, spend: 4000, streams: [], spent: 2900, today: "2026-10-31" })!.left, 100, "last day: nothing more at the usual pace"); assert.ok(leftThisMonth({ income: 2000, spend: 4000, streams: lm, spent: 2100, today: "2026-10-23" })!.left < 0, "negative when spending runs past income"); +// Pay months: Oct 23 is payday, the month runs to Nov 22 (31 days, 30 left after today). Gym lands Oct 24, 31, Nov 7, 14, 21. +const span = { start: "2026-10-23", end: "2026-11-23" }; +assert.deepEqual(billsDueThisMonth(lm, "2026-10-23", span).map((b) => b.date), ["2026-10-24", "2026-10-25", "2026-10-31", "2026-11-07", "2026-11-14", "2026-11-21"]); +const leftPm = leftThisMonth({ income: 5200, spend: 4000, streams: lm, spent: 0, today: "2026-10-23", span })!; +assert.equal(leftPm.due, 1850); +assert.equal(Math.round(leftPm.rest), Math.round(pace * 30)); console.log("insights ok"); diff --git a/src/lib/insights.ts b/src/lib/insights.ts index a958f7d..9e26a77 100644 --- a/src/lib/insights.ts +++ b/src/lib/insights.ts @@ -75,9 +75,13 @@ export function safeToSpend(accts: Acct[], streams: Stream[], today: string) { } // Bills still due from today to the last day of the month. A weekly or every-two-weeks bill counts each time it lands. +// span: a pay month's first day and the day after its last (lib/paymonths.ts), else the calendar month. const STEP_DAYS: Record = { WEEKLY: 7, BIWEEKLY: 14, SEMI_MONTHLY: 15 }; -export function billsDueThisMonth(streams: Stream[], today: string) { - const end = today.slice(0, 8) + String(new Date(Date.UTC(+today.slice(0, 4), +today.slice(5, 7), 0)).getUTCDate()).padStart(2, "0"); +export type Span = { start: string; end: string }; +const lastDayOf = (today: string, span?: Span) => + span ? addDays(span.end, -1) : today.slice(0, 8) + String(new Date(Date.UTC(+today.slice(0, 4), +today.slice(5, 7), 0)).getUTCDate()).padStart(2, "0"); +export function billsDueThisMonth(streams: Stream[], today: string, span?: Span) { + const end = lastDayOf(today, span); const out: { name: string; date: string; amount: number }[] = []; for (const s of streams.filter((s) => !s.is_income && s.next_date && s.next_date >= today)) for (let d = s.next_date!; d <= end; d = addDays(d, STEP_DAYS[s.frequency] ?? 99)) out.push({ name: s.merchant_name, date: d, amount: Number(s.average_amount) }); @@ -88,12 +92,14 @@ export function billsDueThisMonth(streams: Stream[], today: string) { // minus the rest of the month at the usual pace. The usual pace is a typical month's spending without its recurring // bills (they are counted on their own dates), spread over the days left after today. // Null with no typical income: broke doesn't guess one. -export function leftThisMonth(o: { income: number | null; spend: number | null; streams: Stream[]; spent: number; today: string }) { +export function leftThisMonth(o: { income: number | null; spend: number | null; streams: Stream[]; spent: number; today: string; span?: Span }) { if (!o.income || o.income <= 0) return null; - const days = new Date(Date.UTC(+o.today.slice(0, 4), +o.today.slice(5, 7), 0)).getUTCDate(); - const due = sum(billsDueThisMonth(o.streams, o.today).map((b) => b.amount)); + const at = (d: string) => Date.parse(`${d}T00:00:00Z`); + const days = o.span ? Math.round((at(o.span.end) - at(o.span.start)) / 864e5) : new Date(Date.UTC(+o.today.slice(0, 4), +o.today.slice(5, 7), 0)).getUTCDate(); + const day = o.span ? Math.round((at(o.today) - at(o.span.start)) / 864e5) + 1 : +o.today.slice(8, 10); + const due = sum(billsDueThisMonth(o.streams, o.today, o.span).map((b) => b.amount)); const monthlyBills = sum(o.streams.filter((s) => !s.is_income).map((s) => (Number(s.average_amount) * (PER_YEAR[s.frequency] ?? 12)) / 12)); - const rest = (Math.max(0, (o.spend ?? 0) - monthlyBills) / days) * (days - +o.today.slice(8, 10)); + const rest = (Math.max(0, (o.spend ?? 0) - monthlyBills) / days) * Math.max(0, days - day); return { income: o.income, due, spent: o.spent, rest, left: o.income - due - o.spent - rest }; }