From 09c7b32dd123db94abef0a16eedf7d60a427c9a1 Mon Sep 17 00:00:00 2001
From: le king fu
Date: Wed, 4 Nov 2026 23:32:58 -0500
Subject: [PATCH] fix: carry the budget in SREF backups and keep it on restore
(#520)
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
---
.../category-migration.test.ts | 19 +-
src/__integration__/regression-v2-v1.test.ts | 7 +
src/__integration__/restore.test.ts | 568 +++++++++++++++++-
.../CategoriesMigrationRestoreModal.tsx | 15 +-
...goriesMigrationRestoreModal.wiring.test.ts | 47 +-
.../ImportConfirmModal.render.test.tsx | 67 ++-
.../settings/ImportConfirmModal.tsx | 43 +-
src/hooks/useDataExport.ts | 28 +-
src/hooks/useDataImport.test.ts | 65 +-
src/hooks/useDataImport.ts | 11 +-
src/i18n/locales/en.json | 15 +-
src/i18n/locales/fr.json | 15 +-
src/services/categoryBackupService.test.ts | 61 +-
src/services/categoryBackupService.ts | 51 +-
src/services/categoryRestoreService.test.ts | 37 +-
src/services/categoryRestoreService.ts | 11 +-
src/services/categoryService.test.ts | 21 +
src/services/dataExportService.test.ts | 435 ++++++++++++--
src/services/dataExportService.ts | 335 ++++++++++-
src/services/dataRestoreService.ts | 219 ++++++-
20 files changed, 1861 insertions(+), 209 deletions(-)
diff --git a/src/__integration__/category-migration.test.ts b/src/__integration__/category-migration.test.ts
index 38ddbaa..d85b80f 100644
--- a/src/__integration__/category-migration.test.ts
+++ b/src/__integration__/category-migration.test.ts
@@ -30,21 +30,10 @@ vi.mock("@tauri-apps/api/app", () => ({
getVersion: vi.fn(async () => "0.8.3-test"),
}));
-// dataExportService helpers are used by both the backup service and the
-// restore service, which writes the backup back through dataRestoreService. We
-// mock the "DB-reading" ones and that write, and keep the parsers real.
-vi.mock("../services/dataExportService", async () => {
- const actual = await vi.importActual<
- typeof import("../services/dataExportService")
- >("../services/dataExportService");
- return {
- ...actual,
- getExportCategories: vi.fn(async () => []),
- getExportSuppliers: vi.fn(async () => []),
- getExportKeywords: vi.fn(async () => []),
- getExportTransactions: vi.fn(async () => []),
- };
-});
+// The backup service gathers its arrays through `collectExportData` (#520),
+// whose reads reach the fake DB below, which answers every one of them with no
+// row; the parsers stay real. The restore service writes the backup back
+// through dataRestoreService, whose write is mocked.
vi.mock("../services/dataRestoreService", async () => {
const actual = await vi.importActual<
typeof import("../services/dataRestoreService")
diff --git a/src/__integration__/regression-v2-v1.test.ts b/src/__integration__/regression-v2-v1.test.ts
index e628d5d..455f8d8 100644
--- a/src/__integration__/regression-v2-v1.test.ts
+++ b/src/__integration__/regression-v2-v1.test.ts
@@ -282,6 +282,10 @@ function envelopeFixture(schema: Schema): ExportEnvelope {
suppliers: [],
keywords: [],
transactions: [],
+ // A full backup of format 3 carries the budget arrays (#520).
+ budget_entries: [],
+ budget_templates: [],
+ adjustments: [],
},
};
}
@@ -368,6 +372,9 @@ describe.each<[Schema]>([["v2"], ["v1"]])(
parent_transaction_id: 100,
},
],
+ budget_entries: [],
+ budget_templates: [],
+ adjustments: [],
},
};
const json = serializeToJson(envelope.export_type, envelope.data, envelope.app_version);
diff --git a/src/__integration__/restore.test.ts b/src/__integration__/restore.test.ts
index bbca03e..77058e1 100644
--- a/src/__integration__/restore.test.ts
+++ b/src/__integration__/restore.test.ts
@@ -21,6 +21,13 @@
* confirmation; a transaction whose category is gone comes back without one;
* the categories go in without their parents, set in a second pass.
*
+ * And one let a restore succeed with a loss (#520): the budget lines, the
+ * template lines and the adjustment lines name a category `ON DELETE
+ * CASCADE`, so the restores with categories left them all empty, and the
+ * backup held none. The file now carries them (format 3) and they come back;
+ * an older file keeps the profile's lines whose category comes back. The
+ * categories come back with their `i18n_key`.
+ *
* 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`
@@ -56,9 +63,11 @@ vi.mock("../services/db", () => ({
}),
}));
-// « Rétablir la sauvegarde » reads its file through `read_import_file`.
+// « Rétablir la sauvegarde » reads its file through `read_import_file`, and the
+// backup taken before the categories migration writes it (#520).
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
+vi.mock("@tauri-apps/api/app", () => ({ getVersion: vi.fn(async () => "0.17.2") }));
// The Journal line of a restore that brings transactions back without their category (#521).
const { logWarn } = vi.hoisted(() => ({ logWarn: vi.fn() }));
@@ -70,18 +79,16 @@ vi.mock("../services/logService", async (orig) => ({
import { getSplitChildren, saveSplitAdjustment } from "../services/transactionService";
import { linkTransfer, listAccountTransfers } from "../services/balance.service";
import {
- getExportCategories,
- getExportImportSources,
- getExportImportTemplates,
- getExportKeywords,
- getExportSuppliers,
+ collectExportData,
getExportTransactions,
parseImportedCsv,
parseImportedJson,
serializeToJson,
serializeTransactionsToCsv,
+ SREF_FORMAT_VERSION,
SrefValidationError,
type ExportEnvelope,
+ type ExportMode,
type ExportTransaction,
} from "../services/dataExportService";
import {
@@ -92,6 +99,12 @@ import {
type RestoreOutcome,
} from "../services/dataRestoreService";
import { applyBackup, readBackup } from "../services/categoryRestoreService";
+import { saveAsTemplate, upsertBudgetEntry } from "../services/budgetService";
+import { createAdjustment, createEntry } from "../services/adjustmentService";
+import { createPreMigrationBackup } from "../services/categoryBackupService";
+import { computeMigrationPlan } from "../services/categoryMappingService";
+import { applyMigration } from "../services/categoryMigrationService";
+import type { Profile } from "../services/profileService";
const SCHEMA = readFileSync(
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
@@ -225,18 +238,9 @@ async function splitLines(db: DatabaseSync, description: string) {
return lines.map((line) => ({ amount: line.amount, category_id: line.category_id }));
}
-/** What « Exporter » gathers for `mode` (`useDataExport`), from the database in use. */
-async function exportData(mode: Mode): Promise {
- const data: ExportEnvelope["data"] = {};
- if (mode === "transactions_with_categories") {
- data.categories = await getExportCategories();
- data.suppliers = await getExportSuppliers();
- data.keywords = await getExportKeywords();
- }
- data.transactions = await getExportTransactions();
- data.import_sources = await getExportImportSources();
- data.import_config_templates = await getExportImportTemplates();
- return data;
+/** What « Exporter » gathers for `mode` (`collectExportData`, #520), from the database in use. */
+function exportData(mode: ExportMode): Promise {
+ return collectExportData(mode);
}
/** A JSON backup of the database in use, written then read back as the import reads it. */
@@ -244,20 +248,22 @@ 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 {
+/** The restore of the card for `mode`, of a file of `formatVersion` (the format this build writes by default). */
+function restore(
+ mode: Mode,
+ data: ExportEnvelope["data"],
+ filename = "backup.json",
+ formatVersion = SREF_FORMAT_VERSION,
+): Promise {
return mode === "transactions_with_categories"
- ? importTransactionsWithCategories(data, filename)
+ ? importTransactionsWithCategories(data, filename, formatVersion)
: 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;
+ return parseImportedJson(serializeToJson("categories_only", await exportData("categories_only"), "0.17.2")).envelope
+ .data;
}
/**
@@ -265,7 +271,11 @@ async function categoriesBackup(): Promise {
* 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");
+ return restoreTheFile(serializeToJson("transactions_with_categories", data, "0.17.2"));
+}
+
+/** « Rétablir la sauvegarde » of the file `content`, written by this version or an older one (#520). */
+async function restoreTheFile(content: string) {
invoke.mockImplementation(async (cmd: string) => {
if (cmd === "read_import_file") return content;
throw new Error(`unexpected invoke: ${cmd}`);
@@ -713,7 +723,7 @@ describe("restoring a transaction whose category is gone (#521)", () => {
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");
+ const outcome = await importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION);
expect(categorization(profile, gift)).toEqual({ category_id: null, is_manually_categorized: 0 });
expect(outcome.uncategorizedTransactions).toBe(1);
@@ -743,9 +753,13 @@ const WITH_CATEGORIES = ["transactions_with_categories", "categories_only", "Ré
/** 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());
+ await importCategoriesOnly(await categoriesBackup(), SREF_FORMAT_VERSION);
} else if (how === "transactions_with_categories") {
- await importTransactionsWithCategories(await jsonBackup("transactions_with_categories"), "backup.json");
+ await importTransactionsWithCategories(
+ await jsonBackup("transactions_with_categories"),
+ "backup.json",
+ SREF_FORMAT_VERSION,
+ );
} else {
await restoreTheBackup(await exportData("transactions_with_categories"));
}
@@ -782,7 +796,9 @@ describe("restoring a category ranked under a newer one, or caught in a loop (#5
const data = how === "categories_only" ? await categoriesBackup() : await jsonBackup(how);
const fresh = use(open());
- await (how === "categories_only" ? importCategoriesOnly(data) : importTransactionsWithCategories(data, "backup.json"));
+ await (how === "categories_only"
+ ? importCategoriesOnly(data, SREF_FORMAT_VERSION)
+ : importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION));
expect(parents(fresh)).toEqual(before);
},
@@ -821,7 +837,9 @@ describe("a file whose keyword, supplier or parent names a category it does not
expectDangling(refusal);
const run =
- how === "categories_only" ? importCategoriesOnly(data) : importTransactionsWithCategories(data, "backup.json");
+ how === "categories_only"
+ ? importCategoriesOnly(data, SREF_FORMAT_VERSION)
+ : importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION);
await run.then(() => expect.unreachable("the restore should have been refused"), expectDangling);
expect(rows(profile)).toEqual(before);
@@ -830,3 +848,489 @@ describe("a file whose keyword, supplier or parent names a category it does not
},
);
});
+
+// ---------------------------------------------------------------------------
+// #520 — the budget, its templates and the adjustments
+// ---------------------------------------------------------------------------
+
+type BudgetLine = { category_id: number; year: number; month: number; amount: number; notes: string | null };
+type TemplateLine = { category_id: number; amount: number };
+type AdjustmentLine = { category_id: number; amount: number; description: string | null };
+type BudgetState = {
+ entries: BudgetLine[];
+ templates: Array<{ name: string; description: string | null; entries: TemplateLine[] }>;
+ adjustments: Array<{
+ name: string;
+ description: string | null;
+ date: string;
+ is_recurring: number;
+ recurrence_rule: string | null;
+ entries: AdjustmentLine[];
+ }>;
+};
+
+/** Every row `sql` returns on `db`, as plain objects. */
+function all(db: DatabaseSync, sql: string, params: Record = {}): T[] {
+ return db
+ .prepare(sql)
+ .all(params)
+ .map((row) => ({ ...row })) as T[];
+}
+
+/**
+ * What the Budget and Adjustments pages show of `db`: the budget lines, each
+ * template with its lines, each adjustment with its lines, in the order the
+ * pages list them, without the ids SQLite gives.
+ */
+function budgetOf(db: DatabaseSync): BudgetState {
+ return {
+ entries: all(
+ db,
+ "SELECT category_id, year, month, amount, notes FROM budget_entries ORDER BY category_id, year, month",
+ ),
+ templates: all<{ id: number; name: string; description: string | null }>(
+ db,
+ "SELECT id, name, description FROM budget_templates ORDER BY name",
+ ).map(({ id, ...template }) => ({
+ ...template,
+ entries: all(
+ db,
+ "SELECT category_id, amount FROM budget_template_entries WHERE template_id = $id ORDER BY id",
+ { $id: id },
+ ),
+ })),
+ adjustments: all(
+ db,
+ "SELECT id, name, description, date, is_recurring, recurrence_rule FROM adjustments ORDER BY date DESC, id",
+ ).map(({ id, ...adjustment }) => ({
+ ...adjustment,
+ entries: all(
+ db,
+ "SELECT category_id, amount, description FROM adjustment_entries WHERE adjustment_id = $id ORDER BY id",
+ { $id: id },
+ ),
+ })),
+ };
+}
+
+/** Every budget line, template line and adjustment line of `db`, ids and dates included: « kept » is untouched. */
+function budgetRows(db: DatabaseSync) {
+ return {
+ entries: all(db, "SELECT * FROM budget_entries ORDER BY id"),
+ templateLines: all(db, "SELECT * FROM budget_template_entries ORDER BY id"),
+ adjustmentLines: all(db, "SELECT * FROM adjustment_entries ORDER BY id"),
+ };
+}
+
+/** The categories a budget is written on. */
+type BudgetCategories = { groceries: number; rent: number; electricity: number };
+
+/**
+ * A budget on `on`, written by the real services of the Budget and Adjustments
+ * pages: three budget lines, the template « Mois type » and its two lines, the
+ * adjustment « Rattrapage » and its two lines.
+ */
+async function writeBudget(on: BudgetCategories): Promise {
+ await upsertBudgetEntry(on.groceries, 2026, 10, 450, "Octobre");
+ await upsertBudgetEntry(on.groceries, 2026, 11, 470);
+ await upsertBudgetEntry(on.rent, 2026, 10, 1000);
+ await saveAsTemplate("Mois type", "Le budget d'un mois", [
+ { category_id: on.groceries, amount: 400 },
+ { category_id: on.rent, amount: 1000 },
+ ]);
+ const adjustment = await createAdjustment({
+ name: "Rattrapage",
+ description: "Crédit sur facture",
+ date: "2026-10-15",
+ is_recurring: false,
+ });
+ await createEntry({ adjustment_id: adjustment, category_id: on.electricity, amount: -30, description: "Crédit" });
+ await createEntry({ adjustment_id: adjustment, category_id: on.groceries, amount: 15 });
+}
+
+/** The two modes that carry the categories, and with them the budget. */
+const WITH_BUDGET = ["transactions_with_categories", "categories_only"] as const;
+type WithBudget = (typeof WITH_BUDGET)[number];
+
+/** The backup of `how`, as « Exporter » writes it and the import reads it back. */
+function budgetBackup(how: WithBudget): Promise {
+ return how === "categories_only" ? categoriesBackup() : jsonBackup(how);
+}
+
+/** The restore of the card for `how`, of a file of `formatVersion`. */
+function restoreBudgetBackup(
+ how: WithBudget,
+ data: ExportEnvelope["data"],
+ formatVersion = SREF_FORMAT_VERSION,
+): Promise {
+ return how === "categories_only"
+ ? importCategoriesOnly(data, formatVersion)
+ : importTransactionsWithCategories(data, "backup.json", formatVersion);
+}
+
+/**
+ * `data` as the previous version wrote it for `how`: format 2, without the
+ * three budget arrays, then read back as the import reads it.
+ */
+function previousVersionFile(how: ExportMode, data: ExportEnvelope["data"]) {
+ const older = { ...data };
+ delete older.budget_entries;
+ delete older.budget_templates;
+ delete older.adjustments;
+ const content = JSON.stringify({
+ export_type: how,
+ app_version: "0.17.2",
+ format_version: 2,
+ exported_at: "2026-10-18T12:00:00.000Z",
+ data: older,
+ });
+ return { content, ...parseImportedJson(content) };
+}
+
+/** The id of the template or the adjustment `name` in `db`. */
+function idOf(db: DatabaseSync, table: "budget_templates" | "adjustments", name: string): number {
+ return (db.prepare(`SELECT id FROM ${table} WHERE name = $name`).get({ $name: name }) as { id: number }).id;
+}
+
+const INVALID_BUDGET = "settings.dataManagement.import.errors.invalidBudgetRows";
+const NEWER_FORMAT = "settings.dataManagement.import.errors.newerFormat";
+
+/** The refusal `key` (text 9 or text 10). */
+function expectRefusalOf(key: string) {
+ return (error: unknown) => {
+ expect(error).toBeInstanceOf(SrefValidationError);
+ expect((error as SrefValidationError).i18nKey).toBe(key);
+ };
+}
+
+/** What `run` throws; fails when it throws nothing. */
+function thrownBy(run: () => unknown): unknown {
+ try {
+ run();
+ } catch (e) {
+ return e;
+ }
+ return expect.unreachable("should have been refused");
+}
+
+describe("restoring a backup with its budget, its templates and its adjustments (#520)", () => {
+ const SEED: BudgetCategories = { groceries: GROCERIES, rent: RENT, electricity: ELECTRICITY };
+ /** The budget of the profile when the backup is taken. */
+ let before: BudgetState;
+
+ beforeEach(async () => {
+ await writeBudget(SEED);
+ before = budgetOf(profile);
+ expect(before.entries).toHaveLength(3);
+ expect(before.templates.map((t) => [t.name, t.entries.length])).toEqual([["Mois type", 2]]);
+ expect(before.adjustments.map((a) => [a.name, a.entries.length])).toEqual([["Rattrapage", 2]]);
+ });
+
+ it.each(WITH_BUDGET)(
+ "%s, same profile: the budget lines, the templates and the adjustments come back as they were",
+ async (how) => {
+ await restoreBudgetBackup(how, await budgetBackup(how));
+
+ expect(budgetOf(profile)).toEqual(before);
+ },
+ );
+
+ it.each(WITH_BUDGET)("%s, new profile: the same budget lines, templates and adjustments", async (how) => {
+ const data = await budgetBackup(how);
+ const fresh = use(open());
+
+ await restoreBudgetBackup(how, data);
+
+ expect(budgetOf(fresh)).toEqual(before);
+ });
+
+ it.each(WITH_BUDGET)("%s: the budget lines and the adjustments of the file replace those of the profile", async (how) => {
+ const data = await budgetBackup(how);
+ // Since the backup, on categories that come back: an amount changed, a line and an adjustment added.
+ await upsertBudgetEntry(GROCERIES, 2026, 10, 999);
+ await upsertBudgetEntry(ELECTRICITY, 2026, 12, 90);
+ const added = await createAdjustment({ name: "Ajouté", date: "2026-11-01", is_recurring: true });
+ await createEntry({ adjustment_id: added, category_id: RENT, amount: 50 });
+
+ await restoreBudgetBackup(how, data);
+
+ expect(budgetOf(profile)).toEqual(before);
+ });
+
+ it.each(WITH_BUDGET)(
+ "%s: a template of the file is updated by its name, its lines replaced; a template absent from the file keeps its header and its lines whose category comes back",
+ async (how) => {
+ const data = await budgetBackup(how);
+ // Since the backup: « Mois type » changed, and « Vacances » created with a line on a category the file does not hold.
+ const monthly = idOf(profile, "budget_templates", "Mois type");
+ profile.prepare("UPDATE budget_templates SET description = 'Changé' WHERE id = $id").run({ $id: monthly });
+ profile.prepare("DELETE FROM budget_template_entries WHERE template_id = $id").run({ $id: monthly });
+ profile
+ .prepare("INSERT INTO budget_template_entries (template_id, category_id, amount) VALUES ($id, $category, 80)")
+ .run({ $id: monthly, $category: ELECTRICITY });
+ const newer = category(profile, "Nouvelle");
+ await saveAsTemplate("Vacances", undefined, [
+ { category_id: GROCERIES, amount: 200 },
+ { category_id: newer, amount: 50 },
+ ]);
+
+ await restoreBudgetBackup(how, data);
+
+ expect(budgetOf(profile).templates).toEqual([
+ before.templates[0],
+ { name: "Vacances", description: null, entries: [{ category_id: GROCERIES, amount: 200 }] },
+ ]);
+ // Updated in place, under its own id.
+ expect(idOf(profile, "budget_templates", "Mois type")).toBe(monthly);
+ },
+ );
+
+ it("« Rétablir la sauvegarde »: the budget of the backup comes back", async () => {
+ const data = await exportData("transactions_with_categories");
+ await upsertBudgetEntry(ELECTRICITY, 2026, 12, 90);
+
+ const { reading } = await restoreTheBackup(data);
+
+ expect(reading.summary.formatVersion).toBe(SREF_FORMAT_VERSION);
+ expect(budgetOf(profile)).toEqual(before);
+ });
+
+ it.each(WITH_BUDGET)(
+ "%s, a backup of the previous version (format 2): the lines whose category comes back are kept as they were, the others go",
+ async (how) => {
+ const older = previousVersionFile(how, await budgetBackup(how));
+ expect(older.summary.formatVersion).toBe(2);
+ const kept = budgetRows(profile);
+ // Since the backup: a category the file does not hold, with a line of each kind.
+ const newer = category(profile, "Nouvelle");
+ await upsertBudgetEntry(newer, 2026, 10, 60);
+ profile
+ .prepare("INSERT INTO budget_template_entries (template_id, category_id, amount) VALUES ($id, $category, 25)")
+ .run({ $id: idOf(profile, "budget_templates", "Mois type"), $category: newer });
+ await createEntry({ adjustment_id: idOf(profile, "adjustments", "Rattrapage"), category_id: newer, amount: 5 });
+
+ await restoreBudgetBackup(how, older.envelope.data, older.summary.formatVersion);
+
+ expect(budgetOf(profile)).toEqual(before);
+ // Kept is untouched: the same ids, the same dates.
+ expect(budgetRows(profile)).toEqual(kept);
+ },
+ );
+
+ it("« Rétablir la sauvegarde » of a backup of the previous version: the lines whose category comes back are kept", async () => {
+ const older = previousVersionFile("transactions_with_categories", await exportData("transactions_with_categories"));
+ const kept = budgetRows(profile);
+
+ const { reading } = await restoreTheFile(older.content);
+
+ expect(reading.summary.formatVersion).toBe(2);
+ expect(budgetRows(profile)).toEqual(kept);
+ });
+
+ it("witness: « Transactions uniquement » carries no budget and leaves the profile's as it is", async () => {
+ const data = await jsonBackup("transactions_only");
+ expect([data.budget_entries, data.budget_templates, data.adjustments]).toEqual([undefined, undefined, undefined]);
+ const kept = budgetRows(profile);
+
+ await restore("transactions_only", data);
+
+ expect(budgetRows(profile)).toEqual(kept);
+ });
+});
+
+describe("a budget the restore could not write back, or a newer file, is refused before anything is deleted (#520)", () => {
+ let before: BudgetState;
+
+ beforeEach(async () => {
+ await writeBudget({ groceries: GROCERIES, rent: RENT, electricity: ELECTRICITY });
+ before = budgetOf(profile);
+ });
+
+ it.each(WITH_BUDGET)(
+ "%s: a budget line that names a category missing from the file is refused at the parse and at the head of the restore",
+ async (how) => {
+ const full = await budgetBackup(how);
+ const [first, ...others] = full.budget_entries ?? [];
+ const data = { ...full, budget_entries: [{ ...first, category_id: 999_999 }, ...others] };
+ const transactions = rows(profile);
+ const categories = count(profile, "categories");
+
+ expectRefusalOf(INVALID_BUDGET)(thrownBy(() => parseImportedJson(serializeToJson(how, data, "0.17.2"))));
+ await restoreBudgetBackup(how, data).then(
+ () => expect.unreachable("the restore should have been refused"),
+ expectRefusalOf(INVALID_BUDGET),
+ );
+
+ expect(budgetOf(profile)).toEqual(before);
+ expect(rows(profile)).toEqual(transactions);
+ expect(count(profile, "categories")).toBe(categories);
+ },
+ );
+
+ describe.each(WITH_BUDGET)("%s, a file of format 3 that lacks one of its three arrays", (how) => {
+ it.each(["budget_entries", "budget_templates", "adjustments"] as const)(
+ "without %s: refused at the parse and at the head of the restore, the budget never emptied",
+ async (array) => {
+ const data = { ...(await budgetBackup(how)) };
+ delete data[array];
+
+ expectRefusalOf(INVALID_BUDGET)(thrownBy(() => parseImportedJson(serializeToJson(how, data, "0.17.2"))));
+ await restoreBudgetBackup(how, data).then(
+ () => expect.unreachable("the restore should have been refused"),
+ expectRefusalOf(INVALID_BUDGET),
+ );
+
+ expect(budgetOf(profile)).toEqual(before);
+ },
+ );
+ });
+
+ it("a file of a newer version (format 4) is refused in the card and in « Rétablir la sauvegarde », and nothing is deleted", async () => {
+ const data = await exportData("transactions_with_categories");
+ const content = JSON.stringify({
+ export_type: "transactions_with_categories",
+ app_version: "9.0.0",
+ format_version: 4,
+ exported_at: "2027-01-01T00:00:00.000Z",
+ data,
+ });
+ const transactions = rows(profile);
+
+ // The card: refused at the parse, and again at the head of each restore.
+ expectRefusalOf(NEWER_FORMAT)(thrownBy(() => parseImportedJson(content)));
+ await importTransactionsWithCategories(data, "backup.json", 4).then(
+ () => expect.unreachable("the restore should have been refused"),
+ expectRefusalOf(NEWER_FORMAT),
+ );
+ await importCategoriesOnly(data, 4).then(
+ () => expect.unreachable("the restore should have been refused"),
+ expectRefusalOf(NEWER_FORMAT),
+ );
+
+ // « Rétablir la sauvegarde »: refused at the reading, before its second confirmation.
+ invoke.mockImplementation(async (cmd: string) => {
+ if (cmd === "read_import_file") return content;
+ throw new Error(`unexpected invoke: ${cmd}`);
+ });
+ await readBackup("/tmp/backup.sref", null).then(
+ () => expect.unreachable("the reading should have been refused"),
+ expectRefusalOf(NEWER_FORMAT),
+ );
+
+ expect(budgetOf(profile)).toEqual(before);
+ expect(rows(profile)).toEqual(transactions);
+ });
+});
+
+describe("a restore with categories keeps the translation key of each category (#520)", () => {
+ /** Every category of `db` with its translation key. */
+ const keysOf = (db: DatabaseSync) =>
+ all<{ id: number; i18n_key: string | null }>(db, "SELECT id, i18n_key FROM categories ORDER BY id");
+
+ it.each(WITH_CATEGORIES)("%s, same profile: every category comes back with its i18n_key", async (how) => {
+ const before = keysOf(profile);
+ // The standard seed names its categories by key: the English interface reads them.
+ expect(before.filter((c) => c.i18n_key !== null).length).toBeGreaterThan(100);
+
+ await restoreCategoriesBy(how);
+
+ expect(keysOf(profile)).toEqual(before);
+ });
+
+ it.each(WITH_BUDGET)("%s, new profile: the same keys", async (how) => {
+ const before = keysOf(profile);
+ const data = await budgetBackup(how);
+ const fresh = use(open());
+
+ await restoreBudgetBackup(how, data);
+
+ expect(keysOf(fresh)).toEqual(before);
+ });
+});
+
+describe("« Rétablir la sauvegarde » after the categories migration (#520)", () => {
+ /** « Épicerie », « Loyer » and « Électricité » of the former seed, which « Réinitialiser » puts back. */
+ const V2: BudgetCategories = { groceries: 22, rent: 20, electricity: 21 };
+ const PROFILE: Profile = {
+ id: "p1",
+ name: "Profil",
+ color: "#f59e0b",
+ pin_hash: null,
+ db_filename: "profil.db",
+ created_at: "2026-01-01T00:00:00Z",
+ };
+
+ /**
+ * The migration as its page runs it (`CategoriesMigrationPage`): the backup
+ * written and verified first, then the plan computed from the profile and
+ * applied. Returns the backup as it was written.
+ */
+ async function migrate(): Promise {
+ let written = "";
+ invoke.mockImplementation(async (cmd: string, args?: { content?: string }) => {
+ if (cmd === "ensure_backup_dir") return "/tmp/sr-backups";
+ if (cmd === "write_export_file") {
+ written = args?.content ?? "";
+ return undefined;
+ }
+ if (cmd === "read_import_file") return written;
+ if (cmd === "get_file_size") return written.length;
+ throw new Error(`unexpected invoke: ${cmd}`);
+ });
+ const backup = await createPreMigrationBackup({ profile: PROFILE });
+ const plan = computeMigrationPlan({
+ v2Categories: all<{ id: number; name: string; parent_id: number | null }>(
+ profile,
+ "SELECT id, name, parent_id FROM categories WHERE is_active = 1",
+ ),
+ keywords: all<{ id: number; keyword: string; category_id: number }>(
+ profile,
+ "SELECT id, keyword, category_id FROM keywords WHERE is_active = 1",
+ ),
+ transactions: all<{ id: number; description: string; category_id: number | null; supplier_id: number | null }>(
+ profile,
+ "SELECT id, description, category_id, supplier_id FROM transactions",
+ ),
+ suppliers: all<{ id: number; name: string }>(profile, "SELECT id, name FROM suppliers WHERE is_active = 1"),
+ });
+ const outcome = await applyMigration(plan, backup);
+ expect(outcome.succeeded, outcome.error).toBe(true);
+ return written;
+ }
+
+ /** The budget of the former state, when the backup is taken. */
+ let former: BudgetState;
+
+ beforeEach(async () => {
+ // A profile on the former categories: « Réinitialiser » puts their seed back.
+ const { reinitializeCategories } = await import("../services/categoryService");
+ await reinitializeCategories();
+ await writeBudget(V2);
+ former = budgetOf(profile);
+ });
+
+ it("a backup of format 3: the budget, the templates and the adjustments of the former state come back exactly", async () => {
+ const backup = await migrate();
+ expect(JSON.parse(backup).format_version).toBe(SREF_FORMAT_VERSION);
+ // The migration moved the budget onto the standard categories.
+ expect(budgetOf(profile).entries.every((entry) => entry.category_id >= 1000)).toBe(true);
+
+ await restoreTheFile(backup);
+
+ expect(budgetOf(profile)).toEqual(former);
+ });
+
+ it("a backup of the previous version (format 2): the lines the migration moved onto the standard categories do not come back (ADR 0025)", async () => {
+ const backup = await migrate();
+ const older = previousVersionFile("transactions_with_categories", JSON.parse(backup).data);
+
+ const { reading } = await restoreTheFile(older.content);
+
+ expect(reading.summary.formatVersion).toBe(2);
+ const after = budgetOf(profile);
+ expect(after.entries).toEqual([]);
+ expect(after.templates).toEqual(former.templates.map((template) => ({ ...template, entries: [] })));
+ // The migration leaves the adjustment lines on the former categories, which come back with the file.
+ expect(after.adjustments).toEqual(former.adjustments);
+ });
+});
diff --git a/src/components/settings/CategoriesMigrationRestoreModal.tsx b/src/components/settings/CategoriesMigrationRestoreModal.tsx
index 31866f6..ba3a6ad 100644
--- a/src/components/settings/CategoriesMigrationRestoreModal.tsx
+++ b/src/components/settings/CategoriesMigrationRestoreModal.tsx
@@ -13,7 +13,10 @@ import {
type RestorableMigrationJournal,
type RestoreResult,
} from "../../services/categoryRestoreService";
-import { SrefValidationError } from "../../services/dataExportService";
+import {
+ BUDGET_SREF_FORMAT_VERSION,
+ SrefValidationError,
+} from "../../services/dataExportService";
// -----------------------------------------------------------------------------
// Confirmation modal used by both the in-window banner and the permanent
@@ -27,7 +30,9 @@ import { SrefValidationError } from "../../services/dataExportService";
// 3. If the file is SREF-encrypted, prompt the PIN; otherwise proceed.
// 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.
+// transfers it will unlink, and, from a backup older than the budget in
+// backups, the budget lines whose category does not come back (#520),
+// 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.
@@ -308,6 +313,12 @@ export default function CategoriesMigrationRestoreModal({
{reading.filePath}
+ {/* A backup older than the budget in backups brings none back (#520) */}
+ {reading.summary.formatVersion < BUDGET_SREF_FORMAT_VERSION && (
+
+ {t("settings.categoriesCard.restoreModal.legacyBudgetNote")}
+
+ )}
{reading.unlinkedTransfers > 0 && (
{t("settings.categoriesCard.restoreModal.unlinkedTransfersPreview", {
diff --git a/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts b/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts
index 380567d..5fc58ca 100644
--- a/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts
+++ b/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts
@@ -1,8 +1,8 @@
// CategoriesMigrationRestoreModal — what « Rétablir la sauvegarde » shows when
// the import boundary refuses the backup (#518), and its steps once the file is
// read (#521): a second confirmation that announces the Bilan transfers the
-// restore will unlink, then « Sauvegarde rétablie », and a reload only on
-// « Fermer ».
+// restore will unlink, and says when the backup holds no budget (#520), then
+// « Sauvegarde rétablie », and a reload only on « Fermer ».
//
// A static render runs no effect and clicks nothing. React's hooks come from
// the shared harness (src/test/hookHarness.ts, #409): the window runs as a
@@ -60,17 +60,26 @@ const JOURNAL: RestorableMigrationJournal = {
const PROPS = { journal: JOURNAL, onClose: vi.fn(), onRestored: vi.fn() };
-/** The backup as `readBackup` returns it, announcing `unlinkedTransfers`. */
-function readingOf(unlinkedTransfers: number): BackupReading {
+/**
+ * The backup as `readBackup` returns it, announcing `unlinkedTransfers`, of
+ * `formatVersion`: 3 carries the budget, an older one does not (#520).
+ */
+function readingOf(unlinkedTransfers: number, formatVersion = 3): BackupReading {
return {
filePath: JOURNAL.backupPath,
filename: "profile_avant-migration.sref",
envelope: {
export_type: "transactions_with_categories",
app_version: "0.17.2",
- format_version: 2,
+ format_version: formatVersion,
exported_at: "2026-10-01T10:00:00Z",
- data: { categories: [], suppliers: [], keywords: [], transactions: [] },
+ data: {
+ categories: [],
+ suppliers: [],
+ keywords: [],
+ transactions: [],
+ ...(formatVersion >= 3 ? { budget_entries: [], budget_templates: [], adjustments: [] } : {}),
+ },
},
summary: {
type: "transactions_with_categories",
@@ -80,7 +89,10 @@ function readingOf(unlinkedTransfers: number): BackupReading {
transactionsCount: 0,
importSourcesCount: 0,
importTemplatesCount: 0,
- formatVersion: 2,
+ budgetEntriesCount: 0,
+ budgetTemplatesCount: 0,
+ adjustmentsCount: 0,
+ formatVersion,
},
unlinkedTransfers,
};
@@ -263,6 +275,27 @@ describe("CategoriesMigrationRestoreModal — a second confirmation, then « Sau
expect(PROPS.onClose).not.toHaveBeenCalled();
});
+ it.each([2, 1])("a backup of format %i: the second confirmation says it holds no budget (#520)", async (formatVersion) => {
+ service.readBackup.mockResolvedValue(readingOf(0, formatVersion));
+
+ await confirm();
+
+ expect(texts(render())).toContain(label("legacyBudgetNote"));
+ expect(service.applyBackup).not.toHaveBeenCalled();
+ });
+
+ it("a backup of format 3 carries its budget: no note (#520)", async () => {
+ service.readBackup.mockResolvedValue(readingOf(0, 3));
+
+ await confirm();
+
+ expect(texts(render()).join(" ")).not.toContain("legacyBudgetNote");
+ // Nor once restored.
+ service.applyBackup.mockResolvedValue(resultOf(0));
+ await confirm();
+ expect(texts(render()).join(" ")).not.toContain("legacyBudgetNote");
+ });
+
it("an encrypted backup: the PIN first, then the reading and the second confirmation", async () => {
service.isFileEncrypted.mockResolvedValue(true);
service.readBackup.mockResolvedValue(readingOf(1));
diff --git a/src/components/settings/ImportConfirmModal.render.test.tsx b/src/components/settings/ImportConfirmModal.render.test.tsx
index a879caa..12945e9 100644
--- a/src/components/settings/ImportConfirmModal.render.test.tsx
+++ b/src/components/settings/ImportConfirmModal.render.test.tsx
@@ -1,9 +1,10 @@
// ImportConfirmModal — the confirmation of « Importer » announces the Bilan
-// transfers the restore will unlink, before anything is deleted (#521). No
-// jsdom: react-dom/server renders the initial markup in vitest's node
-// environment. It cannot render a portal, and the window is one: `createPortal`
-// becomes the identity, and `document` a stub for the `document.body` it is
-// given.
+// transfers the restore will unlink, before anything is deleted (#521), and
+// what becomes of the budget (#520): the lines a file of format 3 brings back,
+// or, for an older file, the note that it holds none. No jsdom:
+// react-dom/server renders the initial markup in vitest's node environment. It
+// cannot render a portal, and the window is one: `createPortal` becomes the
+// identity, and `document` a stub for the `document.body` it is given.
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
import type { ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
@@ -25,7 +26,10 @@ const SUMMARY: ImportSummary = {
transactionsCount: 12,
importSourcesCount: 0,
importTemplatesCount: 0,
- formatVersion: 2,
+ budgetEntriesCount: 0,
+ budgetTemplatesCount: 0,
+ adjustmentsCount: 0,
+ formatVersion: 3,
};
beforeAll(() => {
@@ -36,10 +40,10 @@ afterAll(() => {
vi.unstubAllGlobals();
});
-const markup = (importType: ExportMode, unlinkedTransfers: number) =>
+const markup = (importType: ExportMode, unlinkedTransfers: number, summary: Partial = {}) =>
renderToStaticMarkup(
/>,
);
+const KEY = "settings.dataManagement.import";
+/** The budget a file carries, as its summary counts it. */
+const WITH_BUDGET = { budgetEntriesCount: 24, budgetTemplatesCount: 2, adjustmentsCount: 3 };
+
describe("ImportConfirmModal — the Bilan transfers the restore will unlink (#521)", () => {
it.each<[ExportMode, number]>([
["transactions_with_categories", 1],
@@ -64,3 +72,46 @@ describe("ImportConfirmModal — the Bilan transfers the restore will unlink (#5
expect(html).toContain("t(settings.dataManagement.import.irreversibleWarning)");
});
});
+
+describe("ImportConfirmModal — the budget, its templates and the adjustments (#520)", () => {
+ it.each<[ExportMode, string]>([
+ ["categories_only", "willDeleteCategories"],
+ ["transactions_with_categories", "willDeleteAll"],
+ ])("%s: names them among what is deleted (%s)", (importType, willDelete) => {
+ expect(markup(importType, 0)).toContain(`t(${KEY}.${willDelete})`);
+ });
+
+ it.each(["categories_only", "transactions_with_categories"])(
+ "%s, format 3: counts the budget lines, templates and adjustments the file brings back, no note",
+ (importType) => {
+ const html = markup(importType, 0, WITH_BUDGET);
+ expect(html).toContain(`t(${KEY}.countBudgetEntries[count=24])`);
+ expect(html).toContain(`t(${KEY}.countBudgetTemplates[count=2])`);
+ expect(html).toContain(`t(${KEY}.countAdjustments[count=3])`);
+ expect(html).not.toContain("legacyBudgetNote");
+ },
+ );
+
+ it("format 3, a profile without a budget: no count, no note", () => {
+ const html = markup("transactions_with_categories", 0);
+ expect(html).not.toMatch(/countBudgetEntries|countBudgetTemplates|countAdjustments|legacyBudgetNote/);
+ });
+
+ it.each<[ExportMode, number]>([
+ ["categories_only", 2],
+ ["transactions_with_categories", 2],
+ ["transactions_with_categories", 1],
+ ])("%s, format %i: the note says the file holds no budget, next to the warning, and nothing is counted", (importType, formatVersion) => {
+ const html = markup(importType, 0, { ...WITH_BUDGET, formatVersion });
+ expect(html).toContain(`t(${KEY}.legacyBudgetNote)`);
+ expect(html).toContain(`t(${KEY}.irreversibleWarning)`);
+ expect(html).not.toMatch(/countBudgetEntries|countBudgetTemplates|countAdjustments/);
+ });
+
+ it("« Transactions uniquement » leaves the budget alone: neither count nor note, whatever the format", () => {
+ for (const formatVersion of [1, 2, 3]) {
+ const html = markup("transactions_only", 0, { ...WITH_BUDGET, formatVersion });
+ expect(html, `format ${formatVersion}`).not.toMatch(/countBudgetEntries|countBudgetTemplates|countAdjustments|legacyBudgetNote/);
+ }
+ });
+});
diff --git a/src/components/settings/ImportConfirmModal.tsx b/src/components/settings/ImportConfirmModal.tsx
index cfadf17..b693151 100644
--- a/src/components/settings/ImportConfirmModal.tsx
+++ b/src/components/settings/ImportConfirmModal.tsx
@@ -2,7 +2,11 @@ import { useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { AlertTriangle, X, Loader2 } from "lucide-react";
-import type { ImportSummary, ExportMode } from "../../services/dataExportService";
+import {
+ BUDGET_SREF_FORMAT_VERSION,
+ type ImportSummary,
+ type ExportMode,
+} from "../../services/dataExportService";
interface ImportConfirmModalProps {
summary: ImportSummary;
@@ -72,6 +76,33 @@ export default function ImportConfirmModal({
);
}
+ // The budget travels with the categories (#520). A file of format 3 or later
+ // brings it back, and says how much of it; an older one holds none, and the
+ // note says that the current lines whose category comes back are kept.
+ const carriesBudget = importType !== "transactions_only";
+ const legacyBudget =
+ carriesBudget && summary.formatVersion < BUDGET_SREF_FORMAT_VERSION;
+ if (carriesBudget && !legacyBudget) {
+ if (summary.budgetEntriesCount > 0)
+ willImport.push(
+ t("settings.dataManagement.import.countBudgetEntries", {
+ count: summary.budgetEntriesCount,
+ })
+ );
+ if (summary.budgetTemplatesCount > 0)
+ willImport.push(
+ t("settings.dataManagement.import.countBudgetTemplates", {
+ count: summary.budgetTemplatesCount,
+ })
+ );
+ if (summary.adjustmentsCount > 0)
+ willImport.push(
+ t("settings.dataManagement.import.countAdjustments", {
+ count: summary.adjustmentsCount,
+ })
+ );
+ }
+
// The import configurations travel with both transaction modes (#331). They
// are listed so the user sees that a restore now brings its sources back
// rather than leaving every one of them to reconfigure.
@@ -139,9 +170,15 @@ export default function ImportConfirmModal({
- {/* Warning, and what the restore loses for good: the Bilan transfers
- whose transaction does not come back as it was (#521) */}
+ {/* Warning, and what the restore loses for good: the budget lines a
+ file older than the budget does not bring back (#520), the Bilan
+ transfers whose transaction does not come back as it was (#521) */}
+ {legacyBudget && (
+
+ {t("settings.dataManagement.import.legacyBudgetNote")}
+
+ )}
{unlinkedTransfers > 0 && (
{t("settings.dataManagement.import.unlinkedTransfersPreview", {
diff --git a/src/hooks/useDataExport.ts b/src/hooks/useDataExport.ts
index 184276d..5830cf1 100644
--- a/src/hooks/useDataExport.ts
+++ b/src/hooks/useDataExport.ts
@@ -2,12 +2,7 @@ import { useReducer, useCallback } from "react";
import { invoke } from "@tauri-apps/api/core";
import { getVersion } from "@tauri-apps/api/app";
import {
- getExportCategories,
- getExportSuppliers,
- getExportKeywords,
- getExportTransactions,
- getExportImportSources,
- getExportImportTemplates,
+ collectExportData,
serializeToJson,
serializeTransactionsToCsv,
type ExportMode,
@@ -54,27 +49,16 @@ export function useDataExport() {
try {
const appVersion = await getVersion();
- // Gather data based on mode
- const data: Record = {};
- if (mode === "transactions_with_categories" || mode === "categories_only") {
- data.categories = await getExportCategories();
- data.suppliers = await getExportSuppliers();
- data.keywords = await getExportKeywords();
- }
- if (mode === "transactions_with_categories" || mode === "transactions_only") {
- data.transactions = await getExportTransactions();
- // The import configurations travel with the transaction modes — the
- // two the restore wipes `import_sources` for. A categories-only
- // backup neither carries them nor touches them (#331).
- data.import_sources = await getExportImportSources();
- data.import_config_templates = await getExportImportTemplates();
- }
+ // Gather data based on mode: the arrays of each mode, the import
+ // configurations (#331) and the budget (#520) among them, are those
+ // of the backup taken before the categories migration.
+ const data = await collectExportData(mode);
// Serialize
let content: string;
let defaultExt: string;
if (format === "csv") {
- content = serializeTransactionsToCsv(data.transactions as never[]);
+ content = serializeTransactionsToCsv(data.transactions ?? []);
defaultExt = "csv";
} else {
content = serializeToJson(mode, data, appVersion);
diff --git a/src/hooks/useDataImport.test.ts b/src/hooks/useDataImport.test.ts
index 669df9e..ef97918 100644
--- a/src/hooks/useDataImport.test.ts
+++ b/src/hooks/useDataImport.test.ts
@@ -44,15 +44,42 @@ const TRANSACTION = {
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 {
- const data =
- mode === "categories_only"
- ? { categories: [], suppliers: [], keywords: [] }
- : mode === "transactions_only"
- ? { transactions: [TRANSACTION], import_sources: [], import_config_templates: [] }
- : { categories: [], suppliers: [], keywords: [], transactions: [TRANSACTION], import_sources: [], import_config_templates: [] };
- return serializeToJson(mode, data, "0.17.2");
+ 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 = { ...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. */
@@ -143,6 +170,30 @@ describe("useDataImport — the outcome of the restore reaches the success state
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"));
diff --git a/src/hooks/useDataImport.ts b/src/hooks/useDataImport.ts
index b7249ed..e9caaa4 100644
--- a/src/hooks/useDataImport.ts
+++ b/src/hooks/useDataImport.ts
@@ -210,17 +210,20 @@ export function useDataImport() {
);
const executeImport = useCallback(async () => {
- if (!state.parsedData || !state.importType) return;
+ if (!state.parsedData || !state.importType || !state.summary) return;
dispatch({ type: "IMPORT_START" });
const filename = state.filePath?.split(/[/\\]/).pop() ?? "unknown";
+ // The format the file declares, read at the parse: it says whether the
+ // file carries the budget (#520).
+ const { formatVersion } = state.summary;
try {
let outcome: RestoreOutcome;
switch (state.importType) {
case "categories_only":
- outcome = await importCategoriesOnly(state.parsedData);
+ outcome = await importCategoriesOnly(state.parsedData, formatVersion);
break;
case "transactions_with_categories":
- outcome = await importTransactionsWithCategories(state.parsedData, filename);
+ outcome = await importTransactionsWithCategories(state.parsedData, filename, formatVersion);
break;
case "transactions_only":
outcome = await importTransactionsOnly(state.parsedData, filename);
@@ -230,7 +233,7 @@ export function useDataImport() {
} catch (e) {
dispatch({ type: "IMPORT_ERROR", error: describeError(e) });
}
- }, [state.parsedData, state.importType, state.filePath, describeError]);
+ }, [state.parsedData, state.importType, state.summary, state.filePath, describeError]);
const reset = useCallback(() => dispatch({ type: "RESET" }), []);
diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json
index 89fae93..9d47274 100644
--- a/src/i18n/locales/en.json
+++ b/src/i18n/locales/en.json
@@ -435,7 +435,7 @@
"deleteConfirm": "Are you sure you want to delete this category? Its children will be promoted to top-level.",
"deleteBlocked": "Cannot delete: this category or its children are used by {{count}} transaction(s).",
"reinitialize": "Re-initialize",
- "reinitializeConfirm": "Reset all categories and keywords to their default values? Transaction categories will be unlinked. This cannot be undone.",
+ "reinitializeConfirm": "Reset all categories and keywords to their default values? Transaction categories will be unlinked, and the budget, budget templates, and adjustments will be erased. This cannot be undone.",
"noParent": "No parent (top-level)",
"isInputable": "Allow input",
"isInputableHint": "Uncheck to hide from budget and transaction dropdowns",
@@ -761,9 +761,9 @@
"decrypt": "Decrypt",
"confirmTitle": "Replace Data",
"willDeleteLabel": "The following data will be deleted:",
- "willDeleteCategories": "All categories, suppliers, and keywords",
+ "willDeleteCategories": "All categories, suppliers, and keywords, along with the budget, budget templates, and adjustments",
"willDeleteTransactions": "All transactions and import history",
- "willDeleteAll": "All transactions, categories, suppliers, keywords, and import history",
+ "willDeleteAll": "All transactions, categories, suppliers, keywords, and import history, along with the budget, budget templates, and adjustments",
"willImportLabel": "The following data will be imported:",
"countCategories": "{{count}} category(ies)",
"countSuppliers": "{{count}} supplier(s)",
@@ -771,6 +771,10 @@
"countTransactions": "{{count}} transaction(s)",
"countImportSources": "{{count}} import source(s)",
"countImportTemplates": "{{count}} import template(s)",
+ "countBudgetEntries": "{{count}} budget line(s)",
+ "countBudgetTemplates": "{{count}} budget template(s)",
+ "countAdjustments": "{{count}} adjustment(s)",
+ "legacyBudgetNote": "This backup predates budgets in backups: it holds no budget, budget templates, or adjustments. Current lines whose category comes back are kept; the others are deleted.",
"irreversibleWarning": "This action is irreversible. All existing data of the selected type will be permanently deleted and replaced.",
"typeToConfirm": "Type \"{{word}}\" to confirm:",
"confirmWord": "REPLACE",
@@ -786,7 +790,9 @@
"unsupportedSignConvention": "This file cannot be imported: the source \"{{name}}\" was saved with a sign convention this version does not support ({{value}}). Nothing has been modified.",
"invalidFormatRow": "This file cannot be imported: the import configuration of \"{{name}}\" is incomplete or damaged. Nothing has been modified.",
"orphanSplitLines": "This file cannot be imported: some split lines cannot find their original transaction. Use a JSON export. Nothing has been modified.",
- "danglingCategoryReference": "This file cannot be imported: some categories, keywords, or suppliers refer to a category missing from the file. Nothing has been modified."
+ "danglingCategoryReference": "This file cannot be imported: some categories, keywords, or suppliers refer to a category missing from the file. Nothing has been modified.",
+ "invalidBudgetRows": "This file cannot be imported: some budget, budget template, or adjustment lines are invalid or refer to a category missing from the file. Nothing has been modified.",
+ "newerFormat": "This file comes from a newer version of Simpl'Résultat. Update the app to import it. Nothing has been modified."
}
}
},
@@ -827,6 +833,7 @@
"retry": "Try again",
"restoring": "Restoring your profile — do not close the application...",
"reading": "Reading the backup...",
+ "legacyBudgetNote": "This backup predates budgets in backups: it holds no budget, budget templates, or adjustments. Current lines whose category comes back are kept; the others are deleted.",
"unlinkedTransfersPreview_one": "{{count}} Balance transfer will not find its transaction and will be unlinked.",
"unlinkedTransfersPreview_other": "{{count}} Balance transfers will not find their transaction and will be unlinked.",
"doneTitle": "Backup restored",
diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json
index e132522..f19ee61 100644
--- a/src/i18n/locales/fr.json
+++ b/src/i18n/locales/fr.json
@@ -435,7 +435,7 @@
"deleteConfirm": "Êtes-vous sûr de vouloir supprimer cette catégorie ? Ses sous-catégories seront promues au niveau supérieur.",
"deleteBlocked": "Impossible de supprimer : cette catégorie ou ses sous-catégories sont utilisées par {{count}} transaction(s).",
"reinitialize": "Réinitialiser",
- "reinitializeConfirm": "Réinitialiser toutes les catégories et mots-clés à leurs valeurs par défaut ? Les catégories des transactions seront dissociées. Cette action est irréversible.",
+ "reinitializeConfirm": "Réinitialiser toutes les catégories et mots-clés à leurs valeurs par défaut ? Les catégories des transactions seront dissociées, et le budget, les modèles de budget et les ajustements seront effacés. Cette action est irréversible.",
"noParent": "Aucun parent (niveau supérieur)",
"isInputable": "Autoriser la saisie",
"isInputableHint": "Décocher pour masquer du budget et des listes de catégories",
@@ -761,9 +761,9 @@
"decrypt": "Déchiffrer",
"confirmTitle": "Remplacer les données",
"willDeleteLabel": "Les données suivantes seront supprimées :",
- "willDeleteCategories": "Toutes les catégories, fournisseurs et mots-clés",
+ "willDeleteCategories": "Toutes les catégories, fournisseurs et mots-clés, ainsi que le budget, les modèles de budget et les ajustements",
"willDeleteTransactions": "Toutes les transactions et l'historique d'import",
- "willDeleteAll": "Toutes les transactions, catégories, fournisseurs, mots-clés et l'historique d'import",
+ "willDeleteAll": "Toutes les transactions, catégories, fournisseurs, mots-clés et l'historique d'import, ainsi que le budget, les modèles de budget et les ajustements",
"willImportLabel": "Les données suivantes seront importées :",
"countCategories": "{{count}} catégorie(s)",
"countSuppliers": "{{count}} fournisseur(s)",
@@ -771,6 +771,10 @@
"countTransactions": "{{count}} transaction(s)",
"countImportSources": "{{count}} source(s) d'import",
"countImportTemplates": "{{count}} modèle(s) d'import",
+ "countBudgetEntries": "{{count}} ligne(s) de budget",
+ "countBudgetTemplates": "{{count}} modèle(s) de budget",
+ "countAdjustments": "{{count}} ajustement(s)",
+ "legacyBudgetNote": "Cette sauvegarde date d'avant l'ajout du budget aux sauvegardes : elle ne contient ni budget, ni modèles de budget, ni ajustements. Les lignes actuelles dont la catégorie revient seront gardées, les autres supprimées.",
"irreversibleWarning": "Cette action est irréversible. Toutes les données existantes du type sélectionné seront définitivement supprimées et remplacées.",
"typeToConfirm": "Tapez « {{word}} » pour confirmer :",
"confirmWord": "REMPLACER",
@@ -786,7 +790,9 @@
"unsupportedSignConvention": "Ce fichier ne peut pas être importé : la source « {{name}} » a été enregistrée avec une convention de signe que cette version ne prend pas en charge ({{value}}). Rien n'a été modifié.",
"invalidFormatRow": "Ce fichier ne peut pas être importé : la configuration d'import de « {{name}} » est incomplète ou endommagée. Rien n'a été modifié.",
"orphanSplitLines": "Ce fichier ne peut pas être importé : des lignes de répartition ne retrouvent pas leur transaction d'origine. Utilisez un export JSON. Rien n'a été modifié.",
- "danglingCategoryReference": "Ce fichier ne peut pas être importé : des catégories, mots-clés ou fournisseurs renvoient à une catégorie absente du fichier. Rien n'a été modifié."
+ "danglingCategoryReference": "Ce fichier ne peut pas être importé : des catégories, mots-clés ou fournisseurs renvoient à une catégorie absente du fichier. Rien n'a été modifié.",
+ "invalidBudgetRows": "Ce fichier ne peut pas être importé : des lignes de budget, de modèle de budget ou d'ajustement sont invalides ou visent une catégorie absente du fichier. Rien n'a été modifié.",
+ "newerFormat": "Ce fichier vient d'une version plus récente de Simpl'Résultat. Mettez l'application à jour pour l'importer. Rien n'a été modifié."
}
}
},
@@ -827,6 +833,7 @@
"retry": "Réessayer",
"restoring": "Rétablissement en cours — ne fermez pas l'application...",
"reading": "Lecture de la sauvegarde en cours...",
+ "legacyBudgetNote": "Cette sauvegarde date d'avant l'ajout du budget aux sauvegardes : elle ne contient ni budget, ni modèles de budget, ni ajustements. Les lignes actuelles dont la catégorie revient seront gardées, les autres supprimées.",
"unlinkedTransfersPreview_one": "{{count}} transfert du Bilan ne retrouvera pas sa transaction et sera délié.",
"unlinkedTransfersPreview_other": "{{count}} transferts du Bilan ne retrouveront pas leur transaction et seront déliés.",
"doneTitle": "Sauvegarde rétablie",
diff --git a/src/services/categoryBackupService.test.ts b/src/services/categoryBackupService.test.ts
index e5e6fb7..a53aae9 100644
--- a/src/services/categoryBackupService.test.ts
+++ b/src/services/categoryBackupService.test.ts
@@ -12,22 +12,33 @@ vi.mock("@tauri-apps/api/app", () => ({
getVersion: vi.fn(async () => "0.8.3-test"),
}));
+// The arrays of the backup come from `collectExportData` (#520), whose reads
+// of the profile are faked here; serialize and parse stay real.
+const { EXPORTED } = vi.hoisted(() => ({
+ EXPORTED: {
+ categories: [],
+ suppliers: [],
+ keywords: [],
+ transactions: [],
+ import_sources: [],
+ import_config_templates: [],
+ budget_entries: [],
+ budget_templates: [],
+ adjustments: [],
+ } as Record,
+}));
vi.mock("./dataExportService", async () => {
const actual = await vi.importActual(
"./dataExportService",
);
return {
...actual,
- getExportCategories: vi.fn(async () => []),
- getExportSuppliers: vi.fn(async () => []),
- getExportKeywords: vi.fn(async () => []),
- getExportTransactions: vi.fn(async () => []),
- getExportImportSources: vi.fn(async () => []),
- getExportImportTemplates: vi.fn(async () => []),
+ collectExportData: vi.fn(async () => EXPORTED),
};
});
import { invoke } from "@tauri-apps/api/core";
+import { collectExportData, SREF_FORMAT_VERSION } from "./dataExportService";
import {
createPreMigrationBackup,
sanitizeProfileName,
@@ -177,6 +188,44 @@ describe("createPreMigrationBackup — happy path (no PIN)", () => {
expect(result.verifiedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
+ it("writes what an export « Transactions avec catégories » carries, the budget among it, at format 3 (#520)", async () => {
+ const budget = {
+ categories: [{ id: 1111, name: "Épicerie", type: "expense", is_active: 1, is_inputable: 1, sort_order: 1 }],
+ budget_entries: [{ category_id: 1111, year: 2026, month: 10, amount: 450, notes: null }],
+ budget_templates: [{ name: "Mois type", description: null, entries: [{ category_id: 1111, amount: 400 }] }],
+ adjustments: [
+ {
+ name: "Rattrapage",
+ description: null,
+ date: "2026-10-15",
+ is_recurring: 0,
+ recurrence_rule: null,
+ entries: [{ category_id: 1111, amount: 15, description: null }],
+ },
+ ],
+ };
+ vi.mocked(collectExportData).mockResolvedValueOnce({ ...EXPORTED, ...budget } as never);
+ let written = "";
+ mockInvoke.mockImplementation(async (cmd, args) => {
+ if (cmd === "ensure_backup_dir") return "/tmp/sr-backups";
+ if (cmd === "write_export_file") {
+ written = (args as { content: string }).content;
+ return undefined;
+ }
+ if (cmd === "read_import_file") return written;
+ if (cmd === "get_file_size") return written.length;
+ throw new Error(`unexpected invoke: ${cmd}`);
+ });
+
+ await createPreMigrationBackup({ profile: plainProfile });
+
+ expect(collectExportData).toHaveBeenLastCalledWith("transactions_with_categories");
+ const envelope = JSON.parse(written);
+ expect(envelope.export_type).toBe("transactions_with_categories");
+ expect(envelope.format_version).toBe(SREF_FORMAT_VERSION);
+ expect(envelope.data).toEqual({ ...EXPORTED, ...budget });
+ });
+
it("calls write_export_file with password=null for an unprotected profile", async () => {
setupHappyPathInvokes(validEnvelope());
// Override write_export_file so we can inspect args.
diff --git a/src/services/categoryBackupService.ts b/src/services/categoryBackupService.ts
index a487b7e..a3b7afd 100644
--- a/src/services/categoryBackupService.ts
+++ b/src/services/categoryBackupService.ts
@@ -2,12 +2,7 @@ import { invoke } from "@tauri-apps/api/core";
import { getVersion } from "@tauri-apps/api/app";
import type { Profile } from "./profileService";
import {
- getExportCategories,
- getExportSuppliers,
- getExportKeywords,
- getExportTransactions,
- getExportImportSources,
- getExportImportTemplates,
+ collectExportData,
serializeToJson,
parseImportedJson,
type ExportEnvelope,
@@ -224,8 +219,10 @@ async function getFileSize(filePath: string): Promise {
* to be used as a safety net before the v2 -> v1 categories migration.
*
* Flow:
- * 1. Gather categories, suppliers, keywords, and transactions via the
- * existing dataExportService helpers.
+ * 1. Gather what an export « Transactions avec catégories » carries, through
+ * `collectExportData`: categories, suppliers, keywords, transactions,
+ * import configurations, and the budget, its templates and the
+ * adjustments (#520).
* 2. Serialize to JSON using the `transactions_with_categories` envelope.
* 3. Resolve `~/Documents/Simpl-Resultat/backups/` (create if missing).
* 4. Write the file via `write_export_file` (encrypted when a PIN password
@@ -255,39 +252,15 @@ export async function createPreMigrationBackup(
);
}
- // 1. Gather data — same mode as "transactions_with_categories" export.
- // Import sources and templates are part of that mode since #331: this
- // backup is a safety net, and one that came back without a single import
- // configuration would be a poor one.
+ // 1. Gather data — the very arrays of a "transactions_with_categories"
+ // export. Import sources and templates are part of that mode since #331,
+ // the budget since #520: this backup is a safety net, and one that came
+ // back without a single import configuration, or without the budget of
+ // the categories it replaces, would be a poor one.
const appVersion = await getVersion();
- const [
- categories,
- suppliers,
- keywords,
- transactions,
- import_sources,
- import_config_templates,
- ] = await Promise.all([
- getExportCategories(),
- getExportSuppliers(),
- getExportKeywords(),
- getExportTransactions(),
- getExportImportSources(),
- getExportImportTemplates(),
- ]);
+ const data = await collectExportData("transactions_with_categories");
- const content = serializeToJson(
- "transactions_with_categories",
- {
- categories,
- suppliers,
- keywords,
- transactions,
- import_sources,
- import_config_templates,
- },
- appVersion,
- );
+ const content = serializeToJson("transactions_with_categories", data, appVersion);
// 2. Compute the expected checksum before writing.
const expectedChecksum = await sha256Hex(content);
diff --git a/src/services/categoryRestoreService.test.ts b/src/services/categoryRestoreService.test.ts
index 66fff28..bb07282 100644
--- a/src/services/categoryRestoreService.test.ts
+++ b/src/services/categoryRestoreService.test.ts
@@ -27,7 +27,7 @@ import {
shouldShowBanner,
type RestorableMigrationJournal,
} from "./categoryRestoreService";
-import { serializeToJson, SrefValidationError } from "./dataExportService";
+import { serializeToJson, SREF_FORMAT_VERSION, SrefValidationError } from "./dataExportService";
const DAY = 24 * 60 * 60 * 1000;
@@ -133,14 +133,27 @@ describe("shouldShowBanner", () => {
const ORPHAN = "settings.dataManagement.import.errors.orphanSplitLines";
const PATH = "/tmp/profile_avant-migration.sref";
+/** The three budget arrays of a format-3 backup whose profile had no budget (#520). */
+const NO_BUDGET = { budget_entries: [], budget_templates: [], adjustments: [] };
+
/** A backup of the categories migration, its transactions as given. */
const backup = (transactions: unknown[]) =>
serializeToJson(
"transactions_with_categories",
- { categories: [], suppliers: [], keywords: [], transactions: transactions as never },
+ { categories: [], suppliers: [], keywords: [], transactions: transactions as never, ...NO_BUDGET },
"0.17.2",
);
+/** The same backup as an earlier version wrote it: `format_version` as given, absent when undefined, no budget. */
+const olderBackup = (formatVersion: number | undefined) =>
+ JSON.stringify({
+ export_type: "transactions_with_categories",
+ app_version: "0.17.2",
+ ...(formatVersion === undefined ? {} : { format_version: formatVersion }),
+ exported_at: "2026-10-18T12:00:00.000Z",
+ data: { categories: [], suppliers: [], keywords: [], transactions: [] },
+ });
+
/** One transaction of a backup. */
const transaction = (id: number, parent: number | null = null) => ({
id,
@@ -215,7 +228,7 @@ describe("readBackup reads the backup and writes nothing (#521)", () => {
});
it("refuses a file that is not a full backup, before counting anything", async () => {
- readingFile(serializeToJson("categories_only", { categories: [], suppliers: [], keywords: [] }, "0.17.2"));
+ readingFile(serializeToJson("categories_only", { categories: [], suppliers: [], keywords: [], ...NO_BUDGET }, "0.17.2"));
const error = await failureOf(() => readBackup(PATH, null));
expect(error).toBeInstanceOf(RestoreError);
expect((error as RestoreError).code).toBe("wrong_envelope_type");
@@ -245,13 +258,29 @@ describe("applyBackup restores the backup read and hands back what the restore d
const result = await applyBackup(envelope, "profile_avant-migration.sref");
- expect(importTransactionsWithCategories).toHaveBeenCalledWith(envelope.data, "profile_avant-migration.sref");
+ expect(importTransactionsWithCategories).toHaveBeenCalledWith(
+ envelope.data,
+ "profile_avant-migration.sref",
+ SREF_FORMAT_VERSION,
+ );
expect(result.outcome).toEqual({ unlinkedTransfers: 3, uncategorizedTransactions: 1 });
expect(result.revertedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
expect(preferences.get("categories_schema_version")).toBe("v2");
expect(JSON.parse(preferences.get("last_categories_migration")!).reverted_at).toBe(result.revertedAt);
});
+ it.each([
+ [2, 2],
+ [undefined, 1],
+ ])("a backup of format %s restores at its own format (%i): the profile's lines whose category comes back are kept (#520)", async (declared, expected) => {
+ const envelope = await envelopeOf(olderBackup(declared));
+ importTransactionsWithCategories.mockResolvedValue({ unlinkedTransfers: 0, uncategorizedTransactions: 0 });
+
+ await applyBackup(envelope, "backup.sref");
+
+ expect(importTransactionsWithCategories).toHaveBeenCalledWith(envelope.data, "backup.sref", expected);
+ });
+
it("a failed restore marks nothing", async () => {
const envelope = await envelopeOf(backup([]));
importTransactionsWithCategories.mockRejectedValue(new Error("FOREIGN KEY constraint failed"));
diff --git a/src/services/categoryRestoreService.ts b/src/services/categoryRestoreService.ts
index d3eb070..0d55dad 100644
--- a/src/services/categoryRestoreService.ts
+++ b/src/services/categoryRestoreService.ts
@@ -1,5 +1,6 @@
import { invoke } from "@tauri-apps/api/core";
import {
+ LEGACY_SREF_FORMAT_VERSION,
parseImportedJson,
SrefValidationError,
type ExportEnvelope,
@@ -311,10 +312,16 @@ export async function applyBackup(
): Promise {
// 1. Perform the destructive re-import. importTransactionsWithCategories
// wipes transactions/imported_files/import_sources/keywords/suppliers/
- // categories and re-inserts them from the envelope.
+ // categories and re-inserts them from the envelope, with the budget of a
+ // backup of format 3, or the profile's lines whose category comes back
+ // from an older one (#520).
let outcome: RestoreOutcome;
try {
- outcome = await importTransactionsWithCategories(envelope.data, filename);
+ outcome = await importTransactionsWithCategories(
+ envelope.data,
+ filename,
+ envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION,
+ );
} catch (e) {
// Same for a refusal raised at the head of the restore itself.
if (e instanceof SrefValidationError) throw e;
diff --git a/src/services/categoryService.test.ts b/src/services/categoryService.test.ts
index b240cb0..e39829d 100644
--- a/src/services/categoryService.test.ts
+++ b/src/services/categoryService.test.ts
@@ -605,3 +605,24 @@ describe("getCategoryDepth (#393)", () => {
expect(db.rows()).toHaveLength(2);
});
});
+
+describe("« Réinitialiser » says what it erases (#520)", () => {
+ // `reinitializeCategories` deletes every category, and with them, through
+ // their foreign keys, the budget, the template lines and the adjustment
+ // lines: its confirmation says so, in both languages.
+ it("names the budget, the budget templates and the adjustments, in French and in English", () => {
+ expect(fr.categories.reinitializeConfirm).toMatch(
+ /le budget, les modèles de budget et les ajustements seront effacés/,
+ );
+ expect(en.categories.reinitializeConfirm).toMatch(
+ /the budget, budget templates, and adjustments will be erased/,
+ );
+ });
+
+ it("still says that the categories of the transactions are unlinked, and that it cannot be undone", () => {
+ expect(fr.categories.reinitializeConfirm).toMatch(/Les catégories des transactions seront dissociées/);
+ expect(fr.categories.reinitializeConfirm).toMatch(/Cette action est irréversible\.$/);
+ expect(en.categories.reinitializeConfirm).toMatch(/Transaction categories will be unlinked/);
+ expect(en.categories.reinitializeConfirm).toMatch(/This cannot be undone\.$/);
+ });
+});
diff --git a/src/services/dataExportService.test.ts b/src/services/dataExportService.test.ts
index fa8455e..61ceb53 100644
--- a/src/services/dataExportService.test.ts
+++ b/src/services/dataExportService.test.ts
@@ -20,8 +20,10 @@
* models `UNIQUE(name)` and BEGIN/ROLLBACK, because those are the failures the
* transaction exists to survive, and, since #521, the second pass of the
* categories (`UPDATE categories SET parent_id`) and the Bilan transfers read
- * with their transaction. It has no foreign key: the restores under foreign
- * keys run on real SQLite in `src/__integration__/restore.test.ts`.
+ * with their transaction; since #520, the budget tables, the template lines
+ * read with their template's name, and `collectExportData`. It has no foreign
+ * key: the restores under foreign keys run on real SQLite in
+ * `src/__integration__/restore.test.ts`.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
@@ -36,22 +38,31 @@ vi.mock("./db", () => {
import { getDb, withTransaction } from "./db";
import {
+ collectExportData,
getExportImportSources,
getExportImportTemplates,
parseImportedCsv,
parseImportedJson,
serializeToJson,
serializeTransactionsToCsv,
+ validateImportedBudget,
validateImportedCategoryReferences,
validateImportedFormatRows,
+ validateImportedFormatVersion,
validateImportedTransactionIds,
LEGACY_SREF_FORMAT_VERSION,
+ MAX_BUDGET_YEAR,
MAX_TRANSACTION_ID,
+ MIN_BUDGET_YEAR,
SREF_FORMAT_VERSION,
SrefValidationError,
+ type ExportAdjustment,
+ type ExportBudgetEntry,
+ type ExportBudgetTemplate,
type ExportEnvelope,
type ExportImportSource,
type ExportImportTemplate,
+ type ExportMode,
type ExportTransaction,
} from "./dataExportService";
import {
@@ -83,6 +94,11 @@ function makeFakeDb(shouldFail?: (sql: string, params: unknown[]) => boolean) {
import_sources: [],
import_config_templates: [],
balance_account_transfers: [],
+ budget_entries: [],
+ budget_templates: [],
+ budget_template_entries: [],
+ adjustments: [],
+ adjustment_entries: [],
};
const log: string[] = [];
let snapshot: Record | null = null;
@@ -189,6 +205,13 @@ function makeFakeDb(shouldFail?: (sql: string, params: unknown[]) => boolean) {
};
});
}
+ // ...and each template line with its template's name (#520).
+ if (table === "budget_template_entries" && /JOIN budget_templates/.test(sql)) {
+ return rows.flatMap((r) => {
+ const template = tables.budget_templates.find((t) => t.id === r.template_id);
+ return template ? [{ ...r, template_name: template.name }] : [];
+ });
+ }
return [...rows];
}),
};
@@ -237,6 +260,9 @@ const SOURCE: ExportImportSource = {
sign_convention: "negative_expense",
};
+/** The three budget arrays of a format-3 file whose profile had no budget (#520). */
+const NO_BUDGET = { budget_entries: [], budget_templates: [], adjustments: [] };
+
function envelopeData(
overrides: Partial = {}
): ExportEnvelope["data"] {
@@ -247,6 +273,7 @@ function envelopeData(
transactions: [],
import_sources: [SOURCE],
import_config_templates: [TEMPLATE],
+ ...NO_BUDGET,
...overrides,
};
}
@@ -379,8 +406,8 @@ describe("a backup written before #331 still imports", () => {
it("restores exactly as it did before — wipe, then one host source", async () => {
db.seed("import_sources", [{ name: "Old source", column_mapping: "{}" }]);
- const { envelope } = parseImportedJson(LEGACY_BACKUP);
- await importTransactionsWithCategories(envelope.data, "backup.json");
+ const { envelope, summary } = parseImportedJson(LEGACY_BACKUP);
+ await importTransactionsWithCategories(envelope.data, "backup.json", summary.formatVersion);
expect(db.tables.import_sources).toHaveLength(1);
expect(db.tables.import_sources[0].name).toBe("Data Import");
@@ -460,7 +487,7 @@ describe("the import boundary refuses a format it cannot store", () => {
envelopeData({
import_sources: [{ ...SOURCE, sign_convention: "inverted" as never }],
}),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
)
).rejects.toBeInstanceOf(SrefValidationError);
expect(db.tables.categories).toHaveLength(1);
@@ -474,7 +501,7 @@ describe("the import boundary refuses a format it cannot store", () => {
describe("restoring brings the configurations back (#331)", () => {
it("restores a source field by field, template resolved to the new id", async () => {
- await importTransactionsWithCategories(envelopeData(), "backup.json");
+ await importTransactionsWithCategories(envelopeData(), "backup.json", SREF_FORMAT_VERSION);
expect(db.tables.import_config_templates).toHaveLength(1);
const template = db.tables.import_config_templates[0];
@@ -489,7 +516,7 @@ describe("restoring brings the configurations back (#331)", () => {
});
it("writes the templates BEFORE the sources — template_id is a foreign key", async () => {
- await importTransactionsWithCategories(envelopeData(), "backup.json");
+ await importTransactionsWithCategories(envelopeData(), "backup.json", SREF_FORMAT_VERSION);
const inserts = db.log.filter((l) => l.startsWith("INSERT INTO"));
expect(inserts.indexOf("INSERT INTO import_config_templates")).toBeLessThan(
inserts.indexOf("INSERT INTO import_sources")
@@ -504,7 +531,7 @@ describe("restoring brings the configurations back (#331)", () => {
]);
const existingId = db.tables.import_config_templates[0].id;
- await importTransactionsWithCategories(envelopeData(), "backup.json");
+ await importTransactionsWithCategories(envelopeData(), "backup.json", SREF_FORMAT_VERSION);
expect(db.tables.import_config_templates).toHaveLength(1);
expect(db.tables.import_config_templates[0].id).toBe(existingId);
@@ -518,13 +545,13 @@ describe("restoring brings the configurations back (#331)", () => {
import_sources: [{ ...SOURCE, template_name: "Gone" }],
import_config_templates: [],
}),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
expect(db.tables.import_sources[0].template_id).toBeNull();
});
it("creates NO host source when the file carries no transactions", async () => {
- await importTransactionsWithCategories(envelopeData(), "backup.json");
+ await importTransactionsWithCategories(envelopeData(), "backup.json", SREF_FORMAT_VERSION);
expect(db.tables.import_sources.map((s) => s.name)).toEqual([SOURCE.name]);
expect(db.tables.imported_files).toHaveLength(0);
});
@@ -532,7 +559,7 @@ describe("restoring brings the configurations back (#331)", () => {
it("creates the host source only to carry transactions, with a readable mapping", async () => {
await importTransactionsWithCategories(
envelopeData({ transactions: [transactionFixture(1), transactionFixture(2)] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
const host = db.tables.import_sources.find((s) => s.name === "Data Import")!;
@@ -557,7 +584,7 @@ describe("restoring brings the configurations back (#331)", () => {
import_sources: [{ ...SOURCE, name: "Data Import" }],
transactions: [transactionFixture(1)],
}),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
expect(db.tables.import_sources).toHaveLength(1);
// The restored configuration wins; it is not overwritten by the host stub.
@@ -573,7 +600,7 @@ describe("restoring brings the configurations back (#331)", () => {
it("leaves import_sources alone in categories_only mode", async () => {
db.seed("import_sources", [{ name: "Kept", column_mapping: "{}" }]);
- await importCategoriesOnly({ categories: [], suppliers: [], keywords: [] });
+ await importCategoriesOnly({ categories: [], suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION);
expect(db.tables.import_sources.map((s) => s.name)).toEqual(["Kept"]);
});
});
@@ -616,7 +643,7 @@ describe("a restore that fails at row N leaves the profile untouched", () => {
categories: CATEGORY_FIXTURES,
transactions: [transactionFixture(1)],
}),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
)
).rejects.toThrow("boom");
@@ -632,7 +659,7 @@ describe("a restore that fails at row N leaves the profile untouched", () => {
await expect(
importTransactionsWithCategories(
envelopeData({ import_sources: [SOURCE, { ...SOURCE }] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
)
).rejects.toThrow(/UNIQUE constraint failed/);
expect(db.tables.categories.map((c) => c.name)).toEqual(["Existing"]);
@@ -650,13 +677,17 @@ describe("a restore that fails at row N leaves the profile untouched", () => {
db.seed("categories", [{ id: 900, name: "Existing" }]);
await expect(
- importCategoriesOnly({
- categories: CATEGORY_FIXTURES,
- suppliers: [],
- keywords: [
- { id: 1, keyword: "epicerie", category_id: 1, priority: 1, is_active: 1 } as never,
- ],
- })
+ importCategoriesOnly(
+ {
+ categories: CATEGORY_FIXTURES,
+ suppliers: [],
+ keywords: [
+ { id: 1, keyword: "epicerie", category_id: 1, priority: 1, is_active: 1 } as never,
+ ],
+ ...NO_BUDGET,
+ },
+ SREF_FORMAT_VERSION
+ )
).rejects.toThrow("boom");
expect(db.log).toContain("ROLLBACK");
@@ -818,7 +849,7 @@ describe("a restore writes the manual flag as an integer (#390)", () => {
it("restores the 'true' of an older JSON backup as 1", async () => {
await importTransactionsWithCategories(
envelopeData({ transactions: [fromTheBug, transactionFixture(2)] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
expect(db.tables.transactions.map((t) => t.is_manually_categorized)).toEqual([1, 0]);
});
@@ -860,7 +891,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
it("transactions with categories: once, after the COMMIT", async () => {
await importTransactionsWithCategories(
envelopeData({ transactions: [transactionFixture(1)] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
expect(seen).toHaveLength(1);
expect(seen[0][seen[0].length - 1]).toBe("COMMIT");
@@ -873,7 +904,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
});
it("categories only: once, after the COMMIT", async () => {
- await importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [] });
+ await importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION);
expect(seen).toHaveLength(1);
expect(seen[0][seen[0].length - 1]).toBe("COMMIT");
});
@@ -886,7 +917,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
() =>
importTransactionsWithCategories(
envelopeData({ transactions: [transactionFixture(1)] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
),
],
[
@@ -895,7 +926,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
],
[
"categories only",
- () => importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [] }),
+ () => importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION),
],
] as const)("%s: notifies once the DB lock is released", async (_name, restore) => {
let inLock = false;
@@ -948,7 +979,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
await expect(
importTransactionsWithCategories(
envelopeData({ import_sources: [{ ...SOURCE, amount_mode: "nonsense" as never }] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
)
).rejects.toThrow();
expect(db.log).toEqual([]);
@@ -1070,7 +1101,7 @@ describe("the rows keep their ids, and a split line its parent (#518)", () => {
it.each([
[
"transactions with categories",
- (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json"),
+ (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION),
],
["transactions only", (data: ExportEnvelope["data"]) => importTransactionsOnly(data, "backup.json")],
] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => {
@@ -1171,9 +1202,9 @@ describe("the import boundary refuses a category reference the file cannot satis
it.each([
[
"transactions with categories",
- (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json"),
+ (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION),
],
- ["categories only", (data: ExportEnvelope["data"]) => importCategoriesOnly(data)],
+ ["categories only", (data: ExportEnvelope["data"]) => importCategoriesOnly(data, SREF_FORMAT_VERSION)],
] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => {
db.seed("categories", [{ name: "Existing" }]);
await expect(
@@ -1200,9 +1231,9 @@ describe("the categories go in without their parents, set in a second pass (#521
it.each([
[
"transactions with categories",
- () => importTransactionsWithCategories(envelopeData({ categories: CATEGORIES }), "backup.json"),
+ () => importTransactionsWithCategories(envelopeData({ categories: CATEGORIES }), "backup.json", SREF_FORMAT_VERSION),
],
- ["categories only", () => importCategoriesOnly({ categories: CATEGORIES, suppliers: [], keywords: [] })],
+ ["categories only", () => importCategoriesOnly({ categories: CATEGORIES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION)],
] as const)("%s: every insert without a parent, then each parent; every parent_id as in the file", async (_name, restore) => {
await restore();
@@ -1239,14 +1270,14 @@ describe("a restore hands back its outcome (#521)", () => {
});
it("categories only: zeros, nothing deleted that a transfer holds", async () => {
- await expect(importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [] })).resolves.toEqual({
+ await expect(importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION)).resolves.toEqual({
unlinkedTransfers: 0,
uncategorizedTransactions: 0,
});
});
it.each([
- ["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json")],
+ ["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION)],
["transactions only", (data: ExportEnvelope["data"]) => importTransactionsOnly(data, "backup.json")],
] as const)("%s: the transfers are read and removed before the transactions are deleted", async (_name, restore) => {
await restore(envelopeData({ transactions: [transactionFixture(1)] }));
@@ -1256,7 +1287,7 @@ describe("a restore hands back its outcome (#521)", () => {
});
it.each([
- ["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json")],
+ ["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION)],
["transactions only", (data: ExportEnvelope["data"]) => importTransactionsOnly(data, "backup.json")],
] as const)("%s: a transfer whose transaction comes back as it was is put back as it was, the other unlinked", async (_name, restore) => {
// The profile: two transactions, each linked to « CELI » (account 2).
@@ -1294,3 +1325,335 @@ describe("a restore hands back its outcome (#521)", () => {
expect(outcome).toEqual({ unlinkedTransfers: 0, uncategorizedTransactions: 1 });
});
});
+
+// ---------------------------------------------------------------------------
+// 12. The budget travels with the categories, from format 3 on (#520)
+// ---------------------------------------------------------------------------
+
+describe("collectExportData gathers the arrays of each mode (#520)", () => {
+ beforeEach(() => {
+ db.seed("categories", [{ id: 1, name: "Épicerie" }]);
+ db.seed("transactions", [transactionFixture(10)]);
+ db.seed("import_config_templates", [{ ...TEMPLATE }]);
+ db.seed("budget_entries", [{ category_id: 1, year: 2026, month: 10, amount: 450, notes: "Octobre" }]);
+ db.seed("budget_templates", [
+ { name: "Mois type", description: "Le mois" },
+ { name: "Vide", description: null },
+ ]);
+ const [monthly] = db.tables.budget_templates;
+ db.seed("budget_template_entries", [{ template_id: monthly.id, category_id: 1, amount: 400 }]);
+ db.seed("adjustments", [
+ { name: "Rattrapage", description: null, date: "2026-10-15", is_recurring: 1, recurrence_rule: null },
+ ]);
+ const [adjustment] = db.tables.adjustments;
+ db.seed("adjustment_entries", [{ adjustment_id: adjustment.id, category_id: 1, amount: 15, description: "Crédit" }]);
+ });
+
+ it.each<[ExportMode, string[]]>([
+ [
+ "transactions_with_categories",
+ [
+ "categories",
+ "suppliers",
+ "keywords",
+ "transactions",
+ "import_sources",
+ "import_config_templates",
+ "budget_entries",
+ "budget_templates",
+ "adjustments",
+ ],
+ ],
+ ["categories_only", ["categories", "suppliers", "keywords", "budget_entries", "budget_templates", "adjustments"]],
+ ["transactions_only", ["transactions", "import_sources", "import_config_templates"]],
+ ])("%s carries %j", async (mode, arrays) => {
+ expect(Object.keys(await collectExportData(mode))).toEqual(arrays);
+ });
+
+ it("carries each budget line by its category and month, each template by its name with its lines, each adjustment with its lines", async () => {
+ const data = await collectExportData("categories_only");
+ expect(data.budget_entries).toEqual([{ category_id: 1, year: 2026, month: 10, amount: 450, notes: "Octobre" }]);
+ expect(data.budget_templates).toEqual([
+ { name: "Mois type", description: "Le mois", entries: [{ category_id: 1, amount: 400 }] },
+ { name: "Vide", description: null, entries: [] },
+ ]);
+ expect(data.adjustments).toEqual([
+ {
+ name: "Rattrapage",
+ description: null,
+ date: "2026-10-15",
+ is_recurring: 1,
+ recurrence_rule: null,
+ entries: [{ category_id: 1, amount: 15, description: "Crédit" }],
+ },
+ ]);
+ });
+});
+
+describe("the format of a file is checked before anything is deleted (#520)", () => {
+ const NEWER = "settings.dataManagement.import.errors.newerFormat";
+
+ it("accepts every format this build reads", () => {
+ for (const version of [1, 2, SREF_FORMAT_VERSION]) {
+ expect(() => validateImportedFormatVersion(version), String(version)).not.toThrow();
+ }
+ });
+
+ it("refuses a format newer than this build with its own message", () => {
+ for (const version of [SREF_FORMAT_VERSION + 1, 99]) {
+ const error = (() => {
+ try {
+ validateImportedFormatVersion(version);
+ } catch (e) {
+ return e;
+ }
+ return null;
+ })();
+ expect(error, String(version)).toBeInstanceOf(SrefValidationError);
+ expect((error as SrefValidationError).i18nKey).toBe(NEWER);
+ }
+ });
+
+ it.each([0, -1, 2.5, "3", null, Number.NaN, Number.POSITIVE_INFINITY])(
+ "refuses a format_version of %s as a malformed file",
+ (version) => {
+ expect(() => validateImportedFormatVersion(version)).toThrow("Invalid export file format");
+ }
+ );
+
+ it("refuses a newer file at PARSE time, before its mode is even read", () => {
+ const json = JSON.stringify({
+ export_type: "budget_only",
+ app_version: "9.0.0",
+ format_version: SREF_FORMAT_VERSION + 1,
+ exported_at: "2027-01-01T00:00:00Z",
+ data: {},
+ });
+ expect(() => parseImportedJson(json)).toThrow(SrefValidationError);
+ });
+
+ it("refuses a malformed format_version at PARSE time", () => {
+ const json = JSON.stringify({ ...JSON.parse(serializeToJson("transactions_only", envelopeData(), "0.17.2")), format_version: 2.5 });
+ expect(() => parseImportedJson(json)).toThrow("Invalid export file format");
+ });
+
+ it("reads a file without format_version as format 1, and a file of this build at its format", () => {
+ expect(parseImportedJson(LEGACY_BACKUP).summary.formatVersion).toBe(LEGACY_SREF_FORMAT_VERSION);
+ expect(
+ parseImportedJson(serializeToJson("transactions_with_categories", envelopeData(), "0.17.2")).summary.formatVersion
+ ).toBe(3);
+ });
+
+ it.each([
+ [
+ "transactions with categories",
+ (data: ExportEnvelope["data"], version: number) => importTransactionsWithCategories(data, "backup.json", version),
+ ],
+ ["categories only", (data: ExportEnvelope["data"], version: number) => importCategoriesOnly(data, version)],
+ ] as const)("%s: a newer format refused again at the restore, before a single DELETE", async (_name, restore) => {
+ db.seed("categories", [{ name: "Existing" }]);
+ await expect(restore(envelopeData(), SREF_FORMAT_VERSION + 1)).rejects.toBeInstanceOf(SrefValidationError);
+ await expect(restore(envelopeData(), 0)).rejects.toThrow("Invalid export file format");
+ expect(db.log).toEqual([]);
+ expect(db.tables.categories.map((c) => c.name)).toEqual(["Existing"]);
+ });
+});
+
+describe("the import boundary refuses a budget the restore could not write back (#520)", () => {
+ const INVALID = "settings.dataManagement.import.errors.invalidBudgetRows";
+
+ const category = (id: number) => ({ ...CATEGORY_FIXTURES[0], id, name: `Cat ${id}` }) as unknown as Category;
+ const entry = (overrides: Partial = {}): ExportBudgetEntry => ({
+ category_id: 1,
+ year: 2026,
+ month: 10,
+ amount: 450,
+ notes: null,
+ ...overrides,
+ });
+ const template = (overrides: Partial = {}): ExportBudgetTemplate => ({
+ name: "Mois type",
+ description: null,
+ entries: [{ category_id: 1, amount: 400 }],
+ ...overrides,
+ });
+ const adjustment = (overrides: Partial = {}): ExportAdjustment => ({
+ name: "Rattrapage",
+ description: null,
+ date: "2026-10-15",
+ is_recurring: 0,
+ recurrence_rule: null,
+ entries: [{ category_id: 2, amount: -30, description: null }],
+ ...overrides,
+ });
+
+ /** A format-3 file of two categories, its budget as given. */
+ const file = (overrides: Partial = {}): ExportEnvelope["data"] => ({
+ categories: [category(1), category(2)],
+ budget_entries: [entry(), entry({ month: 11 })],
+ budget_templates: [template()],
+ adjustments: [adjustment()],
+ ...overrides,
+ });
+
+ /** The refusal `run` throws; fails when it throws nothing. */
+ function refusalOf(run: () => unknown): SrefValidationError {
+ try {
+ run();
+ } catch (e) {
+ expect(e).toBeInstanceOf(SrefValidationError);
+ return e as SrefValidationError;
+ }
+ return expect.unreachable("should have been refused");
+ }
+
+ it("accepts a file whose every line it can write back, the bounds included", () => {
+ expect(() => validateImportedBudget(file(), 3)).not.toThrow();
+ expect(() =>
+ validateImportedBudget(
+ file({
+ budget_entries: [
+ entry({ year: MIN_BUDGET_YEAR, month: 1 }),
+ entry({ year: MAX_BUDGET_YEAR, month: 12 }),
+ // The same month on another category, the same category in another month.
+ entry({ category_id: 2 }),
+ entry({ year: 2027 }),
+ ],
+ budget_templates: [template(), template({ name: "Autre", entries: [] })],
+ adjustments: [adjustment(), adjustment({ entries: [] })],
+ }),
+ 3
+ )
+ ).not.toThrow();
+ // Empty arrays: a profile without a budget.
+ expect(() => validateImportedBudget(file({ budget_entries: [], budget_templates: [], adjustments: [] }), 3)).not.toThrow();
+ });
+
+ it.each<[string, Partial]>([
+ ["no budget_entries", { budget_entries: undefined }],
+ ["no budget_templates", { budget_templates: undefined }],
+ ["no adjustments", { adjustments: undefined }],
+ ["budget_entries that is not an array", { budget_entries: {} as never }],
+ ["a budget line on a category missing from the file", { budget_entries: [entry({ category_id: 9 })] }],
+ ["a budget line on a category given as text", { budget_entries: [entry({ category_id: "1" as never })] }],
+ ["a budget amount that is not a number", { budget_entries: [entry({ amount: "450" as never })] }],
+ ["a budget amount that is not finite", { budget_entries: [entry({ amount: Number.NaN })] }],
+ ["an infinite budget amount", { budget_entries: [entry({ amount: Number.POSITIVE_INFINITY })] }],
+ ["a year before 1900", { budget_entries: [entry({ year: MIN_BUDGET_YEAR - 1 })] }],
+ ["a year after 2200", { budget_entries: [entry({ year: MAX_BUDGET_YEAR + 1 })] }],
+ ["a year that is not an integer", { budget_entries: [entry({ year: 2026.5 })] }],
+ ["month 0", { budget_entries: [entry({ month: 0 })] }],
+ ["month 13", { budget_entries: [entry({ month: 13 })] }],
+ ["a month that is not an integer", { budget_entries: [entry({ month: 1.5 })] }],
+ ["two budget lines on the same category and month", { budget_entries: [entry(), entry({ amount: 1 })] }],
+ ["a template without a name", { budget_templates: [template({ name: undefined as never })] }],
+ ["two templates of the same name", { budget_templates: [template(), template({ entries: [] })] }],
+ ["a template whose lines are not an array", { budget_templates: [template({ entries: undefined as never })] }],
+ ["a template line on a category missing from the file", { budget_templates: [template({ entries: [{ category_id: 9, amount: 1 }] })] }],
+ ["a template line whose amount is not finite", { budget_templates: [template({ entries: [{ category_id: 1, amount: Number.NaN }] })] }],
+ [
+ "two lines of a template on the same category",
+ { budget_templates: [template({ entries: [{ category_id: 1, amount: 1 }, { category_id: 1, amount: 2 }] })] },
+ ],
+ ["an adjustment without a name", { adjustments: [adjustment({ name: 7 as never })] }],
+ ["an adjustment without a date", { adjustments: [adjustment({ date: undefined as never })] }],
+ ["an adjustment whose lines are not an array", { adjustments: [adjustment({ entries: undefined as never })] }],
+ [
+ "an adjustment line on a category missing from the file",
+ { adjustments: [adjustment({ entries: [{ category_id: 9, amount: 1, description: null }] })] },
+ ],
+ [
+ "an adjustment line whose amount is not finite",
+ { adjustments: [adjustment({ entries: [{ category_id: 1, amount: Number.NEGATIVE_INFINITY, description: null }] })] },
+ ],
+ ])("refuses a format-3 file with %s", (_label, overrides) => {
+ expect(refusalOf(() => validateImportedBudget(file(overrides), 3)).i18nKey).toBe(INVALID);
+ });
+
+ it("checks nothing in a file older than the budget in backups: it holds none", () => {
+ for (const version of [1, 2]) {
+ expect(() => validateImportedBudget({ categories: [] }, version), String(version)).not.toThrow();
+ expect(() => validateImportedBudget(file({ budget_entries: [entry({ category_id: 9 })] }), version)).not.toThrow();
+ }
+ });
+
+ it("refuses at PARSE time, for both modes that carry the categories, so the confirmation never opens", () => {
+ for (const mode of ["transactions_with_categories", "categories_only"] as const) {
+ const json = serializeToJson(mode, { ...envelopeData(), ...file({ budget_entries: [entry({ month: 13 })] }) }, "0.17.2");
+ expect(refusalOf(() => parseImportedJson(json)).i18nKey, mode).toBe(INVALID);
+ }
+ });
+
+ it("leaves « Transactions uniquement » alone: it carries no budget, and its restore touches none", () => {
+ const json = serializeToJson("transactions_only", { transactions: [transactionFixture(1)] }, "0.17.2");
+ expect(() => parseImportedJson(json)).not.toThrow();
+ });
+
+ it("counts the budget a file carries in its summary", () => {
+ const { summary } = parseImportedJson(
+ serializeToJson("categories_only", { ...file(), suppliers: [], keywords: [] }, "0.17.2")
+ );
+ expect([summary.budgetEntriesCount, summary.budgetTemplatesCount, summary.adjustmentsCount]).toEqual([2, 1, 1]);
+ expect(summary.formatVersion).toBe(SREF_FORMAT_VERSION);
+ });
+
+ it.each([
+ [
+ "transactions with categories",
+ (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION),
+ ],
+ ["categories only", (data: ExportEnvelope["data"]) => importCategoriesOnly(data, SREF_FORMAT_VERSION)],
+ ] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => {
+ db.seed("categories", [{ name: "Existing" }]);
+ await expect(
+ restore({ ...envelopeData(), ...file({ budget_entries: [entry({ category_id: 9 })] }) })
+ ).rejects.toBeInstanceOf(SrefValidationError);
+ expect(db.log).toEqual([]);
+ expect(db.tables.categories.map((c) => c.name)).toEqual(["Existing"]);
+ });
+});
+
+describe("a restore takes the budget out before it deletes the categories (#520)", () => {
+ it.each([
+ [
+ "transactions with categories",
+ () => importTransactionsWithCategories(envelopeData({ categories: CATEGORY_FIXTURES }), "backup.json", SREF_FORMAT_VERSION),
+ ],
+ [
+ "categories only",
+ () => importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION),
+ ],
+ ] as const)("%s: the budget lines, template lines and adjustment lines go before the categories", async (_name, restore) => {
+ await restore();
+ const deletes = db.log.filter((line) => line.startsWith("DELETE FROM"));
+ const categories = deletes.indexOf("DELETE FROM categories");
+ for (const table of ["budget_entries", "budget_template_entries", "adjustment_entries"]) {
+ const at = deletes.indexOf(`DELETE FROM ${table}`);
+ expect(at, table).toBeGreaterThanOrEqual(0);
+ expect(at, table).toBeLessThan(categories);
+ }
+ });
+
+ it("transactions only: no budget table is touched", async () => {
+ await importTransactionsOnly(envelopeData({ transactions: [transactionFixture(1)] }), "backup.json");
+ expect(db.log.filter((line) => /budget|adjustment/.test(line))).toEqual([]);
+ });
+});
+
+describe("the texts of a restore with the budget exist in both languages (#520)", () => {
+ it("carries the refusal of a budget it could not write back, and of a newer file, in FR and EN", () => {
+ for (const bundle of [fr, en]) {
+ expect(bundle.settings.dataManagement.import.errors.invalidBudgetRows.length).toBeGreaterThan(0);
+ expect(bundle.settings.dataManagement.import.errors.newerFormat.length).toBeGreaterThan(0);
+ }
+ });
+
+ it("the confirmation names the budget, the budget templates and the adjustments among what is deleted", () => {
+ for (const key of ["willDeleteCategories", "willDeleteAll"] as const) {
+ expect(fr.settings.dataManagement.import[key], `fr.${key}`).toMatch(
+ /le budget, les modèles de budget et les ajustements/
+ );
+ expect(en.settings.dataManagement.import[key], `en.${key}`).toMatch(/the budget, budget templates, and adjustments/);
+ }
+ });
+});
diff --git a/src/services/dataExportService.ts b/src/services/dataExportService.ts
index 096e21a..930af5f 100644
--- a/src/services/dataExportService.ts
+++ b/src/services/dataExportService.ts
@@ -33,12 +33,24 @@ export type ExportFormat = "json" | "csv";
* never held any configuration", not "this profile had none". The restore then
* behaves exactly as it did before — wipe the sources and hang the transactions
* off a synthetic one — which is the only reading that cannot invent data.
+ *
+ * Version 3 (#520) is the first to carry the budget: `budget_entries`,
+ * `budget_templates` and `adjustments`, in the two modes that carry the
+ * categories (`BUDGET_SREF_FORMAT_VERSION`). A file of a later version comes
+ * from a newer build and is refused before anything is deleted (ADR 0025).
*/
-export const SREF_FORMAT_VERSION = 2;
+export const SREF_FORMAT_VERSION = 3;
/** What an envelope without an explicit `format_version` is. */
export const LEGACY_SREF_FORMAT_VERSION = 1;
+/**
+ * The first version whose files carry the budget, its templates and the
+ * adjustments (#520). A file of an earlier version holds none of them: the
+ * restore keeps instead the profile's lines whose category comes back.
+ */
+export const BUDGET_SREF_FORMAT_VERSION = 3;
+
export interface ExportEnvelope {
export_type: ExportMode;
app_version: string;
@@ -52,6 +64,10 @@ export interface ExportEnvelope {
transactions?: ExportTransaction[];
import_sources?: ExportImportSource[];
import_config_templates?: ExportImportTemplate[];
+ /** From format 3 on, in the two modes that carry the categories (#520). */
+ budget_entries?: ExportBudgetEntry[];
+ budget_templates?: ExportBudgetTemplate[];
+ adjustments?: ExportAdjustment[];
};
}
@@ -104,6 +120,56 @@ export interface ExportImportTemplate extends ImportFormatRow {
name: string;
}
+/**
+ * A budget line as it travels in the file (#520), designated by its category
+ * and its month, the table's `UNIQUE` key. No id: nothing points at a budget
+ * line.
+ */
+export interface ExportBudgetEntry {
+ category_id: number;
+ year: number;
+ month: number;
+ amount: number;
+ notes: string | null;
+}
+
+/** A line of a budget template (#520). */
+export interface ExportBudgetTemplateEntry {
+ category_id: number;
+ amount: number;
+}
+
+/**
+ * A budget template as it travels in the file (#520), designated by its name,
+ * the table's `UNIQUE` key, like an import template, and carrying its lines.
+ */
+export interface ExportBudgetTemplate {
+ name: string;
+ description: string | null;
+ entries: ExportBudgetTemplateEntry[];
+}
+
+/** A line of an adjustment (#520). */
+export interface ExportAdjustmentEntry {
+ category_id: number;
+ amount: number;
+ description: string | null;
+}
+
+/**
+ * An adjustment as it travels in the file (#520), with its lines. No id and no
+ * natural key (its name is not unique): the restore puts the file's
+ * adjustments in place of the profile's.
+ */
+export interface ExportAdjustment {
+ name: string;
+ description: string | null;
+ date: string;
+ is_recurring: number;
+ recurrence_rule: string | null;
+ entries: ExportAdjustmentEntry[];
+}
+
// --- Import types ---
export interface ImportSummary {
@@ -114,6 +180,10 @@ export interface ImportSummary {
transactionsCount: number;
importSourcesCount: number;
importTemplatesCount: number;
+ /** The budget the file carries, from format 3 on (#520). */
+ budgetEntriesCount: number;
+ budgetTemplatesCount: number;
+ adjustmentsCount: number;
/** `LEGACY_SREF_FORMAT_VERSION` when the file declares none. */
formatVersion: number;
}
@@ -124,12 +194,16 @@ export type SrefValidationErrorKey =
| "settings.dataManagement.import.errors.unsupportedSignConvention"
| "settings.dataManagement.import.errors.invalidFormatRow"
| "settings.dataManagement.import.errors.orphanSplitLines"
- | "settings.dataManagement.import.errors.danglingCategoryReference";
+ | "settings.dataManagement.import.errors.danglingCategoryReference"
+ | "settings.dataManagement.import.errors.invalidBudgetRows"
+ | "settings.dataManagement.import.errors.newerFormat";
/**
* Thrown when a backup carries a configuration this build cannot store, split
- * lines that cannot find their parent (#518), or categories, keywords or
- * suppliers that name a category the file does not hold (#521).
+ * lines that cannot find their parent (#518), categories, keywords or
+ * suppliers that name a category the file does not hold (#521), budget lines,
+ * templates or adjustments the restore could not write back, or a format newer
+ * than this build (#520).
*
* The `CHECK` added by migration v17 already refuses these values, but a SQLite
* constraint error is not something a user can act on — and it would surface
@@ -217,6 +291,119 @@ export async function getExportImportTemplates(): Promise<
}));
}
+/** Every budget line of the profile (#520). */
+export async function getExportBudgetEntries(): Promise {
+ const db = await getDb();
+ const rows = await db.select(
+ "SELECT category_id, year, month, amount, notes FROM budget_entries ORDER BY id"
+ );
+ return rows.map((row) => ({
+ category_id: row.category_id,
+ year: row.year,
+ month: row.month,
+ amount: row.amount,
+ notes: row.notes ?? null,
+ }));
+}
+
+/** Every budget template of the profile, each with its lines (#520). */
+export async function getExportBudgetTemplates(): Promise {
+ const db = await getDb();
+ const templates = await db.select<
+ Array<{ id: number; name: string; description: string | null }>
+ >("SELECT id, name, description FROM budget_templates ORDER BY id");
+ const lines = await db.select<
+ Array<{ template_id: number; category_id: number; amount: number }>
+ >("SELECT template_id, category_id, amount FROM budget_template_entries ORDER BY id");
+ return templates.map((template) => ({
+ name: template.name,
+ description: template.description ?? null,
+ entries: lines
+ .filter((line) => line.template_id === template.id)
+ .map((line) => ({ category_id: line.category_id, amount: line.amount })),
+ }));
+}
+
+/** Every adjustment of the profile, each with its lines (#520). */
+export async function getExportAdjustments(): Promise {
+ const db = await getDb();
+ const adjustments = await db.select<
+ Array<{
+ id: number;
+ name: string;
+ description: string | null;
+ date: string;
+ is_recurring: number;
+ recurrence_rule: string | null;
+ }>
+ >(
+ "SELECT id, name, description, date, is_recurring, recurrence_rule FROM adjustments ORDER BY id"
+ );
+ const lines = await db.select<
+ Array<{
+ adjustment_id: number;
+ category_id: number;
+ amount: number;
+ description: string | null;
+ }>
+ >(
+ "SELECT adjustment_id, category_id, amount, description FROM adjustment_entries ORDER BY id"
+ );
+ return adjustments.map((adjustment) => ({
+ name: adjustment.name,
+ description: adjustment.description ?? null,
+ date: adjustment.date,
+ is_recurring: adjustment.is_recurring,
+ recurrence_rule: adjustment.recurrence_rule ?? null,
+ entries: lines
+ .filter((line) => line.adjustment_id === adjustment.id)
+ .map((line) => ({
+ category_id: line.category_id,
+ amount: line.amount,
+ description: line.description ?? null,
+ })),
+ }));
+}
+
+/**
+ * What an export of `mode` carries, read from the profile: the one list of
+ * arrays per mode, for « Exporter » (`useDataExport`) and for the backup taken
+ * before the categories migration (`createPreMigrationBackup`), so that the two
+ * never carry different things (#520).
+ *
+ * The two modes that carry the categories carry the budget with them, its
+ * templates and the adjustments: their restore deletes the categories, and
+ * every one of these lines names a category. The two modes that carry the
+ * transactions carry the import configurations (#331). « Transactions
+ * uniquement » touches no category, and its budget stays where it is.
+ */
+export async function collectExportData(
+ mode: ExportMode
+): Promise {
+ const withCategories =
+ mode === "transactions_with_categories" || mode === "categories_only";
+ const withTransactions =
+ mode === "transactions_with_categories" || mode === "transactions_only";
+
+ const data: ExportEnvelope["data"] = {};
+ if (withCategories) {
+ data.categories = await getExportCategories();
+ data.suppliers = await getExportSuppliers();
+ data.keywords = await getExportKeywords();
+ }
+ if (withTransactions) {
+ data.transactions = await getExportTransactions();
+ data.import_sources = await getExportImportSources();
+ data.import_config_templates = await getExportImportTemplates();
+ }
+ if (withCategories) {
+ data.budget_entries = await getExportBudgetEntries();
+ data.budget_templates = await getExportBudgetTemplates();
+ data.adjustments = await getExportAdjustments();
+ }
+ return data;
+}
+
// --- Serialization ---
export function serializeToJson(
@@ -418,6 +605,118 @@ export function validateImportedCategoryReferences(
}
}
+/** The refusal of an envelope this app did not write (missing fields, unreadable format). */
+const INVALID_ENVELOPE = "Invalid export file format — missing required fields";
+
+/**
+ * Refuse a file whose format this build cannot read, BEFORE anything is
+ * deleted (#520): a `format_version` above `SREF_FORMAT_VERSION` comes from a
+ * newer Simpl'Résultat, whose files may carry what this build would drop
+ * without a word; one that is not an integer of at least 1 was not written by
+ * the app at all, and gets the refusal of a malformed envelope.
+ *
+ * PURE: no I/O, so it can be called from the parse step and again at the top of
+ * each restore that is given the format, like `validateImportedFormatRows`.
+ */
+export function validateImportedFormatVersion(formatVersion: unknown): void {
+ if (!Number.isInteger(formatVersion) || (formatVersion as number) < 1) {
+ throw new Error(INVALID_ENVELOPE);
+ }
+ if ((formatVersion as number) > SREF_FORMAT_VERSION) {
+ throw new SrefValidationError("settings.dataManagement.import.errors.newerFormat", {});
+ }
+}
+
+/** The years a budget line may name. */
+export const MIN_BUDGET_YEAR = 1900;
+export const MAX_BUDGET_YEAR = 2200;
+
+/**
+ * Refuse a file of format 3 or later whose budget lines, budget templates or
+ * adjustments the restore could not write back as they are, BEFORE anything is
+ * deleted (#520).
+ *
+ * From format 3 on, the two modes that carry the categories carry the three
+ * arrays, and the restore puts them in place of the profile's: a file that
+ * lacks one would empty that part of the budget, so it is refused, as is a
+ * line the tables cannot hold. Each line names a category of the file (the
+ * restore deletes every other one) and holds a finite amount; a budget line
+ * names a year from 1900 to 2200 and a month from 1 to 12, both integers; a
+ * template has a name and an adjustment a name and a date, both texts. No two
+ * budget lines share their category and month, no two lines of a template
+ * their category, no two templates their name: the `UNIQUE` keys of the
+ * tables. The tables are not STRICT, and SQLite's own refusal, midway through
+ * the restore, is not a message a user can act on. A file of an earlier format
+ * holds no budget, and nothing here applies to it.
+ *
+ * PURE: no I/O, so it can be called from the parse step and again at the top of
+ * each restore that writes categories, like `validateImportedFormatRows`.
+ */
+export function validateImportedBudget(
+ data: ExportEnvelope["data"],
+ formatVersion: number
+): void {
+ if (formatVersion < BUDGET_SREF_FORMAT_VERSION) return;
+
+ const refusal = () =>
+ new SrefValidationError(
+ "settings.dataManagement.import.errors.invalidBudgetRows",
+ {}
+ );
+ const { budget_entries: entries, budget_templates: templates, adjustments } = data;
+ if (!Array.isArray(entries) || !Array.isArray(templates) || !Array.isArray(adjustments)) {
+ throw refusal();
+ }
+
+ const categoryIds = new Set(
+ (data.categories ?? [])
+ .map((category) => category?.id)
+ .filter((id): id is number => typeof id === "number")
+ );
+ /** A line the restore can write: a category of the file, a finite amount. */
+ const isLine = (line: { category_id?: unknown; amount?: unknown } | null | undefined) =>
+ categoryIds.has(line?.category_id as number) && Number.isFinite(line?.amount);
+ const isYear = (year: unknown) =>
+ Number.isInteger(year) &&
+ (year as number) >= MIN_BUDGET_YEAR &&
+ (year as number) <= MAX_BUDGET_YEAR;
+ const isMonth = (month: unknown) =>
+ Number.isInteger(month) && (month as number) >= 1 && (month as number) <= 12;
+
+ const months = new Set();
+ for (const entry of entries) {
+ if (!isLine(entry) || !isYear(entry.year) || !isMonth(entry.month)) throw refusal();
+ const key = `${entry.category_id}/${entry.year}/${entry.month}`;
+ if (months.has(key)) throw refusal();
+ months.add(key);
+ }
+
+ const names = new Set();
+ for (const template of templates) {
+ if (typeof template?.name !== "string" || names.has(template.name)) throw refusal();
+ names.add(template.name);
+ if (!Array.isArray(template.entries)) throw refusal();
+ const lines = new Set();
+ for (const line of template.entries) {
+ if (!isLine(line) || lines.has(line.category_id)) throw refusal();
+ lines.add(line.category_id);
+ }
+ }
+
+ for (const adjustment of adjustments) {
+ if (
+ typeof adjustment?.name !== "string" ||
+ typeof adjustment.date !== "string" ||
+ !Array.isArray(adjustment.entries)
+ ) {
+ throw refusal();
+ }
+ for (const line of adjustment.entries) {
+ if (!isLine(line)) throw refusal();
+ }
+ }
+}
+
export function parseImportedJson(content: string): {
envelope: ExportEnvelope;
summary: ImportSummary;
@@ -434,9 +733,14 @@ export function parseImportedJson(content: string): {
!envelope.data ||
typeof envelope.data !== "object"
) {
- throw new Error("Invalid export file format — missing required fields");
+ throw new Error(INVALID_ENVELOPE);
}
+ // A newer format first: a later build may also bring a mode this one does
+ // not know, and « update the app » is then the message that helps (#520).
+ const formatVersion = envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION;
+ validateImportedFormatVersion(formatVersion);
+
const validTypes: ExportMode[] = [
"transactions_with_categories",
"transactions_only",
@@ -447,9 +751,9 @@ export function parseImportedJson(content: string): {
}
// Refuse an unreadable configuration, split lines that cannot find their
- // parent, or a category reference the file cannot satisfy, while the file is
- // only being LOOKED at: the confirmation dialog never opens, so nothing is
- // deleted.
+ // parent, a category reference the file cannot satisfy, or budget lines the
+ // restore could not write back, while the file is only being LOOKED at: the
+ // confirmation dialog never opens, so nothing is deleted.
validateImportedFormatRows(
envelope.data.import_sources,
envelope.data.import_config_templates
@@ -460,6 +764,11 @@ export function parseImportedJson(content: string): {
envelope.data.suppliers,
envelope.data.keywords
);
+ // The budget travels with the categories, in the two modes that carry them;
+ // « Transactions uniquement » carries none and its restore touches none.
+ if (envelope.export_type !== "transactions_only") {
+ validateImportedBudget(envelope.data, formatVersion);
+ }
return {
envelope,
@@ -471,7 +780,10 @@ export function parseImportedJson(content: string): {
transactionsCount: envelope.data.transactions?.length ?? 0,
importSourcesCount: envelope.data.import_sources?.length ?? 0,
importTemplatesCount: envelope.data.import_config_templates?.length ?? 0,
- formatVersion: envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION,
+ budgetEntriesCount: envelope.data.budget_entries?.length ?? 0,
+ budgetTemplatesCount: envelope.data.budget_templates?.length ?? 0,
+ adjustmentsCount: envelope.data.adjustments?.length ?? 0,
+ formatVersion,
},
};
}
@@ -531,9 +843,12 @@ export function parseImportedCsv(content: string): {
suppliersCount: 0,
keywordsCount: 0,
transactionsCount: transactions.length,
- // A flat CSV carries no configuration at all.
+ // A flat CSV carries no configuration at all, and no budget.
importSourcesCount: 0,
importTemplatesCount: 0,
+ budgetEntriesCount: 0,
+ budgetTemplatesCount: 0,
+ adjustmentsCount: 0,
formatVersion: LEGACY_SREF_FORMAT_VERSION,
},
};
diff --git a/src/services/dataRestoreService.ts b/src/services/dataRestoreService.ts
index 059281b..f0ec475 100644
--- a/src/services/dataRestoreService.ts
+++ b/src/services/dataRestoreService.ts
@@ -5,8 +5,11 @@ import { logWarn } from "./logService";
import { toSqlFlag } from "../utils/sqlFlag";
import type { Category, Keyword, Supplier } from "../shared/types";
import {
+ BUDGET_SREF_FORMAT_VERSION,
+ validateImportedBudget,
validateImportedCategoryReferences,
validateImportedFormatRows,
+ validateImportedFormatVersion,
validateImportedTransactionIds,
type ExportEnvelope,
type ExportImportSource,
@@ -201,6 +204,10 @@ async function runRestore(body: (db: Database) => Promise): Promise {
* any order passes, loops included, and the hierarchy check repairs a loop
* afterwards (#393). `validateImportedCategoryReferences` has already refused a
* parent the file does not hold.
+ *
+ * Each category goes back with its `i18n_key` (#520), which the export carries
+ * (`SELECT *`): without it, the categories of the standard seed came back
+ * under their French name in the English interface.
*/
async function restoreCategories(
db: Database,
@@ -208,8 +215,8 @@ async function restoreCategories(
): Promise {
for (const cat of categories ?? []) {
await db.execute(
- `INSERT INTO categories (id, name, parent_id, color, icon, type, is_active, is_inputable, sort_order)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
+ `INSERT INTO categories (id, name, parent_id, color, icon, type, is_active, is_inputable, sort_order, i18n_key)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
[
cat.id,
cat.name,
@@ -220,6 +227,7 @@ async function restoreCategories(
cat.is_active ? 1 : 0,
cat.is_inputable ? 1 : 0,
cat.sort_order,
+ cat.i18n_key ?? null,
]
);
}
@@ -512,12 +520,201 @@ async function restoreTransfers(
return transfers.length - kept.length;
}
+/** The budget of the profile as a restore takes it out (#520): every line that names a category. */
+interface HeldBudget {
+ entries: Array<{
+ id: number;
+ category_id: number;
+ year: number;
+ month: number;
+ amount: number;
+ notes: string | null;
+ created_at: string;
+ updated_at: string;
+ }>;
+ templateLines: Array<{
+ id: number;
+ template_id: number;
+ template_name: string;
+ category_id: number;
+ amount: number;
+ }>;
+ adjustmentLines: Array<{
+ id: number;
+ adjustment_id: number;
+ category_id: number;
+ amount: number;
+ description: string | null;
+ }>;
+}
+
+/**
+ * Read the profile's budget lines, template lines and adjustment lines, then
+ * remove them, ahead of `DELETE FROM categories` (#520).
+ *
+ * The three tables name a category `ON DELETE CASCADE`: the deletion of the
+ * categories used to take every one of their lines with it, and the backup
+ * held none, so a restore with categories left the budget, its templates and
+ * the adjustments empty, without a word. They are read first, in both formats
+ * and by the restore's handle, so that `restoreBudget` can put back what the
+ * file does not replace. The headers of the templates and of the adjustments
+ * name no category, and stay.
+ */
+async function takeBudget(db: Database): Promise {
+ const entries = await db.select(
+ "SELECT id, category_id, year, month, amount, notes, created_at, updated_at FROM budget_entries ORDER BY id"
+ );
+ const templateLines = await db.select(
+ `SELECT e.id, e.template_id, t.name AS template_name, e.category_id, e.amount
+ FROM budget_template_entries e
+ JOIN budget_templates t ON t.id = e.template_id
+ ORDER BY e.id`
+ );
+ const adjustmentLines = await db.select(
+ "SELECT id, adjustment_id, category_id, amount, description FROM adjustment_entries ORDER BY id"
+ );
+ await db.execute("DELETE FROM budget_entries");
+ await db.execute("DELETE FROM budget_template_entries");
+ await db.execute("DELETE FROM adjustment_entries");
+ return { entries, templateLines, adjustmentLines };
+}
+
+/**
+ * Put the budget back once the file's categories are in (#520).
+ *
+ * From format 3 on, the file carries the budget. Its budget lines and its
+ * adjustments, with their lines, replace the profile's: a restore gives back
+ * the state of the backup. Each template of the file is inserted, or updated
+ * by its name, the table's natural key, and gets the file's lines. A template
+ * the file does not hold keeps its header and the lines whose category came
+ * back, as #331 keeps the import templates.
+ *
+ * A file of an earlier format holds no budget: every line taken out by
+ * `takeBudget` comes back as it was when its category does, under the same id
+ * (ADR 0025 says why the id alone is trusted). Everything is written through
+ * the restore's handle, after the categories, which it reads once.
+ */
+async function restoreBudget(
+ db: Database,
+ held: HeldBudget,
+ data: ExportEnvelope["data"],
+ formatVersion: number
+): Promise {
+ const categoryIds = new Set(
+ (await db.select>("SELECT id FROM categories")).map(
+ (row) => row.id
+ )
+ );
+ const comesBack = (line: { category_id: number }) => categoryIds.has(line.category_id);
+ const fromFile = formatVersion >= BUDGET_SREF_FORMAT_VERSION;
+
+ if (fromFile) {
+ for (const entry of data.budget_entries ?? []) {
+ await db.execute(
+ `INSERT INTO budget_entries (category_id, year, month, amount, notes)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [entry.category_id, entry.year, entry.month, entry.amount, entry.notes ?? null]
+ );
+ }
+ // The profile's adjustments go: their lines went with `takeBudget`.
+ await db.execute("DELETE FROM adjustments");
+ for (const adjustment of data.adjustments ?? []) {
+ const result = await db.execute(
+ `INSERT INTO adjustments (name, description, date, is_recurring, recurrence_rule)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [
+ adjustment.name,
+ adjustment.description ?? null,
+ adjustment.date,
+ toSqlFlag(adjustment.is_recurring),
+ adjustment.recurrence_rule ?? null,
+ ]
+ );
+ for (const line of adjustment.entries) {
+ await db.execute(
+ `INSERT INTO adjustment_entries (adjustment_id, category_id, amount, description)
+ VALUES ($1, $2, $3, $4)`,
+ [result.lastInsertId, line.category_id, line.amount, line.description ?? null]
+ );
+ }
+ }
+ } else {
+ for (const entry of held.entries.filter(comesBack)) {
+ await db.execute(
+ `INSERT INTO budget_entries (id, category_id, year, month, amount, notes, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ entry.id,
+ entry.category_id,
+ entry.year,
+ entry.month,
+ entry.amount,
+ entry.notes,
+ entry.created_at,
+ entry.updated_at,
+ ]
+ );
+ }
+ for (const line of held.adjustmentLines.filter(comesBack)) {
+ await db.execute(
+ `INSERT INTO adjustment_entries (id, adjustment_id, category_id, amount, description)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [line.id, line.adjustment_id, line.category_id, line.amount, line.description]
+ );
+ }
+ }
+
+ // The templates of the file, by name, with the file's lines.
+ const fileTemplates = fromFile ? data.budget_templates ?? [] : [];
+ for (const template of fileTemplates) {
+ await db.execute(
+ `INSERT INTO budget_templates (name, description) VALUES ($1, $2)
+ ON CONFLICT(name) DO UPDATE SET description = excluded.description`,
+ [template.name, template.description ?? null]
+ );
+ // `lastInsertId` is 0 on the conflict branch: the id is read back by name,
+ // as `restoreImportTemplates` does.
+ const [row] = await db.select>(
+ "SELECT id FROM budget_templates WHERE name = $1",
+ [template.name]
+ );
+ for (const line of template.entries) {
+ await db.execute(
+ `INSERT INTO budget_template_entries (template_id, category_id, amount)
+ VALUES ($1, $2, $3)`,
+ [row.id, line.category_id, line.amount]
+ );
+ }
+ }
+ // The other templates keep the lines whose category came back.
+ const inFile = new Set(fileTemplates.map((template) => template.name));
+ for (const line of held.templateLines) {
+ if (inFile.has(line.template_name) || !comesBack(line)) continue;
+ await db.execute(
+ `INSERT INTO budget_template_entries (id, template_id, category_id, amount)
+ VALUES ($1, $2, $3, $4)`,
+ [line.id, line.template_id, line.category_id, line.amount]
+ );
+ }
+}
+
+/**
+ * Restore the categories, keywords and suppliers of a file, and from format 3
+ * on its budget (#520); `formatVersion` as for
+ * `importTransactionsWithCategories`.
+ */
export async function importCategoriesOnly(
- data: ExportEnvelope["data"]
+ data: ExportEnvelope["data"],
+ formatVersion: number
): Promise {
+ validateImportedFormatVersion(formatVersion);
validateImportedCategoryReferences(data.categories, data.suppliers, data.keywords);
+ validateImportedBudget(data, formatVersion);
return runRestore(async (db) => {
+ // The budget names the categories: taken out before they go (#520).
+ const budget = await takeBudget(db);
+
// Wipe keywords, suppliers, categories
await db.execute("DELETE FROM keywords");
await db.execute("DELETE FROM suppliers");
@@ -531,22 +728,35 @@ export async function importCategoriesOnly(
await restoreCategories(db, data.categories);
await restoreSuppliers(db, data.suppliers);
await restoreKeywords(db, data.keywords);
+ await restoreBudget(db, budget, data, formatVersion);
// No transaction is deleted: every transfer stays linked.
return { unlinkedTransfers: 0, uncategorizedTransactions: 0 };
});
}
+/**
+ * Restore a full backup. `formatVersion` is the file's (`ImportSummary`,
+ * `LEGACY_SREF_FORMAT_VERSION` when it declares none): from format 3 on, the
+ * file's budget replaces the profile's, and below, the profile's lines whose
+ * category comes back are kept (#520). It is never guessed from the arrays the
+ * file holds: a truncated file would pass for an old one.
+ */
export async function importTransactionsWithCategories(
data: ExportEnvelope["data"],
- filename: string
+ filename: string,
+ formatVersion: number
): Promise {
+ validateImportedFormatVersion(formatVersion);
validateImportedFormatRows(data.import_sources, data.import_config_templates);
const { keepIds } = validateImportedTransactionIds(data.transactions);
validateImportedCategoryReferences(data.categories, data.suppliers, data.keywords);
+ validateImportedBudget(data, formatVersion);
const outcome = await runRestore(async (db) => {
const transfers = await takeTransfers(db);
+ // The budget names the categories: taken out before they go (#520).
+ const budget = await takeBudget(db);
// Wipe everything
await db.execute("DELETE FROM transactions");
@@ -559,6 +769,7 @@ export async function importTransactionsWithCategories(
await restoreCategories(db, data.categories);
await restoreSuppliers(db, data.suppliers);
await restoreKeywords(db, data.keywords);
+ await restoreBudget(db, budget, data, formatVersion);
// Templates first: `import_sources.template_id` points at them.
const templateIds = await restoreImportTemplates(