Simpl-Resultat/src/services/dataExportService.ts
le king fu 4a579f10f9 fix: restore a backup's split lines with their parent (#518)
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 <noreply@anthropic.com>
2026-11-04 21:36:55 -05:00

488 lines
16 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";
/**
* 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, 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 };
}
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, 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,
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,
},
};
}