Simpl-Resultat/src/services/dataRestoreService.ts
le king fu df8da7881b
All checks were successful
PR Check — Frontend / frontend (pull_request) Successful in 3m8s
docs: the Bilan transfers, the missing categories and the two passes of a restore (#521)
- CHANGELOG.md / CHANGELOG.fr.md, Fixed / Corrigé: a profile with a
  Bilan transfer, a transaction whose category is gone, or a category
  under a newer one restores again; the transfers whose transaction
  comes back unchanged are kept, the others unlinked and counted before
  and after; a file whose references cannot be satisfied is refused;
  "Rétablir la sauvegarde" reads the file before a second confirmation
  and reloads on "Fermer".
- ADR 0010 amendment: RESTRICT unchanged; the restore reads, removes and
  puts back the transfers whose transaction returns with the same id,
  date, amount and description, and says how many it unlinks.
- docs/architecture.md: dataExportService.ts and dataRestoreService.ts
  rows, useDataImport, the two passes of restoreCategories, the SREF
  section, the node:sqlite tests of restore.test.ts.
- User guide and in-app docs (docs.settings.tips, appended last so that
  tips[6], which REVIEW.md cites, keeps its index).
- Two comments of attachTransactions name the app's real labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:40:54 -05:00

623 lines
22 KiB
TypeScript

import type Database from "@tauri-apps/plugin-sql";
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,
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.
/**
* 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 ---
/**
* 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). What `body` returns, its `RestoreOutcome`, is
* handed back once committed (#521).
*/
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 {
const value = await body(db);
await db.execute("COMMIT");
open = false;
return value;
} 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();
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
): Promise<void> {
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,
null,
cat.color ?? null,
cat.icon ?? null,
cat.type,
cat.is_active ? 1 : 0,
cat.is_inputable ? 1 : 0,
cat.sort_order,
]
);
}
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(
db: Database,
suppliers: Supplier[] | undefined
): Promise<void> {
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<void> {
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<Map<string, number>> {
const idsByName = new Map<string, number>();
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<Array<{ id: number }>>(
"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<string, number>
): Promise<void> {
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.
*
* 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.
*
* A row whose category the profile does not hold comes back without one, its
* manual flag at 0, so that « Auto-catégoriser » 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
* uniquement » 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<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",
[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;
const ordered = [
...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,
missingCategory ? null : tx.category_id,
tx.original_description,
tx.notes,
// A JSON backup from the time of #390 carries the text "true".
missingCategory ? 0 : 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
);
}
}
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<RestoreOutcome> {
validateImportedCategoryReferences(data.categories, data.suppliers, data.keywords);
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);
// No transaction is deleted: every transfer stays linked.
return { unlinkedTransfers: 0, uncategorizedTransactions: 0 };
});
}
export async function importTransactionsWithCategories(
data: ExportEnvelope["data"],
filename: string
): 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);
// 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);
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<RestoreOutcome> {
validateImportedFormatRows(data.import_sources, data.import_config_templates);
const { keepIds } = validateImportedTransactionIds(data.transactions);
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");
await db.execute("DELETE FROM import_sources");
const templateIds = await restoreImportTemplates(
db,
data.import_config_templates
);
await restoreImportSources(db, data.import_sources, templateIds);
const uncategorizedTransactions = await attachTransactions(
db,
data.transactions,
filename,
keepIds
);
const unlinkedTransfers = await restoreTransfers(
db,
transfers,
data.transactions,
keepIds
);
return { unlinkedTransfers, uncategorizedTransactions };
});
return reportOutcome(outcome);
}