Simpl-Resultat/src/hooks/useDataImport.ts
le king fu 23079da609 fix: restore a profile holding a Bilan transfer, a missing category or a category under a newer one (#521)
Three foreign keys stopped a restore on "FOREIGN KEY constraint failed",
the whole restore rolled back:

- (a) balance_account_transfers.transaction_id is ON DELETE RESTRICT
  (ADR 0010): the DELETE FROM transactions of both transaction modes,
  and so "Rétablir la sauvegarde", failed as soon as one transfer
  existed. Inside the restore's transaction, each transfer is now read
  with the date, amount and description of its transaction, then the
  table is emptied; once the transactions are back, the transfers whose
  transaction returns with the same id, date, amount and description
  are put back as they were (id, account, direction, notes, creation
  date), and the others are unlinked.
- (b) a transaction whose category the profile no longer holds (after
  "Réinitialiser", another restore, or another profile's file) failed
  its insert: it now comes back without a category, manual flag at 0,
  and one Journal line gives their number, nothing else.
- (c) restoreCategories inserted by id against parent_id, so a category
  under a newer one, or a loop, failed. Every category now goes in with
  parent_id NULL, and a second pass sets the parents.

The three restores return a RestoreOutcome { unlinkedTransfers,
uncategorizedTransactions } through runRestore<T> (categories only:
zeros). previewUnlinkedTransfers counts, outside any transaction and by
the same rule, the transfers a restore would unlink.
validateImportedCategoryReferences (pure, dataExportService.ts) refuses,
at the parse and at the head of the two restores that write categories,
a file whose parent_id, keyword or supplier names a category it does
not hold (danglingCategoryReference), before anything is deleted.

The "Gestion des données" card announces the transfers to unlink in its
confirmation and gives the real number after the restore (IMPORT_SUCCESS
carries the outcome). restoreFromBackup is split into readBackup (read,
decrypt, parse, count) and applyBackup (restore, preferences, a
RestoreResult with the outcome): "Rétablir la sauvegarde" reads the file
(after the PIN when encrypted) before a second confirmation, ends on
"Sauvegarde rétablie", and reloads the app on "Fermer" only.

Regression test in src/__integration__/restore.test.ts (real services
on node:sqlite, consolidated_schema.sql, foreign keys on): red on the
base for the three causes, green here.

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

238 lines
7.1 KiB
TypeScript

import { useReducer, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { invoke } from "@tauri-apps/api/core";
import {
parseImportedJson,
parseImportedCsv,
SrefValidationError,
type ExportEnvelope,
type ImportSummary,
} from "../services/dataExportService";
import {
importCategoriesOnly,
importTransactionsWithCategories,
importTransactionsOnly,
previewUnlinkedTransfers,
type RestoreOutcome,
} from "../services/dataRestoreService";
type ImportStatus =
| "idle"
| "reading"
| "needsPassword"
| "confirming"
| "importing"
| "success"
| "error";
interface ImportState {
status: ImportStatus;
filePath: string | null;
summary: ImportSummary | null;
parsedData: ExportEnvelope["data"] | null;
importType: ExportEnvelope["export_type"] | null;
/** Bilan transfers the restore would unlink, announced by the confirmation (#521). */
unlinkedTransfers: number;
/** What the committed restore did, for the success message (#521). */
outcome: RestoreOutcome | null;
error: string | null;
}
type ImportAction =
| { type: "READ_START" }
| { type: "NEEDS_PASSWORD"; filePath: string }
| {
type: "CONFIRMING";
filePath: string;
summary: ImportSummary;
data: ExportEnvelope["data"];
importType: ExportEnvelope["export_type"];
unlinkedTransfers: number;
}
| { type: "IMPORT_START" }
| { type: "IMPORT_SUCCESS"; outcome: RestoreOutcome }
| { type: "IMPORT_ERROR"; error: string }
| { type: "RESET" };
const initialState: ImportState = {
status: "idle",
filePath: null,
summary: null,
parsedData: null,
importType: null,
unlinkedTransfers: 0,
outcome: null,
error: null,
};
function reducer(state: ImportState, action: ImportAction): ImportState {
switch (action.type) {
case "READ_START":
return { ...initialState, status: "reading" };
case "NEEDS_PASSWORD":
return { ...initialState, status: "needsPassword", filePath: action.filePath };
case "CONFIRMING":
return {
...state,
status: "confirming",
filePath: action.filePath,
summary: action.summary,
parsedData: action.data,
importType: action.importType,
unlinkedTransfers: action.unlinkedTransfers,
error: null,
};
case "IMPORT_START":
return { ...state, status: "importing", error: null };
case "IMPORT_SUCCESS":
return { ...state, status: "success", outcome: action.outcome, error: null };
case "IMPORT_ERROR":
return { ...state, status: "error", error: action.error };
case "RESET":
return initialState;
}
}
function parseContent(
content: string,
filePath: string
): { summary: ImportSummary; data: ExportEnvelope["data"]; importType: ExportEnvelope["export_type"] } {
const isCsv =
filePath.toLowerCase().endsWith(".csv") ||
(!filePath.toLowerCase().endsWith(".json") &&
!filePath.toLowerCase().endsWith(".sref") &&
content.trimStart().charAt(0) !== "{");
if (isCsv) {
const { transactions, summary } = parseImportedCsv(content);
return {
summary,
data: { transactions },
importType: "transactions_only",
};
}
const { envelope, summary } = parseImportedJson(content);
return {
summary,
data: envelope.data,
importType: envelope.export_type,
};
}
/**
* The Bilan transfers a restore of `data` would unlink, read before the
* confirmation opens (#521): in the two modes that carry transactions only, a
* restore of the categories deleting no transaction.
*/
async function previewTransfers(
importType: ExportEnvelope["export_type"],
data: ExportEnvelope["data"]
): Promise<number> {
if (importType === "categories_only") return 0;
return previewUnlinkedTransfers(data.transactions);
}
export function useDataImport() {
const [state, dispatch] = useReducer(reducer, initialState);
const { t } = useTranslation();
/**
* A refusal at the configuration boundary carries an i18n key and the name of
* the offending source; everything else is a raw exception message. The card
* renders this string as it comes, so the translation happens here.
*/
const describeError = useCallback(
(e: unknown): string => {
if (e instanceof SrefValidationError) return t(e.i18nKey, e.params);
return e instanceof Error ? e.message : String(e);
},
[t]
);
const pickAndRead = useCallback(async () => {
dispatch({ type: "READ_START" });
try {
const filePath = await invoke<string | null>("pick_import_file", {
filters: [["Simpl'Result Files", ["json", "csv", "sref"]]],
});
if (!filePath) {
dispatch({ type: "RESET" });
return;
}
const encrypted = await invoke<boolean>("is_file_encrypted", { filePath });
if (encrypted) {
dispatch({ type: "NEEDS_PASSWORD", filePath });
return;
}
const content = await invoke<string>("read_import_file", {
filePath,
password: null,
});
const { summary, data, importType } = parseContent(content, filePath);
const unlinkedTransfers = await previewTransfers(importType, data);
dispatch({ type: "CONFIRMING", filePath, summary, data, importType, unlinkedTransfers });
} catch (e) {
dispatch({ type: "IMPORT_ERROR", error: describeError(e) });
}
}, [describeError]);
const readWithPassword = useCallback(
async (password: string) => {
if (!state.filePath) return;
dispatch({ type: "READ_START" });
try {
const content = await invoke<string>("read_import_file", {
filePath: state.filePath,
password,
});
const { summary, data, importType } = parseContent(content, state.filePath);
const unlinkedTransfers = await previewTransfers(importType, data);
dispatch({
type: "CONFIRMING",
filePath: state.filePath,
summary,
data,
importType,
unlinkedTransfers,
});
} catch (e) {
dispatch({ type: "IMPORT_ERROR", error: describeError(e) });
}
},
[state.filePath, describeError]
);
const executeImport = useCallback(async () => {
if (!state.parsedData || !state.importType) return;
dispatch({ type: "IMPORT_START" });
const filename = state.filePath?.split(/[/\\]/).pop() ?? "unknown";
try {
let outcome: RestoreOutcome;
switch (state.importType) {
case "categories_only":
outcome = await importCategoriesOnly(state.parsedData);
break;
case "transactions_with_categories":
outcome = await importTransactionsWithCategories(state.parsedData, filename);
break;
case "transactions_only":
outcome = await importTransactionsOnly(state.parsedData, filename);
break;
}
dispatch({ type: "IMPORT_SUCCESS", outcome });
} catch (e) {
dispatch({ type: "IMPORT_ERROR", error: describeError(e) });
}
}, [state.parsedData, state.importType, state.filePath, describeError]);
const reset = useCallback(() => dispatch({ type: "RESET" }), []);
return { state, pickAndRead, readWithPassword, executeImport, reset };
}