fix: a split's offset line takes its parent's manual flag (#454)
`autoCategorizeTransactions` picks every row without a category whose `is_manually_categorized` is 0, the children of a split included. The offset line kept the flag 0 whatever its parent's, so a split parent set to « Aucune catégorie » by hand lost its offset line to « Catégoriser automatiquement »: the keyword of the parent's description sent it alone to its category. With −120 « EPICERIE METRO » split as −50 to B, then set to no category, the totals went from NULL −70 and B −50 to 1111 +50, B −50 and NULL −120 (scenario R-S3 of the review of PR #515). - propagateCategoryToOffsets reads the parent's flag, after the caller's UPDATE of the parent, and writes it on the offset line with its category, through toSqlFlag (a base written before #390 may hold the TEXT 'true'). - saveSplitAdjustment gives the offset line its parent's flag when it writes the split, so a split made under a parent categorized, or set to no category, by hand does not lose it either. The entries keep the column's default, 0. Tests: a scenario test on a real SQLite database (node:sqlite, the schema of a new profile with its seed, foreign keys on, the real services through an adapter local to the file), unit tests of both copies (flag 1, flag 0 and the TEXT 'true'), and the tests that pinned the offset line's UPDATE and, since #513, its INSERT, which change on purpose. Refs #454 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4d1ac59c1a
commit
36c04ad6b8
6 changed files with 369 additions and 46 deletions
197
src/__integration__/split-offset-manual-flag.test.ts
Normal file
197
src/__integration__/split-offset-manual-flag.test.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
/**
|
||||
* A split's offset line and « Catégoriser automatiquement » (#454, item 1 of
|
||||
* the review of PR #515).
|
||||
*
|
||||
* `autoCategorizeTransactions` picks every row without a category whose
|
||||
* `is_manually_categorized` is 0, the children of a split included. The offset
|
||||
* line of a split cancels, in its parent's category, the part sent to the other
|
||||
* categories: it takes its parent's manual flag when the split is written
|
||||
* (`saveSplitAdjustment`) and when the parent changes category
|
||||
* (`propagateCategoryToOffsets`), so that a parent set to no category by hand
|
||||
* keeps its offset line with it. Without that, the keyword of the parent's
|
||||
* description sends the offset line alone to its category.
|
||||
*
|
||||
* The services run as written on a real SQLite database: `node:sqlite` (built
|
||||
* into Node, no package), the schema of a new profile with its seed
|
||||
* (`consolidated_schema.sql`), foreign keys on, as under sqlx. `../services/db`
|
||||
* is replaced by an adapter local to this file (#392 plans a shared harness):
|
||||
* `select` and `execute` run the statement with its `$N` bound by name,
|
||||
* `execute` answers `rowsAffected` and `lastInsertId`, `withTransaction` hands
|
||||
* its callback the same handle, and `getDb()` throws while a transaction runs,
|
||||
* where the real lock, which is not reentrant, would deadlock.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { readFileSync } from "fs";
|
||||
import { resolve } from "path";
|
||||
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
|
||||
|
||||
const fake = vi.hoisted(() => ({
|
||||
handle: null as unknown,
|
||||
inTransaction: false,
|
||||
}));
|
||||
|
||||
vi.mock("../services/db", () => ({
|
||||
getDb: vi.fn(async () => {
|
||||
if (fake.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
|
||||
return fake.handle;
|
||||
}),
|
||||
withTransaction: vi.fn(async (fn: (db: unknown) => Promise<unknown>) => {
|
||||
fake.inTransaction = true;
|
||||
try {
|
||||
return await fn(fake.handle);
|
||||
} finally {
|
||||
fake.inTransaction = false;
|
||||
}
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
autoCategorizeTransactions,
|
||||
saveSplitAdjustment,
|
||||
updateTransactionCategory,
|
||||
} from "../services/transactionService";
|
||||
|
||||
const SCHEMA = readFileSync(
|
||||
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
/** « Épicerie régulière », where the seed's `METRO` keyword sends a description that holds METRO. */
|
||||
const GROCERIES = 1111;
|
||||
/** « Boucherie & poissonnerie », the category the split sends −50 to. */
|
||||
const B = 1112;
|
||||
const DESCRIPTION = "EPICERIE METRO";
|
||||
/** The split of the reproduction of #454: −50 of the −120 to B, with the parent's description. */
|
||||
const ENTRIES = [{ category_id: B, amount: -50, description: DESCRIPTION }];
|
||||
|
||||
/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */
|
||||
function adapter(db: DatabaseSync) {
|
||||
// tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name.
|
||||
const bind = (params?: unknown[]) =>
|
||||
Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue]));
|
||||
return {
|
||||
select: async (sql: string, params?: unknown[]) =>
|
||||
db.prepare(sql).all(bind(params)).map((row) => ({ ...row })),
|
||||
execute: async (sql: string, params?: unknown[]) => {
|
||||
const result = db.prepare(sql).run(bind(params));
|
||||
return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let db: DatabaseSync;
|
||||
|
||||
beforeEach(() => {
|
||||
db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true });
|
||||
db.exec(SCHEMA);
|
||||
fake.handle = adapter(db);
|
||||
fake.inTransaction = false;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
db.close();
|
||||
});
|
||||
|
||||
/**
|
||||
* A transaction of −120 as an import writes it: its category from the
|
||||
* keywords, or none, and no manual flag (the column's default, 0).
|
||||
*/
|
||||
function imported(categoryId: number | null): number {
|
||||
const result = db
|
||||
.prepare(
|
||||
`INSERT INTO transactions (date, description, amount, category_id, original_description)
|
||||
VALUES ('2026-10-01', $description, -120, $category, $description)`,
|
||||
)
|
||||
.run({ $description: DESCRIPTION, $category: categoryId });
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
|
||||
type Line = { category_id: number | null; is_manually_categorized: number };
|
||||
|
||||
/** The category and the manual flag of the parent, of its entry (−50) and of its offset line (+50). */
|
||||
function split(parentId: number): { parent: Line; entry: Line; offset: Line } {
|
||||
const line = (where: string) =>
|
||||
({
|
||||
...db
|
||||
.prepare(`SELECT category_id, is_manually_categorized FROM transactions WHERE ${where}`)
|
||||
.get({ $id: parentId }),
|
||||
}) as Line;
|
||||
return {
|
||||
parent: line("id = $id"),
|
||||
entry: line("parent_transaction_id = $id AND amount < 0"),
|
||||
offset: line("parent_transaction_id = $id AND amount > 0"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What the reports add up, per category (`none` for no category): every row,
|
||||
* the split parent and its children included, the offset line cancelling in
|
||||
* the parent's category the part sent to the others.
|
||||
*/
|
||||
function totals(): Record<string, number> {
|
||||
const rows = db
|
||||
.prepare("SELECT category_id, SUM(amount) AS total FROM transactions GROUP BY category_id")
|
||||
.all() as Array<{ category_id: number | null; total: number }>;
|
||||
return Object.fromEntries(rows.map((r) => [r.category_id === null ? "none" : String(r.category_id), r.total]));
|
||||
}
|
||||
|
||||
describe("a split's offset line keeps its parent's manual flag (#454)", () => {
|
||||
it("the seed sends « EPICERIE METRO » to « Épicerie régulière », by its METRO keyword", () => {
|
||||
expect({ ...db.prepare("SELECT category_id FROM keywords WHERE keyword = 'METRO'").get() }).toEqual({
|
||||
category_id: GROCERIES,
|
||||
});
|
||||
});
|
||||
|
||||
// Scenario R-S3 of the review of PR #515.
|
||||
it("a split parent set to no category by hand keeps its offset line through « Catégoriser automatiquement »", async () => {
|
||||
const parent = imported(GROCERIES);
|
||||
await saveSplitAdjustment(parent, ENTRIES);
|
||||
// « Aucune catégorie » in the Transactions list (TransactionTable → useTransactions).
|
||||
await updateTransactionCategory(parent, null, true);
|
||||
expect(totals()).toEqual({ none: -70, [B]: -50 });
|
||||
|
||||
const categorized = await autoCategorizeTransactions();
|
||||
|
||||
expect(totals()).toEqual({ none: -70, [B]: -50 });
|
||||
expect(categorized).toBe(0);
|
||||
expect(split(parent)).toEqual({
|
||||
parent: { category_id: null, is_manually_categorized: 1 },
|
||||
// The entries keep the flag 0: out of the scope of #454.
|
||||
entry: { category_id: B, is_manually_categorized: 0 },
|
||||
offset: { category_id: null, is_manually_categorized: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("a split made under a parent set to no category by hand keeps its offset line through « Catégoriser automatiquement »", async () => {
|
||||
const parent = imported(GROCERIES);
|
||||
await updateTransactionCategory(parent, null, true);
|
||||
await saveSplitAdjustment(parent, ENTRIES);
|
||||
expect(totals()).toEqual({ none: -70, [B]: -50 });
|
||||
|
||||
const categorized = await autoCategorizeTransactions();
|
||||
|
||||
expect(totals()).toEqual({ none: -70, [B]: -50 });
|
||||
expect(categorized).toBe(0);
|
||||
expect(split(parent).offset).toEqual({ category_id: null, is_manually_categorized: 1 });
|
||||
});
|
||||
|
||||
it("witness: a parent imported without a category and its offset line get the same category from « Catégoriser automatiquement », as before", async () => {
|
||||
const parent = imported(null);
|
||||
await saveSplitAdjustment(parent, ENTRIES);
|
||||
expect(split(parent)).toEqual({
|
||||
parent: { category_id: null, is_manually_categorized: 0 },
|
||||
entry: { category_id: B, is_manually_categorized: 0 },
|
||||
offset: { category_id: null, is_manually_categorized: 0 },
|
||||
});
|
||||
|
||||
const categorized = await autoCategorizeTransactions();
|
||||
|
||||
expect(totals()).toEqual({ [GROCERIES]: -70, [B]: -50 });
|
||||
expect(categorized).toBe(2);
|
||||
expect(split(parent)).toEqual({
|
||||
parent: { category_id: GROCERIES, is_manually_categorized: 0 },
|
||||
entry: { category_id: B, is_manually_categorized: 0 },
|
||||
offset: { category_id: GROCERIES, is_manually_categorized: 0 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -320,8 +320,17 @@ describe("applyKeywordWithReassignment — data-change notification (#396)", ()
|
|||
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 };
|
||||
// which cancels those −50 in A. The keyword moves the parent to category 9;
|
||||
// the offset propagation reads the parent after that UPDATE, which writes
|
||||
// the manual flag 1.
|
||||
const PARENT = {
|
||||
id: 5,
|
||||
description: "EPICERIE METRO",
|
||||
amount: -120,
|
||||
is_split: 1,
|
||||
is_manually_categorized: 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 };
|
||||
|
|
@ -337,9 +346,10 @@ describe("applyKeywordWithReassignment — a split's offset line follows its par
|
|||
|
||||
const sent = statements();
|
||||
const offsetMove = sent.findIndex(
|
||||
(s) => s.sql.startsWith("UPDATE transactions SET category_id = $1, updated_at") && targetOf(s) === OFFSET.id,
|
||||
(s) => s.sql.startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2,") && targetOf(s) === OFFSET.id,
|
||||
);
|
||||
expect(sent[offsetMove]?.params).toEqual([9, OFFSET.id]);
|
||||
// The offset line takes the parent's category and its manual flag.
|
||||
expect(sent[offsetMove]?.params).toEqual([9, 1, OFFSET.id]);
|
||||
// The entry keeps its own category.
|
||||
expect(sent.filter((s) => targetOf(s) === ENTRY.id)).toEqual([]);
|
||||
expect(sent[0].sql).toBe("BEGIN");
|
||||
|
|
@ -371,7 +381,7 @@ describe("applyKeywordWithReassignment — a split's offset line follows its par
|
|||
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) {
|
||||
if (String(sql).startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2,") && params?.[2] === OFFSET.id) {
|
||||
throw new Error("disk full");
|
||||
}
|
||||
return { lastInsertId: 77, rowsAffected: 1 };
|
||||
|
|
|
|||
|
|
@ -39,11 +39,24 @@ function answer(row: Record<string, unknown> | undefined, children: Array<Record
|
|||
}
|
||||
|
||||
// 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 };
|
||||
// with the parent's description) and the offset line of +50. The parent is
|
||||
// read after its caller's UPDATE, which both callers write with the manual
|
||||
// flag 1.
|
||||
const PARENT = {
|
||||
id: 5,
|
||||
description: "EPICERIE METRO",
|
||||
amount: -120,
|
||||
is_split: 1,
|
||||
is_manually_categorized: 1,
|
||||
parent_transaction_id: null,
|
||||
};
|
||||
const ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 };
|
||||
const OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 };
|
||||
|
||||
/** The UPDATE of the offset line: the parent's category and manual flag. */
|
||||
const MOVE_OFFSET =
|
||||
"UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3";
|
||||
|
||||
const notifications: number[] = [];
|
||||
let stop: () => void = () => undefined;
|
||||
|
||||
|
|
@ -63,20 +76,15 @@ 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],
|
||||
},
|
||||
]);
|
||||
expect(sent()).toEqual([{ sql: MOVE_OFFSET, params: [9, 1, OFFSET.id] }]);
|
||||
});
|
||||
|
||||
it("reads the row by its id, then the children by their parent, whatever their category", async () => {
|
||||
it("reads the row by its id, with its manual flag, 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",
|
||||
sql: "SELECT id, description, amount, is_split, is_manually_categorized, parent_transaction_id FROM transactions WHERE id = $1",
|
||||
params: [PARENT.id],
|
||||
},
|
||||
{
|
||||
|
|
@ -92,13 +100,13 @@ describe("propagateCategoryToOffsets — which rows it moves (#454)", () => {
|
|||
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]]);
|
||||
expect(sent().map((s) => s.params)).toEqual([[9, 1, 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]]);
|
||||
expect(sent().map((s) => s.params)).toEqual([[null, 1, OFFSET.id]]);
|
||||
});
|
||||
|
||||
it("leaves a child of the opposite sign alone when it carries another description", async () => {
|
||||
|
|
@ -143,9 +151,34 @@ describe("propagateCategoryToOffsets — inside the caller's transaction (#454)"
|
|||
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(sent().map((s) => s.sql)).toEqual([MOVE_OFFSET]);
|
||||
expect(notifications).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// `autoCategorizeTransactions` picks every row without a category and with the
|
||||
// manual flag 0, children included: an offset line left at 0 under a parent set
|
||||
// to no category by hand would be categorized alone (review of PR #515).
|
||||
describe("propagateCategoryToOffsets — the offset line takes its parent's manual flag (#454)", () => {
|
||||
it.each<[string, unknown, 0 | 1]>([
|
||||
["the flag 1", 1, 1],
|
||||
["the flag 0", 0, 0],
|
||||
["the TEXT 'true' of a base written before #390, as 1", "true", 1],
|
||||
])("copies %s, bound as an integer", async (_label, flag, bound) => {
|
||||
answer({ ...PARENT, is_manually_categorized: flag }, [ENTRY, OFFSET]);
|
||||
await expect(propagateCategoryToOffsets(handle, PARENT.id, null)).resolves.toBe(1);
|
||||
expect(sent()).toEqual([{ sql: MOVE_OFFSET, params: [null, bound, OFFSET.id] }]);
|
||||
expect(typeof sent()[0].params[1]).toBe("number");
|
||||
});
|
||||
|
||||
it("reads the flag on the parent, never on the offset line", async () => {
|
||||
answer({ ...PARENT, is_manually_categorized: 1 }, [ENTRY, { ...OFFSET, is_manually_categorized: 0 }]);
|
||||
await propagateCategoryToOffsets(handle, PARENT.id, null);
|
||||
answer({ ...PARENT, is_manually_categorized: 0 }, [ENTRY, { ...OFFSET, is_manually_categorized: 1 }]);
|
||||
await propagateCategoryToOffsets(handle, PARENT.id, null);
|
||||
expect(sent().map((s) => s.params)).toEqual([
|
||||
[null, 1, OFFSET.id],
|
||||
[null, 0, OFFSET.id],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ interface ParentRow {
|
|||
description: string;
|
||||
amount: number;
|
||||
is_split: unknown;
|
||||
is_manually_categorized: unknown;
|
||||
parent_transaction_id: number | null;
|
||||
}
|
||||
|
||||
|
|
@ -27,8 +28,9 @@ interface ChildRow {
|
|||
|
||||
/**
|
||||
* 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).
|
||||
* category the caller has just given the parent, with the parent's
|
||||
* `is_manually_categorized` flag, 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
|
||||
|
|
@ -41,8 +43,16 @@ interface ChildRow {
|
|||
* `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.
|
||||
* next change (decision D2 of #454).
|
||||
*
|
||||
* The flag is read on the parent's row after the caller's UPDATE, so it is the
|
||||
* one the caller has just written. The offset line takes it because
|
||||
* `autoCategorizeTransactions` picks every row without a category and with the
|
||||
* flag 0, children included: under a parent set to no category by hand, an
|
||||
* offset line left at 0 would be categorized alone, by the keyword of the
|
||||
* parent's description, and its amount would leave the parent's category
|
||||
* (review of PR #515). `saveSplitAdjustment` gives it the same flag when it
|
||||
* writes the split.
|
||||
*/
|
||||
export async function propagateCategoryToOffsets(
|
||||
db: Database,
|
||||
|
|
@ -50,7 +60,7 @@ export async function propagateCategoryToOffsets(
|
|||
categoryId: number | null,
|
||||
): Promise<number> {
|
||||
const [parent] = await db.select<ParentRow[]>(
|
||||
`SELECT id, description, amount, is_split, parent_transaction_id
|
||||
`SELECT id, description, amount, is_split, is_manually_categorized, parent_transaction_id
|
||||
FROM transactions
|
||||
WHERE id = $1`,
|
||||
[parentId],
|
||||
|
|
@ -67,12 +77,15 @@ export async function propagateCategoryToOffsets(
|
|||
[parentId],
|
||||
);
|
||||
|
||||
// Never the value as read: a base written before #390 may hold the TEXT
|
||||
// 'true', which `is_manually_categorized = 1` never matches.
|
||||
const manualFlag = toSqlFlag(parent.is_manually_categorized);
|
||||
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],
|
||||
`UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3`,
|
||||
[categoryId, manualFlag, child.id],
|
||||
);
|
||||
moved++;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,8 +90,17 @@ function answerSplitReads(row: Record<string, unknown> | null, children: Array<R
|
|||
// 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 };
|
||||
// cancels in A the part sent to B. The offset propagation reads the parent
|
||||
// after its UPDATE, here with the manual flag 1 that `updateTransactionCategory`
|
||||
// has just written.
|
||||
const SPLIT_PARENT = {
|
||||
id: 5,
|
||||
description: "EPICERIE METRO",
|
||||
amount: -120,
|
||||
is_split: 1,
|
||||
is_manually_categorized: 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. */
|
||||
|
|
@ -100,7 +109,12 @@ 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. */
|
||||
/**
|
||||
* The UPDATE of the recategorized transaction itself, found by its SQL: a BEGIN
|
||||
* comes first since #454. The offset line's UPDATE has the same SQL since it
|
||||
* takes its parent's manual flag: on a split parent, tell them apart by their
|
||||
* target (`targetOf`).
|
||||
*/
|
||||
const ownUpdates = () =>
|
||||
writes().filter((w) => w.sql.startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2"));
|
||||
|
||||
|
|
@ -196,8 +210,8 @@ describe("updateTransactionCategory — a split's offset line follows its parent
|
|||
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 offset follows the parent to C, with its manual flag…
|
||||
expect(sent[offsetMove]?.params).toEqual([C, 1, 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.
|
||||
|
|
@ -211,6 +225,26 @@ describe("updateTransactionCategory — a split's offset line follows its parent
|
|||
expect(offsetMove).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// `autoCategorizeTransactions` picks every row without a category and with
|
||||
// the manual flag 0, children included: the offset line takes the flag its
|
||||
// parent has just been given, read after the parent's UPDATE (review of PR
|
||||
// #515).
|
||||
it("reads the parent after its own UPDATE, and gives the offset line the flag it has just been given", async () => {
|
||||
answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
|
||||
await updateTransactionCategory(SPLIT_PARENT.id, null, true);
|
||||
|
||||
const sent = statements();
|
||||
const parentMove = sent.findIndex((s) => s.sql.startsWith("UPDATE ") && targetOf(s) === SPLIT_PARENT.id);
|
||||
const parentRead = sent.findIndex((s) => /^SELECT .*\bis_manually_categorized\b.* WHERE id = \$1$/.test(s.sql));
|
||||
const offsetMove = sent.findIndex((s) => s.sql.startsWith("UPDATE ") && targetOf(s) === SPLIT_OFFSET.id);
|
||||
expect(sent[parentMove]?.params).toEqual([null, 1, SPLIT_PARENT.id]);
|
||||
expect(parentRead).toBeGreaterThan(parentMove);
|
||||
expect(offsetMove).toBeGreaterThan(parentRead);
|
||||
expect(sent[offsetMove]?.params).toEqual([null, 1, SPLIT_OFFSET.id]);
|
||||
});
|
||||
|
||||
it("moves nothing else for a transaction that is not split", async () => {
|
||||
answerSplitReads(PLAIN, []);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
|
|
@ -225,7 +259,7 @@ describe("updateTransactionCategory — a split's offset line follows its parent
|
|||
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) {
|
||||
if (String(sql).startsWith("UPDATE transactions SET category_id = $1,") && targetOf({ params: params ?? [] }) === SPLIT_OFFSET.id) {
|
||||
throw new Error("disk full");
|
||||
}
|
||||
return { rowsAffected: 1 };
|
||||
|
|
@ -295,16 +329,21 @@ const statements = (): Statement[] =>
|
|||
|
||||
const TRANSACTION_CONTROL = ["BEGIN", "COMMIT", "ROLLBACK"];
|
||||
|
||||
// The statements of a split, as `main` writes them before #513.
|
||||
// The statements of a split, as `main` writes them before #513, but the
|
||||
// offset line's INSERT: since the review of #454, it also writes the parent's
|
||||
// manual flag (`INSERT_OFFSET`).
|
||||
const READ_PARENT = "SELECT * FROM transactions WHERE id = $1";
|
||||
const DELETE_CHILDREN = "DELETE FROM transactions WHERE parent_transaction_id = $1";
|
||||
const INSERT_CHILD =
|
||||
"INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1)";
|
||||
const INSERT_OFFSET =
|
||||
"INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split, is_manually_categorized) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)";
|
||||
const MARK_SPLIT = "UPDATE transactions SET is_split = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1";
|
||||
const UNMARK_SPLIT = "UPDATE transactions SET is_split = 0, updated_at = CURRENT_TIMESTAMP WHERE id = $1";
|
||||
|
||||
// A transaction of −120 in category 3, split from the Transactions page: −50 to
|
||||
// category 8 with the parent's description, −20 to category 11 with its own.
|
||||
// A transaction of −120 put in category 3 by hand, split from the Transactions
|
||||
// page: −50 to category 8 with the parent's description, −20 to category 11
|
||||
// with its own.
|
||||
const SAVED_PARENT = {
|
||||
id: 5,
|
||||
date: "2026-10-01",
|
||||
|
|
@ -314,6 +353,7 @@ const SAVED_PARENT = {
|
|||
source_id: 2,
|
||||
file_id: 4,
|
||||
original_description: "EPICERIE METRO 0042",
|
||||
is_manually_categorized: 1,
|
||||
is_split: 0,
|
||||
parent_transaction_id: null,
|
||||
};
|
||||
|
|
@ -326,8 +366,8 @@ const SAVED_WRITES = [
|
|||
{ sql: DELETE_CHILDREN, params: [5] },
|
||||
{ sql: INSERT_CHILD, params: ["2026-10-01", "EPICERIE METRO", -50, 8, 2, 4, "EPICERIE METRO 0042", 5] },
|
||||
{ sql: INSERT_CHILD, params: ["2026-10-01", "PHARMACIE", -20, 11, 2, 4, "EPICERIE METRO 0042", 5] },
|
||||
// The offset line: the parent's description and category, minus the entries' total.
|
||||
{ sql: INSERT_CHILD, params: ["2026-10-01", "EPICERIE METRO", 70, 3, 2, 4, "EPICERIE METRO 0042", 5] },
|
||||
// The offset line: the parent's description, category and manual flag, minus the entries' total.
|
||||
{ sql: INSERT_OFFSET, params: ["2026-10-01", "EPICERIE METRO", 70, 3, 2, 4, "EPICERIE METRO 0042", 5, 1] },
|
||||
{ sql: MARK_SPLIT, params: [5] },
|
||||
];
|
||||
|
||||
|
|
@ -379,7 +419,7 @@ describe("a split is saved or deleted in one transaction (#513)", () => {
|
|||
}
|
||||
|
||||
describe("saveSplitAdjustment", () => {
|
||||
it("writes the same statements, with the same values, as before #513", async () => {
|
||||
it("writes the same statements, with the same values, as before #513, but the offset line's manual flag (#454)", async () => {
|
||||
answerSplitReads(SAVED_PARENT, []);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
await saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES);
|
||||
|
|
@ -393,12 +433,31 @@ describe("a split is saved or deleted in one transaction (#513)", () => {
|
|||
);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
await saveSplitAdjustment(SAVED_PARENT.id, [SAVED_ENTRIES[0]]);
|
||||
expect(writes().filter((w) => w.sql === INSERT_CHILD).map((w) => w.params)).toEqual([
|
||||
expect(writes().filter((w) => w.sql === INSERT_CHILD || w.sql === INSERT_OFFSET).map((w) => w.params)).toEqual([
|
||||
["2026-10-01", "EPICERIE METRO", -50, 8, null, null, "", 5],
|
||||
["2026-10-01", "EPICERIE METRO", 50, null, null, null, "", 5],
|
||||
["2026-10-01", "EPICERIE METRO", 50, null, null, null, "", 5, 1],
|
||||
]);
|
||||
});
|
||||
|
||||
// `autoCategorizeTransactions` picks every row without a category and with
|
||||
// the manual flag 0, children included: an offset line written at 0 under a
|
||||
// parent categorized (or set to no category) by hand would be categorized
|
||||
// alone once its parent has no category (review of PR #515).
|
||||
it.each<[string, unknown, 0 | 1]>([
|
||||
["the flag 1", 1, 1],
|
||||
["the flag 0", 0, 0],
|
||||
["the TEXT 'true' of a base written before #390, as 1", "true", 1],
|
||||
])("gives the offset line its parent's manual flag, %s, bound as an integer, and leaves the entries' alone (#454)", async (_label, flag, bound) => {
|
||||
answerSplitReads({ ...SAVED_PARENT, is_manually_categorized: flag }, []);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
await saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES);
|
||||
const offset = writes().filter((w) => w.sql === INSERT_OFFSET);
|
||||
expect(offset.map((w) => w.params[8])).toEqual([bound]);
|
||||
expect(typeof offset[0].params[8]).toBe("number");
|
||||
// The entries keep the column's default, 0: out of the scope of #454.
|
||||
expect(writes().filter((w) => w.sql === INSERT_CHILD)).toHaveLength(SAVED_ENTRIES.length);
|
||||
});
|
||||
|
||||
it("reads the parent first, writes between one BEGIN and its COMMIT, then notifies once, lock released", async () => {
|
||||
answerSplitReads(SAVED_PARENT, []);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
|
|
@ -429,7 +488,7 @@ describe("a split is saved or deleted in one transaction (#513)", () => {
|
|||
it.each<[string, (w: Statement) => boolean]>([
|
||||
["the DELETE of the former children", (w) => w.sql === DELETE_CHILDREN],
|
||||
["the INSERT of an entry", (w) => w.sql === INSERT_CHILD && w.params[2] === -20],
|
||||
["the INSERT of the offset line", (w) => w.sql === INSERT_CHILD && w.params[2] === 70],
|
||||
["the INSERT of the offset line", (w) => w.sql === INSERT_OFFSET],
|
||||
["the UPDATE of the split flag", (w) => w.sql === MARK_SPLIT],
|
||||
])("rolls back right after %s fails, rethrows and does not notify", async (_label, failing) => {
|
||||
answerSplitReads(SAVED_PARENT, []);
|
||||
|
|
|
|||
|
|
@ -439,7 +439,9 @@ export async function getSplitChildren(parentId: number): Promise<SplitChild[]>
|
|||
* cancels in the parent's category the part sent to the other categories, then
|
||||
* the parent's split flag. One transaction (#513): an error on any statement
|
||||
* rolls the whole split back, and a parent that cannot be found throws before
|
||||
* any write.
|
||||
* any write. The offset line takes the parent's category and its manual flag
|
||||
* (#454), as `propagateCategoryToOffsets` gives them when the parent changes
|
||||
* category; the entries keep the flag's default, 0.
|
||||
*/
|
||||
export async function saveSplitAdjustment(
|
||||
parentId: number,
|
||||
|
|
@ -497,10 +499,18 @@ async function saveSplitAdjustmentInTransaction(
|
|||
offsetTotal += entry.amount;
|
||||
}
|
||||
|
||||
// Insert offset child (cancels the redistributed portion from the original category)
|
||||
// Insert offset child (cancels the redistributed portion from the original
|
||||
// category). It also takes the parent's manual flag (#454):
|
||||
// `autoCategorizeTransactions` picks every row without a category and with
|
||||
// the flag 0, children included. Left at 0 under a parent categorized by
|
||||
// hand, it would be categorized alone, without its parent, as soon as both
|
||||
// have no category: the parent set to « Aucune catégorie » by hand, or the
|
||||
// categories reset (`reinitializeCategories`). Never the flag as read: a
|
||||
// base written before #390 may hold the TEXT 'true', which
|
||||
// `is_manually_categorized = 1` never matches.
|
||||
await db.execute(
|
||||
`INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1)`,
|
||||
`INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split, is_manually_categorized)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)`,
|
||||
[
|
||||
parent.date,
|
||||
parent.description,
|
||||
|
|
@ -510,6 +520,7 @@ async function saveSplitAdjustmentInTransaction(
|
|||
parent.file_id ?? null,
|
||||
parent.original_description ?? "",
|
||||
parentId,
|
||||
toSqlFlag(parent.is_manually_categorized),
|
||||
]
|
||||
);
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue