diff --git a/CHANGELOG.fr.md b/CHANGELOG.fr.md
index ec94d9b..448756b 100644
--- a/CHANGELOG.fr.md
+++ b/CHANGELOG.fr.md
@@ -16,6 +16,7 @@
- L'écran de déverrouillage qui s'ouvre dans une fenêtre en édition Gratuite, depuis un profil verrouillé du sélecteur de profil ou depuis le bouton Répartition de la page Transactions, se ferme désormais avec Échap. Les lecteurs d'écran reconnaissent désormais la fenêtre du sélecteur de profil comme une boîte de dialogue, nommée d'après l'édition requise (par exemple « Fonctionnalité Base »), avec un bouton « Fermer », comme celle du bouton Répartition. Ces fenêtres, et la fenêtre « Gérer les profils », s'ouvrent désormais avec le focus sur leur bouton « Fermer », gardent Tab et Maj+Tab à l'intérieur et rendent le focus quand elles se ferment : au bouton du sélecteur de profil pour les fenêtres ouvertes depuis son menu, sinon au bouton qui les a ouvertes. La fenêtre « Gérer les profils » se ferme aussi avec Échap, sauf pendant l'enregistrement d'un profil ; les lecteurs d'écran la reconnaissent comme une boîte de dialogue nommée d'après son titre, avec un bouton « Fermer », et le bouton du sélecteur de profil dit désormais si sa liste est ouverte. Dans « Gérer les profils », le focus revient sur « Créer un profil » après « Annuler » ou après l'enregistrement des modifications d'un profil (#451, #494).
- Rapports : les rapports s'ouvrent désormais sur « Cette année », du 1er janvier à aujourd'hui, avec son bouton allumé, au lieu de « Personnalisé » sur toute l'année civile, mois à venir compris ; le tableau de bord ne change pas. L'aide de la page Rapports dit désormais que Tendances montre vos revenus et dépenses mois par mois sur la période choisie, et sa carte Tendances affiche « Où vous allez, mois par mois », au lieu de « sur 12 mois » : Tendances suit le sélecteur de période. Sur les Comparables, dont le mois de référence suit la fin de la période, « Ce mois », « 3 mois », « 6 mois » et « 12 mois » finissent aujourd'hui comme « Cette année » : choisis juste après l'ouverture, ils ne déplacent plus le mois de référence vers le mois en cours ; la liste « Mois de référence » le fait toujours (#479).
- Les liens vers la page produit ouverts depuis l'application portent une étiquette qui indique au site de quel bouton ils viennent, sans aucune donnée personnelle.
+- Export/import de données : les exports avec catégories (« Transactions avec catégories » et « Catégories uniquement »), et la sauvegarde prise avant une migration des catégories, portent désormais le budget, les modèles de budget et les ajustements. Une restauration met les lignes de budget et les ajustements du fichier à la place de ceux du profil ; un modèle de budget du fichier remplace celui du même nom, et un modèle créé depuis la sauvegarde garde ses lignes dont la catégorie revient. La confirmation les nomme désormais parmi ce qui est supprimé et compte ce que le fichier rapporte. Une sauvegarde écrite par une version antérieure ne contient pas de budget : les lignes actuelles dont la catégorie revient sont gardées, les autres supprimées, et les deux confirmations le disent. Un fichier écrit par une version plus récente de Simpl'Résultat, ou dont des lignes de budget ne peuvent pas être réécrites, est refusé avec un message, sans rien modifier. La confirmation de « Réinitialiser » (page Catégories) dit désormais qu'elle efface le budget, les modèles de budget et les ajustements (#520).
### Corrigé
@@ -31,6 +32,7 @@
- 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).
- Export/import de données : restaurer une sauvegarde ne s'arrête plus sur une erreur, sans rien modifier, dans trois cas. Un profil dont une transaction est liée à un compte du Bilan (« Lier transferts ») ne pouvait plus du tout restaurer ses transactions, dans aucun des deux modes ni par « Rétablir la sauvegarde » : chaque transfert dont la transaction revient avec le même numéro, la même date, le même montant et la même description est désormais gardé tel quel, si bien que les rendements du Bilan ne changent pas, et les autres sont déliés ; la confirmation dit combien le seront avant que rien ne soit remplacé, et le message de réussite combien l'ont été. Une transaction dont la catégorie n'existe plus dans le profil (en « Transactions uniquement » après « Réinitialiser », par exemple) revient désormais sans catégorie, prête pour « Auto-catégoriser », et les journaux en donnent le nombre. Une catégorie rangée sous une catégorie plus récente, ou deux catégories rangées l'une sous l'autre, ne bloquent plus une restauration avec catégories, et reviennent à leur place. Un fichier dont des catégories, mots-clés ou fournisseurs renvoient à une catégorie absente du fichier est refusé avec un message, sans rien modifier. « Rétablir la sauvegarde » lit maintenant le fichier (après le NIP s'il est chiffré) avant une seconde confirmation, puis affiche « Sauvegarde rétablie » et recharge l'application au clic sur « Fermer » (#521).
+- Export/import de données : restaurer une sauvegarde avec ses catégories (« Transactions avec catégories », « Catégories uniquement », et « Rétablir la sauvegarde » après une migration des catégories) ne laisse plus vides, sans un mot, le budget, les modèles de budget et les ajustements : leurs lignes partaient avec les catégories que la restauration remplaçait, et la sauvegarde n'en contenait aucune. Elles reviennent désormais telles quelles, dans le même profil comme dans un profil neuf, et « Rétablir la sauvegarde » rend exactement le budget des anciennes catégories. Les catégories standard restaurées ainsi retrouvent leur nom anglais dans l'interface anglaise (#520).
### Sécurité
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3960cd7..97be673 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@
- The unlock screen that opens in a window on the Free edition, from a locked profile of the profile switcher or from the Split button of the Transactions page, now closes with Escape. Screen readers now identify the profile switcher's window as a dialog, named after the edition it needs (such as “Base feature”), with a “Close” button, like the Split button's. These windows, and the “Manage Profiles” window, now open with the focus on their “Close” button, keep Tab and Shift+Tab inside them, and give the focus back when they close: to the profile switcher's button for the windows opened from its menu, otherwise to the button that opened them. The “Manage Profiles” window also closes with Escape, except while a profile is being saved; screen readers identify it as a dialog named after its title, with a “Close” button, and the profile switcher's button now tells whether its list is open. In “Manage Profiles”, the focus goes back to “Create Profile” after “Cancel” or after saving a profile's changes (#451, #494).
- Reports: the reports now open on “This year”, from January 1st to today, with its button lit, instead of “Custom” over the whole calendar year, months to come included; the Dashboard does not change. The help of the Reports page now says that Trends shows your income and expenses month by month over the selected period, and its Trends card reads “Where you're heading, month by month”, instead of “over 12 months”: Trends follows the period selector. On Compare, whose reference month follows the end of the period, “This month”, “3 months”, “6 months” and “12 months” end today like “This year”: chosen right after opening, they no longer move the reference month to the current month; the “Reference month” list still does (#479).
- Product page links opened from the app carry a label that tells the site which button they come from, with no personal data.
+- Data export/import: exports with categories (“Transactions with categories” and “Categories only”), and the backup taken before a category migration, now carry the budget, the budget templates and the adjustments. A restore puts the budget lines and the adjustments of the file in place of those of the profile; a budget template of the file replaces the one of the same name, and a template created since the backup keeps its lines whose category comes back. The confirmation now names them among what is deleted and counts what the file brings back. A backup written by an earlier version holds no budget: the current lines whose category comes back are kept, the others deleted, and both confirmations say so. A file written by a newer version of Simpl'Résultat, or whose budget lines cannot be written back, is refused with a message, nothing modified. The confirmation of “Re-initialize” (Categories page) now says that it erases the budget, the budget templates and the adjustments (#520).
### Fixed
@@ -31,6 +32,7 @@
- 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).
- Data export/import: restoring a backup no longer stops on an error, changing nothing, in three cases. A profile with a transaction linked to a Balance sheet account (“Link transfers”) could not restore its transactions at all, in either mode or with “Restore the backup”: each transfer whose transaction comes back with the same number, date, amount and description is now kept as it was, so the returns of the Balance sheet do not change, and the others are unlinked; the confirmation says how many will be before anything is replaced, and the success message how many were. A transaction whose category no longer exists in the profile (with “Transactions only” after “Re-initialize”, for instance) now comes back without a category, ready for “Auto-categorize”, and the logs give their number. A category placed under a newer one, or two categories each placed under the other, no longer blocks a restore with categories, and comes back in its place. A file whose categories, keywords or suppliers refer to a category missing from it is refused with a message, nothing modified. “Restore the backup” now reads the file (after the PIN when it is encrypted) before a second confirmation, then shows “Backup restored” and reloads the app when you click “Close” (#521).
+- Data export/import: restoring a backup with its categories (“Transactions with categories”, “Categories only”, and “Restore the backup” after a category migration) no longer leaves the budget, the budget templates and the adjustments empty, without a word: their lines went with the categories the restore replaced, and the backup held none. They now come back as they were, in the same profile as in a new one, and “Restore the backup” gives back the budget of the former categories exactly. The standard categories restored this way show their English names again in the English interface (#520).
### Security
diff --git a/STATE.md b/STATE.md
index 120cdcf..fda8308 100644
--- a/STATE.md
+++ b/STATE.md
@@ -43,7 +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, #521) : PR #531 et #532.
+ - Restauration d'une sauvegarde (#518, #521, #520) : PR #531, #532 et #533.
- **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.
diff --git a/docs/adr/0010-fk-restrict-balance-transfers.md b/docs/adr/0010-fk-restrict-balance-transfers.md
index 8d1bd41..5c4571a 100644
--- a/docs/adr/0010-fk-restrict-balance-transfers.md
+++ b/docs/adr/0010-fk-restrict-balance-transfers.md
@@ -4,7 +4,7 @@
- Date: 2026-04-25
- Milestone: `overnight-2026-04-26-bilan` (Issues #138 → #145)
-> **Amendement du 2026-11-04 (#521)** — `ON DELETE RESTRICT` reste en place ; la restauration d'une sauvegarde, qui efface puis réinsère toutes les transactions, le traite elle-même. La contrainte agit tout de suite (`PRAGMA defer_foreign_keys` ne la retarde pas, `PRAGMA foreign_keys = OFF` n'a aucun effet après `BEGIN`), et la sauvegarde ne porte pas les transferts : un seul transfert faisait échouer toute restauration de transactions sur « FOREIGN KEY constraint failed », dans les deux modes comme par « Rétablir la sauvegarde ». Dans la transaction de restauration (`src/services/dataRestoreService.ts`), chaque transfert est lu avec la date, le montant et la description de sa transaction, puis la table est vidée avant `DELETE FROM transactions` ; une fois les transactions réinsérées, les transferts dont la transaction revient avec le même identifiant, la même date, le même montant et la même description sont réinsérés tels quels (identifiant, compte, sens, notes, date de création), et les autres sont déliés. L'identifiant seul ne suffit pas : le fichier d'un autre profil, ou une sauvegarde plus ancienne qu'une restauration, peut le donner à une autre transaction ; la catégorie n'entre pas dans la règle, un reclassement ne changeant pas le flux d'argent. Un rendement déjà calculé reste ainsi reproductible tant que ses transactions reviennent à l'identique. La perte des autres transferts, définitive au `COMMIT`, est annoncée : la confirmation dit combien seront déliés avant toute suppression (`previewUnlinkedTransfers`, même règle, lue hors transaction), et le message de réussite combien l'ont été (`RestoreOutcome.unlinkedTransfers`). Décision de Max du 2026-10-29 (`/analyze 520 521`) ; l'action « Délier » que promet la section « UX correspondante » n'a toujours aucun écran (#522).
+> **Amendement du 2026-11-04 (#521)** — `ON DELETE RESTRICT` reste en place ; la restauration d'une sauvegarde, qui efface puis réinsère toutes les transactions, le traite elle-même. La contrainte agit tout de suite (`PRAGMA defer_foreign_keys` ne la retarde pas, `PRAGMA foreign_keys = OFF` n'a aucun effet après `BEGIN`), et la sauvegarde ne porte pas les transferts : un seul transfert faisait échouer toute restauration de transactions sur « FOREIGN KEY constraint failed », dans les deux modes comme par « Rétablir la sauvegarde ». Dans la transaction de restauration (`src/services/dataRestoreService.ts`), chaque transfert est lu avec la date, le montant et la description de sa transaction, puis la table est vidée avant `DELETE FROM transactions` ; une fois les transactions réinsérées, les transferts dont la transaction revient avec le même identifiant, la même date, le même montant et la même description sont réinsérés tels quels (identifiant, compte, sens, notes, date de création), et les autres sont déliés. L'identifiant seul ne suffit pas : le fichier d'un autre profil, ou une sauvegarde plus ancienne qu'une restauration, peut le donner à une autre transaction ; la catégorie n'entre pas dans la règle, un reclassement ne changeant pas le flux d'argent. Un rendement déjà calculé reste ainsi reproductible tant que ses transactions reviennent à l'identique. La perte des autres transferts, définitive au `COMMIT`, est annoncée : la confirmation dit combien seront déliés avant toute suppression (`previewUnlinkedTransfers`, même règle, lue hors transaction), et le message de réussite combien l'ont été (`RestoreOutcome.unlinkedTransfers`). Décision de Max du 2026-10-29 (`/analyze 520 521`) ; l'action « Délier » que promet la section « UX correspondante » n'a toujours aucun écran (#522). Ce que porte une sauvegarde et la règle d'ensemble de sa restauration (identifiants, transferts, catégories, budget) sont dans l'[ADR 0025](0025-contenu-restauration-sauvegarde-sref.md).
## Context
@@ -84,4 +84,4 @@ L'asymétrie est délibérée :
- Implémentation : `src-tauri/src/database/balance_schema.sql` (FK definition), `src/services/transactionService.ts` (`TransactionLinkedToBalanceError` mapping) ; restauration d'une sauvegarde (amendement #521) : `src/services/dataRestoreService.ts`
- Tests : `src/services/transactionService.test.ts` (mapping FK error → typed error), `src/__integration__/balance-flow.test.ts` (lien + tentative de suppression bloquée), `src/__integration__/restore.test.ts` (restauration sous clés étrangères actives, transferts gardés ou déliés, #521)
- Spec : [`spec-decisions-bilan.md`](../../spec-decisions-bilan.md) — décision "FK `balance_account_transfers.transaction_id` : `ON DELETE RESTRICT` + UI force unlink avec message clair"
-- ADR liée : [0008 — Modified Dietz pour le calcul du rendement](0008-modified-dietz-pour-rendement.md)
+- ADR liées : [0008 — Modified Dietz pour le calcul du rendement](0008-modified-dietz-pour-rendement.md) ; [0025 — Contenu et restauration d'une sauvegarde SREF](0025-contenu-restauration-sauvegarde-sref.md) (amendement #521)
diff --git a/docs/adr/0025-contenu-restauration-sauvegarde-sref.md b/docs/adr/0025-contenu-restauration-sauvegarde-sref.md
new file mode 100644
index 0000000..f299188
--- /dev/null
+++ b/docs/adr/0025-contenu-restauration-sauvegarde-sref.md
@@ -0,0 +1,108 @@
+# ADR 0025 — Contenu et restauration d'une sauvegarde SREF
+
+- Status: **Accepted**
+- Date: 2026-11-04
+- Issues: #518, #521 et #520 (milestone `planned-2026-11-04-restauration-sauvegarde`), une pile mergée d'un bloc (décision de Max du 2026-10-29)
+- S'appuie sur l'[ADR 0004](0004-aes-256-gcm-encryption.md) (conteneur chiffré), l'[ADR 0010](0010-fk-restrict-balance-transfers.md) (transferts du Bilan, amendé par #521), l'[ADR 0019](0019-format-import-persiste.md) (format d'import) et l'[ADR 0022](0022-canal-evenements-donnees.md) (notification après le `COMMIT`) ; prolonge #331 (format 2, restauration en une transaction)
+
+## Contexte
+
+Une sauvegarde SREF est une enveloppe JSON (`export_type`, `app_version`, `format_version`, `exported_at`, `data`), chiffrée ou non par le conteneur de l'ADR 0004. « Exporter » (Paramètres → Données) l'écrit dans l'un des trois modes ; la migration des catégories vers la structure standard en écrit une, vérifiée, avant de rien modifier (`createPreMigrationBackup`), que « Rétablir la sauvegarde » restaure. Chaque restauration efface ce que son mode remplace, puis réinsère les lignes du fichier, dans une seule transaction (`runRestore`, `src/services/dataRestoreService.ts`), et ne notifie qu'après le `COMMIT`.
+
+Effacer puis réinsérer heurte les clés étrangères, et trois familles de défauts en venaient, toutes présentes dans la v0.17.2 :
+
+- les identifiants : les transactions revenaient sans leur identifiant, et une ligne de répartition, qui nomme son parent par le sien, visait une ligne disparue (restauration annulée) ou une autre transaction (#518) ;
+- trois clés qui arrêtaient tout sur « FOREIGN KEY constraint failed » : le transfert du Bilan (`ON DELETE RESTRICT`), la catégorie d'une transaction absente du profil, le parent d'une catégorie plus récente (#521) ;
+- une cascade qui réussissait en silence : `budget_entries`, `budget_template_entries` et `adjustment_entries` nomment une catégorie `ON DELETE CASCADE`, le `DELETE FROM categories` des deux modes qui portent les catégories les vidait, et la sauvegarde n'en portait aucune ligne (#520). « Rétablir la sauvegarde » ne rendait pas le budget d'avant la migration, que rien d'autre ne garde : le journal `last_categories_migration` n'a aucune correspondance entre les deux structures.
+
+Cet ADR fixe ce que porte une sauvegarde et la règle de sa restauration, pour les trois issues.
+
+## Décision
+
+### 1. Ce que porte une sauvegarde (format 3)
+
+`SREF_FORMAT_VERSION = 3`. Une seule fonction rassemble les tableaux d'un mode, `collectExportData(mode)` (`dataExportService.ts`), pour « Exporter » (`useDataExport`) comme pour la sauvegarde d'avant migration (mode « Transactions avec catégories ») : les deux ne peuvent plus porter des choses différentes.
+
+| Mode | Tableaux de `data` |
+|---|---|
+| Transactions avec catégories | `categories`, `suppliers`, `keywords`, `transactions`, `import_sources`, `import_config_templates`, `budget_entries`, `budget_templates`, `adjustments` |
+| Catégories uniquement | `categories`, `suppliers`, `keywords`, `budget_entries`, `budget_templates`, `adjustments` |
+| Transactions uniquement | `transactions`, `import_sources`, `import_config_templates` ; l'export CSV, les seules transactions, une colonne `id` en tête |
+
+Le budget voyage avec les catégories : leurs deux modes les effacent, et chaque ligne de budget, de modèle ou d'ajustement en nomme une. « Transactions uniquement » ne touche aucune catégorie, et le budget du profil y reste tel quel.
+
+Chaque ligne y est désignée par ce que la restauration sait retrouver : les catégories, fournisseurs, mots-clés et transactions par leur identifiant ; les sources et modèles d'import par leur nom (#331) ; une ligne de budget par sa catégorie, son année et son mois, la clé `UNIQUE` de la table ; un modèle de budget par son nom, `UNIQUE`, avec ses lignes (catégorie, montant) ; un ajustement avec ses lignes (catégorie, montant, description), sans clé, son nom n'étant pas unique.
+
+Restent hors de la sauvegarde : les transferts du Bilan et tout le Bilan, les préférences, la source et le fournisseur de chaque transaction (`source_id`, `supplier_id`), l'historique d'import.
+
+### 2. Les identifiants (#518)
+
+Les transactions reviennent avec leur identifiant exporté quand chacune porte un entier sûr de 1 à 2 147 483 647 qu'aucune autre ne porte (`validateImportedTransactionIds`, qui rend `{ keepIds }`) ; sinon SQLite les attribue, ce que seul un fichier sans ligne de répartition peut se permettre. Les lignes sans parent passent avant les lignes de répartition. Un fichier dont une ligne de répartition ne nomme pas une ligne du fichier sans parent est refusé (`orphanSplitLines`) : un CSV exporté avant #518, sans colonne `id`, qui contient des répartitions, un fichier aux identifiants en double qui en contient, une ligne qui est son propre parent.
+
+### 3. Les transferts du Bilan (#521)
+
+La sauvegarde ne les porte pas. Dans la transaction de restauration, chaque transfert est lu avec la date, le montant et la description de sa transaction, puis retiré avant `DELETE FROM transactions` ; ceux dont la transaction revient avec le même identifiant, la même date, le même montant et la même description sont remis tels quels, les autres déliés. La confirmation annonce combien le seront (`previewUnlinkedTransfers`, même règle, lue hors transaction), le message de réussite combien l'ont été. Détail dans l'amendement de l'ADR 0010.
+
+### 4. Les catégories (#521, #520)
+
+Elles reviennent avec leur identifiant, sans parent, puis un second passage pose les parents : un ordre quelconque et une boucle passent. Une transaction dont la catégorie manque au profil revient sans catégorie, drapeau manuel à 0, pour « Auto-catégoriser ». Chaque catégorie revient avec son `i18n_key`, que l'export portait déjà (`SELECT *`) : sans lui, les catégories standard revenaient sous leur nom français dans l'interface anglaise (#520).
+
+### 5. Le budget d'un fichier de format 3 (#520)
+
+Avant `DELETE FROM categories`, dans les deux formats, par un seul chemin et par le handle de la restauration, les lignes de budget, de modèle et d'ajustement du profil sont lues puis retirées (`takeBudget`). Une fois les catégories du fichier en place (`restoreBudget`) :
+
+- les lignes de budget et les ajustements du fichier, avec leurs lignes, remplacent ceux du profil : une restauration rend l'état de la sauvegarde ;
+- chaque modèle du fichier est inséré, ou mis à jour par son nom (`ON CONFLICT(name) DO UPDATE`), et prend les lignes du fichier ;
+- un modèle absent du fichier garde son en-tête et ses lignes dont la catégorie revient, comme #331 garde les modèles d'import.
+
+### 6. Le repli d'un fichier de format 1 ou 2 (#520)
+
+Toutes les sauvegardes écrites avant le format 3, celles d'avant migration comprises, ne portent aucun budget. Les lignes retirées par `takeBudget` reviennent alors telles quelles (mêmes identifiants, mêmes dates) quand leur catégorie revient, et les autres sont supprimées ; les en-têtes des modèles et des ajustements, qui ne nomment aucune catégorie, restent. Les deux confirmations le disent avant toute suppression : la confirmation de la carte et la seconde confirmation de « Rétablir la sauvegarde » (`legacyBudgetNote`).
+
+**Limite acceptée** : le repli se fie au seul identifiant de la catégorie. Après une migration des catégories, ou avec le fichier d'un autre profil, un identifiant peut revenir porté par une autre catégorie, et une ligne s'y rattacher. Contrôler aussi le nom a été écarté : une catégorie renommée depuis la sauvegarde perdrait ses lignes. Après une migration, les lignes que la migration a réécrites sur les catégories standard (identifiants 1000 et plus) ne reviennent pas avec une sauvegarde de l'ancienne structure ; les lignes d'ajustement, que la migration laisse sur les anciennes catégories, reviennent.
+
+### 7. Le format est donné, jamais deviné
+
+`importTransactionsWithCategories(data, filename, formatVersion)` et `importCategoriesOnly(data, formatVersion)` reçoivent le format que déclare le fichier : `summary.formatVersion` pour la carte (`useDataImport`), `envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION` pour « Rétablir la sauvegarde » (`applyBackup`). Déduire le format de la présence des tableaux ferait passer un fichier tronqué pour un ancien, et sa restauration viderait le budget.
+
+### 8. Les refus, tous avant la moindre suppression
+
+Des validations pures, au parse (`parseImportedJson`, `parseImportedCsv` : la confirmation ne s'ouvre pas) et en tête de chaque restauration, lèvent une `SrefValidationError` dont la clé i18n dit quoi faire :
+
+- un `format_version` plus grand que `SREF_FORMAT_VERSION` vient d'une version plus récente (`newerFormat`) ; il est lu avant le mode, qu'une version plus récente peut ajouter. Un `format_version` qui n'est pas un entier d'au moins 1 reçoit l'erreur d'une enveloppe mal formée (« Invalid export file format ») ;
+- une configuration d'import illisible (#331), des lignes de répartition orphelines (#518), une catégorie, un mot-clé ou un fournisseur qui vise une catégorie absente du fichier (#521) ;
+- au format 3, pour les deux modes qui portent les catégories, un des trois tableaux absent, ou une ligne que les tables ne peuvent pas tenir (`invalidBudgetRows`) : une catégorie absente du fichier, un montant qui n'est pas un nombre fini, une année hors de 1900 à 2200 ou un mois hors de 1 à 12 (entiers tous deux), un nom de modèle, un nom ou une date d'ajustement qui n'est pas un texte, deux lignes de budget sur la même catégorie et le même mois, deux lignes d'un modèle sur la même catégorie, deux modèles du même nom. Les tables ne sont pas STRICT, et le refus de SQLite, en cours de restauration, n'est pas un message lisible.
+
+### 9. Deux numéros de version distincts
+
+L'octet de version du conteneur chiffré (`0x01`, ADR 0004, vérifié au déchiffrement par `export_import_commands.rs`) ne change pas : il décrit le chiffrement. `format_version` décrit l'enveloppe, que seul le front lit.
+
+## Conséquences
+
+### Positives
+
+- Une sauvegarde complète l'est vraiment : le budget, les modèles et les ajustements reviennent, dans le même profil comme dans un profil neuf, et « Rétablir la sauvegarde » rend l'état d'avant la migration, budget compris, comme le promet le consentement de la migration.
+- Un fichier que la restauration ne pourrait pas écrire, ou qu'une version plus récente a écrit, est refusé avant toute suppression, avec un message qui dit quoi faire.
+- Un fichier ancien perd le moins possible : les lignes dont la catégorie revient sont gardées, et la confirmation le dit.
+
+### Négatives et points de vigilance
+
+- **Une version antérieure lit un fichier de format 3 sans son budget.** La v0.17.2 et les précédentes n'ont pas le refus des formats plus récents : elles restaurent le fichier en ignorant ses trois tableaux, et leur cascade vide le budget comme avant.
+- **Les ajustements du fichier remplacent ceux du profil** : un ajustement créé depuis la sauvegarde disparaît, comme toute donnée créée depuis ; les identifiants des ajustements et des lignes du format 3 changent, aucun écran ne les gardant.
+- **La liste des tableaux est manuelle.** Une table de plus qui nomme une catégorie entre dans `collectExportData`, dans `takeBudget` et `restoreBudget` et dans la validation, faute de quoi la cascade la viderait.
+- **Le repli du format 2 se fie à l'identifiant** (§ 6).
+
+## Alternatives écartées
+
+- **Garder les lignes qui retrouvent leur catégorie, format inchangé** (option B de #520) : le budget ne passerait jamais à une autre machine, et le rétablissement d'une migration perdrait les lignes réécrites sur les catégories standard. **Annoncer la perte seulement** (option C) : la perte resterait.
+- **Désactiver les catégories au lieu de les supprimer**, comme la migration : la restauration rend les catégories du fichier sous leurs identifiants, qui peuvent être ceux de catégories encore présentes.
+- **Changer l'action `ON DELETE`** des trois tables : une migration v18, hors du périmètre de la pile ; la cascade reste la règle hors de la restauration (« Réinitialiser », dont la confirmation le dit désormais).
+- **Fusionner le budget du fichier et celui du profil** : un ajustement n'a pas de clé naturelle, et une restauration rend l'état de la sauvegarde. **Vider les modèles absents du fichier** : #331 garde les modèles d'import absents.
+- **Laisser SQLite refuser** un fichier mal formé : son message n'est pas lisible, et il arrive après les premières suppressions.
+- **Amender l'ADR 0019** (le format d'import) ou **l'ADR 0004** (le chiffrement), ou **un ADR par issue** : la pile se merge d'un bloc, et ses règles se tiennent.
+
+## Références
+
+- Implémentation : `src/services/dataExportService.ts` (`collectExportData`, enveloppe, validations), `src/services/dataRestoreService.ts` (`runRestore`, `takeTransfers`, `takeBudget`, `restoreBudget`, `restoreCategories`), `src/services/categoryBackupService.ts`, `src/services/categoryRestoreService.ts` (`readBackup`, `applyBackup`), `src/hooks/useDataExport.ts`, `src/hooks/useDataImport.ts`, `src/components/settings/ImportConfirmModal.tsx`, `src/components/settings/CategoriesMigrationRestoreModal.tsx`
+- Tests : `src/__integration__/restore.test.ts` (services réels sur `node:sqlite`, `consolidated_schema.sql`, clés étrangères actives, migration des catégories comprise), `src/services/dataExportService.test.ts`, `src/hooks/useDataExport.test.ts`, `src/hooks/useDataImport.test.ts`
+- Issues : #518, #521, #520 ; #331 (format 2) ; #120 et #122 (sauvegarde et rétablissement de la migration)
diff --git a/docs/architecture.md b/docs/architecture.md
index e0bc0fa..6877443 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -212,8 +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é), 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), et `parseImportedJson` des catégories, mots-clés ou fournisseurs qui renvoient à une catégorie absente du fichier (`validateImportedCategoryReferences`, clé `danglingCategoryReference`, #521), 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). Les deux restaurations de transactions lisent puis retirent les transferts du Bilan avant `DELETE FROM transactions`, et réinsèrent tels quels ceux dont la transaction revient avec le même identifiant, la même date, le même montant et la même description ([ADR 0010](adr/0010-fk-restrict-balance-transfers.md), amendement #521) ; une transaction dont la catégorie manque au profil revient sans catégorie, drapeau manuel à 0, et une ligne `logWarn` en donne le nombre ; `restoreCategories` insère les catégories sans parent, puis pose les `parent_id` dans un second passage (#521). Les trois restaurations rendent un `RestoreOutcome` (`unlinkedTransfers`, `uncategorizedTransactions` ; zéros pour « Catégories uniquement ») ; `previewUnlinkedTransfers` compte, hors transaction et par la même règle, les transferts qu'une restauration délierait. `importTransactionsOnly` et `importTransactionsWithCategories` rejouent en tête les validations du parse, `importTransactionsWithCategories` et `importCategoriesOnly` celle des références de catégorie, avant toute suppression. Appelé par `useDataImport` et, pour « Rétablir la sauvegarde », par `readBackup` (lecture, déchiffrement, analyse et compte des transferts, sans écriture) puis `applyBackup` (restauration et préférences, `RestoreResult` avec le `RestoreOutcome`) de `categoryRestoreService.ts` |
+| `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 = 3`), **inclut `import_sources` + `import_config_templates`** depuis #331 et, dans les deux modes qui portent les catégories, **`budget_entries`, `budget_templates` et `adjustments`** depuis #520 ; `collectExportData(mode)` rassemble les tableaux de chaque mode, pour « Exporter » comme pour la sauvegarde d'avant migration ; 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), et `parseImportedJson` un format plus récent que celui de l'application (`validateImportedFormatVersion`, clé `newerFormat`, #520), des catégories, mots-clés ou fournisseurs qui renvoient à une catégorie absente du fichier (`validateImportedCategoryReferences`, clé `danglingCategoryReference`, #521) et, au format 3, un budget que la restauration ne pourrait pas réécrire (`validateImportedBudget`, clé `invalidBudgetRows`, #520), par une `SrefValidationError` qui porte sa clé i18n. La restauration vit dans `dataRestoreService.ts` ([ADR 0025](adr/0025-contenu-restauration-sauvegarde-sref.md)) |
+| `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). Les deux restaurations de transactions lisent puis retirent les transferts du Bilan avant `DELETE FROM transactions`, et réinsèrent tels quels ceux dont la transaction revient avec le même identifiant, la même date, le même montant et la même description ([ADR 0010](adr/0010-fk-restrict-balance-transfers.md), amendement #521) ; une transaction dont la catégorie manque au profil revient sans catégorie, drapeau manuel à 0, et une ligne `logWarn` en donne le nombre ; `restoreCategories` insère les catégories sans parent, puis pose les `parent_id` dans un second passage (#521), et écrit leur `i18n_key` (#520). Les deux restaurations qui portent les catégories reçoivent le format du fichier (`formatVersion`), lisent puis retirent les lignes de budget, de modèle et d'ajustement avant `DELETE FROM categories` (`takeBudget`), et les remettent une fois les catégories en place (`restoreBudget`) : au format 3, le budget du fichier (lignes de budget et ajustements remplacés, modèles insérés ou mis à jour par leur nom, un modèle absent du fichier gardant ses lignes dont la catégorie revient) ; en dessous, les lignes du profil dont la catégorie revient ([ADR 0025](adr/0025-contenu-restauration-sauvegarde-sref.md), #520). Les trois restaurations rendent un `RestoreOutcome` (`unlinkedTransfers`, `uncategorizedTransactions` ; zéros pour « Catégories uniquement ») ; `previewUnlinkedTransfers` compte, hors transaction et par la même règle, les transferts qu'une restauration délierait. `importTransactionsOnly` et `importTransactionsWithCategories` rejouent en tête les validations du parse, `importTransactionsWithCategories` et `importCategoriesOnly` celles du format, des références de catégorie et du budget, avant toute suppression. Appelé par `useDataImport` et, pour « Rétablir la sauvegarde », par `readBackup` (lecture, déchiffrement, analyse et compte des transferts, sans écriture) puis `applyBackup` (restauration et préférences, `RestoreResult` avec le `RestoreOutcome`) de `categoryRestoreService.ts` |
| `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_` = `"1"` par étape, lues en une requête et filtrées sur les huit clés), les étapes de visite reconnues (`onboarding_acknowledged_` = `"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 |
@@ -245,7 +245,7 @@ Les 30 fichiers `.ts` de `src/hooks/`, hors tests (`ls src/hooks/*.ts | grep -v
| `useCategoryMigration` | Migration vers la taxonomie standard (`/settings/categories/migrate`, `CategoriesMigrationPage`) : machine d'états des étapes découvrir, simuler et consentir, puis exécution et résultat. Reducer sans appel de service : la page calcule le plan, écrit la sauvegarde préalable (SREF) et applique la migration, puis dispatche |
| `useCategoryTaxonomy` | Taxonomie standard v1 en lecture (`getTaxonomyV1`, `findById`, `findByPath`, `getLeaves`, `getParentById` de `categoryTaxonomyService`), mémorisée une fois : guide des catégories standard (`CategoriesStandardGuidePage`) et étapes de la migration |
| `useTransactions` | Transactions et filtrage. `useTransactions(initialFilters?)` part de filtres de départ posés sur les filtres par défaut et lus au montage seulement (`initTransactionsState`) : l'entrée guidée de l'étape « Classer une transaction à la main » passe `GUIDED_ENTRY_FILTERS` (non catégorisées, sans borne de date). Si sa première page revient vide, le reducer retire le filtre « non catégorisées » une seule fois (`guidedFallback`) et la page relit (#399) |
-| `useDataImport` | Import de données. Compte, une fois le fichier lu et avant la confirmation, les transferts du Bilan qu'une restauration délierait (`previewUnlinkedTransfers`, modes qui portent des transactions), et garde le `RestoreOutcome` de la restauration, que porte `IMPORT_SUCCESS`, pour le message de réussite (#521) |
+| `useDataImport` | Import de données. Compte, une fois le fichier lu et avant la confirmation, les transferts du Bilan qu'une restauration délierait (`previewUnlinkedTransfers`, modes qui portent des transactions), et garde le `RestoreOutcome` de la restauration, que porte `IMPORT_SUCCESS`, pour le message de réussite (#521). Passe aux deux restaurations qui portent les catégories le format du fichier, `summary.formatVersion` (#520) |
| `useImportWizard` | Assistant d'import multi-étapes. Restaure le format enregistré **tel quel** via `formatFromRow` (aucune ré-inférence), déclenche la détection seule sur une source sans format (garde `!existing`), traverse l'étape `file-preview` à **chaque** import, et n'écrit la configuration qu'à `executeImport` (point d'écriture unique) — voir la section « Import CSV » et l'[ADR 0019](adr/0019-format-import-persiste.md). Expose `importFolderLoaded`, posé dans le `finally` de la lecture du dossier au montage (après son premier scan) et gardé par `RESET` : l'état vide de la page Import et sa carte de démarrage l'attendent (#384, #398). Expose aussi `rootFiles`, les CSV/TXT posés à la racine du dossier d'import que le scan (`ImportFolderScan`) rend à côté des sources : posé avec elles par la même action `SET_SCANNED_SOURCES`, gardé par `RESET` comme elles, vidé par `SET_IMPORT_FOLDER` jusqu'au scan du nouveau dossier, pour que l'avertissement ne nomme pas les fichiers de l'ancien dossier sous le nom du nouveau (les sources, `scannedSources`, restent celles du dernier scan jusque-là : comportement antérieur, #446), nommé à l'écran par `RootFilesWarning` (au plus cinq noms, `formatRootFiles`) et jamais écrit au Journal (#427). `executeImport` enregistre la source sous `selectedSource.folder_name`, à la création comme à la mise à jour, jamais sous `config.name` : la source et ses fichiers importés sont retrouvés par le nom du sous-dossier, que `SourceNameDisplay` affiche en lecture seule (#426) |
| `useImportHistory` | Historique des imports |
| `useAdjustments` | Ajustements |
@@ -261,7 +261,7 @@ Les 30 fichiers `.ts` de `src/hooks/`, hors tests (`ls src/hooks/*.ts | grep -v
| `useBalanceAccounts` | Bilan — état de la page `/balance/accounts` : CRUD comptes ET catégories (un seul hook pour les deux onglets, aligné sur la convention "1 hook par page") |
| `useSnapshotEditor` | Bilan — cycle de vie d'un snapshot unique (`/balance/snapshot`) : valeurs simple (string) + valeurs priced (`{quantity, unit_price}` strings), prefill depuis snapshot précédent, save (rewrite-all), delete avec double-confirmation par re-saisie de la date |
| `useBalanceOverview` | Bilan — page `/balance` : sélecteur de période (`3M / 6M / 1A / 3A / Tout`), série temporelle agrégée, mode chart (`line` / `stacked`), tableau des comptes avec valeurs courantes et Δ% sur la période. Les rendements multi-horizons sont chargés *lazily* dans `BalanceAccountsTable` (un appel `compute_account_return` par cellule) |
-| `useDataExport` | Export de données |
+| `useDataExport` | Export de données : les tableaux du mode choisi, ceux de `collectExportData`, comme la sauvegarde d'avant migration (#520) |
| `useTheme` | Thème clair/sombre |
| `useUpdater` | Mise à jour de l'application — gatée par l'entitlement `auto-update` (Base+) via la commande `check_entitlement` |
| `useEntitlement` | Gating par édition : lecture **synchrone** `{ allowed, ready }` d'une `FeatureKey` depuis `LicenseContext` — `ready` évite le flash de verrouillage au boot (voir section « Gating par édition ») |
@@ -342,14 +342,16 @@ L'étape `file-preview`, déclarée depuis l'origine dans `ImportWizardStep` san
- **`RepairPathNotice`**, rendu dans le panneau de dérive **et** à côté du bouton d'inversion : `findDuplicates` apparie sur date + description + montant, donc ré-importer un fichier « maintenant qu'il se lit bien » ne corrige pas les lignes déjà écrites — il les **double**, et une inversion de signe produit des paires miroir qui s'annulent dans tous les rapports. La seule voie sûre est `deleteImportWithTransactions` puis rejeu. Aucun montant déjà écrit n'est jamais muté.
- **`ImportConfirmation`** énonce désormais le mode de montant, la convention de signe (seulement dans le mode qui l'applique) et le mapping nommé par en-tête. Le sélecteur de convention est **masqué** en mode débit/crédit, où le parsing ne le lit pas — masqué, pas réinitialisé : la valeur stockée est intacte.
-### 4. Le format SREF porte les sources et les modèles
+### 4. Le format SREF porte les sources, les modèles et le budget
-`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).
+`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` à #331 ; 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.
+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é. #518 laisse `SREF_FORMAT_VERSION` à 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.
Depuis #521, trois autres clés étrangères ne font plus échouer une restauration, où elles arrêtaient tout sur « FOREIGN KEY constraint failed ». (a) `balance_account_transfers.transaction_id` est `ON DELETE RESTRICT` ([ADR 0010](adr/0010-fk-restrict-balance-transfers.md)) et la sauvegarde ne porte pas les transferts : dans la transaction de `runRestore`, les deux restaurations de transactions lisent chaque transfert avec la date, le montant et la description de sa transaction, vident la table avant `DELETE FROM transactions`, puis réinsèrent tels quels (identifiant, compte, sens, notes, date de création) ceux dont la transaction revient avec le même identifiant, la même date, le même montant et la même description ; les autres sont déliés. Une seule fonction pure, `transfersThatReturn`, porte cette règle pour la restauration et pour `previewUnlinkedTransfers`, qui la lit hors transaction (`getDb`) : le nombre annoncé par la confirmation est celui que la restauration délie sur le même profil, et quand les lignes ne gardent pas leur identifiant (`keepIds` faux), aucun transfert ne retrouve sa transaction. (b) Une transaction dont la catégorie manque au profil (après « Réinitialiser », une restauration qui a remplacé les catégories, ou avec le fichier d'un autre profil) revient sans catégorie, drapeau manuel à 0, pour qu'« Auto-catégoriser » la reprenne : `attachTransactions` lit une fois les identifiants des catégories par le handle de la restauration, après `restoreCategories` dans le mode qui les écrit, et une ligne `logWarn` donne le nombre, sans nom ni montant. (c) `restoreCategories` insère chaque catégorie avec `parent_id` à NULL, puis pose les parents dans un second passage : une catégorie rangée sous une plus récente (la catégorie 2000 de la migration) et une boucle passent. `validateImportedCategoryReferences`, pure, refuse au parse et en tête des deux restaurations qui écrivent des catégories un fichier dont un `parent_id`, un mot-clé ou un fournisseur vise une catégorie absente du fichier (clé `danglingCategoryReference`) ; la catégorie d'une transaction n'y est pas vérifiée, puisque (b) la remet à NULL. Les restaurations rendent un `RestoreOutcome` (`unlinkedTransfers`, `uncategorizedTransactions`) par `runRestore` : la carte « Gestion des données » annonce les transferts à délier dans sa confirmation et le nombre réel après la restauration. « Rétablir la sauvegarde » passe par `readBackup`, qui lit, déchiffre, analyse et compte sans rien écrire, puis, après une seconde confirmation qui annonce les transferts à délier, par `applyBackup` ; sa fenêtre finit sur « Sauvegarde rétablie » et ne recharge l'application qu'au clic sur « Fermer ».
+Depuis #520, l'enveloppe est au format 3 ([ADR 0025](adr/0025-contenu-restauration-sauvegarde-sref.md), qui fixe le contenu et la restauration d'une sauvegarde pour #518, #521 et #520). Les deux modes qui portent les catégories effacent les catégories, et avec elles, par `ON DELETE CASCADE`, les lignes de budget, de modèle et d'ajustement, que la sauvegarde ne portait pas : la restauration réussissait et laissait le budget vide, « Rétablir la sauvegarde » compris. Ces deux modes, et la sauvegarde d'avant migration, portent désormais `budget_entries` (désignées par catégorie, année et mois), `budget_templates` (par leur nom, avec leurs lignes) et `adjustments` (avec leurs lignes), que rassemble `collectExportData(mode)` ; « Transactions uniquement » et le CSV ne changent pas. Dans la transaction de `runRestore`, `takeBudget` lit puis retire les trois tables de lignes avant `DELETE FROM categories`, dans les deux formats ; une fois les catégories en place, `restoreBudget` met, au format 3, les lignes de budget et les ajustements du fichier à la place de ceux du profil, insère ou met à jour chaque modèle du fichier par son nom (`ON CONFLICT(name) DO UPDATE`) avec les lignes du fichier, et rend à un modèle absent du fichier ses lignes dont la catégorie revient ; au format 2 ou antérieur, il remet telles quelles (mêmes identifiants, mêmes dates) les lignes dont la catégorie revient, sur son seul identifiant (limite acceptée par l'ADR 0025). Le format n'est jamais deviné : `importTransactionsWithCategories(data, filename, formatVersion)` et `importCategoriesOnly(data, formatVersion)` reçoivent celui du fichier (`summary.formatVersion` par `useDataImport`, `envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION` par `applyBackup`). `validateImportedFormatVersion` refuse un format plus récent (`newerFormat`), vérifié avant le mode, et un `format_version` qui n'est pas un entier d'au moins 1 (« Invalid export file format ») ; `validateImportedBudget` refuse, au format 3, un des trois tableaux absent ou une ligne que les tables ne peuvent pas tenir (`invalidBudgetRows`). La confirmation de la carte et la seconde confirmation de « Rétablir la sauvegarde » le disent pour un fichier plus ancien (`legacyBudgetNote`), et `ImportConfirmModal` compte les lignes de budget, les modèles et les ajustements d'un fichier de format 3. `restoreCategories` écrit `i18n_key`. L'octet de version du conteneur chiffré (`export_import_commands.rs`, ADR 0004) ne change pas : `format_version` décrit l'enveloppe, que seul le front lit.
+
### 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.
@@ -709,7 +711,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. `src/__integration__/restore.test.ts` (#518) en copie l'adaptateur pour les restaurations (`importTransactionsOnly`, `importTransactionsWithCategories`, `importCategoriesOnly`, et « Rétablir la sauvegarde » par `readBackup` puis `applyBackup`), avec une seconde base qui tient lieu de profil neuf ; #521 y ajoute les transferts du Bilan, liés par le vrai `linkTransfer`, les catégories absentes, « Réinitialiser » compris, et les catégories rangées sous une plus récente ou en boucle. 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`, `importCategoriesOnly`, et « Rétablir la sauvegarde » par `readBackup` puis `applyBackup`), avec une seconde base qui tient lieu de profil neuf ; #521 y ajoute les transferts du Bilan, liés par le vrai `linkTransfer`, les catégories absentes, « Réinitialiser » compris, et les catégories rangées sous une plus récente ou en boucle ; #520 le budget, les modèles et les ajustements, écrits par les vrais services des pages Budget et Ajustements, au format 3 comme au format 2, et la migration des catégories elle-même (`createPreMigrationBackup`, `computeMigrationPlan` puis `applyMigration`) avant « Rétablir la sauvegarde ». Aucun harnais partagé : #392 le prévoit. Les autres tests de services gardent leurs faux.
### Limites connues (#437)
@@ -800,3 +802,4 @@ Les ADRs documentent les décisions techniques structurantes. Ils vivent dans `d
| [0022](adr/0022-canal-evenements-donnees.md) | Canal d'événements de données : les écritures signalent, le parcours de démarrage relit | 2026-10-08 | Accepted |
| [0023](adr/0023-windows-sys-pinning.md) | Épinglage de `windows-sys` 0.61.2 : garde-fou CI sur la version résolue, condition de sortie écrite | 2026-10-10 | Accepted |
| [0024](adr/0024-serveur-mcp.md) | Serveur MCP : un mode `--mcp` du binaire, stdio seul, accès par profil, Premium | 2026-10-12 | Proposed |
+| [0025](adr/0025-contenu-restauration-sauvegarde-sref.md) | Contenu et restauration d'une sauvegarde SREF : identifiants, transferts du Bilan, budget au format 3 et repli des formats antérieurs | 2026-11-04 | Accepted |
diff --git a/docs/guide-utilisateur.md b/docs/guide-utilisateur.md
index 3f88ebe..59f5016 100644
--- a/docs/guide-utilisateur.md
+++ b/docs/guide-utilisateur.md
@@ -223,7 +223,7 @@ L'historique téléchargeable est limité à **123 jours** au maximum : exportez
- Sauvegardez votre configuration comme modèle pour ne pas avoir à reconfigurer à chaque fois. Un modèle sert à initialiser une source ; le modifier ensuite ne change aucune source déjà configurée.
- Les fichiers déjà importés sont marqués d'un badge — les ré-importer déclenchera la détection de doublons
- Vous pouvez supprimer un import de l'historique pour retirer toutes ses transactions
-- Vos sources et vos modèles d'import font désormais partie de la sauvegarde chiffrée : restaurer un backup ne vous oblige plus à tout reconfigurer
+- Vos sources et vos modèles d'import font désormais partie de la sauvegarde chiffrée, comme votre budget, vos modèles de budget et vos ajustements : restaurer un backup ne vous oblige plus à tout reconfigurer
- Si des fichiers CSV sont posés directement dans le dossier d'import, un avertissement les nomme : déplacez-les dans un sous-dossier par compte
- Le nom d'une source est celui de son sous-dossier
@@ -589,7 +589,7 @@ Configurez les préférences de l'application, vérifiez les mises à jour, acc
- Journaux de l'application (logs) consultables avec filtres par niveau, copie et effacement
- Historique des versions : les notes de la version installée s'affichent d'emblée, les autres versions sont repliées et se déplient d'un clic sur leur numéro, ou toutes ensemble avec « Tout déplier »
- Envoi de feedback optionnel vers `feedback.lacompagniemaximus.com` (sur demande ; une demande de consentement précède le premier envoi)
-- Export des données (transactions, catégories, ou les deux) en format JSON ou CSV
+- Export des données (transactions, catégories, ou les deux) en format JSON ou CSV ; avec les catégories, l'export porte aussi le budget, les modèles de budget et les ajustements
- Import des données depuis un fichier exporté précédemment
- Chiffrement AES-256-GCM optionnel pour les fichiers exportés
- Réaffichage du parcours de démarrage (Paramètres → Utilisateurs) quand il a été masqué
@@ -613,6 +613,7 @@ Configurez les préférences de l'application, vérifiez les mises à jour, acc
- 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
- Restaurer une sauvegarde garde les transferts du Bilan dont la transaction revient à l'identique (même numéro, même date, même montant, même description) ; les autres sont déliés, et la confirmation dit combien avant que rien ne soit remplacé. Une transaction dont la catégorie n'existe plus revient sans catégorie : « Auto-catégoriser » la reprend
+- Les exports avec catégories (« Transactions avec catégories », « Catégories uniquement ») et la sauvegarde prise avant une migration des catégories portent le budget, les modèles de budget et les ajustements : une restauration les remet tels qu'ils étaient. Une sauvegarde écrite par une version antérieure n'en contient pas : les lignes actuelles dont la catégorie revient sont gardées, les autres supprimées, et la confirmation le dit. Un fichier écrit par une version plus récente est refusé : mettez l'application à jour pour l'importer
- 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.
diff --git a/src/__integration__/category-migration.test.ts b/src/__integration__/category-migration.test.ts
index 38ddbaa..d85b80f 100644
--- a/src/__integration__/category-migration.test.ts
+++ b/src/__integration__/category-migration.test.ts
@@ -30,21 +30,10 @@ vi.mock("@tauri-apps/api/app", () => ({
getVersion: vi.fn(async () => "0.8.3-test"),
}));
-// dataExportService helpers are used by both the backup service and the
-// 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")
- >("../services/dataExportService");
- return {
- ...actual,
- getExportCategories: vi.fn(async () => []),
- getExportSuppliers: vi.fn(async () => []),
- getExportKeywords: vi.fn(async () => []),
- getExportTransactions: vi.fn(async () => []),
- };
-});
+// The backup service gathers its arrays through `collectExportData` (#520),
+// whose reads reach the fake DB below, which answers every one of them with no
+// row; the parsers stay real. The restore service writes the backup back
+// through dataRestoreService, whose write is mocked.
vi.mock("../services/dataRestoreService", async () => {
const actual = await vi.importActual<
typeof import("../services/dataRestoreService")
diff --git a/src/__integration__/regression-v2-v1.test.ts b/src/__integration__/regression-v2-v1.test.ts
index e628d5d..455f8d8 100644
--- a/src/__integration__/regression-v2-v1.test.ts
+++ b/src/__integration__/regression-v2-v1.test.ts
@@ -282,6 +282,10 @@ function envelopeFixture(schema: Schema): ExportEnvelope {
suppliers: [],
keywords: [],
transactions: [],
+ // A full backup of format 3 carries the budget arrays (#520).
+ budget_entries: [],
+ budget_templates: [],
+ adjustments: [],
},
};
}
@@ -368,6 +372,9 @@ describe.each<[Schema]>([["v2"], ["v1"]])(
parent_transaction_id: 100,
},
],
+ budget_entries: [],
+ budget_templates: [],
+ adjustments: [],
},
};
const json = serializeToJson(envelope.export_type, envelope.data, envelope.app_version);
diff --git a/src/__integration__/restore.test.ts b/src/__integration__/restore.test.ts
index bbca03e..196f435 100644
--- a/src/__integration__/restore.test.ts
+++ b/src/__integration__/restore.test.ts
@@ -21,6 +21,13 @@
* confirmation; a transaction whose category is gone comes back without one;
* the categories go in without their parents, set in a second pass.
*
+ * And one let a restore succeed with a loss (#520): the budget lines, the
+ * template lines and the adjustment lines name a category `ON DELETE
+ * CASCADE`, so the restores with categories left them all empty, and the
+ * backup held none. The file now carries them (format 3) and they come back;
+ * an older file keeps the profile's lines whose category comes back. The
+ * categories come back with their `i18n_key`.
+ *
* 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`
@@ -56,9 +63,11 @@ vi.mock("../services/db", () => ({
}),
}));
-// « Rétablir la sauvegarde » reads its file through `read_import_file`.
+// « Rétablir la sauvegarde » reads its file through `read_import_file`, and the
+// backup taken before the categories migration writes it (#520).
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
+vi.mock("@tauri-apps/api/app", () => ({ getVersion: vi.fn(async () => "0.17.2") }));
// The Journal line of a restore that brings transactions back without their category (#521).
const { logWarn } = vi.hoisted(() => ({ logWarn: vi.fn() }));
@@ -70,18 +79,16 @@ vi.mock("../services/logService", async (orig) => ({
import { getSplitChildren, saveSplitAdjustment } from "../services/transactionService";
import { linkTransfer, listAccountTransfers } from "../services/balance.service";
import {
- getExportCategories,
- getExportImportSources,
- getExportImportTemplates,
- getExportKeywords,
- getExportSuppliers,
+ collectExportData,
getExportTransactions,
parseImportedCsv,
parseImportedJson,
serializeToJson,
serializeTransactionsToCsv,
+ SREF_FORMAT_VERSION,
SrefValidationError,
type ExportEnvelope,
+ type ExportMode,
type ExportTransaction,
} from "../services/dataExportService";
import {
@@ -92,6 +99,12 @@ import {
type RestoreOutcome,
} from "../services/dataRestoreService";
import { applyBackup, readBackup } from "../services/categoryRestoreService";
+import { saveAsTemplate, upsertBudgetEntry } from "../services/budgetService";
+import { createAdjustment, createEntry } from "../services/adjustmentService";
+import { createPreMigrationBackup } from "../services/categoryBackupService";
+import { computeMigrationPlan } from "../services/categoryMappingService";
+import { applyMigration } from "../services/categoryMigrationService";
+import type { Profile } from "../services/profileService";
const SCHEMA = readFileSync(
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
@@ -225,18 +238,9 @@ async function splitLines(db: DatabaseSync, description: string) {
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 {
- 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;
+/** What « Exporter » gathers for `mode` (`collectExportData`, #520), from the database in use. */
+function exportData(mode: ExportMode): Promise {
+ return collectExportData(mode);
}
/** A JSON backup of the database in use, written then read back as the import reads it. */
@@ -244,20 +248,22 @@ async function jsonBackup(mode: Mode): Promise {
return parseImportedJson(serializeToJson(mode, await exportData(mode), "0.17.2")).envelope.data;
}
-function restore(mode: Mode, data: ExportEnvelope["data"], filename = "backup.json"): Promise {
+/** The restore of the card for `mode`, of a file of `formatVersion` (the format this build writes by default). */
+function restore(
+ mode: Mode,
+ data: ExportEnvelope["data"],
+ filename = "backup.json",
+ formatVersion = SREF_FORMAT_VERSION,
+): Promise {
return mode === "transactions_with_categories"
- ? importTransactionsWithCategories(data, filename)
+ ? importTransactionsWithCategories(data, filename, formatVersion)
: importTransactionsOnly(data, filename);
}
/** What « Exporter » writes for « Catégories uniquement », read back as the import reads it. */
async function categoriesBackup(): Promise {
- const data: ExportEnvelope["data"] = {
- categories: await getExportCategories(),
- suppliers: await getExportSuppliers(),
- keywords: await getExportKeywords(),
- };
- return parseImportedJson(serializeToJson("categories_only", data, "0.17.2")).envelope.data;
+ return parseImportedJson(serializeToJson("categories_only", await exportData("categories_only"), "0.17.2")).envelope
+ .data;
}
/**
@@ -265,7 +271,11 @@ async function categoriesBackup(): Promise {
* transfers counted) before the second confirmation, then restored (#521).
*/
async function restoreTheBackup(data: ExportEnvelope["data"]) {
- const content = serializeToJson("transactions_with_categories", data, "0.17.2");
+ return restoreTheFile(serializeToJson("transactions_with_categories", data, "0.17.2"));
+}
+
+/** « Rétablir la sauvegarde » of the file `content`, written by this version or an older one (#520). */
+async function restoreTheFile(content: string) {
invoke.mockImplementation(async (cmd: string) => {
if (cmd === "read_import_file") return content;
throw new Error(`unexpected invoke: ${cmd}`);
@@ -713,7 +723,7 @@ describe("restoring a transaction whose category is gone (#521)", () => {
const full = await jsonBackup("transactions_with_categories");
const data = { ...full, categories: (full.categories ?? []).filter((c) => c.id !== perso) };
- const outcome = await importTransactionsWithCategories(data, "backup.json");
+ const outcome = await importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION);
expect(categorization(profile, gift)).toEqual({ category_id: null, is_manually_categorized: 0 });
expect(outcome.uncategorizedTransactions).toBe(1);
@@ -743,9 +753,13 @@ const WITH_CATEGORIES = ["transactions_with_categories", "categories_only", "Ré
/** Restores the backup of `db` the way `how` does. */
async function restoreCategoriesBy(how: (typeof WITH_CATEGORIES)[number]): Promise {
if (how === "categories_only") {
- await importCategoriesOnly(await categoriesBackup());
+ await importCategoriesOnly(await categoriesBackup(), SREF_FORMAT_VERSION);
} else if (how === "transactions_with_categories") {
- await importTransactionsWithCategories(await jsonBackup("transactions_with_categories"), "backup.json");
+ await importTransactionsWithCategories(
+ await jsonBackup("transactions_with_categories"),
+ "backup.json",
+ SREF_FORMAT_VERSION,
+ );
} else {
await restoreTheBackup(await exportData("transactions_with_categories"));
}
@@ -782,7 +796,9 @@ describe("restoring a category ranked under a newer one, or caught in a loop (#5
const data = how === "categories_only" ? await categoriesBackup() : await jsonBackup(how);
const fresh = use(open());
- await (how === "categories_only" ? importCategoriesOnly(data) : importTransactionsWithCategories(data, "backup.json"));
+ await (how === "categories_only"
+ ? importCategoriesOnly(data, SREF_FORMAT_VERSION)
+ : importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION));
expect(parents(fresh)).toEqual(before);
},
@@ -821,7 +837,9 @@ describe("a file whose keyword, supplier or parent names a category it does not
expectDangling(refusal);
const run =
- how === "categories_only" ? importCategoriesOnly(data) : importTransactionsWithCategories(data, "backup.json");
+ how === "categories_only"
+ ? importCategoriesOnly(data, SREF_FORMAT_VERSION)
+ : importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION);
await run.then(() => expect.unreachable("the restore should have been refused"), expectDangling);
expect(rows(profile)).toEqual(before);
@@ -830,3 +848,494 @@ describe("a file whose keyword, supplier or parent names a category it does not
},
);
});
+
+// ---------------------------------------------------------------------------
+// #520 — the budget, its templates and the adjustments
+// ---------------------------------------------------------------------------
+
+type BudgetLine = { category_id: number; year: number; month: number; amount: number; notes: string | null };
+type TemplateLine = { category_id: number; amount: number };
+type AdjustmentLine = { category_id: number; amount: number; description: string | null };
+type BudgetState = {
+ entries: BudgetLine[];
+ templates: Array<{ name: string; description: string | null; entries: TemplateLine[] }>;
+ adjustments: Array<{
+ name: string;
+ description: string | null;
+ date: string;
+ is_recurring: number;
+ recurrence_rule: string | null;
+ entries: AdjustmentLine[];
+ }>;
+};
+
+/** Every row `sql` returns on `db`, as plain objects. */
+function all(db: DatabaseSync, sql: string, params: Record = {}): T[] {
+ return db
+ .prepare(sql)
+ .all(params)
+ .map((row) => ({ ...row })) as T[];
+}
+
+/**
+ * What the Budget and Adjustments pages show of `db`: the budget lines, each
+ * template with its lines, each adjustment with its lines, in the order the
+ * pages list them, without the ids SQLite gives.
+ */
+function budgetOf(db: DatabaseSync): BudgetState {
+ return {
+ entries: all(
+ db,
+ "SELECT category_id, year, month, amount, notes FROM budget_entries ORDER BY category_id, year, month",
+ ),
+ templates: all<{ id: number; name: string; description: string | null }>(
+ db,
+ "SELECT id, name, description FROM budget_templates ORDER BY name",
+ ).map(({ id, ...template }) => ({
+ ...template,
+ entries: all(
+ db,
+ "SELECT category_id, amount FROM budget_template_entries WHERE template_id = $id ORDER BY id",
+ { $id: id },
+ ),
+ })),
+ adjustments: all(
+ db,
+ "SELECT id, name, description, date, is_recurring, recurrence_rule FROM adjustments ORDER BY date DESC, id",
+ ).map(({ id, ...adjustment }) => ({
+ ...adjustment,
+ entries: all(
+ db,
+ "SELECT category_id, amount, description FROM adjustment_entries WHERE adjustment_id = $id ORDER BY id",
+ { $id: id },
+ ),
+ })),
+ };
+}
+
+/** Every budget line, template line and adjustment line of `db`, ids and dates included: « kept » is untouched. */
+function budgetRows(db: DatabaseSync) {
+ return {
+ entries: all(db, "SELECT * FROM budget_entries ORDER BY id"),
+ templateLines: all(db, "SELECT * FROM budget_template_entries ORDER BY id"),
+ adjustmentLines: all(db, "SELECT * FROM adjustment_entries ORDER BY id"),
+ };
+}
+
+/** The categories a budget is written on. */
+type BudgetCategories = { groceries: number; rent: number; electricity: number };
+
+/**
+ * A budget on `on`, written by the real services of the Budget and Adjustments
+ * pages: three budget lines, the template « Mois type » and its two lines, the
+ * recurring adjustment « Rattrapage » and its two lines. Its recurrence rule,
+ * which no page writes yet, is set in `db`, so that it travels too.
+ */
+async function writeBudget(db: DatabaseSync, on: BudgetCategories): Promise {
+ await upsertBudgetEntry(on.groceries, 2026, 10, 450, "Octobre");
+ await upsertBudgetEntry(on.groceries, 2026, 11, 470);
+ await upsertBudgetEntry(on.rent, 2026, 10, 1000);
+ await saveAsTemplate("Mois type", "Le budget d'un mois", [
+ { category_id: on.groceries, amount: 400 },
+ { category_id: on.rent, amount: 1000 },
+ ]);
+ const adjustment = await createAdjustment({
+ name: "Rattrapage",
+ description: "Crédit sur facture",
+ date: "2026-10-15",
+ is_recurring: true,
+ });
+ db.prepare("UPDATE adjustments SET recurrence_rule = $rule WHERE id = $id").run({
+ $rule: '{"every":"month"}',
+ $id: adjustment,
+ });
+ await createEntry({ adjustment_id: adjustment, category_id: on.electricity, amount: -30, description: "Crédit" });
+ await createEntry({ adjustment_id: adjustment, category_id: on.groceries, amount: 15 });
+}
+
+/** The two modes that carry the categories, and with them the budget. */
+const WITH_BUDGET = ["transactions_with_categories", "categories_only"] as const;
+type WithBudget = (typeof WITH_BUDGET)[number];
+
+/** The backup of `how`, as « Exporter » writes it and the import reads it back. */
+function budgetBackup(how: WithBudget): Promise {
+ return how === "categories_only" ? categoriesBackup() : jsonBackup(how);
+}
+
+/** The restore of the card for `how`, of a file of `formatVersion`. */
+function restoreBudgetBackup(
+ how: WithBudget,
+ data: ExportEnvelope["data"],
+ formatVersion = SREF_FORMAT_VERSION,
+): Promise {
+ return how === "categories_only"
+ ? importCategoriesOnly(data, formatVersion)
+ : importTransactionsWithCategories(data, "backup.json", formatVersion);
+}
+
+/**
+ * `data` as the previous version wrote it for `how`: format 2, without the
+ * three budget arrays, then read back as the import reads it.
+ */
+function previousVersionFile(how: ExportMode, data: ExportEnvelope["data"]) {
+ const older = { ...data };
+ delete older.budget_entries;
+ delete older.budget_templates;
+ delete older.adjustments;
+ const content = JSON.stringify({
+ export_type: how,
+ app_version: "0.17.2",
+ format_version: 2,
+ exported_at: "2026-10-18T12:00:00.000Z",
+ data: older,
+ });
+ return { content, ...parseImportedJson(content) };
+}
+
+/** The id of the template or the adjustment `name` in `db`. */
+function idOf(db: DatabaseSync, table: "budget_templates" | "adjustments", name: string): number {
+ return (db.prepare(`SELECT id FROM ${table} WHERE name = $name`).get({ $name: name }) as { id: number }).id;
+}
+
+const INVALID_BUDGET = "settings.dataManagement.import.errors.invalidBudgetRows";
+const NEWER_FORMAT = "settings.dataManagement.import.errors.newerFormat";
+
+/** The refusal `key` (text 9 or text 10). */
+function expectRefusalOf(key: string) {
+ return (error: unknown) => {
+ expect(error).toBeInstanceOf(SrefValidationError);
+ expect((error as SrefValidationError).i18nKey).toBe(key);
+ };
+}
+
+/** What `run` throws; fails when it throws nothing. */
+function thrownBy(run: () => unknown): unknown {
+ try {
+ run();
+ } catch (e) {
+ return e;
+ }
+ return expect.unreachable("should have been refused");
+}
+
+describe("restoring a backup with its budget, its templates and its adjustments (#520)", () => {
+ const SEED: BudgetCategories = { groceries: GROCERIES, rent: RENT, electricity: ELECTRICITY };
+ /** The budget of the profile when the backup is taken. */
+ let before: BudgetState;
+
+ beforeEach(async () => {
+ await writeBudget(profile, SEED);
+ before = budgetOf(profile);
+ expect(before.entries).toHaveLength(3);
+ expect(before.templates.map((t) => [t.name, t.entries.length])).toEqual([["Mois type", 2]]);
+ expect(before.adjustments.map((a) => [a.name, a.entries.length])).toEqual([["Rattrapage", 2]]);
+ });
+
+ it.each(WITH_BUDGET)(
+ "%s, same profile: the budget lines, the templates and the adjustments come back as they were",
+ async (how) => {
+ await restoreBudgetBackup(how, await budgetBackup(how));
+
+ expect(budgetOf(profile)).toEqual(before);
+ },
+ );
+
+ it.each(WITH_BUDGET)("%s, new profile: the same budget lines, templates and adjustments", async (how) => {
+ const data = await budgetBackup(how);
+ const fresh = use(open());
+
+ await restoreBudgetBackup(how, data);
+
+ expect(budgetOf(fresh)).toEqual(before);
+ });
+
+ it.each(WITH_BUDGET)("%s: the budget lines and the adjustments of the file replace those of the profile", async (how) => {
+ const data = await budgetBackup(how);
+ // Since the backup, on categories that come back: an amount changed, a line and an adjustment added.
+ await upsertBudgetEntry(GROCERIES, 2026, 10, 999);
+ await upsertBudgetEntry(ELECTRICITY, 2026, 12, 90);
+ const added = await createAdjustment({ name: "Ajouté", date: "2026-11-01", is_recurring: true });
+ await createEntry({ adjustment_id: added, category_id: RENT, amount: 50 });
+
+ await restoreBudgetBackup(how, data);
+
+ expect(budgetOf(profile)).toEqual(before);
+ });
+
+ it.each(WITH_BUDGET)(
+ "%s: a template of the file is updated by its name, its lines replaced; a template absent from the file keeps its header and its lines whose category comes back",
+ async (how) => {
+ const data = await budgetBackup(how);
+ // Since the backup: « Mois type » changed, and « Vacances » created with a line on a category the file does not hold.
+ const monthly = idOf(profile, "budget_templates", "Mois type");
+ profile.prepare("UPDATE budget_templates SET description = 'Changé' WHERE id = $id").run({ $id: monthly });
+ profile.prepare("DELETE FROM budget_template_entries WHERE template_id = $id").run({ $id: monthly });
+ profile
+ .prepare("INSERT INTO budget_template_entries (template_id, category_id, amount) VALUES ($id, $category, 80)")
+ .run({ $id: monthly, $category: ELECTRICITY });
+ const newer = category(profile, "Nouvelle");
+ await saveAsTemplate("Vacances", undefined, [
+ { category_id: GROCERIES, amount: 200 },
+ { category_id: newer, amount: 50 },
+ ]);
+
+ await restoreBudgetBackup(how, data);
+
+ expect(budgetOf(profile).templates).toEqual([
+ before.templates[0],
+ { name: "Vacances", description: null, entries: [{ category_id: GROCERIES, amount: 200 }] },
+ ]);
+ // Updated in place, under its own id.
+ expect(idOf(profile, "budget_templates", "Mois type")).toBe(monthly);
+ },
+ );
+
+ it("« Rétablir la sauvegarde »: the budget of the backup comes back", async () => {
+ const data = await exportData("transactions_with_categories");
+ await upsertBudgetEntry(ELECTRICITY, 2026, 12, 90);
+
+ const { reading } = await restoreTheBackup(data);
+
+ expect(reading.summary.formatVersion).toBe(SREF_FORMAT_VERSION);
+ expect(budgetOf(profile)).toEqual(before);
+ });
+
+ it.each(WITH_BUDGET)(
+ "%s, a backup of the previous version (format 2): the lines whose category comes back are kept as they were, the others go",
+ async (how) => {
+ const older = previousVersionFile(how, await budgetBackup(how));
+ expect(older.summary.formatVersion).toBe(2);
+ const kept = budgetRows(profile);
+ // Since the backup: a category the file does not hold, with a line of each kind.
+ const newer = category(profile, "Nouvelle");
+ await upsertBudgetEntry(newer, 2026, 10, 60);
+ profile
+ .prepare("INSERT INTO budget_template_entries (template_id, category_id, amount) VALUES ($id, $category, 25)")
+ .run({ $id: idOf(profile, "budget_templates", "Mois type"), $category: newer });
+ await createEntry({ adjustment_id: idOf(profile, "adjustments", "Rattrapage"), category_id: newer, amount: 5 });
+
+ await restoreBudgetBackup(how, older.envelope.data, older.summary.formatVersion);
+
+ expect(budgetOf(profile)).toEqual(before);
+ // Kept is untouched: the same ids, the same dates.
+ expect(budgetRows(profile)).toEqual(kept);
+ },
+ );
+
+ it("« Rétablir la sauvegarde » of a backup of the previous version: the lines whose category comes back are kept", async () => {
+ const older = previousVersionFile("transactions_with_categories", await exportData("transactions_with_categories"));
+ const kept = budgetRows(profile);
+
+ const { reading } = await restoreTheFile(older.content);
+
+ expect(reading.summary.formatVersion).toBe(2);
+ expect(budgetRows(profile)).toEqual(kept);
+ });
+
+ it("witness: « Transactions uniquement » carries no budget and leaves the profile's as it is", async () => {
+ const data = await jsonBackup("transactions_only");
+ expect([data.budget_entries, data.budget_templates, data.adjustments]).toEqual([undefined, undefined, undefined]);
+ const kept = budgetRows(profile);
+
+ await restore("transactions_only", data);
+
+ expect(budgetRows(profile)).toEqual(kept);
+ });
+});
+
+describe("a budget the restore could not write back, or a newer file, is refused before anything is deleted (#520)", () => {
+ let before: BudgetState;
+
+ beforeEach(async () => {
+ await writeBudget(profile, { groceries: GROCERIES, rent: RENT, electricity: ELECTRICITY });
+ before = budgetOf(profile);
+ });
+
+ it.each(WITH_BUDGET)(
+ "%s: a budget line that names a category missing from the file is refused at the parse and at the head of the restore",
+ async (how) => {
+ const full = await budgetBackup(how);
+ const [first, ...others] = full.budget_entries ?? [];
+ const data = { ...full, budget_entries: [{ ...first, category_id: 999_999 }, ...others] };
+ const transactions = rows(profile);
+ const categories = count(profile, "categories");
+
+ expectRefusalOf(INVALID_BUDGET)(thrownBy(() => parseImportedJson(serializeToJson(how, data, "0.17.2"))));
+ await restoreBudgetBackup(how, data).then(
+ () => expect.unreachable("the restore should have been refused"),
+ expectRefusalOf(INVALID_BUDGET),
+ );
+
+ expect(budgetOf(profile)).toEqual(before);
+ expect(rows(profile)).toEqual(transactions);
+ expect(count(profile, "categories")).toBe(categories);
+ },
+ );
+
+ describe.each(WITH_BUDGET)("%s, a file of format 3 that lacks one of its three arrays", (how) => {
+ it.each(["budget_entries", "budget_templates", "adjustments"] as const)(
+ "without %s: refused at the parse and at the head of the restore, the budget never emptied",
+ async (array) => {
+ const data = { ...(await budgetBackup(how)) };
+ delete data[array];
+
+ expectRefusalOf(INVALID_BUDGET)(thrownBy(() => parseImportedJson(serializeToJson(how, data, "0.17.2"))));
+ await restoreBudgetBackup(how, data).then(
+ () => expect.unreachable("the restore should have been refused"),
+ expectRefusalOf(INVALID_BUDGET),
+ );
+
+ expect(budgetOf(profile)).toEqual(before);
+ },
+ );
+ });
+
+ it("a file of a newer version (format 4) is refused in the card and in « Rétablir la sauvegarde », and nothing is deleted", async () => {
+ const data = await exportData("transactions_with_categories");
+ const content = JSON.stringify({
+ export_type: "transactions_with_categories",
+ app_version: "9.0.0",
+ format_version: 4,
+ exported_at: "2027-01-01T00:00:00.000Z",
+ data,
+ });
+ const transactions = rows(profile);
+
+ // The card: refused at the parse, and again at the head of each restore.
+ expectRefusalOf(NEWER_FORMAT)(thrownBy(() => parseImportedJson(content)));
+ await importTransactionsWithCategories(data, "backup.json", 4).then(
+ () => expect.unreachable("the restore should have been refused"),
+ expectRefusalOf(NEWER_FORMAT),
+ );
+ await importCategoriesOnly(data, 4).then(
+ () => expect.unreachable("the restore should have been refused"),
+ expectRefusalOf(NEWER_FORMAT),
+ );
+
+ // « Rétablir la sauvegarde »: refused at the reading, before its second confirmation.
+ invoke.mockImplementation(async (cmd: string) => {
+ if (cmd === "read_import_file") return content;
+ throw new Error(`unexpected invoke: ${cmd}`);
+ });
+ await readBackup("/tmp/backup.sref", null).then(
+ () => expect.unreachable("the reading should have been refused"),
+ expectRefusalOf(NEWER_FORMAT),
+ );
+
+ expect(budgetOf(profile)).toEqual(before);
+ expect(rows(profile)).toEqual(transactions);
+ });
+});
+
+describe("a restore with categories keeps the translation key of each category (#520)", () => {
+ /** Every category of `db` with its translation key. */
+ const keysOf = (db: DatabaseSync) =>
+ all<{ id: number; i18n_key: string | null }>(db, "SELECT id, i18n_key FROM categories ORDER BY id");
+
+ it.each(WITH_CATEGORIES)("%s, same profile: every category comes back with its i18n_key", async (how) => {
+ const before = keysOf(profile);
+ // The standard seed names its categories by key: the English interface reads them.
+ expect(before.filter((c) => c.i18n_key !== null).length).toBeGreaterThan(100);
+
+ await restoreCategoriesBy(how);
+
+ expect(keysOf(profile)).toEqual(before);
+ });
+
+ it.each(WITH_BUDGET)("%s, new profile: the same keys", async (how) => {
+ const before = keysOf(profile);
+ const data = await budgetBackup(how);
+ const fresh = use(open());
+
+ await restoreBudgetBackup(how, data);
+
+ expect(keysOf(fresh)).toEqual(before);
+ });
+});
+
+describe("« Rétablir la sauvegarde » after the categories migration (#520)", () => {
+ /** « Épicerie », « Loyer » and « Électricité » of the former seed, which « Réinitialiser » puts back. */
+ const V2: BudgetCategories = { groceries: 22, rent: 20, electricity: 21 };
+ const PROFILE: Profile = {
+ id: "p1",
+ name: "Profil",
+ color: "#f59e0b",
+ pin_hash: null,
+ db_filename: "profil.db",
+ created_at: "2026-01-01T00:00:00Z",
+ };
+
+ /**
+ * The migration as its page runs it (`CategoriesMigrationPage`): the backup
+ * written and verified first, then the plan computed from the profile and
+ * applied. Returns the backup as it was written.
+ */
+ async function migrate(): Promise {
+ let written = "";
+ invoke.mockImplementation(async (cmd: string, args?: { content?: string }) => {
+ if (cmd === "ensure_backup_dir") return "/tmp/sr-backups";
+ if (cmd === "write_export_file") {
+ written = args?.content ?? "";
+ return undefined;
+ }
+ if (cmd === "read_import_file") return written;
+ if (cmd === "get_file_size") return written.length;
+ throw new Error(`unexpected invoke: ${cmd}`);
+ });
+ const backup = await createPreMigrationBackup({ profile: PROFILE });
+ const plan = computeMigrationPlan({
+ v2Categories: all<{ id: number; name: string; parent_id: number | null }>(
+ profile,
+ "SELECT id, name, parent_id FROM categories WHERE is_active = 1",
+ ),
+ keywords: all<{ id: number; keyword: string; category_id: number }>(
+ profile,
+ "SELECT id, keyword, category_id FROM keywords WHERE is_active = 1",
+ ),
+ transactions: all<{ id: number; description: string; category_id: number | null; supplier_id: number | null }>(
+ profile,
+ "SELECT id, description, category_id, supplier_id FROM transactions",
+ ),
+ suppliers: all<{ id: number; name: string }>(profile, "SELECT id, name FROM suppliers WHERE is_active = 1"),
+ });
+ const outcome = await applyMigration(plan, backup);
+ expect(outcome.succeeded, outcome.error).toBe(true);
+ return written;
+ }
+
+ /** The budget of the former state, when the backup is taken. */
+ let former: BudgetState;
+
+ beforeEach(async () => {
+ // A profile on the former categories: « Réinitialiser » puts their seed back.
+ const { reinitializeCategories } = await import("../services/categoryService");
+ await reinitializeCategories();
+ await writeBudget(profile, V2);
+ former = budgetOf(profile);
+ });
+
+ it("a backup of format 3: the budget, the templates and the adjustments of the former state come back exactly", async () => {
+ const backup = await migrate();
+ expect(JSON.parse(backup).format_version).toBe(SREF_FORMAT_VERSION);
+ // The migration moved the budget onto the standard categories.
+ expect(budgetOf(profile).entries.every((entry) => entry.category_id >= 1000)).toBe(true);
+
+ await restoreTheFile(backup);
+
+ expect(budgetOf(profile)).toEqual(former);
+ });
+
+ it("a backup of the previous version (format 2): the lines the migration moved onto the standard categories do not come back (ADR 0025)", async () => {
+ const backup = await migrate();
+ const older = previousVersionFile("transactions_with_categories", JSON.parse(backup).data);
+
+ const { reading } = await restoreTheFile(older.content);
+
+ expect(reading.summary.formatVersion).toBe(2);
+ const after = budgetOf(profile);
+ expect(after.entries).toEqual([]);
+ expect(after.templates).toEqual(former.templates.map((template) => ({ ...template, entries: [] })));
+ // The migration leaves the adjustment lines on the former categories, which come back with the file.
+ expect(after.adjustments).toEqual(former.adjustments);
+ });
+});
diff --git a/src/components/settings/CategoriesMigrationRestoreModal.tsx b/src/components/settings/CategoriesMigrationRestoreModal.tsx
index 31866f6..ba3a6ad 100644
--- a/src/components/settings/CategoriesMigrationRestoreModal.tsx
+++ b/src/components/settings/CategoriesMigrationRestoreModal.tsx
@@ -13,7 +13,10 @@ import {
type RestorableMigrationJournal,
type RestoreResult,
} from "../../services/categoryRestoreService";
-import { SrefValidationError } from "../../services/dataExportService";
+import {
+ BUDGET_SREF_FORMAT_VERSION,
+ SrefValidationError,
+} from "../../services/dataExportService";
// -----------------------------------------------------------------------------
// Confirmation modal used by both the in-window banner and the permanent
@@ -27,7 +30,9 @@ import { SrefValidationError } from "../../services/dataExportService";
// 3. If the file is SREF-encrypted, prompt the PIN; otherwise proceed.
// 4. Read the file (`readBackup`): nothing is written yet.
// 5. Second confirmation: what the restore will lose for good, the Bilan
-// transfers it will unlink, before the user clicks "Restore" again.
+// transfers it will unlink, and, from a backup older than the budget in
+// backups, the budget lines whose category does not come back (#520),
+// before the user clicks "Restore" again.
// 6. Run `applyBackup`, then show "Backup restored" with what it did. The
// app reloads only on "Close", so that every page sees the restored state
// after the user has read it.
@@ -308,6 +313,12 @@ export default function CategoriesMigrationRestoreModal({
{reading.filePath}
+ {/* A backup older than the budget in backups brings none back (#520) */}
+ {reading.summary.formatVersion < BUDGET_SREF_FORMAT_VERSION && (
+
+ {t("settings.categoriesCard.restoreModal.legacyBudgetNote")}
+
+ )}
{reading.unlinkedTransfers > 0 && (
{t("settings.categoriesCard.restoreModal.unlinkedTransfersPreview", {
diff --git a/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts b/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts
index 380567d..5fc58ca 100644
--- a/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts
+++ b/src/components/settings/CategoriesMigrationRestoreModal.wiring.test.ts
@@ -1,8 +1,8 @@
// CategoriesMigrationRestoreModal — what « Rétablir la sauvegarde » shows when
// the import boundary refuses the backup (#518), and its steps once the file is
// read (#521): a second confirmation that announces the Bilan transfers the
-// restore will unlink, then « Sauvegarde rétablie », and a reload only on
-// « Fermer ».
+// restore will unlink, and says when the backup holds no budget (#520), then
+// « Sauvegarde rétablie », and a reload only on « Fermer ».
//
// 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
@@ -60,17 +60,26 @@ const JOURNAL: RestorableMigrationJournal = {
const PROPS = { journal: JOURNAL, onClose: vi.fn(), onRestored: vi.fn() };
-/** The backup as `readBackup` returns it, announcing `unlinkedTransfers`. */
-function readingOf(unlinkedTransfers: number): BackupReading {
+/**
+ * The backup as `readBackup` returns it, announcing `unlinkedTransfers`, of
+ * `formatVersion`: 3 carries the budget, an older one does not (#520).
+ */
+function readingOf(unlinkedTransfers: number, formatVersion = 3): BackupReading {
return {
filePath: JOURNAL.backupPath,
filename: "profile_avant-migration.sref",
envelope: {
export_type: "transactions_with_categories",
app_version: "0.17.2",
- format_version: 2,
+ format_version: formatVersion,
exported_at: "2026-10-01T10:00:00Z",
- data: { categories: [], suppliers: [], keywords: [], transactions: [] },
+ data: {
+ categories: [],
+ suppliers: [],
+ keywords: [],
+ transactions: [],
+ ...(formatVersion >= 3 ? { budget_entries: [], budget_templates: [], adjustments: [] } : {}),
+ },
},
summary: {
type: "transactions_with_categories",
@@ -80,7 +89,10 @@ function readingOf(unlinkedTransfers: number): BackupReading {
transactionsCount: 0,
importSourcesCount: 0,
importTemplatesCount: 0,
- formatVersion: 2,
+ budgetEntriesCount: 0,
+ budgetTemplatesCount: 0,
+ adjustmentsCount: 0,
+ formatVersion,
},
unlinkedTransfers,
};
@@ -263,6 +275,27 @@ describe("CategoriesMigrationRestoreModal — a second confirmation, then « Sau
expect(PROPS.onClose).not.toHaveBeenCalled();
});
+ it.each([2, 1])("a backup of format %i: the second confirmation says it holds no budget (#520)", async (formatVersion) => {
+ service.readBackup.mockResolvedValue(readingOf(0, formatVersion));
+
+ await confirm();
+
+ expect(texts(render())).toContain(label("legacyBudgetNote"));
+ expect(service.applyBackup).not.toHaveBeenCalled();
+ });
+
+ it("a backup of format 3 carries its budget: no note (#520)", async () => {
+ service.readBackup.mockResolvedValue(readingOf(0, 3));
+
+ await confirm();
+
+ expect(texts(render()).join(" ")).not.toContain("legacyBudgetNote");
+ // Nor once restored.
+ service.applyBackup.mockResolvedValue(resultOf(0));
+ await confirm();
+ expect(texts(render()).join(" ")).not.toContain("legacyBudgetNote");
+ });
+
it("an encrypted backup: the PIN first, then the reading and the second confirmation", async () => {
service.isFileEncrypted.mockResolvedValue(true);
service.readBackup.mockResolvedValue(readingOf(1));
diff --git a/src/components/settings/ImportConfirmModal.render.test.tsx b/src/components/settings/ImportConfirmModal.render.test.tsx
index a879caa..12945e9 100644
--- a/src/components/settings/ImportConfirmModal.render.test.tsx
+++ b/src/components/settings/ImportConfirmModal.render.test.tsx
@@ -1,9 +1,10 @@
// ImportConfirmModal — the confirmation of « Importer » announces the Bilan
-// transfers the restore will unlink, before anything is deleted (#521). No
-// jsdom: react-dom/server renders the initial markup in vitest's node
-// environment. It cannot render a portal, and the window is one: `createPortal`
-// becomes the identity, and `document` a stub for the `document.body` it is
-// given.
+// transfers the restore will unlink, before anything is deleted (#521), and
+// what becomes of the budget (#520): the lines a file of format 3 brings back,
+// or, for an older file, the note that it holds none. No jsdom:
+// react-dom/server renders the initial markup in vitest's node environment. It
+// cannot render a portal, and the window is one: `createPortal` becomes the
+// identity, and `document` a stub for the `document.body` it is given.
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
import type { ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
@@ -25,7 +26,10 @@ const SUMMARY: ImportSummary = {
transactionsCount: 12,
importSourcesCount: 0,
importTemplatesCount: 0,
- formatVersion: 2,
+ budgetEntriesCount: 0,
+ budgetTemplatesCount: 0,
+ adjustmentsCount: 0,
+ formatVersion: 3,
};
beforeAll(() => {
@@ -36,10 +40,10 @@ afterAll(() => {
vi.unstubAllGlobals();
});
-const markup = (importType: ExportMode, unlinkedTransfers: number) =>
+const markup = (importType: ExportMode, unlinkedTransfers: number, summary: Partial = {}) =>
renderToStaticMarkup(
/>,
);
+const KEY = "settings.dataManagement.import";
+/** The budget a file carries, as its summary counts it. */
+const WITH_BUDGET = { budgetEntriesCount: 24, budgetTemplatesCount: 2, adjustmentsCount: 3 };
+
describe("ImportConfirmModal — the Bilan transfers the restore will unlink (#521)", () => {
it.each<[ExportMode, number]>([
["transactions_with_categories", 1],
@@ -64,3 +72,46 @@ describe("ImportConfirmModal — the Bilan transfers the restore will unlink (#5
expect(html).toContain("t(settings.dataManagement.import.irreversibleWarning)");
});
});
+
+describe("ImportConfirmModal — the budget, its templates and the adjustments (#520)", () => {
+ it.each<[ExportMode, string]>([
+ ["categories_only", "willDeleteCategories"],
+ ["transactions_with_categories", "willDeleteAll"],
+ ])("%s: names them among what is deleted (%s)", (importType, willDelete) => {
+ expect(markup(importType, 0)).toContain(`t(${KEY}.${willDelete})`);
+ });
+
+ it.each(["categories_only", "transactions_with_categories"])(
+ "%s, format 3: counts the budget lines, templates and adjustments the file brings back, no note",
+ (importType) => {
+ const html = markup(importType, 0, WITH_BUDGET);
+ expect(html).toContain(`t(${KEY}.countBudgetEntries[count=24])`);
+ expect(html).toContain(`t(${KEY}.countBudgetTemplates[count=2])`);
+ expect(html).toContain(`t(${KEY}.countAdjustments[count=3])`);
+ expect(html).not.toContain("legacyBudgetNote");
+ },
+ );
+
+ it("format 3, a profile without a budget: no count, no note", () => {
+ const html = markup("transactions_with_categories", 0);
+ expect(html).not.toMatch(/countBudgetEntries|countBudgetTemplates|countAdjustments|legacyBudgetNote/);
+ });
+
+ it.each<[ExportMode, number]>([
+ ["categories_only", 2],
+ ["transactions_with_categories", 2],
+ ["transactions_with_categories", 1],
+ ])("%s, format %i: the note says the file holds no budget, next to the warning, and nothing is counted", (importType, formatVersion) => {
+ const html = markup(importType, 0, { ...WITH_BUDGET, formatVersion });
+ expect(html).toContain(`t(${KEY}.legacyBudgetNote)`);
+ expect(html).toContain(`t(${KEY}.irreversibleWarning)`);
+ expect(html).not.toMatch(/countBudgetEntries|countBudgetTemplates|countAdjustments/);
+ });
+
+ it("« Transactions uniquement » leaves the budget alone: neither count nor note, whatever the format", () => {
+ for (const formatVersion of [1, 2, 3]) {
+ const html = markup("transactions_only", 0, { ...WITH_BUDGET, formatVersion });
+ expect(html, `format ${formatVersion}`).not.toMatch(/countBudgetEntries|countBudgetTemplates|countAdjustments|legacyBudgetNote/);
+ }
+ });
+});
diff --git a/src/components/settings/ImportConfirmModal.tsx b/src/components/settings/ImportConfirmModal.tsx
index cfadf17..b693151 100644
--- a/src/components/settings/ImportConfirmModal.tsx
+++ b/src/components/settings/ImportConfirmModal.tsx
@@ -2,7 +2,11 @@ import { useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { AlertTriangle, X, Loader2 } from "lucide-react";
-import type { ImportSummary, ExportMode } from "../../services/dataExportService";
+import {
+ BUDGET_SREF_FORMAT_VERSION,
+ type ImportSummary,
+ type ExportMode,
+} from "../../services/dataExportService";
interface ImportConfirmModalProps {
summary: ImportSummary;
@@ -72,6 +76,33 @@ export default function ImportConfirmModal({
);
}
+ // The budget travels with the categories (#520). A file of format 3 or later
+ // brings it back, and says how much of it; an older one holds none, and the
+ // note says that the current lines whose category comes back are kept.
+ const carriesBudget = importType !== "transactions_only";
+ const legacyBudget =
+ carriesBudget && summary.formatVersion < BUDGET_SREF_FORMAT_VERSION;
+ if (carriesBudget && !legacyBudget) {
+ if (summary.budgetEntriesCount > 0)
+ willImport.push(
+ t("settings.dataManagement.import.countBudgetEntries", {
+ count: summary.budgetEntriesCount,
+ })
+ );
+ if (summary.budgetTemplatesCount > 0)
+ willImport.push(
+ t("settings.dataManagement.import.countBudgetTemplates", {
+ count: summary.budgetTemplatesCount,
+ })
+ );
+ if (summary.adjustmentsCount > 0)
+ willImport.push(
+ t("settings.dataManagement.import.countAdjustments", {
+ count: summary.adjustmentsCount,
+ })
+ );
+ }
+
// The import configurations travel with both transaction modes (#331). They
// are listed so the user sees that a restore now brings its sources back
// rather than leaving every one of them to reconfigure.
@@ -139,9 +170,15 @@ export default function ImportConfirmModal({
- {/* Warning, and what the restore loses for good: the Bilan transfers
- whose transaction does not come back as it was (#521) */}
+ {/* Warning, and what the restore loses for good: the budget lines a
+ file older than the budget does not bring back (#520), the Bilan
+ transfers whose transaction does not come back as it was (#521) */}
+ {legacyBudget && (
+
+ {t("settings.dataManagement.import.legacyBudgetNote")}
+
+ )}
{unlinkedTransfers > 0 && (
{t("settings.dataManagement.import.unlinkedTransfersPreview", {
diff --git a/src/hooks/useDataExport.test.ts b/src/hooks/useDataExport.test.ts
new file mode 100644
index 0000000..ff81243
--- /dev/null
+++ b/src/hooks/useDataExport.test.ts
@@ -0,0 +1,105 @@
+// useDataExport — « Exporter » writes the arrays `collectExportData` gathers
+// for its mode (#520): the budget, its templates and the adjustments with the
+// categories, the same arrays as the backup taken before the categories
+// migration. No jsdom: the hook runs as a plain function under the shared
+// harness (src/test/hookHarness.ts, #409); the file dialog and the write are
+// fakes, the serialization is real.
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
+const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
+vi.mock("@tauri-apps/api/core", () => ({ invoke }));
+vi.mock("@tauri-apps/api/app", () => ({ getVersion: vi.fn(async () => "0.17.2") }));
+const { collectExportData } = vi.hoisted(() => ({ collectExportData: vi.fn() }));
+vi.mock("../services/dataExportService", async (orig) => ({
+ ...(await orig()),
+ collectExportData,
+}));
+
+import { hookHarness } from "../test/hookHarness";
+import { useDataExport } from "./useDataExport";
+import { SREF_FORMAT_VERSION, type ExportEnvelope, type ExportMode } from "../services/dataExportService";
+
+const harness = hookHarness();
+
+/** One render of the mounted hook. */
+const render = () => harness.render(() => useDataExport());
+
+const TRANSACTION = {
+ id: 1,
+ date: "2026-10-04",
+ description: "EPICERIE",
+ amount: -50,
+ category_id: 1111,
+ category_name: "Épicerie",
+ original_description: null,
+ notes: null,
+ is_manually_categorized: 0,
+ is_split: 0,
+ parent_transaction_id: null,
+};
+
+/** What `collectExportData` gathers for `mode`, the budget with the categories. */
+function gathered(mode: ExportMode): ExportEnvelope["data"] {
+ const categories = {
+ categories: [],
+ suppliers: [],
+ keywords: [],
+ budget_entries: [{ category_id: 1111, year: 2026, month: 10, amount: 450, notes: null }],
+ budget_templates: [{ name: "Mois type", description: null, entries: [{ category_id: 1111, amount: 400 }] }],
+ adjustments: [],
+ };
+ const transactions = { transactions: [TRANSACTION], import_sources: [], import_config_templates: [] };
+ if (mode === "categories_only") return categories;
+ if (mode === "transactions_only") return transactions;
+ return { ...categories, ...transactions };
+}
+
+/** The content « Exporter » writes, once the user picked `path`. */
+function saving(path: string): () => string {
+ let written = "";
+ invoke.mockImplementation(async (cmd: string, args?: { content?: string }) => {
+ if (cmd === "pick_save_file") return path;
+ if (cmd === "write_export_file") {
+ written = args?.content ?? "";
+ return undefined;
+ }
+ throw new Error(`unexpected invoke: ${cmd}`);
+ });
+ return () => written;
+}
+
+beforeEach(() => {
+ harness.clear();
+ invoke.mockReset();
+ collectExportData.mockReset();
+ collectExportData.mockImplementation(async (mode: ExportMode) => gathered(mode));
+});
+
+describe("useDataExport writes what collectExportData gathers for the mode (#520)", () => {
+ it.each(["transactions_with_categories", "categories_only", "transactions_only"])(
+ "%s: the JSON carries the arrays of its mode, at the format of this build",
+ async (mode) => {
+ const written = saving("/tmp/export.json");
+
+ await render().performExport(mode, "json");
+
+ expect(collectExportData).toHaveBeenCalledWith(mode);
+ const envelope = JSON.parse(written());
+ expect(envelope.export_type).toBe(mode);
+ expect(envelope.format_version).toBe(SREF_FORMAT_VERSION);
+ expect(envelope.data).toEqual(gathered(mode));
+ expect(render().state.status).toBe("success");
+ },
+ );
+
+ it("a CSV writes the transactions of the mode, as before", async () => {
+ const written = saving("/tmp/export.csv");
+
+ await render().performExport("transactions_only", "csv");
+
+ const [header, row] = written().split(/\r?\n/);
+ expect(header.split(",")[0]).toBe("id");
+ expect(row.split(",").slice(0, 3)).toEqual(["1", "2026-10-04", "EPICERIE"]);
+ });
+});
diff --git a/src/hooks/useDataExport.ts b/src/hooks/useDataExport.ts
index 184276d..5830cf1 100644
--- a/src/hooks/useDataExport.ts
+++ b/src/hooks/useDataExport.ts
@@ -2,12 +2,7 @@ import { useReducer, useCallback } from "react";
import { invoke } from "@tauri-apps/api/core";
import { getVersion } from "@tauri-apps/api/app";
import {
- getExportCategories,
- getExportSuppliers,
- getExportKeywords,
- getExportTransactions,
- getExportImportSources,
- getExportImportTemplates,
+ collectExportData,
serializeToJson,
serializeTransactionsToCsv,
type ExportMode,
@@ -54,27 +49,16 @@ export function useDataExport() {
try {
const appVersion = await getVersion();
- // Gather data based on mode
- const data: Record = {};
- if (mode === "transactions_with_categories" || mode === "categories_only") {
- data.categories = await getExportCategories();
- data.suppliers = await getExportSuppliers();
- data.keywords = await getExportKeywords();
- }
- if (mode === "transactions_with_categories" || mode === "transactions_only") {
- data.transactions = await getExportTransactions();
- // The import configurations travel with the transaction modes — the
- // two the restore wipes `import_sources` for. A categories-only
- // backup neither carries them nor touches them (#331).
- data.import_sources = await getExportImportSources();
- data.import_config_templates = await getExportImportTemplates();
- }
+ // Gather data based on mode: the arrays of each mode, the import
+ // configurations (#331) and the budget (#520) among them, are those
+ // of the backup taken before the categories migration.
+ const data = await collectExportData(mode);
// Serialize
let content: string;
let defaultExt: string;
if (format === "csv") {
- content = serializeTransactionsToCsv(data.transactions as never[]);
+ content = serializeTransactionsToCsv(data.transactions ?? []);
defaultExt = "csv";
} else {
content = serializeToJson(mode, data, appVersion);
diff --git a/src/hooks/useDataImport.test.ts b/src/hooks/useDataImport.test.ts
index 669df9e..ef97918 100644
--- a/src/hooks/useDataImport.test.ts
+++ b/src/hooks/useDataImport.test.ts
@@ -44,15 +44,42 @@ const TRANSACTION = {
parent_transaction_id: null,
};
+/** The budget arrays of the two modes that carry the categories, from format 3 on (#520). */
+const NO_BUDGET = { budget_entries: [], budget_templates: [], adjustments: [] };
+
+/** The data of a backup of `mode`, as « Exporter » gathers it. */
+function dataOf(mode: ExportMode) {
+ return mode === "categories_only"
+ ? { categories: [], suppliers: [], keywords: [], ...NO_BUDGET }
+ : mode === "transactions_only"
+ ? { transactions: [TRANSACTION], import_sources: [], import_config_templates: [] }
+ : {
+ categories: [],
+ suppliers: [],
+ keywords: [],
+ transactions: [TRANSACTION],
+ import_sources: [],
+ import_config_templates: [],
+ ...NO_BUDGET,
+ };
+}
+
/** A backup of `mode`, as « Exporter » writes it. */
function backupOf(mode: ExportMode): string {
- const data =
- mode === "categories_only"
- ? { categories: [], suppliers: [], keywords: [] }
- : mode === "transactions_only"
- ? { transactions: [TRANSACTION], import_sources: [], import_config_templates: [] }
- : { categories: [], suppliers: [], keywords: [], transactions: [TRANSACTION], import_sources: [], import_config_templates: [] };
- return serializeToJson(mode, data, "0.17.2");
+ return serializeToJson(mode, dataOf(mode), "0.17.2");
+}
+
+/** A backup of `mode` as the previous version wrote it: format 2, no budget. */
+function previousVersionBackupOf(mode: ExportMode): string {
+ const data: Record = { ...dataOf(mode) };
+ for (const array of Object.keys(NO_BUDGET)) delete data[array];
+ return JSON.stringify({
+ export_type: mode,
+ app_version: "0.17.2",
+ format_version: 2,
+ exported_at: "2026-10-18T12:00:00.000Z",
+ data,
+ });
}
/** The file the user picks: `content`, encrypted or not. */
@@ -143,6 +170,30 @@ describe("useDataImport — the outcome of the restore reaches the success state
expect(harness.dispatch).toHaveBeenCalledWith({ type: "IMPORT_SUCCESS", outcome });
});
+ it.each<[string, () => string, number]>([
+ ["this version's backup", () => backupOf("transactions_with_categories"), 3],
+ ["a backup of the previous version", () => previousVersionBackupOf("transactions_with_categories"), 2],
+ ])("transactions_with_categories, %s: the restore is given the format the file declares (%i) (#520)", async (_label, file, formatVersion) => {
+ picking(file());
+ await render().pickAndRead();
+
+ await render().executeImport();
+
+ expect(restore.importTransactionsWithCategories).toHaveBeenCalledWith(expect.anything(), "backup.json", formatVersion);
+ });
+
+ it.each<[string, () => string, number]>([
+ ["this version's backup", () => backupOf("categories_only"), 3],
+ ["a backup of the previous version", () => previousVersionBackupOf("categories_only"), 2],
+ ])("categories_only, %s: the restore is given the format the file declares (%i) (#520)", async (_label, file, formatVersion) => {
+ picking(file());
+ await render().pickAndRead();
+
+ await render().executeImport();
+
+ expect(restore.importCategoriesOnly).toHaveBeenCalledWith(expect.anything(), formatVersion);
+ });
+
it("a new file starts without the outcome of the last restore", async () => {
restore.importTransactionsOnly.mockResolvedValue({ unlinkedTransfers: 2, uncategorizedTransactions: 0 });
picking(backupOf("transactions_only"));
diff --git a/src/hooks/useDataImport.ts b/src/hooks/useDataImport.ts
index b7249ed..e9caaa4 100644
--- a/src/hooks/useDataImport.ts
+++ b/src/hooks/useDataImport.ts
@@ -210,17 +210,20 @@ export function useDataImport() {
);
const executeImport = useCallback(async () => {
- if (!state.parsedData || !state.importType) return;
+ if (!state.parsedData || !state.importType || !state.summary) return;
dispatch({ type: "IMPORT_START" });
const filename = state.filePath?.split(/[/\\]/).pop() ?? "unknown";
+ // The format the file declares, read at the parse: it says whether the
+ // file carries the budget (#520).
+ const { formatVersion } = state.summary;
try {
let outcome: RestoreOutcome;
switch (state.importType) {
case "categories_only":
- outcome = await importCategoriesOnly(state.parsedData);
+ outcome = await importCategoriesOnly(state.parsedData, formatVersion);
break;
case "transactions_with_categories":
- outcome = await importTransactionsWithCategories(state.parsedData, filename);
+ outcome = await importTransactionsWithCategories(state.parsedData, filename, formatVersion);
break;
case "transactions_only":
outcome = await importTransactionsOnly(state.parsedData, filename);
@@ -230,7 +233,7 @@ export function useDataImport() {
} catch (e) {
dispatch({ type: "IMPORT_ERROR", error: describeError(e) });
}
- }, [state.parsedData, state.importType, state.filePath, describeError]);
+ }, [state.parsedData, state.importType, state.summary, state.filePath, describeError]);
const reset = useCallback(() => dispatch({ type: "RESET" }), []);
diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json
index 89fae93..99ad5e2 100644
--- a/src/i18n/locales/en.json
+++ b/src/i18n/locales/en.json
@@ -435,7 +435,7 @@
"deleteConfirm": "Are you sure you want to delete this category? Its children will be promoted to top-level.",
"deleteBlocked": "Cannot delete: this category or its children are used by {{count}} transaction(s).",
"reinitialize": "Re-initialize",
- "reinitializeConfirm": "Reset all categories and keywords to their default values? Transaction categories will be unlinked. This cannot be undone.",
+ "reinitializeConfirm": "Reset all categories and keywords to their default values? Transaction categories will be unlinked, and the budget, budget templates, and adjustments will be erased. This cannot be undone.",
"noParent": "No parent (top-level)",
"isInputable": "Allow input",
"isInputableHint": "Uncheck to hide from budget and transaction dropdowns",
@@ -761,9 +761,9 @@
"decrypt": "Decrypt",
"confirmTitle": "Replace Data",
"willDeleteLabel": "The following data will be deleted:",
- "willDeleteCategories": "All categories, suppliers, and keywords",
+ "willDeleteCategories": "All categories, suppliers, and keywords, along with the budget, budget templates, and adjustments",
"willDeleteTransactions": "All transactions and import history",
- "willDeleteAll": "All transactions, categories, suppliers, keywords, and import history",
+ "willDeleteAll": "All transactions, categories, suppliers, keywords, and import history, along with the budget, budget templates, and adjustments",
"willImportLabel": "The following data will be imported:",
"countCategories": "{{count}} category(ies)",
"countSuppliers": "{{count}} supplier(s)",
@@ -771,6 +771,10 @@
"countTransactions": "{{count}} transaction(s)",
"countImportSources": "{{count}} import source(s)",
"countImportTemplates": "{{count}} import template(s)",
+ "countBudgetEntries": "{{count}} budget line(s)",
+ "countBudgetTemplates": "{{count}} budget template(s)",
+ "countAdjustments": "{{count}} adjustment(s)",
+ "legacyBudgetNote": "This backup predates budgets in backups: it holds no budget, budget templates, or adjustments. Current lines whose category comes back are kept; the others are deleted.",
"irreversibleWarning": "This action is irreversible. All existing data of the selected type will be permanently deleted and replaced.",
"typeToConfirm": "Type \"{{word}}\" to confirm:",
"confirmWord": "REPLACE",
@@ -786,7 +790,9 @@
"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.",
"orphanSplitLines": "This file cannot be imported: some split lines cannot find their original transaction. Use a JSON export. Nothing has been modified.",
- "danglingCategoryReference": "This file cannot be imported: some categories, keywords, or suppliers refer to a category missing from the file. Nothing has been modified."
+ "danglingCategoryReference": "This file cannot be imported: some categories, keywords, or suppliers refer to a category missing from the file. Nothing has been modified.",
+ "invalidBudgetRows": "This file cannot be imported: some budget, budget template, or adjustment lines are invalid or refer to a category missing from the file. Nothing has been modified.",
+ "newerFormat": "This file comes from a newer version of Simpl'Résultat. Update the app to import it. Nothing has been modified."
}
}
},
@@ -827,6 +833,7 @@
"retry": "Try again",
"restoring": "Restoring your profile — do not close the application...",
"reading": "Reading the backup...",
+ "legacyBudgetNote": "This backup predates budgets in backups: it holds no budget, budget templates, or adjustments. Current lines whose category comes back are kept; the others are deleted.",
"unlinkedTransfersPreview_one": "{{count}} Balance transfer will not find its transaction and will be unlinked.",
"unlinkedTransfersPreview_other": "{{count}} Balance transfers will not find their transaction and will be unlinked.",
"doneTitle": "Backup restored",
@@ -1154,7 +1161,7 @@
"Save your configuration as a template so you don't have to reconfigure each time. A template initialises a source; editing it afterwards changes no source you have already configured.",
"Files already imported are marked with a badge — re-importing them will trigger duplicate detection",
"You can delete an import from the history to remove all its transactions",
- "Your import sources and templates are now part of the encrypted backup: restoring a backup no longer forces you to reconfigure everything",
+ "Your import sources and templates are now part of the encrypted backup, as are your budget, budget templates, and adjustments: restoring a backup no longer forces you to reconfigure everything",
"If CSV files sit directly in the import folder, a warning names them: move them into a subfolder per account",
"A source is named after its subfolder"
]
@@ -1353,7 +1360,7 @@
"Update check on request, with one-click install",
"Application logs viewable with level filters, copy, and clear",
"Version history: the installed version's notes show right away, other versions are folded and unfold with a click on their number, or all together with \"Expand all\"",
- "Data export (transactions, categories, or both) in JSON or CSV format",
+ "Data export (transactions, categories, or both) in JSON or CSV format; with the categories, the export also carries the budget, budget templates, and adjustments",
"Data import from a previously exported file",
"Optional AES-256-GCM encryption for exported files",
"Optional feedback submission to feedback.lacompagniemaximus.com (on request, after a consent prompt)",
@@ -1379,7 +1386,8 @@
"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.",
"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",
- "Restoring a backup keeps the Balance sheet transfers whose transaction comes back unchanged (same number, date, amount and description); the others are unlinked, and the confirmation says how many before anything is replaced. A transaction whose category no longer exists comes back without one: \"Auto-categorize\" picks it up"
+ "Restoring a backup keeps the Balance sheet transfers whose transaction comes back unchanged (same number, date, amount and description); the others are unlinked, and the confirmation says how many before anything is replaced. A transaction whose category no longer exists comes back without one: \"Auto-categorize\" picks it up",
+ "Exports with categories (\"Transactions with categories\", \"Categories only\") and the backup taken before a category migration carry the budget, the budget templates, and the adjustments: a restore puts them back as they were. A backup written by an earlier version holds none: current lines whose category comes back are kept, the others deleted, and the confirmation says so. A file written by a newer version is refused: update the app to import it"
]
},
"editions": {
diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json
index e132522..d565b04 100644
--- a/src/i18n/locales/fr.json
+++ b/src/i18n/locales/fr.json
@@ -435,7 +435,7 @@
"deleteConfirm": "Êtes-vous sûr de vouloir supprimer cette catégorie ? Ses sous-catégories seront promues au niveau supérieur.",
"deleteBlocked": "Impossible de supprimer : cette catégorie ou ses sous-catégories sont utilisées par {{count}} transaction(s).",
"reinitialize": "Réinitialiser",
- "reinitializeConfirm": "Réinitialiser toutes les catégories et mots-clés à leurs valeurs par défaut ? Les catégories des transactions seront dissociées. Cette action est irréversible.",
+ "reinitializeConfirm": "Réinitialiser toutes les catégories et mots-clés à leurs valeurs par défaut ? Les catégories des transactions seront dissociées, et le budget, les modèles de budget et les ajustements seront effacés. Cette action est irréversible.",
"noParent": "Aucun parent (niveau supérieur)",
"isInputable": "Autoriser la saisie",
"isInputableHint": "Décocher pour masquer du budget et des listes de catégories",
@@ -761,9 +761,9 @@
"decrypt": "Déchiffrer",
"confirmTitle": "Remplacer les données",
"willDeleteLabel": "Les données suivantes seront supprimées :",
- "willDeleteCategories": "Toutes les catégories, fournisseurs et mots-clés",
+ "willDeleteCategories": "Toutes les catégories, fournisseurs et mots-clés, ainsi que le budget, les modèles de budget et les ajustements",
"willDeleteTransactions": "Toutes les transactions et l'historique d'import",
- "willDeleteAll": "Toutes les transactions, catégories, fournisseurs, mots-clés et l'historique d'import",
+ "willDeleteAll": "Toutes les transactions, catégories, fournisseurs, mots-clés et l'historique d'import, ainsi que le budget, les modèles de budget et les ajustements",
"willImportLabel": "Les données suivantes seront importées :",
"countCategories": "{{count}} catégorie(s)",
"countSuppliers": "{{count}} fournisseur(s)",
@@ -771,6 +771,10 @@
"countTransactions": "{{count}} transaction(s)",
"countImportSources": "{{count}} source(s) d'import",
"countImportTemplates": "{{count}} modèle(s) d'import",
+ "countBudgetEntries": "{{count}} ligne(s) de budget",
+ "countBudgetTemplates": "{{count}} modèle(s) de budget",
+ "countAdjustments": "{{count}} ajustement(s)",
+ "legacyBudgetNote": "Cette sauvegarde date d'avant l'ajout du budget aux sauvegardes : elle ne contient ni budget, ni modèles de budget, ni ajustements. Les lignes actuelles dont la catégorie revient seront gardées, les autres supprimées.",
"irreversibleWarning": "Cette action est irréversible. Toutes les données existantes du type sélectionné seront définitivement supprimées et remplacées.",
"typeToConfirm": "Tapez « {{word}} » pour confirmer :",
"confirmWord": "REMPLACER",
@@ -786,7 +790,9 @@
"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é.",
"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é.",
- "danglingCategoryReference": "Ce fichier ne peut pas être importé : des catégories, mots-clés ou fournisseurs renvoient à une catégorie absente du fichier. Rien n'a été modifié."
+ "danglingCategoryReference": "Ce fichier ne peut pas être importé : des catégories, mots-clés ou fournisseurs renvoient à une catégorie absente du fichier. Rien n'a été modifié.",
+ "invalidBudgetRows": "Ce fichier ne peut pas être importé : des lignes de budget, de modèle de budget ou d'ajustement sont invalides ou visent une catégorie absente du fichier. Rien n'a été modifié.",
+ "newerFormat": "Ce fichier vient d'une version plus récente de Simpl'Résultat. Mettez l'application à jour pour l'importer. Rien n'a été modifié."
}
}
},
@@ -827,6 +833,7 @@
"retry": "Réessayer",
"restoring": "Rétablissement en cours — ne fermez pas l'application...",
"reading": "Lecture de la sauvegarde en cours...",
+ "legacyBudgetNote": "Cette sauvegarde date d'avant l'ajout du budget aux sauvegardes : elle ne contient ni budget, ni modèles de budget, ni ajustements. Les lignes actuelles dont la catégorie revient seront gardées, les autres supprimées.",
"unlinkedTransfersPreview_one": "{{count}} transfert du Bilan ne retrouvera pas sa transaction et sera délié.",
"unlinkedTransfersPreview_other": "{{count}} transferts du Bilan ne retrouveront pas leur transaction et seront déliés.",
"doneTitle": "Sauvegarde rétablie",
@@ -1154,7 +1161,7 @@
"Sauvegardez votre configuration comme modèle pour ne pas avoir à reconfigurer à chaque fois. Un modèle sert à initialiser une source ; le modifier ensuite ne change aucune source déjà configurée.",
"Les fichiers déjà importés sont marqués d'un badge — les ré-importer déclenchera la détection de doublons",
"Vous pouvez supprimer un import de l'historique pour retirer toutes ses transactions",
- "Vos sources et vos modèles d'import font désormais partie de la sauvegarde chiffrée : restaurer un backup ne vous oblige plus à tout reconfigurer",
+ "Vos sources et vos modèles d'import font désormais partie de la sauvegarde chiffrée, comme votre budget, vos modèles de budget et vos ajustements : restaurer un backup ne vous oblige plus à tout reconfigurer",
"Si des fichiers CSV sont posés directement dans le dossier d'import, un avertissement les nomme : déplacez-les dans un sous-dossier par compte",
"Le nom d'une source est celui de son sous-dossier"
]
@@ -1353,7 +1360,7 @@
"Vérification des mises à jour sur demande, avec installation en un clic",
"Journaux de l'application (logs) consultables avec filtres par niveau, copie et effacement",
"Historique des versions : les notes de la version installée s'affichent d'emblée, les autres versions sont repliées et se déplient d'un clic sur leur numéro, ou toutes ensemble avec « Tout déplier »",
- "Export des données (transactions, catégories, ou les deux) en format JSON ou CSV",
+ "Export des données (transactions, catégories, ou les deux) en format JSON ou CSV ; avec les catégories, l'export porte aussi le budget, les modèles de budget et les ajustements",
"Import des données depuis un fichier exporté précédemment",
"Chiffrement AES-256-GCM optionnel pour les fichiers exportés",
"Envoi de feedback optionnel vers feedback.lacompagniemaximus.com (sur demande, après une demande de consentement)",
@@ -1379,7 +1386,8 @@
"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.",
"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",
- "Restaurer une sauvegarde garde les transferts du Bilan dont la transaction revient à l'identique (même numéro, même date, même montant, même description) ; les autres sont déliés, et la confirmation dit combien avant que rien ne soit remplacé. Une transaction dont la catégorie n'existe plus revient sans catégorie : « Auto-catégoriser » la reprend"
+ "Restaurer une sauvegarde garde les transferts du Bilan dont la transaction revient à l'identique (même numéro, même date, même montant, même description) ; les autres sont déliés, et la confirmation dit combien avant que rien ne soit remplacé. Une transaction dont la catégorie n'existe plus revient sans catégorie : « Auto-catégoriser » la reprend",
+ "Les exports avec catégories (« Transactions avec catégories », « Catégories uniquement ») et la sauvegarde prise avant une migration des catégories portent le budget, les modèles de budget et les ajustements : une restauration les remet tels qu'ils étaient. Une sauvegarde écrite par une version antérieure n'en contient pas : les lignes actuelles dont la catégorie revient sont gardées, les autres supprimées, et la confirmation le dit. Un fichier écrit par une version plus récente est refusé : mettez l'application à jour pour l'importer"
]
},
"editions": {
diff --git a/src/services/categoryBackupService.test.ts b/src/services/categoryBackupService.test.ts
index e5e6fb7..a53aae9 100644
--- a/src/services/categoryBackupService.test.ts
+++ b/src/services/categoryBackupService.test.ts
@@ -12,22 +12,33 @@ vi.mock("@tauri-apps/api/app", () => ({
getVersion: vi.fn(async () => "0.8.3-test"),
}));
+// The arrays of the backup come from `collectExportData` (#520), whose reads
+// of the profile are faked here; serialize and parse stay real.
+const { EXPORTED } = vi.hoisted(() => ({
+ EXPORTED: {
+ categories: [],
+ suppliers: [],
+ keywords: [],
+ transactions: [],
+ import_sources: [],
+ import_config_templates: [],
+ budget_entries: [],
+ budget_templates: [],
+ adjustments: [],
+ } as Record,
+}));
vi.mock("./dataExportService", async () => {
const actual = await vi.importActual(
"./dataExportService",
);
return {
...actual,
- getExportCategories: vi.fn(async () => []),
- getExportSuppliers: vi.fn(async () => []),
- getExportKeywords: vi.fn(async () => []),
- getExportTransactions: vi.fn(async () => []),
- getExportImportSources: vi.fn(async () => []),
- getExportImportTemplates: vi.fn(async () => []),
+ collectExportData: vi.fn(async () => EXPORTED),
};
});
import { invoke } from "@tauri-apps/api/core";
+import { collectExportData, SREF_FORMAT_VERSION } from "./dataExportService";
import {
createPreMigrationBackup,
sanitizeProfileName,
@@ -177,6 +188,44 @@ describe("createPreMigrationBackup — happy path (no PIN)", () => {
expect(result.verifiedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
+ it("writes what an export « Transactions avec catégories » carries, the budget among it, at format 3 (#520)", async () => {
+ const budget = {
+ categories: [{ id: 1111, name: "Épicerie", type: "expense", is_active: 1, is_inputable: 1, sort_order: 1 }],
+ budget_entries: [{ category_id: 1111, year: 2026, month: 10, amount: 450, notes: null }],
+ budget_templates: [{ name: "Mois type", description: null, entries: [{ category_id: 1111, amount: 400 }] }],
+ adjustments: [
+ {
+ name: "Rattrapage",
+ description: null,
+ date: "2026-10-15",
+ is_recurring: 0,
+ recurrence_rule: null,
+ entries: [{ category_id: 1111, amount: 15, description: null }],
+ },
+ ],
+ };
+ vi.mocked(collectExportData).mockResolvedValueOnce({ ...EXPORTED, ...budget } as never);
+ let written = "";
+ mockInvoke.mockImplementation(async (cmd, args) => {
+ if (cmd === "ensure_backup_dir") return "/tmp/sr-backups";
+ if (cmd === "write_export_file") {
+ written = (args as { content: string }).content;
+ return undefined;
+ }
+ if (cmd === "read_import_file") return written;
+ if (cmd === "get_file_size") return written.length;
+ throw new Error(`unexpected invoke: ${cmd}`);
+ });
+
+ await createPreMigrationBackup({ profile: plainProfile });
+
+ expect(collectExportData).toHaveBeenLastCalledWith("transactions_with_categories");
+ const envelope = JSON.parse(written);
+ expect(envelope.export_type).toBe("transactions_with_categories");
+ expect(envelope.format_version).toBe(SREF_FORMAT_VERSION);
+ expect(envelope.data).toEqual({ ...EXPORTED, ...budget });
+ });
+
it("calls write_export_file with password=null for an unprotected profile", async () => {
setupHappyPathInvokes(validEnvelope());
// Override write_export_file so we can inspect args.
diff --git a/src/services/categoryBackupService.ts b/src/services/categoryBackupService.ts
index a487b7e..a3b7afd 100644
--- a/src/services/categoryBackupService.ts
+++ b/src/services/categoryBackupService.ts
@@ -2,12 +2,7 @@ import { invoke } from "@tauri-apps/api/core";
import { getVersion } from "@tauri-apps/api/app";
import type { Profile } from "./profileService";
import {
- getExportCategories,
- getExportSuppliers,
- getExportKeywords,
- getExportTransactions,
- getExportImportSources,
- getExportImportTemplates,
+ collectExportData,
serializeToJson,
parseImportedJson,
type ExportEnvelope,
@@ -224,8 +219,10 @@ async function getFileSize(filePath: string): Promise {
* to be used as a safety net before the v2 -> v1 categories migration.
*
* Flow:
- * 1. Gather categories, suppliers, keywords, and transactions via the
- * existing dataExportService helpers.
+ * 1. Gather what an export « Transactions avec catégories » carries, through
+ * `collectExportData`: categories, suppliers, keywords, transactions,
+ * import configurations, and the budget, its templates and the
+ * adjustments (#520).
* 2. Serialize to JSON using the `transactions_with_categories` envelope.
* 3. Resolve `~/Documents/Simpl-Resultat/backups/` (create if missing).
* 4. Write the file via `write_export_file` (encrypted when a PIN password
@@ -255,39 +252,15 @@ export async function createPreMigrationBackup(
);
}
- // 1. Gather data — same mode as "transactions_with_categories" export.
- // Import sources and templates are part of that mode since #331: this
- // backup is a safety net, and one that came back without a single import
- // configuration would be a poor one.
+ // 1. Gather data — the very arrays of a "transactions_with_categories"
+ // export. Import sources and templates are part of that mode since #331,
+ // the budget since #520: this backup is a safety net, and one that came
+ // back without a single import configuration, or without the budget of
+ // the categories it replaces, would be a poor one.
const appVersion = await getVersion();
- const [
- categories,
- suppliers,
- keywords,
- transactions,
- import_sources,
- import_config_templates,
- ] = await Promise.all([
- getExportCategories(),
- getExportSuppliers(),
- getExportKeywords(),
- getExportTransactions(),
- getExportImportSources(),
- getExportImportTemplates(),
- ]);
+ const data = await collectExportData("transactions_with_categories");
- const content = serializeToJson(
- "transactions_with_categories",
- {
- categories,
- suppliers,
- keywords,
- transactions,
- import_sources,
- import_config_templates,
- },
- appVersion,
- );
+ const content = serializeToJson("transactions_with_categories", data, appVersion);
// 2. Compute the expected checksum before writing.
const expectedChecksum = await sha256Hex(content);
diff --git a/src/services/categoryRestoreService.test.ts b/src/services/categoryRestoreService.test.ts
index 66fff28..bb07282 100644
--- a/src/services/categoryRestoreService.test.ts
+++ b/src/services/categoryRestoreService.test.ts
@@ -27,7 +27,7 @@ import {
shouldShowBanner,
type RestorableMigrationJournal,
} from "./categoryRestoreService";
-import { serializeToJson, SrefValidationError } from "./dataExportService";
+import { serializeToJson, SREF_FORMAT_VERSION, SrefValidationError } from "./dataExportService";
const DAY = 24 * 60 * 60 * 1000;
@@ -133,14 +133,27 @@ describe("shouldShowBanner", () => {
const ORPHAN = "settings.dataManagement.import.errors.orphanSplitLines";
const PATH = "/tmp/profile_avant-migration.sref";
+/** The three budget arrays of a format-3 backup whose profile had no budget (#520). */
+const NO_BUDGET = { budget_entries: [], budget_templates: [], adjustments: [] };
+
/** 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 },
+ { categories: [], suppliers: [], keywords: [], transactions: transactions as never, ...NO_BUDGET },
"0.17.2",
);
+/** The same backup as an earlier version wrote it: `format_version` as given, absent when undefined, no budget. */
+const olderBackup = (formatVersion: number | undefined) =>
+ JSON.stringify({
+ export_type: "transactions_with_categories",
+ app_version: "0.17.2",
+ ...(formatVersion === undefined ? {} : { format_version: formatVersion }),
+ exported_at: "2026-10-18T12:00:00.000Z",
+ data: { categories: [], suppliers: [], keywords: [], transactions: [] },
+ });
+
/** One transaction of a backup. */
const transaction = (id: number, parent: number | null = null) => ({
id,
@@ -215,7 +228,7 @@ describe("readBackup reads the backup and writes nothing (#521)", () => {
});
it("refuses a file that is not a full backup, before counting anything", async () => {
- readingFile(serializeToJson("categories_only", { categories: [], suppliers: [], keywords: [] }, "0.17.2"));
+ readingFile(serializeToJson("categories_only", { categories: [], suppliers: [], keywords: [], ...NO_BUDGET }, "0.17.2"));
const error = await failureOf(() => readBackup(PATH, null));
expect(error).toBeInstanceOf(RestoreError);
expect((error as RestoreError).code).toBe("wrong_envelope_type");
@@ -245,13 +258,29 @@ describe("applyBackup restores the backup read and hands back what the restore d
const result = await applyBackup(envelope, "profile_avant-migration.sref");
- expect(importTransactionsWithCategories).toHaveBeenCalledWith(envelope.data, "profile_avant-migration.sref");
+ expect(importTransactionsWithCategories).toHaveBeenCalledWith(
+ envelope.data,
+ "profile_avant-migration.sref",
+ SREF_FORMAT_VERSION,
+ );
expect(result.outcome).toEqual({ unlinkedTransfers: 3, uncategorizedTransactions: 1 });
expect(result.revertedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
expect(preferences.get("categories_schema_version")).toBe("v2");
expect(JSON.parse(preferences.get("last_categories_migration")!).reverted_at).toBe(result.revertedAt);
});
+ it.each([
+ [2, 2],
+ [undefined, 1],
+ ])("a backup of format %s restores at its own format (%i): the profile's lines whose category comes back are kept (#520)", async (declared, expected) => {
+ const envelope = await envelopeOf(olderBackup(declared));
+ importTransactionsWithCategories.mockResolvedValue({ unlinkedTransfers: 0, uncategorizedTransactions: 0 });
+
+ await applyBackup(envelope, "backup.sref");
+
+ expect(importTransactionsWithCategories).toHaveBeenCalledWith(envelope.data, "backup.sref", expected);
+ });
+
it("a failed restore marks nothing", async () => {
const envelope = await envelopeOf(backup([]));
importTransactionsWithCategories.mockRejectedValue(new Error("FOREIGN KEY constraint failed"));
diff --git a/src/services/categoryRestoreService.ts b/src/services/categoryRestoreService.ts
index d3eb070..0d55dad 100644
--- a/src/services/categoryRestoreService.ts
+++ b/src/services/categoryRestoreService.ts
@@ -1,5 +1,6 @@
import { invoke } from "@tauri-apps/api/core";
import {
+ LEGACY_SREF_FORMAT_VERSION,
parseImportedJson,
SrefValidationError,
type ExportEnvelope,
@@ -311,10 +312,16 @@ export async function applyBackup(
): Promise {
// 1. Perform the destructive re-import. importTransactionsWithCategories
// wipes transactions/imported_files/import_sources/keywords/suppliers/
- // categories and re-inserts them from the envelope.
+ // categories and re-inserts them from the envelope, with the budget of a
+ // backup of format 3, or the profile's lines whose category comes back
+ // from an older one (#520).
let outcome: RestoreOutcome;
try {
- outcome = await importTransactionsWithCategories(envelope.data, filename);
+ outcome = await importTransactionsWithCategories(
+ envelope.data,
+ filename,
+ envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION,
+ );
} catch (e) {
// Same for a refusal raised at the head of the restore itself.
if (e instanceof SrefValidationError) throw e;
diff --git a/src/services/categoryService.test.ts b/src/services/categoryService.test.ts
index b240cb0..e39829d 100644
--- a/src/services/categoryService.test.ts
+++ b/src/services/categoryService.test.ts
@@ -605,3 +605,24 @@ describe("getCategoryDepth (#393)", () => {
expect(db.rows()).toHaveLength(2);
});
});
+
+describe("« Réinitialiser » says what it erases (#520)", () => {
+ // `reinitializeCategories` deletes every category, and with them, through
+ // their foreign keys, the budget, the template lines and the adjustment
+ // lines: its confirmation says so, in both languages.
+ it("names the budget, the budget templates and the adjustments, in French and in English", () => {
+ expect(fr.categories.reinitializeConfirm).toMatch(
+ /le budget, les modèles de budget et les ajustements seront effacés/,
+ );
+ expect(en.categories.reinitializeConfirm).toMatch(
+ /the budget, budget templates, and adjustments will be erased/,
+ );
+ });
+
+ it("still says that the categories of the transactions are unlinked, and that it cannot be undone", () => {
+ expect(fr.categories.reinitializeConfirm).toMatch(/Les catégories des transactions seront dissociées/);
+ expect(fr.categories.reinitializeConfirm).toMatch(/Cette action est irréversible\.$/);
+ expect(en.categories.reinitializeConfirm).toMatch(/Transaction categories will be unlinked/);
+ expect(en.categories.reinitializeConfirm).toMatch(/This cannot be undone\.$/);
+ });
+});
diff --git a/src/services/dataExportService.test.ts b/src/services/dataExportService.test.ts
index fa8455e..61ceb53 100644
--- a/src/services/dataExportService.test.ts
+++ b/src/services/dataExportService.test.ts
@@ -20,8 +20,10 @@
* models `UNIQUE(name)` and BEGIN/ROLLBACK, because those are the failures the
* transaction exists to survive, and, since #521, the second pass of the
* categories (`UPDATE categories SET parent_id`) and the Bilan transfers read
- * with their transaction. It has no foreign key: the restores under foreign
- * keys run on real SQLite in `src/__integration__/restore.test.ts`.
+ * with their transaction; since #520, the budget tables, the template lines
+ * read with their template's name, and `collectExportData`. It has no foreign
+ * key: the restores under foreign keys run on real SQLite in
+ * `src/__integration__/restore.test.ts`.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
@@ -36,22 +38,31 @@ vi.mock("./db", () => {
import { getDb, withTransaction } from "./db";
import {
+ collectExportData,
getExportImportSources,
getExportImportTemplates,
parseImportedCsv,
parseImportedJson,
serializeToJson,
serializeTransactionsToCsv,
+ validateImportedBudget,
validateImportedCategoryReferences,
validateImportedFormatRows,
+ validateImportedFormatVersion,
validateImportedTransactionIds,
LEGACY_SREF_FORMAT_VERSION,
+ MAX_BUDGET_YEAR,
MAX_TRANSACTION_ID,
+ MIN_BUDGET_YEAR,
SREF_FORMAT_VERSION,
SrefValidationError,
+ type ExportAdjustment,
+ type ExportBudgetEntry,
+ type ExportBudgetTemplate,
type ExportEnvelope,
type ExportImportSource,
type ExportImportTemplate,
+ type ExportMode,
type ExportTransaction,
} from "./dataExportService";
import {
@@ -83,6 +94,11 @@ function makeFakeDb(shouldFail?: (sql: string, params: unknown[]) => boolean) {
import_sources: [],
import_config_templates: [],
balance_account_transfers: [],
+ budget_entries: [],
+ budget_templates: [],
+ budget_template_entries: [],
+ adjustments: [],
+ adjustment_entries: [],
};
const log: string[] = [];
let snapshot: Record | null = null;
@@ -189,6 +205,13 @@ function makeFakeDb(shouldFail?: (sql: string, params: unknown[]) => boolean) {
};
});
}
+ // ...and each template line with its template's name (#520).
+ if (table === "budget_template_entries" && /JOIN budget_templates/.test(sql)) {
+ return rows.flatMap((r) => {
+ const template = tables.budget_templates.find((t) => t.id === r.template_id);
+ return template ? [{ ...r, template_name: template.name }] : [];
+ });
+ }
return [...rows];
}),
};
@@ -237,6 +260,9 @@ const SOURCE: ExportImportSource = {
sign_convention: "negative_expense",
};
+/** The three budget arrays of a format-3 file whose profile had no budget (#520). */
+const NO_BUDGET = { budget_entries: [], budget_templates: [], adjustments: [] };
+
function envelopeData(
overrides: Partial = {}
): ExportEnvelope["data"] {
@@ -247,6 +273,7 @@ function envelopeData(
transactions: [],
import_sources: [SOURCE],
import_config_templates: [TEMPLATE],
+ ...NO_BUDGET,
...overrides,
};
}
@@ -379,8 +406,8 @@ describe("a backup written before #331 still imports", () => {
it("restores exactly as it did before — wipe, then one host source", async () => {
db.seed("import_sources", [{ name: "Old source", column_mapping: "{}" }]);
- const { envelope } = parseImportedJson(LEGACY_BACKUP);
- await importTransactionsWithCategories(envelope.data, "backup.json");
+ const { envelope, summary } = parseImportedJson(LEGACY_BACKUP);
+ await importTransactionsWithCategories(envelope.data, "backup.json", summary.formatVersion);
expect(db.tables.import_sources).toHaveLength(1);
expect(db.tables.import_sources[0].name).toBe("Data Import");
@@ -460,7 +487,7 @@ describe("the import boundary refuses a format it cannot store", () => {
envelopeData({
import_sources: [{ ...SOURCE, sign_convention: "inverted" as never }],
}),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
)
).rejects.toBeInstanceOf(SrefValidationError);
expect(db.tables.categories).toHaveLength(1);
@@ -474,7 +501,7 @@ describe("the import boundary refuses a format it cannot store", () => {
describe("restoring brings the configurations back (#331)", () => {
it("restores a source field by field, template resolved to the new id", async () => {
- await importTransactionsWithCategories(envelopeData(), "backup.json");
+ await importTransactionsWithCategories(envelopeData(), "backup.json", SREF_FORMAT_VERSION);
expect(db.tables.import_config_templates).toHaveLength(1);
const template = db.tables.import_config_templates[0];
@@ -489,7 +516,7 @@ describe("restoring brings the configurations back (#331)", () => {
});
it("writes the templates BEFORE the sources — template_id is a foreign key", async () => {
- await importTransactionsWithCategories(envelopeData(), "backup.json");
+ await importTransactionsWithCategories(envelopeData(), "backup.json", SREF_FORMAT_VERSION);
const inserts = db.log.filter((l) => l.startsWith("INSERT INTO"));
expect(inserts.indexOf("INSERT INTO import_config_templates")).toBeLessThan(
inserts.indexOf("INSERT INTO import_sources")
@@ -504,7 +531,7 @@ describe("restoring brings the configurations back (#331)", () => {
]);
const existingId = db.tables.import_config_templates[0].id;
- await importTransactionsWithCategories(envelopeData(), "backup.json");
+ await importTransactionsWithCategories(envelopeData(), "backup.json", SREF_FORMAT_VERSION);
expect(db.tables.import_config_templates).toHaveLength(1);
expect(db.tables.import_config_templates[0].id).toBe(existingId);
@@ -518,13 +545,13 @@ describe("restoring brings the configurations back (#331)", () => {
import_sources: [{ ...SOURCE, template_name: "Gone" }],
import_config_templates: [],
}),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
expect(db.tables.import_sources[0].template_id).toBeNull();
});
it("creates NO host source when the file carries no transactions", async () => {
- await importTransactionsWithCategories(envelopeData(), "backup.json");
+ await importTransactionsWithCategories(envelopeData(), "backup.json", SREF_FORMAT_VERSION);
expect(db.tables.import_sources.map((s) => s.name)).toEqual([SOURCE.name]);
expect(db.tables.imported_files).toHaveLength(0);
});
@@ -532,7 +559,7 @@ describe("restoring brings the configurations back (#331)", () => {
it("creates the host source only to carry transactions, with a readable mapping", async () => {
await importTransactionsWithCategories(
envelopeData({ transactions: [transactionFixture(1), transactionFixture(2)] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
const host = db.tables.import_sources.find((s) => s.name === "Data Import")!;
@@ -557,7 +584,7 @@ describe("restoring brings the configurations back (#331)", () => {
import_sources: [{ ...SOURCE, name: "Data Import" }],
transactions: [transactionFixture(1)],
}),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
expect(db.tables.import_sources).toHaveLength(1);
// The restored configuration wins; it is not overwritten by the host stub.
@@ -573,7 +600,7 @@ describe("restoring brings the configurations back (#331)", () => {
it("leaves import_sources alone in categories_only mode", async () => {
db.seed("import_sources", [{ name: "Kept", column_mapping: "{}" }]);
- await importCategoriesOnly({ categories: [], suppliers: [], keywords: [] });
+ await importCategoriesOnly({ categories: [], suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION);
expect(db.tables.import_sources.map((s) => s.name)).toEqual(["Kept"]);
});
});
@@ -616,7 +643,7 @@ describe("a restore that fails at row N leaves the profile untouched", () => {
categories: CATEGORY_FIXTURES,
transactions: [transactionFixture(1)],
}),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
)
).rejects.toThrow("boom");
@@ -632,7 +659,7 @@ describe("a restore that fails at row N leaves the profile untouched", () => {
await expect(
importTransactionsWithCategories(
envelopeData({ import_sources: [SOURCE, { ...SOURCE }] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
)
).rejects.toThrow(/UNIQUE constraint failed/);
expect(db.tables.categories.map((c) => c.name)).toEqual(["Existing"]);
@@ -650,13 +677,17 @@ describe("a restore that fails at row N leaves the profile untouched", () => {
db.seed("categories", [{ id: 900, name: "Existing" }]);
await expect(
- importCategoriesOnly({
- categories: CATEGORY_FIXTURES,
- suppliers: [],
- keywords: [
- { id: 1, keyword: "epicerie", category_id: 1, priority: 1, is_active: 1 } as never,
- ],
- })
+ importCategoriesOnly(
+ {
+ categories: CATEGORY_FIXTURES,
+ suppliers: [],
+ keywords: [
+ { id: 1, keyword: "epicerie", category_id: 1, priority: 1, is_active: 1 } as never,
+ ],
+ ...NO_BUDGET,
+ },
+ SREF_FORMAT_VERSION
+ )
).rejects.toThrow("boom");
expect(db.log).toContain("ROLLBACK");
@@ -818,7 +849,7 @@ describe("a restore writes the manual flag as an integer (#390)", () => {
it("restores the 'true' of an older JSON backup as 1", async () => {
await importTransactionsWithCategories(
envelopeData({ transactions: [fromTheBug, transactionFixture(2)] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
expect(db.tables.transactions.map((t) => t.is_manually_categorized)).toEqual([1, 0]);
});
@@ -860,7 +891,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
it("transactions with categories: once, after the COMMIT", async () => {
await importTransactionsWithCategories(
envelopeData({ transactions: [transactionFixture(1)] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
);
expect(seen).toHaveLength(1);
expect(seen[0][seen[0].length - 1]).toBe("COMMIT");
@@ -873,7 +904,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
});
it("categories only: once, after the COMMIT", async () => {
- await importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [] });
+ await importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION);
expect(seen).toHaveLength(1);
expect(seen[0][seen[0].length - 1]).toBe("COMMIT");
});
@@ -886,7 +917,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
() =>
importTransactionsWithCategories(
envelopeData({ transactions: [transactionFixture(1)] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
),
],
[
@@ -895,7 +926,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
],
[
"categories only",
- () => importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [] }),
+ () => importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION),
],
] as const)("%s: notifies once the DB lock is released", async (_name, restore) => {
let inLock = false;
@@ -948,7 +979,7 @@ describe("a committed restore is announced on the data channel (#396)", () => {
await expect(
importTransactionsWithCategories(
envelopeData({ import_sources: [{ ...SOURCE, amount_mode: "nonsense" as never }] }),
- "backup.json"
+ "backup.json", SREF_FORMAT_VERSION
)
).rejects.toThrow();
expect(db.log).toEqual([]);
@@ -1070,7 +1101,7 @@ describe("the rows keep their ids, and a split line its parent (#518)", () => {
it.each([
[
"transactions with categories",
- (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json"),
+ (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION),
],
["transactions only", (data: ExportEnvelope["data"]) => importTransactionsOnly(data, "backup.json")],
] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => {
@@ -1171,9 +1202,9 @@ describe("the import boundary refuses a category reference the file cannot satis
it.each([
[
"transactions with categories",
- (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json"),
+ (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION),
],
- ["categories only", (data: ExportEnvelope["data"]) => importCategoriesOnly(data)],
+ ["categories only", (data: ExportEnvelope["data"]) => importCategoriesOnly(data, SREF_FORMAT_VERSION)],
] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => {
db.seed("categories", [{ name: "Existing" }]);
await expect(
@@ -1200,9 +1231,9 @@ describe("the categories go in without their parents, set in a second pass (#521
it.each([
[
"transactions with categories",
- () => importTransactionsWithCategories(envelopeData({ categories: CATEGORIES }), "backup.json"),
+ () => importTransactionsWithCategories(envelopeData({ categories: CATEGORIES }), "backup.json", SREF_FORMAT_VERSION),
],
- ["categories only", () => importCategoriesOnly({ categories: CATEGORIES, suppliers: [], keywords: [] })],
+ ["categories only", () => importCategoriesOnly({ categories: CATEGORIES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION)],
] as const)("%s: every insert without a parent, then each parent; every parent_id as in the file", async (_name, restore) => {
await restore();
@@ -1239,14 +1270,14 @@ describe("a restore hands back its outcome (#521)", () => {
});
it("categories only: zeros, nothing deleted that a transfer holds", async () => {
- await expect(importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [] })).resolves.toEqual({
+ await expect(importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION)).resolves.toEqual({
unlinkedTransfers: 0,
uncategorizedTransactions: 0,
});
});
it.each([
- ["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json")],
+ ["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION)],
["transactions only", (data: ExportEnvelope["data"]) => importTransactionsOnly(data, "backup.json")],
] as const)("%s: the transfers are read and removed before the transactions are deleted", async (_name, restore) => {
await restore(envelopeData({ transactions: [transactionFixture(1)] }));
@@ -1256,7 +1287,7 @@ describe("a restore hands back its outcome (#521)", () => {
});
it.each([
- ["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json")],
+ ["transactions with categories", (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION)],
["transactions only", (data: ExportEnvelope["data"]) => importTransactionsOnly(data, "backup.json")],
] as const)("%s: a transfer whose transaction comes back as it was is put back as it was, the other unlinked", async (_name, restore) => {
// The profile: two transactions, each linked to « CELI » (account 2).
@@ -1294,3 +1325,335 @@ describe("a restore hands back its outcome (#521)", () => {
expect(outcome).toEqual({ unlinkedTransfers: 0, uncategorizedTransactions: 1 });
});
});
+
+// ---------------------------------------------------------------------------
+// 12. The budget travels with the categories, from format 3 on (#520)
+// ---------------------------------------------------------------------------
+
+describe("collectExportData gathers the arrays of each mode (#520)", () => {
+ beforeEach(() => {
+ db.seed("categories", [{ id: 1, name: "Épicerie" }]);
+ db.seed("transactions", [transactionFixture(10)]);
+ db.seed("import_config_templates", [{ ...TEMPLATE }]);
+ db.seed("budget_entries", [{ category_id: 1, year: 2026, month: 10, amount: 450, notes: "Octobre" }]);
+ db.seed("budget_templates", [
+ { name: "Mois type", description: "Le mois" },
+ { name: "Vide", description: null },
+ ]);
+ const [monthly] = db.tables.budget_templates;
+ db.seed("budget_template_entries", [{ template_id: monthly.id, category_id: 1, amount: 400 }]);
+ db.seed("adjustments", [
+ { name: "Rattrapage", description: null, date: "2026-10-15", is_recurring: 1, recurrence_rule: null },
+ ]);
+ const [adjustment] = db.tables.adjustments;
+ db.seed("adjustment_entries", [{ adjustment_id: adjustment.id, category_id: 1, amount: 15, description: "Crédit" }]);
+ });
+
+ it.each<[ExportMode, string[]]>([
+ [
+ "transactions_with_categories",
+ [
+ "categories",
+ "suppliers",
+ "keywords",
+ "transactions",
+ "import_sources",
+ "import_config_templates",
+ "budget_entries",
+ "budget_templates",
+ "adjustments",
+ ],
+ ],
+ ["categories_only", ["categories", "suppliers", "keywords", "budget_entries", "budget_templates", "adjustments"]],
+ ["transactions_only", ["transactions", "import_sources", "import_config_templates"]],
+ ])("%s carries %j", async (mode, arrays) => {
+ expect(Object.keys(await collectExportData(mode))).toEqual(arrays);
+ });
+
+ it("carries each budget line by its category and month, each template by its name with its lines, each adjustment with its lines", async () => {
+ const data = await collectExportData("categories_only");
+ expect(data.budget_entries).toEqual([{ category_id: 1, year: 2026, month: 10, amount: 450, notes: "Octobre" }]);
+ expect(data.budget_templates).toEqual([
+ { name: "Mois type", description: "Le mois", entries: [{ category_id: 1, amount: 400 }] },
+ { name: "Vide", description: null, entries: [] },
+ ]);
+ expect(data.adjustments).toEqual([
+ {
+ name: "Rattrapage",
+ description: null,
+ date: "2026-10-15",
+ is_recurring: 1,
+ recurrence_rule: null,
+ entries: [{ category_id: 1, amount: 15, description: "Crédit" }],
+ },
+ ]);
+ });
+});
+
+describe("the format of a file is checked before anything is deleted (#520)", () => {
+ const NEWER = "settings.dataManagement.import.errors.newerFormat";
+
+ it("accepts every format this build reads", () => {
+ for (const version of [1, 2, SREF_FORMAT_VERSION]) {
+ expect(() => validateImportedFormatVersion(version), String(version)).not.toThrow();
+ }
+ });
+
+ it("refuses a format newer than this build with its own message", () => {
+ for (const version of [SREF_FORMAT_VERSION + 1, 99]) {
+ const error = (() => {
+ try {
+ validateImportedFormatVersion(version);
+ } catch (e) {
+ return e;
+ }
+ return null;
+ })();
+ expect(error, String(version)).toBeInstanceOf(SrefValidationError);
+ expect((error as SrefValidationError).i18nKey).toBe(NEWER);
+ }
+ });
+
+ it.each([0, -1, 2.5, "3", null, Number.NaN, Number.POSITIVE_INFINITY])(
+ "refuses a format_version of %s as a malformed file",
+ (version) => {
+ expect(() => validateImportedFormatVersion(version)).toThrow("Invalid export file format");
+ }
+ );
+
+ it("refuses a newer file at PARSE time, before its mode is even read", () => {
+ const json = JSON.stringify({
+ export_type: "budget_only",
+ app_version: "9.0.0",
+ format_version: SREF_FORMAT_VERSION + 1,
+ exported_at: "2027-01-01T00:00:00Z",
+ data: {},
+ });
+ expect(() => parseImportedJson(json)).toThrow(SrefValidationError);
+ });
+
+ it("refuses a malformed format_version at PARSE time", () => {
+ const json = JSON.stringify({ ...JSON.parse(serializeToJson("transactions_only", envelopeData(), "0.17.2")), format_version: 2.5 });
+ expect(() => parseImportedJson(json)).toThrow("Invalid export file format");
+ });
+
+ it("reads a file without format_version as format 1, and a file of this build at its format", () => {
+ expect(parseImportedJson(LEGACY_BACKUP).summary.formatVersion).toBe(LEGACY_SREF_FORMAT_VERSION);
+ expect(
+ parseImportedJson(serializeToJson("transactions_with_categories", envelopeData(), "0.17.2")).summary.formatVersion
+ ).toBe(3);
+ });
+
+ it.each([
+ [
+ "transactions with categories",
+ (data: ExportEnvelope["data"], version: number) => importTransactionsWithCategories(data, "backup.json", version),
+ ],
+ ["categories only", (data: ExportEnvelope["data"], version: number) => importCategoriesOnly(data, version)],
+ ] as const)("%s: a newer format refused again at the restore, before a single DELETE", async (_name, restore) => {
+ db.seed("categories", [{ name: "Existing" }]);
+ await expect(restore(envelopeData(), SREF_FORMAT_VERSION + 1)).rejects.toBeInstanceOf(SrefValidationError);
+ await expect(restore(envelopeData(), 0)).rejects.toThrow("Invalid export file format");
+ expect(db.log).toEqual([]);
+ expect(db.tables.categories.map((c) => c.name)).toEqual(["Existing"]);
+ });
+});
+
+describe("the import boundary refuses a budget the restore could not write back (#520)", () => {
+ const INVALID = "settings.dataManagement.import.errors.invalidBudgetRows";
+
+ const category = (id: number) => ({ ...CATEGORY_FIXTURES[0], id, name: `Cat ${id}` }) as unknown as Category;
+ const entry = (overrides: Partial = {}): ExportBudgetEntry => ({
+ category_id: 1,
+ year: 2026,
+ month: 10,
+ amount: 450,
+ notes: null,
+ ...overrides,
+ });
+ const template = (overrides: Partial = {}): ExportBudgetTemplate => ({
+ name: "Mois type",
+ description: null,
+ entries: [{ category_id: 1, amount: 400 }],
+ ...overrides,
+ });
+ const adjustment = (overrides: Partial = {}): ExportAdjustment => ({
+ name: "Rattrapage",
+ description: null,
+ date: "2026-10-15",
+ is_recurring: 0,
+ recurrence_rule: null,
+ entries: [{ category_id: 2, amount: -30, description: null }],
+ ...overrides,
+ });
+
+ /** A format-3 file of two categories, its budget as given. */
+ const file = (overrides: Partial = {}): ExportEnvelope["data"] => ({
+ categories: [category(1), category(2)],
+ budget_entries: [entry(), entry({ month: 11 })],
+ budget_templates: [template()],
+ adjustments: [adjustment()],
+ ...overrides,
+ });
+
+ /** 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("accepts a file whose every line it can write back, the bounds included", () => {
+ expect(() => validateImportedBudget(file(), 3)).not.toThrow();
+ expect(() =>
+ validateImportedBudget(
+ file({
+ budget_entries: [
+ entry({ year: MIN_BUDGET_YEAR, month: 1 }),
+ entry({ year: MAX_BUDGET_YEAR, month: 12 }),
+ // The same month on another category, the same category in another month.
+ entry({ category_id: 2 }),
+ entry({ year: 2027 }),
+ ],
+ budget_templates: [template(), template({ name: "Autre", entries: [] })],
+ adjustments: [adjustment(), adjustment({ entries: [] })],
+ }),
+ 3
+ )
+ ).not.toThrow();
+ // Empty arrays: a profile without a budget.
+ expect(() => validateImportedBudget(file({ budget_entries: [], budget_templates: [], adjustments: [] }), 3)).not.toThrow();
+ });
+
+ it.each<[string, Partial]>([
+ ["no budget_entries", { budget_entries: undefined }],
+ ["no budget_templates", { budget_templates: undefined }],
+ ["no adjustments", { adjustments: undefined }],
+ ["budget_entries that is not an array", { budget_entries: {} as never }],
+ ["a budget line on a category missing from the file", { budget_entries: [entry({ category_id: 9 })] }],
+ ["a budget line on a category given as text", { budget_entries: [entry({ category_id: "1" as never })] }],
+ ["a budget amount that is not a number", { budget_entries: [entry({ amount: "450" as never })] }],
+ ["a budget amount that is not finite", { budget_entries: [entry({ amount: Number.NaN })] }],
+ ["an infinite budget amount", { budget_entries: [entry({ amount: Number.POSITIVE_INFINITY })] }],
+ ["a year before 1900", { budget_entries: [entry({ year: MIN_BUDGET_YEAR - 1 })] }],
+ ["a year after 2200", { budget_entries: [entry({ year: MAX_BUDGET_YEAR + 1 })] }],
+ ["a year that is not an integer", { budget_entries: [entry({ year: 2026.5 })] }],
+ ["month 0", { budget_entries: [entry({ month: 0 })] }],
+ ["month 13", { budget_entries: [entry({ month: 13 })] }],
+ ["a month that is not an integer", { budget_entries: [entry({ month: 1.5 })] }],
+ ["two budget lines on the same category and month", { budget_entries: [entry(), entry({ amount: 1 })] }],
+ ["a template without a name", { budget_templates: [template({ name: undefined as never })] }],
+ ["two templates of the same name", { budget_templates: [template(), template({ entries: [] })] }],
+ ["a template whose lines are not an array", { budget_templates: [template({ entries: undefined as never })] }],
+ ["a template line on a category missing from the file", { budget_templates: [template({ entries: [{ category_id: 9, amount: 1 }] })] }],
+ ["a template line whose amount is not finite", { budget_templates: [template({ entries: [{ category_id: 1, amount: Number.NaN }] })] }],
+ [
+ "two lines of a template on the same category",
+ { budget_templates: [template({ entries: [{ category_id: 1, amount: 1 }, { category_id: 1, amount: 2 }] })] },
+ ],
+ ["an adjustment without a name", { adjustments: [adjustment({ name: 7 as never })] }],
+ ["an adjustment without a date", { adjustments: [adjustment({ date: undefined as never })] }],
+ ["an adjustment whose lines are not an array", { adjustments: [adjustment({ entries: undefined as never })] }],
+ [
+ "an adjustment line on a category missing from the file",
+ { adjustments: [adjustment({ entries: [{ category_id: 9, amount: 1, description: null }] })] },
+ ],
+ [
+ "an adjustment line whose amount is not finite",
+ { adjustments: [adjustment({ entries: [{ category_id: 1, amount: Number.NEGATIVE_INFINITY, description: null }] })] },
+ ],
+ ])("refuses a format-3 file with %s", (_label, overrides) => {
+ expect(refusalOf(() => validateImportedBudget(file(overrides), 3)).i18nKey).toBe(INVALID);
+ });
+
+ it("checks nothing in a file older than the budget in backups: it holds none", () => {
+ for (const version of [1, 2]) {
+ expect(() => validateImportedBudget({ categories: [] }, version), String(version)).not.toThrow();
+ expect(() => validateImportedBudget(file({ budget_entries: [entry({ category_id: 9 })] }), version)).not.toThrow();
+ }
+ });
+
+ it("refuses at PARSE time, for both modes that carry the categories, so the confirmation never opens", () => {
+ for (const mode of ["transactions_with_categories", "categories_only"] as const) {
+ const json = serializeToJson(mode, { ...envelopeData(), ...file({ budget_entries: [entry({ month: 13 })] }) }, "0.17.2");
+ expect(refusalOf(() => parseImportedJson(json)).i18nKey, mode).toBe(INVALID);
+ }
+ });
+
+ it("leaves « Transactions uniquement » alone: it carries no budget, and its restore touches none", () => {
+ const json = serializeToJson("transactions_only", { transactions: [transactionFixture(1)] }, "0.17.2");
+ expect(() => parseImportedJson(json)).not.toThrow();
+ });
+
+ it("counts the budget a file carries in its summary", () => {
+ const { summary } = parseImportedJson(
+ serializeToJson("categories_only", { ...file(), suppliers: [], keywords: [] }, "0.17.2")
+ );
+ expect([summary.budgetEntriesCount, summary.budgetTemplatesCount, summary.adjustmentsCount]).toEqual([2, 1, 1]);
+ expect(summary.formatVersion).toBe(SREF_FORMAT_VERSION);
+ });
+
+ it.each([
+ [
+ "transactions with categories",
+ (data: ExportEnvelope["data"]) => importTransactionsWithCategories(data, "backup.json", SREF_FORMAT_VERSION),
+ ],
+ ["categories only", (data: ExportEnvelope["data"]) => importCategoriesOnly(data, SREF_FORMAT_VERSION)],
+ ] as const)("%s: refuses again at the restore, before a single DELETE", async (_name, restore) => {
+ db.seed("categories", [{ name: "Existing" }]);
+ await expect(
+ restore({ ...envelopeData(), ...file({ budget_entries: [entry({ category_id: 9 })] }) })
+ ).rejects.toBeInstanceOf(SrefValidationError);
+ expect(db.log).toEqual([]);
+ expect(db.tables.categories.map((c) => c.name)).toEqual(["Existing"]);
+ });
+});
+
+describe("a restore takes the budget out before it deletes the categories (#520)", () => {
+ it.each([
+ [
+ "transactions with categories",
+ () => importTransactionsWithCategories(envelopeData({ categories: CATEGORY_FIXTURES }), "backup.json", SREF_FORMAT_VERSION),
+ ],
+ [
+ "categories only",
+ () => importCategoriesOnly({ categories: CATEGORY_FIXTURES, suppliers: [], keywords: [], ...NO_BUDGET }, SREF_FORMAT_VERSION),
+ ],
+ ] as const)("%s: the budget lines, template lines and adjustment lines go before the categories", async (_name, restore) => {
+ await restore();
+ const deletes = db.log.filter((line) => line.startsWith("DELETE FROM"));
+ const categories = deletes.indexOf("DELETE FROM categories");
+ for (const table of ["budget_entries", "budget_template_entries", "adjustment_entries"]) {
+ const at = deletes.indexOf(`DELETE FROM ${table}`);
+ expect(at, table).toBeGreaterThanOrEqual(0);
+ expect(at, table).toBeLessThan(categories);
+ }
+ });
+
+ it("transactions only: no budget table is touched", async () => {
+ await importTransactionsOnly(envelopeData({ transactions: [transactionFixture(1)] }), "backup.json");
+ expect(db.log.filter((line) => /budget|adjustment/.test(line))).toEqual([]);
+ });
+});
+
+describe("the texts of a restore with the budget exist in both languages (#520)", () => {
+ it("carries the refusal of a budget it could not write back, and of a newer file, in FR and EN", () => {
+ for (const bundle of [fr, en]) {
+ expect(bundle.settings.dataManagement.import.errors.invalidBudgetRows.length).toBeGreaterThan(0);
+ expect(bundle.settings.dataManagement.import.errors.newerFormat.length).toBeGreaterThan(0);
+ }
+ });
+
+ it("the confirmation names the budget, the budget templates and the adjustments among what is deleted", () => {
+ for (const key of ["willDeleteCategories", "willDeleteAll"] as const) {
+ expect(fr.settings.dataManagement.import[key], `fr.${key}`).toMatch(
+ /le budget, les modèles de budget et les ajustements/
+ );
+ expect(en.settings.dataManagement.import[key], `en.${key}`).toMatch(/the budget, budget templates, and adjustments/);
+ }
+ });
+});
diff --git a/src/services/dataExportService.ts b/src/services/dataExportService.ts
index 096e21a..930af5f 100644
--- a/src/services/dataExportService.ts
+++ b/src/services/dataExportService.ts
@@ -33,12 +33,24 @@ export type ExportFormat = "json" | "csv";
* never held any configuration", not "this profile had none". The restore then
* behaves exactly as it did before — wipe the sources and hang the transactions
* off a synthetic one — which is the only reading that cannot invent data.
+ *
+ * Version 3 (#520) is the first to carry the budget: `budget_entries`,
+ * `budget_templates` and `adjustments`, in the two modes that carry the
+ * categories (`BUDGET_SREF_FORMAT_VERSION`). A file of a later version comes
+ * from a newer build and is refused before anything is deleted (ADR 0025).
*/
-export const SREF_FORMAT_VERSION = 2;
+export const SREF_FORMAT_VERSION = 3;
/** What an envelope without an explicit `format_version` is. */
export const LEGACY_SREF_FORMAT_VERSION = 1;
+/**
+ * The first version whose files carry the budget, its templates and the
+ * adjustments (#520). A file of an earlier version holds none of them: the
+ * restore keeps instead the profile's lines whose category comes back.
+ */
+export const BUDGET_SREF_FORMAT_VERSION = 3;
+
export interface ExportEnvelope {
export_type: ExportMode;
app_version: string;
@@ -52,6 +64,10 @@ export interface ExportEnvelope {
transactions?: ExportTransaction[];
import_sources?: ExportImportSource[];
import_config_templates?: ExportImportTemplate[];
+ /** From format 3 on, in the two modes that carry the categories (#520). */
+ budget_entries?: ExportBudgetEntry[];
+ budget_templates?: ExportBudgetTemplate[];
+ adjustments?: ExportAdjustment[];
};
}
@@ -104,6 +120,56 @@ export interface ExportImportTemplate extends ImportFormatRow {
name: string;
}
+/**
+ * A budget line as it travels in the file (#520), designated by its category
+ * and its month, the table's `UNIQUE` key. No id: nothing points at a budget
+ * line.
+ */
+export interface ExportBudgetEntry {
+ category_id: number;
+ year: number;
+ month: number;
+ amount: number;
+ notes: string | null;
+}
+
+/** A line of a budget template (#520). */
+export interface ExportBudgetTemplateEntry {
+ category_id: number;
+ amount: number;
+}
+
+/**
+ * A budget template as it travels in the file (#520), designated by its name,
+ * the table's `UNIQUE` key, like an import template, and carrying its lines.
+ */
+export interface ExportBudgetTemplate {
+ name: string;
+ description: string | null;
+ entries: ExportBudgetTemplateEntry[];
+}
+
+/** A line of an adjustment (#520). */
+export interface ExportAdjustmentEntry {
+ category_id: number;
+ amount: number;
+ description: string | null;
+}
+
+/**
+ * An adjustment as it travels in the file (#520), with its lines. No id and no
+ * natural key (its name is not unique): the restore puts the file's
+ * adjustments in place of the profile's.
+ */
+export interface ExportAdjustment {
+ name: string;
+ description: string | null;
+ date: string;
+ is_recurring: number;
+ recurrence_rule: string | null;
+ entries: ExportAdjustmentEntry[];
+}
+
// --- Import types ---
export interface ImportSummary {
@@ -114,6 +180,10 @@ export interface ImportSummary {
transactionsCount: number;
importSourcesCount: number;
importTemplatesCount: number;
+ /** The budget the file carries, from format 3 on (#520). */
+ budgetEntriesCount: number;
+ budgetTemplatesCount: number;
+ adjustmentsCount: number;
/** `LEGACY_SREF_FORMAT_VERSION` when the file declares none. */
formatVersion: number;
}
@@ -124,12 +194,16 @@ export type SrefValidationErrorKey =
| "settings.dataManagement.import.errors.unsupportedSignConvention"
| "settings.dataManagement.import.errors.invalidFormatRow"
| "settings.dataManagement.import.errors.orphanSplitLines"
- | "settings.dataManagement.import.errors.danglingCategoryReference";
+ | "settings.dataManagement.import.errors.danglingCategoryReference"
+ | "settings.dataManagement.import.errors.invalidBudgetRows"
+ | "settings.dataManagement.import.errors.newerFormat";
/**
* Thrown when a backup carries a configuration this build cannot store, split
- * lines that cannot find their parent (#518), or categories, keywords or
- * suppliers that name a category the file does not hold (#521).
+ * lines that cannot find their parent (#518), categories, keywords or
+ * suppliers that name a category the file does not hold (#521), budget lines,
+ * templates or adjustments the restore could not write back, or a format newer
+ * than this build (#520).
*
* The `CHECK` added by migration v17 already refuses these values, but a SQLite
* constraint error is not something a user can act on — and it would surface
@@ -217,6 +291,119 @@ export async function getExportImportTemplates(): Promise<
}));
}
+/** Every budget line of the profile (#520). */
+export async function getExportBudgetEntries(): Promise {
+ const db = await getDb();
+ const rows = await db.select(
+ "SELECT category_id, year, month, amount, notes FROM budget_entries ORDER BY id"
+ );
+ return rows.map((row) => ({
+ category_id: row.category_id,
+ year: row.year,
+ month: row.month,
+ amount: row.amount,
+ notes: row.notes ?? null,
+ }));
+}
+
+/** Every budget template of the profile, each with its lines (#520). */
+export async function getExportBudgetTemplates(): Promise {
+ const db = await getDb();
+ const templates = await db.select<
+ Array<{ id: number; name: string; description: string | null }>
+ >("SELECT id, name, description FROM budget_templates ORDER BY id");
+ const lines = await db.select<
+ Array<{ template_id: number; category_id: number; amount: number }>
+ >("SELECT template_id, category_id, amount FROM budget_template_entries ORDER BY id");
+ return templates.map((template) => ({
+ name: template.name,
+ description: template.description ?? null,
+ entries: lines
+ .filter((line) => line.template_id === template.id)
+ .map((line) => ({ category_id: line.category_id, amount: line.amount })),
+ }));
+}
+
+/** Every adjustment of the profile, each with its lines (#520). */
+export async function getExportAdjustments(): Promise {
+ const db = await getDb();
+ const adjustments = await db.select<
+ Array<{
+ id: number;
+ name: string;
+ description: string | null;
+ date: string;
+ is_recurring: number;
+ recurrence_rule: string | null;
+ }>
+ >(
+ "SELECT id, name, description, date, is_recurring, recurrence_rule FROM adjustments ORDER BY id"
+ );
+ const lines = await db.select<
+ Array<{
+ adjustment_id: number;
+ category_id: number;
+ amount: number;
+ description: string | null;
+ }>
+ >(
+ "SELECT adjustment_id, category_id, amount, description FROM adjustment_entries ORDER BY id"
+ );
+ return adjustments.map((adjustment) => ({
+ name: adjustment.name,
+ description: adjustment.description ?? null,
+ date: adjustment.date,
+ is_recurring: adjustment.is_recurring,
+ recurrence_rule: adjustment.recurrence_rule ?? null,
+ entries: lines
+ .filter((line) => line.adjustment_id === adjustment.id)
+ .map((line) => ({
+ category_id: line.category_id,
+ amount: line.amount,
+ description: line.description ?? null,
+ })),
+ }));
+}
+
+/**
+ * What an export of `mode` carries, read from the profile: the one list of
+ * arrays per mode, for « Exporter » (`useDataExport`) and for the backup taken
+ * before the categories migration (`createPreMigrationBackup`), so that the two
+ * never carry different things (#520).
+ *
+ * The two modes that carry the categories carry the budget with them, its
+ * templates and the adjustments: their restore deletes the categories, and
+ * every one of these lines names a category. The two modes that carry the
+ * transactions carry the import configurations (#331). « Transactions
+ * uniquement » touches no category, and its budget stays where it is.
+ */
+export async function collectExportData(
+ mode: ExportMode
+): Promise {
+ const withCategories =
+ mode === "transactions_with_categories" || mode === "categories_only";
+ const withTransactions =
+ mode === "transactions_with_categories" || mode === "transactions_only";
+
+ const data: ExportEnvelope["data"] = {};
+ if (withCategories) {
+ data.categories = await getExportCategories();
+ data.suppliers = await getExportSuppliers();
+ data.keywords = await getExportKeywords();
+ }
+ if (withTransactions) {
+ data.transactions = await getExportTransactions();
+ data.import_sources = await getExportImportSources();
+ data.import_config_templates = await getExportImportTemplates();
+ }
+ if (withCategories) {
+ data.budget_entries = await getExportBudgetEntries();
+ data.budget_templates = await getExportBudgetTemplates();
+ data.adjustments = await getExportAdjustments();
+ }
+ return data;
+}
+
// --- Serialization ---
export function serializeToJson(
@@ -418,6 +605,118 @@ export function validateImportedCategoryReferences(
}
}
+/** The refusal of an envelope this app did not write (missing fields, unreadable format). */
+const INVALID_ENVELOPE = "Invalid export file format — missing required fields";
+
+/**
+ * Refuse a file whose format this build cannot read, BEFORE anything is
+ * deleted (#520): a `format_version` above `SREF_FORMAT_VERSION` comes from a
+ * newer Simpl'Résultat, whose files may carry what this build would drop
+ * without a word; one that is not an integer of at least 1 was not written by
+ * the app at all, and gets the refusal of a malformed envelope.
+ *
+ * PURE: no I/O, so it can be called from the parse step and again at the top of
+ * each restore that is given the format, like `validateImportedFormatRows`.
+ */
+export function validateImportedFormatVersion(formatVersion: unknown): void {
+ if (!Number.isInteger(formatVersion) || (formatVersion as number) < 1) {
+ throw new Error(INVALID_ENVELOPE);
+ }
+ if ((formatVersion as number) > SREF_FORMAT_VERSION) {
+ throw new SrefValidationError("settings.dataManagement.import.errors.newerFormat", {});
+ }
+}
+
+/** The years a budget line may name. */
+export const MIN_BUDGET_YEAR = 1900;
+export const MAX_BUDGET_YEAR = 2200;
+
+/**
+ * Refuse a file of format 3 or later whose budget lines, budget templates or
+ * adjustments the restore could not write back as they are, BEFORE anything is
+ * deleted (#520).
+ *
+ * From format 3 on, the two modes that carry the categories carry the three
+ * arrays, and the restore puts them in place of the profile's: a file that
+ * lacks one would empty that part of the budget, so it is refused, as is a
+ * line the tables cannot hold. Each line names a category of the file (the
+ * restore deletes every other one) and holds a finite amount; a budget line
+ * names a year from 1900 to 2200 and a month from 1 to 12, both integers; a
+ * template has a name and an adjustment a name and a date, both texts. No two
+ * budget lines share their category and month, no two lines of a template
+ * their category, no two templates their name: the `UNIQUE` keys of the
+ * tables. The tables are not STRICT, and SQLite's own refusal, midway through
+ * the restore, is not a message a user can act on. A file of an earlier format
+ * holds no budget, and nothing here applies to it.
+ *
+ * PURE: no I/O, so it can be called from the parse step and again at the top of
+ * each restore that writes categories, like `validateImportedFormatRows`.
+ */
+export function validateImportedBudget(
+ data: ExportEnvelope["data"],
+ formatVersion: number
+): void {
+ if (formatVersion < BUDGET_SREF_FORMAT_VERSION) return;
+
+ const refusal = () =>
+ new SrefValidationError(
+ "settings.dataManagement.import.errors.invalidBudgetRows",
+ {}
+ );
+ const { budget_entries: entries, budget_templates: templates, adjustments } = data;
+ if (!Array.isArray(entries) || !Array.isArray(templates) || !Array.isArray(adjustments)) {
+ throw refusal();
+ }
+
+ const categoryIds = new Set(
+ (data.categories ?? [])
+ .map((category) => category?.id)
+ .filter((id): id is number => typeof id === "number")
+ );
+ /** A line the restore can write: a category of the file, a finite amount. */
+ const isLine = (line: { category_id?: unknown; amount?: unknown } | null | undefined) =>
+ categoryIds.has(line?.category_id as number) && Number.isFinite(line?.amount);
+ const isYear = (year: unknown) =>
+ Number.isInteger(year) &&
+ (year as number) >= MIN_BUDGET_YEAR &&
+ (year as number) <= MAX_BUDGET_YEAR;
+ const isMonth = (month: unknown) =>
+ Number.isInteger(month) && (month as number) >= 1 && (month as number) <= 12;
+
+ const months = new Set();
+ for (const entry of entries) {
+ if (!isLine(entry) || !isYear(entry.year) || !isMonth(entry.month)) throw refusal();
+ const key = `${entry.category_id}/${entry.year}/${entry.month}`;
+ if (months.has(key)) throw refusal();
+ months.add(key);
+ }
+
+ const names = new Set();
+ for (const template of templates) {
+ if (typeof template?.name !== "string" || names.has(template.name)) throw refusal();
+ names.add(template.name);
+ if (!Array.isArray(template.entries)) throw refusal();
+ const lines = new Set();
+ for (const line of template.entries) {
+ if (!isLine(line) || lines.has(line.category_id)) throw refusal();
+ lines.add(line.category_id);
+ }
+ }
+
+ for (const adjustment of adjustments) {
+ if (
+ typeof adjustment?.name !== "string" ||
+ typeof adjustment.date !== "string" ||
+ !Array.isArray(adjustment.entries)
+ ) {
+ throw refusal();
+ }
+ for (const line of adjustment.entries) {
+ if (!isLine(line)) throw refusal();
+ }
+ }
+}
+
export function parseImportedJson(content: string): {
envelope: ExportEnvelope;
summary: ImportSummary;
@@ -434,9 +733,14 @@ export function parseImportedJson(content: string): {
!envelope.data ||
typeof envelope.data !== "object"
) {
- throw new Error("Invalid export file format — missing required fields");
+ throw new Error(INVALID_ENVELOPE);
}
+ // A newer format first: a later build may also bring a mode this one does
+ // not know, and « update the app » is then the message that helps (#520).
+ const formatVersion = envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION;
+ validateImportedFormatVersion(formatVersion);
+
const validTypes: ExportMode[] = [
"transactions_with_categories",
"transactions_only",
@@ -447,9 +751,9 @@ export function parseImportedJson(content: string): {
}
// Refuse an unreadable configuration, split lines that cannot find their
- // parent, or a category reference the file cannot satisfy, while the file is
- // only being LOOKED at: the confirmation dialog never opens, so nothing is
- // deleted.
+ // parent, a category reference the file cannot satisfy, or budget lines the
+ // restore could not write back, while the file is only being LOOKED at: the
+ // confirmation dialog never opens, so nothing is deleted.
validateImportedFormatRows(
envelope.data.import_sources,
envelope.data.import_config_templates
@@ -460,6 +764,11 @@ export function parseImportedJson(content: string): {
envelope.data.suppliers,
envelope.data.keywords
);
+ // The budget travels with the categories, in the two modes that carry them;
+ // « Transactions uniquement » carries none and its restore touches none.
+ if (envelope.export_type !== "transactions_only") {
+ validateImportedBudget(envelope.data, formatVersion);
+ }
return {
envelope,
@@ -471,7 +780,10 @@ export function parseImportedJson(content: string): {
transactionsCount: envelope.data.transactions?.length ?? 0,
importSourcesCount: envelope.data.import_sources?.length ?? 0,
importTemplatesCount: envelope.data.import_config_templates?.length ?? 0,
- formatVersion: envelope.format_version ?? LEGACY_SREF_FORMAT_VERSION,
+ budgetEntriesCount: envelope.data.budget_entries?.length ?? 0,
+ budgetTemplatesCount: envelope.data.budget_templates?.length ?? 0,
+ adjustmentsCount: envelope.data.adjustments?.length ?? 0,
+ formatVersion,
},
};
}
@@ -531,9 +843,12 @@ export function parseImportedCsv(content: string): {
suppliersCount: 0,
keywordsCount: 0,
transactionsCount: transactions.length,
- // A flat CSV carries no configuration at all.
+ // A flat CSV carries no configuration at all, and no budget.
importSourcesCount: 0,
importTemplatesCount: 0,
+ budgetEntriesCount: 0,
+ budgetTemplatesCount: 0,
+ adjustmentsCount: 0,
formatVersion: LEGACY_SREF_FORMAT_VERSION,
},
};
diff --git a/src/services/dataRestoreService.ts b/src/services/dataRestoreService.ts
index 059281b..f0ec475 100644
--- a/src/services/dataRestoreService.ts
+++ b/src/services/dataRestoreService.ts
@@ -5,8 +5,11 @@ import { logWarn } from "./logService";
import { toSqlFlag } from "../utils/sqlFlag";
import type { Category, Keyword, Supplier } from "../shared/types";
import {
+ BUDGET_SREF_FORMAT_VERSION,
+ validateImportedBudget,
validateImportedCategoryReferences,
validateImportedFormatRows,
+ validateImportedFormatVersion,
validateImportedTransactionIds,
type ExportEnvelope,
type ExportImportSource,
@@ -201,6 +204,10 @@ async function runRestore(body: (db: Database) => Promise): Promise {
* any order passes, loops included, and the hierarchy check repairs a loop
* afterwards (#393). `validateImportedCategoryReferences` has already refused a
* parent the file does not hold.
+ *
+ * Each category goes back with its `i18n_key` (#520), which the export carries
+ * (`SELECT *`): without it, the categories of the standard seed came back
+ * under their French name in the English interface.
*/
async function restoreCategories(
db: Database,
@@ -208,8 +215,8 @@ async function restoreCategories(
): Promise {
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)`,
+ `INSERT INTO categories (id, name, parent_id, color, icon, type, is_active, is_inputable, sort_order, i18n_key)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
[
cat.id,
cat.name,
@@ -220,6 +227,7 @@ async function restoreCategories(
cat.is_active ? 1 : 0,
cat.is_inputable ? 1 : 0,
cat.sort_order,
+ cat.i18n_key ?? null,
]
);
}
@@ -512,12 +520,201 @@ async function restoreTransfers(
return transfers.length - kept.length;
}
+/** The budget of the profile as a restore takes it out (#520): every line that names a category. */
+interface HeldBudget {
+ entries: Array<{
+ id: number;
+ category_id: number;
+ year: number;
+ month: number;
+ amount: number;
+ notes: string | null;
+ created_at: string;
+ updated_at: string;
+ }>;
+ templateLines: Array<{
+ id: number;
+ template_id: number;
+ template_name: string;
+ category_id: number;
+ amount: number;
+ }>;
+ adjustmentLines: Array<{
+ id: number;
+ adjustment_id: number;
+ category_id: number;
+ amount: number;
+ description: string | null;
+ }>;
+}
+
+/**
+ * Read the profile's budget lines, template lines and adjustment lines, then
+ * remove them, ahead of `DELETE FROM categories` (#520).
+ *
+ * The three tables name a category `ON DELETE CASCADE`: the deletion of the
+ * categories used to take every one of their lines with it, and the backup
+ * held none, so a restore with categories left the budget, its templates and
+ * the adjustments empty, without a word. They are read first, in both formats
+ * and by the restore's handle, so that `restoreBudget` can put back what the
+ * file does not replace. The headers of the templates and of the adjustments
+ * name no category, and stay.
+ */
+async function takeBudget(db: Database): Promise {
+ const entries = await db.select(
+ "SELECT id, category_id, year, month, amount, notes, created_at, updated_at FROM budget_entries ORDER BY id"
+ );
+ const templateLines = await db.select(
+ `SELECT e.id, e.template_id, t.name AS template_name, e.category_id, e.amount
+ FROM budget_template_entries e
+ JOIN budget_templates t ON t.id = e.template_id
+ ORDER BY e.id`
+ );
+ const adjustmentLines = await db.select(
+ "SELECT id, adjustment_id, category_id, amount, description FROM adjustment_entries ORDER BY id"
+ );
+ await db.execute("DELETE FROM budget_entries");
+ await db.execute("DELETE FROM budget_template_entries");
+ await db.execute("DELETE FROM adjustment_entries");
+ return { entries, templateLines, adjustmentLines };
+}
+
+/**
+ * Put the budget back once the file's categories are in (#520).
+ *
+ * From format 3 on, the file carries the budget. Its budget lines and its
+ * adjustments, with their lines, replace the profile's: a restore gives back
+ * the state of the backup. Each template of the file is inserted, or updated
+ * by its name, the table's natural key, and gets the file's lines. A template
+ * the file does not hold keeps its header and the lines whose category came
+ * back, as #331 keeps the import templates.
+ *
+ * A file of an earlier format holds no budget: every line taken out by
+ * `takeBudget` comes back as it was when its category does, under the same id
+ * (ADR 0025 says why the id alone is trusted). Everything is written through
+ * the restore's handle, after the categories, which it reads once.
+ */
+async function restoreBudget(
+ db: Database,
+ held: HeldBudget,
+ data: ExportEnvelope["data"],
+ formatVersion: number
+): Promise {
+ const categoryIds = new Set(
+ (await db.select>("SELECT id FROM categories")).map(
+ (row) => row.id
+ )
+ );
+ const comesBack = (line: { category_id: number }) => categoryIds.has(line.category_id);
+ const fromFile = formatVersion >= BUDGET_SREF_FORMAT_VERSION;
+
+ if (fromFile) {
+ for (const entry of data.budget_entries ?? []) {
+ await db.execute(
+ `INSERT INTO budget_entries (category_id, year, month, amount, notes)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [entry.category_id, entry.year, entry.month, entry.amount, entry.notes ?? null]
+ );
+ }
+ // The profile's adjustments go: their lines went with `takeBudget`.
+ await db.execute("DELETE FROM adjustments");
+ for (const adjustment of data.adjustments ?? []) {
+ const result = await db.execute(
+ `INSERT INTO adjustments (name, description, date, is_recurring, recurrence_rule)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [
+ adjustment.name,
+ adjustment.description ?? null,
+ adjustment.date,
+ toSqlFlag(adjustment.is_recurring),
+ adjustment.recurrence_rule ?? null,
+ ]
+ );
+ for (const line of adjustment.entries) {
+ await db.execute(
+ `INSERT INTO adjustment_entries (adjustment_id, category_id, amount, description)
+ VALUES ($1, $2, $3, $4)`,
+ [result.lastInsertId, line.category_id, line.amount, line.description ?? null]
+ );
+ }
+ }
+ } else {
+ for (const entry of held.entries.filter(comesBack)) {
+ await db.execute(
+ `INSERT INTO budget_entries (id, category_id, year, month, amount, notes, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ entry.id,
+ entry.category_id,
+ entry.year,
+ entry.month,
+ entry.amount,
+ entry.notes,
+ entry.created_at,
+ entry.updated_at,
+ ]
+ );
+ }
+ for (const line of held.adjustmentLines.filter(comesBack)) {
+ await db.execute(
+ `INSERT INTO adjustment_entries (id, adjustment_id, category_id, amount, description)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [line.id, line.adjustment_id, line.category_id, line.amount, line.description]
+ );
+ }
+ }
+
+ // The templates of the file, by name, with the file's lines.
+ const fileTemplates = fromFile ? data.budget_templates ?? [] : [];
+ for (const template of fileTemplates) {
+ await db.execute(
+ `INSERT INTO budget_templates (name, description) VALUES ($1, $2)
+ ON CONFLICT(name) DO UPDATE SET description = excluded.description`,
+ [template.name, template.description ?? null]
+ );
+ // `lastInsertId` is 0 on the conflict branch: the id is read back by name,
+ // as `restoreImportTemplates` does.
+ const [row] = await db.select>(
+ "SELECT id FROM budget_templates WHERE name = $1",
+ [template.name]
+ );
+ for (const line of template.entries) {
+ await db.execute(
+ `INSERT INTO budget_template_entries (template_id, category_id, amount)
+ VALUES ($1, $2, $3)`,
+ [row.id, line.category_id, line.amount]
+ );
+ }
+ }
+ // The other templates keep the lines whose category came back.
+ const inFile = new Set(fileTemplates.map((template) => template.name));
+ for (const line of held.templateLines) {
+ if (inFile.has(line.template_name) || !comesBack(line)) continue;
+ await db.execute(
+ `INSERT INTO budget_template_entries (id, template_id, category_id, amount)
+ VALUES ($1, $2, $3, $4)`,
+ [line.id, line.template_id, line.category_id, line.amount]
+ );
+ }
+}
+
+/**
+ * Restore the categories, keywords and suppliers of a file, and from format 3
+ * on its budget (#520); `formatVersion` as for
+ * `importTransactionsWithCategories`.
+ */
export async function importCategoriesOnly(
- data: ExportEnvelope["data"]
+ data: ExportEnvelope["data"],
+ formatVersion: number
): Promise {
+ validateImportedFormatVersion(formatVersion);
validateImportedCategoryReferences(data.categories, data.suppliers, data.keywords);
+ validateImportedBudget(data, formatVersion);
return runRestore(async (db) => {
+ // The budget names the categories: taken out before they go (#520).
+ const budget = await takeBudget(db);
+
// Wipe keywords, suppliers, categories
await db.execute("DELETE FROM keywords");
await db.execute("DELETE FROM suppliers");
@@ -531,22 +728,35 @@ export async function importCategoriesOnly(
await restoreCategories(db, data.categories);
await restoreSuppliers(db, data.suppliers);
await restoreKeywords(db, data.keywords);
+ await restoreBudget(db, budget, data, formatVersion);
// No transaction is deleted: every transfer stays linked.
return { unlinkedTransfers: 0, uncategorizedTransactions: 0 };
});
}
+/**
+ * Restore a full backup. `formatVersion` is the file's (`ImportSummary`,
+ * `LEGACY_SREF_FORMAT_VERSION` when it declares none): from format 3 on, the
+ * file's budget replaces the profile's, and below, the profile's lines whose
+ * category comes back are kept (#520). It is never guessed from the arrays the
+ * file holds: a truncated file would pass for an old one.
+ */
export async function importTransactionsWithCategories(
data: ExportEnvelope["data"],
- filename: string
+ filename: string,
+ formatVersion: number
): Promise {
+ validateImportedFormatVersion(formatVersion);
validateImportedFormatRows(data.import_sources, data.import_config_templates);
const { keepIds } = validateImportedTransactionIds(data.transactions);
validateImportedCategoryReferences(data.categories, data.suppliers, data.keywords);
+ validateImportedBudget(data, formatVersion);
const outcome = await runRestore(async (db) => {
const transfers = await takeTransfers(db);
+ // The budget names the categories: taken out before they go (#520).
+ const budget = await takeBudget(db);
// Wipe everything
await db.execute("DELETE FROM transactions");
@@ -559,6 +769,7 @@ export async function importTransactionsWithCategories(
await restoreCategories(db, data.categories);
await restoreSuppliers(db, data.suppliers);
await restoreKeywords(db, data.keywords);
+ await restoreBudget(db, budget, data, formatVersion);
// Templates first: `import_sources.template_id` points at them.
const templateIds = await restoreImportTemplates(