fix: a split's offset line follows its parent when it is recategorized (#454)

Recategorizing a split transaction moved the parent only: its offset
line, which cancels in the parent's category the part sent to other
categories, stayed in the former category. Every report adds all rows,
so a transaction of -120 with -50 split to B, moved from A to C, left
+50 in A and -120 in C instead of -70 in C. The keyword path had the
same defect, and its preview also offered the children of a split,
which it then recategorized alone.

- src/utils/splitOffset.ts: isOffsetChild(parent, child), the rule the
  split window already used, extracted and freed from the category: the
  parent's description, the sign opposite to the parent's, a non-zero
  amount (decision D1: no role column, no migration).
- src/services/splitOffsetService.ts: propagateCategoryToOffsets(db,
  parentId, categoryId) gives the parent's new category to the offset
  line, whatever its current category (decision D2: an offset left in a
  former category is repaired at the parent's next change). It runs on
  the caller's transaction handle: no BEGIN/COMMIT, no getDb(), no
  notification. Nothing for an unknown id, a transaction that is not
  split, or a child (children carry is_split = 1 too). Its own module:
  transactionService.ts already imports categorizationService.ts.
- updateTransactionCategory now runs in withTransaction, with its own
  BEGIN, the parent's UPDATE (unchanged, toSqlFlag), the propagation and
  COMMIT, or ROLLBACK and rethrow; it notifies after the COMMIT only.
- previewKeywordMatches offers rows without a parent only; the keyword
  loop's UPDATE skips a child (AND parent_transaction_id IS NULL),
  counts rowsAffected, and propagates for each id before the COMMIT.
- SplitAdjustmentModal leaves out the child isOffsetChild recognizes,
  so an offset left in a former category is no longer shown as a row.

Tests: the regression test of transactionService.test.ts fails on main
(no UPDATE of the offset); the tests of #390 and #396 now find the
parent's UPDATE by its SQL and answer the reads of the propagation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-10-27 22:13:08 -04:00
commit 6db898b7ae
10 changed files with 803 additions and 36 deletions

View file

@ -0,0 +1,106 @@
// SplitAdjustmentModal — which children of a split it shows as entries (#454).
//
// The window loads the children in an effect, then keeps those that are not
// the offset line as its entries. React's hooks come from the shared harness
// (src/test/hookHarness.ts, #409): `commit()` runs the loading effect, the
// test lets its promise settle, then renders again and reads the entries
// through the props of their CategoryCombobox and amount field.
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { ReactNode } from "react";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
import { hookHarness } from "../../test/hookHarness";
import { find } from "../../test/elementTree";
import SplitAdjustmentModal from "./SplitAdjustmentModal";
import CategoryCombobox from "../shared/CategoryCombobox";
import type { SplitChild, TransactionRow } from "../../shared/types";
const harness = hookHarness();
// The reproduction of #454: −120 split as −50 to category B, whose offset line
// of +50 was written in A, the parent's category at the time.
const A = 3;
const B = 4;
const C = 9;
const parentIn = (categoryId: number): TransactionRow => ({
id: 5,
date: "2026-10-01",
description: "EPICERIE METRO",
amount: -120,
category_id: categoryId,
category_name: null,
category_color: null,
source_name: null,
notes: null,
is_manually_categorized: true,
is_split: true,
});
const childOf = (id: number, amount: number, categoryId: number): SplitChild => ({
id,
category_id: categoryId,
category_name: null,
category_color: null,
amount,
description: "EPICERIE METRO",
});
const ENTRY = childOf(6, -50, B);
/** Lets the loading promise settle. */
const flush = async () => {
for (let i = 0; i < 10; i++) await Promise.resolve();
};
/** One render of the mounted window: its entries, as category and amount. */
const entriesOf = (transaction: TransactionRow, children: SplitChild[]) => {
const tree: ReactNode = harness.render(() =>
SplitAdjustmentModal({
transaction,
categories: [],
onLoadChildren: async () => children,
onSave: vi.fn(async () => undefined),
onDelete: vi.fn(async () => undefined),
onClose: vi.fn(),
}),
);
const categories = find(tree, (el) => el.type === CategoryCombobox).map((el) => el.props.value);
const amounts = find(tree, (el) => el.type === "input" && el.props.type === "number").map((el) => el.props.value);
return categories.map((category, i) => ({ category, amount: amounts[i] }));
};
/** Mounts the window, runs its loading effect, and reads the entries once loaded. */
const loadedEntries = async (transaction: TransactionRow, children: SplitChild[]) => {
entriesOf(transaction, children);
harness.commit();
await flush();
return entriesOf(transaction, children);
};
beforeEach(() => harness.clear());
describe("SplitAdjustmentModal — the offset line is never an entry (#454)", () => {
it("leaves out the offset line in the parent's category", async () => {
const entries = await loadedEntries(parentIn(A), [ENTRY, childOf(7, 50, A)]);
expect(entries).toEqual([{ category: B, amount: "50.00" }]);
});
// Decision D2: a reclassification made before #454 left the offset line in A
// while the parent went to C; reopened, the window must not offer it as an
// entry (saving would turn it into a real one).
it("leaves out an offset line left in a former category", async () => {
const entries = await loadedEntries(parentIn(C), [ENTRY, childOf(7, 50, A)]);
expect(entries).toEqual([{ category: B, amount: "50.00" }]);
});
it("keeps an entry of the parent's category, which has the parent's sign", async () => {
const entries = await loadedEntries(parentIn(A), [ENTRY, childOf(8, -20, A), childOf(7, 70, A)]);
expect(entries).toEqual([
{ category: B, amount: "50.00" },
{ category: A, amount: "20.00" },
]);
});
});

View file

@ -2,6 +2,7 @@ import { useState, useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { X, Plus, Trash2 } from "lucide-react";
import type { TransactionRow, Category, SplitChild } from "../../shared/types";
import { isOffsetChild } from "../../utils/splitOffset";
import CategoryCombobox from "../shared/CategoryCombobox";
interface SplitEntry {
@ -46,10 +47,9 @@ export default function SplitAdjustmentModal({
if (!transaction.is_split) return;
setLoading(true);
onLoadChildren(transaction.id).then((children) => {
// Filter out the offset child (same category as parent)
const splitEntries = children.filter(
(c) => c.category_id !== transaction.category_id || Math.sign(c.amount) === Math.sign(transaction.amount)
);
// The offset line is not an entry: leave it out whatever its category,
// one left in a former category by an earlier change included (#454).
const splitEntries = children.filter((c) => !isOffsetChild(transaction, c));
if (splitEntries.length > 0) {
setEntries(
splitEntries.map((c) => ({

View file

@ -31,6 +31,45 @@ beforeEach(() => {
mockExecute.mockReset();
});
/** The statements sent through `execute`, whitespace collapsed, with their parameters. */
const statements = () =>
mockExecute.mock.calls.map(([sql, params]) => ({
sql: String(sql).replace(/\s+/g, " ").trim(),
params: (params ?? []) as unknown[],
}));
/** The last parameter of a statement: the id of its `WHERE id = $n`. */
const targetOf = (statement: { params: unknown[] }) => statement.params[statement.params.length - 1];
/** A transaction that is not split, as the offset propagation reads it (#454). */
const plainRow = (id: number) => ({ id, description: "METRO", amount: -10, is_split: 0, parent_transaction_id: null });
/**
* Answers every read of the keyword path: the lookup of the keyword's spelling
* (`keywordRows`, none by default), then, for each checked id, the offset
* propagation's read of the transaction (`rows`, a transaction that is not
* split by default) and of a split's children (`children`, by parent id;
* #454). Any other read fails the test.
*/
function answerReads({
keywordRows = [],
rows = {},
children = {},
}: {
keywordRows?: Array<{ id: number; category_id: number }>;
rows?: Record<number, Record<string, unknown>>;
children?: Record<number, Array<Record<string, unknown>>>;
} = {}) {
mockSelect.mockImplementation(async (sql: string, params?: unknown[]) => {
const flat = String(sql).replace(/\s+/g, " ");
const id = Number(params?.[0]);
if (/FROM keywords WHERE keyword = \$1/.test(flat)) return keywordRows;
if (/FROM transactions WHERE parent_transaction_id = \$1/.test(flat)) return children[id] ?? [];
if (/FROM transactions WHERE id = \$1/.test(flat)) return [rows[id] ?? plainRow(id)];
throw new Error(`unexpected read: ${flat}`);
});
}
describe("validateKeyword", () => {
it("rejects whitespace-only input", () => {
expect(validateKeyword(" ")).toEqual({ ok: false, reason: "tooShort" });
@ -91,11 +130,22 @@ describe("previewKeywordMatches", () => {
expect(result.visible[0].id).toBe(1);
expect(result.visible[1].id).toBe(2);
});
// An entry or the offset line of a split (which carries the parent's
// description) would be recategorized without its parent (#454).
it("never offers a child of a split: the candidates are rows without a parent (#454)", async () => {
mockSelect.mockResolvedValueOnce([]);
await previewKeywordMatches("METRO");
const sql = String(mockSelect.mock.calls[0][0]).replace(/\s+/g, " ");
expect(sql).toMatch(/WHERE LOWER\(t\.description\) LIKE \$1 AND t\.parent_transaction_id IS NULL ORDER BY/);
});
});
describe("applyKeywordWithReassignment", () => {
it("wraps INSERT + UPDATEs in a BEGIN/COMMIT transaction", async () => {
mockSelect.mockResolvedValueOnce([]); // existing keyword lookup → none
answerReads(); // existing keyword lookup → none; transactions not split
mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 });
await applyKeywordWithReassignment({
@ -115,7 +165,7 @@ describe("applyKeywordWithReassignment", () => {
// The Transactions step card leads to this dialog (#430): the transactions it
// categorizes must count as categorized by hand, so the step checks off.
it("marks every checked transaction as categorized by hand, with a literal 1 (#430)", async () => {
mockSelect.mockResolvedValueOnce([]);
answerReads();
mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 });
await applyKeywordWithReassignment({
@ -138,7 +188,7 @@ describe("applyKeywordWithReassignment", () => {
});
it("rolls back when an UPDATE throws", async () => {
mockSelect.mockResolvedValueOnce([]);
answerReads();
mockExecute
.mockResolvedValueOnce(undefined) // BEGIN
.mockResolvedValueOnce({ lastInsertId: 77 }) // INSERT keywords
@ -160,7 +210,7 @@ describe("applyKeywordWithReassignment", () => {
});
it("blocks reassignment when keyword exists for another category without allowReplaceExisting", async () => {
mockSelect.mockResolvedValueOnce([{ id: 10, category_id: 5 }]);
answerReads({ keywordRows: [{ id: 10, category_id: 5 }] });
await expect(
applyKeywordWithReassignment({
@ -177,7 +227,7 @@ describe("applyKeywordWithReassignment", () => {
});
it("reassigns existing keyword when allowReplaceExisting is true", async () => {
mockSelect.mockResolvedValueOnce([{ id: 10, category_id: 5 }]);
answerReads({ keywordRows: [{ id: 10, category_id: 5 }] });
mockExecute.mockResolvedValue({ rowsAffected: 1 });
const result = await applyKeywordWithReassignment({
@ -243,14 +293,14 @@ describe("applyKeywordWithReassignment — data-change notification (#396)", ()
});
it("notifies once, after the COMMIT and once the DB lock is released", async () => {
mockSelect.mockResolvedValueOnce([]);
answerReads();
mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 });
await applyKeywordWithReassignment(input);
expect(seen).toEqual([{ last: "COMMIT", inLock: false }]);
});
it("does not notify after a ROLLBACK", async () => {
mockSelect.mockResolvedValueOnce([]);
answerReads();
mockExecute
.mockResolvedValueOnce(undefined) // BEGIN
.mockResolvedValueOnce({ lastInsertId: 77 }) // INSERT keywords
@ -266,3 +316,89 @@ describe("applyKeywordWithReassignment — data-change notification (#396)", ()
expect(seen).toEqual([]);
});
});
describe("applyKeywordWithReassignment — a split's offset line follows its parent (#454)", () => {
// The reproduction of #454: −120 in category A, of which −50 are split to B
// (the entry, with the parent's description), and the offset line of +50,
// which cancels those −50 in A. The keyword moves the parent to category 9.
const PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null };
const ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 };
const OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 };
const input = { keyword: "METRO", categoryId: 9, transactionIds: [PARENT.id], allowReplaceExisting: false };
/** The children of PARENT, as the offset propagation reads them. */
const splitReads = () => answerReads({ rows: { [PARENT.id]: PARENT }, children: { [PARENT.id]: [ENTRY, OFFSET] } });
it("moves the offset line of a checked split parent with it, before the COMMIT", async () => {
splitReads();
mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 });
const result = await applyKeywordWithReassignment(input);
const sent = statements();
const offsetMove = sent.findIndex(
(s) => s.sql.startsWith("UPDATE transactions SET category_id = $1, updated_at") && targetOf(s) === OFFSET.id,
);
expect(sent[offsetMove]?.params).toEqual([9, OFFSET.id]);
// The entry keeps its own category.
expect(sent.filter((s) => targetOf(s) === ENTRY.id)).toEqual([]);
expect(sent[0].sql).toBe("BEGIN");
expect(sent[sent.length - 1].sql).toBe("COMMIT");
expect(sent.map((s) => s.sql)).not.toContain("ROLLBACK");
// The count is the transactions the keyword recategorized; the offset line
// that follows its parent is not one of them.
expect(result.updatedTransactions).toBe(1);
});
// The preview no longer offers a child, but an id from elsewhere could still
// reach this path: its UPDATE only matches a row without a parent.
it("never recategorizes a child alone, and counts only the rows changed", async () => {
answerReads({ rows: { [OFFSET.id]: { ...OFFSET, is_split: 1, parent_transaction_id: PARENT.id } } });
// What SQLite answers: the guarded UPDATE matches no row for a child.
mockExecute.mockImplementation(async (sql: string) =>
/AND parent_transaction_id IS NULL/.test(String(sql)) ? { rowsAffected: 0 } : { lastInsertId: 77, rowsAffected: 1 },
);
const result = await applyKeywordWithReassignment({ ...input, transactionIds: [OFFSET.id] });
const updates = statements().filter((s) => s.sql.startsWith("UPDATE transactions"));
expect(updates).toHaveLength(1);
expect(updates[0].sql).toMatch(/ WHERE id = \$2 AND parent_transaction_id IS NULL$/);
expect(updates[0].params).toEqual([9, OFFSET.id]);
expect(result.updatedTransactions).toBe(0);
});
it("rolls the keyword and the transactions back when the offset cannot be moved", async () => {
splitReads();
mockExecute.mockImplementation(async (sql: string, params?: unknown[]) => {
if (String(sql).startsWith("UPDATE transactions SET category_id = $1, updated_at") && params?.[1] === OFFSET.id) {
throw new Error("disk full");
}
return { lastInsertId: 77, rowsAffected: 1 };
});
await expect(applyKeywordWithReassignment(input)).rejects.toThrow("disk full");
const sent = statements().map((s) => s.sql);
expect(sent[0]).toBe("BEGIN");
expect(sent[sent.length - 1]).toBe("ROLLBACK");
expect(sent).not.toContain("COMMIT");
});
// Under the real lock, a getDb() call inside the callback waits for the
// transaction that waits for it: a deadlock (#408).
it("reads and writes the split through the transaction's handle, never through getDb()", async () => {
const outside = vi.fn(async () => {
throw new Error("getDb() inside the transaction deadlocks");
});
vi.mocked(getDb).mockResolvedValue({ select: outside, execute: outside } as never);
vi.mocked(withTransaction).mockImplementationOnce(async (fn) => fn(mockDb as never));
splitReads();
mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 });
await applyKeywordWithReassignment(input);
expect(outside).not.toHaveBeenCalled();
expect(statements().filter((s) => targetOf(s) === OFFSET.id)).toHaveLength(1);
});
});

View file

@ -1,5 +1,6 @@
import { getDb, withTransaction } from "./db";
import { notifyDataChanged } from "./dataEvents";
import { propagateCategoryToOffsets } from "./splitOffsetService";
import type Database from "@tauri-apps/plugin-sql";
import type { Keyword, RecentTransaction } from "../shared/types";
@ -145,6 +146,10 @@ export function validateKeyword(raw: string): { ok: true; value: string } | { ok
* SECURITY: the keyword is never interpolated into the SQL string. `LIKE ?1`
* is the only parameterised binding, and the `%...%` wrapping happens inside
* the bound parameter value.
*
* The children of a split are never offered (#454): an entry or the offset
* line, which carries the parent's description, would be recategorised without
* its parent. The parent is offered, and its offset line follows it.
*/
export async function previewKeywordMatches(
keyword: string,
@ -170,6 +175,7 @@ export async function previewKeywordMatches(
FROM transactions t
LEFT JOIN categories c ON t.category_id = c.id
WHERE LOWER(t.description) LIKE $1
AND t.parent_transaction_id IS NULL
ORDER BY t.date DESC
LIMIT 1000`,
[likePattern],
@ -269,15 +275,20 @@ async function applyKeywordInTransaction(
let updatedTransactions = 0;
for (const txId of input.transactionIds) {
await db.execute(
// A child of a split is never recategorised alone (#454): only its parent
// is, and the parent's offset line follows it, on this same handle and
// before the COMMIT. `updatedTransactions` counts the rows changed.
const result = await db.execute(
`UPDATE transactions
SET category_id = $1,
is_manually_categorized = 1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2`,
WHERE id = $2
AND parent_transaction_id IS NULL`,
[input.categoryId, txId],
);
updatedTransactions++;
updatedTransactions += Number(result.rowsAffected ?? 0);
await propagateCategoryToOffsets(db, txId, input.categoryId);
}
await db.execute("COMMIT");

View file

@ -0,0 +1,151 @@
// propagateCategoryToOffsets — what follows a recategorized split parent (#454).
//
// The function runs inside its caller's transaction, on the handle the caller
// passes: the tests hand it a fake handle and read what it sends. getDb()
// rejects, so a call to it (a deadlock under the real lock, inside a
// withTransaction callback) fails the test, and a subscriber catches any
// data-change notification, which belongs to the caller, after its COMMIT.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
vi.mock("./db", () => ({
getDb: vi.fn(async () => {
throw new Error("getDb() inside a transaction deadlocks");
}),
withTransaction: vi.fn(async () => {
throw new Error("the caller holds the transaction");
}),
}));
import { subscribeDataChanged } from "./dataEvents";
import { propagateCategoryToOffsets } from "./splitOffsetService";
const select = vi.fn();
const execute = vi.fn();
const handle = { select, execute } as never;
/** The statements sent, whitespace collapsed, with their parameters. */
const sent = () =>
execute.mock.calls.map(([sql, params]) => ({ sql: String(sql).replace(/\s+/g, " ").trim(), params }));
/** The reads, whitespace collapsed, with their parameters. */
const reads = () =>
select.mock.calls.map(([sql, params]) => ({ sql: String(sql).replace(/\s+/g, " ").trim(), params }));
/** Answers the read of the row by its id, then the read of its children. */
function answer(row: Record<string, unknown> | undefined, children: Array<Record<string, unknown>> = []) {
select.mockImplementation(async (sql: string) =>
/WHERE parent_transaction_id = \$1/.test(String(sql)) ? children : row ? [row] : [],
);
}
// The reproduction of #454: −120 split as −50 to another category (the entry,
// with the parent's description) and the offset line of +50.
const PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null };
const ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 };
const OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 };
const notifications: number[] = [];
let stop: () => void = () => undefined;
beforeEach(() => {
select.mockReset();
execute.mockReset();
execute.mockResolvedValue({ rowsAffected: 1 });
notifications.length = 0;
stop = subscribeDataChanged(() => notifications.push(1));
});
afterEach(() => {
stop();
});
describe("propagateCategoryToOffsets — which rows it moves (#454)", () => {
it("moves the offset line of a split parent, and only it", async () => {
answer(PARENT, [ENTRY, OFFSET]);
await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).resolves.toBe(1);
expect(sent()).toEqual([
{
sql: "UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2",
params: [9, OFFSET.id],
},
]);
});
it("reads the row by its id, then the children by their parent, whatever their category", async () => {
answer(PARENT, [ENTRY, OFFSET]);
await propagateCategoryToOffsets(handle, PARENT.id, 9);
expect(reads()).toEqual([
{
sql: "SELECT id, description, amount, is_split, parent_transaction_id FROM transactions WHERE id = $1",
params: [PARENT.id],
},
{
sql: "SELECT id, description, amount FROM transactions WHERE parent_transaction_id = $1 ORDER BY id",
params: [PARENT.id],
},
]);
});
it("moves the offset line of a split income, the negative child", async () => {
const income = { ...PARENT, amount: 2000 };
const entry = { id: 6, description: "EPICERIE METRO", amount: 500 };
const offset = { id: 7, description: "EPICERIE METRO", amount: -500 };
answer(income, [entry, offset]);
await expect(propagateCategoryToOffsets(handle, income.id, 9)).resolves.toBe(1);
expect(sent().map((s) => s.params)).toEqual([[9, offset.id]]);
});
it("moves the offset line to no category when the parent loses its own", async () => {
answer(PARENT, [ENTRY, OFFSET]);
await propagateCategoryToOffsets(handle, PARENT.id, null);
expect(sent().map((s) => s.params)).toEqual([[null, OFFSET.id]]);
});
it("leaves a child of the opposite sign alone when it carries another description", async () => {
answer(PARENT, [ENTRY, { ...OFFSET, description: "REMBOURSEMENT" }]);
await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).resolves.toBe(0);
expect(sent()).toEqual([]);
});
it("writes nothing for an unknown id", async () => {
answer(undefined);
await expect(propagateCategoryToOffsets(handle, 42, 9)).resolves.toBe(0);
expect(reads()).toHaveLength(1);
expect(sent()).toEqual([]);
});
it("writes nothing, and reads no child, for a transaction that is not split", async () => {
answer({ ...PARENT, is_split: 0 }, [ENTRY, OFFSET]);
await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).resolves.toBe(0);
expect(reads()).toHaveLength(1);
expect(sent()).toEqual([]);
});
// Children carry is_split = 1 too: only the missing parent link makes a parent.
it("writes nothing for a child of a split, which carries is_split = 1 too", async () => {
answer({ ...OFFSET, is_split: 1, parent_transaction_id: PARENT.id }, [ENTRY, OFFSET]);
await expect(propagateCategoryToOffsets(handle, OFFSET.id, 9)).resolves.toBe(0);
expect(reads()).toHaveLength(1);
expect(sent()).toEqual([]);
});
});
describe("propagateCategoryToOffsets — inside the caller's transaction (#454)", () => {
it("sends neither BEGIN, COMMIT nor ROLLBACK, and does not notify", async () => {
answer(PARENT, [ENTRY, OFFSET]);
await propagateCategoryToOffsets(handle, PARENT.id, 9);
expect(sent()).toHaveLength(1);
expect(sent().filter((s) => /^(BEGIN|COMMIT|ROLLBACK)\b/.test(s.sql))).toEqual([]);
expect(notifications).toEqual([]);
});
it("lets a failed move reach the caller, which rolls back", async () => {
answer(PARENT, [ENTRY, OFFSET]);
execute.mockRejectedValueOnce(new Error("disk full"));
await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).rejects.toThrow("disk full");
expect(sent().map((s) => s.sql)).toEqual([
"UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2",
]);
expect(notifications).toEqual([]);
});
});

View file

@ -0,0 +1,80 @@
// splitOffsetService — a split's offset line follows its parent (#454).
//
// Shared by the two paths that recategorize a transaction: the category chosen
// in the Transactions list (`updateTransactionCategory`, transactionService.ts)
// and a keyword applied with reassignment (`applyKeywordWithReassignment`,
// categorizationService.ts). It has a module of its own because
// transactionService.ts already imports categorizationService.ts: exported
// from either one, it would make an import cycle. It imports neither.
import type Database from "@tauri-apps/plugin-sql";
import { isOffsetChild } from "../utils/splitOffset";
import { toSqlFlag } from "../utils/sqlFlag";
interface ParentRow {
id: number;
description: string;
amount: number;
is_split: unknown;
parent_transaction_id: number | null;
}
interface ChildRow {
id: number;
description: string;
amount: number;
}
/**
* Moves the offset line of the split parent `parentId` to `categoryId`, the
* category the caller has just given the parent, and returns the number of
* rows moved (one for a split written by the split window).
*
* Runs on `db`, the handle of the caller's transaction, between the caller's
* BEGIN and COMMIT: it never issues BEGIN, COMMIT or ROLLBACK (it also runs
* inside the BEGIN of the keyword path), never calls `getDb()` (the DB lock is
* not reentrant: inside a `withTransaction` callback, a deadlock) and never
* notifies (the caller does, after its COMMIT).
*
* Writes nothing when `parentId` is not a split parent: an unknown id, a
* transaction that is not split, or a child of a split (children carry
* `is_split = 1` too, so a parent is the row without `parent_transaction_id`).
* An offset line follows whatever its current category, so one left in a
* former category by a change made before #454 is repaired at the parent's
* next change (decision D2 of #454). Its `is_manually_categorized` flag stays
* as it is: nothing reads it on a child.
*/
export async function propagateCategoryToOffsets(
db: Database,
parentId: number,
categoryId: number | null,
): Promise<number> {
const [parent] = await db.select<ParentRow[]>(
`SELECT id, description, amount, is_split, parent_transaction_id
FROM transactions
WHERE id = $1`,
[parentId],
);
if (!parent || toSqlFlag(parent.is_split) === 0 || parent.parent_transaction_id != null) {
return 0;
}
const children = await db.select<ChildRow[]>(
`SELECT id, description, amount
FROM transactions
WHERE parent_transaction_id = $1
ORDER BY id`,
[parentId],
);
let moved = 0;
for (const child of children) {
if (!isOffsetChild(parent, child)) continue;
await db.execute(
`UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2`,
[categoryId, child.id],
);
moved++;
}
return moved;
}

View file

@ -8,7 +8,7 @@ vi.mock("./db", () => {
};
});
import { getDb } from "./db";
import { getDb, withTransaction } from "./db";
import { subscribeDataChanged } from "./dataEvents";
import {
getTransactionCount,
@ -58,45 +58,198 @@ describe("getTransactionCount (#351)", () => {
});
});
/** The statements sent through `execute`, whitespace collapsed, with their parameters. */
const writes = () =>
mockExecute.mock.calls.map(([sql, params]) => ({
sql: String(sql).replace(/\s+/g, " ").trim(),
params: (params ?? []) as unknown[],
}));
/** The last parameter of a statement: the id of its `WHERE id = $n`. */
const targetOf = (write: { params: unknown[] }) => write.params[write.params.length - 1];
/**
* Answers the two reads of the offset propagation (#454): the row of the
* transaction being recategorized, by its id, and the children of a split, by
* `parent_transaction_id`. Any other read fails the test.
*/
function answerSplitReads(row: Record<string, unknown>, children: Array<Record<string, unknown>>) {
mockSelect.mockImplementation(async (sql: string) => {
const flat = String(sql).replace(/\s+/g, " ");
if (/WHERE parent_transaction_id = \$1/.test(flat)) return children;
if (/WHERE id = \$1/.test(flat)) return [row];
throw new Error(`unexpected read: ${flat}`);
});
}
// The reproduction of #454: a transaction of −120 in category A, of which −50
// are split to category B. The split wrote two children: the entry (−50 in B,
// with the parent's description, as the split window writes an entry left
// without one) and the offset line (+50 in A, the parent's description), which
// cancels in A the part sent to B.
const SPLIT_PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null };
const SPLIT_ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 };
const SPLIT_OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 };
/** The category the parent is moved to. */
const C = 9;
/** A transaction that is not split, as the offset propagation reads it. */
const PLAIN = { id: 5, description: "LOYER", amount: -900, is_split: 0, parent_transaction_id: null };
/** The UPDATE of the recategorized transaction itself, found by its SQL: a BEGIN comes first since #454. */
const ownUpdates = () =>
writes().filter((w) => w.sql.startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2"));
describe("updateTransactionCategory (#390)", () => {
// tauri-plugin-sql stores a bound JS boolean as the TEXT 'true', which the
// getting-started checklist's `is_manually_categorized = 1` never matches.
it("binds the manual flag as the integer 1, never as a boolean", async () => {
mockExecute.mockResolvedValueOnce({ rowsAffected: 1 });
answerSplitReads(PLAIN, []);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await updateTransactionCategory(5, 12, true);
expect(mockExecute).toHaveBeenCalledTimes(1);
const params = mockExecute.mock.calls[0][1] as unknown[];
expect(params).toEqual([12, 1, 5]);
expect(typeof params[1]).toBe("number");
const updates = ownUpdates();
expect(updates).toHaveLength(1);
expect(updates[0].params).toEqual([12, 1, 5]);
expect(typeof updates[0].params[1]).toBe("number");
});
it("binds 0 when the category is not set by hand", async () => {
mockExecute.mockResolvedValueOnce({ rowsAffected: 1 });
answerSplitReads(PLAIN, []);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await updateTransactionCategory(5, null, false);
expect(mockExecute.mock.calls[0][1]).toEqual([null, 0, 5]);
expect(ownUpdates().map((w) => w.params)).toEqual([[null, 0, 5]]);
});
});
describe("updateTransactionCategory — data-change notification (#396)", () => {
it("notifies once after the update", async () => {
mockExecute.mockResolvedValueOnce({ rowsAffected: 1 });
await updateTransactionCategory(5, 12, true);
expect(notified).toEqual([1]);
/** At each notification: the last statement sent, and whether the DB lock was held. */
const seen: Array<{ last: string; inLock: boolean }> = [];
let inLock = false;
let stop: () => void = () => undefined;
beforeEach(() => {
seen.length = 0;
inLock = false;
vi.mocked(withTransaction).mockImplementation(async (fn) => {
inLock = true;
try {
return await fn((await getDb()) as never);
} finally {
inLock = false;
}
});
stop = subscribeDataChanged(() => {
const sent = writes();
seen.push({ last: sent[sent.length - 1]?.sql ?? "", inLock });
});
});
it("does not notify when the update fails", async () => {
mockExecute.mockRejectedValueOnce(new Error("database is locked"));
afterEach(() => {
stop();
vi.mocked(withTransaction).mockImplementation(async (fn) => fn((await getDb()) as never));
});
it("notifies once, after the COMMIT and once the DB lock is released", async () => {
answerSplitReads(PLAIN, []);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await updateTransactionCategory(5, 12, true);
expect(seen).toEqual([{ last: "COMMIT", inLock: false }]);
});
it("does not notify when the update fails, and rolls it back", async () => {
answerSplitReads(PLAIN, []);
mockExecute
.mockResolvedValueOnce(undefined) // BEGIN
.mockRejectedValueOnce(new Error("database is locked")); // the transaction's own UPDATE
await expect(updateTransactionCategory(5, 12, true)).rejects.toThrow("database is locked");
expect(notified).toEqual([]);
expect(seen).toEqual([]);
expect(writes().map((w) => w.sql)).toEqual([
"BEGIN",
"UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3",
"ROLLBACK",
]);
});
it("a note changes no counter: updateTransactionNotes stays silent", async () => {
mockExecute.mockResolvedValueOnce({ rowsAffected: 1 });
await updateTransactionNotes(5, "loyer");
expect(seen).toEqual([]);
expect(notified).toEqual([]);
});
});
describe("updateTransactionCategory — a split's offset line follows its parent (#454)", () => {
it("moves the offset to the new category with the parent, between one BEGIN and its COMMIT", async () => {
answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await updateTransactionCategory(SPLIT_PARENT.id, C, true);
const sent = writes();
const parentMove = sent.findIndex(
(w) => w.sql.startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2") && targetOf(w) === SPLIT_PARENT.id,
);
const offsetMove = sent.findIndex(
(w) => w.sql.startsWith("UPDATE transactions SET category_id = $1,") && targetOf(w) === SPLIT_OFFSET.id,
);
// The offset follows the parent to C…
expect(sent[offsetMove]?.params).toEqual([C, SPLIT_OFFSET.id]);
// …the entry keeps its own category…
expect(sent.filter((w) => targetOf(w) === SPLIT_ENTRY.id)).toEqual([]);
// …and both moves sit between one BEGIN and its COMMIT.
expect(sent.map((w) => w.sql).filter((s) => ["BEGIN", "COMMIT", "ROLLBACK"].includes(s))).toEqual([
"BEGIN",
"COMMIT",
]);
expect(sent[0].sql).toBe("BEGIN");
expect(sent[sent.length - 1].sql).toBe("COMMIT");
expect(parentMove).toBeGreaterThan(0);
expect(offsetMove).toBeGreaterThan(0);
});
it("moves nothing else for a transaction that is not split", async () => {
answerSplitReads(PLAIN, []);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await updateTransactionCategory(PLAIN.id, C, true);
expect(writes().map((w) => w.sql)).toEqual([
"BEGIN",
"UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3",
"COMMIT",
]);
});
it("rolls back, rethrows and does not notify when the offset cannot be moved", async () => {
answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]);
mockExecute.mockImplementation(async (sql: string, params?: unknown[]) => {
if (String(sql).startsWith("UPDATE transactions SET category_id = $1, updated_at") && params?.[1] === SPLIT_OFFSET.id) {
throw new Error("disk full");
}
return { rowsAffected: 1 };
});
await expect(updateTransactionCategory(SPLIT_PARENT.id, C, true)).rejects.toThrow("disk full");
const sent = writes().map((w) => w.sql);
expect(sent[0]).toBe("BEGIN");
expect(sent[sent.length - 1]).toBe("ROLLBACK");
expect(sent).not.toContain("COMMIT");
expect(notified).toEqual([]);
});
// Under the real lock, a getDb() call inside the callback waits for the
// transaction that waits for it: a deadlock (#408).
it("sends every statement through the transaction's handle, none through getDb()", async () => {
const outside = vi.fn(async () => {
throw new Error("getDb() inside the transaction deadlocks");
});
vi.mocked(getDb).mockResolvedValue({ select: outside, execute: outside } as never);
vi.mocked(withTransaction).mockImplementationOnce(async (fn) => fn(mockDb as never));
answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]);
mockExecute.mockResolvedValue({ rowsAffected: 1 });
await updateTransactionCategory(SPLIT_PARENT.id, C, true);
expect(outside).not.toHaveBeenCalled();
expect(writes().map((w) => w.sql)).toContain("COMMIT");
});
});
describe("insertBatch — data-change notification (#396)", () => {
const row = (i: number) => ({
date: "2026-09-0" + i,

View file

@ -1,6 +1,8 @@
import { getDb } from "./db";
import type Database from "@tauri-apps/plugin-sql";
import { getDb, withTransaction } from "./db";
import { notifyDataChanged } from "./dataEvents";
import { categorizeBatch } from "./categorizationService";
import { propagateCategoryToOffsets } from "./splitOffsetService";
import {
isLinkedTransactionFkError,
type LinkedTransferTooltipRow,
@ -298,22 +300,49 @@ export async function getTransactionPage(
};
}
/**
* Gives `txId` the category `categoryId`. When `txId` is a split parent, its
* offset line follows it, in the same transaction (#454): left in the former
* category, it would keep there an amount of the opposite sign that matches no
* transaction, and the new category would carry the whole amount.
*/
export async function updateTransactionCategory(
txId: number,
categoryId: number | null,
isManual: boolean
): Promise<void> {
const db = await getDb();
// Never bind the boolean itself: tauri-plugin-sql would store the TEXT
// 'true', which `is_manually_categorized = 1` never matches (#390).
await db.execute(
`UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3`,
[categoryId, toSqlFlag(isManual), txId]
await withTransaction((db) =>
updateTransactionCategoryInTransaction(db, txId, categoryId, isManual)
);
// The manual flag is the "categorize by hand" step (ADR 0022).
// Reached only after the COMMIT (a ROLLBACK rethrows), once the DB lock is
// released. The manual flag is the "categorize by hand" step (ADR 0022).
notifyDataChanged();
}
async function updateTransactionCategoryInTransaction(
db: Database,
txId: number,
categoryId: number | null,
isManual: boolean
): Promise<void> {
// `withTransaction` only holds the DB lock: the BEGIN, the COMMIT and the
// ROLLBACK are this function's.
await db.execute("BEGIN");
try {
// Never bind the boolean itself: tauri-plugin-sql would store the TEXT
// 'true', which `is_manually_categorized = 1` never matches (#390).
await db.execute(
`UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3`,
[categoryId, toSqlFlag(isManual), txId]
);
await propagateCategoryToOffsets(db, txId, categoryId);
await db.execute("COMMIT");
} catch (e) {
await db.execute("ROLLBACK");
throw e;
}
}
export async function updateTransactionNotes(
txId: number,
notes: string

View file

@ -0,0 +1,61 @@
import { describe, it, expect } from "vitest";
import { isOffsetChild } from "./splitOffset";
import type { SplitChild } from "../shared/types";
// The reproduction of #454: −120 split as −50 to category B (the entry, with
// the parent's description, as the split window writes an entry left without
// one) and the offset line of +50, written in the parent's category A.
const A = 3;
const B = 4;
const C = 9;
const PARENT = { description: "EPICERIE METRO", amount: -120 };
/** A child as `getSplitChildren` returns it. */
const child = (amount: number, categoryId: number | null, description = PARENT.description): SplitChild => ({
id: 1,
category_id: categoryId,
category_name: null,
category_color: null,
amount,
description,
});
describe("isOffsetChild (#454)", () => {
it("recognizes the offset line: the parent's description and the opposite sign", () => {
expect(isOffsetChild(PARENT, child(50, A))).toBe(true);
});
// Decision D2: an offset line left in a former category still follows.
it("recognizes it whatever its category", () => {
for (const categoryId of [A, B, C, null]) {
expect(isOffsetChild(PARENT, child(50, categoryId)), `category ${categoryId}`).toBe(true);
}
});
it("refuses an entry, which has the parent's sign, even with the parent's description and category", () => {
expect(isOffsetChild(PARENT, child(-50, B))).toBe(false);
expect(isOffsetChild(PARENT, child(-50, A))).toBe(false);
});
it("refuses a child of the opposite sign that carries another description", () => {
expect(isOffsetChild(PARENT, child(50, A, "REMBOURSEMENT"))).toBe(false);
expect(isOffsetChild(PARENT, child(50, A, "epicerie metro"))).toBe(false);
});
it("refuses an amount of zero", () => {
expect(isOffsetChild(PARENT, child(0, A))).toBe(false);
expect(isOffsetChild(PARENT, child(-0, A))).toBe(false);
});
it("recognizes the offset line of a split income: a positive parent, a negative offset", () => {
const income = { description: "SALAIRE", amount: 2000 };
expect(isOffsetChild(income, child(-500, A, "SALAIRE"))).toBe(true);
expect(isOffsetChild(income, child(500, B, "SALAIRE"))).toBe(false);
});
it("finds no offset line under a parent of zero", () => {
const zero = { description: "EPICERIE METRO", amount: 0 };
expect(isOffsetChild(zero, child(50, A))).toBe(false);
expect(isOffsetChild(zero, child(-50, A))).toBe(false);
});
});

40
src/utils/splitOffset.ts Normal file
View file

@ -0,0 +1,40 @@
// splitOffset — which child of a split transaction is its offset line (#454).
//
// Unrelated to src/shared/splitGate.ts, which decides whether the split window
// opens in the current edition (#369): this module only recognizes rows.
//
// `saveSplitAdjustment` (transactionService.ts) writes a split as children of
// the parent transaction (`parent_transaction_id`): one row per entry, with
// the parent's sign (the split window gives every entry that sign, and the
// parent's description when it has none), plus one offset line of
// `-(sum of the entries)`, with the parent's description, that cancels in the
// parent's category the part sent to other categories. No column marks the
// offset line (decision D1 of #454: no role column, no migration), so this
// predicate is the one rule that recognizes it, shared by the split window,
// which leaves it out of the entries, and by `propagateCategoryToOffsets`
// (splitOffsetService.ts), which moves it with its parent.
//
// "amount = -(sum of the other children)" would not tell it apart: the
// children of a split always sum to zero, so every child satisfies it. The
// rule is ambiguous only for an entry that carries the parent's description
// with the opposite sign, which the split window never writes.
//
// The callers only pass the children of `parent` (`WHERE
// parent_transaction_id = $1`): the predicate reads neither the category nor
// the parent link, so an offset line left in a former category is still
// recognized (decision D2 of #454).
/** The two fields the rule reads, on the parent and on its child. */
export interface SplitLine {
description: string;
amount: number;
}
/** True when `child`, a child of `parent`, is the offset line of its split. */
export function isOffsetChild(parent: SplitLine, child: SplitLine): boolean {
return (
child.amount !== 0 &&
child.description === parent.description &&
Math.sign(child.amount) === -Math.sign(parent.amount)
);
}