fix: one sign convention for every report (#392) #536
52 changed files with 2809 additions and 819 deletions
|
|
@ -17,6 +17,8 @@
|
|||
- Rapports : les rapports s'ouvrent désormais sur « Cette année », du 1er janvier à aujourd'hui, avec son bouton allumé, au lieu de « Personnalisé » sur toute l'année civile, mois à venir compris ; le tableau de bord ne change pas. L'aide de la page Rapports dit désormais que Tendances montre vos revenus et dépenses mois par mois sur la période choisie, et sa carte Tendances affiche « Où vous allez, mois par mois », au lieu de « sur 12 mois » : Tendances suit le sélecteur de période. Sur les Comparables, dont le mois de référence suit la fin de la période, « Ce mois », « 3 mois », « 6 mois » et « 12 mois » finissent aujourd'hui comme « Cette année » : choisis juste après l'ouverture, ils ne déplacent plus le mois de référence vers le mois en cours ; la liste « Mois de référence » le fait toujours (#479).
|
||||
- Les liens vers la page produit ouverts depuis l'application portent une étiquette qui indique au site de quel bouton ils viennent, sans aucune donnée personnelle.
|
||||
- Export/import de données : les exports avec catégories (« Transactions avec catégories » et « Catégories uniquement »), et la sauvegarde prise avant une migration des catégories, portent désormais le budget, les modèles de budget et les ajustements. Une restauration met les lignes de budget et les ajustements du fichier à la place de ceux du profil ; un modèle de budget du fichier remplace celui du même nom, et un modèle créé depuis la sauvegarde garde ses lignes dont la catégorie revient. La confirmation les nomme désormais parmi ce qui est supprimé et compte ce que le fichier rapporte. Une sauvegarde écrite par une version antérieure ne contient pas de budget : les lignes actuelles dont la catégorie revient sont gardées, les autres supprimées, et les deux confirmations le disent. Un fichier écrit par une version plus récente de Simpl'Résultat, dont le numéro de format est invalide, ou dont des lignes de budget ne peuvent pas être réécrites, est refusé avec un message, sans rien modifier. La confirmation de « Réinitialiser » (page Catégories) dit désormais qu'elle efface le budget, les modèles de budget et les ajustements (#520).
|
||||
- Rapports et tableau de bord : revenus, dépenses et résultats se comptent désormais de la même façon sur tous les écrans, catégorie par catégorie, signes compris (#392). Un remboursement réduit la dépense de sa catégorie, une transaction répartie compte une fois, chaque part dans sa catégorie, les transferts restent à part avec leur signe (un transfert équilibré, comme le paiement d'une carte de crédit et sa réception, fait zéro ; un transfert dont l'autre moitié n'est pas importée garde son signe dans le résultat net), et les transactions sans catégorie forment une ligne « Non classé », comptée dans le résultat sans être ni un revenu ni une dépense. Les chiffres changent pour qui a des transferts, des remboursements, des répartitions ou des transactions sans catégorie. Sur le tableau de bord et dans Cartes, les revenus et les dépenses ne comptent plus les transferts, les remboursements et les lignes de répartition selon leur signe, les graphiques de dépenses ne montrent plus les transactions sans catégorie, et la carte de saisonnalité lit les mêmes dépenses. « Solde net » reste la somme de toutes les transactions du mois, avec une note sous la carte qui en donne la part non classée et celle des transferts quand elles ne sont pas nulles ; le taux d'épargne vaut désormais (revenus − dépenses) ÷ revenus, sans les transferts : un virement vers un CELI ne le fait plus baisser. Le tableau du flux global des Tendances gagne les colonnes « Non classé » et « Transferts », et sa colonne « Net » est ce solde net. Les top mouvements des Faits saillants ne listent plus que des catégories de dépense, sans les transferts ni les débits des catégories de revenu. Les Comparables, la Tendance par catégorie et Réel vs budget montrent la ligne « Non classé » entre les dépenses et le résultat avant transferts. Une catégorie dont les remboursements dépassent les achats a désormais une dépense négative : les graphiques la tracent sous zéro, barres et aires empilées comprises, et le donut de l'analyse par catégorie l'omet, avec une ligne qui dit combien de sous-catégories il ne trace pas.
|
||||
- Transactions : la barre de résumé affiche désormais « Entrées », « Sorties » et « Solde » : elle additionne les transactions de la liste par signe, sans les lignes de répartition, alors que les rapports comptent les revenus et les dépenses par catégorie (#392).
|
||||
|
||||
### Corrigé
|
||||
|
||||
|
|
@ -33,6 +35,11 @@
|
|||
- Export/import de données : restaurer une sauvegarde qui contient une répartition fonctionne. Dans le même profil, la restauration s'arrêtait sur une erreur sans rien modifier, dans les deux modes, comme « Rétablir la sauvegarde » après une migration des catégories ; dans un profil neuf, les lignes d'une répartition pouvaient se rattacher en silence à une autre transaction, et la fenêtre de répartition de la vraie restait vide. Chaque transaction revient désormais avec son propre numéro, celui que nomment les lignes de sa répartition. Pour la même raison, l'export CSV commence maintenant par une colonne `id`, et un CSV exporté par une version antérieure qui contient des répartitions est refusé avec un message, sans rien modifier : utilisez un export JSON. « Rétablir la sauvegarde » dit aussi pourquoi un fichier est refusé, au lieu d'un message générique (#518).
|
||||
- Export/import de données : restaurer une sauvegarde ne s'arrête plus sur une erreur, sans rien modifier, dans trois cas. Un profil dont une transaction est liée à un compte du Bilan (« Lier transferts ») ne pouvait plus du tout restaurer ses transactions, dans aucun des deux modes ni par « Rétablir la sauvegarde » : chaque transfert dont la transaction revient avec le même numéro, la même date, le même montant et la même description est désormais gardé tel quel, si bien que les rendements du Bilan ne changent pas, et les autres sont déliés ; la confirmation dit combien le seront avant que rien ne soit remplacé, et le message de réussite combien l'ont été. Une transaction dont la catégorie n'existe plus dans le profil (en « Transactions uniquement » après « Réinitialiser », par exemple) revient désormais sans catégorie, prête pour « Auto-catégoriser », et les journaux en donnent le nombre. Une catégorie rangée sous une catégorie plus récente, ou deux catégories rangées l'une sous l'autre, ne bloquent plus une restauration avec catégories, et reviennent à leur place. Un fichier dont des catégories, mots-clés ou fournisseurs renvoient à une catégorie absente du fichier est refusé avec un message, sans rien modifier. « Rétablir la sauvegarde » lit maintenant le fichier (après le NIP s'il est chiffré) avant une seconde confirmation, puis affiche « Sauvegarde rétablie » et recharge l'application au clic sur « Fermer » (#521).
|
||||
- Export/import de données : restaurer une sauvegarde avec ses catégories (« Transactions avec catégories », « Catégories uniquement », et « Rétablir la sauvegarde » après une migration des catégories) ne laisse plus vides, sans un mot, le budget, les modèles de budget et les ajustements : leurs lignes partaient avec les catégories que la restauration remplaçait, et la sauvegarde n'en contenait aucune. Avec une sauvegarde écrite par cette version, elles reviennent désormais telles quelles, dans le même profil comme dans un profil neuf, et « Rétablir la sauvegarde » d'une migration faite avec cette version rend exactement le budget des anciennes catégories. Les catégories standard restaurées ainsi retrouvent leur nom anglais dans l'interface anglaise (#520).
|
||||
- Comparables : une transaction répartie ne compte plus deux fois dans les dépenses (son montant entier dans sa catégorie, plus chaque part dans l'autre), et un remboursement ou un crédit sans catégorie n'est plus écarté du résultat (#392).
|
||||
- Cartes et tableau de bord : un remboursement ne compte plus comme un dépassement dans « Respect du budget » : une catégorie dont les remboursements dépassent les achats reste dans la cible (#392).
|
||||
- Analyse par catégorie : le total, la répartition par sous-catégorie et l'évolution mensuelle d'une catégorie déduisent désormais ses remboursements et ses répartitions, au lieu d'additionner leurs valeurs absolues (#392).
|
||||
- Tendance par catégorie : un remboursement ou un crédit sans catégorie ne compte plus comme une dépense, et un transfert dont l'autre moitié n'est pas importée garde son signe dans le résultat net au lieu de s'y ajouter (#392).
|
||||
- Cartes, tableau de bord et Comparables : quand la période précédente est négative (« Solde net », taux d'épargne, transferts), l'écart en pourcentage prend désormais le signe de l'écart : de −500 $ à +200 $, il affiche +140 % au lieu de −140 % (#392).
|
||||
|
||||
### Sécurité
|
||||
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@
|
|||
- Reports: the reports now open on “This year”, from January 1st to today, with its button lit, instead of “Custom” over the whole calendar year, months to come included; the Dashboard does not change. The help of the Reports page now says that Trends shows your income and expenses month by month over the selected period, and its Trends card reads “Where you're heading, month by month”, instead of “over 12 months”: Trends follows the period selector. On Compare, whose reference month follows the end of the period, “This month”, “3 months”, “6 months” and “12 months” end today like “This year”: chosen right after opening, they no longer move the reference month to the current month; the “Reference month” list still does (#479).
|
||||
- Product page links opened from the app carry a label that tells the site which button they come from, with no personal data.
|
||||
- Data export/import: exports with categories (“Transactions with categories” and “Categories only”), and the backup taken before a category migration, now carry the budget, the budget templates and the adjustments. A restore puts the budget lines and the adjustments of the file in place of those of the profile; a budget template of the file replaces the one of the same name, and a template created since the backup keeps its lines whose category comes back. The confirmation now names them among what is deleted and counts what the file brings back. A backup written by an earlier version holds no budget: the current lines whose category comes back are kept, the others deleted, and both confirmations say so. A file written by a newer version of Simpl'Résultat, whose format number is invalid, or whose budget lines cannot be written back, is refused with a message, nothing modified. The confirmation of “Re-initialize” (Categories page) now says that it erases the budget, the budget templates and the adjustments (#520).
|
||||
- Reports and Dashboard: income, expenses and results are now counted the same way on every screen, category by category with signs included (#392). A refund lowers the expense of its category, a split transaction counts once, each part in its category, transfers stay apart with their sign (a balanced transfer, such as a credit card payment and its receipt, nets to zero; a transfer whose other half is not imported keeps its sign in the net result), and transactions without a category form an “Uncategorized” line, counted in the result but neither income nor expense. The figures change for anyone with transfers, refunds, splits or uncategorized transactions. On the Dashboard and Cards, income and expenses no longer count transfers, refunds and split lines by their sign, the expense charts no longer show uncategorized transactions, and the seasonality card reads the same expenses. “Net balance” stays the sum of every transaction of the month, with a note under the card giving its uncategorized and transfer parts when they are not zero; the savings rate is now (income − expenses) ÷ income, without transfers: a transfer to a TFSA no longer lowers it. Trends' global flow table gains “Uncategorized” and “Transfers” columns, and its “Net” column is that net balance. Highlights' top movers now list expense categories only, without transfers or debits of income categories. Compare, Trends by category and Actual vs budget show the “Uncategorized” line between the expenses and the result before transfers. A category whose refunds exceed its purchases now shows a negative expense: charts draw it below zero, stacked bars and areas included, and the Category Analysis donut leaves it out with a line that says how many subcategories it does not draw.
|
||||
- Transactions: the summary bar now reads “Money in”, “Money out” and “Balance”: it adds up the listed transactions by sign, without the split lines, while the reports count income and expenses by category (#392).
|
||||
|
||||
### Fixed
|
||||
|
||||
|
|
@ -33,6 +35,11 @@
|
|||
- Data export/import: restoring a backup that holds a split now works. In the same profile, the restore stopped on an error and changed nothing, in both modes, as did “Restore the backup” after a category migration; in a new profile, the lines of a split could hang, without a word, off another transaction, and the split window of the real one stayed empty. Each transaction now comes back with its own number, the one the lines of its split name. For the same reason, the CSV export now starts with an `id` column, and a CSV exported by an earlier version that holds splits is refused with a message, nothing modified: use a JSON export. “Restore the backup” also says why a file is refused, instead of a generic message (#518).
|
||||
- Data export/import: restoring a backup no longer stops on an error, changing nothing, in three cases. A profile with a transaction linked to a Balance sheet account (“Link transfers”) could not restore its transactions at all, in either mode or with “Restore the backup”: each transfer whose transaction comes back with the same number, date, amount and description is now kept as it was, so the returns of the Balance sheet do not change, and the others are unlinked; the confirmation says how many will be before anything is replaced, and the success message how many were. A transaction whose category no longer exists in the profile (with “Transactions only” after “Re-initialize”, for instance) now comes back without a category, ready for “Auto-categorize”, and the logs give their number. A category placed under a newer one, or two categories each placed under the other, no longer blocks a restore with categories, and comes back in its place. A file whose categories, keywords or suppliers refer to a category missing from it is refused with a message, nothing modified. “Restore the backup” now reads the file (after the PIN when it is encrypted) before a second confirmation, then shows “Backup restored” and reloads the app when you click “Close” (#521).
|
||||
- Data export/import: restoring a backup with its categories (“Transactions with categories”, “Categories only”, and “Restore the backup” after a category migration) no longer leaves the budget, the budget templates and the adjustments empty, without a word: their lines went with the categories the restore replaced, and the backup held none. With a backup written by this version, they now come back as they were, in the same profile as in a new one, and “Restore the backup” of a migration made with this version gives back the budget of the former categories exactly. The standard categories restored this way show their English names again in the English interface (#520).
|
||||
- Compare: a split transaction is no longer counted twice in the expenses (its whole amount in its category plus each part in the other one), and a refund or a credit without a category is no longer dropped from the result (#392).
|
||||
- Cards and Dashboard: a refund no longer shows as an overrun in “Budget adherence”: a category whose refunds exceed its purchases stays on target (#392).
|
||||
- Category Analysis: the total, the breakdown by subcategory and the monthly evolution of a category now net its refunds and splits, instead of adding their absolute values (#392).
|
||||
- Trends by category: a refund or a credit without a category no longer counts as an expense, and a transfer whose other half is not imported keeps its sign in the net result instead of adding to it (#392).
|
||||
- Cards, Dashboard and Compare: when the previous period is negative (“Net balance”, savings rate, transfers), the percentage change now takes the sign of the change: from −$500 to +$200, it reads +140% instead of −140% (#392).
|
||||
|
||||
### Security
|
||||
|
||||
|
|
|
|||
|
|
@ -194,5 +194,5 @@ Les trois premiers viennent du skill global `pr-review`, corrigés pour ce dép
|
|||
- **Booléen lié en texte.** tauri-plugin-sql stocke un booléen JS en texte `'true'`, qu'une condition `= 1` ne trouve pas : défaut resté invisible de la v0.1.0 à #390. — [ADR 0021](docs/adr/0021-migrations-profils-secondaires.md)
|
||||
- **Transaction hors verrou.** Un `BEGIN` et son `COMMIT` envoyés par deux `db.execute` peuvent partir sur deux connexions du pool et laisser un verrou zombie (« database is locked », v0.10.0) : toujours `withTransaction` et son handle. — `docs/architecture.md` « Accès DB et transactions »
|
||||
- **Dépôt public.** Aucune coordonnée d'un tiers (courriel, adresse, téléphone), aucune clé de licence ni aucun jeton dans un fichier commité, `STATE.md`, `docs/` et `.claude/skills/` compris ; un testeur se désigne par son identifiant Logto. — `.claude/skills/issue-license/SKILL.md`
|
||||
- **Tests vitest qui lisent `src-tauri/`.** Des tests du front lisent des fichiers de `src-tauri/` : `src/hooks/useImportWizard.test.ts` lit les codes `SAMPLE_ERROR_*` de `fs_commands.rs` (contrat avec leur traduction), `src/services/categoryService.test.ts`, `src/__integration__/onboarding-samples.test.ts`, `src/__integration__/split-offset-manual-flag.test.ts` et `src/__integration__/restore.test.ts` lisent `consolidated_schema.sql` (les deux derniers l'exécutent en entier, seed compris), `src/utils/changelog.test.ts` la version de `tauri.conf.json`. Une PR qui ne touche que `src-tauri/**` saute `check-frontend` : la dérive ne rougit que la PR suivante qui touche `src/`, sans rapport avec elle. La revue d'une telle PR lance ces tests (`npx vitest run <fichier>`). — `check-frontend.yml` (`paths-ignore`), #384
|
||||
- **Tests vitest qui lisent `src-tauri/`.** Des tests du front lisent des fichiers de `src-tauri/` : `src/hooks/useImportWizard.test.ts` lit les codes `SAMPLE_ERROR_*` de `fs_commands.rs` (contrat avec leur traduction), `src/services/categoryService.test.ts`, `src/__integration__/onboarding-samples.test.ts` et le harnais `src/test/sqliteHarness.ts` lisent `consolidated_schema.sql` (le harnais l'exécute en entier, seed compris, pour `src/test/sqliteHarness.test.ts`, `src/__integration__/report-totals.test.ts`, `src/__integration__/split-offset-manual-flag.test.ts` et `src/__integration__/restore.test.ts` ; #392), `src/utils/changelog.test.ts` la version de `tauri.conf.json`. Une PR qui ne touche que `src-tauri/**` saute `check-frontend` : la dérive ne rougit que la PR suivante qui touche `src/`, sans rapport avec elle. La revue d'une telle PR lance ces tests (`npx vitest run <fichier>`). — `check-frontend.yml` (`paths-ignore`), #384
|
||||
- **Garde du README.** `check-frontend.yml` ignore `*.md` à la racine : une PR qui ne touche que `README.md` ne lance donc pas `src/__integration__/readme-guard.test.ts`, et un README qui ne la passe plus ne rougit que la PR suivante qui lance `check-frontend`, sans rapport avec lui. La revue d'une telle PR lance `npx vitest run src/__integration__/readme-guard.test.ts`. — `check-frontend.yml` (`paths-ignore`), #523
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ Le binaire release ignore toute variable d'environnement : les dossiers de test
|
|||
|
||||
### 5. Lecture et écritures ciblées
|
||||
|
||||
Lecture : profils, résumé mensuel (par type de catégorie, comme les rapports : revenus et transferts en somme signée, dépenses en valeur absolue, résultat avant et après transferts), répartition hiérarchique par catégorie, transactions filtrées et paginées, non-catégorisées, budget vs réel, catégories, règles de mots-clés. Écriture : `set_transaction_category` (feuille active et saisissable seulement, `is_manually_categorized = 1`, drapeaux en 1/0) et `create_keyword_rule` (mêmes règles que l'app : 2 à 64 caractères, priorité 100, réactivation d'une règle existante vers la même catégorie, refus vers une autre ; application aux transactions existantes par `LIKE ? ESCAPE` puis frontière de mot, en dry-run tant que `apply_to_existing` est faux). Rien d'autre : ni suppression, ni import, ni budget, ni catégorie nouvelle.
|
||||
Lecture : profils, résumé mensuel (par type de catégorie, comme les rapports : la convention de signe de l'[ADR 0026](0026-convention-signe-rapports.md), solde signé de chaque catégorie, dépenses = opposé du solde des catégories de dépense, ligne non classée, résultat avant et après transferts ; #392), répartition hiérarchique par catégorie, transactions filtrées et paginées, non-catégorisées, budget vs réel, catégories, règles de mots-clés. Écriture : `set_transaction_category` (feuille active et saisissable seulement, `is_manually_categorized = 1`, drapeaux en 1/0) et `create_keyword_rule` (mêmes règles que l'app : 2 à 64 caractères, priorité 100, réactivation d'une règle existante vers la même catégorie, refus vers une autre ; application aux transactions existantes par `LIKE ? ESCAPE` puis frontière de mot, en dry-run tant que `apply_to_existing` est faux). Rien d'autre : ni suppression, ni import, ni budget, ni catégorie nouvelle.
|
||||
|
||||
Les libellés, notes et noms de catégorie sont des données importées, jamais des consignes, et les `instructions` du serveur le disent : un libellé piégé ne peut provoquer qu'une catégorisation, réversible dans l'app.
|
||||
|
||||
|
|
|
|||
90
docs/adr/0026-convention-signe-rapports.md
Normal file
90
docs/adr/0026-convention-signe-rapports.md
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
# ADR 0026 — Convention de signe des rapports
|
||||
|
||||
- Status: **Accepted**
|
||||
- Date: 2026-11-07
|
||||
- Issue: #392 (décisions D1 à D4 de Max du 2026-10-06, D5 à D8 du 2026-11-07 ; registre `DECISIONS.md`, § Rapports)
|
||||
- S'appuie sur #243 (transferts nets), #253 (état de résultat des Comparables), #454 et #513 (ligne de compensation d'une répartition) ; prolonge l'[ADR 0024](0024-serveur-mcp.md), dont le résumé mensuel suit cette convention
|
||||
|
||||
## Contexte
|
||||
|
||||
Les revenus, les dépenses et le résultat d'un même mois changeaient de valeur selon l'écran. Six règles d'agrégation coexistaient dans la v0.17.2, aucune ne traitait de la même façon les transferts, les remboursements, les répartitions et les transactions sans catégorie :
|
||||
|
||||
| Règle | Où | Formule |
|
||||
|---|---|---|
|
||||
| A | KPI, sparklines et saisonnalité du tableau de bord et de Cartes, Flux global des Tendances | revenus = somme des montants positifs, dépenses = somme des négatifs, sans catégorie |
|
||||
| B | Comparables réel vs réel, mouvements de Cartes | dépense = `ABS(amount)` ligne à ligne, débits seuls |
|
||||
| C | Tendance par catégorie, graphiques de dépenses du tableau de bord | `ABS(SUM(amount))` par catégorie, transferts en magnitude |
|
||||
| D | Réel vs budget | `SUM(amount)` signé par catégorie, la seule juste ; l'adhésion de Cartes la repassait en `Math.abs` |
|
||||
| E | Analyse par catégorie | `SUM(ABS(amount))` ligne à ligne |
|
||||
| F | Faits saillants | net signé, mouvements par débits sans type |
|
||||
|
||||
Une répartition garde le montant du parent dans sa catégorie, met chaque part dans la sienne et ajoute une ligne de compensation, de signe opposé, dans la catégorie du parent (`saveSplitAdjustment`). Aucune requête de rapport ne filtre `parent_transaction_id` : la compensation rend la somme de chaque catégorie juste, et toute règle qui écarte les montants positifs ou additionne des valeurs absolues la casse. Sur le jeu de reproduction de #392 (paie +1000 ; épicerie −100 dont −30 répartis en pharmacie ; remboursement +20 ; paiement de carte −500 / +500), la dépense réelle est de 80 : la règle A en lisait 630, la règle B 130 (la répartition comptée deux fois), la règle E 150 pour la seule épicerie.
|
||||
|
||||
## Décision
|
||||
|
||||
### 1. Le solde signé par catégorie, partout (D1)
|
||||
|
||||
Pour une catégorie, `solde = SUM(amount)` sur la période, parent, parts et compensation d'une répartition compris, remboursements compris.
|
||||
|
||||
- **Revenus** : la somme des soldes des catégories `income`.
|
||||
- **Dépenses** : l'opposé de la somme des soldes des catégories `expense`. Un remboursement réduit la dépense de sa catégorie ; une catégorie dont les remboursements dépassent les achats a une dépense négative.
|
||||
- **Transferts** : la somme signée des soldes des catégories `transfer`. Un transfert équilibré fait 0, un transfert à une jambe garde son signe.
|
||||
- **Non classé** (D4) : la somme signée des transactions sans catégorie existante (aucune, ou une catégorie disparue : `c.id IS NULL`), ni revenu ni dépense.
|
||||
|
||||
Aucune agrégation de montants n'utilise `ABS` ni un filtre de signe ; `ABS` ne sert qu'au tri (classement du top N, ordre des écarts) et à l'affichage.
|
||||
|
||||
### 2. Les résultats
|
||||
|
||||
- **Résultat avant transferts** = revenus − dépenses + non classé.
|
||||
- **Résultat net** = résultat avant transferts + transferts = la somme de tous les montants de la période. C'est un invariant, vérifié rapport par rapport par `src/__integration__/report-totals.test.ts`.
|
||||
|
||||
Les trois tableaux (Comparables, Tendance par catégorie, Réel vs budget) suivent cet ordre : revenus, dépenses, la ligne « Non classé » (une seule ligne, sans en-tête), le résultat avant transferts quand il y a des transferts, les transferts, le résultat net. Réel vs budget garde son affichage signé (une dépense y est négative), les deux autres montrent la dépense.
|
||||
|
||||
### 3. Solde net et taux d'épargne (D5, D6)
|
||||
|
||||
« Solde net », sur les cartes KPI du tableau de bord et de Cartes, dans la colonne « Net » du Flux global et sur la courbe de `IncomeExpenseOverlayChart`, est le résultat net : il reste égal aux soldes des Faits saillants et à la ligne « Résultat net » des Comparables. Une note sous la carte donne la part non classée et celle des transferts quand elles ne sont pas nulles ; le tableau du Flux global les montre en deux colonnes.
|
||||
|
||||
Le taux d'épargne vaut (revenus − dépenses) ÷ revenus, sans transferts ni non classé : un virement vers un CELI ne le fait plus baisser, et il se recalcule à partir des deux cartes voisines. Il vaut `null` (« — ») quand les revenus ne sont pas positifs.
|
||||
|
||||
### 4. Où vit la règle
|
||||
|
||||
- **SQL** : `SECTION_SQL` (`CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END`) sur `CATEGORY_JOIN_SQL` (`LEFT JOIN categories c ON c.id = t.category_id`), dans `src/utils/incomeStatement.ts`. Chaque requête rend des soldes signés avec leur section et regroupe sur `c.id`, si bien que les lignes sans catégorie existante forment un seul groupe.
|
||||
- **JS** : le même module, pur. `orient(section, solde)` donne ce qu'une ligne montre (une dépense : l'opposé de son solde), `incomeStatement` et `statementOf` les cinq chiffres d'une période, `addStatements` leur somme (cumul annuel), `savingsRate` le taux d'épargne. `toCents` arrondit au cent et retire le zéro négatif : un remboursement qui annule deux achats laisse un reste flottant (10,10 + 20,20 − 30,30 = −3,6e-15) qu'un format monétaire affiche « -0 $ ».
|
||||
- `getMonthlyTrends` est la seule requête mensuelle : Tendances, Cartes et le tableau de bord la lisent.
|
||||
|
||||
### 5. Les graphiques (D7)
|
||||
|
||||
Un montant négatif reste signé : barres et courbes passent sous zéro, les barres et aires empilées (`CategoryOverTimeChart`) posent le segment négatif sous zéro (`stackOffset="sign"`). Seul le donut de l'analyse par catégorie, qui ne peut pas tracer une part négative, l'omet, avec une ligne qui dit combien de sous-catégories il laisse de côté. Les tableaux restent signés.
|
||||
|
||||
### 6. La barre de la page Transactions (D8)
|
||||
|
||||
Elle décrit la liste filtrée, sans les lignes de répartition : sommes par signe, sous « Entrées / Sorties / Solde ». Elle n'est pas un état de résultat ; les rapports comptent par catégorie.
|
||||
|
||||
## Conséquences
|
||||
|
||||
### Positives
|
||||
|
||||
- Un même mois lit les mêmes revenus, dépenses et résultat sur tous les écrans.
|
||||
- Une répartition compte une fois, un remboursement n'apparaît plus comme un dépassement de budget, un transfert ne gonfle plus revenus et dépenses.
|
||||
- La règle vit en un fragment SQL et un module pur ; les rapports sont prouvés sur une vraie base SQLite (`src/test/sqliteHarness.ts`), et une passe de mutations remet une à une les six anciennes règles, chacune rougit.
|
||||
|
||||
### Négatives et points de vigilance
|
||||
|
||||
- Les chiffres changent pour tout utilisateur qui a des transferts, des remboursements, des répartitions ou des transactions sans catégorie (CHANGELOG, Changed).
|
||||
- Une dépense peut être négative : un écran qui ajoute un graphique en parts doit l'omettre et le dire, comme le donut.
|
||||
- Une catégorie désactivée qui porte encore des transactions reste hors de Réel vs budget, qui ne lit que les catégories actives. La suppression d'une catégorie est refusée tant qu'elle porte des transactions, et la migration des catégories ne désactive les anciennes qu'après avoir déplacé leurs transactions : le cas ne se produit pas par l'app.
|
||||
- L'app embarque SQLite 3.46.0 (`libsqlite3-sys` 0.30.1), les tests tournent sur une version plus récente (Node 22) : une requête des rapports n'utilise rien de postérieur à 3.46.
|
||||
|
||||
## Alternatives écartées
|
||||
|
||||
- **Garder une règle par écran, en documentant chacune** : c'était l'état de la v0.17.2 ; les écarts entre écrans restaient, et la règle B comptait les répartitions deux fois.
|
||||
- **Des magnitudes partout (`ABS`)** : une catégorie de dépense créditrice deviendrait une dépense positive, un remboursement une dépense de plus, et un transfert à une jambe perdrait son signe.
|
||||
- **Écarter les lignes de répartition des sommes** (filtre sur `parent_transaction_id`) : il faudrait alors retirer le parent ou les parts selon le rapport ; la compensation donne déjà des sommes justes par catégorie sans filtre.
|
||||
- **Orienter les dépenses dans le SQL** (`CASE … THEN -t.amount`) : chaque requête porterait sa copie de la règle, et l'arrondi au cent se fait de toute façon en JS.
|
||||
- **Compter le non classé comme une dépense** (`COALESCE(c.type, 'expense')`, l'ancien défaut) : un crédit sans catégorie devenait une dépense de plus dans la Tendance par catégorie (D4).
|
||||
|
||||
## Références
|
||||
|
||||
- #392 et son commentaire 32351 (ancien corps, écarts depuis le 2026-10-06) ; registre `DECISIONS.md`, § Rapports
|
||||
- `src/utils/incomeStatement.ts`, `src/services/reportService.ts`, `src/services/dashboardService.ts`, `src/services/budgetService.ts`
|
||||
- `src/test/sqliteHarness.ts`, `src/__integration__/report-totals.test.ts`
|
||||
|
|
@ -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/ # 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)
|
||||
│ ├── 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)
|
||||
│ ├── 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
|
||||
|
|
@ -210,8 +210,8 @@ Le dossier des bases est celui du plugin : `app_config_dir()`, résolu par `prof
|
|||
| `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 |
|
||||
| `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`) |
|
||||
| `reportService.ts` | Génération de rapports : `getMonthlyTrends`, `getCategoryOverTime`, `getHighlights`, `getCompareMonthOverMonth`, `getCompareYearOverYear`, `getCategoryZoom` (CTE récursive bornée anti-cycle), `getCartesSnapshot` (snapshot dashboard Cartes, requêtes parallèles) |
|
||||
| `dashboardService.ts` | Agrégation données tableau de bord : `getExpensesByCategory` (barres classées, dépense de chaque catégorie de dépense, `accountIds`), `deriveNetWorthTile` (pur — tuile valeur nette du Bilan, réutilise `deriveLandingState`). `getDashboardSummary`, sans appelant depuis #279, est retiré par #392 |
|
||||
| `reportService.ts` | Génération de rapports : `getMonthlyTrends` (état de résultat par mois, aussi lu par Cartes et le tableau de bord), `getCategoryOverTime`, `getHighlights`, `getCompareMonthOverMonth`, `getCompareYearOverYear`, `getCategoryZoom` (CTE récursive bornée anti-cycle), `getCartesSnapshot` (snapshot dashboard Cartes, requêtes parallèles). Toutes les sommes de montants suivent la convention de signe de l'[ADR 0026](adr/0026-convention-signe-rapports.md) (#392) : le SQL rend le solde signé de chaque catégorie avec sa section (`SECTION_SQL` sur `CATEGORY_JOIN_SQL`), `src/utils/incomeStatement.ts` (pur) en tire ce que les écrans montrent (`orient`, `incomeStatement`, `savingsRate`, `toCents`) ; `ABS` ne sert qu'au tri |
|
||||
| `dataExportService.ts` | Export de données (chiffré), lecture du fichier et validations de la frontière d'import. L'enveloppe SREF porte un `format_version` explicite (`SREF_FORMAT_VERSION = 3`), **inclut `import_sources` + `import_config_templates`** depuis #331 et, dans les deux modes qui portent les catégories, **`budget_entries`, `budget_templates` et `adjustments`** depuis #520 ; `collectExportData(mode)` rassemble les tableaux de chaque mode, pour « Exporter » comme pour la sauvegarde d'avant migration ; l'export CSV commence par une colonne `id` (#518). `parseImportedJson` et `parseImportedCsv` refusent, avant que la fenêtre de confirmation ne s'ouvre, une configuration illisible (`validateImportedFormatRows`) et des lignes de répartition qui ne retrouvent pas leur parent (`validateImportedTransactionIds`, #518), et `parseImportedJson` un format plus récent que celui de l'application ou un numéro de format invalide (`validateImportedFormatVersion`, clés `newerFormat` et `invalidFormatVersion`, #520), des catégories, mots-clés ou fournisseurs qui renvoient à une catégorie absente du fichier (`validateImportedCategoryReferences`, clé `danglingCategoryReference`, #521) et, au format 3, un budget que la restauration ne pourrait pas réécrire (`validateImportedBudget`, clé `invalidBudgetRows`, #520), par une `SrefValidationError` qui porte sa clé i18n. La restauration vit dans `dataRestoreService.ts` ([ADR 0025](adr/0025-contenu-restauration-sauvegarde-sref.md)) |
|
||||
| `dataRestoreService.ts` | Restauration d'une sauvegarde SREF/JSON ou d'un export CSV, sortie de `dataExportService.ts` par #518 : les trois modes passent par `runRestore`, qui efface puis réinsère dans une seule transaction (`withTransaction`, son `BEGIN`, son `COMMIT`, `ROLLBACK` puis relance sur un échec) et ne notifie qu'après le `COMMIT` ([ADR 0022](adr/0022-canal-evenements-donnees.md)) ; modèles restaurés avant les sources avec remap de `template_id` ; transactions réinsérées avec leur `id` exporté, les lignes sans parent avant les lignes de répartition (#518). Les deux restaurations de transactions lisent puis retirent les transferts du Bilan avant `DELETE FROM transactions`, et réinsèrent tels quels ceux dont la transaction revient avec le même identifiant, la même date, le même montant et la même description ([ADR 0010](adr/0010-fk-restrict-balance-transfers.md), amendement #521) ; une transaction dont la catégorie manque au profil revient sans catégorie, drapeau manuel à 0, et une ligne `logWarn` en donne le nombre ; `restoreCategories` insère les catégories sans parent, puis pose les `parent_id` dans un second passage (#521), et écrit leur `i18n_key` (#520). Les deux restaurations qui portent les catégories reçoivent le format du fichier (`formatVersion`), lisent puis retirent les lignes de budget, de modèle et d'ajustement avant `DELETE FROM categories` (`takeBudget`), et les remettent une fois les catégories en place (`restoreBudget`) : au format 3, le budget du fichier (lignes de budget et ajustements remplacés, modèles insérés ou mis à jour par leur nom, un modèle absent du fichier gardant ses lignes dont la catégorie revient) ; en dessous, les lignes du profil dont la catégorie revient ([ADR 0025](adr/0025-contenu-restauration-sauvegarde-sref.md), #520). Les trois restaurations rendent un `RestoreOutcome` (`unlinkedTransfers`, `uncategorizedTransactions` ; zéros pour « Catégories uniquement ») ; `previewUnlinkedTransfers` compte, hors transaction et par la même règle, les transferts qu'une restauration délierait. `importTransactionsOnly` et `importTransactionsWithCategories` rejouent en tête les validations du parse, `importTransactionsWithCategories` et `importCategoriesOnly` celles du format, des références de catégorie et du budget, avant toute suppression. Appelé par `useDataImport` et, pour « Rétablir la sauvegarde », par `readBackup` (lecture, déchiffrement, analyse et compte des transferts, sans écriture) puis `applyBackup` (restauration et préférences, `RestoreResult` avec le `RestoreOutcome`) de `categoryRestoreService.ts` |
|
||||
| `userPreferenceService.ts` | Stockage préférences utilisateur |
|
||||
|
|
@ -711,7 +711,7 @@ Garde : `src/__integration__/i18n-mock-guard.test.ts` lit tous les `*.test.ts(x)
|
|||
|
||||
`categoryService.test.ts` exécute les requêtes qui vérifient ce que porte un parent (transactions, montants de budget, mots-clés) telles qu'elles sont écrites, sur une base SQLite en mémoire de `node:sqlite`, module intégré à Node (aucun paquet ; expérimental sous Node 22, qui l'annonce par un avertissement à l'exécution). Ses tables y sont créées par leur `CREATE TABLE` de `consolidated_schema.sql`, clés étrangères coupées : la table `categories` reste dans le faux du test. Une condition retirée d'une requête (`amount <> 0`, `is_active = 1`) rougit donc un test, ce qu'un faux qui réimplémente la règle ne ferait pas.
|
||||
|
||||
`src/__integration__/split-offset-manual-flag.test.ts` (#454) y fait tourner des services entiers : `saveSplitAdjustment`, `updateTransactionCategory` et `autoCategorizeTransactions`, tels qu'ils sont écrits, sur le schéma complet d'un profil neuf (`consolidated_schema.sql`, seed compris : mot-clé `METRO`, catégories 1111 et 1112), clés étrangères actives comme sous sqlx. `../services/db` y est remplacé par un adaptateur propre au fichier : `select` et `execute` lient `$N` par nom, `execute` rend `rowsAffected` et `lastInsertId`, `withTransaction` passe à son rappel le même handle, et `getDb()` échoue pendant une transaction, là où le vrai verrou bloquerait. `src/__integration__/restore.test.ts` (#518) en copie l'adaptateur pour les restaurations (`importTransactionsOnly`, `importTransactionsWithCategories`, `importCategoriesOnly`, et « Rétablir la sauvegarde » par `readBackup` puis `applyBackup`), avec une seconde base qui tient lieu de profil neuf ; #521 y ajoute les transferts du Bilan, liés par le vrai `linkTransfer`, les catégories absentes, « Réinitialiser » compris, et les catégories rangées sous une plus récente ou en boucle ; #520 le budget, les modèles et les ajustements, écrits par les vrais services des pages Budget et Ajustements, au format 3 comme au format 2, et la migration des catégories elle-même (`createPreMigrationBackup`, `computeMigrationPlan` puis `applyMigration`) avant « Rétablir la sauvegarde ». Aucun harnais partagé : #392 le prévoit. Les autres tests de services gardent leurs faux.
|
||||
Le harnais partagé `src/test/sqliteHarness.ts` (#392) fait tourner des services entiers, tels qu'ils sont écrits, sur le schéma complet d'un profil neuf (`consolidated_schema.sql`, seed compris), clés étrangères actives comme sous sqlx. Chaque fichier de test remplace `../services/db` par lui (`vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule())`, puis `useDb(openProfileDb())`) : `select` et `execute` lient `$N` par nom, `execute` rend `rowsAffected` et `lastInsertId`, `withTransaction` passe à son rappel le même handle, et `getDb()` comme un `withTransaction` imbriqué échouent pendant une transaction, là où le vrai verrou, non réentrant, bloquerait ; `src/test/sqliteHarness.test.ts` prouve ces règles. Le harnais n'importe aucun service, puisque la fabrique du mock l'importe pendant que `../services/db` se construit. L'app embarque SQLite 3.46.0 (`libsqlite3-sys` 0.30.1), Node 22 une version plus récente : une requête n'utilise rien de postérieur à 3.46. `src/__integration__/report-totals.test.ts` (#392) y lit chaque rapport par son vrai service, sur le jeu de reproduction de #392 et sur ses cas limites (convention de l'[ADR 0026](adr/0026-convention-signe-rapports.md)). `src/__integration__/split-offset-manual-flag.test.ts` (#454) y fait tourner `saveSplitAdjustment`, `updateTransactionCategory` et `autoCategorizeTransactions` (mot-clé `METRO`, catégories 1111 et 1112). `src/__integration__/restore.test.ts` (#518) y fait tourner les restaurations (`importTransactionsOnly`, `importTransactionsWithCategories`, `importCategoriesOnly`, et « Rétablir la sauvegarde » par `readBackup` puis `applyBackup`), avec une seconde base qui tient lieu de profil neuf ; #521 y ajoute les transferts du Bilan, liés par le vrai `linkTransfer`, les catégories absentes, « Réinitialiser » compris, et les catégories rangées sous une plus récente ou en boucle ; #520 le budget, les modèles et les ajustements, écrits par les vrais services des pages Budget et Ajustements, au format 3 comme au format 2, et la migration des catégories elle-même (`createPreMigrationBackup`, `computeMigrationPlan` puis `applyMigration`) avant « Rétablir la sauvegarde ». Les autres tests de services gardent leurs faux.
|
||||
|
||||
### Limites connues (#437)
|
||||
|
||||
|
|
@ -803,3 +803,4 @@ Les ADRs documentent les décisions techniques structurantes. Ils vivent dans `d
|
|||
| [0023](adr/0023-windows-sys-pinning.md) | Épinglage de `windows-sys` 0.61.2 : garde-fou CI sur la version résolue, condition de sortie écrite | 2026-10-10 | Accepted |
|
||||
| [0024](adr/0024-serveur-mcp.md) | Serveur MCP : un mode `--mcp` du binaire, stdio seul, accès par profil, Premium | 2026-10-12 | Proposed |
|
||||
| [0025](adr/0025-contenu-restauration-sauvegarde-sref.md) | Contenu et restauration d'une sauvegarde SREF : identifiants, transferts du Bilan, budget au format 3 et repli des formats antérieurs | 2026-11-04 | Accepted |
|
||||
| [0026](adr/0026-convention-signe-rapports.md) | Convention de signe des rapports : solde signé par catégorie, ligne « Non classé », solde net et taux d'épargne | 2026-11-07 | Accepted |
|
||||
|
|
|
|||
|
|
@ -113,7 +113,7 @@ Le tableau de bord vous donne un aperçu rapide de votre situation financière p
|
|||
### Astuces
|
||||
|
||||
- La période par défaut est « année à ce jour » pour un aperçu annuel dès l'ouverture
|
||||
- Le solde est calculé comme les revenus moins les dépenses pour la période sélectionnée
|
||||
- Le solde net est la somme de toutes les transactions du mois de référence : les revenus moins les dépenses, plus les transactions non classées et les transferts, qu'une note sous la carte détaille quand ils ne sont pas nuls. Le taux d'épargne vaut (revenus − dépenses) ÷ revenus (voir Rapports → Comment les montants sont calculés)
|
||||
- Les catégories masquées apparaissent sous forme de pastilles au-dessus du graphique — cliquez sur Tout afficher pour les restaurer
|
||||
- Les motifs SVG (lignes, points, hachures) aident à distinguer les catégories au-delà des couleurs
|
||||
- Les cases de la liste de démarrage se cochent sur vos données, pas sur un clic : « Classer une transaction à la main » attend une transaction dont vous avez changé la catégorie vous-même, la catégorisation automatique de l'import ne la coche pas
|
||||
|
|
@ -259,6 +259,7 @@ Parcourez, filtrez, triez et catégorisez toutes vos transactions importées. C'
|
|||
- L'auto-catégorisation n'affecte que les transactions non catégorisées — elle n'écrase pas les assignations manuelles
|
||||
- Ajouter un mot-clé depuis une transaction pré-remplit la catégorie pour construire rapidement vos règles
|
||||
- Les transactions réparties affichent un indicateur visuel, quelle que soit l'édition ; le détail de la répartition s'ouvre par le bouton Répartition (édition Base et plus)
|
||||
- La barre au-dessus de la liste additionne les transactions affichées par signe : « Entrées », « Sorties » et « Solde », sans les lignes de répartition. Les revenus et les dépenses des rapports se comptent par catégorie (voir Rapports → Comment les montants sont calculés)
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -360,16 +361,27 @@ Planifiez votre budget mensuel pour chaque catégorie et suivez le prévu par ra
|
|||
|
||||
`/reports` est un **hub** qui répond à quatre questions : *qu'est-ce qui a bougé ce mois ?*, *où je vais, mois par mois ?*, *comment je me situe vs période précédente ou vs budget ?*, *que se passe-t-il dans cette catégorie ?*
|
||||
|
||||
### Comment les montants sont calculés
|
||||
|
||||
Tous les rapports, comme le tableau de bord, comptent les montants de la même façon : catégorie par catégorie, signes compris.
|
||||
|
||||
- **Revenus** : la somme des transactions des catégories de revenu
|
||||
- **Dépenses** : la somme des transactions des catégories de dépense, changée de signe. Un remboursement réduit la dépense de sa catégorie ; une catégorie dont les remboursements dépassent les achats a une dépense négative, qu'un graphique trace sous zéro
|
||||
- **Répartitions** : une transaction répartie compte une fois, chaque part dans sa catégorie
|
||||
- **Transferts** : à part, avec leur signe. Un transfert équilibré (le paiement d'une carte de crédit et sa réception) fait zéro ; un transfert dont l'autre moitié n'est pas importée compte avec son signe dans le résultat net
|
||||
- **Non classé** : les transactions sans catégorie forment une ligne à part, ni revenu ni dépense, comptée dans les deux résultats
|
||||
- **Résultat avant transferts** = revenus − dépenses + non classé ; **résultat net** = résultat avant transferts + transferts, soit la somme de toutes les transactions de la période
|
||||
|
||||
### Le hub
|
||||
|
||||
En haut, un **panneau de faits saillants** condensé : solde net du mois courant + solde cumul annuel (YTD) avec sparkline 12 mois, top mouvements vs mois précédent et top 5 des plus grosses transactions récentes. En bas, cinq cartes mènent aux cinq sous-rapports dédiés.
|
||||
En haut, un **panneau de faits saillants** condensé : solde net du mois courant + solde cumul annuel (YTD) avec sparkline 12 mois, top mouvements des catégories de dépense vs mois précédent et top 5 des plus grosses transactions récentes. En bas, cinq cartes mènent aux cinq sous-rapports dédiés.
|
||||
|
||||
Le sélecteur de période en haut à droite est **partagé** entre toutes les pages via l'URL : `?period=…` pour un bouton prédéfini, par exemple `?period=year` pour « Cette année » (du 1er janvier à aujourd'hui) ou `?period=all` pour « Tout » (toutes les dates), et `?period=custom&from=YYYY-MM-DD&to=YYYY-MM-DD` pour une période personnalisée. Ouverts sans paramètre, les Rapports montrent « Cette année ». Copiez l'URL pour revenir plus tard au même état ou la partager.
|
||||
|
||||
### Rapport Faits saillants (`/reports/highlights`)
|
||||
|
||||
- Tuiles de soldes mois courant + YTD avec sparklines 12 mois
|
||||
- Tableau triable des **top mouvements** (catégories avec la plus forte variation vs mois précédent), ou graphique en barres divergentes centré sur zéro (toggle graphique/tableau)
|
||||
- Tableau triable des **top mouvements** (catégories de dépense avec la plus forte variation vs mois précédent, remboursements compris), ou graphique en barres divergentes centré sur zéro (toggle graphique/tableau)
|
||||
- Liste des **plus grosses transactions récentes** avec fenêtre configurable 30 / 60 / 90 jours
|
||||
|
||||
### Rapport Cartes (`/reports/cartes`)
|
||||
|
|
@ -378,10 +390,10 @@ Un tableau de bord condensé qui résume un mois de référence en quatre KPIs,
|
|||
|
||||
#### Les 4 cartes KPI et leurs formules
|
||||
|
||||
- **Revenus** = somme des transactions positives
|
||||
- **Dépenses** = valeur absolue de la somme des transactions négatives
|
||||
- **Solde net** = `revenus − dépenses`
|
||||
- **Taux d'épargne** = `(revenus − dépenses) ÷ revenus × 100`. Affiché comme « — » quand les revenus sont à zéro (évite la division par zéro et le « 0 % » trompeur)
|
||||
- **Revenus** = somme des transactions des catégories de revenu
|
||||
- **Dépenses** = somme des transactions des catégories de dépense, changée de signe : un remboursement la réduit
|
||||
- **Solde net** = somme de toutes les transactions du mois : `revenus − dépenses`, plus le non classé et les transferts. Une note sous la carte donne ces deux parts quand elles ne sont pas nulles
|
||||
- **Taux d'épargne** = `(revenus − dépenses) ÷ revenus × 100`, sans les transferts ni le non classé : un virement vers un CELI ne le fait pas baisser. Affiché comme « — » quand les revenus sont nuls ou négatifs (évite la division par zéro et le « 0 % » trompeur)
|
||||
|
||||
Chaque carte affiche la valeur courante, deux deltas (vs mois précédent, vs l'an dernier) et une sparkline 13 mois. Le delta est vert si la variation est favorable au KPI (hausse pour Revenus, baisse pour Dépenses), rouge dans le cas contraire.
|
||||
|
||||
|
|
@ -393,7 +405,7 @@ Placé à côté du sélecteur de mois, il bascule les 4 cartes entre deux vues
|
|||
- **Cumul annuel (YTD)** — la valeur courante est la somme depuis le 1er janvier de l'année de référence jusqu'à la fin du mois de référence inclus. Les deltas deviennent :
|
||||
- **MoM YTD** = cumul actuel (Jan→mois de réf) vs cumul précédent (Jan→mois de réf−1) de la même année. **Null en janvier** (pas de fenêtre antérieure dans la même année) — affiché comme « — »
|
||||
- **YoY YTD** = cumul actuel vs le même cumul (Jan→mois de réf) de l'année précédente
|
||||
- **Taux d'épargne YTD** = `(revenus YTD − dépenses YTD) ÷ revenus YTD × 100`, null si les revenus YTD sont à zéro
|
||||
- **Taux d'épargne YTD** = `(revenus YTD − dépenses YTD) ÷ revenus YTD × 100`, null si les revenus YTD sont nuls ou négatifs
|
||||
|
||||
Le choix du mode est **persisté** (clé locale `reports-cartes-period-mode`) et restauré au redémarrage. La sparkline 13 mois, elle, reste toujours mensuelle — elle donne le contexte temporel indépendamment du toggle.
|
||||
|
||||
|
|
@ -403,11 +415,11 @@ Chaque KPI inclut une mini-courbe des 13 derniers mois (mois de référence + 12
|
|||
|
||||
#### Top mouvements (MoM)
|
||||
|
||||
Deux listes : les 5 catégories avec la plus forte **hausse** de dépenses vs mois précédent et les 5 avec la plus forte **baisse**. Triées par variation absolue en dollars, avec la variation en pourcentage à droite. Toujours mensuelles, indépendamment du toggle.
|
||||
Deux listes : les 5 catégories de dépense avec la plus forte **hausse** vs mois précédent et les 5 avec la plus forte **baisse**, remboursements compris. Triées par variation absolue en dollars, avec la variation en pourcentage à droite. Toujours mensuelles, indépendamment du toggle.
|
||||
|
||||
#### Saisonnalité
|
||||
|
||||
Compare les dépenses du mois de référence à la **moyenne du même mois calendaire sur les 2 années précédentes**.
|
||||
Compare les dépenses du mois de référence, comptées comme la carte Dépenses, à la **moyenne du même mois calendaire sur les 2 années précédentes**.
|
||||
|
||||
- Écart en pourcentage : `(dépenses du mois − moyenne historique) ÷ moyenne historique × 100`
|
||||
- Affiché comme « pas assez d'historique pour ce mois » s'il n'y a aucune donnée historique ou si la moyenne est à zéro
|
||||
|
|
@ -416,7 +428,7 @@ Toujours basée sur le mois de référence, indépendamment du toggle Mensuel /
|
|||
|
||||
#### Adhésion budgétaire
|
||||
|
||||
Score `N/M` des catégories dont les dépenses restent sous le budget mensuel (comparaison en valeur absolue pour gérer correctement les budgets de dépenses stockés signés négatifs).
|
||||
Score `N/M` des catégories de dépense dont la dépense du mois, remboursements compris, reste sous le budget mensuel. Un remboursement réduit la dépense : il ne compte jamais comme un dépassement.
|
||||
|
||||
- Seules les catégories de type **dépense** avec un budget non nul sont comptées, feuilles uniquement (les catégories parentes sont ignorées pour éviter le double comptage)
|
||||
- Suivi des **3 pires dépassements** avec le montant et le pourcentage de dépassement
|
||||
|
|
@ -430,7 +442,7 @@ Toujours mensuelle, indépendamment du toggle.
|
|||
|
||||
### Rapport Tendances (`/reports/trends`)
|
||||
|
||||
- **Flux global** : revenus vs dépenses vs solde net sur la période, en graphique d'aires ou tableau
|
||||
- **Flux global** : revenus et dépenses mois par mois sur la période, en graphique d'aires ; le tableau y ajoute le non classé, les transferts et le solde net
|
||||
- **Par catégorie** : évolution de chaque catégorie, en lignes ou tableau. En mode tableau, la hiérarchie se **replie / déplie à chaque niveau** (voir ci-dessous)
|
||||
|
||||
### Rapport Comparables (`/reports/compare`)
|
||||
|
|
@ -441,6 +453,8 @@ Trois modes accessibles via un tab bar :
|
|||
- **Année vs année précédente** — même logique sur 12 mois vs 12 mois
|
||||
- **Réel vs budget** — reprend la vue Budget vs Réel avec ses totaux mensuels et cumul annuel
|
||||
|
||||
Les trois tableaux suivent l'ordre d'un état de résultat : revenus, dépenses, la ligne **Non classé** quand des transactions n'ont pas de catégorie, le résultat avant transferts quand il y a des transferts, les transferts, puis le résultat net.
|
||||
|
||||
#### Repli de la hiérarchie
|
||||
|
||||
Les trois modes ci-dessus, comme le tableau **Par catégorie** des Tendances, présentent les catégories en arbre repliable **à chaque niveau**. Chaque catégorie parente — y compris les niveaux intermédiaires — porte son propre chevron : le déplier révèle ses enfants directs (eux-mêmes repliés), de sorte que vous descendez d'un niveau à la fois. Le tableau s'ouvre **entièrement replié** (seules les catégories de premier niveau visibles) ; le bouton **« Tout déplier / Tout replier »** ouvre ou ferme tous les niveaux d'un coup. Replier une catégorie est **purement visuel** — les sous-totaux, totaux et lignes de résultat restent calculés sur l'ensemble des lignes, jamais sur les seules lignes visibles. Vos choix de repli sont **mémorisés par profil** (dans la base du profil, ils disparaissent donc avec lui).
|
||||
|
|
@ -449,7 +463,7 @@ Les trois modes ci-dessus, comme le tableau **Par catégorie** des Tendances, pr
|
|||
|
||||
Choisissez une catégorie dans la combobox en haut. Par défaut le rapport inclut automatiquement les sous-catégories (toggle *Directe seulement* pour les exclure). Vous voyez :
|
||||
|
||||
- Un **donut chart** de la répartition par sous-catégorie avec le total au centre
|
||||
- Un **donut chart** de la répartition par sous-catégorie avec le total au centre ; une sous-catégorie au montant négatif (des remboursements supérieurs aux achats) n'y figure pas, et une ligne sous le donut le dit
|
||||
- Un graphique d'évolution mensuelle de la catégorie
|
||||
- Un tableau triable des transactions
|
||||
|
||||
|
|
|
|||
|
|
@ -229,7 +229,7 @@ describe.each<[Schema]>([["v2"], ["v1"]])(
|
|||
if (/FROM categories/i.test(sql)) return Promise.resolve(categories);
|
||||
if (/FROM budget_entries WHERE year/i.test(sql))
|
||||
return Promise.resolve(entries);
|
||||
if (/GROUP BY category_id/i.test(sql)) return Promise.resolve([]);
|
||||
if (/AS actual/i.test(sql)) return Promise.resolve([]);
|
||||
return Promise.resolve([]);
|
||||
});
|
||||
|
||||
|
|
@ -240,7 +240,7 @@ describe.each<[Schema]>([["v2"], ["v1"]])(
|
|||
const parentId = schema === "v2" ? 22 : 1110;
|
||||
|
||||
// Collect budgets per row keyed by category_id.
|
||||
const budgetById = new Map<number, number>();
|
||||
const budgetById = new Map<number | null, number>();
|
||||
for (const r of rows) {
|
||||
budgetById.set(r.category_id, r.monthBudget);
|
||||
}
|
||||
|
|
|
|||
578
src/__integration__/report-totals.test.ts
Normal file
578
src/__integration__/report-totals.test.ts
Normal file
|
|
@ -0,0 +1,578 @@
|
|||
/**
|
||||
* The totals of the reports, read through their real services (#392, ADR 0026).
|
||||
*
|
||||
* The income, the expenses and the result of one month used to change with the
|
||||
* screen: six aggregation rules, none of which treated transfers, refunds,
|
||||
* splits and transactions without a category alike, and the real-vs-real
|
||||
* compare counted every split amount twice. There is now one rule (D1): the
|
||||
* signed sum of each category over the period, splits and refunds included.
|
||||
* Income is the balance of the income categories, expenses the opposite of
|
||||
* the balance of the expense categories (negative when refunds exceed
|
||||
* purchases), transfers the signed balance of the transfer categories, and
|
||||
* the transactions without a category form a line of their own, neither
|
||||
* income nor expense, counted in the result (D4). « Solde net » is the sum of
|
||||
* every amount of the period (D5), the savings rate (income − expenses) ÷
|
||||
* income (D6).
|
||||
*
|
||||
* Every report is read here on the two datasets of the issue, on a real SQLite
|
||||
* database (`src/test/sqliteHarness.ts`): the SQL runs as written.
|
||||
*/
|
||||
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());
|
||||
|
||||
import { openProfileDb, useDb } from "../test/sqliteHarness";
|
||||
import { getTransactionPage, saveSplitAdjustment } from "../services/transactionService";
|
||||
import {
|
||||
getCartesSnapshot,
|
||||
getCategoryOverTime,
|
||||
getCategoryZoom,
|
||||
getCompareMonthOverMonth,
|
||||
getCompareYearOverYear,
|
||||
getHighlights,
|
||||
getMonthlyTrends,
|
||||
} from "../services/reportService";
|
||||
import { getExpensesByCategory } from "../services/dashboardService";
|
||||
import { getActualTotalsForYear, getBudgetVsActualData } from "../services/budgetService";
|
||||
import { computeResults as compareResults } from "../components/reports/compareResults";
|
||||
import { computeOverTimeResults } from "../components/reports/overTimeResults";
|
||||
import { computeResults as budgetResults } from "../components/reports/budgetVsActualResults";
|
||||
import type { IncomeStatementFigures } from "../shared/types";
|
||||
|
||||
// Categories of the seed of a new profile.
|
||||
const EMPLOYMENT = 1010; // « Emploi », income, parent of the next one
|
||||
const PAY = 1011; // « Paie régulière », income
|
||||
const GROCERY_AND_MARKET = 1110; // « Épicerie & marché », parent of the next two
|
||||
const GROCERIES = 1111; // « Épicerie régulière »
|
||||
const BUTCHER = 1112; // « Boucherie & poissonnerie »
|
||||
const PHARMACY = 1611; // « Pharmacie »
|
||||
const CARD = 1971; // « Paiement carte crédit », transfer
|
||||
|
||||
const PAY_NAME = "Paie régulière";
|
||||
const GROCERIES_NAME = "Épicerie régulière";
|
||||
const BUTCHER_NAME = "Boucherie & poissonnerie";
|
||||
const PHARMACY_NAME = "Pharmacie";
|
||||
const CARD_NAME = "Paiement carte crédit";
|
||||
|
||||
const FROM = "2026-10-01";
|
||||
const TO = "2026-10-31";
|
||||
const TODAY = new Date(2026, 9, 31);
|
||||
|
||||
let db: DatabaseSync;
|
||||
|
||||
beforeEach(() => {
|
||||
db = useDb(openProfileDb());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
db.close();
|
||||
});
|
||||
|
||||
/** A transaction as an import writes it; its id. */
|
||||
function insert(
|
||||
date: string,
|
||||
description: string,
|
||||
amount: number,
|
||||
categoryId: number | null,
|
||||
sourceId: number | null = null,
|
||||
): number {
|
||||
const result = db
|
||||
.prepare(
|
||||
`INSERT INTO transactions (date, description, amount, category_id, source_id, original_description)
|
||||
VALUES ($date, $description, $amount, $category, $source, $description)`,
|
||||
)
|
||||
.run({ $date: date, $description: description, $amount: amount, $category: categoryId, $source: sourceId });
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
|
||||
/** An import source; its id. */
|
||||
function source(name: string): number {
|
||||
const result = db
|
||||
.prepare("INSERT INTO import_sources (name, column_mapping) VALUES ($name, '{}')")
|
||||
.run({ $name: name });
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
|
||||
/** The budget of a category for October 2026, entered positive as on the Budget page. */
|
||||
function budget(categoryId: number, amount: number): void {
|
||||
db.prepare("INSERT INTO budget_entries (category_id, year, month, amount) VALUES ($c, 2026, 10, $a)").run({
|
||||
$c: categoryId,
|
||||
$a: amount,
|
||||
});
|
||||
}
|
||||
|
||||
/** The sum of every amount of October 2026, split lines included. */
|
||||
function sumOfOctober(): number {
|
||||
const row = db
|
||||
.prepare("SELECT COALESCE(SUM(amount), 0) AS s FROM transactions WHERE date BETWEEN $f AND $t")
|
||||
.get({ $f: FROM, $t: TO }) as { s: number };
|
||||
return Math.round(row.s * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reproduction of the issue: pay +1000; groceries −100, of which −30 split
|
||||
* to Pharmacy (the real service writes the −30 line and the +30 offset line in
|
||||
* Groceries); a +20 refund in Groceries; a card payment −500 / +500. Expenses
|
||||
* 80 (Groceries 50, Pharmacy 30), net 920.
|
||||
*/
|
||||
async function seedReproduction(sourceId: number | null = null): Promise<void> {
|
||||
insert("2026-10-02", "PAIE", 1000, PAY, sourceId);
|
||||
const groceries = insert("2026-10-05", "EPICERIE METRO", -100, GROCERIES, sourceId);
|
||||
await saveSplitAdjustment(groceries, [{ category_id: PHARMACY, amount: -30, description: "PHARMACIE" }]);
|
||||
insert("2026-10-08", "REMBOURSEMENT METRO", 20, GROCERIES, sourceId);
|
||||
insert("2026-10-10", "PAIEMENT CARTE", -500, CARD, sourceId);
|
||||
insert("2026-10-10", "PAIEMENT RECU", 500, CARD, sourceId);
|
||||
// Spent 50 in Groceries against a budget of 40.
|
||||
budget(GROCERIES, 40);
|
||||
}
|
||||
|
||||
/**
|
||||
* The edge cases of the issue: pay +1000; groceries −80; a refund of +50 alone
|
||||
* in Butcher, budgeted 30; a credit of +40 without a category; a card payment
|
||||
* with one leg only, −300. Income 1000, expenses 30, uncategorized +40,
|
||||
* transfers −300, result before transfers 1010, net 710.
|
||||
*/
|
||||
function seedEdgeCases(): void {
|
||||
insert("2026-10-02", "PAIE", 1000, PAY);
|
||||
insert("2026-10-03", "EPICERIE", -80, GROCERIES);
|
||||
insert("2026-10-04", "REMBOURSEMENT BOUCHERIE", 50, BUTCHER);
|
||||
insert("2026-10-06", "VIREMENT INCONNU", 40, null);
|
||||
insert("2026-10-07", "PAIEMENT CARTE", -300, CARD);
|
||||
budget(BUTCHER, 30);
|
||||
budget(GROCERIES, 100);
|
||||
}
|
||||
|
||||
const REPRODUCTION = {
|
||||
income: 1000,
|
||||
expenses: 80,
|
||||
uncategorized: 0,
|
||||
transfers: 0,
|
||||
resultBeforeTransfers: 920,
|
||||
net: 920,
|
||||
};
|
||||
|
||||
const EDGE_CASES = {
|
||||
income: 1000,
|
||||
expenses: 30,
|
||||
uncategorized: 40,
|
||||
transfers: -300,
|
||||
resultBeforeTransfers: 1010,
|
||||
net: 710,
|
||||
};
|
||||
|
||||
const page = () =>
|
||||
getTransactionPage(
|
||||
{ search: "", categoryId: null, sourceId: null, dateFrom: FROM, dateTo: TO, uncategorizedOnly: false },
|
||||
{ column: "date", direction: "desc" },
|
||||
1,
|
||||
50,
|
||||
);
|
||||
|
||||
describe("the reproduction of #392: every report reads income 1000, expenses 80, net 920", () => {
|
||||
beforeEach(async () => {
|
||||
await seedReproduction();
|
||||
expect(sumOfOctober()).toBe(920);
|
||||
});
|
||||
|
||||
it("Trends, global flow", async () => {
|
||||
expect(await getMonthlyTrends(FROM, TO)).toEqual([{ month: "2026-10", ...REPRODUCTION }]);
|
||||
});
|
||||
|
||||
it("Dashboard and Cartes: the four indicators, their note, seasonality, movers and budget adherence", async () => {
|
||||
const snapshot = await getCartesSnapshot(2026, 10, "month");
|
||||
expect(snapshot.kpis.income.current).toBe(1000);
|
||||
expect(snapshot.kpis.expenses.current).toBe(80);
|
||||
expect(snapshot.kpis.net.current).toBe(920);
|
||||
expect(snapshot.kpis.savingsRate.current).toBe(92);
|
||||
expect(snapshot.netBreakdown).toEqual({ uncategorized: 0, transfers: 0 });
|
||||
expect(snapshot.flow12Months[snapshot.flow12Months.length - 1]).toEqual({ month: "2026-10", ...REPRODUCTION });
|
||||
expect(snapshot.seasonality.referenceAmount).toBe(80);
|
||||
// Spending categories only, each split part in its own category, counted once.
|
||||
expect(snapshot.topMoversUp.map((m) => [m.categoryName, m.currentAmount])).toEqual([
|
||||
[GROCERIES_NAME, 50],
|
||||
[PHARMACY_NAME, 30],
|
||||
]);
|
||||
expect(snapshot.budgetAdherence).toEqual({
|
||||
categoriesInTarget: 0,
|
||||
categoriesTotal: 1,
|
||||
worstOverruns: [
|
||||
expect.objectContaining({ categoryName: GROCERIES_NAME, actual: 50, budget: 40, overrunAbs: 10 }),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("Compare, real vs real: the split counted once (it was 130)", async () => {
|
||||
for (const rows of [await getCompareMonthOverMonth(2026, 10), await getCompareYearOverYear(2026, 10)]) {
|
||||
const r = compareResults(rows);
|
||||
expect([
|
||||
r.income.monthCurrent,
|
||||
r.expense.monthCurrent,
|
||||
r.uncategorized.monthCurrent,
|
||||
r.transfer.monthCurrent,
|
||||
r.resultBefore.monthCurrent,
|
||||
r.resultNet.monthCurrent,
|
||||
]).toEqual([1000, 80, 0, 0, 920, 920]);
|
||||
const leaves = Object.fromEntries(
|
||||
rows.filter((row) => !row.is_parent).map((row) => [row.categoryName, row.currentAmount]),
|
||||
);
|
||||
expect(leaves).toMatchObject({ [GROCERIES_NAME]: 50, [PHARMACY_NAME]: 30, [CARD_NAME]: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
it("Trends, by category", async () => {
|
||||
const analysis = computeOverTimeResults(await getCategoryOverTime(FROM, TO));
|
||||
expect(Object.fromEntries(analysis.sections.map((s) => [s.type, s.total]))).toEqual({
|
||||
income: 1000,
|
||||
expense: 80,
|
||||
transfer: 0,
|
||||
});
|
||||
expect(analysis.uncategorized.total).toBe(0);
|
||||
expect(analysis.beforeTransfers.total).toBe(920);
|
||||
expect(analysis.net.total).toBe(920);
|
||||
});
|
||||
|
||||
it("Dashboard: expenses by category, and their monthly chart", async () => {
|
||||
expect((await getExpensesByCategory(FROM, TO)).map((c) => [c.category_name, c.total])).toEqual([
|
||||
[GROCERIES_NAME, 50],
|
||||
[PHARMACY_NAME, 30],
|
||||
]);
|
||||
const overTime = await getCategoryOverTime(FROM, TO, undefined, undefined, "expense");
|
||||
expect(overTime.data).toEqual([{ month: "2026-10", [GROCERIES_NAME]: 50, [PHARMACY_NAME]: 30 }]);
|
||||
});
|
||||
|
||||
it("Compare, actual vs budget", async () => {
|
||||
const r = budgetResults(await getBudgetVsActualData(2026, 10));
|
||||
expect([
|
||||
r.income.monthActual,
|
||||
r.expense.monthActual,
|
||||
r.uncategorized.monthActual,
|
||||
r.transfer.monthActual,
|
||||
r.resultBefore.monthActual,
|
||||
r.resultNet.monthActual,
|
||||
]).toEqual([1000, -80, 0, 0, 920, 920]);
|
||||
});
|
||||
|
||||
it("Highlights: the net of the month, and movers among spending categories only", async () => {
|
||||
const highlights = await getHighlights(2026, 10, 2026, 30, 5, 10, TODAY);
|
||||
expect(highlights.netBalanceCurrent).toBe(920);
|
||||
expect(highlights.topMovers.map((m) => [m.categoryName, m.currentAmount])).toEqual([
|
||||
[GROCERIES_NAME, 50],
|
||||
[PHARMACY_NAME, 30],
|
||||
]);
|
||||
});
|
||||
|
||||
it("Category analysis: the zoom nets the split and the refund (it was 150)", async () => {
|
||||
const zoom = await getCategoryZoom(GROCERY_AND_MARKET, FROM, TO, true);
|
||||
expect(zoom.rollupTotal).toBe(50);
|
||||
expect(zoom.byChild.find((c) => c.categoryId === GROCERIES)?.total).toBe(50);
|
||||
expect(zoom.monthlyEvolution).toEqual([{ month: "2026-10", total: 50 }]);
|
||||
});
|
||||
|
||||
it("Category analysis: a zoom on an income category shows its balance as it is", async () => {
|
||||
const zoom = await getCategoryZoom(EMPLOYMENT, FROM, TO, true);
|
||||
expect(zoom.rollupTotal).toBe(1000);
|
||||
expect(zoom.byChild.find((c) => c.categoryId === PAY)).toMatchObject({ categoryName: PAY_NAME, total: 1000 });
|
||||
expect(zoom.monthlyEvolution).toEqual([{ month: "2026-10", total: 1000 }]);
|
||||
});
|
||||
|
||||
it("Transactions: the summary bar keeps its sums by sign, without the split lines (D8)", async () => {
|
||||
const p = await page();
|
||||
expect([p.totalCount, p.incomeTotal, p.expenseTotal, p.totalAmount]).toEqual([5, 1520, -600, 920]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the edge cases of #392: every report reads the same net, 710", () => {
|
||||
beforeEach(() => {
|
||||
seedEdgeCases();
|
||||
expect(sumOfOctober()).toBe(710);
|
||||
});
|
||||
|
||||
it("Trends, global flow: the uncategorized line and the one-leg transfer apart", async () => {
|
||||
expect(await getMonthlyTrends(FROM, TO)).toEqual([{ month: "2026-10", ...EDGE_CASES }]);
|
||||
});
|
||||
|
||||
it("Dashboard and Cartes: a refund lowers the expenses, the savings rate leaves transfers out", async () => {
|
||||
const snapshot = await getCartesSnapshot(2026, 10, "month");
|
||||
expect(snapshot.kpis.income.current).toBe(1000);
|
||||
expect(snapshot.kpis.expenses.current).toBe(30);
|
||||
expect(snapshot.kpis.net.current).toBe(710);
|
||||
expect(snapshot.kpis.savingsRate.current).toBe(97);
|
||||
expect(snapshot.netBreakdown).toEqual({ uncategorized: 40, transfers: -300 });
|
||||
expect(snapshot.seasonality.referenceAmount).toBe(30);
|
||||
expect(snapshot.topMoversUp.map((m) => [m.categoryName, m.currentAmount])).toEqual([[GROCERIES_NAME, 80]]);
|
||||
expect(snapshot.topMoversDown.map((m) => [m.categoryName, m.currentAmount])).toEqual([[BUTCHER_NAME, -50]]);
|
||||
// The refund alone in Butcher is no overrun of its budget of 30.
|
||||
expect(snapshot.budgetAdherence).toEqual({ categoriesInTarget: 2, categoriesTotal: 2, worstOverruns: [] });
|
||||
// The savings sparkline follows the same rule as the card.
|
||||
const spark = snapshot.kpis.savingsRate.sparkline;
|
||||
expect(spark[spark.length - 1]).toEqual({ month: "2026-10", value: 97 });
|
||||
});
|
||||
|
||||
it("Cartes, year to date: the figures and the note of January to October", async () => {
|
||||
// September: 20 spent in Groceries, a credit of +25 without a category.
|
||||
insert("2026-09-16", "EPICERIE", -20, GROCERIES);
|
||||
insert("2026-09-15", "VIREMENT INCONNU", 25, null);
|
||||
|
||||
const snapshot = await getCartesSnapshot(2026, 10, "ytd");
|
||||
|
||||
expect([
|
||||
snapshot.kpis.income.current,
|
||||
snapshot.kpis.expenses.current,
|
||||
snapshot.kpis.net.current,
|
||||
snapshot.kpis.savingsRate.current,
|
||||
]).toEqual([1000, 50, 715, 95]);
|
||||
// The note follows the period of the cards: the year to date.
|
||||
expect(snapshot.netBreakdown).toEqual({ uncategorized: 65, transfers: -300 });
|
||||
// Seasonality stays on the month, whatever the mode.
|
||||
expect(snapshot.seasonality.referenceAmount).toBe(30);
|
||||
});
|
||||
|
||||
it("Cartes, seasonality: a past year's month reads its expenses, refunds netted, nothing else", async () => {
|
||||
insert("2025-10-03", "EPICERIE", -60, GROCERIES);
|
||||
insert("2025-10-09", "REMBOURSEMENT", 10, GROCERIES);
|
||||
insert("2025-10-02", "PAIE", 500, PAY);
|
||||
insert("2025-10-05", "INCONNU", -25, null);
|
||||
insert("2025-10-07", "PAIEMENT CARTE", -200, CARD);
|
||||
|
||||
const { seasonality } = await getCartesSnapshot(2026, 10, "month");
|
||||
|
||||
expect(seasonality.historicalYears).toEqual([{ year: 2025, amount: 50 }]);
|
||||
expect(seasonality.historicalAverage).toBe(50);
|
||||
expect(seasonality.referenceAmount).toBe(30);
|
||||
expect(seasonality.deviationPct).toBeCloseTo(-40, 6);
|
||||
});
|
||||
|
||||
it("Compare, real vs real: the refund and the credit without a category are no longer dropped", async () => {
|
||||
const rows = await getCompareMonthOverMonth(2026, 10);
|
||||
const r = compareResults(rows);
|
||||
expect([
|
||||
r.income.monthCurrent,
|
||||
r.expense.monthCurrent,
|
||||
r.uncategorized.monthCurrent,
|
||||
r.transfer.monthCurrent,
|
||||
r.resultBefore.monthCurrent,
|
||||
r.resultNet.monthCurrent,
|
||||
]).toEqual([1000, 30, 40, -300, 1010, 710]);
|
||||
expect(rows.filter((row) => row.category_type === "uncategorized")).toEqual([
|
||||
expect.objectContaining({ categoryId: null, currentAmount: 40, is_parent: false }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("Trends, by category: a signed transfer, the refund lowers its category", async () => {
|
||||
const data = await getCategoryOverTime(FROM, TO);
|
||||
const analysis = computeOverTimeResults(data);
|
||||
expect(Object.fromEntries(analysis.sections.map((s) => [s.type, s.total]))).toEqual({
|
||||
income: 1000,
|
||||
expense: 30,
|
||||
transfer: -300,
|
||||
});
|
||||
expect(analysis.uncategorized.total).toBe(40);
|
||||
expect(analysis.beforeTransfers.total).toBe(1010);
|
||||
expect(analysis.net.total).toBe(710);
|
||||
expect(data.tree.find((row) => row.categoryId === BUTCHER)?.total).toBe(-50);
|
||||
});
|
||||
|
||||
it("Dashboard: the expense charts carry the negative expense, and no line without a category", async () => {
|
||||
expect((await getExpensesByCategory(FROM, TO)).map((c) => [c.category_name, c.total])).toEqual([
|
||||
[GROCERIES_NAME, 80],
|
||||
[BUTCHER_NAME, -50],
|
||||
]);
|
||||
const overTime = await getCategoryOverTime(FROM, TO, undefined, undefined, "expense");
|
||||
expect(overTime.data).toEqual([{ month: "2026-10", [GROCERIES_NAME]: 80, [BUTCHER_NAME]: -50 }]);
|
||||
expect(overTime.tree.some((row) => row.category_type !== "expense")).toBe(false);
|
||||
// The top N ranks by the size of the balance: 80 spent outranks 50 refunded.
|
||||
const topOne = await getCategoryOverTime(FROM, TO, 1, undefined, "expense");
|
||||
expect(topOne.categories).toEqual([GROCERIES_NAME, "Other"]);
|
||||
expect(topOne.data).toEqual([{ month: "2026-10", [GROCERIES_NAME]: 80, Other: -50 }]);
|
||||
});
|
||||
|
||||
it("Compare, actual vs budget: the uncategorized line counts in the result", async () => {
|
||||
const rows = await getBudgetVsActualData(2026, 10);
|
||||
const r = budgetResults(rows);
|
||||
expect([
|
||||
r.income.monthActual,
|
||||
r.expense.monthActual,
|
||||
r.uncategorized.monthActual,
|
||||
r.transfer.monthActual,
|
||||
r.resultBefore.monthActual,
|
||||
r.resultNet.monthActual,
|
||||
]).toEqual([1000, -30, 40, -300, 1010, 710]);
|
||||
expect(rows.filter((row) => row.category_type === "uncategorized")).toEqual([
|
||||
expect.objectContaining({ category_id: null, monthActual: 40, monthBudget: 0, is_parent: false }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("Compare, actual vs budget: the uncategorized line stays when only the year to date holds it", async () => {
|
||||
db.prepare("DELETE FROM transactions WHERE category_id IS NULL").run();
|
||||
insert("2026-09-15", "VIREMENT INCONNU", 25, null);
|
||||
|
||||
const rows = await getBudgetVsActualData(2026, 10);
|
||||
|
||||
expect(rows.filter((row) => row.category_type === "uncategorized")).toEqual([
|
||||
expect.objectContaining({ category_id: null, monthActual: 0, ytdActual: 25 }),
|
||||
]);
|
||||
expect(budgetResults(rows).resultNet.ytdActual).toBe(695);
|
||||
});
|
||||
|
||||
it("Highlights: the net of the month, movers without the transfer", async () => {
|
||||
const highlights = await getHighlights(2026, 10, 2026, 30, 5, 10, TODAY);
|
||||
expect(highlights.netBalanceCurrent).toBe(710);
|
||||
expect(highlights.topMovers.map((m) => [m.categoryName, m.currentAmount])).toEqual([
|
||||
[GROCERIES_NAME, 80],
|
||||
[BUTCHER_NAME, -50],
|
||||
]);
|
||||
});
|
||||
|
||||
it("Category analysis: a subcategory with refunds only has a negative part", async () => {
|
||||
const zoom = await getCategoryZoom(GROCERY_AND_MARKET, FROM, TO, true);
|
||||
expect(zoom.rollupTotal).toBe(30);
|
||||
const byChild = Object.fromEntries(zoom.byChild.map((c) => [c.categoryId, c.total]));
|
||||
expect(byChild[GROCERIES]).toBe(80);
|
||||
expect(byChild[BUTCHER]).toBe(-50);
|
||||
// Largest first, the negative part last.
|
||||
expect(zoom.byChild[0].categoryId).toBe(GROCERIES);
|
||||
expect(zoom.byChild[zoom.byChild.length - 1].categoryId).toBe(BUTCHER);
|
||||
expect(zoom.monthlyEvolution).toEqual([{ month: "2026-10", total: 30 }]);
|
||||
});
|
||||
|
||||
it("Transactions: the summary bar keeps its sums by sign (D8)", async () => {
|
||||
const p = await page();
|
||||
expect([p.totalCount, p.incomeTotal, p.expenseTotal, p.totalAmount]).toEqual([5, 1090, -380, 710]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the account filter (#273, #279) keeps every report on the chosen sources", () => {
|
||||
let chosen: number;
|
||||
let other: number;
|
||||
|
||||
beforeEach(async () => {
|
||||
chosen = source("Compte courant");
|
||||
other = source("Carte");
|
||||
await seedReproduction(chosen);
|
||||
insert("2026-10-12", "EPICERIE IGA", -70, GROCERIES, other);
|
||||
insert("2026-10-15", "BONI", 200, PAY, other);
|
||||
});
|
||||
|
||||
it("filtered on the chosen source, every report reads the reproduction again", async () => {
|
||||
const ids = [chosen];
|
||||
// October 2025, for the seasonality: 40 spent from the chosen source, 70 from the other.
|
||||
insert("2025-10-03", "EPICERIE", -40, GROCERIES, chosen);
|
||||
insert("2025-10-04", "EPICERIE IGA", -70, GROCERIES, other);
|
||||
expect(await getMonthlyTrends(FROM, TO, ids)).toEqual([{ month: "2026-10", ...REPRODUCTION }]);
|
||||
const snapshot = await getCartesSnapshot(2026, 10, "month", ids);
|
||||
expect([snapshot.kpis.income.current, snapshot.kpis.expenses.current, snapshot.kpis.net.current]).toEqual([
|
||||
1000, 80, 920,
|
||||
]);
|
||||
expect(snapshot.seasonality.referenceAmount).toBe(80);
|
||||
expect(snapshot.seasonality.historicalYears).toEqual([{ year: 2025, amount: 40 }]);
|
||||
expect(compareResults(await getCompareMonthOverMonth(2026, 10, ids)).expense.monthCurrent).toBe(80);
|
||||
expect(compareResults(await getCompareYearOverYear(2026, 10, ids)).expense.monthCurrent).toBe(80);
|
||||
const actuals = await getActualTotalsForYear(2026, ids);
|
||||
expect(actuals.find((a) => a.category_id === GROCERIES)?.actual).toBe(-50);
|
||||
expect(computeOverTimeResults(await getCategoryOverTime(FROM, TO, undefined, ids)).net.total).toBe(920);
|
||||
expect((await getExpensesByCategory(FROM, TO, ids)).map((c) => c.total)).toEqual([50, 30]);
|
||||
expect(budgetResults(await getBudgetVsActualData(2026, 10, ids)).resultNet.monthActual).toBe(920);
|
||||
});
|
||||
|
||||
it("without a filter, the other source counts too", async () => {
|
||||
expect(await getMonthlyTrends(FROM, TO)).toEqual([
|
||||
{ month: "2026-10", income: 1200, expenses: 150, uncategorized: 0, transfers: 0, resultBeforeTransfers: 1050, net: 1050 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a negative previous month: a change keeps the sign of the change (review of PR #536)", () => {
|
||||
// September: a refund alone in Butcher, an expense of −50. October: 80 spent
|
||||
// in Butcher, 10 in Groceries. Butcher rises by 130, +260 % of the size of
|
||||
// its previous expense, as the section total (`pct`) already reads it.
|
||||
beforeEach(() => {
|
||||
insert("2026-09-12", "REMBOURSEMENT BOUCHERIE", 50, BUTCHER);
|
||||
insert("2026-10-03", "BOUCHERIE", -80, BUTCHER);
|
||||
insert("2026-10-05", "EPICERIE", -10, GROCERIES);
|
||||
});
|
||||
|
||||
it("Compare: the line, its group and the section total agree on the sign", async () => {
|
||||
const rows = await getCompareMonthOverMonth(2026, 10);
|
||||
const line = (id: number) => rows.find((r) => r.categoryId === id && !r.is_parent)!;
|
||||
expect(line(BUTCHER)).toMatchObject({ previousAmount: -50, currentAmount: 80, deltaAbs: 130, deltaPct: 260 });
|
||||
// Cumulative: −50 by the end of September, 30 by the end of October.
|
||||
expect(line(BUTCHER)).toMatchObject({ cumulativePreviousAmount: -50, cumulativeCurrentAmount: 30, cumulativeDeltaPct: 160 });
|
||||
const group = rows.find((r) => r.categoryId === GROCERY_AND_MARKET && r.is_parent)!;
|
||||
expect(group).toMatchObject({ previousAmount: -50, currentAmount: 90, deltaAbs: 140, deltaPct: 280 });
|
||||
expect(group).toMatchObject({ cumulativeDeltaAbs: 90, cumulativeDeltaPct: 180 });
|
||||
const { expense } = compareResults(rows);
|
||||
expect([expense.monthPrevious, expense.monthCurrent, expense.monthDelta]).toEqual([-50, 90, 140]);
|
||||
});
|
||||
|
||||
it("Cartes: the mover and the expense card read +260 % and +280 %", async () => {
|
||||
const snapshot = await getCartesSnapshot(2026, 10, "month");
|
||||
expect(snapshot.topMoversUp.find((m) => m.categoryId === BUTCHER)).toMatchObject({ deltaAbs: 130, deltaPct: 260 });
|
||||
expect(snapshot.kpis.expenses).toMatchObject({ current: 90, previousMonth: -50, deltaMoMAbs: 140, deltaMoMPct: 280 });
|
||||
});
|
||||
|
||||
it("Highlights: the mover reads +260 %", async () => {
|
||||
const highlights = await getHighlights(2026, 10, 2026, 30, 5, 10, TODAY);
|
||||
expect(highlights.topMovers.find((m) => m.categoryId === BUTCHER)).toMatchObject({ deltaAbs: 130, deltaPct: 260 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("each case of #392 alone: the monthly statement and the compare agree with the sum of the period", () => {
|
||||
const cases: Array<[string, () => unknown, Partial<IncomeStatementFigures>]> = [
|
||||
[
|
||||
"a split counts once",
|
||||
async () => {
|
||||
const id = insert("2026-10-05", "EPICERIE METRO", -100, GROCERIES);
|
||||
await saveSplitAdjustment(id, [{ category_id: PHARMACY, amount: -30, description: "PHARMACIE" }]);
|
||||
},
|
||||
{ expenses: 100, net: -100 },
|
||||
],
|
||||
[
|
||||
"a refund lowers its category",
|
||||
() => {
|
||||
insert("2026-10-05", "EPICERIE", -100, GROCERIES);
|
||||
insert("2026-10-08", "REMBOURSEMENT", 20, GROCERIES);
|
||||
},
|
||||
{ expenses: 80, net: -80 },
|
||||
],
|
||||
[
|
||||
"a balanced transfer nets to zero",
|
||||
() => {
|
||||
insert("2026-10-10", "PAIEMENT CARTE", -500, CARD);
|
||||
insert("2026-10-10", "PAIEMENT RECU", 500, CARD);
|
||||
},
|
||||
{ income: 0, expenses: 0, transfers: 0, net: 0 },
|
||||
],
|
||||
[
|
||||
"a one-leg transfer keeps its sign, in the net only",
|
||||
() => insert("2026-10-07", "PAIEMENT CARTE", -300, CARD),
|
||||
{ expenses: 0, transfers: -300, resultBeforeTransfers: 0, net: -300 },
|
||||
],
|
||||
[
|
||||
"a credit without a category is the uncategorized line, neither income nor expense",
|
||||
() => insert("2026-10-06", "VIREMENT INCONNU", 40, null),
|
||||
{ income: 0, expenses: 0, uncategorized: 40, resultBeforeTransfers: 40, net: 40 },
|
||||
],
|
||||
[
|
||||
"refunds above purchases make a negative expense",
|
||||
() => insert("2026-10-04", "REMBOURSEMENT BOUCHERIE", 50, BUTCHER),
|
||||
{ expenses: -50, resultBeforeTransfers: 50, net: 50 },
|
||||
],
|
||||
];
|
||||
|
||||
it.each(cases)("%s", async (_name, seed, expected) => {
|
||||
await seed();
|
||||
|
||||
const [month] = await getMonthlyTrends(FROM, TO);
|
||||
expect(month).toMatchObject(expected);
|
||||
expect(month.net).toBe(sumOfOctober());
|
||||
const r = compareResults(await getCompareMonthOverMonth(2026, 10));
|
||||
expect([
|
||||
r.income.monthCurrent,
|
||||
r.expense.monthCurrent,
|
||||
r.uncategorized.monthCurrent,
|
||||
r.transfer.monthCurrent,
|
||||
r.resultNet.monthCurrent,
|
||||
]).toEqual([month.income, month.expenses, month.uncategorized, month.transfers, month.net]);
|
||||
});
|
||||
});
|
||||
|
|
@ -28,40 +28,16 @@
|
|||
* an older file keeps the profile's lines whose category comes back. The
|
||||
* categories come back with their `i18n_key`.
|
||||
*
|
||||
* The services run as written on a real SQLite database: `node:sqlite` (built
|
||||
* into Node, no package), the schema of a new profile with its seed
|
||||
* (`consolidated_schema.sql`), foreign keys on, as under sqlx. `../services/db`
|
||||
* is replaced by the adapter of `split-offset-manual-flag.test.ts`, copied here
|
||||
* (#392 plans a shared harness): `select` and `execute` run the statement with
|
||||
* its `$N` bound by name, `execute` answers `rowsAffected` and `lastInsertId`,
|
||||
* `withTransaction` hands its callback the same handle, and `getDb()` throws
|
||||
* while a transaction runs, where the real lock, which is not reentrant, would
|
||||
* deadlock. A second database stands for a new profile.
|
||||
* The services run as written on a real SQLite database, the schema of a new
|
||||
* profile with its seed (`consolidated_schema.sql`), foreign keys on, as under
|
||||
* sqlx: `../services/db` is replaced by the shared harness
|
||||
* (`src/test/sqliteHarness.ts`, #392). A second database stands for a new
|
||||
* profile.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { readFileSync } from "fs";
|
||||
import { resolve } from "path";
|
||||
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
|
||||
import type { DatabaseSync, SQLInputValue } from "node:sqlite";
|
||||
|
||||
const fake = vi.hoisted(() => ({
|
||||
handle: null as unknown,
|
||||
inTransaction: false,
|
||||
}));
|
||||
|
||||
vi.mock("../services/db", () => ({
|
||||
getDb: vi.fn(async () => {
|
||||
if (fake.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
|
||||
return fake.handle;
|
||||
}),
|
||||
withTransaction: vi.fn(async (fn: (db: unknown) => Promise<unknown>) => {
|
||||
fake.inTransaction = true;
|
||||
try {
|
||||
return await fn(fake.handle);
|
||||
} finally {
|
||||
fake.inTransaction = false;
|
||||
}
|
||||
}),
|
||||
}));
|
||||
vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
|
||||
|
||||
// « Rétablir la sauvegarde » reads its file through `read_import_file`, and the
|
||||
// backup taken before the categories migration writes it (#520).
|
||||
|
|
@ -76,6 +52,7 @@ vi.mock("../services/logService", async (orig) => ({
|
|||
logWarn,
|
||||
}));
|
||||
|
||||
import { openProfileDb, useDb } from "../test/sqliteHarness";
|
||||
import { getSplitChildren, saveSplitAdjustment } from "../services/transactionService";
|
||||
import { linkTransfer, listAccountTransfers } from "../services/balance.service";
|
||||
import {
|
||||
|
|
@ -106,11 +83,6 @@ import { computeMigrationPlan } from "../services/categoryMappingService";
|
|||
import { applyMigration } from "../services/categoryMigrationService";
|
||||
import type { Profile } from "../services/profileService";
|
||||
|
||||
const SCHEMA = readFileSync(
|
||||
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
/** Categories of the seed of a new profile. */
|
||||
const GROCERIES = 1111; // « Épicerie régulière »
|
||||
const B = 1112; // « Boucherie & poissonnerie », where the split sends −50
|
||||
|
|
@ -129,37 +101,20 @@ const GROCERY_SPLIT = [
|
|||
type Mode = "transactions_with_categories" | "transactions_only";
|
||||
const MODES: Mode[] = ["transactions_with_categories", "transactions_only"];
|
||||
|
||||
/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */
|
||||
function adapter(db: DatabaseSync) {
|
||||
// tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name.
|
||||
const bind = (params?: unknown[]) =>
|
||||
Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue]));
|
||||
return {
|
||||
select: async (sql: string, params?: unknown[]) =>
|
||||
db.prepare(sql).all(bind(params)).map((row) => ({ ...row })),
|
||||
execute: async (sql: string, params?: unknown[]) => {
|
||||
const result = db.prepare(sql).run(bind(params));
|
||||
return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let opened: DatabaseSync[] = [];
|
||||
/** The profile the backups are taken from. */
|
||||
let profile: DatabaseSync;
|
||||
|
||||
/** A database with the schema of a new profile, foreign keys on. */
|
||||
function open(): DatabaseSync {
|
||||
const db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true });
|
||||
db.exec(SCHEMA);
|
||||
const db = openProfileDb();
|
||||
opened.push(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
/** Points the services at `db`. */
|
||||
function use(db: DatabaseSync): DatabaseSync {
|
||||
fake.handle = adapter(db);
|
||||
return db;
|
||||
return useDb(db);
|
||||
}
|
||||
|
||||
/** A transaction as an import writes it, with its category; its id. */
|
||||
|
|
@ -180,7 +135,6 @@ function imported(date: string, description: string, amount: number, categoryId:
|
|||
*/
|
||||
beforeEach(async () => {
|
||||
opened = [];
|
||||
fake.inTransaction = false;
|
||||
invoke.mockReset();
|
||||
logWarn.mockReset();
|
||||
profile = use(open());
|
||||
|
|
|
|||
|
|
@ -11,51 +11,23 @@
|
|||
* keeps its offset line with it. Without that, the keyword of the parent's
|
||||
* description sends the offset line alone to its category.
|
||||
*
|
||||
* The services run as written on a real SQLite database: `node:sqlite` (built
|
||||
* into Node, no package), the schema of a new profile with its seed
|
||||
* (`consolidated_schema.sql`), foreign keys on, as under sqlx. `../services/db`
|
||||
* is replaced by an adapter local to this file (#392 plans a shared harness):
|
||||
* `select` and `execute` run the statement with its `$N` bound by name,
|
||||
* `execute` answers `rowsAffected` and `lastInsertId`, `withTransaction` hands
|
||||
* its callback the same handle, and `getDb()` throws while a transaction runs,
|
||||
* where the real lock, which is not reentrant, would deadlock.
|
||||
* The services run as written on a real SQLite database, the schema of a new
|
||||
* profile with its seed (`consolidated_schema.sql`), foreign keys on, as under
|
||||
* sqlx: `../services/db` is replaced by the shared harness
|
||||
* (`src/test/sqliteHarness.ts`, #392).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { readFileSync } from "fs";
|
||||
import { resolve } from "path";
|
||||
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
|
||||
const fake = vi.hoisted(() => ({
|
||||
handle: null as unknown,
|
||||
inTransaction: false,
|
||||
}));
|
||||
|
||||
vi.mock("../services/db", () => ({
|
||||
getDb: vi.fn(async () => {
|
||||
if (fake.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
|
||||
return fake.handle;
|
||||
}),
|
||||
withTransaction: vi.fn(async (fn: (db: unknown) => Promise<unknown>) => {
|
||||
fake.inTransaction = true;
|
||||
try {
|
||||
return await fn(fake.handle);
|
||||
} finally {
|
||||
fake.inTransaction = false;
|
||||
}
|
||||
}),
|
||||
}));
|
||||
vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
|
||||
|
||||
import { openProfileDb, useDb } from "../test/sqliteHarness";
|
||||
import {
|
||||
autoCategorizeTransactions,
|
||||
saveSplitAdjustment,
|
||||
updateTransactionCategory,
|
||||
} from "../services/transactionService";
|
||||
|
||||
const SCHEMA = readFileSync(
|
||||
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
/** « Épicerie régulière », where the seed's `METRO` keyword sends a description that holds METRO. */
|
||||
const GROCERIES = 1111;
|
||||
/** « Boucherie & poissonnerie », the category the split sends −50 to. */
|
||||
|
|
@ -64,28 +36,10 @@ const DESCRIPTION = "EPICERIE METRO";
|
|||
/** The split of the reproduction of #454: −50 of the −120 to B, with the parent's description. */
|
||||
const ENTRIES = [{ category_id: B, amount: -50, description: DESCRIPTION }];
|
||||
|
||||
/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */
|
||||
function adapter(db: DatabaseSync) {
|
||||
// tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name.
|
||||
const bind = (params?: unknown[]) =>
|
||||
Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue]));
|
||||
return {
|
||||
select: async (sql: string, params?: unknown[]) =>
|
||||
db.prepare(sql).all(bind(params)).map((row) => ({ ...row })),
|
||||
execute: async (sql: string, params?: unknown[]) => {
|
||||
const result = db.prepare(sql).run(bind(params));
|
||||
return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let db: DatabaseSync;
|
||||
|
||||
beforeEach(() => {
|
||||
db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true });
|
||||
db.exec(SCHEMA);
|
||||
fake.handle = adapter(db);
|
||||
fake.inTransaction = false;
|
||||
db = useDb(openProfileDb());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
|
|
|||
|
|
@ -75,11 +75,13 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
|
|||
const typeLabels: Record<SectionType, string> = {
|
||||
expense: t("budget.expenses"),
|
||||
income: t("budget.income"),
|
||||
uncategorized: t("reports.uncategorized"),
|
||||
transfer: t("budget.transfers"),
|
||||
};
|
||||
const typeTotalKeys: Record<SectionType, string> = {
|
||||
expense: "budget.totalExpenses",
|
||||
income: "budget.totalIncome",
|
||||
uncategorized: "reports.uncategorized",
|
||||
transfer: "budget.totalTransfers",
|
||||
};
|
||||
|
||||
|
|
@ -94,10 +96,11 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
|
|||
|
||||
// Income-statement result lines (Issue #277): income + expense (expense
|
||||
// already arrives signed negative in BudgetVsActualRow — see
|
||||
// budgetVsActualResults.ts), then the net after adding transfers. Replaces
|
||||
// the old flat grand total row.
|
||||
// budgetVsActualResults.ts) + the uncategorized line, then the net after
|
||||
// adding transfers. Replaces the old flat grand total row. The uncategorized
|
||||
// row forms no section: one line, before the result before transfers (#392).
|
||||
const results = computeResults(data);
|
||||
const nonTransferSections = sections.filter((s) => s.type !== "transfer");
|
||||
const nonTransferSections = sections.filter((s) => s.type !== "transfer" && s.type !== "uncategorized");
|
||||
const transferSection = sections.find((s) => s.type === "transfer");
|
||||
|
||||
const renderSection = (section: { type: SectionType; label: string; rows: BudgetVsActualRow[] }) => {
|
||||
|
|
@ -212,6 +215,25 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
|
|||
);
|
||||
};
|
||||
|
||||
// The uncategorized line (D4, #392): actuals without a budget, neither income
|
||||
// nor expense, counted in both results; uncoloured.
|
||||
const renderUncategorizedRow = (tot: Totals) => {
|
||||
const rowBg = "bg-[color-mix(in_srgb,var(--muted)_40%,var(--card))]";
|
||||
return (
|
||||
<tr key="uncategorized" className={`border-b border-[var(--border)] font-semibold text-sm ${rowBg}`}>
|
||||
<td className={`px-3 py-2.5 sticky left-0 z-10 ${rowBg}`}>{t("reports.uncategorized")}</td>
|
||||
<td className="text-right px-3 py-2.5 border-l border-[var(--border)]/50">{cadFormatter(tot.monthActual)}</td>
|
||||
<td className="text-right px-3 py-2.5">{cadFormatter(tot.monthBudget)}</td>
|
||||
<td className="text-right px-3 py-2.5">{cadFormatter(tot.monthVariation)}</td>
|
||||
<td className="text-right px-3 py-2.5">{pctFormatter(pct(tot.monthVariation, tot.monthBudget))}</td>
|
||||
<td className="text-right px-3 py-2.5 border-l border-[var(--border)]/50">{cadFormatter(tot.ytdActual)}</td>
|
||||
<td className="text-right px-3 py-2.5">{cadFormatter(tot.ytdBudget)}</td>
|
||||
<td className="text-right px-3 py-2.5">{cadFormatter(tot.ytdVariation)}</td>
|
||||
<td className="text-right px-3 py-2.5">{pctFormatter(pct(tot.ytdVariation, tot.ytdBudget))}</td>
|
||||
</tr>
|
||||
);
|
||||
};
|
||||
|
||||
// A result line (before-transfers subtotal or the net total). Every cell is
|
||||
// coloured by its own sign — a surplus is green, a deficit red — mirroring
|
||||
// ComparePeriodTable.renderResultRow (unlike normal rows, which only colour
|
||||
|
|
@ -314,9 +336,11 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
|
|||
</thead>
|
||||
<tbody>
|
||||
{nonTransferSections.map(renderSection)}
|
||||
{/* Operating result (income + expense), shown before the transfers
|
||||
section only when transfers exist — otherwise it equals the net
|
||||
total below and would just be noise (mirrors ComparePeriodTable). */}
|
||||
{results.hasUncategorized && renderUncategorizedRow(results.uncategorized)}
|
||||
{/* Operating result (income + expense + uncategorized), shown before
|
||||
the transfers section only when transfers exist — otherwise it
|
||||
equals the net total below and would just be noise (mirrors
|
||||
ComparePeriodTable). */}
|
||||
{results.hasTransfers &&
|
||||
renderResultRow("reports.compare.resultBeforeTransfers", results.resultBefore, false)}
|
||||
{transferSection && renderSection(transferSection)}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { useTranslation } from "react-i18next";
|
|||
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from "recharts";
|
||||
import type { CategoryZoomChild } from "../../shared/types";
|
||||
import { ChartPatternDefs, getPatternFill } from "../../utils/chartPatterns";
|
||||
import { donutParts } from "./donutParts";
|
||||
|
||||
export interface CategoryDonutChartProps {
|
||||
byChild: CategoryZoomChild[];
|
||||
|
|
@ -15,58 +16,70 @@ export default function CategoryDonutChart({
|
|||
centerValue,
|
||||
}: CategoryDonutChartProps) {
|
||||
const { t } = useTranslation();
|
||||
// Only the positive parts can be drawn; the negative ones are named by count (D7, #392).
|
||||
const { parts, negativeCount } = donutParts(byChild);
|
||||
const omitted =
|
||||
negativeCount > 0 ? (
|
||||
<p className="text-xs text-[var(--muted-foreground)] text-center mt-2 not-italic">
|
||||
{t("reports.category.donutOmitted", { count: negativeCount })}
|
||||
</p>
|
||||
) : null;
|
||||
|
||||
if (byChild.length === 0) {
|
||||
if (parts.length === 0) {
|
||||
return (
|
||||
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-6 text-center text-[var(--muted-foreground)] italic">
|
||||
{t("reports.empty.noData")}
|
||||
{omitted}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-4 relative">
|
||||
<ResponsiveContainer width="100%" height={240}>
|
||||
<PieChart>
|
||||
<ChartPatternDefs
|
||||
prefix="cat-donut"
|
||||
categories={byChild.map((c, index) => ({ color: c.categoryColor, index }))}
|
||||
/>
|
||||
<Pie
|
||||
data={byChild}
|
||||
dataKey="total"
|
||||
nameKey="categoryName"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={55}
|
||||
outerRadius={95}
|
||||
paddingAngle={2}
|
||||
>
|
||||
{byChild.map((entry, index) => (
|
||||
<Cell
|
||||
key={entry.categoryId}
|
||||
fill={getPatternFill("cat-donut", index, entry.categoryColor)}
|
||||
/>
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip
|
||||
formatter={(value) =>
|
||||
typeof value === "number"
|
||||
? new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" }).format(value)
|
||||
: String(value)
|
||||
}
|
||||
contentStyle={{
|
||||
backgroundColor: "var(--card)",
|
||||
border: "1px solid var(--border)",
|
||||
borderRadius: "0.5rem",
|
||||
}}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
|
||||
<span className="text-xs text-[var(--muted-foreground)]">{centerLabel}</span>
|
||||
<span className="text-lg font-bold">{centerValue}</span>
|
||||
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-4">
|
||||
<div className="relative">
|
||||
<ResponsiveContainer width="100%" height={240}>
|
||||
<PieChart>
|
||||
<ChartPatternDefs
|
||||
prefix="cat-donut"
|
||||
categories={parts.map((c, index) => ({ color: c.categoryColor, index }))}
|
||||
/>
|
||||
<Pie
|
||||
data={parts}
|
||||
dataKey="total"
|
||||
nameKey="categoryName"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={55}
|
||||
outerRadius={95}
|
||||
paddingAngle={2}
|
||||
>
|
||||
{parts.map((entry, index) => (
|
||||
<Cell
|
||||
key={entry.categoryId}
|
||||
fill={getPatternFill("cat-donut", index, entry.categoryColor)}
|
||||
/>
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip
|
||||
formatter={(value) =>
|
||||
typeof value === "number"
|
||||
? new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" }).format(value)
|
||||
: String(value)
|
||||
}
|
||||
contentStyle={{
|
||||
backgroundColor: "var(--card)",
|
||||
border: "1px solid var(--border)",
|
||||
borderRadius: "0.5rem",
|
||||
}}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
|
||||
<span className="text-xs text-[var(--muted-foreground)]">{centerLabel}</span>
|
||||
<span className="text-lg font-bold">{centerValue}</span>
|
||||
</div>
|
||||
</div>
|
||||
{omitted}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -63,6 +63,9 @@ export default function CategoryOverTimeChart({
|
|||
// (Issue #264 sidecar) so the stacked series never explode to 80+ layers. The
|
||||
// full, uncapped hierarchy lives in `data.tree` and drives the table instead.
|
||||
const visibleCategories = data.categories.filter((name) => !hiddenCategories.has(name));
|
||||
// The series of the rows without a category (its id is null) is keyed by the
|
||||
// SQL's 'Uncategorized': show the translated label instead (#392).
|
||||
const labelOf = (name: string) => (data.categoryIds[name] === null ? t("reports.uncategorized") : name);
|
||||
const categoryEntries = visibleCategories.map((name, index) => ({
|
||||
name,
|
||||
color: data.colors[name],
|
||||
|
|
@ -108,7 +111,7 @@ export default function CategoryOverTimeChart({
|
|||
/>
|
||||
<Tooltip
|
||||
formatter={(value: unknown, name: unknown) => {
|
||||
if (hoveredCategory && name !== hoveredCategory) return [null, null];
|
||||
if (hoveredCategory && name !== labelOf(hoveredCategory)) return [null, null];
|
||||
return [cadFormatter(Number(value) || 0), String(name)];
|
||||
}}
|
||||
labelFormatter={(label) => formatMonth(String(label))}
|
||||
|
|
@ -147,7 +150,7 @@ export default function CategoryOverTimeChart({
|
|||
className="inline-flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-[var(--muted)] text-[var(--muted-foreground)] hover:bg-[var(--border)] transition-colors"
|
||||
>
|
||||
<Eye size={12} />
|
||||
{name}
|
||||
{labelOf(name)}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
|
|
@ -160,9 +163,12 @@ export default function CategoryOverTimeChart({
|
|||
)}
|
||||
|
||||
<div onContextMenu={handleContextMenu}>
|
||||
{/* `stackOffset="sign"`: a negative value (an expense whose refunds
|
||||
exceed its purchases, a one-leg transfer) stacks below zero, in
|
||||
bars as in areas (D7, #392). */}
|
||||
<ResponsiveContainer width="100%" height={400}>
|
||||
{chartType === "area" ? (
|
||||
<AreaChart data={data.data} margin={{ top: 10, right: 10, left: 10, bottom: 0 }}>
|
||||
<AreaChart data={data.data} stackOffset="sign" margin={{ top: 10, right: 10, left: 10, bottom: 0 }}>
|
||||
{patternDefs}
|
||||
{commonAxes}
|
||||
{categoryEntries.map((c) => (
|
||||
|
|
@ -170,6 +176,7 @@ export default function CategoryOverTimeChart({
|
|||
key={c.name}
|
||||
type="monotone"
|
||||
dataKey={c.name}
|
||||
name={labelOf(c.name)}
|
||||
stackId="1"
|
||||
stroke={c.color}
|
||||
fill={getPatternFill(patternPrefix, c.index, c.color)}
|
||||
|
|
@ -181,13 +188,14 @@ export default function CategoryOverTimeChart({
|
|||
))}
|
||||
</AreaChart>
|
||||
) : (
|
||||
<BarChart data={data.data} margin={{ top: 10, right: 10, left: 10, bottom: 0 }}>
|
||||
<BarChart data={data.data} stackOffset="sign" margin={{ top: 10, right: 10, left: 10, bottom: 0 }}>
|
||||
{patternDefs}
|
||||
{commonAxes}
|
||||
{categoryEntries.map((c) => (
|
||||
<Bar
|
||||
key={c.name}
|
||||
dataKey={c.name}
|
||||
name={labelOf(c.name)}
|
||||
stackId="stack"
|
||||
fill={getPatternFill(patternPrefix, c.index, c.color)}
|
||||
fillOpacity={hoveredCategory === null || hoveredCategory === c.name ? 1 : 0.2}
|
||||
|
|
@ -215,14 +223,14 @@ export default function CategoryOverTimeChart({
|
|||
<ChartContextMenu
|
||||
x={contextMenu.x}
|
||||
y={contextMenu.y}
|
||||
categoryName={contextMenu.name}
|
||||
categoryName={labelOf(contextMenu.name)}
|
||||
onHide={() => onToggleHidden(contextMenu.name)}
|
||||
onViewDetails={() => {
|
||||
const color = data.colors[contextMenu.name] || "#9ca3af";
|
||||
const categoryId = data.categoryIds[contextMenu.name] ?? null;
|
||||
onViewDetails({
|
||||
category_id: categoryId,
|
||||
category_name: contextMenu.name,
|
||||
category_name: labelOf(contextMenu.name),
|
||||
category_color: color,
|
||||
total: 0,
|
||||
});
|
||||
|
|
|
|||
80
src/components/reports/CategoryOverTimeChart.wiring.test.ts
Normal file
80
src/components/reports/CategoryOverTimeChart.wiring.test.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// CategoryOverTimeChart — negative amounts and the uncategorized series (#392).
|
||||
//
|
||||
// Recharts draws nothing under a static render, so the stacking cannot be read
|
||||
// from the markup: the chart runs as a plain function under the shared hook
|
||||
// harness (src/test/hookHarness.ts), and the test reads the props it hands to
|
||||
// Recharts. With `stackOffset="sign"`, a negative value (an expense whose
|
||||
// refunds exceed its purchases, a one-leg transfer) stacks below zero instead
|
||||
// of overlapping the positive ones (D7); what that looks like was checked on
|
||||
// screenshots (PR of #392).
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { AreaChart, Area, Bar, BarChart } from "recharts";
|
||||
|
||||
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, texts } from "../../test/elementTree";
|
||||
import CategoryOverTimeChart, { type CategoryOverTimeChartType } from "./CategoryOverTimeChart";
|
||||
import type { CategoryOverTimeData } from "../../shared/types";
|
||||
|
||||
const harness = hookHarness();
|
||||
|
||||
const G = "Épicerie régulière";
|
||||
const U = "Uncategorized"; // the SQL's key of the rows without a category
|
||||
const T = "Paiement carte crédit";
|
||||
|
||||
const DATA: CategoryOverTimeData = {
|
||||
categories: [G, U, T],
|
||||
data: [{ month: "2026-10", [G]: 80, [U]: 40, [T]: -300 }],
|
||||
colors: { [G]: "#ea580c", [U]: "#9ca3af", [T]: "#16a34a" },
|
||||
categoryIds: { [G]: 1111, [U]: null, [T]: 1971 },
|
||||
types: { [G]: "expense", [U]: "uncategorized", [T]: "transfer" },
|
||||
tree: [],
|
||||
};
|
||||
|
||||
const render = (chartType: CategoryOverTimeChartType, hidden: string[] = []) =>
|
||||
harness.render(() =>
|
||||
CategoryOverTimeChart({
|
||||
data: DATA,
|
||||
hiddenCategories: new Set(hidden),
|
||||
onToggleHidden: () => {},
|
||||
onShowAll: () => {},
|
||||
onViewDetails: () => {},
|
||||
chartType,
|
||||
}),
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
harness.clear();
|
||||
});
|
||||
|
||||
describe("CategoryOverTimeChart", () => {
|
||||
it("stacks a negative value below zero, in bars", () => {
|
||||
const [chart] = find(render("bar"), (el) => el.type === BarChart);
|
||||
expect(chart.props.stackOffset).toBe("sign");
|
||||
});
|
||||
|
||||
it("stacks a negative value below zero, in areas", () => {
|
||||
const [chart] = find(render("area"), (el) => el.type === AreaChart);
|
||||
expect(chart.props.stackOffset).toBe("sign");
|
||||
});
|
||||
|
||||
it("names the series of the rows without a category from i18n, its data key unchanged", () => {
|
||||
for (const [type, series] of [
|
||||
["bar", Bar],
|
||||
["area", Area],
|
||||
] as const) {
|
||||
const names = find(render(type), (el) => el.type === series).map((el) => [el.props.dataKey, el.props.name]);
|
||||
expect(names).toEqual([
|
||||
[G, G],
|
||||
[U, "t(reports.uncategorized)"],
|
||||
[T, T],
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("names a hidden uncategorized series from i18n in its chip", () => {
|
||||
expect(texts(render("bar", [U]))).toContain("t(reports.uncategorized)");
|
||||
});
|
||||
});
|
||||
|
|
@ -65,7 +65,7 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
|
|||
// Consumes the id-keyed tree (every category, no top-N/"Other"): subtotals and
|
||||
// the result lines are exact, and homonym categories never collide.
|
||||
const analysis = computeOverTimeResults(data);
|
||||
const { months, hasTransfers, net, beforeTransfers } = analysis;
|
||||
const { months, hasTransfers, hasUncategorized, uncategorized, net, beforeTransfers } = analysis;
|
||||
const { nonTransferSections, transferSection } = groupOverTimeSections(analysis, data.tree);
|
||||
const colSpan = months.length + 2;
|
||||
|
||||
|
|
@ -176,6 +176,24 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
|
|||
</Fragment>
|
||||
);
|
||||
|
||||
// The uncategorized line (D4, #392): neither income nor expense, counted in
|
||||
// both results, shown on one uncoloured line like a section subtotal.
|
||||
const renderUncategorizedRow = (series: OverTimeSeries) => (
|
||||
<tr className="border-b border-[var(--border)] bg-[color-mix(in_srgb,var(--muted)_40%,var(--card))] font-semibold">
|
||||
<td className="px-3 py-2.5 sticky left-0 bg-[color-mix(in_srgb,var(--muted)_40%,var(--card))] z-10">
|
||||
{t("reports.uncategorized")}
|
||||
</td>
|
||||
{months.map((month) => (
|
||||
<td key={month} className="text-right px-3 py-2.5 tabular-nums">
|
||||
{series.monthly[month] ? cadFormatter(series.monthly[month]) : "—"}
|
||||
</td>
|
||||
))}
|
||||
<td className="text-right px-3 py-2.5 border-l border-[var(--border)]/50 tabular-nums">
|
||||
{cadFormatter(series.total)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
|
||||
// A result line (before-transfers subtotal or the net bottom line). Amounts are
|
||||
// coloured by sign (surplus green / deficit red). Computed from the raw tree,
|
||||
// so folding groups never moves these figures.
|
||||
|
|
@ -239,9 +257,11 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
|
|||
</thead>
|
||||
<tbody>
|
||||
{nonTransferSections.map(renderSection)}
|
||||
{/* Operating result (revenues − expenses), interleaved before the
|
||||
transfers section only when transfers exist — otherwise it equals
|
||||
the net total below and would just be noise. */}
|
||||
{hasUncategorized && renderUncategorizedRow(uncategorized)}
|
||||
{/* Operating result (revenues − expenses + uncategorized),
|
||||
interleaved before the transfers section only when transfers
|
||||
exist — otherwise it equals the net total below and would just
|
||||
be noise. */}
|
||||
{hasTransfers && renderResultRow("reports.compare.resultBeforeTransfers", beforeTransfers, false)}
|
||||
{transferSection && renderSection(transferSection)}
|
||||
{/* Bottom line: result after netting transfers. */}
|
||||
|
|
|
|||
|
|
@ -110,11 +110,13 @@ export default function ComparePeriodTable({
|
|||
const sectionLabels: Record<SectionType, string> = {
|
||||
expense: t("reports.compare.sections.expenses"),
|
||||
income: t("reports.compare.sections.income"),
|
||||
uncategorized: t("reports.uncategorized"),
|
||||
transfer: t("reports.compare.sections.transfers"),
|
||||
};
|
||||
const sectionTotalKeys: Record<SectionType, string> = {
|
||||
expense: "reports.compare.totalExpenses",
|
||||
income: "reports.compare.totalIncome",
|
||||
uncategorized: "reports.uncategorized",
|
||||
transfer: "reports.compare.totalTransfers",
|
||||
};
|
||||
const sections: { type: SectionType; rows: CategoryDelta[] }[] = [];
|
||||
|
|
@ -128,11 +130,12 @@ export default function ComparePeriodTable({
|
|||
sections[sections.length - 1].rows.push(row);
|
||||
}
|
||||
|
||||
// Income-statement result lines (Issue #253): revenues − expenses, then the
|
||||
// net after transfers. Replaces the old flat grand total, which is meaningless
|
||||
// once revenues and (ABS) expenses share one table.
|
||||
// Income-statement result lines (Issue #253): revenues − expenses + the
|
||||
// uncategorized line, then the net after transfers (ADR 0026). Replaces the
|
||||
// old flat grand total. The uncategorized rows form no section: one line,
|
||||
// between the expenses and the result before transfers (#392).
|
||||
const results = computeResults(rows);
|
||||
const nonTransferSections = sections.filter((s) => s.type !== "transfer");
|
||||
const nonTransferSections = sections.filter((s) => s.type !== "transfer" && s.type !== "uncategorized");
|
||||
const transferSection = sections.find((s) => s.type === "transfer");
|
||||
|
||||
const renderSection = (section: { type: SectionType; rows: CategoryDelta[] }) => {
|
||||
|
|
@ -294,6 +297,26 @@ export default function ComparePeriodTable({
|
|||
);
|
||||
};
|
||||
|
||||
// The uncategorized line (D4, #392): neither income nor expense, counted in
|
||||
// both results. Its deltas stay uncoloured — a rise is neither good nor bad.
|
||||
const renderUncategorizedRow = (tot: Totals) => {
|
||||
const rowBg = "bg-[color-mix(in_srgb,var(--muted)_40%,var(--card))]";
|
||||
const cell = "text-right px-3 py-2.5 tabular-nums";
|
||||
return (
|
||||
<tr key="uncategorized" className={`border-b border-[var(--border)] font-semibold text-sm ${rowBg}`}>
|
||||
<td className={`px-3 py-2.5 sticky left-0 z-10 ${rowBg}`}>{t("reports.uncategorized")}</td>
|
||||
<td className={`${cell} border-l border-[var(--border)]/50`}>{formatCurrency(tot.monthCurrent, lang)}</td>
|
||||
<td className={cell}>{formatCurrency(tot.monthPrevious, lang)}</td>
|
||||
<td className={cell}>{formatSignedCurrency(tot.monthDelta, lang)}</td>
|
||||
<td className={cell}>{formatPct(pct(tot.monthDelta, tot.monthPrevious), lang)}</td>
|
||||
<td className={`${cell} border-l border-[var(--border)]/50`}>{formatCurrency(tot.ytdCurrent, lang)}</td>
|
||||
<td className={cell}>{formatCurrency(tot.ytdPrevious, lang)}</td>
|
||||
<td className={cell}>{formatSignedCurrency(tot.ytdDelta, lang)}</td>
|
||||
<td className={cell}>{formatPct(pct(tot.ytdDelta, tot.ytdPrevious), lang)}</td>
|
||||
</tr>
|
||||
);
|
||||
};
|
||||
|
||||
// A result line (before-transfers subtotal or the net total). Higher is always
|
||||
// better here: amounts are coloured by sign (surplus green / deficit red) and
|
||||
// deltas by improvement.
|
||||
|
|
@ -430,9 +453,11 @@ export default function ComparePeriodTable({
|
|||
) : (
|
||||
<>
|
||||
{nonTransferSections.map(renderSection)}
|
||||
{/* Operating result (revenues − expenses), shown before the
|
||||
transfers section only when transfers exist — otherwise it
|
||||
equals the net total below and would just be noise. */}
|
||||
{results.hasUncategorized && renderUncategorizedRow(results.uncategorized)}
|
||||
{/* Operating result (revenues − expenses + uncategorized), shown
|
||||
before the transfers section only when transfers exist —
|
||||
otherwise it equals the net total below and would just be
|
||||
noise. */}
|
||||
{results.hasTransfers &&
|
||||
renderResultRow(
|
||||
"reports.compare.resultBeforeTransfers",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useTranslation } from "react-i18next";
|
||||
import type { MonthlyTrendItem } from "../../shared/types";
|
||||
import { EMPTY_STATEMENT, addStatements } from "../../utils/incomeStatement";
|
||||
|
||||
const cadFormatter = (value: number) =>
|
||||
new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(value);
|
||||
|
|
@ -25,10 +26,11 @@ export default function MonthlyTrendsTable({ data }: MonthlyTrendsTableProps) {
|
|||
);
|
||||
}
|
||||
|
||||
const totals = data.reduce(
|
||||
(acc, row) => ({ income: acc.income + row.income, expenses: acc.expenses + row.expenses }),
|
||||
{ income: 0, expenses: 0 },
|
||||
);
|
||||
// Each month is an income statement (#392, ADR 0026): « Net » is the net
|
||||
// result, every amount of the month, so the uncategorized line and the
|
||||
// transfers it holds beyond income − expenses have their own columns (D5).
|
||||
const totals = data.reduce(addStatements, EMPTY_STATEMENT);
|
||||
const signColor = (value: number) => (value >= 0 ? "text-[var(--positive)]" : "text-[var(--negative)]");
|
||||
|
||||
return (
|
||||
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl overflow-hidden">
|
||||
|
|
@ -45,6 +47,12 @@ export default function MonthlyTrendsTable({ data }: MonthlyTrendsTableProps) {
|
|||
<th className="text-right px-3 py-2 font-medium text-[var(--muted-foreground)] bg-[var(--card)]">
|
||||
{t("dashboard.expenses")}
|
||||
</th>
|
||||
<th className="text-right px-3 py-2 font-medium text-[var(--muted-foreground)] bg-[var(--card)]">
|
||||
{t("reports.uncategorized")}
|
||||
</th>
|
||||
<th className="text-right px-3 py-2 font-medium text-[var(--muted-foreground)] bg-[var(--card)]">
|
||||
{t("reports.compare.sections.transfers")}
|
||||
</th>
|
||||
<th className="text-right px-3 py-2 font-medium text-[var(--muted-foreground)] bg-[var(--card)]">
|
||||
{t("dashboard.net")}
|
||||
</th>
|
||||
|
|
@ -56,18 +64,18 @@ export default function MonthlyTrendsTable({ data }: MonthlyTrendsTableProps) {
|
|||
<td className="px-3 py-1.5">{formatMonth(row.month)}</td>
|
||||
<td className="text-right px-3 py-1.5 text-[var(--positive)]">{cadFormatter(row.income)}</td>
|
||||
<td className="text-right px-3 py-1.5 text-[var(--negative)]">{cadFormatter(row.expenses)}</td>
|
||||
<td className={`text-right px-3 py-1.5 ${row.income - row.expenses >= 0 ? "text-[var(--positive)]" : "text-[var(--negative)]"}`}>
|
||||
{cadFormatter(row.income - row.expenses)}
|
||||
</td>
|
||||
<td className="text-right px-3 py-1.5">{cadFormatter(row.uncategorized)}</td>
|
||||
<td className="text-right px-3 py-1.5">{cadFormatter(row.transfers)}</td>
|
||||
<td className={`text-right px-3 py-1.5 ${signColor(row.net)}`}>{cadFormatter(row.net)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr className="border-t-2 border-[var(--border)] font-bold text-sm bg-[var(--muted)]/20">
|
||||
<td className="px-3 py-3">{t("common.total")}</td>
|
||||
<td className="text-right px-3 py-3 text-[var(--positive)]">{cadFormatter(totals.income)}</td>
|
||||
<td className="text-right px-3 py-3 text-[var(--negative)]">{cadFormatter(totals.expenses)}</td>
|
||||
<td className={`text-right px-3 py-3 ${totals.income - totals.expenses >= 0 ? "text-[var(--positive)]" : "text-[var(--negative)]"}`}>
|
||||
{cadFormatter(totals.income - totals.expenses)}
|
||||
</td>
|
||||
<td className="text-right px-3 py-3">{cadFormatter(totals.uncategorized)}</td>
|
||||
<td className="text-right px-3 py-3">{cadFormatter(totals.transfers)}</td>
|
||||
<td className={`text-right px-3 py-3 ${signColor(totals.net)}`}>{cadFormatter(totals.net)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { computeResults, sumLeaves } from "./budgetVsActualResults";
|
|||
// user-entered budget negated to match via signFor); income/transfer stay
|
||||
// however they naturally sum (positive for income, signed net for transfer).
|
||||
function leaf(
|
||||
type: "expense" | "income" | "transfer",
|
||||
type: "expense" | "income" | "transfer" | "uncategorized",
|
||||
monthActual: number,
|
||||
monthBudget: number,
|
||||
ytdActual = monthActual,
|
||||
|
|
@ -88,4 +88,20 @@ describe("computeResults — income-statement roll-up (Issue #277)", () => {
|
|||
expect(t.monthActual).toBe(-100);
|
||||
expect(t.monthBudget).toBe(-50);
|
||||
});
|
||||
|
||||
it("counts the uncategorized line in both results, without a budget (#392, D4)", () => {
|
||||
const r = computeResults([
|
||||
leaf("income", 1000, 1000),
|
||||
leaf("expense", -30, -130),
|
||||
{ ...leaf("uncategorized", 40, 0), category_id: null },
|
||||
leaf("transfer", -300, 0),
|
||||
]);
|
||||
expect(r.uncategorized.monthActual).toBe(40);
|
||||
expect(r.uncategorized.monthBudget).toBe(0);
|
||||
// 1000 + (−30) + 40, then the one-leg transfer.
|
||||
expect(r.resultBefore.monthActual).toBe(1010);
|
||||
expect(r.resultNet.monthActual).toBe(710);
|
||||
expect(r.resultBefore.monthBudget).toBe(870);
|
||||
expect(r.hasUncategorized).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { BudgetVsActualRow } from "../../shared/types";
|
||||
import type { BudgetVsActualRow, ReportSection } from "../../shared/types";
|
||||
|
||||
export type SectionType = "expense" | "income" | "transfer";
|
||||
export type SectionType = ReportSection;
|
||||
|
||||
/** Aggregate of the 6 budget-vs-actual figures across a set of leaf rows. */
|
||||
export interface Totals {
|
||||
|
|
@ -59,37 +59,49 @@ function add(a: Totals, b: Totals): Totals {
|
|||
export interface BudgetVsActualResults {
|
||||
income: Totals;
|
||||
expense: Totals;
|
||||
/** The uncategorized line (D4, #392): actuals only, in the result. */
|
||||
uncategorized: Totals;
|
||||
transfer: Totals;
|
||||
/** Income + expense: the operating result, before transfers. */
|
||||
/** Income + expense + uncategorized: the operating result, before transfers. */
|
||||
resultBefore: Totals;
|
||||
/** resultBefore + transfers: the bottom-line total. */
|
||||
resultNet: Totals;
|
||||
hasTransfers: boolean;
|
||||
hasUncategorized: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Income-statement roll-up for the budget-vs-actual report (Issue #277).
|
||||
*
|
||||
* Mirrors `compareResults.computeResults`, with one key sign difference: BVA
|
||||
* amounts already arrive signed the "accounting" way rather than ABS'd to
|
||||
* positive magnitudes. `getBudgetVsActualData` computes `monthActual`/
|
||||
* `ytdActual` as the raw (unsigned-by-us) `SUM(transactions.amount)` — negative
|
||||
* for expense categories, since expense transactions are stored as negative
|
||||
* amounts throughout this app (see reportService/dashboardService `amount < 0`
|
||||
* conventions) — and negates the user-entered (positive) budget figure to
|
||||
* match via `signFor`. So expense totals here are already ≤ 0, and the
|
||||
* operating result is a straight ADD of income + expense (not a subtraction
|
||||
* like the real-vs-real compare, whose expense figures are ABS'd positive
|
||||
* magnitudes). The net just adds the transfer total on top.
|
||||
* amounts stay signed the "accounting" way (ADR 0026). `getBudgetVsActualData`
|
||||
* computes `monthActual`/`ytdActual` as the signed balance of the category —
|
||||
* negative for an expense category that spent, since expense transactions are
|
||||
* stored as negative amounts throughout this app — and negates the
|
||||
* user-entered (positive) budget figure to match via `signFor`. So expense
|
||||
* totals here are ≤ 0 when the category spent, and the operating result is a
|
||||
* straight ADD of income + expense + uncategorized (not a subtraction like the
|
||||
* real-vs-real compare, whose expense figures show the spending). The net
|
||||
* just adds the transfer total on top.
|
||||
*/
|
||||
export function computeResults(rows: BudgetVsActualRow[]): BudgetVsActualResults {
|
||||
const byType = (type: SectionType): Totals =>
|
||||
sumLeaves(rows.filter((r) => r.category_type === type));
|
||||
const income = byType("income");
|
||||
const expense = byType("expense");
|
||||
const uncategorized = byType("uncategorized");
|
||||
const transfer = byType("transfer");
|
||||
const resultBefore = add(income, expense);
|
||||
const resultBefore = add(add(income, expense), uncategorized);
|
||||
const resultNet = add(resultBefore, transfer);
|
||||
const hasTransfers = rows.some((r) => r.category_type === "transfer" && !r.is_parent);
|
||||
return { income, expense, transfer, resultBefore, resultNet, hasTransfers };
|
||||
const has = (type: SectionType) => rows.some((r) => r.category_type === type && !r.is_parent);
|
||||
return {
|
||||
income,
|
||||
expense,
|
||||
uncategorized,
|
||||
transfer,
|
||||
resultBefore,
|
||||
resultNet,
|
||||
hasTransfers: has("transfer"),
|
||||
hasUncategorized: has("uncategorized"),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ export interface KpiCardProps {
|
|||
deltaIsBadWhenUp?: boolean;
|
||||
/** Optional help text shown on hover of a (?) icon next to the title. */
|
||||
tooltip?: string;
|
||||
/** Optional line under the value, e.g. what « Solde net » holds beyond income − expenses (#392). */
|
||||
note?: string;
|
||||
}
|
||||
|
||||
function formatCurrency(amount: number, language: string): string {
|
||||
|
|
@ -106,6 +108,7 @@ export default function KpiCard({
|
|||
format,
|
||||
deltaIsBadWhenUp = false,
|
||||
tooltip,
|
||||
note,
|
||||
}: KpiCardProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const language = i18n.language;
|
||||
|
|
@ -130,6 +133,7 @@ export default function KpiCard({
|
|||
<div className="text-2xl font-bold tabular-nums text-[var(--foreground)]">
|
||||
{kpi.current === null ? "—" : formatValue(kpi.current, format, language)}
|
||||
</div>
|
||||
{note && <div className="-mt-2 text-xs text-[var(--muted-foreground)]">{note}</div>}
|
||||
<KpiSparkline data={kpi.sparkline} />
|
||||
<div className="flex items-start justify-between gap-2 pt-1 border-t border-[var(--border)]">
|
||||
<DeltaBadge
|
||||
|
|
|
|||
30
src/components/reports/cards/netNote.test.ts
Normal file
30
src/components/reports/cards/netNote.test.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { markedT } from "../../../test/i18nMock";
|
||||
import { netNote } from "./netNote";
|
||||
|
||||
// The note under « Solde net » (D5, #392): what the net result holds beyond
|
||||
// income − expenses.
|
||||
|
||||
const nbsp = (s: string) => s.replace(/[ ]/g, " ");
|
||||
|
||||
describe("netNote", () => {
|
||||
it("names the uncategorized line and the transfers when both are non-zero", () => {
|
||||
expect(nbsp(netNote(markedT, "fr", { uncategorized: 40, transfers: -300 })!)).toBe(
|
||||
"t(reports.cartes.netNote.both[uncategorized=40 $,transfers=-300 $])",
|
||||
);
|
||||
});
|
||||
|
||||
it("names the one part that is non-zero", () => {
|
||||
expect(nbsp(netNote(markedT, "en", { uncategorized: 40, transfers: 0 })!)).toBe(
|
||||
"t(reports.cartes.netNote.uncategorized[amount=$40])",
|
||||
);
|
||||
expect(nbsp(netNote(markedT, "en", { uncategorized: 0, transfers: -300 })!)).toBe(
|
||||
"t(reports.cartes.netNote.transfers[amount=-$300])",
|
||||
);
|
||||
});
|
||||
|
||||
it("is absent when both parts are zero, or round to zero as the card shows them", () => {
|
||||
expect(netNote(markedT, "fr", { uncategorized: 0, transfers: 0 })).toBeUndefined();
|
||||
expect(netNote(markedT, "fr", { uncategorized: 0.4, transfers: -0.2 })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
33
src/components/reports/cards/netNote.ts
Normal file
33
src/components/reports/cards/netNote.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import type { CartesSnapshot } from "../../../shared/types";
|
||||
|
||||
/**
|
||||
* The note under « Solde net » (D5, #392). The card shows the net result,
|
||||
* every amount of the period; beyond income − expenses, it holds the
|
||||
* uncategorized line and the transfers. The note names each part that shows
|
||||
* as a whole amount other than zero, as the card rounds them, and is absent
|
||||
* when neither does.
|
||||
*/
|
||||
export function netNote(
|
||||
t: (key: string, options?: Record<string, unknown>) => string,
|
||||
language: string,
|
||||
breakdown: CartesSnapshot["netBreakdown"],
|
||||
): string | undefined {
|
||||
const format = (amount: number) =>
|
||||
new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", {
|
||||
style: "currency",
|
||||
currency: "CAD",
|
||||
maximumFractionDigits: 0,
|
||||
}).format(amount);
|
||||
const shows = (amount: number) => Math.round(amount) !== 0;
|
||||
const { uncategorized, transfers } = breakdown;
|
||||
|
||||
if (shows(uncategorized) && shows(transfers)) {
|
||||
return t("reports.cartes.netNote.both", {
|
||||
uncategorized: format(uncategorized),
|
||||
transfers: format(transfers),
|
||||
});
|
||||
}
|
||||
if (shows(uncategorized)) return t("reports.cartes.netNote.uncategorized", { amount: format(uncategorized) });
|
||||
if (shows(transfers)) return t("reports.cartes.netNote.transfers", { amount: format(transfers) });
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -2,10 +2,11 @@ import { describe, it, expect } from "vitest";
|
|||
import type { CategoryDelta } from "../../shared/types";
|
||||
import { computeResults, sumLeaves } from "./compareResults";
|
||||
|
||||
// Minimal leaf factory. Amounts arrive from COMPARE_DELTA_SQL already in the
|
||||
// per-type sign convention (expenses = positive ABS, income/transfer = signed).
|
||||
// Minimal leaf factory. Amounts arrive from rowsToDeltas in the sign
|
||||
// convention of the reports (ADR 0026): an expense shows its spending (the
|
||||
// opposite of its balance), every other section its signed balance.
|
||||
function leaf(
|
||||
type: "expense" | "income" | "transfer",
|
||||
type: "expense" | "income" | "transfer" | "uncategorized",
|
||||
mc: number,
|
||||
mp: number,
|
||||
cc = mc,
|
||||
|
|
@ -84,4 +85,29 @@ describe("computeResults — income-statement roll-up (Issue #253)", () => {
|
|||
expect(t.monthCurrent).toBe(100);
|
||||
expect(t.monthPrevious).toBe(50);
|
||||
});
|
||||
|
||||
it("counts the uncategorized line in both results, neither income nor expense (#392, D4)", () => {
|
||||
const r = computeResults([
|
||||
leaf("income", 1000, 1000),
|
||||
leaf("expense", 30, 30),
|
||||
leaf("uncategorized", 40, 0),
|
||||
leaf("transfer", -300, 0),
|
||||
]);
|
||||
expect(r.income.monthCurrent).toBe(1000);
|
||||
expect(r.expense.monthCurrent).toBe(30);
|
||||
expect(r.uncategorized.monthCurrent).toBe(40);
|
||||
// 1000 − 30 + 40, then the one-leg transfer.
|
||||
expect(r.resultBefore.monthCurrent).toBe(1010);
|
||||
expect(r.resultNet.monthCurrent).toBe(710);
|
||||
expect(r.resultBefore.monthDelta).toBe(40);
|
||||
expect(r.hasUncategorized).toBe(true);
|
||||
expect(r.hasTransfers).toBe(true);
|
||||
});
|
||||
|
||||
it("adds a negative expense back to the result: refunds above purchases (#392, D1)", () => {
|
||||
const r = computeResults([leaf("income", 1000, 1000), leaf("expense", 80, 80), leaf("expense", -50, 0)]);
|
||||
expect(r.expense.monthCurrent).toBe(30);
|
||||
expect(r.resultNet.monthCurrent).toBe(970);
|
||||
expect(r.hasUncategorized).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { CategoryDelta } from "../../shared/types";
|
||||
import type { CategoryDelta, ReportSection } from "../../shared/types";
|
||||
|
||||
export type SectionType = "expense" | "income" | "transfer";
|
||||
export type SectionType = ReportSection;
|
||||
|
||||
/** Aggregate of the 6 comparable figures across a set of leaf rows. */
|
||||
export interface Totals {
|
||||
|
|
@ -57,34 +57,46 @@ function combine(a: Totals, b: Totals, sign: 1 | -1): Totals {
|
|||
export interface CompareResults {
|
||||
income: Totals;
|
||||
expense: Totals;
|
||||
/** The uncategorized line (D4): neither income nor expense, in the result. */
|
||||
uncategorized: Totals;
|
||||
transfer: Totals;
|
||||
/** Revenues − expenses: the operating result, before transfers. */
|
||||
/** Revenues − expenses + uncategorized: the operating result, before transfers. */
|
||||
resultBefore: Totals;
|
||||
/** resultBefore + net transfers: the bottom-line total. */
|
||||
/** resultBefore + net transfers: the bottom-line total, every amount of the period. */
|
||||
resultNet: Totals;
|
||||
hasTransfers: boolean;
|
||||
hasUncategorized: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Income-statement roll-up for the real-vs-real compare (Issue #253).
|
||||
* Income-statement roll-up for the real-vs-real compare (Issue #253, ADR 0026).
|
||||
*
|
||||
* Sign convention flowing in from COMPARE_DELTA_SQL: expenses are positive
|
||||
* magnitudes (ABS of outflows), income is a signed SUM (positive), transfers a
|
||||
* signed net (~0 when balanced). So the operating result is a straight
|
||||
* `income − expense`, and the net adds the (usually ~0) transfer total. When a
|
||||
* transfer is unbalanced (a single leg categorised) its residual shows up as
|
||||
* the gap between resultBefore and resultNet.
|
||||
* Sign convention flowing in from rowsToDeltas: each category shows its signed
|
||||
* balance, an expense its spending (the opposite of its balance, refunds
|
||||
* netted, negative when refunds exceed purchases), transfers a signed net (0
|
||||
* when balanced). So the operating result is `income − expense +
|
||||
* uncategorized`, and the net adds the transfer total. When a transfer is
|
||||
* unbalanced (a single leg categorised) its residual shows up as the gap
|
||||
* between resultBefore and resultNet.
|
||||
*/
|
||||
export function computeResults(rows: CategoryDelta[]): CompareResults {
|
||||
const byType = (type: SectionType): Totals =>
|
||||
sumLeaves(rows.filter((r) => (r.category_type ?? "expense") === type));
|
||||
const typeOf = (r: CategoryDelta): SectionType => r.category_type ?? "expense";
|
||||
const byType = (type: SectionType): Totals => sumLeaves(rows.filter((r) => typeOf(r) === type));
|
||||
const income = byType("income");
|
||||
const expense = byType("expense");
|
||||
const uncategorized = byType("uncategorized");
|
||||
const transfer = byType("transfer");
|
||||
const resultBefore = combine(income, expense, -1);
|
||||
const resultBefore = combine(combine(income, expense, -1), uncategorized, 1);
|
||||
const resultNet = combine(resultBefore, transfer, 1);
|
||||
const hasTransfers = rows.some(
|
||||
(r) => (r.category_type ?? "expense") === "transfer" && !r.is_parent,
|
||||
);
|
||||
return { income, expense, transfer, resultBefore, resultNet, hasTransfers };
|
||||
const has = (type: SectionType) => rows.some((r) => typeOf(r) === type && !r.is_parent);
|
||||
return {
|
||||
income,
|
||||
expense,
|
||||
uncategorized,
|
||||
transfer,
|
||||
resultBefore,
|
||||
resultNet,
|
||||
hasTransfers: has("transfer"),
|
||||
hasUncategorized: has("uncategorized"),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
47
src/components/reports/donutParts.test.tsx
Normal file
47
src/components/reports/donutParts.test.tsx
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// The zoom's donut and its negative parts (D7, #392). No jsdom: react-dom/server
|
||||
// renders the markup; Recharts draws nothing without a size, the mention line
|
||||
// is what is read here.
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
|
||||
|
||||
import CategoryDonutChart from "./CategoryDonutChart";
|
||||
import { donutParts } from "./donutParts";
|
||||
import type { CategoryZoomChild } from "../../shared/types";
|
||||
|
||||
const child = (categoryId: number, total: number): CategoryZoomChild => ({
|
||||
categoryId,
|
||||
categoryName: `C${categoryId}`,
|
||||
categoryColor: "#000",
|
||||
total,
|
||||
});
|
||||
|
||||
describe("donutParts", () => {
|
||||
it("keeps the positive parts and counts the negative ones; a zero part is neither", () => {
|
||||
const { parts, negativeCount } = donutParts([child(1, 80), child(2, 0), child(3, -50), child(4, 20)]);
|
||||
expect(parts.map((c) => c.categoryId)).toEqual([1, 4]);
|
||||
expect(negativeCount).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CategoryDonutChart", () => {
|
||||
const render = (byChild: CategoryZoomChild[]) =>
|
||||
renderToStaticMarkup(<CategoryDonutChart byChild={byChild} centerLabel="Total" centerValue="30 $" />);
|
||||
|
||||
it("says how many negative parts it leaves out", () => {
|
||||
const html = render([child(1, 80), child(3, -50)]);
|
||||
expect(html).toContain("t(reports.category.donutOmitted[count=1])");
|
||||
expect(html).not.toContain("t(reports.empty.noData)");
|
||||
});
|
||||
|
||||
it("shows no ring when every part is negative or zero, and still says why", () => {
|
||||
const html = render([child(2, 0), child(3, -50), child(5, -10)]);
|
||||
expect(html).toContain("t(reports.empty.noData)");
|
||||
expect(html).toContain("t(reports.category.donutOmitted[count=2])");
|
||||
});
|
||||
|
||||
it("adds no line when no part is negative", () => {
|
||||
expect(render([child(1, 80), child(2, 0)])).not.toContain("donutOmitted");
|
||||
});
|
||||
});
|
||||
18
src/components/reports/donutParts.ts
Normal file
18
src/components/reports/donutParts.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import type { CategoryZoomChild } from "../../shared/types";
|
||||
|
||||
/**
|
||||
* The parts the zoom's donut can draw (D7, #392): the subcategories that show
|
||||
* a positive amount. A pie cannot draw a negative part — a subcategory whose
|
||||
* refunds exceed its purchases — so the donut leaves the negative ones out and
|
||||
* says how many; a zero part never had a visible slice. The figures stay
|
||||
* signed in the total at the centre and in the table.
|
||||
*/
|
||||
export function donutParts(byChild: CategoryZoomChild[]): {
|
||||
parts: CategoryZoomChild[];
|
||||
negativeCount: number;
|
||||
} {
|
||||
return {
|
||||
parts: byChild.filter((c) => c.total > 0),
|
||||
negativeCount: byChild.filter((c) => c.total < 0).length,
|
||||
};
|
||||
}
|
||||
93
src/components/reports/incomeStatementCells.render.test.tsx
Normal file
93
src/components/reports/incomeStatementCells.render.test.tsx
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
// The cells that show « Solde net » and its parts (#392, D5): the « Net » of
|
||||
// Trends' global flow is the net result, every amount of the month, and the
|
||||
// KPI card shows the note it is given. No jsdom: react-dom/server renders the
|
||||
// markup.
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
|
||||
|
||||
import MonthlyTrendsTable from "./MonthlyTrendsTable";
|
||||
import KpiCard from "./cards/KpiCard";
|
||||
import type { CartesKpi } from "../../shared/types";
|
||||
|
||||
/** The text of each cell of the table row at `rowIndex` (the head is row 0). */
|
||||
function cellsOf(html: string, rowIndex: number): string[] {
|
||||
const rows = html.split("<tr").slice(1);
|
||||
return [...rows[rowIndex].matchAll(/<td[^>]*>(.*?)<\/td>/g)].map((m) => m[1].replace(/<[^>]+>/g, ""));
|
||||
}
|
||||
|
||||
describe("MonthlyTrendsTable", () => {
|
||||
// October holds the edge cases of #392: income 1000, expenses 30,
|
||||
// uncategorized 40, transfers −300.
|
||||
const html = renderToStaticMarkup(
|
||||
<MonthlyTrendsTable
|
||||
data={[
|
||||
{
|
||||
month: "2026-09",
|
||||
income: 500,
|
||||
expenses: 100,
|
||||
uncategorized: 0,
|
||||
transfers: 0,
|
||||
resultBeforeTransfers: 400,
|
||||
net: 400,
|
||||
},
|
||||
{
|
||||
month: "2026-10",
|
||||
income: 1000,
|
||||
expenses: 30,
|
||||
uncategorized: 40,
|
||||
transfers: -300,
|
||||
resultBeforeTransfers: 1010,
|
||||
net: 710,
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
it("heads its columns income, expenses, uncategorized, transfers and net", () => {
|
||||
const heads = [...html.matchAll(/<th[^>]*>(.*?)<\/th>/g)].map((m) => m[1]);
|
||||
expect(heads.slice(1)).toEqual([
|
||||
"t(dashboard.income)",
|
||||
"t(dashboard.expenses)",
|
||||
"t(reports.uncategorized)",
|
||||
"t(reports.compare.sections.transfers)",
|
||||
"t(dashboard.net)",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows the net result in « Net », not income − expenses", () => {
|
||||
expect(cellsOf(html, 1).slice(1)).toEqual(["$500", "$100", "$0", "$0", "$400"]);
|
||||
expect(cellsOf(html, 2).slice(1)).toEqual(["$1,000", "$30", "$40", "-$300", "$710"]);
|
||||
});
|
||||
|
||||
it("totals every column, the net result included", () => {
|
||||
expect(cellsOf(html, 3)).toEqual(["t(common.total)", "$1,500", "$130", "$40", "-$300", "$1,110"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("KpiCard", () => {
|
||||
const kpi: CartesKpi = {
|
||||
current: 710,
|
||||
previousMonth: null,
|
||||
previousYear: null,
|
||||
deltaMoMAbs: null,
|
||||
deltaMoMPct: null,
|
||||
deltaYoYAbs: null,
|
||||
deltaYoYPct: null,
|
||||
sparkline: [],
|
||||
};
|
||||
const render = (note?: string) =>
|
||||
renderToStaticMarkup(<KpiCard id="net" title="Solde net" kpi={kpi} format="currency" note={note} />);
|
||||
const divs = (html: string) => html.split("<div").length - 1;
|
||||
|
||||
it("shows the note it is given under the value", () => {
|
||||
const html = render("Dont 40 $ non classés");
|
||||
expect(html).toContain(">Dont 40 $ non classés<");
|
||||
expect(html.indexOf("Dont 40 $ non classés")).toBeGreaterThan(html.indexOf("710"));
|
||||
});
|
||||
|
||||
it("adds no line without a note", () => {
|
||||
expect(divs(render())).toBe(divs(render("Dont 40 $ non classés")) - 1);
|
||||
});
|
||||
});
|
||||
|
|
@ -7,7 +7,7 @@ function leaf(
|
|||
categoryId: number | null,
|
||||
categoryName: string,
|
||||
monthly: number[],
|
||||
category_type: "income" | "expense" | "transfer",
|
||||
category_type: "income" | "expense" | "transfer" | "uncategorized",
|
||||
extra: Partial<OverTimeRow> = {},
|
||||
): OverTimeRow {
|
||||
return {
|
||||
|
|
@ -192,4 +192,42 @@ describe("computeOverTimeResults", () => {
|
|||
expect(r.net.monthly).toEqual({ "2025-01": 1000, "2025-02": 1500 });
|
||||
expect(r.net.total).toBe(2500);
|
||||
});
|
||||
|
||||
it("keeps the uncategorized line out of the sections and in both results (#392, D4)", () => {
|
||||
const data = makeData(
|
||||
["2025-01", "2025-02"],
|
||||
[
|
||||
leaf(1, "Salary", [1000, 1000], "income"),
|
||||
leaf(2, "Groceries", [80, 80], "expense"),
|
||||
leaf(null, "Uncategorized", [40, -10], "uncategorized"),
|
||||
leaf(4, "Card", [-300, 0], "transfer"),
|
||||
],
|
||||
);
|
||||
|
||||
const r = computeOverTimeResults(data);
|
||||
|
||||
expect(r.sections.map((s) => s.type)).toEqual(["income", "expense", "transfer"]);
|
||||
expect(r.hasUncategorized).toBe(true);
|
||||
expect(r.uncategorized.monthly).toEqual({ "2025-01": 40, "2025-02": -10 });
|
||||
expect(r.uncategorized.total).toBe(30);
|
||||
// income − expense + uncategorized
|
||||
expect(r.beforeTransfers.monthly).toEqual({ "2025-01": 960, "2025-02": 910 });
|
||||
// … + the signed one-leg transfer
|
||||
expect(r.net.monthly).toEqual({ "2025-01": 660, "2025-02": 910 });
|
||||
expect(r.net.total).toBe(1570);
|
||||
});
|
||||
|
||||
it("adds a negative expense back: a category whose refunds exceed its purchases (#392, D1)", () => {
|
||||
const data = makeData(
|
||||
["2025-01"],
|
||||
[leaf(1, "Salary", [1000], "income"), leaf(2, "Groceries", [80], "expense"), leaf(3, "Butcher", [-50], "expense")],
|
||||
);
|
||||
|
||||
const r = computeOverTimeResults(data);
|
||||
|
||||
expect(r.sections.find((s) => s.type === "expense")!.total).toBe(30);
|
||||
expect(r.net.total).toBe(970);
|
||||
expect(r.hasUncategorized).toBe(false);
|
||||
expect(r.uncategorized.total).toBe(0);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { CategoryOverTimeData, OverTimeRow } from "../../shared/types";
|
||||
import { toCents } from "../../utils/incomeStatement";
|
||||
|
||||
export type OverTimeType = "income" | "expense" | "transfer";
|
||||
|
||||
|
|
@ -43,24 +44,33 @@ export interface OverTimeAnalysis {
|
|||
sections: OverTimeSection[];
|
||||
/** True when at least one visible transfer-type category is present. */
|
||||
hasTransfers: boolean;
|
||||
/** Income − Expenses + Transfers, per month (+ grand total). */
|
||||
/**
|
||||
* The uncategorized line (D4, #392), per month (+ grand total): neither
|
||||
* income nor expense, counted in both results. Not a section: the table
|
||||
* shows it on one line.
|
||||
*/
|
||||
uncategorized: OverTimeSeries;
|
||||
/** True when the tree holds the uncategorized row. */
|
||||
hasUncategorized: boolean;
|
||||
/** Income − Expenses + Uncategorized + Transfers, per month (+ grand total). */
|
||||
net: OverTimeSeries;
|
||||
/** Income − Expenses, per month (+ grand total). Only shown when `hasTransfers`. */
|
||||
/** Income − Expenses + Uncategorized, per month (+ grand total). Only shown when `hasTransfers`. */
|
||||
beforeTransfers: OverTimeSeries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure reducer that turns the category-over-time report into an "income
|
||||
* statement" shape: per-type sections with per-month subtotals, plus the
|
||||
* net-result rows.
|
||||
* statement" shape: per-type sections with per-month subtotals, the
|
||||
* uncategorized line, plus the net-result rows.
|
||||
*
|
||||
* Consumes the **id-keyed tree** (`data.tree`) — NOT the name-keyed pivot — so
|
||||
* two homonym categories of different types never collide: each leaf carries its
|
||||
* own `category_id`-resolved `category_type`, and the subtotals + result lines
|
||||
* are summed over the tree's LEAVES only (never its `is_parent` subtotal rows,
|
||||
* which would double-count their own descendants). Leaf `monthly[]` values are
|
||||
* positive magnitudes (`ABS(SUM())` in SQL), so income/expense/transfer
|
||||
* subtotals are all ≥ 0 and the net is `income − expense + transfer`.
|
||||
* what each category shows (ADR 0026): its signed balance, an expense its
|
||||
* spending (negative when refunds exceed purchases), a transfer its signed net.
|
||||
* So the net is `income − expense + uncategorized + transfer`.
|
||||
*
|
||||
* The tree is already ordered income → expense → transfer, so section ordering
|
||||
* falls out of the leaves' own `category_type`.
|
||||
|
|
@ -70,47 +80,57 @@ export function computeOverTimeResults(data: CategoryOverTimeData): OverTimeAnal
|
|||
|
||||
// Leaves only — subtotals (`is_parent`) are excluded so a parent group can
|
||||
// never double-count against its own descendants.
|
||||
const typeOf = (row: OverTimeRow): OverTimeType => {
|
||||
const typeOf = (row: OverTimeRow): OverTimeType | "uncategorized" => {
|
||||
const t = row.category_type;
|
||||
return t === "income" || t === "transfer" ? t : "expense";
|
||||
return t === "income" || t === "transfer" || t === "uncategorized" ? t : "expense";
|
||||
};
|
||||
const byType: Record<OverTimeType | "uncategorized", OverTimeRow[]> = {
|
||||
income: [],
|
||||
expense: [],
|
||||
uncategorized: [],
|
||||
transfer: [],
|
||||
};
|
||||
const byType: Record<OverTimeType, OverTimeRow[]> = { income: [], expense: [], transfer: [] };
|
||||
for (const row of data.tree) {
|
||||
if (!row.is_parent) byType[typeOf(row)].push(row);
|
||||
}
|
||||
|
||||
const buildSection = (type: OverTimeType): OverTimeSection => {
|
||||
const rows = byType[type];
|
||||
const seriesOf = (rows: OverTimeRow[]): OverTimeSeries => {
|
||||
const monthly: Record<string, number> = {};
|
||||
let total = 0;
|
||||
months.forEach((month, i) => {
|
||||
const sum = rows.reduce((s, row) => s + (row.monthly[i] ?? 0), 0);
|
||||
const sum = toCents(rows.reduce((s, row) => s + (row.monthly[i] ?? 0), 0));
|
||||
monthly[month] = sum;
|
||||
total += sum;
|
||||
total = toCents(total + sum);
|
||||
});
|
||||
return { type, rows, monthly, total };
|
||||
return { monthly, total };
|
||||
};
|
||||
const buildSection = (type: OverTimeType): OverTimeSection => {
|
||||
const rows = byType[type];
|
||||
return { type, rows, ...seriesOf(rows) };
|
||||
};
|
||||
|
||||
const income = buildSection("income");
|
||||
const expense = buildSection("expense");
|
||||
const transfer = buildSection("transfer");
|
||||
const uncategorized = seriesOf(byType.uncategorized);
|
||||
|
||||
const hasTransfers = transfer.rows.length > 0;
|
||||
const hasUncategorized = byType.uncategorized.length > 0;
|
||||
|
||||
const net: OverTimeSeries = { monthly: {}, total: 0 };
|
||||
const beforeTransfers: OverTimeSeries = { monthly: {}, total: 0 };
|
||||
for (const month of months) {
|
||||
const before = income.monthly[month] - expense.monthly[month];
|
||||
const netMonth = before + transfer.monthly[month];
|
||||
const before = toCents(income.monthly[month] - expense.monthly[month] + uncategorized.monthly[month]);
|
||||
const netMonth = toCents(before + transfer.monthly[month]);
|
||||
beforeTransfers.monthly[month] = before;
|
||||
beforeTransfers.total += before;
|
||||
beforeTransfers.total = toCents(beforeTransfers.total + before);
|
||||
net.monthly[month] = netMonth;
|
||||
net.total += netMonth;
|
||||
net.total = toCents(net.total + netMonth);
|
||||
}
|
||||
|
||||
const sections = [income, expense, transfer]
|
||||
.filter((s) => s.rows.length > 0)
|
||||
.sort((a, b) => OVER_TIME_TYPE_ORDER[a.type] - OVER_TIME_TYPE_ORDER[b.type]);
|
||||
|
||||
return { months, sections, hasTransfers, net, beforeTransfers };
|
||||
return { months, sections, hasTransfers, uncategorized, hasUncategorized, net, beforeTransfers };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import {
|
|||
groupOverTimeSections,
|
||||
} from "./overTimeTableModel";
|
||||
|
||||
type RowType = "income" | "expense" | "transfer";
|
||||
type RowType = "income" | "expense" | "transfer" | "uncategorized";
|
||||
|
||||
/** Builds one id-keyed tree row; `monthly` is index-aligned to the months list. */
|
||||
function mkRow(
|
||||
|
|
@ -141,6 +141,18 @@ describe("overTimeTableModel.groupOverTimeSections", () => {
|
|||
expect(expense.total).toBe(3300);
|
||||
});
|
||||
|
||||
it("leaves the uncategorized row out of every section (#392): the table shows it on one line", () => {
|
||||
const tree = [...buildTree(), mkRow(0, "Uncategorized", [40, 0], "uncategorized", { categoryId: null })];
|
||||
const data = makeData(MONTHS, tree);
|
||||
const analysis = computeOverTimeResults(data);
|
||||
const { nonTransferSections, transferSection } = groupOverTimeSections(analysis, data.tree);
|
||||
|
||||
const sectionRows = [...nonTransferSections, transferSection!].flatMap((s) => s.rows);
|
||||
expect(sectionRows.some((r) => r.category_type === "uncategorized")).toBe(false);
|
||||
expect(nonTransferSections.find((s) => s.type === "expense")!.total).toBe(3300);
|
||||
expect(analysis.uncategorized.total).toBe(40);
|
||||
});
|
||||
|
||||
it("drops empty sections: no transfers → transferSection is null", () => {
|
||||
const tree = buildTree().filter((r) => r.category_type !== "transfer");
|
||||
const data = makeData(MONTHS, tree);
|
||||
|
|
|
|||
|
|
@ -45,8 +45,10 @@ export interface OverTimeRenderSection {
|
|||
total: number;
|
||||
}
|
||||
|
||||
const typeOf = (row: OverTimeRow): OverTimeType => {
|
||||
const typeOf = (row: OverTimeRow): OverTimeType | null => {
|
||||
const t = row.category_type;
|
||||
// The uncategorized row is no section: the table shows it on one line (#392).
|
||||
if (t === "uncategorized") return null;
|
||||
return t === "income" || t === "transfer" ? t : "expense";
|
||||
};
|
||||
|
||||
|
|
@ -74,7 +76,10 @@ export function groupOverTimeSections(
|
|||
expense: [],
|
||||
transfer: [],
|
||||
};
|
||||
for (const row of tree) rowsByType[typeOf(row)].push(row);
|
||||
for (const row of tree) {
|
||||
const type = typeOf(row);
|
||||
if (type) rowsByType[type].push(row);
|
||||
}
|
||||
|
||||
const sections: OverTimeRenderSection[] = analysis.sections.map((s) => ({
|
||||
type: s.type,
|
||||
|
|
|
|||
157
src/components/reports/uncategorizedLine.render.test.tsx
Normal file
157
src/components/reports/uncategorizedLine.render.test.tsx
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
// The uncategorized line of the three income-statement tables (#392, D4):
|
||||
// one line « Non classé », after the expenses and before the result before
|
||||
// transfers, never a category row named by the SQL's 'Uncategorized'. No
|
||||
// jsdom: react-dom/server renders the markup, effects do not run.
|
||||
import { describe, it, expect, vi, beforeAll } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
|
||||
// The collapse state is read from the profile in an effect, which never runs here.
|
||||
vi.mock("../../services/userPreferenceService", () => ({
|
||||
getPreference: vi.fn(async () => null),
|
||||
setPreference: vi.fn(async () => undefined),
|
||||
}));
|
||||
|
||||
import ComparePeriodTable from "./ComparePeriodTable";
|
||||
import BudgetVsActualTable from "./BudgetVsActualTable";
|
||||
import CategoryOverTimeTable from "./CategoryOverTimeTable";
|
||||
import type { BudgetVsActualRow, CategoryDelta, OverTimeRow, ReportSection } from "../../shared/types";
|
||||
|
||||
beforeAll(() => {
|
||||
// Where the tables keep the position of their subtotals.
|
||||
vi.stubGlobal("localStorage", { getItem: () => null, setItem: () => undefined });
|
||||
});
|
||||
|
||||
const LINE = "t(reports.uncategorized)";
|
||||
|
||||
/** The markers appear in this order in the markup, each exactly once. */
|
||||
function expectOrder(html: string, ...markers: string[]) {
|
||||
for (const marker of markers) expect(html.split(marker).length - 1, marker).toBe(1);
|
||||
const positions = markers.map((marker) => html.indexOf(marker));
|
||||
expect(positions).toEqual([...positions].sort((a, b) => a - b));
|
||||
}
|
||||
|
||||
const delta = (type: ReportSection, categoryId: number | null, amount: number): CategoryDelta => ({
|
||||
categoryId,
|
||||
categoryName: categoryId === null ? "Uncategorized" : `C${categoryId}`,
|
||||
categoryColor: "#000",
|
||||
previousAmount: 0,
|
||||
currentAmount: amount,
|
||||
deltaAbs: amount,
|
||||
deltaPct: null,
|
||||
cumulativePreviousAmount: 0,
|
||||
cumulativeCurrentAmount: amount,
|
||||
cumulativeDeltaAbs: amount,
|
||||
cumulativeDeltaPct: null,
|
||||
parent_id: null,
|
||||
is_parent: false,
|
||||
depth: 0,
|
||||
category_type: type,
|
||||
});
|
||||
|
||||
describe("ComparePeriodTable", () => {
|
||||
it("shows the uncategorized line between the expenses and the result before transfers", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ComparePeriodTable
|
||||
rows={[
|
||||
delta("income", 1, 1000),
|
||||
delta("expense", 2, 30),
|
||||
delta("uncategorized", null, 40),
|
||||
delta("transfer", 3, -300),
|
||||
]}
|
||||
previousLabel="Sept."
|
||||
currentLabel="Oct."
|
||||
/>,
|
||||
);
|
||||
expectOrder(
|
||||
html,
|
||||
"t(reports.compare.totalExpenses)",
|
||||
LINE,
|
||||
"t(reports.compare.resultBeforeTransfers)",
|
||||
"t(reports.compare.totalTransfers)",
|
||||
"t(reports.compare.resultNet)",
|
||||
);
|
||||
expect(html).not.toContain(">Uncategorized<");
|
||||
});
|
||||
|
||||
it("shows no such line without uncategorized rows", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ComparePeriodTable rows={[delta("income", 1, 1000), delta("expense", 2, 30)]} previousLabel="" currentLabel="" />,
|
||||
);
|
||||
expect(html).not.toContain(LINE);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BudgetVsActualTable", () => {
|
||||
const row = (type: ReportSection, categoryId: number | null, actual: number, budget = 0): BudgetVsActualRow => ({
|
||||
category_id: categoryId,
|
||||
category_name: categoryId === null ? "" : `C${categoryId}`,
|
||||
category_color: "#000",
|
||||
category_type: type,
|
||||
parent_id: null,
|
||||
is_parent: false,
|
||||
depth: 0,
|
||||
monthActual: actual,
|
||||
monthBudget: budget,
|
||||
monthVariation: actual - budget,
|
||||
monthVariationPct: null,
|
||||
ytdActual: actual,
|
||||
ytdBudget: budget,
|
||||
ytdVariation: actual - budget,
|
||||
ytdVariationPct: null,
|
||||
});
|
||||
|
||||
it("shows the uncategorized line between the expenses and the result before transfers", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<BudgetVsActualTable
|
||||
data={[row("income", 1, 1000), row("expense", 2, -30, -100), row("uncategorized", null, 40), row("transfer", 3, -300)]}
|
||||
/>,
|
||||
);
|
||||
expectOrder(
|
||||
html,
|
||||
"t(budget.totalExpenses)",
|
||||
LINE,
|
||||
"t(reports.compare.resultBeforeTransfers)",
|
||||
"t(budget.totalTransfers)",
|
||||
"t(reports.compare.resultNet)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CategoryOverTimeTable", () => {
|
||||
const leaf = (type: ReportSection, categoryId: number | null, value: number): OverTimeRow => ({
|
||||
categoryId,
|
||||
categoryName: categoryId === null ? "Uncategorized" : `C${categoryId}`,
|
||||
categoryColor: "#000",
|
||||
monthly: [value],
|
||||
total: value,
|
||||
parent_id: null,
|
||||
is_parent: false,
|
||||
depth: 0,
|
||||
category_type: type,
|
||||
});
|
||||
|
||||
it("shows the uncategorized line between the expenses and the result before transfers", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<CategoryOverTimeTable
|
||||
data={{
|
||||
categories: [],
|
||||
data: [{ month: "2026-10" }],
|
||||
colors: {},
|
||||
categoryIds: {},
|
||||
types: {},
|
||||
tree: [leaf("income", 1, 1000), leaf("expense", 2, 30), leaf("uncategorized", null, 40), leaf("transfer", 3, -300)],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expectOrder(
|
||||
html,
|
||||
"t(reports.compare.totalExpenses)",
|
||||
LINE,
|
||||
"t(reports.compare.resultBeforeTransfers)",
|
||||
"t(reports.compare.totalTransfers)",
|
||||
"t(reports.compare.resultNet)",
|
||||
);
|
||||
expect(html).not.toContain(">Uncategorized<");
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
// The summary bar of the Transactions page (#392, D8): a view of the listed
|
||||
// transactions, summed by sign, under « Entrées / Sorties / Solde ».
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
|
||||
|
||||
import TransactionSummaryBar from "./TransactionSummaryBar";
|
||||
|
||||
describe("TransactionSummaryBar", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<TransactionSummaryBar totalCount={5} totalAmount={920} incomeTotal={1520} expenseTotal={-600} />,
|
||||
);
|
||||
|
||||
it("labels its sums money in and money out, not income and expenses", () => {
|
||||
expect(html).toContain("t(transactions.summary.moneyIn)");
|
||||
expect(html).toContain("t(transactions.summary.moneyOut)");
|
||||
expect(html).toContain("t(transactions.summary.balance)");
|
||||
expect(html).not.toContain("t(transactions.summary.income)");
|
||||
expect(html).not.toContain("t(transactions.summary.expenses)");
|
||||
});
|
||||
|
||||
it("keeps its sums by sign: what came in, what went out, and the balance", () => {
|
||||
const inIndex = html.indexOf("t(transactions.summary.moneyIn)");
|
||||
const outIndex = html.indexOf("t(transactions.summary.moneyOut)");
|
||||
expect(html.slice(inIndex, outIndex)).toMatch(/1.520[.,]00/);
|
||||
expect(html.slice(outIndex)).toMatch(/600[.,]00/);
|
||||
expect(html.slice(html.indexOf("t(transactions.summary.balance)"))).toMatch(/920[.,]00/);
|
||||
});
|
||||
});
|
||||
|
|
@ -8,6 +8,11 @@ interface TransactionSummaryBarProps {
|
|||
expenseTotal: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The totals of the listed transactions (#392, D8): what came in and what went
|
||||
* out, by sign, split lines left out like the list, and the balance. A view of
|
||||
* the list, not an income statement: the reports count by category.
|
||||
*/
|
||||
export default function TransactionSummaryBar({
|
||||
totalCount,
|
||||
totalAmount,
|
||||
|
|
@ -25,7 +30,7 @@ export default function TransactionSummaryBar({
|
|||
},
|
||||
{
|
||||
icon: TrendingUp,
|
||||
label: t("transactions.summary.income"),
|
||||
label: t("transactions.summary.moneyIn"),
|
||||
value: incomeTotal.toLocaleString(undefined, {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
|
|
@ -34,7 +39,7 @@ export default function TransactionSummaryBar({
|
|||
},
|
||||
{
|
||||
icon: TrendingDown,
|
||||
label: t("transactions.summary.expenses"),
|
||||
label: t("transactions.summary.moneyOut"),
|
||||
value: Math.abs(expenseTotal).toLocaleString(undefined, {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
|
|
|
|||
|
|
@ -367,8 +367,8 @@
|
|||
},
|
||||
"summary": {
|
||||
"count": "Transactions",
|
||||
"income": "Income",
|
||||
"expenses": "Expenses",
|
||||
"moneyIn": "Money in",
|
||||
"moneyOut": "Money out",
|
||||
"balance": "Balance"
|
||||
},
|
||||
"table": {
|
||||
|
|
@ -639,6 +639,11 @@
|
|||
"income": "Income",
|
||||
"expenses": "Expenses",
|
||||
"net": "Net balance",
|
||||
"netNote": {
|
||||
"both": "Includes {{uncategorized}} uncategorized and {{transfers}} of transfers",
|
||||
"uncategorized": "Includes {{amount}} uncategorized",
|
||||
"transfers": "Includes {{amount}} of transfers"
|
||||
},
|
||||
"savingsRate": "Savings rate",
|
||||
"savingsRateTooltip": {
|
||||
"month": "Formula: (income − expenses) ÷ income × 100, computed on the reference month.",
|
||||
|
|
@ -669,6 +674,8 @@
|
|||
"includeSubcategories": "Include subcategories",
|
||||
"directOnly": "Direct only",
|
||||
"breakdown": "Total",
|
||||
"donutOmitted_one": "{{count}} subcategory with a negative amount is not drawn",
|
||||
"donutOmitted_other": "{{count}} subcategories with a negative amount are not drawn",
|
||||
"evolution": "Evolution",
|
||||
"transactions": "Transactions"
|
||||
},
|
||||
|
|
@ -704,6 +711,7 @@
|
|||
"noData": "No data for this period",
|
||||
"importCta": "Import a statement"
|
||||
},
|
||||
"uncategorized": "Uncategorized",
|
||||
"help": {
|
||||
"title": "How to use Reports",
|
||||
"tips": [
|
||||
|
|
@ -1048,7 +1056,7 @@
|
|||
],
|
||||
"tips": [
|
||||
"The default period is year to date for an annual overview when you open the app",
|
||||
"The balance is calculated as income minus expenses for the selected period",
|
||||
"The net balance is the sum of every transaction of the reference month: income minus expenses, plus uncategorized transactions and transfers, which a note under the card details when they are not zero. The savings rate is (income − expenses) ÷ income",
|
||||
"Hidden categories appear as dismissible chips above the chart — click Show All to restore them",
|
||||
"SVG patterns (lines, dots, crosshatch) help distinguish categories beyond just color",
|
||||
"The checklist boxes tick on your data, not on a click: \"Categorize a transaction by hand\" expects a transaction whose category you changed yourself; the automatic categorization of the import does not tick it"
|
||||
|
|
@ -1192,7 +1200,8 @@
|
|||
"Use the quick period buttons (This month, Last month, etc.) for fast date filtering",
|
||||
"Auto-categorize only affects uncategorized transactions — it won't overwrite manual assignments",
|
||||
"Adding a keyword from a transaction pre-fills the category so you can quickly build rules",
|
||||
"Split transactions display a visual indicator whatever the edition; the breakdown opens from the Split button (Base edition and above)"
|
||||
"Split transactions display a visual indicator whatever the edition; the breakdown opens from the Split button (Base edition and above)",
|
||||
"The bar above the list adds up the listed transactions by sign: “Money in”, “Money out” and “Balance”, without the split lines; the reports count by category"
|
||||
]
|
||||
},
|
||||
"categories": {
|
||||
|
|
@ -1279,7 +1288,7 @@
|
|||
"overview": "A hub with a live highlights panel plus five dedicated sub-reports (Highlights, Trends, Compare, Category Analysis, Cards). Every page shares a bookmarkable period via the URL query string.",
|
||||
"features": [
|
||||
"Hub: compact highlights panel + 5 navigation cards",
|
||||
"Highlights: current month and YTD balances with sparklines, top movers vs. last month, top recent transactions (30/60/90 day window)",
|
||||
"Highlights: current month and YTD balances with sparklines, top movers among expense categories vs. last month, top recent transactions (30/60/90 day window)",
|
||||
"Cartes: single-month KPI dashboard (income, expenses, net, savings rate) with a Monthly/YTD toggle, 13-month sparklines, top movers, budget adherence, and seasonality",
|
||||
"Trends: global flow (income vs. expenses) and by-category evolution with a chart/table toggle",
|
||||
"Compare: Month vs. Previous Month, Year vs. Previous Year, and Actual vs. Budget",
|
||||
|
|
@ -1304,7 +1313,8 @@
|
|||
"The Category Analysis is protected against malformed category trees: a parent_id cycle cannot freeze the app",
|
||||
"On /reports/cartes in YTD mode, the MoM delta for January is always \"—\" (no prior YTD window inside the same year), and the savings rate stays \"—\" when YTD income is zero",
|
||||
"Seasonality, top movers, and budget adherence stay monthly even when the toggle is set to YTD — only the 4 KPI numbers change",
|
||||
"Your category collapse choices (Compare, Trends, Budget) are remembered per profile: stored in the profile's own database, they are destroyed with it"
|
||||
"Your category collapse choices (Compare, Trends, Budget) are remembered per profile: stored in the profile's own database, they are destroyed with it",
|
||||
"Every report counts amounts by category, signs included: a refund lowers the expense of its category, a split counts once, transfers stay apart with their sign, and transactions without a category form an “Uncategorized” line, counted in the result. An expense that turns negative (refunds above purchases) is drawn below zero; the Category Analysis donut leaves it out and says so"
|
||||
]
|
||||
},
|
||||
"balance": {
|
||||
|
|
|
|||
|
|
@ -367,8 +367,8 @@
|
|||
},
|
||||
"summary": {
|
||||
"count": "Transactions",
|
||||
"income": "Revenus",
|
||||
"expenses": "Dépenses",
|
||||
"moneyIn": "Entrées",
|
||||
"moneyOut": "Sorties",
|
||||
"balance": "Solde"
|
||||
},
|
||||
"table": {
|
||||
|
|
@ -639,6 +639,11 @@
|
|||
"income": "Revenus",
|
||||
"expenses": "Dépenses",
|
||||
"net": "Solde net",
|
||||
"netNote": {
|
||||
"both": "Dont {{uncategorized}} non classés et {{transfers}} de transferts",
|
||||
"uncategorized": "Dont {{amount}} non classés",
|
||||
"transfers": "Dont {{amount}} de transferts"
|
||||
},
|
||||
"savingsRate": "Taux d'épargne",
|
||||
"savingsRateTooltip": {
|
||||
"month": "Formule : (revenus − dépenses) ÷ revenus × 100, calculée sur le mois de référence.",
|
||||
|
|
@ -669,6 +674,8 @@
|
|||
"includeSubcategories": "Inclure les sous-catégories",
|
||||
"directOnly": "Directe seulement",
|
||||
"breakdown": "Total",
|
||||
"donutOmitted_one": "{{count}} sous-catégorie au montant négatif n'apparaît pas dans le graphique",
|
||||
"donutOmitted_other": "{{count}} sous-catégories au montant négatif n'apparaissent pas dans le graphique",
|
||||
"evolution": "Évolution",
|
||||
"transactions": "Transactions"
|
||||
},
|
||||
|
|
@ -704,6 +711,7 @@
|
|||
"noData": "Aucune donnée pour cette période",
|
||||
"importCta": "Importer un relevé"
|
||||
},
|
||||
"uncategorized": "Non classé",
|
||||
"help": {
|
||||
"title": "Comment utiliser les Rapports",
|
||||
"tips": [
|
||||
|
|
@ -1048,7 +1056,7 @@
|
|||
],
|
||||
"tips": [
|
||||
"La période par défaut est « année à ce jour » pour un aperçu annuel dès l'ouverture",
|
||||
"Le solde est calculé comme les revenus moins les dépenses pour la période sélectionnée",
|
||||
"Le solde net est la somme de toutes les transactions du mois de référence : les revenus moins les dépenses, plus les transactions non classées et les transferts, qu'une note sous la carte détaille quand ils ne sont pas nuls. Le taux d'épargne vaut (revenus − dépenses) ÷ revenus",
|
||||
"Les catégories masquées apparaissent sous forme de pastilles au-dessus du graphique — cliquez sur Tout afficher pour les restaurer",
|
||||
"Les motifs SVG (lignes, points, hachures) aident à distinguer les catégories au-delà des couleurs",
|
||||
"Les cases de la liste de démarrage se cochent sur vos données, pas sur un clic : « Classer une transaction à la main » attend une transaction dont vous avez changé la catégorie vous-même, la catégorisation automatique de l'import ne la coche pas"
|
||||
|
|
@ -1192,7 +1200,8 @@
|
|||
"Utilisez les boutons de période rapide (Ce mois, Mois dernier, etc.) pour filtrer rapidement par date",
|
||||
"L'auto-catégorisation n'affecte que les transactions non catégorisées — elle n'écrase pas les assignations manuelles",
|
||||
"Ajouter un mot-clé depuis une transaction pré-remplit la catégorie pour construire rapidement vos règles",
|
||||
"Les transactions réparties affichent un indicateur visuel, quelle que soit l'édition ; le détail de la répartition s'ouvre par le bouton Répartition (édition Base et plus)"
|
||||
"Les transactions réparties affichent un indicateur visuel, quelle que soit l'édition ; le détail de la répartition s'ouvre par le bouton Répartition (édition Base et plus)",
|
||||
"La barre au-dessus de la liste additionne les transactions affichées par signe : « Entrées », « Sorties » et « Solde », sans les lignes de répartition ; les rapports comptent par catégorie"
|
||||
]
|
||||
},
|
||||
"categories": {
|
||||
|
|
@ -1279,7 +1288,7 @@
|
|||
"overview": "Un hub qui affiche un panneau de faits saillants en direct plus cinq sous-rapports dédiés (Faits saillants, Tendances, Comparables, Analyse par catégorie, Cartes). Chaque page partage une période bookmarkable via la query string de l'URL.",
|
||||
"features": [
|
||||
"Hub : panneau de faits saillants condensé + 5 cartes de navigation",
|
||||
"Faits saillants : soldes mois courant et cumul annuel avec sparklines, top mouvements vs mois précédent, plus grosses transactions récentes (fenêtre 30/60/90 jours)",
|
||||
"Faits saillants : soldes mois courant et cumul annuel avec sparklines, top mouvements des catégories de dépense vs mois précédent, plus grosses transactions récentes (fenêtre 30/60/90 jours)",
|
||||
"Cartes : tableau de bord KPI d'un mois (revenus, dépenses, solde net, taux d'épargne) avec toggle Mensuel/YTD, sparklines 13 mois, top mouvements, adhésion budgétaire et saisonnalité",
|
||||
"Tendances : flux global (revenus vs dépenses) et évolution par catégorie avec toggle graphique/tableau",
|
||||
"Comparables : Mois vs Mois précédent, Année vs Année précédente, et Réel vs Budget",
|
||||
|
|
@ -1304,7 +1313,8 @@
|
|||
"L'analyse par catégorie est protégée contre les arborescences malformées : un cycle parent_id ne peut pas figer l'app",
|
||||
"Sur /reports/cartes en mode YTD, le delta MoM du mois de janvier est toujours « — » (pas de fenêtre YTD antérieure dans la même année), et le taux d'épargne reste « — » quand les revenus YTD sont à zéro",
|
||||
"La saisonnalité, les top mouvements et l'adhésion budgétaire restent mensuels même quand le toggle est sur YTD — seuls les 4 chiffres KPI changent",
|
||||
"Vos choix de repli des catégories (Comparables, Tendances, Budget) sont mémorisés par profil : stockés dans la base du profil, ils disparaissent avec lui"
|
||||
"Vos choix de repli des catégories (Comparables, Tendances, Budget) sont mémorisés par profil : stockés dans la base du profil, ils disparaissent avec lui",
|
||||
"Tous les rapports comptent les montants par catégorie, signes compris : un remboursement réduit la dépense de sa catégorie, une répartition compte une fois, les transferts restent à part avec leur signe et les transactions sans catégorie forment une ligne « Non classé », comptée dans le résultat. Une dépense devenue négative (des remboursements supérieurs aux achats) se trace sous zéro ; le donut de l'analyse par catégorie l'omet et le dit"
|
||||
]
|
||||
},
|
||||
"balance": {
|
||||
|
|
|
|||
|
|
@ -3,23 +3,27 @@
|
|||
// fake `useOnboarding()`, and the dashboard's data hook and widgets are stubbed
|
||||
// to markers: what is pinned is the page's branching on the path. Since #397
|
||||
// the page has no list of its own once transactions exist: the banner of
|
||||
// AppShell replaced the compact bar (D7).
|
||||
// AppShell replaced the compact bar (D7). The fake KpiCard records its props:
|
||||
// the page hands « Solde net » the note of the snapshot (#392, D5).
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import type { OnboardingValue } from "../hooks/useOnboardingChecklist";
|
||||
import type { CartesKpi, CartesSnapshot } from "../shared/types";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../test/i18nMock")).i18nMock());
|
||||
|
||||
let onboarding: OnboardingValue;
|
||||
vi.mock("../contexts/OnboardingContext", () => ({ useOnboarding: () => onboarding }));
|
||||
|
||||
let cartesSnapshot: CartesSnapshot | null = null;
|
||||
|
||||
vi.mock("../hooks/useDashboard", () => ({
|
||||
useDashboard: () => ({
|
||||
state: {
|
||||
categoryBreakdown: [],
|
||||
categoryOverTime: { categories: [], data: [] },
|
||||
cartesSnapshot: null,
|
||||
cartesSnapshot,
|
||||
period: "year",
|
||||
customDateFrom: "2026-01-01",
|
||||
customDateTo: "2026-10-08",
|
||||
|
|
@ -39,9 +43,10 @@ vi.mock("../hooks/useDashboard", () => ({
|
|||
}));
|
||||
|
||||
// Hoisted with the mocks below, which run before the imports.
|
||||
const { marker, emptyStateProps } = vi.hoisted(() => ({
|
||||
const { marker, emptyStateProps, kpiProps } = vi.hoisted(() => ({
|
||||
marker: (name: string) => ({ default: () => <i data-marker={name} /> }),
|
||||
emptyStateProps: { current: null as Record<string, unknown> | null },
|
||||
kpiProps: new Map<string, Record<string, unknown>>(),
|
||||
}));
|
||||
vi.mock("../components/shared/PageHelp", () => ({ PageHelp: () => null }));
|
||||
vi.mock("../components/dashboard/CategoriesV1DiscoveryBanner", () => marker("discovery"));
|
||||
|
|
@ -59,13 +64,20 @@ vi.mock("../components/dashboard/NetWorthTile", () => marker("net-worth"));
|
|||
vi.mock("../components/reports/CategoryBarChart", () => marker("bar-chart"));
|
||||
vi.mock("../components/reports/CategoryOverTimeChart", () => marker("over-time"));
|
||||
vi.mock("../components/reports/FilterPanel", () => marker("filters"));
|
||||
vi.mock("../components/reports/cards/KpiCard", () => marker("kpi"));
|
||||
vi.mock("../components/reports/cards/KpiCard", () => ({
|
||||
default: (props: Record<string, unknown>) => {
|
||||
kpiProps.set(props.id as string, props);
|
||||
return <i data-marker="kpi" />;
|
||||
},
|
||||
}));
|
||||
vi.mock("../components/reports/cards/IncomeExpenseOverlayChart", () => marker("overlay"));
|
||||
vi.mock("../components/reports/cards/TopMoversList", () => marker("movers"));
|
||||
vi.mock("../components/reports/cards/BudgetAdherenceCard", () => marker("adherence"));
|
||||
vi.mock("../components/shared/TransactionDetailModal", () => marker("detail"));
|
||||
|
||||
import DashboardPage from "./DashboardPage";
|
||||
import { netNote } from "../components/reports/cards/netNote";
|
||||
import { markedT } from "../test/i18nMock";
|
||||
import { computeChecklist } from "../utils/onboardingChecklist";
|
||||
import type { OnboardingCounters } from "../shared/types";
|
||||
|
||||
|
|
@ -115,6 +127,8 @@ const render = () =>
|
|||
beforeEach(() => {
|
||||
onboarding = path();
|
||||
emptyStateProps.current = null;
|
||||
cartesSnapshot = null;
|
||||
kpiProps.clear();
|
||||
});
|
||||
|
||||
describe("DashboardPage on the shared path (#352, #396, #397)", () => {
|
||||
|
|
@ -169,3 +183,36 @@ describe("DashboardPage — texts that go through t (#437)", () => {
|
|||
expect(render()).toContain(">t(dashboard.kpiSectionTitle)<");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DashboardPage — the note under « Solde net » (#392, D5)", () => {
|
||||
const kpi = (current: number): CartesKpi => ({
|
||||
current,
|
||||
previousMonth: null,
|
||||
previousYear: null,
|
||||
deltaMoMAbs: null,
|
||||
deltaMoMPct: null,
|
||||
deltaYoYAbs: null,
|
||||
deltaYoYPct: null,
|
||||
sparkline: [],
|
||||
});
|
||||
|
||||
it("hands the net card the note of the snapshot's breakdown, and no other card a note", () => {
|
||||
const netBreakdown = { uncategorized: 40, transfers: -300 };
|
||||
cartesSnapshot = {
|
||||
referenceYear: 2026,
|
||||
referenceMonth: 10,
|
||||
kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(710), savingsRate: kpi(97) },
|
||||
netBreakdown,
|
||||
flow12Months: [],
|
||||
topMoversUp: [],
|
||||
topMoversDown: [],
|
||||
budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] },
|
||||
seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null },
|
||||
};
|
||||
render();
|
||||
expect([...kpiProps.keys()]).toEqual(["income", "expenses", "net", "savingsRate"]);
|
||||
expect(kpiProps.get("net")!.note).toContain("t(reports.cartes.netNote.both[");
|
||||
expect(kpiProps.get("net")!.note).toBe(netNote(markedT, "fr", netBreakdown));
|
||||
for (const id of ["income", "expenses", "savingsRate"]) expect(kpiProps.get(id)!.note).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ import DashboardEmptyState from "../components/dashboard/DashboardEmptyState";
|
|||
import NetWorthTile from "../components/dashboard/NetWorthTile";
|
||||
import FilterPanel from "../components/reports/FilterPanel";
|
||||
import KpiCard from "../components/reports/cards/KpiCard";
|
||||
import { netNote } from "../components/reports/cards/netNote";
|
||||
import IncomeExpenseOverlayChart from "../components/reports/cards/IncomeExpenseOverlayChart";
|
||||
import TopMoversList from "../components/reports/cards/TopMoversList";
|
||||
import BudgetAdherenceCard from "../components/reports/cards/BudgetAdherenceCard";
|
||||
|
|
@ -179,6 +180,7 @@ export default function DashboardPage() {
|
|||
kpi={cartesSnapshot.kpis.net}
|
||||
format="currency"
|
||||
deltaIsBadWhenUp={false}
|
||||
note={netNote(t, i18n.language, cartesSnapshot.netBreakdown)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-[180px]">
|
||||
|
|
|
|||
96
src/pages/ReportsCartesPage.render.test.tsx
Normal file
96
src/pages/ReportsCartesPage.render.test.tsx
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
// ReportsCartesPage hands « Solde net » the note of its snapshot (#392, D5).
|
||||
// No jsdom: react-dom/server renders the page in vitest's node environment.
|
||||
// The data hook and the widgets are stubbed, and the fake KpiCard records the
|
||||
// props it receives.
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import type { CartesKpi, CartesSnapshot } from "../shared/types";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../test/i18nMock")).i18nMock());
|
||||
|
||||
let snapshot: CartesSnapshot | null = null;
|
||||
vi.mock("../hooks/useCartes", () => ({
|
||||
useCartes: () => ({
|
||||
year: 2026,
|
||||
month: 10,
|
||||
mode: "month",
|
||||
snapshot,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
setReferencePeriod: vi.fn(),
|
||||
setMode: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Hoisted with the mocks below, which run before the imports.
|
||||
const { marker, kpiProps } = vi.hoisted(() => ({
|
||||
marker: (name: string) => ({ default: () => <i data-marker={name} /> }),
|
||||
kpiProps: new Map<string, Record<string, unknown>>(),
|
||||
}));
|
||||
vi.mock("../components/reports/CompareReferenceMonthPicker", () => marker("month-picker"));
|
||||
vi.mock("../components/reports/cards/CartesPeriodModeToggle", () => marker("mode-toggle"));
|
||||
vi.mock("../components/reports/cards/KpiCard", () => ({
|
||||
default: (props: Record<string, unknown>) => {
|
||||
kpiProps.set(props.id as string, props);
|
||||
return <i data-marker="kpi" />;
|
||||
},
|
||||
}));
|
||||
vi.mock("../components/reports/cards/IncomeExpenseOverlayChart", () => marker("overlay"));
|
||||
vi.mock("../components/reports/cards/TopMoversList", () => marker("movers"));
|
||||
vi.mock("../components/reports/cards/BudgetAdherenceCard", () => marker("adherence"));
|
||||
vi.mock("../components/reports/cards/SeasonalityCard", () => marker("seasonality"));
|
||||
|
||||
import ReportsCartesPage from "./ReportsCartesPage";
|
||||
import { netNote } from "../components/reports/cards/netNote";
|
||||
import { markedT } from "../test/i18nMock";
|
||||
|
||||
const kpi = (current: number): CartesKpi => ({
|
||||
current,
|
||||
previousMonth: null,
|
||||
previousYear: null,
|
||||
deltaMoMAbs: null,
|
||||
deltaMoMPct: null,
|
||||
deltaYoYAbs: null,
|
||||
deltaYoYPct: null,
|
||||
sparkline: [],
|
||||
});
|
||||
|
||||
const render = () =>
|
||||
renderToStaticMarkup(
|
||||
<MemoryRouter>
|
||||
<ReportsCartesPage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
snapshot = null;
|
||||
kpiProps.clear();
|
||||
});
|
||||
|
||||
describe("ReportsCartesPage — the note under « Solde net » (#392, D5)", () => {
|
||||
it("hands the net card the note of the snapshot's breakdown, and no other card a note", () => {
|
||||
const netBreakdown = { uncategorized: 40, transfers: -300 };
|
||||
snapshot = {
|
||||
referenceYear: 2026,
|
||||
referenceMonth: 10,
|
||||
kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(710), savingsRate: kpi(97) },
|
||||
netBreakdown,
|
||||
flow12Months: [],
|
||||
topMoversUp: [],
|
||||
topMoversDown: [],
|
||||
budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] },
|
||||
seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null },
|
||||
};
|
||||
render();
|
||||
expect([...kpiProps.keys()]).toEqual(["income", "expenses", "net", "savingsRate"]);
|
||||
expect(kpiProps.get("net")!.note).toContain("t(reports.cartes.netNote.both[");
|
||||
expect(kpiProps.get("net")!.note).toBe(netNote(markedT, "fr", netBreakdown));
|
||||
for (const id of ["income", "expenses", "savingsRate"]) expect(kpiProps.get(id)!.note).toBeUndefined();
|
||||
});
|
||||
|
||||
it("renders no card without a snapshot", () => {
|
||||
expect(render()).toContain("t(reports.empty.noData)");
|
||||
expect(kpiProps.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -7,6 +7,7 @@ import { ArrowLeft } from "lucide-react";
|
|||
import CompareReferenceMonthPicker from "../components/reports/CompareReferenceMonthPicker";
|
||||
import CartesPeriodModeToggle from "../components/reports/cards/CartesPeriodModeToggle";
|
||||
import KpiCard from "../components/reports/cards/KpiCard";
|
||||
import { netNote } from "../components/reports/cards/netNote";
|
||||
import IncomeExpenseOverlayChart from "../components/reports/cards/IncomeExpenseOverlayChart";
|
||||
import TopMoversList from "../components/reports/cards/TopMoversList";
|
||||
import BudgetAdherenceCard from "../components/reports/cards/BudgetAdherenceCard";
|
||||
|
|
@ -14,7 +15,7 @@ import SeasonalityCard from "../components/reports/cards/SeasonalityCard";
|
|||
import { useCartes } from "../hooks/useCartes";
|
||||
|
||||
export default function ReportsCartesPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { year, month, mode, snapshot, isLoading, error, setReferencePeriod, setMode } =
|
||||
useCartes();
|
||||
|
||||
|
|
@ -84,6 +85,7 @@ export default function ReportsCartesPage() {
|
|||
kpi={snapshot.kpis.net}
|
||||
format="currency"
|
||||
deltaIsBadWhenUp={false}
|
||||
note={netNote(t, i18n.language, snapshot.netBreakdown)}
|
||||
/>
|
||||
<KpiCard
|
||||
id="savingsRate"
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { getDb } from "./db";
|
|||
import { notifyDataChanged } from "./dataEvents";
|
||||
import { inPlaceholders } from "../utils/sqlFilters";
|
||||
import { displaysAsRoot } from "../utils/categoryHierarchy";
|
||||
import { CATEGORY_JOIN_SQL, SECTION_ORDER, toCents } from "../utils/incomeStatement";
|
||||
import type {
|
||||
Category,
|
||||
BudgetEntry,
|
||||
|
|
@ -216,6 +217,12 @@ export async function getActualTotalsForYear(
|
|||
|
||||
// --- Budget vs Actual ---
|
||||
|
||||
/**
|
||||
* The signed balance of each category over the range, splits and refunds
|
||||
* included (#392, ADR 0026). Every row without an existing category (no
|
||||
* category, or one that is gone) is one group, `category_id` NULL: the
|
||||
* uncategorized line.
|
||||
*/
|
||||
async function getActualsByCategoryRange(
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
|
|
@ -224,20 +231,23 @@ async function getActualsByCategoryRange(
|
|||
const db = await getDb();
|
||||
const params: unknown[] = [dateFrom, dateTo];
|
||||
const accountPlaceholders = inPlaceholders(accountIds, params.length + 1);
|
||||
const accountFilter = accountPlaceholders ? ` AND source_id IN (${accountPlaceholders})` : "";
|
||||
const accountFilter = accountPlaceholders ? ` AND t.source_id IN (${accountPlaceholders})` : "";
|
||||
if (accountPlaceholders) params.push(...accountIds!);
|
||||
return db.select<Array<{ category_id: number | null; actual: number }>>(
|
||||
`SELECT category_id, COALESCE(SUM(amount), 0) AS actual
|
||||
FROM transactions
|
||||
WHERE date BETWEEN $1 AND $2${accountFilter}
|
||||
GROUP BY category_id`,
|
||||
const rows = await db.select<Array<{ category_id: number | null; actual: number | null }>>(
|
||||
`SELECT c.id AS category_id, COALESCE(SUM(t.amount), 0) AS actual
|
||||
FROM transactions t
|
||||
${CATEGORY_JOIN_SQL}
|
||||
WHERE t.date BETWEEN $1 AND $2${accountFilter}
|
||||
GROUP BY c.id`,
|
||||
params
|
||||
);
|
||||
return rows.map((r) => ({ category_id: r.category_id, actual: toCents(Number(r.actual ?? 0)) }));
|
||||
}
|
||||
|
||||
// Income-statement reading order: revenue first, then expenses, then
|
||||
// transfers (Issue #277 — matches COMPARE_TYPE_ORDER / OVER_TIME_TYPE_ORDER).
|
||||
const TYPE_ORDER: Record<string, number> = { income: 0, expense: 1, transfer: 2 };
|
||||
// Income-statement reading order: revenue first, then expenses, the
|
||||
// uncategorized line, then transfers (Issue #277, ADR 0026 — matches
|
||||
// COMPARE_TYPE_ORDER / OVER_TIME_TYPE_ORDER).
|
||||
const TYPE_ORDER: Record<string, number> = SECTION_ORDER;
|
||||
|
||||
/**
|
||||
* Budget vs actual, by category, for the reference month plus YTD. `accountIds`
|
||||
|
|
@ -271,13 +281,17 @@ export async function getBudgetVsActualData(
|
|||
}
|
||||
|
||||
const monthActualMap = new Map<number, number>();
|
||||
let monthUncategorized = 0;
|
||||
for (const a of monthActuals) {
|
||||
if (a.category_id != null) monthActualMap.set(a.category_id, a.actual);
|
||||
else monthUncategorized = a.actual;
|
||||
}
|
||||
|
||||
const ytdActualMap = new Map<number, number>();
|
||||
let ytdUncategorized = 0;
|
||||
for (const a of ytdActuals) {
|
||||
if (a.category_id != null) ytdActualMap.set(a.category_id, a.actual);
|
||||
else ytdUncategorized = a.actual;
|
||||
}
|
||||
|
||||
// Index categories
|
||||
|
|
@ -459,6 +473,28 @@ export async function getBudgetVsActualData(
|
|||
}
|
||||
}
|
||||
|
||||
// The uncategorized line (D4, #392): its actuals, no budget, counted in the
|
||||
// result lines but neither income nor expense. Its label comes from the UI.
|
||||
if (monthUncategorized !== 0 || ytdUncategorized !== 0) {
|
||||
rows.push({
|
||||
category_id: null,
|
||||
category_name: "",
|
||||
category_color: "#9ca3af",
|
||||
category_type: "uncategorized",
|
||||
parent_id: null,
|
||||
is_parent: false,
|
||||
depth: 0,
|
||||
monthActual: monthUncategorized,
|
||||
monthBudget: 0,
|
||||
monthVariation: monthUncategorized,
|
||||
monthVariationPct: null,
|
||||
ytdActual: ytdUncategorized,
|
||||
ytdBudget: 0,
|
||||
ytdVariation: ytdUncategorized,
|
||||
ytdVariationPct: null,
|
||||
});
|
||||
}
|
||||
|
||||
// Sort by type only, preserving tree order within groups (already built correctly)
|
||||
const rowOrder = new Map<BudgetVsActualRow, number>();
|
||||
rows.forEach((r, i) => rowOrder.set(r, i));
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ describe("getExpensesByCategory — accountIds filter (Issue #273)", () => {
|
|||
const sql = mockSelect.mock.calls[0][0] as string;
|
||||
const params = mockSelect.mock.calls[0][1] as unknown[];
|
||||
expect(sql).toContain("t.source_id IN ($1)");
|
||||
expect(sql).toContain("COALESCE(c.type, 'expense') = 'expense'");
|
||||
expect(sql).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END = 'expense'");
|
||||
expect(params).toEqual([2]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,59 +1,20 @@
|
|||
import { getDb } from "./db";
|
||||
import { inPlaceholders } from "../utils/sqlFilters";
|
||||
import { CATEGORY_JOIN_SQL, SECTION_SQL, orient } from "../utils/incomeStatement";
|
||||
import { deriveLandingState } from "../components/balance/balanceLanding";
|
||||
import type { SnapshotTotalPoint } from "./balance.service";
|
||||
import type {
|
||||
DashboardSummary,
|
||||
CategoryBreakdownItem,
|
||||
RecentTransaction,
|
||||
TransactionRow,
|
||||
} from "../shared/types";
|
||||
|
||||
export async function getDashboardSummary(
|
||||
dateFrom?: string,
|
||||
dateTo?: string
|
||||
): Promise<DashboardSummary> {
|
||||
const db = await getDb();
|
||||
|
||||
const whereClauses: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (dateFrom) {
|
||||
whereClauses.push(`date >= $${paramIndex}`);
|
||||
params.push(dateFrom);
|
||||
paramIndex++;
|
||||
}
|
||||
if (dateTo) {
|
||||
whereClauses.push(`date <= $${paramIndex}`);
|
||||
params.push(dateTo);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
const whereSQL =
|
||||
whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
|
||||
|
||||
const rows = await db.select<
|
||||
Array<{
|
||||
totalCount: number;
|
||||
totalAmount: number;
|
||||
incomeTotal: number;
|
||||
expenseTotal: number;
|
||||
}>
|
||||
>(
|
||||
`SELECT
|
||||
COUNT(*) AS totalCount,
|
||||
COALESCE(SUM(amount), 0) AS totalAmount,
|
||||
COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) AS incomeTotal,
|
||||
COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0) AS expenseTotal
|
||||
FROM transactions
|
||||
${whereSQL}`,
|
||||
params
|
||||
);
|
||||
|
||||
return rows[0] ?? { totalCount: 0, totalAmount: 0, incomeTotal: 0, expenseTotal: 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The spending of each expense category over the period, largest first: the
|
||||
* opposite of its signed balance, refunds and splits netted (#392, ADR 0026),
|
||||
* negative for a category whose refunds exceed its purchases. The rows
|
||||
* without a category are no expense: they stay out (D4).
|
||||
*/
|
||||
export async function getExpensesByCategory(
|
||||
dateFrom?: string,
|
||||
dateTo?: string,
|
||||
|
|
@ -61,7 +22,7 @@ export async function getExpensesByCategory(
|
|||
): Promise<CategoryBreakdownItem[]> {
|
||||
const db = await getDb();
|
||||
|
||||
const whereClauses: string[] = ["COALESCE(c.type, 'expense') = 'expense'"];
|
||||
const whereClauses: string[] = [`${SECTION_SQL} = 'expense'`];
|
||||
const params: unknown[] = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
|
|
@ -84,19 +45,27 @@ export async function getExpensesByCategory(
|
|||
|
||||
const whereSQL = `WHERE ${whereClauses.join(" AND ")}`;
|
||||
|
||||
return db.select<CategoryBreakdownItem[]>(
|
||||
const rows = await db.select<
|
||||
Array<{ category_id: number; category_name: string; category_color: string; balance: number | null }>
|
||||
>(
|
||||
`SELECT
|
||||
t.category_id,
|
||||
COALESCE(c.name, 'Uncategorized') AS category_name,
|
||||
c.id AS category_id,
|
||||
c.name AS category_name,
|
||||
COALESCE(c.color, '#9ca3af') AS category_color,
|
||||
ABS(SUM(t.amount)) AS total
|
||||
SUM(t.amount) AS balance
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
${CATEGORY_JOIN_SQL}
|
||||
${whereSQL}
|
||||
GROUP BY t.category_id
|
||||
ORDER BY total DESC`,
|
||||
GROUP BY c.id
|
||||
ORDER BY balance ASC`,
|
||||
params
|
||||
);
|
||||
return rows.map((r) => ({
|
||||
category_id: r.category_id,
|
||||
category_name: r.category_name,
|
||||
category_color: r.category_color,
|
||||
total: orient("expense", Number(r.balance ?? 0)),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getTransactionsByCategory(
|
||||
|
|
|
|||
|
|
@ -54,6 +54,40 @@ function routeSelect(routes: { match: string; rows: unknown[] }[]): void {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of the monthly query (`getMonthlyTrends`, #392) for months given as
|
||||
* income and expenses: one signed balance per section, an expense's negative.
|
||||
*/
|
||||
function flowRows(months: Array<{ month: string; income: number; expenses: number }>): unknown[] {
|
||||
return months.flatMap(({ month, income, expenses }) => [
|
||||
{ month, section: "income", balance: income },
|
||||
{ month, section: "expense", balance: -expenses },
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare rows of expense categories given as spending: the query returns
|
||||
* their signed balance (the opposite) with their section (#392).
|
||||
*/
|
||||
function expenseRows(rows: Array<Record<string, unknown> & {
|
||||
month_current_total: number;
|
||||
month_previous_total: number;
|
||||
cumulative_current_total: number;
|
||||
cumulative_previous_total: number;
|
||||
}>): unknown[] {
|
||||
return rows.map((r) => ({
|
||||
...r,
|
||||
section: "expense",
|
||||
month_current_total: -r.month_current_total,
|
||||
month_previous_total: -r.month_previous_total,
|
||||
cumulative_current_total: -r.cumulative_current_total,
|
||||
cumulative_previous_total: -r.cumulative_previous_total,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The monthly query, the only snapshot query selecting a "%Y-%m" month. */
|
||||
const FLOWS = "strftime('%Y-%m', t.date) AS month";
|
||||
|
||||
describe("getCartesSnapshot", () => {
|
||||
it("returns zero-filled KPIs when there is no data", async () => {
|
||||
routeSelect([]);
|
||||
|
|
@ -79,12 +113,12 @@ describe("getCartesSnapshot", () => {
|
|||
// Reference = 2026-03
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
{ month: "2025-03", income: 3000, expenses: 1800 }, // YoY comparison
|
||||
{ month: "2026-02", income: 4000, expenses: 2000 }, // MoM comparison
|
||||
{ month: "2026-03", income: 5000, expenses: 2500 }, // Reference
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -106,11 +140,11 @@ describe("getCartesSnapshot", () => {
|
|||
it("January reference month shifts MoM to December of previous year", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
{ month: "2025-12", income: 2000, expenses: 1000 },
|
||||
{ month: "2026-01", income: 3000, expenses: 1500 },
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -126,10 +160,10 @@ describe("getCartesSnapshot", () => {
|
|||
it("savings rate is null when income is zero (no division by zero, renders as — in UI)", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
{ month: "2026-03", income: 0, expenses: 500 },
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -143,10 +177,10 @@ describe("getCartesSnapshot", () => {
|
|||
it("handles less than 13 months of history by filling gaps with zero", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
{ month: "2026-03", income: 1000, expenses: 400 },
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -163,14 +197,15 @@ describe("getCartesSnapshot", () => {
|
|||
it("computes seasonality only when historical data exists", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [{ month: "2026-03", income: 3000, expenses: 1500 }],
|
||||
match: FLOWS,
|
||||
rows: flowRows([{ month: "2026-03", income: 3000, expenses: 1500 }]),
|
||||
},
|
||||
{
|
||||
match: "CAST(strftime('%Y', date) AS INTEGER) AS year",
|
||||
// The expense balance of March in each year: spending 1200 and 1000.
|
||||
match: "CAST(strftime('%Y', t.date) AS INTEGER) AS year",
|
||||
rows: [
|
||||
{ year: 2025, amount: 1200 },
|
||||
{ year: 2024, amount: 1000 },
|
||||
{ year: 2025, balance: -1200 },
|
||||
{ year: 2024, balance: -1000 },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
|
@ -186,8 +221,8 @@ describe("getCartesSnapshot", () => {
|
|||
it("seasonality deviation stays null when there is no historical average", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [{ month: "2026-03", income: 2000, expenses: 800 }],
|
||||
match: FLOWS,
|
||||
rows: flowRows([{ month: "2026-03", income: 2000, expenses: 800 }]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -201,8 +236,9 @@ describe("getCartesSnapshot", () => {
|
|||
// Seven up-movers, three down-movers — verify we get 5 up and 3 down.
|
||||
// Cumulative totals mirror the monthly ones in this fixture — the Cartes
|
||||
// service only reads the monthly block for top movers, so cumulative
|
||||
// values are inert here.
|
||||
const momRows = [
|
||||
// values are inert here. The compare query returns signed balances with
|
||||
// their section (#392): an expense that spent 200 has a balance of −200.
|
||||
const momRows = expenseRows([
|
||||
{ category_id: 1, category_name: "C1", category_color: "#000", month_current_total: 200, month_previous_total: 100, cumulative_current_total: 200, cumulative_previous_total: 100 },
|
||||
{ category_id: 2, category_name: "C2", category_color: "#000", month_current_total: 400, month_previous_total: 100, cumulative_current_total: 400, cumulative_previous_total: 100 },
|
||||
{ category_id: 3, category_name: "C3", category_color: "#000", month_current_total: 500, month_previous_total: 100, cumulative_current_total: 500, cumulative_previous_total: 100 },
|
||||
|
|
@ -213,11 +249,11 @@ describe("getCartesSnapshot", () => {
|
|||
{ category_id: 8, category_name: "D1", category_color: "#000", month_current_total: 100, month_previous_total: 500, cumulative_current_total: 100, cumulative_previous_total: 500 },
|
||||
{ category_id: 9, category_name: "D2", category_color: "#000", month_current_total: 100, month_previous_total: 700, cumulative_current_total: 100, cumulative_previous_total: 700 },
|
||||
{ category_id: 10, category_name: "D3", category_color: "#000", month_current_total: 100, month_previous_total: 900, cumulative_current_total: 100, cumulative_previous_total: 900 },
|
||||
];
|
||||
]);
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [{ month: "2026-03", income: 1000, expenses: 500 }],
|
||||
match: FLOWS,
|
||||
rows: flowRows([{ month: "2026-03", income: 1000, expenses: 500 }]),
|
||||
},
|
||||
{
|
||||
// Matches the getCompareMonthOverMonth SQL pattern.
|
||||
|
|
@ -240,14 +276,17 @@ describe("getCartesSnapshot", () => {
|
|||
// revenue rows now reach getCartesSnapshot. Top movers is a spending view
|
||||
// (up = red), so income must be filtered out — otherwise a salary jump tops
|
||||
// "biggest increases" in red. The category metadata query types id 99 as
|
||||
// income; the two expense movers are absent from it and default to expense.
|
||||
// income; the two expense movers are absent from it and keep the section
|
||||
// the query gives them.
|
||||
const momRows = [
|
||||
{ category_id: 99, category_name: "Salaire", category_color: "#000", month_current_total: 5000, month_previous_total: 100, cumulative_current_total: 5000, cumulative_previous_total: 100 },
|
||||
{ category_id: 1, category_name: "Épicerie", category_color: "#000", month_current_total: 300, month_previous_total: 100, cumulative_current_total: 300, cumulative_previous_total: 100 },
|
||||
{ category_id: 2, category_name: "Resto", category_color: "#000", month_current_total: 100, month_previous_total: 400, cumulative_current_total: 100, cumulative_previous_total: 400 },
|
||||
{ category_id: 99, category_name: "Salaire", category_color: "#000", section: "income", month_current_total: 5000, month_previous_total: 100, cumulative_current_total: 5000, cumulative_previous_total: 100 },
|
||||
...expenseRows([
|
||||
{ category_id: 1, category_name: "Épicerie", category_color: "#000", month_current_total: 300, month_previous_total: 100, cumulative_current_total: 300, cumulative_previous_total: 100 },
|
||||
{ category_id: 2, category_name: "Resto", category_color: "#000", month_current_total: 100, month_previous_total: 400, cumulative_current_total: 100, cumulative_previous_total: 400 },
|
||||
]),
|
||||
];
|
||||
routeSelect([
|
||||
{ match: "strftime('%Y-%m', date)", rows: [{ month: "2026-03", income: 5000, expenses: 400 }] },
|
||||
{ match: FLOWS, rows: flowRows([{ month: "2026-03", income: 5000, expenses: 400 }]) },
|
||||
{ match: "ORDER BY ABS(month_current_total - month_previous_total) DESC", rows: momRows },
|
||||
{ match: "parent_id FROM categories", rows: [{ id: 99, name: "Salaire", color: null, type: "income", parent_id: null }] },
|
||||
]);
|
||||
|
|
@ -266,8 +305,8 @@ describe("getCartesSnapshot", () => {
|
|||
// Reference = 2026-03, YTD = Jan + Feb + Mar of 2026.
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
// Previous year YTD: Jan + Feb + Mar 2025 = income 3000, expenses 1500.
|
||||
{ month: "2025-01", income: 1000, expenses: 500 },
|
||||
{ month: "2025-02", income: 1000, expenses: 500 },
|
||||
|
|
@ -276,7 +315,7 @@ describe("getCartesSnapshot", () => {
|
|||
{ month: "2026-01", income: 2000, expenses: 800 },
|
||||
{ month: "2026-02", income: 2500, expenses: 1000 },
|
||||
{ month: "2026-03", income: 3000, expenses: 1200 },
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -303,12 +342,12 @@ describe("getCartesSnapshot", () => {
|
|||
it("YTD savings rate is null when YTD income is zero", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
{ month: "2026-01", income: 0, expenses: 200 },
|
||||
{ month: "2026-02", income: 0, expenses: 150 },
|
||||
{ month: "2026-03", income: 0, expenses: 300 },
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -321,11 +360,11 @@ describe("getCartesSnapshot", () => {
|
|||
it("YTD MoM delta is null when reference month is January (no prior YTD window in same year)", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
{ month: "2025-01", income: 500, expenses: 200 },
|
||||
{ month: "2026-01", income: 1000, expenses: 400 },
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -344,8 +383,8 @@ describe("getCartesSnapshot", () => {
|
|||
it("YTD YoY delta uses Jan→refMonth of the previous year", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
// Prev year YTD Jan→Apr 2025
|
||||
{ month: "2025-01", income: 100, expenses: 50 },
|
||||
{ month: "2025-02", income: 100, expenses: 50 },
|
||||
|
|
@ -358,7 +397,7 @@ describe("getCartesSnapshot", () => {
|
|||
{ month: "2026-02", income: 300, expenses: 100 },
|
||||
{ month: "2026-03", income: 300, expenses: 100 },
|
||||
{ month: "2026-04", income: 300, expenses: 100 },
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -373,12 +412,12 @@ describe("getCartesSnapshot", () => {
|
|||
it("defaults to mode=month and produces monthly KPIs (back-compat)", async () => {
|
||||
routeSelect([
|
||||
{
|
||||
match: "strftime('%Y-%m', date)",
|
||||
rows: [
|
||||
match: FLOWS,
|
||||
rows: flowRows([
|
||||
{ month: "2026-01", income: 1000, expenses: 400 },
|
||||
{ month: "2026-02", income: 1000, expenses: 400 },
|
||||
{ month: "2026-03", income: 5000, expenses: 2500 },
|
||||
],
|
||||
]),
|
||||
},
|
||||
]);
|
||||
|
||||
|
|
@ -447,7 +486,7 @@ describe("getCartesSnapshot", () => {
|
|||
{
|
||||
// Matches both the monthly and YTD actuals queries; for this test
|
||||
// the YTD slice can mirror the monthly one.
|
||||
match: "FROM transactions\n WHERE date BETWEEN",
|
||||
match: "AS actual",
|
||||
rows: [
|
||||
{ category_id: 10, actual: -400 }, // 400 spent against 500 budget -> in target
|
||||
{ category_id: 11, actual: -350 }, // 350 spent against 200 budget -> overrun
|
||||
|
|
@ -497,7 +536,7 @@ describe("getCartesSnapshot", () => {
|
|||
await getCartesSnapshot(2026, 3, "month", [3, 8]);
|
||||
|
||||
const actualsCalls = mockSelect.mock.calls.filter(([sql]) =>
|
||||
(sql as string).includes("FROM transactions\n WHERE date BETWEEN"),
|
||||
(sql as string).includes("AS actual"),
|
||||
);
|
||||
// Both the month and YTD actuals queries (getBudgetVsActualData) receive it.
|
||||
expect(actualsCalls.length).toBeGreaterThanOrEqual(2);
|
||||
|
|
@ -512,11 +551,8 @@ describe("getCartesSnapshot", () => {
|
|||
|
||||
await getCartesSnapshot(2026, 3, "month", [3, 8]);
|
||||
|
||||
// fetchMonthlyFlows is the only snapshot query selecting a "%Y-%m" month.
|
||||
const flowCall = mockSelect.mock.calls.find(([sql]) =>
|
||||
(sql as string).includes("strftime('%Y-%m', date) AS month"),
|
||||
)!;
|
||||
expect(flowCall[0]).toContain("AND source_id IN ($3, $4)");
|
||||
const flowCall = mockSelect.mock.calls.find(([sql]) => (sql as string).includes(FLOWS))!;
|
||||
expect(flowCall[0]).toContain("AND t.source_id IN ($3, $4)");
|
||||
expect(flowCall[1]).toEqual(expect.arrayContaining([3, 8]));
|
||||
});
|
||||
|
||||
|
|
@ -527,9 +563,9 @@ describe("getCartesSnapshot", () => {
|
|||
|
||||
// fetchSeasonality is the only snapshot query filtering on a "%m" month.
|
||||
const seasonalityCall = mockSelect.mock.calls.find(([sql]) =>
|
||||
(sql as string).includes("strftime('%m', date) = $1"),
|
||||
(sql as string).includes("strftime('%m', t.date) = $1"),
|
||||
)!;
|
||||
expect(seasonalityCall[0]).toContain("AND source_id IN ($4, $5)");
|
||||
expect(seasonalityCall[0]).toContain("AND t.source_id IN ($4, $5)");
|
||||
expect(seasonalityCall[1]).toEqual(expect.arrayContaining([3, 8]));
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ describe("getMonthlyTrends", () => {
|
|||
|
||||
const sql = mockSelect.mock.calls[0][0] as string;
|
||||
const params = mockSelect.mock.calls[0][1] as unknown[];
|
||||
expect(sql).toContain("WHERE source_id IN ($1)");
|
||||
expect(sql).toContain("WHERE t.source_id IN ($1)");
|
||||
expect(params).toEqual([5]);
|
||||
});
|
||||
});
|
||||
|
|
@ -113,7 +113,7 @@ describe("getCategoryOverTime", () => {
|
|||
|
||||
const topCatSQL = mockSelect.mock.calls[0][0] as string;
|
||||
const topCatParams = mockSelect.mock.calls[0][1] as unknown[];
|
||||
expect(topCatSQL).toContain("COALESCE(c.type, 'expense')");
|
||||
expect(topCatSQL).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END");
|
||||
expect(topCatSQL).toContain("WHERE");
|
||||
expect(topCatParams[0]).toBe("expense");
|
||||
});
|
||||
|
|
@ -127,7 +127,7 @@ describe("getCategoryOverTime", () => {
|
|||
|
||||
const topCatSQL = mockSelect.mock.calls[0][0] as string;
|
||||
const topCatParams = mockSelect.mock.calls[0][1] as unknown[];
|
||||
expect(topCatSQL).toContain("COALESCE(c.type, 'expense') = $1");
|
||||
expect(topCatSQL).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END = $1");
|
||||
expect(topCatParams[0]).toBe("income");
|
||||
// Date params follow
|
||||
expect(topCatParams[1]).toBe("2025-01-01");
|
||||
|
|
@ -198,14 +198,14 @@ describe("getCategoryOverTime", () => {
|
|||
|
||||
const topCatSQL = mockSelect.mock.calls[0][0] as string;
|
||||
const topCatParams = mockSelect.mock.calls[0][1] as unknown[];
|
||||
expect(topCatSQL).toContain("COALESCE(c.type, 'expense') = $1");
|
||||
expect(topCatSQL).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END = $1");
|
||||
expect(topCatSQL).toContain("t.date >= $2");
|
||||
expect(topCatSQL).toContain("t.date <= $3");
|
||||
expect(topCatSQL).toContain("t.source_id IN ($4)");
|
||||
expect(topCatParams).toEqual(["expense", "2025-01-01", "2025-06-30", 2, 10]);
|
||||
});
|
||||
|
||||
it("projects category type into the top-N SELECT", async () => {
|
||||
it("projects the section of each category into the top-N SELECT (#392)", async () => {
|
||||
mockSelect
|
||||
.mockResolvedValueOnce([]) // topCategories
|
||||
.mockResolvedValueOnce([]); // monthlyRows
|
||||
|
|
@ -213,7 +213,7 @@ describe("getCategoryOverTime", () => {
|
|||
await getCategoryOverTime();
|
||||
|
||||
const topCatSQL = mockSelect.mock.calls[0][0] as string;
|
||||
expect(topCatSQL).toContain("COALESCE(c.type, 'expense') AS category_type");
|
||||
expect(topCatSQL).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END AS category_type");
|
||||
});
|
||||
|
||||
it("returns correct structure with categories, data, colors, categoryIds, and types", async () => {
|
||||
|
|
@ -240,17 +240,17 @@ describe("getCategoryOverTime", () => {
|
|||
expect(result.data[1]).toEqual({ month: "2025-02", Food: 200, Salary: 100 });
|
||||
});
|
||||
|
||||
it("defaults a null category type to expense in the types map", async () => {
|
||||
it("reads a missing section as the uncategorized one in the types map (#392)", async () => {
|
||||
mockSelect
|
||||
.mockResolvedValueOnce([
|
||||
// COALESCE(c.type, 'expense') yields 'expense'; a null slipping through defaults too.
|
||||
// The SQL gives every row its section; a null slipping through is no category type.
|
||||
{ category_id: 1, category_name: "Food", category_color: "#ff0000", category_type: null, total: 500 },
|
||||
])
|
||||
.mockResolvedValueOnce([{ month: "2025-01", category_id: 1, category_name: "Food", total: 300 }]);
|
||||
|
||||
const result = await getCategoryOverTime();
|
||||
|
||||
expect(result.types).toEqual({ Food: "expense" });
|
||||
expect(result.types).toEqual({ Food: "uncategorized" });
|
||||
});
|
||||
|
||||
it("keeps the pivot top-N + Other but the id-keyed tree carries every category (Issue #264)", async () => {
|
||||
|
|
@ -403,6 +403,17 @@ describe("getHighlights", () => {
|
|||
expect(moversParams[3]).toBe("2026-02-28");
|
||||
});
|
||||
|
||||
it("ranks movers among expense categories only, on signed amounts (#392)", async () => {
|
||||
queueEmpty(5);
|
||||
|
||||
await getHighlights(REF_YEAR, REF_MONTH, YTD_YEAR, 30, 5, 10, TODAY);
|
||||
|
||||
const moversSql = mockSelect.mock.calls[3][0] as string;
|
||||
expect(moversSql).toContain("WHERE CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END = 'expense'");
|
||||
expect(moversSql).not.toContain("ABS(t.amount)");
|
||||
expect(moversSql).not.toMatch(/t\.amount\s*[<>]/);
|
||||
});
|
||||
|
||||
it("wraps January reference month back to December of the previous year for top movers", async () => {
|
||||
queueEmpty(5);
|
||||
|
||||
|
|
@ -415,7 +426,7 @@ describe("getHighlights", () => {
|
|||
expect(moversParams[3]).toBe("2025-12-31");
|
||||
});
|
||||
|
||||
it("computes deltaAbs and deltaPct from movers rows", async () => {
|
||||
it("computes deltaAbs and deltaPct from movers rows, each on its spending (#392)", async () => {
|
||||
mockSelect
|
||||
.mockResolvedValueOnce([{ net: -500 }]) // current balance
|
||||
.mockResolvedValueOnce([{ net: -1800 }]) // ytd
|
||||
|
|
@ -423,20 +434,21 @@ describe("getHighlights", () => {
|
|||
{ month: "2026-03", net: -500 },
|
||||
{ month: "2026-02", net: -400 },
|
||||
]) // series
|
||||
// Signed balances of expense categories: spending 240 and 200, 85 and 170.
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
category_id: 1,
|
||||
category_name: "Restaurants",
|
||||
category_color: "#f97316",
|
||||
current_total: 240,
|
||||
previous_total: 200,
|
||||
current_total: -240,
|
||||
previous_total: -200,
|
||||
},
|
||||
{
|
||||
category_id: 2,
|
||||
category_name: "Groceries",
|
||||
category_color: "#10b981",
|
||||
current_total: 85,
|
||||
previous_total: 170,
|
||||
current_total: -85,
|
||||
previous_total: -170,
|
||||
},
|
||||
])
|
||||
.mockResolvedValueOnce([]); // recent
|
||||
|
|
@ -467,7 +479,7 @@ describe("getHighlights", () => {
|
|||
category_id: 3,
|
||||
category_name: "New expense",
|
||||
category_color: "#3b82f6",
|
||||
current_total: 120,
|
||||
current_total: -120,
|
||||
previous_total: 0,
|
||||
},
|
||||
])
|
||||
|
|
@ -708,122 +720,108 @@ describe("getCompareYearOverYear", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("real-vs-real compare — transfer netting (Issue #243)", () => {
|
||||
// A `transfer` category (e.g. "Paiement CC") is a money move, not spending:
|
||||
// its debit and matching credit must cancel to ~0 in the real-vs-real
|
||||
// compare. Ordinary categories keep the expense-report behavior (only
|
||||
// outflows, summed as positive magnitudes). The netting lives entirely in
|
||||
// the SQL (COMPARE_DELTA_SQL): a signed SUM(t.amount) for `transfer`,
|
||||
// ABS(t.amount) filtered on amount < 0 for plain expenses. Income, like
|
||||
// transfers, is a signed SUM (Issue #253); the WHERE is broadened so
|
||||
// income/transfer credits are not dropped before they can count or cancel.
|
||||
//
|
||||
// There is no runnable SQLite in these unit tests (tauri-plugin-sql only
|
||||
// exists inside the Tauri WebView, and no harness opens node:sqlite yet:
|
||||
// CI runs Node 24 since #376, which has it, and #392 plans that harness), so
|
||||
// the netting is pinned two ways: (1) a reference-semantics check over
|
||||
// concrete debit/credit rows that reproduces the exact per-row rule the SQL
|
||||
// encodes, and (2) structural assertions that the real query on BOTH compare
|
||||
// functions carries that rule and the broadened WHERE.
|
||||
describe("real-vs-real compare — signed balances (Issues #243, #392)", () => {
|
||||
// The compare sums the SIGNED amounts of each category in each date bucket,
|
||||
// with the category's section (ADR 0026); rowsToDeltas shows an expense
|
||||
// category its spending, the opposite of its balance. A split is counted once
|
||||
// (its offset line cancels, in the parent's category, the parts sent
|
||||
// elsewhere), a refund lowers its category, a transfer debit/credit pair nets
|
||||
// to 0 (#243), and the rows without a category are one uncategorized line.
|
||||
// These figures are proved on a real database, with the real split service,
|
||||
// by src/__integration__/report-totals.test.ts; here, the shape of the query
|
||||
// and what rowsToDeltas makes of its rows.
|
||||
|
||||
/** Per-row contribution to a bucket — the exact rule COMPARE_DELTA_SQL encodes. */
|
||||
function bucketContribution(amount: number, type: string | null): number {
|
||||
const t = type ?? "expense";
|
||||
return t === "transfer" || t === "income"
|
||||
? amount // signed → transfer debit/credit cancel; income credits kept as revenue (#253)
|
||||
: amount < 0
|
||||
? Math.abs(amount) // expense outflow as a positive magnitude
|
||||
: 0; // other (expense) credits dropped — the report stays outflow-only for them
|
||||
}
|
||||
|
||||
it("nets a balanced transfer to ~0 while an expense keeps its sum of outflows", () => {
|
||||
// "Paiement CC" (transfer): -500 out of chequing, +500 onto the card.
|
||||
const transfer = [-500, 500].reduce((s, a) => s + bucketContribution(a, "transfer"), 0);
|
||||
expect(transfer).toBeCloseTo(0, 6);
|
||||
|
||||
// "Épicerie" (expense): two debits + one refund credit that must NOT net it down.
|
||||
const expense = [-120, -80, 60].reduce((s, a) => s + bucketContribution(a, "expense"), 0);
|
||||
expect(expense).toBe(200);
|
||||
|
||||
// Uncategorized (c.type NULL) defaults to expense behavior.
|
||||
const uncategorized = [-40, 15].reduce((s, a) => s + bucketContribution(a, null), 0);
|
||||
expect(uncategorized).toBe(40);
|
||||
|
||||
// Income (paie + a small correction) is a signed SUM — credits are kept as
|
||||
// revenue (Issue #253), not dropped like non-transfer expense credits.
|
||||
const income = [4200, 150, -50].reduce((s, a) => s + bucketContribution(a, "income"), 0);
|
||||
expect(income).toBe(4300);
|
||||
});
|
||||
|
||||
it("getCompareMonthOverMonth SQL nets transfers (signed) but keeps ABS for other types", async () => {
|
||||
it.each([
|
||||
["getCompareMonthOverMonth", () => getCompareMonthOverMonth(2026, 4)],
|
||||
["getCompareYearOverYear", () => getCompareYearOverYear(2026, 4)],
|
||||
])("%s sums signed amounts by section, with neither ABS nor a sign filter", async (_name, run) => {
|
||||
mockSelect.mockResolvedValueOnce([]);
|
||||
|
||||
await getCompareMonthOverMonth(2026, 4);
|
||||
await run();
|
||||
|
||||
const sql = mockSelect.mock.calls[0][0] as string;
|
||||
// transfer → signed t.amount; every other type → ABS(t.amount)
|
||||
expect(sql).toContain(
|
||||
"COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount)",
|
||||
);
|
||||
// WHERE broadened so transfer credits survive the expense (amount < 0) filter
|
||||
expect(sql).toContain(
|
||||
"WHERE (t.amount < 0 OR COALESCE(c.type, 'expense') IN ('transfer', 'income'))",
|
||||
);
|
||||
expect(sql).toContain("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END AS section");
|
||||
expect(sql).toContain("COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN t.amount ELSE 0 END), 0) AS month_current_total");
|
||||
// Every row without an existing category is one group.
|
||||
expect(sql).toContain("GROUP BY c.id");
|
||||
expect(sql).not.toContain("ABS(t.amount)");
|
||||
expect(sql).not.toMatch(/t\.amount\s*[<>]/);
|
||||
// still four date buckets
|
||||
expect(sql).toContain("month_current_total");
|
||||
expect(sql).toContain("cumulative_previous_total");
|
||||
});
|
||||
|
||||
it("getCompareYearOverYear applies the identical netting contract (both tabs fixed)", async () => {
|
||||
mockSelect.mockResolvedValueOnce([]);
|
||||
|
||||
await getCompareYearOverYear(2026, 4);
|
||||
|
||||
const sql = mockSelect.mock.calls[0][0] as string;
|
||||
expect(sql).toContain(
|
||||
"COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount)",
|
||||
);
|
||||
expect(sql).toContain(
|
||||
"WHERE (t.amount < 0 OR COALESCE(c.type, 'expense') IN ('transfer', 'income'))",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a netted transfer at 0 through the pipeline while an expense is unchanged", async () => {
|
||||
// Rows as the netted SQL returns them: the balanced transfer arrives at 0,
|
||||
// the ordinary expense keeps its outflow sum. Assert nothing downstream
|
||||
// re-inflates the transfer.
|
||||
it("shows an expense its spending, keeps a netted transfer at 0, and the uncategorized line apart", async () => {
|
||||
mockSelect.mockResolvedValueOnce([
|
||||
{
|
||||
category_id: 5,
|
||||
category_name: "Épicerie",
|
||||
category_color: "#10b981",
|
||||
month_current_total: 200,
|
||||
month_previous_total: 150,
|
||||
cumulative_current_total: 800,
|
||||
cumulative_previous_total: 600,
|
||||
section: "expense",
|
||||
month_current_total: -200,
|
||||
month_previous_total: -150,
|
||||
cumulative_current_total: -800,
|
||||
cumulative_previous_total: -600,
|
||||
},
|
||||
{
|
||||
category_id: 71,
|
||||
category_name: "Paiement CC",
|
||||
category_color: "#9ca3af",
|
||||
section: "transfer",
|
||||
month_current_total: 0,
|
||||
month_previous_total: 0,
|
||||
cumulative_current_total: 0,
|
||||
cumulative_previous_total: 0,
|
||||
},
|
||||
{
|
||||
category_id: null,
|
||||
category_name: "Uncategorized",
|
||||
category_color: "#9ca3af",
|
||||
section: "uncategorized",
|
||||
month_current_total: 40,
|
||||
month_previous_total: 0,
|
||||
cumulative_current_total: 40,
|
||||
cumulative_previous_total: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await getCompareMonthOverMonth(2026, 4);
|
||||
const transferRow = result.find((r) => r.categoryName === "Paiement CC")!;
|
||||
const expenseRow = result.find((r) => r.categoryName === "Épicerie")!;
|
||||
const transferRow = result.find((r) => r.categoryName === "Paiement CC")!;
|
||||
const uncategorized = result.find((r) => r.categoryId === null)!;
|
||||
|
||||
expect(transferRow.currentAmount).toBe(0);
|
||||
expect(transferRow.previousAmount).toBe(0);
|
||||
expect(transferRow.deltaAbs).toBe(0);
|
||||
expect(transferRow.cumulativeCurrentAmount).toBe(0);
|
||||
// Ordinary expense keeps EXACTLY its sum of outflows.
|
||||
expect(expenseRow.currentAmount).toBe(200);
|
||||
expect(expenseRow.previousAmount).toBe(150);
|
||||
// The expense shows its spending: the opposite of its balance.
|
||||
expect(expenseRow).toMatchObject({
|
||||
currentAmount: 200,
|
||||
previousAmount: 150,
|
||||
deltaAbs: 50,
|
||||
cumulativeCurrentAmount: 800,
|
||||
cumulativePreviousAmount: 600,
|
||||
category_type: "expense",
|
||||
});
|
||||
// Nothing downstream re-inflates the netted transfer.
|
||||
expect(transferRow).toMatchObject({ currentAmount: 0, previousAmount: 0, deltaAbs: 0, category_type: "transfer" });
|
||||
// The uncategorized line keeps its signed balance, in its own section.
|
||||
expect(uncategorized).toMatchObject({ currentAmount: 40, category_type: "uncategorized", is_parent: false });
|
||||
});
|
||||
|
||||
it("shows a negative spending for an expense category whose refunds exceed its purchases", async () => {
|
||||
mockSelect.mockResolvedValueOnce([
|
||||
{
|
||||
category_id: 6,
|
||||
category_name: "Boucherie",
|
||||
category_color: "#000",
|
||||
section: "expense",
|
||||
month_current_total: 50,
|
||||
month_previous_total: 0,
|
||||
cumulative_current_total: 50,
|
||||
cumulative_previous_total: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
const [row] = await getCompareMonthOverMonth(2026, 4);
|
||||
|
||||
expect(row).toMatchObject({ currentAmount: -50, deltaAbs: -50, deltaPct: null });
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -1186,25 +1184,28 @@ describe("buildOverTimeTree — hierarchical trends (Issue #264)", () => {
|
|||
describe("getCompareMonthOverMonth — wires the hierarchy (Issue #247)", () => {
|
||||
it("returns parent subtotal rows when category metadata is available", async () => {
|
||||
mockSelect
|
||||
// 1. COMPARE_DELTA_SQL — two sibling leaves under parent id 2.
|
||||
// 1. COMPARE_DELTA_SQL — two sibling leaves under parent id 2, signed
|
||||
// balances of expense categories (spending 500 and 120 this month).
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
category_id: 22,
|
||||
category_name: "Épicerie",
|
||||
category_color: "#10b981",
|
||||
month_current_total: 500,
|
||||
month_previous_total: 400,
|
||||
cumulative_current_total: 2000,
|
||||
cumulative_previous_total: 1500,
|
||||
section: "expense",
|
||||
month_current_total: -500,
|
||||
month_previous_total: -400,
|
||||
cumulative_current_total: -2000,
|
||||
cumulative_previous_total: -1500,
|
||||
},
|
||||
{
|
||||
category_id: 24,
|
||||
category_name: "Restaurant",
|
||||
category_color: "#f97316",
|
||||
month_current_total: 120,
|
||||
month_previous_total: 200,
|
||||
cumulative_current_total: 300,
|
||||
cumulative_previous_total: 500,
|
||||
section: "expense",
|
||||
month_current_total: -120,
|
||||
month_previous_total: -200,
|
||||
cumulative_current_total: -300,
|
||||
cumulative_previous_total: -500,
|
||||
},
|
||||
])
|
||||
// 2. COMPARE_CATEGORIES_SQL — the hierarchy.
|
||||
|
|
|
|||
|
|
@ -1,9 +1,20 @@
|
|||
import { getDb } from "./db";
|
||||
import { getBudgetVsActualData } from "./budgetService";
|
||||
import { inPlaceholders } from "../utils/sqlFilters";
|
||||
import {
|
||||
CATEGORY_JOIN_SQL,
|
||||
EMPTY_STATEMENT,
|
||||
SECTION_ORDER,
|
||||
SECTION_SQL,
|
||||
addStatements,
|
||||
incomeStatement,
|
||||
orient,
|
||||
savingsRate,
|
||||
toCents,
|
||||
toSection,
|
||||
} from "../utils/incomeStatement";
|
||||
import type {
|
||||
MonthlyTrendItem,
|
||||
CategoryBreakdownItem,
|
||||
CategoryOverTimeData,
|
||||
CategoryOverTimeItem,
|
||||
OverTimeRow,
|
||||
|
|
@ -25,8 +36,19 @@ import type {
|
|||
CartesSeasonality,
|
||||
CartesSeasonalityYear,
|
||||
CartesKpiPeriodMode,
|
||||
BudgetVsActualRow,
|
||||
IncomeStatementFigures,
|
||||
ReportSection,
|
||||
} from "../shared/types";
|
||||
|
||||
/**
|
||||
* The income statement of each month (#392, ADR 0026): the signed balances of
|
||||
* the month's transactions by section, turned into income, expenses, the
|
||||
* uncategorized line, transfers and the two results. Trends (global flow) and
|
||||
* the KPI cards, sparklines and overlay chart of Cartes and the Dashboard all
|
||||
* read this one query. An absent `dateFrom` or `dateTo` is no bound on that
|
||||
* side (« Tout », #479).
|
||||
*/
|
||||
export async function getMonthlyTrends(
|
||||
dateFrom?: string,
|
||||
dateTo?: string,
|
||||
|
|
@ -39,18 +61,18 @@ export async function getMonthlyTrends(
|
|||
let paramIndex = 1;
|
||||
|
||||
if (dateFrom) {
|
||||
whereClauses.push(`date >= $${paramIndex}`);
|
||||
whereClauses.push(`t.date >= $${paramIndex}`);
|
||||
params.push(dateFrom);
|
||||
paramIndex++;
|
||||
}
|
||||
if (dateTo) {
|
||||
whereClauses.push(`date <= $${paramIndex}`);
|
||||
whereClauses.push(`t.date <= $${paramIndex}`);
|
||||
params.push(dateTo);
|
||||
paramIndex++;
|
||||
}
|
||||
const accountPlaceholders = inPlaceholders(accountIds, paramIndex);
|
||||
if (accountPlaceholders) {
|
||||
whereClauses.push(`source_id IN (${accountPlaceholders})`);
|
||||
whereClauses.push(`t.source_id IN (${accountPlaceholders})`);
|
||||
params.push(...accountIds!);
|
||||
paramIndex += accountIds!.length;
|
||||
}
|
||||
|
|
@ -58,17 +80,27 @@ export async function getMonthlyTrends(
|
|||
const whereSQL =
|
||||
whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
|
||||
|
||||
return db.select<MonthlyTrendItem[]>(
|
||||
const rows = await db.select<Array<{ month: string; section: string; balance: number | null }>>(
|
||||
`SELECT
|
||||
strftime('%Y-%m', date) AS month,
|
||||
COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) AS income,
|
||||
ABS(COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0)) AS expenses
|
||||
FROM transactions
|
||||
strftime('%Y-%m', t.date) AS month,
|
||||
${SECTION_SQL} AS section,
|
||||
SUM(t.amount) AS balance
|
||||
FROM transactions t
|
||||
${CATEGORY_JOIN_SQL}
|
||||
${whereSQL}
|
||||
GROUP BY month
|
||||
GROUP BY month, section
|
||||
ORDER BY month ASC`,
|
||||
params
|
||||
);
|
||||
|
||||
// One statement per month, in the order the rows come (ORDER BY month).
|
||||
const byMonth = new Map<string, typeof rows>();
|
||||
for (const row of rows) {
|
||||
const monthRows = byMonth.get(row.month);
|
||||
if (monthRows) monthRows.push(row);
|
||||
else byMonth.set(row.month, [row]);
|
||||
}
|
||||
return Array.from(byMonth, ([month, monthRows]) => ({ month, ...incomeStatement(monthRows) }));
|
||||
}
|
||||
|
||||
export async function getCategoryOverTime(
|
||||
|
|
@ -85,7 +117,7 @@ export async function getCategoryOverTime(
|
|||
let paramIndex = 1;
|
||||
|
||||
if (typeFilter) {
|
||||
whereClauses.push(`COALESCE(c.type, 'expense') = $${paramIndex}`);
|
||||
whereClauses.push(`${SECTION_SQL} = $${paramIndex}`);
|
||||
params.push(typeFilter);
|
||||
paramIndex++;
|
||||
}
|
||||
|
|
@ -109,21 +141,27 @@ export async function getCategoryOverTime(
|
|||
|
||||
const whereSQL = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
|
||||
|
||||
// Get top N categories by total spend
|
||||
// Top N categories by the size of their balance: `ABS` only ranks them, the
|
||||
// amounts below stay signed. Every row without an existing category is one
|
||||
// group (`c.id` NULL), the uncategorized one.
|
||||
const topCategories = await db.select<
|
||||
(CategoryBreakdownItem & { category_type: "expense" | "income" | "transfer" })[]
|
||||
Array<{
|
||||
category_id: number | null;
|
||||
category_name: string;
|
||||
category_color: string;
|
||||
category_type: string | null;
|
||||
}>
|
||||
>(
|
||||
`SELECT
|
||||
t.category_id,
|
||||
c.id AS category_id,
|
||||
COALESCE(c.name, 'Uncategorized') AS category_name,
|
||||
COALESCE(c.color, '#9ca3af') AS category_color,
|
||||
COALESCE(c.type, 'expense') AS category_type,
|
||||
ABS(SUM(t.amount)) AS total
|
||||
${SECTION_SQL} AS category_type
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
${CATEGORY_JOIN_SQL}
|
||||
${whereSQL}
|
||||
GROUP BY t.category_id
|
||||
ORDER BY total DESC
|
||||
GROUP BY c.id
|
||||
ORDER BY ABS(SUM(t.amount)) DESC
|
||||
LIMIT $${paramIndex}`,
|
||||
[...params, topN]
|
||||
);
|
||||
|
|
@ -131,34 +169,38 @@ export async function getCategoryOverTime(
|
|||
const topCategoryIds = new Set(topCategories.map((c) => c.category_id));
|
||||
const colors: Record<string, string> = {};
|
||||
const categoryIds: Record<string, number | null> = {};
|
||||
const types: Record<string, "expense" | "income" | "transfer"> = {};
|
||||
const types: Record<string, ReportSection> = {};
|
||||
for (const cat of topCategories) {
|
||||
colors[cat.category_name] = cat.category_color;
|
||||
categoryIds[cat.category_name] = cat.category_id;
|
||||
types[cat.category_name] = cat.category_type ?? "expense";
|
||||
types[cat.category_name] = toSection(cat.category_type);
|
||||
}
|
||||
|
||||
// Get monthly breakdown for all categories
|
||||
// Signed balance of every category, month by month, with its section.
|
||||
const monthlyRows = await db.select<
|
||||
Array<{
|
||||
month: string;
|
||||
category_id: number | null;
|
||||
category_name: string;
|
||||
total: number;
|
||||
section: string | null;
|
||||
total: number | null;
|
||||
}>
|
||||
>(
|
||||
`SELECT
|
||||
strftime('%Y-%m', t.date) AS month,
|
||||
t.category_id,
|
||||
c.id AS category_id,
|
||||
COALESCE(c.name, 'Uncategorized') AS category_name,
|
||||
ABS(SUM(t.amount)) AS total
|
||||
${SECTION_SQL} AS section,
|
||||
SUM(t.amount) AS total
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
${CATEGORY_JOIN_SQL}
|
||||
${whereSQL}
|
||||
GROUP BY month, t.category_id
|
||||
GROUP BY month, c.id
|
||||
ORDER BY month ASC`,
|
||||
params
|
||||
);
|
||||
// What each row shows: an expense its spending (D1), the others their balance.
|
||||
const shown = (row: (typeof monthlyRows)[number]) => orient(toSection(row.section), Number(row.total ?? 0));
|
||||
|
||||
// Build pivot data
|
||||
const monthMap = new Map<string, CategoryOverTimeItem>();
|
||||
|
|
@ -171,9 +213,9 @@ export async function getCategoryOverTime(
|
|||
const item = monthMap.get(row.month)!;
|
||||
|
||||
if (topCategoryIds.has(row.category_id)) {
|
||||
item[row.category_name] = ((item[row.category_name] as number) || 0) + row.total;
|
||||
item[row.category_name] = toCents(((item[row.category_name] as number) || 0) + shown(row));
|
||||
} else {
|
||||
item["Other"] = ((item["Other"] as number) || 0) + row.total;
|
||||
item["Other"] = toCents(((item["Other"] as number) || 0) + shown(row));
|
||||
hasOther = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -199,9 +241,9 @@ export async function getCategoryOverTime(
|
|||
const monthIndex = new Map<string, number>();
|
||||
months.forEach((m, i) => monthIndex.set(m, i));
|
||||
|
||||
// Aggregate every category into an id-keyed per-month magnitude series. A null
|
||||
// category_id (truly uncategorized) collapses to one bucket; a non-null id that
|
||||
// has no metadata row (hard-deleted) stays distinct and surfaces as an orphan.
|
||||
// Aggregate every category into an id-keyed per-month series of what it
|
||||
// shows (signed, ADR 0026). Every row without an existing category (no
|
||||
// category, or one that is gone) is one bucket, the uncategorized one.
|
||||
const leafByKey = new Map<number | string, OverTimeRow>();
|
||||
for (const row of monthlyRows) {
|
||||
const key = row.category_id ?? "__uncategorized__";
|
||||
|
|
@ -216,14 +258,14 @@ export async function getCategoryOverTime(
|
|||
parent_id: null,
|
||||
is_parent: false,
|
||||
depth: 0,
|
||||
category_type: "expense",
|
||||
category_type: toSection(row.section),
|
||||
};
|
||||
leafByKey.set(key, leaf);
|
||||
}
|
||||
const idx = monthIndex.get(row.month);
|
||||
if (idx != null) {
|
||||
leaf.monthly[idx] += row.total;
|
||||
leaf.total += row.total;
|
||||
leaf.monthly[idx] = toCents(leaf.monthly[idx] + shown(row));
|
||||
leaf.total = toCents(leaf.total + shown(row));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -357,8 +399,10 @@ export async function getHighlights(
|
|||
monthlyBalanceSeries.push({ month: monthKey, netBalance: seriesMap.get(monthKey) ?? 0 });
|
||||
}
|
||||
|
||||
// 4. Top movers — expense-side only (amount < 0), compare reference month
|
||||
// vs the immediately-previous month.
|
||||
// 4. Top movers — expense categories only, each on its spending (the
|
||||
// opposite of its signed balance, refunds and splits netted, ADR 0026), as
|
||||
// the Cartes movers: reference month vs the immediately-previous month.
|
||||
// `ABS` only ranks them.
|
||||
const moversRows = await db.select<
|
||||
Array<{
|
||||
category_id: number | null;
|
||||
|
|
@ -369,28 +413,29 @@ export async function getHighlights(
|
|||
}>
|
||||
>(
|
||||
`SELECT
|
||||
t.category_id,
|
||||
c.id AS category_id,
|
||||
COALESCE(c.name, 'Uncategorized') AS category_name,
|
||||
COALESCE(c.color, '#9ca3af') AS category_color,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN ABS(t.amount) ELSE 0 END), 0) AS current_total,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $3 AND t.date <= $4 THEN ABS(t.amount) ELSE 0 END), 0) AS previous_total
|
||||
COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN t.amount ELSE 0 END), 0) AS current_total,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $3 AND t.date <= $4 THEN t.amount ELSE 0 END), 0) AS previous_total
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
WHERE t.amount < 0
|
||||
${CATEGORY_JOIN_SQL}
|
||||
WHERE ${SECTION_SQL} = 'expense'
|
||||
AND (
|
||||
(t.date >= $1 AND t.date <= $2)
|
||||
OR (t.date >= $3 AND t.date <= $4)
|
||||
)
|
||||
GROUP BY t.category_id, category_name, category_color
|
||||
GROUP BY c.id
|
||||
ORDER BY ABS(current_total - previous_total) DESC
|
||||
LIMIT $5`,
|
||||
[currentMonthStart, currentMonthEnd, previousMonthStart, previousMonthEnd, topMoversLimit],
|
||||
);
|
||||
const topMovers: HighlightMover[] = moversRows.map((r) => {
|
||||
const current = Number(r.current_total ?? 0);
|
||||
const previous = Number(r.previous_total ?? 0);
|
||||
const deltaAbs = current - previous;
|
||||
const deltaPct = previous === 0 ? null : (deltaAbs / previous) * 100;
|
||||
const current = orient("expense", Number(r.current_total ?? 0));
|
||||
const previous = orient("expense", Number(r.previous_total ?? 0));
|
||||
const deltaAbs = toCents(current - previous);
|
||||
// On the size of the previous amount: a spending can be negative (ADR 0026).
|
||||
const deltaPct = previous === 0 ? null : (deltaAbs / Math.abs(previous)) * 100;
|
||||
// Highlights only exposes a monthly view, so the cumulative block mirrors
|
||||
// the monthly values — keeps the CategoryDelta shape uniform for
|
||||
// downstream consumers that never read the cumulative block.
|
||||
|
|
@ -442,23 +487,34 @@ interface RawDeltaRow {
|
|||
category_id: number | null;
|
||||
category_name: string;
|
||||
category_color: string;
|
||||
/** `SECTION_SQL` of the row's category. */
|
||||
section?: string | null;
|
||||
month_current_total: number | null;
|
||||
month_previous_total: number | null;
|
||||
cumulative_current_total: number | null;
|
||||
cumulative_previous_total: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns the signed balances of compareDeltaSql() into what each row shows
|
||||
* (ADR 0026): an expense category its spending, the opposite of its balance,
|
||||
* every other section its balance. The row keeps its section. A change in
|
||||
* percent is taken on the size of the previous amount, which can be negative
|
||||
* (refunds above purchases), as `pct` of compareResults.ts takes it: from −50
|
||||
* to 80 is +260 %, never −260 %.
|
||||
*/
|
||||
function rowsToDeltas(rows: RawDeltaRow[]): CategoryDelta[] {
|
||||
return rows.map((r) => {
|
||||
const monthCurrent = Number(r.month_current_total ?? 0);
|
||||
const monthPrevious = Number(r.month_previous_total ?? 0);
|
||||
const monthDeltaAbs = monthCurrent - monthPrevious;
|
||||
const monthDeltaPct = monthPrevious === 0 ? null : (monthDeltaAbs / monthPrevious) * 100;
|
||||
const section = toSection(r.section);
|
||||
const monthCurrent = orient(section, Number(r.month_current_total ?? 0));
|
||||
const monthPrevious = orient(section, Number(r.month_previous_total ?? 0));
|
||||
const monthDeltaAbs = toCents(monthCurrent - monthPrevious);
|
||||
const monthDeltaPct = monthPrevious === 0 ? null : (monthDeltaAbs / Math.abs(monthPrevious)) * 100;
|
||||
|
||||
const cumCurrent = Number(r.cumulative_current_total ?? 0);
|
||||
const cumPrevious = Number(r.cumulative_previous_total ?? 0);
|
||||
const cumDeltaAbs = cumCurrent - cumPrevious;
|
||||
const cumDeltaPct = cumPrevious === 0 ? null : (cumDeltaAbs / cumPrevious) * 100;
|
||||
const cumCurrent = orient(section, Number(r.cumulative_current_total ?? 0));
|
||||
const cumPrevious = orient(section, Number(r.cumulative_previous_total ?? 0));
|
||||
const cumDeltaAbs = toCents(cumCurrent - cumPrevious);
|
||||
const cumDeltaPct = cumPrevious === 0 ? null : (cumDeltaAbs / Math.abs(cumPrevious)) * 100;
|
||||
|
||||
return {
|
||||
categoryId: r.category_id,
|
||||
|
|
@ -474,6 +530,7 @@ function rowsToDeltas(rows: RawDeltaRow[]): CategoryDelta[] {
|
|||
cumulativeCurrentAmount: cumCurrent,
|
||||
cumulativeDeltaAbs: cumDeltaAbs,
|
||||
cumulativeDeltaPct: cumDeltaPct,
|
||||
category_type: section,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
|
@ -488,7 +545,7 @@ function monthBoundaries(year: number, month: number): { start: string; end: str
|
|||
// --- Generic leaf-driven tree builder (Issue #263) ---
|
||||
|
||||
/** Section key shared by every hierarchical report (income-statement order). */
|
||||
export type TreeSectionType = "expense" | "income" | "transfer";
|
||||
export type TreeSectionType = ReportSection;
|
||||
|
||||
/**
|
||||
* Minimal category metadata every hierarchical report needs: id, display
|
||||
|
|
@ -697,19 +754,20 @@ type CompareCatMeta = TreeCatMeta;
|
|||
|
||||
const COMPARE_CATEGORIES_SQL = `SELECT id, name, color, type, parent_id FROM categories`;
|
||||
|
||||
// Income statement reading order: revenues first, then expenses, then the
|
||||
// (netted) transfers — the two result lines are injected around them in the UI.
|
||||
const COMPARE_TYPE_ORDER: Record<string, number> = { income: 0, expense: 1, transfer: 2 };
|
||||
// Income statement reading order: revenues first, then expenses, the
|
||||
// uncategorized line, then the (netted) transfers — the two result lines are
|
||||
// injected around them in the UI (ADR 0026).
|
||||
const COMPARE_TYPE_ORDER: Record<string, number> = SECTION_ORDER;
|
||||
|
||||
/**
|
||||
* Turns the flat per-category deltas returned by compareDeltaSql() into a
|
||||
* parent/child tree with subtotal (`is_parent`) rows, mirroring the hierarchy of
|
||||
* getBudgetVsActualData.
|
||||
*
|
||||
* The #243 transfer netting is untouched: leaf values are exactly what the SQL
|
||||
* returned, and a subtotal is the arithmetic sum of its descendant leaves — so a
|
||||
* group of balanced (netted-to-zero) transfers subtotals to ~0, i.e. the group's
|
||||
* net.
|
||||
* Leaf values are what rowsToDeltas made of the signed balances of the SQL
|
||||
* (ADR 0026), and a subtotal is the arithmetic sum of its descendant leaves — so
|
||||
* a group of balanced (netted-to-zero) transfers subtotals to 0, the group's net
|
||||
* (#243), and an expense group nets its refunds.
|
||||
*
|
||||
* A thin specialisation of `buildLeafDrivenTree` (Issue #263): the generic
|
||||
* skeleton drives the hierarchy walk, sibling ordering, depth guard and section
|
||||
|
|
@ -754,15 +812,15 @@ export function buildCompareTree(
|
|||
previousAmount,
|
||||
currentAmount,
|
||||
deltaAbs,
|
||||
// Match rowsToDeltas' leaf formula (signed denominator) so a single-child
|
||||
// parent shows the same % as its child.
|
||||
deltaPct: previousAmount !== 0 ? (deltaAbs / previousAmount) * 100 : null,
|
||||
// Match rowsToDeltas' leaf formula (the size of the previous amount) so a
|
||||
// single-child parent shows the same % as its child.
|
||||
deltaPct: previousAmount !== 0 ? (deltaAbs / Math.abs(previousAmount)) * 100 : null,
|
||||
cumulativePreviousAmount,
|
||||
cumulativeCurrentAmount,
|
||||
cumulativeDeltaAbs,
|
||||
cumulativeDeltaPct:
|
||||
cumulativePreviousAmount !== 0
|
||||
? (cumulativeDeltaAbs / cumulativePreviousAmount) * 100
|
||||
? (cumulativeDeltaAbs / Math.abs(cumulativePreviousAmount)) * 100
|
||||
: null,
|
||||
parent_id: parentId,
|
||||
is_parent: true,
|
||||
|
|
@ -774,13 +832,14 @@ export function buildCompareTree(
|
|||
// spend as a "(direct)" leaf (mirrors getBudgetVsActualData).
|
||||
decorateDirectLeaf: (row, cat) => ({ ...row, categoryName: `${cat.name} (direct)` }),
|
||||
// Orphans keep their own already-computed delta; only the hierarchy fields
|
||||
// are stamped. Uncategorized rows (category_type undefined) → 'expense'.
|
||||
// are stamped. An orphan is a row without an existing category: the
|
||||
// uncategorized line (ADR 0026), the section rowsToDeltas gives it.
|
||||
makeOrphan: (d) => ({
|
||||
...d,
|
||||
parent_id: null,
|
||||
is_parent: false,
|
||||
depth: 0,
|
||||
category_type: d.category_type ?? "expense",
|
||||
category_type: d.category_type ?? "uncategorized",
|
||||
}),
|
||||
sortKey: (row) => Math.abs(row.deltaAbs),
|
||||
isSubtotal: (row) => row.is_parent === true,
|
||||
|
|
@ -845,14 +904,14 @@ export function buildOverTimeTree(
|
|||
// A parent with both children and its own transactions surfaces the direct
|
||||
// spend as a "(direct)" leaf (mirrors buildCompareTree / getBudgetVsActualData).
|
||||
decorateDirectLeaf: (row, cat) => ({ ...row, categoryName: `${cat.name} (direct)` }),
|
||||
// Orphans (Uncategorized / hard-deleted) keep their own series; only the
|
||||
// hierarchy fields are stamped. No metadata → default 'expense'.
|
||||
// Orphans (rows without an existing category) keep their own series; only
|
||||
// the hierarchy fields are stamped. No metadata → the uncategorized line.
|
||||
makeOrphan: (l) => ({
|
||||
...l,
|
||||
parent_id: null,
|
||||
is_parent: false,
|
||||
depth: 0,
|
||||
category_type: l.category_type ?? "expense",
|
||||
category_type: l.category_type ?? "uncategorized",
|
||||
}),
|
||||
sortKey: (row) => Math.abs(row.total),
|
||||
isSubtotal: (row) => row.is_parent === true,
|
||||
|
|
@ -871,48 +930,42 @@ function previousMonth(year: number, month: number): { year: number; month: numb
|
|||
* exact same query — only the eight date bounds differ). Four date buckets
|
||||
* ($1..$8): monthly current/previous and cumulative current/previous.
|
||||
*
|
||||
* This report is an INCOME STATEMENT ("analyse de résultat", Issue #253), not a
|
||||
* pure expense report: revenues are surfaced alongside expenses so the compare
|
||||
* can show a result (revenues − expenses). Per-category sign convention:
|
||||
* - `income` and `transfer` categories use a signed SUM(t.amount). Income
|
||||
* credits stay positive; a `transfer` debit/credit pair (e.g. "Paiement CC":
|
||||
* -500 out, +500 in) nets to ~0 (Issue #243 — a money move, not spending).
|
||||
* - Every other type keeps the expense-report behavior: only outflows
|
||||
* (amount < 0) count, summed as positive magnitudes via ABS.
|
||||
*
|
||||
* The WHERE admits outflows OR any income/transfer row, so income and transfer
|
||||
* *credits* survive the `amount < 0` filter — without it a pure-income category
|
||||
* would be dropped entirely and a transfer could never net to zero. Expense
|
||||
* rows still contribute only their outflows, byte-identical to before. The two
|
||||
* result lines (before/after transfers) are computed in ComparePeriodTable from
|
||||
* the per-type subtotals, not here. Uncategorized rows (c.type NULL) → 'expense'.
|
||||
* This report is an INCOME STATEMENT ("analyse de résultat", Issue #253): each
|
||||
* bucket is the signed balance of the category (#392, ADR 0026), splits and
|
||||
* refunds included, with the category's section; rowsToDeltas turns it into
|
||||
* what the row shows (an expense its spending). A split is counted once: its
|
||||
* parent keeps its amount and the offset line cancels, in the parent's
|
||||
* category, the parts sent elsewhere. A `transfer` debit/credit pair (e.g.
|
||||
* "Paiement CC": -500 out, +500 in) nets to 0 (Issue #243). Every row without
|
||||
* an existing category is one group (`c.id` NULL), the uncategorized line. The
|
||||
* result lines are computed from the per-section subtotals (compareResults),
|
||||
* not here. `ABS` only orders the rows.
|
||||
*
|
||||
* `accountIds` (Issue #273) adds an optional `t.source_id IN (...)` clause —
|
||||
* one bound placeholder per id, starting at $9 (the 8 date bounds occupy
|
||||
* $1-$8). Omitted/empty → no clause at all, so the query text and results stay
|
||||
* byte-identical to the pre-#273 behavior.
|
||||
* $1-$8). Omitted/empty → no clause at all.
|
||||
*/
|
||||
function compareDeltaSql(accountIds?: number[]): string {
|
||||
const accountPlaceholders = inPlaceholders(accountIds, 9);
|
||||
const accountFilter = accountPlaceholders ? ` AND t.source_id IN (${accountPlaceholders})` : "";
|
||||
return `SELECT
|
||||
t.category_id,
|
||||
c.id AS category_id,
|
||||
COALESCE(c.name, 'Uncategorized') AS category_name,
|
||||
COALESCE(c.color, '#9ca3af') AS category_color,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN CASE WHEN COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount) END ELSE 0 END), 0) AS month_current_total,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $3 AND t.date <= $4 THEN CASE WHEN COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount) END ELSE 0 END), 0) AS month_previous_total,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $5 AND t.date <= $6 THEN CASE WHEN COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount) END ELSE 0 END), 0) AS cumulative_current_total,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $7 AND t.date <= $8 THEN CASE WHEN COALESCE(c.type, 'expense') IN ('transfer', 'income') THEN t.amount ELSE ABS(t.amount) END ELSE 0 END), 0) AS cumulative_previous_total
|
||||
${SECTION_SQL} AS section,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $1 AND t.date <= $2 THEN t.amount ELSE 0 END), 0) AS month_current_total,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $3 AND t.date <= $4 THEN t.amount ELSE 0 END), 0) AS month_previous_total,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $5 AND t.date <= $6 THEN t.amount ELSE 0 END), 0) AS cumulative_current_total,
|
||||
COALESCE(SUM(CASE WHEN t.date >= $7 AND t.date <= $8 THEN t.amount ELSE 0 END), 0) AS cumulative_previous_total
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
WHERE (t.amount < 0 OR COALESCE(c.type, 'expense') IN ('transfer', 'income'))
|
||||
AND (
|
||||
${CATEGORY_JOIN_SQL}
|
||||
WHERE (
|
||||
(t.date >= $1 AND t.date <= $2)
|
||||
OR (t.date >= $3 AND t.date <= $4)
|
||||
OR (t.date >= $5 AND t.date <= $6)
|
||||
OR (t.date >= $7 AND t.date <= $8)
|
||||
)${accountFilter}
|
||||
GROUP BY t.category_id, category_name, category_color
|
||||
GROUP BY c.id
|
||||
ORDER BY ABS(month_current_total - month_previous_total) DESC`;
|
||||
}
|
||||
|
||||
|
|
@ -1038,6 +1091,11 @@ const ZOOM_DATE_BOUNDS = "($2 IS NULL OR t.date >= $2) AND ($3 IS NULL OR t.date
|
|||
* false, only direct transactions on `categoryId` are considered. Every
|
||||
* query is parameterised; the category id is never interpolated. An absent
|
||||
* `dateFrom` or `dateTo` is no bound on that side (« Tout »).
|
||||
*
|
||||
* The total, each child and each month are signed balances (#392, ADR 0026),
|
||||
* splits and refunds netted, shown the way of the zoomed category's type: a
|
||||
* zoom on an expense category shows its spending, the opposite of its balance.
|
||||
* `ABS` only orders the transactions.
|
||||
*/
|
||||
export async function getCategoryZoom(
|
||||
categoryId: number,
|
||||
|
|
@ -1074,12 +1132,17 @@ export async function getCategoryZoom(
|
|||
params,
|
||||
);
|
||||
|
||||
// 2. Rollup total (sum of absolute amounts of matching rows)
|
||||
const totalRows = await db.select<Array<{ rollup: number | null }>>(
|
||||
`${categoryFilter.replace("SELECT t.id, t.date, t.description, t.amount, t.category_id", "SELECT COALESCE(SUM(ABS(t.amount)), 0) AS rollup")}`,
|
||||
// 2. Rollup total: the signed balance of the matching rows, with the type of
|
||||
// the zoomed category, which orients every figure of the zoom.
|
||||
const totalRows = await db.select<Array<{ rollup: number | null; category_type: string | null }>>(
|
||||
`${categoryFilter.replace(
|
||||
"SELECT t.id, t.date, t.description, t.amount, t.category_id",
|
||||
"SELECT COALESCE(SUM(t.amount), 0) AS rollup, (SELECT type FROM categories WHERE id = $1) AS category_type",
|
||||
)}`,
|
||||
params,
|
||||
);
|
||||
const rollupTotal = Number(totalRows[0]?.rollup ?? 0);
|
||||
const section = toSection(totalRows[0]?.category_type);
|
||||
const rollupTotal = orient(section, Number(totalRows[0]?.rollup ?? 0));
|
||||
|
||||
// 3. Breakdown by direct child (only meaningful when includeSubcategories is true)
|
||||
const byChild: CategoryZoomChild[] = [];
|
||||
|
|
@ -1090,13 +1153,12 @@ export async function getCategoryZoom(
|
|||
`SELECT child.id AS child_id,
|
||||
child.name AS child_name,
|
||||
COALESCE(child.color, '#9ca3af') AS child_color,
|
||||
COALESCE(SUM(ABS(t.amount)), 0) AS total
|
||||
COALESCE(SUM(t.amount), 0) AS total
|
||||
FROM categories child
|
||||
LEFT JOIN transactions t ON t.category_id = child.id
|
||||
AND ${ZOOM_DATE_BOUNDS}
|
||||
WHERE child.parent_id = $1
|
||||
GROUP BY child.id, child.name, child.color
|
||||
ORDER BY total DESC`,
|
||||
GROUP BY child.id, child.name, child.color`,
|
||||
params,
|
||||
);
|
||||
for (const r of childRows) {
|
||||
|
|
@ -1104,16 +1166,18 @@ export async function getCategoryZoom(
|
|||
categoryId: r.child_id,
|
||||
categoryName: r.child_name,
|
||||
categoryColor: r.child_color,
|
||||
total: Number(r.total ?? 0),
|
||||
total: orient(section, Number(r.total ?? 0)),
|
||||
});
|
||||
}
|
||||
// Largest first, once each child shows what it shows.
|
||||
byChild.sort((a, b) => b.total - a.total);
|
||||
}
|
||||
|
||||
// 4. Monthly evolution across the window
|
||||
const evolutionRows = await db.select<Array<{ month: string; total: number | null }>>(
|
||||
`${includeSubcategories ? CATEGORY_TREE_CTE : ""}
|
||||
SELECT strftime('%Y-%m', t.date) AS month,
|
||||
COALESCE(SUM(ABS(t.amount)), 0) AS total
|
||||
COALESCE(SUM(t.amount), 0) AS total
|
||||
FROM transactions t
|
||||
WHERE ${includeSubcategories
|
||||
? "t.category_id IN (SELECT id FROM cat_tree)"
|
||||
|
|
@ -1125,7 +1189,7 @@ export async function getCategoryZoom(
|
|||
);
|
||||
const monthlyEvolution: CategoryZoomEvolutionPoint[] = evolutionRows.map((r) => ({
|
||||
month: r.month,
|
||||
total: Number(r.total ?? 0),
|
||||
total: orient(section, Number(r.total ?? 0)),
|
||||
}));
|
||||
|
||||
return {
|
||||
|
|
@ -1165,7 +1229,9 @@ function extractDelta(
|
|||
): { abs: number | null; pct: number | null } {
|
||||
if (current === null || previous === null) return { abs: null, pct: null };
|
||||
const abs = current - previous;
|
||||
const pct = previous === 0 ? null : (abs / previous) * 100;
|
||||
// On the size of the previous value: expenses, « Solde net » and the savings
|
||||
// rate can all be negative (ADR 0026).
|
||||
const pct = previous === 0 ? null : (abs / Math.abs(previous)) * 100;
|
||||
return { abs, pct };
|
||||
}
|
||||
|
||||
|
|
@ -1189,42 +1255,17 @@ function buildKpi(
|
|||
};
|
||||
}
|
||||
|
||||
interface RawMonthFlow {
|
||||
month: string;
|
||||
income: number | null;
|
||||
expenses: number | null;
|
||||
}
|
||||
|
||||
async function fetchMonthlyFlows(
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
accountIds?: number[],
|
||||
): Promise<RawMonthFlow[]> {
|
||||
const db = await getDb();
|
||||
const params: unknown[] = [dateFrom, dateTo];
|
||||
const accountPlaceholders = inPlaceholders(accountIds, 3);
|
||||
const accountClause = accountPlaceholders
|
||||
? ` AND source_id IN (${accountPlaceholders})`
|
||||
: "";
|
||||
if (accountPlaceholders) params.push(...accountIds!);
|
||||
return db.select<RawMonthFlow[]>(
|
||||
`SELECT
|
||||
strftime('%Y-%m', date) AS month,
|
||||
COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) AS income,
|
||||
ABS(COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0)) AS expenses
|
||||
FROM transactions
|
||||
WHERE date >= $1 AND date <= $2${accountClause}
|
||||
GROUP BY month
|
||||
ORDER BY month ASC`,
|
||||
params,
|
||||
);
|
||||
}
|
||||
|
||||
interface RawSeasonalityRow {
|
||||
year: number;
|
||||
amount: number | null;
|
||||
/** Signed balance of the expense categories in that year's month. */
|
||||
balance: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The expense balance of one calendar month across a range of years. Every
|
||||
* year with a transaction in that month has a row, its expense balance 0 when
|
||||
* it holds no expense.
|
||||
*/
|
||||
async function fetchSeasonality(
|
||||
month: number,
|
||||
yearFrom: number,
|
||||
|
|
@ -1236,17 +1277,18 @@ async function fetchSeasonality(
|
|||
const params: unknown[] = [mm, yearFrom, yearTo];
|
||||
const accountPlaceholders = inPlaceholders(accountIds, 4);
|
||||
const accountClause = accountPlaceholders
|
||||
? ` AND source_id IN (${accountPlaceholders})`
|
||||
? ` AND t.source_id IN (${accountPlaceholders})`
|
||||
: "";
|
||||
if (accountPlaceholders) params.push(...accountIds!);
|
||||
return db.select<RawSeasonalityRow[]>(
|
||||
`SELECT
|
||||
CAST(strftime('%Y', date) AS INTEGER) AS year,
|
||||
ABS(COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0)) AS amount
|
||||
FROM transactions
|
||||
WHERE strftime('%m', date) = $1
|
||||
AND CAST(strftime('%Y', date) AS INTEGER) >= $2
|
||||
AND CAST(strftime('%Y', date) AS INTEGER) <= $3${accountClause}
|
||||
CAST(strftime('%Y', t.date) AS INTEGER) AS year,
|
||||
COALESCE(SUM(CASE WHEN ${SECTION_SQL} = 'expense' THEN t.amount END), 0) AS balance
|
||||
FROM transactions t
|
||||
${CATEGORY_JOIN_SQL}
|
||||
WHERE strftime('%m', t.date) = $1
|
||||
AND CAST(strftime('%Y', t.date) AS INTEGER) >= $2
|
||||
AND CAST(strftime('%Y', t.date) AS INTEGER) <= $3${accountClause}
|
||||
GROUP BY year
|
||||
ORDER BY year DESC`,
|
||||
params,
|
||||
|
|
@ -1258,18 +1300,22 @@ async function fetchSeasonality(
|
|||
* data for the Cartes report, computed against a reference (year, month).
|
||||
*
|
||||
* Layout (all concurrent):
|
||||
* 1. 25-month expense/income series (covers ref, MoM, YoY, 12-month flow,
|
||||
* 13-month sparklines without any extra round trips).
|
||||
* 1. 25-month income statement series (`getMonthlyTrends`, the query of
|
||||
* Trends; covers ref, MoM, YoY, 12-month flow, 13-month sparklines
|
||||
* without any extra round trips).
|
||||
* 2. Month-over-month category deltas for top movers (existing service).
|
||||
* 3. Year-over-year category deltas to seed the savings-rate YoY lookup
|
||||
* via the monthly series instead of re-querying.
|
||||
* 4. Budget vs actual for the reference month.
|
||||
* 5. Seasonality: same calendar month across the two prior years.
|
||||
* 3. Budget vs actual for the reference month.
|
||||
* 4. Seasonality: same calendar month across the two prior years.
|
||||
*
|
||||
* Every figure follows the sign convention of the reports (#392, ADR 0026):
|
||||
* « Solde net » is the net result, the sum of every amount (D5), with its
|
||||
* uncategorized and transfer parts in `netBreakdown`; the savings rate is
|
||||
* (income − expenses) ÷ income (D6).
|
||||
*
|
||||
* `accountIds` (Issues #273/#279) is forwarded to every sub-query so the whole
|
||||
* dashboard honours an active account filter: the top-movers
|
||||
* (`getCompareMonthOverMonth`) and budget (`getBudgetVsActualData`) sub-reports,
|
||||
* and the KPI/sparkline/seasonality series (`fetchMonthlyFlows`,
|
||||
* and the KPI/sparkline/seasonality series (`getMonthlyTrends`,
|
||||
* `fetchSeasonality`). Omitting it anywhere would let the dashboard silently mix
|
||||
* filtered and unfiltered figures on the same screen.
|
||||
*/
|
||||
|
|
@ -1288,30 +1334,22 @@ export async function getCartesSnapshot(
|
|||
// Seasonality range: previous 2 years for the same calendar month.
|
||||
const [seasonalityRows, flowRows, momRows, budgetRows] = await Promise.all([
|
||||
fetchSeasonality(referenceMonth, referenceYear - 2, referenceYear - 1, accountIds),
|
||||
fetchMonthlyFlows(windowStartIso, refEnd, accountIds),
|
||||
getMonthlyTrends(windowStartIso, refEnd, accountIds),
|
||||
getCompareMonthOverMonth(referenceYear, referenceMonth, accountIds),
|
||||
getBudgetVsActualData(referenceYear, referenceMonth, accountIds),
|
||||
]);
|
||||
|
||||
// Index the flow rows by month for O(1) lookup, then fill missing months
|
||||
// with zeroes so downstream consumers get a contiguous series.
|
||||
const flowByMonth = new Map<string, { income: number; expenses: number }>();
|
||||
for (const r of flowRows) {
|
||||
flowByMonth.set(r.month, {
|
||||
income: Number(r.income ?? 0),
|
||||
expenses: Number(r.expenses ?? 0),
|
||||
});
|
||||
}
|
||||
// Index the monthly statements by month for O(1) lookup, then fill missing
|
||||
// months with zeroes so downstream consumers get a contiguous series.
|
||||
const flowByMonth = new Map<string, IncomeStatementFigures>();
|
||||
for (const { month, ...figures } of flowRows) flowByMonth.set(month, figures);
|
||||
|
||||
const buildSeries = (count: number): CartesMonthFlow[] => {
|
||||
const series: CartesMonthFlow[] = [];
|
||||
for (let i = count - 1; i >= 0; i--) {
|
||||
const { year: y, month: m } = shiftMonth(referenceYear, referenceMonth, -i);
|
||||
const key = monthKey(y, m);
|
||||
const row = flowByMonth.get(key);
|
||||
const income = row?.income ?? 0;
|
||||
const expenses = row?.expenses ?? 0;
|
||||
series.push({ month: key, income, expenses, net: income - expenses });
|
||||
series.push({ month: key, ...(flowByMonth.get(key) ?? EMPTY_STATEMENT) });
|
||||
}
|
||||
return series;
|
||||
};
|
||||
|
|
@ -1332,7 +1370,7 @@ export async function getCartesSnapshot(
|
|||
}));
|
||||
const savingsSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({
|
||||
month: p.month,
|
||||
value: p.income > 0 ? (p.net / p.income) * 100 : 0,
|
||||
value: savingsRate(p.income, p.expenses) ?? 0,
|
||||
}));
|
||||
|
||||
// Compute MoM / YoY values directly from `flowByMonth` (which preserves the
|
||||
|
|
@ -1344,99 +1382,62 @@ export async function getCartesSnapshot(
|
|||
const yoyMeta = { year: referenceYear - 1, month: referenceMonth };
|
||||
const yoyKey = monthKey(yoyMeta.year, yoyMeta.month);
|
||||
|
||||
// Monthly aggregates — the "month" mode default behavior.
|
||||
const refRow = flowByMonth.get(refKey);
|
||||
const monthRefIncome = refRow?.income ?? 0;
|
||||
const monthRefExpenses = refRow?.expenses ?? 0;
|
||||
const monthRefNet = monthRefIncome - monthRefExpenses;
|
||||
// Savings rate is undefined when income is zero — expose as null rather than
|
||||
// rendering a misleading "0 %" in the UI.
|
||||
const monthRefSavings = monthRefIncome > 0 ? (monthRefNet / monthRefIncome) * 100 : null;
|
||||
// The four KPI figures of a period, or null for a period without data.
|
||||
// « Solde net » is the net result (D5); the savings rate is undefined when
|
||||
// income is not positive — null rather than a misleading "0 %" in the UI (D6).
|
||||
const kpiFigures = (s: IncomeStatementFigures | undefined) => ({
|
||||
income: s ? s.income : null,
|
||||
expenses: s ? s.expenses : null,
|
||||
net: s ? s.net : null,
|
||||
savings: s ? savingsRate(s.income, s.expenses) : null,
|
||||
});
|
||||
|
||||
const momRow = flowByMonth.get(momKey);
|
||||
const monthMomIncome = momRow ? momRow.income : null;
|
||||
const monthMomExpenses = momRow ? momRow.expenses : null;
|
||||
const monthMomNet = momRow ? momRow.income - momRow.expenses : null;
|
||||
const monthMomSavings =
|
||||
momRow && momRow.income > 0 ? ((momRow.income - momRow.expenses) / momRow.income) * 100 : null;
|
||||
|
||||
const yoyRow = flowByMonth.get(yoyKey);
|
||||
const monthYoyIncome = yoyRow ? yoyRow.income : null;
|
||||
const monthYoyExpenses = yoyRow ? yoyRow.expenses : null;
|
||||
const monthYoyNet = yoyRow ? yoyRow.income - yoyRow.expenses : null;
|
||||
const monthYoySavings =
|
||||
yoyRow && yoyRow.income > 0 ? ((yoyRow.income - yoyRow.expenses) / yoyRow.income) * 100 : null;
|
||||
|
||||
// YTD aggregates — sum monthly flows from January of a given year up to (and
|
||||
// including) `upToMonth`. Reuses the already-fetched `flowByMonth` map, so
|
||||
// no additional SQL round trip is required. Missing months contribute zero
|
||||
// to the sum (unlike monthly deltas which preserve the null distinction).
|
||||
const sumYtd = (year: number, upToMonth: number): { income: number; expenses: number } => {
|
||||
let income = 0;
|
||||
let expenses = 0;
|
||||
// YTD aggregates — sum the monthly statements from January of a given year
|
||||
// up to (and including) `upToMonth`. Reuses the already-fetched
|
||||
// `flowByMonth` map, so no additional SQL round trip is required. Missing
|
||||
// months contribute zero to the sum (unlike monthly deltas which preserve
|
||||
// the null distinction).
|
||||
const sumYtd = (year: number, upToMonth: number): IncomeStatementFigures => {
|
||||
let sum = EMPTY_STATEMENT;
|
||||
for (let m = 1; m <= upToMonth; m++) {
|
||||
const row = flowByMonth.get(monthKey(year, m));
|
||||
if (row) {
|
||||
income += row.income;
|
||||
expenses += row.expenses;
|
||||
}
|
||||
if (row) sum = addStatements(sum, row);
|
||||
}
|
||||
return { income, expenses };
|
||||
return sum;
|
||||
};
|
||||
|
||||
// Current YTD: Jan→refMonth of refYear.
|
||||
const ytdCurrent = sumYtd(referenceYear, referenceMonth);
|
||||
const ytdRefIncome = ytdCurrent.income;
|
||||
const ytdRefExpenses = ytdCurrent.expenses;
|
||||
const ytdRefNet = ytdRefIncome - ytdRefExpenses;
|
||||
const ytdRefSavings = ytdRefIncome > 0 ? (ytdRefNet / ytdRefIncome) * 100 : null;
|
||||
|
||||
// YTD MoM: previous YTD window is Jan→(refMonth-1) of refYear. When the
|
||||
// reference month is January, there is no prior window inside the same
|
||||
// year, so MoM deltas must be null (not zero).
|
||||
let ytdMomIncome: number | null = null;
|
||||
let ytdMomExpenses: number | null = null;
|
||||
let ytdMomNet: number | null = null;
|
||||
let ytdMomSavings: number | null = null;
|
||||
if (referenceMonth > 1) {
|
||||
const prev = sumYtd(referenceYear, referenceMonth - 1);
|
||||
ytdMomIncome = prev.income;
|
||||
ytdMomExpenses = prev.expenses;
|
||||
ytdMomNet = prev.income - prev.expenses;
|
||||
ytdMomSavings = prev.income > 0 ? ((prev.income - prev.expenses) / prev.income) * 100 : null;
|
||||
}
|
||||
|
||||
// YTD YoY: same window (Jan→refMonth) of the previous calendar year.
|
||||
const ytdPrevYear = sumYtd(referenceYear - 1, referenceMonth);
|
||||
const ytdYoyIncome = ytdPrevYear.income;
|
||||
const ytdYoyExpenses = ytdPrevYear.expenses;
|
||||
const ytdYoyNet = ytdPrevYear.income - ytdPrevYear.expenses;
|
||||
const ytdYoySavings =
|
||||
ytdPrevYear.income > 0 ? (ytdYoyNet / ytdPrevYear.income) * 100 : null;
|
||||
|
||||
// Select the KPI aggregate set based on the requested mode. Sparklines are
|
||||
// always the 13-month monthly series regardless of mode — the toggle only
|
||||
// affects the "current" value and its MoM/YoY comparisons.
|
||||
const isYtd = mode === "ytd";
|
||||
const refIncome = isYtd ? ytdRefIncome : monthRefIncome;
|
||||
const refExpenses = isYtd ? ytdRefExpenses : monthRefExpenses;
|
||||
const refNet = isYtd ? ytdRefNet : monthRefNet;
|
||||
const refSavings = isYtd ? ytdRefSavings : monthRefSavings;
|
||||
// Monthly ("month" mode, the default): the reference month vs the month
|
||||
// before it and the same month of the previous year. YTD: Jan→refMonth of
|
||||
// refYear vs Jan→(refMonth-1) of refYear — none when the reference month is
|
||||
// January, so the MoM deltas stay null, not zero — and vs Jan→refMonth of the
|
||||
// previous calendar year.
|
||||
const refStatement = isYtd
|
||||
? sumYtd(referenceYear, referenceMonth)
|
||||
: (flowByMonth.get(refKey) ?? EMPTY_STATEMENT);
|
||||
const ref = kpiFigures(refStatement);
|
||||
const mom = kpiFigures(
|
||||
isYtd
|
||||
? referenceMonth > 1
|
||||
? sumYtd(referenceYear, referenceMonth - 1)
|
||||
: undefined
|
||||
: flowByMonth.get(momKey),
|
||||
);
|
||||
const yoy = kpiFigures(isYtd ? sumYtd(referenceYear - 1, referenceMonth) : flowByMonth.get(yoyKey));
|
||||
|
||||
const kpiMomIncome = isYtd ? ytdMomIncome : monthMomIncome;
|
||||
const kpiMomExpenses = isYtd ? ytdMomExpenses : monthMomExpenses;
|
||||
const kpiMomNet = isYtd ? ytdMomNet : monthMomNet;
|
||||
const kpiMomSavings = isYtd ? ytdMomSavings : monthMomSavings;
|
||||
const incomeKpi = buildKpi(incomeSpark, ref.income, mom.income, yoy.income);
|
||||
const expensesKpi = buildKpi(expensesSpark, ref.expenses, mom.expenses, yoy.expenses);
|
||||
const netKpi = buildKpi(netSpark, ref.net, mom.net, yoy.net);
|
||||
const savingsKpi = buildKpi(savingsSpark, ref.savings, mom.savings, yoy.savings);
|
||||
|
||||
const kpiYoyIncome = isYtd ? ytdYoyIncome : monthYoyIncome;
|
||||
const kpiYoyExpenses = isYtd ? ytdYoyExpenses : monthYoyExpenses;
|
||||
const kpiYoyNet = isYtd ? ytdYoyNet : monthYoyNet;
|
||||
const kpiYoySavings = isYtd ? ytdYoySavings : monthYoySavings;
|
||||
|
||||
const incomeKpi = buildKpi(incomeSpark, refIncome, kpiMomIncome, kpiYoyIncome);
|
||||
const expensesKpi = buildKpi(expensesSpark, refExpenses, kpiMomExpenses, kpiYoyExpenses);
|
||||
const netKpi = buildKpi(netSpark, refNet, kpiMomNet, kpiYoyNet);
|
||||
const savingsKpi = buildKpi(savingsSpark, refSavings, kpiMomSavings, kpiYoySavings);
|
||||
// What « Solde net » holds beyond income − expenses, for the note under its card (D5).
|
||||
const netBreakdown = {
|
||||
uncategorized: refStatement.uncategorized,
|
||||
transfers: refStatement.transfers,
|
||||
};
|
||||
|
||||
// 12-month income vs expenses series for the overlay chart.
|
||||
const flow12Months = buildSeries(12);
|
||||
|
|
@ -1448,15 +1449,12 @@ export async function getCartesSnapshot(
|
|||
// net transfers), momRows now also carries revenue rows — and this card is a
|
||||
// spending view whose colours read "up = red" (more spending is bad), so a
|
||||
// salary rise must not appear under "biggest increases" in red. Mirror the
|
||||
// expense-only filter ComparePeriodChart uses. The surviving expense leaves
|
||||
// are byte-identical to the pre-#253 flat output. `momRows` are sorted by
|
||||
// absolute delta already; filter out near-zero noise and split by sign.
|
||||
// expense-only filter ComparePeriodChart uses; the uncategorized line is no
|
||||
// expense either (ADR 0026). Each leaf shows its spending, refunds netted, so
|
||||
// a category whose refunds exceed its purchases moves down like any other.
|
||||
// `momRows` are sorted by absolute delta already; split by sign.
|
||||
const significantMovers = momRows.filter(
|
||||
(r) =>
|
||||
!r.is_parent &&
|
||||
(r.category_type ?? "expense") === "expense" &&
|
||||
r.deltaAbs !== 0 &&
|
||||
(r.previousAmount > 0 || r.currentAmount > 0),
|
||||
(r) => !r.is_parent && r.category_type === "expense" && r.deltaAbs !== 0,
|
||||
);
|
||||
// Project the richer CategoryDelta shape down to the narrower CartesTopMover
|
||||
// shape so the Cartes dashboard keeps its stable contract regardless of how
|
||||
|
|
@ -1481,24 +1479,25 @@ export async function getCartesSnapshot(
|
|||
.slice(0, 5)
|
||||
.map(toCartesMover);
|
||||
|
||||
// Budget adherence — only expense categories with a non-zero budget count.
|
||||
// Both `monthActual` and `monthBudget` are signed (expense categories are
|
||||
// stored with a negative sign by `budgetService`), so all comparisons and
|
||||
// deltas on the adherence card must go through `Math.abs` — otherwise the
|
||||
// `> 0` filter rejects every expense row and the card shows "no budgeted
|
||||
// categories this month" even when budgets exist.
|
||||
// Budget adherence — only expense leaves with a non-zero budget count (a
|
||||
// parent would count again against its own children). `monthActual` and
|
||||
// `monthBudget` are signed (`budgetService` stores an expense budget
|
||||
// negated): a category's spending is the opposite of its actual, refunds
|
||||
// netted, and its budget the amount entered (ADR 0026). A refund lowers the
|
||||
// spending: it can never read as an overrun, as `Math.abs` made it (#392).
|
||||
const budgetedExpenseRows = budgetRows.filter(
|
||||
(r) => r.category_type === "expense" && Math.abs(r.monthBudget) > 0 && !r.is_parent,
|
||||
(r): r is BudgetVsActualRow & { category_id: number } =>
|
||||
r.category_type === "expense" && r.monthBudget !== 0 && !r.is_parent && r.category_id !== null,
|
||||
);
|
||||
const budgetsInTarget = budgetedExpenseRows.filter(
|
||||
(r) => Math.abs(r.monthActual) <= Math.abs(r.monthBudget),
|
||||
).length;
|
||||
const spendingOf = (r: BudgetVsActualRow) => orient("expense", r.monthActual);
|
||||
const budgetOf = (r: BudgetVsActualRow) => orient("expense", r.monthBudget);
|
||||
const budgetsInTarget = budgetedExpenseRows.filter((r) => spendingOf(r) <= budgetOf(r)).length;
|
||||
|
||||
const overruns: CartesBudgetWorstOverrun[] = budgetedExpenseRows
|
||||
.map((r) => {
|
||||
const actual = Math.abs(r.monthActual);
|
||||
const budget = Math.abs(r.monthBudget);
|
||||
const overrunAbs = actual - budget;
|
||||
const actual = spendingOf(r);
|
||||
const budget = budgetOf(r);
|
||||
const overrunAbs = toCents(actual - budget);
|
||||
const overrunPct = budget > 0 ? (overrunAbs / budget) * 100 : null;
|
||||
return {
|
||||
categoryId: r.category_id,
|
||||
|
|
@ -1524,15 +1523,15 @@ export async function getCartesSnapshot(
|
|||
// two years. If no data, average stays null.
|
||||
const historicalYears: CartesSeasonalityYear[] = seasonalityRows.map((r) => ({
|
||||
year: Number(r.year),
|
||||
amount: Number(r.amount ?? 0),
|
||||
amount: orient("expense", Number(r.balance ?? 0)),
|
||||
}));
|
||||
const historicalAverage = historicalYears.length
|
||||
? historicalYears.reduce((sum, r) => sum + r.amount, 0) / historicalYears.length
|
||||
? toCents(historicalYears.reduce((sum, r) => sum + r.amount, 0) / historicalYears.length)
|
||||
: null;
|
||||
// Seasonality compares the reference month's expenses to the same calendar
|
||||
// month in previous years — it is intentionally insensitive to the KPI
|
||||
// period toggle, so always use the monthly expenses (not the YTD figure).
|
||||
const referenceAmount = monthRefExpenses;
|
||||
const referenceAmount = (flowByMonth.get(refKey) ?? EMPTY_STATEMENT).expenses;
|
||||
const deviationPct =
|
||||
historicalAverage !== null && historicalAverage > 0
|
||||
? ((referenceAmount - historicalAverage) / historicalAverage) * 100
|
||||
|
|
@ -1554,6 +1553,7 @@ export async function getCartesSnapshot(
|
|||
net: netKpi,
|
||||
savingsRate: savingsKpi,
|
||||
},
|
||||
netBreakdown,
|
||||
flow12Months,
|
||||
topMoversUp,
|
||||
topMoversDown,
|
||||
|
|
|
|||
|
|
@ -336,13 +336,6 @@ export interface ImportReport {
|
|||
|
||||
export type DashboardPeriod = "month" | "3months" | "6months" | "year" | "12months" | "all" | "custom";
|
||||
|
||||
export interface DashboardSummary {
|
||||
totalCount: number;
|
||||
totalAmount: number;
|
||||
incomeTotal: number;
|
||||
expenseTotal: number;
|
||||
}
|
||||
|
||||
export interface CategoryBreakdownItem {
|
||||
category_id: number | null;
|
||||
category_name: string;
|
||||
|
|
@ -363,6 +356,30 @@ export interface RecentTransaction {
|
|||
|
||||
export type ReportTab = "trends" | "byCategory" | "overTime" | "budgetVsActual";
|
||||
|
||||
/**
|
||||
* Section of an income-statement row (#392, ADR 0026): the type of its
|
||||
* category, or `uncategorized` for a transaction without an existing
|
||||
* category — neither income nor expense, counted in the result (D4).
|
||||
*/
|
||||
export type ReportSection = "income" | "expense" | "uncategorized" | "transfer";
|
||||
|
||||
/**
|
||||
* The income statement of a period (#392, ADR 0026), from the signed balances
|
||||
* of its categories: `expenses` is the opposite of the balance of the expense
|
||||
* categories, so a refund lowers it and it turns negative when refunds exceed
|
||||
* purchases. `net` is the sum of every amount of the period.
|
||||
*/
|
||||
export interface IncomeStatementFigures {
|
||||
income: number;
|
||||
expenses: number;
|
||||
uncategorized: number;
|
||||
transfers: number;
|
||||
/** income − expenses + uncategorized */
|
||||
resultBeforeTransfers: number;
|
||||
/** resultBeforeTransfers + transfers */
|
||||
net: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared filter state for the report pages: the active period plus the
|
||||
* account (import source) subset. `accountIds` is a list of `ImportSource.id`
|
||||
|
|
@ -398,15 +415,16 @@ export interface CategoryDelta {
|
|||
cumulativeDeltaAbs: number;
|
||||
cumulativeDeltaPct: number | null;
|
||||
// Hierarchy block (Issue #247) — populated ONLY by the real-vs-real Compare
|
||||
// tree builder (getCompareMonthOverMonth / getCompareYearOverYear). Flat
|
||||
// consumers (Highlights movers, Cartes top movers) leave these undefined and
|
||||
// must not read them. Snake_case (unlike the camelCase value fields above) to
|
||||
// mirror BudgetVsActualRow and stay compatible with the shared `reorderRows`
|
||||
// util. `is_parent` rows are subtotals whose value = the net of their group.
|
||||
// (getCompareMonthOverMonth / getCompareYearOverYear), whose rows also carry
|
||||
// their section (#392). Flat consumers (Highlights movers) leave these
|
||||
// undefined and must not read them. Snake_case (unlike the camelCase value
|
||||
// fields above) to mirror BudgetVsActualRow and stay compatible with the
|
||||
// shared `reorderRows` util. `is_parent` rows are subtotals whose value = the
|
||||
// net of their group.
|
||||
parent_id?: number | null;
|
||||
is_parent?: boolean;
|
||||
depth?: number;
|
||||
category_type?: "expense" | "income" | "transfer";
|
||||
category_type?: ReportSection;
|
||||
}
|
||||
|
||||
// Historical alias — used by the highlights hub. Shape identical to CategoryDelta.
|
||||
|
|
@ -445,10 +463,9 @@ export interface HighlightsData {
|
|||
topTransactions: RecentTransaction[];
|
||||
}
|
||||
|
||||
export interface MonthlyTrendItem {
|
||||
/** The income statement of one month (#392, ADR 0026). */
|
||||
export interface MonthlyTrendItem extends IncomeStatementFigures {
|
||||
month: string; // "2025-01"
|
||||
income: number;
|
||||
expenses: number;
|
||||
}
|
||||
|
||||
export interface CategoryOverTimeItem {
|
||||
|
|
@ -469,7 +486,10 @@ export interface OverTimeRow {
|
|||
categoryId: number | null;
|
||||
categoryName: string;
|
||||
categoryColor: string;
|
||||
/** Positive magnitude per month, index-aligned to `CategoryOverTimeData.data`. */
|
||||
/**
|
||||
* What the row shows per month, index-aligned to `CategoryOverTimeData.data`:
|
||||
* the signed balance, an expense's spending for an expense row (ADR 0026).
|
||||
*/
|
||||
monthly: number[];
|
||||
/** Sum of `monthly` — sibling ordering + row total convenience. */
|
||||
total: number;
|
||||
|
|
@ -478,7 +498,7 @@ export interface OverTimeRow {
|
|||
parent_id: number | null;
|
||||
is_parent: boolean;
|
||||
depth: number;
|
||||
category_type: "expense" | "income" | "transfer";
|
||||
category_type: ReportSection;
|
||||
}
|
||||
|
||||
export interface CategoryOverTimeData {
|
||||
|
|
@ -486,8 +506,8 @@ export interface CategoryOverTimeData {
|
|||
data: CategoryOverTimeItem[];
|
||||
colors: Record<string, string>;
|
||||
categoryIds: Record<string, number | null>;
|
||||
/** Category name -> its type. Built from the top-N rows (mirrors `colors`). */
|
||||
types: Record<string, "expense" | "income" | "transfer">;
|
||||
/** Category name -> its section. Built from the top-N rows (mirrors `colors`). */
|
||||
types: Record<string, ReportSection>;
|
||||
/**
|
||||
* Id-keyed hierarchical sidecar (Issue #264): EVERY category (no top-N, no
|
||||
* "Other" bucket), parent-first depth-first, income → expense → transfer.
|
||||
|
|
@ -498,10 +518,11 @@ export interface CategoryOverTimeData {
|
|||
}
|
||||
|
||||
export interface BudgetVsActualRow {
|
||||
category_id: number;
|
||||
/** Null for the uncategorized line (#392), the only row without a category. */
|
||||
category_id: number | null;
|
||||
category_name: string;
|
||||
category_color: string;
|
||||
category_type: "expense" | "income" | "transfer";
|
||||
category_type: ReportSection;
|
||||
parent_id: number | null;
|
||||
is_parent: boolean;
|
||||
depth?: number;
|
||||
|
|
@ -556,11 +577,9 @@ export interface CartesTopMover {
|
|||
deltaPct: number | null;
|
||||
}
|
||||
|
||||
export interface CartesMonthFlow {
|
||||
/** The income statement of one month of the Cartes series (#392, ADR 0026). */
|
||||
export interface CartesMonthFlow extends IncomeStatementFigures {
|
||||
month: string; // "YYYY-MM"
|
||||
income: number;
|
||||
expenses: number;
|
||||
net: number;
|
||||
}
|
||||
|
||||
export interface CartesBudgetWorstOverrun {
|
||||
|
|
@ -600,6 +619,11 @@ export interface CartesSnapshot {
|
|||
net: CartesKpi;
|
||||
savingsRate: CartesKpi; // value stored as 0-100
|
||||
};
|
||||
/**
|
||||
* What « Solde net » holds beyond income − expenses, over the KPI period
|
||||
* (the month, or the year to date): the note under its card (D5, #392).
|
||||
*/
|
||||
netBreakdown: { uncategorized: number; transfers: number };
|
||||
flow12Months: CartesMonthFlow[];
|
||||
topMoversUp: CartesTopMover[];
|
||||
topMoversDown: CartesTopMover[];
|
||||
|
|
|
|||
74
src/test/sqliteHarness.test.ts
Normal file
74
src/test/sqliteHarness.test.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { adapter, dbModule, openProfileDb, useDb } from "./sqliteHarness";
|
||||
|
||||
// The semantics the tests on a real database lean on, proved once.
|
||||
|
||||
let db: DatabaseSync;
|
||||
|
||||
beforeEach(() => {
|
||||
db = useDb(openProfileDb());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
db.close();
|
||||
});
|
||||
|
||||
describe("sqliteHarness", () => {
|
||||
it("opens the schema of a new profile, seed included", () => {
|
||||
expect({ ...db.prepare("SELECT name, type FROM categories WHERE id = 1111").get() }).toEqual({
|
||||
name: "Épicerie régulière",
|
||||
type: "expense",
|
||||
});
|
||||
});
|
||||
|
||||
it("binds $1, $2… by position, as tauri-plugin-sql does", async () => {
|
||||
const rows = await adapter(db).select("SELECT $2 AS second, $1 AS first", [1, "two"]);
|
||||
expect(rows).toEqual([{ second: "two", first: 1 }]);
|
||||
});
|
||||
|
||||
it("answers rowsAffected and lastInsertId", async () => {
|
||||
const insert = await adapter(db).execute(
|
||||
"INSERT INTO transactions (date, description, amount, original_description) VALUES ($1, $2, $3, $2)",
|
||||
["2026-10-01", "PAIE", 1000],
|
||||
);
|
||||
expect(insert).toEqual({ rowsAffected: 1, lastInsertId: 1 });
|
||||
const update = await adapter(db).execute("UPDATE transactions SET amount = $1", [900]);
|
||||
expect(update.rowsAffected).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps foreign keys on, as sqlx does", async () => {
|
||||
await expect(
|
||||
adapter(db).execute(
|
||||
"INSERT INTO transactions (date, description, amount, category_id, original_description) VALUES ('2026-10-01', 'X', 1, 999999, 'X')",
|
||||
),
|
||||
).rejects.toThrow(/FOREIGN KEY/);
|
||||
});
|
||||
|
||||
it("hands the transaction the same handle, and refuses getDb() inside it", async () => {
|
||||
const { getDb, withTransaction } = dbModule();
|
||||
const outside = await getDb();
|
||||
const inside = await withTransaction(async (handle) => {
|
||||
await expect(getDb()).rejects.toThrow(/inside a transaction/);
|
||||
return handle;
|
||||
});
|
||||
expect(inside).toBe(outside);
|
||||
// The transaction is over: getDb() answers again.
|
||||
await expect(getDb()).resolves.toBe(outside);
|
||||
});
|
||||
|
||||
it("refuses a transaction inside a transaction, and still refuses getDb() after it", async () => {
|
||||
const { getDb, withTransaction } = dbModule();
|
||||
let inner = false;
|
||||
await withTransaction(async () => {
|
||||
await expect(
|
||||
withTransaction(async () => {
|
||||
inner = true;
|
||||
}),
|
||||
).rejects.toThrow(/inside a transaction/);
|
||||
await expect(getDb()).rejects.toThrow(/inside a transaction/);
|
||||
});
|
||||
expect(inner).toBe(false);
|
||||
await expect(getDb()).resolves.toBeDefined();
|
||||
});
|
||||
});
|
||||
96
src/test/sqliteHarness.ts
Normal file
96
src/test/sqliteHarness.ts
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
// sqliteHarness — a real SQLite database under the services, for tests (#392).
|
||||
//
|
||||
// A fake `select` that returns canned rows proves nothing about a query: the
|
||||
// rows are already aggregated, so a test of a report could never go red on its
|
||||
// arithmetic. Under this harness the services run their SQL as written, on
|
||||
// `node:sqlite` (built into Node, no package; experimental under Node 22,
|
||||
// which prints a warning once per test file), with the schema of a new profile
|
||||
// and its seed (`consolidated_schema.sql`), foreign keys on, as under sqlx.
|
||||
// The app runs SQLite 3.46.0 (`libsqlite3-sys` 0.30.1, bundled) and Node 22
|
||||
// a later one: a query may not lean on anything newer than 3.46.
|
||||
//
|
||||
// USE — at the head of the test module, before the imports of the code under
|
||||
// test (the factory of `vi.mock` is hoisted, hence the dynamic import):
|
||||
//
|
||||
// vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
|
||||
// import { openProfileDb, useDb } from "../test/sqliteHarness";
|
||||
//
|
||||
// then, per test, `db = useDb(openProfileDb())` in `beforeEach` and
|
||||
// `db.close()` in `afterEach`. Every test module gets its own copy of this
|
||||
// module, so the database is shared by the mock and the test of one file,
|
||||
// never across files.
|
||||
//
|
||||
// THE FAKE `../services/db`
|
||||
// - `select` and `execute` run the statement with its `$1`, `$2`… bound by
|
||||
// name: tauri-plugin-sql binds them by position, `node:sqlite` by name.
|
||||
// - `execute` answers `rowsAffected` and `lastInsertId`.
|
||||
// - `withTransaction` hands its callback the same handle; `getDb()` and a
|
||||
// nested `withTransaction` throw while a transaction runs, where the real
|
||||
// lock, which is not reentrant, would deadlock.
|
||||
//
|
||||
// This module imports no value from a module that imports `../services/db`
|
||||
// (no service): the factory above imports it while that module is being built.
|
||||
// A test that uses it never calls `vi.resetModules()` nor `vi.doMock` on the db
|
||||
// module: a second copy of this module would split the database in two.
|
||||
|
||||
import { readFileSync } from "fs";
|
||||
import { resolve } from "path";
|
||||
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
|
||||
|
||||
/** The schema of a new profile, seed included. */
|
||||
export const SCHEMA = readFileSync(
|
||||
resolve(import.meta.dirname, "../../src-tauri/src/database/consolidated_schema.sql"),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
/** A database with the schema of a new profile, foreign keys on. */
|
||||
export function openProfileDb(): DatabaseSync {
|
||||
const db = new DatabaseSync(":memory:", { enableForeignKeyConstraints: true });
|
||||
db.exec(SCHEMA);
|
||||
return db;
|
||||
}
|
||||
|
||||
/** The connection the services see: tauri-plugin-sql's `select` and `execute`, on `db`. */
|
||||
export function adapter(db: DatabaseSync) {
|
||||
// tauri-plugin-sql binds `$1`, `$2`… by position; node:sqlite binds them by name.
|
||||
const bind = (params?: unknown[]) =>
|
||||
Object.fromEntries((params ?? []).map((value, i) => [`$${i + 1}`, value as SQLInputValue]));
|
||||
return {
|
||||
select: async (sql: string, params?: unknown[]) =>
|
||||
db.prepare(sql).all(bind(params)).map((row) => ({ ...row })),
|
||||
execute: async (sql: string, params?: unknown[]) => {
|
||||
const result = db.prepare(sql).run(bind(params));
|
||||
return { rowsAffected: Number(result.changes), lastInsertId: Number(result.lastInsertRowid) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const state = { handle: null as ReturnType<typeof adapter> | null, inTransaction: false };
|
||||
|
||||
/** Points the services at `db`, out of any transaction; returns `db`. */
|
||||
export function useDb(db: DatabaseSync): DatabaseSync {
|
||||
state.handle = adapter(db);
|
||||
state.inTransaction = false;
|
||||
return db;
|
||||
}
|
||||
|
||||
/** The module `../services/db` for `vi.mock`. */
|
||||
export function dbModule() {
|
||||
return {
|
||||
getDb: async () => {
|
||||
if (state.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
|
||||
if (!state.handle) throw new Error("sqliteHarness: no database, call useDb() first");
|
||||
return state.handle;
|
||||
},
|
||||
withTransaction: async <T>(fn: (db: ReturnType<typeof adapter>) => Promise<T>): Promise<T> => {
|
||||
if (state.inTransaction) throw new Error("withTransaction() inside a transaction: the real lock would deadlock");
|
||||
if (!state.handle) throw new Error("sqliteHarness: no database, call useDb() first");
|
||||
state.inTransaction = true;
|
||||
try {
|
||||
return await fn(state.handle);
|
||||
} finally {
|
||||
state.inTransaction = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
132
src/utils/incomeStatement.test.ts
Normal file
132
src/utils/incomeStatement.test.ts
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
SECTION_ORDER,
|
||||
SECTION_SQL,
|
||||
addStatements,
|
||||
incomeStatement,
|
||||
orient,
|
||||
savingsRate,
|
||||
statementOf,
|
||||
toCents,
|
||||
toSection,
|
||||
} from "./incomeStatement";
|
||||
|
||||
describe("toSection", () => {
|
||||
it("keeps the three category types and makes anything else uncategorized", () => {
|
||||
expect(toSection("income")).toBe("income");
|
||||
expect(toSection("expense")).toBe("expense");
|
||||
expect(toSection("transfer")).toBe("transfer");
|
||||
expect(toSection("uncategorized")).toBe("uncategorized");
|
||||
expect(toSection(null)).toBe("uncategorized");
|
||||
expect(toSection(undefined)).toBe("uncategorized");
|
||||
});
|
||||
|
||||
it("reads the section the SQL fragment gives, the uncategorized one included", () => {
|
||||
expect(SECTION_SQL).toBe("CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toCents", () => {
|
||||
it("drops the floating remainder of a refund that cancels two purchases, without a negative zero", () => {
|
||||
const remainder = 10.1 + 20.2 - 30.3;
|
||||
expect(remainder).not.toBe(0);
|
||||
expect(Object.is(toCents(remainder), 0)).toBe(true);
|
||||
expect(Object.is(toCents(-0), 0)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the cents", () => {
|
||||
expect(toCents(12.34)).toBe(12.34);
|
||||
expect(toCents(-0.1 - 0.2)).toBe(-0.3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("orient", () => {
|
||||
it("shows an expense category's spending: the opposite of its balance", () => {
|
||||
expect(orient("expense", -80)).toBe(80);
|
||||
// Refunds above purchases: a negative expense (D1).
|
||||
expect(orient("expense", 50)).toBe(-50);
|
||||
});
|
||||
|
||||
it("shows every other section's balance as it is", () => {
|
||||
expect(orient("income", 1000)).toBe(1000);
|
||||
expect(orient("transfer", -300)).toBe(-300);
|
||||
expect(orient("uncategorized", 40)).toBe(40);
|
||||
});
|
||||
|
||||
it("never shows a negative zero", () => {
|
||||
expect(Object.is(orient("expense", 0), 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("incomeStatement", () => {
|
||||
it("adds the signed balances by section, a split and a refund included (reproduction of #392)", () => {
|
||||
// Groceries: −100, its +30 offset line and a +20 refund; −30 split to Pharmacy.
|
||||
const r = incomeStatement([
|
||||
{ section: "income", balance: 1000 },
|
||||
{ section: "expense", balance: -100 + 30 + 20 },
|
||||
{ section: "expense", balance: -30 },
|
||||
{ section: "transfer", balance: -500 + 500 },
|
||||
]);
|
||||
expect(r).toEqual({
|
||||
income: 1000,
|
||||
expenses: 80,
|
||||
uncategorized: 0,
|
||||
transfers: 0,
|
||||
resultBeforeTransfers: 920,
|
||||
net: 920,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the uncategorized line and a one-leg transfer apart, both in the net (edge cases of #392)", () => {
|
||||
const r = incomeStatement([
|
||||
{ section: "income", balance: 1000 },
|
||||
{ section: "expense", balance: -80 },
|
||||
{ section: "expense", balance: 50 },
|
||||
{ section: "uncategorized", balance: 40 },
|
||||
{ section: "transfer", balance: -300 },
|
||||
]);
|
||||
expect(r).toEqual({
|
||||
income: 1000,
|
||||
expenses: 30,
|
||||
uncategorized: 40,
|
||||
transfers: -300,
|
||||
resultBeforeTransfers: 1010,
|
||||
net: 710,
|
||||
});
|
||||
});
|
||||
|
||||
it("is empty without rows, and reads a null balance as zero", () => {
|
||||
expect(incomeStatement([])).toEqual(statementOf(0, 0, 0, 0));
|
||||
expect(incomeStatement([{ section: "income", balance: null }]).income).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addStatements", () => {
|
||||
it("adds two periods, the result lines recomputed", () => {
|
||||
const sum = addStatements(statementOf(1000, 80, 0, 0), statementOf(500, 30, 40, -300));
|
||||
expect(sum).toEqual(statementOf(1500, 110, 40, -300));
|
||||
// 1500 − 110 + 40 − 300
|
||||
expect(sum.net).toBe(1130);
|
||||
});
|
||||
});
|
||||
|
||||
describe("savingsRate", () => {
|
||||
it("is (income − expenses) ÷ income, without transfers nor uncategorized amounts (D6)", () => {
|
||||
expect(savingsRate(1000, 80)).toBe(92);
|
||||
expect(savingsRate(1000, 30)).toBe(97);
|
||||
});
|
||||
|
||||
it("is null when income is not positive", () => {
|
||||
expect(savingsRate(0, 80)).toBeNull();
|
||||
expect(savingsRate(-10, 80)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("SECTION_ORDER", () => {
|
||||
it("reads income, expenses, the uncategorized line, then transfers", () => {
|
||||
const order = Object.entries(SECTION_ORDER)
|
||||
.sort((a, b) => a[1] - b[1])
|
||||
.map(([section]) => section);
|
||||
expect(order).toEqual(["income", "expense", "uncategorized", "transfer"]);
|
||||
});
|
||||
});
|
||||
114
src/utils/incomeStatement.ts
Normal file
114
src/utils/incomeStatement.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
// Sign convention of the reports (#392, ADR 0026).
|
||||
//
|
||||
// Every report sums the SIGNED amounts of a category over its period. A split
|
||||
// keeps its parent's amount in the parent's category, puts each part in its
|
||||
// own category and adds an offset line that cancels, in the parent's
|
||||
// category, what was sent elsewhere: the signed sum of a category is exactly
|
||||
// what it spent or earned, refunds included. A row takes the section of its
|
||||
// category's type; a row without an existing category is « Non classé »,
|
||||
// neither income nor expense, counted in the result (D4).
|
||||
//
|
||||
// The SQL returns those signed balances with their section (`SECTION_SQL`,
|
||||
// on `CATEGORY_JOIN_SQL`); this module turns them into what the screens show.
|
||||
// `ABS` only sorts and displays, it never adds amounts up.
|
||||
|
||||
import type { IncomeStatementFigures, ReportSection } from "../shared/types";
|
||||
|
||||
/**
|
||||
* Section of a transaction `t` joined to its category `c` by
|
||||
* `CATEGORY_JOIN_SQL`: the type of its category, or 'uncategorized' when the
|
||||
* row has no category or its category is gone (`c.id IS NULL`).
|
||||
*/
|
||||
export const SECTION_SQL = "CASE WHEN c.id IS NULL THEN 'uncategorized' ELSE c.type END";
|
||||
|
||||
/** The join of every report aggregation: LEFT, so the rows without a category stay. */
|
||||
export const CATEGORY_JOIN_SQL = "LEFT JOIN categories c ON c.id = t.category_id";
|
||||
|
||||
/**
|
||||
* Income-statement reading order. The uncategorized line comes after the
|
||||
* expenses: it belongs to the result before transfers.
|
||||
*/
|
||||
export const SECTION_ORDER: Record<ReportSection, number> = {
|
||||
income: 0,
|
||||
expense: 1,
|
||||
uncategorized: 2,
|
||||
transfer: 3,
|
||||
};
|
||||
|
||||
/** A section read from the SQL; anything that is no category type is uncategorized. */
|
||||
export function toSection(value: unknown): ReportSection {
|
||||
return value === "income" || value === "expense" || value === "transfer" ? value : "uncategorized";
|
||||
}
|
||||
|
||||
/**
|
||||
* Rounds to the cent and drops a negative zero. A refund that cancels two
|
||||
* purchases leaves a floating remainder (10.10 + 20.20 − 30.30 is
|
||||
* −3.6e-15), which a currency format shows as « -0 $ ».
|
||||
*/
|
||||
export function toCents(amount: number): number {
|
||||
return Math.round(amount * 100) / 100 + 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a section shows for a signed balance: an expense shows its spending,
|
||||
* the opposite of its balance (negative when refunds exceed purchases), and
|
||||
* every other section its balance.
|
||||
*/
|
||||
export function orient(section: ReportSection, balance: number): number {
|
||||
return toCents(section === "expense" ? 0 - balance : balance);
|
||||
}
|
||||
|
||||
/** The two result lines of four section figures (D4, D5). */
|
||||
export function statementOf(
|
||||
income: number,
|
||||
expenses: number,
|
||||
uncategorized: number,
|
||||
transfers: number,
|
||||
): IncomeStatementFigures {
|
||||
const resultBeforeTransfers = toCents(income - expenses + uncategorized);
|
||||
return {
|
||||
income,
|
||||
expenses,
|
||||
uncategorized,
|
||||
transfers,
|
||||
resultBeforeTransfers,
|
||||
net: toCents(resultBeforeTransfers + transfers),
|
||||
};
|
||||
}
|
||||
|
||||
export const EMPTY_STATEMENT: IncomeStatementFigures = statementOf(0, 0, 0, 0);
|
||||
|
||||
/** The income statement of signed balances, one or several per section. */
|
||||
export function incomeStatement(
|
||||
rows: Iterable<{ section: unknown; balance: number | null }>,
|
||||
): IncomeStatementFigures {
|
||||
const sums: Record<ReportSection, number> = { income: 0, expense: 0, uncategorized: 0, transfer: 0 };
|
||||
for (const row of rows) sums[toSection(row.section)] += Number(row.balance ?? 0);
|
||||
return statementOf(
|
||||
orient("income", sums.income),
|
||||
orient("expense", sums.expense),
|
||||
orient("uncategorized", sums.uncategorized),
|
||||
orient("transfer", sums.transfer),
|
||||
);
|
||||
}
|
||||
|
||||
/** The income statement of two periods added up (a year to date, for instance). */
|
||||
export function addStatements(
|
||||
a: IncomeStatementFigures,
|
||||
b: IncomeStatementFigures,
|
||||
): IncomeStatementFigures {
|
||||
return statementOf(
|
||||
toCents(a.income + b.income),
|
||||
toCents(a.expenses + b.expenses),
|
||||
toCents(a.uncategorized + b.uncategorized),
|
||||
toCents(a.transfers + b.transfers),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Savings rate (D6), in percent: (income − expenses) ÷ income, with neither
|
||||
* transfers nor uncategorized amounts; null when income is not positive.
|
||||
*/
|
||||
export function savingsRate(income: number, expenses: number): number | null {
|
||||
return income > 0 ? ((income - expenses) / income) * 100 : null;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue