fix: restore a profile holding a Bilan transfer, a missing category or a category under a newer one (#521)
Three foreign keys stopped a restore on "FOREIGN KEY constraint failed",
the whole restore rolled back:
- (a) balance_account_transfers.transaction_id is ON DELETE RESTRICT
(ADR 0010): the DELETE FROM transactions of both transaction modes,
and so "Rétablir la sauvegarde", failed as soon as one transfer
existed. Inside the restore's transaction, each transfer is now read
with the date, amount and description of its transaction, then the
table is emptied; once the transactions are back, the transfers whose
transaction returns with the same id, date, amount and description
are put back as they were (id, account, direction, notes, creation
date), and the others are unlinked.
- (b) a transaction whose category the profile no longer holds (after
"Réinitialiser", another restore, or another profile's file) failed
its insert: it now comes back without a category, manual flag at 0,
and one Journal line gives their number, nothing else.
- (c) restoreCategories inserted by id against parent_id, so a category
under a newer one, or a loop, failed. Every category now goes in with
parent_id NULL, and a second pass sets the parents.
The three restores return a RestoreOutcome { unlinkedTransfers,
uncategorizedTransactions } through runRestore<T> (categories only:
zeros). previewUnlinkedTransfers counts, outside any transaction and by
the same rule, the transfers a restore would unlink.
validateImportedCategoryReferences (pure, dataExportService.ts) refuses,
at the parse and at the head of the two restores that write categories,
a file whose parent_id, keyword or supplier names a category it does
not hold (danglingCategoryReference), before anything is deleted.
The "Gestion des données" card announces the transfers to unlink in its
confirmation and gives the real number after the restore (IMPORT_SUCCESS
carries the outcome). restoreFromBackup is split into readBackup (read,
decrypt, parse, count) and applyBackup (restore, preferences, a
RestoreResult with the outcome): "Rétablir la sauvegarde" reads the file
(after the PIN when encrypted) before a second confirmation, ends on
"Sauvegarde rétablie", and reloads the app on "Fermer" only.
Regression test in src/__integration__/restore.test.ts (real services
on node:sqlite, consolidated_schema.sql, foreign keys on): red on the
base for the three causes, green here.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1539b42bb3
commit
23079da609
17 changed files with 2019 additions and 194 deletions
|
|
@ -51,7 +51,10 @@ vi.mock("../services/dataRestoreService", async () => {
|
|||
>("../services/dataRestoreService");
|
||||
return {
|
||||
...actual,
|
||||
importTransactionsWithCategories: vi.fn(async () => undefined),
|
||||
importTransactionsWithCategories: vi.fn(async () => ({
|
||||
unlinkedTransfers: 0,
|
||||
uncategorizedTransactions: 0,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -60,7 +63,7 @@ import { invoke } from "@tauri-apps/api/core";
|
|||
import { computeMigrationPlan } from "../services/categoryMappingService";
|
||||
import { createPreMigrationBackup } from "../services/categoryBackupService";
|
||||
import { applyMigration } from "../services/categoryMigrationService";
|
||||
import { restoreFromBackup } from "../services/categoryRestoreService";
|
||||
import { applyBackup, readBackup } from "../services/categoryRestoreService";
|
||||
import { importTransactionsWithCategories } from "../services/dataRestoreService";
|
||||
import { makeV2Profile, makeV2ProfileWithCustom } from "../__fixtures__/profiles";
|
||||
import type { Profile } from "../services/profileService";
|
||||
|
|
@ -116,7 +119,10 @@ beforeEach(() => {
|
|||
vi.mocked(getDb).mockResolvedValue(fake as never);
|
||||
mockInvoke.mockReset();
|
||||
vi.mocked(importTransactionsWithCategories).mockReset();
|
||||
vi.mocked(importTransactionsWithCategories).mockResolvedValue(undefined);
|
||||
vi.mocked(importTransactionsWithCategories).mockResolvedValue({
|
||||
unlinkedTransfers: 0,
|
||||
uncategorizedTransactions: 0,
|
||||
});
|
||||
});
|
||||
|
||||
const PROFILE: Profile = {
|
||||
|
|
@ -327,10 +333,14 @@ describe("integration: restore from SREF after a migration", () => {
|
|||
const outcome = await applyMigration(plan, backup);
|
||||
expect(outcome.succeeded).toBe(true);
|
||||
|
||||
// 2. Now call restoreFromBackup using the same path.
|
||||
const restoreResult = await restoreFromBackup(backup.path, null);
|
||||
expect(restoreResult.filePath).toBe(backup.path);
|
||||
// 2. Now read the backup at the same path, then restore it, as the window
|
||||
// does around its second confirmation (#521).
|
||||
const reading = await readBackup(backup.path, null);
|
||||
expect(reading.filePath).toBe(backup.path);
|
||||
expect(vi.mocked(importTransactionsWithCategories)).not.toHaveBeenCalled();
|
||||
const restoreResult = await applyBackup(reading.envelope, reading.filename);
|
||||
expect(restoreResult.revertedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
|
||||
expect(restoreResult.outcome).toEqual({ unlinkedTransfers: 0, uncategorizedTransactions: 0 });
|
||||
|
||||
// 3. importTransactionsWithCategories must have been called exactly once.
|
||||
expect(vi.mocked(importTransactionsWithCategories)).toHaveBeenCalledTimes(1);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
/**
|
||||
* Restoring a backup that holds a split (#518).
|
||||
* Restoring a backup that holds a split (#518), a Bilan transfer, a
|
||||
* transaction whose category is gone, or a category ranked under a newer one
|
||||
* (#521).
|
||||
*
|
||||
* A split line names its parent by `parent_transaction_id`, a foreign key to
|
||||
* `transactions(id)`. The restore used to insert every row without its id. In
|
||||
|
|
@ -11,6 +13,14 @@
|
|||
* lines without a parent first, and a file whose split lines cannot find their
|
||||
* parent is refused before anything is deleted.
|
||||
*
|
||||
* Three other foreign keys stopped a restore the same way (#521): a Bilan
|
||||
* transfer (`ON DELETE RESTRICT`, ADR 0010), the category of a transaction
|
||||
* that the profile no longer holds, and the parent of a category inserted
|
||||
* after it. The transfers whose transaction comes back as it was are now kept
|
||||
* and the others unlinked, with their number announced before the
|
||||
* confirmation; a transaction whose category is gone comes back without one;
|
||||
* the categories go in without their parents, set in a second pass.
|
||||
*
|
||||
* The services run as written on a real SQLite database: `node:sqlite` (built
|
||||
* into Node, no package), the schema of a new profile with its seed
|
||||
* (`consolidated_schema.sql`), foreign keys on, as under sqlx. `../services/db`
|
||||
|
|
@ -50,7 +60,15 @@ vi.mock("../services/db", () => ({
|
|||
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
|
||||
// The Journal line of a restore that brings transactions back without their category (#521).
|
||||
const { logWarn } = vi.hoisted(() => ({ logWarn: vi.fn() }));
|
||||
vi.mock("../services/logService", async (orig) => ({
|
||||
...(await orig<typeof import("../services/logService")>()),
|
||||
logWarn,
|
||||
}));
|
||||
|
||||
import { getSplitChildren, saveSplitAdjustment } from "../services/transactionService";
|
||||
import { linkTransfer, listAccountTransfers } from "../services/balance.service";
|
||||
import {
|
||||
getExportCategories,
|
||||
getExportImportSources,
|
||||
|
|
@ -66,8 +84,14 @@ import {
|
|||
type ExportEnvelope,
|
||||
type ExportTransaction,
|
||||
} from "../services/dataExportService";
|
||||
import { importTransactionsOnly, importTransactionsWithCategories } from "../services/dataRestoreService";
|
||||
import { restoreFromBackup } from "../services/categoryRestoreService";
|
||||
import {
|
||||
importCategoriesOnly,
|
||||
importTransactionsOnly,
|
||||
importTransactionsWithCategories,
|
||||
previewUnlinkedTransfers,
|
||||
type RestoreOutcome,
|
||||
} from "../services/dataRestoreService";
|
||||
import { applyBackup, readBackup } from "../services/categoryRestoreService";
|
||||
|
||||
const SCHEMA = readFileSync(
|
||||
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
|
||||
|
|
@ -145,6 +169,7 @@ beforeEach(async () => {
|
|||
opened = [];
|
||||
fake.inTransaction = false;
|
||||
invoke.mockReset();
|
||||
logWarn.mockReset();
|
||||
profile = use(open());
|
||||
expect(imported("2026-10-05", "EPICERIE METRO", -120, GROCERIES)).toBe(1);
|
||||
expect(imported("2026-10-01", "LOYER", -1000, RENT)).toBe(2);
|
||||
|
|
@ -219,12 +244,37 @@ async function jsonBackup(mode: Mode): Promise<ExportEnvelope["data"]> {
|
|||
return parseImportedJson(serializeToJson(mode, await exportData(mode), "0.17.2")).envelope.data;
|
||||
}
|
||||
|
||||
function restore(mode: Mode, data: ExportEnvelope["data"], filename = "backup.json"): Promise<void> {
|
||||
function restore(mode: Mode, data: ExportEnvelope["data"], filename = "backup.json"): Promise<RestoreOutcome> {
|
||||
return mode === "transactions_with_categories"
|
||||
? importTransactionsWithCategories(data, filename)
|
||||
: importTransactionsOnly(data, filename);
|
||||
}
|
||||
|
||||
/** What « Exporter » writes for « Catégories uniquement », read back as the import reads it. */
|
||||
async function categoriesBackup(): Promise<ExportEnvelope["data"]> {
|
||||
const data: ExportEnvelope["data"] = {
|
||||
categories: await getExportCategories(),
|
||||
suppliers: await getExportSuppliers(),
|
||||
keywords: await getExportKeywords(),
|
||||
};
|
||||
return parseImportedJson(serializeToJson("categories_only", data, "0.17.2")).envelope.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* « Rétablir la sauvegarde » as its window runs it: the file read (and its
|
||||
* transfers counted) before the second confirmation, then restored (#521).
|
||||
*/
|
||||
async function restoreTheBackup(data: ExportEnvelope["data"]) {
|
||||
const content = serializeToJson("transactions_with_categories", data, "0.17.2");
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === "read_import_file") return content;
|
||||
throw new Error(`unexpected invoke: ${cmd}`);
|
||||
});
|
||||
const reading = await readBackup("/tmp/backup.sref", null);
|
||||
const result = await applyBackup(reading.envelope, reading.filename);
|
||||
return { reading, result };
|
||||
}
|
||||
|
||||
/** The refusal of a file whose split lines cannot find their parent. */
|
||||
function expectRefusal(error: unknown): void {
|
||||
expect(error).toBeInstanceOf(SrefValidationError);
|
||||
|
|
@ -365,19 +415,414 @@ describe("restoring a backup that holds a split (#518)", () => {
|
|||
|
||||
it("« Rétablir la sauvegarde » of the categories migration restores a profile that holds a split", async () => {
|
||||
const before = rows(profile);
|
||||
const content = serializeToJson(
|
||||
"transactions_with_categories",
|
||||
await exportData("transactions_with_categories"),
|
||||
"0.17.2",
|
||||
);
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === "read_import_file") return content;
|
||||
throw new Error(`unexpected invoke: ${cmd}`);
|
||||
});
|
||||
|
||||
await restoreFromBackup("/tmp/backup.sref", null);
|
||||
await restoreTheBackup(await exportData("transactions_with_categories"));
|
||||
|
||||
expect(rows(profile)).toEqual(before);
|
||||
expect(await splitLines(profile, "EPICERIE METRO")).toEqual(GROCERY_SPLIT);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// #521 (a) — a Bilan transfer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Accounts of the seed of a new profile. */
|
||||
const CELI = 2; // « CELI »
|
||||
const REER = 3; // « REER »
|
||||
const CELI_CATEGORY = 1962; // « CELI / TFSA », a transfer category of the seed
|
||||
|
||||
type TransferRow = {
|
||||
id: number;
|
||||
account_id: number;
|
||||
transaction_id: number;
|
||||
direction: string;
|
||||
notes: string | null;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
/** Every Bilan transfer of `db`, as the table holds it. */
|
||||
function transfersOf(db: DatabaseSync): TransferRow[] {
|
||||
return db
|
||||
.prepare(
|
||||
"SELECT id, account_id, transaction_id, direction, notes, created_at FROM balance_account_transfers ORDER BY id",
|
||||
)
|
||||
.all()
|
||||
.map((row) => ({ ...row })) as TransferRow[];
|
||||
}
|
||||
|
||||
/** A copy of `data` whose transaction `id` is changed by `change`. */
|
||||
function changingTransaction(
|
||||
data: ExportEnvelope["data"],
|
||||
id: number,
|
||||
change: (tx: ExportTransaction) => ExportTransaction | null,
|
||||
): ExportEnvelope["data"] {
|
||||
return {
|
||||
...data,
|
||||
transactions: (data.transactions ?? []).flatMap((tx) => {
|
||||
if (tx.id !== id) return [tx];
|
||||
const changed = change(tx);
|
||||
return changed === null ? [] : [changed];
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
describe("restoring a profile that holds a Bilan transfer (#521)", () => {
|
||||
/** « VIREMENT CELI », linked to « CELI »: transfer 1. */
|
||||
let contribution: number;
|
||||
/** « RETRAIT REER », linked to « REER »: transfer 2. */
|
||||
let withdrawal: number;
|
||||
let transfersBefore: TransferRow[];
|
||||
let celiBefore: Awaited<ReturnType<typeof listAccountTransfers>>;
|
||||
|
||||
beforeEach(async () => {
|
||||
contribution = imported("2026-10-04", "VIREMENT CELI", -500, CELI_CATEGORY);
|
||||
withdrawal = imported("2026-10-06", "RETRAIT REER", 300, CELI_CATEGORY);
|
||||
// The ids the files of `FILES` change, after the five rows of the probe of #518.
|
||||
expect([contribution, withdrawal]).toEqual([6, 7]);
|
||||
// As « Lier transferts » links them, by the real service.
|
||||
await linkTransfer(CELI, contribution, "in", "Cotisation d'octobre");
|
||||
await linkTransfer(REER, withdrawal, "out");
|
||||
transfersBefore = transfersOf(profile);
|
||||
expect(transfersBefore.map((t) => [t.id, t.account_id, t.transaction_id, t.direction])).toEqual([
|
||||
[1, CELI, contribution, "in"],
|
||||
[2, REER, withdrawal, "out"],
|
||||
]);
|
||||
// What the Bilan reads for the return of « CELI »: the transfer with its transaction.
|
||||
celiBefore = await listAccountTransfers(CELI);
|
||||
});
|
||||
|
||||
it.each(MODES)(
|
||||
"%s, same profile: the restore succeeds, every transfer comes back as it was, none unlinked",
|
||||
async (mode) => {
|
||||
const before = rows(profile);
|
||||
|
||||
const outcome = await restore(mode, await jsonBackup(mode));
|
||||
|
||||
expect(outcome.unlinkedTransfers).toBe(0);
|
||||
expect(transfersOf(profile)).toEqual(transfersBefore);
|
||||
expect(await listAccountTransfers(CELI)).toEqual(celiBefore);
|
||||
expect(rows(profile)).toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(MODES)(
|
||||
"%s: a transfer whose transaction comes back with another amount is unlinked, the other kept",
|
||||
async (mode) => {
|
||||
const data = changingTransaction(await jsonBackup(mode), contribution, (tx) => ({ ...tx, amount: -450 }));
|
||||
|
||||
const outcome = await restore(mode, data);
|
||||
|
||||
expect(outcome.unlinkedTransfers).toBe(1);
|
||||
expect(transfersOf(profile)).toEqual([transfersBefore[1]]);
|
||||
expect(await listAccountTransfers(CELI)).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(MODES)("%s: the number of transfers to unlink is announced before the restore, which writes nothing", async (mode) => {
|
||||
const data = changingTransaction(await jsonBackup(mode), contribution, (tx) => ({ ...tx, amount: -450 }));
|
||||
const before = rows(profile);
|
||||
|
||||
expect(await previewUnlinkedTransfers(data.transactions)).toBe(1);
|
||||
expect(await previewUnlinkedTransfers((await jsonBackup(mode)).transactions)).toBe(0);
|
||||
expect(rows(profile)).toEqual(before);
|
||||
expect(transfersOf(profile)).toEqual(transfersBefore);
|
||||
});
|
||||
|
||||
it.each(MODES)("%s, new profile: no transfer there, none unlinked; the profile of the file keeps its own", async (mode) => {
|
||||
const data = await jsonBackup(mode);
|
||||
const fresh = use(open());
|
||||
|
||||
expect(await previewUnlinkedTransfers(data.transactions)).toBe(0);
|
||||
const outcome = await restore(mode, data);
|
||||
|
||||
expect(outcome.unlinkedTransfers).toBe(0);
|
||||
expect(transfersOf(fresh)).toEqual([]);
|
||||
expect(transfersOf(profile)).toEqual(transfersBefore);
|
||||
});
|
||||
|
||||
/**
|
||||
* The files of the rule: a transfer is kept when its transaction comes back
|
||||
* with the same id, the same date, the same amount and the same
|
||||
* description; the number announced before the confirmation is the number
|
||||
* unlinked.
|
||||
*/
|
||||
const FILES: Array<[string, (data: ExportEnvelope["data"]) => ExportEnvelope["data"], number[]]> = [
|
||||
["the same file", (data) => data, [1, 2]],
|
||||
["the amount of « VIREMENT CELI » changed", (data) => changingTransaction(data, 6, (tx) => ({ ...tx, amount: -500.01 })), [2]],
|
||||
["its date changed", (data) => changingTransaction(data, 6, (tx) => ({ ...tx, date: "2026-10-05" })), [2]],
|
||||
["its description changed", (data) => changingTransaction(data, 6, (tx) => ({ ...tx, description: "VIREMENT CELI 2" })), [2]],
|
||||
["its id changed", (data) => changingTransaction(data, 6, (tx) => ({ ...tx, id: 60 })), [2]],
|
||||
["it is missing from the file", (data) => changingTransaction(data, 6, () => null), [2]],
|
||||
[
|
||||
"« VIREMENT CELI » and « RETRAIT REER » swapped their ids",
|
||||
(data) =>
|
||||
changingTransaction(
|
||||
changingTransaction(changingTransaction(data, 6, (tx) => ({ ...tx, id: 70 })), 7, (tx) => ({ ...tx, id: 6 })),
|
||||
70,
|
||||
(tx) => ({ ...tx, id: 7 }),
|
||||
),
|
||||
[],
|
||||
],
|
||||
[
|
||||
"its rows do not keep their ids (two share one, no split line)",
|
||||
(data) => ({
|
||||
...data,
|
||||
transactions: (data.transactions ?? [])
|
||||
.filter((tx) => tx.parent_transaction_id === null)
|
||||
.map((tx) => (tx.id === 7 ? { ...tx, id: 6 } : { ...tx, is_split: 0 })),
|
||||
}),
|
||||
[],
|
||||
],
|
||||
];
|
||||
|
||||
describe.each(MODES)("%s: the number announced is the number unlinked", (mode) => {
|
||||
it.each(FILES)("%s", async (_label, file, kept) => {
|
||||
const data = file(await jsonBackup(mode));
|
||||
const announced = await previewUnlinkedTransfers(data.transactions);
|
||||
|
||||
const outcome = await restore(mode, data);
|
||||
|
||||
expect(transfersOf(profile).map((t) => t.id)).toEqual(kept);
|
||||
expect(outcome.unlinkedTransfers).toBe(2 - kept.length);
|
||||
expect(announced).toBe(outcome.unlinkedTransfers);
|
||||
});
|
||||
});
|
||||
|
||||
it("« Rétablir la sauvegarde »: the transfers come back, none announced, none unlinked", async () => {
|
||||
const { reading, result } = await restoreTheBackup(await exportData("transactions_with_categories"));
|
||||
|
||||
expect(reading.unlinkedTransfers).toBe(0);
|
||||
expect(result.outcome.unlinkedTransfers).toBe(0);
|
||||
expect(transfersOf(profile)).toEqual(transfersBefore);
|
||||
expect(await listAccountTransfers(CELI)).toEqual(celiBefore);
|
||||
});
|
||||
|
||||
it("« Rétablir la sauvegarde »: a transfer whose transaction changed is announced at the reading, then unlinked", async () => {
|
||||
const data = changingTransaction(await exportData("transactions_with_categories"), contribution, (tx) => ({
|
||||
...tx,
|
||||
amount: -450,
|
||||
}));
|
||||
|
||||
const { reading, result } = await restoreTheBackup(data);
|
||||
|
||||
expect(reading.unlinkedTransfers).toBe(1);
|
||||
expect(result.outcome.unlinkedTransfers).toBe(1);
|
||||
expect(transfersOf(profile)).toEqual([transfersBefore[1]]);
|
||||
});
|
||||
|
||||
it("the reading of « Rétablir la sauvegarde » writes nothing", async () => {
|
||||
const data = changingTransaction(await exportData("transactions_with_categories"), contribution, () => null);
|
||||
const content = serializeToJson("transactions_with_categories", data, "0.17.2");
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === "read_import_file") return content;
|
||||
throw new Error(`unexpected invoke: ${cmd}`);
|
||||
});
|
||||
const before = rows(profile);
|
||||
|
||||
const reading = await readBackup("/tmp/backup.sref", null);
|
||||
|
||||
expect(reading.unlinkedTransfers).toBe(1);
|
||||
expect(rows(profile)).toEqual(before);
|
||||
expect(transfersOf(profile)).toEqual(transfersBefore);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// #521 (b) — a transaction whose category is gone
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** A category created by the user, outside the seed; its id. */
|
||||
function category(db: DatabaseSync, name: string): number {
|
||||
const result = db
|
||||
.prepare("INSERT INTO categories (name, type, sort_order) VALUES ($name, 'expense', 99)")
|
||||
.run({ $name: name });
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
|
||||
describe("restoring a transaction whose category is gone (#521)", () => {
|
||||
/** « Perso », created by the user. */
|
||||
let perso: number;
|
||||
/** « CADEAU », put by hand in « Perso ». */
|
||||
let gift: number;
|
||||
|
||||
beforeEach(() => {
|
||||
perso = category(profile, "Perso");
|
||||
gift = imported("2026-10-07", "CADEAU", -80, perso);
|
||||
profile.prepare("UPDATE transactions SET is_manually_categorized = 1 WHERE id = $id").run({ $id: gift });
|
||||
});
|
||||
|
||||
/** The category and the manual flag of the transaction `id` of `db`. */
|
||||
const categorization = (db: DatabaseSync, id: number) => {
|
||||
const row = rows(db).find((tx) => tx.id === id)!;
|
||||
return { category_id: row.category_id, is_manually_categorized: row.is_manually_categorized };
|
||||
};
|
||||
|
||||
it("« Transactions uniquement » after the category was deleted: the transaction comes back without a category, manual flag at 0", async () => {
|
||||
const before = rows(profile);
|
||||
const data = await jsonBackup("transactions_only");
|
||||
// What « Réinitialiser » does to the categories: the rows are gone.
|
||||
profile.prepare("DELETE FROM categories WHERE id = $id").run({ $id: perso });
|
||||
|
||||
const outcome = await importTransactionsOnly(data, "backup.json");
|
||||
|
||||
expect(categorization(profile, gift)).toEqual({ category_id: null, is_manually_categorized: 0 });
|
||||
expect(outcome.uncategorizedTransactions).toBe(1);
|
||||
// The others come back as they were.
|
||||
expect(rows(profile).filter((tx) => tx.id !== gift)).toEqual(before.filter((tx) => tx.id !== gift));
|
||||
});
|
||||
|
||||
it("the Journal gives their number, without a name or an amount", async () => {
|
||||
const data = await jsonBackup("transactions_only");
|
||||
profile.prepare("DELETE FROM categories WHERE id = $id").run({ $id: perso });
|
||||
|
||||
await importTransactionsOnly(data, "backup.json");
|
||||
|
||||
expect(logWarn).toHaveBeenCalledTimes(1);
|
||||
const [line] = logWarn.mock.calls[0];
|
||||
expect(line).toBe("Data restore: 1 transaction restored without a category, missing from the profile");
|
||||
});
|
||||
|
||||
it("no Journal line when every category is there", async () => {
|
||||
const outcome = await importTransactionsOnly(await jsonBackup("transactions_only"), "backup.json");
|
||||
|
||||
expect(outcome.uncategorizedTransactions).toBe(0);
|
||||
expect(logWarn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("« Transactions uniquement » after « Réinitialiser »: every transaction comes back without a category", async () => {
|
||||
const data = await jsonBackup("transactions_only");
|
||||
// The real « Réinitialiser » puts the v2 seed back (ids 1 to 73): no IPC category is left.
|
||||
const { reinitializeCategories } = await import("../services/categoryService");
|
||||
await reinitializeCategories();
|
||||
|
||||
const outcome = await importTransactionsOnly(data, "backup.json");
|
||||
|
||||
expect(outcome.uncategorizedTransactions).toBe(data.transactions!.length);
|
||||
expect(rows(profile).every((tx) => tx.category_id === null && tx.is_manually_categorized === 0)).toBe(true);
|
||||
expect(logWarn).toHaveBeenCalledWith(
|
||||
`Data restore: ${data.transactions!.length} transactions restored without a category, missing from the profile`,
|
||||
);
|
||||
});
|
||||
|
||||
it("« Transactions avec catégories » whose file lacks the category: the same", async () => {
|
||||
const full = await jsonBackup("transactions_with_categories");
|
||||
const data = { ...full, categories: (full.categories ?? []).filter((c) => c.id !== perso) };
|
||||
|
||||
const outcome = await importTransactionsWithCategories(data, "backup.json");
|
||||
|
||||
expect(categorization(profile, gift)).toEqual({ category_id: null, is_manually_categorized: 0 });
|
||||
expect(outcome.uncategorizedTransactions).toBe(1);
|
||||
});
|
||||
|
||||
it("witness: a category that is there keeps the transaction and its manual flag", async () => {
|
||||
await importTransactionsOnly(await jsonBackup("transactions_only"), "backup.json");
|
||||
|
||||
expect(categorization(profile, gift)).toEqual({ category_id: perso, is_manually_categorized: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// #521 (c) — a category ranked under a newer one, or caught in a loop
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Every category of `db` with its parent. */
|
||||
function parents(db: DatabaseSync): Array<{ id: number; parent_id: number | null }> {
|
||||
return db
|
||||
.prepare("SELECT id, parent_id FROM categories ORDER BY id")
|
||||
.all()
|
||||
.map((row) => ({ ...row })) as Array<{ id: number; parent_id: number | null }>;
|
||||
}
|
||||
|
||||
const WITH_CATEGORIES = ["transactions_with_categories", "categories_only", "Rétablir la sauvegarde"] as const;
|
||||
|
||||
/** Restores the backup of `db` the way `how` does. */
|
||||
async function restoreCategoriesBy(how: (typeof WITH_CATEGORIES)[number]): Promise<void> {
|
||||
if (how === "categories_only") {
|
||||
await importCategoriesOnly(await categoriesBackup());
|
||||
} else if (how === "transactions_with_categories") {
|
||||
await importTransactionsWithCategories(await jsonBackup("transactions_with_categories"), "backup.json");
|
||||
} else {
|
||||
await restoreTheBackup(await exportData("transactions_with_categories"));
|
||||
}
|
||||
}
|
||||
|
||||
describe("restoring a category ranked under a newer one, or caught in a loop (#521)", () => {
|
||||
let before: Array<{ id: number; parent_id: number | null }>;
|
||||
|
||||
beforeEach(() => {
|
||||
// « Ancienne » under « Nouvelle », created after it, as the migration puts
|
||||
// a personal category under « Catégories personnalisées (migration) » (2000).
|
||||
const older = category(profile, "Ancienne");
|
||||
const newer = category(profile, "Nouvelle");
|
||||
profile.prepare("UPDATE categories SET parent_id = $p WHERE id = $id").run({ $p: newer, $id: older });
|
||||
// A loop: « Boucle A » under « Boucle B », « Boucle B » under « Boucle A ».
|
||||
const a = category(profile, "Boucle A");
|
||||
const b = category(profile, "Boucle B");
|
||||
profile.prepare("UPDATE categories SET parent_id = $p WHERE id = $id").run({ $p: b, $id: a });
|
||||
profile.prepare("UPDATE categories SET parent_id = $p WHERE id = $id").run({ $p: a, $id: b });
|
||||
before = parents(profile);
|
||||
expect(before.find((c) => c.id === older)?.parent_id).toBe(newer);
|
||||
expect(newer).toBeGreaterThan(older);
|
||||
});
|
||||
|
||||
it.each(WITH_CATEGORIES)("%s, same profile: the restore succeeds, every parent_id comes back as it was", async (how) => {
|
||||
await restoreCategoriesBy(how);
|
||||
|
||||
expect(parents(profile)).toEqual(before);
|
||||
});
|
||||
|
||||
it.each(["transactions_with_categories", "categories_only"] as const)(
|
||||
"%s, new profile: the same hierarchy",
|
||||
async (how) => {
|
||||
const data = how === "categories_only" ? await categoriesBackup() : await jsonBackup(how);
|
||||
const fresh = use(open());
|
||||
|
||||
await (how === "categories_only" ? importCategoriesOnly(data) : importTransactionsWithCategories(data, "backup.json"));
|
||||
|
||||
expect(parents(fresh)).toEqual(before);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// #521 — a category reference the file cannot satisfy (text 8)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("a file whose keyword, supplier or parent names a category it does not hold (#521)", () => {
|
||||
const DANGLING = "settings.dataManagement.import.errors.danglingCategoryReference";
|
||||
|
||||
const expectDangling = (error: unknown) => {
|
||||
expect(error).toBeInstanceOf(SrefValidationError);
|
||||
expect((error as SrefValidationError).i18nKey).toBe(DANGLING);
|
||||
};
|
||||
|
||||
it.each(["transactions_with_categories", "categories_only"] as const)(
|
||||
"%s: a keyword pointing to a missing category is refused at the parse and before anything is deleted; the profile is intact",
|
||||
async (how) => {
|
||||
const full = how === "categories_only" ? await categoriesBackup() : await jsonBackup(how);
|
||||
const [keyword] = full.keywords ?? [];
|
||||
// The keyword's category is not in the file.
|
||||
const data = { ...full, categories: (full.categories ?? []).filter((c) => c.id !== keyword.category_id) };
|
||||
const before = rows(profile);
|
||||
const categories = count(profile, "categories");
|
||||
const keywords = count(profile, "keywords");
|
||||
|
||||
let refusal: unknown = null;
|
||||
try {
|
||||
parseImportedJson(serializeToJson(how, data, "0.17.2"));
|
||||
} catch (e) {
|
||||
refusal = e;
|
||||
}
|
||||
expectDangling(refusal);
|
||||
|
||||
const run =
|
||||
how === "categories_only" ? importCategoriesOnly(data) : importTransactionsWithCategories(data, "backup.json");
|
||||
await run.then(() => expect.unreachable("the restore should have been refused"), expectDangling);
|
||||
|
||||
expect(rows(profile)).toEqual(before);
|
||||
expect(count(profile, "categories")).toBe(categories);
|
||||
expect(count(profile, "keywords")).toBe(keywords);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,14 +1,17 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertTriangle, FolderOpen, Loader2, X } from "lucide-react";
|
||||
import { AlertTriangle, CheckCircle, FolderOpen, Loader2, X } from "lucide-react";
|
||||
import {
|
||||
applyBackup,
|
||||
backupFileExists,
|
||||
isFileEncrypted,
|
||||
pickBackupFile,
|
||||
restoreFromBackup,
|
||||
readBackup,
|
||||
RestoreError,
|
||||
type BackupReading,
|
||||
type RestorableMigrationJournal,
|
||||
type RestoreResult,
|
||||
} from "../../services/categoryRestoreService";
|
||||
import { SrefValidationError } from "../../services/dataExportService";
|
||||
|
||||
|
|
@ -17,13 +20,17 @@ import { SrefValidationError } from "../../services/dataExportService";
|
|||
// Settings entry to roll back a category migration. Mounted via a portal on
|
||||
// document.body so it escapes any ancestor stacking context.
|
||||
//
|
||||
// High-level flow:
|
||||
// High-level flow (#521):
|
||||
// 1. Mount with the recorded `journal` — show the date + path and two CTAs.
|
||||
// 2. On "Restore" click: verify the recorded file still exists on disk. If
|
||||
// not, flip to the "missing file" state and let the user pick a file.
|
||||
// 3. If the file is SREF-encrypted, prompt the PIN; otherwise proceed.
|
||||
// 4. Run `restoreFromBackup`, reload the app on success so every page sees
|
||||
// the restored state.
|
||||
// 4. Read the file (`readBackup`): nothing is written yet.
|
||||
// 5. Second confirmation: what the restore will lose for good, the Bilan
|
||||
// transfers it will unlink, before the user clicks "Restore" again.
|
||||
// 6. Run `applyBackup`, then show "Backup restored" with what it did. The
|
||||
// app reloads only on "Close", so that every page sees the restored state
|
||||
// after the user has read it.
|
||||
//
|
||||
// The UX intentionally keeps destructive action behind an explicit "Restore"
|
||||
// button — a single click does not restore; the user must read the warning
|
||||
|
|
@ -35,16 +42,20 @@ type Phase =
|
|||
| "confirm" // initial screen with the data/path + Restore/Cancel buttons
|
||||
| "missing" // recorded path no longer on disk — user must pick a file
|
||||
| "password" // detected SREF encryption — ask for the PIN
|
||||
| "reading" // in-flight read of the file, nothing written
|
||||
| "review" // second confirmation, once the file is read
|
||||
| "restoring" // in-flight restore call
|
||||
| "done" // restored — reloads the app on "Close"
|
||||
| "error"; // failed — surface the error and allow retry
|
||||
|
||||
interface CategoriesMigrationRestoreModalProps {
|
||||
journal: RestorableMigrationJournal;
|
||||
onClose: () => void;
|
||||
/**
|
||||
* Called after the restore finishes successfully. By default, the app is
|
||||
* reloaded to refresh all data-bound views. Consumers may override this
|
||||
* (e.g. in tests) but the default is the safe path.
|
||||
* Called when the user closes the window once the restore has succeeded
|
||||
* ("Close" of the "Backup restored" phase). By default, the app is reloaded
|
||||
* to refresh all data-bound views. Consumers may override this (e.g. in
|
||||
* tests) but the default is the safe path.
|
||||
*/
|
||||
onRestored?: () => void;
|
||||
}
|
||||
|
|
@ -60,15 +71,31 @@ export default function CategoriesMigrationRestoreModal({
|
|||
const [password, setPassword] = useState<string>("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isEncrypted, setIsEncrypted] = useState<boolean>(false);
|
||||
const [reading, setReading] = useState<BackupReading | null>(null);
|
||||
const [result, setResult] = useState<RestoreResult | null>(null);
|
||||
|
||||
// Close on Escape (disabled while restoring to avoid interrupting the wipe).
|
||||
const isBusy = phase === "reading" || phase === "restoring";
|
||||
|
||||
/** Leaves the window once restored: the app reloads, so every page reads the restored profile. */
|
||||
function finish() {
|
||||
if (onRestored) {
|
||||
onRestored();
|
||||
} else {
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// Once restored, every way out of the window is "Close": it reloads.
|
||||
const dismiss = phase === "done" ? finish : onClose;
|
||||
|
||||
// Close on Escape (disabled while reading or restoring).
|
||||
useEffect(() => {
|
||||
function handleEscape(e: KeyboardEvent) {
|
||||
if (e.key === "Escape" && phase !== "restoring") onClose();
|
||||
if (e.key === "Escape" && !isBusy) dismiss();
|
||||
}
|
||||
document.addEventListener("keydown", handleEscape);
|
||||
return () => document.removeEventListener("keydown", handleEscape);
|
||||
}, [onClose, phase]);
|
||||
}, [dismiss, isBusy]);
|
||||
|
||||
const formattedDate = formatJournalDate(journal.timestamp);
|
||||
|
||||
|
|
@ -114,21 +141,32 @@ export default function CategoriesMigrationRestoreModal({
|
|||
return;
|
||||
}
|
||||
|
||||
await runRestore(pathToUse, null);
|
||||
await readFile(pathToUse, null);
|
||||
}
|
||||
|
||||
async function runRestore(pathToUse: string, pw: string | null) {
|
||||
/** Reads the file, then opens the second confirmation: nothing is written yet. */
|
||||
async function readFile(pathToUse: string, pw: string | null) {
|
||||
setPhase("reading");
|
||||
setError(null);
|
||||
try {
|
||||
setReading(await readBackup(pathToUse, pw));
|
||||
setPhase("review");
|
||||
} catch (e) {
|
||||
setError(messageForError(e));
|
||||
setPhase("error");
|
||||
}
|
||||
}
|
||||
|
||||
/** The destructive write, after the second confirmation. */
|
||||
async function runRestore() {
|
||||
if (!reading) return;
|
||||
setPhase("restoring");
|
||||
setError(null);
|
||||
try {
|
||||
await restoreFromBackup(pathToUse, pw);
|
||||
if (onRestored) {
|
||||
onRestored();
|
||||
} else {
|
||||
// Full reload so every page (dashboard, transactions, etc.) reflects
|
||||
// the restored v2 state instead of stale v1 derived data.
|
||||
window.location.reload();
|
||||
}
|
||||
setResult(await applyBackup(reading.envelope, reading.filename));
|
||||
// The app reloads on "Close" only, once the user has read what the
|
||||
// restore did (#521).
|
||||
setPhase("done");
|
||||
} catch (e) {
|
||||
setError(messageForError(e));
|
||||
setPhase("error");
|
||||
|
|
@ -154,16 +192,14 @@ export default function CategoriesMigrationRestoreModal({
|
|||
|
||||
function handlePasswordSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
void runRestore(effectivePath, password.length > 0 ? password : null);
|
||||
void readFile(effectivePath, password.length > 0 ? password : null);
|
||||
}
|
||||
|
||||
const isBusy = phase === "restoring";
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
className="fixed inset-0 z-[200] flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget && !isBusy) onClose();
|
||||
if (e.target === e.currentTarget && !isBusy) dismiss();
|
||||
}}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
|
|
@ -173,12 +209,20 @@ export default function CategoriesMigrationRestoreModal({
|
|||
{/* Header */}
|
||||
<div className="flex items-start justify-between px-6 py-4 border-b border-[var(--border)]">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="mt-0.5 shrink-0 rounded-lg bg-[var(--negative)]/10 p-2 text-[var(--negative)]">
|
||||
<AlertTriangle size={18} />
|
||||
</div>
|
||||
{phase === "done" ? (
|
||||
<div className="mt-0.5 shrink-0 rounded-lg bg-[var(--positive)]/10 p-2 text-[var(--positive)]">
|
||||
<CheckCircle size={18} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-0.5 shrink-0 rounded-lg bg-[var(--negative)]/10 p-2 text-[var(--negative)]">
|
||||
<AlertTriangle size={18} />
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<h2 id="restore-modal-title" className="text-lg font-semibold">
|
||||
{t("settings.categoriesCard.restoreModal.title")}
|
||||
{phase === "done"
|
||||
? t("settings.categoriesCard.restoreModal.doneTitle")
|
||||
: t("settings.categoriesCard.restoreModal.title")}
|
||||
</h2>
|
||||
<p className="text-sm text-[var(--muted-foreground)] mt-0.5">
|
||||
{t("settings.categoriesCard.restoreModal.subtitle", {
|
||||
|
|
@ -189,7 +233,7 @@ export default function CategoriesMigrationRestoreModal({
|
|||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
onClick={dismiss}
|
||||
disabled={isBusy}
|
||||
aria-label={t("settings.categoriesCard.restoreModal.close")}
|
||||
className="shrink-0 rounded-md p-1 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)] transition-colors disabled:opacity-50"
|
||||
|
|
@ -200,10 +244,12 @@ export default function CategoriesMigrationRestoreModal({
|
|||
|
||||
{/* Body */}
|
||||
<div className="px-6 py-4 space-y-4">
|
||||
{/* Destructive action warning — kept visible across every phase */}
|
||||
<p className="text-sm text-[var(--foreground)]">
|
||||
{t("settings.categoriesCard.restoreModal.warning")}
|
||||
</p>
|
||||
{/* Destructive action warning — kept visible until the restore is done */}
|
||||
{phase !== "done" && (
|
||||
<p className="text-sm text-[var(--foreground)]">
|
||||
{t("settings.categoriesCard.restoreModal.warning")}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{phase === "confirm" && (
|
||||
<div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-xs text-[var(--muted-foreground)] break-all">
|
||||
|
|
@ -246,6 +292,32 @@ export default function CategoriesMigrationRestoreModal({
|
|||
</form>
|
||||
)}
|
||||
|
||||
{phase === "reading" && (
|
||||
<div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">
|
||||
<Loader2 size={16} className="animate-spin" />
|
||||
{t("settings.categoriesCard.restoreModal.reading")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Second confirmation: the file is read, nothing is written yet (#521) */}
|
||||
{phase === "review" && reading && (
|
||||
<>
|
||||
<div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-xs text-[var(--muted-foreground)] break-all">
|
||||
<p className="font-medium text-[var(--foreground)] mb-1">
|
||||
{t("settings.categoriesCard.restoreModal.filePath")}
|
||||
</p>
|
||||
<code>{reading.filePath}</code>
|
||||
</div>
|
||||
{reading.unlinkedTransfers > 0 && (
|
||||
<p className="rounded-lg border border-[var(--negative)]/30 bg-[var(--negative)]/5 px-3 py-2 text-sm text-[var(--negative)]">
|
||||
{t("settings.categoriesCard.restoreModal.unlinkedTransfersPreview", {
|
||||
count: reading.unlinkedTransfers,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{phase === "restoring" && (
|
||||
<div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">
|
||||
<Loader2 size={16} className="animate-spin" />
|
||||
|
|
@ -253,6 +325,21 @@ export default function CategoriesMigrationRestoreModal({
|
|||
</div>
|
||||
)}
|
||||
|
||||
{phase === "done" && result && (
|
||||
<>
|
||||
<p className="text-sm text-[var(--foreground)]">
|
||||
{t("settings.categoriesCard.restoreModal.doneReload")}
|
||||
</p>
|
||||
{result.outcome.unlinkedTransfers > 0 && (
|
||||
<p className="text-sm text-[var(--negative)]">
|
||||
{t("settings.categoriesCard.restoreModal.unlinkedTransfers", {
|
||||
count: result.outcome.unlinkedTransfers,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{phase === "error" && error && (
|
||||
<div className="rounded-lg border border-[var(--negative)]/30 bg-[var(--negative)]/5 px-3 py-3 text-sm text-[var(--negative)]">
|
||||
{error}
|
||||
|
|
@ -313,7 +400,7 @@ export default function CategoriesMigrationRestoreModal({
|
|||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
runRestore(effectivePath, password.length > 0 ? password : null)
|
||||
readFile(effectivePath, password.length > 0 ? password : null)
|
||||
}
|
||||
disabled={password.length === 0}
|
||||
className="px-4 py-2 text-sm font-medium rounded-lg bg-[var(--negative)] text-white hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
|
|
@ -323,6 +410,35 @@ export default function CategoriesMigrationRestoreModal({
|
|||
</>
|
||||
)}
|
||||
|
||||
{phase === "review" && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm rounded-lg border border-[var(--border)] hover:bg-[var(--muted)] transition-colors"
|
||||
>
|
||||
{t("settings.categoriesCard.restoreModal.cancel")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => runRestore()}
|
||||
className="px-4 py-2 text-sm font-medium rounded-lg bg-[var(--negative)] text-white hover:opacity-90 transition-opacity"
|
||||
>
|
||||
{t("settings.categoriesCard.restoreModal.confirm")}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{phase === "done" && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={finish}
|
||||
className="px-4 py-2 text-sm font-medium rounded-lg bg-[var(--primary)] text-white hover:opacity-90 transition-opacity"
|
||||
>
|
||||
{t("settings.categoriesCard.restoreModal.close")}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{phase === "error" && (
|
||||
<>
|
||||
<button
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
// CategoriesMigrationRestoreModal — what « Rétablir la sauvegarde » shows when
|
||||
// the import boundary refuses the backup (#518).
|
||||
// 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 ».
|
||||
//
|
||||
// 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
|
||||
// plain function, its state survives from one call to the next, the test calls
|
||||
// the onClick of its « Restore » button, then renders again to read the
|
||||
// message. `createPortal` is the identity and `document` a stub: the window is
|
||||
// a portal.
|
||||
// the onClick of its buttons, then renders again to read the result.
|
||||
// `createPortal` is the identity and `document` a stub: the window is a portal.
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
|
|
@ -16,19 +18,29 @@ vi.mock("react-dom", async (orig) => ({
|
|||
...(await orig<typeof import("react-dom")>()),
|
||||
createPortal: (children: ReactNode) => children,
|
||||
}));
|
||||
const { restoreFromBackup } = vi.hoisted(() => ({ restoreFromBackup: vi.fn() }));
|
||||
const service = vi.hoisted(() => ({
|
||||
readBackup: vi.fn(),
|
||||
applyBackup: vi.fn(),
|
||||
isFileEncrypted: vi.fn(),
|
||||
}));
|
||||
vi.mock("../../services/categoryRestoreService", async (orig) => ({
|
||||
...(await orig<typeof import("../../services/categoryRestoreService")>()),
|
||||
backupFileExists: vi.fn(async () => true),
|
||||
isFileEncrypted: vi.fn(async () => false),
|
||||
isFileEncrypted: service.isFileEncrypted,
|
||||
pickBackupFile: vi.fn(async () => null),
|
||||
restoreFromBackup,
|
||||
readBackup: service.readBackup,
|
||||
applyBackup: service.applyBackup,
|
||||
}));
|
||||
|
||||
import { hookHarness } from "../../test/hookHarness";
|
||||
import { find, texts } from "../../test/elementTree";
|
||||
import CategoriesMigrationRestoreModal from "./CategoriesMigrationRestoreModal";
|
||||
import { RestoreError, type RestorableMigrationJournal } from "../../services/categoryRestoreService";
|
||||
import {
|
||||
RestoreError,
|
||||
type BackupReading,
|
||||
type RestorableMigrationJournal,
|
||||
type RestoreResult,
|
||||
} from "../../services/categoryRestoreService";
|
||||
import { SrefValidationError } from "../../services/dataExportService";
|
||||
|
||||
const harness = hookHarness();
|
||||
|
|
@ -48,18 +60,59 @@ 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 {
|
||||
return {
|
||||
filePath: JOURNAL.backupPath,
|
||||
filename: "profile_avant-migration.sref",
|
||||
envelope: {
|
||||
export_type: "transactions_with_categories",
|
||||
app_version: "0.17.2",
|
||||
format_version: 2,
|
||||
exported_at: "2026-10-01T10:00:00Z",
|
||||
data: { categories: [], suppliers: [], keywords: [], transactions: [] },
|
||||
},
|
||||
summary: {
|
||||
type: "transactions_with_categories",
|
||||
categoriesCount: 0,
|
||||
suppliersCount: 0,
|
||||
keywordsCount: 0,
|
||||
transactionsCount: 0,
|
||||
importSourcesCount: 0,
|
||||
importTemplatesCount: 0,
|
||||
formatVersion: 2,
|
||||
},
|
||||
unlinkedTransfers,
|
||||
};
|
||||
}
|
||||
|
||||
/** What `applyBackup` returns, the restore having unlinked `unlinkedTransfers`. */
|
||||
function resultOf(unlinkedTransfers: number): RestoreResult {
|
||||
return {
|
||||
revertedAt: "2026-11-04T12:00:00.000Z",
|
||||
outcome: { unlinkedTransfers, uncategorizedTransactions: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
/** One render of the mounted window. */
|
||||
const render = () => harness.render(() => CategoriesMigrationRestoreModal(PROPS));
|
||||
|
||||
/** « Restore » on the confirmation screen, clicked as the user does; resolves once the restore has answered. */
|
||||
async function confirm(): Promise<void> {
|
||||
const [button] = find(
|
||||
render(),
|
||||
(el) => el.type === "button" && texts(el).includes("t(settings.categoriesCard.restoreModal.confirm)"),
|
||||
);
|
||||
const label = (key: string) => `t(settings.categoriesCard.restoreModal.${key})`;
|
||||
|
||||
/** The buttons of the window whose text is the label `key`. */
|
||||
const buttons = (key: string) =>
|
||||
find(render(), (el) => el.type === "button" && texts(el).includes(label(key)));
|
||||
|
||||
/** Clicks the button labelled `key`, as the user does; resolves once its handler has answered. */
|
||||
async function click(key: string): Promise<void> {
|
||||
const [button] = buttons(key);
|
||||
expect(button, `a button « ${key} »`).toBeDefined();
|
||||
await (button.props.onClick as () => Promise<void>)();
|
||||
}
|
||||
|
||||
/** « Restore » on the confirmation screen: reads the file. */
|
||||
const confirm = () => click("confirm");
|
||||
|
||||
beforeAll(() => {
|
||||
vi.stubGlobal("document", { body: {} });
|
||||
});
|
||||
|
|
@ -70,30 +123,162 @@ afterAll(() => {
|
|||
|
||||
beforeEach(() => {
|
||||
harness.clear();
|
||||
restoreFromBackup.mockReset();
|
||||
service.readBackup.mockReset();
|
||||
service.applyBackup.mockReset();
|
||||
service.isFileEncrypted.mockReset();
|
||||
service.isFileEncrypted.mockResolvedValue(false);
|
||||
PROPS.onRestored.mockReset();
|
||||
PROPS.onClose.mockReset();
|
||||
});
|
||||
|
||||
describe("CategoriesMigrationRestoreModal — a backup the import boundary refuses (#518)", () => {
|
||||
it("shows the refusal's own translated text, neither parse_failed nor import_failed", async () => {
|
||||
restoreFromBackup.mockRejectedValue(
|
||||
service.readBackup.mockRejectedValue(
|
||||
new SrefValidationError("settings.dataManagement.import.errors.orphanSplitLines", {}),
|
||||
);
|
||||
|
||||
await confirm();
|
||||
|
||||
const shown = texts(render());
|
||||
expect(restoreFromBackup).toHaveBeenCalledWith(JOURNAL.backupPath, null);
|
||||
expect(service.readBackup).toHaveBeenCalledWith(JOURNAL.backupPath, null);
|
||||
expect(shown).toContain("t(settings.dataManagement.import.errors.orphanSplitLines[])");
|
||||
expect(shown.join(" ")).not.toMatch(/parse_failed|import_failed/);
|
||||
expect(service.applyBackup).not.toHaveBeenCalled();
|
||||
expect(PROPS.onRestored).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("a refusal at the head of the restore, after the second confirmation, is shown the same way", async () => {
|
||||
service.readBackup.mockResolvedValue(readingOf(0));
|
||||
service.applyBackup.mockRejectedValue(
|
||||
new SrefValidationError("settings.dataManagement.import.errors.danglingCategoryReference", {}),
|
||||
);
|
||||
|
||||
await confirm();
|
||||
await confirm();
|
||||
|
||||
expect(texts(render())).toContain("t(settings.dataManagement.import.errors.danglingCategoryReference[])");
|
||||
expect(PROPS.onRestored).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("witness: any other failure of the restore keeps its own message", async () => {
|
||||
restoreFromBackup.mockRejectedValue(new RestoreError("import_failed", "FOREIGN KEY constraint failed"));
|
||||
service.readBackup.mockResolvedValue(readingOf(0));
|
||||
service.applyBackup.mockRejectedValue(new RestoreError("import_failed", "FOREIGN KEY constraint failed"));
|
||||
|
||||
await confirm();
|
||||
await confirm();
|
||||
|
||||
expect(texts(render()).join(" ")).toContain("t(settings.categoriesCard.restoreModal.errors.import_failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("CategoriesMigrationRestoreModal — a second confirmation, then « Sauvegarde rétablie » (#521)", () => {
|
||||
it("the first « Rétablir » reads the file and restores nothing: the second confirmation opens", async () => {
|
||||
service.readBackup.mockResolvedValue(readingOf(0));
|
||||
|
||||
await confirm();
|
||||
|
||||
expect(service.readBackup).toHaveBeenCalledWith(JOURNAL.backupPath, null);
|
||||
expect(service.applyBackup).not.toHaveBeenCalled();
|
||||
const shown = texts(render());
|
||||
// The file read, the warning, and « Rétablir » again.
|
||||
expect(shown).toContain(JOURNAL.backupPath);
|
||||
expect(shown).toContain(label("warning"));
|
||||
expect(buttons("confirm")).toHaveLength(1);
|
||||
expect(buttons("cancel")).toHaveLength(1);
|
||||
// No transfer to unlink: nothing announced.
|
||||
expect(shown.join(" ")).not.toContain("unlinkedTransfersPreview");
|
||||
});
|
||||
|
||||
it.each([1, 3])("the second confirmation announces the %i Bilan transfer(s) the restore will unlink", async (count) => {
|
||||
service.readBackup.mockResolvedValue(readingOf(count));
|
||||
|
||||
await confirm();
|
||||
|
||||
expect(texts(render())).toContain(`t(settings.categoriesCard.restoreModal.unlinkedTransfersPreview[count=${count}])`);
|
||||
expect(service.applyBackup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("« Annuler » of the second confirmation closes the window without restoring", async () => {
|
||||
service.readBackup.mockResolvedValue(readingOf(2));
|
||||
|
||||
await confirm();
|
||||
await click("cancel");
|
||||
|
||||
expect(PROPS.onClose).toHaveBeenCalledTimes(1);
|
||||
expect(service.applyBackup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("the second « Rétablir » restores the file read, then shows « Sauvegarde rétablie » without reloading", async () => {
|
||||
const reading = readingOf(0);
|
||||
service.readBackup.mockResolvedValue(reading);
|
||||
service.applyBackup.mockResolvedValue(resultOf(0));
|
||||
|
||||
await confirm();
|
||||
await confirm();
|
||||
|
||||
expect(service.applyBackup).toHaveBeenCalledWith(reading.envelope, reading.filename);
|
||||
const shown = texts(render());
|
||||
expect(shown).toContain(label("doneTitle"));
|
||||
expect(shown).toContain(label("doneReload"));
|
||||
// The warning of the confirmation is gone, and no transfer was unlinked.
|
||||
expect(shown).not.toContain(label("warning"));
|
||||
expect(shown.join(" ")).not.toContain("unlinkedTransfers");
|
||||
// Only « Fermer » reloads.
|
||||
expect(PROPS.onRestored).not.toHaveBeenCalled();
|
||||
expect(buttons("confirm")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.each([1, 2])("« Sauvegarde rétablie » gives the number of transfers really unlinked (%i)", async (count) => {
|
||||
service.readBackup.mockResolvedValue(readingOf(5));
|
||||
service.applyBackup.mockResolvedValue(resultOf(count));
|
||||
|
||||
await confirm();
|
||||
await confirm();
|
||||
|
||||
expect(texts(render())).toContain(`t(settings.categoriesCard.restoreModal.unlinkedTransfers[count=${count}])`);
|
||||
});
|
||||
|
||||
it("« Fermer » reloads the app (onRestored), once", async () => {
|
||||
service.readBackup.mockResolvedValue(readingOf(0));
|
||||
service.applyBackup.mockResolvedValue(resultOf(0));
|
||||
|
||||
await confirm();
|
||||
await confirm();
|
||||
await click("close");
|
||||
|
||||
expect(PROPS.onRestored).toHaveBeenCalledTimes(1);
|
||||
expect(PROPS.onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("the X of « Sauvegarde rétablie » reloads too: the window never closes on stale pages", async () => {
|
||||
service.readBackup.mockResolvedValue(readingOf(0));
|
||||
service.applyBackup.mockResolvedValue(resultOf(0));
|
||||
|
||||
await confirm();
|
||||
await confirm();
|
||||
const [x] = find(render(), (el) => el.type === "button" && el.props["aria-label"] === label("close"));
|
||||
(x.props.onClick as () => void)();
|
||||
|
||||
expect(PROPS.onRestored).toHaveBeenCalledTimes(1);
|
||||
expect(PROPS.onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("an encrypted backup: the PIN first, then the reading and the second confirmation", async () => {
|
||||
service.isFileEncrypted.mockResolvedValue(true);
|
||||
service.readBackup.mockResolvedValue(readingOf(1));
|
||||
|
||||
await confirm();
|
||||
// The PIN prompt: nothing read yet.
|
||||
expect(texts(render())).toContain(label("passwordLabel"));
|
||||
expect(service.readBackup).not.toHaveBeenCalled();
|
||||
|
||||
// The PIN typed, then « Rétablir » of the prompt.
|
||||
const [input] = find(render(), (el) => el.type === "input");
|
||||
(input.props.onChange as (e: { target: { value: string } }) => void)({ target: { value: "1234" } });
|
||||
await confirm();
|
||||
|
||||
expect(service.readBackup).toHaveBeenCalledWith(JOURNAL.backupPath, "1234");
|
||||
expect(service.applyBackup).not.toHaveBeenCalled();
|
||||
expect(texts(render())).toContain("t(settings.categoriesCard.restoreModal.unlinkedTransfersPreview[count=1])");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
95
src/components/settings/DataManagementCard.render.test.tsx
Normal file
95
src/components/settings/DataManagementCard.render.test.tsx
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
// DataManagementCard — what the card says around a restore (#521): the
|
||||
// confirmation announces the Bilan transfers the restore will unlink, and the
|
||||
// success message gives the number it really unlinked. The two hooks of the
|
||||
// card are fakes whose state the test sets. No jsdom: react-dom/server renders
|
||||
// the initial markup; the confirmation is a portal, so `createPortal` becomes
|
||||
// the identity and `document` a stub.
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest";
|
||||
import type { ReactNode } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
|
||||
vi.mock("react-dom", async (orig) => ({
|
||||
...(await orig<typeof import("react-dom")>()),
|
||||
createPortal: (children: ReactNode) => children,
|
||||
}));
|
||||
const hooks = vi.hoisted(() => ({ importState: {} as Record<string, unknown> }));
|
||||
vi.mock("../../hooks/useDataExport", () => ({
|
||||
useDataExport: () => ({ state: { status: "idle", error: null }, performExport: vi.fn(), reset: vi.fn() }),
|
||||
}));
|
||||
vi.mock("../../hooks/useDataImport", () => ({
|
||||
useDataImport: () => ({
|
||||
state: hooks.importState,
|
||||
pickAndRead: vi.fn(),
|
||||
readWithPassword: vi.fn(),
|
||||
executeImport: vi.fn(),
|
||||
reset: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
import DataManagementCard from "./DataManagementCard";
|
||||
|
||||
const IDLE = {
|
||||
status: "idle",
|
||||
filePath: null,
|
||||
summary: null,
|
||||
parsedData: null,
|
||||
importType: null,
|
||||
unlinkedTransfers: 0,
|
||||
outcome: null,
|
||||
error: null,
|
||||
};
|
||||
|
||||
const SUMMARY = {
|
||||
type: "transactions_only",
|
||||
categoriesCount: 0,
|
||||
suppliersCount: 0,
|
||||
keywordsCount: 0,
|
||||
transactionsCount: 12,
|
||||
importSourcesCount: 0,
|
||||
importTemplatesCount: 0,
|
||||
formatVersion: 2,
|
||||
};
|
||||
|
||||
beforeAll(() => {
|
||||
vi.stubGlobal("document", { body: {} });
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
hooks.importState = { ...IDLE };
|
||||
});
|
||||
|
||||
const markup = () => renderToStaticMarkup(<DataManagementCard />);
|
||||
|
||||
describe("DataManagementCard — the Bilan transfers of a restore (#521)", () => {
|
||||
it.each(["confirming", "importing"])("the confirmation (%s) announces the transfers the hook counted", (status) => {
|
||||
hooks.importState = {
|
||||
...IDLE,
|
||||
status,
|
||||
filePath: "/tmp/backup.json",
|
||||
summary: SUMMARY,
|
||||
parsedData: { transactions: [] },
|
||||
importType: "transactions_only",
|
||||
unlinkedTransfers: 3,
|
||||
};
|
||||
expect(markup()).toContain("t(settings.dataManagement.import.unlinkedTransfersPreview[count=3])");
|
||||
});
|
||||
|
||||
it.each([1, 2])("the success message gives the number really unlinked (%i)", (count) => {
|
||||
hooks.importState = { ...IDLE, status: "success", outcome: { unlinkedTransfers: count, uncategorizedTransactions: 0 } };
|
||||
const html = markup();
|
||||
expect(html).toContain("t(settings.dataManagement.import.success)");
|
||||
expect(html).toContain(`t(settings.dataManagement.import.unlinkedTransfers[count=${count}])`);
|
||||
});
|
||||
|
||||
it("no transfer unlinked: the success message alone", () => {
|
||||
hooks.importState = { ...IDLE, status: "success", outcome: { unlinkedTransfers: 0, uncategorizedTransactions: 4 } };
|
||||
const html = markup();
|
||||
expect(html).toContain("t(settings.dataManagement.import.success)");
|
||||
expect(html).not.toContain("unlinkedTransfers");
|
||||
});
|
||||
});
|
||||
|
|
@ -282,9 +282,20 @@ export default function DataManagementCard() {
|
|||
|
||||
{/* Import feedback */}
|
||||
{importHook.state.status === "success" && (
|
||||
<div className="flex items-center gap-2 text-[var(--positive)] text-sm">
|
||||
<CheckCircle size={14} />
|
||||
{t("settings.dataManagement.import.success")}
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 text-[var(--positive)] text-sm">
|
||||
<CheckCircle size={14} />
|
||||
{t("settings.dataManagement.import.success")}
|
||||
</div>
|
||||
{/* The Bilan transfers the restore unlinked, the real number (#521) */}
|
||||
{(importHook.state.outcome?.unlinkedTransfers ?? 0) > 0 && (
|
||||
<div className="flex items-center gap-2 text-[var(--negative)] text-sm">
|
||||
<AlertCircle size={14} />
|
||||
{t("settings.dataManagement.import.unlinkedTransfers", {
|
||||
count: importHook.state.outcome?.unlinkedTransfers,
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{importHook.state.status === "error" && (
|
||||
|
|
@ -311,6 +322,7 @@ export default function DataManagementCard() {
|
|||
<ImportConfirmModal
|
||||
summary={importHook.state.summary}
|
||||
importType={importHook.state.importType}
|
||||
unlinkedTransfers={importHook.state.unlinkedTransfers}
|
||||
isImporting={false}
|
||||
onConfirm={importHook.executeImport}
|
||||
onCancel={importHook.reset}
|
||||
|
|
@ -320,6 +332,7 @@ export default function DataManagementCard() {
|
|||
<ImportConfirmModal
|
||||
summary={importHook.state.summary}
|
||||
importType={importHook.state.importType}
|
||||
unlinkedTransfers={importHook.state.unlinkedTransfers}
|
||||
isImporting={true}
|
||||
onConfirm={() => {}}
|
||||
onCancel={() => {}}
|
||||
|
|
|
|||
66
src/components/settings/ImportConfirmModal.render.test.tsx
Normal file
66
src/components/settings/ImportConfirmModal.render.test.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// 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.
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
|
||||
import type { ReactNode } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
|
||||
vi.mock("react-dom", async (orig) => ({
|
||||
...(await orig<typeof import("react-dom")>()),
|
||||
createPortal: (children: ReactNode) => children,
|
||||
}));
|
||||
|
||||
import ImportConfirmModal from "./ImportConfirmModal";
|
||||
import type { ExportMode, ImportSummary } from "../../services/dataExportService";
|
||||
|
||||
const SUMMARY: ImportSummary = {
|
||||
type: "transactions_with_categories",
|
||||
categoriesCount: 3,
|
||||
suppliersCount: 0,
|
||||
keywordsCount: 0,
|
||||
transactionsCount: 12,
|
||||
importSourcesCount: 0,
|
||||
importTemplatesCount: 0,
|
||||
formatVersion: 2,
|
||||
};
|
||||
|
||||
beforeAll(() => {
|
||||
vi.stubGlobal("document", { body: {} });
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
const markup = (importType: ExportMode, unlinkedTransfers: number) =>
|
||||
renderToStaticMarkup(
|
||||
<ImportConfirmModal
|
||||
summary={{ ...SUMMARY, type: importType }}
|
||||
importType={importType}
|
||||
unlinkedTransfers={unlinkedTransfers}
|
||||
isImporting={false}
|
||||
onConfirm={vi.fn()}
|
||||
onCancel={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
describe("ImportConfirmModal — the Bilan transfers the restore will unlink (#521)", () => {
|
||||
it.each<[ExportMode, number]>([
|
||||
["transactions_with_categories", 1],
|
||||
["transactions_only", 4],
|
||||
])("%s: announces the %i transfer(s), next to the warning", (importType, count) => {
|
||||
const html = markup(importType, count);
|
||||
expect(html).toContain(`t(settings.dataManagement.import.unlinkedTransfersPreview[count=${count}])`);
|
||||
expect(html).toContain("t(settings.dataManagement.import.irreversibleWarning)");
|
||||
});
|
||||
|
||||
it("announces nothing when no transfer would be unlinked", () => {
|
||||
const html = markup("transactions_only", 0);
|
||||
expect(html).not.toContain("unlinkedTransfersPreview");
|
||||
expect(html).toContain("t(settings.dataManagement.import.irreversibleWarning)");
|
||||
});
|
||||
});
|
||||
|
|
@ -7,6 +7,8 @@ import type { ImportSummary, ExportMode } from "../../services/dataExportService
|
|||
interface ImportConfirmModalProps {
|
||||
summary: ImportSummary;
|
||||
importType: ExportMode;
|
||||
/** Bilan transfers the restore will unlink, read in the profile (#521). */
|
||||
unlinkedTransfers: number;
|
||||
isImporting: boolean;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
|
|
@ -15,6 +17,7 @@ interface ImportConfirmModalProps {
|
|||
export default function ImportConfirmModal({
|
||||
summary,
|
||||
importType,
|
||||
unlinkedTransfers,
|
||||
isImporting,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
|
|
@ -136,8 +139,16 @@ export default function ImportConfirmModal({
|
|||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Warning */}
|
||||
<div className="bg-[var(--negative)]/10 border border-[var(--negative)]/30 rounded-lg p-3">
|
||||
{/* Warning, and what the restore loses for good: the Bilan transfers
|
||||
whose transaction does not come back as it was (#521) */}
|
||||
<div className="bg-[var(--negative)]/10 border border-[var(--negative)]/30 rounded-lg p-3 space-y-2">
|
||||
{unlinkedTransfers > 0 && (
|
||||
<p className="text-sm text-[var(--negative)]">
|
||||
{t("settings.dataManagement.import.unlinkedTransfersPreview", {
|
||||
count: unlinkedTransfers,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-[var(--negative)]">
|
||||
{t("settings.dataManagement.import.irreversibleWarning")}
|
||||
</p>
|
||||
|
|
|
|||
157
src/hooks/useDataImport.test.ts
Normal file
157
src/hooks/useDataImport.test.ts
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
// useDataImport — what the « Gestion des données » card learns before and
|
||||
// after a restore (#521): the Bilan transfers the restore would unlink, counted
|
||||
// once the file is read, before the confirmation opens; and the outcome of the
|
||||
// committed restore, which the success message reads.
|
||||
//
|
||||
// No jsdom: the hook runs as a plain function under the shared harness
|
||||
// (src/test/hookHarness.ts, #409). Its reducer is applied, but nothing renders
|
||||
// again by itself: the test renders after each call to read the new state and
|
||||
// the callbacks of that render.
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
|
||||
vi.mock("react-i18next", async () => (await import("../test/i18nMock")).i18nMock());
|
||||
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
const restore = vi.hoisted(() => ({
|
||||
importCategoriesOnly: vi.fn(),
|
||||
importTransactionsWithCategories: vi.fn(),
|
||||
importTransactionsOnly: vi.fn(),
|
||||
previewUnlinkedTransfers: vi.fn(),
|
||||
}));
|
||||
vi.mock("../services/dataRestoreService", () => restore);
|
||||
|
||||
import { hookHarness } from "../test/hookHarness";
|
||||
import { useDataImport } from "./useDataImport";
|
||||
import { serializeToJson, type ExportMode } from "../services/dataExportService";
|
||||
|
||||
const harness = hookHarness();
|
||||
|
||||
/** One render of the mounted hook. */
|
||||
const render = () => harness.render(() => useDataImport());
|
||||
|
||||
const TRANSACTION = {
|
||||
id: 1,
|
||||
date: "2026-10-04",
|
||||
description: "VIREMENT CELI",
|
||||
amount: -500,
|
||||
category_id: null,
|
||||
category_name: null,
|
||||
original_description: null,
|
||||
notes: null,
|
||||
is_manually_categorized: 0,
|
||||
is_split: 0,
|
||||
parent_transaction_id: null,
|
||||
};
|
||||
|
||||
/** 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");
|
||||
}
|
||||
|
||||
/** The file the user picks: `content`, encrypted or not. */
|
||||
function picking(content: string, encrypted = false) {
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === "pick_import_file") return encrypted ? "/tmp/backup.sref" : "/tmp/backup.json";
|
||||
if (cmd === "is_file_encrypted") return encrypted;
|
||||
if (cmd === "read_import_file") return content;
|
||||
throw new Error(`unexpected invoke: ${cmd}`);
|
||||
});
|
||||
}
|
||||
|
||||
const NO_OUTCOME = { unlinkedTransfers: 0, uncategorizedTransactions: 0 };
|
||||
|
||||
beforeEach(() => {
|
||||
harness.clear();
|
||||
invoke.mockReset();
|
||||
for (const fn of Object.values(restore)) fn.mockReset();
|
||||
restore.previewUnlinkedTransfers.mockResolvedValue(0);
|
||||
restore.importCategoriesOnly.mockResolvedValue(NO_OUTCOME);
|
||||
restore.importTransactionsWithCategories.mockResolvedValue(NO_OUTCOME);
|
||||
restore.importTransactionsOnly.mockResolvedValue(NO_OUTCOME);
|
||||
});
|
||||
|
||||
describe("useDataImport — the Bilan transfers a restore would unlink (#521)", () => {
|
||||
it.each<ExportMode>(["transactions_with_categories", "transactions_only"])(
|
||||
"%s: counted once the file is read, before the confirmation opens",
|
||||
async (mode) => {
|
||||
picking(backupOf(mode));
|
||||
restore.previewUnlinkedTransfers.mockResolvedValue(2);
|
||||
|
||||
await render().pickAndRead();
|
||||
|
||||
const { state } = render();
|
||||
expect(state.status).toBe("confirming");
|
||||
expect(state.unlinkedTransfers).toBe(2);
|
||||
// Counted on the transactions of the file, and nothing restored yet.
|
||||
expect(restore.previewUnlinkedTransfers).toHaveBeenCalledWith([TRANSACTION]);
|
||||
expect(restore.importTransactionsWithCategories).not.toHaveBeenCalled();
|
||||
expect(restore.importTransactionsOnly).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("categories only: no transaction is deleted, so nothing is counted", async () => {
|
||||
picking(backupOf("categories_only"));
|
||||
|
||||
await render().pickAndRead();
|
||||
|
||||
const { state } = render();
|
||||
expect(state.status).toBe("confirming");
|
||||
expect(state.unlinkedTransfers).toBe(0);
|
||||
expect(restore.previewUnlinkedTransfers).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("an encrypted file: counted once decrypted", async () => {
|
||||
picking(backupOf("transactions_only"), true);
|
||||
restore.previewUnlinkedTransfers.mockResolvedValue(1);
|
||||
|
||||
await render().pickAndRead();
|
||||
expect(render().state.status).toBe("needsPassword");
|
||||
expect(restore.previewUnlinkedTransfers).not.toHaveBeenCalled();
|
||||
|
||||
await render().readWithPassword("secret-password");
|
||||
|
||||
const { state } = render();
|
||||
expect(state.status).toBe("confirming");
|
||||
expect(state.unlinkedTransfers).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useDataImport — the outcome of the restore reaches the success state (#521)", () => {
|
||||
it.each<[ExportMode, keyof typeof restore]>([
|
||||
["transactions_with_categories", "importTransactionsWithCategories"],
|
||||
["transactions_only", "importTransactionsOnly"],
|
||||
["categories_only", "importCategoriesOnly"],
|
||||
])("%s: IMPORT_SUCCESS carries what %s returned", async (mode, entry) => {
|
||||
const outcome = { unlinkedTransfers: 3, uncategorizedTransactions: 1 };
|
||||
restore[entry].mockResolvedValue(outcome);
|
||||
picking(backupOf(mode));
|
||||
await render().pickAndRead();
|
||||
|
||||
await render().executeImport();
|
||||
|
||||
const { state } = render();
|
||||
expect(restore[entry]).toHaveBeenCalledTimes(1);
|
||||
expect(state.status).toBe("success");
|
||||
expect(state.outcome).toEqual(outcome);
|
||||
expect(harness.dispatch).toHaveBeenCalledWith({ type: "IMPORT_SUCCESS", outcome });
|
||||
});
|
||||
|
||||
it("a new file starts without the outcome of the last restore", async () => {
|
||||
restore.importTransactionsOnly.mockResolvedValue({ unlinkedTransfers: 2, uncategorizedTransactions: 0 });
|
||||
picking(backupOf("transactions_only"));
|
||||
await render().pickAndRead();
|
||||
await render().executeImport();
|
||||
expect(render().state.outcome?.unlinkedTransfers).toBe(2);
|
||||
|
||||
await render().pickAndRead();
|
||||
|
||||
expect(render().state.outcome).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -12,6 +12,8 @@ import {
|
|||
importCategoriesOnly,
|
||||
importTransactionsWithCategories,
|
||||
importTransactionsOnly,
|
||||
previewUnlinkedTransfers,
|
||||
type RestoreOutcome,
|
||||
} from "../services/dataRestoreService";
|
||||
|
||||
type ImportStatus =
|
||||
|
|
@ -29,6 +31,10 @@ interface ImportState {
|
|||
summary: ImportSummary | null;
|
||||
parsedData: ExportEnvelope["data"] | null;
|
||||
importType: ExportEnvelope["export_type"] | null;
|
||||
/** Bilan transfers the restore would unlink, announced by the confirmation (#521). */
|
||||
unlinkedTransfers: number;
|
||||
/** What the committed restore did, for the success message (#521). */
|
||||
outcome: RestoreOutcome | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
|
|
@ -41,9 +47,10 @@ type ImportAction =
|
|||
summary: ImportSummary;
|
||||
data: ExportEnvelope["data"];
|
||||
importType: ExportEnvelope["export_type"];
|
||||
unlinkedTransfers: number;
|
||||
}
|
||||
| { type: "IMPORT_START" }
|
||||
| { type: "IMPORT_SUCCESS" }
|
||||
| { type: "IMPORT_SUCCESS"; outcome: RestoreOutcome }
|
||||
| { type: "IMPORT_ERROR"; error: string }
|
||||
| { type: "RESET" };
|
||||
|
||||
|
|
@ -53,6 +60,8 @@ const initialState: ImportState = {
|
|||
summary: null,
|
||||
parsedData: null,
|
||||
importType: null,
|
||||
unlinkedTransfers: 0,
|
||||
outcome: null,
|
||||
error: null,
|
||||
};
|
||||
|
||||
|
|
@ -70,12 +79,13 @@ function reducer(state: ImportState, action: ImportAction): ImportState {
|
|||
summary: action.summary,
|
||||
parsedData: action.data,
|
||||
importType: action.importType,
|
||||
unlinkedTransfers: action.unlinkedTransfers,
|
||||
error: null,
|
||||
};
|
||||
case "IMPORT_START":
|
||||
return { ...state, status: "importing", error: null };
|
||||
case "IMPORT_SUCCESS":
|
||||
return { ...state, status: "success", error: null };
|
||||
return { ...state, status: "success", outcome: action.outcome, error: null };
|
||||
case "IMPORT_ERROR":
|
||||
return { ...state, status: "error", error: action.error };
|
||||
case "RESET":
|
||||
|
|
@ -110,6 +120,19 @@ function parseContent(
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The Bilan transfers a restore of `data` would unlink, read before the
|
||||
* confirmation opens (#521): in the two modes that carry transactions only, a
|
||||
* restore of the categories deleting no transaction.
|
||||
*/
|
||||
async function previewTransfers(
|
||||
importType: ExportEnvelope["export_type"],
|
||||
data: ExportEnvelope["data"]
|
||||
): Promise<number> {
|
||||
if (importType === "categories_only") return 0;
|
||||
return previewUnlinkedTransfers(data.transactions);
|
||||
}
|
||||
|
||||
export function useDataImport() {
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const { t } = useTranslation();
|
||||
|
|
@ -152,7 +175,8 @@ export function useDataImport() {
|
|||
});
|
||||
|
||||
const { summary, data, importType } = parseContent(content, filePath);
|
||||
dispatch({ type: "CONFIRMING", filePath, summary, data, importType });
|
||||
const unlinkedTransfers = await previewTransfers(importType, data);
|
||||
dispatch({ type: "CONFIRMING", filePath, summary, data, importType, unlinkedTransfers });
|
||||
} catch (e) {
|
||||
dispatch({ type: "IMPORT_ERROR", error: describeError(e) });
|
||||
}
|
||||
|
|
@ -169,7 +193,15 @@ export function useDataImport() {
|
|||
});
|
||||
|
||||
const { summary, data, importType } = parseContent(content, state.filePath);
|
||||
dispatch({ type: "CONFIRMING", filePath: state.filePath, summary, data, importType });
|
||||
const unlinkedTransfers = await previewTransfers(importType, data);
|
||||
dispatch({
|
||||
type: "CONFIRMING",
|
||||
filePath: state.filePath,
|
||||
summary,
|
||||
data,
|
||||
importType,
|
||||
unlinkedTransfers,
|
||||
});
|
||||
} catch (e) {
|
||||
dispatch({ type: "IMPORT_ERROR", error: describeError(e) });
|
||||
}
|
||||
|
|
@ -182,18 +214,19 @@ export function useDataImport() {
|
|||
dispatch({ type: "IMPORT_START" });
|
||||
const filename = state.filePath?.split(/[/\\]/).pop() ?? "unknown";
|
||||
try {
|
||||
let outcome: RestoreOutcome;
|
||||
switch (state.importType) {
|
||||
case "categories_only":
|
||||
await importCategoriesOnly(state.parsedData);
|
||||
outcome = await importCategoriesOnly(state.parsedData);
|
||||
break;
|
||||
case "transactions_with_categories":
|
||||
await importTransactionsWithCategories(state.parsedData, filename);
|
||||
outcome = await importTransactionsWithCategories(state.parsedData, filename);
|
||||
break;
|
||||
case "transactions_only":
|
||||
await importTransactionsOnly(state.parsedData, filename);
|
||||
outcome = await importTransactionsOnly(state.parsedData, filename);
|
||||
break;
|
||||
}
|
||||
dispatch({ type: "IMPORT_SUCCESS" });
|
||||
dispatch({ type: "IMPORT_SUCCESS", outcome });
|
||||
} catch (e) {
|
||||
dispatch({ type: "IMPORT_ERROR", error: describeError(e) });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -777,11 +777,16 @@
|
|||
"replaceButton": "Replace Data",
|
||||
"success": "Import completed successfully",
|
||||
"tryAgain": "Try again",
|
||||
"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.",
|
||||
"unlinkedTransfers_one": "{{count}} Balance transfer did not find its transaction and was unlinked.",
|
||||
"unlinkedTransfers_other": "{{count}} Balance transfers did not find their transaction and were unlinked.",
|
||||
"errors": {
|
||||
"unsupportedAmountMode": "This file cannot be imported: the source \"{{name}}\" was saved with an amount mode this version does not support ({{value}}). Nothing has been modified.",
|
||||
"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."
|
||||
"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."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -821,6 +826,13 @@
|
|||
"close": "Close",
|
||||
"retry": "Try again",
|
||||
"restoring": "Restoring your profile — do not close the application...",
|
||||
"reading": "Reading the backup...",
|
||||
"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",
|
||||
"doneReload": "The app will reload.",
|
||||
"unlinkedTransfers_one": "{{count}} Balance transfer did not find its transaction and was unlinked.",
|
||||
"unlinkedTransfers_other": "{{count}} Balance transfers did not find their transaction and were unlinked.",
|
||||
"errors": {
|
||||
"file_missing": "The backup file was not found at the recorded location.",
|
||||
"read_failed": "The backup file could not be read.",
|
||||
|
|
|
|||
|
|
@ -777,11 +777,16 @@
|
|||
"replaceButton": "Remplacer les données",
|
||||
"success": "Import terminé avec succès",
|
||||
"tryAgain": "Réessayer",
|
||||
"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.",
|
||||
"unlinkedTransfers_one": "{{count}} transfert du Bilan n'a pas retrouvé sa transaction et a été délié.",
|
||||
"unlinkedTransfers_other": "{{count}} transferts du Bilan n'ont pas retrouvé leur transaction et ont été déliés.",
|
||||
"errors": {
|
||||
"unsupportedAmountMode": "Ce fichier ne peut pas être importé : la source « {{name}} » a été enregistrée avec un mode de montant que cette version ne prend pas en charge ({{value}}). Rien n'a été modifié.",
|
||||
"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é."
|
||||
"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é."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -821,6 +826,13 @@
|
|||
"close": "Fermer",
|
||||
"retry": "Réessayer",
|
||||
"restoring": "Rétablissement en cours — ne fermez pas l'application...",
|
||||
"reading": "Lecture de la sauvegarde en cours...",
|
||||
"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",
|
||||
"doneReload": "L'application va se recharger.",
|
||||
"unlinkedTransfers_one": "{{count}} transfert du Bilan n'a pas retrouvé sa transaction et a été délié.",
|
||||
"unlinkedTransfers_other": "{{count}} transferts du Bilan n'ont pas retrouvé leur transaction et ont été déliés.",
|
||||
"errors": {
|
||||
"file_missing": "Le fichier de sauvegarde est introuvable à l'emplacement enregistré.",
|
||||
"read_failed": "Le fichier de sauvegarde n'a pas pu être lu.",
|
||||
|
|
|
|||
|
|
@ -1,17 +1,28 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// `restoreFromBackup` reads its file through `read_import_file`, then writes it
|
||||
// back through dataRestoreService: both are fakes here, the parse is real.
|
||||
const { invoke, importTransactionsWithCategories } = vi.hoisted(() => ({
|
||||
// `readBackup` reads its file through `read_import_file` and counts the Bilan
|
||||
// transfers through dataRestoreService; `applyBackup` writes the file back
|
||||
// through dataRestoreService, then the preferences. All are fakes here, the
|
||||
// parse is real.
|
||||
const { invoke, importTransactionsWithCategories, previewUnlinkedTransfers, preferences } = vi.hoisted(() => ({
|
||||
invoke: vi.fn(),
|
||||
importTransactionsWithCategories: vi.fn(),
|
||||
previewUnlinkedTransfers: vi.fn(),
|
||||
preferences: new Map<string, string>(),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
vi.mock("./dataRestoreService", () => ({ importTransactionsWithCategories }));
|
||||
vi.mock("./dataRestoreService", () => ({ importTransactionsWithCategories, previewUnlinkedTransfers }));
|
||||
vi.mock("./userPreferenceService", () => ({
|
||||
getPreference: vi.fn(async (key: string) => preferences.get(key) ?? null),
|
||||
setPreference: vi.fn(async (key: string, value: string) => {
|
||||
preferences.set(key, value);
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
applyBackup,
|
||||
isWithinBannerWindow,
|
||||
restoreFromBackup,
|
||||
readBackup,
|
||||
RestoreError,
|
||||
shouldShowBanner,
|
||||
type RestorableMigrationJournal,
|
||||
|
|
@ -119,79 +130,166 @@ describe("shouldShowBanner", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("restoreFromBackup lets a refusal of the file through as it is (#518)", () => {
|
||||
const ORPHAN = "settings.dataManagement.import.errors.orphanSplitLines";
|
||||
const PATH = "/tmp/backup.sref";
|
||||
const ORPHAN = "settings.dataManagement.import.errors.orphanSplitLines";
|
||||
const PATH = "/tmp/profile_avant-migration.sref";
|
||||
|
||||
/** 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 },
|
||||
"0.17.2",
|
||||
);
|
||||
/** A split line that names a row the backup does not hold. */
|
||||
const ORPHAN_BACKUP = backup([
|
||||
{
|
||||
id: 2,
|
||||
date: "2026-03-10",
|
||||
description: "EPICERIE METRO",
|
||||
amount: -50,
|
||||
category_id: null,
|
||||
category_name: null,
|
||||
original_description: null,
|
||||
notes: null,
|
||||
is_manually_categorized: 0,
|
||||
is_split: 1,
|
||||
parent_transaction_id: 9,
|
||||
},
|
||||
]);
|
||||
/** 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 },
|
||||
"0.17.2",
|
||||
);
|
||||
|
||||
function reading(content: string) {
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === "read_import_file") return content;
|
||||
throw new Error(`unexpected invoke: ${cmd}`);
|
||||
});
|
||||
}
|
||||
/** One transaction of a backup. */
|
||||
const transaction = (id: number, parent: number | null = null) => ({
|
||||
id,
|
||||
date: "2026-03-10",
|
||||
description: "EPICERIE METRO",
|
||||
amount: -50,
|
||||
category_id: null,
|
||||
category_name: null,
|
||||
original_description: null,
|
||||
notes: null,
|
||||
is_manually_categorized: 0,
|
||||
is_split: parent === null ? 0 : 1,
|
||||
parent_transaction_id: parent,
|
||||
});
|
||||
|
||||
/** What `restoreFromBackup` rejects with. */
|
||||
async function failure(): Promise<unknown> {
|
||||
return restoreFromBackup(PATH, null).then(
|
||||
() => expect.unreachable("the restore should have failed"),
|
||||
(e: unknown) => e,
|
||||
);
|
||||
}
|
||||
/** A split line that names a row the backup does not hold. */
|
||||
const ORPHAN_BACKUP = backup([transaction(2, 9)]);
|
||||
|
||||
beforeEach(() => {
|
||||
invoke.mockReset();
|
||||
importTransactionsWithCategories.mockReset();
|
||||
function readingFile(content: string) {
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === "read_import_file") return content;
|
||||
throw new Error(`unexpected invoke: ${cmd}`);
|
||||
});
|
||||
}
|
||||
|
||||
/** What `run` rejects with. */
|
||||
async function failureOf(run: () => Promise<unknown>): Promise<unknown> {
|
||||
return run().then(
|
||||
() => expect.unreachable("the call should have failed"),
|
||||
(e: unknown) => e,
|
||||
);
|
||||
}
|
||||
|
||||
/** The envelope of `content`, as `readBackup` returns it. */
|
||||
async function envelopeOf(content: string) {
|
||||
readingFile(content);
|
||||
return (await readBackup(PATH, null)).envelope;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
invoke.mockReset();
|
||||
importTransactionsWithCategories.mockReset();
|
||||
previewUnlinkedTransfers.mockReset();
|
||||
previewUnlinkedTransfers.mockResolvedValue(0);
|
||||
preferences.clear();
|
||||
});
|
||||
|
||||
describe("readBackup reads the backup and writes nothing (#521)", () => {
|
||||
it("returns the envelope, its summary, the file and the Bilan transfers the restore would unlink", async () => {
|
||||
const content = backup([transaction(1), transaction(2, 1)]);
|
||||
readingFile(content);
|
||||
previewUnlinkedTransfers.mockResolvedValue(2);
|
||||
|
||||
const reading = await readBackup(PATH, "1234");
|
||||
|
||||
expect(invoke).toHaveBeenCalledWith("read_import_file", { filePath: PATH, password: "1234" });
|
||||
expect(reading.filePath).toBe(PATH);
|
||||
expect(reading.filename).toBe("profile_avant-migration.sref");
|
||||
expect(reading.envelope.export_type).toBe("transactions_with_categories");
|
||||
expect(reading.summary.transactionsCount).toBe(2);
|
||||
expect(reading.unlinkedTransfers).toBe(2);
|
||||
// Counted on the transactions of the file.
|
||||
expect(previewUnlinkedTransfers).toHaveBeenCalledWith(reading.envelope.data.transactions);
|
||||
expect(importTransactionsWithCategories).not.toHaveBeenCalled();
|
||||
expect(preferences.size).toBe(0);
|
||||
});
|
||||
|
||||
it("names the file from a Windows path too", async () => {
|
||||
readingFile(backup([]));
|
||||
const reading = await readBackup("C:\\Users\\x\\backups\\avant.sref", null);
|
||||
expect(reading.filename).toBe("avant.sref");
|
||||
});
|
||||
|
||||
it("refuses a file that is not a full backup, before counting anything", async () => {
|
||||
readingFile(serializeToJson("categories_only", { categories: [], suppliers: [], keywords: [] }, "0.17.2"));
|
||||
const error = await failureOf(() => readBackup(PATH, null));
|
||||
expect(error).toBeInstanceOf(RestoreError);
|
||||
expect((error as RestoreError).code).toBe("wrong_envelope_type");
|
||||
expect(previewUnlinkedTransfers).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Decryption failed: aead::Error", "wrong_password"],
|
||||
["A password is required for this file", "needs_password"],
|
||||
["No such file or directory", "read_failed"],
|
||||
])("a read that fails with « %s » is a RestoreError %s", async (message, code) => {
|
||||
invoke.mockRejectedValue(new Error(message));
|
||||
const error = await failureOf(() => readBackup(PATH, null));
|
||||
expect(error).toBeInstanceOf(RestoreError);
|
||||
expect((error as RestoreError).code).toBe(code);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyBackup restores the backup read and hands back what the restore did (#521)", () => {
|
||||
it("restores the envelope under its file name, then marks the migration reverted", async () => {
|
||||
preferences.set(
|
||||
"last_categories_migration",
|
||||
JSON.stringify({ timestamp: "2026-10-01T10:00:00Z", backupPath: PATH }),
|
||||
);
|
||||
const envelope = await envelopeOf(backup([transaction(1)]));
|
||||
importTransactionsWithCategories.mockResolvedValue({ unlinkedTransfers: 3, uncategorizedTransactions: 1 });
|
||||
|
||||
const result = await applyBackup(envelope, "profile_avant-migration.sref");
|
||||
|
||||
expect(importTransactionsWithCategories).toHaveBeenCalledWith(envelope.data, "profile_avant-migration.sref");
|
||||
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("a failed restore marks nothing", async () => {
|
||||
const envelope = await envelopeOf(backup([]));
|
||||
importTransactionsWithCategories.mockRejectedValue(new Error("FOREIGN KEY constraint failed"));
|
||||
|
||||
const error = await failureOf(() => applyBackup(envelope, "backup.sref"));
|
||||
|
||||
expect(error).toBeInstanceOf(RestoreError);
|
||||
expect((error as RestoreError).code).toBe("import_failed");
|
||||
expect(preferences.has("categories_schema_version")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readBackup and applyBackup let a refusal of the file through as it is (#518)", () => {
|
||||
it("a file the parse refuses reaches the window as the SrefValidationError it is, with nothing restored", async () => {
|
||||
reading(ORPHAN_BACKUP);
|
||||
const error = await failure();
|
||||
readingFile(ORPHAN_BACKUP);
|
||||
const error = await failureOf(() => readBackup(PATH, null));
|
||||
expect(error).toBeInstanceOf(SrefValidationError);
|
||||
expect((error as SrefValidationError).i18nKey).toBe(ORPHAN);
|
||||
expect(importTransactionsWithCategories).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("a refusal raised at the head of the restore is not wrapped either", async () => {
|
||||
reading(backup([]));
|
||||
const envelope = await envelopeOf(backup([]));
|
||||
importTransactionsWithCategories.mockRejectedValue(new SrefValidationError(ORPHAN, {}));
|
||||
const error = await failure();
|
||||
const error = await failureOf(() => applyBackup(envelope, "backup.sref"));
|
||||
expect(error).toBeInstanceOf(SrefValidationError);
|
||||
expect((error as SrefValidationError).i18nKey).toBe(ORPHAN);
|
||||
});
|
||||
|
||||
it("witness: any other failure is still a RestoreError, parse_failed or import_failed", async () => {
|
||||
reading("not json");
|
||||
const parse = await failure();
|
||||
readingFile("not json");
|
||||
const parse = await failureOf(() => readBackup(PATH, null));
|
||||
expect(parse).toBeInstanceOf(RestoreError);
|
||||
expect((parse as RestoreError).code).toBe("parse_failed");
|
||||
|
||||
reading(backup([]));
|
||||
const envelope = await envelopeOf(backup([]));
|
||||
importTransactionsWithCategories.mockRejectedValue(new Error("FOREIGN KEY constraint failed"));
|
||||
const restore = await failure();
|
||||
const restore = await failureOf(() => applyBackup(envelope, "backup.sref"));
|
||||
expect(restore).toBeInstanceOf(RestoreError);
|
||||
expect((restore as RestoreError).code).toBe("import_failed");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,15 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { parseImportedJson, SrefValidationError } from "./dataExportService";
|
||||
import { importTransactionsWithCategories } from "./dataRestoreService";
|
||||
import {
|
||||
parseImportedJson,
|
||||
SrefValidationError,
|
||||
type ExportEnvelope,
|
||||
type ImportSummary,
|
||||
} from "./dataExportService";
|
||||
import {
|
||||
importTransactionsWithCategories,
|
||||
previewUnlinkedTransfers,
|
||||
type RestoreOutcome,
|
||||
} from "./dataRestoreService";
|
||||
import { getPreference, setPreference } from "./userPreferenceService";
|
||||
import type { LastMigrationJournal } from "./categoryMigrationService";
|
||||
|
||||
|
|
@ -13,16 +22,19 @@ import type { LastMigrationJournal } from "./categoryMigrationService";
|
|||
// "transactions_with_categories" import). Calling it is the user's explicit
|
||||
// choice, gated by a confirmation modal in the UI layer.
|
||||
//
|
||||
// Flow:
|
||||
// Flow, in two calls with a second confirmation between them (#521):
|
||||
// 1. Resolve the backup file path — either the one recorded in
|
||||
// `last_categories_migration.backupPath`, or a user-picked file when the
|
||||
// recorded path no longer exists on disk.
|
||||
// 2. Read it via `read_import_file` (Rust transparently handles the SREF
|
||||
// AES-256-GCM decryption when the file starts with the magic bytes).
|
||||
// 3. Parse it, assert `export_type === "transactions_with_categories"`.
|
||||
// 4. Call `importTransactionsWithCategories` to wipe + restore everything.
|
||||
// 5. Reset `categories_schema_version` back to `v2` and merge a `reverted_at`
|
||||
// timestamp into `last_categories_migration`.
|
||||
// 2. `readBackup`: read it via `read_import_file` (Rust transparently
|
||||
// handles the SREF AES-256-GCM decryption when the file starts with the
|
||||
// magic bytes), parse it, assert
|
||||
// `export_type === "transactions_with_categories"`, and count the Bilan
|
||||
// transfers the restore would unlink. Nothing is written.
|
||||
// 3. `applyBackup`: call `importTransactionsWithCategories` to wipe +
|
||||
// restore everything, then reset `categories_schema_version` back to
|
||||
// `v2` and merge a `reverted_at` timestamp into
|
||||
// `last_categories_migration`.
|
||||
//
|
||||
// The service never swallows errors — the caller (modal) is responsible for
|
||||
// surfacing them via i18n-mapped messages.
|
||||
|
|
@ -39,12 +51,25 @@ export interface RestorableMigrationJournal extends LastMigrationJournal {
|
|||
reverted_at?: string;
|
||||
}
|
||||
|
||||
export interface RestoreResult {
|
||||
/** Path that was actually restored from (may differ from the recorded one
|
||||
* when the user picked a fallback file). */
|
||||
/** A backup read, decrypted and parsed, before the second confirmation (#521). */
|
||||
export interface BackupReading {
|
||||
/** Path that was read (may differ from the recorded one when the user
|
||||
* picked a fallback file). */
|
||||
filePath: string;
|
||||
/** Its name, recorded on the `imported_files` row of the restore. */
|
||||
filename: string;
|
||||
envelope: ExportEnvelope;
|
||||
summary: ImportSummary;
|
||||
/** Bilan transfers the restore would unlink, announced by the second
|
||||
* confirmation (`previewUnlinkedTransfers`). */
|
||||
unlinkedTransfers: number;
|
||||
}
|
||||
|
||||
export interface RestoreResult {
|
||||
/** ISO-8601 timestamp recorded on `last_categories_migration.reverted_at`. */
|
||||
revertedAt: string;
|
||||
/** What the restore did, the transfers it unlinked among it (#521). */
|
||||
outcome: RestoreOutcome;
|
||||
}
|
||||
|
||||
export type RestoreErrorCode =
|
||||
|
|
@ -189,23 +214,24 @@ export async function pickBackupFile(): Promise<string | null> {
|
|||
// -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Restore a profile from a pre-migration SREF backup and mark the migration
|
||||
* as reverted. This is the destructive write performed after confirmation.
|
||||
* Read a pre-migration SREF backup, without writing anything: the first half
|
||||
* of « Rétablir la sauvegarde », before its second confirmation (#521).
|
||||
*
|
||||
* @param filePath Absolute path to the backup SREF/JSON file.
|
||||
* @param password Clear-text PIN — required when the file is encrypted
|
||||
* (SREF magic detected). Pass `null` for plaintext JSON
|
||||
* backups or when the profile had no PIN.
|
||||
*
|
||||
* Throws a `RestoreError` on any failure, except a file the import boundary
|
||||
* refuses: that one stays the `SrefValidationError` it is, whose message says
|
||||
* what is wrong with the file (#518). On success updates
|
||||
* `categories_schema_version=v2` and stamps `reverted_at` on the journal.
|
||||
* Throws a `RestoreError` when the file cannot be read, decrypted or parsed,
|
||||
* or is not a full backup, except a file the import boundary refuses: that
|
||||
* one stays the `SrefValidationError` it is, whose message says what is wrong
|
||||
* with the file (#518). Returns the envelope, its summary and the number of
|
||||
* Bilan transfers the restore would unlink, read in the profile.
|
||||
*/
|
||||
export async function restoreFromBackup(
|
||||
export async function readBackup(
|
||||
filePath: string,
|
||||
password: string | null,
|
||||
): Promise<RestoreResult> {
|
||||
): Promise<BackupReading> {
|
||||
// 1. Read the file — decryption happens inside read_import_file when the
|
||||
// magic prefix is present.
|
||||
let content: string;
|
||||
|
|
@ -232,9 +258,9 @@ export async function restoreFromBackup(
|
|||
// 2. Parse the envelope. The export_type MUST be
|
||||
// `transactions_with_categories` — anything else would be a user error
|
||||
// (they picked the wrong file).
|
||||
let envelope;
|
||||
let parsed: { envelope: ExportEnvelope; summary: ImportSummary };
|
||||
try {
|
||||
envelope = parseImportedJson(content).envelope;
|
||||
parsed = parseImportedJson(content);
|
||||
} catch (e) {
|
||||
// A refusal of the import boundary keeps its own message: wrapped, the
|
||||
// modal would show the generic parse failure instead (#518).
|
||||
|
|
@ -242,6 +268,7 @@ export async function restoreFromBackup(
|
|||
const message = e instanceof Error ? e.message : String(e);
|
||||
throw new RestoreError("parse_failed", message);
|
||||
}
|
||||
const { envelope, summary } = parsed;
|
||||
|
||||
if (envelope.export_type !== "transactions_with_categories") {
|
||||
throw new RestoreError(
|
||||
|
|
@ -250,12 +277,44 @@ export async function restoreFromBackup(
|
|||
);
|
||||
}
|
||||
|
||||
// 3. Perform the destructive re-import. importTransactionsWithCategories
|
||||
// 3. What the second confirmation announces: the Bilan transfers whose
|
||||
// transaction would not come back as it was (#521), read in the profile.
|
||||
const unlinkedTransfers = await previewUnlinkedTransfers(
|
||||
envelope.data.transactions,
|
||||
);
|
||||
|
||||
return {
|
||||
filePath,
|
||||
filename: filePath.split(/[/\\]/).pop() ?? "backup.sref",
|
||||
envelope,
|
||||
summary,
|
||||
unlinkedTransfers,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore a profile from a backup `readBackup` has read and mark the
|
||||
* migration as reverted. This is the destructive write performed after the
|
||||
* second confirmation (#521).
|
||||
*
|
||||
* @param envelope The envelope `readBackup` returned.
|
||||
* @param filename Its file name, recorded on the `imported_files` row.
|
||||
*
|
||||
* Throws a `RestoreError` when the restore fails, except a refusal of the
|
||||
* import boundary, which stays the `SrefValidationError` it is (#518). On
|
||||
* success updates `categories_schema_version=v2`, stamps `reverted_at` on the
|
||||
* journal, and returns the outcome of the restore.
|
||||
*/
|
||||
export async function applyBackup(
|
||||
envelope: ExportEnvelope,
|
||||
filename: string,
|
||||
): Promise<RestoreResult> {
|
||||
// 1. Perform the destructive re-import. importTransactionsWithCategories
|
||||
// wipes transactions/imported_files/import_sources/keywords/suppliers/
|
||||
// categories and re-inserts them from the envelope.
|
||||
const filename = filePath.split(/[/\\]/).pop() ?? "backup.sref";
|
||||
let outcome: RestoreOutcome;
|
||||
try {
|
||||
await importTransactionsWithCategories(envelope.data, filename);
|
||||
outcome = await importTransactionsWithCategories(envelope.data, filename);
|
||||
} catch (e) {
|
||||
// Same for a refusal raised at the head of the restore itself.
|
||||
if (e instanceof SrefValidationError) throw e;
|
||||
|
|
@ -263,7 +322,7 @@ export async function restoreFromBackup(
|
|||
throw new RestoreError("import_failed", message);
|
||||
}
|
||||
|
||||
// 4. Reset schema version and stamp the journal. Both are best-effort in the
|
||||
// 2. Reset schema version and stamp the journal. Both are best-effort in the
|
||||
// sense that the DB restore has already succeeded by this point — we
|
||||
// still surface a preference write failure because stale prefs would
|
||||
// make the banner misleading.
|
||||
|
|
@ -271,5 +330,5 @@ export async function restoreFromBackup(
|
|||
await setPreference(CATEGORIES_SCHEMA_VERSION_KEY, "v2");
|
||||
await markMigrationReverted(revertedAt);
|
||||
|
||||
return { filePath, revertedAt };
|
||||
return { revertedAt, outcome };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,10 @@
|
|||
* runs against an in-memory FakeDb that interprets the statements it issues —
|
||||
* the same approach as `import-format-roundtrip.test.ts`. This one additionally
|
||||
* models `UNIQUE(name)` and BEGIN/ROLLBACK, because those are the failures the
|
||||
* transaction exists to survive.
|
||||
* 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`.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
|
|
@ -39,6 +42,7 @@ import {
|
|||
parseImportedJson,
|
||||
serializeToJson,
|
||||
serializeTransactionsToCsv,
|
||||
validateImportedCategoryReferences,
|
||||
validateImportedFormatRows,
|
||||
validateImportedTransactionIds,
|
||||
LEGACY_SREF_FORMAT_VERSION,
|
||||
|
|
@ -57,7 +61,7 @@ import {
|
|||
} from "./dataRestoreService";
|
||||
import { subscribeDataChanged } from "./dataEvents";
|
||||
import { formatFromRow, FORMAT_FIELD_PAIRS } from "../utils/importFormat";
|
||||
import type { Category } from "../shared/types";
|
||||
import type { Category, Keyword, Supplier } from "../shared/types";
|
||||
import fr from "../i18n/locales/fr.json";
|
||||
import en from "../i18n/locales/en.json";
|
||||
|
||||
|
|
@ -78,6 +82,7 @@ function makeFakeDb(shouldFail?: (sql: string, params: unknown[]) => boolean) {
|
|||
imported_files: [],
|
||||
import_sources: [],
|
||||
import_config_templates: [],
|
||||
balance_account_transfers: [],
|
||||
};
|
||||
const log: string[] = [];
|
||||
let snapshot: Record<string, Row[]> | null = null;
|
||||
|
|
@ -149,6 +154,12 @@ function makeFakeDb(shouldFail?: (sql: string, params: unknown[]) => boolean) {
|
|||
if (trimmed.startsWith("UPDATE transactions SET")) {
|
||||
return { rowsAffected: 0 };
|
||||
}
|
||||
// The second pass of `restoreCategories` (#521).
|
||||
if (/^UPDATE categories SET parent_id = \$1 WHERE id = \$2$/.test(trimmed)) {
|
||||
const row = tables.categories.find((r) => r.id === params[1]);
|
||||
if (row) row.parent_id = params[0];
|
||||
return { rowsAffected: row ? 1 : 0 };
|
||||
}
|
||||
if (trimmed.startsWith("INSERT")) return insert(sql, params);
|
||||
throw new Error(`FakeDb: unsupported statement ${sql.slice(0, 40)}`);
|
||||
}),
|
||||
|
|
@ -166,6 +177,18 @@ function makeFakeDb(shouldFail?: (sql: string, params: unknown[]) => boolean) {
|
|||
?.name ?? null,
|
||||
}));
|
||||
}
|
||||
// A restore reads each Bilan transfer with its transaction (#521).
|
||||
if (table === "balance_account_transfers" && /LEFT JOIN transactions/.test(sql)) {
|
||||
return rows.map((r) => {
|
||||
const tx = tables.transactions.find((t) => t.id === r.transaction_id);
|
||||
return {
|
||||
...r,
|
||||
date: tx?.date ?? null,
|
||||
amount: tx?.amount ?? null,
|
||||
description: tx?.description ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
return [...rows];
|
||||
}),
|
||||
};
|
||||
|
|
@ -716,6 +739,11 @@ describe("the refusal messages are translated (#331)", () => {
|
|||
expect(en.settings.dataManagement.import.errors.orphanSplitLines.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("carries the refusal of a category reference the file cannot satisfy in FR and EN (#521)", () => {
|
||||
expect(fr.settings.dataManagement.import.errors.danglingCategoryReference.length).toBeGreaterThan(0);
|
||||
expect(en.settings.dataManagement.import.errors.danglingCategoryReference.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("keys every SrefValidationError to a string that exists", () => {
|
||||
const cases: Array<[ExportImportSource, string]> = [
|
||||
[{ ...SOURCE, amount_mode: "absolute_indicator" as never }, "unsupportedAmountMode"],
|
||||
|
|
@ -757,6 +785,24 @@ describe("the refusal messages are translated (#331)", () => {
|
|||
.reduce<unknown>((node, part) => (node as Record<string, unknown>)[part], bundle as unknown);
|
||||
expect(typeof resolved).toBe("string");
|
||||
}
|
||||
|
||||
// The refusal of #521 carries no name either, and resolves in both bundles.
|
||||
let dangling: unknown = null;
|
||||
try {
|
||||
validateImportedCategoryReferences([], [], [{ id: 1, keyword: "x", category_id: 9 } as Keyword]);
|
||||
} catch (e) {
|
||||
dangling = e;
|
||||
}
|
||||
expect(dangling).toBeInstanceOf(SrefValidationError);
|
||||
const danglingKey = (dangling as SrefValidationError).i18nKey;
|
||||
expect(danglingKey).toBe("settings.dataManagement.import.errors.danglingCategoryReference");
|
||||
expect((dangling as SrefValidationError).params).toEqual({});
|
||||
for (const bundle of [fr, en]) {
|
||||
const resolved = danglingKey
|
||||
.split(".")
|
||||
.reduce<unknown>((node, part) => (node as Record<string, unknown>)[part], bundle as unknown);
|
||||
expect(typeof resolved).toBe("string");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -1067,3 +1113,184 @@ describe("the rows keep their ids, and a split line its parent (#518)", () => {
|
|||
expect(refusalOf(() => parseImportedCsv(csv)).i18nKey).toBe(ORPHAN);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 10. A category reference the file cannot satisfy (#521)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("the import boundary refuses a category reference the file cannot satisfy (#521)", () => {
|
||||
const DANGLING = "settings.dataManagement.import.errors.danglingCategoryReference";
|
||||
|
||||
const cat = (id: number, parent_id: number | null = null) =>
|
||||
({ ...CATEGORY_FIXTURES[0], id, name: `Cat ${id}`, parent_id }) as unknown as Category;
|
||||
const supplier = (id: number, category_id: number | null) =>
|
||||
({ id, name: `Sup ${id}`, normalized_name: `sup ${id}`, category_id, is_active: 1 }) as unknown as Supplier;
|
||||
const keyword = (id: number, category_id: number | null) =>
|
||||
({ id, keyword: `kw ${id}`, category_id, priority: 1, is_active: 1 }) as unknown as Keyword;
|
||||
|
||||
/** The refusal `run` throws; fails when it throws nothing. */
|
||||
function danglingOf(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 reference names one of its categories, in any order, loops included", () => {
|
||||
const categories = [cat(1, 3), cat(2, null), cat(3, 2), cat(4, 5), cat(5, 4), cat(6, 6)];
|
||||
expect(() =>
|
||||
validateImportedCategoryReferences(categories, [supplier(1, 3), supplier(2, null)], [keyword(1, 1), keyword(2, 6)])
|
||||
).not.toThrow();
|
||||
expect(() => validateImportedCategoryReferences(undefined, undefined, undefined)).not.toThrow();
|
||||
});
|
||||
|
||||
it.each<[string, Category[] | undefined, Supplier[] | undefined, Keyword[] | undefined]>([
|
||||
["a category whose parent is not in the file", [cat(1, 9)], [], []],
|
||||
["a supplier whose category is not in the file", [cat(1)], [supplier(1, 9)], []],
|
||||
["a keyword whose category is not in the file", [cat(1)], [], [keyword(1, 9)]],
|
||||
["a keyword without a category", [cat(1)], [], [keyword(1, null)]],
|
||||
["a keyword in a file without categories", undefined, undefined, [keyword(1, 1)]],
|
||||
])("refuses %s", (_label, categories, suppliers, keywords) => {
|
||||
expect(danglingOf(() => validateImportedCategoryReferences(categories, suppliers, keywords)).i18nKey).toBe(
|
||||
DANGLING
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses at PARSE time, so the confirmation never opens", () => {
|
||||
const json = serializeToJson(
|
||||
"categories_only",
|
||||
{ categories: [cat(1)], suppliers: [], keywords: [keyword(1, 2)] },
|
||||
"0.17.2"
|
||||
);
|
||||
expect(danglingOf(() => parseImportedJson(json)).i18nKey).toBe(DANGLING);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"transactions with categories",
|
||||
(data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json"),
|
||||
],
|
||||
["categories only", (data: ExportEnvelope["data"]) => importCategoriesOnly(data)],
|
||||
] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => {
|
||||
db.seed("categories", [{ name: "Existing" }]);
|
||||
await expect(
|
||||
restore(envelopeData({ categories: [cat(1, 9)], suppliers: [], keywords: [] }))
|
||||
).rejects.toBeInstanceOf(SrefValidationError);
|
||||
expect(db.log).toEqual([]);
|
||||
expect(db.tables.categories.map((c) => c.name)).toEqual(["Existing"]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 11. What a restore does beyond the rows of the file (#521)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("the categories go in without their parents, set in a second pass (#521)", () => {
|
||||
/** A category ranked under a newer one, then a loop. */
|
||||
const CATEGORIES = [
|
||||
{ ...CATEGORY_FIXTURES[0], id: 1, name: "Ancienne", parent_id: 2 },
|
||||
{ ...CATEGORY_FIXTURES[0], id: 2, name: "Nouvelle", parent_id: null },
|
||||
{ ...CATEGORY_FIXTURES[0], id: 3, name: "Boucle A", parent_id: 4 },
|
||||
{ ...CATEGORY_FIXTURES[0], id: 4, name: "Boucle B", parent_id: 3 },
|
||||
] as unknown as Category[];
|
||||
|
||||
it.each([
|
||||
[
|
||||
"transactions with categories",
|
||||
() => importTransactionsWithCategories(envelopeData({ categories: CATEGORIES }), "backup.json"),
|
||||
],
|
||||
["categories only", () => importCategoriesOnly({ categories: CATEGORIES, suppliers: [], keywords: [] })],
|
||||
] as const)("%s: every insert without a parent, then each parent; every parent_id as in the file", async (_name, restore) => {
|
||||
await restore();
|
||||
|
||||
const inserts = db.execute.mock.calls
|
||||
.map(([sql, params]) => [sql as string, params as unknown[]] as const)
|
||||
.filter(([sql]) => sql.includes("INSERT INTO categories"));
|
||||
expect(inserts).toHaveLength(4);
|
||||
// The third value of each insert is its parent_id: always NULL.
|
||||
expect(inserts.map(([, params]) => params[2])).toEqual([null, null, null, null]);
|
||||
// Every update after the last insert, one per category that has a parent.
|
||||
const heads = db.log.filter((line) => line.startsWith("INSERT INTO categories") || line.startsWith("UPDATE categories"));
|
||||
expect(heads).toEqual([
|
||||
...Array(4).fill("INSERT INTO categories"),
|
||||
...Array(3).fill("UPDATE categories SET"),
|
||||
]);
|
||||
expect(db.tables.categories.map((c) => [c.id, c.parent_id])).toEqual([
|
||||
[1, 2],
|
||||
[2, null],
|
||||
[3, 4],
|
||||
[4, 3],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a restore hands back its outcome (#521)", () => {
|
||||
/** A transfer of the Bilan, as the profile holds it. */
|
||||
const transfer = (id: number, transactionId: number) => ({
|
||||
id,
|
||||
account_id: 2,
|
||||
transaction_id: transactionId,
|
||||
direction: "in",
|
||||
notes: null,
|
||||
created_at: "2026-10-04 12:00:00",
|
||||
});
|
||||
|
||||
it("categories only: zeros, nothing deleted that a transfer holds", async () => {
|
||||
await expect(importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [] })).resolves.toEqual({
|
||||
unlinkedTransfers: 0,
|
||||
uncategorizedTransactions: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json")],
|
||||
["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)] }));
|
||||
const deletes = db.log.filter((line) => line.startsWith("DELETE FROM"));
|
||||
expect(deletes[0]).toBe("DELETE FROM balance_account_transfers");
|
||||
expect(deletes).toContain("DELETE FROM transactions");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json")],
|
||||
["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).
|
||||
db.seed("transactions", [transactionFixture(1), transactionFixture(2)]);
|
||||
db.tables.balance_account_transfers.push(transfer(10, 1), transfer(11, 2));
|
||||
|
||||
const outcome = await restore(
|
||||
envelopeData({ transactions: [transactionFixture(1), { ...transactionFixture(2), amount: -11 }] })
|
||||
);
|
||||
|
||||
expect(outcome.unlinkedTransfers).toBe(1);
|
||||
expect(db.tables.balance_account_transfers).toEqual([transfer(10, 1)]);
|
||||
});
|
||||
|
||||
it("transactions only: a transaction whose category the profile does not hold comes back without one, manual flag at 0", async () => {
|
||||
db.seed("categories", [{ name: "Kept" }]);
|
||||
const kept = db.tables.categories[0].id as number;
|
||||
|
||||
const outcome = await importTransactionsOnly(
|
||||
envelopeData({
|
||||
transactions: [
|
||||
{ ...transactionFixture(1), category_id: kept, is_manually_categorized: 1 },
|
||||
{ ...transactionFixture(2), category_id: kept + 100, is_manually_categorized: 1 },
|
||||
{ ...transactionFixture(3), category_id: null },
|
||||
],
|
||||
}),
|
||||
"backup.json"
|
||||
);
|
||||
|
||||
expect(db.tables.transactions.map((t) => [t.id, t.category_id, t.is_manually_categorized])).toEqual([
|
||||
[1, kept, 1],
|
||||
[2, null, 0],
|
||||
[3, null, 0],
|
||||
]);
|
||||
expect(outcome).toEqual({ unlinkedTransfers: 0, uncategorizedTransactions: 1 });
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -123,11 +123,13 @@ export type SrefValidationErrorKey =
|
|||
| "settings.dataManagement.import.errors.unsupportedAmountMode"
|
||||
| "settings.dataManagement.import.errors.unsupportedSignConvention"
|
||||
| "settings.dataManagement.import.errors.invalidFormatRow"
|
||||
| "settings.dataManagement.import.errors.orphanSplitLines";
|
||||
| "settings.dataManagement.import.errors.orphanSplitLines"
|
||||
| "settings.dataManagement.import.errors.danglingCategoryReference";
|
||||
|
||||
/**
|
||||
* Thrown when a backup carries a configuration this build cannot store, or
|
||||
* split lines that cannot find their parent (#518).
|
||||
* 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).
|
||||
*
|
||||
* 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
|
||||
|
|
@ -372,6 +374,50 @@ export function validateImportedTransactionIds(
|
|||
return { keepIds };
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse a file whose categories, keywords or suppliers name a category the
|
||||
* file does not hold, BEFORE anything is deleted (#521).
|
||||
*
|
||||
* The two modes that carry categories delete the profile's and insert the
|
||||
* file's, against foreign keys: a `parent_id`, the `category_id` of a keyword
|
||||
* or the `category_id` of a supplier that names no category of the file would
|
||||
* stop the restore midway on SQLite's raw message. A category or a supplier
|
||||
* may name none; a keyword always names one (the column is NOT NULL), so a
|
||||
* keyword without it is refused too. A file without a `categories` array holds
|
||||
* no category at all. The category of a transaction is not checked here: a
|
||||
* transaction whose category is missing comes back without one
|
||||
* (`attachTransactions`, decision of Max of 2026-10-29).
|
||||
*
|
||||
* 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 validateImportedCategoryReferences(
|
||||
categories: Category[] | undefined,
|
||||
suppliers: Supplier[] | undefined,
|
||||
keywords: Keyword[] | undefined
|
||||
): void {
|
||||
const ids = new Set(
|
||||
(categories ?? [])
|
||||
.map((category) => category?.id)
|
||||
.filter((id): id is number => typeof id === "number")
|
||||
);
|
||||
const refusal = () =>
|
||||
new SrefValidationError(
|
||||
"settings.dataManagement.import.errors.danglingCategoryReference",
|
||||
{}
|
||||
);
|
||||
|
||||
for (const category of categories ?? []) {
|
||||
if (category?.parent_id != null && !ids.has(category.parent_id)) throw refusal();
|
||||
}
|
||||
for (const supplier of suppliers ?? []) {
|
||||
if (supplier?.category_id != null && !ids.has(supplier.category_id)) throw refusal();
|
||||
}
|
||||
for (const keyword of keywords ?? []) {
|
||||
if (!ids.has(keyword?.category_id)) throw refusal();
|
||||
}
|
||||
}
|
||||
|
||||
export function parseImportedJson(content: string): {
|
||||
envelope: ExportEnvelope;
|
||||
summary: ImportSummary;
|
||||
|
|
@ -400,14 +446,20 @@ export function parseImportedJson(content: string): {
|
|||
throw new Error(`Unknown export type: ${envelope.export_type}`);
|
||||
}
|
||||
|
||||
// Refuse an unreadable configuration, or split lines that cannot find their
|
||||
// parent, while the file is only being LOOKED at: the confirmation dialog
|
||||
// never opens, so nothing is deleted.
|
||||
// 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.
|
||||
validateImportedFormatRows(
|
||||
envelope.data.import_sources,
|
||||
envelope.data.import_config_templates
|
||||
);
|
||||
validateImportedTransactionIds(envelope.data.transactions);
|
||||
validateImportedCategoryReferences(
|
||||
envelope.data.categories,
|
||||
envelope.data.suppliers,
|
||||
envelope.data.keywords
|
||||
);
|
||||
|
||||
return {
|
||||
envelope,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import type Database from "@tauri-apps/plugin-sql";
|
||||
import { withTransaction } from "./db";
|
||||
import { getDb, withTransaction } from "./db";
|
||||
import { notifyDataChanged } from "./dataEvents";
|
||||
import { logWarn } from "./logService";
|
||||
import { toSqlFlag } from "../utils/sqlFlag";
|
||||
import type { Category, Keyword, Supplier } from "../shared/types";
|
||||
import {
|
||||
validateImportedCategoryReferences,
|
||||
validateImportedFormatRows,
|
||||
validateImportedTransactionIds,
|
||||
type ExportEnvelope,
|
||||
|
|
@ -18,6 +20,115 @@ import {
|
|||
// the export, the parse and the validations of the import boundary stay in
|
||||
// dataExportService.ts.
|
||||
|
||||
/**
|
||||
* What a restore did beyond putting the file's rows back (#521), for the
|
||||
* success message and the Journal. `importCategoriesOnly` deletes no
|
||||
* transaction and leaves both at zero.
|
||||
*/
|
||||
export interface RestoreOutcome {
|
||||
/**
|
||||
* Bilan transfers whose transaction did not come back as it was: unlinked,
|
||||
* and gone with the COMMIT, the backup holding no transfer.
|
||||
*/
|
||||
unlinkedTransfers: number;
|
||||
/**
|
||||
* Transactions of the file whose category the profile does not hold:
|
||||
* restored without a category, manual flag at 0.
|
||||
*/
|
||||
uncategorizedTransactions: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Bilan transfer as a restore reads it, with what identifies its
|
||||
* transaction: the date, the amount and the description (#521).
|
||||
*/
|
||||
interface LinkedTransfer {
|
||||
id: number;
|
||||
account_id: number;
|
||||
transaction_id: number;
|
||||
direction: string;
|
||||
notes: string | null;
|
||||
created_at: string;
|
||||
date: string | null;
|
||||
amount: number | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every transfer of the profile with its transaction. A LEFT JOIN, so that a
|
||||
* transfer left without its transaction, which the foreign key forbids, is
|
||||
* still counted among those that do not come back.
|
||||
*/
|
||||
const LINKED_TRANSFERS_SQL = `SELECT bat.id, bat.account_id, bat.transaction_id, bat.direction, bat.notes, bat.created_at,
|
||||
t.date, t.amount, t.description
|
||||
FROM balance_account_transfers bat
|
||||
LEFT JOIN transactions t ON t.id = bat.transaction_id
|
||||
ORDER BY bat.id`;
|
||||
|
||||
/**
|
||||
* The transfers a restore of `transactions` keeps (#521, decision of Max of
|
||||
* 2026-10-29): those whose transaction comes back with the same id, the same
|
||||
* date, the same amount and the same description. The id alone would not do:
|
||||
* the file of another profile, or a backup older than a restore, can give that
|
||||
* id to another transaction. When the rows do not keep their ids (`keepIds`
|
||||
* false), SQLite gives each a new one, above every id the sequence has handed
|
||||
* out, so no transfer finds its transaction.
|
||||
*
|
||||
* The one rule of the restore and of its preview (`previewUnlinkedTransfers`):
|
||||
* the number announced before the confirmation is the number the restore
|
||||
* unlinks on the same profile.
|
||||
*/
|
||||
function transfersThatReturn(
|
||||
transfers: LinkedTransfer[],
|
||||
transactions: ExportTransaction[] | undefined,
|
||||
keepIds: boolean
|
||||
): LinkedTransfer[] {
|
||||
if (!keepIds) return [];
|
||||
const restored = new Map((transactions ?? []).map((tx) => [tx.id, tx]));
|
||||
return transfers.filter((transfer) => {
|
||||
const tx = restored.get(transfer.transaction_id);
|
||||
return (
|
||||
tx !== undefined &&
|
||||
tx.date === transfer.date &&
|
||||
tx.amount === transfer.amount &&
|
||||
tx.description === transfer.description
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* How many Bilan transfers a restore of `transactions` would unlink in the
|
||||
* profile, for the confirmation to announce before anything is deleted
|
||||
* (#521). Read outside any transaction (`getDb`), by the rule of the restore
|
||||
* (`transfersThatReturn`). Meant for the two modes that carry transactions: a
|
||||
* restore of the categories only deletes no transaction and unlinks nothing,
|
||||
* so its callers do not ask.
|
||||
*/
|
||||
export async function previewUnlinkedTransfers(
|
||||
transactions: ExportTransaction[] | undefined
|
||||
): Promise<number> {
|
||||
const { keepIds } = validateImportedTransactionIds(transactions);
|
||||
const db = await getDb();
|
||||
const transfers = await db.select<LinkedTransfer[]>(LINKED_TRANSFERS_SQL);
|
||||
return (
|
||||
transfers.length -
|
||||
transfersThatReturn(transfers, transactions, keepIds).length
|
||||
);
|
||||
}
|
||||
|
||||
/** The Journal line of a restore that brought transactions back without their category: counts only. */
|
||||
function uncategorizedLogLine(count: number): string {
|
||||
return `Data restore: ${count} ${count === 1 ? "transaction" : "transactions"} restored without a category, missing from the profile`;
|
||||
}
|
||||
|
||||
/** Writes to the Journal what the committed restore did, then hands its outcome back. */
|
||||
function reportOutcome(outcome: RestoreOutcome): RestoreOutcome {
|
||||
if (outcome.uncategorizedTransactions > 0) {
|
||||
logWarn(uncategorizedLogLine(outcome.uncategorizedTransactions));
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
// --- Import execution ---
|
||||
|
||||
/**
|
||||
|
|
@ -51,18 +162,18 @@ const HOST_SOURCE_MAPPING = JSON.stringify({
|
|||
* A committed restore replaces the data every getting-started counter reads,
|
||||
* so it is announced on the data channel: one point for the three restore
|
||||
* modes, reached only after the COMMIT (a rollback rethrows) and once the DB
|
||||
* lock is released (ADR 0022).
|
||||
* lock is released (ADR 0022). What `body` returns, its `RestoreOutcome`, is
|
||||
* handed back once committed (#521).
|
||||
*/
|
||||
async function runRestore(
|
||||
body: (db: Database) => Promise<void>
|
||||
): Promise<void> {
|
||||
await withTransaction(async (db) => {
|
||||
async function runRestore<T>(body: (db: Database) => Promise<T>): Promise<T> {
|
||||
const result = await withTransaction(async (db) => {
|
||||
await db.execute("BEGIN");
|
||||
let open = true;
|
||||
try {
|
||||
await body(db);
|
||||
const value = await body(db);
|
||||
await db.execute("COMMIT");
|
||||
open = false;
|
||||
return value;
|
||||
} catch (e) {
|
||||
if (open) {
|
||||
try {
|
||||
|
|
@ -75,8 +186,22 @@ async function runRestore(
|
|||
}
|
||||
});
|
||||
notifyDataChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert the file's categories, then set their parents (#521).
|
||||
*
|
||||
* `categories.parent_id` is a foreign key checked at each statement, and the
|
||||
* export lists the categories by id: a category ranked under a newer one (the
|
||||
* migration's « Catégories personnalisées (migration) » is 2000, a drag and
|
||||
* drop can do the same) used to fail its insert, and a loop (A under B, B
|
||||
* under A) fits no order at all. Every category goes in with `parent_id` at
|
||||
* NULL, then a second pass sets each parent, all of them in the table by then:
|
||||
* 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.
|
||||
*/
|
||||
async function restoreCategories(
|
||||
db: Database,
|
||||
categories: Category[] | undefined
|
||||
|
|
@ -88,7 +213,7 @@ async function restoreCategories(
|
|||
[
|
||||
cat.id,
|
||||
cat.name,
|
||||
cat.parent_id ?? null,
|
||||
null,
|
||||
cat.color ?? null,
|
||||
cat.icon ?? null,
|
||||
cat.type,
|
||||
|
|
@ -98,6 +223,13 @@ async function restoreCategories(
|
|||
]
|
||||
);
|
||||
}
|
||||
for (const cat of categories ?? []) {
|
||||
if (cat.parent_id == null) continue;
|
||||
await db.execute("UPDATE categories SET parent_id = $1 WHERE id = $2", [
|
||||
cat.parent_id,
|
||||
cat.id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreSuppliers(
|
||||
|
|
@ -236,14 +368,29 @@ async function restoreImportSources(
|
|||
* The rows without a parent go in first, then the split lines, each pass in
|
||||
* the order of the file: the foreign key of a split line never waits for a row
|
||||
* still to come, whatever order the file lists them in.
|
||||
*
|
||||
* A row whose category the profile does not hold comes back without one, its
|
||||
* manual flag at 0, so that « Catégoriser automatiquement » picks it up (#521,
|
||||
* decision of Max of 2026-10-29): its `category_id` would otherwise fail the
|
||||
* foreign key and stop the whole restore. That happens with « Transactions
|
||||
* seulement » after « Réinitialiser », after a restore that replaced the
|
||||
* categories, or with the file of another profile. The categories are read
|
||||
* once, through the restore's handle, after `restoreCategories` in the mode
|
||||
* that writes them. Returns how many rows came back so.
|
||||
*/
|
||||
async function attachTransactions(
|
||||
db: Database,
|
||||
transactions: ExportTransaction[] | undefined,
|
||||
filename: string,
|
||||
keepIds: boolean
|
||||
): Promise<void> {
|
||||
if (!transactions || transactions.length === 0) return;
|
||||
): Promise<number> {
|
||||
if (!transactions || transactions.length === 0) return 0;
|
||||
|
||||
const categoryIds = new Set(
|
||||
(await db.select<Array<{ id: number }>>("SELECT id FROM categories")).map(
|
||||
(row) => row.id
|
||||
)
|
||||
);
|
||||
|
||||
const existing = await db.select<Array<{ id: number }>>(
|
||||
"SELECT id FROM import_sources WHERE name = $1",
|
||||
|
|
@ -283,16 +430,20 @@ async function attachTransactions(
|
|||
...transactions.filter((tx) => tx.parent_transaction_id == null),
|
||||
...transactions.filter((tx) => tx.parent_transaction_id != null),
|
||||
];
|
||||
let uncategorized = 0;
|
||||
for (const tx of ordered) {
|
||||
const missingCategory =
|
||||
tx.category_id != null && !categoryIds.has(tx.category_id);
|
||||
if (missingCategory) uncategorized++;
|
||||
const values = [
|
||||
tx.date,
|
||||
tx.description,
|
||||
tx.amount,
|
||||
tx.category_id,
|
||||
missingCategory ? null : tx.category_id,
|
||||
tx.original_description,
|
||||
tx.notes,
|
||||
// A JSON backup from the time of #390 carries the text "true".
|
||||
toSqlFlag(tx.is_manually_categorized),
|
||||
missingCategory ? 0 : toSqlFlag(tx.is_manually_categorized),
|
||||
tx.is_split,
|
||||
tx.parent_transaction_id,
|
||||
sourceId,
|
||||
|
|
@ -312,11 +463,60 @@ async function attachTransactions(
|
|||
);
|
||||
}
|
||||
}
|
||||
return uncategorized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the profile's Bilan transfers with their transactions, then remove
|
||||
* them, ahead of `DELETE FROM transactions` (#521).
|
||||
*
|
||||
* `balance_account_transfers.transaction_id` is `ON DELETE RESTRICT` (ADR
|
||||
* 0010): it fires at once, `PRAGMA defer_foreign_keys` does not delay it and
|
||||
* `PRAGMA foreign_keys = OFF` does nothing after `BEGIN`, so a single transfer
|
||||
* stopped every restore of transactions. The backup holds no transfer:
|
||||
* `restoreTransfers` puts back the ones whose transaction returns.
|
||||
*/
|
||||
async function takeTransfers(db: Database): Promise<LinkedTransfer[]> {
|
||||
const transfers = await db.select<LinkedTransfer[]>(LINKED_TRANSFERS_SQL);
|
||||
await db.execute("DELETE FROM balance_account_transfers");
|
||||
return transfers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put back, as they were (id, account, direction, notes, date of creation),
|
||||
* the transfers whose transaction came back as it was
|
||||
* (`transfersThatReturn`), once the transactions are in. Returns how many
|
||||
* were unlinked.
|
||||
*/
|
||||
async function restoreTransfers(
|
||||
db: Database,
|
||||
transfers: LinkedTransfer[],
|
||||
transactions: ExportTransaction[] | undefined,
|
||||
keepIds: boolean
|
||||
): Promise<number> {
|
||||
const kept = transfersThatReturn(transfers, transactions, keepIds);
|
||||
for (const transfer of kept) {
|
||||
await db.execute(
|
||||
`INSERT INTO balance_account_transfers (id, account_id, transaction_id, direction, notes, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)`,
|
||||
[
|
||||
transfer.id,
|
||||
transfer.account_id,
|
||||
transfer.transaction_id,
|
||||
transfer.direction,
|
||||
transfer.notes,
|
||||
transfer.created_at,
|
||||
]
|
||||
);
|
||||
}
|
||||
return transfers.length - kept.length;
|
||||
}
|
||||
|
||||
export async function importCategoriesOnly(
|
||||
data: ExportEnvelope["data"]
|
||||
): Promise<void> {
|
||||
): Promise<RestoreOutcome> {
|
||||
validateImportedCategoryReferences(data.categories, data.suppliers, data.keywords);
|
||||
|
||||
return runRestore(async (db) => {
|
||||
// Wipe keywords, suppliers, categories
|
||||
await db.execute("DELETE FROM keywords");
|
||||
|
|
@ -331,17 +531,23 @@ export async function importCategoriesOnly(
|
|||
await restoreCategories(db, data.categories);
|
||||
await restoreSuppliers(db, data.suppliers);
|
||||
await restoreKeywords(db, data.keywords);
|
||||
|
||||
// No transaction is deleted: every transfer stays linked.
|
||||
return { unlinkedTransfers: 0, uncategorizedTransactions: 0 };
|
||||
});
|
||||
}
|
||||
|
||||
export async function importTransactionsWithCategories(
|
||||
data: ExportEnvelope["data"],
|
||||
filename: string
|
||||
): Promise<void> {
|
||||
): Promise<RestoreOutcome> {
|
||||
validateImportedFormatRows(data.import_sources, data.import_config_templates);
|
||||
const { keepIds } = validateImportedTransactionIds(data.transactions);
|
||||
validateImportedCategoryReferences(data.categories, data.suppliers, data.keywords);
|
||||
|
||||
const outcome = await runRestore(async (db) => {
|
||||
const transfers = await takeTransfers(db);
|
||||
|
||||
return runRestore(async (db) => {
|
||||
// Wipe everything
|
||||
await db.execute("DELETE FROM transactions");
|
||||
await db.execute("DELETE FROM imported_files");
|
||||
|
|
@ -361,18 +567,33 @@ export async function importTransactionsWithCategories(
|
|||
);
|
||||
await restoreImportSources(db, data.import_sources, templateIds);
|
||||
|
||||
await attachTransactions(db, data.transactions, filename, keepIds);
|
||||
const uncategorizedTransactions = await attachTransactions(
|
||||
db,
|
||||
data.transactions,
|
||||
filename,
|
||||
keepIds
|
||||
);
|
||||
const unlinkedTransfers = await restoreTransfers(
|
||||
db,
|
||||
transfers,
|
||||
data.transactions,
|
||||
keepIds
|
||||
);
|
||||
return { unlinkedTransfers, uncategorizedTransactions };
|
||||
});
|
||||
return reportOutcome(outcome);
|
||||
}
|
||||
|
||||
export async function importTransactionsOnly(
|
||||
data: ExportEnvelope["data"],
|
||||
filename: string
|
||||
): Promise<void> {
|
||||
): Promise<RestoreOutcome> {
|
||||
validateImportedFormatRows(data.import_sources, data.import_config_templates);
|
||||
const { keepIds } = validateImportedTransactionIds(data.transactions);
|
||||
|
||||
return runRestore(async (db) => {
|
||||
const outcome = await runRestore(async (db) => {
|
||||
const transfers = await takeTransfers(db);
|
||||
|
||||
// Wipe transactions and import history
|
||||
await db.execute("DELETE FROM transactions");
|
||||
await db.execute("DELETE FROM imported_files");
|
||||
|
|
@ -384,6 +605,19 @@ export async function importTransactionsOnly(
|
|||
);
|
||||
await restoreImportSources(db, data.import_sources, templateIds);
|
||||
|
||||
await attachTransactions(db, data.transactions, filename, keepIds);
|
||||
const uncategorizedTransactions = await attachTransactions(
|
||||
db,
|
||||
data.transactions,
|
||||
filename,
|
||||
keepIds
|
||||
);
|
||||
const unlinkedTransfers = await restoreTransfers(
|
||||
db,
|
||||
transfers,
|
||||
data.transactions,
|
||||
keepIds
|
||||
);
|
||||
return { unlinkedTransfers, uncategorizedTransactions };
|
||||
});
|
||||
return reportOutcome(outcome);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue