fix: count every report by the signed balance of its categories (#392)

Six aggregation rules gave one month six different incomes and expenses, and
the real-vs-real compare counted every split amount twice. Every report now
sums the signed amounts of each category with its section (ADR 0026, D1):
income is the balance of the income categories, expenses the opposite of the
balance of the expense categories (a refund lowers them, refunds above
purchases make them negative), transfers keep their sign, and the rows
without an existing category form one uncategorized line, neither income nor
expense, counted in the result (D4).

- getMonthlyTrends returns the income statement of each month; Cartes and
  the Dashboard read it in place of fetchMonthlyFlows, whose net is the net
  result (D5) and whose savings rate is (income - expenses) / income (D6),
  with the uncategorized and transfer parts in netBreakdown.
- compareDeltaSql, getCategoryOverTime, the Highlights movers, the zoom, the
  seasonality and getExpensesByCategory sum signed amounts; ABS only sorts.
- The budget adherence compares signed spending to the budget, so a refund
  is no overrun; Actual vs budget gets the uncategorized line.
- The three reducers and the three tables carry the uncategorized line, between
  the expenses and the result before transfers.
- getDashboardSummary, without a caller, is removed.

test: reproduces #392 — src/__integration__/report-totals.test.ts reads every
report through its real service, on the reproduction and the edge cases of
the issue, on the shared node:sqlite harness; it failed 17 of its 20 first
tests on the previous code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-07 22:32:30 -05:00
commit d742415e09
23 changed files with 1524 additions and 603 deletions

View file

@ -229,7 +229,7 @@ describe.each<[Schema]>([["v2"], ["v1"]])(
if (/FROM categories/i.test(sql)) return Promise.resolve(categories); if (/FROM categories/i.test(sql)) return Promise.resolve(categories);
if (/FROM budget_entries WHERE year/i.test(sql)) if (/FROM budget_entries WHERE year/i.test(sql))
return Promise.resolve(entries); return Promise.resolve(entries);
if (/GROUP BY category_id/i.test(sql)) return Promise.resolve([]); if (/AS actual/i.test(sql)) return Promise.resolve([]);
return Promise.resolve([]); return Promise.resolve([]);
}); });
@ -240,7 +240,7 @@ describe.each<[Schema]>([["v2"], ["v1"]])(
const parentId = schema === "v2" ? 22 : 1110; const parentId = schema === "v2" ? 22 : 1110;
// Collect budgets per row keyed by category_id. // Collect budgets per row keyed by category_id.
const budgetById = new Map<number, number>(); const budgetById = new Map<number | null, number>();
for (const r of rows) { for (const r of rows) {
budgetById.set(r.category_id, r.monthBudget); budgetById.set(r.category_id, r.monthBudget);
} }

View file

@ -0,0 +1,516 @@
/**
* The totals of the reports, read through their real services (#392, ADR 0026).
*
* The income, the expenses and the result of one month used to change with the
* screen: six aggregation rules, none of which treated transfers, refunds,
* splits and transactions without a category alike, and the real-vs-real
* compare counted every split amount twice. There is now one rule (D1): the
* signed sum of each category over the period, splits and refunds included.
* Income is the balance of the income categories, expenses the opposite of
* the balance of the expense categories (negative when refunds exceed
* purchases), transfers the signed balance of the transfer categories, and
* the transactions without a category form a line of their own, neither
* income nor expense, counted in the result (D4). « Solde net » is the sum of
* every amount of the period (D5), the savings rate (income − expenses) ÷
* income (D6).
*
* Every report is read here on the two datasets of the issue, on a real SQLite
* database (`src/test/sqliteHarness.ts`): the SQL runs as written.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { DatabaseSync } from "node:sqlite";
vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
import { openProfileDb, useDb } from "../test/sqliteHarness";
import { getTransactionPage, saveSplitAdjustment } from "../services/transactionService";
import {
getCartesSnapshot,
getCategoryOverTime,
getCategoryZoom,
getCompareMonthOverMonth,
getCompareYearOverYear,
getHighlights,
getMonthlyTrends,
} from "../services/reportService";
import { getExpensesByCategory } from "../services/dashboardService";
import { getActualTotalsForYear, getBudgetVsActualData } from "../services/budgetService";
import { computeResults as compareResults } from "../components/reports/compareResults";
import { computeOverTimeResults } from "../components/reports/overTimeResults";
import { computeResults as budgetResults } from "../components/reports/budgetVsActualResults";
import type { IncomeStatementFigures } from "../shared/types";
// Categories of the seed of a new profile.
const EMPLOYMENT = 1010; // « Emploi », income, parent of the next one
const PAY = 1011; // « Paie régulière », income
const GROCERY_AND_MARKET = 1110; // « Épicerie & marché », parent of the next two
const GROCERIES = 1111; // « Épicerie régulière »
const BUTCHER = 1112; // « Boucherie & poissonnerie »
const PHARMACY = 1611; // « Pharmacie »
const CARD = 1971; // « Paiement carte crédit », transfer
const PAY_NAME = "Paie régulière";
const GROCERIES_NAME = "Épicerie régulière";
const BUTCHER_NAME = "Boucherie & poissonnerie";
const PHARMACY_NAME = "Pharmacie";
const CARD_NAME = "Paiement carte crédit";
const FROM = "2026-10-01";
const TO = "2026-10-31";
const TODAY = new Date(2026, 9, 31);
let db: DatabaseSync;
beforeEach(() => {
db = useDb(openProfileDb());
});
afterEach(() => {
db.close();
});
/** A transaction as an import writes it; its id. */
function insert(
date: string,
description: string,
amount: number,
categoryId: number | null,
sourceId: number | null = null,
): number {
const result = db
.prepare(
`INSERT INTO transactions (date, description, amount, category_id, source_id, original_description)
VALUES ($date, $description, $amount, $category, $source, $description)`,
)
.run({ $date: date, $description: description, $amount: amount, $category: categoryId, $source: sourceId });
return Number(result.lastInsertRowid);
}
/** An import source; its id. */
function source(name: string): number {
const result = db
.prepare("INSERT INTO import_sources (name, column_mapping) VALUES ($name, '{}')")
.run({ $name: name });
return Number(result.lastInsertRowid);
}
/** The budget of a category for October 2026, entered positive as on the Budget page. */
function budget(categoryId: number, amount: number): void {
db.prepare("INSERT INTO budget_entries (category_id, year, month, amount) VALUES ($c, 2026, 10, $a)").run({
$c: categoryId,
$a: amount,
});
}
/** The sum of every amount of October 2026, split lines included. */
function sumOfOctober(): number {
const row = db
.prepare("SELECT COALESCE(SUM(amount), 0) AS s FROM transactions WHERE date BETWEEN $f AND $t")
.get({ $f: FROM, $t: TO }) as { s: number };
return Math.round(row.s * 100) / 100;
}
/**
* The reproduction of the issue: pay +1000; groceries −100, of which −30 split
* to Pharmacy (the real service writes the −30 line and the +30 offset line in
* Groceries); a +20 refund in Groceries; a card payment −500 / +500. Expenses
* 80 (Groceries 50, Pharmacy 30), net 920.
*/
async function seedReproduction(sourceId: number | null = null): Promise<void> {
insert("2026-10-02", "PAIE", 1000, PAY, sourceId);
const groceries = insert("2026-10-05", "EPICERIE METRO", -100, GROCERIES, sourceId);
await saveSplitAdjustment(groceries, [{ category_id: PHARMACY, amount: -30, description: "PHARMACIE" }]);
insert("2026-10-08", "REMBOURSEMENT METRO", 20, GROCERIES, sourceId);
insert("2026-10-10", "PAIEMENT CARTE", -500, CARD, sourceId);
insert("2026-10-10", "PAIEMENT RECU", 500, CARD, sourceId);
// Spent 50 in Groceries against a budget of 40.
budget(GROCERIES, 40);
}
/**
* The edge cases of the issue: pay +1000; groceries −80; a refund of +50 alone
* in Butcher, budgeted 30; a credit of +40 without a category; a card payment
* with one leg only, −300. Income 1000, expenses 30, uncategorized +40,
* transfers −300, result before transfers 1010, net 710.
*/
function seedEdgeCases(): void {
insert("2026-10-02", "PAIE", 1000, PAY);
insert("2026-10-03", "EPICERIE", -80, GROCERIES);
insert("2026-10-04", "REMBOURSEMENT BOUCHERIE", 50, BUTCHER);
insert("2026-10-06", "VIREMENT INCONNU", 40, null);
insert("2026-10-07", "PAIEMENT CARTE", -300, CARD);
budget(BUTCHER, 30);
budget(GROCERIES, 100);
}
const REPRODUCTION = {
income: 1000,
expenses: 80,
uncategorized: 0,
transfers: 0,
resultBeforeTransfers: 920,
net: 920,
};
const EDGE_CASES = {
income: 1000,
expenses: 30,
uncategorized: 40,
transfers: -300,
resultBeforeTransfers: 1010,
net: 710,
};
const page = () =>
getTransactionPage(
{ search: "", categoryId: null, sourceId: null, dateFrom: FROM, dateTo: TO, uncategorizedOnly: false },
{ column: "date", direction: "desc" },
1,
50,
);
describe("the reproduction of #392: every report reads income 1000, expenses 80, net 920", () => {
beforeEach(async () => {
await seedReproduction();
expect(sumOfOctober()).toBe(920);
});
it("Trends, global flow", async () => {
expect(await getMonthlyTrends(FROM, TO)).toEqual([{ month: "2026-10", ...REPRODUCTION }]);
});
it("Dashboard and Cartes: the four indicators, their note, seasonality, movers and budget adherence", async () => {
const snapshot = await getCartesSnapshot(2026, 10, "month");
expect(snapshot.kpis.income.current).toBe(1000);
expect(snapshot.kpis.expenses.current).toBe(80);
expect(snapshot.kpis.net.current).toBe(920);
expect(snapshot.kpis.savingsRate.current).toBe(92);
expect(snapshot.netBreakdown).toEqual({ uncategorized: 0, transfers: 0 });
expect(snapshot.flow12Months[snapshot.flow12Months.length - 1]).toEqual({ month: "2026-10", ...REPRODUCTION });
expect(snapshot.seasonality.referenceAmount).toBe(80);
// Spending categories only, each split part in its own category, counted once.
expect(snapshot.topMoversUp.map((m) => [m.categoryName, m.currentAmount])).toEqual([
[GROCERIES_NAME, 50],
[PHARMACY_NAME, 30],
]);
expect(snapshot.budgetAdherence).toEqual({
categoriesInTarget: 0,
categoriesTotal: 1,
worstOverruns: [
expect.objectContaining({ categoryName: GROCERIES_NAME, actual: 50, budget: 40, overrunAbs: 10 }),
],
});
});
it("Compare, real vs real: the split counted once (it was 130)", async () => {
for (const rows of [await getCompareMonthOverMonth(2026, 10), await getCompareYearOverYear(2026, 10)]) {
const r = compareResults(rows);
expect([
r.income.monthCurrent,
r.expense.monthCurrent,
r.uncategorized.monthCurrent,
r.transfer.monthCurrent,
r.resultBefore.monthCurrent,
r.resultNet.monthCurrent,
]).toEqual([1000, 80, 0, 0, 920, 920]);
const leaves = Object.fromEntries(
rows.filter((row) => !row.is_parent).map((row) => [row.categoryName, row.currentAmount]),
);
expect(leaves).toMatchObject({ [GROCERIES_NAME]: 50, [PHARMACY_NAME]: 30, [CARD_NAME]: 0 });
}
});
it("Trends, by category", async () => {
const analysis = computeOverTimeResults(await getCategoryOverTime(FROM, TO));
expect(Object.fromEntries(analysis.sections.map((s) => [s.type, s.total]))).toEqual({
income: 1000,
expense: 80,
transfer: 0,
});
expect(analysis.uncategorized.total).toBe(0);
expect(analysis.beforeTransfers.total).toBe(920);
expect(analysis.net.total).toBe(920);
});
it("Dashboard: expenses by category, and their monthly chart", async () => {
expect((await getExpensesByCategory(FROM, TO)).map((c) => [c.category_name, c.total])).toEqual([
[GROCERIES_NAME, 50],
[PHARMACY_NAME, 30],
]);
const overTime = await getCategoryOverTime(FROM, TO, undefined, undefined, "expense");
expect(overTime.data).toEqual([{ month: "2026-10", [GROCERIES_NAME]: 50, [PHARMACY_NAME]: 30 }]);
});
it("Compare, actual vs budget", async () => {
const r = budgetResults(await getBudgetVsActualData(2026, 10));
expect([
r.income.monthActual,
r.expense.monthActual,
r.uncategorized.monthActual,
r.transfer.monthActual,
r.resultBefore.monthActual,
r.resultNet.monthActual,
]).toEqual([1000, -80, 0, 0, 920, 920]);
});
it("Highlights: the net of the month, and movers among spending categories only", async () => {
const highlights = await getHighlights(2026, 10, 2026, 30, 5, 10, TODAY);
expect(highlights.netBalanceCurrent).toBe(920);
expect(highlights.topMovers.map((m) => [m.categoryName, m.currentAmount])).toEqual([
[GROCERIES_NAME, 50],
[PHARMACY_NAME, 30],
]);
});
it("Category analysis: the zoom nets the split and the refund (it was 150)", async () => {
const zoom = await getCategoryZoom(GROCERY_AND_MARKET, FROM, TO, true);
expect(zoom.rollupTotal).toBe(50);
expect(zoom.byChild.find((c) => c.categoryId === GROCERIES)?.total).toBe(50);
expect(zoom.monthlyEvolution).toEqual([{ month: "2026-10", total: 50 }]);
});
it("Category analysis: a zoom on an income category shows its balance as it is", async () => {
const zoom = await getCategoryZoom(EMPLOYMENT, FROM, TO, true);
expect(zoom.rollupTotal).toBe(1000);
expect(zoom.byChild.find((c) => c.categoryId === PAY)).toMatchObject({ categoryName: PAY_NAME, total: 1000 });
expect(zoom.monthlyEvolution).toEqual([{ month: "2026-10", total: 1000 }]);
});
it("Transactions: the summary bar keeps its sums by sign, without the split lines (D8)", async () => {
const p = await page();
expect([p.totalCount, p.incomeTotal, p.expenseTotal, p.totalAmount]).toEqual([5, 1520, -600, 920]);
});
});
describe("the edge cases of #392: every report reads the same net, 710", () => {
beforeEach(() => {
seedEdgeCases();
expect(sumOfOctober()).toBe(710);
});
it("Trends, global flow: the uncategorized line and the one-leg transfer apart", async () => {
expect(await getMonthlyTrends(FROM, TO)).toEqual([{ month: "2026-10", ...EDGE_CASES }]);
});
it("Dashboard and Cartes: a refund lowers the expenses, the savings rate leaves transfers out", async () => {
const snapshot = await getCartesSnapshot(2026, 10, "month");
expect(snapshot.kpis.income.current).toBe(1000);
expect(snapshot.kpis.expenses.current).toBe(30);
expect(snapshot.kpis.net.current).toBe(710);
expect(snapshot.kpis.savingsRate.current).toBe(97);
expect(snapshot.netBreakdown).toEqual({ uncategorized: 40, transfers: -300 });
expect(snapshot.seasonality.referenceAmount).toBe(30);
expect(snapshot.topMoversUp.map((m) => [m.categoryName, m.currentAmount])).toEqual([[GROCERIES_NAME, 80]]);
expect(snapshot.topMoversDown.map((m) => [m.categoryName, m.currentAmount])).toEqual([[BUTCHER_NAME, -50]]);
// The refund alone in Butcher is no overrun of its budget of 30.
expect(snapshot.budgetAdherence).toEqual({ categoriesInTarget: 2, categoriesTotal: 2, worstOverruns: [] });
// The savings sparkline follows the same rule as the card.
const spark = snapshot.kpis.savingsRate.sparkline;
expect(spark[spark.length - 1]).toEqual({ month: "2026-10", value: 97 });
});
it("Cartes, year to date: the same figures and the same note", async () => {
const snapshot = await getCartesSnapshot(2026, 10, "ytd");
expect([
snapshot.kpis.income.current,
snapshot.kpis.expenses.current,
snapshot.kpis.net.current,
snapshot.kpis.savingsRate.current,
]).toEqual([1000, 30, 710, 97]);
expect(snapshot.netBreakdown).toEqual({ uncategorized: 40, transfers: -300 });
});
it("Cartes, seasonality: a past year's month reads its expenses, refunds netted, nothing else", async () => {
insert("2025-10-03", "EPICERIE", -60, GROCERIES);
insert("2025-10-09", "REMBOURSEMENT", 10, GROCERIES);
insert("2025-10-02", "PAIE", 500, PAY);
insert("2025-10-05", "INCONNU", -25, null);
insert("2025-10-07", "PAIEMENT CARTE", -200, CARD);
const { seasonality } = await getCartesSnapshot(2026, 10, "month");
expect(seasonality.historicalYears).toEqual([{ year: 2025, amount: 50 }]);
expect(seasonality.historicalAverage).toBe(50);
expect(seasonality.referenceAmount).toBe(30);
expect(seasonality.deviationPct).toBeCloseTo(-40, 6);
});
it("Compare, real vs real: the refund and the credit without a category are no longer dropped", async () => {
const rows = await getCompareMonthOverMonth(2026, 10);
const r = compareResults(rows);
expect([
r.income.monthCurrent,
r.expense.monthCurrent,
r.uncategorized.monthCurrent,
r.transfer.monthCurrent,
r.resultBefore.monthCurrent,
r.resultNet.monthCurrent,
]).toEqual([1000, 30, 40, -300, 1010, 710]);
expect(rows.filter((row) => row.category_type === "uncategorized")).toEqual([
expect.objectContaining({ categoryId: null, currentAmount: 40, is_parent: false }),
]);
});
it("Trends, by category: a signed transfer, the refund lowers its category", async () => {
const data = await getCategoryOverTime(FROM, TO);
const analysis = computeOverTimeResults(data);
expect(Object.fromEntries(analysis.sections.map((s) => [s.type, s.total]))).toEqual({
income: 1000,
expense: 30,
transfer: -300,
});
expect(analysis.uncategorized.total).toBe(40);
expect(analysis.beforeTransfers.total).toBe(1010);
expect(analysis.net.total).toBe(710);
expect(data.tree.find((row) => row.categoryId === BUTCHER)?.total).toBe(-50);
});
it("Dashboard: the expense charts carry the negative expense, and no line without a category", async () => {
expect((await getExpensesByCategory(FROM, TO)).map((c) => [c.category_name, c.total])).toEqual([
[GROCERIES_NAME, 80],
[BUTCHER_NAME, -50],
]);
const overTime = await getCategoryOverTime(FROM, TO, undefined, undefined, "expense");
expect(overTime.data).toEqual([{ month: "2026-10", [GROCERIES_NAME]: 80, [BUTCHER_NAME]: -50 }]);
expect(overTime.tree.some((row) => row.category_type !== "expense")).toBe(false);
});
it("Compare, actual vs budget: the uncategorized line counts in the result", async () => {
const rows = await getBudgetVsActualData(2026, 10);
const r = budgetResults(rows);
expect([
r.income.monthActual,
r.expense.monthActual,
r.uncategorized.monthActual,
r.transfer.monthActual,
r.resultBefore.monthActual,
r.resultNet.monthActual,
]).toEqual([1000, -30, 40, -300, 1010, 710]);
expect(rows.filter((row) => row.category_type === "uncategorized")).toEqual([
expect.objectContaining({ category_id: null, monthActual: 40, monthBudget: 0, is_parent: false }),
]);
});
it("Highlights: the net of the month, movers without the transfer", async () => {
const highlights = await getHighlights(2026, 10, 2026, 30, 5, 10, TODAY);
expect(highlights.netBalanceCurrent).toBe(710);
expect(highlights.topMovers.map((m) => [m.categoryName, m.currentAmount])).toEqual([
[GROCERIES_NAME, 80],
[BUTCHER_NAME, -50],
]);
});
it("Category analysis: a subcategory with refunds only has a negative part", async () => {
const zoom = await getCategoryZoom(GROCERY_AND_MARKET, FROM, TO, true);
expect(zoom.rollupTotal).toBe(30);
const byChild = Object.fromEntries(zoom.byChild.map((c) => [c.categoryId, c.total]));
expect(byChild[GROCERIES]).toBe(80);
expect(byChild[BUTCHER]).toBe(-50);
expect(zoom.monthlyEvolution).toEqual([{ month: "2026-10", total: 30 }]);
});
it("Transactions: the summary bar keeps its sums by sign (D8)", async () => {
const p = await page();
expect([p.totalCount, p.incomeTotal, p.expenseTotal, p.totalAmount]).toEqual([5, 1090, -380, 710]);
});
});
describe("the account filter (#273, #279) keeps every report on the chosen sources", () => {
let chosen: number;
let other: number;
beforeEach(async () => {
chosen = source("Compte courant");
other = source("Carte");
await seedReproduction(chosen);
insert("2026-10-12", "EPICERIE IGA", -70, GROCERIES, other);
insert("2026-10-15", "BONI", 200, PAY, other);
});
it("filtered on the chosen source, every report reads the reproduction again", async () => {
const ids = [chosen];
// October 2025, for the seasonality: 40 spent from the chosen source, 70 from the other.
insert("2025-10-03", "EPICERIE", -40, GROCERIES, chosen);
insert("2025-10-04", "EPICERIE IGA", -70, GROCERIES, other);
expect(await getMonthlyTrends(FROM, TO, ids)).toEqual([{ month: "2026-10", ...REPRODUCTION }]);
const snapshot = await getCartesSnapshot(2026, 10, "month", ids);
expect([snapshot.kpis.income.current, snapshot.kpis.expenses.current, snapshot.kpis.net.current]).toEqual([
1000, 80, 920,
]);
expect(snapshot.seasonality.referenceAmount).toBe(80);
expect(snapshot.seasonality.historicalYears).toEqual([{ year: 2025, amount: 40 }]);
expect(compareResults(await getCompareMonthOverMonth(2026, 10, ids)).expense.monthCurrent).toBe(80);
expect(compareResults(await getCompareYearOverYear(2026, 10, ids)).expense.monthCurrent).toBe(80);
const actuals = await getActualTotalsForYear(2026, ids);
expect(actuals.find((a) => a.category_id === GROCERIES)?.actual).toBe(-50);
expect(computeOverTimeResults(await getCategoryOverTime(FROM, TO, undefined, ids)).net.total).toBe(920);
expect((await getExpensesByCategory(FROM, TO, ids)).map((c) => c.total)).toEqual([50, 30]);
expect(budgetResults(await getBudgetVsActualData(2026, 10, ids)).resultNet.monthActual).toBe(920);
});
it("without a filter, the other source counts too", async () => {
expect(await getMonthlyTrends(FROM, TO)).toEqual([
{ month: "2026-10", income: 1200, expenses: 150, uncategorized: 0, transfers: 0, resultBeforeTransfers: 1050, net: 1050 },
]);
});
});
describe("each case of #392 alone: the monthly statement and the compare agree with the sum of the period", () => {
const cases: Array<[string, () => unknown, Partial<IncomeStatementFigures>]> = [
[
"a split counts once",
async () => {
const id = insert("2026-10-05", "EPICERIE METRO", -100, GROCERIES);
await saveSplitAdjustment(id, [{ category_id: PHARMACY, amount: -30, description: "PHARMACIE" }]);
},
{ expenses: 100, net: -100 },
],
[
"a refund lowers its category",
() => {
insert("2026-10-05", "EPICERIE", -100, GROCERIES);
insert("2026-10-08", "REMBOURSEMENT", 20, GROCERIES);
},
{ expenses: 80, net: -80 },
],
[
"a balanced transfer nets to zero",
() => {
insert("2026-10-10", "PAIEMENT CARTE", -500, CARD);
insert("2026-10-10", "PAIEMENT RECU", 500, CARD);
},
{ income: 0, expenses: 0, transfers: 0, net: 0 },
],
[
"a one-leg transfer keeps its sign, in the net only",
() => insert("2026-10-07", "PAIEMENT CARTE", -300, CARD),
{ expenses: 0, transfers: -300, resultBeforeTransfers: 0, net: -300 },
],
[
"a credit without a category is the uncategorized line, neither income nor expense",
() => insert("2026-10-06", "VIREMENT INCONNU", 40, null),
{ income: 0, expenses: 0, uncategorized: 40, resultBeforeTransfers: 40, net: 40 },
],
[
"refunds above purchases make a negative expense",
() => insert("2026-10-04", "REMBOURSEMENT BOUCHERIE", 50, BUTCHER),
{ expenses: -50, resultBeforeTransfers: 50, net: 50 },
],
];
it.each(cases)("%s", async (_name, seed, expected) => {
await seed();
const [month] = await getMonthlyTrends(FROM, TO);
expect(month).toMatchObject(expected);
expect(month.net).toBe(sumOfOctober());
const r = compareResults(await getCompareMonthOverMonth(2026, 10));
expect([
r.income.monthCurrent,
r.expense.monthCurrent,
r.uncategorized.monthCurrent,
r.transfer.monthCurrent,
r.resultNet.monthCurrent,
]).toEqual([month.income, month.expenses, month.uncategorized, month.transfers, month.net]);
});
});

View file

@ -75,11 +75,13 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
const typeLabels: Record<SectionType, string> = { const typeLabels: Record<SectionType, string> = {
expense: t("budget.expenses"), expense: t("budget.expenses"),
income: t("budget.income"), income: t("budget.income"),
uncategorized: t("reports.uncategorized"),
transfer: t("budget.transfers"), transfer: t("budget.transfers"),
}; };
const typeTotalKeys: Record<SectionType, string> = { const typeTotalKeys: Record<SectionType, string> = {
expense: "budget.totalExpenses", expense: "budget.totalExpenses",
income: "budget.totalIncome", income: "budget.totalIncome",
uncategorized: "reports.uncategorized",
transfer: "budget.totalTransfers", transfer: "budget.totalTransfers",
}; };
@ -94,10 +96,11 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
// Income-statement result lines (Issue #277): income + expense (expense // Income-statement result lines (Issue #277): income + expense (expense
// already arrives signed negative in BudgetVsActualRow — see // already arrives signed negative in BudgetVsActualRow — see
// budgetVsActualResults.ts), then the net after adding transfers. Replaces // budgetVsActualResults.ts) + the uncategorized line, then the net after
// the old flat grand total row. // adding transfers. Replaces the old flat grand total row. The uncategorized
// row forms no section: one line, before the result before transfers (#392).
const results = computeResults(data); const results = computeResults(data);
const nonTransferSections = sections.filter((s) => s.type !== "transfer"); const nonTransferSections = sections.filter((s) => s.type !== "transfer" && s.type !== "uncategorized");
const transferSection = sections.find((s) => s.type === "transfer"); const transferSection = sections.find((s) => s.type === "transfer");
const renderSection = (section: { type: SectionType; label: string; rows: BudgetVsActualRow[] }) => { const renderSection = (section: { type: SectionType; label: string; rows: BudgetVsActualRow[] }) => {
@ -212,6 +215,25 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
); );
}; };
// The uncategorized line (D4, #392): actuals without a budget, neither income
// nor expense, counted in both results; uncoloured.
const renderUncategorizedRow = (tot: Totals) => {
const rowBg = "bg-[color-mix(in_srgb,var(--muted)_40%,var(--card))]";
return (
<tr key="uncategorized" className={`border-b border-[var(--border)] font-semibold text-sm ${rowBg}`}>
<td className={`px-3 py-2.5 sticky left-0 z-10 ${rowBg}`}>{t("reports.uncategorized")}</td>
<td className="text-right px-3 py-2.5 border-l border-[var(--border)]/50">{cadFormatter(tot.monthActual)}</td>
<td className="text-right px-3 py-2.5">{cadFormatter(tot.monthBudget)}</td>
<td className="text-right px-3 py-2.5">{cadFormatter(tot.monthVariation)}</td>
<td className="text-right px-3 py-2.5">{pctFormatter(pct(tot.monthVariation, tot.monthBudget))}</td>
<td className="text-right px-3 py-2.5 border-l border-[var(--border)]/50">{cadFormatter(tot.ytdActual)}</td>
<td className="text-right px-3 py-2.5">{cadFormatter(tot.ytdBudget)}</td>
<td className="text-right px-3 py-2.5">{cadFormatter(tot.ytdVariation)}</td>
<td className="text-right px-3 py-2.5">{pctFormatter(pct(tot.ytdVariation, tot.ytdBudget))}</td>
</tr>
);
};
// A result line (before-transfers subtotal or the net total). Every cell is // A result line (before-transfers subtotal or the net total). Every cell is
// coloured by its own sign — a surplus is green, a deficit red — mirroring // coloured by its own sign — a surplus is green, a deficit red — mirroring
// ComparePeriodTable.renderResultRow (unlike normal rows, which only colour // ComparePeriodTable.renderResultRow (unlike normal rows, which only colour
@ -314,9 +336,11 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
</thead> </thead>
<tbody> <tbody>
{nonTransferSections.map(renderSection)} {nonTransferSections.map(renderSection)}
{/* Operating result (income + expense), shown before the transfers {results.hasUncategorized && renderUncategorizedRow(results.uncategorized)}
section only when transfers exist — otherwise it equals the net {/* Operating result (income + expense + uncategorized), shown before
total below and would just be noise (mirrors ComparePeriodTable). */} the transfers section only when transfers exist — otherwise it
equals the net total below and would just be noise (mirrors
ComparePeriodTable). */}
{results.hasTransfers && {results.hasTransfers &&
renderResultRow("reports.compare.resultBeforeTransfers", results.resultBefore, false)} renderResultRow("reports.compare.resultBeforeTransfers", results.resultBefore, false)}
{transferSection && renderSection(transferSection)} {transferSection && renderSection(transferSection)}

