fix: restore a backup's split lines with their parent (#518) #531

Merged
maximus merged 4 commits from issue-518-restore-split-ids into main 2026-11-07 18:58:08 +00:00
20 changed files with 1320 additions and 384 deletions

View file

@ -29,6 +29,7 @@
- Transactions : changer la catégorie d'une transaction répartie déplace désormais toute sa part non répartie vers la nouvelle catégorie. Les rapports gardaient, dans l'ancienne catégorie, le montant envoyé vers les autres catégories avec le signe inverse, sans transaction correspondante, et comptaient la transaction entière dans la nouvelle : une transaction de −120 dont −50 sont répartis vers B, déplacée de A vers C, laissait +50 dans A et −120 dans C, au lieu de −70 dans C. Cela vaut pour la catégorie choisie dans la liste des transactions comme pour les transactions recatégorisées par un nouveau mot-clé. « Auto-catégoriser » ne déplace plus ce montant seul quand la transaction a été mise à la main sur « Sans catégorie ». Une répartition déjà touchée se répare au prochain changement de catégorie de sa transaction, et sa fenêtre de répartition ne montre plus ce montant comme l'une de ses lignes. La prévisualisation d'un mot-clé ne liste plus les parts d'une répartition, qu'elle pouvait recatégoriser sans leur transaction (#454).
- Transactions : enregistrer ou supprimer une répartition ne laisse plus de répartition à moitié écrite après une erreur (#513).
- Rapports : « Tout » montre désormais toutes les dates sur Tendances, dans ses deux vues, et sur l'Analyse par catégorie ; il montrait l'année civile en cours. Sur les Comparables, « Tout » ne déplace plus le mois de référence vers décembre de l'année en cours : le mois affiché reste le même jusqu'au choix d'une période datée, qui le place à la fin de cette période (#479).
- Export/import de données : restaurer une sauvegarde qui contient une répartition fonctionne. Dans le même profil, la restauration s'arrêtait sur une erreur sans rien modifier, dans les deux modes, comme « Rétablir la sauvegarde » après une migration des catégories ; dans un profil neuf, les lignes d'une répartition pouvaient se rattacher en silence à une autre transaction, et la fenêtre de répartition de la vraie restait vide. Chaque transaction revient désormais avec son propre numéro, celui que nomment les lignes de sa répartition. Pour la même raison, l'export CSV commence maintenant par une colonne `id`, et un CSV exporté par une version antérieure qui contient des répartitions est refusé avec un message, sans rien modifier : utilisez un export JSON. « Rétablir la sauvegarde » dit aussi pourquoi un fichier est refusé, au lieu d'un message générique (#518).
### Sécurité

View file

@ -29,6 +29,7 @@
- Transactions: changing the category of a split transaction now moves all of its unsplit part to the new category. The reports used to keep, in the former category, the amount sent to the other categories with the opposite sign, matching no transaction, and to count the whole transaction in the new one: a transaction of −120 with −50 split to B, moved from A to C, left +50 in A and −120 in C, instead of −70 in C. This holds for the category chosen in the Transactions list and for the transactions recategorized by a new keyword. “Auto-categorize” no longer moves that amount alone when the transaction was set to “No category” by hand. A split already affected is repaired the next time its transaction changes category, and its split window no longer shows that amount as one of its rows. The keyword preview no longer lists the parts of a split, which it could recategorize without their transaction (#454).
- Transactions: saving or deleting a split no longer leaves a half-written split after an error (#513).
- Reports: “All” now shows every date on Trends, in both views, and on Category Analysis; it showed the current calendar year. On Compare, “All” no longer moves the reference month to December of the current year: the month shown stays as it is until you choose a dated period, which moves it to the end of that period (#479).
- Data export/import: restoring a backup that holds a split now works. In the same profile, the restore stopped on an error and changed nothing, in both modes, as did “Restore the backup” after a category migration; in a new profile, the lines of a split could hang, without a word, off another transaction, and the split window of the real one stayed empty. Each transaction now comes back with its own number, the one the lines of its split name. For the same reason, the CSV export now starts with an `id` column, and a CSV exported by an earlier version that holds splits is refused with a message, nothing modified: use a JSON export. “Restore the backup” also says why a file is refused, instead of a generic message (#518).
### Security

View file

@ -57,7 +57,7 @@ src/
├── contexts/ # ProfileContext (état global profil)
├── hooks/ # 30 hooks custom (useReducer)
├── pages/ # 11 pages
├── services/ # 29 services métier
├── services/ # 30 services métier
├── shared/ # Types et constantes partagés
├── utils/ # Utilitaires (parsing, CSV, charts)
├── i18n/ # Config i18next + locales FR/EN

View file

@ -47,7 +47,7 @@ Restent au moins normaux, et leurs règles de zone s'appliquent quand même :
- une montée de version d'un paquet déjà présent dans un lock, correctif d'advisory compris (décision de Max du 2026-10-17, consignée sur #456), et une arête re-résolue vers une version déjà présente : seul le garde `windows-sys` de la CI en surveille, pour ses sept crates ([ADR 0023](docs/adr/0023-windows-sys-pinning.md)) ;
- dans `check-rust.yml` et `check-frontend.yml` : un déclencheur ajouté, sauf `pull_request_target`, une étape `run:` ajoutée qui ne fait que lire, un cache (`Swatinem/rust-cache`, `actions/cache`), un commentaire au sens donné sous « Motifs » (une ligne qui porte `${{ … }}` n'en est pas un), la version de Node ;
- `src/services/db.ts` et `src/services/dataExportService.ts`, même quand le diff touche le verrou, le changement de profil ou les suppressions de la restauration (décision de Max du 2026-10-18, revue de #460) : contre leurs défauts, la mutation du niveau normal est le bon outil ;
- `src/services/db.ts`, `src/services/dataExportService.ts` et `src/services/dataRestoreService.ts`, même quand le diff touche le verrou, le changement de profil ou les suppressions de la restauration (décision de Max du 2026-10-18, revue de #460) : contre leurs défauts, la mutation du niveau normal est le bon outil ;
- `src-tauri/src/commands/{fs_commands,backup_commands}.rs`, et le reste de `balance_commands.rs` ;
- `src/shared/entitlements.ts` : la matrice ne verrouille que l'interface ([ADR 0017](docs/adr/0017-feature-gating-par-tier.md), § 2) ;
- `CLAUDE.md`, `REVIEW.md` hors de la section « Niveaux », `docs/adr/**`, `docs/architecture.md`, `docs/qa-update-cycle.md` et `.claude/**` : sources de ce fichier et instructions des agents, jamais de niveau bas.
@ -106,7 +106,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
- Tout changement de schéma et toute correction de données (seed, mots-clés, catégories) se reportent dans `consolidated_schema.sql` : un profil neuf naît avec l'historique complet et ne rejoue aucune migration. Aucun marqueur ajouté à `infer_floor`, réservé aux bases créées avant #390. — [ADR 0021](docs/adr/0021-migrations-profils-secondaires.md), `.claude/rules/sql-migrations.md`
- Les comptes de tables, d'index et de migrations de `CLAUDE.md` et de `docs/architecture.md` suivent. — `CLAUDE.md` « Base de données » et « Documentation technique »
- Les bases vivent sous `app_config_dir()`, qui n'est pas `app_data_dir()` sous Linux. Les deux dossiers dérivent de l'`identifier` de `tauri.conf.json` : le changer orpheline tout ce que l'app range sous l'un ou l'autre. Par exemple, sous `app_config_dir()`, les bases des profils ; sous `app_data_dir()`, `profiles.json` (la liste des profils et leur `pin_hash`), la clé de licence, le jeton d'activation et tout le dossier `auth/`, dont le fichier de repli des jetons OAuth. Le service du trousseau (`KEYCHAIN_SERVICE`, une constante de `token_store.rs` et une autre d'`account_cache.rs`) est aligné sur l'`identifier` par convention : il ne suit pas. — [ADR 0021](docs/adr/0021-migrations-profils-secondaires.md), [ADR 0006](docs/adr/0006-oauth-tokens-keychain.md), `CLAUDE.md` « Base de données », `src-tauri/src/commands/{profile_commands,license_commands,token_store,account_cache}.rs`
- Toute requête passe par le verrou unique de `db.ts`, et une transaction par `withTransaction` et son handle ; un changement de profil ferme puis rouvre la connexion. La restauration d'une sauvegarde (`runRestore` de `dataExportService.ts`) efface puis réinsère dans une seule transaction et ne notifie qu'après le `COMMIT`, une fois le verrou relâché. — [ADR 0022](docs/adr/0022-canal-evenements-donnees.md), [ADR 0005](docs/adr/0005-multi-profile-db.md), `docs/architecture.md` « Accès DB et transactions »
- Toute requête passe par le verrou unique de `db.ts`, et une transaction par `withTransaction` et son handle ; un changement de profil ferme puis rouvre la connexion. La restauration d'une sauvegarde (`runRestore` de `dataRestoreService.ts`) efface puis réinsère dans une seule transaction et ne notifie qu'après le `COMMIT`, une fois le verrou relâché. — [ADR 0022](docs/adr/0022-canal-evenements-donnees.md), [ADR 0005](docs/adr/0005-multi-profile-db.md), `docs/architecture.md` « Accès DB et transactions »
- Un booléen se lie en `1`/`0` (`toSqlFlag`), jamais en `true`/`false`. — [ADR 0021](docs/adr/0021-migrations-profils-secondaires.md)
- Une base par profil, PIN haché par Argon2. — [ADR 0005](docs/adr/0005-multi-profile-db.md)
- Une nouvelle écriture d'une table que lit `COUNTERS_SQL` appelle `notifyDataChanged()` après succès, avec un test qui prouve la notification. — [ADR 0022](docs/adr/0022-canal-evenements-donnees.md)
@ -194,5 +194,5 @@ Les trois premiers viennent du skill global `pr-review`, corrigés pour ce dép
- **Booléen lié en texte.** tauri-plugin-sql stocke un booléen JS en texte `'true'`, qu'une condition `= 1` ne trouve pas : défaut resté invisible de la v0.1.0 à #390. — [ADR 0021](docs/adr/0021-migrations-profils-secondaires.md)
- **Transaction hors verrou.** Un `BEGIN` et son `COMMIT` envoyés par deux `db.execute` peuvent partir sur deux connexions du pool et laisser un verrou zombie (« database is locked », v0.10.0) : toujours `withTransaction` et son handle. — `docs/architecture.md` « Accès DB et transactions »
- **Dépôt public.** Aucune coordonnée d'un tiers (courriel, adresse, téléphone), aucune clé de licence ni aucun jeton dans un fichier commité, `STATE.md`, `docs/` et `.claude/skills/` compris ; un testeur se désigne par son identifiant Logto. — `.claude/skills/issue-license/SKILL.md`
- **Tests vitest qui lisent `src-tauri/`.** Des tests du front lisent des fichiers de `src-tauri/` : `src/hooks/useImportWizard.test.ts` lit les codes `SAMPLE_ERROR_*` de `fs_commands.rs` (contrat avec leur traduction), `src/services/categoryService.test.ts`, `src/__integration__/onboarding-samples.test.ts` et `src/__integration__/split-offset-manual-flag.test.ts` lisent `consolidated_schema.sql` (le dernier l'exécute en entier, seed compris), `src/utils/changelog.test.ts` la version de `tauri.conf.json`. Une PR qui ne touche que `src-tauri/**` saute `check-frontend` : la dérive ne rougit que la PR suivante qui touche `src/`, sans rapport avec elle. La revue d'une telle PR lance ces tests (`npx vitest run <fichier>`). — `check-frontend.yml` (`paths-ignore`), #384
- **Tests vitest qui lisent `src-tauri/`.** Des tests du front lisent des fichiers de `src-tauri/` : `src/hooks/useImportWizard.test.ts` lit les codes `SAMPLE_ERROR_*` de `fs_commands.rs` (contrat avec leur traduction), `src/services/categoryService.test.ts`, `src/__integration__/onboarding-samples.test.ts`, `src/__integration__/split-offset-manual-flag.test.ts` et `src/__integration__/restore.test.ts` lisent `consolidated_schema.sql` (les deux derniers l'exécutent en entier, seed compris), `src/utils/changelog.test.ts` la version de `tauri.conf.json`. Une PR qui ne touche que `src-tauri/**` saute `check-frontend` : la dérive ne rougit que la PR suivante qui touche `src/`, sans rapport avec elle. La revue d'une telle PR lance ces tests (`npx vitest run <fichier>`). — `check-frontend.yml` (`paths-ignore`), #384
- **Garde du README.** `check-frontend.yml` ignore `*.md` à la racine : une PR qui ne touche que `README.md` ne lance donc pas `src/__integration__/readme-guard.test.ts`, et un README qui ne la passe plus ne rougit que la PR suivante qui lance `check-frontend`, sans rapport avec lui. La revue d'une telle PR lance `npx vitest run src/__integration__/readme-guard.test.ts`. — `check-frontend.yml` (`paths-ignore`), #523

View file

@ -43,6 +43,7 @@
- Compensation d'une répartition (#454) et répartition en une transaction (#513) : PR #515 et #516.
- Période des Rapports (#479) : PR #517.
- Étiquette des liens vers la page produit (#525) : PR #528, texte complet dans le commentaire 30933 de #508.
- Restauration d'une sauvegarde (#518) : PR #531.
- **Contrôles de niveau dus** : la première PR qui ne monte qu'une version dans un lock affiche « Niveau : normal », et le prochain changement d'un consentement « Niveau : haut » (#476) ; la première PR qui ne touche que des messages du Journal, « Niveau : normal » (#462 ; le cas du `SKILL.md` de `/release` est prouvé par la PR #503, revue 28394) ; la première PR qui ne touche que `release.yml` lance `check-frontend` (#419 ; le cas de `.claude/**` est prouvé par les PR #450 et #503, runs 567 et 641).
- **Suivis sans issue** :
- Le refus du format « montant absolu + indicateur D/C » ne regarde que `amountCol ± 1` (`src/utils/csvAutoDetect.ts:953`) : une colonne D/C placée ailleurs passe encore.

View file

@ -35,7 +35,7 @@ La liste est construite depuis les tables que lit `COUNTERS_SQL`, plus le dossie
| `transactionService.ts` | `insertBatch`, `updateTransactionCategory`, `saveSplitAdjustment`, `deleteSplitAdjustment` | `insertBatch` une fois, après la dernière insertion ; `updateTransactionCategory` (#454), `saveSplitAdjustment` et `deleteSplitAdjustment` (#513) après le `COMMIT` de leur transaction, une fois le verrou relâché, et un `ROLLBACK` relance l'erreur et ne notifie pas |
| `categorizationService.ts` | `applyKeywordWithReassignment` | après le `COMMIT`, une fois le verrou de `db.ts` relâché ; un `ROLLBACK` relance l'erreur et ne notifie pas |
| `budgetService.ts` | `upsertBudgetEntry`, `deleteBudgetEntry`, `upsertBudgetEntriesForYear`, `applyTemplate` | après l'écriture ; `upsertBudgetEntriesForYear` après les douze mois, `applyTemplate` une fois après la dernière entrée du modèle |
| `dataExportService.ts` | `runRestore` | après le `COMMIT`, une fois le verrou relâché : un seul point pour les trois modes de restauration |
| `dataRestoreService.ts` | `runRestore` | après le `COMMIT`, une fois le verrou relâché : un seul point pour les trois modes de restauration |
| `useImportWizard.ts` | fin d'`executeImport` | une notification de plus, en succès comme en échec (`finally`), pour que la dernière relecture voie l'état final de l'import |
Cette liste ne doit pas rétrécir. Sans `insertBatch` ni `updateFileStatus`, la dernière relecture d'un import partait avant l'insertion des transactions, et le parcours restait sur un état intermédiaire.

View file

@ -44,7 +44,7 @@ simpl-resultat/
│ ├── contexts/ # LicenseContext (licence machine) + ProfileContext (état global profil) + OnboardingContext (parcours de démarrage, #396)
│ ├── hooks/ # 30 hooks custom (useReducer, 5 hooks rapports par domaine)
│ ├── pages/ # 14 pages (dont 4 sous-pages rapports)
│ ├── services/ # 29 services métier (23 détaillés dans la section « Services TypeScript »)
│ ├── services/ # 30 services métier (24 détaillés dans la section « Services TypeScript »)
│ ├── shared/ # Types, constantes, matrice d'entitlements (entitlements.ts), gate profils (profileGate.ts), gate de la Répartition (splitGate.ts), CTA d'upsell (upsellCta.ts), URL d'achat (purchaseUrl.ts), échéance de licence (licenseExpiry.ts)
│ ├── utils/ # 21 utilitaires purs (parsing montants/dates, détection CSV, codec de format d'import, dictionnaire lexical, signatures de banques, charts, drapeaux SQL 0/1, liste et parcours de démarrage, historique des versions, hiérarchie des catégories, ligne de compensation d'une répartition)
│ ├── i18n/ # Config i18next + locales FR/EN
@ -195,7 +195,7 @@ Les **profils secondaires** (`profile_<id>.db`) sont créés par `get_new_profil
Le dossier des bases est celui du plugin : `app_config_dir()`, résolu par `profile_db_path` (`profile_commands.rs`). Il diffère de `app_data_dir()`, où vit `profiles.json`, sous Linux seulement (`~/.config/com.simpl.resultat` et `~/.local/share/com.simpl.resultat`).
## Services TypeScript (23)
## Services TypeScript (24)
| Service | Responsabilité |
|---------|---------------|
@ -212,7 +212,8 @@ Le dossier des bases est celui du plugin : `app_config_dir()`, résolu par `prof
| `budgetService.ts` | Gestion budgétaire |
| `dashboardService.ts` | Agrégation données tableau de bord : `getExpensesByCategory` (barres classées, `accountIds`), `getDashboardSummary` (non consommé depuis #279), `deriveNetWorthTile` (pur — tuile valeur nette du Bilan, réutilise `deriveLandingState`) |
| `reportService.ts` | Génération de rapports : `getMonthlyTrends`, `getCategoryOverTime`, `getHighlights`, `getCompareMonthOverMonth`, `getCompareYearOverYear`, `getCategoryZoom` (CTE récursive bornée anti-cycle), `getCartesSnapshot` (snapshot dashboard Cartes, requêtes parallèles) |
| `dataExportService.ts` | Export de données (chiffré). L'enveloppe SREF porte un `format_version` explicite (`SREF_FORMAT_VERSION = 2`) et **inclut `import_sources` + `import_config_templates`** depuis #331 ; wipe et restauration sous `withTransaction`, modèles restaurés avant les sources avec remap de `template_id` |
| `dataExportService.ts` | Export de données (chiffré), lecture du fichier et validations de la frontière d'import. L'enveloppe SREF porte un `format_version` explicite (`SREF_FORMAT_VERSION = 2`) et **inclut `import_sources` + `import_config_templates`** depuis #331 ; l'export CSV commence par une colonne `id` (#518). `parseImportedJson` et `parseImportedCsv` refusent, avant que la fenêtre de confirmation ne s'ouvre, une configuration illisible (`validateImportedFormatRows`) et des lignes de répartition qui ne retrouvent pas leur parent (`validateImportedTransactionIds`, #518), par une `SrefValidationError` qui porte sa clé i18n. La restauration vit dans `dataRestoreService.ts` |
| `dataRestoreService.ts` | Restauration d'une sauvegarde SREF/JSON ou d'un export CSV, sortie de `dataExportService.ts` par #518 : les trois modes passent par `runRestore`, qui efface puis réinsère dans une seule transaction (`withTransaction`, son `BEGIN`, son `COMMIT`, `ROLLBACK` puis relance sur un échec) et ne notifie qu'après le `COMMIT` ([ADR 0022](adr/0022-canal-evenements-donnees.md)) ; modèles restaurés avant les sources avec remap de `template_id` ; transactions réinsérées avec leur `id` exporté, les lignes sans parent avant les lignes de répartition (#518). `importTransactionsOnly` et `importTransactionsWithCategories` rejouent en tête les deux validations du parse, avant toute suppression. Appelé par `useDataImport` et par `restoreFromBackup` (`categoryRestoreService.ts`, « Rétablir la sauvegarde ») |
| `userPreferenceService.ts` | Stockage préférences utilisateur |
| `onboardingService.ts` | Parcours de démarrage (#351, #396) : `getOnboardingSnapshot`, une lecture pure, lit en une passe parallèle les cinq compteurs (`import_sources`, `imported_files` terminés, transactions `is_manually_categorized = 1`, `budget_entries`, transactions), le dossier d'import, la préférence `onboarding_checklist_hidden`, les étapes passées (une préférence `onboarding_skipped_<clé>` = `"1"` par étape, lues en une requête et filtrées sur les huit clés), les étapes de visite reconnues (`onboarding_acknowledged_<clé>` = `"1"`, lues en une requête et filtrées sur `VISIT_STEP_KEYS`, #425) et le drapeau `onboarding_visit_steps_initialized` ; `initializeGuidedPath` applique la règle D9 une fois par profil, dans une transaction (un profil qui a déjà des transactions est masqué, puis `onboarding_guided_initialized` est posé) ; `initializeVisitSteps(acknowledge)` initialise les étapes de visite une fois par profil, **sans transaction** (les deux reconnaissances si `acknowledge`, puis le drapeau, par écritures idempotentes) ; `hideChecklist` / `showChecklist`, `skipStep` / `resumeStep` et `acknowledgeStep` posent et retirent les préférences, sans notifier. Aucune UI ici : `computeChecklist` (`utils/onboardingChecklist.ts`, pur) transforme le snapshot en huit lignes — voir la section « Onboarding » |
| `dataEvents.ts` | Canal d'événements de données (#396, [ADR 0022](adr/0022-canal-evenements-donnees.md)) : `notifyDataChanged()` après chaque écriture réussie d'une table que lit un compteur du parcours de démarrage (liste dans l'ADR), `subscribeDataChanged(listener)` rend le désabonnement. Sans React ni charge utile ; un abonné qui lève est écrit au Journal et n'empêche pas les autres |
@ -345,6 +346,8 @@ L'étape `file-preview`, déclarée depuis l'origine dans `ImportWizardStep` san
`dataExportService` sérialisait uniquement catégories, fournisseurs, mots-clés et transactions, puis exécutait `DELETE FROM import_sources` à la restauration en les remplaçant par une source synthétique « Data Import » — restaurer une sauvegarde détruisait toute configuration d'import. Depuis #331 : `import_sources` et `import_config_templates` sont dans l'enveloppe derrière un `format_version` explicite (`SREF_FORMAT_VERSION = 2` ; une enveloppe sans le champ est l'ancien format, ses tableaux absents traités comme vides). Les **modèles sont restaurés avant les sources** (`template_id` est une FK), upsertés par nom, et `template_id` remappé sur les identifiants résolus. Wipe et restauration des deux chemins sont enveloppés dans `withTransaction` — le service n'en avait aucune, et une violation de contrainte en cours de restauration détruisait l'historique financier sans rollback. `amount_mode` et `sign_convention` sont whitelistés à la frontière d'import avec un message lisible (le `CHECK` v17 refuse déjà les mauvaises valeurs, mais une erreur de contrainte SQLite n'est pas un message utilisateur).
Depuis #518, la restauration (`dataRestoreService.ts`) réinsère chaque transaction avec son `id` exporté, comme les catégories, les fournisseurs et les mots-clés : une ligne de répartition nomme son parent par cet identifiant (`parent_transaction_id`, clé étrangère vers `transactions(id)`). Réinsérée sans lui, elle visait dans le même profil un identifiant disparu, la séquence `AUTOINCREMENT` survivant au `DELETE` (« FOREIGN KEY constraint failed », restauration annulée, « Rétablir la sauvegarde » compris), et se rattachait en silence, dans un profil neuf, à la ligne qui avait repris l'ancien identifiant de son parent. Les lignes sans parent passent avant les lignes de répartition, l'ordre du fichier gardé dans chaque passe. `validateImportedTransactionIds`, pure, rend `{ keepIds }` : les lignes gardent leur identifiant si chacune porte un entier sûr de 1 à 2 147 483 647 qu'aucune autre ne porte ; sinon SQLite les attribue, ce que seul un fichier sans ligne de répartition peut se permettre. Une ligne de répartition qui ne nomme pas une ligne du fichier sans parent fait refuser le fichier (`SrefValidationError`, clé `orphanSplitLines`), au parse comme en tête de restauration : un fichier aux identifiants en double, une ligne qui est son propre parent, un parent qui est lui-même une ligne de répartition. L'export CSV porte une colonne `id` en tête ; `parseImportedCsv` lit `id` et `parent_transaction_id` par `/^\d+$/` seulement (« 12abc » n'est pas 12) et ne prend jamais le numéro de ligne pour un identifiant, si bien qu'un CSV exporté avant #518 qui contient des répartitions est refusé. `SREF_FORMAT_VERSION` reste à 2 : le JSON portait déjà `id`. « Rétablir la sauvegarde » laisse passer une `SrefValidationError` telle quelle, et sa fenêtre en affiche le texte traduit.
### Corpus de fixtures — `src/__fixtures__/csv/`
15 fichiers CSV **synthétiques** (aucune donnée réelle, aucun relevé réel n'entre dans ce dépôt — les signatures de banques sont écrites depuis des dispositions documentées). Ils couvrent des formes qu'un vrai relevé ne réunit jamais toutes : montant signé, débit/crédit, débit/crédit inversés, colonne inutilisée à `0,00`, préambule, en-tête contenant un nombre, en-tête à libellé numérique, sans en-tête, tout-positif, Desjardins quoté, montant absolu + indicateur, plus les quatre dispositions de banque. Posés en #326 **avant** la refonte, avec le comportement fautif figé et marqué `KNOWN DEFECT` + l'issue devant le corriger ; chaque maillon suivant a mis à jour l'attente et retiré le marqueur, sans jamais supprimer un test.
@ -704,7 +707,7 @@ Garde : `src/__integration__/i18n-mock-guard.test.ts` lit tous les `*.test.ts(x)
`categoryService.test.ts` exécute les requêtes qui vérifient ce que porte un parent (transactions, montants de budget, mots-clés) telles qu'elles sont écrites, sur une base SQLite en mémoire de `node:sqlite`, module intégré à Node (aucun paquet ; expérimental sous Node 22, qui l'annonce par un avertissement à l'exécution). Ses tables y sont créées par leur `CREATE TABLE` de `consolidated_schema.sql`, clés étrangères coupées : la table `categories` reste dans le faux du test. Une condition retirée d'une requête (`amount <> 0`, `is_active = 1`) rougit donc un test, ce qu'un faux qui réimplémente la règle ne ferait pas.
`src/__integration__/split-offset-manual-flag.test.ts` (#454) y fait tourner des services entiers : `saveSplitAdjustment`, `updateTransactionCategory` et `autoCategorizeTransactions`, tels qu'ils sont écrits, sur le schéma complet d'un profil neuf (`consolidated_schema.sql`, seed compris : mot-clé `METRO`, catégories 1111 et 1112), clés étrangères actives comme sous sqlx. `../services/db` y est remplacé par un adaptateur propre au fichier : `select` et `execute` lient `$N` par nom, `execute` rend `rowsAffected` et `lastInsertId`, `withTransaction` passe à son rappel le même handle, et `getDb()` échoue pendant une transaction, là où le vrai verrou bloquerait. Aucun harnais partagé : #392 le prévoit. Les autres tests de services gardent leurs faux.
`src/__integration__/split-offset-manual-flag.test.ts` (#454) y fait tourner des services entiers : `saveSplitAdjustment`, `updateTransactionCategory` et `autoCategorizeTransactions`, tels qu'ils sont écrits, sur le schéma complet d'un profil neuf (`consolidated_schema.sql`, seed compris : mot-clé `METRO`, catégories 1111 et 1112), clés étrangères actives comme sous sqlx. `../services/db` y est remplacé par un adaptateur propre au fichier : `select` et `execute` lient `$N` par nom, `execute` rend `rowsAffected` et `lastInsertId`, `withTransaction` passe à son rappel le même handle, et `getDb()` échoue pendant une transaction, là où le vrai verrou bloquerait. `src/__integration__/restore.test.ts` (#518) en copie l'adaptateur pour les restaurations (`importTransactionsOnly`, `importTransactionsWithCategories`, et « Rétablir la sauvegarde » par `restoreFromBackup`), avec une seconde base qui tient lieu de profil neuf. Aucun harnais partagé : #392 le prévoit. Les autres tests de services gardent leurs faux.
### Limites connues (#437)

View file

@ -611,6 +611,7 @@ Configurez les préférences de l'application, vérifiez les mises à jour, acc
- Les mises à jour ne remplacent que le programme — votre base de données n'est jamais modifiée
- Changez la langue de l'application via le sélecteur de langue dans la barre latérale
- Exportez régulièrement pour garder une sauvegarde de vos données
- Un export CSV commence par une colonne `id`, le numéro de chaque transaction, qui garde les lignes d'une répartition avec leur transaction d'origine. Un CSV exporté par une version antérieure qui contient des répartitions est refusé à l'import, sans rien modifier : utilisez un export JSON
- Le guide d'utilisation peut être imprimé ou exporté en PDF via le bouton Imprimer
- Les journaux persistent pendant la session — ils survivent à un rafraîchissement de la page
- L'application ne contacte un serveur que pour les mises à jour, la connexion Maximus, le feedback, la licence (activation et vérification) et les cours du marché. Une seule requête part d'elle-même, au démarrage et à la saisie d'une clé : la vérification de la licence, au plus une fois par 24 heures pour une même clé et seulement si une clé est enregistrée. Aucune télémétrie. Les liens vers la page produit indiquent au site qu'ils viennent de l'application et de quel bouton, sans rien qui vous identifie.

View file

@ -31,7 +31,8 @@ vi.mock("@tauri-apps/api/app", () => ({
}));
// dataExportService helpers are used by both the backup service and the
// restore service. We mock the "DB-reading" ones and keep the parsers real.
// restore service, which writes the backup back through dataRestoreService. We
// mock the "DB-reading" ones and that write, and keep the parsers real.
vi.mock("../services/dataExportService", async () => {
const actual = await vi.importActual<
typeof import("../services/dataExportService")
@ -42,6 +43,14 @@ vi.mock("../services/dataExportService", async () => {
getExportSuppliers: vi.fn(async () => []),
getExportKeywords: vi.fn(async () => []),
getExportTransactions: vi.fn(async () => []),
};
});
vi.mock("../services/dataRestoreService", async () => {
const actual = await vi.importActual<
typeof import("../services/dataRestoreService")
>("../services/dataRestoreService");
return {
...actual,
importTransactionsWithCategories: vi.fn(async () => undefined),
};
});
@ -52,7 +61,7 @@ import { computeMigrationPlan } from "../services/categoryMappingService";
import { createPreMigrationBackup } from "../services/categoryBackupService";
import { applyMigration } from "../services/categoryMigrationService";
import { restoreFromBackup } from "../services/categoryRestoreService";
import { importTransactionsWithCategories } from "../services/dataExportService";
import { importTransactionsWithCategories } from "../services/dataRestoreService";
import { makeV2Profile, makeV2ProfileWithCustom } from "../__fixtures__/profiles";
import type { Profile } from "../services/profileService";

View file

@ -0,0 +1,383 @@
/**
* Restoring a backup that holds a split (#518).
*
* A split line names its parent by `parent_transaction_id`, a foreign key to
* `transactions(id)`. The restore used to insert every row without its 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, « Rétablir la
* sauvegarde » included. In a new profile, the line hung off whichever row had
* taken its parent's old id. The rows now go back with their exported ids, the
* lines without a parent first, and a file whose split lines cannot find their
* parent is refused before anything is deleted.
*
* The services run as written on a real SQLite database: `node:sqlite` (built
* into Node, no package), the schema of a new profile with its seed
* (`consolidated_schema.sql`), foreign keys on, as under sqlx. `../services/db`
* is replaced by the adapter of `split-offset-manual-flag.test.ts`, copied here
* (#392 plans a shared harness): `select` and `execute` run the statement with
* its `$N` bound by name, `execute` answers `rowsAffected` and `lastInsertId`,
* `withTransaction` hands its callback the same handle, and `getDb()` throws
* while a transaction runs, where the real lock, which is not reentrant, would
* deadlock. A second database stands for a new profile.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { readFileSync } from "fs";
import { resolve } from "path";
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
const fake = vi.hoisted(() => ({
handle: null as unknown,
inTransaction: false,
}));
vi.mock("../services/db", () => ({
getDb: vi.fn(async () => {
if (fake.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
return fake.handle;
}),
withTransaction: vi.fn(async (fn: (db: unknown) => Promise<unknown>) => {
fake.inTransaction = true;
try {
return await fn(fake.handle);
} finally {
fake.inTransaction = false;
}
}),
}));
// « Rétablir la sauvegarde » reads its file through `read_import_file`.
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import { getSplitChildren, saveSplitAdjustment } from "../services/transactionService";
import {
getExportCategories,
getExportImportSources,
getExportImportTemplates,
getExportKeywords,
getExportSuppliers,
getExportTransactions,
parseImportedCsv,
parseImportedJson,
serializeToJson,
serializeTransactionsToCsv,
SrefValidationError,
type ExportEnvelope,
type ExportTransaction,
} from "../services/dataExportService";
import { importTransactionsOnly, importTransactionsWithCategories } from "../services/dataRestoreService";
import { restoreFromBackup } from "../services/categoryRestoreService";
const SCHEMA = readFileSync(
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
"utf-8",
);
/** Categories of the seed of a new profile. */
const GROCERIES = 1111; // « Épicerie régulière »
const B = 1112; // « Boucherie & poissonnerie », where the split sends −50
const RENT = 1211; // « Loyer »
const ELECTRICITY = 1221; // « Électricité »
const PAY = 1011; // « Paie régulière »
const REFUSAL = "settings.dataManagement.import.errors.orphanSplitLines";
/** What the split window of « EPICERIE METRO » shows: −50 sent to B, +50 cancelling it in its category. */
const GROCERY_SPLIT = [
{ amount: -50, category_id: B },
{ amount: 50, category_id: GROCERIES },
];
type Mode = "transactions_with_categories" | "transactions_only";
const MODES: Mode[] = ["transactions_with_categories", "transactions_only"];
/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */
function adapter(db: DatabaseSync) {
// tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name.
const bind = (params?: unknown[]) =>
Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue]));
return {
select: async (sql: string, params?: unknown[]) =>
db.prepare(sql).all(bind(params)).map((row) => ({ ...row })),
execute: async (sql: string, params?: unknown[]) => {
const result = db.prepare(sql).run(bind(params));
return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) };
},
};
}
let opened: DatabaseSync[] = [];
/** The profile the backups are taken from. */
let profile: DatabaseSync;
/** A database with the schema of a new profile, foreign keys on. */
function open(): DatabaseSync {
const db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true });
db.exec(SCHEMA);
opened.push(db);
return db;
}
/** Points the services at `db`. */
function use(db: DatabaseSync): DatabaseSync {
fake.handle = adapter(db);
return db;
}
/** A transaction as an import writes it, with its category; its id. */
function imported(date: string, description: string, amount: number, categoryId: number): number {
const result = profile
.prepare(
`INSERT INTO transactions (date, description, amount, category_id, original_description)
VALUES ($date, $description, $amount, $category, $description)`,
)
.run({ $date: date, $description: description, $amount: amount, $category: categoryId });
return Number(result.lastInsertRowid);
}
/**
* The profile of the probe of #518: the split parent is NOT the first
* transaction by date, so a restore that renumbers in the export's order
* (`ORDER BY t.date, t.id`) hands its old id to « LOYER ».
*/
beforeEach(async () => {
opened = [];
fake.inTransaction = false;
invoke.mockReset();
profile = use(open());
expect(imported("2026-10-05", "EPICERIE METRO", -120, GROCERIES)).toBe(1);
expect(imported("2026-10-01", "LOYER", -1000, RENT)).toBe(2);
expect(imported("2026-10-03", "PAIE", 2000, PAY)).toBe(3);
// Children 4 (−50 to B) and 5 (+50, the offset line), by the real service.
await saveSplitAdjustment(1, [{ category_id: B, amount: -50, description: "EPICERIE METRO" }]);
});
afterEach(() => {
for (const db of opened) db.close();
});
type Row = {
id: number;
date: string;
description: string;
amount: number;
category_id: number | null;
is_manually_categorized: number;
is_split: number;
parent_transaction_id: number | null;
};
/** Every transaction of `db`, by id: what a restore must give back as it was. */
function rows(db: DatabaseSync): Row[] {
return db
.prepare(
`SELECT id, date, description, amount, category_id, is_manually_categorized, is_split, parent_transaction_id
FROM transactions ORDER BY id`,
)
.all()
.map((row) => ({ ...row })) as Row[];
}
/** What the reports add up, per category: every row, split parent and children included. */
function totals(db: DatabaseSync): Record<string, number> {
const sums = db
.prepare("SELECT category_id, SUM(amount) AS total FROM transactions GROUP BY category_id")
.all() as Array<{ category_id: number | null; total: number }>;
return Object.fromEntries(sums.map((r) => [r.category_id === null ? "none" : String(r.category_id), r.total]));
}
function count(db: DatabaseSync, table: string): number {
return Number((db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n);
}
/** What the split window of the transaction `description` shows, through the real service. */
async function splitLines(db: DatabaseSync, description: string) {
const parent = db
.prepare("SELECT id FROM transactions WHERE description = $description AND parent_transaction_id IS NULL")
.get({ $description: description }) as { id: number };
const lines = await getSplitChildren(parent.id);
return lines.map((line) => ({ amount: line.amount, category_id: line.category_id }));
}
/** What « Exporter » gathers for `mode` (`useDataExport`), from the database in use. */
async function exportData(mode: Mode): Promise<ExportEnvelope["data"]> {
const data: ExportEnvelope["data"] = {};
if (mode === "transactions_with_categories") {
data.categories = await getExportCategories();
data.suppliers = await getExportSuppliers();
data.keywords = await getExportKeywords();
}
data.transactions = await getExportTransactions();
data.import_sources = await getExportImportSources();
data.import_config_templates = await getExportImportTemplates();
return data;
}
/** A JSON backup of the database in use, written then read back as the import reads it. */
async function jsonBackup(mode: Mode): Promise<ExportEnvelope["data"]> {
return parseImportedJson(serializeToJson(mode, await exportData(mode), "0.17.2")).envelope.data;
}
function restore(mode: Mode, data: ExportEnvelope["data"], filename = "backup.json"): Promise<void> {
return mode === "transactions_with_categories"
? importTransactionsWithCategories(data, filename)
: importTransactionsOnly(data, filename);
}
/** The refusal of a file whose split lines cannot find their parent. */
function expectRefusal(error: unknown): void {
expect(error).toBeInstanceOf(SrefValidationError);
expect((error as SrefValidationError).i18nKey).toBe(REFUSAL);
}
/**
* The probe's profile as the CSV export wrote it before #518: no `id` column,
* so the `parent_transaction_id` of the two split lines (1) names a row the
* file never names.
*/
const PRE_FIX_CSV = [
"date,description,amount,category_name,category_id,original_description,notes,is_manually_categorized,is_split,parent_transaction_id",
"2026-10-01,LOYER,-1000,Loyer,1211,LOYER,,0,0,",
"2026-10-03,PAIE,2000,Paie régulière,1011,PAIE,,0,0,",
"2026-10-05,EPICERIE METRO,-120,Épicerie régulière,1111,EPICERIE METRO,,0,1,",
"2026-10-05,EPICERIE METRO,-50,Boucherie & poissonnerie,1112,EPICERIE METRO,,0,1,1",
"2026-10-05,EPICERIE METRO,50,Épicerie régulière,1111,EPICERIE METRO,,0,1,1",
].join("\r\n");
describe("restoring a backup that holds a split (#518)", () => {
it("the profile of the probe: the split parent comes third in the export, after « LOYER » and « PAIE »", async () => {
const exported = await getExportTransactions();
expect(exported.map((tx) => [tx.id, tx.description, tx.parent_transaction_id])).toEqual([
[2, "LOYER", null],
[3, "PAIE", null],
[1, "EPICERIE METRO", null],
[4, "EPICERIE METRO", 1],
[5, "EPICERIE METRO", 1],
]);
expect(await splitLines(profile, "EPICERIE METRO")).toEqual(GROCERY_SPLIT);
});
it.each(MODES)("%s, same profile: the restore succeeds and each split line keeps its parent", async (mode) => {
const before = rows(profile);
const totalsBefore = totals(profile);
const data = await jsonBackup(mode);
await restore(mode, data);
expect(rows(profile)).toEqual(before);
expect(await splitLines(profile, "EPICERIE METRO")).toEqual(GROCERY_SPLIT);
expect(totals(profile)).toEqual(totalsBefore);
});
it.each(MODES)("%s, new profile: the same links, nothing hangs off « LOYER »", async (mode) => {
const before = rows(profile);
const totalsBefore = totals(profile);
const data = await jsonBackup(mode);
const fresh = use(open());
await restore(mode, data);
expect(rows(fresh)).toEqual(before);
expect(await splitLines(fresh, "LOYER")).toEqual([]);
expect(await splitLines(fresh, "EPICERIE METRO")).toEqual(GROCERY_SPLIT);
expect(totals(fresh)).toEqual(totalsBefore);
});
it("a split line listed before its parent still finds it: the lines without a parent go in first", async () => {
const before = rows(profile);
const data = await jsonBackup("transactions_only");
const reversed = { ...data, transactions: [...(data.transactions ?? [])].reverse() };
expect(reversed.transactions[0].parent_transaction_id).toBe(1);
const fresh = use(open());
await importTransactionsOnly(reversed, "backup.json");
expect(rows(fresh)).toEqual(before);
expect(await splitLines(fresh, "EPICERIE METRO")).toEqual(GROCERY_SPLIT);
});
it.each(["same profile", "new profile"])("a CSV export starts with an `id` column and restores its splits (%s)", async (target) => {
const before = rows(profile);
const csv = serializeTransactionsToCsv(await getExportTransactions());
expect(csv.split(/\r?\n/)[0].split(",")[0]).toBe("id");
const { transactions } = parseImportedCsv(csv);
const db = target === "same profile" ? profile : use(open());
await importTransactionsOnly({ transactions }, "export.csv");
expect(rows(db)).toEqual(before);
expect(await splitLines(db, "LOYER")).toEqual([]);
expect(await splitLines(db, "EPICERIE METRO")).toEqual(GROCERY_SPLIT);
});
it("a CSV exported before the fix that holds a split is refused, at the parse and at the head of the restore; the profile is intact", async () => {
const before = rows(profile);
const files = count(profile, "imported_files");
let refusal: unknown = null;
try {
parseImportedCsv(PRE_FIX_CSV);
} catch (e) {
refusal = e;
}
expectRefusal(refusal);
// What the parse of the time handed the restore: each line's number as its id.
const asReadThen: ExportTransaction[] = (await getExportTransactions()).map((tx, i) => ({ ...tx, id: i }));
await importTransactionsOnly({ transactions: asReadThen }, "old.csv").then(
() => expect.unreachable("the restore should have been refused"),
expectRefusal,
);
expect(rows(profile)).toEqual(before);
expect(count(profile, "imported_files")).toBe(files);
});
it.each(MODES)("%s: a backup whose ids repeat cannot place its split lines: refused before anything is deleted", async (mode) => {
const before = rows(profile);
const categories = count(profile, "categories");
const data = await jsonBackup(mode);
// Two rows share an id: no row keeps its own, and nothing tells a split line its parent.
const repeated = { ...data, transactions: (data.transactions ?? []).map((tx) => (tx.id === 3 ? { ...tx, id: 2 } : tx)) };
await restore(mode, repeated).then(() => expect.unreachable("the restore should have been refused"), expectRefusal);
expect(rows(profile)).toEqual(before);
expect(count(profile, "categories")).toBe(categories);
});
it.each(["same profile", "new profile"])("after a restore, a new split saves (%s)", async (target) => {
const data = await jsonBackup("transactions_only");
const db = target === "same profile" ? profile : use(open());
await importTransactionsOnly(data, "backup.json");
const rent = db.prepare("SELECT id FROM transactions WHERE description = 'LOYER'").get() as { id: number };
// Its two lines take the next ids, which no restored row holds.
await saveSplitAdjustment(rent.id, [{ category_id: ELECTRICITY, amount: -200, description: "LOYER" }]);
expect(await splitLines(db, "LOYER")).toEqual([
{ amount: -200, category_id: ELECTRICITY },
{ amount: 200, category_id: RENT },
]);
expect(await splitLines(db, "EPICERIE METRO")).toEqual(GROCERY_SPLIT);
});
it("« Rétablir la sauvegarde » of the categories migration restores a profile that holds a split", async () => {
const before = rows(profile);
const content = serializeToJson(
"transactions_with_categories",
await exportData("transactions_with_categories"),
"0.17.2",
);
invoke.mockImplementation(async (cmd: string) => {
if (cmd === "read_import_file") return content;
throw new Error(`unexpected invoke: ${cmd}`);
});
await restoreFromBackup("/tmp/backup.sref", null);
expect(rows(profile)).toEqual(before);
expect(await splitLines(profile, "EPICERIE METRO")).toEqual(GROCERY_SPLIT);
});
});

View file

@ -10,6 +10,7 @@ import {
RestoreError,
type RestorableMigrationJournal,
} from "../../services/categoryRestoreService";
import { SrefValidationError } from "../../services/dataExportService";
// -----------------------------------------------------------------------------
// Confirmation modal used by both the in-window banner and the permanent
@ -73,6 +74,8 @@ export default function CategoriesMigrationRestoreModal({
// Centralised error mapping — keeps the rendered messages i18n-driven.
function messageForError(e: unknown): string {
// A file the import boundary refuses says what is wrong with it (#518).
if (e instanceof SrefValidationError) return t(e.i18nKey, e.params);
if (e instanceof RestoreError) {
return t(
`settings.categoriesCard.restoreModal.errors.${e.code}`,

View file

@ -0,0 +1,99 @@
// CategoriesMigrationRestoreModal — what « Rétablir la sauvegarde » shows when
// the import boundary refuses the backup (#518).
//
// A static render runs no effect and clicks nothing. React's hooks come from
// the shared harness (src/test/hookHarness.ts, #409): the window runs as a
// plain function, its state survives from one call to the next, the test calls
// the onClick of its « Restore » button, then renders again to read the
// message. `createPortal` is the identity and `document` a stub: the window is
// a portal.
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest";
import type { ReactNode } from "react";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
vi.mock("react-dom", async (orig) => ({
...(await orig<typeof import("react-dom")>()),
createPortal: (children: ReactNode) => children,
}));
const { restoreFromBackup } = vi.hoisted(() => ({ restoreFromBackup: vi.fn() }));
vi.mock("../../services/categoryRestoreService", async (orig) => ({
...(await orig<typeof import("../../services/categoryRestoreService")>()),
backupFileExists: vi.fn(async () => true),
isFileEncrypted: vi.fn(async () => false),
pickBackupFile: vi.fn(async () => null),
restoreFromBackup,
}));
import { hookHarness } from "../../test/hookHarness";
import { find, texts } from "../../test/elementTree";
import CategoriesMigrationRestoreModal from "./CategoriesMigrationRestoreModal";
import { RestoreError, type RestorableMigrationJournal } from "../../services/categoryRestoreService";
import { SrefValidationError } from "../../services/dataExportService";
const harness = hookHarness();
const JOURNAL: RestorableMigrationJournal = {
timestamp: "2026-10-01T10:00:00Z",
backupPath: "/tmp/profile_avant-migration.sref",
outcome: {
insertedV1Count: 1,
updatedTransactionsCount: 2,
updatedBudgetsCount: 0,
updatedKeywordsCount: 0,
deletedV2Count: 0,
customPreservedCount: 0,
},
};
const PROPS = { journal: JOURNAL, onClose: vi.fn(), onRestored: vi.fn() };
/** One render of the mounted window. */
const render = () => harness.render(() => CategoriesMigrationRestoreModal(PROPS));
/** « Restore » on the confirmation screen, clicked as the user does; resolves once the restore has answered. */
async function confirm(): Promise<void> {
const [button] = find(
render(),
(el) => el.type === "button" && texts(el).includes("t(settings.categoriesCard.restoreModal.confirm)"),
);
await (button.props.onClick as () => Promise<void>)();
}
beforeAll(() => {
vi.stubGlobal("document", { body: {} });
});
afterAll(() => {
vi.unstubAllGlobals();
});
beforeEach(() => {
harness.clear();
restoreFromBackup.mockReset();
PROPS.onRestored.mockReset();
});
describe("CategoriesMigrationRestoreModal — a backup the import boundary refuses (#518)", () => {
it("shows the refusal's own translated text, neither parse_failed nor import_failed", async () => {
restoreFromBackup.mockRejectedValue(
new SrefValidationError("settings.dataManagement.import.errors.orphanSplitLines", {}),
);
await confirm();
const shown = texts(render());
expect(restoreFromBackup).toHaveBeenCalledWith(JOURNAL.backupPath, null);
expect(shown).toContain("t(settings.dataManagement.import.errors.orphanSplitLines[])");
expect(shown.join(" ")).not.toMatch(/parse_failed|import_failed/);
expect(PROPS.onRestored).not.toHaveBeenCalled();
});
it("witness: any other failure of the restore keeps its own message", async () => {
restoreFromBackup.mockRejectedValue(new RestoreError("import_failed", "FOREIGN KEY constraint failed"));
await confirm();
expect(texts(render()).join(" ")).toContain("t(settings.categoriesCard.restoreModal.errors.import_failed");
});
});

View file

@ -4,13 +4,15 @@ import { invoke } from "@tauri-apps/api/core";
import {
parseImportedJson,
parseImportedCsv,
importCategoriesOnly,
importTransactionsWithCategories,
importTransactionsOnly,
SrefValidationError,
type ExportEnvelope,
type ImportSummary,
} from "../services/dataExportService";
import {
importCategoriesOnly,
importTransactionsWithCategories,
importTransactionsOnly,
} from "../services/dataRestoreService";
type ImportStatus =
| "idle"

View file

@ -780,7 +780,8 @@
"errors": {
"unsupportedAmountMode": "This file cannot be imported: the source \"{{name}}\" was saved with an amount mode this version does not support ({{value}}). Nothing has been modified.",
"unsupportedSignConvention": "This file cannot be imported: the source \"{{name}}\" was saved with a sign convention this version does not support ({{value}}). Nothing has been modified.",
"invalidFormatRow": "This file cannot be imported: the import configuration of \"{{name}}\" is incomplete or damaged. Nothing has been modified."
"invalidFormatRow": "This file cannot be imported: the import configuration of \"{{name}}\" is incomplete or damaged. Nothing has been modified.",
"orphanSplitLines": "This file cannot be imported: some split lines cannot find their original transaction. Use a JSON export. Nothing has been modified."
}
}
},
@ -1364,7 +1365,8 @@
"The user guide can be printed or exported to PDF via the Print button",
"Logs persist for the session — they survive a page refresh",
"If you encounter an issue, copy the logs and attach them to your report",
"The app only contacts a server for updates, Maximus sign-in, feedback, the license (activation and check) and market prices. One request goes out on its own, at startup and when a key is entered: the license check, at most once every 24 hours for the same key and only when a key is stored. No telemetry. Links to the product page tell the site they come from the app and from which button, with nothing that identifies you."
"The app only contacts a server for updates, Maximus sign-in, feedback, the license (activation and check) and market prices. One request goes out on its own, at startup and when a key is entered: the license check, at most once every 24 hours for the same key and only when a key is stored. No telemetry. Links to the product page tell the site they come from the app and from which button, with nothing that identifies you.",
"A CSV export starts with an \"id\" column, the number of each transaction, which keeps the lines of a split with their original transaction. A CSV exported by an earlier version that holds splits is refused at import, and nothing is modified: use a JSON export"
]
},
"editions": {

View file

@ -780,7 +780,8 @@
"errors": {
"unsupportedAmountMode": "Ce fichier ne peut pas être importé : la source « {{name}} » a été enregistrée avec un mode de montant que cette version ne prend pas en charge ({{value}}). Rien n'a été modifié.",
"unsupportedSignConvention": "Ce fichier ne peut pas être importé : la source « {{name}} » a été enregistrée avec une convention de signe que cette version ne prend pas en charge ({{value}}). Rien n'a été modifié.",
"invalidFormatRow": "Ce fichier ne peut pas être importé : la configuration d'import de « {{name}} » est incomplète ou endommagée. Rien n'a été modifié."
"invalidFormatRow": "Ce fichier ne peut pas être importé : la configuration d'import de « {{name}} » est incomplète ou endommagée. Rien n'a été modifié.",
"orphanSplitLines": "Ce fichier ne peut pas être importé : des lignes de répartition ne retrouvent pas leur transaction d'origine. Utilisez un export JSON. Rien n'a été modifié."
}
}
},
@ -1364,7 +1365,8 @@
"Le guide d'utilisation peut être imprimé ou exporté en PDF via le bouton Imprimer",
"Les journaux persistent pendant la session — ils survivent à un rafraîchissement de la page",
"En cas de problème, copiez les journaux et joignez-les à votre signalement",
"L'application ne contacte un serveur que pour les mises à jour, la connexion Maximus, le feedback, la licence (activation et vérification) et les cours du marché. Une seule requête part d'elle-même, au démarrage et à la saisie d'une clé : la vérification de la licence, au plus une fois par 24 heures pour une même clé et seulement si une clé est enregistrée. Aucune télémétrie. Les liens vers la page produit indiquent au site qu'ils viennent de l'application et de quel bouton, sans rien qui vous identifie."
"L'application ne contacte un serveur que pour les mises à jour, la connexion Maximus, le feedback, la licence (activation et vérification) et les cours du marché. Une seule requête part d'elle-même, au démarrage et à la saisie d'une clé : la vérification de la licence, au plus une fois par 24 heures pour une même clé et seulement si une clé est enregistrée. Aucune télémétrie. Les liens vers la page produit indiquent au site qu'ils viennent de l'application et de quel bouton, sans rien qui vous identifie.",
"Un export CSV commence par une colonne « id », le numéro de chaque transaction, qui garde les lignes d'une répartition avec leur transaction d'origine. Un CSV exporté par une version antérieure qui contient des répartitions est refusé à l'import, sans rien modifier : utilisez un export JSON"
]
},
"editions": {

View file

@ -1,9 +1,22 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi, beforeEach } from "vitest";
// `restoreFromBackup` reads its file through `read_import_file`, then writes it
// back through dataRestoreService: both are fakes here, the parse is real.
const { invoke, importTransactionsWithCategories } = vi.hoisted(() => ({
invoke: vi.fn(),
importTransactionsWithCategories: vi.fn(),
}));
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("./dataRestoreService", () => ({ importTransactionsWithCategories }));
import {
isWithinBannerWindow,
restoreFromBackup,
RestoreError,
shouldShowBanner,
type RestorableMigrationJournal,
} from "./categoryRestoreService";
import { serializeToJson, SrefValidationError } from "./dataExportService";
const DAY = 24 * 60 * 60 * 1000;
@ -105,3 +118,81 @@ describe("shouldShowBanner", () => {
expect(shouldShowBanner(journal(), "", now)).toBe(true);
});
});
describe("restoreFromBackup lets a refusal of the file through as it is (#518)", () => {
const ORPHAN = "settings.dataManagement.import.errors.orphanSplitLines";
const PATH = "/tmp/backup.sref";
/** A backup of the categories migration, its transactions as given. */
const backup = (transactions: unknown[]) =>
serializeToJson(
"transactions_with_categories",
{ categories: [], suppliers: [], keywords: [], transactions: transactions as never },
"0.17.2",
);
/** A split line that names a row the backup does not hold. */
const ORPHAN_BACKUP = backup([
{
id: 2,
date: "2026-03-10",
description: "EPICERIE METRO",
amount: -50,
category_id: null,
category_name: null,
original_description: null,
notes: null,
is_manually_categorized: 0,
is_split: 1,
parent_transaction_id: 9,
},
]);
function reading(content: string) {
invoke.mockImplementation(async (cmd: string) => {
if (cmd === "read_import_file") return content;
throw new Error(`unexpected invoke: ${cmd}`);
});
}
/** What `restoreFromBackup` rejects with. */
async function failure(): Promise<unknown> {
return restoreFromBackup(PATH, null).then(
() => expect.unreachable("the restore should have failed"),
(e: unknown) => e,
);
}
beforeEach(() => {
invoke.mockReset();
importTransactionsWithCategories.mockReset();
});
it("a file the parse refuses reaches the window as the SrefValidationError it is, with nothing restored", async () => {
reading(ORPHAN_BACKUP);
const error = await failure();
expect(error).toBeInstanceOf(SrefValidationError);
expect((error as SrefValidationError).i18nKey).toBe(ORPHAN);
expect(importTransactionsWithCategories).not.toHaveBeenCalled();
});
it("a refusal raised at the head of the restore is not wrapped either", async () => {
reading(backup([]));
importTransactionsWithCategories.mockRejectedValue(new SrefValidationError(ORPHAN, {}));
const error = await failure();
expect(error).toBeInstanceOf(SrefValidationError);
expect((error as SrefValidationError).i18nKey).toBe(ORPHAN);
});
it("witness: any other failure is still a RestoreError, parse_failed or import_failed", async () => {
reading("not json");
const parse = await failure();
expect(parse).toBeInstanceOf(RestoreError);
expect((parse as RestoreError).code).toBe("parse_failed");
reading(backup([]));
importTransactionsWithCategories.mockRejectedValue(new Error("FOREIGN KEY constraint failed"));
const restore = await failure();
expect(restore).toBeInstanceOf(RestoreError);
expect((restore as RestoreError).code).toBe("import_failed");
});
});

View file

@ -1,8 +1,6 @@
import { invoke } from "@tauri-apps/api/core";
import {
parseImportedJson,
importTransactionsWithCategories,
} from "./dataExportService";
import { parseImportedJson, SrefValidationError } from "./dataExportService";
import { importTransactionsWithCategories } from "./dataRestoreService";
import { getPreference, setPreference } from "./userPreferenceService";
import type { LastMigrationJournal } from "./categoryMigrationService";
@ -199,7 +197,9 @@ export async function pickBackupFile(): Promise<string | null> {
* (SREF magic detected). Pass `null` for plaintext JSON
* backups or when the profile had no PIN.
*
* Throws a `RestoreError` on any failure; on success updates
* Throws a `RestoreError` on any failure, except a file the import boundary
* refuses: that one stays the `SrefValidationError` it is, whose message says
* what is wrong with the file (#518). On success updates
* `categories_schema_version=v2` and stamps `reverted_at` on the journal.
*/
export async function restoreFromBackup(
@ -236,6 +236,9 @@ export async function restoreFromBackup(
try {
envelope = parseImportedJson(content).envelope;
} catch (e) {
// A refusal of the import boundary keeps its own message: wrapped, the
// modal would show the generic parse failure instead (#518).
if (e instanceof SrefValidationError) throw e;
const message = e instanceof Error ? e.message : String(e);
throw new RestoreError("parse_failed", message);
}
@ -254,6 +257,8 @@ export async function restoreFromBackup(
try {
await importTransactionsWithCategories(envelope.data, filename);
} catch (e) {
// Same for a refusal raised at the head of the restore itself.
if (e instanceof SrefValidationError) throw e;
const message = e instanceof Error ? e.message : String(e);
throw new RestoreError("import_failed", message);
}

View file

@ -35,20 +35,26 @@ import { getDb, withTransaction } from "./db";
import {
getExportImportSources,
getExportImportTemplates,
importCategoriesOnly,
importTransactionsOnly,
importTransactionsWithCategories,
parseImportedCsv,
parseImportedJson,
serializeToJson,
serializeTransactionsToCsv,
validateImportedFormatRows,
validateImportedTransactionIds,
LEGACY_SREF_FORMAT_VERSION,
MAX_TRANSACTION_ID,
SREF_FORMAT_VERSION,
SrefValidationError,
type ExportEnvelope,
type ExportImportSource,
type ExportImportTemplate,
type ExportTransaction,
} from "./dataExportService";
import {
importCategoriesOnly,
importTransactionsOnly,
importTransactionsWithCategories,
} from "./dataRestoreService";
import { subscribeDataChanged } from "./dataEvents";
import { formatFromRow, FORMAT_FIELD_PAIRS } from "../utils/importFormat";
import type { Category } from "../shared/types";
@ -705,6 +711,11 @@ describe("the refusal messages are translated (#331)", () => {
}
});
it("carries the refusal of split lines that cannot find their parent in FR and EN (#518)", () => {
expect(fr.settings.dataManagement.import.errors.orphanSplitLines.length).toBeGreaterThan(0);
expect(en.settings.dataManagement.import.errors.orphanSplitLines.length).toBeGreaterThan(0);
});
it("keys every SrefValidationError to a string that exists", () => {
const cases: Array<[ExportImportSource, string]> = [
[{ ...SOURCE, amount_mode: "absolute_indicator" as never }, "unsupportedAmountMode"],
@ -728,6 +739,24 @@ describe("the refusal messages are translated (#331)", () => {
expect(typeof resolved).toBe("string");
}
}
// The refusal of #518 carries no source name, and resolves in both bundles.
let refusal: unknown = null;
try {
validateImportedTransactionIds([{ ...transactionFixture(2), parent_transaction_id: 9 }]);
} catch (e) {
refusal = e;
}
expect(refusal).toBeInstanceOf(SrefValidationError);
const key = (refusal as SrefValidationError).i18nKey;
expect(key).toBe("settings.dataManagement.import.errors.orphanSplitLines");
expect((refusal as SrefValidationError).params).toEqual({});
for (const bundle of [fr, en]) {
const resolved = key
.split(".")
.reduce<unknown>((node, part) => (node as Record<string, unknown>)[part], bundle as unknown);
expect(typeof resolved).toBe("string");
}
});
});
@ -880,3 +909,161 @@ describe("a committed restore is announced on the data channel (#396)", () => {
expect(seen).toEqual([]);
});
});
// ---------------------------------------------------------------------------
// 9. The rows keep their ids, a split line its parent (#518)
// ---------------------------------------------------------------------------
describe("the rows keep their ids, and a split line its parent (#518)", () => {
const ORPHAN = "settings.dataManagement.import.errors.orphanSplitLines";
/** A split parent, with its own id. */
const parent = (id: number): ExportTransaction => ({ ...transactionFixture(id), is_split: 1 });
/** A split line that names `parentId`, with its own id. */
const line = (id: number, parentId: unknown): ExportTransaction => ({
...transactionFixture(id),
is_split: 1,
parent_transaction_id: parentId as number,
});
/** The refusal `run` throws; fails when it throws nothing. */
function refusalOf(run: () => unknown): SrefValidationError {
try {
run();
} catch (e) {
expect(e).toBeInstanceOf(SrefValidationError);
return e as SrefValidationError;
}
return expect.unreachable("should have been refused");
}
it("keeps the ids of a file whose rows each bear a valid id of their own, the highest included", () => {
expect(
validateImportedTransactionIds([transactionFixture(1), transactionFixture(MAX_TRANSACTION_ID)])
).toEqual({ keepIds: true });
expect(validateImportedTransactionIds([parent(1), line(2, 1), line(3, 1)])).toEqual({ keepIds: true });
});
it.each([
["0", 0],
["a negative id", -1],
["one past the highest", MAX_TRANSACTION_ID + 1],
["an id past 2^53, where JSON.parse rounds", 2 ** 53 + 2],
["a fraction", 1.5],
["a string", "2"],
["null", null],
["NaN, a CSV line without an id", NaN],
])("gives no row its own id when one bears %s", (_label, id) => {
const rows = [transactionFixture(1), { ...transactionFixture(2), id: id as number }];
expect(validateImportedTransactionIds(rows)).toEqual({ keepIds: false });
});
it("gives no row its own id when two bear the same", () => {
expect(validateImportedTransactionIds([transactionFixture(1), transactionFixture(1)])).toEqual({
keepIds: false,
});
});
it.each<[string, ExportTransaction[]]>([
["names no row of the file", [parent(1), line(2, 9)]],
["is its own parent", [transactionFixture(1), line(2, 2)]],
["names another split line", [parent(1), line(2, 1), line(3, 2)]],
["names its parent in a file whose ids repeat", [parent(1), line(2, 1), transactionFixture(2)]],
[
"names its parent in a file without ids, as a CSV exported before #518",
[parent(1), line(2, 1)].map((tx) => ({ ...tx, id: NaN })),
],
["names its parent by 0", [parent(1), line(2, 0)]],
["names its parent by a fraction", [parent(1), line(2, 1.5)]],
["names its parent by a string", [parent(1), line(2, "1")]],
])("refuses a file whose split line %s", (_label, rows) => {
expect(refusalOf(() => validateImportedTransactionIds(rows)).i18nKey).toBe(ORPHAN);
});
it("restores a file whose ids repeat, when it holds no split line, with the ids SQLite gives", async () => {
await importTransactionsOnly(
envelopeData({ transactions: [transactionFixture(5), transactionFixture(5)] }),
"backup.json"
);
const inserts = db.execute.mock.calls
.map(([sql]) => sql as string)
.filter((sql) => sql.includes("INSERT INTO transactions"));
expect(inserts).toHaveLength(2);
for (const sql of inserts) expect(sql).toContain("INSERT INTO transactions (date,");
});
it("restores the ids it keeps, the rows without a parent first, each pass in the order of the file", async () => {
await importTransactionsOnly(
envelopeData({ transactions: [line(3, 1), parent(1), line(2, 1)] }),
"backup.json"
);
expect(db.tables.transactions.map((t) => [t.id, t.parent_transaction_id])).toEqual([
[1, null],
[3, 1],
[2, 1],
]);
});
it("refuses a JSON backup at PARSE time, so the confirmation never opens", () => {
const json = serializeToJson(
"transactions_only",
envelopeData({ transactions: [transactionFixture(1), line(2, 9)] }),
"0.17.2"
);
expect(refusalOf(() => parseImportedJson(json)).i18nKey).toBe(ORPHAN);
});
it("refuses a CSV at PARSE time too", () => {
const csv =
"id,date,description,amount,is_split,parent_transaction_id\n" +
"1,2026-03-10,a,-10,1,\n" +
"2,2026-03-10,b,-4,1,9\n";
expect(refusalOf(() => parseImportedCsv(csv)).i18nKey).toBe(ORPHAN);
});
it.each([
[
"transactions with categories",
(data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json"),
],
["transactions only", (data: ExportEnvelope["data"]) => importTransactionsOnly(data, "backup.json")],
] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => {
db.seed("transactions", [{ description: "existing tx" }]);
await expect(restore(envelopeData({ transactions: [line(2, 9)] }))).rejects.toBeInstanceOf(
SrefValidationError
);
expect(db.log).toEqual([]);
expect(db.tables.transactions).toHaveLength(1);
});
it("writes the `id` column first in a CSV export", () => {
const [header, row] = serializeTransactionsToCsv([transactionFixture(7)]).split(/\r?\n/);
expect(header.split(",")[0]).toBe("id");
expect(row.split(",")[0]).toBe("7");
});
it("reads the `id` column of a CSV as digits only: « 12abc » is not 12, « 1.5 » is not 1", () => {
const csv =
"id,date,description,amount\n" +
"12abc,2026-01-01,a,-1\n" +
"1.5,2026-01-02,b,-2\n" +
"007,2026-01-03,c,-3\n" +
",2026-01-04,d,-4\n";
expect(parseImportedCsv(csv).transactions.map((t) => t.id)).toEqual([NaN, NaN, 7, NaN]);
});
it("never takes a line's number for its id: a CSV without an `id` column keeps no id of its own", () => {
const csv = "date,description,amount\n2026-01-01,a,-1\n2026-01-02,b,-2\n";
const { transactions } = parseImportedCsv(csv);
expect(transactions.map((t) => t.id)).toEqual([NaN, NaN]);
expect(validateImportedTransactionIds(transactions)).toEqual({ keepIds: false });
});
it("reads the parent of a CSV split line as digits only too: « 1abc » names no row", () => {
const csv =
"id,date,description,amount,is_split,parent_transaction_id\n" +
"1,2026-03-10,a,-10,1,\n" +
"2,2026-03-10,b,-4,1,1abc\n";
expect(refusalOf(() => parseImportedCsv(csv)).i18nKey).toBe(ORPHAN);
});
});

View file

@ -1,6 +1,4 @@
import type Database from "@tauri-apps/plugin-sql";
import { getDb, withTransaction } from "./db";
import { notifyDataChanged } from "./dataEvents";
import { getDb } from "./db";
import Papa from "papaparse";
import { toSqlFlag } from "../utils/sqlFlag";
import type {
@ -58,6 +56,12 @@ export interface ExportEnvelope {
}
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;
@ -114,20 +118,22 @@ export interface ImportSummary {
formatVersion: number;
}
/** i18n keys for the ways an imported configuration can be refused. */
/** 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.invalidFormatRow"
| "settings.dataManagement.import.errors.orphanSplitLines";
/**
* Thrown when a backup carries a configuration this build cannot store.
* 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 the
* offending source name so the message can name what to fix.
* 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;
@ -231,6 +237,8 @@ export function serializeTransactionsToCsv(
): 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,
@ -290,6 +298,80 @@ export function validateImportedFormatRows(
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;
@ -318,12 +400,14 @@ export function parseImportedJson(content: string): {
throw new Error(`Unknown export type: ${envelope.export_type}`);
}
// Refuse an unreadable configuration while the file is only being LOOKED at:
// the confirmation dialog never opens, so nothing is deleted.
// 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,
@ -340,6 +424,16 @@ export function parseImportedJson(content: string): {
};
}
/**
* 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;
@ -353,8 +447,10 @@ export function parseImportedCsv(content: string): {
throw new Error(`CSV parse error: ${result.errors[0].message}`);
}
const transactions: ExportTransaction[] = result.data.map((row, i) => ({
id: i,
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,
@ -365,11 +461,16 @@ export function parseImportedCsv(content: string): {
// 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
? parseInt(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: {
@ -385,347 +486,3 @@ export function parseImportedCsv(content: string): {
},
};
}
// --- 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).
*/
async function runRestore(
body: (db: Database) => Promise<void>
): Promise<void> {
await withTransaction(async (db) => {
await db.execute("BEGIN");
let open = true;
try {
await body(db);
await db.execute("COMMIT");
open = false;
} 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();
}
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,
cat.parent_id ?? null,
cat.color ?? null,
cat.icon ?? null,
cat.type,
cat.is_active ? 1 : 0,
cat.is_inputable ? 1 : 0,
cat.sort_order,
]
);
}
}
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.
*/
async function attachTransactions(
db: Database,
transactions: ExportTransaction[] | undefined,
filename: string
): Promise<void> {
if (!transactions || transactions.length === 0) return;
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;
for (const tx of transactions) {
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)`,
[
tx.date,
tx.description,
tx.amount,
tx.category_id,
tx.original_description,
tx.notes,
// A JSON backup from the time of #390 carries the text "true".
toSqlFlag(tx.is_manually_categorized),
tx.is_split,
tx.parent_transaction_id,
sourceId,
fileId,
]
);
}
}
export async function importCategoriesOnly(
data: ExportEnvelope["data"]
): Promise<void> {
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);
});
}
export async function importTransactionsWithCategories(
data: ExportEnvelope["data"],
filename: string
): Promise<void> {
validateImportedFormatRows(data.import_sources, data.import_config_templates);
return runRestore(async (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);
await attachTransactions(db, data.transactions, filename);
});
}
export async function importTransactionsOnly(
data: ExportEnvelope["data"],
filename: string
): Promise<void> {
validateImportedFormatRows(data.import_sources, data.import_config_templates);
return runRestore(async (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);
await attachTransactions(db, data.transactions, filename);
});
}

View file

@ -0,0 +1,389 @@
import type Database from "@tauri-apps/plugin-sql";
import { withTransaction } from "./db";
import { notifyDataChanged } from "./dataEvents";
import { toSqlFlag } from "../utils/sqlFlag";
import type { Category, Keyword, Supplier } from "../shared/types";
import {
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.
// --- 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).
*/
async function runRestore(
body: (db: Database) => Promise<void>
): Promise<void> {
await withTransaction(async (db) => {
await db.execute("BEGIN");
let open = true;
try {
await body(db);
await db.execute("COMMIT");
open = false;
} 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();
}
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,
cat.parent_id ?? null,
cat.color ?? null,
cat.icon ?? null,
cat.type,
cat.is_active ? 1 : 0,
cat.is_inputable ? 1 : 0,
cat.sort_order,
]
);
}
}
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.
*/
async function attachTransactions(
db: Database,
transactions: ExportTransaction[] | undefined,
filename: string,
keepIds: boolean
): Promise<void> {
if (!transactions || transactions.length === 0) return;
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),
];
for (const tx of ordered) {
const values = [
tx.date,
tx.description,
tx.amount,
tx.category_id,
tx.original_description,
tx.notes,
// A JSON backup from the time of #390 carries the text "true".
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
);
}
}
}
export async function importCategoriesOnly(
data: ExportEnvelope["data"]
): Promise<void> {
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);
});
}
export async function importTransactionsWithCategories(
data: ExportEnvelope["data"],
filename: string
): Promise<void> {
validateImportedFormatRows(data.import_sources, data.import_config_templates);
const { keepIds } = validateImportedTransactionIds(data.transactions);
return runRestore(async (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);
await attachTransactions(db, data.transactions, filename, keepIds);
});
}
export async function importTransactionsOnly(
data: ExportEnvelope["data"],
filename: string
): Promise<void> {
validateImportedFormatRows(data.import_sources, data.import_config_templates);
const { keepIds } = validateImportedTransactionIds(data.transactions);
return runRestore(async (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);
await attachTransactions(db, data.transactions, filename, keepIds);
});
}