Compare commits

..
7 Commits
Author SHA1 Message Date
MangaValkandClaude Opus 5.5 bda9265d70 Move "A month starts" to Settings, Profile
It sat in the money profile form on Optimize, where nobody looks for a
display setting. Now it's its own card in Settings, Profile, and saves
as soon as it's picked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:12:11 +01:00
MangaValkandClaude Opus 5.5 943b19d743 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>
2026-11-22 18:06:51 +01:00
MangaValkandClaude Opus 5.5 9d42d52e4d 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>
2026-11-22 18:02:23 +01:00
MangaValkandClaude Opus 5.5 1bdcc57c2f Keep accounts and history when a connection is removed
Removing a bank connection deleted its accounts and transactions through
the cascade, so a relink or "Remove this copy" could wipe years of
history and every edit. Now an account that another connection also has
folds into that one (older rows move, edits carry over), and any other
account stays as an account added by hand. Test banks still go entirely.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 16:04:27 +01:00
MangaValkandClaude Opus 5.5 fbdeea630a Bank feeds: sync no longer fails on long transaction ids
Enable Banking ids are about 150 characters, so looking up 500 of them in one
request made a URL the database gateway turned away. The error was ignored,
every row looked new, and inserting them failed on the saved ones (23505), so
the connection showed "Needs you to sign in again" and linking again failed too.

- saved rows are read by account and date range, in pages, and errors stop the sync
- a new row whose id is saved after all is skipped; the same id twice in one
  fetch is one row
- database errors keep their message in the log and on Accounts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:05:52 +01:00
MangaValkandClaude Opus 5.5 0d399b77c3 Remove the donation popup and the Support broke links
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:01:48 +01:00
MangaValkandClaude Opus 5.5 5ef800e618 Bank feeds: a row sent again under a new id updates the saved one
ING through Enable Banking gave every row a new transaction_id after linking
again, so the 14-day re-fetch saved all of it a second time.

- before inserting, a new-looking row is paired with a saved row of the same
  provider, account, day, amount and name whose id this fetch didn't return
- the saved row takes the new id and keeps its category, name and tags
- one saved row per new row, so two identical buys on a day stay two rows;
  visible rows are used before hidden ones

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:01:47 +01:00
35 changed files with 555 additions and 174 deletions

No files matched your search

