Pay months on Charts, left this month, check-ins and onboarding

With months that start on payday, Charts groups by pay month (presets,
savings rate and month to date included, day 1 being payday). Left this
month counts bills and the usual pace up to the day before the next
salary. Check-ins read this month, budget tips and the weekly cap from
the pay month, and onboarding looks at full pay months.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
MangaValkandClaude Opus 5.5 committed 2026-11-22 18:06:51 +01:00
1 parent 9d42d52e4d
commit 943b19d743
10 files changed
+112 -55

No files matched your search

+17 -14
View File
@@ -1,8 +1,8 @@
import { ChartFilters } from "@/components/charts/ChartFilters"; import { ChartFilters } from "@/components/charts/ChartFilters";
import { ChartsView, type ChartsData } from "@/components/charts/ChartsView"; import { ChartsView, type ChartsData } from "@/components/charts/ChartsView";
import { EmptyBank } from "@/components/EmptyBank"; 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 { 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, today, transactionsSince } from "@/lib/data"; import { accountName, allTags, categories, displayName, getUser, isIncome, isSpend, months, today, transactionsSince } from "@/lib/data";
import { ymd } from "@/lib/format"; 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 // 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<S
const sp = await searchParams; const sp = await searchParams;
const { supabase, user } = await getUser(); const { supabase, user } = await getUser();
const now = ymd(await today()); const now = ymd(await today());
// Months that start on payday (profile.month): grouping by month, month presets and month to date follow them.
const mo = await months();
const pm: Months = mo.payday ? { of: mo.of, range: mo.range } : null;
const [txns, cats, tags, { data: accts }] = await Promise.all([ const [txns, cats, tags, { data: accts }] = await Promise.all([
transactionsSince("1900-01-01"), transactionsSince("1900-01-01"),
categories(), categories(),
@@ -39,7 +42,7 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
// Time range: a preset, or custom dates (either end open). // Time range: a preset, or custom dates (either end open).
const range = sp.range ?? "12m"; const range = sp.range ?? "12m";
const monthsBack = (n: number) => { 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 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 from = DAY.test(sp.from ?? "") ? sp.from! : DAY.test(sp.to ?? "") ? first : preset;
const to = DAY.test(sp.to ?? "") ? sp.to! : now; const to = DAY.test(sp.to ?? "") ? sp.to! : now;
@@ -57,14 +60,14 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
.filter((r) => !q || r.text.includes(q) || r.merchant.toLowerCase().includes(q)) .filter((r) => !q || r.text.includes(q) || r.merchant.toLowerCase().includes(q))
.map((r) => (dir === "out" ? { ...r, income: false } : dir === "in" ? { ...r, spend: false } : r)); .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 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 rows = within(from, to);
const compare = sp.cmp === "1"; const compare = sp.cmp === "1";
const prev = previousRange(from, to); const prev = previousRange(from, to);
const before = within(prev.from, prev.to); const before = within(prev.from, prev.to);
// The period before, lined up period by period with this one (same length, same grouping). // 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 psBefore = periods(prev.from, prev.to, group, pm).slice(-ps.length);
const flowBefore = compare ? cashFlow(before, psBefore, group) : null; const flowBefore = compare ? cashFlow(before, psBefore, group, pm) : null;
const pad = <T,>(xs: T[] | null) => (xs ? [...Array(Math.max(0, ps.length - xs.length)).fill(null), ...xs] : null); const pad = <T,>(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. // 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<S
const accounts = (accts ?? []).filter((a) => a.included !== false && ["depository", "credit", "loan"].includes(a.type) && (!acct.length || acct.includes(a.id))); const accounts = (accts ?? []).filter((a) => a.included !== false && ["depository", "credit", "loan"].includes(a.type) && (!acct.length || acct.includes(a.id)));
const bal = balances( 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" })), 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 flow = cashFlow(rows, ps, group, pm);
const psMonth = periods(from, to, "month"); const psMonth = periods(from, to, "month", pm);
const ch = biggestChanges(rows, before, (r) => r.categoryId); const ch = biggestChanges(rows, before, (r) => r.categoryId);
const data: ChartsData = { const data: ChartsData = {
@@ -93,14 +96,14 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
flow, flow,
flowBefore: flowBefore ? (pad(flowBefore) as ChartsData["flow"]).map((f, i) => f ?? { key: ps[i].key, income: 0, spend: 0, net: 0 }) : null, flowBefore: flowBefore ? (pad(flowBefore) as ChartsData["flow"]).map((f, i) => 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%. // 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) }, rate: { periods: psMonth, values: savingsRate(cashFlow(rows, psMonth, "month", pm)).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, 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).map((c) => c.values) }, 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), mtd: monthToDate(filtered, now, pm),
balance: { ...bal, series: bal.series.map((s, i) => ({ ...s, slot: (i % 8) + 1 })) }, balance: { ...bal, series: bal.series.map((s, i) => ({ ...s, slot: (i % 8) + 1 })) },
weekday: byWeekday(rows, from, to), weekday: byWeekday(rows, from, to),
weekdayBefore: compare ? byWeekday(before, prev.from, prev.to) : null, 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: { 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" })) }, 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), merchants: biggestChanges(rows, before, (r) => r.merchant),
+3 -1
View File
@@ -1,7 +1,7 @@
import { mkdirSync, writeFileSync } from "node:fs"; import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
import { changeLines, checkinFacts, sameDollars, type CheckinFacts } from "@/lib/checkins"; 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 { runViaHelper } from "@/lib/llm/helper";
import { runCodex, runGemini, runOpencode } from "@/lib/llm/cli-snapshot"; import { runCodex, runGemini, runOpencode } from "@/lib/llm/cli-snapshot";
import { AGENT_DIR, runClaudeCode } from "@/lib/llm/claude-code"; 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(), 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), 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. // 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 }; 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[]; 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, 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, move: pick ? { title: pick.title, line: whyLine(pick.title, pick.why), done: pick === justDone, by: pick.deadline ?? addDays(today, 7) } : null,
today, today,
span,
}); });
// Off: no model call, the card shows the plain facts. Summary: placeholders and rounded amounts, names swapped back below. // Off: no model call, the card shows the plain facts. Summary: placeholders and rounded amounts, names swapped back below.
+6 -4
View File
@@ -1,5 +1,5 @@
import { NextResponse } from "next/server"; 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 { firstFact } from "@/lib/first-fact";
import { dateLabel, FREQ_PER_MONTH, money0, monthStart, ymd } from "@/lib/format"; import { dateLabel, FREQ_PER_MONTH, money0, monthStart, ymd } from "@/lib/format";
import { typicalMonth } from "@/lib/insights"; import { typicalMonth } from "@/lib/insights";
@@ -17,13 +17,15 @@ export async function GET() {
const now = await userToday(); const now = await userToday();
const today = ymd(now); const today = ymd(now);
const since90 = ymd(new Date(now.getTime() - 90 * 864e5)); 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([ 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("plaid_items").select("id, last_synced_at").eq("user_id", uid),
supabase.from("accounts").select("id, type, manual").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("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("categories").select("id, label"),
supabase.from("transactions").select("date").eq("user_id", uid).order("date").limit(1), 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. // 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) 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)), .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" }); 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. // 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 covered = [1, 2, 3].map(ym).filter((m) => `${m}-01` >= oldest);
const spentIn = (m: string) => { const spentIn = (m: string) => {
const by = new Map<string, number>(); const by = new Map<string, number>();
@@ -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 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)); 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 }); return NextResponse.json({ ...base, status: fact ? "ready" : "thin", fact });
+2 -2
View File
@@ -20,7 +20,7 @@ export type ChartsData = {
rate: { periods: Period[]; values: (number | null)[] }; rate: { periods: Period[]; values: (number | null)[] };
rateBefore: (number | null)[] | null; rateBefore: (number | null)[] | null;
cats: { order: { id: string; label: string; slot: number }[]; values: Record<string, number>[] }; cats: { order: { id: string; label: string; slot: number }[]; values: Record<string, number>[] };
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[] }; balance: { days: string[]; series: { id: string; name: string; owed: boolean; slot: number; values: number[] }[]; total: number[] };
weekday: number[]; weekday: number[];
weekdayBefore: number[] | null; weekdayBefore: number[] | null;
@@ -99,7 +99,7 @@ export function ChartsView({ d }: { d: ChartsData }) {
<Card title="This month so far" note={`Spending added up day by day: ${monthName(d.mtd.thisMonth)} against ${monthName(d.mtd.lastMonth)} and the average of the 3 months before.`} <Card title="This month so far" note={`Spending added up day by day: ${monthName(d.mtd.thisMonth)} against ${monthName(d.mtd.lastMonth)} and the average of the 3 months before.`}
legend={[{ name: "This month", color: "var(--chart)" }, { name: "Last month", color: "var(--muted)", dashed: true }, { name: "3-month average", color: "var(--series-other)" }]} legend={[{ name: "This month", color: "var(--chart)" }, { name: "Last month", color: "var(--muted)", dashed: true }, { name: "3-month average", color: "var(--series-other)" }]}
table={{ head: ["Day", "This month", "Last month", "Average"], rows: mtdDays.map((l, i) => [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])]) }}> table={{ head: ["Day", "This month", "Last month", "Average"], rows: mtdDays.map((l, i) => [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])]) }}>
<Lines labels={mtdDays} fmt={money0} hrefs={(i) => activity({ from: `${d.mtd.thisMonth}-01`, to: `${d.mtd.thisMonth}-${String(i + 1).padStart(2, "0")}` })} series={[ <Lines labels={mtdDays} fmt={money0} hrefs={(i) => 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: "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: "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 }, { name: "This month", color: "var(--chart)", values: mtdDays.map((_, i) => d.mtd.current[i] ?? null), width: 2.5 },
+14
View File
@@ -1,5 +1,6 @@
// node src/lib/charts.test.ts // node src/lib/charts.test.ts
import assert from "node:assert/strict"; 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"; 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> = {}): Row => ({ const r = (date: string, amount: number, extra: Partial<Row> = {}): 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); 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.up, [{ id: "fun", now: 300, before: 100, delta: 200 }]);
assert.deepEqual(ch.down, [{ id: "food", now: 20, before: 90, delta: -70 }]); 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"); console.log("charts ok");
+39 -24
View File
@@ -13,6 +13,9 @@ export type Row = {
accountId: string | null; accountId: string | null;
}; };
export type Period = { key: string; label: string; from: string; to: string }; 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 DAY = 864e5;
const iso = (t: number) => new Date(t).toISOString().slice(0, 10); 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; 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. */ /** 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 === "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 const t = at(d), wd = (new Date(t).getUTCDay() + 6) % 7; // Monday = 0
return iso(t - wd * DAY); return iso(t - wd * DAY);
} }
/** Every period from `from` to `to` (inclusive), so empty ones still show as zero. */ /** 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[] = []; const out: Period[] = [];
let key = periodKey(from, g); let key = periodKey(from, g, pm);
const last = periodKey(to, g); const last = periodKey(to, g, pm);
for (let guard = 0; key <= last && guard < 4000; guard++) { for (let guard = 0; key <= last && guard < 4000; guard++) {
if (g === "month") { if (g === "month") {
const [y, m] = key.split("-").map(Number); const [y, m] = key.split("-").map(Number);
const next = m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, "0")}`; 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; key = next;
} else { } else {
const span = g === "day" ? 1 : 7, d = new Date(at(key)); 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 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 }])); const by = new Map(ps.map((p) => [p.key, { key: p.key, income: 0, spend: 0, net: 0 }]));
for (const r of rows) { 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 (!f) continue;
if (r.spend) f.spend += r.amount; if (r.spend) f.spend += r.amount;
else if (r.income) f.income -= r.amount; // money in is negative in the app's sign 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 })); 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". */ /** 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<string, number>])); const by = new Map(ps.map((p) => [p.key, Object.fromEntries([...keep, "other"].map((k) => [k, 0])) as Record<string, number>]));
for (const r of rows) { for (const r of rows) {
if (!r.spend) continue; if (!r.spend) continue;
const b = by.get(periodKey(r.date, g)); const b = by.get(periodKey(r.date, g, pm));
if (!b) continue; if (!b) continue;
const k = r.categoryId && keep.includes(r.categoryId) ? r.categoryId : "other"; const k = r.categoryId && keep.includes(r.categoryId) ? r.categoryId : "other";
b[k] = round2(b[k] + r.amount); 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); 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. */ /** 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) { * 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 month = (offset: number) => {
const [y, m] = today.slice(0, 7).split("-").map(Number); const [y, m] = cur.split("-").map(Number);
const d = new Date(Date.UTC(y, m - 1 + offset, 1)); return iso(Date.UTC(y, m - 1 + offset, 1)).slice(0, 7);
return iso(d.getTime()).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 daily = (key: string) => {
const out = new Array(days(key)).fill(0) as number[]; 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; let run = 0;
return out.map((v) => (run = round2(run + v))); return out.map((v) => (run = round2(run + v)));
}; };
const thisKey = month(0), lastKey = month(-1); 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 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 { return {
thisMonth: thisKey, lastMonth: lastKey, thisMonth: thisKey, lastMonth: lastKey, start: pm ? span(thisKey).start : `${thisKey}-01`,
current: daily(thisKey).slice(0, upTo), current: daily(thisKey).slice(0, upTo),
last: daily(lastKey), last: daily(lastKey),
average: avg.slice(0, days(thisKey)), 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 }; 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 /** 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. */ * 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[] = []; const ds: string[] = [];
for (let t = at(from); t <= at(to); t += DAY) ds.push(iso(t)); 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 series = accounts.map((a) => {
const mine = rows.filter((r) => r.accountId === a.id).sort((x, y) => y.date.localeCompare(x.date)); 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 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. */ /** 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]))])); const by = new Map(names.map((n) => [n, new Map(ps.map((p) => [p.key, 0]))]));
for (const r of rows) { for (const r of rows) {
const m = r.spend ? by.get(r.merchant) : undefined; 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)); 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)!) })); return names.map((n) => ({ name: n, values: ps.map((p) => by.get(n)!.get(p.key)!) }));
+5 -4
View File
@@ -53,6 +53,7 @@ const same = (a: string, b: string) => a.toLowerCase().includes(b.toLowerCase())
export function checkinFacts(o: { export function checkinFacts(o: {
txns: CheckinTxn[]; streams: CheckinStream[]; cash: number | null; available?: number | null; spendable?: number | null; spendableIn?: string; income?: number | null; today: string; 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"]; 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 { }): CheckinFacts {
const weekAgo = shift(o.today, -7); const weekAgo = shift(o.today, -7);
const unusual: CheckinFacts["unusual"] = []; const unusual: CheckinFacts["unusual"] = [];
@@ -91,7 +92,7 @@ export function checkinFacts(o: {
const upcomingTotal = r2(upcoming.reduce((s, u) => s + u.amount, 0)); 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 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 monthSpend = sum(month);
const byCat = new Map<string, number>(); const byCat = new Map<string, number>();
for (const t of month) byCat.set(t.category ?? "Other", (byCat.get(t.category ?? "Other") ?? 0) + t.amount); 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<typeof checkinFacts>[0] & { function reviewOf(o: Parameters<typeof checkinFacts>[0] & {
weekSpend: number; monthSpend: number; month: CheckinTxn[]; bills: CheckinStream[]; newSubs: CheckinFacts["newSubs"]; priceUps: CheckinFacts["priceUps"]; 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 subs = [...new Set(o.bills.map((s) => s.merchant_name))].sort();
const prev = o.prev?.subs ? o.prev : null; 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 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) })); 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<typeof checkinFacts>[0] & {
// A budget tip from last month has nothing to check against in a new month. // A budget tip from last month has nothing to check against in a new month.
const checks: Check[] = (prev?.tips ?? []).flatMap((t): Check[] => { 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 === "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 }]; } 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); 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 }]; return [{ tip: t, now: r2(charged), ok: charged === 0 }];
+8
View File
@@ -128,6 +128,14 @@ export async function payMonthToday(supabase: SupabaseClient, userId: string, to
const m = data?.[0]?.month as string | undefined; const m = data?.[0]?.month as string | undefined;
return m && m.slice(0, 7) !== today.slice(0, 7) ? m : today; 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), // 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.
+6
View File
@@ -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: 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.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"); 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"); console.log("insights ok");
+12 -6
View File
@@ -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. // 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<string, number> = { WEEKLY: 7, BIWEEKLY: 14, SEMI_MONTHLY: 15 }; const STEP_DAYS: Record<string, number> = { WEEKLY: 7, BIWEEKLY: 14, SEMI_MONTHLY: 15 };
export function billsDueThisMonth(streams: Stream[], today: string) { export type Span = { start: string; end: 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"); 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 }[] = []; 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 (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) }); 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 // 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. // 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. // 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; 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 at = (d: string) => Date.parse(`${d}T00:00:00Z`);
const due = sum(billsDueThisMonth(o.streams, o.today).map((b) => b.amount)); 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 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 }; return { income: o.income, due, spent: o.spent, rest, left: o.income - due - o.spent - rest };
} }