Simpl-Resultat/src/services/dataExportService.ts
le king fu 09c7b32dd1 fix: carry the budget in SREF backups and keep it on restore (#520)
A restore with categories (full backup, categories only, and "Restore the
backup" of the categories migration) ran DELETE FROM categories, whose
ON DELETE CASCADE took every budget line, template line and adjustment
line with it, while the backup held none: the restore succeeded and left
the budget empty.

- SREF format 3: the two modes that carry the categories now carry
  budget_entries, budget_templates (by name, with their lines) and
  adjustments (with their lines). collectExportData(mode) gathers the
  arrays of each mode for the export and for the pre-migration backup.
- Restore: the profile's budget lines, template lines and adjustment
  lines are read and taken out before DELETE FROM categories, in both
  formats, through the restore's handle. At format 3 the file's budget
  lines and adjustments replace the profile's, each file template is
  upserted by name with its lines replaced, and a template absent from
  the file keeps its header and its lines whose category comes back.
  Below format 3 the lines whose category comes back are put back as
  they were.
- The restores of the two category modes take the file's format
  (formatVersion), passed by useDataImport and applyBackup.
- Pure validation at the parse and at the head of each restore: a
  format newer than this build is refused (newerFormat), a non-integer
  or below 1 gets the malformed-file error, and at format 3 a missing
  array or a line the tables cannot hold is refused (invalidBudgetRows).
- restoreCategories writes i18n_key.
- Confirmations: willDeleteCategories and willDeleteAll name the budget,
  the counts of budget lines, templates and adjustments, and the note of
  a backup older than format 3 in the card and in the second
  confirmation of "Restore the backup"; categories.reinitializeConfirm
  names what "Re-initialize" erases.

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

855 lines
30 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.
*
* Version 3 (#520) is the first to carry the budget: `budget_entries`,
* `budget_templates` and `adjustments`, in the two modes that carry the
* categories (`BUDGET_SREF_FORMAT_VERSION`). A file of a later version comes
* from a newer build and is refused before anything is deleted (ADR 0025).
*/
export const SREF_FORMAT_VERSION = 3;
/** What an envelope without an explicit `format_version` is. */
export const LEGACY_SREF_FORMAT_VERSION = 1;
/**
* The first version whose files carry the budget, its templates and the
* adjustments (#520). A file of an earlier version holds none of them: the
* restore keeps instead the profile's lines whose category comes back.
*/
export const BUDGET_SREF_FORMAT_VERSION = 3;
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[];
/** From format 3 on, in the two modes that carry the categories (#520). */
budget_entries?: ExportBudgetEntry[];
budget_templates?: ExportBudgetTemplate[];
adjustments?: ExportAdjustment[];
};
}
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;
}
/**
* A budget line as it travels in the file (#520), designated by its category
* and its month, the table's `UNIQUE` key. No id: nothing points at a budget
* line.
*/
export interface ExportBudgetEntry {
category_id: number;
year: number;
month: number;
amount: number;
notes: string | null;
}
/** A line of a budget template (#520). */
export interface ExportBudgetTemplateEntry {
category_id: number;
amount: number;
}
/**
* A budget template as it travels in the file (#520), designated by its name,
* the table's `UNIQUE` key, like an import template, and carrying its lines.
*/
export interface ExportBudgetTemplate {
name: string;
description: string | null;
entries: ExportBudgetTemplateEntry[];
}
/** A line of an adjustment (#520). */
export interface ExportAdjustmentEntry {
category_id: number;
amount: number;
description: string | null;
}
/**
* An adjustment as it travels in the file (#520), with its lines. No id and no
* natural key (its name is not unique): the restore puts the file's
* adjustments in place of the profile's.
*/
export interface ExportAdjustment {
name: string;
description: string | null;
date: string;
is_recurring: number;
recurrence_rule: string | null;
entries: ExportAdjustmentEntry[];
}
// --- Import types ---
export interface ImportSummary {
type: ExportMode;
categoriesCount: number;
suppliersCount: number;
keywordsCount: number;
transactionsCount: number;
importSourcesCount: number;
importTemplatesCount: number;
/** The budget the file carries, from format 3 on (#520). */
budgetEntriesCount: number;
budgetTemplatesCount: number;
adjustmentsCount: 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"
| "settings.dataManagement.import.errors.invalidBudgetRows"
| "settings.dataManagement.import.errors.newerFormat";
/**
* Thrown when a backup carries a configuration this build cannot store, split
* lines that cannot find their parent (#518), categories, keywords or
* suppliers that name a category the file does not hold (#521), budget lines,
* templates or adjustments the restore could not write back, or a format newer
* than this build (#520).
*
* 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>),
}));
}
/** Every budget line of the profile (#520). */
export async function getExportBudgetEntries(): Promise<ExportBudgetEntry[]> {
const db = await getDb();
const rows = await db.select<ExportBudgetEntry[]>(
"SELECT category_id, year, month, amount, notes FROM budget_entries ORDER BY id"
);
return rows.map((row) => ({
category_id: row.category_id,
year: row.year,
month: row.month,
amount: row.amount,
notes: row.notes ?? null,
}));
}
/** Every budget template of the profile, each with its lines (#520). */
export async function getExportBudgetTemplates(): Promise<ExportBudgetTemplate[]> {
const db = await getDb();
const templates = await db.select<
Array<{ id: number; name: string; description: string | null }>
>("SELECT id, name, description FROM budget_templates ORDER BY id");
const lines = await db.select<
Array<{ template_id: number; category_id: number; amount: number }>
>("SELECT template_id, category_id, amount FROM budget_template_entries ORDER BY id");
return templates.map((template) => ({
name: template.name,
description: template.description ?? null,
entries: lines
.filter((line) => line.template_id === template.id)
.map((line) => ({ category_id: line.category_id, amount: line.amount })),
}));
}
/** Every adjustment of the profile, each with its lines (#520). */
export async function getExportAdjustments(): Promise<ExportAdjustment[]> {
const db = await getDb();
const adjustments = await db.select<
Array<{
id: number;
name: string;
description: string | null;
date: string;
is_recurring: number;
recurrence_rule: string | null;
}>
>(
"SELECT id, name, description, date, is_recurring, recurrence_rule FROM adjustments ORDER BY id"
);
const lines = await db.select<
Array<{
adjustment_id: number;
category_id: number;
amount: number;
description: string | null;
}>
>(
"SELECT adjustment_id, category_id, amount, description FROM adjustment_entries ORDER BY id"
);
return adjustments.map((adjustment) => ({
name: adjustment.name,
description: adjustment.description ?? null,
date: adjustment.date,
is_recurring: adjustment.is_recurring,
recurrence_rule: adjustment.recurrence_rule ?? null,
entries: lines
.filter((line) => line.adjustment_id === adjustment.id)
.map((line) => ({
category_id: line.category_id,
amount: line.amount,
description: line.description ?? null,
})),
}));
}
/**
* What an export of `mode` carries, read from the profile: the one list of
* arrays per mode, for « Exporter » (`useDataExport`) and for the backup taken
* before the categories migration (`createPreMigrationBackup`), so that the two
* never carry different things (#520).
*
* The two modes that carry the categories carry the budget with them, its
* templates and the adjustments: their restore deletes the categories, and
* every one of these lines names a category. The two modes that carry the
* transactions carry the import configurations (#331). « Transactions
* uniquement » touches no category, and its budget stays where it is.
*/
export async function collectExportData(
mode: ExportMode
): Promise<ExportEnvelope["data"]> {
const withCategories =
mode === "transactions_with_categories" || mode === "categories_only";
const withTransactions =
mode === "transactions_with_categories" || mode === "transactions_only";
const data: ExportEnvelope["data"] = {};
if (withCategories) {
data.categories = await getExportCategories();
data.suppliers = await getExportSuppliers();
data.keywords = await getExportKeywords();
}
if (withTransactions) {
data.transactions = await getExportTransactions();
data.import_sources = await getExportImportSources();
data.import_config_templates = await getExportImportTemplates();
}
if (withCategories) {
data.budget_entries = await getExportBudgetEntries();
data.budget_templates = await getExportBudgetTemplates();
data.adjustments = await getExportAdjustments();
}
return data;
}
// --- 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();
}
}
/** The refusal of an envelope this app did not write (missing fields, unreadable format). */
const INVALID_ENVELOPE = "Invalid export file format — missing required fields";
/**
* Refuse a file whose format this build cannot read, BEFORE anything is
* deleted (#520): a `format_version` above `SREF_FORMAT_VERSION` comes from a
* newer Simpl'Résultat, whose files may carry what this build would drop
* without a word; one that is not an integer of at least 1 was not written by
* the app at all, and gets the refusal of a malformed envelope.
*
* PURE: no I/O, so it can be called from the parse step and again at the top of
* each restore that is given the format, like `validateImportedFormatRows`.
*/
export function validateImportedFormatVersion(formatVersion: unknown): void {
if (!Number.isInteger(formatVersion) || (formatVersion as number) < 1) {
throw new Error(INVALID_ENVELOPE);
}
if ((formatVersion as number) > SREF_FORMAT_VERSION) {
throw new SrefValidationError("settings.dataManagement.import.errors.newerFormat", {});
}
}
/** The years a budget line may name. */
export const MIN_BUDGET_YEAR = 1900;
export const MAX_BUDGET_YEAR = 2200;
/**
* Refuse a file of format 3 or later whose budget lines, budget templates or
* adjustments the restore could not write back as they are, BEFORE anything is
* deleted (#520).
*
* From format 3 on, the two modes that carry the categories carry the three
* arrays, and the restore puts them in place of the profile's: a file that
* lacks one would empty that part of the budget, so it is refused, as is a
* line the tables cannot hold. Each line names a category of the file (the
* restore deletes every other one) and holds a finite amount; a budget line
* names a year from 1900 to 2200 and a month from 1 to 12, both integers; a
* template has a name and an adjustment a name and a date, both texts. No two
* budget lines share their category and month, no two lines of a template
* their category, no two templates their name: the `UNIQUE` keys of the
* tables. The tables are not STRICT, and SQLite's own refusal, midway through
* the restore, is not a message a user can act on. A file of an earlier format
* holds no budget, and nothing here applies to it.
*
* 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 validateImportedBudget(
data: ExportEnvelope["data"],
formatVersion: number
): void {
if (formatVersion < BUDGET_SREF_FORMAT_VERSION) return;
const refusal = () =>
new SrefValidationError(
"settings.dataManagement.import.errors.invalidBudgetRows",
{}
);
const { budget_entries: entries, budget_templates: templates, adjustments } = data;
if (!Array.isArray(entries) || !Array.isArray(templates) || !Array.isArray(adjustments)) {
throw refusal();
}
const categoryIds = new Set(
(data.categories ?? [])
.map((category) => category?.id)
.filter((id): id is number => typeof id === "number")
);
/** A line the restore can write: a category of the file, a finite amount. */
const isLine = (line: { category_id?: unknown; amount?: unknown } | null | undefined) =>
categoryIds.has(line?.category_id as number) && Number.isFinite(line?.amount);
const isYear = (year: unknown) =>
Number.isInteger(year) &&
(year as number) >= MIN_BUDGET_YEAR &&
(year as number) <= MAX_BUDGET_YEAR;
const isMonth = (month: unknown) =>
Number.isInteger(month) && (month as number) >= 1 && (month as number) <= 12;
const months = new Set<string>();
for (const entry of entries) {
if (!isLine(entry) || !isYear(entry.year) || !isMonth(entry.month)) throw refusal();
const key = `${entry.category_id}/${entry.year}/${entry.month}`;
if (months.has(key)) throw refusal();
months.add(key);
}
const names = new Set<string>();
for (const template of templates) {
if (typeof template?.name !== "string" || names.has(template.name)) throw refusal();
names.add(template.name);
if (!Array.isArray(template.entries)) throw refusal();
const lines = new Set<number>();
for (const line of template.entries) {
if (!isLine(line) || lines.has(line.category_id)) throw refusal();
lines.add(line.category_id);
}
}
for (const adjustment of adjustments) {
if (
typeof adjustment?.name !== "string" ||
typeof adjustment.date !== "string" ||
!Array.isArray(adjustment.entries)
) {
throw refusal();
}
for (const line of adjustment.entries) {
if (!isLine(line)) 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_ENVELOPE);
}
// A newer format first: a later build may also bring a mode this one does
// not know, and « update the app » is then the message that helps (#520).
const formatVersion = envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION;
validateImportedFormatVersion(formatVersion);
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, a category reference the file cannot satisfy, or budget lines the
// restore could not write back, 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
);
// The budget travels with the categories, in the two modes that carry them;
// « Transactions uniquement » carries none and its restore touches none.
if (envelope.export_type !== "transactions_only") {
validateImportedBudget(envelope.data, formatVersion);
}
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,
budgetEntriesCount: envelope.data.budget_entries?.length ?? 0,
budgetTemplatesCount: envelope.data.budget_templates?.length ?? 0,
adjustmentsCount: envelope.data.adjustments?.length ?? 0,
formatVersion,
},
};
}
/**
* 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, and no budget.
importSourcesCount: 0,
importTemplatesCount: 0,
budgetEntriesCount: 0,
budgetTemplatesCount: 0,
adjustmentsCount: 0,
formatVersion: LEGACY_SREF_FORMAT_VERSION,
},
};
}