View file

@ -65,7 +65,7 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
// Consumes the id-keyed tree (every category, no top-N/"Other"): subtotals and // Consumes the id-keyed tree (every category, no top-N/"Other"): subtotals and
// the result lines are exact, and homonym categories never collide. // the result lines are exact, and homonym categories never collide.
const analysis = computeOverTimeResults(data); const analysis = computeOverTimeResults(data);
const { months, hasTransfers, net, beforeTransfers } = analysis; const { months, hasTransfers, hasUncategorized, uncategorized, net, beforeTransfers } = analysis;
const { nonTransferSections, transferSection } = groupOverTimeSections(analysis, data.tree); const { nonTransferSections, transferSection } = groupOverTimeSections(analysis, data.tree);
const colSpan = months.length + 2; const colSpan = months.length + 2;
@ -176,6 +176,24 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
</Fragment> </Fragment>
); );
// The uncategorized line (D4, #392): neither income nor expense, counted in
// both results, shown on one uncoloured line like a section subtotal.
const renderUncategorizedRow = (series: OverTimeSeries) => (
<tr className="border-b border-[var(--border)] bg-[color-mix(in_srgb,var(--muted)_40%,var(--card))] font-semibold">
<td className="px-3 py-2.5 sticky left-0 bg-[color-mix(in_srgb,var(--muted)_40%,var(--card))] z-10">
{t("reports.uncategorized")}
</td>
{months.map((month) => (
<td key={month} className="text-right px-3 py-2.5 tabular-nums">
{series.monthly[month] ? cadFormatter(series.monthly[month]) : "—"}
</td>
))}
<td className="text-right px-3 py-2.5 border-l border-[var(--border)]/50 tabular-nums">
{cadFormatter(series.total)}
</td>
</tr>
);
// A result line (before-transfers subtotal or the net bottom line). Amounts are // A result line (before-transfers subtotal or the net bottom line). Amounts are
// coloured by sign (surplus green / deficit red). Computed from the raw tree, // coloured by sign (surplus green / deficit red). Computed from the raw tree,
// so folding groups never moves these figures. // so folding groups never moves these figures.
@ -239,9 +257,11 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
</thead> </thead>
<tbody> <tbody>
{nonTransferSections.map(renderSection)} {nonTransferSections.map(renderSection)}
{/* Operating result (revenues − expenses), interleaved before the {hasUncategorized && renderUncategorizedRow(uncategorized)}
transfers section only when transfers exist — otherwise it equals {/* Operating result (revenues − expenses + uncategorized),
the net total below and would just be noise. */} interleaved before the transfers section only when transfers
exist — otherwise it equals the net total below and would just
be noise. */}
{hasTransfers && renderResultRow("reports.compare.resultBeforeTransfers", beforeTransfers, false)} {hasTransfers && renderResultRow("reports.compare.resultBeforeTransfers", beforeTransfers, false)}
{transferSection && renderSection(transferSection)} {transferSection && renderSection(transferSection)}
{/* Bottom line: result after netting transfers. */} {/* Bottom line: result after netting transfers. */}

View file

@ -110,11 +110,13 @@ export default function ComparePeriodTable({
const sectionLabels: Record<SectionType, string> = { const sectionLabels: Record<SectionType, string> = {
expense: t("reports.compare.sections.expenses"), expense: t("reports.compare.sections.expenses"),
income: t("reports.compare.sections.income"), income: t("reports.compare.sections.income"),
uncategorized: t("reports.uncategorized"),
transfer: t("reports.compare.sections.transfers"), transfer: t("reports.compare.sections.transfers"),
}; };
const sectionTotalKeys: Record<SectionType, string> = { const sectionTotalKeys: Record<SectionType, string> = {
expense: "reports.compare.totalExpenses", expense: "reports.compare.totalExpenses",
income: "reports.compare.totalIncome", income: "reports.compare.totalIncome",
uncategorized: "reports.uncategorized",
transfer: "reports.compare.totalTransfers", transfer: "reports.compare.totalTransfers",
}; };
const sections: { type: SectionType; rows: CategoryDelta[] }[] = []; const sections: { type: SectionType; rows: CategoryDelta[] }[] = [];
@ -128,11 +130,12 @@ export default function ComparePeriodTable({
sections[sections.length - 1].rows.push(row); sections[sections.length - 1].rows.push(row);
} }
// Income-statement result lines (Issue #253): revenues − expenses, then the // Income-statement result lines (Issue #253): revenues − expenses + the
// net after transfers. Replaces the old flat grand total, which is meaningless // uncategorized line, then the net after transfers (ADR 0026). Replaces the
// once revenues and (ABS) expenses share one table. // old flat grand total. The uncategorized rows form no section: one line,
// between the expenses and the result before transfers (#392).
const results = computeResults(rows); const results = computeResults(rows);
const nonTransferSections = sections.filter((s) => s.type !== "transfer"); const nonTransferSections = sections.filter((s) => s.type !== "transfer" && s.type !== "uncategorized");
const transferSection = sections.find((s) => s.type === "transfer"); const transferSection = sections.find((s) => s.type === "transfer");
const renderSection = (section: { type: SectionType; rows: CategoryDelta[] }) => { const renderSection = (section: { type: SectionType; rows: CategoryDelta[] }) => {
@ -294,6 +297,26 @@ export default function ComparePeriodTable({
); );
}; };
// The uncategorized line (D4, #392): neither income nor expense, counted in
// both results. Its deltas stay uncoloured — a rise is neither good nor bad.
const renderUncategorizedRow = (tot: Totals) => {
const rowBg = "bg-[color-mix(in_srgb,var(--muted)_40%,var(--card))]";
const cell = "text-right px-3 py-2.5 tabular-nums";
return (
<tr key="uncategorized" className={`border-b border-[var(--border)] font-semibold text-sm ${rowBg}`}>
<td className={`px-3 py-2.5 sticky left-0 z-10 ${rowBg}`}>{t("reports.uncategorized")}</td>
<td className={`${cell} border-l border-[var(--border)]/50`}>{formatCurrency(tot.monthCurrent, lang)}</td>
<td className={cell}>{formatCurrency(tot.monthPrevious, lang)}</td>
<td className={cell}>{formatSignedCurrency(tot.monthDelta, lang)}</td>
<td className={cell}>{formatPct(pct(tot.monthDelta, tot.monthPrevious), lang)}</td>
<td className={`${cell} border-l border-[var(--border)]/50`}>{formatCurrency(tot.ytdCurrent, lang)}</td>
<td className={cell}>{formatCurrency(tot.ytdPrevious, lang)}</td>
<td className={cell}>{formatSignedCurrency(tot.ytdDelta, lang)}</td>
<td className={cell}>{formatPct(pct(tot.ytdDelta, tot.ytdPrevious), lang)}</td>
</tr>
);
};
// A result line (before-transfers subtotal or the net total). Higher is always // A result line (before-transfers subtotal or the net total). Higher is always
// better here: amounts are coloured by sign (surplus green / deficit red) and // better here: amounts are coloured by sign (surplus green / deficit red) and
// deltas by improvement. // deltas by improvement.
@ -430,9 +453,11 @@ export default function ComparePeriodTable({
) : ( ) : (
<> <>
{nonTransferSections.map(renderSection)} {nonTransferSections.map(renderSection)}
{/* Operating result (revenues − expenses), shown before the {results.hasUncategorized && renderUncategorizedRow(results.uncategorized)}
transfers section only when transfers exist — otherwise it {/* Operating result (revenues − expenses + uncategorized), shown
equals the net total below and would just be noise. */} before the transfers section only when transfers exist —
otherwise it equals the net total below and would just be
noise. */}
{results.hasTransfers && {results.hasTransfers &&
renderResultRow( renderResultRow(
"reports.compare.resultBeforeTransfers", "reports.compare.resultBeforeTransfers",

View file

@ -8,7 +8,7 @@ import { computeResults, sumLeaves } from "./budgetVsActualResults";
// user-entered budget negated to match via signFor); income/transfer stay // user-entered budget negated to match via signFor); income/transfer stay
// however they naturally sum (positive for income, signed net for transfer). // however they naturally sum (positive for income, signed net for transfer).
function leaf( function leaf(
type: "expense" | "income" | "transfer", type: "expense" | "income" | "transfer" | "uncategorized",
monthActual: number, monthActual: number,
monthBudget: number, monthBudget: number,
ytdActual = monthActual, ytdActual = monthActual,
@ -88,4 +88,20 @@ describe("computeResults — income-statement roll-up (Issue #277)", () => {
expect(t.monthActual).toBe(-100); expect(t.monthActual).toBe(-100);
expect(t.monthBudget).toBe(-50); expect(t.monthBudget).toBe(-50);
}); });
it("counts the uncategorized line in both results, without a budget (#392, D4)", () => {
const r = computeResults([
leaf("income", 1000, 1000),
leaf("expense", -30, -130),
{ ...leaf("uncategorized", 40, 0), category_id: null },
leaf("transfer", -300, 0),
]);
expect(r.uncategorized.monthActual).toBe(40);
expect(r.uncategorized.monthBudget).toBe(0);
// 1000 + (−30) + 40, then the one-leg transfer.
expect(r.resultBefore.monthActual).toBe(1010);
expect(r.resultNet.monthActual).toBe(710);
expect(r.resultBefore.monthBudget).toBe(870);
expect(r.hasUncategorized).toBe(true);
});
}); });

View file

@ -1,6 +1,6 @@
import type { BudgetVsActualRow } from "../../shared/types"; import type { BudgetVsActualRow, ReportSection } from "../../shared/types";
export type SectionType = "expense" | "income" | "transfer"; export type SectionType = ReportSection;
/** Aggregate of the 6 budget-vs-actual figures across a set of leaf rows. */ /** Aggregate of the 6 budget-vs-actual figures across a set of leaf rows. */
export interface Totals { export interface Totals {
@ -59,37 +59,49 @@ function add(a: Totals, b: Totals): Totals {
export interface BudgetVsActualResults { export interface BudgetVsActualResults {
income: Totals; income: Totals;
expense: Totals; expense: Totals;
/** The uncategorized line (D4, #392): actuals only, in the result. */
uncategorized: Totals;
transfer: Totals; transfer: Totals;
/** Income + expense: the operating result, before transfers. */ /** Income + expense + uncategorized: the operating result, before transfers. */
resultBefore: Totals; resultBefore: Totals;
/** resultBefore + transfers: the bottom-line total. */ /** resultBefore + transfers: the bottom-line total. */
resultNet: Totals; resultNet: Totals;
hasTransfers: boolean; hasTransfers: boolean;
hasUncategorized: boolean;
} }
/** /**
* Income-statement roll-up for the budget-vs-actual report (Issue #277). * Income-statement roll-up for the budget-vs-actual report (Issue #277).
* *
* Mirrors `compareResults.computeResults`, with one key sign difference: BVA * Mirrors `compareResults.computeResults`, with one key sign difference: BVA
* amounts already arrive signed the "accounting" way rather than ABS'd to * amounts stay signed the "accounting" way (ADR 0026). `getBudgetVsActualData`
* positive magnitudes. `getBudgetVsActualData` computes `monthActual`/ * computes `monthActual`/`ytdActual` as the signed balance of the category —
* `ytdActual` as the raw (unsigned-by-us) `SUM(transactions.amount)` — negative * negative for an expense category that spent, since expense transactions are
* for expense categories, since expense transactions are stored as negative * stored as negative amounts throughout this app — and negates the
* amounts throughout this app (see reportService/dashboardService `amount < 0` * user-entered (positive) budget figure to match via `signFor`. So expense
* conventions) — and negates the user-entered (positive) budget figure to * totals here are ≤ 0 when the category spent, and the operating result is a
* match via `signFor`. So expense totals here are already ≤ 0, and the * straight ADD of income + expense + uncategorized (not a subtraction like the
* operating result is a straight ADD of income + expense (not a subtraction * real-vs-real compare, whose expense figures show the spending). The net
* like the real-vs-real compare, whose expense figures are ABS'd positive * just adds the transfer total on top.
* magnitudes). The net just adds the transfer total on top.
*/ */
export function computeResults(rows: BudgetVsActualRow[]): BudgetVsActualResults { export function computeResults(rows: BudgetVsActualRow[]): BudgetVsActualResults {
const byType = (type: SectionType): Totals => const byType = (type: SectionType): Totals =>
sumLeaves(rows.filter((r) => r.category_type === type)); sumLeaves(rows.filter((r) => r.category_type === type));
const income = byType("income"); const income = byType("income");
const expense = byType("expense"); const expense = byType("expense");
const uncategorized = byType("uncategorized");
const transfer = byType("transfer"); const transfer = byType("transfer");
const resultBefore = add(income, expense); const resultBefore = add(add(income, expense), uncategorized);
const resultNet = add(resultBefore, transfer); const resultNet = add(resultBefore, transfer);
const hasTransfers = rows.some((r) => r.category_type === "transfer" && !r.is_parent); const has = (type: SectionType) => rows.some((r) => r.category_type === type && !r.is_parent);
return { income, expense, transfer, resultBefore, resultNet, hasTransfers }; return {
income,
expense,
uncategorized,
transfer,
resultBefore,
resultNet,
hasTransfers: has("transfer"),
hasUncategorized: has("uncategorized"),
};
} }

View file

@ -2,10 +2,11 @@ import { describe, it, expect } from "vitest";
import type { CategoryDelta } from "../../shared/types"; import type { CategoryDelta } from "../../shared/types";
import { computeResults, sumLeaves } from "./compareResults"; import { computeResults, sumLeaves } from "./compareResults";
// Minimal leaf factory. Amounts arrive from COMPARE_DELTA_SQL already in the // Minimal leaf factory. Amounts arrive from rowsToDeltas in the sign
// per-type sign convention (expenses = positive ABS, income/transfer = signed). // convention of the reports (ADR 0026): an expense shows its spending (the
// opposite of its balance), every other section its signed balance.
function leaf( function leaf(
type: "expense" | "income" | "transfer", type: "expense" | "income" | "transfer" | "uncategorized",
mc: number, mc: number,
mp: number, mp: number,
cc = mc, cc = mc,
@ -84,4 +85,29 @@ describe("computeResults — income-statement roll-up (Issue #253)", () => {
expect(t.monthCurrent).toBe(100); expect(t.monthCurrent).toBe(100);
expect(t.monthPrevious).toBe(50); expect(t.monthPrevious).toBe(50);
}); });
it("counts the uncategorized line in both results, neither income nor expense (#392, D4)", () => {
const r = computeResults([
leaf("income", 1000, 1000),
leaf("expense", 30, 30),
leaf("uncategorized", 40, 0),
leaf("transfer", -300, 0),
]);
expect(r.income.monthCurrent).toBe(1000);
expect(r.expense.monthCurrent).toBe(30);
expect(r.uncategorized.monthCurrent).toBe(40);
// 1000 − 30 + 40, then the one-leg transfer.
expect(r.resultBefore.monthCurrent).toBe(1010);
expect(r.resultNet.monthCurrent).toBe(710);
expect(r.resultBefore.monthDelta).toBe(40);
expect(r.hasUncategorized).toBe(true);
expect(r.hasTransfers).toBe(true);
});
it("adds a negative expense back to the result: refunds above purchases (#392, D1)", () => {
const r = computeResults([leaf("income", 1000, 1000), leaf("expense", 80, 80), leaf("expense", -50, 0)]);
expect(r.expense.monthCurrent).toBe(30);
expect(r.resultNet.monthCurrent).toBe(970);
expect(r.hasUncategorized).toBe(false);
});
}); });

View file

@ -1,6 +1,6 @@
import type { CategoryDelta } from "../../shared/types"; import type { CategoryDelta, ReportSection } from "../../shared/types";
export type SectionType = "expense" | "income" | "transfer"; export type SectionType = ReportSection;
/** Aggregate of the 6 comparable figures across a set of leaf rows. */ /** Aggregate of the 6 comparable figures across a set of leaf rows. */
export interface Totals { export interface Totals {
@ -57,34 +57,46 @@ function combine(a: Totals, b: Totals, sign: 1 | -1): Totals {
export interface CompareResults { export interface CompareResults {
income: Totals; income: Totals;
expense: Totals; expense: Totals;
/** The uncategorized line (D4): neither income nor expense, in the result. */
uncategorized: Totals;
transfer: Totals; transfer: Totals;
/** Revenues − expenses: the operating result, before transfers. */ /** Revenues − expenses + uncategorized: the operating result, before transfers. */
resultBefore: Totals; resultBefore: Totals;
/** resultBefore + net transfers: the bottom-line total. */ /** resultBefore + net transfers: the bottom-line total, every amount of the period. */
resultNet: Totals; resultNet: Totals;
hasTransfers: boolean; hasTransfers: boolean;
hasUncategorized: boolean;
} }
/** /**
* Income-statement roll-up for the real-vs-real compare (Issue #253). * Income-statement roll-up for the real-vs-real compare (Issue #253, ADR 0026).
* *
* Sign convention flowing in from COMPARE_DELTA_SQL: expenses are positive * Sign convention flowing in from rowsToDeltas: each category shows its signed
* magnitudes (ABS of outflows), income is a signed SUM (positive), transfers a * balance, an expense its spending (the opposite of its balance, refunds
* signed net (~0 when balanced). So the operating result is a straight * netted, negative when refunds exceed purchases), transfers a signed net (0
* `income − expense`, and the net adds the (usually ~0) transfer total. When a * when balanced). So the operating result is `income − expense +
* transfer is unbalanced (a single leg categorised) its residual shows up as * uncategorized`, and the net adds the transfer total. When a transfer is
* the gap between resultBefore and resultNet. * unbalanced (a single leg categorised) its residual shows up as the gap
* between resultBefore and resultNet.
*/ */
export function computeResults(rows: CategoryDelta[]): CompareResults { export function computeResults(rows: CategoryDelta[]): CompareResults {
const byType = (type: SectionType): Totals => const typeOf = (r: CategoryDelta): SectionType => r.category_type ?? "expense";
sumLeaves(rows.filter((r) => (r.category_type ?? "expense") === type)); const byType = (type: SectionType): Totals => sumLeaves(rows.filter((r) => typeOf(r) === type));
const income = byType("income"); const income = byType("income");
const expense = byType("expense"); const expense = byType("expense");
const uncategorized = byType("uncategorized");
const transfer = byType("transfer"); const transfer = byType("transfer");
const resultBefore = combine(income, expense, -1); const resultBefore = combine(combine(income, expense, -1), uncategorized, 1);
const resultNet = combine(resultBefore, transfer, 1); const resultNet = combine(resultBefore, transfer, 1);
const hasTransfers = rows.some( const has = (type: SectionType) => rows.some((r) => typeOf(r) === type && !r.is_parent);
(r) => (r.category_type ?? "expense") === "transfer" && !r.is_parent, return {
); income,
return { income, expense, transfer, resultBefore, resultNet, hasTransfers }; expense,
uncategorized,
transfer,
resultBefore,
resultNet,
hasTransfers: has("transfer"),
hasUncategorized: has("uncategorized"),
};
} }

View file

@ -7,7 +7,7 @@ function leaf(
categoryId: number | null, categoryId: number | null,
categoryName: string, categoryName: string,
monthly: number[], monthly: number[],
category_type: "income" | "expense" | "transfer", category_type: "income" | "expense" | "transfer" | "uncategorized",
extra: Partial<OverTimeRow> = {}, extra: Partial<OverTimeRow> = {},
): OverTimeRow { ): OverTimeRow {
return { return {
@ -192,4 +192,42 @@ describe("computeOverTimeResults", () => {
expect(r.net.monthly).toEqual({ "2025-01": 1000, "2025-02": 1500 }); expect(r.net.monthly).toEqual({ "2025-01": 1000, "2025-02": 1500 });
expect(r.net.total).toBe(2500); expect(r.net.total).toBe(2500);
}); });
it("keeps the uncategorized line out of the sections and in both results (#392, D4)", () => {
const data = makeData(
["2025-01", "2025-02"],
[
leaf(1, "Salary", [1000, 1000], "income"),
leaf(2, "Groceries", [80, 80], "expense"),
leaf(null, "Uncategorized", [40, -10], "uncategorized"),
leaf(4, "Card", [-300, 0], "transfer"),
],
);
const r = computeOverTimeResults(data);
expect(r.sections.map((s) => s.type)).toEqual(["income", "expense", "transfer"]);
expect(r.hasUncategorized).toBe(true);
expect(r.uncategorized.monthly).toEqual({ "2025-01": 40, "2025-02": -10 });
expect(r.uncategorized.total).toBe(30);
// income − expense + uncategorized
expect(r.beforeTransfers.monthly).toEqual({ "2025-01": 960, "2025-02": 910 });
// … + the signed one-leg transfer
expect(r.net.monthly).toEqual({ "2025-01": 660, "2025-02": 910 });
expect(r.net.total).toBe(1570);
});
it("adds a negative expense back: a category whose refunds exceed its purchases (#392, D1)", () => {
const data = makeData(
["2025-01"],
[leaf(1, "Salary", [1000], "income"), leaf(2, "Groceries", [80], "expense"), leaf(3, "Butcher", [-50], "expense")],
);
const r = computeOverTimeResults(data);
expect(r.sections.find((s) => s.type === "expense")!.total).toBe(30);
expect(r.net.total).toBe(970);
expect(r.hasUncategorized).toBe(false);
expect(r.uncategorized.total).toBe(0);
});
}); });

View file

@ -1,4 +1,5 @@
import type { CategoryOverTimeData, OverTimeRow } from "../../shared/types"; import type { CategoryOverTimeData, OverTimeRow } from "../../shared/types";
import { toCents } from "../../utils/incomeStatement";
export type OverTimeType = "income" | "expense" | "transfer"; export type OverTimeType = "income" | "expense" | "transfer";
@ -43,24 +44,33 @@ export interface OverTimeAnalysis {
sections: OverTimeSection[]; sections: OverTimeSection[];
/** True when at least one visible transfer-type category is present. */ /** True when at least one visible transfer-type category is present. */
hasTransfers: boolean; hasTransfers: boolean;
/** Income − Expenses + Transfers, per month (+ grand total). */ /**
* The uncategorized line (D4, #392), per month (+ grand total): neither
* income nor expense, counted in both results. Not a section: the table
* shows it on one line.
*/
uncategorized: OverTimeSeries;
/** True when the tree holds the uncategorized row. */
hasUncategorized: boolean;
/** Income − Expenses + Uncategorized + Transfers, per month (+ grand total). */
net: OverTimeSeries; net: OverTimeSeries;
/** Income − Expenses, per month (+ grand total). Only shown when `hasTransfers`. */ /** Income − Expenses + Uncategorized, per month (+ grand total). Only shown when `hasTransfers`. */
beforeTransfers: OverTimeSeries; beforeTransfers: OverTimeSeries;
} }
/** /**
* Pure reducer that turns the category-over-time report into an "income * Pure reducer that turns the category-over-time report into an "income
* statement" shape: per-type sections with per-month subtotals, plus the * statement" shape: per-type sections with per-month subtotals, the
* net-result rows. * uncategorized line, plus the net-result rows.
* *
* Consumes the **id-keyed tree** (`data.tree`) — NOT the name-keyed pivot — so * Consumes the **id-keyed tree** (`data.tree`) — NOT the name-keyed pivot — so
* two homonym categories of different types never collide: each leaf carries its * two homonym categories of different types never collide: each leaf carries its
* own `category_id`-resolved `category_type`, and the subtotals + result lines * own `category_id`-resolved `category_type`, and the subtotals + result lines
* are summed over the tree's LEAVES only (never its `is_parent` subtotal rows, * are summed over the tree's LEAVES only (never its `is_parent` subtotal rows,
* which would double-count their own descendants). Leaf `monthly[]` values are * which would double-count their own descendants). Leaf `monthly[]` values are
* positive magnitudes (`ABS(SUM())` in SQL), so income/expense/transfer * what each category shows (ADR 0026): its signed balance, an expense its
* subtotals are all ≥ 0 and the net is `income − expense + transfer`. * spending (negative when refunds exceed purchases), a transfer its signed net.
* So the net is `income − expense + uncategorized + transfer`.
* *
* The tree is already ordered income → expense → transfer, so section ordering * The tree is already ordered income → expense → transfer, so section ordering
* falls out of the leaves' own `category_type`. * falls out of the leaves' own `category_type`.
@ -70,47 +80,57 @@ export function computeOverTimeResults(data: CategoryOverTimeData): OverTimeAnal
// Leaves only — subtotals (`is_parent`) are excluded so a parent group can // Leaves only — subtotals (`is_parent`) are excluded so a parent group can
// never double-count against its own descendants. // never double-count against its own descendants.
const typeOf = (row: OverTimeRow): OverTimeType => { const typeOf = (row: OverTimeRow): OverTimeType | "uncategorized" => {
const t = row.category_type; const t = row.category_type;
return t === "income" || t === "transfer" ? t : "expense"; return t === "income" || t === "transfer" || t === "uncategorized" ? t : "expense";
};
const byType: Record<OverTimeType | "uncategorized", OverTimeRow[]> = {
income: [],
expense: [],
uncategorized: [],
transfer: [],
}; };
const byType: Record<OverTimeType, OverTimeRow[]> = { income: [], expense: [], transfer: [] };
for (const row of data.tree) { for (const row of data.tree) {
if (!row.is_parent) byType[typeOf(row)].push(row); if (!row.is_parent) byType[typeOf(row)].push(row);
} }
const buildSection = (type: OverTimeType): OverTimeSection => { const seriesOf = (rows: OverTimeRow[]): OverTimeSeries => {
const rows = byType[type];
const monthly: Record<string, number> = {}; const monthly: Record<string, number> = {};
let total = 0; let total = 0;
months.forEach((month, i) => { months.forEach((month, i) => {
const sum = rows.reduce((s, row) => s + (row.monthly[i] ?? 0), 0); const sum = toCents(rows.reduce((s, row) => s + (row.monthly[i] ?? 0), 0));
monthly[month] = sum; monthly[month] = sum;
total += sum; total = toCents(total + sum);
}); });
return { type, rows, monthly, total }; return { monthly, total };
};
const buildSection = (type: OverTimeType): OverTimeSection => {
const rows = byType[type];
return { type, rows, ...seriesOf(rows) };
}; };
const income = buildSection("income"); const income = buildSection("income");
const expense = buildSection("expense"); const expense = buildSection("expense");
const transfer = buildSection("transfer"); const transfer = buildSection("transfer");
const uncategorized = seriesOf(byType.uncategorized);
const hasTransfers = transfer.rows.length > 0; const hasTransfers = transfer.rows.length > 0;
const hasUncategorized = byType.uncategorized.length > 0;
const net: OverTimeSeries = { monthly: {}, total: 0 }; const net: OverTimeSeries = { monthly: {}, total: 0 };
const beforeTransfers: OverTimeSeries = { monthly: {}, total: 0 }; const beforeTransfers: OverTimeSeries = { monthly: {}, total: 0 };
for (const month of months) { for (const month of months) {
const before = income.monthly[month] - expense.monthly[month]; const before = toCents(income.monthly[month] - expense.monthly[month] + uncategorized.monthly[month]);
const netMonth = before + transfer.monthly[month]; const netMonth = toCents(before + transfer.monthly[month]);
beforeTransfers.monthly[month] = before; beforeTransfers.monthly[month] = before;
beforeTransfers.total += before; beforeTransfers.total = toCents(beforeTransfers.total + before);
net.monthly[month] = netMonth; net.monthly[month] = netMonth;
net.total += netMonth; net.total = toCents(net.total + netMonth);
} }
const sections = [income, expense, transfer] const sections = [income, expense, transfer]
.filter((s) => s.rows.length > 0) .filter((s) => s.rows.length > 0)
.sort((a, b) => OVER_TIME_TYPE_ORDER[a.type] - OVER_TIME_TYPE_ORDER[b.type]); .sort((a, b) => OVER_TIME_TYPE_ORDER[a.type] - OVER_TIME_TYPE_ORDER[b.type]);
return { months, sections, hasTransfers, net, beforeTransfers }; return { months, sections, hasTransfers, uncategorized, hasUncategorized, net, beforeTransfers };
} }

View file

@ -8,7 +8,7 @@ import {
groupOverTimeSections, groupOverTimeSections,
} from "./overTimeTableModel"; } from "./overTimeTableModel";
type RowType = "income" | "expense" | "transfer"; type RowType = "income" | "expense" | "transfer" | "uncategorized";
/** Builds one id-keyed tree row; `monthly` is index-aligned to the months list. */ /** Builds one id-keyed tree row; `monthly` is index-aligned to the months list. */
function mkRow( function mkRow(
@ -141,6 +141,18 @@ describe("overTimeTableModel.groupOverTimeSections", () => {
expect(expense.total).toBe(3300); expect(expense.total).toBe(3300);
}); });
it("leaves the uncategorized row out of every section (#392): the table shows it on one line", () => {
const tree = [...buildTree(), mkRow(0, "Uncategorized", [40, 0], "uncategorized", { categoryId: null })];
const data = makeData(MONTHS, tree);
const analysis = computeOverTimeResults(data);
const { nonTransferSections, transferSection } = groupOverTimeSections(analysis, data.tree);
const sectionRows = [...nonTransferSections, transferSection!].flatMap((s) => s.rows);
expect(sectionRows.some((r) => r.category_type === "uncategorized")).toBe(false);
expect(nonTransferSections.find((s) => s.type === "expense")!.total).toBe(3300);
expect(analysis.uncategorized.total).toBe(40);
});
it("drops empty sections: no transfers → transferSection is null", () => { it("drops empty sections: no transfers → transferSection is null", () => {
const tree = buildTree().filter((r) => r.category_type !== "transfer"); const tree = buildTree().filter((r) => r.category_type !== "transfer");
const data = makeData(MONTHS, tree); const data = makeData(MONTHS, tree);

View file

@ -45,8 +45,10 @@ export interface OverTimeRenderSection {
total: number; total: number;
} }
const typeOf = (row: OverTimeRow): OverTimeType => { const typeOf = (row: OverTimeRow): OverTimeType | null => {
const t = row.category_type; const t = row.category_type;
// The uncategorized row is no section: the table shows it on one line (#392).
if (t === "uncategorized") return null;
return t === "income" || t === "transfer" ? t : "expense"; return t === "income" || t === "transfer" ? t : "expense";
}; };
@ -74,7 +76,10 @@ export function groupOverTimeSections(
expense: [], expense: [],
transfer: [], transfer: [],
}; };
for (const row of tree) rowsByType[typeOf(row)].push(row); for (const row of tree) {
const type = typeOf(row);
if (type) rowsByType[type].push(row);
}
const sections: OverTimeRenderSection[] = analysis.sections.map((s) => ({ const sections: OverTimeRenderSection[] = analysis.sections.map((s) => ({
type: s.type, type: s.type,

View file

@ -0,0 +1,157 @@
// The uncategorized line of the three income-statement tables (#392, D4):
// one line « Non classé », after the expenses and before the result before
// transfers, never a category row named by the SQL's 'Uncategorized'. No
// jsdom: react-dom/server renders the markup, effects do not run.
import { describe, it, expect, vi, beforeAll } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
// The collapse state is read from the profile in an effect, which never runs here.
vi.mock("../../services/userPreferenceService", () => ({
getPreference: vi.fn(async () => null),
setPreference: vi.fn(async () => undefined),
}));
import ComparePeriodTable from "./ComparePeriodTable";
import BudgetVsActualTable from "./BudgetVsActualTable";
import CategoryOverTimeTable from "./CategoryOverTimeTable";
import type { BudgetVsActualRow, CategoryDelta, OverTimeRow, ReportSection } from "../../shared/types";
beforeAll(() => {
// Where the tables keep the position of their subtotals.
vi.stubGlobal("localStorage", { getItem: () => null, setItem: () => undefined });
});
const LINE = "t(reports.uncategorized)";
/** The markers appear in this order in the markup, each exactly once. */
function expectOrder(html: string, ...markers: string[]) {
for (const marker of markers) expect(html.split(marker).length - 1, marker).toBe(1);
const positions = markers.map((marker) => html.indexOf(marker));
expect(positions).toEqual([...positions].sort((a, b) => a - b));
}
const delta = (type: ReportSection, categoryId: number | null, amount: number): CategoryDelta => ({
categoryId,
categoryName: categoryId === null ? "Uncategorized" : `C${categoryId}`,
categoryColor: "#000",
previousAmount: 0,
currentAmount: amount,
deltaAbs: amount,
deltaPct: null,
cumulativePreviousAmount: 0,
cumulativeCurrentAmount: amount,
cumulativeDeltaAbs: amount,
cumulativeDeltaPct: null,
parent_id: null,
is_parent: false,
depth: 0,
category_type: type,
});
describe("ComparePeriodTable", () => {
it("shows the uncategorized line between the expenses and the result before transfers", () => {
const html = renderToStaticMarkup(
<ComparePeriodTable
rows={[
delta("income", 1, 1000),
delta("expense", 2, 30),
delta("uncategorized", null, 40),
delta("transfer", 3, -300),
]}
previousLabel="Sept."
currentLabel="Oct."
/>,
);
expectOrder(
html,
"t(reports.compare.totalExpenses)",
LINE,
"t(reports.compare.resultBeforeTransfers)",
"t(reports.compare.totalTransfers)",
"t(reports.compare.resultNet)",
);
expect(html).not.toContain(">Uncategorized<");
});
it("shows no such line without uncategorized rows", () => {
const html = renderToStaticMarkup(
<ComparePeriodTable rows={[delta("income", 1, 1000), delta("expense", 2, 30)]} previousLabel="" currentLabel="" />,
);
expect(html).not.toContain(LINE);
});
});
describe("BudgetVsActualTable", () => {
const row = (type: ReportSection, categoryId: number | null, actual: number, budget = 0): BudgetVsActualRow => ({
category_id: categoryId,
category_name: categoryId === null ? "" : `C${categoryId}`,
category_color: "#000",
category_type: type,
parent_id: null,
is_parent: false,
depth: 0,
monthActual: actual,
monthBudget: budget,
monthVariation: actual - budget,
monthVariationPct: null,
ytdActual: actual,
ytdBudget: budget,
ytdVariation: actual - budget,
ytdVariationPct: null,
});
it("shows the uncategorized line between the expenses and the result before transfers", () => {
const html = renderToStaticMarkup(
<BudgetVsActualTable
data={[row("income", 1, 1000), row("expense", 2, -30, -100), row("uncategorized", null, 40), row("transfer", 3, -300)]}
/>,
);
expectOrder(
html,
"t(budget.totalExpenses)",
LINE,
"t(reports.compare.resultBeforeTransfers)",
"t(budget.totalTransfers)",
"t(reports.compare.resultNet)",
);
});
});
describe("CategoryOverTimeTable", () => {
const leaf = (type: ReportSection, categoryId: number | null, value: number): OverTimeRow => ({
categoryId,
categoryName: categoryId === null ? "Uncategorized" : `C${categoryId}`,
categoryColor: "#000",
monthly: [value],
total: value,
parent_id: null,
is_parent: false,
depth: 0,
category_type: type,
});
it("shows the uncategorized line between the expenses and the result before transfers", () => {
const html = renderToStaticMarkup(
<CategoryOverTimeTable
data={{
categories: [],
data: [{ month: "2026-10" }],
colors: {},
categoryIds: {},
types: {},
tree: [leaf("income", 1, 1000), leaf("expense", 2, 30), leaf("uncategorized", null, 40), leaf("transfer", 3, -300)],
}}
/>,
);
expectOrder(
html,
"t(reports.compare.totalExpenses)",
LINE,
"t(reports.compare.resultBeforeTransfers)",
"t(reports.compare.totalTransfers)",
"t(reports.compare.resultNet)",
);
expect(html).not.toContain(">Uncategorized<");
});
});

View file

@ -704,6 +704,7 @@
"noData": "No data for this period", "noData": "No data for this period",
"importCta": "Import a statement" "importCta": "Import a statement"
}, },
"uncategorized": "Uncategorized",
"help": { "help": {
"title": "How to use Reports", "title": "How to use Reports",
"tips": [ "tips": [

View file

@ -704,6 +704,7 @@
"noData": "Aucune donnée pour cette période", "noData": "Aucune donnée pour cette période",
"importCta": "Importer un relevé" "importCta": "Importer un relevé"
}, },
"uncategorized": "Non classé",
"help": { "help": {
"title": "Comment utiliser les Rapports", "title": "Comment utiliser les Rapports",
"tips": [ "tips": [

View file

@ -3,6 +3,7 @@ import { getDb } from "./db";
import { notifyDataChanged } from "./dataEvents"; import { notifyDataChanged } from "./dataEvents";
import { inPlaceholders } from "../utils/sqlFilters"; import { inPlaceholders } from "../utils/sqlFilters";
import { displaysAsRoot } from "../utils/categoryHierarchy"; import { displaysAsRoot } from "../utils/categoryHierarchy";
import { CATEGORY_JOIN_SQL, SECTION_ORDER, toCents } from "../utils/incomeStatement";
import type { import type {
Category, Category,
BudgetEntry, BudgetEntry,
@ -216,6 +217,12 @@ export async function getActualTotalsForYear(
// --- Budget vs Actual --- // --- Budget vs Actual ---
/**
* The signed balance of each category over the range, splits and refunds
* included (#392, ADR 0026). Every row without an existing category (no
* category, or one that is gone) is one group, `category_id` NULL: the
* uncategorized line.
*/
async function getActualsByCategoryRange( async function getActualsByCategoryRange(
dateFrom: string, dateFrom: string,
dateTo: string, dateTo: string,
@ -224,20 +231,23 @@ async function getActualsByCategoryRange(
const db = await getDb(); const db = await getDb();
const params: unknown[] = [dateFrom, dateTo]; const params: unknown[] = [dateFrom, dateTo];
const accountPlaceholders = inPlaceholders(accountIds, params.length + 1); const accountPlaceholders = inPlaceholders(accountIds, params.length + 1);
const accountFilter = accountPlaceholders ? ` AND source_id IN (${accountPlaceholders})` : ""; const accountFilter = accountPlaceholders ? ` AND t.source_id IN (${accountPlaceholders})` : "";
if (accountPlaceholders) params.push(...accountIds!); if (accountPlaceholders) params.push(...accountIds!);
return db.select<Array<{ category_id: number | null; actual: number }>>( const rows = await db.select<Array<{ category_id: number | null; actual: number | null }>>(
`SELECT category_id, COALESCE(SUM(amount), 0) AS actual `SELECT c.id AS category_id, COALESCE(SUM(t.amount), 0) AS actual
FROM transactions FROM transactions t
WHERE date BETWEEN $1 AND $2${accountFilter} ${CATEGORY_JOIN_SQL}
GROUP BY category_id`, WHERE t.date BETWEEN $1 AND $2${accountFilter}
GROUP BY c.id`,
params params
); );
return rows.map((r) => ({ category_id: r.category_id, actual: toCents(Number(r.actual ?? 0)) }));
} }
// Income-statement reading order: revenue first, then expenses, then // Income-statement reading order: revenue first, then expenses, the
// transfers (Issue #277 — matches COMPARE_TYPE_ORDER / OVER_TIME_TYPE_ORDER). // uncategorized line, then transfers (Issue #277, ADR 0026 — matches
const TYPE_ORDER: Record<string, number> = { income: 0, expense: 1, transfer: 2 }; // COMPARE_TYPE_ORDER / OVER_TIME_TYPE_ORDER).
const TYPE_ORDER: Record<string, number> = SECTION_ORDER;
/** /**
* Budget vs actual, by category, for the reference month plus YTD. `accountIds` * Budget vs actual, by category, for the reference month plus YTD. `accountIds`
@ -271,13 +281,17 @@ export async function getBudgetVsActualData(
} }
const monthActualMap = new Map<number, number>(); const monthActualMap = new Map<number, number>();
let monthUncategorized = 0;
for (const a of monthActuals) { for (const a of monthActuals) {
if (a.category_id != null) monthActualMap.set(a.category_id, a.actual); if (a.category_id != null) monthActualMap.set(a.category_id, a.actual);
else monthUncategorized = a.actual;
} }
const ytdActualMap = new Map<number, number>(); const ytdActualMap = new Map<number, number>();
let ytdUncategorized = 0;
for (const a of ytdActuals) { for (const a of ytdActuals) {
if (a.category_id != null) ytdActualMap.set(a.category_id, a.actual); if (a.category_id != null) ytdActualMap.set(a.category_id, a.actual);
else ytdUncategorized = a.actual;
} }
// Index categories // Index categories
@ -459,6 +473,28 @@ export async function getBudgetVsActualData(
} }
} }
// The uncategorized line (D4, #392): its actuals, no budget, counted in the
// result lines but neither income nor expense. Its label comes from the UI.
if (monthUncategorized !== 0 || ytdUncategorized !== 0) {
rows.push({
category_id: null,
category_name: "",
category_color: "#9ca3af",
category_type: "uncategorized",
parent_id: null,
is_parent: false,
depth: 0,
monthActual: monthUncategorized,
monthBudget: 0,
monthVariation: monthUncategorized,
monthVariationPct: null,
ytdActual: ytdUncategorized,
ytdBudget: 0,
ytdVariation: ytdUncategorized,
ytdVariationPct: null,
});
}
// Sort by type only, preserving tree order within groups (already built correctly) // Sort by type only, preserving tree order within groups (already built correctly)
const rowOrder = new Map<BudgetVsActualRow, number>(); const rowOrder = new Map<BudgetVsActualRow, number>();
rows.forEach((r, i) => rowOrder.set(r, i)); rows.forEach((r, i) => rowOrder.set(r, i));

View file

@ -60,7 +60,7 @@ describe("getExpensesByCategory — accountIds filter (Issue #273)", () => {
const sql = mockSelect.mock.calls[0][0] as string; const sql = mockSelect.mock.calls[0][0] as string;
const params = mockSelect.mock.calls[0][1] as unknown[]; const params = mockSelect.mock.calls[0][1] as unknown[];
expect(sql).toContain("t.source_id IN ($1)"); expect(sql).toContain("t.source_id IN ($1)");
expect(sql).toContain("COALESCE(c.type, 'expense') = 'expense'"); expect(sql).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END = 'expense'");
expect(params).toEqual([2]); expect(params).toEqual([2]);
}); });
}); });

View file

@ -1,59 +1,20 @@
import { getDb } from "./db"; import { getDb } from "./db";
import { inPlaceholders } from "../utils/sqlFilters"; import { inPlaceholders } from "../utils/sqlFilters";
import { CATEGORY_JOIN_SQL, SECTION_SQL, orient } from "../utils/incomeStatement";
import { deriveLandingState } from "../components/balance/balanceLanding"; import { deriveLandingState } from "../components/balance/balanceLanding";
import type { SnapshotTotalPoint } from "./balance.service"; import type { SnapshotTotalPoint } from "./balance.service";
import type { import type {
DashboardSummary,
CategoryBreakdownItem, CategoryBreakdownItem,
RecentTransaction, RecentTransaction,
TransactionRow, TransactionRow,
} from "../shared/types"; } from "../shared/types";
export async function getDashboardSummary( /**
dateFrom?: string, * The spending of each expense category over the period, largest first: the
dateTo?: string * opposite of its signed balance, refunds and splits netted (#392, ADR 0026),
): Promise<DashboardSummary> { * negative for a category whose refunds exceed its purchases. The rows
const db = await getDb(); * without a category are no expense: they stay out (D4).
*/
const whereClauses: string[] = [];
const params: unknown[] = [];
let paramIndex = 1;
if (dateFrom) {
whereClauses.push(`date >= $${paramIndex}`);
params.push(dateFrom);
paramIndex++;
}
if (dateTo) {
whereClauses.push(`date <= $${paramIndex}`);
params.push(dateTo);
paramIndex++;
}
const whereSQL =
whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
const rows = await db.select<
Array<{
totalCount: number;
totalAmount: number;
incomeTotal: number;
expenseTotal: number;
}>
>(
`SELECT
COUNT(*) AS totalCount,
COALESCE(SUM(amount), 0) AS totalAmount,
COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) AS incomeTotal,
COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0) AS expenseTotal
FROM transactions
${whereSQL}`,
params
);
return rows[0] ?? { totalCount: 0, totalAmount: 0, incomeTotal: 0, expenseTotal: 0 };
}
export async function getExpensesByCategory( export async function getExpensesByCategory(
dateFrom?: string, dateFrom?: string,
dateTo?: string, dateTo?: string,
@ -61,7 +22,7 @@ export async function getExpensesByCategory(
): Promise<CategoryBreakdownItem[]> { ): Promise<CategoryBreakdownItem[]> {
const db = await getDb(); const db = await getDb();
const whereClauses: string[] = ["COALESCE(c.type, 'expense') = 'expense'"]; const whereClauses: string[] = [`${SECTION_SQL} = 'expense'`];
const params: unknown[] = []; const params: unknown[] = [];
let paramIndex = 1; let paramIndex = 1;
@ -84,19 +45,27 @@ export async function getExpensesByCategory(
const whereSQL = `WHERE ${whereClauses.join(" AND ")}`; const whereSQL = `WHERE ${whereClauses.join(" AND ")}`;
return db.select<CategoryBreakdownItem[]>( const rows = await db.select<
Array<{ category_id: number; category_name: string; category_color: string; balance: number | null }>
>(
`SELECT `SELECT
t.category_id, c.id AS category_id,
COALESCE(c.name, 'Uncategorized') AS category_name, c.name AS category_name,
COALESCE(c.color, '#9ca3af') AS category_color, COALESCE(c.color, '#9ca3af') AS category_color,
ABS(SUM(t.amount)) AS total SUM(t.amount) AS balance
FROM transactions t FROM transactions t
LEFT JOIN categories c ON t.category_id = c.id ${CATEGORY_JOIN_SQL}
${whereSQL} ${whereSQL}
GROUP BY t.category_id GROUP BY c.id
ORDER BY total DESC`, ORDER BY balance ASC`,
params params
); );
return rows.map((r) => ({
category_id: r.category_id,
category_name: r.category_name,
category_color: r.category_color,
total: orient("expense", Number(r.balance ?? 0)),
}));
} }
export async function getTransactionsByCategory( export async function getTransactionsByCategory(

View file

@ -54,6 +54,40 @@ function routeSelect(routes: { match: string; rows: unknown[] }[]): void {
}); });
} }
/**
* The rows of the monthly query (`getMonthlyTrends`, #392) for months given as
* income and expenses: one signed balance per section, an expense's negative.
*/
function flowRows(months: Array<{ month: string; income: number; expenses: number }>): unknown[] {
return months.flatMap(({ month, income, expenses }) => [
{ month, section: "income", balance: income },
{ month, section: "expense", balance: -expenses },
]);
}
/**
* Compare rows of expense categories given as spending: the query returns
* their signed balance (the opposite) with their section (#392).
*/
function expenseRows(rows: Array<Record<string, unknown> & {
month_current_total: number;
month_previous_total: number;
cumulative_current_total: number;
cumulative_previous_total: number;
}>): unknown[] {
return rows.map((r) => ({
...r,
section: "expense",
month_current_total: -r.month_current_total,
month_previous_total: -r.month_previous_total,
cumulative_current_total: -r.cumulative_current_total,
cumulative_previous_total: -r.cumulative_previous_total,
}));
}
/** The monthly query, the only snapshot query selecting a "%Y-%m" month. */
const FLOWS = "strftime('%Y-%m', t.date) AS month";
describe("getCartesSnapshot", () => { describe("getCartesSnapshot", () => {
it("returns zero-filled KPIs when there is no data", async () => { it("returns zero-filled KPIs when there is no data", async () => {
routeSelect([]); routeSelect([]);
@ -79,12 +113,12 @@ describe("getCartesSnapshot", () => {
// Reference = 2026-03 // Reference = 2026-03
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
{ month: "2025-03", income: 3000, expenses: 1800 }, // YoY comparison { month: "2025-03", income: 3000, expenses: 1800 }, // YoY comparison
{ month: "2026-02", income: 4000, expenses: 2000 }, // MoM comparison { month: "2026-02", income: 4000, expenses: 2000 }, // MoM comparison
{ month: "2026-03", income: 5000, expenses: 2500 }, // Reference { month: "2026-03", income: 5000, expenses: 2500 }, // Reference
], ]),
}, },
]); ]);
@ -106,11 +140,11 @@ describe("getCartesSnapshot", () => {
it("January reference month shifts MoM to December of previous year", async () => { it("January reference month shifts MoM to December of previous year", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
{ month: "2025-12", income: 2000, expenses: 1000 }, { month: "2025-12", income: 2000, expenses: 1000 },
{ month: "2026-01", income: 3000, expenses: 1500 }, { month: "2026-01", income: 3000, expenses: 1500 },
], ]),
}, },
]); ]);
@ -126,10 +160,10 @@ describe("getCartesSnapshot", () => {
it("savings rate is null when income is zero (no division by zero, renders as — in UI)", async () => { it("savings rate is null when income is zero (no division by zero, renders as — in UI)", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
{ month: "2026-03", income: 0, expenses: 500 }, { month: "2026-03", income: 0, expenses: 500 },
], ]),
}, },
]); ]);
@ -143,10 +177,10 @@ describe("getCartesSnapshot", () => {
it("handles less than 13 months of history by filling gaps with zero", async () => { it("handles less than 13 months of history by filling gaps with zero", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
{ month: "2026-03", income: 1000, expenses: 400 }, { month: "2026-03", income: 1000, expenses: 400 },
], ]),
}, },
]); ]);
@ -163,14 +197,15 @@ describe("getCartesSnapshot", () => {
it("computes seasonality only when historical data exists", async () => { it("computes seasonality only when historical data exists", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [{ month: "2026-03", income: 3000, expenses: 1500 }], rows: flowRows([{ month: "2026-03", income: 3000, expenses: 1500 }]),
}, },
{ {
match: "CAST(strftime('%Y', date) AS INTEGER) AS year", // The expense balance of March in each year: spending 1200 and 1000.
match: "CAST(strftime('%Y', t.date) AS INTEGER) AS year",
rows: [ rows: [
{ year: 2025, amount: 1200 }, { year: 2025, balance: -1200 },
{ year: 2024, amount: 1000 }, { year: 2024, balance: -1000 },
], ],
}, },
]); ]);
@ -186,8 +221,8 @@ describe("getCartesSnapshot", () => {
it("seasonality deviation stays null when there is no historical average", async () => { it("seasonality deviation stays null when there is no historical average", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [{ month: "2026-03", income: 2000, expenses: 800 }], rows: flowRows([{ month: "2026-03", income: 2000, expenses: 800 }]),
}, },
]); ]);
@ -201,8 +236,9 @@ describe("getCartesSnapshot", () => {
// Seven up-movers, three down-movers — verify we get 5 up and 3 down. // Seven up-movers, three down-movers — verify we get 5 up and 3 down.
// Cumulative totals mirror the monthly ones in this fixture — the Cartes // Cumulative totals mirror the monthly ones in this fixture — the Cartes
// service only reads the monthly block for top movers, so cumulative // service only reads the monthly block for top movers, so cumulative
// values are inert here. // values are inert here. The compare query returns signed balances with
const momRows = [ // their section (#392): an expense that spent 200 has a balance of −200.
const momRows = expenseRows([
{ category_id: 1, category_name: "C1", category_color: "#000", month_current_total: 200, month_previous_total: 100, cumulative_current_total: 200, cumulative_previous_total: 100 }, { category_id: 1, category_name: "C1", category_color: "#000", month_current_total: 200, month_previous_total: 100, cumulative_current_total: 200, cumulative_previous_total: 100 },
{ category_id: 2, category_name: "C2", category_color: "#000", month_current_total: 400, month_previous_total: 100, cumulative_current_total: 400, cumulative_previous_total: 100 }, { category_id: 2, category_name: "C2", category_color: "#000", month_current_total: 400, month_previous_total: 100, cumulative_current_total: 400, cumulative_previous_total: 100 },
{ category_id: 3, category_name: "C3", category_color: "#000", month_current_total: 500, month_previous_total: 100, cumulative_current_total: 500, cumulative_previous_total: 100 }, { category_id: 3, category_name: "C3", category_color: "#000", month_current_total: 500, month_previous_total: 100, cumulative_current_total: 500, cumulative_previous_total: 100 },
@ -213,11 +249,11 @@ describe("getCartesSnapshot", () => {
{ category_id: 8, category_name: "D1", category_color: "#000", month_current_total: 100, month_previous_total: 500, cumulative_current_total: 100, cumulative_previous_total: 500 }, { category_id: 8, category_name: "D1", category_color: "#000", month_current_total: 100, month_previous_total: 500, cumulative_current_total: 100, cumulative_previous_total: 500 },
{ category_id: 9, category_name: "D2", category_color: "#000", month_current_total: 100, month_previous_total: 700, cumulative_current_total: 100, cumulative_previous_total: 700 }, { category_id: 9, category_name: "D2", category_color: "#000", month_current_total: 100, month_previous_total: 700, cumulative_current_total: 100, cumulative_previous_total: 700 },
{ category_id: 10, category_name: "D3", category_color: "#000", month_current_total: 100, month_previous_total: 900, cumulative_current_total: 100, cumulative_previous_total: 900 }, { category_id: 10, category_name: "D3", category_color: "#000", month_current_total: 100, month_previous_total: 900, cumulative_current_total: 100, cumulative_previous_total: 900 },
]; ]);
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [{ month: "2026-03", income: 1000, expenses: 500 }], rows: flowRows([{ month: "2026-03", income: 1000, expenses: 500 }]),
}, },
{ {
// Matches the getCompareMonthOverMonth SQL pattern. // Matches the getCompareMonthOverMonth SQL pattern.
@ -240,11 +276,14 @@ describe("getCartesSnapshot", () => {
// revenue rows now reach getCartesSnapshot. Top movers is a spending view // revenue rows now reach getCartesSnapshot. Top movers is a spending view
// (up = red), so income must be filtered out — otherwise a salary jump tops // (up = red), so income must be filtered out — otherwise a salary jump tops
// "biggest increases" in red. The category metadata query types id 99 as // "biggest increases" in red. The category metadata query types id 99 as
// income; the two expense movers are absent from it and default to expense. // income; the two expense movers are absent from it and keep the section
// the query gives them.
const momRows = [ const momRows = [
{ category_id: 99, category_name: "Salaire", category_color: "#000", month_current_total: 5000, month_previous_total: 100, cumulative_current_total: 5000, cumulative_previous_total: 100 }, { category_id: 99, category_name: "Salaire", category_color: "#000", section: "income", month_current_total: 5000, month_previous_total: 100, cumulative_current_total: 5000, cumulative_previous_total: 100 },
{ category_id: 1, category_name: "Épicerie", category_color: "#000", month_current_total: 300, month_previous_total: 100, cumulative_current_total: 300, cumulative_previous_total: 100 }, ...expenseRows([
{ category_id: 2, category_name: "Resto", category_color: "#000", month_current_total: 100, month_previous_total: 400, cumulative_current_total: 100, cumulative_previous_total: 400 }, { category_id: 1, category_name: "Épicerie", category_color: "#000", month_current_total: 300, month_previous_total: 100, cumulative_current_total: 300, cumulative_previous_total: 100 },
{ category_id: 2, category_name: "Resto", category_color: "#000", month_current_total: 100, month_previous_total: 400, cumulative_current_total: 100, cumulative_previous_total: 400 },
]),
]; ];
routeSelect([ routeSelect([
{ match: "strftime('%Y-%m', date)", rows: [{ month: "2026-03", income: 5000, expenses: 400 }] }, { match: "strftime('%Y-%m', date)", rows: [{ month: "2026-03", income: 5000, expenses: 400 }] },
@ -266,8 +305,8 @@ describe("getCartesSnapshot", () => {
// Reference = 2026-03, YTD = Jan + Feb + Mar of 2026. // Reference = 2026-03, YTD = Jan + Feb + Mar of 2026.
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
// Previous year YTD: Jan + Feb + Mar 2025 = income 3000, expenses 1500. // Previous year YTD: Jan + Feb + Mar 2025 = income 3000, expenses 1500.
{ month: "2025-01", income: 1000, expenses: 500 }, { month: "2025-01", income: 1000, expenses: 500 },
{ month: "2025-02", income: 1000, expenses: 500 }, { month: "2025-02", income: 1000, expenses: 500 },
@ -276,7 +315,7 @@ describe("getCartesSnapshot", () => {
{ month: "2026-01", income: 2000, expenses: 800 }, { month: "2026-01", income: 2000, expenses: 800 },
{ month: "2026-02", income: 2500, expenses: 1000 }, { month: "2026-02", income: 2500, expenses: 1000 },
{ month: "2026-03", income: 3000, expenses: 1200 }, { month: "2026-03", income: 3000, expenses: 1200 },
], ]),
}, },
]); ]);
@ -303,12 +342,12 @@ describe("getCartesSnapshot", () => {
it("YTD savings rate is null when YTD income is zero", async () => { it("YTD savings rate is null when YTD income is zero", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
{ month: "2026-01", income: 0, expenses: 200 }, { month: "2026-01", income: 0, expenses: 200 },
{ month: "2026-02", income: 0, expenses: 150 }, { month: "2026-02", income: 0, expenses: 150 },
{ month: "2026-03", income: 0, expenses: 300 }, { month: "2026-03", income: 0, expenses: 300 },
], ]),
}, },
]); ]);
@ -321,11 +360,11 @@ describe("getCartesSnapshot", () => {
it("YTD MoM delta is null when reference month is January (no prior YTD window in same year)", async () => { it("YTD MoM delta is null when reference month is January (no prior YTD window in same year)", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
{ month: "2025-01", income: 500, expenses: 200 }, { month: "2025-01", income: 500, expenses: 200 },
{ month: "2026-01", income: 1000, expenses: 400 }, { month: "2026-01", income: 1000, expenses: 400 },
], ]),
}, },
]); ]);
@ -344,8 +383,8 @@ describe("getCartesSnapshot", () => {
it("YTD YoY delta uses Jan→refMonth of the previous year", async () => { it("YTD YoY delta uses Jan→refMonth of the previous year", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
// Prev year YTD Jan→Apr 2025 // Prev year YTD Jan→Apr 2025
{ month: "2025-01", income: 100, expenses: 50 }, { month: "2025-01", income: 100, expenses: 50 },
{ month: "2025-02", income: 100, expenses: 50 }, { month: "2025-02", income: 100, expenses: 50 },
@ -358,7 +397,7 @@ describe("getCartesSnapshot", () => {
{ month: "2026-02", income: 300, expenses: 100 }, { month: "2026-02", income: 300, expenses: 100 },
{ month: "2026-03", income: 300, expenses: 100 }, { month: "2026-03", income: 300, expenses: 100 },
{ month: "2026-04", income: 300, expenses: 100 }, { month: "2026-04", income: 300, expenses: 100 },
], ]),
}, },
]); ]);
@ -373,12 +412,12 @@ describe("getCartesSnapshot", () => {
it("defaults to mode=month and produces monthly KPIs (back-compat)", async () => { it("defaults to mode=month and produces monthly KPIs (back-compat)", async () => {
routeSelect([ routeSelect([
{ {
match: "strftime('%Y-%m', date)", match: FLOWS,
rows: [ rows: flowRows([
{ month: "2026-01", income: 1000, expenses: 400 }, { month: "2026-01", income: 1000, expenses: 400 },
{ month: "2026-02", income: 1000, expenses: 400 }, { month: "2026-02", income: 1000, expenses: 400 },
{ month: "2026-03", income: 5000, expenses: 2500 }, { month: "2026-03", income: 5000, expenses: 2500 },
], ]),
}, },
]); ]);
@ -447,7 +486,7 @@ describe("getCartesSnapshot", () => {
{ {
// Matches both the monthly and YTD actuals queries; for this test // Matches both the monthly and YTD actuals queries; for this test
// the YTD slice can mirror the monthly one. // the YTD slice can mirror the monthly one.
match: "FROM transactions\n WHERE date BETWEEN", match: "AS actual",
rows: [ rows: [
{ category_id: 10, actual: -400 }, // 400 spent against 500 budget -> in target { category_id: 10, actual: -400 }, // 400 spent against 500 budget -> in target
{ category_id: 11, actual: -350 }, // 350 spent against 200 budget -> overrun { category_id: 11, actual: -350 }, // 350 spent against 200 budget -> overrun
@ -497,7 +536,7 @@ describe("getCartesSnapshot", () => {
await getCartesSnapshot(2026, 3, "month", [3, 8]); await getCartesSnapshot(2026, 3, "month", [3, 8]);
const actualsCalls = mockSelect.mock.calls.filter(([sql]) => const actualsCalls = mockSelect.mock.calls.filter(([sql]) =>
(sql as string).includes("FROM transactions\n WHERE date BETWEEN"), (sql as string).includes("AS actual"),
); );
// Both the month and YTD actuals queries (getBudgetVsActualData) receive it. // Both the month and YTD actuals queries (getBudgetVsActualData) receive it.
expect(actualsCalls.length).toBeGreaterThanOrEqual(2); expect(actualsCalls.length).toBeGreaterThanOrEqual(2);
@ -512,11 +551,8 @@ describe("getCartesSnapshot", () => {
await getCartesSnapshot(2026, 3, "month", [3, 8]); await getCartesSnapshot(2026, 3, "month", [3, 8]);
// fetchMonthlyFlows is the only snapshot query selecting a "%Y-%m" month. const flowCall = mockSelect.mock.calls.find(([sql]) => (sql as string).includes(FLOWS))!;
const flowCall = mockSelect.mock.calls.find(([sql]) => expect(flowCall[0]).toContain("AND t.source_id IN ($3, $4)");
(sql as string).includes("strftime('%Y-%m', date) AS month"),
)!;
expect(flowCall[0]).toContain("AND source_id IN ($3, $4)");
expect(flowCall[1]).toEqual(expect.arrayContaining([3, 8])); expect(flowCall[1]).toEqual(expect.arrayContaining([3, 8]));
}); });
@ -527,9 +563,9 @@ describe("getCartesSnapshot", () => {
// fetchSeasonality is the only snapshot query filtering on a "%m" month. // fetchSeasonality is the only snapshot query filtering on a "%m" month.
const seasonalityCall = mockSelect.mock.calls.find(([sql]) => const seasonalityCall = mockSelect.mock.calls.find(([sql]) =>
(sql as string).includes("strftime('%m', date) = $1"), (sql as string).includes("strftime('%m', t.date) = $1"),
)!; )!;
expect(seasonalityCall[0]).toContain("AND source_id IN ($4, $5)"); expect(seasonalityCall[0]).toContain("AND t.source_id IN ($4, $5)");
expect(seasonalityCall[1]).toEqual(expect.arrayContaining([3, 8])); expect(seasonalityCall[1]).toEqual(expect.arrayContaining([3, 8]));
}); });

View file

@ -85,7 +85,7 @@ describe("getMonthlyTrends", () => {
const sql = mockSelect.mock.calls[0][0] as string; const sql = mockSelect.mock.calls[0][0] as string;
const params = mockSelect.mock.calls[0][1] as unknown[]; const params = mockSelect.mock.calls[0][1] as unknown[];
expect(sql).toContain("WHERE source_id IN ($1)"); expect(sql).toContain("WHERE t.source_id IN ($1)");
expect(params).toEqual([5]); expect(params).toEqual([5]);
}); });
}); });
@ -113,7 +113,7 @@ describe("getCategoryOverTime", () => {
const topCatSQL = mockSelect.mock.calls[0][0] as string; const topCatSQL = mockSelect.mock.calls[0][0] as string;
const topCatParams = mockSelect.mock.calls[0][1] as unknown[]; const topCatParams = mockSelect.mock.calls[0][1] as unknown[];
expect(topCatSQL).toContain("COALESCE(c.type, 'expense')"); expect(topCatSQL).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END");
expect(topCatSQL).toContain("WHERE"); expect(topCatSQL).toContain("WHERE");
expect(topCatParams[0]).toBe("expense"); expect(topCatParams[0]).toBe("expense");
}); });
@ -127,7 +127,7 @@ describe("getCategoryOverTime", () => {
const topCatSQL = mockSelect.mock.calls[0][0] as string; const topCatSQL = mockSelect.mock.calls[0][0] as string;
const topCatParams = mockSelect.mock.calls[0][1] as unknown[]; const topCatParams = mockSelect.mock.calls[0][1] as unknown[];
expect(topCatSQL).toContain("COALESCE(c.type, 'expense') = $1"); expect(topCatSQL).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END = $1");
expect(topCatParams[0]).toBe("income"); expect(topCatParams[0]).toBe("income");
// Date params follow // Date params follow
expect(topCatParams[1]).toBe("2025-01-01"); expect(topCatParams[1]).toBe("2025-01-01");
@ -198,14 +198,14 @@ describe("getCategoryOverTime", () => {
const topCatSQL = mockSelect.mock.calls[0][0] as string; const topCatSQL = mockSelect.mock.calls[0][0] as string;
const topCatParams = mockSelect.mock.calls[0][1] as unknown[]; const topCatParams = mockSelect.mock.calls[0][1] as unknown[];
expect(topCatSQL).toContain("COALESCE(c.type, 'expense') = $1"); expect(topCatSQL).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END = $1");
expect(topCatSQL).toContain("t.date >= $2"); expect(topCatSQL).toContain("t.date >= $2");
expect(topCatSQL).toContain("t.date <= $3"); expect(topCatSQL).toContain("t.date <= $3");
expect(topCatSQL).toContain("t.source_id IN ($4)"); expect(topCatSQL).toContain("t.source_id IN ($4)");
expect(topCatParams).toEqual(["expense", "2025-01-01", "2025-06-30", 2, 10]); expect(topCatParams).toEqual(["expense", "2025-01-01", "2025-06-30", 2, 10]);
}); });
it("projects category type into the top-N SELECT", async () => { it("projects the section of each category into the top-N SELECT (#392)", async () => {
mockSelect mockSelect
.mockResolvedValueOnce([]) // topCategories .mockResolvedValueOnce([]) // topCategories
.mockResolvedValueOnce([]); // monthlyRows .mockResolvedValueOnce([]); // monthlyRows
@ -213,7 +213,7 @@ describe("getCategoryOverTime", () => {
await getCategoryOverTime(); await getCategoryOverTime();
const topCatSQL = mockSelect.mock.calls[0][0] as string; const topCatSQL = mockSelect.mock.calls[0][0] as string;
expect(topCatSQL).toContain("COALESCE(c.type, 'expense') AS category_type"); expect(topCatSQL).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END AS category_type");
}); });
it("returns correct structure with categories, data, colors, categoryIds, and types", async () => { it("returns correct structure with categories, data, colors, categoryIds, and types", async () => {
@ -240,17 +240,17 @@ describe("getCategoryOverTime", () => {
expect(result.data[1]).toEqual({ month: "2025-02", Food: 200, Salary: 100 }); expect(result.data[1]).toEqual({ month: "2025-02", Food: 200, Salary: 100 });
}); });
it("defaults a null category type to expense in the types map", async () => { it("reads a missing section as the uncategorized one in the types map (#392)", async () => {
mockSelect mockSelect
.mockResolvedValueOnce([ .mockResolvedValueOnce([
// COALESCE(c.type, 'expense') yields 'expense'; a null slipping through defaults too. // The SQL gives every row its section; a null slipping through is no category type.
{ category_id: 1, category_name: "Food", category_color: "#ff0000", category_type: null, total: 500 }, { category_id: 1, category_name: "Food", category_color: "#ff0000", category_type: null, total: 500 },
]) ])
.mockResolvedValueOnce([{ month: "2025-01", category_id: 1, category_name: "Food", total: 300 }]); .mockResolvedValueOnce([{ month: "2025-01", category_id: 1, category_name: "Food", total: 300 }]);
const result = await getCategoryOverTime(); const result = await getCategoryOverTime();
expect(result.types).toEqual({ Food: "expense" }); expect(result.types).toEqual({ Food: "uncategorized" });
}); });
it("keeps the pivot top-N + Other but the id-keyed tree carries every category (Issue #264)", async () => { it("keeps the pivot top-N + Other but the id-keyed tree carries every category (Issue #264)", async () => {
@ -403,6 +403,17 @@ describe("getHighlights", () => {
expect(moversParams[3]).toBe("2026-02-28"); expect(moversParams[3]).toBe("2026-02-28");
}); });
it("ranks movers among expense categories only, on signed amounts (#392)", async () => {
queueEmpty(5);
await getHighlights(REF_YEAR, REF_MONTH, YTD_YEAR, 30, 5, 10, TODAY);
const moversSql = mockSelect.mock.calls[3][0] as string;
expect(moversSql).toContain("WHERE CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END = 'expense'");
expect(moversSql).not.toContain("ABS(t.amount)");
expect(moversSql).not.toMatch(/t\.amount\s*[<>]/);
});
it("wraps January reference month back to December of the previous year for top movers", async () => { it("wraps January reference month back to December of the previous year for top movers", async () => {
queueEmpty(5); queueEmpty(5);
@ -415,7 +426,7 @@ describe("getHighlights", () => {
expect(moversParams[3]).toBe("2025-12-31"); expect(moversParams[3]).toBe("2025-12-31");
}); });
it("computes deltaAbs and deltaPct from movers rows", async () => { it("computes deltaAbs and deltaPct from movers rows, each on its spending (#392)", async () => {
mockSelect mockSelect
.mockResolvedValueOnce([{ net: -500 }]) // current balance .mockResolvedValueOnce([{ net: -500 }]) // current balance
.mockResolvedValueOnce([{ net: -1800 }]) // ytd .mockResolvedValueOnce([{ net: -1800 }]) // ytd
@ -423,20 +434,21 @@ describe("getHighlights", () => {
{ month: "2026-03", net: -500 }, { month: "2026-03", net: -500 },
{ month: "2026-02", net: -400 }, { month: "2026-02", net: -400 },
]) // series ]) // series
// Signed balances of expense categories: spending 240 and 200, 85 and 170.
.mockResolvedValueOnce([ .mockResolvedValueOnce([
{ {
category_id: 1, category_id: 1,
category_name: "Restaurants", category_name: "Restaurants",
category_color: "#f97316", category_color: "#f97316",
current_total: 240, current_total: -240,
previous_total: 200, previous_total: -200,
}, },
{ {
category_id: 2, category_id: 2,
category_name: "Groceries", category_name: "Groceries",
category_color: "#10b981", category_color: "#10b981",
current_total: 85, current_total: -85,
previous_total: 170, previous_total: -170,
}, },
]) ])
.mockResolvedValueOnce([]); // recent .mockResolvedValueOnce([]); // recent
@ -467,7 +479,7 @@ describe("getHighlights", () => {
category_id: 3, category_id: 3,
category_name: "New expense", category_name: "New expense",
category_color: "#3b82f6", category_color: "#3b82f6",
current_total: 120, current_total: -120,
previous_total: 0, previous_total: 0,
}, },
]) ])
@ -708,122 +720,108 @@ describe("getCompareYearOverYear", () => {
}); });
}); });
describe("real-vs-real compare — transfer netting (Issue #243)", () => { describe("real-vs-real compare — signed balances (Issues #243, #392)", () => {
// A `transfer` category (e.g. "Paiement CC") is a money move, not spending: // The compare sums the SIGNED amounts of each category in each date bucket,
// its debit and matching credit must cancel to ~0 in the real-vs-real // with the category's section (ADR 0026); rowsToDeltas shows an expense
// compare. Ordinary categories keep the expense-report behavior (only // category its spending, the opposite of its balance. A split is counted once
// outflows, summed as positive magnitudes). The netting lives entirely in // (its offset line cancels, in the parent's category, the parts sent
// the SQL (COMPARE_DELTA_SQL): a signed SUM(t.amount) for `transfer`, // elsewhere), a refund lowers its category, a transfer debit/credit pair nets
// ABS(t.amount) filtered on amount < 0 for plain expenses. Income, like // to 0 (#243), and the rows without a category are one uncategorized line.
// transfers, is a signed SUM (Issue #253); the WHERE is broadened so // These figures are proved on a real database, with the real split service,
// income/transfer credits are not dropped before they can count or cancel. // by src/__integration__/report-totals.test.ts; here, the shape of the query
// // and what rowsToDeltas makes of its rows.
// There is no runnable SQLite in these unit tests (tauri-plugin-sql only
// exists inside the Tauri WebView, and no harness opens node:sqlite yet:
// CI runs Node 24 since #376, which has it, and #392 plans that harness), so
// the netting is pinned two ways: (1) a reference-semantics check over
// concrete debit/credit rows that reproduces the exact per-row rule the SQL
// encodes, and (2) structural assertions that the real query on BOTH compare
// functions carries that rule and the broadened WHERE.
/** Per-row contribution to a bucket — the exact rule COMPARE_DELTA_SQL encodes. */ it.each([
function bucketContribution(amount: number, type: string | null): number { ["getCompareMonthOverMonth", () => getCompareMonthOverMonth(2026, 4)],
const t = type ?? "expense"; ["getCompareYearOverYear", () => getCompareYearOverYear(2026, 4)],
return t === "transfer" || t === "income" ])("%s sums signed amounts by section, with neither ABS nor a sign filter", async (_name, run) => {
? amount // signed → transfer debit/credit cancel; income credits kept as revenue (#253)
: amount < 0
? Math.abs(amount) // expense outflow as a positive magnitude
: 0; // other (expense) credits dropped — the report stays outflow-only for them
}
it("nets a balanced transfer to ~0 while an expense keeps its sum of outflows", () => {
// "Paiement CC" (transfer): -500 out of chequing, +500 onto the card.
const transfer = [-500, 500].reduce((s, a) => s + bucketContribution(a, "transfer"), 0);
expect(transfer).toBeCloseTo(0, 6);
// "Épicerie" (expense): two debits + one refund credit that must NOT net it down.
const expense = [-120, -80, 60].reduce((s, a) => s + bucketContribution(a, "expense"), 0);
expect(expense).toBe(200);
// Uncategorized (c.type NULL) defaults to expense behavior.
const uncategorized = [-40, 15].reduce((s, a) => s + bucketContribution(a, null), 0);
expect(uncategorized).toBe(40);
// Income (paie + a small correction) is a signed SUM — credits are kept as
// revenue (Issue #253), not dropped like non-transfer expense credits.
const income = [4200, 150, -50].reduce((s, a) => s + bucketContribution(a, "income"), 0);
expect(income).toBe(4300);
});
it("getCompareMonthOverMonth SQL nets transfers (signed) but keeps ABS for other types", async () => {
mockSelect.mockResolvedValueOnce([]); mockSelect.mockResolvedValueOnce([]);
await getCompareMonthOverMonth(2026, 4); await run();
const sql = mockSelect.mock.calls[0][0] as string; const sql = mockSelect.mock.calls[0][0] as string;
// transfer → signed t.amount; every other type → ABS(t.amount) expect(sql).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END AS section");
expect(sql).toContain( expect(sql).toContain("COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN t.amount ELSE 0 END), 0) AS month_current_total");
"COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount)", // Every row without an existing category is one group.
); expect(sql).toContain("GROUP BY c.id");
// WHERE broadened so transfer credits survive the expense (amount < 0) filter expect(sql).not.toContain("ABS(t.amount)");
expect(sql).toContain( expect(sql).not.toMatch(/t\.amount\s*[<>]/);
"WHERE (t.amount < 0 OR COALESCE(c.type, 'expense') IN ('transfer', 'income'))",
);
// still four date buckets // still four date buckets
expect(sql).toContain("month_current_total"); expect(sql).toContain("month_current_total");
expect(sql).toContain("cumulative_previous_total"); expect(sql).toContain("cumulative_previous_total");
}); });
it("getCompareYearOverYear applies the identical netting contract (both tabs fixed)", async () => { it("shows an expense its spending, keeps a netted transfer at 0, and the uncategorized line apart", async () => {
mockSelect.mockResolvedValueOnce([]);
await getCompareYearOverYear(2026, 4);
const sql = mockSelect.mock.calls[0][0] as string;
expect(sql).toContain(
"COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount)",
);
expect(sql).toContain(
"WHERE (t.amount < 0 OR COALESCE(c.type, 'expense') IN ('transfer', 'income'))",
);
});
it("keeps a netted transfer at 0 through the pipeline while an expense is unchanged", async () => {
// Rows as the netted SQL returns them: the balanced transfer arrives at 0,
// the ordinary expense keeps its outflow sum. Assert nothing downstream
// re-inflates the transfer.
mockSelect.mockResolvedValueOnce([ mockSelect.mockResolvedValueOnce([
{ {
category_id: 5, category_id: 5,
category_name: "Épicerie", category_name: "Épicerie",
category_color: "#10b981", category_color: "#10b981",
month_current_total: 200, section: "expense",
month_previous_total: 150, month_current_total: -200,
cumulative_current_total: 800, month_previous_total: -150,
cumulative_previous_total: 600, cumulative_current_total: -800,
cumulative_previous_total: -600,
}, },
{ {
category_id: 71, category_id: 71,
category_name: "Paiement CC", category_name: "Paiement CC",
category_color: "#9ca3af", category_color: "#9ca3af",
section: "transfer",
month_current_total: 0, month_current_total: 0,
month_previous_total: 0, month_previous_total: 0,
cumulative_current_total: 0, cumulative_current_total: 0,
cumulative_previous_total: 0, cumulative_previous_total: 0,
}, },
{
category_id: null,
category_name: "Uncategorized",
category_color: "#9ca3af",
section: "uncategorized",
month_current_total: 40,
month_previous_total: 0,
cumulative_current_total: 40,
cumulative_previous_total: 0,
},
]); ]);
const result = await getCompareMonthOverMonth(2026, 4); const result = await getCompareMonthOverMonth(2026, 4);
const transferRow = result.find((r) => r.categoryName === "Paiement CC")!;
const expenseRow = result.find((r) => r.categoryName === "Épicerie")!; const expenseRow = result.find((r) => r.categoryName === "Épicerie")!;
const transferRow = result.find((r) => r.categoryName === "Paiement CC")!;
const uncategorized = result.find((r) => r.categoryId === null)!;
expect(transferRow.currentAmount).toBe(0); // The expense shows its spending: the opposite of its balance.
expect(transferRow.previousAmount).toBe(0); expect(expenseRow).toMatchObject({
expect(transferRow.deltaAbs).toBe(0); currentAmount: 200,
expect(transferRow.cumulativeCurrentAmount).toBe(0); previousAmount: 150,
// Ordinary expense keeps EXACTLY its sum of outflows. deltaAbs: 50,
expect(expenseRow.currentAmount).toBe(200); cumulativeCurrentAmount: 800,
expect(expenseRow.previousAmount).toBe(150); cumulativePreviousAmount: 600,
category_type: "expense",
});
// Nothing downstream re-inflates the netted transfer.
expect(transferRow).toMatchObject({ currentAmount: 0, previousAmount: 0, deltaAbs: 0, category_type: "transfer" });
// The uncategorized line keeps its signed balance, in its own section.
expect(uncategorized).toMatchObject({ currentAmount: 40, category_type: "uncategorized", is_parent: false });
});
it("shows a negative spending for an expense category whose refunds exceed its purchases", async () => {
mockSelect.mockResolvedValueOnce([
{
category_id: 6,
category_name: "Boucherie",
category_color: "#000",
section: "expense",
month_current_total: 50,
month_previous_total: 0,
cumulative_current_total: 50,
cumulative_previous_total: 0,
},
]);
const [row] = await getCompareMonthOverMonth(2026, 4);
expect(row).toMatchObject({ currentAmount: -50, deltaAbs: -50, deltaPct: null });
}); });
}); });
@ -1186,25 +1184,28 @@ describe("buildOverTimeTree — hierarchical trends (Issue #264)", () => {
describe("getCompareMonthOverMonth — wires the hierarchy (Issue #247)", () => { describe("getCompareMonthOverMonth — wires the hierarchy (Issue #247)", () => {
it("returns parent subtotal rows when category metadata is available", async () => { it("returns parent subtotal rows when category metadata is available", async () => {
mockSelect mockSelect
// 1. COMPARE_DELTA_SQL — two sibling leaves under parent id 2. // 1. COMPARE_DELTA_SQL — two sibling leaves under parent id 2, signed
// balances of expense categories (spending 500 and 120 this month).
.mockResolvedValueOnce([ .mockResolvedValueOnce([
{ {
category_id: 22, category_id: 22,
category_name: "Épicerie", category_name: "Épicerie",
category_color: "#10b981", category_color: "#10b981",
month_current_total: 500, section: "expense",
month_previous_total: 400, month_current_total: -500,
cumulative_current_total: 2000, month_previous_total: -400,
cumulative_previous_total: 1500, cumulative_current_total: -2000,
cumulative_previous_total: -1500,
}, },
{ {
category_id: 24, category_id: 24,
category_name: "Restaurant", category_name: "Restaurant",
category_color: "#f97316", category_color: "#f97316",
month_current_total: 120, section: "expense",
month_previous_total: 200, month_current_total: -120,
cumulative_current_total: 300, month_previous_total: -200,
cumulative_previous_total: 500, cumulative_current_total: -300,
cumulative_previous_total: -500,
}, },
]) ])
// 2. COMPARE_CATEGORIES_SQL — the hierarchy. // 2. COMPARE_CATEGORIES_SQL — the hierarchy.

View file

@ -1,9 +1,20 @@
import { getDb } from "./db"; import { getDb } from "./db";
import { getBudgetVsActualData } from "./budgetService"; import { getBudgetVsActualData } from "./budgetService";
import { inPlaceholders } from "../utils/sqlFilters"; import { inPlaceholders } from "../utils/sqlFilters";
import {
CATEGORY_JOIN_SQL,
EMPTY_STATEMENT,
SECTION_ORDER,
SECTION_SQL,
addStatements,
incomeStatement,
orient,
savingsRate,
toCents,
toSection,
} from "../utils/incomeStatement";
import type { import type {
MonthlyTrendItem, MonthlyTrendItem,
CategoryBreakdownItem,
CategoryOverTimeData, CategoryOverTimeData,
CategoryOverTimeItem, CategoryOverTimeItem,
OverTimeRow, OverTimeRow,
@ -25,8 +36,19 @@ import type {
CartesSeasonality, CartesSeasonality,
CartesSeasonalityYear, CartesSeasonalityYear,
CartesKpiPeriodMode, CartesKpiPeriodMode,
BudgetVsActualRow,
IncomeStatementFigures,
ReportSection,
} from "../shared/types"; } from "../shared/types";
/**
* The income statement of each month (#392, ADR 0026): the signed balances of
* the month's transactions by section, turned into income, expenses, the
* uncategorized line, transfers and the two results. Trends (global flow) and
* the KPI cards, sparklines and overlay chart of Cartes and the Dashboard all
* read this one query. An absent `dateFrom` or `dateTo` is no bound on that
* side (« Tout », #479).
*/
export async function getMonthlyTrends( export async function getMonthlyTrends(
dateFrom?: string, dateFrom?: string,
dateTo?: string, dateTo?: string,
@ -39,18 +61,18 @@ export async function getMonthlyTrends(
let paramIndex = 1; let paramIndex = 1;
if (dateFrom) { if (dateFrom) {
whereClauses.push(`date >= $${paramIndex}`); whereClauses.push(`t.date >= $${paramIndex}`);
params.push(dateFrom); params.push(dateFrom);
paramIndex++; paramIndex++;
} }
if (dateTo) { if (dateTo) {
whereClauses.push(`date <= $${paramIndex}`); whereClauses.push(`t.date <= $${paramIndex}`);
params.push(dateTo); params.push(dateTo);
paramIndex++; paramIndex++;
} }
const accountPlaceholders = inPlaceholders(accountIds, paramIndex); const accountPlaceholders = inPlaceholders(accountIds, paramIndex);
if (accountPlaceholders) { if (accountPlaceholders) {
whereClauses.push(`source_id IN (${accountPlaceholders})`); whereClauses.push(`t.source_id IN (${accountPlaceholders})`);
params.push(...accountIds!); params.push(...accountIds!);
paramIndex += accountIds!.length; paramIndex += accountIds!.length;
} }
@ -58,17 +80,27 @@ export async function getMonthlyTrends(
const whereSQL = const whereSQL =
whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : ""; whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
return db.select<MonthlyTrendItem[]>( const rows = await db.select<Array<{ month: string; section: string; balance: number | null }>>(
`SELECT `SELECT
strftime('%Y-%m', date) AS month, strftime('%Y-%m', t.date) AS month,
COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) AS income, ${SECTION_SQL} AS section,
ABS(COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0)) AS expenses SUM(t.amount) AS balance
FROM transactions FROM transactions t
${CATEGORY_JOIN_SQL}
${whereSQL} ${whereSQL}
GROUP BY month GROUP BY month, section
ORDER BY month ASC`, ORDER BY month ASC`,
params params
); );
// One statement per month, in the order the rows come (ORDER BY month).
const byMonth = new Map<string, typeof rows>();
for (const row of rows) {
const monthRows = byMonth.get(row.month);
if (monthRows) monthRows.push(row);
else byMonth.set(row.month, [row]);
}
return Array.from(byMonth, ([month, monthRows]) => ({ month, ...incomeStatement(monthRows) }));
} }
export async function getCategoryOverTime( export async function getCategoryOverTime(
@ -85,7 +117,7 @@ export async function getCategoryOverTime(
let paramIndex = 1; let paramIndex = 1;
if (typeFilter) { if (typeFilter) {
whereClauses.push(`COALESCE(c.type, 'expense') = $${paramIndex}`); whereClauses.push(`${SECTION_SQL} = $${paramIndex}`);
params.push(typeFilter); params.push(typeFilter);
paramIndex++; paramIndex++;
} }
@ -109,21 +141,27 @@ export async function getCategoryOverTime(
const whereSQL = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : ""; const whereSQL = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
// Get top N categories by total spend // Top N categories by the size of their balance: `ABS` only ranks them, the
// amounts below stay signed. Every row without an existing category is one
// group (`c.id` NULL), the uncategorized one.
const topCategories = await db.select< const topCategories = await db.select<
(CategoryBreakdownItem & { category_type: "expense" | "income" | "transfer" })[] Array<{
category_id: number | null;
category_name: string;
category_color: string;
category_type: string | null;
}>
>( >(
`SELECT `SELECT
t.category_id, c.id AS category_id,
COALESCE(c.name, 'Uncategorized') AS category_name, COALESCE(c.name, 'Uncategorized') AS category_name,
COALESCE(c.color, '#9ca3af') AS category_color, COALESCE(c.color, '#9ca3af') AS category_color,
COALESCE(c.type, 'expense') AS category_type, ${SECTION_SQL} AS category_type
ABS(SUM(t.amount)) AS total
FROM transactions t FROM transactions t
LEFT JOIN categories c ON t.category_id = c.id ${CATEGORY_JOIN_SQL}
${whereSQL} ${whereSQL}
GROUP BY t.category_id GROUP BY c.id
ORDER BY total DESC ORDER BY ABS(SUM(t.amount)) DESC
LIMIT $${paramIndex}`, LIMIT $${paramIndex}`,
[...params, topN] [...params, topN]
); );
@ -131,34 +169,38 @@ export async function getCategoryOverTime(
const topCategoryIds = new Set(topCategories.map((c) => c.category_id)); const topCategoryIds = new Set(topCategories.map((c) => c.category_id));
const colors: Record<string, string> = {}; const colors: Record<string, string> = {};
const categoryIds: Record<string, number | null> = {}; const categoryIds: Record<string, number | null> = {};
const types: Record<string, "expense" | "income" | "transfer"> = {}; const types: Record<string, ReportSection> = {};
for (const cat of topCategories) { for (const cat of topCategories) {
colors[cat.category_name] = cat.category_color; colors[cat.category_name] = cat.category_color;
categoryIds[cat.category_name] = cat.category_id; categoryIds[cat.category_name] = cat.category_id;
types[cat.category_name] = cat.category_type ?? "expense"; types[cat.category_name] = toSection(cat.category_type);
} }
// Get monthly breakdown for all categories // Signed balance of every category, month by month, with its section.
const monthlyRows = await db.select< const monthlyRows = await db.select<
Array<{ Array<{
month: string; month: string;
category_id: number | null; category_id: number | null;
category_name: string; category_name: string;
total: number; section: string | null;
total: number | null;
}> }>
>( >(
`SELECT `SELECT
strftime('%Y-%m', t.date) AS month, strftime('%Y-%m', t.date) AS month,
t.category_id, c.id AS category_id,
COALESCE(c.name, 'Uncategorized') AS category_name, COALESCE(c.name, 'Uncategorized') AS category_name,
ABS(SUM(t.amount)) AS total ${SECTION_SQL} AS section,
SUM(t.amount) AS total
FROM transactions t FROM transactions t
LEFT JOIN categories c ON t.category_id = c.id ${CATEGORY_JOIN_SQL}
${whereSQL} ${whereSQL}
GROUP BY month, t.category_id GROUP BY month, c.id
ORDER BY month ASC`, ORDER BY month ASC`,
params params
); );
// What each row shows: an expense its spending (D1), the others their balance.
const shown = (row: (typeof monthlyRows)[number]) => orient(toSection(row.section), Number(row.total ?? 0));
// Build pivot data // Build pivot data
const monthMap = new Map<string, CategoryOverTimeItem>(); const monthMap = new Map<string, CategoryOverTimeItem>();
@ -171,9 +213,9 @@ export async function getCategoryOverTime(
const item = monthMap.get(row.month)!; const item = monthMap.get(row.month)!;
if (topCategoryIds.has(row.category_id)) { if (topCategoryIds.has(row.category_id)) {
item[row.category_name] = ((item[row.category_name] as number) || 0) + row.total; item[row.category_name] = toCents(((item[row.category_name] as number) || 0) + shown(row));
} else { } else {
item["Other"] = ((item["Other"] as number) || 0) + row.total; item["Other"] = toCents(((item["Other"] as number) || 0) + shown(row));
hasOther = true; hasOther = true;
} }
} }
@ -199,9 +241,9 @@ export async function getCategoryOverTime(
const monthIndex = new Map<string, number>(); const monthIndex = new Map<string, number>();
months.forEach((m, i) => monthIndex.set(m, i)); months.forEach((m, i) => monthIndex.set(m, i));
// Aggregate every category into an id-keyed per-month magnitude series. A null // Aggregate every category into an id-keyed per-month series of what it
// category_id (truly uncategorized) collapses to one bucket; a non-null id that // shows (signed, ADR 0026). Every row without an existing category (no
// has no metadata row (hard-deleted) stays distinct and surfaces as an orphan. // category, or one that is gone) is one bucket, the uncategorized one.
const leafByKey = new Map<number | string, OverTimeRow>(); const leafByKey = new Map<number | string, OverTimeRow>();
for (const row of monthlyRows) { for (const row of monthlyRows) {
const key = row.category_id ?? "__uncategorized__"; const key = row.category_id ?? "__uncategorized__";
@ -216,14 +258,14 @@ export async function getCategoryOverTime(
parent_id: null, parent_id: null,
is_parent: false, is_parent: false,
depth: 0, depth: 0,
category_type: "expense", category_type: toSection(row.section),
}; };
leafByKey.set(key, leaf); leafByKey.set(key, leaf);
} }
const idx = monthIndex.get(row.month); const idx = monthIndex.get(row.month);
if (idx != null) { if (idx != null) {
leaf.monthly[idx] += row.total; leaf.monthly[idx] = toCents(leaf.monthly[idx] + shown(row));
leaf.total += row.total; leaf.total = toCents(leaf.total + shown(row));
} }
} }
@ -357,8 +399,10 @@ export async function getHighlights(
monthlyBalanceSeries.push({ month: monthKey, netBalance: seriesMap.get(monthKey) ?? 0 }); monthlyBalanceSeries.push({ month: monthKey, netBalance: seriesMap.get(monthKey) ?? 0 });
} }
// 4. Top movers — expense-side only (amount < 0), compare reference month // 4. Top movers — expense categories only, each on its spending (the
// vs the immediately-previous month. // opposite of its signed balance, refunds and splits netted, ADR 0026), as
// the Cartes movers: reference month vs the immediately-previous month.
// `ABS` only ranks them.
const moversRows = await db.select< const moversRows = await db.select<
Array<{ Array<{
category_id: number | null; category_id: number | null;
@ -369,27 +413,27 @@ export async function getHighlights(
}> }>
>( >(
`SELECT `SELECT
t.category_id, c.id AS category_id,
COALESCE(c.name, 'Uncategorized') AS category_name, COALESCE(c.name, 'Uncategorized') AS category_name,
COALESCE(c.color, '#9ca3af') AS category_color, COALESCE(c.color, '#9ca3af') AS category_color,
COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN ABS(t.amount) ELSE 0 END), 0) AS current_total, COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN t.amount ELSE 0 END), 0) AS current_total,
COALESCE(SUM(CASE WHEN t.date >= $3 AND t.date <= $4 THEN ABS(t.amount) ELSE 0 END), 0) AS previous_total COALESCE(SUM(CASE WHEN t.date >= $3 AND t.date <= $4 THEN t.amount ELSE 0 END), 0) AS previous_total
FROM transactions t FROM transactions t
LEFT JOIN categories c ON t.category_id = c.id ${CATEGORY_JOIN_SQL}
WHERE t.amount < 0 WHERE ${SECTION_SQL} = 'expense'
AND ( AND (
(t.date >= $1 AND t.date <= $2) (t.date >= $1 AND t.date <= $2)
OR (t.date >= $3 AND t.date <= $4) OR (t.date >= $3 AND t.date <= $4)
) )
GROUP BY t.category_id, category_name, category_color GROUP BY c.id
ORDER BY ABS(current_total - previous_total) DESC ORDER BY ABS(current_total - previous_total) DESC
LIMIT $5`, LIMIT $5`,
[currentMonthStart, currentMonthEnd, previousMonthStart, previousMonthEnd, topMoversLimit], [currentMonthStart, currentMonthEnd, previousMonthStart, previousMonthEnd, topMoversLimit],
); );
const topMovers: HighlightMover[] = moversRows.map((r) => { const topMovers: HighlightMover[] = moversRows.map((r) => {
const current = Number(r.current_total ?? 0); const current = orient("expense", Number(r.current_total ?? 0));
const previous = Number(r.previous_total ?? 0); const previous = orient("expense", Number(r.previous_total ?? 0));
const deltaAbs = current - previous; const deltaAbs = toCents(current - previous);
const deltaPct = previous === 0 ? null : (deltaAbs / previous) * 100; const deltaPct = previous === 0 ? null : (deltaAbs / previous) * 100;
// Highlights only exposes a monthly view, so the cumulative block mirrors // Highlights only exposes a monthly view, so the cumulative block mirrors
// the monthly values — keeps the CategoryDelta shape uniform for // the monthly values — keeps the CategoryDelta shape uniform for
@ -442,22 +486,30 @@ interface RawDeltaRow {
category_id: number | null; category_id: number | null;
category_name: string; category_name: string;
category_color: string; category_color: string;
/** `SECTION_SQL` of the row's category. */
section?: string | null;
month_current_total: number | null; month_current_total: number | null;
month_previous_total: number | null; month_previous_total: number | null;
cumulative_current_total: number | null; cumulative_current_total: number | null;
cumulative_previous_total: number | null; cumulative_previous_total: number | null;
} }
/**
* Turns the signed balances of compareDeltaSql() into what each row shows
* (ADR 0026): an expense category its spending, the opposite of its balance,
* every other section its balance. The row keeps its section.
*/
function rowsToDeltas(rows: RawDeltaRow[]): CategoryDelta[] { function rowsToDeltas(rows: RawDeltaRow[]): CategoryDelta[] {
return rows.map((r) => { return rows.map((r) => {
const monthCurrent = Number(r.month_current_total ?? 0); const section = toSection(r.section);
const monthPrevious = Number(r.month_previous_total ?? 0); const monthCurrent = orient(section, Number(r.month_current_total ?? 0));
const monthDeltaAbs = monthCurrent - monthPrevious; const monthPrevious = orient(section, Number(r.month_previous_total ?? 0));
const monthDeltaAbs = toCents(monthCurrent - monthPrevious);
const monthDeltaPct = monthPrevious === 0 ? null : (monthDeltaAbs / monthPrevious) * 100; const monthDeltaPct = monthPrevious === 0 ? null : (monthDeltaAbs / monthPrevious) * 100;
const cumCurrent = Number(r.cumulative_current_total ?? 0); const cumCurrent = orient(section, Number(r.cumulative_current_total ?? 0));
const cumPrevious = Number(r.cumulative_previous_total ?? 0); const cumPrevious = orient(section, Number(r.cumulative_previous_total ?? 0));
const cumDeltaAbs = cumCurrent - cumPrevious; const cumDeltaAbs = toCents(cumCurrent - cumPrevious);
const cumDeltaPct = cumPrevious === 0 ? null : (cumDeltaAbs / cumPrevious) * 100; const cumDeltaPct = cumPrevious === 0 ? null : (cumDeltaAbs / cumPrevious) * 100;
return { return {
@ -474,6 +526,7 @@ function rowsToDeltas(rows: RawDeltaRow[]): CategoryDelta[] {
cumulativeCurrentAmount: cumCurrent, cumulativeCurrentAmount: cumCurrent,
cumulativeDeltaAbs: cumDeltaAbs, cumulativeDeltaAbs: cumDeltaAbs,
cumulativeDeltaPct: cumDeltaPct, cumulativeDeltaPct: cumDeltaPct,
category_type: section,
}; };
}); });
} }
@ -488,7 +541,7 @@ function monthBoundaries(year: number, month: number): { start: string; end: str
// --- Generic leaf-driven tree builder (Issue #263) --- // --- Generic leaf-driven tree builder (Issue #263) ---
/** Section key shared by every hierarchical report (income-statement order). */ /** Section key shared by every hierarchical report (income-statement order). */
export type TreeSectionType = "expense" | "income" | "transfer"; export type TreeSectionType = ReportSection;
/** /**
* Minimal category metadata every hierarchical report needs: id, display * Minimal category metadata every hierarchical report needs: id, display
@ -697,19 +750,20 @@ type CompareCatMeta = TreeCatMeta;
const COMPARE_CATEGORIES_SQL = `SELECT id, name, color, type, parent_id FROM categories`; const COMPARE_CATEGORIES_SQL = `SELECT id, name, color, type, parent_id FROM categories`;
// Income statement reading order: revenues first, then expenses, then the // Income statement reading order: revenues first, then expenses, the
// (netted) transfers — the two result lines are injected around them in the UI. // uncategorized line, then the (netted) transfers — the two result lines are
const COMPARE_TYPE_ORDER: Record<string, number> = { income: 0, expense: 1, transfer: 2 }; // injected around them in the UI (ADR 0026).
const COMPARE_TYPE_ORDER: Record<string, number> = SECTION_ORDER;
/** /**
* Turns the flat per-category deltas returned by compareDeltaSql() into a * Turns the flat per-category deltas returned by compareDeltaSql() into a
* parent/child tree with subtotal (`is_parent`) rows, mirroring the hierarchy of * parent/child tree with subtotal (`is_parent`) rows, mirroring the hierarchy of
* getBudgetVsActualData. * getBudgetVsActualData.
* *
* The #243 transfer netting is untouched: leaf values are exactly what the SQL * Leaf values are what rowsToDeltas made of the signed balances of the SQL
* returned, and a subtotal is the arithmetic sum of its descendant leaves — so a * (ADR 0026), and a subtotal is the arithmetic sum of its descendant leaves — so
* group of balanced (netted-to-zero) transfers subtotals to ~0, i.e. the group's * a group of balanced (netted-to-zero) transfers subtotals to 0, the group's net
* net. * (#243), and an expense group nets its refunds.
* *
* A thin specialisation of `buildLeafDrivenTree` (Issue #263): the generic * A thin specialisation of `buildLeafDrivenTree` (Issue #263): the generic
* skeleton drives the hierarchy walk, sibling ordering, depth guard and section * skeleton drives the hierarchy walk, sibling ordering, depth guard and section
@ -774,13 +828,14 @@ export function buildCompareTree(
// spend as a "(direct)" leaf (mirrors getBudgetVsActualData). // spend as a "(direct)" leaf (mirrors getBudgetVsActualData).
decorateDirectLeaf: (row, cat) => ({ ...row, categoryName: `${cat.name} (direct)` }), decorateDirectLeaf: (row, cat) => ({ ...row, categoryName: `${cat.name} (direct)` }),
// Orphans keep their own already-computed delta; only the hierarchy fields // Orphans keep their own already-computed delta; only the hierarchy fields
// are stamped. Uncategorized rows (category_type undefined) → 'expense'. // are stamped. An orphan is a row without an existing category: the
// uncategorized line (ADR 0026), the section rowsToDeltas gives it.
makeOrphan: (d) => ({ makeOrphan: (d) => ({
...d, ...d,
parent_id: null, parent_id: null,
is_parent: false, is_parent: false,
depth: 0, depth: 0,
category_type: d.category_type ?? "expense", category_type: d.category_type ?? "uncategorized",
}), }),
sortKey: (row) => Math.abs(row.deltaAbs), sortKey: (row) => Math.abs(row.deltaAbs),
isSubtotal: (row) => row.is_parent === true, isSubtotal: (row) => row.is_parent === true,
@ -845,14 +900,14 @@ export function buildOverTimeTree(
// A parent with both children and its own transactions surfaces the direct // A parent with both children and its own transactions surfaces the direct
// spend as a "(direct)" leaf (mirrors buildCompareTree / getBudgetVsActualData). // spend as a "(direct)" leaf (mirrors buildCompareTree / getBudgetVsActualData).
decorateDirectLeaf: (row, cat) => ({ ...row, categoryName: `${cat.name} (direct)` }), decorateDirectLeaf: (row, cat) => ({ ...row, categoryName: `${cat.name} (direct)` }),
// Orphans (Uncategorized / hard-deleted) keep their own series; only the // Orphans (rows without an existing category) keep their own series; only
// hierarchy fields are stamped. No metadata → default 'expense'. // the hierarchy fields are stamped. No metadata → the uncategorized line.
makeOrphan: (l) => ({ makeOrphan: (l) => ({
...l, ...l,
parent_id: null, parent_id: null,
is_parent: false, is_parent: false,
depth: 0, depth: 0,
category_type: l.category_type ?? "expense", category_type: l.category_type ?? "uncategorized",
}), }),
sortKey: (row) => Math.abs(row.total), sortKey: (row) => Math.abs(row.total),
isSubtotal: (row) => row.is_parent === true, isSubtotal: (row) => row.is_parent === true,
@ -871,48 +926,42 @@ function previousMonth(year: number, month: number): { year: number; month: numb
* exact same query — only the eight date bounds differ). Four date buckets * exact same query — only the eight date bounds differ). Four date buckets
* ($1..$8): monthly current/previous and cumulative current/previous. * ($1..$8): monthly current/previous and cumulative current/previous.
* *
* This report is an INCOME STATEMENT ("analyse de résultat", Issue #253), not a * This report is an INCOME STATEMENT ("analyse de résultat", Issue #253): each
* pure expense report: revenues are surfaced alongside expenses so the compare * bucket is the signed balance of the category (#392, ADR 0026), splits and
* can show a result (revenues − expenses). Per-category sign convention: * refunds included, with the category's section; rowsToDeltas turns it into
* - `income` and `transfer` categories use a signed SUM(t.amount). Income * what the row shows (an expense its spending). A split is counted once: its
* credits stay positive; a `transfer` debit/credit pair (e.g. "Paiement CC": * parent keeps its amount and the offset line cancels, in the parent's
* -500 out, +500 in) nets to ~0 (Issue #243 — a money move, not spending). * category, the parts sent elsewhere. A `transfer` debit/credit pair (e.g.
* - Every other type keeps the expense-report behavior: only outflows * "Paiement CC": -500 out, +500 in) nets to 0 (Issue #243). Every row without
* (amount < 0) count, summed as positive magnitudes via ABS. * an existing category is one group (`c.id` NULL), the uncategorized line. The
* * result lines are computed from the per-section subtotals (compareResults),
* The WHERE admits outflows OR any income/transfer row, so income and transfer * not here. `ABS` only orders the rows.
* *credits* survive the `amount < 0` filter — without it a pure-income category
* would be dropped entirely and a transfer could never net to zero. Expense
* rows still contribute only their outflows, byte-identical to before. The two
* result lines (before/after transfers) are computed in ComparePeriodTable from
* the per-type subtotals, not here. Uncategorized rows (c.type NULL) → 'expense'.
* *
* `accountIds` (Issue #273) adds an optional `t.source_id IN (...)` clause — * `accountIds` (Issue #273) adds an optional `t.source_id IN (...)` clause —
* one bound placeholder per id, starting at $9 (the 8 date bounds occupy * one bound placeholder per id, starting at $9 (the 8 date bounds occupy
* $1-$8). Omitted/empty → no clause at all, so the query text and results stay * $1-$8). Omitted/empty → no clause at all.
* byte-identical to the pre-#273 behavior.
*/ */
function compareDeltaSql(accountIds?: number[]): string { function compareDeltaSql(accountIds?: number[]): string {
const accountPlaceholders = inPlaceholders(accountIds, 9); const accountPlaceholders = inPlaceholders(accountIds, 9);
const accountFilter = accountPlaceholders ? ` AND t.source_id IN (${accountPlaceholders})` : ""; const accountFilter = accountPlaceholders ? ` AND t.source_id IN (${accountPlaceholders})` : "";
return `SELECT return `SELECT
t.category_id, c.id AS category_id,
COALESCE(c.name, 'Uncategorized') AS category_name, COALESCE(c.name, 'Uncategorized') AS category_name,
COALESCE(c.color, '#9ca3af') AS category_color, COALESCE(c.color, '#9ca3af') AS category_color,
COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN CASE WHEN COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount) END ELSE 0 END), 0) AS month_current_total, ${SECTION_SQL} AS section,
COALESCE(SUM(CASE WHEN t.date >= $3 AND t.date <= $4 THEN CASE WHEN COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount) END ELSE 0 END), 0) AS month_previous_total, COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN t.amount ELSE 0 END), 0) AS month_current_total,
COALESCE(SUM(CASE WHEN t.date >= $5 AND t.date <= $6 THEN CASE WHEN COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount) END ELSE 0 END), 0) AS cumulative_current_total, COALESCE(SUM(CASE WHEN t.date >= $3 AND t.date <= $4 THEN t.amount ELSE 0 END), 0) AS month_previous_total,
COALESCE(SUM(CASE WHEN t.date >= $7 AND t.date <= $8 THEN CASE WHEN COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount) END ELSE 0 END), 0) AS cumulative_previous_total COALESCE(SUM(CASE WHEN t.date >= $5 AND t.date <= $6 THEN t.amount ELSE 0 END), 0) AS cumulative_current_total,
COALESCE(SUM(CASE WHEN t.date >= $7 AND t.date <= $8 THEN t.amount ELSE 0 END), 0) AS cumulative_previous_total
FROM transactions t FROM transactions t
LEFT JOIN categories c ON t.category_id = c.id ${CATEGORY_JOIN_SQL}
WHERE (t.amount < 0 OR COALESCE(c.type, 'expense') IN ('transfer', 'income')) WHERE (
AND (
(t.date >= $1 AND t.date <= $2) (t.date >= $1 AND t.date <= $2)
OR (t.date >= $3 AND t.date <= $4) OR (t.date >= $3 AND t.date <= $4)
OR (t.date >= $5 AND t.date <= $6) OR (t.date >= $5 AND t.date <= $6)
OR (t.date >= $7 AND t.date <= $8) OR (t.date >= $7 AND t.date <= $8)
)${accountFilter} )${accountFilter}
GROUP BY t.category_id, category_name, category_color GROUP BY c.id
ORDER BY ABS(month_current_total - month_previous_total) DESC`; ORDER BY ABS(month_current_total - month_previous_total) DESC`;
} }
@ -1038,6 +1087,11 @@ const ZOOM_DATE_BOUNDS = "($2 IS NULL OR t.date >= $2) AND ($3 IS NULL OR t.date
* false, only direct transactions on `categoryId` are considered. Every * false, only direct transactions on `categoryId` are considered. Every
* query is parameterised; the category id is never interpolated. An absent * query is parameterised; the category id is never interpolated. An absent
* `dateFrom` or `dateTo` is no bound on that side (« Tout »). * `dateFrom` or `dateTo` is no bound on that side (« Tout »).
*
* The total, each child and each month are signed balances (#392, ADR 0026),
* splits and refunds netted, shown the way of the zoomed category's type: a
* zoom on an expense category shows its spending, the opposite of its balance.
* `ABS` only orders the transactions.
*/ */
export async function getCategoryZoom( export async function getCategoryZoom(
categoryId: number, categoryId: number,
@ -1074,12 +1128,17 @@ export async function getCategoryZoom(
params, params,
); );
// 2. Rollup total (sum of absolute amounts of matching rows) // 2. Rollup total: the signed balance of the matching rows, with the type of
const totalRows = await db.select<Array<{ rollup: number | null }>>( // the zoomed category, which orients every figure of the zoom.
`${categoryFilter.replace("SELECT t.id, t.date, t.description, t.amount, t.category_id", "SELECT COALESCE(SUM(ABS(t.amount)), 0) AS rollup")}`, const totalRows = await db.select<Array<{ rollup: number | null; category_type: string | null }>>(
`${categoryFilter.replace(
"SELECT t.id, t.date, t.description, t.amount, t.category_id",
"SELECT COALESCE(SUM(t.amount), 0) AS rollup, (SELECT type FROM categories WHERE id = $1) AS category_type",
)}`,
params, params,
); );
const rollupTotal = Number(totalRows[0]?.rollup ?? 0); const section = toSection(totalRows[0]?.category_type);
const rollupTotal = orient(section, Number(totalRows[0]?.rollup ?? 0));
// 3. Breakdown by direct child (only meaningful when includeSubcategories is true) // 3. Breakdown by direct child (only meaningful when includeSubcategories is true)
const byChild: CategoryZoomChild[] = []; const byChild: CategoryZoomChild[] = [];
@ -1090,13 +1149,12 @@ export async function getCategoryZoom(
`SELECT child.id AS child_id, `SELECT child.id AS child_id,
child.name AS child_name, child.name AS child_name,
COALESCE(child.color, '#9ca3af') AS child_color, COALESCE(child.color, '#9ca3af') AS child_color,
COALESCE(SUM(ABS(t.amount)), 0) AS total COALESCE(SUM(t.amount), 0) AS total
FROM categories child FROM categories child
LEFT JOIN transactions t ON t.category_id = child.id LEFT JOIN transactions t ON t.category_id = child.id
AND ${ZOOM_DATE_BOUNDS} AND ${ZOOM_DATE_BOUNDS}
WHERE child.parent_id = $1 WHERE child.parent_id = $1
GROUP BY child.id, child.name, child.color GROUP BY child.id, child.name, child.color`,
ORDER BY total DESC`,
params, params,
); );
for (const r of childRows) { for (const r of childRows) {
@ -1104,16 +1162,18 @@ export async function getCategoryZoom(
categoryId: r.child_id, categoryId: r.child_id,
categoryName: r.child_name, categoryName: r.child_name,
categoryColor: r.child_color, categoryColor: r.child_color,
total: Number(r.total ?? 0), total: orient(section, Number(r.total ?? 0)),
}); });
} }
// Largest first, once each child shows what it shows.
byChild.sort((a, b) => b.total - a.total);
} }
// 4. Monthly evolution across the window // 4. Monthly evolution across the window
const evolutionRows = await db.select<Array<{ month: string; total: number | null }>>( const evolutionRows = await db.select<Array<{ month: string; total: number | null }>>(
`${includeSubcategories ? CATEGORY_TREE_CTE : ""} `${includeSubcategories ? CATEGORY_TREE_CTE : ""}
SELECT strftime('%Y-%m', t.date) AS month, SELECT strftime('%Y-%m', t.date) AS month,
COALESCE(SUM(ABS(t.amount)), 0) AS total COALESCE(SUM(t.amount), 0) AS total
FROM transactions t FROM transactions t
WHERE ${includeSubcategories WHERE ${includeSubcategories
? "t.category_id IN (SELECT id FROM cat_tree)" ? "t.category_id IN (SELECT id FROM cat_tree)"
@ -1125,7 +1185,7 @@ export async function getCategoryZoom(
); );
const monthlyEvolution: CategoryZoomEvolutionPoint[] = evolutionRows.map((r) => ({ const monthlyEvolution: CategoryZoomEvolutionPoint[] = evolutionRows.map((r) => ({
month: r.month, month: r.month,
total: Number(r.total ?? 0), total: orient(section, Number(r.total ?? 0)),
})); }));
return { return {
@ -1189,42 +1249,17 @@ function buildKpi(
}; };
} }
interface RawMonthFlow {
month: string;
income: number | null;
expenses: number | null;
}
async function fetchMonthlyFlows(
dateFrom: string,
dateTo: string,
accountIds?: number[],
): Promise<RawMonthFlow[]> {
const db = await getDb();
const params: unknown[] = [dateFrom, dateTo];
const accountPlaceholders = inPlaceholders(accountIds, 3);
const accountClause = accountPlaceholders
? ` AND source_id IN (${accountPlaceholders})`
: "";
if (accountPlaceholders) params.push(...accountIds!);
return db.select<RawMonthFlow[]>(
`SELECT
strftime('%Y-%m', date) AS month,
COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) AS income,
ABS(COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0)) AS expenses
FROM transactions
WHERE date >= $1 AND date <= $2${accountClause}
GROUP BY month
ORDER BY month ASC`,
params,
);
}
interface RawSeasonalityRow { interface RawSeasonalityRow {
year: number; year: number;
amount: number | null; /** Signed balance of the expense categories in that year's month. */
balance: number | null;
} }
/**
* The expense balance of one calendar month across a range of years. Every
* year with a transaction in that month has a row, its expense balance 0 when
* it holds no expense.
*/
async function fetchSeasonality( async function fetchSeasonality(
month: number, month: number,
yearFrom: number, yearFrom: number,
@ -1236,17 +1271,18 @@ async function fetchSeasonality(
const params: unknown[] = [mm, yearFrom, yearTo]; const params: unknown[] = [mm, yearFrom, yearTo];
const accountPlaceholders = inPlaceholders(accountIds, 4); const accountPlaceholders = inPlaceholders(accountIds, 4);
const accountClause = accountPlaceholders const accountClause = accountPlaceholders
? ` AND source_id IN (${accountPlaceholders})` ? ` AND t.source_id IN (${accountPlaceholders})`
: ""; : "";
if (accountPlaceholders) params.push(...accountIds!); if (accountPlaceholders) params.push(...accountIds!);
return db.select<RawSeasonalityRow[]>( return db.select<RawSeasonalityRow[]>(
`SELECT `SELECT
CAST(strftime('%Y', date) AS INTEGER) AS year, CAST(strftime('%Y', t.date) AS INTEGER) AS year,
ABS(COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0)) AS amount COALESCE(SUM(CASE WHEN ${SECTION_SQL} = 'expense' THEN t.amount END), 0) AS balance
FROM transactions FROM transactions t
WHERE strftime('%m', date) = $1 ${CATEGORY_JOIN_SQL}
AND CAST(strftime('%Y', date) AS INTEGER) >= $2 WHERE strftime('%m', t.date) = $1
AND CAST(strftime('%Y', date) AS INTEGER) <= $3${accountClause} AND CAST(strftime('%Y', t.date) AS INTEGER) >= $2
AND CAST(strftime('%Y', t.date) AS INTEGER) <= $3${accountClause}
GROUP BY year GROUP BY year
ORDER BY year DESC`, ORDER BY year DESC`,
params, params,
@ -1258,18 +1294,22 @@ async function fetchSeasonality(
* data for the Cartes report, computed against a reference (year, month). * data for the Cartes report, computed against a reference (year, month).
* *
* Layout (all concurrent): * Layout (all concurrent):
* 1. 25-month expense/income series (covers ref, MoM, YoY, 12-month flow, * 1. 25-month income statement series (`getMonthlyTrends`, the query of
* 13-month sparklines without any extra round trips). * Trends; covers ref, MoM, YoY, 12-month flow, 13-month sparklines
* without any extra round trips).
* 2. Month-over-month category deltas for top movers (existing service). * 2. Month-over-month category deltas for top movers (existing service).
* 3. Year-over-year category deltas to seed the savings-rate YoY lookup * 3. Budget vs actual for the reference month.
* via the monthly series instead of re-querying. * 4. Seasonality: same calendar month across the two prior years.
* 4. Budget vs actual for the reference month. *
* 5. Seasonality: same calendar month across the two prior years. * Every figure follows the sign convention of the reports (#392, ADR 0026):
* « Solde net » is the net result, the sum of every amount (D5), with its
* uncategorized and transfer parts in `netBreakdown`; the savings rate is
* (income − expenses) ÷ income (D6).
* *
* `accountIds` (Issues #273/#279) is forwarded to every sub-query so the whole * `accountIds` (Issues #273/#279) is forwarded to every sub-query so the whole
* dashboard honours an active account filter: the top-movers * dashboard honours an active account filter: the top-movers
* (`getCompareMonthOverMonth`) and budget (`getBudgetVsActualData`) sub-reports, * (`getCompareMonthOverMonth`) and budget (`getBudgetVsActualData`) sub-reports,
* and the KPI/sparkline/seasonality series (`fetchMonthlyFlows`, * and the KPI/sparkline/seasonality series (`getMonthlyTrends`,
* `fetchSeasonality`). Omitting it anywhere would let the dashboard silently mix * `fetchSeasonality`). Omitting it anywhere would let the dashboard silently mix
* filtered and unfiltered figures on the same screen. * filtered and unfiltered figures on the same screen.
*/ */
@ -1288,30 +1328,22 @@ export async function getCartesSnapshot(
// Seasonality range: previous 2 years for the same calendar month. // Seasonality range: previous 2 years for the same calendar month.
const [seasonalityRows, flowRows, momRows, budgetRows] = await Promise.all([ const [seasonalityRows, flowRows, momRows, budgetRows] = await Promise.all([
fetchSeasonality(referenceMonth, referenceYear - 2, referenceYear - 1, accountIds), fetchSeasonality(referenceMonth, referenceYear - 2, referenceYear - 1, accountIds),
fetchMonthlyFlows(windowStartIso, refEnd, accountIds), getMonthlyTrends(windowStartIso, refEnd, accountIds),
getCompareMonthOverMonth(referenceYear, referenceMonth, accountIds), getCompareMonthOverMonth(referenceYear, referenceMonth, accountIds),
getBudgetVsActualData(referenceYear, referenceMonth, accountIds), getBudgetVsActualData(referenceYear, referenceMonth, accountIds),
]); ]);
// Index the flow rows by month for O(1) lookup, then fill missing months // Index the monthly statements by month for O(1) lookup, then fill missing
// with zeroes so downstream consumers get a contiguous series. // months with zeroes so downstream consumers get a contiguous series.
const flowByMonth = new Map<string, { income: number; expenses: number }>(); const flowByMonth = new Map<string, IncomeStatementFigures>();
for (const r of flowRows) { for (const { month, ...figures } of flowRows) flowByMonth.set(month, figures);
flowByMonth.set(r.month, {
income: Number(r.income ?? 0),
expenses: Number(r.expenses ?? 0),
});
}
const buildSeries = (count: number): CartesMonthFlow[] => { const buildSeries = (count: number): CartesMonthFlow[] => {
const series: CartesMonthFlow[] = []; const series: CartesMonthFlow[] = [];
for (let i = count - 1; i >= 0; i--) { for (let i = count - 1; i >= 0; i--) {
const { year: y, month: m } = shiftMonth(referenceYear, referenceMonth, -i); const { year: y, month: m } = shiftMonth(referenceYear, referenceMonth, -i);
const key = monthKey(y, m); const key = monthKey(y, m);
const row = flowByMonth.get(key); series.push({ month: key, ...(flowByMonth.get(key) ?? EMPTY_STATEMENT) });
const income = row?.income ?? 0;
const expenses = row?.expenses ?? 0;
series.push({ month: key, income, expenses, net: income - expenses });
} }
return series; return series;
}; };
@ -1332,7 +1364,7 @@ export async function getCartesSnapshot(
})); }));
const savingsSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({ const savingsSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({
month: p.month, month: p.month,
value: p.income > 0 ? (p.net / p.income) * 100 : 0, value: savingsRate(p.income, p.expenses) ?? 0,
})); }));
// Compute MoM / YoY values directly from `flowByMonth` (which preserves the // Compute MoM / YoY values directly from `flowByMonth` (which preserves the
@ -1344,99 +1376,62 @@ export async function getCartesSnapshot(
const yoyMeta = { year: referenceYear - 1, month: referenceMonth }; const yoyMeta = { year: referenceYear - 1, month: referenceMonth };
const yoyKey = monthKey(yoyMeta.year, yoyMeta.month); const yoyKey = monthKey(yoyMeta.year, yoyMeta.month);
// Monthly aggregates — the "month" mode default behavior. // The four KPI figures of a period, or null for a period without data.
const refRow = flowByMonth.get(refKey); // « Solde net » is the net result (D5); the savings rate is undefined when
const monthRefIncome = refRow?.income ?? 0; // income is not positive — null rather than a misleading "0 %" in the UI (D6).
const monthRefExpenses = refRow?.expenses ?? 0; const kpiFigures = (s: IncomeStatementFigures | undefined) => ({
const monthRefNet = monthRefIncome - monthRefExpenses; income: s ? s.income : null,
// Savings rate is undefined when income is zero — expose as null rather than expenses: s ? s.expenses : null,
// rendering a misleading "0 %" in the UI. net: s ? s.net : null,
const monthRefSavings = monthRefIncome > 0 ? (monthRefNet / monthRefIncome) * 100 : null; savings: s ? savingsRate(s.income, s.expenses) : null,
});
const momRow = flowByMonth.get(momKey); // YTD aggregates — sum the monthly statements from January of a given year
const monthMomIncome = momRow ? momRow.income : null; // up to (and including) `upToMonth`. Reuses the already-fetched
const monthMomExpenses = momRow ? momRow.expenses : null; // `flowByMonth` map, so no additional SQL round trip is required. Missing
const monthMomNet = momRow ? momRow.income - momRow.expenses : null; // months contribute zero to the sum (unlike monthly deltas which preserve
const monthMomSavings = // the null distinction).
momRow && momRow.income > 0 ? ((momRow.income - momRow.expenses) / momRow.income) * 100 : null; const sumYtd = (year: number, upToMonth: number): IncomeStatementFigures => {
let sum = EMPTY_STATEMENT;
const yoyRow = flowByMonth.get(yoyKey);
const monthYoyIncome = yoyRow ? yoyRow.income : null;
const monthYoyExpenses = yoyRow ? yoyRow.expenses : null;
const monthYoyNet = yoyRow ? yoyRow.income - yoyRow.expenses : null;
const monthYoySavings =
yoyRow && yoyRow.income > 0 ? ((yoyRow.income - yoyRow.expenses) / yoyRow.income) * 100 : null;
// YTD aggregates — sum monthly flows from January of a given year up to (and
// including) `upToMonth`. Reuses the already-fetched `flowByMonth` map, so
// no additional SQL round trip is required. Missing months contribute zero
// to the sum (unlike monthly deltas which preserve the null distinction).
const sumYtd = (year: number, upToMonth: number): { income: number; expenses: number } => {
let income = 0;
let expenses = 0;
for (let m = 1; m <= upToMonth; m++) { for (let m = 1; m <= upToMonth; m++) {
const row = flowByMonth.get(monthKey(year, m)); const row = flowByMonth.get(monthKey(year, m));
if (row) { if (row) sum = addStatements(sum, row);
income += row.income;
expenses += row.expenses;
}
} }
return { income, expenses }; return sum;
}; };
// Current YTD: Jan→refMonth of refYear.
const ytdCurrent = sumYtd(referenceYear, referenceMonth);
const ytdRefIncome = ytdCurrent.income;
const ytdRefExpenses = ytdCurrent.expenses;
const ytdRefNet = ytdRefIncome - ytdRefExpenses;
const ytdRefSavings = ytdRefIncome > 0 ? (ytdRefNet / ytdRefIncome) * 100 : null;
// YTD MoM: previous YTD window is Jan→(refMonth-1) of refYear. When the
// reference month is January, there is no prior window inside the same
// year, so MoM deltas must be null (not zero).
let ytdMomIncome: number | null = null;
let ytdMomExpenses: number | null = null;
let ytdMomNet: number | null = null;
let ytdMomSavings: number | null = null;
if (referenceMonth > 1) {
const prev = sumYtd(referenceYear, referenceMonth - 1);
ytdMomIncome = prev.income;
ytdMomExpenses = prev.expenses;
ytdMomNet = prev.income - prev.expenses;
ytdMomSavings = prev.income > 0 ? ((prev.income - prev.expenses) / prev.income) * 100 : null;
}
// YTD YoY: same window (Jan→refMonth) of the previous calendar year.
const ytdPrevYear = sumYtd(referenceYear - 1, referenceMonth);
const ytdYoyIncome = ytdPrevYear.income;
const ytdYoyExpenses = ytdPrevYear.expenses;
const ytdYoyNet = ytdPrevYear.income - ytdPrevYear.expenses;
const ytdYoySavings =
ytdPrevYear.income > 0 ? (ytdYoyNet / ytdPrevYear.income) * 100 : null;
// Select the KPI aggregate set based on the requested mode. Sparklines are // Select the KPI aggregate set based on the requested mode. Sparklines are
// always the 13-month monthly series regardless of mode — the toggle only // always the 13-month monthly series regardless of mode — the toggle only
// affects the "current" value and its MoM/YoY comparisons. // affects the "current" value and its MoM/YoY comparisons.
const isYtd = mode === "ytd"; const isYtd = mode === "ytd";
const refIncome = isYtd ? ytdRefIncome : monthRefIncome; // Monthly ("month" mode, the default): the reference month vs the month
const refExpenses = isYtd ? ytdRefExpenses : monthRefExpenses; // before it and the same month of the previous year. YTD: Jan→refMonth of
const refNet = isYtd ? ytdRefNet : monthRefNet; // refYear vs Jan→(refMonth-1) of refYear — none when the reference month is
const refSavings = isYtd ? ytdRefSavings : monthRefSavings; // January, so the MoM deltas stay null, not zero — and vs Jan→refMonth of the
// previous calendar year.
const refStatement = isYtd
? sumYtd(referenceYear, referenceMonth)
: (flowByMonth.get(refKey) ?? EMPTY_STATEMENT);
const ref = kpiFigures(refStatement);
const mom = kpiFigures(
isYtd
? referenceMonth > 1
? sumYtd(referenceYear, referenceMonth - 1)
: undefined
: flowByMonth.get(momKey),
);
const yoy = kpiFigures(isYtd ? sumYtd(referenceYear - 1, referenceMonth) : flowByMonth.get(yoyKey));
const kpiMomIncome = isYtd ? ytdMomIncome : monthMomIncome; const incomeKpi = buildKpi(incomeSpark, ref.income, mom.income, yoy.income);
const kpiMomExpenses = isYtd ? ytdMomExpenses : monthMomExpenses; const expensesKpi = buildKpi(expensesSpark, ref.expenses, mom.expenses, yoy.expenses);
const kpiMomNet = isYtd ? ytdMomNet : monthMomNet; const netKpi = buildKpi(netSpark, ref.net, mom.net, yoy.net);
const kpiMomSavings = isYtd ? ytdMomSavings : monthMomSavings; const savingsKpi = buildKpi(savingsSpark, ref.savings, mom.savings, yoy.savings);
const kpiYoyIncome = isYtd ? ytdYoyIncome : monthYoyIncome; // What « Solde net » holds beyond income − expenses, for the note under its card (D5).
const kpiYoyExpenses = isYtd ? ytdYoyExpenses : monthYoyExpenses; const netBreakdown = {
const kpiYoyNet = isYtd ? ytdYoyNet : monthYoyNet; uncategorized: refStatement.uncategorized,
const kpiYoySavings = isYtd ? ytdYoySavings : monthYoySavings; transfers: refStatement.transfers,
};
const incomeKpi = buildKpi(incomeSpark, refIncome, kpiMomIncome, kpiYoyIncome);
const expensesKpi = buildKpi(expensesSpark, refExpenses, kpiMomExpenses, kpiYoyExpenses);
const netKpi = buildKpi(netSpark, refNet, kpiMomNet, kpiYoyNet);
const savingsKpi = buildKpi(savingsSpark, refSavings, kpiMomSavings, kpiYoySavings);
// 12-month income vs expenses series for the overlay chart. // 12-month income vs expenses series for the overlay chart.
const flow12Months = buildSeries(12); const flow12Months = buildSeries(12);
@ -1448,15 +1443,12 @@ export async function getCartesSnapshot(
// net transfers), momRows now also carries revenue rows — and this card is a // net transfers), momRows now also carries revenue rows — and this card is a
// spending view whose colours read "up = red" (more spending is bad), so a // spending view whose colours read "up = red" (more spending is bad), so a
// salary rise must not appear under "biggest increases" in red. Mirror the // salary rise must not appear under "biggest increases" in red. Mirror the
// expense-only filter ComparePeriodChart uses. The surviving expense leaves // expense-only filter ComparePeriodChart uses; the uncategorized line is no
// are byte-identical to the pre-#253 flat output. `momRows` are sorted by // expense either (ADR 0026). Each leaf shows its spending, refunds netted, so
// absolute delta already; filter out near-zero noise and split by sign. // a category whose refunds exceed its purchases moves down like any other.
// `momRows` are sorted by absolute delta already; split by sign.
const significantMovers = momRows.filter( const significantMovers = momRows.filter(
(r) => (r) => !r.is_parent && r.category_type === "expense" && r.deltaAbs !== 0,
!r.is_parent &&
(r.category_type ?? "expense") === "expense" &&
r.deltaAbs !== 0 &&
(r.previousAmount > 0 || r.currentAmount > 0),
); );
// Project the richer CategoryDelta shape down to the narrower CartesTopMover // Project the richer CategoryDelta shape down to the narrower CartesTopMover
// shape so the Cartes dashboard keeps its stable contract regardless of how // shape so the Cartes dashboard keeps its stable contract regardless of how
@ -1481,24 +1473,25 @@ export async function getCartesSnapshot(
.slice(0, 5) .slice(0, 5)
.map(toCartesMover); .map(toCartesMover);
// Budget adherence — only expense categories with a non-zero budget count. // Budget adherence — only expense leaves with a non-zero budget count (a
// Both `monthActual` and `monthBudget` are signed (expense categories are // parent would count again against its own children). `monthActual` and
// stored with a negative sign by `budgetService`), so all comparisons and // `monthBudget` are signed (`budgetService` stores an expense budget
// deltas on the adherence card must go through `Math.abs` — otherwise the // negated): a category's spending is the opposite of its actual, refunds
// `> 0` filter rejects every expense row and the card shows "no budgeted // netted, and its budget the amount entered (ADR 0026). A refund lowers the
// categories this month" even when budgets exist. // spending: it can never read as an overrun, as `Math.abs` made it (#392).
const budgetedExpenseRows = budgetRows.filter( const budgetedExpenseRows = budgetRows.filter(
(r) => r.category_type === "expense" && Math.abs(r.monthBudget) > 0 && !r.is_parent, (r): r is BudgetVsActualRow & { category_id: number } =>
r.category_type === "expense" && r.monthBudget !== 0 && !r.is_parent && r.category_id !== null,
); );
const budgetsInTarget = budgetedExpenseRows.filter( const spendingOf = (r: BudgetVsActualRow) => orient("expense", r.monthActual);
(r) => Math.abs(r.monthActual) <= Math.abs(r.monthBudget), const budgetOf = (r: BudgetVsActualRow) => orient("expense", r.monthBudget);
).length; const budgetsInTarget = budgetedExpenseRows.filter((r) => spendingOf(r) <= budgetOf(r)).length;
const overruns: CartesBudgetWorstOverrun[] = budgetedExpenseRows const overruns: CartesBudgetWorstOverrun[] = budgetedExpenseRows
.map((r) => { .map((r) => {
const actual = Math.abs(r.monthActual); const actual = spendingOf(r);
const budget = Math.abs(r.monthBudget); const budget = budgetOf(r);
const overrunAbs = actual - budget; const overrunAbs = toCents(actual - budget);
const overrunPct = budget > 0 ? (overrunAbs / budget) * 100 : null; const overrunPct = budget > 0 ? (overrunAbs / budget) * 100 : null;
return { return {
categoryId: r.category_id, categoryId: r.category_id,
@ -1524,15 +1517,15 @@ export async function getCartesSnapshot(
// two years. If no data, average stays null. // two years. If no data, average stays null.
const historicalYears: CartesSeasonalityYear[] = seasonalityRows.map((r) => ({ const historicalYears: CartesSeasonalityYear[] = seasonalityRows.map((r) => ({
year: Number(r.year), year: Number(r.year),
amount: Number(r.amount ?? 0), amount: orient("expense", Number(r.balance ?? 0)),
})); }));
const historicalAverage = historicalYears.length const historicalAverage = historicalYears.length
? historicalYears.reduce((sum, r) => sum + r.amount, 0) / historicalYears.length ? toCents(historicalYears.reduce((sum, r) => sum + r.amount, 0) / historicalYears.length)
: null; : null;
// Seasonality compares the reference month's expenses to the same calendar // Seasonality compares the reference month's expenses to the same calendar
// month in previous years — it is intentionally insensitive to the KPI // month in previous years — it is intentionally insensitive to the KPI
// period toggle, so always use the monthly expenses (not the YTD figure). // period toggle, so always use the monthly expenses (not the YTD figure).
const referenceAmount = monthRefExpenses; const referenceAmount = (flowByMonth.get(refKey) ?? EMPTY_STATEMENT).expenses;
const deviationPct = const deviationPct =
historicalAverage !== null && historicalAverage > 0 historicalAverage !== null && historicalAverage > 0
? ((referenceAmount - historicalAverage) / historicalAverage) * 100 ? ((referenceAmount - historicalAverage) / historicalAverage) * 100
@ -1554,6 +1547,7 @@ export async function getCartesSnapshot(
net: netKpi, net: netKpi,
savingsRate: savingsKpi, savingsRate: savingsKpi,
}, },
netBreakdown,
flow12Months, flow12Months,
topMoversUp, topMoversUp,
topMoversDown, topMoversDown,

View file

@ -336,13 +336,6 @@ export interface ImportReport {
export type DashboardPeriod = "month" | "3months" | "6months" | "year" | "12months" | "all" | "custom"; export type DashboardPeriod = "month" | "3months" | "6months" | "year" | "12months" | "all" | "custom";
export interface DashboardSummary {
totalCount: number;
totalAmount: number;
incomeTotal: number;
expenseTotal: number;
}
export interface CategoryBreakdownItem { export interface CategoryBreakdownItem {
category_id: number | null; category_id: number | null;
category_name: string; category_name: string;
@ -422,15 +415,16 @@ export interface CategoryDelta {
cumulativeDeltaAbs: number; cumulativeDeltaAbs: number;
cumulativeDeltaPct: number | null; cumulativeDeltaPct: number | null;
// Hierarchy block (Issue #247) — populated ONLY by the real-vs-real Compare // Hierarchy block (Issue #247) — populated ONLY by the real-vs-real Compare
// tree builder (getCompareMonthOverMonth / getCompareYearOverYear). Flat // (getCompareMonthOverMonth / getCompareYearOverYear), whose rows also carry
// consumers (Highlights movers, Cartes top movers) leave these undefined and // their section (#392). Flat consumers (Highlights movers) leave these
// must not read them. Snake_case (unlike the camelCase value fields above) to // undefined and must not read them. Snake_case (unlike the camelCase value
// mirror BudgetVsActualRow and stay compatible with the shared `reorderRows` // fields above) to mirror BudgetVsActualRow and stay compatible with the
// util. `is_parent` rows are subtotals whose value = the net of their group. // shared `reorderRows` util. `is_parent` rows are subtotals whose value = the
// net of their group.
parent_id?: number | null; parent_id?: number | null;
is_parent?: boolean; is_parent?: boolean;
depth?: number; depth?: number;
category_type?: "expense" | "income" | "transfer"; category_type?: ReportSection;
} }
// Historical alias — used by the highlights hub. Shape identical to CategoryDelta. // Historical alias — used by the highlights hub. Shape identical to CategoryDelta.
@ -469,10 +463,9 @@ export interface HighlightsData {
topTransactions: RecentTransaction[]; topTransactions: RecentTransaction[];
} }
export interface MonthlyTrendItem { /** The income statement of one month (#392, ADR 0026). */
export interface MonthlyTrendItem extends IncomeStatementFigures {
month: string; // "2025-01" month: string; // "2025-01"
income: number;
expenses: number;
} }
export interface CategoryOverTimeItem { export interface CategoryOverTimeItem {
@ -493,7 +486,10 @@ export interface OverTimeRow {
categoryId: number | null; categoryId: number | null;
categoryName: string; categoryName: string;
categoryColor: string; categoryColor: string;
/** Positive magnitude per month, index-aligned to `CategoryOverTimeData.data`. */ /**
* What the row shows per month, index-aligned to `CategoryOverTimeData.data`:
* the signed balance, an expense's spending for an expense row (ADR 0026).
*/
monthly: number[]; monthly: number[];
/** Sum of `monthly` — sibling ordering + row total convenience. */ /** Sum of `monthly` — sibling ordering + row total convenience. */
total: number; total: number;
@ -502,7 +498,7 @@ export interface OverTimeRow {
parent_id: number | null; parent_id: number | null;
is_parent: boolean; is_parent: boolean;
depth: number; depth: number;
category_type: "expense" | "income" | "transfer"; category_type: ReportSection;
} }
export interface CategoryOverTimeData { export interface CategoryOverTimeData {
@ -510,8 +506,8 @@ export interface CategoryOverTimeData {
data: CategoryOverTimeItem[]; data: CategoryOverTimeItem[];
colors: Record<string, string>; colors: Record<string, string>;
categoryIds: Record<string, number | null>; categoryIds: Record<string, number | null>;
/** Category name -> its type. Built from the top-N rows (mirrors `colors`). */ /** Category name -> its section. Built from the top-N rows (mirrors `colors`). */
types: Record<string, "expense" | "income" | "transfer">; types: Record<string, ReportSection>;
/** /**
* Id-keyed hierarchical sidecar (Issue #264): EVERY category (no top-N, no * Id-keyed hierarchical sidecar (Issue #264): EVERY category (no top-N, no
* "Other" bucket), parent-first depth-first, income → expense → transfer. * "Other" bucket), parent-first depth-first, income → expense → transfer.
@ -522,10 +518,11 @@ export interface CategoryOverTimeData {
} }
export interface BudgetVsActualRow { export interface BudgetVsActualRow {
category_id: number; /** Null for the uncategorized line (#392), the only row without a category. */
category_id: number | null;
category_name: string; category_name: string;
category_color: string; category_color: string;
category_type: "expense" | "income" | "transfer"; category_type: ReportSection;
parent_id: number | null; parent_id: number | null;
is_parent: boolean; is_parent: boolean;
depth?: number; depth?: number;
@ -580,11 +577,9 @@ export interface CartesTopMover {
deltaPct: number | null; deltaPct: number | null;
} }
export interface CartesMonthFlow { /** The income statement of one month of the Cartes series (#392, ADR 0026). */
export interface CartesMonthFlow extends IncomeStatementFigures {
month: string; // "YYYY-MM" month: string; // "YYYY-MM"
income: number;
expenses: number;
net: number;
} }
export interface CartesBudgetWorstOverrun { export interface CartesBudgetWorstOverrun {
@ -624,6 +619,11 @@ export interface CartesSnapshot {
net: CartesKpi; net: CartesKpi;
savingsRate: CartesKpi; // value stored as 0-100 savingsRate: CartesKpi; // value stored as 0-100
}; };
/**
* What « Solde net » holds beyond income − expenses, over the KPI period
* (the month, or the year to date): the note under its card (D5, #392).
*/
netBreakdown: { uncategorized: number; transfers: number };
flow12Months: CartesMonthFlow[]; flow12Months: CartesMonthFlow[];
topMoversUp: CartesTopMover[]; topMoversUp: CartesTopMover[];
topMoversDown: CartesTopMover[]; topMoversDown: CartesTopMover[];