+11 -8
View File
@@ -3,7 +3,7 @@ import { AskButton } from "@/components/Assistant";
import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor";
import { EmptyBank } from "@/components/EmptyBank";
import { budgetContext, median, monthList, suggest, type MonthSpend } from "@/lib/budget";
import { categories, getUser, isSpend, moneyByMonth, sumOf, today, transactionsSince, typicalMonthly } from "@/lib/data";
import { categories, getUser, isSpend, moneyByMonth, months, sumOf, today, transactionsSince, typicalMonthly } from "@/lib/data";
import { monthStart, ymd } from "@/lib/format";
// Budgets: tracked against this month with a pace marker. Suggestions come from the full months of data (up to 3, the
@@ -16,16 +16,19 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
const from = DAY.test(sp.from ?? "") ? sp.from! : "", to = DAY.test(sp.to ?? "") ? sp.to! : "";
const { supabase, user } = await getUser();
const now = await today();
const thisMonth = ymd(monthStart(now)).slice(0, 7);
const lastMonth = ymd(monthStart(now, -1)).slice(0, 7);
// Pay months on: this month is the pay month today is in (named after the calendar month it mostly covers).
const mo = await months();
const thisMonth = await mo.current();
const cur = new Date(`${thisMonth}-01T00:00:00Z`);
const lastMonth = ymd(monthStart(cur, -1)).slice(0, 7);
const [txns, cats, saved, typical] = await Promise.all([
moneyByMonth(supabase, ymd(monthStart(now, -Math.max(3, now.getUTCMonth())))), // own rows, totalled in SQL: 3 months, or back to January
moneyByMonth(supabase, ymd(monthStart(cur, -Math.max(3, cur.getUTCMonth())))), // own rows, totalled in SQL: 3 months, or back to January
categories(),
supabase.from("budgets").select("category_id, amount"),
typicalMonthly(supabase, user!.id, ymd(now)),
]);
const threeMonthsAgo = ymd(monthStart(now, -3)).slice(0, 7);
const threeMonthsAgo = ymd(monthStart(cur, -3)).slice(0, 7);
const past = txns.filter((r) => !r.month.startsWith(thisMonth) && r.month.slice(0, 7) >= threeMonthsAgo);
const monthsOfData = Math.max(1, new Set(past.map((r) => r.month.slice(0, 7))).size);
const sum = (catId: string, month?: string) =>
@@ -44,8 +47,8 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
return { id: c.id, label: c.label, icon: c.icon, color: c.color, spent, last: sum(c.id, lastMonth), avg, suggested: suggest(avg, spent), main: c.key !== "BANK_FEES" && Math.max(avg, spent) >= 10 };
});
// Each month of this year, spend by category, for the year view.
const year = String(now.getUTCFullYear());
const yearMonths: MonthSpend[] = Array.from({ length: now.getUTCMonth() + 1 }, (_, i) => {
const year = String(cur.getUTCFullYear());
const yearMonths: MonthSpend[] = Array.from({ length: cur.getUTCMonth() + 1 }, (_, i) => {
const month = `${year}-${String(i + 1).padStart(2, "0")}`;
const cats: Record<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;
@@ -65,7 +68,7 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
return (
// The key takes in saved changes from elsewhere (the AI's Apply) on refresh.
<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
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"
+17 -14
View File
@@ -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<S
const sp = await searchParams;
const { supabase, user } = await getUser();
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([
transactionsSince("1900-01-01"),
categories(),
@@ -39,7 +42,7 @@ export default async function Charts({ searchParams }: { searchParams: Promise<S
// Time range: a preset, or custom dates (either end open).
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 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<S
.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));
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 = <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.
@@ -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 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<S
flow,
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%.
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),
+1 -4
View File
@@ -1,12 +1,11 @@
import { ChevronRight, Sparkles } from "lucide-react";
import { DonateLink } from "@/components/Donate";
import Link from "next/link";
const PAGES = [
{ href: "/debt", label: "Debt", what: "What you owe, what you're paying and what it costs." },
];
// What isn't in the main menu: Debt, connecting your AI and supporting broke.
// What isn't in the main menu: Debt and connecting your AI.
export default function More() {
return (
<div className="max-w-2xl space-y-4">
@@ -23,8 +22,6 @@ export default function More() {
<span className="flex-1 font-medium">Connect your AI</span>
<ChevronRight size={18} className="text-muted shrink-0" />
</Link>
{/* The sidebar has this link too; on a phone, More is the only place. */}
<DonateLink className="card-link flex items-center gap-3 px-6 py-4 font-medium [&_svg]:text-muted" />
</div>
);
}
+7 -5
View File
@@ -11,8 +11,8 @@ import { PayQuestion } from "@/components/PayQuestion";
import { SyncButton } from "@/components/PlaidButtons";
import { TxnList } from "@/components/TxnList";
import { WeekCard } from "@/components/WeekCard";
import { categories, getUser, moneyByMonth, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
import { dateLabel, money0, monthStart, ymd } from "@/lib/format";
import { categories, getUser, moneyByMonth, months, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
import { dateLabel, money0, ymd } from "@/lib/format";
import { deterministicMoves, ladder } from "@/lib/plan";
import { myPlanFacts } from "@/lib/plan-facts";
import { payGuess } from "@/lib/pay";
@@ -66,6 +66,8 @@ export default async function Dashboard() {
const now = await today(); // the user's date at UTC midnight: read it with getUTC* and ymd
const day = ymd(now), soon = ymd(new Date(now.getTime() + 14 * 864e5));
const checks = (fetchChecks(supabase, uid, day) as Promise<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.
const [{ data: recent }, { data: accounts }, { data: noRate }, { data: bills }, rows, cats] = await Promise.all([
@@ -73,7 +75,7 @@ export default async function Dashboard() {
supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", uid),
supabase.rpc("fx_missing"),
supabase.from("recurring").select("id, merchant_name, logo_url, average_amount:home_average, next_date").eq("user_id", uid).eq("active", true).eq("is_income", false).neq("status", "TOMBSTONED").gte("next_date", day).lte("next_date", soon).order("next_date").limit(4),
moneyByMonth(supabase, ymd(monthStart(now))),
moneyByMonth(supabase, `${thisMonth}-01`),
categories(),
]);
@@ -93,8 +95,8 @@ export default async function Dashboard() {
{ label: "You owe", value: owed == null ? null : Math.abs(owed), href: "/debt" },
].filter((t) => t.value != null);
const pic = moneyPicture(rows, cats, ymd(monthStart(now)).slice(0, 7), null);
const monthName = dateLabel(day, { month: "long" });
const pic = moneyPicture(rows, cats, thisMonth, null);
const monthName = dateLabel(`${thisMonth}-01`, { month: "long" });
return (
<div className="space-y-4 max-w-4xl">
+22
View File
@@ -181,6 +181,27 @@ function Card({ title, what, s, children }: { title: string; what?: string; s?:
);
}
// When a month starts: on the 1st, or on payday (lib/paymonths.ts). Saved as soon as it's picked.
function MonthStart({ profile }: { profile: Profile }) {
const router = useRouter();
const [v, setV] = useState(profile.month === "payday" ? "payday" : "calendar");
const [msg, setMsg] = useState("");
async function pick(next: string) {
setV(next);
const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, month: next === "payday" ? "payday" : undefined } } });
setMsg(error ? "Couldn't save that. Try again." : "Saved.");
if (!error) router.refresh();
}
return (
<Card title="A month starts" what="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.">
<div className="max-w-sm">
<Dropdown label="A month starts" value={v} options={[{ value: "calendar", label: "On the 1st" }, { value: "payday", label: "On payday" }]} onChange={pick} placeholder="On the 1st" />
</div>
{msg && <span className="text-sm text-muted">{msg}</span>}
</Card>
);
}
function ProfileCards({ email, profile }: { email: string; profile: Profile }) {
const router = useRouter();
const start = { country: profile.country ?? "US", currency: profile.currency ?? countryOf(profile.country).currency };
@@ -210,6 +231,7 @@ function ProfileCards({ email, profile }: { email: string; profile: Profile }) {
{msg && <span className="text-sm text-muted">{msg}</span>}
</div>
</Card>
<MonthStart profile={profile} />
<Card title="Money profile" what="Filing status, income, goals and more. Ask broke and Optimize use it to tailor advice.">
<Link href="/optimize#profile" className="btn inline-block">Edit money profile</Link>
</Card>
+22 -9
View File
@@ -5,7 +5,7 @@ import { EmptyBank } from "@/components/EmptyBank";
import { MonthBars } from "@/components/MonthBars";
import { PageDates } from "@/components/PageDates";
import { Merchant } from "@/components/Merchant";
import { categories, displayName, getUser, isIncome, isSpend, loanPayments, moneyByMonth, savedByMonth, sumOf, today, transactionsSince, type MonthRow, type Txn } from "@/lib/data";
import { categories, displayName, getUser, isIncome, isSpend, loanPayments, moneyByMonth, months as monthsOf, savedByMonth, sumOf, today, transactionsSince, type MonthRow, type Txn } from "@/lib/data";
import { dateLabel, money, money0, monthLabel, monthStart, ymd } from "@/lib/format";
const DAY = /^\d{4}-\d{2}-\d{2}$/;
@@ -108,13 +108,21 @@ export default async function Spending({ searchParams }: { searchParams: Promise
const { m, bills, from: rawFrom, to: rawTo, span } = await searchParams;
const from = DAY.test(rawFrom ?? "") ? rawFrom! : "", to = DAY.test(rawTo ?? "") ? rawTo! : "";
const includeBills = bills !== "0";
const now = await today();
let now = await today();
if (from || to) return <CustomRange from={from} to={to} today={ymd(now)} />;
const { supabase, user } = await getUser();
// Pay months on (profile.month = "payday"): "now" is the pay month today is in, so after salary on the 24th it's
// already next month. Calendar months otherwise. Month arithmetic runs on the month's name, its dates come from mo.range.
const mo = await monthsOf();
const curYm = await mo.current();
const daysIn = Math.round((now.getTime() - Date.parse(`${mo.range(curYm).start}T00:00:00Z`)) / 864e5) + 1;
const real = now;
now = new Date(`${curYm}-01T00:00:00Z`);
const ymOf = (d: Date) => ymd(d).slice(0, 7);
// m = "YYYY-MM" (the arrows or a bar), "last" or "now"; anything else = this month. Up to 5 years back.
const ym = /^\d{4}-\d{2}$/.test(m ?? "") ? m!.split("-").map(Number) : null;
// The first days of a month open on last month: this one is still empty. m=now asks for this month anyway.
const offset = m === "last" || (!m && now.getUTCDate() <= 3) ? -1 : ym ? Math.max(-59, Math.min(0, (ym[0] - now.getUTCFullYear()) * 12 + ym[1] - 1 - now.getUTCMonth())) : 0;
const offset = m === "last" || (!m && daysIn <= 3) ? -1 : ym ? Math.max(-59, Math.min(0, (ym[0] - now.getUTCFullYear()) * 12 + ym[1] - 1 - now.getUTCMonth())) : 0;
const month = monthStart(now, offset);
const prevMonth = monthStart(now, offset - 1);
// The chart and table: the picked month's whole year by default, or the last 12 or 6 months (the 6 or 12 ending at the
@@ -130,9 +138,9 @@ export default async function Spending({ searchParams }: { searchParams: Promise
const [rows, allCats, monthTxns, loans, savedMonths] = await Promise.all([
moneyByMonth(supabase, ymd(first)),
categories(),
transactionsSince(ymd(month), ymd(monthStart(now, offset + 1))),
loanPayments(supabase, user!.id, ymd(first)),
savedByMonth(supabase, user!.id, ymd(first)),
transactionsSince(mo.range(ymOf(month)).start, mo.range(ymOf(month)).end),
loanPayments(supabase, user!.id, mo.range(ymOf(first)).start, undefined, mo.of),
savedByMonth(supabase, user!.id, mo.range(ymOf(first)).start, undefined, mo.of),
]);
// ponytail: "no transactions in 6 months" is treated as "no bank yet"; split the copy if linked-but-quiet accounts show up.
if (!rows.length) return <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 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][]);
return (
@@ -191,14 +201,17 @@ export default async function Spending({ searchParams }: { searchParams: Promise
{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>
) : <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 ? (
<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" />}
{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>
<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">
{[
@@ -289,7 +302,7 @@ export default async function Spending({ searchParams }: { searchParams: Promise
)}
</section>
</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 className="space-y-6">
@@ -40,7 +40,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
}
return back("connect=done");
} catch (e) {
console.error(`[broke] ${id} connect:`, e instanceof Error ? e.message : e);
console.error(`[broke] ${id} connect:`, e instanceof Error ? e.message : JSON.stringify(e));
return back("connect=failed");
}
}
+3 -1
View File
@@ -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.
+1 -1
View File
@@ -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
// 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.
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) {
const { data: { user } } = await (await createClient()).auth.getUser();
+6 -4
View File
@@ -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<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 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 });
+37 -1
View File
@@ -1,9 +1,16 @@
import { NextResponse } from "next/server";
import { twinAccounts } from "@/lib/links";
import { foldInto } from "@/lib/merge-run";
import { revokeItem } from "@/lib/plaid";
import { createAdminClient } from "@/utils/supabase/admin";
import { createClient } from "@/utils/supabase/server";
// Removes a bank connection: revokes it at Plaid, then deletes the item (its accounts, transactions and holdings cascade).
type Acct = { id: string; item_id: string | null; name: string | null; mask: string | null; type: string | null };
// Removes a bank connection: revokes it at the provider, then deletes the connection. Its accounts and their history
// stay. An account that another connection also has (linked twice, or linked again) folds into that one: older rows
// move over and your categories and names carry over. Any other account stays as an account added by hand, no longer
// syncing. Only a test bank's accounts and transactions go with it, because test data never stays next to real banks.
export async function POST(request: Request) {
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
@@ -15,7 +22,36 @@ export async function POST(request: Request) {
if (!item) return NextResponse.json({ error: "Connection not found" }, { status: 404 });
if (!(await revokeItem(item)).ok) return NextResponse.json({ error: "Plaid couldn't remove this connection. Try again in a moment." }, { status: 502 });
if (!item.access_token?.startsWith("access-sandbox-")) {
try {
await keepAccounts(db, user.id, item.id);
} catch (e) {
console.error("[broke] remove, keeping accounts:", e instanceof Error ? e.message : JSON.stringify(e));
return NextResponse.json({ error: "Couldn't keep this connection's accounts, so nothing was removed. Try again." }, { status: 500 });
}
}
const { error } = await db.from("plaid_items").delete().eq("id", item.id);
if (error) return NextResponse.json({ error: "Couldn't remove this connection." }, { status: 500 });
return NextResponse.json({ ok: true });
}
async function keepAccounts(db: ReturnType<typeof createAdminClient>, userId: string, itemId: string) {
const { data, error } = await db.from("accounts").select("id, item_id, name, mask, type").eq("user_id", userId).not("item_id", "is", null);
if (error) throw error;
const all = (data ?? []) as Acct[];
const leaving = all.filter((a) => a.item_id === itemId);
const twins = twinAccounts(leaving, all.filter((a) => a.item_id !== itemId));
for (const a of leaving) {
const twin = twins.get(a.id);
if (twin) {
await foldInto(db, userId, a.id, twin);
continue;
}
// No twin: unlink it. Its rows lose the bank's ids, so linking the bank again adds the bank's rows fresh and
// Accounts can merge this one into the new account like an imported statement.
const rows = await db.from("transactions").update({ plaid_transaction_id: null }).eq("user_id", userId).eq("account_id", a.id);
if (rows.error) throw rows.error;
const acct = await db.from("accounts").update({ item_id: null, plaid_account_id: null, manual: true }).eq("id", a.id).eq("user_id", userId);
if (acct.error) throw acct.error;
}
}
+5 -4
View File
@@ -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.
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 root = useRef<HTMLDivElement>(null);
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 {}
};
const m = month(new Date(now));
const d = new Date(now);
const m = month(new Date(now), span);
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" });
// 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)));
@@ -227,7 +228,7 @@ export function BudgetEditor({ basis, cats: all, initial, year, range, today, in
<div className="section-label px-1">Summary</div>
<section className="card p-6 space-y-5">
<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">
{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>
-55
View File
@@ -1,55 +0,0 @@
"use client";
import { Heart } from "lucide-react";
import { useEffect, useState } from "react";
import { Modal } from "@/components/Modal";
export const DONATE_URL = "https://buy.stripe.com/5kQ6oHgXWc1T33CbNt5Vu05";
const USED = "broke.minutesUsed", ASKED = "broke.donateAsked";
const ASK_AFTER = 120; // minutes with broke open and on screen
const read = (k: string) => { try { return localStorage.getItem(k); } catch { return null; } };
const write = (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* private window: just don't count */ } };
export function DonateLink({ className = "" }: { className?: string }) {
return (
<a href={DONATE_URL} target="_blank" rel="noopener noreferrer" className={className}>
<Heart size={18} strokeWidth={1.6} className="shrink-0" />
<span className="flex-1 text-left">Support broke</span>
</a>
);
}
// Asks once, after about two hours of use: minutes count only while a broke tab is open and visible, in this browser.
export function DonatePrompt() {
const [open, setOpen] = useState(false);
useEffect(() => {
if (read(ASKED)) return;
const tick = setInterval(() => {
if (document.visibilityState !== "visible") return;
const used = Number(read(USED) ?? 0) + 1;
write(USED, String(used));
if (used < ASK_AFTER || read(ASKED)) return;
write(ASKED, new Date().toISOString());
setOpen(true);
clearInterval(tick);
}, 60_000);
return () => clearInterval(tick);
}, []);
if (!open) return null;
return (
<Modal label="Support broke" onClose={() => setOpen(false)}>
<div className="space-y-4">
<Heart size={22} strokeWidth={1.6} className="text-muted" />
<div className="space-y-1.5">
<h2 className="text-lg font-semibold">Finding broke useful?</h2>
<p className="text-sm text-muted">broke is free and open source. If it&apos;s saved you money, you can chip in to keep it going. This is the only time it asks.</p>
</div>
<div className="flex gap-3">
<a href={DONATE_URL} target="_blank" rel="noopener noreferrer" onClick={() => setOpen(false)} className="btn-primary" data-autofocus>Donate</a>
<button className="btn" onClick={() => setOpen(false)}>Not now</button>
</div>
</div>
</Modal>
);
}
-3
View File
@@ -7,7 +7,6 @@ import { usePathname, useRouter } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import { useAssistant } from "@/components/Assistant";
import { BookmarkButton, SavedList } from "@/components/Bookmarks";
import { DonateLink, DonatePrompt } from "@/components/Donate";
// Spending holds Budgets and Recurring as tabs, Plan holds Optimize, Bonuses and Cards, More holds the rest. Every page keeps its own URL.
type Icon = ComponentType<{ size?: number; strokeWidth?: number }>;
@@ -61,10 +60,8 @@ export function Nav() {
<MessageCircle size={18} strokeWidth={1.6} />
<span className="flex-1 text-left">Ask broke ai</span>
</button>
<DonateLink className="flex items-center gap-3 px-3 py-2 rounded-xl text-[14px] whitespace-nowrap text-ink/70 hover:text-ink hover:bg-canvas/60" />
<Suspense><SavedList /></Suspense>
</nav>
<DonatePrompt />
</>
);
}
+2 -2
View File
@@ -155,7 +155,7 @@ export function ConnectionActions({ itemId, broken, name }: { itemId: string; br
<span className="flex items-center gap-2">
{confirm ? (
<>
<span className="text-xs text-muted">Remove {name} and its transactions?</span>
<span className="text-xs text-muted">Stop syncing {name}? Its accounts and history stay.</span>
<button className="btn text-bad" onClick={remove} disabled={removing}>{removing ? "Removing..." : "Remove"}</button>
<button className="btn" onClick={() => setConfirm(false)} disabled={removing}>Cancel</button>
</>
@@ -226,7 +226,7 @@ export function RemoveCopy({ itemId, name }: { itemId: string; name: string }) {
}
return confirm ? (
<span className="flex flex-wrap items-center gap-2 text-sm">
<span className="text-muted">Remove this copy of {name}? The other one keeps all your transactions.</span>
<span className="text-muted">Remove this copy of {name}? Its history and your changes move to the other one.</span>
<button className="btn text-bad" onClick={remove} disabled={busy}>{busy ? "Removing..." : "Remove copy"}</button>
<button className="text-muted hover:text-ink" onClick={() => setConfirm(false)} disabled={busy}>Cancel</button>
{err && <span className="text-bad">{err}</span>}
+1
View File
@@ -21,6 +21,7 @@ export type Profile = {
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
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
};
+2 -2
View File
@@ -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<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[] };
weekday: number[];
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.`}
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])]) }}>
<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: "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 },
+5 -3
View File
@@ -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.
export function month(now: Date) {
const day = now.getUTCDate();
const days = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();
// span: a pay month's first day and the day after its last (lib/paymonths.ts), else the calendar month.
export function month(now: Date, span?: { start: string; end: string }) {
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 };
}
+14
View File
@@ -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> = {}): 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");
+39 -24
View File
@@ -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<string, number>]));
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)!) }));
+5 -4
View File
@@ -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<string, number>();
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] & {
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<typeof checkinFacts>[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 }];
+70 -4
View File
@@ -5,6 +5,7 @@ import { cache } from "react";
import { dayIn, fmtFor, setFmtScope, US_FMT, type Fmt } from "@/lib/format";
import { ensureRates } from "@/lib/fx";
import { typicalMonth } from "@/lib/insights";
import { detectPeriods, monthOf, rangeOf, type Pay, type Period } from "@/lib/paymonths";
import { createAdminClient } from "@/utils/supabase/admin";
import { createClient } from "@/utils/supabase/server";
@@ -94,7 +95,12 @@ export async function transactionsSince(gte: string, lt?: string) {
// Totals from SQL (migration 0014), own rows only, same rules as isSpend / isIncome. income is money in, positive.
// Take the client so the AI tools can call them with theirs.
export type MonthRow = { month: string; category_id: string; spend: number; income: number; n: number };
// With pay months on, a month's first day is its payday, so a start on the 1st moves back to that day.
export async function moneyByMonth(supabase: SupabaseClient, start: string, end?: string) {
if (start.endsWith("-01")) {
const { data: p } = await supabase.from("pay_periods").select("start_date").eq("month", start).maybeSingle();
if (p?.start_date && p.start_date < start) start = p.start_date as string;
}
const { data, error } = await supabase.rpc("money_by_month", { start_date: start, end_date: end ?? null });
if (error) throw new Error(error.message);
return ((data ?? []) as MonthRow[]).map((r) => ({ ...r, spend: Number(r.spend), income: Number(r.income), n: Number(r.n) }));
@@ -107,6 +113,7 @@ export async function spendByDay(supabase: SupabaseClient, start: string, end?:
// The user's typical month: income and spend averaged over the last 3 full months (typicalMonth in insights.ts has
// the rule). The one source for "about $X a month" income on every page. Null until there is a full month.
export async function typicalMonthly(supabase: SupabaseClient, userId: string, today: string) {
today = await payMonthToday(supabase, userId, today);
const [y, m] = today.split("-").map(Number);
const [rows, { data }] = await Promise.all([
moneyByMonth(supabase, new Date(Date.UTC(y, m - 4, 1)).toISOString().slice(0, 10)),
@@ -114,25 +121,41 @@ export async function typicalMonthly(supabase: SupabaseClient, userId: string, t
]);
return typicalMonth(rows, today, (data?.[0]?.date as string | undefined) ?? null);
}
/** With pay months on, today as seen by month logic: the first day of the pay month it's in (after salary on the
* 24th it's already next month). Else today itself. */
export async function payMonthToday(supabase: SupabaseClient, userId: string, today: string) {
const { data } = await supabase.from("pay_periods").select("month").eq("user_id", userId).lte("start_date", today).order("start_date", { ascending: false }).limit(1);
const m = data?.[0]?.month as string | undefined;
return m && m.slice(0, 7) !== today.slice(0, 7) ? m : today;
}
/** 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.
export async function loanPayments(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31") {
// key: the month a date is in (months().of with pay months on), calendar by default. Same for savedByMonth.
export async function loanPayments(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31", key = (d: string) => d.slice(0, 7)) {
const rows = await allRows<{ date: string; amount: number }>((a, b) =>
supabase.from("transactions").select("date, amount, category:categories!inner(key), account:accounts!inner(type)")
.eq("user_id", userId).eq("ignored", false).gt("amount", 0).gte("date", start).lte("date", end)
.eq("category.key", "LOAN_PAYMENTS").neq("account.type", "loan").order("id").range(a, b));
const by = new Map<string, number>();
for (const r of rows) by.set(r.date.slice(0, 7), (by.get(r.date.slice(0, 7)) ?? 0) + Number(r.amount));
for (const r of rows) by.set(key(r.date), (by.get(key(r.date)) ?? 0) + Number(r.amount));
return by;
}
// Money going into savings and investment accounts per "YYYY-MM": what arrives on a savings account (net of what leaves it)
// and contributions to investment accounts. Only accounts broke can see.
export async function savedByMonth(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31") {
export async function savedByMonth(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31", key = (d: string) => d.slice(0, 7)) {
const { data: accts } = await supabase.from("accounts").select("id, type, subtype").eq("user_id", userId).or("type.eq.investment,subtype.eq.savings");
const by = new Map<string, number>();
const savings = (accts ?? []).filter((a) => a.type !== "investment").map((a) => a.id), invest = (accts ?? []).filter((a) => a.type === "investment").map((a) => a.id);
const add = (date: string, n: number) => by.set(date.slice(0, 7), (by.get(date.slice(0, 7)) ?? 0) + n);
const add = (date: string, n: number) => by.set(key(date), (by.get(key(date)) ?? 0) + n);
if (savings.length)
for (const t of await allRows<{ date: string; amount: number }>((a, b) => supabase.from("transactions").select("date, amount").eq("ignored", false).gte("date", start).lte("date", end).in("account_id", savings).order("id").range(a, b))) add(t.date, -Number(t.amount));
if (invest.length) {
@@ -161,3 +184,46 @@ export async function allTags() {
if (!seen.has(tag.toLowerCase())) seen.set(tag.toLowerCase(), tag);
return [...seen.values()].sort((a, b) => a.localeCompare(b));
}
// Months that start on payday (profile.month = "payday", lib/paymonths.ts), worked out from the salary in the
// transactions on every request, so a new paycheck or a category change shows at once. money_by_month (migration 0035)
// reads the same months from pay_periods, which is rewritten here only when they change. Null: calendar months.
export const payPeriods = cache(async (): Promise<Period[] | null> => {
const { supabase, user } = await getUser();
if (!user) return null;
const on = (user.user_metadata?.profile as { month?: string } | undefined)?.month === "payday";
const [{ data: stored }, periods] = await Promise.all([
supabase.from("pay_periods").select("month, start_date").order("month"),
on ? findPeriods(supabase, user.id) : Promise.resolve(null),
]);
const want = periods ?? [];
const same = (stored ?? []).length === want.length && want.every((p, i) => stored![i].month === p.month && stored![i].start_date === p.start);
if (!same) {
const db = createAdminClient();
await db.from("pay_periods").delete().eq("user_id", user.id);
if (want.length) await db.from("pay_periods").insert(want.map((p) => ({ user_id: user.id, month: p.month, start_date: p.start })));
}
return periods;
});
async function findPeriods(supabase: SupabaseClient, userId: string) {
const [pays, { data: first }, now] = await Promise.all([
allRows<{ date: string; amount: number }>((a, b) => supabase.from("transactions").select("date, amount, category:categories!inner(key), account:accounts!inner(included)")
.eq("user_id", userId).eq("ignored", false).lt("amount", 0).eq("category.key", "INCOME").eq("account.included", true).order("id").range(a, b)),
supabase.from("transactions").select("date").eq("user_id", userId).order("date").limit(1),
today(),
]);
if (!first?.length) return null;
return detectPeriods(pays.map((p): Pay => ({ date: p.date, amount: -Number(p.amount) })), first[0].date as string, now.toISOString().slice(0, 10));
}
/** This request's months: what month a date is in, a month's dates, and the month today is in. */
export async function months() {
const periods = await payPeriods();
return {
payday: !!periods,
of: (date: string) => monthOf(periods, date),
range: (ym: string) => rangeOf(periods, ym),
current: async () => monthOf(periods, (await today()).toISOString().slice(0, 10)),
};
}
+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: 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");
+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.
// 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 };
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 };
}
+8 -1
View File
@@ -1,6 +1,6 @@
// Run: node src/lib/links.test.ts
import assert from "node:assert/strict";
import { duplicateItems, sameAccounts } from "./links.ts";
import { duplicateItems, sameAccounts, twinAccounts } from "./links.ts";
const wf = [{ mask: "8640", type: "depository" }, { mask: "4381", type: "credit" }];
assert.equal(sameAccounts(wf, wf), true);
@@ -17,4 +17,11 @@ const items = [
{ id: "co3", institution_id: "ins_128026", created_at: "2026-10-29T15:40", accounts: [{ mask: "7777", type: "credit" }] },
];
assert.deepEqual([...duplicateItems(items)], [["wf2", "wf1"], ["co2", "co1"]]);
// Removing a connection: its accounts find their twins on the connection that stays.
const leaving = [{ id: "a1", mask: "5339", type: "depository" }, { id: "a2", mask: null, type: "depository", name: "Savings" }, { id: "a3", mask: "1111", type: "credit" }];
const staying = [{ id: "b1", mask: "5339", type: "depository" }, { id: "b2", mask: null, type: "depository", name: "Savings" }, { id: "b3", mask: "1111", type: "depository" }];
assert.deepEqual([...twinAccounts(leaving, staying)], [["a1", "b1"], ["a2", "b2"]], "a3 has no twin: another type");
assert.deepEqual([...twinAccounts([leaving[0], { ...leaving[0], id: "a4" }], staying)], [["a1", "b1"]], "each twin used once");
assert.deepEqual([...twinAccounts([{ id: "a5", mask: null, type: "depository", name: null }], [{ id: "b5", mask: null, type: "depository", name: null }])], [], "no digits and no name: can't tell");
console.log("links ok");
+12
View File
@@ -13,6 +13,18 @@ export function sameAccounts(next: Acct[], existing: Acct[]) {
return masked.every((a) => have.has(a.mask));
}
/** The same account on another connection, for a connection that is being removed: same type and last four digits,
* or, without digits, the same type and name. Each other account is used once. */
export function twinAccounts<T extends Acct & { id: string; name?: string | null }>(leaving: T[], others: T[]) {
const pool = [...others], twins = new Map<string, string>();
const same = (a: T, b: T) => (a.type ?? "") === (b.type ?? "") && (a.mask ? a.mask === b.mask : !b.mask && !!a.name && a.name === b.name);
for (const a of leaving) {
const i = pool.findIndex((b) => same(a, b));
if (i >= 0) twins.set(a.id, pool.splice(i, 1)[0].id);
}
return twins;
}
/** Connections that copy an earlier one at the same bank: id -> the earlier connection's id. */
export function duplicateItems(items: { id: string; institution_id: string | null; created_at: string; accounts: Acct[] }[]) {
const copies = new Map<string, string>();
+7
View File
@@ -24,6 +24,13 @@ export async function mergeAccounts(db: SupabaseClient, userId: string, from: st
const src = accts?.find((a) => a.id === from), dst = accts?.find((a) => a.id === into);
if (!src || !dst) return { error: "Account not found.", status: 404 };
if (!src.manual) return { error: "Only an imported account can be merged into another.", status: 400 };
return foldInto(db, userId, from, into, preview);
}
/** Moves one account's history into another: older rows move, the overlap the target already has goes, edits carry
* over. Then the source account is deleted. Also used when a connection is removed and the same account stays on
* another connection (api/plaid/remove), so nothing typed or chosen there is lost. */
export async function foldInto(db: SupabaseClient, userId: string, from: string, into: string, preview = false): Promise<MergeResult> {
const plan = planMerge(await rowsOf(db, userId, from), await rowsOf(db, userId, into));
const counts = { start: plan.start, moved: plan.move.length, replaced: plan.drop.length, edits: plan.edits.length };
if (preview) return counts;
+42
View File
@@ -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");
+67
View File
@@ -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)) };
}
+3 -1
View File
@@ -42,7 +42,9 @@ export function plaidError(e: unknown): { code: string; message: string } {
if (d?.error_code) return { code: d.error_code, message: d.display_message || d.error_message || d.error_code };
const code = (e as { code?: unknown })?.code; // other providers (src/lib/providers) throw { code: "AKAHU_401", message }
if (typeof code === "string" && /^(AKAHU_|CONSENT_EXPIRED$|FEED_CONSENT$)/.test(code) && e instanceof Error) return { code, message: e.message };
return { code: "ERROR", message: e instanceof Error ? e.message : "Plaid request failed" };
// A database error is a plain object with a message, not an Error: keep its message so the log and Accounts say what broke.
const message = e instanceof Error ? e.message : typeof (e as { message?: unknown })?.message === "string" ? (e as { message: string }).message : "Plaid request failed";
return { code: "ERROR", message };
}
/** Revokes a bank connection at Plaid. Akahu tokens belong to the server owner, and a test connection can't be revoked
+7 -5
View File
@@ -6,7 +6,7 @@ import { cardMatches } from "@/lib/cards-data";
import { cashInsights, myCashInsights } from "@/lib/cash";
import { countryOf } from "@/lib/countries";
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 { addDays, toldMonthly } from "@/lib/insights";
import { contributionRoom } from "@/lib/invest";
@@ -52,6 +52,8 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
const country = countryOf(profile.country);
const since = addDays(today, -90);
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.
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 }),
@@ -62,7 +64,7 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
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(() => []),
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),
usTax
? 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),
// 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 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> }>();
for (const row of byMonth) {
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.
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.
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 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 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 now = perMonth.get(thisMonth);
const spikes = earlier.length && now
+21 -1
View File
@@ -1,7 +1,7 @@
// Run: node src/lib/providers/feeds.test.ts
import assert from "node:assert/strict";
import { createVerify, generateKeyPairSync } from "node:crypto";
import { basiqAccount, basiqStart, basiqTxn, belvoAccount, belvoStart, belvoTxn, ebAccount, ebJwt, ebStart, ebTxn, feedData, pemFrom, validCpf } from "./feeds.ts";
import { basiqAccount, basiqStart, basiqTxn, belvoAccount, belvoStart, belvoTxn, ebAccount, ebJwt, ebStart, ebTxn, feedData, matchRenamed, pemFrom, validCpf } from "./feeds.ts";
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
const pem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
@@ -99,6 +99,26 @@ console.log("feeds: ok");
const b = ebTxn({ transaction_id: "x2", entry_reference: "ref-9", booking_date: "2026-11-02", transaction_amount: { amount: "3.50" }, credit_debit_indicator: "DBIT", status: "BOOK" }, "u1")!;
assert.equal(a.plaid_transaction_id, b.plaid_transaction_id);
}
// Linking again gave every row a new transaction_id: each new row takes over its saved twin instead of doubling.
{
const t = (id: string, date: string, amount: number, name: string) => ({ ...ebTxn({ transaction_id: id, booking_date: date, transaction_amount: { amount: String(amount) }, credit_debit_indicator: "DBIT", status: "BOOK", note: name }, "h")!, account_id: "acc" });
const saved = [
{ id: "s1", account_id: "acc", date: "2026-11-17", amount: "3.49", name: "Action" },
{ id: "s2", account_id: "acc", date: "2026-11-17", amount: "3.49", name: "Action" }, // two identical buys
{ id: "s3", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza" },
{ id: "s4", account_id: "other", date: "2026-11-17", amount: 14, name: "Pizza" }, // other account: never matched
];
const fresh = [t("n1", "2026-11-17", 3.49, "Action"), t("n2", "2026-11-17", 3.49, "Action"), t("n3", "2026-11-17", 3.49, "Action"), t("n4", "2026-11-17", 14, "Pizza"), t("n5", "2026-11-18", 14, "Pizza")];
const m = matchRenamed(fresh, saved);
assert.equal(m.size, 3); // two Actions and the pizza; the third Action and the next day's pizza are really new
assert.deepEqual(new Set([m.get(fresh[0].plaid_transaction_id), m.get(fresh[1].plaid_transaction_id)]), new Set(["s1", "s2"]));
assert.equal(m.get(fresh[2].plaid_transaction_id), undefined);
assert.equal(m.get(fresh[3].plaid_transaction_id), "s3");
assert.equal(m.get(fresh[4].plaid_transaction_id), undefined);
// A hidden copy is only used when the visible one is taken.
const h = matchRenamed([fresh[3]], [{ id: "hidden", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza", ignored: true }, { id: "shown", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza", ignored: false }]);
assert.equal(h.get(fresh[3].plaid_transaction_id), "shown");
}
// A key pasted on one line keeps its own label, PKCS#1 included, and still signs.
{
const { generateKeyPairSync, createPrivateKey: load } = await import("node:crypto");
+19
View File
@@ -97,6 +97,25 @@ export function ebTxn(t: EbTxn, uid: string): FeedTxn | null {
const id = t.entry_reference || t.transaction_id || `${date}|${n}|${text}`;
return { plaid_transaction_id: `enablebanking:${uid}:${id}`, account_ref: `enablebanking:${uid}`, date: date.slice(0, 10), amount: out ? Math.abs(n) : -Math.abs(n), name: text || other || "Transaction", merchant_name: other, logo_url: null, pending: false, plaid_category: t.bank_transaction_code?.code ?? null };
}
/** A bank can give a row a new id on a later fetch (ING through Enable Banking does after linking again), so a row
* already saved under its old id looks new. Pairs each such "new" row with a saved row of the same account, day, amount
* and name whose id didn't come back in this fetch. One saved row per new row, so two identical coffees stay two rows.
* Returns new id -> saved row's id. Saved rows that aren't hidden are used first. */
export type SavedRow = { id: string; account_id: string; date: string; amount: number | string; name: string | null; ignored?: boolean | null };
export function matchRenamed(fresh: (FeedTxn & { account_id: string })[], unmatchedSaved: SavedRow[]) {
const key = (r: { account_id: string; date: string; amount: number | string; name: string | null }) => `${r.account_id}|${r.date.slice(0, 10)}|${Number(r.amount).toFixed(2)}|${r.name ?? ""}`;
const pool = new Map<string, SavedRow[]>();
for (const s of [...unmatchedSaved].sort((a, b) => Number(!!b.ignored) - Number(!!a.ignored))) {
const k = key(s);
pool.set(k, [...(pool.get(k) ?? []), s]); // hidden first, popped last
}
const out = new Map<string, string>();
for (const t of fresh) {
const s = pool.get(key(t))?.pop();
if (s) out.set(t.plaid_transaction_id, s.id);
}
return out;
}
async function ebFeed(env: Env, token: string, since: string, f?: Fetch, now = Date.now()) {
const s = JSON.parse(token) as { accounts: EbAccount[]; institution?: string; valid_until?: string | null };
if (s.valid_until && Date.parse(s.valid_until) <= now) throw consentExpired();
+52 -11
View File
@@ -3,7 +3,7 @@ import type { CountryCode, InvestmentTransaction, RemovedTransaction, Transactio
import { categoryKey, plaid, PLAID_COUNTRIES } from "@/lib/plaid";
import { akahuTokens } from "@/lib/providers";
import { akahuAccounts, akahuTransactions, toAccount, toTxn } from "@/lib/providers/akahu";
import { feedData, isFeed, type FeedAccount, type FeedId, type FeedTxn } from "@/lib/providers/feeds";
import { feedData, isFeed, matchRenamed, type FeedAccount, type FeedId, type FeedTxn, type SavedRow } from "@/lib/providers/feeds";
import { applyRules, RULE_COLS, type Rule } from "@/lib/rules";
import { pairTransfers, findOwnTransfers, type OwnRow } from "@/lib/transfers";
import { createAdminClient } from "@/utils/supabase/admin";
@@ -420,6 +420,43 @@ export async function linkFeed(userId: string, id: FeedId, ref: string, institut
return result;
}
/** This provider's saved rows on these accounts between the first and last day of the fetch, read in pages. Read by
* account and date, not by a list of ids: bank ids can be 150 characters, and hundreds of them make a URL the database
* gateway turns away. */
async function savedInWindow(item: Item, txns: FeedTxn[], accountId: Map<string, string>) {
const rows: (SavedRow & { plaid_transaction_id: string })[] = [];
if (!txns.length) return rows;
const db = createAdminClient();
const dates = txns.map((t) => t.date).sort();
const accounts = [...new Set(txns.map((t) => accountId.get(t.account_ref)!))];
for (let from = 0; ; from += 1000) {
let q = db.from("transactions").select("id, plaid_transaction_id, account_id, date, amount, name, ignored")
.eq("user_id", item.user_id).in("account_id", accounts).gte("date", dates[0]).lte("date", dates[dates.length - 1]);
if (item.provider) q = q.like("plaid_transaction_id", `${item.provider}:%`);
const { data, error } = await q.order("id").range(from, from + 999);
if (error) throw error;
rows.push(...((data ?? []) as typeof rows));
if ((data ?? []).length < 1000) break;
}
return rows;
}
/** New-looking rows that match a saved row (same account, day, amount, name) whose id this fetch didn't return: the
* saved row moves to the new id, keeping its edits. Returns the new ids that now exist. */
async function adoptRenamed(unknown: FeedTxn[], unmatched: SavedRow[], accountId: Map<string, string>) {
if (!unknown.length || !unmatched.length) return [];
const db = createAdminClient();
const moves = [...matchRenamed(unknown.map((t) => ({ ...t, account_id: accountId.get(t.account_ref)! })), unmatched)];
const moved: string[] = [];
for (let i = 0; i < moves.length; i += 50)
await Promise.all(moves.slice(i, i + 50).map(async ([to, id]) => {
const { error } = await db.from("transactions").update({ plaid_transaction_id: to }).eq("id", id);
if (!error) moved.push(to);
else if (error.code !== "23505") throw error; // the new id is already saved elsewhere: leave this row be
}));
return moved;
}
// Writes any provider's accounts and rows the same way: new rows get the user's rules, seen rows keep their edits.
async function saveFeed(item: Item, accounts: FeedAccount[] | ReturnType<typeof toAccount>[], feed: FeedTxn[]) {
const db = createAdminClient();
@@ -433,28 +470,32 @@ async function saveFeed(item: Item, accounts: FeedAccount[] | ReturnType<typeof
const row = ({ account_ref, ...t }: FeedTxn) => ({ ...t, user_id: item.user_id, account_id: accountId.get(account_ref)! });
const chunks = <T,>(xs: T[]) => Array.from({ length: Math.ceil(xs.length / 500) }, (_, i) => xs.slice(i * 500, i * 500 + 500));
const known = new Set<string>();
for (const c of chunks(txns.map((t) => t.plaid_transaction_id))) {
const { data } = await db.from("transactions").select("plaid_transaction_id").eq("user_id", item.user_id).in("plaid_transaction_id", c);
for (const r of data ?? []) known.add(r.plaid_transaction_id);
}
const fetched = new Set(txns.map((t) => t.plaid_transaction_id));
const stored = await savedInWindow(item, txns, accountId);
const known = new Set(stored.map((r) => r.plaid_transaction_id).filter((id) => fetched.has(id)));
// Rows the bank sent again under a new id: the saved row takes the new id, so it updates instead of doubling.
const unmatched = stored.filter((r) => !fetched.has(r.plaid_transaction_id));
for (const id of await adoptRenamed(txns.filter((t) => !known.has(t.plaid_transaction_id)), unmatched, accountId)) known.add(id);
const fresh = txns.filter((t) => !known.has(t.plaid_transaction_id));
const seen = txns.filter((t) => known.has(t.plaid_transaction_id));
const { data: rules } = await db.from("rules").select(RULE_COLS).eq("user_id", item.user_id).order("created_at", { ascending: false });
const { data: other } = await db.from("categories").select("id").is("user_id", null).eq("key", "OTHER").maybeSingle();
for (const c of chunks(fresh)) {
const { error } = await db.from("transactions").insert(c.map((t) => {
// A new row whose id is saved after all (outside the date window, say) is skipped, never a failed sync: the saved
// one keeps its edits. The same id twice in one fetch is one row.
const unique = [...new Map(fresh.map((t) => [t.plaid_transaction_id, t])).values()];
for (const c of chunks(unique)) {
const { error } = await db.from("transactions").upsert(c.map((t) => {
const r = applyRules((rules ?? []) as Rule[], row(t));
// No category we can map with confidence: money out is Other, money in stays blank (counts as income).
return { ...row(t), category_id: r.category_id ?? (t.amount > 0 ? other?.id ?? null : null), custom_name: r.custom_name ?? null, ignored: r.ignored ?? false, tags: r.tags ?? [] };
}));
}), { onConflict: "plaid_transaction_id", ignoreDuplicates: true });
if (error) throw error;
}
// Seen rows: refresh what the provider owns; the user's category, name, note and tags stay.
for (const c of chunks(seen)) {
for (const c of chunks([...new Map(seen.map((t) => [t.plaid_transaction_id, t])).values()])) {
const { error } = await db.from("transactions").upsert(c.map(row), { onConflict: "plaid_transaction_id" });
if (error) throw error;
}
await db.from("plaid_items").update({ cursor: new Date().toISOString(), last_synced_at: new Date().toISOString(), status: "ok", error: null }).eq("id", item.id);
return { added: fresh.length, modified: seen.length, removed: 0 };
return { added: unique.length, modified: seen.length, removed: 0 };
}
+28
View File
@@ -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
$$;