From 4a579f10f96aabb1e9b95db78b027db00eb03080 Mon Sep 17 00:00:00 2001 From: le king fu Date: Wed, 4 Nov 2026 21:36:55 -0500 Subject: [PATCH] fix: restore a backup's split lines with their parent (#518) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The restore inserted every transaction without its id and copied the exported parent_transaction_id. In the same profile the AUTOINCREMENT sequence survives the DELETE, so the first split line pointed at an id that no longer existed: FOREIGN KEY constraint failed and the whole restore rolled back, in both modes and through "Rétablir la sauvegarde". In a new profile the split lines hung, without a word, off whichever row had taken their parent's old id. - attachTransactions puts each row back with its exported id, as the categories, suppliers and keywords already are, in two passes: the rows without a parent, then the split lines, file order kept in each. - validateImportedTransactionIds (pure, dataExportService.ts) runs at the parse (JSON and CSV) and again at the head of both restores. The rows keep their ids only when each bears a safe integer from 1 to 2147483647 that no other row bears; otherwise SQLite gives new ones, and a file holding a split line is refused before anything is deleted (SrefValidationError, orphanSplitLines), as is a split line that does not name a row of the file without a parent. - The CSV export starts with an id column; parseImportedCsv reads id and parent_transaction_id as /^\d+$/ only and never takes the line number for an id, so a CSV exported before the fix that holds a split is refused with the message. - restoreFromBackup no longer wraps an SrefValidationError in a RestoreError, and the restore window shows t(e.i18nKey, e.params). Regression test src/__integration__/restore.test.ts (real services on node:sqlite, consolidated_schema.sql, foreign keys on): 13 of its 14 cases red on the base, all green here. Co-Authored-By: Claude Opus 5.5 --- src/__integration__/restore.test.ts | 383 ++++++++++++++++++ .../CategoriesMigrationRestoreModal.tsx | 3 + ...goriesMigrationRestoreModal.wiring.test.ts | 99 +++++ src/i18n/locales/en.json | 3 +- src/i18n/locales/fr.json | 3 +- src/services/categoryRestoreService.test.ts | 93 ++++- src/services/categoryRestoreService.ts | 11 +- src/services/dataExportService.test.ts | 185 +++++++++ src/services/dataExportService.ts | 123 +++++- src/services/dataRestoreService.ts | 71 +++- 10 files changed, 937 insertions(+), 37 deletions(-) create mode 100644 src/__integration__/restore.test.ts create mode 100644 src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts diff --git a/src/__integration__/restore.test.ts b/src/__integration__/restore.test.ts new file mode 100644 index 0000000..3101eef --- /dev/null +++ b/src/__integration__/restore.test.ts @@ -0,0 +1,383 @@ +/** + * Restoring a backup that holds a split (#518). + * + * 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 + * the same profile, the AUTOINCREMENT sequence survives the DELETE, so the + * first split line pointed at an id that no longer existed: « FOREIGN KEY + * constraint failed », and the whole restore rolled back, « Rétablir la + * sauvegarde » included. In a new profile, the line hung off whichever row had + * taken its parent's old id. The rows now go back with their exported ids, the + * lines without a parent first, and a file whose split lines cannot find their + * parent is refused before anything is deleted. + * + * 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` + * is replaced by the adapter of `split-offset-manual-flag.test.ts`, copied here + * (#392 plans a shared harness): `select` and `execute` run the statement with + * its `$N` bound by name, `execute` answers `rowsAffected` and `lastInsertId`, + * `withTransaction` hands its callback the same handle, and `getDb()` throws + * while a transaction runs, where the real lock, which is not reentrant, would + * deadlock. A second database stands for a new profile. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { readFileSync } from "fs"; +import { resolve } from "path"; +import { DatabaseSync, type SQLInputValue } from "node:sqlite"; + +const fake = vi.hoisted(() => ({ + handle: null as unknown, + inTransaction: false, +})); + +vi.mock("../services/db", () => ({ + getDb: vi.fn(async () => { + if (fake.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock"); + return fake.handle; + }), + withTransaction: vi.fn(async (fn: (db: unknown) => Promise) => { + fake.inTransaction = true; + try { + return await fn(fake.handle); + } finally { + fake.inTransaction = false; + } + }), +})); + +// « Rétablir la sauvegarde » reads its file through `read_import_file`. +const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() })); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import { getSplitChildren, saveSplitAdjustment } from "../services/transactionService"; +import { + getExportCategories, + getExportImportSources, + getExportImportTemplates, + getExportKeywords, + getExportSuppliers, + getExportTransactions, + parseImportedCsv, + parseImportedJson, + serializeToJson, + serializeTransactionsToCsv, + SrefValidationError, + type ExportEnvelope, + type ExportTransaction, +} from "../services/dataExportService"; +import { importTransactionsOnly, importTransactionsWithCategories } from "../services/dataRestoreService"; +import { restoreFromBackup } from "../services/categoryRestoreService"; + +const SCHEMA = readFileSync( + resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"), + "utf-8", +); + +/** Categories of the seed of a new profile. */ +const GROCERIES = 1111; // « Épicerie régulière » +const B = 1112; // « Boucherie & poissonnerie », where the split sends −50 +const RENT = 1211; // « Loyer » +const ELECTRICITY = 1221; // « Électricité » +const PAY = 1011; // « Paie régulière » + +const REFUSAL = "settings.dataManagement.import.errors.orphanSplitLines"; + +/** What the split window of « EPICERIE METRO » shows: −50 sent to B, +50 cancelling it in its category. */ +const GROCERY_SPLIT = [ + { amount: -50, category_id: B }, + { amount: 50, category_id: GROCERIES }, +]; + +type Mode = "transactions_with_categories" | "transactions_only"; +const MODES: Mode[] = ["transactions_with_categories", "transactions_only"]; + +/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */ +function adapter(db: DatabaseSync) { + // tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name. + const bind = (params?: unknown[]) => + Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue])); + return { + select: async (sql: string, params?: unknown[]) => + db.prepare(sql).all(bind(params)).map((row) => ({ ...row })), + execute: async (sql: string, params?: unknown[]) => { + const result = db.prepare(sql).run(bind(params)); + return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) }; + }, + }; +} + +let opened: DatabaseSync[] = []; +/** The profile the backups are taken from. */ +let profile: DatabaseSync; + +/** A database with the schema of a new profile, foreign keys on. */ +function open(): DatabaseSync { + const db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true }); + db.exec(SCHEMA); + opened.push(db); + return db; +} + +/** Points the services at `db`. */ +function use(db: DatabaseSync): DatabaseSync { + fake.handle = adapter(db); + return db; +} + +/** A transaction as an import writes it, with its category; its id. */ +function imported(date: string, description: string, amount: number, categoryId: number): number { + const result = profile + .prepare( + `INSERT INTO transactions (date, description, amount, category_id, original_description) + VALUES ($date, $description, $amount, $category, $description)`, + ) + .run({ $date: date, $description: description, $amount: amount, $category: categoryId }); + return Number(result.lastInsertRowid); +} + +/** + * The profile of the probe of #518: the split parent is NOT the first + * transaction by date, so a restore that renumbers in the export's order + * (`ORDER BY t.date, t.id`) hands its old id to « LOYER ». + */ +beforeEach(async () => { + opened = []; + fake.inTransaction = false; + invoke.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); + expect(imported("2026-10-03", "PAIE", 2000, PAY)).toBe(3); + // Children 4 (−50 to B) and 5 (+50, the offset line), by the real service. + await saveSplitAdjustment(1, [{ category_id: B, amount: -50, description: "EPICERIE METRO" }]); +}); + +afterEach(() => { + for (const db of opened) db.close(); +}); + +type Row = { + id: number; + date: string; + description: string; + amount: number; + category_id: number | null; + is_manually_categorized: number; + is_split: number; + parent_transaction_id: number | null; +}; + +/** Every transaction of `db`, by id: what a restore must give back as it was. */ +function rows(db: DatabaseSync): Row[] { + return db + .prepare( + `SELECT id, date, description, amount, category_id, is_manually_categorized, is_split, parent_transaction_id + FROM transactions ORDER BY id`, + ) + .all() + .map((row) => ({ ...row })) as Row[]; +} + +/** What the reports add up, per category: every row, split parent and children included. */ +function totals(db: DatabaseSync): Record { + const sums = db + .prepare("SELECT category_id, SUM(amount) AS total FROM transactions GROUP BY category_id") + .all() as Array<{ category_id: number | null; total: number }>; + return Object.fromEntries(sums.map((r) => [r.category_id === null ? "none" : String(r.category_id), r.total])); +} + +function count(db: DatabaseSync, table: string): number { + return Number((db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n); +} + +/** What the split window of the transaction `description` shows, through the real service. */ +async function splitLines(db: DatabaseSync, description: string) { + const parent = db + .prepare("SELECT id FROM transactions WHERE description = $description AND parent_transaction_id IS NULL") + .get({ $description: description }) as { id: number }; + const lines = await getSplitChildren(parent.id); + return lines.map((line) => ({ amount: line.amount, category_id: line.category_id })); +} + +/** What « Exporter » gathers for `mode` (`useDataExport`), from the database in use. */ +async function exportData(mode: Mode): Promise { + const data: ExportEnvelope["data"] = {}; + if (mode === "transactions_with_categories") { + data.categories = await getExportCategories(); + data.suppliers = await getExportSuppliers(); + data.keywords = await getExportKeywords(); + } + data.transactions = await getExportTransactions(); + data.import_sources = await getExportImportSources(); + data.import_config_templates = await getExportImportTemplates(); + return data; +} + +/** A JSON backup of the database in use, written then read back as the import reads it. */ +async function jsonBackup(mode: Mode): Promise { + return parseImportedJson(serializeToJson(mode, await exportData(mode), "0.17.2")).envelope.data; +} + +function restore(mode: Mode, data: ExportEnvelope["data"], filename = "backup.json"): Promise { + return mode === "transactions_with_categories" + ? importTransactionsWithCategories(data, filename) + : importTransactionsOnly(data, filename); +} + +/** The refusal of a file whose split lines cannot find their parent. */ +function expectRefusal(error: unknown): void { + expect(error).toBeInstanceOf(SrefValidationError); + expect((error as SrefValidationError).i18nKey).toBe(REFUSAL); +} + +/** + * The probe's profile as the CSV export wrote it before #518: no `id` column, + * so the `parent_transaction_id` of the two split lines (1) names a row the + * file never names. + */ +const PRE_FIX_CSV = [ + "date,description,amount,category_name,category_id,original_description,notes,is_manually_categorized,is_split,parent_transaction_id", + "2026-10-01,LOYER,-1000,Loyer,1211,LOYER,,0,0,", + "2026-10-03,PAIE,2000,Paie régulière,1011,PAIE,,0,0,", + "2026-10-05,EPICERIE METRO,-120,Épicerie régulière,1111,EPICERIE METRO,,0,1,", + "2026-10-05,EPICERIE METRO,-50,Boucherie & poissonnerie,1112,EPICERIE METRO,,0,1,1", + "2026-10-05,EPICERIE METRO,50,Épicerie régulière,1111,EPICERIE METRO,,0,1,1", +].join("\r\n"); + +describe("restoring a backup that holds a split (#518)", () => { + it("the profile of the probe: the split parent comes third in the export, after « LOYER » and « PAIE »", async () => { + const exported = await getExportTransactions(); + expect(exported.map((tx) => [tx.id, tx.description, tx.parent_transaction_id])).toEqual([ + [2, "LOYER", null], + [3, "PAIE", null], + [1, "EPICERIE METRO", null], + [4, "EPICERIE METRO", 1], + [5, "EPICERIE METRO", 1], + ]); + expect(await splitLines(profile, "EPICERIE METRO")).toEqual(GROCERY_SPLIT); + }); + + it.each(MODES)("%s, same profile: the restore succeeds and each split line keeps its parent", async (mode) => { + const before = rows(profile); + const totalsBefore = totals(profile); + const data = await jsonBackup(mode); + + await restore(mode, data); + + expect(rows(profile)).toEqual(before); + expect(await splitLines(profile, "EPICERIE METRO")).toEqual(GROCERY_SPLIT); + expect(totals(profile)).toEqual(totalsBefore); + }); + + it.each(MODES)("%s, new profile: the same links, nothing hangs off « LOYER »", async (mode) => { + const before = rows(profile); + const totalsBefore = totals(profile); + const data = await jsonBackup(mode); + + const fresh = use(open()); + await restore(mode, data); + + expect(rows(fresh)).toEqual(before); + expect(await splitLines(fresh, "LOYER")).toEqual([]); + expect(await splitLines(fresh, "EPICERIE METRO")).toEqual(GROCERY_SPLIT); + expect(totals(fresh)).toEqual(totalsBefore); + }); + + it("a split line listed before its parent still finds it: the lines without a parent go in first", async () => { + const before = rows(profile); + const data = await jsonBackup("transactions_only"); + const reversed = { ...data, transactions: [...(data.transactions ?? [])].reverse() }; + expect(reversed.transactions[0].parent_transaction_id).toBe(1); + + const fresh = use(open()); + await importTransactionsOnly(reversed, "backup.json"); + + expect(rows(fresh)).toEqual(before); + expect(await splitLines(fresh, "EPICERIE METRO")).toEqual(GROCERY_SPLIT); + }); + + it.each(["same profile", "new profile"])("a CSV export starts with an `id` column and restores its splits (%s)", async (target) => { + const before = rows(profile); + const csv = serializeTransactionsToCsv(await getExportTransactions()); + expect(csv.split(/\r?\n/)[0].split(",")[0]).toBe("id"); + + const { transactions } = parseImportedCsv(csv); + const db = target === "same profile" ? profile : use(open()); + await importTransactionsOnly({ transactions }, "export.csv"); + + expect(rows(db)).toEqual(before); + expect(await splitLines(db, "LOYER")).toEqual([]); + expect(await splitLines(db, "EPICERIE METRO")).toEqual(GROCERY_SPLIT); + }); + + it("a CSV exported before the fix that holds a split is refused, at the parse and at the head of the restore; the profile is intact", async () => { + const before = rows(profile); + const files = count(profile, "imported_files"); + + let refusal: unknown = null; + try { + parseImportedCsv(PRE_FIX_CSV); + } catch (e) { + refusal = e; + } + expectRefusal(refusal); + + // What the parse of the time handed the restore: each line's number as its id. + const asReadThen: ExportTransaction[] = (await getExportTransactions()).map((tx, i) => ({ ...tx, id: i })); + await importTransactionsOnly({ transactions: asReadThen }, "old.csv").then( + () => expect.unreachable("the restore should have been refused"), + expectRefusal, + ); + + expect(rows(profile)).toEqual(before); + expect(count(profile, "imported_files")).toBe(files); + }); + + it.each(MODES)("%s: a backup whose ids repeat cannot place its split lines: refused before anything is deleted", async (mode) => { + const before = rows(profile); + const categories = count(profile, "categories"); + const data = await jsonBackup(mode); + // Two rows share an id: no row keeps its own, and nothing tells a split line its parent. + const repeated = { ...data, transactions: (data.transactions ?? []).map((tx) => (tx.id === 3 ? { ...tx, id: 2 } : tx)) }; + + await restore(mode, repeated).then(() => expect.unreachable("the restore should have been refused"), expectRefusal); + + expect(rows(profile)).toEqual(before); + expect(count(profile, "categories")).toBe(categories); + }); + + it.each(["same profile", "new profile"])("after a restore, a new split saves (%s)", async (target) => { + const data = await jsonBackup("transactions_only"); + const db = target === "same profile" ? profile : use(open()); + await importTransactionsOnly(data, "backup.json"); + + const rent = db.prepare("SELECT id FROM transactions WHERE description = 'LOYER'").get() as { id: number }; + // Its two lines take the next ids, which no restored row holds. + await saveSplitAdjustment(rent.id, [{ category_id: ELECTRICITY, amount: -200, description: "LOYER" }]); + + expect(await splitLines(db, "LOYER")).toEqual([ + { amount: -200, category_id: ELECTRICITY }, + { amount: 200, category_id: RENT }, + ]); + expect(await splitLines(db, "EPICERIE METRO")).toEqual(GROCERY_SPLIT); + }); + + 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); + + expect(rows(profile)).toEqual(before); + expect(await splitLines(profile, "EPICERIE METRO")).toEqual(GROCERY_SPLIT); + }); +}); diff --git a/src/components/settings/CategoriesMigrationRestoreModal.tsx b/src/components/settings/CategoriesMigrationRestoreModal.tsx index e0953cc..d10192d 100644 --- a/src/components/settings/CategoriesMigrationRestoreModal.tsx +++ b/src/components/settings/CategoriesMigrationRestoreModal.tsx @@ -10,6 +10,7 @@ import { RestoreError, type RestorableMigrationJournal, } from "../../services/categoryRestoreService"; +import { SrefValidationError } from "../../services/dataExportService"; // ----------------------------------------------------------------------------- // Confirmation modal used by both the in-window banner and the permanent @@ -73,6 +74,8 @@ export default function CategoriesMigrationRestoreModal({ // Centralised error mapping — keeps the rendered messages i18n-driven. function messageForError(e: unknown): string { + // A file the import boundary refuses says what is wrong with it (#518). + if (e instanceof SrefValidationError) return t(e.i18nKey, e.params); if (e instanceof RestoreError) { return t( `settings.categoriesCard.restoreModal.errors.${e.code}`, diff --git a/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts b/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts new file mode 100644 index 0000000..cf5fbe2 --- /dev/null +++ b/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts @@ -0,0 +1,99 @@ +// CategoriesMigrationRestoreModal — what « Rétablir la sauvegarde » shows when +// the import boundary refuses the backup (#518). +// +// 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. +import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest"; +import type { ReactNode } from "react"; + +vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); +vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); +vi.mock("react-dom", async (orig) => ({ + ...(await orig()), + createPortal: (children: ReactNode) => children, +})); +const { restoreFromBackup } = vi.hoisted(() => ({ restoreFromBackup: vi.fn() })); +vi.mock("../../services/categoryRestoreService", async (orig) => ({ + ...(await orig()), + backupFileExists: vi.fn(async () => true), + isFileEncrypted: vi.fn(async () => false), + pickBackupFile: vi.fn(async () => null), + restoreFromBackup, +})); + +import { hookHarness } from "../../test/hookHarness"; +import { find, texts } from "../../test/elementTree"; +import CategoriesMigrationRestoreModal from "./CategoriesMigrationRestoreModal"; +import { RestoreError, type RestorableMigrationJournal } from "../../services/categoryRestoreService"; +import { SrefValidationError } from "../../services/dataExportService"; + +const harness = hookHarness(); + +const JOURNAL: RestorableMigrationJournal = { + timestamp: "2026-10-01T10:00:00Z", + backupPath: "/tmp/profile_avant-migration.sref", + outcome: { + insertedV1Count: 1, + updatedTransactionsCount: 2, + updatedBudgetsCount: 0, + updatedKeywordsCount: 0, + deletedV2Count: 0, + customPreservedCount: 0, + }, +}; + +const PROPS = { journal: JOURNAL, onClose: vi.fn(), onRestored: vi.fn() }; + +/** 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 { + const [button] = find( + render(), + (el) => el.type === "button" && texts(el).includes("t(settings.categoriesCard.restoreModal.confirm)"), + ); + await (button.props.onClick as () => Promise)(); +} + +beforeAll(() => { + vi.stubGlobal("document", { body: {} }); +}); + +afterAll(() => { + vi.unstubAllGlobals(); +}); + +beforeEach(() => { + harness.clear(); + restoreFromBackup.mockReset(); + PROPS.onRestored.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( + new SrefValidationError("settings.dataManagement.import.errors.orphanSplitLines", {}), + ); + + await confirm(); + + const shown = texts(render()); + expect(restoreFromBackup).toHaveBeenCalledWith(JOURNAL.backupPath, null); + expect(shown).toContain("t(settings.dataManagement.import.errors.orphanSplitLines[])"); + expect(shown.join(" ")).not.toMatch(/parse_failed|import_failed/); + 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")); + + await confirm(); + + expect(texts(render()).join(" ")).toContain("t(settings.categoriesCard.restoreModal.errors.import_failed"); + }); +}); diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index d46d15f..774e17b 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -780,7 +780,8 @@ "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." + "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." } } }, diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index c8256f3..89e653c 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -780,7 +780,8 @@ "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é." + "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é." } } }, diff --git a/src/services/categoryRestoreService.test.ts b/src/services/categoryRestoreService.test.ts index 0edb34b..ed9828e 100644 --- a/src/services/categoryRestoreService.test.ts +++ b/src/services/categoryRestoreService.test.ts @@ -1,9 +1,22 @@ -import { describe, it, expect } from "vitest"; +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(() => ({ + invoke: vi.fn(), + importTransactionsWithCategories: vi.fn(), +})); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); +vi.mock("./dataRestoreService", () => ({ importTransactionsWithCategories })); + import { isWithinBannerWindow, + restoreFromBackup, + RestoreError, shouldShowBanner, type RestorableMigrationJournal, } from "./categoryRestoreService"; +import { serializeToJson, SrefValidationError } from "./dataExportService"; const DAY = 24 * 60 * 60 * 1000; @@ -105,3 +118,81 @@ describe("shouldShowBanner", () => { expect(shouldShowBanner(journal(), "", now)).toBe(true); }); }); + +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"; + + /** 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, + }, + ]); + + function reading(content: string) { + invoke.mockImplementation(async (cmd: string) => { + if (cmd === "read_import_file") return content; + throw new Error(`unexpected invoke: ${cmd}`); + }); + } + + /** What `restoreFromBackup` rejects with. */ + async function failure(): Promise { + return restoreFromBackup(PATH, null).then( + () => expect.unreachable("the restore should have failed"), + (e: unknown) => e, + ); + } + + beforeEach(() => { + invoke.mockReset(); + importTransactionsWithCategories.mockReset(); + }); + + 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(); + 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([])); + importTransactionsWithCategories.mockRejectedValue(new SrefValidationError(ORPHAN, {})); + const error = await failure(); + 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(); + expect(parse).toBeInstanceOf(RestoreError); + expect((parse as RestoreError).code).toBe("parse_failed"); + + reading(backup([])); + importTransactionsWithCategories.mockRejectedValue(new Error("FOREIGN KEY constraint failed")); + const restore = await failure(); + expect(restore).toBeInstanceOf(RestoreError); + expect((restore as RestoreError).code).toBe("import_failed"); + }); +}); diff --git a/src/services/categoryRestoreService.ts b/src/services/categoryRestoreService.ts index 064d22a..39dcf5f 100644 --- a/src/services/categoryRestoreService.ts +++ b/src/services/categoryRestoreService.ts @@ -1,5 +1,5 @@ import { invoke } from "@tauri-apps/api/core"; -import { parseImportedJson } from "./dataExportService"; +import { parseImportedJson, SrefValidationError } from "./dataExportService"; import { importTransactionsWithCategories } from "./dataRestoreService"; import { getPreference, setPreference } from "./userPreferenceService"; import type { LastMigrationJournal } from "./categoryMigrationService"; @@ -197,7 +197,9 @@ export async function pickBackupFile(): Promise { * (SREF magic detected). Pass `null` for plaintext JSON * backups or when the profile had no PIN. * - * Throws a `RestoreError` on any failure; on success updates + * 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. */ export async function restoreFromBackup( @@ -234,6 +236,9 @@ export async function restoreFromBackup( try { envelope = parseImportedJson(content).envelope; } catch (e) { + // A refusal of the import boundary keeps its own message: wrapped, the + // modal would show the generic parse failure instead (#518). + if (e instanceof SrefValidationError) throw e; const message = e instanceof Error ? e.message : String(e); throw new RestoreError("parse_failed", message); } @@ -252,6 +257,8 @@ export async function restoreFromBackup( try { 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; const message = e instanceof Error ? e.message : String(e); throw new RestoreError("import_failed", message); } diff --git a/src/services/dataExportService.test.ts b/src/services/dataExportService.test.ts index 0f4748f..99494e4 100644 --- a/src/services/dataExportService.test.ts +++ b/src/services/dataExportService.test.ts @@ -38,13 +38,17 @@ import { parseImportedCsv, parseImportedJson, serializeToJson, + serializeTransactionsToCsv, validateImportedFormatRows, + validateImportedTransactionIds, LEGACY_SREF_FORMAT_VERSION, + MAX_TRANSACTION_ID, SREF_FORMAT_VERSION, SrefValidationError, type ExportEnvelope, type ExportImportSource, type ExportImportTemplate, + type ExportTransaction, } from "./dataExportService"; import { importCategoriesOnly, @@ -707,6 +711,11 @@ describe("the refusal messages are translated (#331)", () => { } }); + it("carries the refusal of split lines that cannot find their parent in FR and EN (#518)", () => { + expect(fr.settings.dataManagement.import.errors.orphanSplitLines.length).toBeGreaterThan(0); + expect(en.settings.dataManagement.import.errors.orphanSplitLines.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"], @@ -730,6 +739,24 @@ describe("the refusal messages are translated (#331)", () => { expect(typeof resolved).toBe("string"); } } + + // The refusal of #518 carries no source name, and resolves in both bundles. + let refusal: unknown = null; + try { + validateImportedTransactionIds([{ ...transactionFixture(2), parent_transaction_id: 9 }]); + } catch (e) { + refusal = e; + } + expect(refusal).toBeInstanceOf(SrefValidationError); + const key = (refusal as SrefValidationError).i18nKey; + expect(key).toBe("settings.dataManagement.import.errors.orphanSplitLines"); + expect((refusal as SrefValidationError).params).toEqual({}); + for (const bundle of [fr, en]) { + const resolved = key + .split(".") + .reduce((node, part) => (node as Record)[part], bundle as unknown); + expect(typeof resolved).toBe("string"); + } }); }); @@ -882,3 +909,161 @@ describe("a committed restore is announced on the data channel (#396)", () => { expect(seen).toEqual([]); }); }); + +// --------------------------------------------------------------------------- +// 9. The rows keep their ids, a split line its parent (#518) +// --------------------------------------------------------------------------- + +describe("the rows keep their ids, and a split line its parent (#518)", () => { + const ORPHAN = "settings.dataManagement.import.errors.orphanSplitLines"; + + /** A split parent, with its own id. */ + const parent = (id: number): ExportTransaction => ({ ...transactionFixture(id), is_split: 1 }); + /** A split line that names `parentId`, with its own id. */ + const line = (id: number, parentId: unknown): ExportTransaction => ({ + ...transactionFixture(id), + is_split: 1, + parent_transaction_id: parentId as number, + }); + + /** The refusal `run` throws; fails when it throws nothing. */ + function refusalOf(run: () => unknown): SrefValidationError { + try { + run(); + } catch (e) { + expect(e).toBeInstanceOf(SrefValidationError); + return e as SrefValidationError; + } + return expect.unreachable("should have been refused"); + } + + it("keeps the ids of a file whose rows each bear a valid id of their own, the highest included", () => { + expect( + validateImportedTransactionIds([transactionFixture(1), transactionFixture(MAX_TRANSACTION_ID)]) + ).toEqual({ keepIds: true }); + expect(validateImportedTransactionIds([parent(1), line(2, 1), line(3, 1)])).toEqual({ keepIds: true }); + }); + + it.each([ + ["0", 0], + ["a negative id", -1], + ["one past the highest", MAX_TRANSACTION_ID + 1], + ["an id past 2^53, where JSON.parse rounds", 2 ** 53 + 2], + ["a fraction", 1.5], + ["a string", "2"], + ["null", null], + ["NaN, a CSV line without an id", NaN], + ])("gives no row its own id when one bears %s", (_label, id) => { + const rows = [transactionFixture(1), { ...transactionFixture(2), id: id as number }]; + expect(validateImportedTransactionIds(rows)).toEqual({ keepIds: false }); + }); + + it("gives no row its own id when two bear the same", () => { + expect(validateImportedTransactionIds([transactionFixture(1), transactionFixture(1)])).toEqual({ + keepIds: false, + }); + }); + + it.each<[string, ExportTransaction[]]>([ + ["names no row of the file", [parent(1), line(2, 9)]], + ["is its own parent", [transactionFixture(1), line(2, 2)]], + ["names another split line", [parent(1), line(2, 1), line(3, 2)]], + ["names its parent in a file whose ids repeat", [parent(1), line(2, 1), transactionFixture(2)]], + [ + "names its parent in a file without ids, as a CSV exported before #518", + [parent(1), line(2, 1)].map((tx) => ({ ...tx, id: NaN })), + ], + ["names its parent by 0", [parent(1), line(2, 0)]], + ["names its parent by a fraction", [parent(1), line(2, 1.5)]], + ["names its parent by a string", [parent(1), line(2, "1")]], + ])("refuses a file whose split line %s", (_label, rows) => { + expect(refusalOf(() => validateImportedTransactionIds(rows)).i18nKey).toBe(ORPHAN); + }); + + it("restores a file whose ids repeat, when it holds no split line, with the ids SQLite gives", async () => { + await importTransactionsOnly( + envelopeData({ transactions: [transactionFixture(5), transactionFixture(5)] }), + "backup.json" + ); + const inserts = db.execute.mock.calls + .map(([sql]) => sql as string) + .filter((sql) => sql.includes("INSERT INTO transactions")); + expect(inserts).toHaveLength(2); + for (const sql of inserts) expect(sql).toContain("INSERT INTO transactions (date,"); + }); + + it("restores the ids it keeps, the rows without a parent first, each pass in the order of the file", async () => { + await importTransactionsOnly( + envelopeData({ transactions: [line(3, 1), parent(1), line(2, 1)] }), + "backup.json" + ); + expect(db.tables.transactions.map((t) => [t.id, t.parent_transaction_id])).toEqual([ + [1, null], + [3, 1], + [2, 1], + ]); + }); + + it("refuses a JSON backup at PARSE time, so the confirmation never opens", () => { + const json = serializeToJson( + "transactions_only", + envelopeData({ transactions: [transactionFixture(1), line(2, 9)] }), + "0.17.2" + ); + expect(refusalOf(() => parseImportedJson(json)).i18nKey).toBe(ORPHAN); + }); + + it("refuses a CSV at PARSE time too", () => { + const csv = + "id,date,description,amount,is_split,parent_transaction_id\n" + + "1,2026-03-10,a,-10,1,\n" + + "2,2026-03-10,b,-4,1,9\n"; + expect(refusalOf(() => parseImportedCsv(csv)).i18nKey).toBe(ORPHAN); + }); + + it.each([ + [ + "transactions with categories", + (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json"), + ], + ["transactions only", (data: ExportEnvelope["data"]) => importTransactionsOnly(data, "backup.json")], + ] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => { + db.seed("transactions", [{ description: "existing tx" }]); + await expect(restore(envelopeData({ transactions: [line(2, 9)] }))).rejects.toBeInstanceOf( + SrefValidationError + ); + expect(db.log).toEqual([]); + expect(db.tables.transactions).toHaveLength(1); + }); + + it("writes the `id` column first in a CSV export", () => { + const [header, row] = serializeTransactionsToCsv([transactionFixture(7)]).split(/\r?\n/); + expect(header.split(",")[0]).toBe("id"); + expect(row.split(",")[0]).toBe("7"); + }); + + it("reads the `id` column of a CSV as digits only: « 12abc » is not 12, « 1.5 » is not 1", () => { + const csv = + "id,date,description,amount\n" + + "12abc,2026-01-01,a,-1\n" + + "1.5,2026-01-02,b,-2\n" + + "007,2026-01-03,c,-3\n" + + ",2026-01-04,d,-4\n"; + expect(parseImportedCsv(csv).transactions.map((t) => t.id)).toEqual([NaN, NaN, 7, NaN]); + }); + + it("never takes a line's number for its id: a CSV without an `id` column keeps no id of its own", () => { + const csv = "date,description,amount\n2026-01-01,a,-1\n2026-01-02,b,-2\n"; + const { transactions } = parseImportedCsv(csv); + expect(transactions.map((t) => t.id)).toEqual([NaN, NaN]); + expect(validateImportedTransactionIds(transactions)).toEqual({ keepIds: false }); + }); + + it("reads the parent of a CSV split line as digits only too: « 1abc » names no row", () => { + const csv = + "id,date,description,amount,is_split,parent_transaction_id\n" + + "1,2026-03-10,a,-10,1,\n" + + "2,2026-03-10,b,-4,1,1abc\n"; + expect(refusalOf(() => parseImportedCsv(csv)).i18nKey).toBe(ORPHAN); + }); +}); diff --git a/src/services/dataExportService.ts b/src/services/dataExportService.ts index 634eccd..23e7760 100644 --- a/src/services/dataExportService.ts +++ b/src/services/dataExportService.ts @@ -56,6 +56,12 @@ export interface ExportEnvelope { } export interface ExportTransaction { + /** + * The row's own id, which the restore gives back to it (#518): a split line + * names its parent by this id (`parent_transaction_id`). `NaN` when a CSV + * carries none, or one `parseImportedCsv` cannot read: a line's number is + * never taken for it. + */ id: number; date: string; description: string; @@ -112,20 +118,22 @@ export interface ImportSummary { formatVersion: number; } -/** i18n keys for the ways an imported configuration can be refused. */ +/** i18n keys for the ways an imported file can be refused. */ export type SrefValidationErrorKey = | "settings.dataManagement.import.errors.unsupportedAmountMode" | "settings.dataManagement.import.errors.unsupportedSignConvention" - | "settings.dataManagement.import.errors.invalidFormatRow"; + | "settings.dataManagement.import.errors.invalidFormatRow" + | "settings.dataManagement.import.errors.orphanSplitLines"; /** - * Thrown when a backup carries a configuration this build cannot store. + * Thrown when a backup carries a configuration this build cannot store, or + * split lines that cannot find their parent (#518). * * 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 * only once the restore had already started deleting. This is raised at the - * boundary, before anything is touched, and carries an i18n key plus the - * offending source name so the message can name what to fix. + * boundary, before anything is touched, and carries an i18n key plus, for a + * configuration, the offending source name so the message can name what to fix. */ export class SrefValidationError extends Error { readonly i18nKey: SrefValidationErrorKey; @@ -229,6 +237,8 @@ export function serializeTransactionsToCsv( ): string { return Papa.unparse( transactions.map((t) => ({ + // The id the `parent_transaction_id` of a split line names (#518). + id: t.id, date: t.date, description: t.description, amount: t.amount, @@ -288,6 +298,80 @@ export function validateImportedFormatRows( for (const source of sources ?? []) check(source, source?.name); } +/** The highest id a restored row may keep: the top of a signed 32-bit integer. */ +export const MAX_TRANSACTION_ID = 2_147_483_647; + +/** + * Whether `value` can be an id the restore gives back: a safe integer from 1 + * to `MAX_TRANSACTION_ID`. Past 2^53, `JSON.parse` rounds distinct ids into + * the same number; an id near 2^63 - 1 would leave the AUTOINCREMENT sequence + * no room for the rows inserted after the restore. + */ +function isTransactionId(value: unknown): value is number { + return ( + Number.isSafeInteger(value) && + (value as number) >= 1 && + (value as number) <= MAX_TRANSACTION_ID + ); +} + +/** + * Decide whether the transactions of a file keep their own ids, and refuse a + * file whose split lines cannot find their parent, BEFORE anything is deleted + * (#518). + * + * A split line names its parent by `parent_transaction_id`, a foreign key to + * `transactions.id`. The rows keep their ids only when each one bears a valid + * id (`isTransactionId`) that no other row bears; otherwise none keeps its own + * and SQLite gives them new ones, which only a file without split lines can + * afford. So a split line must name, by its id, a row of the file that has no + * parent itself, or the file is refused: a CSV exported before #518, which has + * no `id` column, a file whose ids repeat, a line that is its own parent and a + * line whose parent is a split line all end there. The foreign key alone would + * not do: in a new profile, a split line hangs without a word off whichever + * row took its parent's old id. + * + * PURE: no I/O, so it can be called from the parse step and again at the top of + * each restore, like `validateImportedFormatRows`. + */ +export function validateImportedTransactionIds( + transactions: ExportTransaction[] | undefined +): { keepIds: boolean } { + const rows = Array.isArray(transactions) ? transactions : []; + + let keepIds = true; + const ids = new Set(); + for (const tx of rows) { + const id = tx?.id; + if (!isTransactionId(id) || ids.has(id)) { + keepIds = false; + break; + } + ids.add(id); + } + + const splitLines = rows.filter((tx) => tx?.parent_transaction_id != null); + if (splitLines.length === 0) return { keepIds }; + + const refusal = () => + new SrefValidationError( + "settings.dataManagement.import.errors.orphanSplitLines", + {} + ); + if (!keepIds) throw refusal(); + + // The rows a split line may name: those without a parent, never the line + // itself nor another split line. Their ids all passed `isTransactionId`, so + // a parent outside that rule (0, 1.5, "1", 2^31) is never found either. + const parents = new Set( + rows.filter((tx) => tx.parent_transaction_id == null).map((tx) => tx.id) + ); + for (const line of splitLines) { + if (!parents.has(line.parent_transaction_id as number)) throw refusal(); + } + return { keepIds }; +} + export function parseImportedJson(content: string): { envelope: ExportEnvelope; summary: ImportSummary; @@ -316,12 +400,14 @@ export function parseImportedJson(content: string): { throw new Error(`Unknown export type: ${envelope.export_type}`); } - // Refuse an unreadable configuration while the file is only being LOOKED at: - // the confirmation dialog never opens, so nothing is deleted. + // 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. validateImportedFormatRows( envelope.data.import_sources, envelope.data.import_config_templates ); + validateImportedTransactionIds(envelope.data.transactions); return { envelope, @@ -338,6 +424,16 @@ export function parseImportedJson(content: string): { }; } +/** + * An id as a CSV cell holds it: digits only, else `NaN`, never the number + * `parseInt` reads off the start of the cell ("12abc" is 12, "1.5" is 1). + * Whether the restore may keep it is for `validateImportedTransactionIds` to + * say. + */ +function readCsvId(cell: string | undefined): number { + return cell !== undefined && /^\d+$/.test(cell) ? Number(cell) : NaN; +} + export function parseImportedCsv(content: string): { transactions: ExportTransaction[]; summary: ImportSummary; @@ -351,8 +447,10 @@ export function parseImportedCsv(content: string): { throw new Error(`CSV parse error: ${result.errors[0].message}`); } - const transactions: ExportTransaction[] = result.data.map((row, i) => ({ - id: i, + const transactions: ExportTransaction[] = result.data.map((row) => ({ + // Read from the `id` column alone: without it, no line keeps an id of its + // own, and its line number is never taken for one (#518). + id: readCsvId(row.id), date: row.date ?? "", description: row.description ?? "", amount: parseFloat(row.amount) || 0, @@ -363,11 +461,16 @@ export function parseImportedCsv(content: string): { // An export from the time of #390 carries "true" in this column. is_manually_categorized: toSqlFlag(row.is_manually_categorized), is_split: parseInt(row.is_split) || 0, + // Read like `id`: "12abc" names no row, where `parseInt` read row 12. parent_transaction_id: row.parent_transaction_id - ? parseInt(row.parent_transaction_id) + ? readCsvId(row.parent_transaction_id) : null, })); + // Refuse split lines that cannot find their parent, a CSV exported before + // #518 among them, while the file is only being LOOKED at. + validateImportedTransactionIds(transactions); + return { transactions, summary: { diff --git a/src/services/dataRestoreService.ts b/src/services/dataRestoreService.ts index 71567e7..8658662 100644 --- a/src/services/dataRestoreService.ts +++ b/src/services/dataRestoreService.ts @@ -5,6 +5,7 @@ import { toSqlFlag } from "../utils/sqlFlag"; import type { Category, Keyword, Supplier } from "../shared/types"; import { validateImportedFormatRows, + validateImportedTransactionIds, type ExportEnvelope, type ExportImportSource, type ExportImportTemplate, @@ -225,11 +226,22 @@ async function restoreImportSources( * already bear the name (an earlier restore of this same profile wrote one), in * which case it is reused rather than re-inserted: `import_sources.name` is * UNIQUE, and a collision here would roll back the entire restore. + * + * With `keepIds`, each row goes back with its own id (#518), as categories, + * suppliers and keywords do: a split line names its parent by that id, which + * an insert without it would hand to another row, or to no row at all in the + * same profile, whose AUTOINCREMENT sequence survives the DELETE. Without + * `keepIds`, SQLite gives every row a new id, which + * `validateImportedTransactionIds` allows only for a file without split lines. + * 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. */ async function attachTransactions( db: Database, transactions: ExportTransaction[] | undefined, - filename: string + filename: string, + keepIds: boolean ): Promise { if (!transactions || transactions.length === 0) return; @@ -267,25 +279,38 @@ async function attachTransactions( ); const fileId = fileResult.lastInsertId; - for (const tx of transactions) { - await db.execute( - `INSERT INTO transactions (date, description, amount, category_id, original_description, notes, is_manually_categorized, is_split, parent_transaction_id, source_id, file_id) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, - [ - tx.date, - tx.description, - tx.amount, - 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), - tx.is_split, - tx.parent_transaction_id, - sourceId, - fileId, - ] - ); + const ordered = [ + ...transactions.filter((tx) => tx.parent_transaction_id == null), + ...transactions.filter((tx) => tx.parent_transaction_id != null), + ]; + for (const tx of ordered) { + const values = [ + tx.date, + tx.description, + tx.amount, + 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), + tx.is_split, + tx.parent_transaction_id, + sourceId, + fileId, + ]; + if (keepIds) { + await db.execute( + `INSERT INTO transactions (id, date, description, amount, category_id, original_description, notes, is_manually_categorized, is_split, parent_transaction_id, source_id, file_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, + [tx.id, ...values] + ); + } else { + await db.execute( + `INSERT INTO transactions (date, description, amount, category_id, original_description, notes, is_manually_categorized, is_split, parent_transaction_id, source_id, file_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, + values + ); + } } } @@ -314,6 +339,7 @@ export async function importTransactionsWithCategories( filename: string ): Promise { validateImportedFormatRows(data.import_sources, data.import_config_templates); + const { keepIds } = validateImportedTransactionIds(data.transactions); return runRestore(async (db) => { // Wipe everything @@ -335,7 +361,7 @@ export async function importTransactionsWithCategories( ); await restoreImportSources(db, data.import_sources, templateIds); - await attachTransactions(db, data.transactions, filename); + await attachTransactions(db, data.transactions, filename, keepIds); }); } @@ -344,6 +370,7 @@ export async function importTransactionsOnly( filename: string ): Promise { validateImportedFormatRows(data.import_sources, data.import_config_templates); + const { keepIds } = validateImportedTransactionIds(data.transactions); return runRestore(async (db) => { // Wipe transactions and import history @@ -357,6 +384,6 @@ export async function importTransactionsOnly( ); await restoreImportSources(db, data.import_sources, templateIds); - await attachTransactions(db, data.transactions, filename); + await attachTransactions(db, data.transactions, filename, keepIds); }); }