Review 32494 of PR #536: an expense can now be negative (refunds above
purchases, ADR 0026), and six percentages divided the change by the signed
previous amount, so a category going from -50 to 80 read +130 $ and -260 %
while its section total, through pct of compareResults.ts, read +280 %. The
compare lines and group subtotals (month and cumulative each), the
Highlights movers and the KPI cards (extractDelta: expenses, « Solde net »,
savings rate) now divide by Math.abs(previous), as pct does.
The test is the reviewer's probe on the harness: a refund alone in Butcher in
September, 80 spent in October. Red on c404f10 (3 tests); each of the six
expressions mutated back alone turns it red.
Fixes #392
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
551 lines
24 KiB
TypeScript
551 lines
24 KiB
TypeScript
/**
|
||
* 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("a negative previous month: a change keeps the sign of the change (review of PR #536)", () => {
|
||
// September: a refund alone in Butcher, an expense of −50. October: 80 spent
|
||
// in Butcher, 10 in Groceries. Butcher rises by 130, +260 % of the size of
|
||
// its previous expense, as the section total (`pct`) already reads it.
|
||
beforeEach(() => {
|
||
insert("2026-09-12", "REMBOURSEMENT BOUCHERIE", 50, BUTCHER);
|
||
insert("2026-10-03", "BOUCHERIE", -80, BUTCHER);
|
||
insert("2026-10-05", "EPICERIE", -10, GROCERIES);
|
||
});
|
||
|
||
it("Compare: the line, its group and the section total agree on the sign", async () => {
|
||
const rows = await getCompareMonthOverMonth(2026, 10);
|
||
const line = (id: number) => rows.find((r) => r.categoryId === id && !r.is_parent)!;
|
||
expect(line(BUTCHER)).toMatchObject({ previousAmount: -50, currentAmount: 80, deltaAbs: 130, deltaPct: 260 });
|
||
// Cumulative: −50 by the end of September, 30 by the end of October.
|
||
expect(line(BUTCHER)).toMatchObject({ cumulativePreviousAmount: -50, cumulativeCurrentAmount: 30, cumulativeDeltaPct: 160 });
|
||
const group = rows.find((r) => r.categoryId === GROCERY_AND_MARKET && r.is_parent)!;
|
||
expect(group).toMatchObject({ previousAmount: -50, currentAmount: 90, deltaAbs: 140, deltaPct: 280 });
|
||
expect(group).toMatchObject({ cumulativeDeltaAbs: 90, cumulativeDeltaPct: 180 });
|
||
const { expense } = compareResults(rows);
|
||
expect([expense.monthPrevious, expense.monthCurrent, expense.monthDelta]).toEqual([-50, 90, 140]);
|
||
});
|
||
|
||
it("Cartes: the mover and the expense card read +260 % and +280 %", async () => {
|
||
const snapshot = await getCartesSnapshot(2026, 10, "month");
|
||
expect(snapshot.topMoversUp.find((m) => m.categoryId === BUTCHER)).toMatchObject({ deltaAbs: 130, deltaPct: 260 });
|
||
expect(snapshot.kpis.expenses).toMatchObject({ current: 90, previousMonth: -50, deltaMoMAbs: 140, deltaMoMPct: 280 });
|
||
});
|
||
|
||
it("Highlights: the mover reads +260 %", async () => {
|
||
const highlights = await getHighlights(2026, 10, 2026, 30, 5, 10, TODAY);
|
||
expect(highlights.topMovers.find((m) => m.categoryId === BUTCHER)).toMatchObject({ deltaAbs: 130, deltaPct: 260 });
|
||
});
|
||
});
|
||
|
||
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]);
|
||
});
|
||
});
|