Files
finance-app/src/app/api/analytics/monthly/route.ts
T
siddharthd 6c14b493ef
ci / lint-test (push) Successful in 1m25s
analytics: your share of what someone else paid is your spend
Every spend analytic gated on `OWNER_SCOPE = $1` and scaled by `mySplitOf`
*within* that gate, so ownership was a precondition for an expense being
yours. Half a grocery shop Sonu paid for counted as zero — in monthly,
daily, merchants, subscriptions, fees and the budget page. 167 rows /
$3,210.91 across Jan-Jul 2026, worst in April (+$1,354.83, the Europe
trips), while getParticipantBalances booked the matching debt correctly.
The app could say you owed her for a shop while insisting you had not
spent anything on it.

New MY_SPEND_SCOPE(): owner = me OR I hold a split. OWNER_SCOPE stays on
the things that measure an *account* rather than a person — the income
and investment lines, and the statement-level fee rollup.

myShare had to change with it, and widening the gate alone would have
been worse than the bug: its `100 - everyone else` fallback is the
payer's remainder, so on someone else's unsplit row it returns 100 and
moves their whole bill onto you. It now branches on ownership — my row
resolves as before; their row takes an explicit split row only, absent
meaning 0. That 0 is what makes the wider gate safe.

my_share_percent is deliberately not read on someone else's row: one
unscoped column, writable by anyone who can see the row, so "my" can
only mean the owner's. All 402 rows carrying one today are owner-side.

MY_SHARE_PCT mirrors myShare for the transactions list, which has no
viewer-scoped ts join; a test asserts the two agree across seven fixture
shapes.

No historical restatement — every non-owner split is 2026-dated, and the
1,266 pre-2026 SplitMyExpenses splits are all on rows you own.

Also fixes a latent failure in the NATIVE_CURRENCY test, which inserted a
statement relying on participant id 1 existing (owner_id is NOT NULL
DEFAULT 1 with an FK) and only passed when a sibling file had left one
behind. It now owns its fixture.

15 new integration tests; 189 integration + 130 unit green.
2026-08-15 15:37:32 +10:00

162 lines
5.6 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import {
OWNER_SCOPE,
MY_SPEND_SCOPE,
STATEMENTS_JOIN,
EFFECTIVE_CATEGORY,
EXCLUDE_NON_SPEND,
EXCLUDE_RECONCILED_SOURCE,
NET_SPEND_ROWS,
SPEND_SIGNED,
INVESTMENT_SIGNED,
mySplitOf,
toDateStr,
} from "@/lib/analytics-sql";
export async function GET(req: NextRequest) {
const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
const { searchParams } = new URL(req.url);
const monthCount = Math.min(Math.max(Number(searchParams.get("months") || "6"), 1), 24);
const now = new Date();
const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const startDate = new Date(now.getFullYear(), now.getMonth() - monthCount + 1, 1);
const startStr = toDateStr(startDate);
const endStr = toDateStr(endDate);
// Expenses: debits excluding transfers and investments, split-adjusted
const spendRows = await queryRaw<{
month: string;
category: string;
total_spent: number;
transaction_count: number;
}>(
`SELECT
TO_CHAR(DATE_TRUNC('month', t.transaction_date::date), 'YYYY-MM') as month,
${EFFECTIVE_CATEGORY} as category,
-- 4dp so the month total is summed from unrounded parts; every consumer
-- rounds for display. See the note in /api/analytics/daily.
SUM(${mySplitOf(SPEND_SIGNED)})::numeric(14,4) as total_spent,
COUNT(*)::int as transaction_count
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = $1
${STATEMENTS_JOIN}
WHERE ${MY_SPEND_SCOPE()}
AND ${NET_SPEND_ROWS}
AND ${EXCLUDE_NON_SPEND}
AND ${EXCLUDE_RECONCILED_SOURCE}
AND t.transaction_date >= $2
AND t.transaction_date < $3
GROUP BY 1, 2
ORDER BY 1 DESC, total_spent DESC`,
[user.id, startStr, endStr]
);
// Income: credits/payments categorised as income
const incomeRows = await queryRaw<{
month: string;
total_income: number;
transaction_count: number;
}>(
`SELECT
TO_CHAR(DATE_TRUNC('month', t.transaction_date::date), 'YYYY-MM') as month,
SUM(COALESCE(t.amount_aud, t.amount))::numeric(12,2) as total_income,
COUNT(*)::int as transaction_count
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
${STATEMENTS_JOIN}
WHERE ${OWNER_SCOPE} = $1
AND t.transaction_type IN ('credit', 'payment')
AND ${EFFECTIVE_CATEGORY} = 'income'
AND ${EXCLUDE_RECONCILED_SOURCE}
AND t.transaction_date >= $2
AND t.transaction_date < $3
GROUP BY 1
ORDER BY 1 DESC`,
[user.id, startStr, endStr]
);
// Investments: any transaction categorised as investment, signed so that
// withdrawals net against contributions (see INVESTMENT_SIGNED).
const investmentRows = await queryRaw<{
month: string;
total_invested: number;
transaction_count: number;
}>(
`SELECT
TO_CHAR(DATE_TRUNC('month', t.transaction_date::date), 'YYYY-MM') as month,
SUM(${INVESTMENT_SIGNED})::numeric(12,2) as total_invested,
COUNT(*)::int as transaction_count
FROM transactions t
LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
${STATEMENTS_JOIN}
WHERE ${OWNER_SCOPE} = $1
AND ${EFFECTIVE_CATEGORY} = 'investment'
AND ${EXCLUDE_RECONCILED_SOURCE}
AND t.transaction_date >= $2
AND t.transaction_date < $3
GROUP BY 1
ORDER BY 1 DESC`,
[user.id, startStr, endStr]
);
// Build month list (most recent first)
const months: string[] = [];
for (let i = monthCount - 1; i >= 0; i--) {
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
months.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`);
}
months.reverse();
const spendMap = new Map<string, number>();
const countMap = new Map<string, number>();
const incomeMap = new Map<string, number>();
const investMap = new Map<string, number>();
for (const r of spendRows) {
spendMap.set(`${r.category}:${r.month}`, Number(r.total_spent));
countMap.set(`${r.category}:${r.month}`, r.transaction_count);
}
for (const r of incomeRows) incomeMap.set(r.month, Number(r.total_income));
for (const r of investmentRows) investMap.set(r.month, Number(r.total_invested));
const allCategories = new Set<string>();
for (const r of spendRows) allCategories.add(r.category);
const rows = Array.from(allCategories)
.sort()
.map((cat) => {
const spent: Record<string, number> = {};
const txCount: Record<string, number> = {};
for (const m of months) {
const s = spendMap.get(`${cat}:${m}`);
const c = countMap.get(`${cat}:${m}`);
if (s !== undefined) spent[m] = s;
if (c !== undefined) txCount[m] = c;
}
return { category: cat, spent, txCount };
});
const totals: Record<string, { spent: number; income: number; investments: number; net: number }> = {};
for (const m of months) {
let spent = 0;
for (const row of rows) spent += row.spent[m] || 0;
const income = incomeMap.get(m) || 0;
const investments = investMap.get(m) || 0;
totals[m] = {
spent: Math.round(spent * 100) / 100,
income: Math.round(income * 100) / 100,
investments: Math.round(investments * 100) / 100,
net: Math.round((income - spent - investments) * 100) / 100,
};
}
return NextResponse.json({ months, rows, income: Object.fromEntries(incomeMap), investments: Object.fromEntries(investMap), totals });
}