A restore with categories (full backup, categories only, and "Restore the backup" of the categories migration) ran DELETE FROM categories, whose ON DELETE CASCADE took every budget line, template line and adjustment line with it, while the backup held none: the restore succeeded and left the budget empty. - SREF format 3: the two modes that carry the categories now carry budget_entries, budget_templates (by name, with their lines) and adjustments (with their lines). collectExportData(mode) gathers the arrays of each mode for the export and for the pre-migration backup. - Restore: the profile's budget lines, template lines and adjustment lines are read and taken out before DELETE FROM categories, in both formats, through the restore's handle. At format 3 the file's budget lines and adjustments replace the profile's, each file template is upserted by name with its lines replaced, and a template absent from the file keeps its header and its lines whose category comes back. Below format 3 the lines whose category comes back are put back as they were. - The restores of the two category modes take the file's format (formatVersion), passed by useDataImport and applyBackup. - Pure validation at the parse and at the head of each restore: a format newer than this build is refused (newerFormat), a non-integer or below 1 gets the malformed-file error, and at format 3 a missing array or a line the tables cannot hold is refused (invalidBudgetRows). - restoreCategories writes i18n_key. - Confirmations: willDeleteCategories and willDeleteAll name the budget, the counts of budget lines, templates and adjustments, and the note of a backup older than format 3 in the card and in the second confirmation of "Restore the backup"; categories.reinitializeConfirm names what "Re-initialize" erases. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
208 lines
8 KiB
TypeScript
208 lines
8 KiB
TypeScript
// useDataImport — what the « Gestion des données » card learns before and
|
|
// after a restore (#521): the Bilan transfers the restore would unlink, counted
|
|
// once the file is read, before the confirmation opens; and the outcome of the
|
|
// committed restore, which the success message reads.
|
|
//
|
|
// No jsdom: the hook runs as a plain function under the shared harness
|
|
// (src/test/hookHarness.ts, #409). Its reducer is applied, but nothing renders
|
|
// again by itself: the test renders after each call to read the new state and
|
|
// the callbacks of that render.
|
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
|
|
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
|
|
vi.mock("react-i18next", async () => (await import("../test/i18nMock")).i18nMock());
|
|
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
|
|
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
|
const restore = vi.hoisted(() => ({
|
|
importCategoriesOnly: vi.fn(),
|
|
importTransactionsWithCategories: vi.fn(),
|
|
importTransactionsOnly: vi.fn(),
|
|
previewUnlinkedTransfers: vi.fn(),
|
|
}));
|
|
vi.mock("../services/dataRestoreService", () => restore);
|
|
|
|
import { hookHarness } from "../test/hookHarness";
|
|
import { useDataImport } from "./useDataImport";
|
|
import { serializeToJson, type ExportMode } from "../services/dataExportService";
|
|
|
|
const harness = hookHarness();
|
|
|
|
/** One render of the mounted hook. */
|
|
const render = () => harness.render(() => useDataImport());
|
|
|
|
const TRANSACTION = {
|
|
id: 1,
|
|
date: "2026-10-04",
|
|
description: "VIREMENT CELI",
|
|
amount: -500,
|
|
category_id: null,
|
|
category_name: null,
|
|
original_description: null,
|
|
notes: null,
|
|
is_manually_categorized: 0,
|
|
is_split: 0,
|
|
parent_transaction_id: null,
|
|
};
|
|
|
|
/** The budget arrays of the two modes that carry the categories, from format 3 on (#520). */
|
|
const NO_BUDGET = { budget_entries: [], budget_templates: [], adjustments: [] };
|
|
|
|
/** The data of a backup of `mode`, as « Exporter » gathers it. */
|
|
function dataOf(mode: ExportMode) {
|
|
return mode === "categories_only"
|
|
? { categories: [], suppliers: [], keywords: [], ...NO_BUDGET }
|
|
: mode === "transactions_only"
|
|
? { transactions: [TRANSACTION], import_sources: [], import_config_templates: [] }
|
|
: {
|
|
categories: [],
|
|
suppliers: [],
|
|
keywords: [],
|
|
transactions: [TRANSACTION],
|
|
import_sources: [],
|
|
import_config_templates: [],
|
|
...NO_BUDGET,
|
|
};
|
|
}
|
|
|
|
/** A backup of `mode`, as « Exporter » writes it. */
|
|
function backupOf(mode: ExportMode): string {
|
|
return serializeToJson(mode, dataOf(mode), "0.17.2");
|
|
}
|
|
|
|
/** A backup of `mode` as the previous version wrote it: format 2, no budget. */
|
|
function previousVersionBackupOf(mode: ExportMode): string {
|
|
const data: Record<string, unknown> = { ...dataOf(mode) };
|
|
for (const array of Object.keys(NO_BUDGET)) delete data[array];
|
|
return JSON.stringify({
|
|
export_type: mode,
|
|
app_version: "0.17.2",
|
|
format_version: 2,
|
|
exported_at: "2026-10-18T12:00:00.000Z",
|
|
data,
|
|
});
|
|
}
|
|
|
|
/** The file the user picks: `content`, encrypted or not. */
|
|
function picking(content: string, encrypted = false) {
|
|
invoke.mockImplementation(async (cmd: string) => {
|
|
if (cmd === "pick_import_file") return encrypted ? "/tmp/backup.sref" : "/tmp/backup.json";
|
|
if (cmd === "is_file_encrypted") return encrypted;
|
|
if (cmd === "read_import_file") return content;
|
|
throw new Error(`unexpected invoke: ${cmd}`);
|
|
});
|
|
}
|
|
|
|
const NO_OUTCOME = { unlinkedTransfers: 0, uncategorizedTransactions: 0 };
|
|
|
|
beforeEach(() => {
|
|
harness.clear();
|
|
invoke.mockReset();
|
|
for (const fn of Object.values(restore)) fn.mockReset();
|
|
restore.previewUnlinkedTransfers.mockResolvedValue(0);
|
|
restore.importCategoriesOnly.mockResolvedValue(NO_OUTCOME);
|
|
restore.importTransactionsWithCategories.mockResolvedValue(NO_OUTCOME);
|
|
restore.importTransactionsOnly.mockResolvedValue(NO_OUTCOME);
|
|
});
|
|
|
|
describe("useDataImport — the Bilan transfers a restore would unlink (#521)", () => {
|
|
it.each<ExportMode>(["transactions_with_categories", "transactions_only"])(
|
|
"%s: counted once the file is read, before the confirmation opens",
|
|
async (mode) => {
|
|
picking(backupOf(mode));
|
|
restore.previewUnlinkedTransfers.mockResolvedValue(2);
|
|
|
|
await render().pickAndRead();
|
|
|
|
const { state } = render();
|
|
expect(state.status).toBe("confirming");
|
|
expect(state.unlinkedTransfers).toBe(2);
|
|
// Counted on the transactions of the file, and nothing restored yet.
|
|
expect(restore.previewUnlinkedTransfers).toHaveBeenCalledWith([TRANSACTION]);
|
|
expect(restore.importTransactionsWithCategories).not.toHaveBeenCalled();
|
|
expect(restore.importTransactionsOnly).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
|
|
it("categories only: no transaction is deleted, so nothing is counted", async () => {
|
|
picking(backupOf("categories_only"));
|
|
|
|
await render().pickAndRead();
|
|
|
|
const { state } = render();
|
|
expect(state.status).toBe("confirming");
|
|
expect(state.unlinkedTransfers).toBe(0);
|
|
expect(restore.previewUnlinkedTransfers).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("an encrypted file: counted once decrypted", async () => {
|
|
picking(backupOf("transactions_only"), true);
|
|
restore.previewUnlinkedTransfers.mockResolvedValue(1);
|
|
|
|
await render().pickAndRead();
|
|
expect(render().state.status).toBe("needsPassword");
|
|
expect(restore.previewUnlinkedTransfers).not.toHaveBeenCalled();
|
|
|
|
await render().readWithPassword("secret-password");
|
|
|
|
const { state } = render();
|
|
expect(state.status).toBe("confirming");
|
|
expect(state.unlinkedTransfers).toBe(1);
|
|
});
|
|
});
|
|
|
|
describe("useDataImport — the outcome of the restore reaches the success state (#521)", () => {
|
|
it.each<[ExportMode, keyof typeof restore]>([
|
|
["transactions_with_categories", "importTransactionsWithCategories"],
|
|
["transactions_only", "importTransactionsOnly"],
|
|
["categories_only", "importCategoriesOnly"],
|
|
])("%s: IMPORT_SUCCESS carries what %s returned", async (mode, entry) => {
|
|
const outcome = { unlinkedTransfers: 3, uncategorizedTransactions: 1 };
|
|
restore[entry].mockResolvedValue(outcome);
|
|
picking(backupOf(mode));
|
|
await render().pickAndRead();
|
|
|
|
await render().executeImport();
|
|
|
|
const { state } = render();
|
|
expect(restore[entry]).toHaveBeenCalledTimes(1);
|
|
expect(state.status).toBe("success");
|
|
expect(state.outcome).toEqual(outcome);
|
|
expect(harness.dispatch).toHaveBeenCalledWith({ type: "IMPORT_SUCCESS", outcome });
|
|
});
|
|
|
|
it.each<[string, () => string, number]>([
|
|
["this version's backup", () => backupOf("transactions_with_categories"), 3],
|
|
["a backup of the previous version", () => previousVersionBackupOf("transactions_with_categories"), 2],
|
|
])("transactions_with_categories, %s: the restore is given the format the file declares (%i) (#520)", async (_label, file, formatVersion) => {
|
|
picking(file());
|
|
await render().pickAndRead();
|
|
|
|
await render().executeImport();
|
|
|
|
expect(restore.importTransactionsWithCategories).toHaveBeenCalledWith(expect.anything(), "backup.json", formatVersion);
|
|
});
|
|
|
|
it.each<[string, () => string, number]>([
|
|
["this version's backup", () => backupOf("categories_only"), 3],
|
|
["a backup of the previous version", () => previousVersionBackupOf("categories_only"), 2],
|
|
])("categories_only, %s: the restore is given the format the file declares (%i) (#520)", async (_label, file, formatVersion) => {
|
|
picking(file());
|
|
await render().pickAndRead();
|
|
|
|
await render().executeImport();
|
|
|
|
expect(restore.importCategoriesOnly).toHaveBeenCalledWith(expect.anything(), formatVersion);
|
|
});
|
|
|
|
it("a new file starts without the outcome of the last restore", async () => {
|
|
restore.importTransactionsOnly.mockResolvedValue({ unlinkedTransfers: 2, uncategorizedTransactions: 0 });
|
|
picking(backupOf("transactions_only"));
|
|
await render().pickAndRead();
|
|
await render().executeImport();
|
|
expect(render().state.outcome?.unlinkedTransfers).toBe(2);
|
|
|
|
await render().pickAndRead();
|
|
|
|
expect(render().state.outcome).toBeNull();
|
|
});
|
|
});
|