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>
540 lines
19 KiB
TypeScript
540 lines
19 KiB
TypeScript
import { getDb } from "./db";
|
|
import Papa from "papaparse";
|
|
import { toSqlFlag } from "../utils/sqlFlag";
|
|
import type {
|
|
Category,
|
|
ImportConfigTemplate,
|
|
ImportFormatRow,
|
|
ImportSource,
|
|
Keyword,
|
|
Supplier,
|
|
} from "../shared/types";
|
|
import {
|
|
AMOUNT_MODES,
|
|
SIGN_CONVENTIONS,
|
|
pickFormatRow,
|
|
} from "../utils/importFormat";
|
|
|
|
// --- Export types ---
|
|
|
|
export type ExportMode =
|
|
| "transactions_with_categories"
|
|
| "transactions_only"
|
|
| "categories_only";
|
|
|
|
export type ExportFormat = "json" | "csv";
|
|
|
|
/**
|
|
* Version of the SREF envelope this build writes.
|
|
*
|
|
* Version 2 is the first to carry `import_sources` and
|
|
* `import_config_templates`. A file with no `format_version` at all is a
|
|
* version 1 file: it predates #331, so its missing arrays mean "this backup
|
|
* never held any configuration", not "this profile had none". The restore then
|
|
* behaves exactly as it did before — wipe the sources and hang the transactions
|
|
* off a synthetic one — which is the only reading that cannot invent data.
|
|
*/
|
|
export const SREF_FORMAT_VERSION = 2;
|
|
|
|
/** What an envelope without an explicit `format_version` is. */
|
|
export const LEGACY_SREF_FORMAT_VERSION = 1;
|
|
|
|
export interface ExportEnvelope {
|
|
export_type: ExportMode;
|
|
app_version: string;
|
|
/** Absent on files written before #331 — see `SREF_FORMAT_VERSION`. */
|
|
format_version?: number;
|
|
exported_at: string;
|
|
data: {
|
|
categories?: Category[];
|
|
suppliers?: Supplier[];
|
|
keywords?: Keyword[];
|
|
transactions?: ExportTransaction[];
|
|
import_sources?: ExportImportSource[];
|
|
import_config_templates?: ExportImportTemplate[];
|
|
};
|
|
}
|
|
|
|
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;
|
|
amount: number;
|
|
category_id: number | null;
|
|
category_name: string | null;
|
|
original_description: string | null;
|
|
notes: string | null;
|
|
is_manually_categorized: number;
|
|
is_split: number;
|
|
parent_transaction_id: number | null;
|
|
}
|
|
|
|
/**
|
|
* An import source as it travels in the file: the eight format fields in their
|
|
* persisted shape, plus the source's own columns.
|
|
*
|
|
* No `id`: nothing in the envelope points at a source by id (`ExportTransaction`
|
|
* carries no `source_id`), so ids would only be noise that collides on restore.
|
|
* The link to a template travels as `template_name` for the same reason — the
|
|
* name is the table's natural key (`UNIQUE`), it survives renumbering, and it is
|
|
* what the restore resolves the foreign key through.
|
|
*/
|
|
export interface ExportImportSource extends ImportFormatRow {
|
|
name: string;
|
|
description: string | null;
|
|
/**
|
|
* Drift metadata (#330), NOT one of the eight format fields — it travels
|
|
* beside them, never through the codec. Round-tripping it keeps drift
|
|
* detection armed across a restore; a source that comes back without one just
|
|
* has detection off until its next successful import records it.
|
|
*/
|
|
header_signature: string | null;
|
|
/** Name of the template this source was configured from, or null. */
|
|
template_name: string | null;
|
|
}
|
|
|
|
/** A template as it travels in the file: a named format, nothing more. */
|
|
export interface ExportImportTemplate extends ImportFormatRow {
|
|
name: string;
|
|
}
|
|
|
|
// --- Import types ---
|
|
|
|
export interface ImportSummary {
|
|
type: ExportMode;
|
|
categoriesCount: number;
|
|
suppliersCount: number;
|
|
keywordsCount: number;
|
|
transactionsCount: number;
|
|
importSourcesCount: number;
|
|
importTemplatesCount: number;
|
|
/** `LEGACY_SREF_FORMAT_VERSION` when the file declares none. */
|
|
formatVersion: number;
|
|
}
|
|
|
|
/** 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.orphanSplitLines"
|
|
| "settings.dataManagement.import.errors.danglingCategoryReference";
|
|
|
|
/**
|
|
* Thrown when a backup carries a configuration this build cannot store, split
|
|
* lines that cannot find their parent (#518), or categories, keywords or
|
|
* suppliers that name a category the file does not hold (#521).
|
|
*
|
|
* The `CHECK` added by migration v17 already refuses these values, but a SQLite
|
|
* constraint error is not something a user can act on — and it would surface
|
|
* only once the restore had already started deleting. This is raised at the
|
|
* 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;
|
|
readonly params: Record<string, string>;
|
|
|
|
constructor(i18nKey: SrefValidationErrorKey, params: Record<string, string>) {
|
|
super(`${i18nKey}: ${JSON.stringify(params)}`);
|
|
this.name = "SrefValidationError";
|
|
this.i18nKey = i18nKey;
|
|
this.params = params;
|
|
}
|
|
}
|
|
|
|
// --- Data gathering ---
|
|
|
|
export async function getExportCategories(): Promise<Category[]> {
|
|
const db = await getDb();
|
|
return db.select<Category[]>("SELECT * FROM categories ORDER BY id");
|
|
}
|
|
|
|
export async function getExportSuppliers(): Promise<Supplier[]> {
|
|
const db = await getDb();
|
|
return db.select<Supplier[]>("SELECT * FROM suppliers ORDER BY id");
|
|
}
|
|
|
|
export async function getExportKeywords(): Promise<Keyword[]> {
|
|
const db = await getDb();
|
|
return db.select<Keyword[]>("SELECT * FROM keywords ORDER BY id");
|
|
}
|
|
|
|
export async function getExportTransactions(): Promise<ExportTransaction[]> {
|
|
const db = await getDb();
|
|
return db.select<ExportTransaction[]>(
|
|
`SELECT t.id, t.date, t.description, t.amount, t.category_id,
|
|
c.name AS category_name, t.original_description, t.notes,
|
|
t.is_manually_categorized, t.is_split, t.parent_transaction_id
|
|
FROM transactions t
|
|
LEFT JOIN categories c ON t.category_id = c.id
|
|
ORDER BY t.date, t.id`
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Every configured import source, with its template resolved to a name.
|
|
*
|
|
* This is what the export was missing (#331): the file carried transactions but
|
|
* not a single line of how they had been read, so restoring a backup meant
|
|
* reconfiguring every source by hand.
|
|
*/
|
|
export async function getExportImportSources(): Promise<ExportImportSource[]> {
|
|
const db = await getDb();
|
|
const rows = await db.select<
|
|
Array<ImportSource & { template_name: string | null }>
|
|
>(
|
|
`SELECT s.*, t.name AS template_name
|
|
FROM import_sources s
|
|
LEFT JOIN import_config_templates t ON s.template_id = t.id
|
|
ORDER BY s.id`
|
|
);
|
|
return rows.map((row) => ({
|
|
name: row.name,
|
|
description: row.description ?? null,
|
|
header_signature: row.header_signature ?? null,
|
|
template_name: row.template_name ?? null,
|
|
...pickFormatRow(row as unknown as Record<string, unknown>),
|
|
}));
|
|
}
|
|
|
|
export async function getExportImportTemplates(): Promise<
|
|
ExportImportTemplate[]
|
|
> {
|
|
const db = await getDb();
|
|
const rows = await db.select<ImportConfigTemplate[]>(
|
|
"SELECT * FROM import_config_templates ORDER BY id"
|
|
);
|
|
return rows.map((row) => ({
|
|
name: row.name,
|
|
...pickFormatRow(row as unknown as Record<string, unknown>),
|
|
}));
|
|
}
|
|
|
|
// --- Serialization ---
|
|
|
|
export function serializeToJson(
|
|
exportType: ExportMode,
|
|
data: ExportEnvelope["data"],
|
|
appVersion: string
|
|
): string {
|
|
const envelope: ExportEnvelope = {
|
|
export_type: exportType,
|
|
app_version: appVersion,
|
|
format_version: SREF_FORMAT_VERSION,
|
|
exported_at: new Date().toISOString(),
|
|
data,
|
|
};
|
|
return JSON.stringify(envelope, null, 2);
|
|
}
|
|
|
|
export function serializeTransactionsToCsv(
|
|
transactions: ExportTransaction[]
|
|
): 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,
|
|
category_name: t.category_name ?? "",
|
|
category_id: t.category_id ?? "",
|
|
original_description: t.original_description ?? "",
|
|
notes: t.notes ?? "",
|
|
is_manually_categorized: t.is_manually_categorized,
|
|
is_split: t.is_split,
|
|
parent_transaction_id: t.parent_transaction_id ?? "",
|
|
}))
|
|
);
|
|
}
|
|
|
|
// --- Import parsing ---
|
|
|
|
/**
|
|
* Refuse a configuration this build cannot store, BEFORE anything is deleted.
|
|
*
|
|
* Only the two enumerated fields are checked. `column_mapping` deliberately is
|
|
* not decoded: a profile that already went through an old restore holds sources
|
|
* with `'{}'` there, and refusing to restore a backup because of a row the app
|
|
* itself wrote would strand the user with no way back in. It is carried through
|
|
* as the opaque string the column stores, exactly as it was found — the wizard
|
|
* validates it when it is actually about to read a file.
|
|
*
|
|
* PURE: no I/O, so it can be called from the parse step and again at the top of
|
|
* each restore, which is where the guarantee has to hold.
|
|
*/
|
|
export function validateImportedFormatRows(
|
|
sources: ExportImportSource[] | undefined,
|
|
templates: ExportImportTemplate[] | undefined
|
|
): void {
|
|
const check = (row: ImportFormatRow, name: unknown) => {
|
|
const label = typeof name === "string" && name.length > 0 ? name : "?";
|
|
if (typeof row?.column_mapping !== "string") {
|
|
throw new SrefValidationError(
|
|
"settings.dataManagement.import.errors.invalidFormatRow",
|
|
{ name: label }
|
|
);
|
|
}
|
|
if (!AMOUNT_MODES.includes(row.amount_mode)) {
|
|
throw new SrefValidationError(
|
|
"settings.dataManagement.import.errors.unsupportedAmountMode",
|
|
{ name: label, value: String(row.amount_mode) }
|
|
);
|
|
}
|
|
if (!SIGN_CONVENTIONS.includes(row.sign_convention)) {
|
|
throw new SrefValidationError(
|
|
"settings.dataManagement.import.errors.unsupportedSignConvention",
|
|
{ name: label, value: String(row.sign_convention) }
|
|
);
|
|
}
|
|
};
|
|
|
|
for (const template of templates ?? []) check(template, template?.name);
|
|
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<number>();
|
|
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 };
|
|
}
|
|
|
|
/**
|
|
* Refuse a file whose categories, keywords or suppliers name a category the
|
|
* file does not hold, BEFORE anything is deleted (#521).
|
|
*
|
|
* The two modes that carry categories delete the profile's and insert the
|
|
* file's, against foreign keys: a `parent_id`, the `category_id` of a keyword
|
|
* or the `category_id` of a supplier that names no category of the file would
|
|
* stop the restore midway on SQLite's raw message. A category or a supplier
|
|
* may name none; a keyword always names one (the column is NOT NULL), so a
|
|
* keyword without it is refused too. A file without a `categories` array holds
|
|
* no category at all. The category of a transaction is not checked here: a
|
|
* transaction whose category is missing comes back without one
|
|
* (`attachTransactions`, decision of Max of 2026-10-29).
|
|
*
|
|
* PURE: no I/O, so it can be called from the parse step and again at the top of
|
|
* each restore that writes categories, like `validateImportedFormatRows`.
|
|
*/
|
|
export function validateImportedCategoryReferences(
|
|
categories: Category[] | undefined,
|
|
suppliers: Supplier[] | undefined,
|
|
keywords: Keyword[] | undefined
|
|
): void {
|
|
const ids = new Set(
|
|
(categories ?? [])
|
|
.map((category) => category?.id)
|
|
.filter((id): id is number => typeof id === "number")
|
|
);
|
|
const refusal = () =>
|
|
new SrefValidationError(
|
|
"settings.dataManagement.import.errors.danglingCategoryReference",
|
|
{}
|
|
);
|
|
|
|
for (const category of categories ?? []) {
|
|
if (category?.parent_id != null && !ids.has(category.parent_id)) throw refusal();
|
|
}
|
|
for (const supplier of suppliers ?? []) {
|
|
if (supplier?.category_id != null && !ids.has(supplier.category_id)) throw refusal();
|
|
}
|
|
for (const keyword of keywords ?? []) {
|
|
if (!ids.has(keyword?.category_id)) throw refusal();
|
|
}
|
|
}
|
|
|
|
export function parseImportedJson(content: string): {
|
|
envelope: ExportEnvelope;
|
|
summary: ImportSummary;
|
|
} {
|
|
let envelope: ExportEnvelope;
|
|
try {
|
|
envelope = JSON.parse(content);
|
|
} catch {
|
|
throw new Error("Invalid JSON file");
|
|
}
|
|
|
|
if (
|
|
!envelope.export_type ||
|
|
!envelope.data ||
|
|
typeof envelope.data !== "object"
|
|
) {
|
|
throw new Error("Invalid export file format — missing required fields");
|
|
}
|
|
|
|
const validTypes: ExportMode[] = [
|
|
"transactions_with_categories",
|
|
"transactions_only",
|
|
"categories_only",
|
|
];
|
|
if (!validTypes.includes(envelope.export_type)) {
|
|
throw new Error(`Unknown export type: ${envelope.export_type}`);
|
|
}
|
|
|
|
// Refuse an unreadable configuration, split lines that cannot find their
|
|
// parent, or a category reference the file cannot satisfy, while the file is
|
|
// only being LOOKED at: the confirmation dialog never opens, so nothing is
|
|
// deleted.
|
|
validateImportedFormatRows(
|
|
envelope.data.import_sources,
|
|
envelope.data.import_config_templates
|
|
);
|
|
validateImportedTransactionIds(envelope.data.transactions);
|
|
validateImportedCategoryReferences(
|
|
envelope.data.categories,
|
|
envelope.data.suppliers,
|
|
envelope.data.keywords
|
|
);
|
|
|
|
return {
|
|
envelope,
|
|
summary: {
|
|
type: envelope.export_type,
|
|
categoriesCount: envelope.data.categories?.length ?? 0,
|
|
suppliersCount: envelope.data.suppliers?.length ?? 0,
|
|
keywordsCount: envelope.data.keywords?.length ?? 0,
|
|
transactionsCount: envelope.data.transactions?.length ?? 0,
|
|
importSourcesCount: envelope.data.import_sources?.length ?? 0,
|
|
importTemplatesCount: envelope.data.import_config_templates?.length ?? 0,
|
|
formatVersion: envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION,
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 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;
|
|
} {
|
|
const result = Papa.parse<Record<string, string>>(content, {
|
|
header: true,
|
|
skipEmptyLines: true,
|
|
});
|
|
|
|
if (result.errors.length > 0 && result.data.length === 0) {
|
|
throw new Error(`CSV parse error: ${result.errors[0].message}`);
|
|
}
|
|
|
|
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,
|
|
category_id: row.category_id ? parseInt(row.category_id) : null,
|
|
category_name: row.category_name || null,
|
|
original_description: row.original_description || null,
|
|
notes: row.notes || null,
|
|
// 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
|
|
? 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: {
|
|
type: "transactions_only",
|
|
categoriesCount: 0,
|
|
suppliersCount: 0,
|
|
keywordsCount: 0,
|
|
transactionsCount: transactions.length,
|
|
// A flat CSV carries no configuration at all.
|
|
importSourcesCount: 0,
|
|
importTemplatesCount: 0,
|
|
formatVersion: LEGACY_SREF_FORMAT_VERSION,
|
|
},
|
|
};
|
|
}
|