Simpl-Resultat/src/services/categorizationService.test.ts
le king fu 6db898b7ae 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>
2026-10-27 22:13:08 -04:00

404 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
validateKeyword,
previewKeywordMatches,
applyKeywordWithReassignment,
KEYWORD_MAX_LENGTH,
} from "./categorizationService";
import { subscribeDataChanged } from "./dataEvents";
vi.mock("./db", () => {
const getDb = vi.fn();
return {
getDb,
// Tests don't exercise the real lock; withTransaction just runs the
// callback with whatever db the test wired getDb to resolve, so every
// existing BEGIN/COMMIT/ROLLBACK ordering assertion still holds (the
// service issues them on the mock db inside the callback).
withTransaction: vi.fn(async (fn: (db: any) => any) => fn(await getDb())),
};
});
import { getDb, withTransaction } from "./db";
const mockSelect = vi.fn();
const mockExecute = vi.fn();
const mockDb = { select: mockSelect, execute: mockExecute };
beforeEach(() => {
vi.mocked(getDb).mockResolvedValue(mockDb as never);
mockSelect.mockReset();
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" });
});
it("rejects single-character keywords", () => {
expect(validateKeyword("a")).toEqual({ ok: false, reason: "tooShort" });
});
it("accepts a minimal two-character keyword after trim", () => {
expect(validateKeyword(" ab ")).toEqual({ ok: true, value: "ab" });
});
it("rejects keywords longer than 64 characters (ReDoS cap)", () => {
const long = "a".repeat(KEYWORD_MAX_LENGTH + 1);
expect(validateKeyword(long)).toEqual({ ok: false, reason: "tooLong" });
});
it("accepts keywords at exactly 64 characters", () => {
const borderline = "a".repeat(KEYWORD_MAX_LENGTH);
expect(validateKeyword(borderline)).toEqual({ ok: true, value: borderline });
});
});
describe("previewKeywordMatches", () => {
it("binds the LIKE pattern as a parameter (no interpolation)", async () => {
mockSelect.mockResolvedValueOnce([]);
await previewKeywordMatches("METRO");
expect(mockSelect).toHaveBeenCalledTimes(1);
const sql = mockSelect.mock.calls[0][0] as string;
const params = mockSelect.mock.calls[0][1] as unknown[];
expect(sql).toContain("LIKE $1");
expect(sql).not.toContain("'metro'");
expect(sql).not.toContain("'%metro%'");
expect(params[0]).toBe("%metro%");
});
it("returns an empty preview when the keyword is invalid", async () => {
const result = await previewKeywordMatches("a");
expect(result).toEqual({ visible: [], totalMatches: 0 });
expect(mockSelect).not.toHaveBeenCalled();
});
it("filters candidates with the regex and respects the visible cap", async () => {
// 3 rows: 2 true matches, 1 substring-only (should be dropped by word-boundary)
mockSelect.mockResolvedValueOnce([
{ id: 1, date: "2026-03-15", description: "METRO #123", amount: -45, category_name: null, category_color: null },
{ id: 2, date: "2026-03-02", description: "METRO PLUS", amount: -67.2, category_name: null, category_color: null },
{ id: 3, date: "2026-02-18", description: "METROPOLITAIN", amount: -12, category_name: null, category_color: null },
]);
const result = await previewKeywordMatches("METRO", 2);
expect(result.totalMatches).toBe(2);
expect(result.visible).toHaveLength(2);
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 () => {
answerReads(); // existing keyword lookup → none; transactions not split
mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 });
await applyKeywordWithReassignment({
keyword: "METRO",
categoryId: 3,
transactionIds: [1, 2],
allowReplaceExisting: false,
});
const commands = mockExecute.mock.calls.map((c) => (c[0] as string).trim());
expect(commands[0]).toBe("BEGIN");
expect(commands[commands.length - 1]).toBe("COMMIT");
expect(commands.filter((c) => c.startsWith("INSERT INTO keywords"))).toHaveLength(1);
expect(commands.filter((c) => c.startsWith("UPDATE transactions"))).toHaveLength(2);
});
// 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 () => {
answerReads();
mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 });
await applyKeywordWithReassignment({
keyword: "METRO",
categoryId: 3,
transactionIds: [1, 2],
allowReplaceExisting: false,
});
const updates = mockExecute.mock.calls.filter((c) =>
(c[0] as string).trim().startsWith("UPDATE transactions"),
);
expect(updates.map((c) => c[1])).toEqual([
[3, 1],
[3, 2],
]);
for (const [sql] of updates) {
expect((sql as string).replace(/\s+/g, " ")).toContain("is_manually_categorized = 1,");
}
});
it("rolls back when an UPDATE throws", async () => {
answerReads();
mockExecute
.mockResolvedValueOnce(undefined) // BEGIN
.mockResolvedValueOnce({ lastInsertId: 77 }) // INSERT keywords
.mockRejectedValueOnce(new Error("disk full")); // UPDATE transactions fails
await expect(
applyKeywordWithReassignment({
keyword: "METRO",
categoryId: 3,
transactionIds: [1],
allowReplaceExisting: false,
}),
).rejects.toThrow("disk full");
const commands = mockExecute.mock.calls.map((c) => (c[0] as string).trim());
expect(commands).toContain("BEGIN");
expect(commands).toContain("ROLLBACK");
expect(commands).not.toContain("COMMIT");
});
it("blocks reassignment when keyword exists for another category without allowReplaceExisting", async () => {
answerReads({ keywordRows: [{ id: 10, category_id: 5 }] });
await expect(
applyKeywordWithReassignment({
keyword: "METRO",
categoryId: 3,
transactionIds: [1],
allowReplaceExisting: false,
}),
).rejects.toThrow("keyword_already_exists");
const commands = mockExecute.mock.calls.map((c) => (c[0] as string).trim());
expect(commands).toContain("BEGIN");
expect(commands).toContain("ROLLBACK");
});
it("reassigns existing keyword when allowReplaceExisting is true", async () => {
answerReads({ keywordRows: [{ id: 10, category_id: 5 }] });
mockExecute.mockResolvedValue({ rowsAffected: 1 });
const result = await applyKeywordWithReassignment({
keyword: "METRO",
categoryId: 3,
transactionIds: [1, 2],
allowReplaceExisting: true,
});
expect(result.replacedExisting).toBe(true);
expect(result.updatedTransactions).toBe(2);
const commands = mockExecute.mock.calls.map((c) => (c[0] as string).trim());
expect(commands.some((c) => c.startsWith("UPDATE keywords SET category_id"))).toBe(true);
expect(commands).toContain("COMMIT");
});
it("rejects invalid keywords before touching the database", async () => {
await expect(
applyKeywordWithReassignment({
keyword: "a",
categoryId: 3,
transactionIds: [1],
allowReplaceExisting: false,
}),
).rejects.toThrow("invalid_keyword:tooShort");
expect(mockExecute).not.toHaveBeenCalled();
});
});
describe("applyKeywordWithReassignment — data-change notification (#396)", () => {
const input = {
keyword: "METRO",
categoryId: 3,
transactionIds: [1, 2],
allowReplaceExisting: false,
};
/** At each notification: the last statement issued, and whether the DB lock was held. */
const seen: Array<{ last: string; inLock: boolean }> = [];
let inLock = false;
let unsubscribe: () => 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;
}
});
unsubscribe = subscribeDataChanged(() => {
const calls = mockExecute.mock.calls;
seen.push({ last: String(calls[calls.length - 1]?.[0]).trim(), inLock });
});
});
afterEach(() => {
unsubscribe();
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 () => {
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 () => {
answerReads();
mockExecute
.mockResolvedValueOnce(undefined) // BEGIN
.mockResolvedValueOnce({ lastInsertId: 77 }) // INSERT keywords
.mockRejectedValueOnce(new Error("disk full")); // UPDATE transactions fails
await expect(applyKeywordWithReassignment(input)).rejects.toThrow("disk full");
expect(seen).toEqual([]);
});
it("does not notify for a refused keyword", async () => {
await expect(applyKeywordWithReassignment({ ...input, keyword: "a" })).rejects.toThrow(
"invalid_keyword:tooShort",
);
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);
});
});