diff --git a/CHANGELOG.fr.md b/CHANGELOG.fr.md index d446bc3..0274630 100644 --- a/CHANGELOG.fr.md +++ b/CHANGELOG.fr.md @@ -24,6 +24,7 @@ - Import : un message d'erreur ne reste plus affiché une fois le dossier d'import relu, après « Actualiser » ou après le choix d'un autre dossier par « Parcourir » ; le message d'un dossier d'exemple déjà présent dans le dossier d'import demandait justement d'actualiser. Annuler le choix du dossier garde le message (#384). - Journaux (Paramètres → Système) : une ligne d'erreur sur l'ouverture ou la fermeture d'un profil ne garde plus le nom d'un dossier qui contient `;`, `|`, une apostrophe inverse ou une parenthèse fermante suivie d'un mot, comme `Jean (Work) Smith` : elle ne nomme que le fichier. La ligne écrite quand la réparation des migrations d'un profil échoue à son ouverture (« Migration repair failed ») ne nomme plus, elle aussi, que le fichier de la base ; elle en montrait le chemin complet, dossiers de votre compte compris. Ces lignes peuvent partir avec une rétroaction quand vous y incluez les derniers logs d'erreur. En contrepartie, le texte qui suit un chemin après l'un de ces caractères et qui contient un `/` ou un `\` est désormais retiré avec les dossiers, jusqu'à son dernier `/` ou `\` (#478). - Journaux (Paramètres → Système) : une ligne des journaux ne porte plus votre dossier personnel ni le dossier qui contient les bases des profils, nommés tous deux d'après votre compte d'utilisateur, quoi qu'il y ait autour, comme un nom de dossier qui contient une virgule (`Smith, Jean`) ou un chemin collé à un `;` : le dossier personnel devient `~` et celui des bases ``. Cela vaut pour toutes les lignes, ce que copie « Copier » compris, et les lignes écrites au démarrage avant que ces dossiers soient connus les perdent dès qu'ils le sont. Une ligne d'erreur sur l'ouverture ou la fermeture d'un profil ne nomme toujours que le fichier. Ces lignes peuvent partir avec une rétroaction quand vous y incluez les derniers logs d'erreur (#497). +- Transactions : changer la catégorie d'une transaction répartie déplace désormais toute sa part non répartie vers la nouvelle catégorie. Les rapports gardaient, dans l'ancienne catégorie, le montant envoyé vers les autres catégories avec le signe inverse, sans transaction correspondante, et comptaient la transaction entière dans la nouvelle : une transaction de −120 dont −50 sont répartis vers B, déplacée de A vers C, laissait +50 dans A et −120 dans C, au lieu de −70 dans C. Cela vaut pour la catégorie choisie dans la liste des transactions comme pour les transactions recatégorisées par un nouveau mot-clé. Une répartition déjà touchée se répare au prochain changement de catégorie de sa transaction, et sa fenêtre de répartition ne montre plus ce montant comme l'une de ses lignes. La prévisualisation d'un mot-clé ne liste plus les parts d'une répartition, qu'elle pouvait recatégoriser sans leur transaction (#454). ### Sécurité diff --git a/CHANGELOG.md b/CHANGELOG.md index 35dcd6e..4e154de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ - Import: an error message no longer stays on screen once the import folder is read again, after “Refresh” or after choosing another folder with “Browse”; the message of a sample folder already in the import folder asked for that very refresh. Cancelling the folder choice keeps the message (#384). - Logs (Settings → System): an error line about opening or closing a profile no longer keeps the name of a folder that holds `;`, `|`, a backtick or a closing parenthesis followed by a word, such as `Jean (Work) Smith`: it names the file only. The line written when the migration repair of a profile fails at opening (“Migration repair failed”) now names the database file only too; it showed the file's full path, folders of your user account included. These lines can go with a feedback report when you include the recent error logs. In return, text that follows a path after one of these characters and holds a `/` or a `\` is now dropped with the folders, up to its last `/` or `\` (#478). - Logs (Settings → System): a line of the logs no longer carries your home folder or the folder that holds the profile databases, both named after your user account, whatever surrounds them, such as a folder name that holds a comma (`Smith, Jean`) or a path glued to a `;`: the home folder becomes `~` and the databases' folder ``. This holds for every line, what “Copy” copies included, and the lines written at startup before these folders are known lose them as soon as they are. An error line about opening or closing a profile still names the file only. These lines can go with a feedback report when you include the recent error logs (#497). +- Transactions: changing the category of a split transaction now moves all of its unsplit part to the new category. The reports used to keep, in the former category, the amount sent to the other categories with the opposite sign, matching no transaction, and to count the whole transaction in the new one: a transaction of −120 with −50 split to B, moved from A to C, left +50 in A and −120 in C, instead of −70 in C. This holds for the category chosen in the Transactions list and for the transactions recategorized by a new keyword. A split already affected is repaired the next time its transaction changes category, and its split window no longer shows that amount as one of its rows. The keyword preview no longer lists the parts of a split, which it could recategorize without their transaction (#454). ### Security diff --git a/CLAUDE.md b/CLAUDE.md index 343767d..63d6f41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,7 +56,7 @@ src/ ├── contexts/ # ProfileContext (état global profil) ├── hooks/ # 30 hooks custom (useReducer) ├── pages/ # 11 pages -├── services/ # 28 services métier +├── services/ # 29 services métier ├── shared/ # Types et constantes partagés ├── utils/ # Utilitaires (parsing, CSV, charts) ├── i18n/ # Config i18next + locales FR/EN diff --git a/STATE.md b/STATE.md index 122c044..f85d2fe 100644 --- a/STATE.md +++ b/STATE.md @@ -204,6 +204,7 @@ Côté site, la demande « merger et déployer après la publication » pour l' - Procédure `/release` revue par la pile #499 → #506 (dossiers 28630 et 28647) : à l'étape 0, lancer les deux commandes de report de la matrice des éditions et lire chaque commit trouvé, la PR du site n'étant mergée et déployée qu'après le `VERDICT : OK` ; à l'étape 3, la sous-étape « Vérifier les en-têtes » doit mener au vert sans toucher à la version des autres fichiers ; à l'étape 10, si seul l'endpoint de mise à jour change, `curl … | jq -r .version` doit rendre la nouvelle version. - Focus des fenêtres d'incitation (#494, PR #511), en édition Gratuite sauf mention, en FR et en EN, thèmes clair et sombre, sous Linux et sous Windows : Transactions → bouton Répartition verrouillé (à la souris, puis par Tab et Entrée), et sélecteur de profil → profil verrouillé : anneau de focus visible sur le X à l'ouverture, Tab et Maj+Tab font le tour de la fenêtre sans passer derrière le voile, X et Échap rendent le focus au bouton Répartition de la ligne, ou au bouton du sélecteur pour la fenêtre ouverte depuis son menu, comme « J'ai déjà une clé » depuis le sélecteur (depuis Transactions, la page change et le focus n'est nulle part, comme après toute navigation) ; « Gérer les profils » : focus sur le X à l'ouverture, Tab qui boucle dans chaque mode, « Créer un profil » verrouillé → focus sur le X, « Annuler » → focus sur « Créer un profil », en Base « Créer un profil » et « Modifier » → champ Nom, « Annuler » ou « Enregistrer » d'une modification → « Créer un profil », Échap qui ferme la fenêtre (depuis le champ Nom aussi) sauf pendant un enregistrement, X et Échap qui rendent le focus au bouton du sélecteur ; la même fenêtre ouverte depuis l'écran de choix du profil (aucun profil actif, hors routeur), le focus rendu à sa tuile « Créer un profil » ; lecteur d'écran (Orca, Narrateur) : chaque fenêtre annoncée à l'ouverture comme une boîte de dialogue avec son nom, le X lu « Fermer », le bouton du sélecteur annoncé déplié ou replié ; en Base, le sélecteur change toujours de profil et Répartition ouvre la fenêtre de répartition. Après la suppression d'un profil, la fenêtre se ferme le temps du rechargement des profils, comme avant : le focus ne va pas sur « Créer un profil » (attendu, PR #511). - Journal sans dossier (#497, PR #512), sous Linux puis sous Windows, sur un profil secondaire de test : l'app fermée, lire le nom de sa base (`db_filename`, `profile_.db`) dans `profiles.json` (`~/.local/share/com.simpl.resultat/` sous Linux, `%APPDATA%\com.simpl.resultat\` sous Windows), renommer cette base et créer à sa place un dossier vide du même nom, dans le dossier des bases (`~/.config/com.simpl.resultat/` sous Linux, `$XDG_CONFIG_HOME/com.simpl.resultat/` s'il est défini ; `%APPDATA%\com.simpl.resultat\` sous Windows), une base en lecture seule s'ouvrant sans erreur ; ouvrir l'app sur un autre profil et basculer vers celui-ci (l'ouverture échoue), puis lire dans Paramètres → Système → Journaux les lignes « Migration repair failed » et « database preparation failed » : elles nomment `profile_.db` et ne contiennent aucun segment du dossier personnel ; si la page d'erreur s'affiche à la place, remettre la base puis « Actualiser » (le Journal de la session garde les lignes) ; « Copier », puis une rétroaction de test avec « Inclure les derniers logs d'erreur » : aucun dossier ; supprimer le dossier et remettre la base ensuite. + - Compensation d'une répartition (#454, PR #515), en édition Base, en FR et en EN : une transaction répartie reclassée par la liste puis par un mot-clé, l'ancienne catégorie se vide et la fenêtre de répartition ne montre que les vraies lignes ; procédure dans le corps de la PR. - **Le paiement est live : « aucun tag avant le go-live » n'a plus de raison d'être, et la release desktop qu'attendait le go-live est publiée (v0.16.0, 2026-10-03).** Bascule live le 2026-09-29 (Product et Price live à 19 $ CAD, webhook, variables Stripe de production, redeploy `3673d09` de maximus-api, URL `cs_live_` vérifiée), puis achat réel de contrôle le 2026-09-30 : clé sur `/merci` et par courriel, activation dans l'app, remboursement complet et licence révoquée par `charge.refunded`. **Volet serveur clos le 2026-10-03** (derniers commentaires relus le 2026-10-04) : maximus-api#62 fermée, tous critères cochés (maximus-api 0.4.2 en prod, secrets en runtime seul), avec la milestone `spec-paiements` de maximus-api (12/12) ; la-compagnie-maximus#150 (Link dans les textes légaux) livrée et fermée le 2026-10-01. **Go-live clos : la-compagnie-maximus#141** fermée le 2026-10-10 sur décision de Max, l'updater vérifié (Free refuse et invite à acheter, Base accepte ; confirmé le même jour). Restent pour mémoire, sans issue : le Dashboard Stripe (logo, paramètres Checkout, reçus automatiques, alertes d'échec de webhook) et les relevés du commentaire de fermeture. la-compagnie-maximus#184 (politique de confidentialité : données d'activation, contrôle au démarrage) est en `status:review` ; sa PR reste en brouillon jusqu'au déploiement de maximus-api#85 (commentaire du 2026-10-03). Les deux textes des suites de licence (contrôle à la saisie, retrait de la clé) y sont postés depuis le 2026-10-05 (commentaire 19724). **Vérifications manuelles sur la release publiée, toutes faites** : #365 le 2026-10-03, #346 et #350 le 2026-10-04 (voir Décisions). L'étape 10 sous Windows est faite (Michel, confirmée le 2026-10-10). - Backlog ouvert : **vague `planned-2026-09-24-paiements` close 3/3** (milestone fermée le 2026-09-30) : #270 (PR #359) et #346 (PR #362) mergées le 2026-09-27, #347 (PR #364, ferme aussi #360) mergée le 2026-09-30 ; volet site **clos** (maximus/la-compagnie-maximus#153, redirection de `/simpl-resultat` en prod). **#365 fermée le 2026-10-03** après sa vérification manuelle. **Milestone `planned-2026-10-03-suites-licence` fermée 3/3 le 2026-10-05** (#373, #370, #367 mergées, voir Décisions ; suivi #389 en `status:triage`). Hors milestone : **#369** (réserver le fractionnement de transactions à l'édition Base) **fermée le 2026-10-17** (PR #452, voir Décisions) ; **#372** (la liste complète des versions repousse le Journal en bas de Paramètres → Systèmes) reste en `status:ready`. **#350 fermée le 2026-10-04** (étape 3 vérifiée en production, voir Décisions) ; #363 fermée le 2026-10-10 sur décision de Max (ses tests, absorbés par #347, sont livrés dans la v0.16.0) ; réglés côté serveur et site : maximus-api#63 (clés de 100 ans) et maximus-api#70 (réactivation d'une machine désactivée), fermées et contenues dans `3673d09`, le commit déployé à la bascule du 2026-09-29, et la-compagnie-maximus#157, fermée, dont les CGV sont publiées en tronc commun plus annexe Simpl-Résultat (annexe relue en production le 2026-09-30, plus aucune durée de 10 ans) ; côté serveur, `/v1/prices` ne vérifie pas qu'une machine est encore active (une machine désactivée garde les cours jusqu'à l'expiration de son jeton), issue maximus-api à ouvrir ; suites de #350 ouvertes le 2026-10-01 : maximus-api#82 (`status:triage` : identifiants machine bruts déjà stockés, lignes désactivées comprises ; à rehacher avant l'expiration des premiers jetons bruts, sinon une réactivation crée une seconde ligne) et la-compagnie-maximus#184 (`status:review`, voir ci-dessus) ; go-live clos (la-compagnie-maximus#141 fermée le 2026-10-10, maximus-api#62 le 2026-10-03) ; `spec-paiements` fermée ici 5/5 ; onboarding phase 2 (parcours guidé) **mergée** : milestone `planned-2026-10-06-onboarding-parcours-guide` fermée 6/6 le 2026-10-08 (#396 à #401, `ee17f31`), suivis **#408** et **#409** (`status:triage`) ; onboarding phase 1 **livrée** : milestone `planned-2026-10-03-onboarding-phase1` fermée 7/7 le 2026-10-04 (#351 à #357, mergées en avance rapide, `667e058`) ; suivis ouverts : **#384** (`status:ready`, suivis non bloquants des revues) ; **#371** fermée le 2026-10-23 (PR #489, bloc BMO confirmé sur compte réel), la signature d'import BMO suit en **#488** (`status:blocked` : lignes aux valeurs fictives, préambule éventuel et en-tête d'un compte de dépôt à fournir par Max) ; analyse d'origine dans `docs/analyse-onboarding-2026-09.md`, plan détaillé dans les `spec-*-onboarding-phase1.md` locaux, ignorés par git ; #271 absorbé par #301, livré ; `spec-ci-build-optimization` **fermée 4/4** le 2026-10-05 (#232 livrée le 2026-07-27 ; #234 close le 2026-10-05 avec ses quatre preuves : dispatch run 464, PR #386 run 480, run planifié 488, `actcache` à 999 Mo) ; **#376** fermée le 2026-10-12 (Node 24, PR #414). Le suivi « glob `src-tauri/**` non prouvé » ouvert avec #232 est **levé** : la PR #344 est le cas test isolé attendu (`Cargo.lock` + 2 `.md` seulement) — `check-rust` a bien tourné, `check-frontend` a bien été sauté par sa denylist. - Suivis des advisories : **#312, #313 et #315 fermées le 2026-08-15** (PRs #321/#322 mergées). **#314 fermée le 2026-08-15, prémisse infirmée** — elle affirmait « zéro run `schedule` », or `audit.yml` tire tous les jours à 06:00 UTC (**19 runs `schedule` verts** du 07-28 au 08-15, sans trou) ; elle a été écrite le 07-27 vers 23:56Z, ~6 h avant le premier tir programmé possible, et décrivait donc une fenêtre trop courte, pas un scheduler en panne. Ces 19 runs confirment au passage que `.cargo/audit.toml` est bien lu en conteneur **sur `main`** — l'ADR 0018 ne l'avait vérifié que par un `workflow_dispatch` sur une branche. **#343 fermée le 2026-09-04** (PR #344) — RUSTSEC-2026-0258 sur `h2`, la seule vulnérabilité qui rougissait l'audit depuis le 08-19 ; l'audit est de nouveau vert sur `main`, prouvé par `workflow_dispatch` (run 393) et non déduit du run de PR. **#348 fermée le 2026-09-21** (PR #349) — RUSTSEC-2026-0285 sur `rustls`, seule vulnérabilité rougissant l'audit depuis le 09-15 (7 runs, 405→411) ; vert reprouvé par `workflow_dispatch` sur `main` (run 414 : 666 paquets, zéro vulnérabilité, 12 warnings autorisés). Deux advisories en cinq semaines sur le même chemin, celui de la mise à jour automatique. **#447 fermée le 2026-10-16** (PR #448, run 556 vert), quatre avis `rustls` sur ce même chemin ; le Défenseur n'audite pas le Rust (agent-defenseurs#186), `audit.yml` reste le seul canal pour les avis RustSec. **#455 fermée le 2026-10-18** (PR #459, run 564 vert), trois avis `zip` sur ce même chemin, retirés avec la feature `zip` de l'updater plutôt que supprimés. **#317** fermée le 2026-10-12 par la PR #417 (#358). Reste **#319** (déclencheur de retrait pour `rsa`, désormais **seule** entrée de `.cargo/audit.toml` — le garde-fou est passé à 2 vérifications). **#345** fermée le 2026-10-12 (PR #415) : garde `Verify windows-sys pinning` dans `check-rust.yml` et ADR 0023, qui portent la mesure, le coût (3 contre 5 versions compilées pour Windows) et la condition de sortie. Côté npm, **#358** fermée le 2026-10-12 (PR #417) : lock régénéré par `npm@11.21.0` dans les bornes de `package.json`, `npm audit` 8 → 0 au 2026-10-10. diff --git a/docs/adr/0022-canal-evenements-donnees.md b/docs/adr/0022-canal-evenements-donnees.md index 92e51f9..097a3c0 100644 --- a/docs/adr/0022-canal-evenements-donnees.md +++ b/docs/adr/0022-canal-evenements-donnees.md @@ -32,7 +32,7 @@ La liste est construite depuis les tables que lit `COUNTERS_SQL`, plus le dossie | `userPreferenceService.ts` | `setImportFolder` | après l'écriture de la préférence (`setPreference` seul ne notifie pas) | | `importSourceService.ts` | `createSource`, `deleteSource` | après l'écriture ; `createSource` notifie avant la relecture qui suit un conflit de nom, qui ne fait que lire | | `importedFileService.ts` | `createImportedFile` (insertion comme mise à jour), `updateFileStatus`, `deleteImportWithTransactions`, `deleteAllImportsWithTransactions` | après l'écriture ; pour les suppressions, après la dernière (source orpheline comprise). Un refus du contrôle préalable (transactions liées au Bilan) ne notifie pas | -| `transactionService.ts` | `insertBatch`, `updateTransactionCategory` | `insertBatch` une fois, après la dernière insertion | +| `transactionService.ts` | `insertBatch`, `updateTransactionCategory` | `insertBatch` une fois, après la dernière insertion ; `updateTransactionCategory` après le `COMMIT` de sa transaction (#454), une fois le verrou relâché, et un `ROLLBACK` relance l'erreur et ne notifie pas | | `categorizationService.ts` | `applyKeywordWithReassignment` | après le `COMMIT`, une fois le verrou de `db.ts` relâché ; un `ROLLBACK` relance l'erreur et ne notifie pas | | `budgetService.ts` | `upsertBudgetEntry`, `deleteBudgetEntry`, `upsertBudgetEntriesForYear`, `applyTemplate` | après l'écriture ; `upsertBudgetEntriesForYear` après les douze mois, `applyTemplate` une fois après la dernière entrée du modèle | | `dataExportService.ts` | `runRestore` | après le `COMMIT`, une fois le verrou relâché : un seul point pour les trois modes de restauration | diff --git a/docs/architecture.md b/docs/architecture.md index 121ee01..693a1b4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -44,9 +44,9 @@ simpl-resultat/ │ ├── contexts/ # LicenseContext (licence machine) + ProfileContext (état global profil) + OnboardingContext (parcours de démarrage, #396) │ ├── hooks/ # 30 hooks custom (useReducer, 5 hooks rapports par domaine) │ ├── pages/ # 14 pages (dont 4 sous-pages rapports) -│ ├── services/ # 28 services métier (22 détaillés dans la section « Services TypeScript ») +│ ├── services/ # 29 services métier (23 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/ # 20 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) +│ ├── utils/ # 21 utilitaires purs (parsing montants/dates, détection CSV, codec de format d'import, dictionnaire lexical, signatures de banques, charts, drapeaux SQL 0/1, liste et parcours de démarrage, historique des versions, hiérarchie des catégories, ligne de compensation d'une répartition) │ ├── i18n/ # Config i18next + locales FR/EN │ ├── __fixtures__/ # csv/ : corpus de détection (15 cas figés) ; samples/ : gabarits du dossier d'exemple embarqués par Rust │ ├── App.tsx # Router principal @@ -195,18 +195,19 @@ Les **profils secondaires** (`profile_.db`) sont créés par `get_new_profil Le dossier des bases est celui du plugin : `app_config_dir()`, résolu par `profile_db_path` (`profile_commands.rs`). Il diffère de `app_data_dir()`, où vit `profiles.json`, sous Linux seulement (`~/.config/com.simpl.resultat` et `~/.local/share/com.simpl.resultat`). -## Services TypeScript (22) +## Services TypeScript (23) | Service | Responsabilité | |---------|---------------| | `db.ts` | Wrapper de connexion (tauri-plugin-sql), verrou FIFO de tous les accès et `withTransaction` (voir « Accès DB et transactions »). `connectToProfile` appelle `repair_migrations` puis `prepare_profile_db` avant `Database.load`, et écrit au Journal ce que la préparation a changé (`describePreparation`, noms de fichiers seulement, #390) ; un échec est écrit au Journal et le profil s'ouvre quand même. Chaque ligne que le fichier écrit au Journal passe par `cleanLogLine` : le remplacement exact des dossiers connus (`replaceKnownFolders`), puis `withoutFolders`, dans cet ordre (#497, [ADR 0021](adr/0021-migrations-profils-secondaires.md), § 7) ; `connectToProfile` attend ces dossiers (`knownFoldersReady()`) avant `repair_migrations` | | `profileService.ts` | Gestion des profils | | `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) | +| `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) | | `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 | | `importConfigTemplateService.ts` | Modèles de configuration d'import | -| `categorizationService.ts` | Catégorisation automatique + helpers édition de mot-clé (`validateKeyword`, `previewKeywordMatches`, `applyKeywordWithReassignment`) | +| `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 à 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. 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 | | `adjustmentService.ts` | Gestion des ajustements | | `budgetService.ts` | Gestion budgétaire | | `dashboardService.ts` | Agrégation données tableau de bord : `getExpensesByCategory` (barres classées, `accountIds`), `getDashboardSummary` (non consommé depuis #279), `deriveNetWorthTile` (pur — tuile valeur nette du Bilan, réutilise `deriveLandingState`) | diff --git a/src/components/transactions/SplitAdjustmentModal.test.ts b/src/components/transactions/SplitAdjustmentModal.test.ts new file mode 100644 index 0000000..760ce27 --- /dev/null +++ b/src/components/transactions/SplitAdjustmentModal.test.ts @@ -0,0 +1,106 @@ +// SplitAdjustmentModal — which children of a split it shows as entries (#454). +// +// The window loads the children in an effect, then keeps those that are not +// the offset line as its entries. React's hooks come from the shared harness +// (src/test/hookHarness.ts, #409): `commit()` runs the loading effect, the +// test lets its promise settle, then renders again and reads the entries +// through the props of their CategoryCombobox and amount field. +import { describe, it, expect, vi, 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()); + +import { hookHarness } from "../../test/hookHarness"; +import { find } from "../../test/elementTree"; +import SplitAdjustmentModal from "./SplitAdjustmentModal"; +import CategoryCombobox from "../shared/CategoryCombobox"; +import type { SplitChild, TransactionRow } from "../../shared/types"; + +const harness = hookHarness(); + +// The reproduction of #454: −120 split as −50 to category B, whose offset line +// of +50 was written in A, the parent's category at the time. +const A = 3; +const B = 4; +const C = 9; + +const parentIn = (categoryId: number): TransactionRow => ({ + id: 5, + date: "2026-10-01", + description: "EPICERIE METRO", + amount: -120, + category_id: categoryId, + category_name: null, + category_color: null, + source_name: null, + notes: null, + is_manually_categorized: true, + is_split: true, +}); + +const childOf = (id: number, amount: number, categoryId: number): SplitChild => ({ + id, + category_id: categoryId, + category_name: null, + category_color: null, + amount, + description: "EPICERIE METRO", +}); + +const ENTRY = childOf(6, -50, B); + +/** Lets the loading promise settle. */ +const flush = async () => { + for (let i = 0; i < 10; i++) await Promise.resolve(); +}; + +/** One render of the mounted window: its entries, as category and amount. */ +const entriesOf = (transaction: TransactionRow, children: SplitChild[]) => { + const tree: ReactNode = harness.render(() => + SplitAdjustmentModal({ + transaction, + categories: [], + onLoadChildren: async () => children, + onSave: vi.fn(async () => undefined), + onDelete: vi.fn(async () => undefined), + onClose: vi.fn(), + }), + ); + const categories = find(tree, (el) => el.type === CategoryCombobox).map((el) => el.props.value); + const amounts = find(tree, (el) => el.type === "input" && el.props.type === "number").map((el) => el.props.value); + return categories.map((category, i) => ({ category, amount: amounts[i] })); +}; + +/** Mounts the window, runs its loading effect, and reads the entries once loaded. */ +const loadedEntries = async (transaction: TransactionRow, children: SplitChild[]) => { + entriesOf(transaction, children); + harness.commit(); + await flush(); + return entriesOf(transaction, children); +}; + +beforeEach(() => harness.clear()); + +describe("SplitAdjustmentModal — the offset line is never an entry (#454)", () => { + it("leaves out the offset line in the parent's category", async () => { + const entries = await loadedEntries(parentIn(A), [ENTRY, childOf(7, 50, A)]); + expect(entries).toEqual([{ category: B, amount: "50.00" }]); + }); + + // Decision D2: a reclassification made before #454 left the offset line in A + // while the parent went to C; reopened, the window must not offer it as an + // entry (saving would turn it into a real one). + it("leaves out an offset line left in a former category", async () => { + const entries = await loadedEntries(parentIn(C), [ENTRY, childOf(7, 50, A)]); + expect(entries).toEqual([{ category: B, amount: "50.00" }]); + }); + + it("keeps an entry of the parent's category, which has the parent's sign", async () => { + const entries = await loadedEntries(parentIn(A), [ENTRY, childOf(8, -20, A), childOf(7, 70, A)]); + expect(entries).toEqual([ + { category: B, amount: "50.00" }, + { category: A, amount: "20.00" }, + ]); + }); +}); diff --git a/src/components/transactions/SplitAdjustmentModal.tsx b/src/components/transactions/SplitAdjustmentModal.tsx index 2bcd32c..e5e2e62 100644 --- a/src/components/transactions/SplitAdjustmentModal.tsx +++ b/src/components/transactions/SplitAdjustmentModal.tsx @@ -2,6 +2,7 @@ import { useState, useEffect, useMemo } from "react"; import { useTranslation } from "react-i18next"; import { X, Plus, Trash2 } from "lucide-react"; import type { TransactionRow, Category, SplitChild } from "../../shared/types"; +import { isOffsetChild } from "../../utils/splitOffset"; import CategoryCombobox from "../shared/CategoryCombobox"; interface SplitEntry { @@ -46,10 +47,9 @@ export default function SplitAdjustmentModal({ if (!transaction.is_split) return; setLoading(true); onLoadChildren(transaction.id).then((children) => { - // Filter out the offset child (same category as parent) - const splitEntries = children.filter( - (c) => c.category_id !== transaction.category_id || Math.sign(c.amount) === Math.sign(transaction.amount) - ); + // The offset line is not an entry: leave it out whatever its category, + // one left in a former category by an earlier change included (#454). + const splitEntries = children.filter((c) => !isOffsetChild(transaction, c)); if (splitEntries.length > 0) { setEntries( splitEntries.map((c) => ({ diff --git a/src/services/categorizationService.test.ts b/src/services/categorizationService.test.ts index 7a8785b..b798d15 100644 --- a/src/services/categorizationService.test.ts +++ b/src/services/categorizationService.test.ts @@ -31,6 +31,45 @@ beforeEach(() => { mockExecute.mockReset(); }); +/** The statements sent through `execute`, whitespace collapsed, with their parameters. */ +const statements = () => + mockExecute.mock.calls.map(([sql, params]) => ({ + sql: String(sql).replace(/\s+/g, " ").trim(), + params: (params ?? []) as unknown[], + })); + +/** The last parameter of a statement: the id of its `WHERE id = $n`. */ +const targetOf = (statement: { params: unknown[] }) => statement.params[statement.params.length - 1]; + +/** A transaction that is not split, as the offset propagation reads it (#454). */ +const plainRow = (id: number) => ({ id, description: "METRO", amount: -10, is_split: 0, parent_transaction_id: null }); + +/** + * Answers every read of the keyword path: the lookup of the keyword's spelling + * (`keywordRows`, none by default), then, for each checked id, the offset + * propagation's read of the transaction (`rows`, a transaction that is not + * split by default) and of a split's children (`children`, by parent id; + * #454). Any other read fails the test. + */ +function answerReads({ + keywordRows = [], + rows = {}, + children = {}, +}: { + keywordRows?: Array<{ id: number; category_id: number }>; + rows?: Record>; + children?: Record>>; +} = {}) { + mockSelect.mockImplementation(async (sql: string, params?: unknown[]) => { + const flat = String(sql).replace(/\s+/g, " "); + const id = Number(params?.[0]); + if (/FROM keywords WHERE keyword = \$1/.test(flat)) return keywordRows; + if (/FROM transactions WHERE parent_transaction_id = \$1/.test(flat)) return children[id] ?? []; + if (/FROM transactions WHERE id = \$1/.test(flat)) return [rows[id] ?? plainRow(id)]; + throw new Error(`unexpected read: ${flat}`); + }); +} + describe("validateKeyword", () => { it("rejects whitespace-only input", () => { expect(validateKeyword(" ")).toEqual({ ok: false, reason: "tooShort" }); @@ -91,11 +130,22 @@ describe("previewKeywordMatches", () => { expect(result.visible[0].id).toBe(1); expect(result.visible[1].id).toBe(2); }); + + // An entry or the offset line of a split (which carries the parent's + // description) would be recategorized without its parent (#454). + it("never offers a child of a split: the candidates are rows without a parent (#454)", async () => { + mockSelect.mockResolvedValueOnce([]); + + await previewKeywordMatches("METRO"); + + const sql = String(mockSelect.mock.calls[0][0]).replace(/\s+/g, " "); + expect(sql).toMatch(/WHERE LOWER\(t\.description\) LIKE \$1 AND t\.parent_transaction_id IS NULL ORDER BY/); + }); }); describe("applyKeywordWithReassignment", () => { it("wraps INSERT + UPDATEs in a BEGIN/COMMIT transaction", async () => { - mockSelect.mockResolvedValueOnce([]); // existing keyword lookup → none + answerReads(); // existing keyword lookup → none; transactions not split mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 }); await applyKeywordWithReassignment({ @@ -115,7 +165,7 @@ describe("applyKeywordWithReassignment", () => { // The Transactions step card leads to this dialog (#430): the transactions it // categorizes must count as categorized by hand, so the step checks off. it("marks every checked transaction as categorized by hand, with a literal 1 (#430)", async () => { - mockSelect.mockResolvedValueOnce([]); + answerReads(); mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 }); await applyKeywordWithReassignment({ @@ -138,7 +188,7 @@ describe("applyKeywordWithReassignment", () => { }); it("rolls back when an UPDATE throws", async () => { - mockSelect.mockResolvedValueOnce([]); + answerReads(); mockExecute .mockResolvedValueOnce(undefined) // BEGIN .mockResolvedValueOnce({ lastInsertId: 77 }) // INSERT keywords @@ -160,7 +210,7 @@ describe("applyKeywordWithReassignment", () => { }); it("blocks reassignment when keyword exists for another category without allowReplaceExisting", async () => { - mockSelect.mockResolvedValueOnce([{ id: 10, category_id: 5 }]); + answerReads({ keywordRows: [{ id: 10, category_id: 5 }] }); await expect( applyKeywordWithReassignment({ @@ -177,7 +227,7 @@ describe("applyKeywordWithReassignment", () => { }); it("reassigns existing keyword when allowReplaceExisting is true", async () => { - mockSelect.mockResolvedValueOnce([{ id: 10, category_id: 5 }]); + answerReads({ keywordRows: [{ id: 10, category_id: 5 }] }); mockExecute.mockResolvedValue({ rowsAffected: 1 }); const result = await applyKeywordWithReassignment({ @@ -243,14 +293,14 @@ describe("applyKeywordWithReassignment — data-change notification (#396)", () }); it("notifies once, after the COMMIT and once the DB lock is released", async () => { - mockSelect.mockResolvedValueOnce([]); + answerReads(); mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 }); await applyKeywordWithReassignment(input); expect(seen).toEqual([{ last: "COMMIT", inLock: false }]); }); it("does not notify after a ROLLBACK", async () => { - mockSelect.mockResolvedValueOnce([]); + answerReads(); mockExecute .mockResolvedValueOnce(undefined) // BEGIN .mockResolvedValueOnce({ lastInsertId: 77 }) // INSERT keywords @@ -266,3 +316,89 @@ describe("applyKeywordWithReassignment — data-change notification (#396)", () expect(seen).toEqual([]); }); }); + +describe("applyKeywordWithReassignment — a split's offset line follows its parent (#454)", () => { + // The reproduction of #454: −120 in category A, of which −50 are split to B + // (the entry, with the parent's description), and the offset line of +50, + // which cancels those −50 in A. The keyword moves the parent to category 9. + const PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null }; + const ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 }; + const OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 }; + const input = { keyword: "METRO", categoryId: 9, transactionIds: [PARENT.id], allowReplaceExisting: false }; + + /** The children of PARENT, as the offset propagation reads them. */ + const splitReads = () => answerReads({ rows: { [PARENT.id]: PARENT }, children: { [PARENT.id]: [ENTRY, OFFSET] } }); + + it("moves the offset line of a checked split parent with it, before the COMMIT", async () => { + splitReads(); + mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 }); + + const result = await applyKeywordWithReassignment(input); + + const sent = statements(); + const offsetMove = sent.findIndex( + (s) => s.sql.startsWith("UPDATE transactions SET category_id = $1, updated_at") && targetOf(s) === OFFSET.id, + ); + expect(sent[offsetMove]?.params).toEqual([9, OFFSET.id]); + // The entry keeps its own category. + expect(sent.filter((s) => targetOf(s) === ENTRY.id)).toEqual([]); + expect(sent[0].sql).toBe("BEGIN"); + expect(sent[sent.length - 1].sql).toBe("COMMIT"); + expect(sent.map((s) => s.sql)).not.toContain("ROLLBACK"); + // The count is the transactions the keyword recategorized; the offset line + // that follows its parent is not one of them. + expect(result.updatedTransactions).toBe(1); + }); + + // The preview no longer offers a child, but an id from elsewhere could still + // reach this path: its UPDATE only matches a row without a parent. + it("never recategorizes a child alone, and counts only the rows changed", async () => { + answerReads({ rows: { [OFFSET.id]: { ...OFFSET, is_split: 1, parent_transaction_id: PARENT.id } } }); + // What SQLite answers: the guarded UPDATE matches no row for a child. + mockExecute.mockImplementation(async (sql: string) => + /AND parent_transaction_id IS NULL/.test(String(sql)) ? { rowsAffected: 0 } : { lastInsertId: 77, rowsAffected: 1 }, + ); + + const result = await applyKeywordWithReassignment({ ...input, transactionIds: [OFFSET.id] }); + + const updates = statements().filter((s) => s.sql.startsWith("UPDATE transactions")); + expect(updates).toHaveLength(1); + expect(updates[0].sql).toMatch(/ WHERE id = \$2 AND parent_transaction_id IS NULL$/); + expect(updates[0].params).toEqual([9, OFFSET.id]); + expect(result.updatedTransactions).toBe(0); + }); + + it("rolls the keyword and the transactions back when the offset cannot be moved", async () => { + splitReads(); + mockExecute.mockImplementation(async (sql: string, params?: unknown[]) => { + if (String(sql).startsWith("UPDATE transactions SET category_id = $1, updated_at") && params?.[1] === OFFSET.id) { + throw new Error("disk full"); + } + return { lastInsertId: 77, rowsAffected: 1 }; + }); + + await expect(applyKeywordWithReassignment(input)).rejects.toThrow("disk full"); + + const sent = statements().map((s) => s.sql); + expect(sent[0]).toBe("BEGIN"); + expect(sent[sent.length - 1]).toBe("ROLLBACK"); + expect(sent).not.toContain("COMMIT"); + }); + + // Under the real lock, a getDb() call inside the callback waits for the + // transaction that waits for it: a deadlock (#408). + it("reads and writes the split through the transaction's handle, never through getDb()", async () => { + const outside = vi.fn(async () => { + throw new Error("getDb() inside the transaction deadlocks"); + }); + vi.mocked(getDb).mockResolvedValue({ select: outside, execute: outside } as never); + vi.mocked(withTransaction).mockImplementationOnce(async (fn) => fn(mockDb as never)); + splitReads(); + mockExecute.mockResolvedValue({ lastInsertId: 77, rowsAffected: 1 }); + + await applyKeywordWithReassignment(input); + + expect(outside).not.toHaveBeenCalled(); + expect(statements().filter((s) => targetOf(s) === OFFSET.id)).toHaveLength(1); + }); +}); diff --git a/src/services/categorizationService.ts b/src/services/categorizationService.ts index 5e42dde..7a457d1 100644 --- a/src/services/categorizationService.ts +++ b/src/services/categorizationService.ts @@ -1,5 +1,6 @@ import { getDb, withTransaction } from "./db"; import { notifyDataChanged } from "./dataEvents"; +import { propagateCategoryToOffsets } from "./splitOffsetService"; import type Database from "@tauri-apps/plugin-sql"; import type { Keyword, RecentTransaction } from "../shared/types"; @@ -145,6 +146,10 @@ export function validateKeyword(raw: string): { ok: true; value: string } | { ok * SECURITY: the keyword is never interpolated into the SQL string. `LIKE ?1` * is the only parameterised binding, and the `%...%` wrapping happens inside * the bound parameter value. + * + * The children of a split are never offered (#454): an entry or the offset + * line, which carries the parent's description, would be recategorised without + * its parent. The parent is offered, and its offset line follows it. */ export async function previewKeywordMatches( keyword: string, @@ -170,6 +175,7 @@ export async function previewKeywordMatches( FROM transactions t LEFT JOIN categories c ON t.category_id = c.id WHERE LOWER(t.description) LIKE $1 + AND t.parent_transaction_id IS NULL ORDER BY t.date DESC LIMIT 1000`, [likePattern], @@ -269,15 +275,20 @@ async function applyKeywordInTransaction( let updatedTransactions = 0; for (const txId of input.transactionIds) { - await db.execute( + // A child of a split is never recategorised alone (#454): only its parent + // is, and the parent's offset line follows it, on this same handle and + // before the COMMIT. `updatedTransactions` counts the rows changed. + const result = await db.execute( `UPDATE transactions SET category_id = $1, is_manually_categorized = 1, updated_at = CURRENT_TIMESTAMP - WHERE id = $2`, + WHERE id = $2 + AND parent_transaction_id IS NULL`, [input.categoryId, txId], ); - updatedTransactions++; + updatedTransactions += Number(result.rowsAffected ?? 0); + await propagateCategoryToOffsets(db, txId, input.categoryId); } await db.execute("COMMIT"); diff --git a/src/services/splitOffsetService.test.ts b/src/services/splitOffsetService.test.ts new file mode 100644 index 0000000..2f4384f --- /dev/null +++ b/src/services/splitOffsetService.test.ts @@ -0,0 +1,151 @@ +// propagateCategoryToOffsets — what follows a recategorized split parent (#454). +// +// The function runs inside its caller's transaction, on the handle the caller +// passes: the tests hand it a fake handle and read what it sends. getDb() +// rejects, so a call to it (a deadlock under the real lock, inside a +// withTransaction callback) fails the test, and a subscriber catches any +// data-change notification, which belongs to the caller, after its COMMIT. +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +vi.mock("./db", () => ({ + getDb: vi.fn(async () => { + throw new Error("getDb() inside a transaction deadlocks"); + }), + withTransaction: vi.fn(async () => { + throw new Error("the caller holds the transaction"); + }), +})); + +import { subscribeDataChanged } from "./dataEvents"; +import { propagateCategoryToOffsets } from "./splitOffsetService"; + +const select = vi.fn(); +const execute = vi.fn(); +const handle = { select, execute } as never; + +/** The statements sent, whitespace collapsed, with their parameters. */ +const sent = () => + execute.mock.calls.map(([sql, params]) => ({ sql: String(sql).replace(/\s+/g, " ").trim(), params })); + +/** The reads, whitespace collapsed, with their parameters. */ +const reads = () => + select.mock.calls.map(([sql, params]) => ({ sql: String(sql).replace(/\s+/g, " ").trim(), params })); + +/** Answers the read of the row by its id, then the read of its children. */ +function answer(row: Record | undefined, children: Array> = []) { + select.mockImplementation(async (sql: string) => + /WHERE parent_transaction_id = \$1/.test(String(sql)) ? children : row ? [row] : [], + ); +} + +// The reproduction of #454: −120 split as −50 to another category (the entry, +// with the parent's description) and the offset line of +50. +const PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null }; +const ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 }; +const OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 }; + +const notifications: number[] = []; +let stop: () => void = () => undefined; + +beforeEach(() => { + select.mockReset(); + execute.mockReset(); + execute.mockResolvedValue({ rowsAffected: 1 }); + notifications.length = 0; + stop = subscribeDataChanged(() => notifications.push(1)); +}); + +afterEach(() => { + stop(); +}); + +describe("propagateCategoryToOffsets — which rows it moves (#454)", () => { + it("moves the offset line of a split parent, and only it", async () => { + answer(PARENT, [ENTRY, OFFSET]); + await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).resolves.toBe(1); + expect(sent()).toEqual([ + { + sql: "UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2", + params: [9, OFFSET.id], + }, + ]); + }); + + it("reads the row by its id, then the children by their parent, whatever their category", async () => { + answer(PARENT, [ENTRY, OFFSET]); + await propagateCategoryToOffsets(handle, PARENT.id, 9); + expect(reads()).toEqual([ + { + sql: "SELECT id, description, amount, is_split, parent_transaction_id FROM transactions WHERE id = $1", + params: [PARENT.id], + }, + { + sql: "SELECT id, description, amount FROM transactions WHERE parent_transaction_id = $1 ORDER BY id", + params: [PARENT.id], + }, + ]); + }); + + it("moves the offset line of a split income, the negative child", async () => { + const income = { ...PARENT, amount: 2000 }; + const entry = { id: 6, description: "EPICERIE METRO", amount: 500 }; + const offset = { id: 7, description: "EPICERIE METRO", amount: -500 }; + answer(income, [entry, offset]); + await expect(propagateCategoryToOffsets(handle, income.id, 9)).resolves.toBe(1); + expect(sent().map((s) => s.params)).toEqual([[9, offset.id]]); + }); + + it("moves the offset line to no category when the parent loses its own", async () => { + answer(PARENT, [ENTRY, OFFSET]); + await propagateCategoryToOffsets(handle, PARENT.id, null); + expect(sent().map((s) => s.params)).toEqual([[null, OFFSET.id]]); + }); + + it("leaves a child of the opposite sign alone when it carries another description", async () => { + answer(PARENT, [ENTRY, { ...OFFSET, description: "REMBOURSEMENT" }]); + await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).resolves.toBe(0); + expect(sent()).toEqual([]); + }); + + it("writes nothing for an unknown id", async () => { + answer(undefined); + await expect(propagateCategoryToOffsets(handle, 42, 9)).resolves.toBe(0); + expect(reads()).toHaveLength(1); + expect(sent()).toEqual([]); + }); + + it("writes nothing, and reads no child, for a transaction that is not split", async () => { + answer({ ...PARENT, is_split: 0 }, [ENTRY, OFFSET]); + await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).resolves.toBe(0); + expect(reads()).toHaveLength(1); + expect(sent()).toEqual([]); + }); + + // Children carry is_split = 1 too: only the missing parent link makes a parent. + it("writes nothing for a child of a split, which carries is_split = 1 too", async () => { + answer({ ...OFFSET, is_split: 1, parent_transaction_id: PARENT.id }, [ENTRY, OFFSET]); + await expect(propagateCategoryToOffsets(handle, OFFSET.id, 9)).resolves.toBe(0); + expect(reads()).toHaveLength(1); + expect(sent()).toEqual([]); + }); +}); + +describe("propagateCategoryToOffsets — inside the caller's transaction (#454)", () => { + it("sends neither BEGIN, COMMIT nor ROLLBACK, and does not notify", async () => { + answer(PARENT, [ENTRY, OFFSET]); + await propagateCategoryToOffsets(handle, PARENT.id, 9); + expect(sent()).toHaveLength(1); + expect(sent().filter((s) => /^(BEGIN|COMMIT|ROLLBACK)\b/.test(s.sql))).toEqual([]); + expect(notifications).toEqual([]); + }); + + it("lets a failed move reach the caller, which rolls back", async () => { + answer(PARENT, [ENTRY, OFFSET]); + execute.mockRejectedValueOnce(new Error("disk full")); + await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).rejects.toThrow("disk full"); + expect(sent().map((s) => s.sql)).toEqual([ + "UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2", + ]); + expect(notifications).toEqual([]); + }); +}); diff --git a/src/services/splitOffsetService.ts b/src/services/splitOffsetService.ts new file mode 100644 index 0000000..5ddb69e --- /dev/null +++ b/src/services/splitOffsetService.ts @@ -0,0 +1,80 @@ +// splitOffsetService — a split's offset line follows its parent (#454). +// +// Shared by the two paths that recategorize a transaction: the category chosen +// in the Transactions list (`updateTransactionCategory`, transactionService.ts) +// and a keyword applied with reassignment (`applyKeywordWithReassignment`, +// categorizationService.ts). It has a module of its own because +// transactionService.ts already imports categorizationService.ts: exported +// from either one, it would make an import cycle. It imports neither. + +import type Database from "@tauri-apps/plugin-sql"; +import { isOffsetChild } from "../utils/splitOffset"; +import { toSqlFlag } from "../utils/sqlFlag"; + +interface ParentRow { + id: number; + description: string; + amount: number; + is_split: unknown; + parent_transaction_id: number | null; +} + +interface ChildRow { + id: number; + description: string; + amount: number; +} + +/** + * Moves the offset line of the split parent `parentId` to `categoryId`, the + * category the caller has just given the parent, and returns the number of + * rows moved (one for a split written by the split window). + * + * Runs on `db`, the handle of the caller's transaction, between the caller's + * BEGIN and COMMIT: it never issues BEGIN, COMMIT or ROLLBACK (it also runs + * inside the BEGIN of the keyword path), never calls `getDb()` (the DB lock is + * not reentrant: inside a `withTransaction` callback, a deadlock) and never + * notifies (the caller does, after its COMMIT). + * + * Writes nothing when `parentId` is not a split parent: an unknown id, a + * transaction that is not split, or a child of a split (children carry + * `is_split = 1` too, so a parent is the row without `parent_transaction_id`). + * An offset line follows whatever its current category, so one left in a + * former category by a change made before #454 is repaired at the parent's + * next change (decision D2 of #454). Its `is_manually_categorized` flag stays + * as it is: nothing reads it on a child. + */ +export async function propagateCategoryToOffsets( + db: Database, + parentId: number, + categoryId: number | null, +): Promise { + const [parent] = await db.select( + `SELECT id, description, amount, is_split, parent_transaction_id + FROM transactions + WHERE id = $1`, + [parentId], + ); + if (!parent || toSqlFlag(parent.is_split) === 0 || parent.parent_transaction_id != null) { + return 0; + } + + const children = await db.select( + `SELECT id, description, amount + FROM transactions + WHERE parent_transaction_id = $1 + ORDER BY id`, + [parentId], + ); + + let moved = 0; + for (const child of children) { + if (!isOffsetChild(parent, child)) continue; + await db.execute( + `UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2`, + [categoryId, child.id], + ); + moved++; + } + return moved; +} diff --git a/src/services/transactionService.test.ts b/src/services/transactionService.test.ts index fbc6a1b..763a9c8 100644 --- a/src/services/transactionService.test.ts +++ b/src/services/transactionService.test.ts @@ -8,7 +8,7 @@ vi.mock("./db", () => { }; }); -import { getDb } from "./db"; +import { getDb, withTransaction } from "./db"; import { subscribeDataChanged } from "./dataEvents"; import { getTransactionCount, @@ -58,45 +58,198 @@ describe("getTransactionCount (#351)", () => { }); }); +/** The statements sent through `execute`, whitespace collapsed, with their parameters. */ +const writes = () => + mockExecute.mock.calls.map(([sql, params]) => ({ + sql: String(sql).replace(/\s+/g, " ").trim(), + params: (params ?? []) as unknown[], + })); + +/** The last parameter of a statement: the id of its `WHERE id = $n`. */ +const targetOf = (write: { params: unknown[] }) => write.params[write.params.length - 1]; + +/** + * Answers the two reads of the offset propagation (#454): the row of the + * transaction being recategorized, by its id, and the children of a split, by + * `parent_transaction_id`. Any other read fails the test. + */ +function answerSplitReads(row: Record, children: Array>) { + mockSelect.mockImplementation(async (sql: string) => { + const flat = String(sql).replace(/\s+/g, " "); + if (/WHERE parent_transaction_id = \$1/.test(flat)) return children; + if (/WHERE id = \$1/.test(flat)) return [row]; + throw new Error(`unexpected read: ${flat}`); + }); +} + +// The reproduction of #454: a transaction of −120 in category A, of which −50 +// are split to category B. The split wrote two children: the entry (−50 in B, +// with the parent's description, as the split window writes an entry left +// without one) and the offset line (+50 in A, the parent's description), which +// cancels in A the part sent to B. +const SPLIT_PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null }; +const SPLIT_ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 }; +const SPLIT_OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 }; +/** The category the parent is moved to. */ +const C = 9; + +/** A transaction that is not split, as the offset propagation reads it. */ +const PLAIN = { id: 5, description: "LOYER", amount: -900, is_split: 0, parent_transaction_id: null }; + +/** The UPDATE of the recategorized transaction itself, found by its SQL: a BEGIN comes first since #454. */ +const ownUpdates = () => + writes().filter((w) => w.sql.startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2")); + describe("updateTransactionCategory (#390)", () => { // tauri-plugin-sql stores a bound JS boolean as the TEXT 'true', which the // getting-started checklist's `is_manually_categorized = 1` never matches. it("binds the manual flag as the integer 1, never as a boolean", async () => { - mockExecute.mockResolvedValueOnce({ rowsAffected: 1 }); + answerSplitReads(PLAIN, []); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); await updateTransactionCategory(5, 12, true); - expect(mockExecute).toHaveBeenCalledTimes(1); - const params = mockExecute.mock.calls[0][1] as unknown[]; - expect(params).toEqual([12, 1, 5]); - expect(typeof params[1]).toBe("number"); + const updates = ownUpdates(); + expect(updates).toHaveLength(1); + expect(updates[0].params).toEqual([12, 1, 5]); + expect(typeof updates[0].params[1]).toBe("number"); }); it("binds 0 when the category is not set by hand", async () => { - mockExecute.mockResolvedValueOnce({ rowsAffected: 1 }); + answerSplitReads(PLAIN, []); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); await updateTransactionCategory(5, null, false); - expect(mockExecute.mock.calls[0][1]).toEqual([null, 0, 5]); + expect(ownUpdates().map((w) => w.params)).toEqual([[null, 0, 5]]); }); }); describe("updateTransactionCategory — data-change notification (#396)", () => { - it("notifies once after the update", async () => { - mockExecute.mockResolvedValueOnce({ rowsAffected: 1 }); - await updateTransactionCategory(5, 12, true); - expect(notified).toEqual([1]); + /** At each notification: the last statement sent, and whether the DB lock was held. */ + const seen: Array<{ last: string; inLock: boolean }> = []; + let inLock = false; + let stop: () => void = () => undefined; + + beforeEach(() => { + seen.length = 0; + inLock = false; + vi.mocked(withTransaction).mockImplementation(async (fn) => { + inLock = true; + try { + return await fn((await getDb()) as never); + } finally { + inLock = false; + } + }); + stop = subscribeDataChanged(() => { + const sent = writes(); + seen.push({ last: sent[sent.length - 1]?.sql ?? "", inLock }); + }); }); - it("does not notify when the update fails", async () => { - mockExecute.mockRejectedValueOnce(new Error("database is locked")); + afterEach(() => { + stop(); + vi.mocked(withTransaction).mockImplementation(async (fn) => fn((await getDb()) as never)); + }); + + it("notifies once, after the COMMIT and once the DB lock is released", async () => { + answerSplitReads(PLAIN, []); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + await updateTransactionCategory(5, 12, true); + expect(seen).toEqual([{ last: "COMMIT", inLock: false }]); + }); + + it("does not notify when the update fails, and rolls it back", async () => { + answerSplitReads(PLAIN, []); + mockExecute + .mockResolvedValueOnce(undefined) // BEGIN + .mockRejectedValueOnce(new Error("database is locked")); // the transaction's own UPDATE await expect(updateTransactionCategory(5, 12, true)).rejects.toThrow("database is locked"); - expect(notified).toEqual([]); + expect(seen).toEqual([]); + expect(writes().map((w) => w.sql)).toEqual([ + "BEGIN", + "UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3", + "ROLLBACK", + ]); }); it("a note changes no counter: updateTransactionNotes stays silent", async () => { mockExecute.mockResolvedValueOnce({ rowsAffected: 1 }); await updateTransactionNotes(5, "loyer"); + expect(seen).toEqual([]); expect(notified).toEqual([]); }); }); +describe("updateTransactionCategory — a split's offset line follows its parent (#454)", () => { + it("moves the offset to the new category with the parent, between one BEGIN and its COMMIT", async () => { + answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + + await updateTransactionCategory(SPLIT_PARENT.id, C, true); + + const sent = writes(); + const parentMove = sent.findIndex( + (w) => w.sql.startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2") && targetOf(w) === SPLIT_PARENT.id, + ); + const offsetMove = sent.findIndex( + (w) => w.sql.startsWith("UPDATE transactions SET category_id = $1,") && targetOf(w) === SPLIT_OFFSET.id, + ); + // The offset follows the parent to C… + expect(sent[offsetMove]?.params).toEqual([C, SPLIT_OFFSET.id]); + // …the entry keeps its own category… + expect(sent.filter((w) => targetOf(w) === SPLIT_ENTRY.id)).toEqual([]); + // …and both moves sit between one BEGIN and its COMMIT. + expect(sent.map((w) => w.sql).filter((s) => ["BEGIN", "COMMIT", "ROLLBACK"].includes(s))).toEqual([ + "BEGIN", + "COMMIT", + ]); + expect(sent[0].sql).toBe("BEGIN"); + expect(sent[sent.length - 1].sql).toBe("COMMIT"); + expect(parentMove).toBeGreaterThan(0); + expect(offsetMove).toBeGreaterThan(0); + }); + + it("moves nothing else for a transaction that is not split", async () => { + answerSplitReads(PLAIN, []); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + await updateTransactionCategory(PLAIN.id, C, true); + expect(writes().map((w) => w.sql)).toEqual([ + "BEGIN", + "UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3", + "COMMIT", + ]); + }); + + it("rolls back, rethrows and does not notify when the offset cannot be moved", async () => { + answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]); + mockExecute.mockImplementation(async (sql: string, params?: unknown[]) => { + if (String(sql).startsWith("UPDATE transactions SET category_id = $1, updated_at") && params?.[1] === SPLIT_OFFSET.id) { + throw new Error("disk full"); + } + return { rowsAffected: 1 }; + }); + await expect(updateTransactionCategory(SPLIT_PARENT.id, C, true)).rejects.toThrow("disk full"); + const sent = writes().map((w) => w.sql); + expect(sent[0]).toBe("BEGIN"); + expect(sent[sent.length - 1]).toBe("ROLLBACK"); + expect(sent).not.toContain("COMMIT"); + expect(notified).toEqual([]); + }); + + // Under the real lock, a getDb() call inside the callback waits for the + // transaction that waits for it: a deadlock (#408). + it("sends every statement through the transaction's handle, none through getDb()", async () => { + const outside = vi.fn(async () => { + throw new Error("getDb() inside the transaction deadlocks"); + }); + vi.mocked(getDb).mockResolvedValue({ select: outside, execute: outside } as never); + vi.mocked(withTransaction).mockImplementationOnce(async (fn) => fn(mockDb as never)); + answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]); + mockExecute.mockResolvedValue({ rowsAffected: 1 }); + await updateTransactionCategory(SPLIT_PARENT.id, C, true); + expect(outside).not.toHaveBeenCalled(); + expect(writes().map((w) => w.sql)).toContain("COMMIT"); + }); +}); + describe("insertBatch — data-change notification (#396)", () => { const row = (i: number) => ({ date: "2026-09-0" + i, diff --git a/src/services/transactionService.ts b/src/services/transactionService.ts index 5d98036..64598c7 100644 --- a/src/services/transactionService.ts +++ b/src/services/transactionService.ts @@ -1,6 +1,8 @@ -import { getDb } from "./db"; +import type Database from "@tauri-apps/plugin-sql"; +import { getDb, withTransaction } from "./db"; import { notifyDataChanged } from "./dataEvents"; import { categorizeBatch } from "./categorizationService"; +import { propagateCategoryToOffsets } from "./splitOffsetService"; import { isLinkedTransactionFkError, type LinkedTransferTooltipRow, @@ -298,22 +300,49 @@ export async function getTransactionPage( }; } +/** + * Gives `txId` the category `categoryId`. When `txId` is a split parent, its + * offset line follows it, in the same transaction (#454): left in the former + * category, it would keep there an amount of the opposite sign that matches no + * transaction, and the new category would carry the whole amount. + */ export async function updateTransactionCategory( txId: number, categoryId: number | null, isManual: boolean ): Promise { - const db = await getDb(); - // Never bind the boolean itself: tauri-plugin-sql would store the TEXT - // 'true', which `is_manually_categorized = 1` never matches (#390). - await db.execute( - `UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3`, - [categoryId, toSqlFlag(isManual), txId] + await withTransaction((db) => + updateTransactionCategoryInTransaction(db, txId, categoryId, isManual) ); - // The manual flag is the "categorize by hand" step (ADR 0022). + // Reached only after the COMMIT (a ROLLBACK rethrows), once the DB lock is + // released. The manual flag is the "categorize by hand" step (ADR 0022). notifyDataChanged(); } +async function updateTransactionCategoryInTransaction( + db: Database, + txId: number, + categoryId: number | null, + isManual: boolean +): Promise { + // `withTransaction` only holds the DB lock: the BEGIN, the COMMIT and the + // ROLLBACK are this function's. + await db.execute("BEGIN"); + try { + // Never bind the boolean itself: tauri-plugin-sql would store the TEXT + // 'true', which `is_manually_categorized = 1` never matches (#390). + await db.execute( + `UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3`, + [categoryId, toSqlFlag(isManual), txId] + ); + await propagateCategoryToOffsets(db, txId, categoryId); + await db.execute("COMMIT"); + } catch (e) { + await db.execute("ROLLBACK"); + throw e; + } +} + export async function updateTransactionNotes( txId: number, notes: string diff --git a/src/utils/splitOffset.test.ts b/src/utils/splitOffset.test.ts new file mode 100644 index 0000000..b062f38 --- /dev/null +++ b/src/utils/splitOffset.test.ts @@ -0,0 +1,66 @@ +import { describe, it, expect } from "vitest"; +import { isOffsetChild } from "./splitOffset"; +import type { SplitChild } from "../shared/types"; + +// The reproduction of #454: −120 split as −50 to category B (the entry, with +// the parent's description, as the split window writes an entry left without +// one) and the offset line of +50, written in the parent's category A. +const A = 3; +const B = 4; +const C = 9; +const PARENT = { description: "EPICERIE METRO", amount: -120 }; + +/** A child as `getSplitChildren` returns it. */ +const child = (amount: number, categoryId: number | null, description = PARENT.description): SplitChild => ({ + id: 1, + category_id: categoryId, + category_name: null, + category_color: null, + amount, + description, +}); + +describe("isOffsetChild (#454)", () => { + it("recognizes the offset line: the parent's description and the opposite sign", () => { + expect(isOffsetChild(PARENT, child(50, A))).toBe(true); + }); + + // Decision D2: an offset line left in a former category still follows. + it("recognizes it whatever its category", () => { + for (const categoryId of [A, B, C, null]) { + expect(isOffsetChild(PARENT, child(50, categoryId)), `category ${categoryId}`).toBe(true); + } + }); + + it("refuses an entry, which has the parent's sign, even with the parent's description and category", () => { + expect(isOffsetChild(PARENT, child(-50, B))).toBe(false); + expect(isOffsetChild(PARENT, child(-50, A))).toBe(false); + }); + + it("refuses a child of the opposite sign that carries another description", () => { + expect(isOffsetChild(PARENT, child(50, A, "REMBOURSEMENT"))).toBe(false); + expect(isOffsetChild(PARENT, child(50, A, "epicerie metro"))).toBe(false); + }); + + it("refuses an amount of zero", () => { + expect(isOffsetChild(PARENT, child(0, A))).toBe(false); + expect(isOffsetChild(PARENT, child(-0, A))).toBe(false); + // Under a parent of zero, a child of zero passes the sign test + // (Math.sign(0) === -Math.sign(0), since 0 === -0): only the amount refuses it. + const zero = { description: PARENT.description, amount: 0 }; + expect(isOffsetChild(zero, child(0, A))).toBe(false); + expect(isOffsetChild(zero, child(-0, A))).toBe(false); + }); + + it("recognizes the offset line of a split income: a positive parent, a negative offset", () => { + const income = { description: "SALAIRE", amount: 2000 }; + expect(isOffsetChild(income, child(-500, A, "SALAIRE"))).toBe(true); + expect(isOffsetChild(income, child(500, B, "SALAIRE"))).toBe(false); + }); + + it("finds no offset line under a parent of zero", () => { + const zero = { description: "EPICERIE METRO", amount: 0 }; + expect(isOffsetChild(zero, child(50, A))).toBe(false); + expect(isOffsetChild(zero, child(-50, A))).toBe(false); + }); +}); diff --git a/src/utils/splitOffset.ts b/src/utils/splitOffset.ts new file mode 100644 index 0000000..4875c31 --- /dev/null +++ b/src/utils/splitOffset.ts @@ -0,0 +1,40 @@ +// splitOffset — which child of a split transaction is its offset line (#454). +// +// Unrelated to src/shared/splitGate.ts, which decides whether the split window +// opens in the current edition (#369): this module only recognizes rows. +// +// `saveSplitAdjustment` (transactionService.ts) writes a split as children of +// the parent transaction (`parent_transaction_id`): one row per entry, with +// the parent's sign (the split window gives every entry that sign, and the +// parent's description when it has none), plus one offset line of +// `-(sum of the entries)`, with the parent's description, that cancels in the +// parent's category the part sent to other categories. No column marks the +// offset line (decision D1 of #454: no role column, no migration), so this +// predicate is the one rule that recognizes it, shared by the split window, +// which leaves it out of the entries, and by `propagateCategoryToOffsets` +// (splitOffsetService.ts), which moves it with its parent. +// +// "amount = -(sum of the other children)" would not tell it apart: the +// children of a split always sum to zero, so every child satisfies it. The +// rule is ambiguous only for an entry that carries the parent's description +// with the opposite sign, which the split window never writes. +// +// The callers only pass the children of `parent` (`WHERE +// parent_transaction_id = $1`): the predicate reads neither the category nor +// the parent link, so an offset line left in a former category is still +// recognized (decision D2 of #454). + +/** The two fields the rule reads, on the parent and on its child. */ +export interface SplitLine { + description: string; + amount: number; +} + +/** True when `child`, a child of `parent`, is the offset line of its split. */ +export function isOffsetChild(parent: SplitLine, child: SplitLine): boolean { + return ( + child.amount !== 0 && + child.description === parent.description && + Math.sign(child.amount) === -Math.sign(parent.amount) + ); +}