From beae42e5cae35a0bca2059c3b51d45214df8ff6f Mon Sep 17 00:00:00 2001 From: le king fu Date: Wed, 4 Nov 2026 21:24:45 -0500 Subject: [PATCH] refactor: move the restore into dataRestoreService.ts (#518) Pure move, no behaviour change: runRestore, the five restore helpers, attachTransactions with its host source (HOST_SOURCE_NAME, HOST_SOURCE_MAPPING, used by it alone) and the three import entry points leave dataExportService.ts, byte for byte, for the new src/services/dataRestoreService.ts. The envelope types, the export, the parse and the validations of the import boundary stay where they were. useDataImport.ts and categoryRestoreService.ts import the restore from its new place; dataExportService.test.ts imports it from there, and category-migration.test.ts mocks it there. Readable by git diff --color-moved=zebra: only imports and the header of the new file are not moved lines. npm run build green; vitest 177 files / 2902 tests green, as on main. Co-Authored-By: Claude Opus 5.5 --- .../category-migration.test.ts | 13 +- src/hooks/useDataImport.ts | 8 +- src/services/categoryRestoreService.ts | 6 +- src/services/dataExportService.test.ts | 8 +- src/services/dataExportService.ts | 348 +---------------- src/services/dataRestoreService.ts | 362 ++++++++++++++++++ 6 files changed, 386 insertions(+), 359 deletions(-) create mode 100644 src/services/dataRestoreService.ts diff --git a/src/__integration__/category-migration.test.ts b/src/__integration__/category-migration.test.ts index fda6448..9348ce7 100644 --- a/src/__integration__/category-migration.test.ts +++ b/src/__integration__/category-migration.test.ts @@ -31,7 +31,8 @@ vi.mock("@tauri-apps/api/app", () => ({ })); // dataExportService helpers are used by both the backup service and the -// restore service. We mock the "DB-reading" ones and keep the parsers real. +// restore service, which writes the backup back through dataRestoreService. We +// mock the "DB-reading" ones and that write, and keep the parsers real. vi.mock("../services/dataExportService", async () => { const actual = await vi.importActual< typeof import("../services/dataExportService") @@ -42,6 +43,14 @@ vi.mock("../services/dataExportService", async () => { getExportSuppliers: vi.fn(async () => []), getExportKeywords: vi.fn(async () => []), getExportTransactions: vi.fn(async () => []), + }; +}); +vi.mock("../services/dataRestoreService", async () => { + const actual = await vi.importActual< + typeof import("../services/dataRestoreService") + >("../services/dataRestoreService"); + return { + ...actual, importTransactionsWithCategories: vi.fn(async () => undefined), }; }); @@ -52,7 +61,7 @@ import { computeMigrationPlan } from "../services/categoryMappingService"; import { createPreMigrationBackup } from "../services/categoryBackupService"; import { applyMigration } from "../services/categoryMigrationService"; import { restoreFromBackup } from "../services/categoryRestoreService"; -import { importTransactionsWithCategories } from "../services/dataExportService"; +import { importTransactionsWithCategories } from "../services/dataRestoreService"; import { makeV2Profile, makeV2ProfileWithCustom } from "../__fixtures__/profiles"; import type { Profile } from "../services/profileService"; diff --git a/src/hooks/useDataImport.ts b/src/hooks/useDataImport.ts index 8711db6..77a9619 100644 --- a/src/hooks/useDataImport.ts +++ b/src/hooks/useDataImport.ts @@ -4,13 +4,15 @@ import { invoke } from "@tauri-apps/api/core"; import { parseImportedJson, parseImportedCsv, - importCategoriesOnly, - importTransactionsWithCategories, - importTransactionsOnly, SrefValidationError, type ExportEnvelope, type ImportSummary, } from "../services/dataExportService"; +import { + importCategoriesOnly, + importTransactionsWithCategories, + importTransactionsOnly, +} from "../services/dataRestoreService"; type ImportStatus = | "idle" diff --git a/src/services/categoryRestoreService.ts b/src/services/categoryRestoreService.ts index 9f67c9e..064d22a 100644 --- a/src/services/categoryRestoreService.ts +++ b/src/services/categoryRestoreService.ts @@ -1,8 +1,6 @@ import { invoke } from "@tauri-apps/api/core"; -import { - parseImportedJson, - importTransactionsWithCategories, -} from "./dataExportService"; +import { parseImportedJson } from "./dataExportService"; +import { importTransactionsWithCategories } from "./dataRestoreService"; import { getPreference, setPreference } from "./userPreferenceService"; import type { LastMigrationJournal } from "./categoryMigrationService"; diff --git a/src/services/dataExportService.test.ts b/src/services/dataExportService.test.ts index 676f190..0f4748f 100644 --- a/src/services/dataExportService.test.ts +++ b/src/services/dataExportService.test.ts @@ -35,9 +35,6 @@ import { getDb, withTransaction } from "./db"; import { getExportImportSources, getExportImportTemplates, - importCategoriesOnly, - importTransactionsOnly, - importTransactionsWithCategories, parseImportedCsv, parseImportedJson, serializeToJson, @@ -49,6 +46,11 @@ import { type ExportImportSource, type ExportImportTemplate, } from "./dataExportService"; +import { + importCategoriesOnly, + importTransactionsOnly, + importTransactionsWithCategories, +} from "./dataRestoreService"; import { subscribeDataChanged } from "./dataEvents"; import { formatFromRow, FORMAT_FIELD_PAIRS } from "../utils/importFormat"; import type { Category } from "../shared/types"; diff --git a/src/services/dataExportService.ts b/src/services/dataExportService.ts index 5663f39..634eccd 100644 --- a/src/services/dataExportService.ts +++ b/src/services/dataExportService.ts @@ -1,6 +1,4 @@ -import type Database from "@tauri-apps/plugin-sql"; -import { getDb, withTransaction } from "./db"; -import { notifyDataChanged } from "./dataEvents"; +import { getDb } from "./db"; import Papa from "papaparse"; import { toSqlFlag } from "../utils/sqlFlag"; import type { @@ -385,347 +383,3 @@ export function parseImportedCsv(content: string): { }, }; } - -// --- Import execution --- - -/** - * The source that hosts transactions restored from a file, which describe no - * import folder of their own. - * - * Its mapping used to be `'{}'`, which `formatFromRow` cannot decode — a source - * the app itself wrote and then refused to read. It describes the CSV this very - * service exports instead: date, description, amount, comma-separated, ISO - * dates, expenses negative. That is true of the file the rows came from, so the - * wizard finds a usable format if a folder ever bears this name. - */ -const HOST_SOURCE_NAME = "Data Import"; -const HOST_SOURCE_MAPPING = JSON.stringify({ - date: 0, - description: 1, - amount: 2, -}); - -/** - * Run `body` as one all-or-nothing restore. - * - * Every one of these functions starts by DELETING the profile's financial - * history and then re-inserts it row by row, against tables carrying - * `UNIQUE(name)` and a foreign key. Without a transaction, the first constraint - * violation leaves the profile emptied at whatever row it reached, with nothing - * to go back to. `withTransaction` holds the single DB lock for the whole - * BEGIN..COMMIT so the statements cannot be split across pooled connections - * (see `db.ts`); the BEGIN/COMMIT/ROLLBACK themselves are ours to issue. - * - * 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). - */ -async function runRestore( - body: (db: Database) => Promise -): Promise { - await withTransaction(async (db) => { - await db.execute("BEGIN"); - let open = true; - try { - await body(db); - await db.execute("COMMIT"); - open = false; - } catch (e) { - if (open) { - try { - await db.execute("ROLLBACK"); - } catch { - // Preserve the original error — it is the one that explains the failure. - } - } - throw e; - } - }); - notifyDataChanged(); -} - -async function restoreCategories( - db: Database, - categories: Category[] | undefined -): Promise { - for (const cat of categories ?? []) { - await db.execute( - `INSERT INTO categories (id, name, parent_id, color, icon, type, is_active, is_inputable, sort_order) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, - [ - cat.id, - cat.name, - cat.parent_id ?? null, - cat.color ?? null, - cat.icon ?? null, - cat.type, - cat.is_active ? 1 : 0, - cat.is_inputable ? 1 : 0, - cat.sort_order, - ] - ); - } -} - -async function restoreSuppliers( - db: Database, - suppliers: Supplier[] | undefined -): Promise { - for (const sup of suppliers ?? []) { - await db.execute( - `INSERT INTO suppliers (id, name, normalized_name, category_id, is_active) - VALUES ($1, $2, $3, $4, $5)`, - [sup.id, sup.name, sup.normalized_name, sup.category_id ?? null, sup.is_active ? 1 : 0] - ); - } -} - -async function restoreKeywords( - db: Database, - keywords: Keyword[] | undefined -): Promise { - for (const kw of keywords ?? []) { - await db.execute( - `INSERT INTO keywords (id, keyword, category_id, supplier_id, priority, is_active) - VALUES ($1, $2, $3, $4, $5, $6)`, - [kw.id, kw.keyword, kw.category_id, kw.supplier_id ?? null, kw.priority, kw.is_active ? 1 : 0] - ); - } -} - -/** - * Restore the templates and return their resolved ids, keyed by name. - * - * `import_config_templates` is in NEITHER wipe list, and restoring into a - * profile that already has templates is the normal path, not an edge case — a - * plain INSERT would hit `UNIQUE constraint failed: import_config_templates.name` - * and (now) roll the whole restore back. Wiping the table instead was the other - * option and was rejected: it would destroy templates the user never asked to - * replace and that no confirmation dialog mentions. So: upsert by name, and give - * the caller the map it needs to remap `import_sources.template_id`, since the - * ids in the file mean nothing here. - * - * Templates go in BEFORE sources — `template_id` is a foreign key to this table. - */ -async function restoreImportTemplates( - db: Database, - templates: ExportImportTemplate[] | undefined -): Promise> { - const idsByName = new Map(); - for (const template of templates ?? []) { - await db.execute( - `INSERT INTO import_config_templates (name, delimiter, encoding, date_format, skip_lines, has_header, column_mapping, amount_mode, sign_convention) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) - ON CONFLICT(name) DO UPDATE SET - delimiter = excluded.delimiter, - encoding = excluded.encoding, - date_format = excluded.date_format, - skip_lines = excluded.skip_lines, - has_header = excluded.has_header, - column_mapping = excluded.column_mapping, - amount_mode = excluded.amount_mode, - sign_convention = excluded.sign_convention`, - [ - template.name, - template.delimiter, - template.encoding, - template.date_format, - template.skip_lines, - template.has_header, - template.column_mapping, - template.amount_mode, - template.sign_convention, - ] - ); - // `lastInsertId` is 0 on the conflict branch, so the id is read back by - // name — the same reason `importSourceService.createSource` does it. - const rows = await db.select>( - "SELECT id FROM import_config_templates WHERE name = $1", - [template.name] - ); - if (rows.length > 0) idsByName.set(template.name, rows[0].id); - } - return idsByName; -} - -/** - * Restore the sources, resolving each `template_name` to the id the templates - * pass just settled. A name with no match becomes NULL: `template_id` is a - * provenance tag, never re-read as format, so losing it costs no configuration. - * - * Ids are not carried over — nothing in the envelope refers to a source by id. - */ -async function restoreImportSources( - db: Database, - sources: ExportImportSource[] | undefined, - templateIds: Map -): Promise { - for (const source of sources ?? []) { - await db.execute( - `INSERT INTO import_sources (name, description, date_format, delimiter, encoding, column_mapping, skip_lines, has_header, amount_mode, sign_convention, header_signature, template_id) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, - [ - source.name, - source.description ?? null, - source.date_format, - source.delimiter, - source.encoding, - source.column_mapping, - source.skip_lines, - source.has_header, - source.amount_mode, - source.sign_convention, - source.header_signature ?? null, - source.template_name !== null - ? templateIds.get(source.template_name) ?? null - : null, - ] - ); - } -} - -/** - * Attach the restored transactions to a source and one `imported_files` row. - * - * The host source is created ONLY here, and only when there are transactions to - * hang off it — it exists to satisfy `transactions.source_id`, not to stand in - * for the configurations the file now carries on its own. A restored source may - * 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. - */ -async function attachTransactions( - db: Database, - transactions: ExportTransaction[] | undefined, - filename: string -): Promise { - if (!transactions || transactions.length === 0) return; - - const existing = await db.select>( - "SELECT id FROM import_sources WHERE name = $1", - [HOST_SOURCE_NAME] - ); - let sourceId: number; - if (existing.length > 0) { - sourceId = existing[0].id; - } else { - const sourceResult = await db.execute( - `INSERT INTO import_sources (name, description, date_format, delimiter, encoding, column_mapping, skip_lines, has_header, amount_mode, sign_convention) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, - [ - HOST_SOURCE_NAME, - "Imported from settings", - "%Y-%m-%d", - ",", - "utf-8", - HOST_SOURCE_MAPPING, - 0, - 1, - "single", - "negative_expense", - ] - ); - sourceId = sourceResult.lastInsertId as number; - } - - const fileResult = await db.execute( - `INSERT INTO imported_files (source_id, filename, file_hash, row_count, status) - VALUES ($1, $2, $3, $4, $5)`, - [sourceId, filename, `data-import-${Date.now()}`, transactions.length, "completed"] - ); - 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, - ] - ); - } -} - -export async function importCategoriesOnly( - data: ExportEnvelope["data"] -): Promise { - return runRestore(async (db) => { - // Wipe keywords, suppliers, categories - await db.execute("DELETE FROM keywords"); - await db.execute("DELETE FROM suppliers"); - await db.execute("DELETE FROM categories"); - - // Nullify category/supplier references on transactions - await db.execute( - "UPDATE transactions SET category_id = NULL, supplier_id = NULL, is_manually_categorized = 0" - ); - - await restoreCategories(db, data.categories); - await restoreSuppliers(db, data.suppliers); - await restoreKeywords(db, data.keywords); - }); -} - -export async function importTransactionsWithCategories( - data: ExportEnvelope["data"], - filename: string -): Promise { - validateImportedFormatRows(data.import_sources, data.import_config_templates); - - return runRestore(async (db) => { - // Wipe everything - await db.execute("DELETE FROM transactions"); - await db.execute("DELETE FROM imported_files"); - await db.execute("DELETE FROM import_sources"); - await db.execute("DELETE FROM keywords"); - await db.execute("DELETE FROM suppliers"); - await db.execute("DELETE FROM categories"); - - await restoreCategories(db, data.categories); - await restoreSuppliers(db, data.suppliers); - await restoreKeywords(db, data.keywords); - - // Templates first: `import_sources.template_id` points at them. - const templateIds = await restoreImportTemplates( - db, - data.import_config_templates - ); - await restoreImportSources(db, data.import_sources, templateIds); - - await attachTransactions(db, data.transactions, filename); - }); -} - -export async function importTransactionsOnly( - data: ExportEnvelope["data"], - filename: string -): Promise { - validateImportedFormatRows(data.import_sources, data.import_config_templates); - - return runRestore(async (db) => { - // Wipe transactions and import history - await db.execute("DELETE FROM transactions"); - await db.execute("DELETE FROM imported_files"); - await db.execute("DELETE FROM import_sources"); - - const templateIds = await restoreImportTemplates( - db, - data.import_config_templates - ); - await restoreImportSources(db, data.import_sources, templateIds); - - await attachTransactions(db, data.transactions, filename); - }); -} diff --git a/src/services/dataRestoreService.ts b/src/services/dataRestoreService.ts new file mode 100644 index 0000000..71567e7 --- /dev/null +++ b/src/services/dataRestoreService.ts @@ -0,0 +1,362 @@ +import type Database from "@tauri-apps/plugin-sql"; +import { withTransaction } from "./db"; +import { notifyDataChanged } from "./dataEvents"; +import { toSqlFlag } from "../utils/sqlFlag"; +import type { Category, Keyword, Supplier } from "../shared/types"; +import { + validateImportedFormatRows, + type ExportEnvelope, + type ExportImportSource, + type ExportImportTemplate, + type ExportTransaction, +} from "./dataExportService"; + +// The restore of a data export, a SREF envelope or a CSV, moved out of +// dataExportService.ts (#518): each mode deletes what it replaces and inserts +// the file's rows back, in one transaction (`runRestore`). The envelope types, +// the export, the parse and the validations of the import boundary stay in +// dataExportService.ts. + +// --- Import execution --- + +/** + * The source that hosts transactions restored from a file, which describe no + * import folder of their own. + * + * Its mapping used to be `'{}'`, which `formatFromRow` cannot decode — a source + * the app itself wrote and then refused to read. It describes the CSV this very + * service exports instead: date, description, amount, comma-separated, ISO + * dates, expenses negative. That is true of the file the rows came from, so the + * wizard finds a usable format if a folder ever bears this name. + */ +const HOST_SOURCE_NAME = "Data Import"; +const HOST_SOURCE_MAPPING = JSON.stringify({ + date: 0, + description: 1, + amount: 2, +}); + +/** + * Run `body` as one all-or-nothing restore. + * + * Every one of these functions starts by DELETING the profile's financial + * history and then re-inserts it row by row, against tables carrying + * `UNIQUE(name)` and a foreign key. Without a transaction, the first constraint + * violation leaves the profile emptied at whatever row it reached, with nothing + * to go back to. `withTransaction` holds the single DB lock for the whole + * BEGIN..COMMIT so the statements cannot be split across pooled connections + * (see `db.ts`); the BEGIN/COMMIT/ROLLBACK themselves are ours to issue. + * + * 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). + */ +async function runRestore( + body: (db: Database) => Promise +): Promise { + await withTransaction(async (db) => { + await db.execute("BEGIN"); + let open = true; + try { + await body(db); + await db.execute("COMMIT"); + open = false; + } catch (e) { + if (open) { + try { + await db.execute("ROLLBACK"); + } catch { + // Preserve the original error — it is the one that explains the failure. + } + } + throw e; + } + }); + notifyDataChanged(); +} + +async function restoreCategories( + db: Database, + categories: Category[] | undefined +): Promise { + for (const cat of categories ?? []) { + await db.execute( + `INSERT INTO categories (id, name, parent_id, color, icon, type, is_active, is_inputable, sort_order) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, + [ + cat.id, + cat.name, + cat.parent_id ?? null, + cat.color ?? null, + cat.icon ?? null, + cat.type, + cat.is_active ? 1 : 0, + cat.is_inputable ? 1 : 0, + cat.sort_order, + ] + ); + } +} + +async function restoreSuppliers( + db: Database, + suppliers: Supplier[] | undefined +): Promise { + for (const sup of suppliers ?? []) { + await db.execute( + `INSERT INTO suppliers (id, name, normalized_name, category_id, is_active) + VALUES ($1, $2, $3, $4, $5)`, + [sup.id, sup.name, sup.normalized_name, sup.category_id ?? null, sup.is_active ? 1 : 0] + ); + } +} + +async function restoreKeywords( + db: Database, + keywords: Keyword[] | undefined +): Promise { + for (const kw of keywords ?? []) { + await db.execute( + `INSERT INTO keywords (id, keyword, category_id, supplier_id, priority, is_active) + VALUES ($1, $2, $3, $4, $5, $6)`, + [kw.id, kw.keyword, kw.category_id, kw.supplier_id ?? null, kw.priority, kw.is_active ? 1 : 0] + ); + } +} + +/** + * Restore the templates and return their resolved ids, keyed by name. + * + * `import_config_templates` is in NEITHER wipe list, and restoring into a + * profile that already has templates is the normal path, not an edge case — a + * plain INSERT would hit `UNIQUE constraint failed: import_config_templates.name` + * and (now) roll the whole restore back. Wiping the table instead was the other + * option and was rejected: it would destroy templates the user never asked to + * replace and that no confirmation dialog mentions. So: upsert by name, and give + * the caller the map it needs to remap `import_sources.template_id`, since the + * ids in the file mean nothing here. + * + * Templates go in BEFORE sources — `template_id` is a foreign key to this table. + */ +async function restoreImportTemplates( + db: Database, + templates: ExportImportTemplate[] | undefined +): Promise> { + const idsByName = new Map(); + for (const template of templates ?? []) { + await db.execute( + `INSERT INTO import_config_templates (name, delimiter, encoding, date_format, skip_lines, has_header, column_mapping, amount_mode, sign_convention) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT(name) DO UPDATE SET + delimiter = excluded.delimiter, + encoding = excluded.encoding, + date_format = excluded.date_format, + skip_lines = excluded.skip_lines, + has_header = excluded.has_header, + column_mapping = excluded.column_mapping, + amount_mode = excluded.amount_mode, + sign_convention = excluded.sign_convention`, + [ + template.name, + template.delimiter, + template.encoding, + template.date_format, + template.skip_lines, + template.has_header, + template.column_mapping, + template.amount_mode, + template.sign_convention, + ] + ); + // `lastInsertId` is 0 on the conflict branch, so the id is read back by + // name — the same reason `importSourceService.createSource` does it. + const rows = await db.select>( + "SELECT id FROM import_config_templates WHERE name = $1", + [template.name] + ); + if (rows.length > 0) idsByName.set(template.name, rows[0].id); + } + return idsByName; +} + +/** + * Restore the sources, resolving each `template_name` to the id the templates + * pass just settled. A name with no match becomes NULL: `template_id` is a + * provenance tag, never re-read as format, so losing it costs no configuration. + * + * Ids are not carried over — nothing in the envelope refers to a source by id. + */ +async function restoreImportSources( + db: Database, + sources: ExportImportSource[] | undefined, + templateIds: Map +): Promise { + for (const source of sources ?? []) { + await db.execute( + `INSERT INTO import_sources (name, description, date_format, delimiter, encoding, column_mapping, skip_lines, has_header, amount_mode, sign_convention, header_signature, template_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, + [ + source.name, + source.description ?? null, + source.date_format, + source.delimiter, + source.encoding, + source.column_mapping, + source.skip_lines, + source.has_header, + source.amount_mode, + source.sign_convention, + source.header_signature ?? null, + source.template_name !== null + ? templateIds.get(source.template_name) ?? null + : null, + ] + ); + } +} + +/** + * Attach the restored transactions to a source and one `imported_files` row. + * + * The host source is created ONLY here, and only when there are transactions to + * hang off it — it exists to satisfy `transactions.source_id`, not to stand in + * for the configurations the file now carries on its own. A restored source may + * 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. + */ +async function attachTransactions( + db: Database, + transactions: ExportTransaction[] | undefined, + filename: string +): Promise { + if (!transactions || transactions.length === 0) return; + + const existing = await db.select>( + "SELECT id FROM import_sources WHERE name = $1", + [HOST_SOURCE_NAME] + ); + let sourceId: number; + if (existing.length > 0) { + sourceId = existing[0].id; + } else { + const sourceResult = await db.execute( + `INSERT INTO import_sources (name, description, date_format, delimiter, encoding, column_mapping, skip_lines, has_header, amount_mode, sign_convention) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, + [ + HOST_SOURCE_NAME, + "Imported from settings", + "%Y-%m-%d", + ",", + "utf-8", + HOST_SOURCE_MAPPING, + 0, + 1, + "single", + "negative_expense", + ] + ); + sourceId = sourceResult.lastInsertId as number; + } + + const fileResult = await db.execute( + `INSERT INTO imported_files (source_id, filename, file_hash, row_count, status) + VALUES ($1, $2, $3, $4, $5)`, + [sourceId, filename, `data-import-${Date.now()}`, transactions.length, "completed"] + ); + 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, + ] + ); + } +} + +export async function importCategoriesOnly( + data: ExportEnvelope["data"] +): Promise { + return runRestore(async (db) => { + // Wipe keywords, suppliers, categories + await db.execute("DELETE FROM keywords"); + await db.execute("DELETE FROM suppliers"); + await db.execute("DELETE FROM categories"); + + // Nullify category/supplier references on transactions + await db.execute( + "UPDATE transactions SET category_id = NULL, supplier_id = NULL, is_manually_categorized = 0" + ); + + await restoreCategories(db, data.categories); + await restoreSuppliers(db, data.suppliers); + await restoreKeywords(db, data.keywords); + }); +} + +export async function importTransactionsWithCategories( + data: ExportEnvelope["data"], + filename: string +): Promise { + validateImportedFormatRows(data.import_sources, data.import_config_templates); + + return runRestore(async (db) => { + // Wipe everything + await db.execute("DELETE FROM transactions"); + await db.execute("DELETE FROM imported_files"); + await db.execute("DELETE FROM import_sources"); + await db.execute("DELETE FROM keywords"); + await db.execute("DELETE FROM suppliers"); + await db.execute("DELETE FROM categories"); + + await restoreCategories(db, data.categories); + await restoreSuppliers(db, data.suppliers); + await restoreKeywords(db, data.keywords); + + // Templates first: `import_sources.template_id` points at them. + const templateIds = await restoreImportTemplates( + db, + data.import_config_templates + ); + await restoreImportSources(db, data.import_sources, templateIds); + + await attachTransactions(db, data.transactions, filename); + }); +} + +export async function importTransactionsOnly( + data: ExportEnvelope["data"], + filename: string +): Promise { + validateImportedFormatRows(data.import_sources, data.import_config_templates); + + return runRestore(async (db) => { + // Wipe transactions and import history + await db.execute("DELETE FROM transactions"); + await db.execute("DELETE FROM imported_files"); + await db.execute("DELETE FROM import_sources"); + + const templateIds = await restoreImportTemplates( + db, + data.import_config_templates + ); + await restoreImportSources(db, data.import_sources, templateIds); + + await attachTransactions(db, data.transactions, filename); + }); +}