From 23079da6094af68402a69c8b18628f4738ce9035 Mon Sep 17 00:00:00 2001 From: le king fu Date: Wed, 4 Nov 2026 22:32:49 -0500 Subject: [PATCH] fix: restore a profile holding a Bilan transfer, a missing category or a category under a newer one (#521) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three foreign keys stopped a restore on "FOREIGN KEY constraint failed", the whole restore rolled back: - (a) balance_account_transfers.transaction_id is ON DELETE RESTRICT (ADR 0010): the DELETE FROM transactions of both transaction modes, and so "Rétablir la sauvegarde", failed as soon as one transfer existed. Inside the restore's transaction, each transfer is now read with the date, amount and description of its transaction, then the table is emptied; once the transactions are back, the transfers whose transaction returns with the same id, date, amount and description are put back as they were (id, account, direction, notes, creation date), and the others are unlinked. - (b) a transaction whose category the profile no longer holds (after "Réinitialiser", another restore, or another profile's file) failed its insert: it now comes back without a category, manual flag at 0, and one Journal line gives their number, nothing else. - (c) restoreCategories inserted by id against parent_id, so a category under a newer one, or a loop, failed. Every category now goes in with parent_id NULL, and a second pass sets the parents. The three restores return a RestoreOutcome { unlinkedTransfers, uncategorizedTransactions } through runRestore (categories only: zeros). previewUnlinkedTransfers counts, outside any transaction and by the same rule, the transfers a restore would unlink. validateImportedCategoryReferences (pure, dataExportService.ts) refuses, at the parse and at the head of the two restores that write categories, a file whose parent_id, keyword or supplier names a category it does not hold (danglingCategoryReference), before anything is deleted. The "Gestion des données" card announces the transfers to unlink in its confirmation and gives the real number after the restore (IMPORT_SUCCESS carries the outcome). restoreFromBackup is split into readBackup (read, decrypt, parse, count) and applyBackup (restore, preferences, a RestoreResult with the outcome): "Rétablir la sauvegarde" reads the file (after the PIN when encrypted) before a second confirmation, ends on "Sauvegarde rétablie", and reloads the app on "Fermer" only. Regression test in src/__integration__/restore.test.ts (real services on node:sqlite, consolidated_schema.sql, foreign keys on): red on the base for the three causes, green here. Co-Authored-By: Claude Opus 5.5 --- .../category-migration.test.ts | 22 +- src/__integration__/restore.test.ts | 473 +++++++++++++++++- .../CategoriesMigrationRestoreModal.tsx | 186 +++++-- ...goriesMigrationRestoreModal.wiring.test.ts | 221 +++++++- .../DataManagementCard.render.test.tsx | 95 ++++ .../settings/DataManagementCard.tsx | 19 +- .../ImportConfirmModal.render.test.tsx | 66 +++ .../settings/ImportConfirmModal.tsx | 15 +- src/hooks/useDataImport.test.ts | 157 ++++++ src/hooks/useDataImport.ts | 49 +- src/i18n/locales/en.json | 14 +- src/i18n/locales/fr.json | 14 +- src/services/categoryRestoreService.test.ts | 208 ++++++-- src/services/categoryRestoreService.ts | 113 ++++- src/services/dataExportService.test.ts | 231 ++++++++- src/services/dataExportService.ts | 64 ++- src/services/dataRestoreService.ts | 272 +++++++++- 17 files changed, 2022 insertions(+), 197 deletions(-) create mode 100644 src/components/settings/DataManagementCard.render.test.tsx create mode 100644 src/components/settings/ImportConfirmModal.render.test.tsx create mode 100644 src/hooks/useDataImport.test.ts diff --git a/src/__integration__/category-migration.test.ts b/src/__integration__/category-migration.test.ts index 9348ce7..38ddbaa 100644 --- a/src/__integration__/category-migration.test.ts +++ b/src/__integration__/category-migration.test.ts @@ -51,7 +51,10 @@ vi.mock("../services/dataRestoreService", async () => { >("../services/dataRestoreService"); return { ...actual, - importTransactionsWithCategories: vi.fn(async () => undefined), + importTransactionsWithCategories: vi.fn(async () => ({ + unlinkedTransfers: 0, + uncategorizedTransactions: 0, + })), }; }); @@ -60,7 +63,7 @@ import { invoke } from "@tauri-apps/api/core"; import { computeMigrationPlan } from "../services/categoryMappingService"; import { createPreMigrationBackup } from "../services/categoryBackupService"; import { applyMigration } from "../services/categoryMigrationService"; -import { restoreFromBackup } from "../services/categoryRestoreService"; +import { applyBackup, readBackup } from "../services/categoryRestoreService"; import { importTransactionsWithCategories } from "../services/dataRestoreService"; import { makeV2Profile, makeV2ProfileWithCustom } from "../__fixtures__/profiles"; import type { Profile } from "../services/profileService"; @@ -116,7 +119,10 @@ beforeEach(() => { vi.mocked(getDb).mockResolvedValue(fake as never); mockInvoke.mockReset(); vi.mocked(importTransactionsWithCategories).mockReset(); - vi.mocked(importTransactionsWithCategories).mockResolvedValue(undefined); + vi.mocked(importTransactionsWithCategories).mockResolvedValue({ + unlinkedTransfers: 0, + uncategorizedTransactions: 0, + }); }); const PROFILE: Profile = { @@ -327,10 +333,14 @@ describe("integration: restore from SREF after a migration", () => { const outcome = await applyMigration(plan, backup); expect(outcome.succeeded).toBe(true); - // 2. Now call restoreFromBackup using the same path. - const restoreResult = await restoreFromBackup(backup.path, null); - expect(restoreResult.filePath).toBe(backup.path); + // 2. Now read the backup at the same path, then restore it, as the window + // does around its second confirmation (#521). + const reading = await readBackup(backup.path, null); + expect(reading.filePath).toBe(backup.path); + expect(vi.mocked(importTransactionsWithCategories)).not.toHaveBeenCalled(); + const restoreResult = await applyBackup(reading.envelope, reading.filename); expect(restoreResult.revertedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); + expect(restoreResult.outcome).toEqual({ unlinkedTransfers: 0, uncategorizedTransactions: 0 }); // 3. importTransactionsWithCategories must have been called exactly once. expect(vi.mocked(importTransactionsWithCategories)).toHaveBeenCalledTimes(1); diff --git a/src/__integration__/restore.test.ts b/src/__integration__/restore.test.ts index 3101eef..115ce4f 100644 --- a/src/__integration__/restore.test.ts +++ b/src/__integration__/restore.test.ts @@ -1,5 +1,7 @@ /** - * Restoring a backup that holds a split (#518). + * Restoring a backup that holds a split (#518), a Bilan transfer, a + * transaction whose category is gone, or a category ranked under a newer one + * (#521). * * A split line names its parent by `parent_transaction_id`, a foreign key to * `transactions(id)`. The restore used to insert every row without its id. In @@ -11,6 +13,14 @@ * lines without a parent first, and a file whose split lines cannot find their * parent is refused before anything is deleted. * + * Three other foreign keys stopped a restore the same way (#521): a Bilan + * transfer (`ON DELETE RESTRICT`, ADR 0010), the category of a transaction + * that the profile no longer holds, and the parent of a category inserted + * after it. The transfers whose transaction comes back as it was are now kept + * and the others unlinked, with their number announced before the + * confirmation; a transaction whose category is gone comes back without one; + * the categories go in without their parents, set in a second pass. + * * 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` @@ -50,7 +60,15 @@ vi.mock("../services/db", () => ({ const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() })); vi.mock("@tauri-apps/api/core", () => ({ invoke })); +// The Journal line of a restore that brings transactions back without their category (#521). +const { logWarn } = vi.hoisted(() => ({ logWarn: vi.fn() })); +vi.mock("../services/logService", async (orig) => ({ + ...(await orig()), + logWarn, +})); + import { getSplitChildren, saveSplitAdjustment } from "../services/transactionService"; +import { linkTransfer, listAccountTransfers } from "../services/balance.service"; import { getExportCategories, getExportImportSources, @@ -66,8 +84,14 @@ import { type ExportEnvelope, type ExportTransaction, } from "../services/dataExportService"; -import { importTransactionsOnly, importTransactionsWithCategories } from "../services/dataRestoreService"; -import { restoreFromBackup } from "../services/categoryRestoreService"; +import { + importCategoriesOnly, + importTransactionsOnly, + importTransactionsWithCategories, + previewUnlinkedTransfers, + type RestoreOutcome, +} from "../services/dataRestoreService"; +import { applyBackup, readBackup } from "../services/categoryRestoreService"; const SCHEMA = readFileSync( resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"), @@ -145,6 +169,7 @@ beforeEach(async () => { opened = []; fake.inTransaction = false; invoke.mockReset(); + logWarn.mockReset(); profile = use(open()); expect(imported("2026-10-05", "EPICERIE METRO", -120, GROCERIES)).toBe(1); expect(imported("2026-10-01", "LOYER", -1000, RENT)).toBe(2); @@ -219,12 +244,37 @@ async function jsonBackup(mode: Mode): Promise { return parseImportedJson(serializeToJson(mode, await exportData(mode), "0.17.2")).envelope.data; } -function restore(mode: Mode, data: ExportEnvelope["data"], filename = "backup.json"): Promise { +function restore(mode: Mode, data: ExportEnvelope["data"], filename = "backup.json"): Promise { return mode === "transactions_with_categories" ? importTransactionsWithCategories(data, filename) : importTransactionsOnly(data, filename); } +/** What « Exporter » writes for « Catégories uniquement », read back as the import reads it. */ +async function categoriesBackup(): Promise { + const data: ExportEnvelope["data"] = { + categories: await getExportCategories(), + suppliers: await getExportSuppliers(), + keywords: await getExportKeywords(), + }; + return parseImportedJson(serializeToJson("categories_only", data, "0.17.2")).envelope.data; +} + +/** + * « Rétablir la sauvegarde » as its window runs it: the file read (and its + * transfers counted) before the second confirmation, then restored (#521). + */ +async function restoreTheBackup(data: ExportEnvelope["data"]) { + const content = serializeToJson("transactions_with_categories", data, "0.17.2"); + invoke.mockImplementation(async (cmd: string) => { + if (cmd === "read_import_file") return content; + throw new Error(`unexpected invoke: ${cmd}`); + }); + const reading = await readBackup("/tmp/backup.sref", null); + const result = await applyBackup(reading.envelope, reading.filename); + return { reading, result }; +} + /** The refusal of a file whose split lines cannot find their parent. */ function expectRefusal(error: unknown): void { expect(error).toBeInstanceOf(SrefValidationError); @@ -365,19 +415,414 @@ describe("restoring a backup that holds a split (#518)", () => { it("« Rétablir la sauvegarde » of the categories migration restores a profile that holds a split", async () => { const before = rows(profile); - const content = serializeToJson( - "transactions_with_categories", - await exportData("transactions_with_categories"), - "0.17.2", - ); - invoke.mockImplementation(async (cmd: string) => { - if (cmd === "read_import_file") return content; - throw new Error(`unexpected invoke: ${cmd}`); - }); - await restoreFromBackup("/tmp/backup.sref", null); + await restoreTheBackup(await exportData("transactions_with_categories")); expect(rows(profile)).toEqual(before); expect(await splitLines(profile, "EPICERIE METRO")).toEqual(GROCERY_SPLIT); }); }); + +// --------------------------------------------------------------------------- +// #521 (a) — a Bilan transfer +// --------------------------------------------------------------------------- + +/** Accounts of the seed of a new profile. */ +const CELI = 2; // « CELI » +const REER = 3; // « REER » +const CELI_CATEGORY = 1962; // « CELI / TFSA », a transfer category of the seed + +type TransferRow = { + id: number; + account_id: number; + transaction_id: number; + direction: string; + notes: string | null; + created_at: string; +}; + +/** Every Bilan transfer of `db`, as the table holds it. */ +function transfersOf(db: DatabaseSync): TransferRow[] { + return db + .prepare( + "SELECT id, account_id, transaction_id, direction, notes, created_at FROM balance_account_transfers ORDER BY id", + ) + .all() + .map((row) => ({ ...row })) as TransferRow[]; +} + +/** A copy of `data` whose transaction `id` is changed by `change`. */ +function changingTransaction( + data: ExportEnvelope["data"], + id: number, + change: (tx: ExportTransaction) => ExportTransaction | null, +): ExportEnvelope["data"] { + return { + ...data, + transactions: (data.transactions ?? []).flatMap((tx) => { + if (tx.id !== id) return [tx]; + const changed = change(tx); + return changed === null ? [] : [changed]; + }), + }; +} + +describe("restoring a profile that holds a Bilan transfer (#521)", () => { + /** « VIREMENT CELI », linked to « CELI »: transfer 1. */ + let contribution: number; + /** « RETRAIT REER », linked to « REER »: transfer 2. */ + let withdrawal: number; + let transfersBefore: TransferRow[]; + let celiBefore: Awaited>; + + beforeEach(async () => { + contribution = imported("2026-10-04", "VIREMENT CELI", -500, CELI_CATEGORY); + withdrawal = imported("2026-10-06", "RETRAIT REER", 300, CELI_CATEGORY); + // The ids the files of `FILES` change, after the five rows of the probe of #518. + expect([contribution, withdrawal]).toEqual([6, 7]); + // As « Lier transferts » links them, by the real service. + await linkTransfer(CELI, contribution, "in", "Cotisation d'octobre"); + await linkTransfer(REER, withdrawal, "out"); + transfersBefore = transfersOf(profile); + expect(transfersBefore.map((t) => [t.id, t.account_id, t.transaction_id, t.direction])).toEqual([ + [1, CELI, contribution, "in"], + [2, REER, withdrawal, "out"], + ]); + // What the Bilan reads for the return of « CELI »: the transfer with its transaction. + celiBefore = await listAccountTransfers(CELI); + }); + + it.each(MODES)( + "%s, same profile: the restore succeeds, every transfer comes back as it was, none unlinked", + async (mode) => { + const before = rows(profile); + + const outcome = await restore(mode, await jsonBackup(mode)); + + expect(outcome.unlinkedTransfers).toBe(0); + expect(transfersOf(profile)).toEqual(transfersBefore); + expect(await listAccountTransfers(CELI)).toEqual(celiBefore); + expect(rows(profile)).toEqual(before); + }, + ); + + it.each(MODES)( + "%s: a transfer whose transaction comes back with another amount is unlinked, the other kept", + async (mode) => { + const data = changingTransaction(await jsonBackup(mode), contribution, (tx) => ({ ...tx, amount: -450 })); + + const outcome = await restore(mode, data); + + expect(outcome.unlinkedTransfers).toBe(1); + expect(transfersOf(profile)).toEqual([transfersBefore[1]]); + expect(await listAccountTransfers(CELI)).toEqual([]); + }, + ); + + it.each(MODES)("%s: the number of transfers to unlink is announced before the restore, which writes nothing", async (mode) => { + const data = changingTransaction(await jsonBackup(mode), contribution, (tx) => ({ ...tx, amount: -450 })); + const before = rows(profile); + + expect(await previewUnlinkedTransfers(data.transactions)).toBe(1); + expect(await previewUnlinkedTransfers((await jsonBackup(mode)).transactions)).toBe(0); + expect(rows(profile)).toEqual(before); + expect(transfersOf(profile)).toEqual(transfersBefore); + }); + + it.each(MODES)("%s, new profile: no transfer there, none unlinked; the profile of the file keeps its own", async (mode) => { + const data = await jsonBackup(mode); + const fresh = use(open()); + + expect(await previewUnlinkedTransfers(data.transactions)).toBe(0); + const outcome = await restore(mode, data); + + expect(outcome.unlinkedTransfers).toBe(0); + expect(transfersOf(fresh)).toEqual([]); + expect(transfersOf(profile)).toEqual(transfersBefore); + }); + + /** + * The files of the rule: a transfer is kept when its transaction comes back + * with the same id, the same date, the same amount and the same + * description; the number announced before the confirmation is the number + * unlinked. + */ + const FILES: Array<[string, (data: ExportEnvelope["data"]) => ExportEnvelope["data"], number[]]> = [ + ["the same file", (data) => data, [1, 2]], + ["the amount of « VIREMENT CELI » changed", (data) => changingTransaction(data, 6, (tx) => ({ ...tx, amount: -500.01 })), [2]], + ["its date changed", (data) => changingTransaction(data, 6, (tx) => ({ ...tx, date: "2026-10-05" })), [2]], + ["its description changed", (data) => changingTransaction(data, 6, (tx) => ({ ...tx, description: "VIREMENT CELI 2" })), [2]], + ["its id changed", (data) => changingTransaction(data, 6, (tx) => ({ ...tx, id: 60 })), [2]], + ["it is missing from the file", (data) => changingTransaction(data, 6, () => null), [2]], + [ + "« VIREMENT CELI » and « RETRAIT REER » swapped their ids", + (data) => + changingTransaction( + changingTransaction(changingTransaction(data, 6, (tx) => ({ ...tx, id: 70 })), 7, (tx) => ({ ...tx, id: 6 })), + 70, + (tx) => ({ ...tx, id: 7 }), + ), + [], + ], + [ + "its rows do not keep their ids (two share one, no split line)", + (data) => ({ + ...data, + transactions: (data.transactions ?? []) + .filter((tx) => tx.parent_transaction_id === null) + .map((tx) => (tx.id === 7 ? { ...tx, id: 6 } : { ...tx, is_split: 0 })), + }), + [], + ], + ]; + + describe.each(MODES)("%s: the number announced is the number unlinked", (mode) => { + it.each(FILES)("%s", async (_label, file, kept) => { + const data = file(await jsonBackup(mode)); + const announced = await previewUnlinkedTransfers(data.transactions); + + const outcome = await restore(mode, data); + + expect(transfersOf(profile).map((t) => t.id)).toEqual(kept); + expect(outcome.unlinkedTransfers).toBe(2 - kept.length); + expect(announced).toBe(outcome.unlinkedTransfers); + }); + }); + + it("« Rétablir la sauvegarde »: the transfers come back, none announced, none unlinked", async () => { + const { reading, result } = await restoreTheBackup(await exportData("transactions_with_categories")); + + expect(reading.unlinkedTransfers).toBe(0); + expect(result.outcome.unlinkedTransfers).toBe(0); + expect(transfersOf(profile)).toEqual(transfersBefore); + expect(await listAccountTransfers(CELI)).toEqual(celiBefore); + }); + + it("« Rétablir la sauvegarde »: a transfer whose transaction changed is announced at the reading, then unlinked", async () => { + const data = changingTransaction(await exportData("transactions_with_categories"), contribution, (tx) => ({ + ...tx, + amount: -450, + })); + + const { reading, result } = await restoreTheBackup(data); + + expect(reading.unlinkedTransfers).toBe(1); + expect(result.outcome.unlinkedTransfers).toBe(1); + expect(transfersOf(profile)).toEqual([transfersBefore[1]]); + }); + + it("the reading of « Rétablir la sauvegarde » writes nothing", async () => { + const data = changingTransaction(await exportData("transactions_with_categories"), contribution, () => null); + const content = serializeToJson("transactions_with_categories", data, "0.17.2"); + invoke.mockImplementation(async (cmd: string) => { + if (cmd === "read_import_file") return content; + throw new Error(`unexpected invoke: ${cmd}`); + }); + const before = rows(profile); + + const reading = await readBackup("/tmp/backup.sref", null); + + expect(reading.unlinkedTransfers).toBe(1); + expect(rows(profile)).toEqual(before); + expect(transfersOf(profile)).toEqual(transfersBefore); + }); +}); + +// --------------------------------------------------------------------------- +// #521 (b) — a transaction whose category is gone +// --------------------------------------------------------------------------- + +/** A category created by the user, outside the seed; its id. */ +function category(db: DatabaseSync, name: string): number { + const result = db + .prepare("INSERT INTO categories (name, type, sort_order) VALUES ($name, 'expense', 99)") + .run({ $name: name }); + return Number(result.lastInsertRowid); +} + +describe("restoring a transaction whose category is gone (#521)", () => { + /** « Perso », created by the user. */ + let perso: number; + /** « CADEAU », put by hand in « Perso ». */ + let gift: number; + + beforeEach(() => { + perso = category(profile, "Perso"); + gift = imported("2026-10-07", "CADEAU", -80, perso); + profile.prepare("UPDATE transactions SET is_manually_categorized = 1 WHERE id = $id").run({ $id: gift }); + }); + + /** The category and the manual flag of the transaction `id` of `db`. */ + const categorization = (db: DatabaseSync, id: number) => { + const row = rows(db).find((tx) => tx.id === id)!; + return { category_id: row.category_id, is_manually_categorized: row.is_manually_categorized }; + }; + + it("« Transactions uniquement » after the category was deleted: the transaction comes back without a category, manual flag at 0", async () => { + const before = rows(profile); + const data = await jsonBackup("transactions_only"); + // What « Réinitialiser » does to the categories: the rows are gone. + profile.prepare("DELETE FROM categories WHERE id = $id").run({ $id: perso }); + + const outcome = await importTransactionsOnly(data, "backup.json"); + + expect(categorization(profile, gift)).toEqual({ category_id: null, is_manually_categorized: 0 }); + expect(outcome.uncategorizedTransactions).toBe(1); + // The others come back as they were. + expect(rows(profile).filter((tx) => tx.id !== gift)).toEqual(before.filter((tx) => tx.id !== gift)); + }); + + it("the Journal gives their number, without a name or an amount", async () => { + const data = await jsonBackup("transactions_only"); + profile.prepare("DELETE FROM categories WHERE id = $id").run({ $id: perso }); + + await importTransactionsOnly(data, "backup.json"); + + expect(logWarn).toHaveBeenCalledTimes(1); + const [line] = logWarn.mock.calls[0]; + expect(line).toBe("Data restore: 1 transaction restored without a category, missing from the profile"); + }); + + it("no Journal line when every category is there", async () => { + const outcome = await importTransactionsOnly(await jsonBackup("transactions_only"), "backup.json"); + + expect(outcome.uncategorizedTransactions).toBe(0); + expect(logWarn).not.toHaveBeenCalled(); + }); + + it("« Transactions uniquement » after « Réinitialiser »: every transaction comes back without a category", async () => { + const data = await jsonBackup("transactions_only"); + // The real « Réinitialiser » puts the v2 seed back (ids 1 to 73): no IPC category is left. + const { reinitializeCategories } = await import("../services/categoryService"); + await reinitializeCategories(); + + const outcome = await importTransactionsOnly(data, "backup.json"); + + expect(outcome.uncategorizedTransactions).toBe(data.transactions!.length); + expect(rows(profile).every((tx) => tx.category_id === null && tx.is_manually_categorized === 0)).toBe(true); + expect(logWarn).toHaveBeenCalledWith( + `Data restore: ${data.transactions!.length} transactions restored without a category, missing from the profile`, + ); + }); + + it("« Transactions avec catégories » whose file lacks the category: the same", async () => { + const full = await jsonBackup("transactions_with_categories"); + const data = { ...full, categories: (full.categories ?? []).filter((c) => c.id !== perso) }; + + const outcome = await importTransactionsWithCategories(data, "backup.json"); + + expect(categorization(profile, gift)).toEqual({ category_id: null, is_manually_categorized: 0 }); + expect(outcome.uncategorizedTransactions).toBe(1); + }); + + it("witness: a category that is there keeps the transaction and its manual flag", async () => { + await importTransactionsOnly(await jsonBackup("transactions_only"), "backup.json"); + + expect(categorization(profile, gift)).toEqual({ category_id: perso, is_manually_categorized: 1 }); + }); +}); + +// --------------------------------------------------------------------------- +// #521 (c) — a category ranked under a newer one, or caught in a loop +// --------------------------------------------------------------------------- + +/** Every category of `db` with its parent. */ +function parents(db: DatabaseSync): Array<{ id: number; parent_id: number | null }> { + return db + .prepare("SELECT id, parent_id FROM categories ORDER BY id") + .all() + .map((row) => ({ ...row })) as Array<{ id: number; parent_id: number | null }>; +} + +const WITH_CATEGORIES = ["transactions_with_categories", "categories_only", "Rétablir la sauvegarde"] as const; + +/** Restores the backup of `db` the way `how` does. */ +async function restoreCategoriesBy(how: (typeof WITH_CATEGORIES)[number]): Promise { + if (how === "categories_only") { + await importCategoriesOnly(await categoriesBackup()); + } else if (how === "transactions_with_categories") { + await importTransactionsWithCategories(await jsonBackup("transactions_with_categories"), "backup.json"); + } else { + await restoreTheBackup(await exportData("transactions_with_categories")); + } +} + +describe("restoring a category ranked under a newer one, or caught in a loop (#521)", () => { + let before: Array<{ id: number; parent_id: number | null }>; + + beforeEach(() => { + // « Ancienne » under « Nouvelle », created after it, as the migration puts + // a personal category under « Catégories personnalisées (migration) » (2000). + const older = category(profile, "Ancienne"); + const newer = category(profile, "Nouvelle"); + profile.prepare("UPDATE categories SET parent_id = $p WHERE id = $id").run({ $p: newer, $id: older }); + // A loop: « Boucle A » under « Boucle B », « Boucle B » under « Boucle A ». + const a = category(profile, "Boucle A"); + const b = category(profile, "Boucle B"); + profile.prepare("UPDATE categories SET parent_id = $p WHERE id = $id").run({ $p: b, $id: a }); + profile.prepare("UPDATE categories SET parent_id = $p WHERE id = $id").run({ $p: a, $id: b }); + before = parents(profile); + expect(before.find((c) => c.id === older)?.parent_id).toBe(newer); + expect(newer).toBeGreaterThan(older); + }); + + it.each(WITH_CATEGORIES)("%s, same profile: the restore succeeds, every parent_id comes back as it was", async (how) => { + await restoreCategoriesBy(how); + + expect(parents(profile)).toEqual(before); + }); + + it.each(["transactions_with_categories", "categories_only"] as const)( + "%s, new profile: the same hierarchy", + async (how) => { + const data = how === "categories_only" ? await categoriesBackup() : await jsonBackup(how); + const fresh = use(open()); + + await (how === "categories_only" ? importCategoriesOnly(data) : importTransactionsWithCategories(data, "backup.json")); + + expect(parents(fresh)).toEqual(before); + }, + ); +}); + +// --------------------------------------------------------------------------- +// #521 — a category reference the file cannot satisfy (text 8) +// --------------------------------------------------------------------------- + +describe("a file whose keyword, supplier or parent names a category it does not hold (#521)", () => { + const DANGLING = "settings.dataManagement.import.errors.danglingCategoryReference"; + + const expectDangling = (error: unknown) => { + expect(error).toBeInstanceOf(SrefValidationError); + expect((error as SrefValidationError).i18nKey).toBe(DANGLING); + }; + + it.each(["transactions_with_categories", "categories_only"] as const)( + "%s: a keyword pointing to a missing category is refused at the parse and before anything is deleted; the profile is intact", + async (how) => { + const full = how === "categories_only" ? await categoriesBackup() : await jsonBackup(how); + const [keyword] = full.keywords ?? []; + // The keyword's category is not in the file. + const data = { ...full, categories: (full.categories ?? []).filter((c) => c.id !== keyword.category_id) }; + const before = rows(profile); + const categories = count(profile, "categories"); + const keywords = count(profile, "keywords"); + + let refusal: unknown = null; + try { + parseImportedJson(serializeToJson(how, data, "0.17.2")); + } catch (e) { + refusal = e; + } + expectDangling(refusal); + + const run = + how === "categories_only" ? importCategoriesOnly(data) : importTransactionsWithCategories(data, "backup.json"); + await run.then(() => expect.unreachable("the restore should have been refused"), expectDangling); + + expect(rows(profile)).toEqual(before); + expect(count(profile, "categories")).toBe(categories); + expect(count(profile, "keywords")).toBe(keywords); + }, + ); +}); diff --git a/src/components/settings/CategoriesMigrationRestoreModal.tsx b/src/components/settings/CategoriesMigrationRestoreModal.tsx index d10192d..31866f6 100644 --- a/src/components/settings/CategoriesMigrationRestoreModal.tsx +++ b/src/components/settings/CategoriesMigrationRestoreModal.tsx @@ -1,14 +1,17 @@ import { useEffect, useState } from "react"; import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; -import { AlertTriangle, FolderOpen, Loader2, X } from "lucide-react"; +import { AlertTriangle, CheckCircle, FolderOpen, Loader2, X } from "lucide-react"; import { + applyBackup, backupFileExists, isFileEncrypted, pickBackupFile, - restoreFromBackup, + readBackup, RestoreError, + type BackupReading, type RestorableMigrationJournal, + type RestoreResult, } from "../../services/categoryRestoreService"; import { SrefValidationError } from "../../services/dataExportService"; @@ -17,13 +20,17 @@ import { SrefValidationError } from "../../services/dataExportService"; // Settings entry to roll back a category migration. Mounted via a portal on // document.body so it escapes any ancestor stacking context. // -// High-level flow: +// High-level flow (#521): // 1. Mount with the recorded `journal` — show the date + path and two CTAs. // 2. On "Restore" click: verify the recorded file still exists on disk. If // not, flip to the "missing file" state and let the user pick a file. // 3. If the file is SREF-encrypted, prompt the PIN; otherwise proceed. -// 4. Run `restoreFromBackup`, reload the app on success so every page sees -// the restored state. +// 4. Read the file (`readBackup`): nothing is written yet. +// 5. Second confirmation: what the restore will lose for good, the Bilan +// transfers it will unlink, before the user clicks "Restore" again. +// 6. Run `applyBackup`, then show "Backup restored" with what it did. The +// app reloads only on "Close", so that every page sees the restored state +// after the user has read it. // // The UX intentionally keeps destructive action behind an explicit "Restore" // button — a single click does not restore; the user must read the warning @@ -35,16 +42,20 @@ type Phase = | "confirm" // initial screen with the data/path + Restore/Cancel buttons | "missing" // recorded path no longer on disk — user must pick a file | "password" // detected SREF encryption — ask for the PIN + | "reading" // in-flight read of the file, nothing written + | "review" // second confirmation, once the file is read | "restoring" // in-flight restore call + | "done" // restored — reloads the app on "Close" | "error"; // failed — surface the error and allow retry interface CategoriesMigrationRestoreModalProps { journal: RestorableMigrationJournal; onClose: () => void; /** - * Called after the restore finishes successfully. By default, the app is - * reloaded to refresh all data-bound views. Consumers may override this - * (e.g. in tests) but the default is the safe path. + * Called when the user closes the window once the restore has succeeded + * ("Close" of the "Backup restored" phase). By default, the app is reloaded + * to refresh all data-bound views. Consumers may override this (e.g. in + * tests) but the default is the safe path. */ onRestored?: () => void; } @@ -60,15 +71,31 @@ export default function CategoriesMigrationRestoreModal({ const [password, setPassword] = useState(""); const [error, setError] = useState(null); const [isEncrypted, setIsEncrypted] = useState(false); + const [reading, setReading] = useState(null); + const [result, setResult] = useState(null); - // Close on Escape (disabled while restoring to avoid interrupting the wipe). + const isBusy = phase === "reading" || phase === "restoring"; + + /** Leaves the window once restored: the app reloads, so every page reads the restored profile. */ + function finish() { + if (onRestored) { + onRestored(); + } else { + window.location.reload(); + } + } + + // Once restored, every way out of the window is "Close": it reloads. + const dismiss = phase === "done" ? finish : onClose; + + // Close on Escape (disabled while reading or restoring). useEffect(() => { function handleEscape(e: KeyboardEvent) { - if (e.key === "Escape" && phase !== "restoring") onClose(); + if (e.key === "Escape" && !isBusy) dismiss(); } document.addEventListener("keydown", handleEscape); return () => document.removeEventListener("keydown", handleEscape); - }, [onClose, phase]); + }, [dismiss, isBusy]); const formattedDate = formatJournalDate(journal.timestamp); @@ -114,21 +141,32 @@ export default function CategoriesMigrationRestoreModal({ return; } - await runRestore(pathToUse, null); + await readFile(pathToUse, null); } - async function runRestore(pathToUse: string, pw: string | null) { + /** Reads the file, then opens the second confirmation: nothing is written yet. */ + async function readFile(pathToUse: string, pw: string | null) { + setPhase("reading"); + setError(null); + try { + setReading(await readBackup(pathToUse, pw)); + setPhase("review"); + } catch (e) { + setError(messageForError(e)); + setPhase("error"); + } + } + + /** The destructive write, after the second confirmation. */ + async function runRestore() { + if (!reading) return; setPhase("restoring"); setError(null); try { - await restoreFromBackup(pathToUse, pw); - if (onRestored) { - onRestored(); - } else { - // Full reload so every page (dashboard, transactions, etc.) reflects - // the restored v2 state instead of stale v1 derived data. - window.location.reload(); - } + setResult(await applyBackup(reading.envelope, reading.filename)); + // The app reloads on "Close" only, once the user has read what the + // restore did (#521). + setPhase("done"); } catch (e) { setError(messageForError(e)); setPhase("error"); @@ -154,16 +192,14 @@ export default function CategoriesMigrationRestoreModal({ function handlePasswordSubmit(e: React.FormEvent) { e.preventDefault(); - void runRestore(effectivePath, password.length > 0 ? password : null); + void readFile(effectivePath, password.length > 0 ? password : null); } - const isBusy = phase === "restoring"; - return createPortal(
{ - if (e.target === e.currentTarget && !isBusy) onClose(); + if (e.target === e.currentTarget && !isBusy) dismiss(); }} role="dialog" aria-modal="true" @@ -173,12 +209,20 @@ export default function CategoriesMigrationRestoreModal({ {/* Header */}
-
- -
+ {phase === "done" ? ( +
+ +
+ ) : ( +
+ +
+ )}

- {t("settings.categoriesCard.restoreModal.title")} + {phase === "done" + ? t("settings.categoriesCard.restoreModal.doneTitle") + : t("settings.categoriesCard.restoreModal.title")}

{t("settings.categoriesCard.restoreModal.subtitle", { @@ -189,7 +233,7 @@ export default function CategoriesMigrationRestoreModal({

+ + + )} + + {phase === "done" && ( + + )} + {phase === "error" && ( <>