From e09994ada256eb787391f93e5f7883d7eae615b1 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 27 Oct 2026 22:37:31 -0400 Subject: [PATCH 1/3] fix: save and delete a split in one transaction (#513) saveSplitAdjustment and deleteSplitAdjustment sent their statements one by one through getDb(), outside any SQL transaction: an error in the middle left a half-written split that the reports add up as it is (entries without their offset line, children without the parent's split flag), and a parent that could not be found threw after its children were already deleted. Both now run in withTransaction, through a private *InTransaction function that issues BEGIN, the statements on the transaction's handle, then COMMIT, and ROLLBACK then rethrow on any error (the pattern of applyKeywordInTransaction and updateTransactionCategoryInTransaction). The save reads the parent first, so a missing parent throws before any write. The statements and their values are those of main, in the same order once the parent read is moved before the DELETE: same entries, same offset line (the parent's description and category, -offsetTotal), same split flag. Both notify the data-change channel once withTransaction returns, after the COMMIT and with the DB lock released, never after a ROLLBACK (ADR 0022: a split writes rows of transactions, which the getting-started counters read). Tests: the same statements and values as before (green on the base too), the BEGIN/read/writes/COMMIT order and one notification after the lock is released, a missing parent (BEGIN, read, ROLLBACK, nothing written), a failure of each write (ROLLBACK right after it, error rethrown, no notification), and every statement through the transaction's handle, none through getDb(). The callers (useTransactions, AdjustmentsPage) are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/services/transactionService.test.ts | 236 +++++++++++++++++++++++- src/services/transactionService.ts | 151 ++++++++++----- 2 files changed, 334 insertions(+), 53 deletions(-) diff --git a/src/services/transactionService.test.ts b/src/services/transactionService.test.ts index 763a9c8..9220b4a 100644 --- a/src/services/transactionService.test.ts +++ b/src/services/transactionService.test.ts @@ -11,8 +11,10 @@ vi.mock("./db", () => { import { getDb, withTransaction } from "./db"; import { subscribeDataChanged } from "./dataEvents"; import { + deleteSplitAdjustment, getTransactionCount, insertBatch, + saveSplitAdjustment, updateTransactionCategory, updateTransactionNotes, } from "./transactionService"; @@ -71,13 +73,15 @@ const targetOf = (write: { params: unknown[] }) => write.params[write.params.len /** * 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. + * `parent_transaction_id`. The same `WHERE id = $1` answers the parent read of + * a split being saved (#513), with no row for `null`. Any other read fails the + * test. */ -function answerSplitReads(row: Record, children: Array>) { +function answerSplitReads(row: Record | null, children: Array>) { 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]; + if (/WHERE id = \$1/.test(flat)) return row ? [row] : []; throw new Error(`unexpected read: ${flat}`); }); } @@ -274,3 +278,229 @@ describe("insertBatch — data-change notification (#396)", () => { expect(notified).toEqual([]); }); }); + +/** A statement's SQL with its whitespace collapsed, as `writes()` gives it. */ +const collapse = (sql: unknown) => String(sql).replace(/\s+/g, " ").trim(); + +type Statement = { sql: string; params: unknown[] }; + +/** Every statement sent, the reads with the writes, in the order they were sent. */ +const statements = (): Statement[] => + [ + ...mockSelect.mock.calls.map(([sql, params], i) => ({ at: mockSelect.mock.invocationCallOrder[i], sql, params })), + ...mockExecute.mock.calls.map(([sql, params], i) => ({ at: mockExecute.mock.invocationCallOrder[i], sql, params })), + ] + .sort((a, b) => a.at - b.at) + .map(({ sql, params }) => ({ sql: collapse(sql), params: (params ?? []) as unknown[] })); + +const TRANSACTION_CONTROL = ["BEGIN", "COMMIT", "ROLLBACK"]; + +// The statements of a split, as `main` writes them before #513. +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 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. +const SAVED_PARENT = { + id: 5, + date: "2026-10-01", + description: "EPICERIE METRO", + amount: -120, + category_id: 3, + source_id: 2, + file_id: 4, + original_description: "EPICERIE METRO 0042", + is_split: 0, + parent_transaction_id: null, +}; +const SAVED_ENTRIES = [ + { category_id: 8, amount: -50, description: "EPICERIE METRO" }, + { category_id: 11, amount: -20, description: "PHARMACIE" }, +]; +/** The writes of that split, BEGIN and COMMIT aside. */ +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] }, + { sql: MARK_SPLIT, params: [5] }, +]; + +describe("a split is saved or deleted in one transaction (#513)", () => { + /** 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 }); + }); + }); + + afterEach(() => { + stop(); + vi.mocked(withTransaction).mockImplementation(async (fn) => fn((await getDb()) as never)); + }); + + /** Fails, with "disk full", every statement `failing` matches; any other one succeeds. */ + function failOn(failing: (write: Statement) => boolean) { + mockExecute.mockImplementation(async (sql: string, params?: unknown[]) => { + if (failing({ sql: collapse(sql), params: params ?? [] })) throw new Error("disk full"); + return { rowsAffected: 1 }; + }); + } + + /** Runs `run` with getDb() rejecting and the transaction's handle on the mocked database. */ + async function handleOnly(run: () => Promise) { + 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)); + await run(); + return outside; + } + + describe("saveSplitAdjustment", () => { + it("writes the same statements, with the same values, as before #513", async () => { + answerSplitReads(SAVED_PARENT, []); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + await saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES); + expect(writes().filter((w) => !TRANSACTION_CONTROL.includes(w.sql))).toEqual(SAVED_WRITES); + }); + + it("writes the fallbacks of a parent without category, source, file or original description as before", async () => { + answerSplitReads( + { ...SAVED_PARENT, category_id: null, source_id: null, file_id: null, original_description: null }, + [], + ); + 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([ + ["2026-10-01", "EPICERIE METRO", -50, 8, null, null, "", 5], + ["2026-10-01", "EPICERIE METRO", 50, null, null, null, "", 5], + ]); + }); + + 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 }); + await saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES); + expect(statements()).toEqual([ + { sql: "BEGIN", params: [] }, + { sql: READ_PARENT, params: [5] }, + ...SAVED_WRITES, + { sql: "COMMIT", params: [] }, + ]); + expect(seen).toEqual([{ last: "COMMIT", inLock: false }]); + }); + + it("throws before any write when the parent cannot be found, rolls back and does not notify", async () => { + answerSplitReads(null, []); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + await expect(saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES)).rejects.toThrow( + "Parent transaction not found", + ); + expect(statements()).toEqual([ + { sql: "BEGIN", params: [] }, + { sql: READ_PARENT, params: [5] }, + { sql: "ROLLBACK", params: [] }, + ]); + expect(seen).toEqual([]); + }); + + 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 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, []); + failOn(failing); + await expect(saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES)).rejects.toThrow("disk full"); + const sent = statements(); + expect(sent[0].sql).toBe("BEGIN"); + expect(failing(sent[sent.length - 2])).toBe(true); + expect(sent[sent.length - 1].sql).toBe("ROLLBACK"); + expect(sent.map((s) => s.sql)).not.toContain("COMMIT"); + expect(seen).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 () => { + answerSplitReads(SAVED_PARENT, []); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + const outside = await handleOnly(() => saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES)); + expect(outside).not.toHaveBeenCalled(); + expect(statements().map((s) => s.sql)).toEqual([ + "BEGIN", + READ_PARENT, + ...SAVED_WRITES.map((w) => w.sql), + "COMMIT", + ]); + }); + }); + + describe("deleteSplitAdjustment", () => { + const DELETED_WRITES = [ + { sql: DELETE_CHILDREN, params: [5] }, + { sql: UNMARK_SPLIT, params: [5] }, + ]; + + it("writes the same statements, with the same values, as before #513", async () => { + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + await deleteSplitAdjustment(5); + expect(writes().filter((w) => !TRANSACTION_CONTROL.includes(w.sql))).toEqual(DELETED_WRITES); + }); + + it("deletes the children and clears the split flag between one BEGIN and its COMMIT, then notifies once, lock released", async () => { + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + await deleteSplitAdjustment(5); + expect(statements()).toEqual([ + { sql: "BEGIN", params: [] }, + ...DELETED_WRITES, + { sql: "COMMIT", params: [] }, + ]); + expect(seen).toEqual([{ last: "COMMIT", inLock: false }]); + }); + + it.each([ + ["the DELETE of the children", DELETE_CHILDREN], + ["the UPDATE of the split flag", UNMARK_SPLIT], + ])("rolls back right after %s fails, rethrows and does not notify", async (_label, failingSql) => { + failOn((w) => w.sql === failingSql); + await expect(deleteSplitAdjustment(5)).rejects.toThrow("disk full"); + const sent = statements(); + expect(sent[0].sql).toBe("BEGIN"); + expect(sent[sent.length - 2].sql).toBe(failingSql); + expect(sent[sent.length - 1].sql).toBe("ROLLBACK"); + expect(sent.map((s) => s.sql)).not.toContain("COMMIT"); + expect(seen).toEqual([]); + }); + + it("sends every statement through the transaction's handle, none through getDb()", async () => { + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + const outside = await handleOnly(() => deleteSplitAdjustment(5)); + expect(outside).not.toHaveBeenCalled(); + expect(statements().map((s) => s.sql)).toEqual(["BEGIN", DELETE_CHILDREN, UNMARK_SPLIT, "COMMIT"]); + }); + }); +}); diff --git a/src/services/transactionService.ts b/src/services/transactionService.ts index 64598c7..7589259 100644 --- a/src/services/transactionService.ts +++ b/src/services/transactionService.ts @@ -434,76 +434,127 @@ export async function getSplitChildren(parentId: number): Promise ); } +/** + * Writes the split of `parentId`: its entries, then the offset line that + * 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. + */ export async function saveSplitAdjustment( parentId: number, entries: Array<{ category_id: number; amount: number; description: string }> ): Promise { - const db = await getDb(); - - // Delete any existing children - await db.execute( - `DELETE FROM transactions WHERE parent_transaction_id = $1`, - [parentId] + await withTransaction((db) => + saveSplitAdjustmentInTransaction(db, parentId, entries) ); + // Reached only after the COMMIT (a ROLLBACK rethrows), once the DB lock is + // released: a split writes rows of `transactions`, which the getting-started + // counters read (ADR 0022). + notifyDataChanged(); +} - // Fetch parent transaction - const [parent] = await db.select( - `SELECT * FROM transactions WHERE id = $1`, - [parentId] - ); - if (!parent) throw new Error("Parent transaction not found"); +async function saveSplitAdjustmentInTransaction( + db: Database, + parentId: number, + entries: Array<{ category_id: number; amount: number; description: string }> +): Promise { + // `withTransaction` only holds the DB lock: the BEGIN, the COMMIT and the + // ROLLBACK are this function's. + await db.execute("BEGIN"); + try { + // Fetch the parent before any write: a parent that cannot be found throws + // with nothing written. + const [parent] = await db.select( + `SELECT * FROM transactions WHERE id = $1`, + [parentId] + ); + if (!parent) throw new Error("Parent transaction not found"); - // Insert each split child - let offsetTotal = 0; - for (const entry of entries) { + // Delete any existing children + await db.execute( + `DELETE FROM transactions WHERE parent_transaction_id = $1`, + [parentId] + ); + + // Insert each split child + let offsetTotal = 0; + for (const entry of entries) { + 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)`, + [ + parent.date, + entry.description, + entry.amount, + entry.category_id, + parent.source_id ?? null, + parent.file_id ?? null, + parent.original_description ?? "", + parentId, + ] + ); + offsetTotal += entry.amount; + } + + // Insert offset child (cancels the redistributed portion from the original category) 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)`, [ parent.date, - entry.description, - entry.amount, - entry.category_id, + parent.description, + -offsetTotal, + parent.category_id ?? null, parent.source_id ?? null, parent.file_id ?? null, parent.original_description ?? "", parentId, ] ); - offsetTotal += entry.amount; + + // Mark parent as split + await db.execute( + `UPDATE transactions SET is_split = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1`, + [parentId] + ); + await db.execute("COMMIT"); + } catch (e) { + await db.execute("ROLLBACK"); + throw e; } - - // Insert offset child (cancels the redistributed portion from the original category) - 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)`, - [ - parent.date, - parent.description, - -offsetTotal, - parent.category_id ?? null, - parent.source_id ?? null, - parent.file_id ?? null, - parent.original_description ?? "", - parentId, - ] - ); - - // Mark parent as split - await db.execute( - `UPDATE transactions SET is_split = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1`, - [parentId] - ); } +/** + * Removes the split of `parentId`: its children, then its split flag, in one + * transaction (#513). + */ export async function deleteSplitAdjustment(parentId: number): Promise { - const db = await getDb(); - await db.execute( - `DELETE FROM transactions WHERE parent_transaction_id = $1`, - [parentId] - ); - await db.execute( - `UPDATE transactions SET is_split = 0, updated_at = CURRENT_TIMESTAMP WHERE id = $1`, - [parentId] - ); + await withTransaction((db) => deleteSplitAdjustmentInTransaction(db, parentId)); + // Reached only after the COMMIT (a ROLLBACK rethrows), once the DB lock is + // released, as for a saved split (ADR 0022). + notifyDataChanged(); +} + +async function deleteSplitAdjustmentInTransaction( + db: Database, + parentId: number +): Promise { + // `withTransaction` only holds the DB lock: the BEGIN, the COMMIT and the + // ROLLBACK are this function's. + await db.execute("BEGIN"); + try { + await db.execute( + `DELETE FROM transactions WHERE parent_transaction_id = $1`, + [parentId] + ); + await db.execute( + `UPDATE transactions SET is_split = 0, updated_at = CURRENT_TIMESTAMP WHERE id = $1`, + [parentId] + ); + await db.execute("COMMIT"); + } catch (e) { + await db.execute("ROLLBACK"); + throw e; + } } -- 2.52.0 From c2d429d481c9e83b9ba53176f841bf3f0cc814f5 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 27 Oct 2026 22:37:39 -0400 Subject: [PATCH 2/3] docs: split writes in one transaction in the architecture, ADR 0022 and changelogs (#513) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/architecture.md: the row of transactionService.ts adds that a split is saved or deleted in one transaction, on the pattern of updateTransactionCategory, the parent of a saved split read before any write, and notified after the COMMIT only. ADR 0022: the row of transactionService.ts lists saveSplitAdjustment and deleteSplitAdjustment among the writes that notify, after the COMMIT of their transaction, with the lock released, and never after a ROLLBACK (the ADR's rule for a new write of a table COUNTERS_SQL reads). CHANGELOG.md and CHANGELOG.fr.md: one Fixed / Corrigé entry under [Unreleased], after the entry of #454. Resolves #513 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.fr.md | 1 + CHANGELOG.md | 1 + docs/adr/0022-canal-evenements-donnees.md | 2 +- docs/architecture.md | 2 +- 4 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.fr.md b/CHANGELOG.fr.md index 0274630..ecf3f9c 100644 --- a/CHANGELOG.fr.md +++ b/CHANGELOG.fr.md @@ -25,6 +25,7 @@ - Journaux (Paramètres → Système) : une ligne d'erreur sur l'ouverture ou la fermeture d'un profil ne garde plus le nom d'un dossier qui contient `;`, `|`, une apostrophe inverse ou une parenthèse fermante suivie d'un mot, comme `Jean (Work) Smith` : elle ne nomme que le fichier. La ligne écrite quand la réparation des migrations d'un profil échoue à son ouverture (« Migration repair failed ») ne nomme plus, elle aussi, que le fichier de la base ; elle en montrait le chemin complet, dossiers de votre compte compris. Ces lignes peuvent partir avec une rétroaction quand vous y incluez les derniers logs d'erreur. En contrepartie, le texte qui suit un chemin après l'un de ces caractères et qui contient un `/` ou un `\` est désormais retiré avec les dossiers, jusqu'à son dernier `/` ou `\` (#478). - Journaux (Paramètres → Système) : une ligne des journaux ne porte plus votre dossier personnel ni le dossier qui contient les bases des profils, nommés tous deux d'après votre compte d'utilisateur, quoi qu'il y ait autour, comme un nom de dossier qui contient une virgule (`Smith, Jean`) ou un chemin collé à un `;` : le dossier personnel devient `~` et celui des bases ``. Cela vaut pour toutes les lignes, ce que copie « Copier » compris, et les lignes écrites au démarrage avant que ces dossiers soient connus les perdent dès qu'ils le sont. Une ligne d'erreur sur l'ouverture ou la fermeture d'un profil ne nomme toujours que le fichier. Ces lignes peuvent partir avec une rétroaction quand vous y incluez les derniers logs d'erreur (#497). - Transactions : changer la catégorie d'une transaction répartie déplace désormais toute sa part non répartie vers la nouvelle catégorie. Les rapports gardaient, dans l'ancienne catégorie, le montant envoyé vers les autres catégories avec le signe inverse, sans transaction correspondante, et comptaient la transaction entière dans la nouvelle : une transaction de −120 dont −50 sont répartis vers B, déplacée de A vers C, laissait +50 dans A et −120 dans C, au lieu de −70 dans C. Cela vaut pour la catégorie choisie dans la liste des transactions comme pour les transactions recatégorisées par un nouveau mot-clé. Une répartition déjà touchée se répare au prochain changement de catégorie de sa transaction, et sa fenêtre de répartition ne montre plus ce montant comme l'une de ses lignes. La prévisualisation d'un mot-clé ne liste plus les parts d'une répartition, qu'elle pouvait recatégoriser sans leur transaction (#454). +- Transactions : enregistrer ou supprimer une répartition ne laisse plus de répartition à moitié écrite après une erreur (#513). ### Sécurité diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e154de..b1b9035 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ - Logs (Settings → System): an error line about opening or closing a profile no longer keeps the name of a folder that holds `;`, `|`, a backtick or a closing parenthesis followed by a word, such as `Jean (Work) Smith`: it names the file only. The line written when the migration repair of a profile fails at opening (“Migration repair failed”) now names the database file only too; it showed the file's full path, folders of your user account included. These lines can go with a feedback report when you include the recent error logs. In return, text that follows a path after one of these characters and holds a `/` or a `\` is now dropped with the folders, up to its last `/` or `\` (#478). - Logs (Settings → System): a line of the logs no longer carries your home folder or the folder that holds the profile databases, both named after your user account, whatever surrounds them, such as a folder name that holds a comma (`Smith, Jean`) or a path glued to a `;`: the home folder becomes `~` and the databases' folder ``. This holds for every line, what “Copy” copies included, and the lines written at startup before these folders are known lose them as soon as they are. An error line about opening or closing a profile still names the file only. These lines can go with a feedback report when you include the recent error logs (#497). - Transactions: changing the category of a split transaction now moves all of its unsplit part to the new category. The reports used to keep, in the former category, the amount sent to the other categories with the opposite sign, matching no transaction, and to count the whole transaction in the new one: 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. This holds for the category chosen in the Transactions list and for the transactions recategorized by a new keyword. A split already affected is repaired the next time its transaction changes category, and its split window no longer shows that amount as one of its rows. The keyword preview no longer lists the parts of a split, which it could recategorize without their transaction (#454). +- Transactions: saving or deleting a split no longer leaves a half-written split after an error (#513). ### Security diff --git a/docs/adr/0022-canal-evenements-donnees.md b/docs/adr/0022-canal-evenements-donnees.md index 097a3c0..985c1d4 100644 --- a/docs/adr/0022-canal-evenements-donnees.md +++ b/docs/adr/0022-canal-evenements-donnees.md @@ -32,7 +32,7 @@ La liste est construite depuis les tables que lit `COUNTERS_SQL`, plus le dossie | `userPreferenceService.ts` | `setImportFolder` | après l'écriture de la préférence (`setPreference` seul ne notifie pas) | | `importSourceService.ts` | `createSource`, `deleteSource` | après l'écriture ; `createSource` notifie avant la relecture qui suit un conflit de nom, qui ne fait que lire | | `importedFileService.ts` | `createImportedFile` (insertion comme mise à jour), `updateFileStatus`, `deleteImportWithTransactions`, `deleteAllImportsWithTransactions` | après l'écriture ; pour les suppressions, après la dernière (source orpheline comprise). Un refus du contrôle préalable (transactions liées au Bilan) ne notifie pas | -| `transactionService.ts` | `insertBatch`, `updateTransactionCategory` | `insertBatch` une fois, après la dernière insertion ; `updateTransactionCategory` après le `COMMIT` de sa transaction (#454), une fois le verrou relâché, et un `ROLLBACK` relance l'erreur et ne notifie pas | +| `transactionService.ts` | `insertBatch`, `updateTransactionCategory`, `saveSplitAdjustment`, `deleteSplitAdjustment` | `insertBatch` une fois, après la dernière insertion ; `updateTransactionCategory` (#454), `saveSplitAdjustment` et `deleteSplitAdjustment` (#513) après le `COMMIT` de leur transaction, une fois le verrou relâché, et un `ROLLBACK` relance l'erreur et ne notifie pas | | `categorizationService.ts` | `applyKeywordWithReassignment` | après le `COMMIT`, une fois le verrou de `db.ts` relâché ; un `ROLLBACK` relance l'erreur et ne notifie pas | | `budgetService.ts` | `upsertBudgetEntry`, `deleteBudgetEntry`, `upsertBudgetEntriesForYear`, `applyTemplate` | après l'écriture ; `upsertBudgetEntriesForYear` après les douze mois, `applyTemplate` une fois après la dernière entrée du modèle | | `dataExportService.ts` | `runRestore` | après le `COMMIT`, une fois le verrou relâché : un seul point pour les trois modes de restauration | diff --git a/docs/architecture.md b/docs/architecture.md index 693a1b4..68f1f14 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -202,7 +202,7 @@ Le dossier des bases est celui du plugin : `app_config_dir()`, résolu par `prof | `db.ts` | Wrapper de connexion (tauri-plugin-sql), verrou FIFO de tous les accès et `withTransaction` (voir « Accès DB et transactions »). `connectToProfile` appelle `repair_migrations` puis `prepare_profile_db` avant `Database.load`, et écrit au Journal ce que la préparation a changé (`describePreparation`, noms de fichiers seulement, #390) ; un échec est écrit au Journal et le profil s'ouvre quand même. Chaque ligne que le fichier écrit au Journal passe par `cleanLogLine` : le remplacement exact des dossiers connus (`replaceKnownFolders`), puis `withoutFolders`, dans cet ordre (#497, [ADR 0021](adr/0021-migrations-profils-secondaires.md), § 7) ; `connectToProfile` attend ces dossiers (`knownFoldersReady()`) avant `repair_migrations` | | `profileService.ts` | Gestion des profils | | `categoryService.ts` | CRUD catégories hiérarchiques. `updateCategory` vérifie un nouveau parent, `reattachCategory` rattache une catégorie orpheline et `createCategory` vérifie ce que porte le parent d'une sous-catégorie quand il deviendrait parent, chacun en une transaction par son handle ; `CategoryHierarchyError` typée ; `findOrphanCategories` (diagnostic, requête dédiée sur toutes les catégories) ; `getCategoryDepth` s'arrête sur un cycle — voir « Hiérarchie des catégories » | -| `transactionService.ts` | CRUD et filtrage des transactions ; détection d'erreurs FK RESTRICT pour transactions liées à un compte de bilan (typed `TransactionLinkedToBalanceError`) ; `getTransactionCount` (compte brut de la table, sans filtre — signal des états vides de Transactions et Budget, #351/#353) ; `updateTransactionCategory` écrit la catégorie dans une transaction (`withTransaction`, son `BEGIN`, son `COMMIT`, `ROLLBACK` puis relance sur un échec), où la ligne de compensation d'un parent réparti suit (`propagateCategoryToOffsets`), et ne notifie qu'après le `COMMIT` (#454) | +| `transactionService.ts` | CRUD et filtrage des transactions ; détection d'erreurs FK RESTRICT pour transactions liées à un compte de bilan (typed `TransactionLinkedToBalanceError`) ; `getTransactionCount` (compte brut de la table, sans filtre — signal des états vides de Transactions et Budget, #351/#353) ; `updateTransactionCategory` écrit la catégorie dans une transaction (`withTransaction`, son `BEGIN`, son `COMMIT`, `ROLLBACK` puis relance sur un échec), où la ligne de compensation d'un parent réparti suit (`propagateCategoryToOffsets`), et ne notifie qu'après le `COMMIT` (#454) ; répartitions (`saveSplitAdjustment`, `deleteSplitAdjustment`) écrites dans une seule transaction, sur le même motif, le parent d'une répartition enregistrée lu avant toute écriture, et notifiées après le `COMMIT` seulement (#513) | | `importSourceService.ts` | Configuration des sources d'import — lit et écrit le format complet via le codec `importFormat.ts` ([ADR 0019](adr/0019-format-import-persiste.md)) | | `importedFileService.ts` | Suivi des fichiers importés | | `importConfigTemplateService.ts` | Modèles de configuration d'import | -- 2.52.0 From ad759fc3d09e4d5a9ca9ab1b60ff2a9b1cece2be Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 27 Oct 2026 22:42:41 -0400 Subject: [PATCH 3/3] docs(state): manual check of a split saved and deleted in one transaction (#513) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sub-bullet of #454 at the end of « Vérifications dues à la release suivante » gets one more sentence, same split window and same test profile: a split changed then deleted, from the Transactions page and from the Adjustments page, without « database is locked », the transaction back whole in its category. The unit tests mock the database and the SQLite replay runs the SQL with python3: neither runs these two writes through withTransaction in the Tauri runtime. Procedure in the body of PR #516. Resolves #513 Co-Authored-By: Claude Opus 5.5 --- STATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/STATE.md b/STATE.md index f85d2fe..5d591e0 100644 --- a/STATE.md +++ b/STATE.md @@ -204,7 +204,7 @@ Côté site, la demande « merger et déployer après la publication » pour l' - Procédure `/release` revue par la pile #499 → #506 (dossiers 28630 et 28647) : à l'étape 0, lancer les deux commandes de report de la matrice des éditions et lire chaque commit trouvé, la PR du site n'étant mergée et déployée qu'après le `VERDICT : OK` ; à l'étape 3, la sous-étape « Vérifier les en-têtes » doit mener au vert sans toucher à la version des autres fichiers ; à l'étape 10, si seul l'endpoint de mise à jour change, `curl … | jq -r .version` doit rendre la nouvelle version. - Focus des fenêtres d'incitation (#494, PR #511), en édition Gratuite sauf mention, en FR et en EN, thèmes clair et sombre, sous Linux et sous Windows : Transactions → bouton Répartition verrouillé (à la souris, puis par Tab et Entrée), et sélecteur de profil → profil verrouillé : anneau de focus visible sur le X à l'ouverture, Tab et Maj+Tab font le tour de la fenêtre sans passer derrière le voile, X et Échap rendent le focus au bouton Répartition de la ligne, ou au bouton du sélecteur pour la fenêtre ouverte depuis son menu, comme « J'ai déjà une clé » depuis le sélecteur (depuis Transactions, la page change et le focus n'est nulle part, comme après toute navigation) ; « Gérer les profils » : focus sur le X à l'ouverture, Tab qui boucle dans chaque mode, « Créer un profil » verrouillé → focus sur le X, « Annuler » → focus sur « Créer un profil », en Base « Créer un profil » et « Modifier » → champ Nom, « Annuler » ou « Enregistrer » d'une modification → « Créer un profil », Échap qui ferme la fenêtre (depuis le champ Nom aussi) sauf pendant un enregistrement, X et Échap qui rendent le focus au bouton du sélecteur ; la même fenêtre ouverte depuis l'écran de choix du profil (aucun profil actif, hors routeur), le focus rendu à sa tuile « Créer un profil » ; lecteur d'écran (Orca, Narrateur) : chaque fenêtre annoncée à l'ouverture comme une boîte de dialogue avec son nom, le X lu « Fermer », le bouton du sélecteur annoncé déplié ou replié ; en Base, le sélecteur change toujours de profil et Répartition ouvre la fenêtre de répartition. Après la suppression d'un profil, la fenêtre se ferme le temps du rechargement des profils, comme avant : le focus ne va pas sur « Créer un profil » (attendu, PR #511). - Journal sans dossier (#497, PR #512), sous Linux puis sous Windows, sur un profil secondaire de test : l'app fermée, lire le nom de sa base (`db_filename`, `profile_.db`) dans `profiles.json` (`~/.local/share/com.simpl.resultat/` sous Linux, `%APPDATA%\com.simpl.resultat\` sous Windows), renommer cette base et créer à sa place un dossier vide du même nom, dans le dossier des bases (`~/.config/com.simpl.resultat/` sous Linux, `$XDG_CONFIG_HOME/com.simpl.resultat/` s'il est défini ; `%APPDATA%\com.simpl.resultat\` sous Windows), une base en lecture seule s'ouvrant sans erreur ; ouvrir l'app sur un autre profil et basculer vers celui-ci (l'ouverture échoue), puis lire dans Paramètres → Système → Journaux les lignes « Migration repair failed » et « database preparation failed » : elles nomment `profile_.db` et ne contiennent aucun segment du dossier personnel ; si la page d'erreur s'affiche à la place, remettre la base puis « Actualiser » (le Journal de la session garde les lignes) ; « Copier », puis une rétroaction de test avec « Inclure les derniers logs d'erreur » : aucun dossier ; supprimer le dossier et remettre la base ensuite. - - Compensation d'une répartition (#454, PR #515), en édition Base, en FR et en EN : une transaction répartie reclassée par la liste puis par un mot-clé, l'ancienne catégorie se vide et la fenêtre de répartition ne montre que les vraies lignes ; procédure dans le corps de la PR. + - Compensation d'une répartition (#454, PR #515), en édition Base, en FR et en EN : une transaction répartie reclassée par la liste puis par un mot-clé, l'ancienne catégorie se vide et la fenêtre de répartition ne montre que les vraies lignes ; procédure dans le corps de la PR. Même fenêtre, même profil (#513, PR #516) : une répartition modifiée puis supprimée, depuis Transactions et depuis Ajustements, sans « database is locked », la transaction revient entière dans sa catégorie. - **Le paiement est live : « aucun tag avant le go-live » n'a plus de raison d'être, et la release desktop qu'attendait le go-live est publiée (v0.16.0, 2026-10-03).** Bascule live le 2026-09-29 (Product et Price live à 19 $ CAD, webhook, variables Stripe de production, redeploy `3673d09` de maximus-api, URL `cs_live_` vérifiée), puis achat réel de contrôle le 2026-09-30 : clé sur `/merci` et par courriel, activation dans l'app, remboursement complet et licence révoquée par `charge.refunded`. **Volet serveur clos le 2026-10-03** (derniers commentaires relus le 2026-10-04) : maximus-api#62 fermée, tous critères cochés (maximus-api 0.4.2 en prod, secrets en runtime seul), avec la milestone `spec-paiements` de maximus-api (12/12) ; la-compagnie-maximus#150 (Link dans les textes légaux) livrée et fermée le 2026-10-01. **Go-live clos : la-compagnie-maximus#141** fermée le 2026-10-10 sur décision de Max, l'updater vérifié (Free refuse et invite à acheter, Base accepte ; confirmé le même jour). Restent pour mémoire, sans issue : le Dashboard Stripe (logo, paramètres Checkout, reçus automatiques, alertes d'échec de webhook) et les relevés du commentaire de fermeture. la-compagnie-maximus#184 (politique de confidentialité : données d'activation, contrôle au démarrage) est en `status:review` ; sa PR reste en brouillon jusqu'au déploiement de maximus-api#85 (commentaire du 2026-10-03). Les deux textes des suites de licence (contrôle à la saisie, retrait de la clé) y sont postés depuis le 2026-10-05 (commentaire 19724). **Vérifications manuelles sur la release publiée, toutes faites** : #365 le 2026-10-03, #346 et #350 le 2026-10-04 (voir Décisions). L'étape 10 sous Windows est faite (Michel, confirmée le 2026-10-10). - Backlog ouvert : **vague `planned-2026-09-24-paiements` close 3/3** (milestone fermée le 2026-09-30) : #270 (PR #359) et #346 (PR #362) mergées le 2026-09-27, #347 (PR #364, ferme aussi #360) mergée le 2026-09-30 ; volet site **clos** (maximus/la-compagnie-maximus#153, redirection de `/simpl-resultat` en prod). **#365 fermée le 2026-10-03** après sa vérification manuelle. **Milestone `planned-2026-10-03-suites-licence` fermée 3/3 le 2026-10-05** (#373, #370, #367 mergées, voir Décisions ; suivi #389 en `status:triage`). Hors milestone : **#369** (réserver le fractionnement de transactions à l'édition Base) **fermée le 2026-10-17** (PR #452, voir Décisions) ; **#372** (la liste complète des versions repousse le Journal en bas de Paramètres → Systèmes) reste en `status:ready`. **#350 fermée le 2026-10-04** (étape 3 vérifiée en production, voir Décisions) ; #363 fermée le 2026-10-10 sur décision de Max (ses tests, absorbés par #347, sont livrés dans la v0.16.0) ; réglés côté serveur et site : maximus-api#63 (clés de 100 ans) et maximus-api#70 (réactivation d'une machine désactivée), fermées et contenues dans `3673d09`, le commit déployé à la bascule du 2026-09-29, et la-compagnie-maximus#157, fermée, dont les CGV sont publiées en tronc commun plus annexe Simpl-Résultat (annexe relue en production le 2026-09-30, plus aucune durée de 10 ans) ; côté serveur, `/v1/prices` ne vérifie pas qu'une machine est encore active (une machine désactivée garde les cours jusqu'à l'expiration de son jeton), issue maximus-api à ouvrir ; suites de #350 ouvertes le 2026-10-01 : maximus-api#82 (`status:triage` : identifiants machine bruts déjà stockés, lignes désactivées comprises ; à rehacher avant l'expiration des premiers jetons bruts, sinon une réactivation crée une seconde ligne) et la-compagnie-maximus#184 (`status:review`, voir ci-dessus) ; go-live clos (la-compagnie-maximus#141 fermée le 2026-10-10, maximus-api#62 le 2026-10-03) ; `spec-paiements` fermée ici 5/5 ; onboarding phase 2 (parcours guidé) **mergée** : milestone `planned-2026-10-06-onboarding-parcours-guide` fermée 6/6 le 2026-10-08 (#396 à #401, `ee17f31`), suivis **#408** et **#409** (`status:triage`) ; onboarding phase 1 **livrée** : milestone `planned-2026-10-03-onboarding-phase1` fermée 7/7 le 2026-10-04 (#351 à #357, mergées en avance rapide, `667e058`) ; suivis ouverts : **#384** (`status:ready`, suivis non bloquants des revues) ; **#371** fermée le 2026-10-23 (PR #489, bloc BMO confirmé sur compte réel), la signature d'import BMO suit en **#488** (`status:blocked` : lignes aux valeurs fictives, préambule éventuel et en-tête d'un compte de dépôt à fournir par Max) ; analyse d'origine dans `docs/analyse-onboarding-2026-09.md`, plan détaillé dans les `spec-*-onboarding-phase1.md` locaux, ignorés par git ; #271 absorbé par #301, livré ; `spec-ci-build-optimization` **fermée 4/4** le 2026-10-05 (#232 livrée le 2026-07-27 ; #234 close le 2026-10-05 avec ses quatre preuves : dispatch run 464, PR #386 run 480, run planifié 488, `actcache` à 999 Mo) ; **#376** fermée le 2026-10-12 (Node 24, PR #414). Le suivi « glob `src-tauri/**` non prouvé » ouvert avec #232 est **levé** : la PR #344 est le cas test isolé attendu (`Cargo.lock` + 2 `.md` seulement) — `check-rust` a bien tourné, `check-frontend` a bien été sauté par sa denylist. - Suivis des advisories : **#312, #313 et #315 fermées le 2026-08-15** (PRs #321/#322 mergées). **#314 fermée le 2026-08-15, prémisse infirmée** — elle affirmait « zéro run `schedule` », or `audit.yml` tire tous les jours à 06:00 UTC (**19 runs `schedule` verts** du 07-28 au 08-15, sans trou) ; elle a été écrite le 07-27 vers 23:56Z, ~6 h avant le premier tir programmé possible, et décrivait donc une fenêtre trop courte, pas un scheduler en panne. Ces 19 runs confirment au passage que `.cargo/audit.toml` est bien lu en conteneur **sur `main`** — l'ADR 0018 ne l'avait vérifié que par un `workflow_dispatch` sur une branche. **#343 fermée le 2026-09-04** (PR #344) — RUSTSEC-2026-0258 sur `h2`, la seule vulnérabilité qui rougissait l'audit depuis le 08-19 ; l'audit est de nouveau vert sur `main`, prouvé par `workflow_dispatch` (run 393) et non déduit du run de PR. **#348 fermée le 2026-09-21** (PR #349) — RUSTSEC-2026-0285 sur `rustls`, seule vulnérabilité rougissant l'audit depuis le 09-15 (7 runs, 405→411) ; vert reprouvé par `workflow_dispatch` sur `main` (run 414 : 666 paquets, zéro vulnérabilité, 12 warnings autorisés). Deux advisories en cinq semaines sur le même chemin, celui de la mise à jour automatique. **#447 fermée le 2026-10-16** (PR #448, run 556 vert), quatre avis `rustls` sur ce même chemin ; le Défenseur n'audite pas le Rust (agent-defenseurs#186), `audit.yml` reste le seul canal pour les avis RustSec. **#455 fermée le 2026-10-18** (PR #459, run 564 vert), trois avis `zip` sur ce même chemin, retirés avec la feature `zip` de l'updater plutôt que supprimés. **#317** fermée le 2026-10-12 par la PR #417 (#358). Reste **#319** (déclencheur de retrait pour `rsa`, désormais **seule** entrée de `.cargo/audit.toml` — le garde-fou est passé à 2 vérifications). **#345** fermée le 2026-10-12 (PR #415) : garde `Verify windows-sys pinning` dans `check-rust.yml` et ADR 0023, qui portent la mesure, le coût (3 contre 5 versions compilées pour Windows) et la condition de sortie. Côté npm, **#358** fermée le 2026-10-12 (PR #417) : lock régénéré par `npm@11.21.0` dans les bornes de `package.json`, `npm audit` 8 → 0 au 2026-10-10. -- 2.52.0