fix: unlink Balance transfers from the window and the import history (#522) #537

Merged
maximus merged 3 commits from issue-522-unlink-balance-transfers into main 2026-11-09 01:29:48 +00:00
21 changed files with 1609 additions and 74 deletions

View file

@ -5,6 +5,8 @@
### Ajouté
- Catégories : un bouton « Vérifier la hiérarchie », entre « Tous les mots-clés » et « Réinitialiser », liste les catégories orphelines : celles prises dans une boucle de parenté, qui les cache avec leurs sous-catégories de l'arbre, des menus de catégories, du budget et des rapports, et celles dont le parent a été supprimé ou est introuvable. Chacune se rattache à la racine, choisie par défaut, ou à un autre parent, vérifié comme dans le formulaire de catégorie ; elle revient alors à sa place avec ses transactions, ses mots-clés et ses montants de budget. Le Journal note chaque rattachement, sans nom de catégorie (#393).
- Bilan : une transaction déjà liée à un compte de bilan s'affiche désormais en tête de « Lier transferts », cochée, quelle que soit la période choisie ; décochez-la puis enregistrez pour la délier. Le bouton d'enregistrement lie les transactions nouvellement cochées et délie celles qu'on décoche (#522).
- Historique des imports : un import dont des transactions sont liées au Bilan se supprime désormais dans toute édition par « Délier et supprimer », après une confirmation qui dit combien de transferts du Bilan seront perdus sans retour, même avec une clé. Les transferts, les transactions et l'import partent ensemble, ou rien ne change si une étape échoue (#522).
### Modifié
@ -22,6 +24,7 @@
### Corrigé
- Historique des imports : supprimer un import dont des transactions sont liées au Bilan n'affiche plus un message d'erreur anglais brut dans les deux langues. Le message est traduit, nomme les comptes (trois, puis « et N autres »), donne le nombre de transferts liés et, quand l'édition ouvre le Bilan, offre le lien vers « Lier transferts » de chaque compte (#522).
- Catégories : un nouveau parent est désormais vérifié à l'enregistrement d'une catégorie. L'une de ses propres sous-catégories (la boucle de parenté qui cachait toute une branche) et un parent qui créerait un quatrième niveau sont refusés avec un message, et rien n'est enregistré. Une catégorie encore saisissable ne peut pas devenir parent tant qu'elle a des transactions, un montant de budget non nul (d'une année quelconque, ou dans un modèle de budget) ou des mots-clés à son nom, puisqu'elle ne serait plus saisissable : la vérification se fait à l'enregistrement d'une catégorie comme à la création d'une sous-catégorie, et le message dit quoi déplacer d'abord. Un parent existant, qui n'est plus saisissable, accepte de nouvelles sous-catégories comme avant. Une catégorie enregistrée sans changement de parent n'est jamais refusée par ces vérifications (#393).
- Budget : une catégorie dont le parent a été supprimé ou est introuvable ne disparaît plus de la grille Budget ni du rapport Budget vs réel : elle s'affiche au premier niveau, comme dans l'arbre des catégories (#393).
- Import : les messages de « Créer un dossier d'exemple » suivent désormais la langue de l'application : un dossier d'exemple déjà présent dans le dossier d'import (nommé, avec la marche à suivre : actualiser la liste, ou le renommer s'il n'y apparaît pas), un dossier d'import introuvable, une date du jour illisible. Toute autre erreur reste affichée telle que le système l'a écrite. Une fois les dossiers d'exemple écrits, le message de réussite ne s'affiche que si le dossier d'import a pu être relu ; sinon le message d'erreur s'affiche seul, au lieu des deux à la fois (#384).

View file

@ -5,6 +5,8 @@
### Added
- Categories: a “Check hierarchy” button, between “All keywords” and “Re-initialize”, lists the orphan categories: those caught in a parent loop, which hides them and their subcategories from the tree, the category menus, the budget and the reports, and those whose parent was deleted or cannot be found. Each one can be reattached to the root, chosen by default, or to another parent, checked as in the category form; it then comes back in its place with its transactions, keywords and budget amounts. The Journal notes each reattachment, without any category name (#393).
- Balance sheet: a transaction already linked to a balance account now shows first in “Link transfers”, checked, whatever the period chosen; uncheck it and save to unlink it. The save button now links the newly checked transactions and unlinks the unchecked ones (#522).
- Import history: an import that holds transactions linked to the Balance sheet can now be deleted in every edition with “Unlink and delete”, after a confirmation that says how many Balance transfers will be lost for good, even with a key. The transfers, the transactions and the import go together, or nothing changes if a step fails (#522).
### Changed
@ -22,6 +24,7 @@
### Fixed
- Import history: deleting an import that holds transactions linked to the Balance sheet no longer shows a raw English error in both languages. The message is translated, names the accounts (three, then “and N others”), gives the number of linked transfers and, when the edition opens the Balance sheet, links to each account’s “Link transfers” (#522).
- Categories: a new parent is now checked when a category is saved. One of the category's own subcategories (the parent loop that hid a whole branch) and a parent that would make a fourth level are refused with a message, and nothing is saved. A category that still takes input cannot become a parent while it holds transactions, a budget amount other than zero (of any year, or in a budget template) or keywords of its own, since it would no longer take input: this is checked when a category is saved and when a subcategory is created, and the message says what to move first. An existing parent, which no longer takes input, accepts new subcategories as before. A category saved with its parent unchanged is never refused by these checks (#393).
- Budget: a category whose parent was deleted or cannot be found no longer disappears from the Budget grid and the Budget vs Actual report: it now shows at the top level, as in the category tree (#393).
- Import: the messages of “Create a sample folder” now follow the app's language: a sample folder already in the import folder (named, with what to do: refresh the list, or rename it if it does not show up), an import folder that cannot be found, today's date unreadable. Any other error still shows as the system wrote it. Once the sample folders are written, the success message only shows when the import folder could be read again; otherwise the error message shows alone, instead of both at once (#384).

View file

@ -4,7 +4,9 @@
- 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). 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).
> **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 » a son écran depuis l'amendement #522 ci-dessous. 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).
> **Amendement du 2026-11-08 (#522)** — La section « UX correspondante » promettait un chemin de déliaison à un clic du message ; aucun écran ne l'offrait. `unlinkTransfer` n'avait aucun appelant, « Lier transferts » listait une transaction liée décochée, et l'historique d'import affichait le texte anglais de l'erreur dans les deux langues. Le Bilan est réservé à Premium (ADR 0017) et l'historique d'import non : un « Délier » placé dans le seul Bilan laissait bloquée une personne retombée en Gratuite. Décisions de Max du 2026-11-07 (`/analyze 522`) : (1) **Délier dans la fenêtre** : `LinkTransfersModal` charge les transferts du compte sans borne de date et les affiche en tête, cochés, avec leur sens enregistré (pour le changer : décocher, enregistrer, recocher) ; l'enregistrement compare la sélection à cet état, lie les lignes nouvellement cochées et délie les lignes liées décochées. (2) **Refus traduit** : l'historique d'import garde un refus structuré (`useImportHistory`), nomme les comptes (trois, puis « et N autres ») et compte les transferts par un `COUNT(*)` (`getLinkedTransfersSummary`), jamais par la liste de pré-vérification (`LIMIT 50`). Le lien vers « Lier transferts » d'un compte (`/balance?linkTransfers=<id>`) n'est offert que si l'édition ouvre le Bilan, et seulement pour un compte actif. (3) **« Délier et supprimer », dans toute édition** : après une confirmation qui dit combien de transferts seront perdus sans retour, même avec une clé, `unlinkAndDeleteImport` ou `unlinkAndDeleteAllImports` supprime les transferts des transactions visées (enfants d'une répartition compris), puis les transactions, l'import et la source orpheline, en une seule transaction SQL : une étape qui échoue ne laisse rien bouger. Le Journal ne reçoit que les nombres. `ON DELETE RESTRICT` reste en place : la perte d'un transfert n'arrive plus jamais en silence, elle est annoncée et choisie.
## Context
@ -45,9 +47,9 @@ La couche service `transactionService.ts` détecte l'erreur SQLite `FOREIGN KEY
> **Cette transaction est liée au compte de bilan _<nom du compte>_.**
> Pour la supprimer, déliez-la d'abord : ouvrez le compte → Lier transferts → décochez cette transaction.
Avec un lien direct vers la `LinkTransfersModal` du compte concerné. L'utilisateur ne peut pas se retrouver bloqué : le chemin de déliaison est toujours dispo, à un clic du message d'erreur.
Avec un lien direct vers la `LinkTransfersModal` du compte concerné. L'utilisateur ne peut pas se retrouver bloqué : le chemin de déliaison est toujours dispo, à un clic du message d'erreur. Écrans réels depuis l'amendement #522 : les transactions liées s'affichent cochées en tête de la fenêtre et se délient en les décochant ; le lien n'est offert que si l'édition ouvre le Bilan ; dans toute édition, l'historique d'import offre « Délier et supprimer » derrière une confirmation qui dit le nombre de transferts perdus.
Pour les chemins bulk (`deleteImportWithTransactions`, `deleteAllImportsWithTransactions`), une pré-vérification SELECT (`LIMIT 50`) liste les premiers transferts liés AVANT de tenter la suppression — l'utilisateur voit un message agrégé "X transactions de cet import sont liées à des comptes de bilan" plutôt qu'un raw FK error toast.
Pour les chemins bulk (`deleteImportWithTransactions`, `deleteAllImportsWithTransactions`), une pré-vérification SELECT (`LIMIT 50`) liste les premiers transferts liés AVANT de tenter la suppression — l'utilisateur voit un message agrégé "X transactions de cet import sont liées à des comptes de bilan" plutôt qu'un raw FK error toast. Depuis #522, le nombre affiché vient d'un `COUNT(*)` par compte (`getLinkedTransfersSummary`), pas de cette liste bornée.
### Direction CASCADE conservée pour `account_id`
@ -81,7 +83,7 @@ L'asymétrie est délibérée :
## References
- 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)
- 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` ; déliement et « Délier et supprimer » (amendement #522) : `src/components/balance/LinkTransfersModal.tsx`, `src/services/importedFileService.ts`, `src/hooks/useImportHistory.ts`, `src/components/import/LinkedTransfersNotice.tsx`
- 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), `src/__integration__/unlink-and-delete-import.test.ts` (compte réel, « Délier et supprimer » et retour arrière, #522), `src/components/balance/LinkTransfersModal.unlink.test.ts` (déliement depuis la fenêtre, #522)
- 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é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)

View file

@ -33,7 +33,7 @@ simpl-resultat/
│ │ ├── categories/ # 8 composants (dont HierarchyCheckModal, #393)
│ │ ├── categories-migration/ # 5 composants (flux de migration des catégories v1→v2 de CategoriesMigrationPage : StepDiscover, StepSimulate, StepConsent, MappingRow, TransactionPreviewPanel)
│ │ ├── dashboard/ # 7 composants (dont DashboardEmptyState et OnboardingChecklist)
│ │ ├── import/ # 18 composants (wizard d'import, dont FormatDriftPanel, RepairPathNotice, ImportEmptyState, ImportFolderStructure, RootFilesWarning et SourceNameDisplay)
│ │ ├── import/ # 19 composants (wizard d'import, dont FormatDriftPanel, RepairPathNotice, ImportEmptyState, ImportFolderStructure, RootFilesWarning, SourceNameDisplay et LinkedTransfersNotice)
│ │ ├── layout/ # AppShell, Sidebar
│ │ ├── onboarding/ # OnboardingBanner (bandeau de démarrage, #397), StepCard et OnboardingStepCard (carte d'étape, #398)
│ │ ├── profile/ # 3 composants (PIN, formulaire, switcher)
@ -46,7 +46,7 @@ simpl-resultat/
│ ├── pages/ # 14 pages (dont 4 sous-pages rapports)
│ ├── services/ # 30 services métier (24 détaillés dans la section « Services TypeScript »)
│ ├── shared/ # Types, constantes, matrice d'entitlements (entitlements.ts), gate profils (profileGate.ts), gate de la Répartition (splitGate.ts), CTA d'upsell (upsellCta.ts), URL d'achat (purchaseUrl.ts), échéance de licence (licenseExpiry.ts)
│ ├── utils/ # 22 utilitaires purs (parsing montants/dates, détection CSV, codec de format d'import, dictionnaire lexical, signatures de banques, charts, drapeaux SQL 0/1, liste et parcours de démarrage, historique des versions, hiérarchie des catégories, ligne de compensation d'une répartition, convention de signe des rapports)
│ ├── utils/ # 23 utilitaires purs (parsing montants/dates, détection CSV, codec de format d'import, dictionnaire lexical, signatures de banques, charts, drapeaux SQL 0/1, liste et parcours de démarrage, historique des versions, hiérarchie des catégories, ligne de compensation d'une répartition, convention de signe des rapports, lien vers « Lier transferts » d'un compte)
│ ├── i18n/ # Config i18next + locales FR/EN
│ ├── __fixtures__/ # csv/ : corpus de détection (15 cas figés) ; samples/ : gabarits du dossier d'exemple embarqués par Rust
│ ├── App.tsx # Router principal
@ -204,7 +204,7 @@ Le dossier des bases est celui du plugin : `app_config_dir()`, résolu par `prof
| `categoryService.ts` | CRUD catégories hiérarchiques. `updateCategory` vérifie un nouveau parent, `reattachCategory` rattache une catégorie orpheline et `createCategory` vérifie ce que porte le parent d'une sous-catégorie quand il deviendrait parent, chacun en une transaction par son handle ; `CategoryHierarchyError` typée ; `findOrphanCategories` (diagnostic, requête dédiée sur toutes les catégories) ; `getCategoryDepth` s'arrête sur un cycle — voir « Hiérarchie des catégories » |
| `transactionService.ts` | CRUD et filtrage des transactions ; détection d'erreurs FK RESTRICT pour transactions liées à un compte de bilan (typed `TransactionLinkedToBalanceError`) ; `getTransactionCount` (compte brut de la table, sans filtre — signal des états vides de Transactions et Budget, #351/#353) ; `updateTransactionCategory` écrit la catégorie dans une transaction (`withTransaction`, son `BEGIN`, son `COMMIT`, `ROLLBACK` puis relance sur un échec), où la ligne de compensation d'un parent réparti suit (`propagateCategoryToOffsets`), et ne notifie qu'après le `COMMIT` (#454) ; répartitions (`saveSplitAdjustment`, `deleteSplitAdjustment`) écrites dans une seule transaction, sur le même motif, le parent d'une répartition enregistrée lu avant toute écriture, et notifiées après le `COMMIT` seulement (#513) |
| `importSourceService.ts` | Configuration des sources d'import — lit et écrit le format complet via le codec `importFormat.ts` ([ADR 0019](adr/0019-format-import-persiste.md)) |
| `importedFileService.ts` | Suivi des fichiers importés |
| `importedFileService.ts` | Suivi des fichiers importés. Un import dont des transactions sont liées au Bilan (#522, ADR 0010) : `getLinkedTransfersSummary(scope)` compte ses transferts par compte (`COUNT(*)`, enfants d'une répartition compris), `unlinkAndDeleteImport(fileId)` et `unlinkAndDeleteAllImports()` suppriment transferts, transactions, import et source orpheline en une transaction (`withTransaction`, `BEGIN`/`COMMIT`/`ROLLBACK`), puis une ligne de Journal chiffrée et une notification |
| `importConfigTemplateService.ts` | Modèles de configuration d'import |
| `categorizationService.ts` | Catégorisation automatique + helpers édition de mot-clé (`validateKeyword`, `previewKeywordMatches`, `applyKeywordWithReassignment`). L'aperçu ne propose jamais un enfant de répartition (`parent_transaction_id IS NULL`) ; l'application ne reclasse jamais un enfant seul (`AND parent_transaction_id IS NULL`, `updatedTransactions` compté par `rowsAffected`) et, avant le `COMMIT`, fait suivre la ligne de compensation de chaque parent coché (`propagateCategoryToOffsets`, #454) |
| `splitOffsetService.ts` | Ligne de compensation d'une répartition (#454) : `propagateCategoryToOffsets(db, parentId, categoryId)` donne la catégorie du parent et son drapeau `is_manually_categorized` (lu sur la ligne du parent après l'`UPDATE` de l'appelant, lié par `toSqlFlag`) à l'enfant que reconnaît `isOffsetChild` (`utils/splitOffset.ts`, pur : description du parent, signe opposé au sien, montant non nul), quelle que soit sa catégorie actuelle, et rend le nombre de lignes déplacées. Le drapeau suit le parent parce qu'`autoCategorizeTransactions` prend toute ligne sans catégorie au drapeau 0, enfants compris : sous un parent mis à la main sur « Sans catégorie », une compensation restée à 0 partait seule vers la catégorie du mot-clé de sa description. `saveSplitAdjustment` lui donne aussi le drapeau du parent à sa création ; les entrées gardent 0. Rien pour un identifiant inconnu, une transaction non répartie ou un enfant (les enfants portent aussi `is_split = 1` : un parent est la ligne sans `parent_transaction_id`). Tourne sur le handle de la transaction de son appelant (`updateTransactionCategory`, `applyKeywordWithReassignment`) : jamais de `BEGIN` ni de `COMMIT`, de `getDb()` ni de notification. Module à part parce que `transactionService.ts` importe déjà `categorizationService.ts` ; il n'importe ni l'un ni l'autre. La fenêtre de répartition (`SplitAdjustmentModal`) écarte de ses entrées l'enfant que reconnaît le même prédicat |
@ -247,7 +247,7 @@ Les 30 fichiers `.ts` de `src/hooks/`, hors tests (`ls src/hooks/*.ts | grep -v
| `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). 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 |
| `useImportHistory` | Historique des imports ; un refus pour transferts du Bilan devient un état structuré (`blocked` : portée, comptes, nombre), puis « Délier et supprimer » (#522) |
| `useAdjustments` | Ajustements |
| `useBudget` | Budget |
| `useDashboard` | Tableau de bord (`/`) — convergé sur le modèle `/reports/cartes` (#279) : KPIs+deltas/top movers/adherence budget via `getCartesSnapshot` sur un mois de référence propre au Dashboard (`referenceYear`/`referenceMonth`, défaut mois précédent), barres classées + tendance par catégorie sur une période flexible propre (`period`/dates custom), filtre compte (`accountIds`) local partagé par les deux axes temporels, tuile valeur nette (Bilan) chargée une fois, indépendante du filtre compte |
@ -630,7 +630,7 @@ Les modules payants sont enveloppés dans des **layout-routes pathless `RequireF
| `/reports/compare` | `ReportsComparePage` | Comparables (MoM / YoY / Réel vs budget) |
| `/reports/category` | `ReportsCategoryPage` | Zoom catégorie avec rollup + édition contextuelle de mots-clés |
| `/reports/cartes` | `ReportsCartesPage` | Tableau de bord KPI avec sparklines, top movers, budget et saisonnalité |
| `/balance` | `BalancePage` | Bilan — vue d'ensemble : carte "Aujourd'hui" + Δ% + avertissement bilan pas à jour > 60j, graphique d'évolution (toggle ligne / aire empilée par catégorie), tableau des comptes avec rendements multi-horizons (3M / 1A / depuis création — Modified Dietz) côte-à-côte avec rendement non-ajusté |
| `/balance` | `BalancePage` | Bilan — vue d'ensemble : carte "Aujourd'hui" + Δ% + avertissement bilan pas à jour > 60j, graphique d'évolution (toggle ligne / aire empilée par catégorie), tableau des comptes avec rendements multi-horizons (3M / 1A / depuis création — Modified Dietz) côte-à-côte avec rendement non-ajusté ; `?linkTransfers=<id>` ouvre « Lier transferts » d'un compte actif, puis le paramètre est retiré (#522) |
| `/balance/snapshot` | `SnapshotEditPage` | Saisie / édition d'un snapshot daté. Mode `?date=today` (création) ou `?date=YYYY-MM-DD` (édition, date immutable). Lignes groupées par catégorie : `simple` = champ valeur, `priced` = `quantity` × `unit_price` (`value` calculé read-only). Bouton "Pré-remplir depuis le snapshot précédent". Suppression à double-confirmation par re-saisie de la date |
| `/balance/accounts` | `AccountsPage` | CRUD comptes + catégories de bilan (deux onglets). Catégories seedées (`is_seed = 1`) renommables mais non-supprimables ; refus de suppression d'une catégorie avec comptes liés (FK RESTRICT) |
| `/settings` | `SettingsLayout` (layout) + `SettingsHomePage` (index) | Hub des paramètres : 3 cards-cluster vers les sous-pages. Le layout monte `TokenStoreFallbackBanner` une seule fois, partagé par les 4 routes principales |

View file

@ -534,7 +534,7 @@ L'entrée **Bilan** dans la barre latérale (icône portefeuille) donne accès
3. Cliquez **+ Nouveau snapshot** depuis `/balance` pour ouvrir `/balance/snapshot` à la date du jour
4. Remplissez les valeurs par compte (groupées par catégorie). Pour les comptes priced, saisissez la quantité et le prix unitaire — la valeur est calculée
5. Enregistrez. Le graphique sur `/balance` s'actualise immédiatement
6. Pour calculer le rendement réel d'un compte d'investissement, ouvrez le menu actions du compte → **Lier transferts** → cochez les transactions qui correspondent à des apports / retraits (un dépôt CELI, un achat d'actions, etc.). Le sens (in/out) est proposé automatiquement selon le signe de la transaction
6. Pour calculer le rendement réel d'un compte d'investissement, ouvrez le menu actions du compte → **Lier transferts** → cochez les transactions qui correspondent à des apports / retraits (un dépôt CELI, un achat d'actions, etc.). Le sens (in/out) est proposé automatiquement selon le signe de la transaction. Les transactions déjà liées au compte s'affichent en tête, cochées, quelle que soit la période choisie : décochez-en une puis cliquez **Enregistrer** pour la délier
7. Le tableau des comptes affiche maintenant les rendements Modified Dietz sur 3M / 1A / depuis création. Le rendement non-ajusté à droite vous permet de comparer "valeur du compte" et "vraie performance"
8. Pour suivre un compte **titre par titre**, soit créez-le détaillé, soit ouvrez son menu d'actions → **Détailler en titres** (assistant) ; aux snapshots suivants, ajoutez chaque valeur mobilière avec sa quantité, son cours et son coût d'acquisition. Voir [Détail par titre](#détail-par-titre)
9. Pour éditer un snapshot existant, cliquez sur son point dans le graphique ou utilisez le sélecteur de date — la page s'ouvre en mode édition. Vous pouvez aussi y corriger la date : changez-la puis enregistrez, le snapshot est déplacé avec ses lignes (un message s'affiche si la date cible est déjà prise par un autre snapshot)
@ -576,7 +576,7 @@ Un compte d'investissement peut être suivi **titre par titre** plutôt qu'en mo
### Que faire si je supprime une transaction liée ?
C'est intentionnellement bloqué : si vous tentez de supprimer une transaction qui est liée à un compte de bilan, vous voyez le message **"Cette transaction est liée au compte de bilan _<nom>_"** avec un lien direct vers le compte. Ouvrez le compte → Lier transferts → décochez la transaction → revenez la supprimer. Cette friction préserve la reproductibilité de vos rendements passés (un rendement calculé hier ne peut pas changer aujourd'hui à cause d'une suppression silencieuse).
C'est intentionnellement bloqué : si vous supprimez, dans l'historique d'import, un import dont une transaction est liée à un compte de bilan, la suppression est refusée et un message nomme le ou les comptes et dit combien de transferts sont liés. Deux chemins : le bouton **Lier transferts : _<compte>_** (édition Premium, compte actif) ouvre la fenêtre du compte, où la transaction est cochée en tête ; décochez-la, enregistrez, puis revenez supprimer l'import. Ou, dans toute édition, **Délier et supprimer** délie ces transferts et supprime l'import en une fois, après une confirmation qui dit combien de transferts seront perdus : ils le sont sans retour, même avec une clé, et si une étape échoue, rien n'est modifié. Cette friction préserve la reproductibilité de vos rendements passés (un rendement calculé hier ne peut pas changer aujourd'hui à cause d'une suppression silencieuse).
### Astuces

View file

@ -0,0 +1,277 @@
/**
* An import whose transactions are linked to the Balance sheet (#522).
*
* Deleting such an import is refused (`ON DELETE RESTRICT`, ADR 0010), and the
* history used to print the raw English error with no way out. The panel now
* counts the transfers it would lose (`getLinkedTransfersSummary`, a real
* `COUNT(*)`, not the 50-row pre-flight) and offers to unlink them and delete
* in one SQL transaction (`unlinkAndDeleteImport`, `unlinkAndDeleteAllImports`).
*
* Every case runs on a real SQLite database with foreign keys on
* (`src/test/sqliteHarness.ts`), with the four starter balance accounts of a
* new profile (Compte chèque, CELI, REER, Compte non-enregistré).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { DatabaseSync } from "node:sqlite";
vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
const { logInfo } = vi.hoisted(() => ({ logInfo: vi.fn() }));
vi.mock("../services/logService", () => ({ logInfo, logWarn: vi.fn(), logError: vi.fn() }));
import { openProfileDb, useDb } from "../test/sqliteHarness";
import { subscribeDataChanged } from "../services/dataEvents";
import { TransactionLinkedToBalanceError } from "../services/transactionService";
import {
deleteImportWithTransactions,
getLinkedTransfersSummary,
unlinkAndDeleteAllImports,
unlinkAndDeleteImport,
} from "../services/importedFileService";
let db: DatabaseSync;
let notifications = 0;
let unsubscribe: () => void = () => undefined;
const count = (sql: string, ...params: (number | string)[]) =>
Number((db.prepare(sql).get(...params) as { n: number }).n);
const accountId = (name: string) =>
Number((db.prepare("SELECT id FROM balance_accounts WHERE name = ?").get(name) as { id: number }).id);
/** A source with one imported file of `rows` transactions; returns their ids. */
function seedImport(sourceName: string, rows: number): { sourceId: number; fileId: number; txIds: number[] } {
const sourceId = Number(
db.prepare("INSERT INTO import_sources (name, column_mapping) VALUES (?, '{}')").run(sourceName)
.lastInsertRowid,
);
const fileId = Number(
db
.prepare("INSERT INTO imported_files (source_id, filename, file_hash, row_count) VALUES (?, ?, ?, ?)")
.run(sourceId, `${sourceName}.csv`, `hash-${sourceName}`, rows).lastInsertRowid,
);
const insert = db.prepare(
"INSERT INTO transactions (date, description, amount, source_id, file_id) VALUES (?, ?, ?, ?, ?)",
);
const txIds: number[] = [];
for (let i = 0; i < rows; i++) {
const day = String((i % 28) + 1).padStart(2, "0");
txIds.push(Number(insert.run(`2026-01-${day}`, `Virement ${i}`, -100 - i, sourceId, fileId).lastInsertRowid));
}
return { sourceId, fileId, txIds };
}
function link(account: string, transactionId: number, direction: "in" | "out" = "in") {
db.prepare("INSERT INTO balance_account_transfers (account_id, transaction_id, direction) VALUES (?, ?, ?)").run(
accountId(account),
transactionId,
direction,
);
}
beforeEach(() => {
db = useDb(openProfileDb());
notifications = 0;
unsubscribe = subscribeDataChanged(() => {
notifications += 1;
});
logInfo.mockClear();
});
afterEach(() => {
unsubscribe();
db.close();
});
describe("getLinkedTransfersSummary (#522)", () => {
it("counts every transfer of one import, beyond the 50 rows of the pre-flight, per account sorted by name", async () => {
const { fileId, txIds } = seedImport("Desjardins", 70);
for (const id of txIds.slice(0, 60)) link("REER", id);
link("CELI", txIds[60]);
const other = seedImport("Tangerine", 2);
link("CELI", other.txIds[0]);
const summary = await getLinkedTransfersSummary({ kind: "file", fileId });
expect(summary.transferCount).toBe(61);
expect(summary.accounts.map((a) => [a.account_name, a.transfer_count, a.is_active])).toEqual([
["CELI", 1, true],
["REER", 60, true],
]);
});
it("counts every transfer of the profile for the whole history, a manual transaction's link included", async () => {
const a = seedImport("Desjardins", 3);
const b = seedImport("Tangerine", 3);
link("CELI", a.txIds[0]);
link("REER", a.txIds[0]);
link("CELI", b.txIds[2]);
// Entered by hand, no import: "delete all" removes it and its link too.
const manual = Number(
db
.prepare("INSERT INTO transactions (date, description, amount) VALUES ('2026-02-01', 'Manuelle', -10)")
.run().lastInsertRowid,
);
link("Compte non-enregistré", manual);
const summary = await getLinkedTransfersSummary({ kind: "all" });
expect(summary.transferCount).toBe(4);
expect(summary.accounts.map((x) => x.account_name)).toEqual(["CELI", "Compte non-enregistré", "REER"]);
});
it("marks an archived account as inactive", async () => {
const { fileId, txIds } = seedImport("Desjardins", 1);
link("REER", txIds[0]);
db.prepare("UPDATE balance_accounts SET is_active = 0, archived_at = CURRENT_TIMESTAMP WHERE name = 'REER'").run();
const summary = await getLinkedTransfersSummary({ kind: "file", fileId });
expect(summary.accounts).toEqual([
{ account_id: accountId("REER"), account_name: "REER", is_active: false, transfer_count: 1 },
]);
});
it("counts a linked split child that does not carry the import's file_id", async () => {
const { fileId, sourceId, txIds } = seedImport("Desjardins", 1);
const child = Number(
db
.prepare(
"INSERT INTO transactions (date, description, amount, source_id, file_id, parent_transaction_id) VALUES ('2026-01-01', 'Part', -50, ?, NULL, ?)",
)
.run(sourceId, txIds[0]).lastInsertRowid,
);
link("CELI", child);
expect((await getLinkedTransfersSummary({ kind: "file", fileId })).transferCount).toBe(1);
});
});
describe("unlinkAndDeleteImport (#522)", () => {
it("the plain delete is still refused while a transfer is linked", async () => {
const { fileId, txIds } = seedImport("Desjardins", 2);
link("CELI", txIds[0]);
await expect(deleteImportWithTransactions(fileId)).rejects.toBeInstanceOf(TransactionLinkedToBalanceError);
});
it("removes the import's transfers, transactions, file and orphaned source together; another import keeps its own", async () => {
const target = seedImport("Desjardins", 70);
for (const id of target.txIds.slice(0, 55)) link("REER", id);
const kept = seedImport("Tangerine", 2);
link("CELI", kept.txIds[1], "out");
const outcome = await unlinkAndDeleteImport(target.fileId);
expect(outcome).toEqual({ unlinked: 55, deleted: 70 });
expect(count("SELECT COUNT(*) AS n FROM transactions WHERE file_id = ?", target.fileId)).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM imported_files WHERE id = ?", target.fileId)).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM import_sources WHERE id = ?", target.sourceId)).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers")).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers WHERE transaction_id = ?", kept.txIds[1])).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM transactions WHERE file_id = ?", kept.fileId)).toBe(2);
// The balance accounts themselves stay.
expect(count("SELECT COUNT(*) AS n FROM balance_accounts WHERE name = 'REER'")).toBe(1);
expect(notifications).toBe(1);
});
it("keeps the source when another import still uses it", async () => {
const first = seedImport("Desjardins", 1);
const second = Number(
db
.prepare("INSERT INTO imported_files (source_id, filename, file_hash) VALUES (?, 'b.csv', 'hash-b')")
.run(first.sourceId).lastInsertRowid,
);
link("CELI", first.txIds[0]);
await unlinkAndDeleteImport(first.fileId);
expect(count("SELECT COUNT(*) AS n FROM import_sources WHERE id = ?", first.sourceId)).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM imported_files WHERE id = ?", second)).toBe(1);
});
it("unlinks a split child the parent's cascade removes, instead of failing on its link", async () => {
const { fileId, sourceId, txIds } = seedImport("Desjardins", 1);
const child = Number(
db
.prepare(
"INSERT INTO transactions (date, description, amount, source_id, file_id, parent_transaction_id) VALUES ('2026-01-01', 'Part', -50, ?, NULL, ?)",
)
.run(sourceId, txIds[0]).lastInsertRowid,
);
link("CELI", child);
await expect(unlinkAndDeleteImport(fileId)).resolves.toEqual({ unlinked: 1, deleted: 1 });
expect(count("SELECT COUNT(*) AS n FROM transactions")).toBe(0);
});
it("leaves everything in place when a step fails, and announces nothing", async () => {
const { fileId, sourceId, txIds } = seedImport("Desjardins", 3);
link("CELI", txIds[0]);
link("REER", txIds[1]);
db.exec(
"CREATE TRIGGER refuse_file_delete BEFORE DELETE ON imported_files BEGIN SELECT RAISE(ABORT, 'refused by test'); END;",
);
await expect(unlinkAndDeleteImport(fileId)).rejects.toThrow("refused by test");
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers")).toBe(2);
expect(count("SELECT COUNT(*) AS n FROM transactions WHERE file_id = ?", fileId)).toBe(3);
expect(count("SELECT COUNT(*) AS n FROM imported_files WHERE id = ?", fileId)).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM import_sources WHERE id = ?", sourceId)).toBe(1);
expect(notifications).toBe(0);
expect(logInfo).not.toHaveBeenCalled();
});
it("writes one Journal line that carries the numbers and no account name", async () => {
const { fileId, txIds } = seedImport("Desjardins", 4);
link("CELI", txIds[0]);
link("Compte non-enregistré", txIds[1]);
await unlinkAndDeleteImport(fileId);
expect(logInfo).toHaveBeenCalledTimes(1);
const line = logInfo.mock.calls[0].map(String).join(" ");
expect(line).toContain("2 Balance transfer(s) unlinked");
expect(line).toContain("4 transaction(s) deleted");
for (const name of ["CELI", "REER", "Compte", "Desjardins"]) expect(line).not.toContain(name);
});
});
describe("unlinkAndDeleteAllImports (#522)", () => {
it("removes every transfer, transaction, import and source, a manual transaction's link included", async () => {
const a = seedImport("Desjardins", 2);
const b = seedImport("Tangerine", 2);
link("CELI", a.txIds[0]);
link("REER", b.txIds[1]);
const manual = Number(
db
.prepare("INSERT INTO transactions (date, description, amount) VALUES ('2026-02-01', 'Manuelle', -10)")
.run().lastInsertRowid,
);
link("CELI", manual);
await expect(unlinkAndDeleteAllImports()).resolves.toEqual({ unlinked: 3, deleted: 5 });
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers")).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM transactions")).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM imported_files")).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM import_sources")).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM balance_accounts")).toBe(4);
expect(notifications).toBe(1);
expect(logInfo).toHaveBeenCalledTimes(1);
});
it("leaves everything in place when a step fails", async () => {
const a = seedImport("Desjardins", 2);
link("CELI", a.txIds[0]);
db.exec(
"CREATE TRIGGER refuse_source_delete BEFORE DELETE ON import_sources BEGIN SELECT RAISE(ABORT, 'refused by test'); END;",
);
await expect(unlinkAndDeleteAllImports()).rejects.toThrow("refused by test");
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers")).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM transactions")).toBe(2);
expect(count("SELECT COUNT(*) AS n FROM imported_files")).toBe(1);
expect(notifications).toBe(0);
});
});

View file

@ -16,6 +16,8 @@ vi.mock("../../services/transactionService", () => ({
}));
vi.mock("../../services/balance.service", () => ({
linkTransfer: vi.fn(),
unlinkTransfer: vi.fn(),
listAccountTransfers: vi.fn(async () => []),
suggestTransferDirection: vi.fn(() => "in"),
BalanceServiceError: class extends Error {},
}));

View file

@ -10,9 +10,16 @@
// (auto-proposed via `suggestTransferDirection` from the signed amount,
// can be flipped per row), and a checkbox.
//
// On submit, calls `linkTransfer` for every selected row in sequence and
// reports any failures (most likely `transfer_already_linked` if the user
// double-clicked or another tab linked them already).
// The transactions already linked to the account (#522) are loaded once, with
// no date bound, and listed first, checked, whatever the filters: unchecking
// one and saving unlinks it. Their direction stays as stored (to change it:
// uncheck, save, check again). The filtered rows follow, without duplicates.
//
// On submit, the selection is diffed against the loaded links: a newly checked
// row is linked (`linkTransfer`), an unchecked linked row is unlinked
// (`unlinkTransfer`), in sequence, and any failure is reported (most likely
// `transfer_already_linked` when another tab linked it already). A row that is
// already unlinked (`transfer_not_linked`) counts as done.
import { useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
@ -21,12 +28,13 @@ import { X, Loader2, AlertCircle } from "lucide-react";
import { getTransactionPage } from "../../services/transactionService";
import {
linkTransfer,
unlinkTransfer,
listAccountTransfers,
suggestTransferDirection,
BalanceServiceError,
} from "../../services/balance.service";
import type {
Category,
TransactionRow,
BalanceTransferDirection,
} from "../../shared/types";
import CategoryCombobox from "../shared/CategoryCombobox";
@ -46,6 +54,24 @@ function localISO(d: Date): string {
return `${yy}-${mm}-${dd}`;
}
/** One row of the window: a transaction, already linked or not. */
interface ModalRow {
id: number;
date: string;
description: string;
amount: number;
}
/** The changes a save would make: rows to link (with their direction), rows to unlink. */
export function diffTransferSelection(
linked: ReadonlyMap<number, BalanceTransferDirection>,
selection: ReadonlyMap<number, BalanceTransferDirection>
): { toLink: Array<[number, BalanceTransferDirection]>; toUnlink: number[] } {
const toLink = [...selection.entries()].filter(([id]) => !linked.has(id));
const toUnlink = [...linked.keys()].filter((id) => !selection.has(id));
return { toLink, toUnlink };
}
export interface LinkTransfersModalProps {
/** Account that the selected transfers will be attached to. */
accountId: number;
@ -56,8 +82,8 @@ export interface LinkTransfersModalProps {
initialFrom?: string;
initialTo?: string;
onClose: () => void;
/** Fired after at least one transfer was linked (parent typically reloads). */
onLinked?: (linkedCount: number) => void;
/** Fired after at least one transfer was linked or unlinked (parent reloads). */
onChanged?: (counts: { linked: number; unlinked: number }) => void;
}
export default function LinkTransfersModal({
@ -67,7 +93,7 @@ export default function LinkTransfersModal({
initialFrom,
initialTo,
onClose,
onLinked,
onChanged,
}: LinkTransfersModalProps) {
const { t, i18n } = useTranslation();
@ -76,10 +102,16 @@ export default function LinkTransfersModal({
const [categoryId, setCategoryId] = useState<number | null>(null);
const [search, setSearch] = useState("");
const [rows, setRows] = useState<TransactionRow[]>([]);
const [rows, setRows] = useState<ModalRow[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Transfers already linked to this account (#522): transaction id → stored
// direction, and their rows, listed first. null until loaded.
const [linked, setLinked] = useState<Map<number, BalanceTransferDirection> | null>(null);
const [linkedRows, setLinkedRows] = useState<ModalRow[]>([]);
const [linkedError, setLinkedError] = useState<string | null>(null);
// Selection state: id → direction. Presence in the map = selected.
const [selection, setSelection] = useState<
Map<number, BalanceTransferDirection>
@ -104,6 +136,36 @@ export default function LinkTransfersModal({
[t]
);
// Load the account's links once, with no date bound: a link older than the
// filtered period must still show, checked, so it can be unlinked.
useEffect(() => {
let cancelled = false;
async function run() {
try {
const transfers = await listAccountTransfers(accountId);
if (cancelled) return;
const map = new Map<number, BalanceTransferDirection>();
for (const tr of transfers) map.set(tr.transaction_id, tr.direction);
setLinked(map);
setLinkedRows(
transfers.map((tr) => ({
id: tr.transaction_id,
date: tr.transaction_date,
description: tr.transaction_description,
amount: tr.transaction_amount,
}))
);
setSelection(new Map(map));
} catch (e) {
if (!cancelled) setLinkedError(e instanceof Error ? e.message : String(e));
}
}
void run();
return () => {
cancelled = true;
};
}, [accountId]);
// Re-fetch whenever the filters change. Debounced via React's render cycle
// — typing in the search box re-runs the SQL but at < 500 rows that's fine.
useEffect(() => {
@ -144,19 +206,21 @@ export default function LinkTransfersModal({
};
}, [from, to, categoryId, search]);
function toggleRow(row: TransactionRow) {
function toggleRow(row: ModalRow) {
setSelection((prev) => {
const next = new Map(prev);
if (next.has(row.id)) {
next.delete(row.id);
} else {
next.set(row.id, suggestTransferDirection(row.amount));
// A linked row checked again keeps its stored direction.
next.set(row.id, linked?.get(row.id) ?? suggestTransferDirection(row.amount));
}
return next;
});
}
function flipDirection(rowId: number) {
if (linked?.has(rowId)) return;
setSelection((prev) => {
const next = new Map(prev);
const current = next.get(rowId);
@ -166,39 +230,70 @@ export default function LinkTransfersModal({
});
}
const { toLink, toUnlink } = diffTransferSelection(linked ?? new Map(), selection);
const changeCount = toLink.length + toUnlink.length;
function describeFailure(transactionId: number, e: unknown): string {
if (e instanceof BalanceServiceError) {
return `${transactionId}: ${t(`balance.transfers.errors.${e.code}`, { defaultValue: e.message })}`;
}
return `${transactionId}: ${e instanceof Error ? e.message : String(e)}`;
}
async function handleSubmit() {
if (selection.size === 0) return;
if (linked === null || changeCount === 0) return;
setSubmitting(true);
setSubmitError(null);
let linked = 0;
let linkedCount = 0;
let unlinkedCount = 0;
const failures: string[] = [];
for (const [transactionId, direction] of selection.entries()) {
for (const transactionId of toUnlink) {
try {
await unlinkTransfer(accountId, transactionId);
unlinkedCount += 1;
} catch (e) {
// Already unlinked elsewhere: the wanted state is reached.
if (e instanceof BalanceServiceError && e.code === "transfer_not_linked") {
unlinkedCount += 1;
} else {
failures.push(describeFailure(transactionId, e));
}
}
}
for (const [transactionId, direction] of toLink) {
try {
await linkTransfer(accountId, transactionId, direction);
linked += 1;
linkedCount += 1;
} catch (e) {
if (e instanceof BalanceServiceError) {
failures.push(`${transactionId}: ${t(`balance.transfers.errors.${e.code}`, { defaultValue: e.message })}`);
} else {
failures.push(`${transactionId}: ${e instanceof Error ? e.message : String(e)}`);
}
failures.push(describeFailure(transactionId, e));
}
}
setSubmitting(false);
if (failures.length > 0) {
setSubmitError(
`${t("balance.transfers.modal.partialFailure", { linked, total: selection.size })} — ${failures.join("; ")}`
`${t("balance.transfers.modal.partialFailure", {
done: linkedCount + unlinkedCount,
total: changeCount,
linked: linkedCount,
unlinked: unlinkedCount,
})} — ${failures.join("; ")}`
);
}
if (linked > 0) {
onLinked?.(linked);
if (failures.length === 0) {
onClose();
}
if (linkedCount + unlinkedCount > 0) {
onChanged?.({ linked: linkedCount, unlinked: unlinkedCount });
}
if (failures.length === 0) {
onClose();
}
}
const allFiltered = rows.length;
// Linked rows first, then the filtered rows that are not linked.
const displayRows = useMemo(() => {
const linkedIds = new Set(linkedRows.map((r) => r.id));
return [...linkedRows, ...rows.filter((r) => !linkedIds.has(r.id))];
}, [linkedRows, rows]);
const allShown = displayRows.length;
const selectedCount = selection.size;
return createPortal(
@ -290,17 +385,17 @@ export default function LinkTransfersModal({
</div>
<div className="flex-1 overflow-auto">
{isLoading ? (
{(isLoading || linked === null) && !error && !linkedError ? (
<div className="p-8 text-center text-[var(--muted-foreground)] flex items-center justify-center gap-2">
<Loader2 className="animate-spin" size={16} />
{t("balance.transfers.modal.loading")}
</div>
) : error ? (
) : error || linkedError ? (
<div className="p-8 text-center text-[var(--negative)] flex items-center justify-center gap-2">
<AlertCircle size={16} />
{error}
{error ?? linkedError}
</div>
) : rows.length === 0 ? (
) : displayRows.length === 0 ? (
<div className="p-8 text-center text-[var(--muted-foreground)] italic">
{t("balance.transfers.modal.noTransactions")}
</div>
@ -324,9 +419,12 @@ export default function LinkTransfersModal({
</tr>
</thead>
<tbody>
{rows.map((row) => {
{displayRows.map((row) => {
const isSelected = selection.has(row.id);
const direction = selection.get(row.id) ?? suggestTransferDirection(row.amount);
const storedDirection = linked?.get(row.id);
const isLinked = storedDirection !== undefined;
const direction =
selection.get(row.id) ?? storedDirection ?? suggestTransferDirection(row.amount);
return (
<tr
key={row.id}
@ -342,6 +440,11 @@ export default function LinkTransfersModal({
</td>
<td className="px-3 py-2 whitespace-nowrap">{row.date}</td>
<td className="px-3 py-2 max-w-md truncate" title={row.description}>
{isLinked && (
<span className="mr-2 px-1.5 py-0.5 text-[10px] rounded bg-[var(--primary)]/15 text-[var(--primary)] font-medium">
{t("balance.transfers.modal.linkedBadge")}
</span>
)}
{row.description}
</td>
<td
@ -350,7 +453,7 @@ export default function LinkTransfersModal({
{fmt.format(row.amount)}
</td>
<td className="px-3 py-2 text-center">
{isSelected ? (
{isSelected && !isLinked ? (
<button
type="button"
onClick={() => flipDirection(row.id)}
@ -364,7 +467,10 @@ export default function LinkTransfersModal({
{t(`balance.transfers.direction.${direction}`)}
</button>
) : (
<span className="text-xs text-[var(--muted-foreground)]">
<span
className="text-xs text-[var(--muted-foreground)]"
title={isLinked ? t("balance.transfers.modal.directionFixed") : undefined}
>
{t(`balance.transfers.direction.${direction}`)}
</span>
)}
@ -387,8 +493,17 @@ export default function LinkTransfersModal({
<div className="text-xs text-[var(--muted-foreground)]">
{t("balance.transfers.modal.summary", {
selected: selectedCount,
total: allFiltered,
total: allShown,
})}
{changeCount > 0 && (
<>
{" — "}
{t("balance.transfers.modal.changes", {
link: toLink.length,
unlink: toUnlink.length,
})}
</>
)}
</div>
<div className="flex gap-2">
<button
@ -401,7 +516,7 @@ export default function LinkTransfersModal({
<button
type="button"
onClick={handleSubmit}
disabled={submitting || selectedCount === 0}
disabled={submitting || linked === null || changeCount === 0}
className="px-3 py-1.5 text-sm rounded bg-[var(--primary)] text-white disabled:opacity-50 disabled:cursor-not-allowed"
>
{submitting ? (
@ -410,7 +525,7 @@ export default function LinkTransfersModal({
{t("balance.transfers.modal.linking")}
</span>
) : (
t("balance.transfers.modal.linkSelection", { count: selectedCount })
t("balance.transfers.modal.save")
)}
</button>
</div>

View file

@ -0,0 +1,220 @@
// LinkTransfersModal — unlinking from the window (#522).
//
// `unlinkTransfer` had no caller: the window listed the filtered transactions
// unchecked, a linked one included, and only linked the checked rows. Now the
// account's links load once, with no date bound, and come first, checked; a
// save diffs the selection against them. Same harness as the wiring test of
// the category filter (src/test/hookHarness.ts): the window runs as a plain
// function, `commit()` runs its effects, the test clicks through the props of
// the elements it finds.
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest";
import type { ReactNode } from "react";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
vi.mock("react-dom", async (orig) => ({
...(await orig<typeof import("react-dom")>()),
createPortal: (children: ReactNode) => children,
}));
const svc = vi.hoisted(() => {
class BalanceServiceError extends Error {
constructor(
readonly code: string,
message: string,
) {
super(message);
}
}
return {
getTransactionPage: vi.fn(),
listAccountTransfers: vi.fn(),
linkTransfer: vi.fn(),
unlinkTransfer: vi.fn(),
BalanceServiceError,
};
});
vi.mock("../../services/transactionService", () => ({ getTransactionPage: svc.getTransactionPage }));
vi.mock("../../services/balance.service", () => ({
linkTransfer: svc.linkTransfer,
unlinkTransfer: svc.unlinkTransfer,
listAccountTransfers: svc.listAccountTransfers,
suggestTransferDirection: (amount: number) => (amount < 0 ? "in" : "out"),
BalanceServiceError: svc.BalanceServiceError,
}));
import { hookHarness } from "../../test/hookHarness";
import { find, texts, type TreeProps } from "../../test/elementTree";
import LinkTransfersModal, { diffTransferSelection } from "./LinkTransfersModal";
const harness = hookHarness();
/** Linked in March, outside the window's period (July to September). */
const OLD_LINK = {
id: 90,
account_id: 1,
transaction_id: 501,
direction: "out" as const,
notes: null,
created_at: "",
transaction_date: "2026-03-02",
transaction_description: "Dépôt CELI mars",
transaction_amount: -500,
account_name: "CELI",
};
const FILTERED = [
{ id: 600, date: "2026-08-01", description: "Virement août", amount: -200 },
// The same transaction, also in the period: listed once, among the links.
{ id: 501, date: "2026-03-02", description: "Dépôt CELI mars", amount: -500 },
];
const onClose = vi.fn();
const onChanged = vi.fn();
const PROPS = {
accountId: 1,
accountName: "CELI",
categories: [],
initialFrom: "2026-07-01",
initialTo: "2026-09-30",
onClose,
onChanged,
};
const render = () => harness.render(() => LinkTransfersModal(PROPS));
const flush = async () => {
for (let i = 0; i < 10; i++) await Promise.resolve();
};
/** Mounts the window and lets both loads settle. */
async function mount() {
render();
harness.commit();
await flush();
return render();
}
const checkboxes = (tree: ReturnType<typeof render>) =>
find(tree, (el) => el.type === "input" && (el.props as TreeProps).type === "checkbox").map(
(el) => el.props as TreeProps & { checked: boolean; onChange: () => void; "aria-label": string },
);
const saveButton = (tree: ReturnType<typeof render>) => {
const buttons = find(tree, (el) => el.type === "button" && texts(el).includes("t(balance.transfers.modal.save)"));
expect(buttons).toHaveLength(1);
return buttons[0].props as TreeProps & { disabled: boolean; onClick: () => Promise<void> };
};
beforeAll(() => {
vi.stubGlobal("document", { body: {} });
});
afterAll(() => {
vi.unstubAllGlobals();
});
beforeEach(() => {
harness.clear();
for (const fn of [svc.getTransactionPage, svc.listAccountTransfers, svc.linkTransfer, svc.unlinkTransfer]) {
fn.mockReset();
}
onClose.mockReset();
onChanged.mockReset();
svc.getTransactionPage.mockResolvedValue({ rows: FILTERED, total: FILTERED.length });
svc.listAccountTransfers.mockResolvedValue([OLD_LINK]);
svc.linkTransfer.mockResolvedValue(1);
svc.unlinkTransfer.mockResolvedValue(undefined);
});
describe("LinkTransfersModal — linked transactions (#522)", () => {
it("loads the account's links with no date bound", async () => {
await mount();
expect(svc.listAccountTransfers).toHaveBeenCalledWith(1);
});
it("lists a link outside the filtered period first, checked, once, then the other rows unchecked", async () => {
const boxes = checkboxes(await mount());
expect(boxes.map((b) => [b["aria-label"], b.checked])).toEqual([
["select-501", true],
["select-600", false],
]);
});
it("marks the linked row and keeps its stored direction, with no flip button", async () => {
const tree = await mount();
const all = texts(tree);
expect(all).toContain("t(balance.transfers.modal.linkedBadge)");
expect(all.filter((s) => s === "t(balance.transfers.modal.linkedBadge)")).toHaveLength(1);
// Stored "out" although the negative amount would suggest "in".
expect(all).toContain("t(balance.transfers.direction.out)");
expect(find(tree, (el) => el.type === "button" && (el.props as TreeProps).title === "t(balance.transfers.modal.toggleDirection)")).toHaveLength(0);
});
it("keeps the save disabled while nothing changed", async () => {
expect(saveButton(await mount()).disabled).toBe(true);
});
it("unchecking a linked row and saving unlinks it, links nothing, reports the change and closes", async () => {
checkboxes(await mount())[0].onChange();
const save = saveButton(render());
expect(save.disabled).toBe(false);
await save.onClick();
expect(svc.unlinkTransfer).toHaveBeenCalledTimes(1);
expect(svc.unlinkTransfer).toHaveBeenCalledWith(1, 501);
expect(svc.linkTransfer).not.toHaveBeenCalled();
expect(onChanged).toHaveBeenCalledWith({ linked: 0, unlinked: 1 });
expect(onClose).toHaveBeenCalledTimes(1);
});
it("checking a new row links it with its suggested direction, and leaves the linked one alone", async () => {
checkboxes(await mount())[1].onChange();
await saveButton(render()).onClick();
expect(svc.linkTransfer).toHaveBeenCalledTimes(1);
expect(svc.linkTransfer).toHaveBeenCalledWith(1, 600, "in");
expect(svc.unlinkTransfer).not.toHaveBeenCalled();
expect(onChanged).toHaveBeenCalledWith({ linked: 1, unlinked: 0 });
});
it("unchecked then checked again: no change, nothing saved", async () => {
checkboxes(await mount())[0].onChange();
checkboxes(render())[0].onChange();
expect(saveButton(render()).disabled).toBe(true);
});
it("counts a row already unlinked elsewhere as done", async () => {
svc.unlinkTransfer.mockRejectedValue(new svc.BalanceServiceError("transfer_not_linked", "gone"));
checkboxes(await mount())[0].onChange();
await saveButton(render()).onClick();
expect(onChanged).toHaveBeenCalledWith({ linked: 0, unlinked: 1 });
expect(onClose).toHaveBeenCalledTimes(1);
});
it("reports a failed unlink with both counts and stays open", async () => {
svc.unlinkTransfer.mockRejectedValue(new Error("database is locked"));
const boxes = checkboxes(await mount());
boxes[0].onChange();
boxes[1].onChange();
await saveButton(render()).onClick();
expect(onChanged).toHaveBeenCalledWith({ linked: 1, unlinked: 0 });
expect(onClose).not.toHaveBeenCalled();
const message = texts(render()).find((s) => s.includes("partialFailure"));
expect(message).toContain("t(balance.transfers.modal.partialFailure[done=1,total=2,linked=1,unlinked=0])");
expect(message).toContain("501: database is locked");
});
});
describe("diffTransferSelection (#522)", () => {
it("links the new rows and unlinks the linked rows left out", () => {
const linked = new Map([
[1, "in" as const],
[2, "out" as const],
]);
const selection = new Map([
[2, "out" as const],
[3, "in" as const],
]);
expect(diffTransferSelection(linked, selection)).toEqual({ toLink: [[3, "in"]], toUnlink: [1] });
});
});

View file

@ -19,6 +19,8 @@ const { getTransactionPage } = vi.hoisted(() => ({ getTransactionPage: vi.fn() }
vi.mock("../../services/transactionService", () => ({ getTransactionPage }));
vi.mock("../../services/balance.service", () => ({
linkTransfer: vi.fn(),
unlinkTransfer: vi.fn(),
listAccountTransfers: vi.fn(async () => []),
suggestTransferDirection: vi.fn(() => "in"),
BalanceServiceError: class extends Error {},
}));

View file

@ -2,6 +2,8 @@ import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Trash2, Inbox, AlertTriangle } from "lucide-react";
import { useImportHistory } from "../../hooks/useImportHistory";
import { useEntitlement } from "../../hooks/useEntitlement";
import LinkedTransfersNotice, { UnlinkAndDeleteConfirm } from "./LinkedTransfersNotice";
interface ImportHistoryPanelProps {
onChanged?: () => void;
@ -11,9 +13,19 @@ export default function ImportHistoryPanel({
onChanged,
}: ImportHistoryPanelProps) {
const { t } = useTranslation();
const { state, handleDelete, handleDeleteAll } = useImportHistory(onChanged);
const { state, handleDelete, handleDeleteAll, handleUnlinkAndDelete, dismissBlocked } =
useImportHistory(onChanged);
const { allowed: balanceAllowed } = useEntitlement("balance");
const [confirmDelete, setConfirmDelete] = useState<{ id: number; filename: string; rowCount: number } | null>(null);
const [confirmDeleteAll, setConfirmDeleteAll] = useState(false);
const [confirmUnlink, setConfirmUnlink] = useState(false);
// #522 — the file a refused one-import delete targets, for the confirmation.
const blockedScope = state.blocked?.scope;
const blockedFilename =
blockedScope?.kind === "file"
? (state.files.find((f) => f.id === blockedScope.fileId)?.filename ?? null)
: null;
return (
<div className="mt-8">
@ -36,6 +48,17 @@ export default function ImportHistoryPanel({
<p className="text-sm text-[var(--negative)] mb-2">{state.error}</p>
)}
{state.blocked && (
<LinkedTransfersNotice
blocked={state.blocked}
balanceAllowed={balanceAllowed}
failed={state.unlinkFailed}
disabled={state.isDeleting}
onUnlinkAndDelete={() => setConfirmUnlink(true)}
onDismiss={dismissBlocked}
/>
)}
{state.isLoading ? (
<p className="text-sm text-[var(--muted-foreground)]">
{t("common.loading")}
@ -187,6 +210,19 @@ export default function ImportHistoryPanel({
</div>
</div>
)}
{/* Confirm unlink and delete (#522) */}
{confirmUnlink && state.blocked && (
<UnlinkAndDeleteConfirm
blocked={state.blocked}
filename={blockedFilename}
onCancel={() => setConfirmUnlink(false)}
onConfirm={() => {
setConfirmUnlink(false);
void handleUnlinkAndDelete();
}}
/>
)}
</div>
);
}

View file

@ -0,0 +1,166 @@
// LinkedTransfersNotice (#522) through the REAL locales: the history used to
// show the English text of `TransactionLinkedToBalanceError` in both
// languages. The plural forms, the "and N others" of the account list and the
// link to "Lier transferts" only exist in fr.json and en.json.
import { describe, it, expect, afterAll } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import i18n from "../../i18n/config";
import LinkedTransfersNotice, { UnlinkAndDeleteConfirm } from "./LinkedTransfersNotice";
import type { BlockedDeletion } from "../../hooks/useImportHistory";
const account = (account_id: number, account_name: string, transfer_count = 1, is_active = true) => ({
account_id,
account_name,
is_active,
transfer_count,
});
const ONE: BlockedDeletion = {
scope: { kind: "file", fileId: 8 },
summary: { transferCount: 1, accounts: [account(2, "CELI")] },
};
const MANY: BlockedDeletion = {
scope: { kind: "all" },
summary: {
transferCount: 64,
accounts: [
account(9, "Compte chèque"),
account(2, "CELI", 2),
account(3, "REER", 58, false),
account(5, "Ledger"),
account(6, "Wealthsimple", 2),
],
},
};
const UNKNOWN: BlockedDeletion = { scope: { kind: "file", fileId: 8 }, summary: null };
const RAW = "Transaction is linked to one or more balance accounts";
const notice = (blocked: BlockedDeletion, balanceAllowed: boolean) =>
renderToStaticMarkup(
<MemoryRouter>
<LinkedTransfersNotice
blocked={blocked}
balanceAllowed={balanceAllowed}
failed={false}
disabled={false}
onUnlinkAndDelete={() => undefined}
onDismiss={() => undefined}
/>
</MemoryRouter>,
);
const confirm = (blocked: BlockedDeletion, filename: string | null = "releve.csv") =>
renderToStaticMarkup(
<UnlinkAndDeleteConfirm blocked={blocked} filename={filename} onCancel={() => undefined} onConfirm={() => undefined} />,
);
const text = (html: string) =>
html
.replace(/<[^>]+>/g, " ")
.replace(/&#x27;/g, "'")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&")
.replace(/\s+/g, " ")
.trim();
const links = (html: string) => [...html.matchAll(/<a [^>]*href="([^"]+)"[^>]*>([^<]*)<\/a>/g)].map((m) => [m[1], m[2]]);
afterAll(async () => {
await i18n.changeLanguage("fr");
});
describe("LinkedTransfersNotice — French (#522)", () => {
it("one import, one transfer: names the account and counts it", async () => {
await i18n.changeLanguage("fr");
const t = text(notice(ONE, true));
expect(t).toContain(
"Cet import ne peut pas être supprimé tel quel : 1 transfert du Bilan s'appuie sur ses transactions, dans CELI.",
);
expect(t).toContain("Déliez-les dans « Lier transferts » du compte, ou déliez-les et supprimez en une fois.");
expect(t).toContain("Délier et supprimer");
expect(t).not.toContain(RAW);
});
it("the whole history: three names then « et 2 autres », the real count", async () => {
await i18n.changeLanguage("fr");
expect(text(notice(MANY, true))).toContain(
"Les imports ne peuvent pas être supprimés tels quels : 64 transferts du Bilan s'appuient sur leurs transactions, dans Compte chèque, CELI, REER et 2 autres.",
);
});
it("Premium: one link per named active account to its « Lier transferts », none for an archived one", async () => {
await i18n.changeLanguage("fr");
expect(links(notice(MANY, true))).toEqual([
["/balance?linkTransfers=9", "Lier transferts : Compte chèque"],
["/balance?linkTransfers=2", "Lier transferts : CELI"],
]);
});
it("Free: no link, the unlink-and-delete stays offered, and the hint says so", async () => {
await i18n.changeLanguage("fr");
const html = notice(MANY, false);
expect(links(html)).toEqual([]);
expect(text(html)).toContain("Délier et supprimer");
expect(text(html)).toContain("Vous pouvez les délier et supprimer en une fois ; ces transferts seront perdus.");
});
it("the count failed: a translated message without names", async () => {
await i18n.changeLanguage("fr");
const t = text(notice(UNKNOWN, true));
expect(t).toContain("La suppression est refusée : des transactions sont liées à des comptes du Bilan.");
expect(t).not.toContain(RAW);
});
it("the confirmation states the exact count, lost for good, the accounts and the import", async () => {
await i18n.changeLanguage("fr");
const t = text(confirm({ ...MANY, scope: { kind: "file", fileId: 8 } }));
expect(t).toContain("64 transferts du Bilan seront déliés sans retour, même avec une clé.");
expect(t).toContain("Comptes touchés : Compte chèque, CELI, REER et 2 autres.");
expect(t).toContain("Puis l'import « releve.csv » et ses transactions seront supprimés.");
});
it("the confirmation, singular, for the whole history", async () => {
await i18n.changeLanguage("fr");
const t = text(confirm({ ...ONE, scope: { kind: "all" } }));
expect(t).toContain("1 transfert du Bilan sera délié sans retour, même avec une clé.");
expect(t).toContain("Puis tous les imports et leurs transactions seront supprimés.");
});
it("Cancel comes first and holds the focus; the destructive button is the second", async () => {
await i18n.changeLanguage("fr");
const buttons = [...confirm(ONE).matchAll(/<button([^>]*)>([^<]*)<\/button>/g)].map((m) => [m[1], m[2]]);
expect(buttons.map((b) => b[1])).toEqual(["Annuler", "Délier et supprimer"]);
expect(buttons[0][0]).toContain("autofocus");
expect(buttons[1][0]).not.toContain("autofocus");
});
});
describe("LinkedTransfersNotice — English (#522)", () => {
it("one import, one transfer", async () => {
await i18n.changeLanguage("en");
const t = text(notice(ONE, true));
expect(t).toContain("This import cannot be deleted as is: 1 Balance transfer relies on its transactions, in CELI.");
expect(t).toContain("Unlink and delete");
expect(t).not.toContain(RAW);
});
it("the whole history, « and 2 others », and the links", async () => {
await i18n.changeLanguage("en");
const html = notice(MANY, true);
expect(text(html)).toContain(
"The imports cannot be deleted as is: 64 Balance transfers rely on their transactions, in Compte chèque, CELI, REER and 2 others.",
);
expect(links(html)).toEqual([
["/balance?linkTransfers=9", "Link transfers: Compte chèque"],
["/balance?linkTransfers=2", "Link transfers: CELI"],
]);
});
it("the confirmation", async () => {
await i18n.changeLanguage("en");
const t = text(confirm(MANY));
expect(t).toContain("64 Balance transfers will be unlinked for good, even with a key.");
expect(t).toContain("Then every import and its transactions will be deleted.");
});
});

View file

@ -0,0 +1,195 @@
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { AlertTriangle, X } from "lucide-react";
import type { BlockedDeletion } from "../../hooks/useImportHistory";
import type { LinkedTransfersSummary } from "../../services/importedFileService";
import { formatRootFiles } from "../../utils/rootFiles";
import { linkTransfersHref } from "../../utils/balanceLinkParam";
/** Accounts a message names before counting the rest (#522). */
export const NAMED_ACCOUNTS = 3;
/** "CELI, REER, Compte chèque et 2 autres": three names, then the count of the rest. */
export function useAccountList() {
const { t } = useTranslation();
return (summary: LinkedTransfersSummary): string => {
const { shown, more } = formatRootFiles(
summary.accounts.map((a) => a.account_name),
NAMED_ACCOUNTS
);
return (
shown.join(", ") + (more > 0 ? ` ${t("import.history.linked.more", { count: more })}` : "")
);
};
}
export interface LinkedTransfersNoticeProps {
blocked: BlockedDeletion;
/** The Balance sheet is open in this edition: offer the link to "Lier transferts". */
balanceAllowed: boolean;
/** The unlink-and-delete failed: nothing was changed. */
failed: boolean;
disabled: boolean;
onUnlinkAndDelete: () => void;
onDismiss: () => void;
}
/**
* The import history's delete refused because some transactions are linked to
* the Balance sheet (#522, ADR 0010): names the accounts (three, then the
* count of the rest), counts the transfers, links to each named active
* account's "Lier transferts" when the edition opens the Balance sheet, and
* offers "Unlink and delete" in every edition. Never the error's English text.
*/
export default function LinkedTransfersNotice({
blocked,
balanceAllowed,
failed,
disabled,
onUnlinkAndDelete,
onDismiss,
}: LinkedTransfersNoticeProps) {
const { t } = useTranslation();
const accountList = useAccountList();
const { summary, scope } = blocked;
const message =
summary && summary.transferCount > 0
? t(
scope.kind === "file"
? "import.history.linked.messageFile"
: "import.history.linked.messageAll",
{ count: summary.transferCount, accounts: accountList(summary) }
)
: t("import.history.linked.messageUnknown");
const linkable =
balanceAllowed && summary
? summary.accounts.slice(0, NAMED_ACCOUNTS).filter((a) => a.is_active)
: [];
return (
<div
role="alert"
className="mb-4 p-3 rounded-xl bg-[var(--card)] border-2 border-[var(--negative)]/40 flex items-start gap-2"
>
<AlertTriangle size={16} aria-hidden="true" className="text-[var(--negative)] shrink-0 mt-0.5" />
<div className="flex-1 text-sm space-y-2">
<p className="text-[var(--foreground)]">{message}</p>
<p className="text-[var(--muted-foreground)]">
{t(
balanceAllowed
? "import.history.linked.hintBalance"
: "import.history.linked.hintNoBalance"
)}
</p>
{failed && (
<p className="text-[var(--negative)]">{t("import.history.linked.failed")}</p>
)}
<div className="flex flex-wrap items-center gap-2">
{linkable.map((a) => (
<Link
key={a.account_id}
to={linkTransfersHref(a.account_id)}
className="px-3 py-1.5 text-sm rounded-lg border border-[var(--border)] hover:bg-[var(--muted)]"
>
{t("import.history.linked.openAccount", { account: a.account_name })}
</Link>
))}
<button
type="button"
onClick={onUnlinkAndDelete}
disabled={disabled}
className="px-3 py-1.5 text-sm rounded-lg bg-[var(--negative)] text-white hover:opacity-90 disabled:opacity-50"
>
{t("import.history.linked.unlinkAndDelete")}
</button>
</div>
</div>
<button
type="button"
onClick={onDismiss}
className="p-1 rounded hover:bg-[var(--muted)]"
aria-label={t("common.close")}
>
<X size={16} />
</button>
</div>
);
}
export interface UnlinkAndDeleteConfirmProps {
blocked: BlockedDeletion;
/** The file name, for one import's delete. */
filename: string | null;
onCancel: () => void;
onConfirm: () => void;
}
/**
* Confirmation of "Unlink and delete": how many Balance sheet transfers are
* lost for good, even with a key, and which accounts; Cancel has the focus.
*/
export function UnlinkAndDeleteConfirm({
blocked,
filename,
onCancel,
onConfirm,
}: UnlinkAndDeleteConfirmProps) {
const { t } = useTranslation();
const accountList = useAccountList();
const { summary, scope } = blocked;
const known = summary !== null && summary.transferCount > 0;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div
role="alertdialog"
aria-modal="true"
aria-labelledby="unlink-and-delete-title"
className="bg-[var(--card)] rounded-xl border border-[var(--border)] shadow-lg p-6 max-w-md w-full mx-4"
>
<div className="flex items-center gap-3 mb-4">
<div className="p-2 rounded-full bg-[var(--negative)]/10">
<AlertTriangle size={20} className="text-[var(--negative)]" />
</div>
<h2 id="unlink-and-delete-title" className="text-lg font-semibold">
{t("import.history.linked.unlinkAndDelete")}
</h2>
</div>
<p className="text-sm text-[var(--foreground)] mb-2">
{known
? t("import.history.linked.confirmBody", { count: summary.transferCount })
: t("import.history.linked.confirmBodyUnknown")}
</p>
{known && (
<p className="text-sm text-[var(--muted-foreground)] mb-2">
{t("import.history.linked.confirmAccounts", { accounts: accountList(summary) })}
</p>
)}
<p className="text-sm text-[var(--muted-foreground)] mb-6">
{scope.kind === "file"
? t("import.history.linked.confirmFile", { filename: filename ?? "" })
: t("import.history.linked.confirmAll")}
</p>
<div className="flex justify-end gap-3">
<button
type="button"
autoFocus
onClick={onCancel}
className="px-4 py-2 text-sm rounded-lg border border-[var(--border)] hover:bg-[var(--muted)] transition-colors"
>
{t("common.cancel")}
</button>
<button
type="button"
onClick={onConfirm}
className="px-4 py-2 text-sm rounded-lg bg-[var(--negative)] text-white hover:opacity-90 transition-opacity"
>
{t("import.history.linked.unlinkAndDelete")}
</button>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,143 @@
// useImportHistory — a delete refused for linked Balance transfers (#522).
//
// The hook used to keep `String(err)`: the English text of
// `TransactionLinkedToBalanceError`, shown as is in both languages. It now
// keeps a structured refusal (scope, accounts, real count), and "Unlink and
// delete" runs the service of that scope. Under the shared hook harness
// (src/test/hookHarness.ts): the hook runs as a plain function, `commit()`
// runs its load effect.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
const svc = vi.hoisted(() => ({
getAllImportedFiles: vi.fn(),
deleteImportWithTransactions: vi.fn(),
deleteAllImportsWithTransactions: vi.fn(),
getLinkedTransfersSummary: vi.fn(),
unlinkAndDeleteImport: vi.fn(),
unlinkAndDeleteAllImports: vi.fn(),
}));
vi.mock("../services/importedFileService", () => svc);
vi.mock("../services/transactionService", () => ({
TransactionLinkedToBalanceError: class TransactionLinkedToBalanceError extends Error {
constructor() {
super("Transaction is linked to one or more balance accounts; unlink before deleting");
}
},
}));
import { hookHarness } from "../test/hookHarness";
import { TransactionLinkedToBalanceError } from "../services/transactionService";
import { useImportHistory } from "./useImportHistory";
const harness = hookHarness();
const onChanged = vi.fn();
const render = () => harness.render(() => useImportHistory(onChanged));
const SUMMARY = {
transferCount: 61,
accounts: [
{ account_id: 2, account_name: "CELI", is_active: true, transfer_count: 1 },
{ account_id: 3, account_name: "REER", is_active: true, transfer_count: 60 },
],
};
const refusal = () => new (TransactionLinkedToBalanceError as unknown as new () => Error)();
beforeEach(() => {
harness.clear();
for (const fn of Object.values(svc)) fn.mockReset();
onChanged.mockReset();
svc.getAllImportedFiles.mockResolvedValue([]);
svc.getLinkedTransfersSummary.mockResolvedValue(SUMMARY);
svc.unlinkAndDeleteImport.mockResolvedValue({ unlinked: 61, deleted: 70 });
svc.unlinkAndDeleteAllImports.mockResolvedValue({ unlinked: 61, deleted: 70 });
});
describe("useImportHistory — refused delete (#522)", () => {
it("keeps a structured refusal for one import, with the real count, and never the error's text", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
await render().handleDelete(8);
const { state } = render();
expect(svc.getLinkedTransfersSummary).toHaveBeenCalledWith({ kind: "file", fileId: 8 });
expect(state.blocked).toEqual({ scope: { kind: "file", fileId: 8 }, summary: SUMMARY });
expect(state.error).toBeNull();
expect(onChanged).not.toHaveBeenCalled();
});
it("does the same for the whole history", async () => {
svc.deleteAllImportsWithTransactions.mockRejectedValue(refusal());
await render().handleDeleteAll();
expect(svc.getLinkedTransfersSummary).toHaveBeenCalledWith({ kind: "all" });
expect(render().state.blocked).toEqual({ scope: { kind: "all" }, summary: SUMMARY });
});
it("keeps the refusal without a summary when the count fails", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
svc.getLinkedTransfersSummary.mockRejectedValue(new Error("database is locked"));
await render().handleDelete(8);
expect(render().state.blocked).toEqual({ scope: { kind: "file", fileId: 8 }, summary: null });
expect(render().state.error).toBeNull();
});
it("keeps any other error as text", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(new Error("disk full"));
await render().handleDelete(8);
expect(render().state.error).toBe("Error: disk full");
expect(render().state.blocked).toBeNull();
});
it("unlinks and deletes the refused import, clears the refusal, reloads and announces", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
await render().handleDelete(8);
svc.getAllImportedFiles.mockClear();
await render().handleUnlinkAndDelete();
expect(svc.unlinkAndDeleteImport).toHaveBeenCalledWith(8);
expect(svc.unlinkAndDeleteAllImports).not.toHaveBeenCalled();
expect(render().state.blocked).toBeNull();
expect(svc.getAllImportedFiles).toHaveBeenCalledTimes(1);
expect(onChanged).toHaveBeenCalledTimes(1);
});
it("unlinks and deletes everything for a refused delete-all", async () => {
svc.deleteAllImportsWithTransactions.mockRejectedValue(refusal());
await render().handleDeleteAll();
await render().handleUnlinkAndDelete();
expect(svc.unlinkAndDeleteAllImports).toHaveBeenCalledTimes(1);
expect(svc.unlinkAndDeleteImport).not.toHaveBeenCalled();
});
it("a failed unlink-and-delete keeps the refusal and flags the failure, with no raw text", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
await render().handleDelete(8);
svc.unlinkAndDeleteImport.mockRejectedValue(new Error("FOREIGN KEY constraint failed"));
await render().handleUnlinkAndDelete();
const { state } = render();
expect(state.blocked).toEqual({ scope: { kind: "file", fileId: 8 }, summary: SUMMARY });
expect(state.unlinkFailed).toBe(true);
expect(state.error).toBeNull();
expect(onChanged).not.toHaveBeenCalled();
});
it("a new delete clears an earlier refusal", async () => {
svc.deleteImportWithTransactions.mockRejectedValueOnce(refusal()).mockResolvedValueOnce(3);
await render().handleDelete(8);
await render().handleDelete(9);
expect(render().state.blocked).toBeNull();
});
it("dismissing clears the refusal", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
await render().handleDelete(8);
render().dismissBlocked();
expect(render().state.blocked).toBeNull();
});
});

View file

@ -4,26 +4,50 @@ import {
getAllImportedFiles,
deleteImportWithTransactions,
deleteAllImportsWithTransactions,
getLinkedTransfersSummary,
unlinkAndDeleteImport,
unlinkAndDeleteAllImports,
type ImportDeletionScope,
type LinkedTransfersSummary,
} from "../services/importedFileService";
import { TransactionLinkedToBalanceError } from "../services/transactionService";
/**
* A delete refused because transactions of the import are linked to the
* Balance sheet (#522). Kept structured, never as the error's English text:
* the panel names the accounts, counts the transfers and offers "Unlink and
* delete". `summary` is null when the count itself failed (generic message).
*/
export interface BlockedDeletion {
scope: ImportDeletionScope;
summary: LinkedTransfersSummary | null;
}
interface ImportHistoryState {
files: ImportedFileWithSource[];
isLoading: boolean;
isDeleting: boolean;
error: string | null;
blocked: BlockedDeletion | null;
/** The unlink-and-delete itself failed: a translated message, nothing moved. */
unlinkFailed: boolean;
}
type ImportHistoryAction =
| { type: "SET_LOADING"; payload: boolean }
| { type: "SET_DELETING"; payload: boolean }
| { type: "SET_ERROR"; payload: string | null }
| { type: "SET_FILES"; payload: ImportedFileWithSource[] };
| { type: "SET_FILES"; payload: ImportedFileWithSource[] }
| { type: "SET_BLOCKED"; payload: BlockedDeletion | null }
| { type: "SET_UNLINK_FAILED"; payload: boolean };
const initialState: ImportHistoryState = {
files: [],
isLoading: false,
isDeleting: false,
error: null,
blocked: null,
unlinkFailed: false,
};
function reducer(
@ -39,6 +63,10 @@ function reducer(
return { ...state, error: action.payload };
case "SET_FILES":
return { ...state, files: action.payload };
case "SET_BLOCKED":
return { ...state, blocked: action.payload, unlinkFailed: false };
case "SET_UNLINK_FAILED":
return { ...state, unlinkFailed: action.payload };
default:
return state;
}
@ -66,15 +94,28 @@ export function useImportHistory(onChanged?: () => void) {
}
}, []);
const handleDelete = useCallback(
async (fileId: number) => {
/** Runs one delete; a refusal for linked transfers becomes `blocked`. */
const runDelete = useCallback(
async (scope: ImportDeletionScope, remove: () => Promise<unknown>) => {
dispatch({ type: "SET_DELETING", payload: true });
dispatch({ type: "SET_ERROR", payload: null });
dispatch({ type: "SET_BLOCKED", payload: null });
try {
await deleteImportWithTransactions(fileId);
await remove();
await loadHistory();
onChanged?.();
} catch (err) {
dispatch({ type: "SET_ERROR", payload: String(err) });
if (err instanceof TransactionLinkedToBalanceError) {
let summary: LinkedTransfersSummary | null = null;
try {
summary = await getLinkedTransfersSummary(scope);
} catch {
// The panel falls back to a message without names nor count.
}
dispatch({ type: "SET_BLOCKED", payload: { scope, summary } });
} else {
dispatch({ type: "SET_ERROR", payload: String(err) });
}
} finally {
dispatch({ type: "SET_DELETING", payload: false });
}
@ -82,18 +123,46 @@ export function useImportHistory(onChanged?: () => void) {
[loadHistory, onChanged]
);
const handleDeleteAll = useCallback(async () => {
const handleDelete = useCallback(
(fileId: number) =>
runDelete({ kind: "file", fileId }, () => deleteImportWithTransactions(fileId)),
[runDelete]
);
const handleDeleteAll = useCallback(
() => runDelete({ kind: "all" }, () => deleteAllImportsWithTransactions()),
[runDelete]
);
/**
* "Unlink and delete" the refused scope, after the panel's confirmation. On
* failure nothing moved (one SQL transaction): the notice stays, with a
* translated failure line.
*/
const handleUnlinkAndDelete = useCallback(async () => {
const blocked = state.blocked;
if (!blocked) return;
dispatch({ type: "SET_DELETING", payload: true });
dispatch({ type: "SET_UNLINK_FAILED", payload: false });
try {
await deleteAllImportsWithTransactions();
if (blocked.scope.kind === "file") {
await unlinkAndDeleteImport(blocked.scope.fileId);
} else {
await unlinkAndDeleteAllImports();
}
dispatch({ type: "SET_BLOCKED", payload: null });
await loadHistory();
onChanged?.();
} catch (err) {
dispatch({ type: "SET_ERROR", payload: String(err) });
} catch {
dispatch({ type: "SET_UNLINK_FAILED", payload: true });
} finally {
dispatch({ type: "SET_DELETING", payload: false });
}
}, [loadHistory, onChanged]);
}, [state.blocked, loadHistory, onChanged]);
const dismissBlocked = useCallback(() => {
dispatch({ type: "SET_BLOCKED", payload: null });
}, []);
useEffect(() => {
loadHistory();
@ -104,5 +173,7 @@ export function useImportHistory(onChanged?: () => void) {
loadHistory,
handleDelete,
handleDeleteAll,
handleUnlinkAndDelete,
dismissBlocked,
};
}

View file

@ -278,7 +278,27 @@
"filename": "File",
"date": "Date",
"rows": "Rows",
"status": "Status"
"status": "Status",
"linked": {
"messageFile_one": "This import cannot be deleted as is: {{count}} Balance transfer relies on its transactions, in {{accounts}}.",
"messageFile_other": "This import cannot be deleted as is: {{count}} Balance transfers rely on its transactions, in {{accounts}}.",
"messageAll_one": "The imports cannot be deleted as is: {{count}} Balance transfer relies on their transactions, in {{accounts}}.",
"messageAll_other": "The imports cannot be deleted as is: {{count}} Balance transfers rely on their transactions, in {{accounts}}.",
"messageUnknown": "The delete was refused: some transactions are linked to Balance accounts.",
"more_one": "and {{count}} other",
"more_other": "and {{count}} others",
"hintBalance": "Unlink them in the account's \"Link transfers\", or unlink and delete in one go.",
"hintNoBalance": "You can unlink and delete in one go; these transfers will be lost.",
"openAccount": "Link transfers: {{account}}",
"unlinkAndDelete": "Unlink and delete",
"confirmBody_one": "{{count}} Balance transfer will be unlinked for good, even with a key.",
"confirmBody_other": "{{count}} Balance transfers will be unlinked for good, even with a key.",
"confirmBodyUnknown": "The Balance transfers of these transactions will be unlinked for good, even with a key.",
"confirmAccounts": "Accounts affected: {{accounts}}.",
"confirmFile": "Then the import \"{{filename}}\" and its transactions will be deleted.",
"confirmAll": "Then every import and its transactions will be deleted.",
"failed": "The delete failed; nothing was changed."
}
},
"wizard": {
"back": "Back",
@ -1355,7 +1375,7 @@
"Take snapshots on a regular cadence (monthly or quarterly) — return quality depends on regularity",
"The unadjusted return on the right shows \"account value\" vs \"true performance\": the difference comes from contributions, not from performance",
"Vertical chart markers help you read value jumps: a jump followed by a green marker isn't \"performance\", it's a deposit",
"If you try to delete a transaction linked to a balance account, the app asks you to unlink it first — this friction preserves the reproducibility of past returns",
"A transaction linked to a balance account is listed first in \"Link transfers\", checked: uncheck it and save to unlink it. An import that holds one cannot be deleted as is: the import history names the accounts, links to \"Link transfers\" and offers, in every edition, \"Unlink and delete\", which loses those transfers for good — this friction preserves the reproducibility of past returns",
"The \"balance out of date\" warning appears if your latest snapshot is more than 60 days old",
"Unrealized gain ≠ return: the unrealized gain (value − cost basis) measures your gain since purchase, while the Modified Dietz return measures performance accounting for the timing of your contributions — both show on a detailed account. Adjust the cost basis after a buy/sell, otherwise the unrealized gain drifts",
"(Coming in Phase 5) Automatic price fetching for Stocks/Crypto via a private proxy (premium-only) that anonymizes your request — manual entry remains always available",
@ -2365,7 +2385,7 @@
},
"modal": {
"title": "Link transfers to {{account}}",
"subtitle": "Select transactions to attribute to this balance account. The direction is suggested based on the amount sign.",
"subtitle": "Check the transactions to attribute to this balance account; transactions already linked are listed first, checked, and unchecking them unlinks them. The direction is suggested from the sign of the amount.",
"from": "From",
"to": "To",
"category": "Category",
@ -2377,9 +2397,12 @@
"direction": "Direction",
"toggleDirection": "Click to flip direction",
"summary": "{{selected}} selected of {{total}} shown",
"linkSelection": "Link {{count}} transaction(s)",
"linking": "Linking…",
"partialFailure": "{{linked}}/{{total}} linked successfully"
"linking": "Saving…",
"partialFailure": "{{done}}/{{total}} changes saved ({{linked}} linked, {{unlinked}} unlinked)",
"linkedBadge": "Linked",
"save": "Save",
"changes": "{{link}} to link · {{unlink}} to unlink",
"directionFixed": "Direction fixed: uncheck, save, then check again to change it"
},
"errors": {
"transfer_direction_invalid": "Invalid transfer direction (expected in/out).",

View file

@ -278,7 +278,27 @@
"filename": "Fichier",
"date": "Date",
"rows": "Lignes",
"status": "Statut"
"status": "Statut",
"linked": {
"messageFile_one": "Cet import ne peut pas être supprimé tel quel : {{count}} transfert du Bilan s'appuie sur ses transactions, dans {{accounts}}.",
"messageFile_other": "Cet import ne peut pas être supprimé tel quel : {{count}} transferts du Bilan s'appuient sur ses transactions, dans {{accounts}}.",
"messageAll_one": "Les imports ne peuvent pas être supprimés tels quels : {{count}} transfert du Bilan s'appuie sur leurs transactions, dans {{accounts}}.",
"messageAll_other": "Les imports ne peuvent pas être supprimés tels quels : {{count}} transferts du Bilan s'appuient sur leurs transactions, dans {{accounts}}.",
"messageUnknown": "La suppression est refusée : des transactions sont liées à des comptes du Bilan.",
"more_one": "et {{count}} autre",
"more_other": "et {{count}} autres",
"hintBalance": "Déliez-les dans « Lier transferts » du compte, ou déliez-les et supprimez en une fois.",
"hintNoBalance": "Vous pouvez les délier et supprimer en une fois ; ces transferts seront perdus.",
"openAccount": "Lier transferts : {{account}}",
"unlinkAndDelete": "Délier et supprimer",
"confirmBody_one": "{{count}} transfert du Bilan sera délié sans retour, même avec une clé.",
"confirmBody_other": "{{count}} transferts du Bilan seront déliés sans retour, même avec une clé.",
"confirmBodyUnknown": "Les transferts du Bilan de ces transactions seront déliés sans retour, même avec une clé.",
"confirmAccounts": "Comptes touchés : {{accounts}}.",
"confirmFile": "Puis l'import « {{filename}} » et ses transactions seront supprimés.",
"confirmAll": "Puis tous les imports et leurs transactions seront supprimés.",
"failed": "La suppression a échoué ; rien n'a été modifié."
}
},
"wizard": {
"back": "Retour",
@ -1355,7 +1375,7 @@
"Saisissez vos snapshots à un rythme régulier (mensuel ou trimestriel) — la qualité des rendements dépend de la régularité",
"Le rendement non-ajusté à droite vous permet de voir « valeur du compte » vs « vraie performance » : la différence vient des apports, pas de la performance",
"Les marqueurs verticaux du graphique aident à lire les sauts de valeur : un saut suivi d'un marqueur vert n'est pas une « performance », c'est un dépôt",
"Si vous tentez de supprimer une transaction liée à un compte de bilan, l'app vous demande de la délier d'abord — cette friction préserve la reproductibilité de vos rendements passés",
"Une transaction liée à un compte de bilan s'affiche cochée en tête de « Lier transferts » : décochez-la puis enregistrez pour la délier. Un import qui en contient une ne se supprime pas tel quel : l'historique d'import nomme les comptes, offre le lien vers « Lier transferts » et, dans toute édition, « Délier et supprimer », qui perd ces transferts sans retour — cette friction préserve la reproductibilité de vos rendements passés",
"L'avertissement « bilan pas à jour » apparaît si votre dernier snapshot remonte à plus de 60 jours",
"Gain latent ≠ rendement : le gain latent (valeur − coût d'acquisition) mesure votre plus-value depuis l'achat, le rendement Modified Dietz mesure la performance en tenant compte du timing de vos apports — les deux s'affichent sur un compte détaillé. Ajustez le coût d'acquisition après un achat/vente, sinon le gain latent dérive",
"(À venir Phase 5) Récupération automatique des prix pour Actions/Crypto via un proxy privé (premium-only) qui anonymise votre requête — la saisie manuelle reste toujours disponible",
@ -2365,7 +2385,7 @@
},
"modal": {
"title": "Lier des transferts à {{account}}",
"subtitle": "Sélectionnez les transactions à attribuer à ce compte de bilan. La direction est proposée d'après le signe du montant.",
"subtitle": "Cochez les transactions à attribuer à ce compte de bilan ; les transactions déjà liées s'affichent en tête, cochées, et les décocher les délie. La direction est proposée d'après le signe du montant.",
"from": "Du",
"to": "Au",
"category": "Catégorie",
@ -2377,9 +2397,12 @@
"direction": "Sens",
"toggleDirection": "Cliquer pour inverser le sens",
"summary": "{{selected}} sélectionnée(s) sur {{total}} affichée(s)",
"linkSelection": "Lier {{count}} transaction(s)",
"linking": "Liaison…",
"partialFailure": "{{linked}}/{{total}} liées avec succès"
"linking": "Enregistrement…",
"partialFailure": "{{done}}/{{total}} changements enregistrés ({{linked}} liée(s), {{unlinked}} déliée(s))",
"linkedBadge": "Liée",
"save": "Enregistrer",
"changes": "{{link}} à lier · {{unlink}} à délier",
"directionFixed": "Sens fixé : décochez, enregistrez, puis recochez pour le changer"
},
"errors": {
"transfer_direction_invalid": "Direction de transfert invalide (in/out attendu).",

View file

@ -11,8 +11,9 @@
// (Modified Dietz) are deferred to Issue #142 — the accounts table reserves
// columns with a TODO comment.
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";
import { Wallet, FilePlus } from "lucide-react";
import {
useBalanceOverview,
@ -41,6 +42,7 @@ import HubReportNavCard, {
import { deriveLandingState } from "../components/balance/balanceLanding";
import { getPreference, setPreference } from "../services/userPreferenceService";
import { renderCategoryLabelFromAccount } from "../utils/renderCategoryLabel";
import { LINK_TRANSFERS_PARAM, takeLinkTransfersTarget } from "../utils/balanceLinkParam";
const STARTER_PREF_KEY = "balance_starter_proposed";
@ -69,6 +71,29 @@ export default function BalancePage() {
void getAllCategories().then(setCategories).catch(() => setCategories([]));
}, []);
// #522 — `/balance?linkTransfers=<id>`, from the import history's refused
// delete: open that account's "Lier transferts" once the accounts are
// loaded, then drop the parameter (replace), so going back never reopens
// it. An unknown or archived account drops it without opening anything.
const [searchParams, setSearchParams] = useSearchParams();
const linkParam = searchParams.get(LINK_TRANSFERS_PARAM);
// The accounts list starts empty: read the parameter only once a load ran.
const sawLoadRef = useRef(false);
if (state.isLoading) sawLoadRef.current = true;
useEffect(() => {
if (linkParam === null || state.isLoading || !sawLoadRef.current) return;
const target = takeLinkTransfersTarget(linkParam, state.accountsLatest);
if (target) setLinkTarget(target);
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
next.delete(LINK_TRANSFERS_PARAM);
return next;
},
{ replace: true }
);
}, [linkParam, state.isLoading, state.accountsLatest, setSearchParams]);
// Issue #179 — one-shot starter-accounts modal for existing profiles. The
// pref `balance_starter_proposed` is written once (confirmed or dismissed),
// so the modal never re-appears. New profiles get both the 4 starters AND
@ -417,7 +442,8 @@ export default function BalancePage() {
accountName={linkTarget.account_name}
categories={categories}
onClose={() => setLinkTarget(null)}
onLinked={() => {
onChanged={() => {
// Linked or unlinked: the chart markers and returns move (#522).
void reload();
}}
/>

View file

@ -1,5 +1,7 @@
import { getDb } from "./db";
import type Database from "@tauri-apps/plugin-sql";
import { getDb, withTransaction } from "./db";
import { notifyDataChanged } from "./dataEvents";
import { logInfo } from "./logService";
import { isLinkedTransactionFkError } from "./balance.service";
import { TransactionLinkedToBalanceError } from "./transactionService";
import type { ImportedFile, ImportedFileWithSource } from "../shared/types";
@ -188,3 +190,175 @@ export async function deleteAllImportsWithTransactions(): Promise<number> {
notifyDataChanged();
return result.rowsAffected;
}
// ---------------------------------------------------------------------------
// Imports that hold transactions linked to the Balance sheet (#522).
//
// Both delete paths above refuse when a transaction of the import is linked to
// a balance account (`ON DELETE RESTRICT`, ADR 0010). The history panel then
// names the accounts and counts the transfers (`getLinkedTransfersSummary`),
// and offers, in every edition, to unlink them and delete in one go
// (`unlinkAndDeleteImport`, `unlinkAndDeleteAllImports`).
// ---------------------------------------------------------------------------
/**
* The transactions one import's delete removes: its own rows, and the split
* children that the parent's `ON DELETE CASCADE` takes with them even when
* they do not carry the import's `file_id` (an older or restored profile).
*/
const FILE_TRANSACTIONS = `SELECT id FROM transactions
WHERE file_id = $1
OR parent_transaction_id IN (SELECT id FROM transactions WHERE file_id = $1)`;
/** What a delete of the import history targets: one import, or all of them. */
export type ImportDeletionScope = { kind: "file"; fileId: number } | { kind: "all" };
/** A balance account that holds transfers of the targeted transactions. */
export interface LinkedTransferAccount {
account_id: number;
account_name: string;
/** False for an archived account: the Balance page no longer lists it. */
is_active: boolean;
transfer_count: number;
}
/** The Balance sheet transfers a delete would lose, counted in full. */
export interface LinkedTransfersSummary {
transferCount: number;
/** Sorted by name. */
accounts: LinkedTransferAccount[];
}
/**
* Counts the transfers of the targeted transactions, per balance account. A
* `COUNT(*)`, not the pre-flight list of `deleteAllImportsWithTransactions`
* (`LIMIT 50`): the confirmation states the real number.
*/
export async function getLinkedTransfersSummary(
scope: ImportDeletionScope
): Promise<LinkedTransfersSummary> {
const db = await getDb();
const where = scope.kind === "file" ? `WHERE bat.transaction_id IN (${FILE_TRANSACTIONS})` : "";
const params = scope.kind === "file" ? [scope.fileId] : [];
const rows = await db.select<
Array<{ account_id: number; account_name: string; is_active: number; transfer_count: number }>
>(
`SELECT a.id AS account_id,
a.name AS account_name,
(a.is_active = 1 AND a.archived_at IS NULL) AS is_active,
COUNT(*) AS transfer_count
FROM balance_account_transfers bat
JOIN transactions t ON t.id = bat.transaction_id
JOIN balance_accounts a ON a.id = bat.account_id
${where}
GROUP BY a.id, a.name, a.is_active, a.archived_at
ORDER BY a.name COLLATE NOCASE, a.id`,
params
);
const accounts = rows.map((r) => ({
account_id: r.account_id,
account_name: r.account_name,
is_active: Number(r.is_active) === 1,
transfer_count: Number(r.transfer_count),
}));
return {
transferCount: accounts.reduce((sum, a) => sum + a.transfer_count, 0),
accounts,
};
}
/** What an unlink-and-delete did, counted inside its transaction. */
export interface UnlinkAndDeleteOutcome {
/** Balance sheet transfers removed: links, one per (transaction, account) pair, as counted by `transferCount`. */
unlinked: number;
/** Transactions removed. */
deleted: number;
}
/**
* Runs `body` between BEGIN and COMMIT on the transaction handle, ROLLBACK on
* any failure (the original error is rethrown). `withTransaction` holds the
* single DB lock for the whole section (`db.ts`); `body` must only use the
* handle it receives.
*/
async function inTransaction<T>(body: (db: Database) => Promise<T>): Promise<T> {
return withTransaction(async (db) => {
await db.execute("BEGIN");
let open = true;
try {
const value = await body(db);
await db.execute("COMMIT");
open = false;
return value;
} catch (e) {
if (open) {
try {
await db.execute("ROLLBACK");
} catch {
// Keep the original error: it is the one that explains the failure.
}
}
throw e;
}
});
}
/** Journal line of an unlink-and-delete: numbers only (REVIEW.md § Vie privée). */
function logUnlinkAndDelete(scope: ImportDeletionScope["kind"], outcome: UnlinkAndDeleteOutcome) {
logInfo(
`Import history: ${scope === "file" ? "one import" : "all imports"} deleted, ${outcome.unlinked} Balance transfer(s) unlinked, ${outcome.deleted} transaction(s) deleted`
);
}
/**
* Unlinks the Balance sheet transfers of one import's transactions, then
* deletes those transactions, the import and its source when no other import
* uses it: one SQL transaction, so a failing step leaves everything in place.
* The transfers are lost for good (#522, decision of 2026-11-07).
*/
export async function unlinkAndDeleteImport(fileId: number): Promise<UnlinkAndDeleteOutcome> {
const outcome = await inTransaction(async (db) => {
const files = await db.select<Array<{ source_id: number }>>(
"SELECT source_id FROM imported_files WHERE id = $1",
[fileId]
);
const sourceId = files.length > 0 ? files[0].source_id : null;
const unlinked = await db.execute(
`DELETE FROM balance_account_transfers WHERE transaction_id IN (${FILE_TRANSACTIONS})`,
[fileId]
);
const deleted = await db.execute("DELETE FROM transactions WHERE file_id = $1", [fileId]);
await db.execute("DELETE FROM imported_files WHERE id = $1", [fileId]);
if (sourceId !== null) {
const remaining = await db.select<Array<{ cnt: number }>>(
"SELECT COUNT(*) AS cnt FROM imported_files WHERE source_id = $1",
[sourceId]
);
if (Number(remaining[0]?.cnt) === 0) {
await db.execute("DELETE FROM import_sources WHERE id = $1", [sourceId]);
}
}
return { unlinked: unlinked.rowsAffected, deleted: deleted.rowsAffected };
});
logUnlinkAndDelete("file", outcome);
// Announced once, after the COMMIT and out of the DB lock (ADR 0022).
notifyDataChanged();
return outcome;
}
/**
* Unlinks every Balance sheet transfer, then deletes every transaction, import
* and source: the "delete all" of the history, in one SQL transaction.
*/
export async function unlinkAndDeleteAllImports(): Promise<UnlinkAndDeleteOutcome> {
const outcome = await inTransaction(async (db) => {
const unlinked = await db.execute("DELETE FROM balance_account_transfers");
const deleted = await db.execute("DELETE FROM transactions");
await db.execute("DELETE FROM imported_files");
await db.execute("DELETE FROM import_sources");
return { unlinked: unlinked.rowsAffected, deleted: deleted.rowsAffected };
});
logUnlinkAndDelete("all", outcome);
notifyDataChanged();
return outcome;
}

View file

@ -0,0 +1,28 @@
import { describe, it, expect } from "vitest";
import { linkTransfersHref, takeLinkTransfersTarget } from "./balanceLinkParam";
const ACCOUNTS = [
{ account_id: 2, account_name: "CELI" },
{ account_id: 13, account_name: "REER" },
];
describe("balanceLinkParam (#522)", () => {
it("builds the Balance URL that opens an account's window", () => {
expect(linkTransfersHref(13)).toBe("/balance?linkTransfers=13");
});
it("finds the loaded account the value names", () => {
expect(takeLinkTransfersTarget("13", ACCOUNTS)).toEqual(ACCOUNTS[1]);
});
it("opens nothing for an account the page does not list", () => {
expect(takeLinkTransfersTarget("7", ACCOUNTS)).toBeNull();
expect(takeLinkTransfersTarget("2", [])).toBeNull();
});
it("opens nothing for a value that is not a positive integer", () => {
for (const v of ["", "0", "-2", "2.0", "2abc", " 2", "1e1"]) {
expect(takeLinkTransfersTarget(v, ACCOUNTS)).toBeNull();
}
});
});

View file

@ -0,0 +1,26 @@
/**
* `/balance?linkTransfers=<id>` (#522): the import history's refused delete
* links to the "Lier transferts" window of a balance account. The Balance
* page reads the parameter once its accounts are loaded, opens the window of
* the matching active account, and drops the parameter.
*/
export const LINK_TRANSFERS_PARAM = "linkTransfers";
/** The URL of the Balance page that opens `accountId`'s "Lier transferts". */
export function linkTransfersHref(accountId: number): string {
return `/balance?${LINK_TRANSFERS_PARAM}=${accountId}`;
}
/**
* The account a parameter value names among the loaded (active) accounts, or
* null: a value that is not a positive integer, or an account the page does
* not list (archived, deleted), opens nothing.
*/
export function takeLinkTransfersTarget<T extends { account_id: number }>(
value: string,
accounts: readonly T[]
): T | null {
if (!/^[1-9][0-9]*$/.test(value)) return null;
const id = Number(value);
return accounts.find((a) => a.account_id === id) ?? null;
}