fix: a split's offset line takes its parent's manual flag (#454) #519
10 changed files with 376 additions and 51 deletions
|
|
@ -25,7 +25,7 @@
|
|||
- Import : un message d'erreur ne reste plus affiché une fois le dossier d'import relu, après « Actualiser » ou après le choix d'un autre dossier par « Parcourir » ; le message d'un dossier d'exemple déjà présent dans le dossier d'import demandait justement d'actualiser. Annuler le choix du dossier garde le message (#384).
|
||||
- Journaux (Paramètres → Système) : une ligne d'erreur sur l'ouverture ou la fermeture d'un profil ne garde plus le nom d'un dossier qui contient `;`, `|`, une apostrophe inverse ou une parenthèse fermante suivie d'un mot, comme `Jean (Work) Smith` : elle ne nomme que le fichier. La ligne écrite quand la réparation des migrations d'un profil échoue à son ouverture (« Migration repair failed ») ne nomme plus, elle aussi, que le fichier de la base ; elle en montrait le chemin complet, dossiers de votre compte compris. Ces lignes peuvent partir avec une rétroaction quand vous y incluez les derniers logs d'erreur. En contrepartie, le texte qui suit un chemin après l'un de ces caractères et qui contient un `/` ou un `\` est désormais retiré avec les dossiers, jusqu'à son dernier `/` ou `\` (#478).
|
||||
- Journaux (Paramètres → Système) : une ligne des journaux ne porte plus votre dossier personnel ni le dossier qui contient les bases des profils, nommés tous deux d'après votre compte d'utilisateur, quoi qu'il y ait autour, comme un nom de dossier qui contient une virgule (`Smith, Jean`) ou un chemin collé à un `;` : le dossier personnel devient `~` et celui des bases `<profile folder>`. Cela vaut pour toutes les lignes, ce que copie « Copier » compris, et les lignes écrites au démarrage avant que ces dossiers soient connus les perdent dès qu'ils le sont. Une ligne d'erreur sur l'ouverture ou la fermeture d'un profil ne nomme toujours que le fichier. Ces lignes peuvent partir avec une rétroaction quand vous y incluez les derniers logs d'erreur (#497).
|
||||
- Transactions : changer la catégorie d'une transaction répartie déplace désormais toute sa part non répartie vers la nouvelle catégorie. Les rapports gardaient, dans l'ancienne catégorie, le montant envoyé vers les autres catégories avec le signe inverse, sans transaction correspondante, et comptaient la transaction entière dans la nouvelle : une transaction de −120 dont −50 sont répartis vers B, déplacée de A vers C, laissait +50 dans A et −120 dans C, au lieu de −70 dans C. Cela vaut pour la catégorie choisie dans la liste des transactions comme pour les transactions recatégorisées par un nouveau mot-clé. Une répartition déjà touchée se répare au prochain changement de catégorie de sa transaction, et sa fenêtre de répartition ne montre plus ce montant comme l'une de ses lignes. La prévisualisation d'un mot-clé ne liste plus les parts d'une répartition, qu'elle pouvait recatégoriser sans leur transaction (#454).
|
||||
- Transactions : changer la catégorie d'une transaction répartie déplace désormais toute sa part non répartie vers la nouvelle catégorie. Les rapports gardaient, dans l'ancienne catégorie, le montant envoyé vers les autres catégories avec le signe inverse, sans transaction correspondante, et comptaient la transaction entière dans la nouvelle : une transaction de −120 dont −50 sont répartis vers B, déplacée de A vers C, laissait +50 dans A et −120 dans C, au lieu de −70 dans C. Cela vaut pour la catégorie choisie dans la liste des transactions comme pour les transactions recatégorisées par un nouveau mot-clé. « Auto-catégoriser » ne déplace plus ce montant seul quand la transaction a été mise à la main sur « Sans catégorie ». Une répartition déjà touchée se répare au prochain changement de catégorie de sa transaction, et sa fenêtre de répartition ne montre plus ce montant comme l'une de ses lignes. La prévisualisation d'un mot-clé ne liste plus les parts d'une répartition, qu'elle pouvait recatégoriser sans leur transaction (#454).
|
||||
- Transactions : enregistrer ou supprimer une répartition ne laisse plus de répartition à moitié écrite après une erreur (#513).
|
||||
- Rapports : « Tout » montre désormais toutes les dates sur Tendances, dans ses deux vues, et sur l'Analyse par catégorie ; il montrait l'année civile en cours. Sur les Comparables, « Tout » ne déplace plus le mois de référence vers décembre de l'année en cours : le mois affiché reste le même jusqu'au choix d'une période datée, qui le place à la fin de cette période (#479).
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@
|
|||
- Import: an error message no longer stays on screen once the import folder is read again, after “Refresh” or after choosing another folder with “Browse”; the message of a sample folder already in the import folder asked for that very refresh. Cancelling the folder choice keeps the message (#384).
|
||||
- Logs (Settings → System): an error line about opening or closing a profile no longer keeps the name of a folder that holds `;`, `|`, a backtick or a closing parenthesis followed by a word, such as `Jean (Work) Smith`: it names the file only. The line written when the migration repair of a profile fails at opening (“Migration repair failed”) now names the database file only too; it showed the file's full path, folders of your user account included. These lines can go with a feedback report when you include the recent error logs. In return, text that follows a path after one of these characters and holds a `/` or a `\` is now dropped with the folders, up to its last `/` or `\` (#478).
|
||||
- Logs (Settings → System): a line of the logs no longer carries your home folder or the folder that holds the profile databases, both named after your user account, whatever surrounds them, such as a folder name that holds a comma (`Smith, Jean`) or a path glued to a `;`: the home folder becomes `~` and the databases' folder `<profile folder>`. This holds for every line, what “Copy” copies included, and the lines written at startup before these folders are known lose them as soon as they are. An error line about opening or closing a profile still names the file only. These lines can go with a feedback report when you include the recent error logs (#497).
|
||||
- Transactions: changing the category of a split transaction now moves all of its unsplit part to the new category. The reports used to keep, in the former category, the amount sent to the other categories with the opposite sign, matching no transaction, and to count the whole transaction in the new one: a transaction of −120 with −50 split to B, moved from A to C, left +50 in A and −120 in C, instead of −70 in C. This holds for the category chosen in the Transactions list and for the transactions recategorized by a new keyword. A split already affected is repaired the next time its transaction changes category, and its split window no longer shows that amount as one of its rows. The keyword preview no longer lists the parts of a split, which it could recategorize without their transaction (#454).
|
||||
- Transactions: changing the category of a split transaction now moves all of its unsplit part to the new category. The reports used to keep, in the former category, the amount sent to the other categories with the opposite sign, matching no transaction, and to count the whole transaction in the new one: a transaction of −120 with −50 split to B, moved from A to C, left +50 in A and −120 in C, instead of −70 in C. This holds for the category chosen in the Transactions list and for the transactions recategorized by a new keyword. “Auto-categorize” no longer moves that amount alone when the transaction was set to “No category” by hand. A split already affected is repaired the next time its transaction changes category, and its split window no longer shows that amount as one of its rows. The keyword preview no longer lists the parts of a split, which it could recategorize without their transaction (#454).
|
||||
- Transactions: saving or deleting a split no longer leaves a half-written split after an error (#513).
|
||||
- Reports: “All” now shows every date on Trends, in both views, and on Category Analysis; it showed the current calendar year. On Compare, “All” no longer moves the reference month to December of the current year: the month shown stays as it is until you choose a dated period, which moves it to the end of that period (#479).
|
||||
|
||||
|
|
|
|||
|
|
@ -193,4 +193,4 @@ 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` et `src/__integration__/onboarding-samples.test.ts` lisent `consolidated_schema.sql`, `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 `src/__integration__/split-offset-manual-flag.test.ts` lisent `consolidated_schema.sql` (le dernier l'exécute en entier, seed compris), `src/utils/changelog.test.ts` la version de `tauri.conf.json`. Une PR qui ne touche que `src-tauri/**` saute `check-frontend` : la dérive ne rougit que la PR suivante qui touche `src/`, sans rapport avec elle. La revue d'une telle PR lance ces tests (`npx vitest run <fichier>`). — `check-frontend.yml` (`paths-ignore`), #384
|
||||
|
|
|
|||
|
|
@ -207,7 +207,7 @@ Le dossier des bases est celui du plugin : `app_config_dir()`, résolu par `prof
|
|||
| `importedFileService.ts` | Suivi des fichiers importés |
|
||||
| `importConfigTemplateService.ts` | Modèles de configuration d'import |
|
||||
| `categorizationService.ts` | Catégorisation automatique + helpers édition de mot-clé (`validateKeyword`, `previewKeywordMatches`, `applyKeywordWithReassignment`). L'aperçu ne propose jamais un enfant de répartition (`parent_transaction_id IS NULL`) ; l'application ne reclasse jamais un enfant seul (`AND parent_transaction_id IS NULL`, `updatedTransactions` compté par `rowsAffected`) et, avant le `COMMIT`, fait suivre la ligne de compensation de chaque parent coché (`propagateCategoryToOffsets`, #454) |
|
||||
| `splitOffsetService.ts` | Ligne de compensation d'une répartition (#454) : `propagateCategoryToOffsets(db, parentId, categoryId)` donne la catégorie du parent à l'enfant que reconnaît `isOffsetChild` (`utils/splitOffset.ts`, pur : description du parent, signe opposé au sien, montant non nul), quelle que soit sa catégorie actuelle, et rend le nombre de lignes déplacées. Rien pour un identifiant inconnu, une transaction non répartie ou un enfant (les enfants portent aussi `is_split = 1` : un parent est la ligne sans `parent_transaction_id`). Tourne sur le handle de la transaction de son appelant (`updateTransactionCategory`, `applyKeywordWithReassignment`) : jamais de `BEGIN` ni de `COMMIT`, de `getDb()` ni de notification. Module à part parce que `transactionService.ts` importe déjà `categorizationService.ts` ; il n'importe ni l'un ni l'autre. La fenêtre de répartition (`SplitAdjustmentModal`) écarte de ses entrées l'enfant que reconnaît le même prédicat |
|
||||
| `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`) |
|
||||
|
|
@ -702,7 +702,9 @@ Garde : `src/__integration__/i18n-mock-guard.test.ts` lit tous les `*.test.ts(x)
|
|||
|
||||
### SQL réel — `node:sqlite` (#393)
|
||||
|
||||
`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. Les autres tests de services gardent leurs faux.
|
||||
`categoryService.test.ts` exécute les requêtes qui vérifient ce que porte un parent (transactions, montants de budget, mots-clés) telles qu'elles sont écrites, sur une base SQLite en mémoire de `node:sqlite`, module intégré à Node (aucun paquet ; expérimental sous Node 22, qui l'annonce par un avertissement à l'exécution). Ses tables y sont créées par leur `CREATE TABLE` de `consolidated_schema.sql`, clés étrangères coupées : la table `categories` reste dans le faux du test. Une condition retirée d'une requête (`amount <> 0`, `is_active = 1`) rougit donc un test, ce qu'un faux qui réimplémente la règle ne ferait pas.
|
||||
|
||||
`src/__integration__/split-offset-manual-flag.test.ts` (#454) y fait tourner des services entiers : `saveSplitAdjustment`, `updateTransactionCategory` et `autoCategorizeTransactions`, tels qu'ils sont écrits, sur le schéma complet d'un profil neuf (`consolidated_schema.sql`, seed compris : mot-clé `METRO`, catégories 1111 et 1112), clés étrangères actives comme sous sqlx. `../services/db` y est remplacé par un adaptateur propre au fichier : `select` et `execute` lient `$N` par nom, `execute` rend `rowsAffected` et `lastInsertId`, `withTransaction` passe à son rappel le même handle, et `getDb()` échoue pendant une transaction, là où le vrai verrou bloquerait. Aucun harnais partagé : #392 le prévoit. Les autres tests de services gardent leurs faux.
|
||||
|
||||
### Limites connues (#437)
|
||||
|
||||
|
|
|
|||
197
src/__integration__/split-offset-manual-flag.test.ts
Normal file
197
src/__integration__/split-offset-manual-flag.test.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
/**
|
||||
* A split's offset line and « Catégoriser automatiquement » (#454, item 1 of
|
||||
* the review of PR #515).
|
||||
*
|
||||
* `autoCategorizeTransactions` picks every row without a category whose
|
||||
* `is_manually_categorized` is 0, the children of a split included. The offset
|
||||
* line of a split cancels, in its parent's category, the part sent to the other
|
||||
* categories: it takes its parent's manual flag when the split is written
|
||||
* (`saveSplitAdjustment`) and when the parent changes category
|
||||
* (`propagateCategoryToOffsets`), so that a parent set to no category by hand
|
||||
* 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.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { readFileSync } from "fs";
|
||||
import { resolve } from "path";
|
||||
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
|
||||
|
||||
const fake = vi.hoisted(() => ({
|
||||
handle: null as unknown,
|
||||
inTransaction: false,
|
||||
}));
|
||||
|
||||
vi.mock("../services/db", () => ({
|
||||
getDb: vi.fn(async () => {
|
||||
if (fake.inTransaction) throw new Error("getDb() inside a transaction: the real lock would deadlock");
|
||||
return fake.handle;
|
||||
}),
|
||||
withTransaction: vi.fn(async (fn: (db: unknown) => Promise<unknown>) => {
|
||||
fake.inTransaction = true;
|
||||
try {
|
||||
return await fn(fake.handle);
|
||||
} finally {
|
||||
fake.inTransaction = false;
|
||||
}
|
||||
}),
|
||||
}));
|
||||
|
||||
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. */
|
||||
const B = 1112;
|
||||
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;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
db.close();
|
||||
});
|
||||
|
||||
/**
|
||||
* A transaction of −120 as an import writes it: its category from the
|
||||
* keywords, or none, and no manual flag (the column's default, 0).
|
||||
*/
|
||||
function imported(categoryId: number | null): number {
|
||||
const result = db
|
||||
.prepare(
|
||||
`INSERT INTO transactions (date, description, amount, category_id, original_description)
|
||||
VALUES ('2026-10-01', $description, -120, $category, $description)`,
|
||||
)
|
||||
.run({ $description: DESCRIPTION, $category: categoryId });
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
|
||||
type Line = { category_id: number | null; is_manually_categorized: number };
|
||||
|
||||
/** The category and the manual flag of the parent, of its entry (−50) and of its offset line (+50). */
|
||||
function split(parentId: number): { parent: Line; entry: Line; offset: Line } {
|
||||
const line = (where: string) =>
|
||||
({
|
||||
...db
|
||||
.prepare(`SELECT category_id, is_manually_categorized FROM transactions WHERE ${where}`)
|
||||
.get({ $id: parentId }),
|
||||
}) as Line;
|
||||
return {
|
||||
parent: line("id = $id"),
|
||||
entry: line("parent_transaction_id = $id AND amount < 0"),
|
||||
offset: line("parent_transaction_id = $id AND amount > 0"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What the reports add up, per category (`none` for no category): every row,
|
||||
* the split parent and its children included, the offset line cancelling in
|
||||
* the parent's category the part sent to the others.
|
||||
*/
|
||||
function totals(): Record<string, number> {
|
||||
const rows = db
|
||||
.prepare("SELECT category_id, SUM(amount) AS total FROM transactions GROUP BY category_id")
|
||||
.all() as Array<{ category_id: number | null; total: number }>;
|
||||
return Object.fromEntries(rows.map((r) => [r.category_id === null ? "none" : String(r.category_id), r.total]));
|
||||
}
|
||||
|
||||
describe("a split's offset line keeps its parent's manual flag (#454)", () => {
|
||||
it("the seed sends « EPICERIE METRO » to « Épicerie régulière », by its METRO keyword", () => {
|
||||
expect({ ...db.prepare("SELECT category_id FROM keywords WHERE keyword = 'METRO'").get() }).toEqual({
|
||||
category_id: GROCERIES,
|
||||
});
|
||||
});
|
||||
|
||||
// Scenario R-S3 of the review of PR #515.
|
||||
it("a split parent set to no category by hand keeps its offset line through « Catégoriser automatiquement »", async () => {
|
||||
const parent = imported(GROCERIES);
|
||||
await saveSplitAdjustment(parent, ENTRIES);
|
||||
// « Aucune catégorie » in the Transactions list (TransactionTable → useTransactions).
|
||||
await updateTransactionCategory(parent, null, true);
|
||||
expect(totals()).toEqual({ none: -70, [B]: -50 });
|
||||
|
||||
const categorized = await autoCategorizeTransactions();
|
||||
|
||||
expect(totals()).toEqual({ none: -70, [B]: -50 });
|
||||
expect(categorized).toBe(0);
|
||||
expect(split(parent)).toEqual({
|
||||
parent: { category_id: null, is_manually_categorized: 1 },
|
||||
// The entries keep the flag 0: out of the scope of #454.
|
||||
entry: { category_id: B, is_manually_categorized: 0 },
|
||||
offset: { category_id: null, is_manually_categorized: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("a split made under a parent set to no category by hand keeps its offset line through « Catégoriser automatiquement »", async () => {
|
||||
const parent = imported(GROCERIES);
|
||||
await updateTransactionCategory(parent, null, true);
|
||||
await saveSplitAdjustment(parent, ENTRIES);
|
||||
expect(totals()).toEqual({ none: -70, [B]: -50 });
|
||||
|
||||
const categorized = await autoCategorizeTransactions();
|
||||
|
||||
expect(totals()).toEqual({ none: -70, [B]: -50 });
|
||||
expect(categorized).toBe(0);
|
||||
expect(split(parent).offset).toEqual({ category_id: null, is_manually_categorized: 1 });
|
||||
});
|
||||
|
||||
it("witness: a parent imported without a category and its offset line get the same category from « Catégoriser automatiquement », as before", async () => {
|
||||
const parent = imported(null);
|
||||
await saveSplitAdjustment(parent, ENTRIES);
|
||||
expect(split(parent)).toEqual({
|
||||
parent: { category_id: null, is_manually_categorized: 0 },
|
||||
entry: { category_id: B, is_manually_categorized: 0 },
|
||||
offset: { category_id: null, is_manually_categorized: 0 },
|
||||
});
|
||||
|
||||
const categorized = await autoCategorizeTransactions();
|
||||
|
||||
expect(totals()).toEqual({ [GROCERIES]: -70, [B]: -50 });
|
||||
expect(categorized).toBe(2);
|
||||
expect(split(parent)).toEqual({
|
||||
parent: { category_id: GROCERIES, is_manually_categorized: 0 },
|
||||
entry: { category_id: B, is_manually_categorized: 0 },
|
||||
offset: { category_id: GROCERIES, is_manually_categorized: 0 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -320,8 +320,17 @@ describe("applyKeywordWithReassignment — data-change notification (#396)", ()
|
|||
describe("applyKeywordWithReassignment — a split's offset line follows its parent (#454)", () => {
|
||||
// The reproduction of #454: −120 in category A, of which −50 are split to B
|
||||
// (the entry, with the parent's description), and the offset line of +50,
|
||||
// which cancels those −50 in A. The keyword moves the parent to category 9.
|
||||
const PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null };
|
||||
// which cancels those −50 in A. The keyword moves the parent to category 9;
|
||||
// the offset propagation reads the parent after that UPDATE, which writes
|
||||
// the manual flag 1.
|
||||
const PARENT = {
|
||||
id: 5,
|
||||
description: "EPICERIE METRO",
|
||||
amount: -120,
|
||||
is_split: 1,
|
||||
is_manually_categorized: 1,
|
||||
parent_transaction_id: null,
|
||||
};
|
||||
const ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 };
|
||||
const OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 };
|
||||
const input = { keyword: "METRO", categoryId: 9, transactionIds: [PARENT.id], allowReplaceExisting: false };
|
||||
|
|
@ -337,9 +346,10 @@ describe("applyKeywordWithReassignment — a split's offset line follows its par
|
|||
|
||||
const sent = statements();
|
||||
const offsetMove = sent.findIndex(
|
||||
(s) => s.sql.startsWith("UPDATE transactions SET category_id = $1, updated_at") && targetOf(s) === OFFSET.id,
|
||||
(s) => s.sql.startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2,") && targetOf(s) === OFFSET.id,
|
||||
);
|
||||
expect(sent[offsetMove]?.params).toEqual([9, OFFSET.id]);
|
||||
// The offset line takes the parent's category and its manual flag.
|
||||
expect(sent[offsetMove]?.params).toEqual([9, 1, OFFSET.id]);
|
||||
// The entry keeps its own category.
|
||||
expect(sent.filter((s) => targetOf(s) === ENTRY.id)).toEqual([]);
|
||||
expect(sent[0].sql).toBe("BEGIN");
|
||||
|
|
@ -371,7 +381,7 @@ describe("applyKeywordWithReassignment — a split's offset line follows its par
|
|||
it("rolls the keyword and the transactions back when the offset cannot be moved", async () => {
|
||||
splitReads();
|
||||
mockExecute.mockImplementation(async (sql: string, params?: unknown[]) => {
|
||||
if (String(sql).startsWith("UPDATE transactions SET category_id = $1, updated_at") && params?.[1] === OFFSET.id) {
|
||||
if (String(sql).startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2,") && params?.[2] === OFFSET.id) {
|
||||
throw new Error("disk full");
|
||||
}
|
||||
return { lastInsertId: 77, rowsAffected: 1 };
|
||||
|
|
|
|||
|
|
@ -39,11 +39,24 @@ function answer(row: Record<string, unknown> | undefined, children: Array<Record
|
|||
}
|
||||
|
||||
// The reproduction of #454: −120 split as −50 to another category (the entry,
|
||||
// with the parent's description) and the offset line of +50.
|
||||
const PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null };
|
||||
// with the parent's description) and the offset line of +50. The parent is
|
||||
// read after its caller's UPDATE, which both callers write with the manual
|
||||
// flag 1.
|
||||
const PARENT = {
|
||||
id: 5,
|
||||
description: "EPICERIE METRO",
|
||||
amount: -120,
|
||||
is_split: 1,
|
||||
is_manually_categorized: 1,
|
||||
parent_transaction_id: null,
|
||||
};
|
||||
const ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 };
|
||||
const OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 };
|
||||
|
||||
/** The UPDATE of the offset line: the parent's category and manual flag. */
|
||||
const MOVE_OFFSET =
|
||||
"UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3";
|
||||
|
||||
const notifications: number[] = [];
|
||||
let stop: () => void = () => undefined;
|
||||
|
||||
|
|
@ -63,20 +76,15 @@ describe("propagateCategoryToOffsets — which rows it moves (#454)", () => {
|
|||
it("moves the offset line of a split parent, and only it", async () => {
|
||||
answer(PARENT, [ENTRY, OFFSET]);
|
||||
await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).resolves.toBe(1);
|
||||
expect(sent()).toEqual([
|
||||
{
|
||||
sql: "UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2",
|
||||
params: [9, OFFSET.id],
|
||||
},
|
||||
]);
|
||||
expect(sent()).toEqual([{ sql: MOVE_OFFSET, params: [9, 1, OFFSET.id] }]);
|
||||
});
|
||||
|
||||
it("reads the row by its id, then the children by their parent, whatever their category", async () => {
|
||||
it("reads the row by its id, with its manual flag, then the children by their parent, whatever their category", async () => {
|
||||
answer(PARENT, [ENTRY, OFFSET]);
|
||||
await propagateCategoryToOffsets(handle, PARENT.id, 9);
|
||||
expect(reads()).toEqual([
|
||||
{
|
||||
sql: "SELECT id, description, amount, is_split, parent_transaction_id FROM transactions WHERE id = $1",
|
||||
sql: "SELECT id, description, amount, is_split, is_manually_categorized, parent_transaction_id FROM transactions WHERE id = $1",
|
||||
params: [PARENT.id],
|
||||
},
|
||||
{
|
||||
|
|
@ -92,13 +100,13 @@ describe("propagateCategoryToOffsets — which rows it moves (#454)", () => {
|
|||
const offset = { id: 7, description: "EPICERIE METRO", amount: -500 };
|
||||
answer(income, [entry, offset]);
|
||||
await expect(propagateCategoryToOffsets(handle, income.id, 9)).resolves.toBe(1);
|
||||
expect(sent().map((s) => s.params)).toEqual([[9, offset.id]]);
|
||||
expect(sent().map((s) => s.params)).toEqual([[9, 1, offset.id]]);
|
||||
});
|
||||
|
||||
it("moves the offset line to no category when the parent loses its own", async () => {
|
||||
answer(PARENT, [ENTRY, OFFSET]);
|
||||
await propagateCategoryToOffsets(handle, PARENT.id, null);
|
||||
expect(sent().map((s) => s.params)).toEqual([[null, OFFSET.id]]);
|
||||
expect(sent().map((s) => s.params)).toEqual([[null, 1, OFFSET.id]]);
|
||||
});
|
||||
|
||||
it("leaves a child of the opposite sign alone when it carries another description", async () => {
|
||||
|
|
@ -143,9 +151,34 @@ describe("propagateCategoryToOffsets — inside the caller's transaction (#454)"
|
|||
answer(PARENT, [ENTRY, OFFSET]);
|
||||
execute.mockRejectedValueOnce(new Error("disk full"));
|
||||
await expect(propagateCategoryToOffsets(handle, PARENT.id, 9)).rejects.toThrow("disk full");
|
||||
expect(sent().map((s) => s.sql)).toEqual([
|
||||
"UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2",
|
||||
]);
|
||||
expect(sent().map((s) => s.sql)).toEqual([MOVE_OFFSET]);
|
||||
expect(notifications).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// `autoCategorizeTransactions` picks every row without a category and with the
|
||||
// manual flag 0, children included: an offset line left at 0 under a parent set
|
||||
// to no category by hand would be categorized alone (review of PR #515).
|
||||
describe("propagateCategoryToOffsets — the offset line takes its parent's manual flag (#454)", () => {
|
||||
it.each<[string, unknown, 0 | 1]>([
|
||||
["the flag 1", 1, 1],
|
||||
["the flag 0", 0, 0],
|
||||
["the TEXT 'true' of a base written before #390, as 1", "true", 1],
|
||||
])("copies %s, bound as an integer", async (_label, flag, bound) => {
|
||||
answer({ ...PARENT, is_manually_categorized: flag }, [ENTRY, OFFSET]);
|
||||
await expect(propagateCategoryToOffsets(handle, PARENT.id, null)).resolves.toBe(1);
|
||||
expect(sent()).toEqual([{ sql: MOVE_OFFSET, params: [null, bound, OFFSET.id] }]);
|
||||
expect(typeof sent()[0].params[1]).toBe("number");
|
||||
});
|
||||
|
||||
it("reads the flag on the parent, never on the offset line", async () => {
|
||||
answer({ ...PARENT, is_manually_categorized: 1 }, [ENTRY, { ...OFFSET, is_manually_categorized: 0 }]);
|
||||
await propagateCategoryToOffsets(handle, PARENT.id, null);
|
||||
answer({ ...PARENT, is_manually_categorized: 0 }, [ENTRY, { ...OFFSET, is_manually_categorized: 1 }]);
|
||||
await propagateCategoryToOffsets(handle, PARENT.id, null);
|
||||
expect(sent().map((s) => s.params)).toEqual([
|
||||
[null, 1, OFFSET.id],
|
||||
[null, 0, OFFSET.id],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ interface ParentRow {
|
|||
description: string;
|
||||
amount: number;
|
||||
is_split: unknown;
|
||||
is_manually_categorized: unknown;
|
||||
parent_transaction_id: number | null;
|
||||
}
|
||||
|
||||
|
|
@ -27,8 +28,9 @@ interface ChildRow {
|
|||
|
||||
/**
|
||||
* Moves the offset line of the split parent `parentId` to `categoryId`, the
|
||||
* category the caller has just given the parent, and returns the number of
|
||||
* rows moved (one for a split written by the split window).
|
||||
* category the caller has just given the parent, with the parent's
|
||||
* `is_manually_categorized` flag, and returns the number of rows moved (one
|
||||
* for a split written by the split window).
|
||||
*
|
||||
* Runs on `db`, the handle of the caller's transaction, between the caller's
|
||||
* BEGIN and COMMIT: it never issues BEGIN, COMMIT or ROLLBACK (it also runs
|
||||
|
|
@ -41,8 +43,16 @@ interface ChildRow {
|
|||
* `is_split = 1` too, so a parent is the row without `parent_transaction_id`).
|
||||
* An offset line follows whatever its current category, so one left in a
|
||||
* former category by a change made before #454 is repaired at the parent's
|
||||
* next change (decision D2 of #454). Its `is_manually_categorized` flag stays
|
||||
* as it is: nothing reads it on a child.
|
||||
* next change (decision D2 of #454).
|
||||
*
|
||||
* The flag is read on the parent's row after the caller's UPDATE, so it is the
|
||||
* one the caller has just written. The offset line takes it because
|
||||
* `autoCategorizeTransactions` picks every row without a category and with the
|
||||
* flag 0, children included: under a parent set to no category by hand, an
|
||||
* offset line left at 0 would be categorized alone, by the keyword of the
|
||||
* parent's description, and its amount would leave the parent's category
|
||||
* (review of PR #515). `saveSplitAdjustment` gives it the same flag when it
|
||||
* writes the split.
|
||||
*/
|
||||
export async function propagateCategoryToOffsets(
|
||||
db: Database,
|
||||
|
|
@ -50,7 +60,7 @@ export async function propagateCategoryToOffsets(
|
|||
categoryId: number | null,
|
||||
): Promise<number> {
|
||||
const [parent] = await db.select<ParentRow[]>(
|
||||
`SELECT id, description, amount, is_split, parent_transaction_id
|
||||
`SELECT id, description, amount, is_split, is_manually_categorized, parent_transaction_id
|
||||
FROM transactions
|
||||
WHERE id = $1`,
|
||||
[parentId],
|
||||
|
|
@ -67,12 +77,15 @@ export async function propagateCategoryToOffsets(
|
|||
[parentId],
|
||||
);
|
||||
|
||||
// Never the value as read: a base written before #390 may hold the TEXT
|
||||
// 'true', which `is_manually_categorized = 1` never matches.
|
||||
const manualFlag = toSqlFlag(parent.is_manually_categorized);
|
||||
let moved = 0;
|
||||
for (const child of children) {
|
||||
if (!isOffsetChild(parent, child)) continue;
|
||||
await db.execute(
|
||||
`UPDATE transactions SET category_id = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2`,
|
||||
[categoryId, child.id],
|
||||
`UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3`,
|
||||
[categoryId, manualFlag, child.id],
|
||||
);
|
||||
moved++;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,8 +90,17 @@ function answerSplitReads(row: Record<string, unknown> | null, children: Array<R
|
|||
// are split to category B. The split wrote two children: the entry (−50 in B,
|
||||
// with the parent's description, as the split window writes an entry left
|
||||
// without one) and the offset line (+50 in A, the parent's description), which
|
||||
// cancels in A the part sent to B.
|
||||
const SPLIT_PARENT = { id: 5, description: "EPICERIE METRO", amount: -120, is_split: 1, parent_transaction_id: null };
|
||||
// cancels in A the part sent to B. The offset propagation reads the parent
|
||||
// after its UPDATE, here with the manual flag 1 that `updateTransactionCategory`
|
||||
// has just written.
|
||||
const SPLIT_PARENT = {
|
||||
id: 5,
|
||||
description: "EPICERIE METRO",
|
||||
amount: -120,
|
||||
is_split: 1,
|
||||
is_manually_categorized: 1,
|
||||
parent_transaction_id: null,
|
||||
};
|
||||
const SPLIT_ENTRY = { id: 6, description: "EPICERIE METRO", amount: -50 };
|
||||
const SPLIT_OFFSET = { id: 7, description: "EPICERIE METRO", amount: 50 };
|
||||
/** The category the parent is moved to. */
|
||||
|
|
@ -100,7 +109,12 @@ const C = 9;
|
|||
/** A transaction that is not split, as the offset propagation reads it. */
|
||||
const PLAIN = { id: 5, description: "LOYER", amount: -900, is_split: 0, parent_transaction_id: null };
|
||||
|
||||
/** The UPDATE of the recategorized transaction itself, found by its SQL: a BEGIN comes first since #454. */
|
||||
/**
|
||||
* The UPDATE of the recategorized transaction itself, found by its SQL: a BEGIN
|
||||
* comes first since #454. The offset line's UPDATE has the same SQL since it
|
||||
* takes its parent's manual flag: on a split parent, tell them apart by their
|
||||
* target (`targetOf`).
|
||||
*/
|
||||
const ownUpdates = () =>
|
||||
writes().filter((w) => w.sql.startsWith("UPDATE transactions SET category_id = $1, is_manually_categorized = $2"));
|
||||
|
||||
|
|
@ -196,8 +210,8 @@ describe("updateTransactionCategory — a split's offset line follows its parent
|
|||
const offsetMove = sent.findIndex(
|
||||
(w) => w.sql.startsWith("UPDATE transactions SET category_id = $1,") && targetOf(w) === SPLIT_OFFSET.id,
|
||||
);
|
||||
// The offset follows the parent to C…
|
||||
expect(sent[offsetMove]?.params).toEqual([C, SPLIT_OFFSET.id]);
|
||||
// The offset follows the parent to C, with its manual flag…
|
||||
expect(sent[offsetMove]?.params).toEqual([C, 1, SPLIT_OFFSET.id]);
|
||||
// …the entry keeps its own category…
|
||||
expect(sent.filter((w) => targetOf(w) === SPLIT_ENTRY.id)).toEqual([]);
|
||||
// …and both moves sit between one BEGIN and its COMMIT.
|
||||
|
|
@ -211,6 +225,26 @@ describe("updateTransactionCategory — a split's offset line follows its parent
|
|||
expect(offsetMove).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// `autoCategorizeTransactions` picks every row without a category and with
|
||||
// the manual flag 0, children included: the offset line takes the flag its
|
||||
// parent has just been given, read after the parent's UPDATE (review of PR
|
||||
// #515).
|
||||
it("reads the parent after its own UPDATE, and gives the offset line the flag it has just been given", async () => {
|
||||
answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
|
||||
await updateTransactionCategory(SPLIT_PARENT.id, null, true);
|
||||
|
||||
const sent = statements();
|
||||
const parentMove = sent.findIndex((s) => s.sql.startsWith("UPDATE ") && targetOf(s) === SPLIT_PARENT.id);
|
||||
const parentRead = sent.findIndex((s) => /^SELECT .*\bis_manually_categorized\b.* WHERE id = \$1$/.test(s.sql));
|
||||
const offsetMove = sent.findIndex((s) => s.sql.startsWith("UPDATE ") && targetOf(s) === SPLIT_OFFSET.id);
|
||||
expect(sent[parentMove]?.params).toEqual([null, 1, SPLIT_PARENT.id]);
|
||||
expect(parentRead).toBeGreaterThan(parentMove);
|
||||
expect(offsetMove).toBeGreaterThan(parentRead);
|
||||
expect(sent[offsetMove]?.params).toEqual([null, 1, SPLIT_OFFSET.id]);
|
||||
});
|
||||
|
||||
it("moves nothing else for a transaction that is not split", async () => {
|
||||
answerSplitReads(PLAIN, []);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
|
|
@ -225,7 +259,7 @@ describe("updateTransactionCategory — a split's offset line follows its parent
|
|||
it("rolls back, rethrows and does not notify when the offset cannot be moved", async () => {
|
||||
answerSplitReads(SPLIT_PARENT, [SPLIT_ENTRY, SPLIT_OFFSET]);
|
||||
mockExecute.mockImplementation(async (sql: string, params?: unknown[]) => {
|
||||
if (String(sql).startsWith("UPDATE transactions SET category_id = $1, updated_at") && params?.[1] === SPLIT_OFFSET.id) {
|
||||
if (String(sql).startsWith("UPDATE transactions SET category_id = $1,") && targetOf({ params: params ?? [] }) === SPLIT_OFFSET.id) {
|
||||
throw new Error("disk full");
|
||||
}
|
||||
return { rowsAffected: 1 };
|
||||
|
|
@ -295,16 +329,21 @@ const statements = (): Statement[] =>
|
|||
|
||||
const TRANSACTION_CONTROL = ["BEGIN", "COMMIT", "ROLLBACK"];
|
||||
|
||||
// The statements of a split, as `main` writes them before #513.
|
||||
// The statements of a split, as `main` writes them before #513, but the
|
||||
// offset line's INSERT: since the review of #454, it also writes the parent's
|
||||
// manual flag (`INSERT_OFFSET`).
|
||||
const READ_PARENT = "SELECT * FROM transactions WHERE id = $1";
|
||||
const DELETE_CHILDREN = "DELETE FROM transactions WHERE parent_transaction_id = $1";
|
||||
const INSERT_CHILD =
|
||||
"INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1)";
|
||||
const INSERT_OFFSET =
|
||||
"INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split, is_manually_categorized) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)";
|
||||
const MARK_SPLIT = "UPDATE transactions SET is_split = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1";
|
||||
const UNMARK_SPLIT = "UPDATE transactions SET is_split = 0, updated_at = CURRENT_TIMESTAMP WHERE id = $1";
|
||||
|
||||
// A transaction of −120 in category 3, split from the Transactions page: −50 to
|
||||
// category 8 with the parent's description, −20 to category 11 with its own.
|
||||
// A transaction of −120 put in category 3 by hand, split from the Transactions
|
||||
// page: −50 to category 8 with the parent's description, −20 to category 11
|
||||
// with its own.
|
||||
const SAVED_PARENT = {
|
||||
id: 5,
|
||||
date: "2026-10-01",
|
||||
|
|
@ -314,6 +353,7 @@ const SAVED_PARENT = {
|
|||
source_id: 2,
|
||||
file_id: 4,
|
||||
original_description: "EPICERIE METRO 0042",
|
||||
is_manually_categorized: 1,
|
||||
is_split: 0,
|
||||
parent_transaction_id: null,
|
||||
};
|
||||
|
|
@ -326,8 +366,8 @@ const SAVED_WRITES = [
|
|||
{ sql: DELETE_CHILDREN, params: [5] },
|
||||
{ sql: INSERT_CHILD, params: ["2026-10-01", "EPICERIE METRO", -50, 8, 2, 4, "EPICERIE METRO 0042", 5] },
|
||||
{ sql: INSERT_CHILD, params: ["2026-10-01", "PHARMACIE", -20, 11, 2, 4, "EPICERIE METRO 0042", 5] },
|
||||
// The offset line: the parent's description and category, minus the entries' total.
|
||||
{ sql: INSERT_CHILD, params: ["2026-10-01", "EPICERIE METRO", 70, 3, 2, 4, "EPICERIE METRO 0042", 5] },
|
||||
// The offset line: the parent's description, category and manual flag, minus the entries' total.
|
||||
{ sql: INSERT_OFFSET, params: ["2026-10-01", "EPICERIE METRO", 70, 3, 2, 4, "EPICERIE METRO 0042", 5, 1] },
|
||||
{ sql: MARK_SPLIT, params: [5] },
|
||||
];
|
||||
|
||||
|
|
@ -379,7 +419,7 @@ describe("a split is saved or deleted in one transaction (#513)", () => {
|
|||
}
|
||||
|
||||
describe("saveSplitAdjustment", () => {
|
||||
it("writes the same statements, with the same values, as before #513", async () => {
|
||||
it("writes the same statements, with the same values, as before #513, but the offset line's manual flag (#454)", async () => {
|
||||
answerSplitReads(SAVED_PARENT, []);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
await saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES);
|
||||
|
|
@ -393,12 +433,31 @@ describe("a split is saved or deleted in one transaction (#513)", () => {
|
|||
);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
await saveSplitAdjustment(SAVED_PARENT.id, [SAVED_ENTRIES[0]]);
|
||||
expect(writes().filter((w) => w.sql === INSERT_CHILD).map((w) => w.params)).toEqual([
|
||||
expect(writes().filter((w) => w.sql === INSERT_CHILD || w.sql === INSERT_OFFSET).map((w) => w.params)).toEqual([
|
||||
["2026-10-01", "EPICERIE METRO", -50, 8, null, null, "", 5],
|
||||
["2026-10-01", "EPICERIE METRO", 50, null, null, null, "", 5],
|
||||
["2026-10-01", "EPICERIE METRO", 50, null, null, null, "", 5, 1],
|
||||
]);
|
||||
});
|
||||
|
||||
// `autoCategorizeTransactions` picks every row without a category and with
|
||||
// the manual flag 0, children included: an offset line written at 0 under a
|
||||
// parent categorized (or set to no category) by hand would be categorized
|
||||
// alone once its parent has no category (review of PR #515).
|
||||
it.each<[string, unknown, 0 | 1]>([
|
||||
["the flag 1", 1, 1],
|
||||
["the flag 0", 0, 0],
|
||||
["the TEXT 'true' of a base written before #390, as 1", "true", 1],
|
||||
])("gives the offset line its parent's manual flag, %s, bound as an integer, and leaves the entries' alone (#454)", async (_label, flag, bound) => {
|
||||
answerSplitReads({ ...SAVED_PARENT, is_manually_categorized: flag }, []);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
await saveSplitAdjustment(SAVED_PARENT.id, SAVED_ENTRIES);
|
||||
const offset = writes().filter((w) => w.sql === INSERT_OFFSET);
|
||||
expect(offset.map((w) => w.params[8])).toEqual([bound]);
|
||||
expect(typeof offset[0].params[8]).toBe("number");
|
||||
// The entries keep the column's default, 0: out of the scope of #454.
|
||||
expect(writes().filter((w) => w.sql === INSERT_CHILD)).toHaveLength(SAVED_ENTRIES.length);
|
||||
});
|
||||
|
||||
it("reads the parent first, writes between one BEGIN and its COMMIT, then notifies once, lock released", async () => {
|
||||
answerSplitReads(SAVED_PARENT, []);
|
||||
mockExecute.mockResolvedValue({ rowsAffected: 1 });
|
||||
|
|
@ -429,7 +488,7 @@ describe("a split is saved or deleted in one transaction (#513)", () => {
|
|||
it.each<[string, (w: Statement) => boolean]>([
|
||||
["the DELETE of the former children", (w) => w.sql === DELETE_CHILDREN],
|
||||
["the INSERT of an entry", (w) => w.sql === INSERT_CHILD && w.params[2] === -20],
|
||||
["the INSERT of the offset line", (w) => w.sql === INSERT_CHILD && w.params[2] === 70],
|
||||
["the INSERT of the offset line", (w) => w.sql === INSERT_OFFSET],
|
||||
["the UPDATE of the split flag", (w) => w.sql === MARK_SPLIT],
|
||||
])("rolls back right after %s fails, rethrows and does not notify", async (_label, failing) => {
|
||||
answerSplitReads(SAVED_PARENT, []);
|
||||
|
|
|
|||
|
|
@ -439,7 +439,9 @@ export async function getSplitChildren(parentId: number): Promise<SplitChild[]>
|
|||
* cancels in the parent's category the part sent to the other categories, then
|
||||
* the parent's split flag. One transaction (#513): an error on any statement
|
||||
* rolls the whole split back, and a parent that cannot be found throws before
|
||||
* any write.
|
||||
* any write. The offset line takes the parent's category and its manual flag
|
||||
* (#454), as `propagateCategoryToOffsets` gives them when the parent changes
|
||||
* category; the entries keep the flag's default, 0.
|
||||
*/
|
||||
export async function saveSplitAdjustment(
|
||||
parentId: number,
|
||||
|
|
@ -497,10 +499,18 @@ async function saveSplitAdjustmentInTransaction(
|
|||
offsetTotal += entry.amount;
|
||||
}
|
||||
|
||||
// Insert offset child (cancels the redistributed portion from the original category)
|
||||
// Insert offset child (cancels the redistributed portion from the original
|
||||
// category). It also takes the parent's manual flag (#454):
|
||||
// `autoCategorizeTransactions` picks every row without a category and with
|
||||
// the flag 0, children included. Left at 0 under a parent categorized by
|
||||
// hand, it would be categorized alone, without its parent, as soon as both
|
||||
// have no category: the parent set to « Aucune catégorie » by hand, or the
|
||||
// categories reset (`reinitializeCategories`). Never the flag as read: a
|
||||
// base written before #390 may hold the TEXT 'true', which
|
||||
// `is_manually_categorized = 1` never matches.
|
||||
await db.execute(
|
||||
`INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1)`,
|
||||
`INSERT INTO transactions (date, description, amount, category_id, source_id, file_id, original_description, parent_transaction_id, is_split, is_manually_categorized)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)`,
|
||||
[
|
||||
parent.date,
|
||||
parent.description,
|
||||
|
|
@ -510,6 +520,7 @@ async function saveSplitAdjustmentInTransaction(
|
|||
parent.file_id ?? null,
|
||||
parent.original_description ?? "",
|
||||
parentId,
|
||||
toSqlFlag(parent.is_manually_categorized),
|
||||
]
|
||||
);
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue