The "actual vs actual" compare was expenses-only (WHERE amount < 0), so revenue
categories were invisible — you could not tell a surplus from a deficit. Make it
an income statement (the product's namesake "résultat"):
- COMPARE_DELTA_SQL: broaden the WHERE and per-type CASE to include `income` as
a signed SUM (like `transfer`), so revenue credits survive the outflow filter.
Expenses stay ABS-of-outflows, byte-identical. Transfer netting (#243) intact.
- Section order is now income -> expense -> transfer (COMPARE_TYPE_ORDER).
- ComparePeriodTable: replace the now-meaningless flat grand total with two
result lines — "result before transfers" (revenues - expenses) and the net
"result" (after transfers) — extracted into a pure, tested compareResults
module. Delta colours are direction-aware (income/result up = green, spending
up = red); result amounts are coloured by sign (surplus/deficit).
- ComparePeriodChart stays a spending view: filter to expense leaves so revenue
bars don't mix into the same axis.
- useCompare: skip the initial period-sync so the compare opens on the previous
(last complete) month instead of the civil-year December that useReportsPeriod
yields by default.
Also anchor the `reports/` gitignore to `/reports/` — the unanchored rule was
silently ignoring new files under src/components/reports/.
Tests: new compareResults.test.ts (result roll-up, unbalanced transfer, deficit,
subtotal exclusion); reportService.test.ts updated for the broadened SQL, the
income bucket rule, and income-first section order. Build + 685 vitest green.
Resolves#253
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Address the two non-blocking review notes on PR #252:
- The re-injected non-leaf parent (e.g. #1710) is technically clickable, not
'never offered'; correct the MappingRow comment to state selecting it is a
no-op (only leaves resolve).
- Extract the per-row option-building glue into a pure, unit-tested helper
comboboxCategoriesForTarget (4 cases: null/leaf pass-through by reference,
non-leaf append, unresolvable stale id).
The v1 target combobox in the migration preview now offers only leaf
categories (the inputable end-categories), not intermediate parents, so a
transaction is never mapped to a grouping bucket. Leaves render as a flat,
un-indented list in taxonomy order.
A low-confidence default can still point a v2 category at a non-leaf parent
(e.g. 'Divertissement' #1710); MappingRow re-injects that current target for
its single row via findTaxonomyCategory so the input stays populated, while
new picks remain leaves-only. Adds a findTaxonomyCategory pure helper + tests
(adapter now returns 112 leaves, not the 150-node full tree).
Make the v1 target editable on EVERY row of the categories-migration
preview (StepSimulate), not only the "needs review" ones. Each row now
renders a reused CategoryCombobox (accent-insensitive type-ahead,
keyboard, hierarchical) in place of the read-only text / flat <select>.
A pure adapter (taxonomyToComboboxCategories) flattens the full v1
taxonomy into Category-shaped rows once in StepSimulate and passes it as
a prop to the rows. The full tree (not just leaves) is fed so mid-tree
default targets such as "Divertissement" (id 1710, the default for
"Jeux, Films & Livres") both display and can be re-picked. The target
cell stops click/keydown propagation so picker interaction never toggles
the row preview. Reducer/guard behavior unchanged: resolving a "none"
row still bumps confidence to medium, and the unresolved-count guard
stays functional.
Resolves#246
A detailed (by-security) account can now import its positions from a CSV
instead of adding each security one by one. An "Import CSV" button next to
"Add a title" opens a native picker; the delimiter, encoding and columns
(symbol, quantity, optional price + book_cost) are auto-detected via new
csvAutoDetect helpers and adjustable in a small mapping editor. Rows sharing
a symbol are merged (SUM qty + book_cost, first price) and the batch is merged
into the basket by normalized symbol, so no UNIQUE(snapshot_line_id,
security_id) violation can occur at save. A CSV without a price column imports
quantities with an empty unit_price (fetch/type later) — the existing atomic
save path is unchanged (no SQL/Rust change).
- csvAutoDetect: autoDetectHoldingColumns + analyzeHoldingsCsv (+ tests)
- useSnapshotEditor: holdingsFromCsvRows + IMPORT_HOLDINGS action + importHoldings (+ tests)
- HoldingsCsvImportModal: file pick -> parse -> mapping editor + preview
- i18n FR/EN under balance.snapshot.detailed.importCsv.*
- CHANGELOG (Added / Ajouté)
Resolves#245
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Decouple the /balance empty-state guard into three explicit states via a
new pure helper `deriveLandingState` (empty / accounts-no-snapshot /
populated). Having accounts but no snapshot no longer strands the user on a
snapshot-only onboarding card: each state now renders navigation tiles
(HubReportNavCard, modeled on the Reports hub), and "Manage accounts"
(/balance/accounts) is reachable in every state, including the populated
dashboard.
- Remove BalanceOnboardingCard (component + test) and the dead
balance.onboarding.* i18n keys; add balanceLanding.ts + test.
- Add balance.hub.* and balance.landing.* keys in FR and EN.
- CHANGELOG (EN + FR) under [Unreleased].
Resolves#244
Render the real-vs-real comparable report as a parent/child category tree
with subtotal rows, mirroring the budget report — rows grouped into
expense/income/transfer sections with per-section and grand totals and a
subtotals-on-top/bottom toggle. The compare service now builds the tree on
top of the flat per-category deltas, so leaf-category figures are unchanged
and the #243 transfer netting is preserved (a balanced transfer group
subtotals to ~0, i.e. the group's net).
- reportService: buildCompareTree() synthesizes subtotal rows from the flat
leaves + category metadata; getCompareMonthOverMonth/YoY return the tree
(COMPARE_DELTA_SQL and rowsToDeltas untouched).
- CategoryDelta gains optional parent_id/is_parent/depth/category_type.
- ComparePeriodTable: sections, depth indentation, reorderRows toggle,
section/grand net totals.
- Cartes top-movers and ComparePeriodChart filter to leaf rows only.
- reorderRows constraint loosened to the two fields it reads.
- i18n (FR+EN) section labels; CHANGELOG entries.
Resolves#247
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Reports > Compare (real vs real) summed only outflows (SUM(ABS(amount))
filtered on amount < 0), so a `transfer` category like "Paiement CC" -
whose debit and matching credit should cancel - always showed the sum of
its debits instead of ~0.
Net transfer-type categories via a signed SUM(t.amount) while keeping the
expense behavior (ABS + amount < 0) for every other type, and broaden the
WHERE so transfer credits survive the expense filter. Both MoM and YoY now
share a single COMPARE_DELTA_SQL constant so they stay in sync. Real-vs-
budget already nets (signed SUM, no filter) and is unchanged.
Resolves#243
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@babel/core@7.29.0 (pulled transitively by @vitejs/plugin-react, build-only)
was flagged by GHSA-4x5r-pxfx-6jf8 (arbitrary file read via sourceMappingURL,
low, CVSS 3.2). npm audit fix cannot resolve it — the version is pinned by the
parent — so a scoped overrides entry forces the patched 7.29.7 within the
parent's accepted 7.x range (non-breaking). npm audit now reports 0.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
vite@6.4.2: server.fs.deny bypass (GHSA-fx2h-pf6j-xcff, high) + NTLMv2 hash
disclosure (GHSA-v6wh-96g9-6wx3, moderate) -- Windows-only, dev server.
vitest@4.0.18: UI server arbitrary file read/exec (GHSA-5xrq-8626-4rwp,
critical) -- only when 'vitest --ui' is listening. Both dev-only. Bumped
within 6.x/4.x (no major). 635 tests pass, build green.
npm audit: 3 -> 1 (only @babel/core low remains; left out deliberately --
audit fix adds 77 packages without resolving it, needs a scoped override
in a separate change).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
react-router-dom@7.13.0 pulled react-router@7.13.0, affected by 7 advisories
(turbo-stream RCE, DoS __manifest/single-fetch, XSS RSC redirect), corrected
in <7.15.1. Bumping the parent to 7.18.1 pulls react-router@7.18.1 and clears
both npm audit entries. react-router-dom carries no advisory of its own (#238
inherited transitively from #235). Build (tsc + vite) green; no major bump.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Database lock (the reported 0.10.0 regression):
- tauri-plugin-sql loads SQLite through a default multi-connection sqlx pool
(Pool::connect => max_connections = 10) and exposes no JS transaction
primitive. BEGIN and COMMIT issued as separate db.execute calls could land on
different pooled connections, stranding an open write transaction on an idle
connection — a permanent write lock until app restart. Triggered when the
Bilan page's concurrent reads interleaved with an in-flight snapshot save.
- Fix: funnel every db operation through one FIFO lock in db.ts; withTransaction
holds it across the whole BEGIN..COMMIT so a transaction's statements never
span connections (and the saves become genuinely atomic). A reentrancy guard
lets nested getDb() calls run directly instead of deadlocking. Applied to all
5 transaction sites (saveSnapshotAtomic, upsertSnapshotLines,
proposeStarterAccounts, applyKeywordWithReassignment, applyMigration) via
in-place helper extraction. New db.test.ts covers serialization,
cross-transaction non-interleaving, reentrancy, and lock release on error.
Log console (Settings -> Systems -> Journaux):
- getLogs returned the same mutated array reference, so useSyncExternalStore
(identity comparison) never re-rendered on a new log -> the console never
updated live. getLogs now returns an immutable snapshot rebuilt on each
mutation (stable between mutations, new identity after each).
- Add logInfo/logWarn/logError app-logging API and instrument the snapshot save
(info on success, error on failure) so DB issues surface in the console.
tsc + 635 vitest + vite build green.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The v16 belt-and-suspenders abort guard keyed on `a.symbol IS NOT NULL`
instead of convertibility. A simple-category account carrying a residual
symbol (left by a priced→simple recategorization; AccountForm renders the
symbol field unconditionally) has quantity-NULL lines by construction;
they satisfied the over-broad predicate, so the guard inserted 0, the
CHECK(ok = 1) failed, and the whole v16 migration aborted — the app no
longer started for that profile.
JOIN balance_categories and require `c.asset_type IS NOT NULL` in the guard
subquery, in all three copies (Migration v16, V16_SQL mirror, and the
V16_CORRUPT injected-failure test, kept statement-equivalent). Add a
regression test seeding a simple account with a residual symbol plus a
quantity-NULL line: v16 now applies without abort and leaves the account
intact (not converted, no security/holding, qty/value preserved).
Modifying v16 in place is safe: it has never shipped in a tagged release
(v0.9.1 stopped at v13; v14-v16 are unreleased), so no persisted profile
carries its checksum yet.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Cross-cutting Étape 2 coverage proving the per-security detail feature does not
regress aggregations, returns, date-move, or deletion.
Rust (lib.rs, +3 real-SQLite tests):
- regression_detailed_account_totals_equal_simple_account_totals: a detailed
account whose holdings sum to V yields byte-identical date/category/vehicle
SUM() totals to a simple account worth V (frozen golden numbers 1300/300/...).
Proven where SUM() GROUP BY actually runs, unlike the TS mock harness.
- migration_v14_to_v16_on_populated_db_preserves_integrity_and_totals: realistic
multi-type DB (simple + convertible priced w/ 2-snapshot history + non-
convertible priced) — totals byte-identical before/after v16, values
preserved, qty/price NULLed only on converted lines, one shared security,
non-convertible line fully intact.
- regression_snapshot_delete_cascades_to_holdings: two-hop CASCADE
(snapshot -> line -> holdings); security survives (RESTRICT).
TS (balance-flow.test.ts, +6 integration tests):
- detailed snapshot save end-to-end (aggregated line + securities + holdings in
one BEGIN/COMMIT); aggregated line value = rounded-cent SUM(holdings).
- rollback on injected holding INSERT failure (no partial line/holdings).
- snapshot date-move with a detailed account: line + holdings move together;
collision rolls both back (#200).
- golden-value invariant: detailed line stores the same value a simple account
would, feeding getSnapshotTotalsByDate identically.
- deleteSnapshot emits exactly one parent DELETE (FK cascades the rest).
No production code changed — pure test PR. Builds on the v16 tests (#211) and
the detailed-save/securities unit tests (#212) without duplicating them.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds a light confirmation modal (DetailAccountWizard) that flips a simple
balance account to detailed entry mode: sets kind='detailed' and
detailed_since = today (local civil day, YYYY-MM-DD) via updateBalanceAccount.
Toggle-only — no title capture; per-security holdings are entered at the next
normal snapshot, where validateDetailedSnapshot requires them from the pivot on.
Entry point: a 'Détailler en titres' action in the per-row actions menu of
BalanceAccountsTable, shown only for kind==='simple' rows (replaces the disabled
'Détail / coming soon' placeholder). Past aggregated history stays frozen
read-only. The flip is one-way: the #212 service backstop rejects
detailed -> simple once holdings exist, and the UI exposes no inverse action.
Exports buildDetailToggleInput() as a pure helper for a focused unit test
(project has no jsdom harness). FR/EN i18n under balance.detailWizard.*; removed
the now-dead balance.overview.detailAction / detailComingSoon keys.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Surface unrealized (latent) gain on the existing balance surfaces, no new
visualization (decision 2026-06-04).
Service:
- AccountLatestSnapshot gains account `kind` + `latest_snapshot_line_id`, so
the table knows which rows are detailed and where their holdings live.
- getAccountLatentGainByLine(lineId) folds a line's holdings through the
existing computeUnrealizedGain (shares the book_cost=0 / NULL -> N/A guard).
- rollupLatentGain(accounts): pure aggregation by asset class, by envelope
(vehicle_type, 'none' bucket), and grand total; per-bucket % denominator is
the known book_cost only (null when none), mirroring the aggregate guard.
Hook (useBalanceOverview):
- Prefetches per-detailed-account latent gain in parallel (failures isolated),
exposes latentGainByAccount + latentGainRollup. Simple accounts skipped.
UI:
- BalanceAccountsTable: expandable detailed rows -> per-security value + latent
gain %; a latent-gain column (shown only when a detailed account has one);
a summary block aggregating latent gain by asset class / envelope.
- BalanceOverviewCard: total latent gain line (hidden without detailed accounts).
- N/A rendered (never divide-by-zero) when book_cost is NULL or 0; partial-%
flag when some positions lack a cost basis.
Native non-CAD currency display de-scoped this round (untestable while all
securities are CAD). Modified Dietz return columns (#204) unchanged.
i18n: balance.latentGain.* in FR + EN. Focused unit tests for
getAccountLatentGainByLine and rollupLatentGain (grouping, 'none' envelope,
null-% / unknown book_cost, empty).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Turn the detailed-account snapshot variant into the real per-title entry
surface (building on the minimal sub-rows from #213):
- New SecurityPicker (src/components/balance/SecurityPicker.tsx): an
autocomplete combobox over the existing balance_securities catalogue
(loaded via listSecurities()) with inline creation. Accepts any
normalized symbol (UPPER/TRIM) with NO live ticker validation — the
price fetch is best-effort and separate. On pick/create it emits a
SecurityPick {symbol, asset_type, name, isNew}; a stock/crypto toggle
lets the user set the asset class when creating a new symbol (default
'stock'). Built on the CategoryCombobox UI idiom (ARIA listbox,
keyboard nav, click-outside). Pure helpers filterSecurities /
decideCreateOption are exported and unit-tested (no jsdom harness).
- SnapshotLineRow detailed sub-rows: labeled columns
[title (SecurityPicker), quantity, price (+ existing PriceFetchControl),
value (qty x price, read-only), book_cost, live unrealized gain].
Account value = displayed SUM of positions. Simple accounts unchanged.
- useSnapshotEditor: new SET_HOLDING_SECURITY action + setHoldingSecurity
callback (atomically sets symbol + asset_type + name and drops the
stale fetched-price attribution since the symbol changed). The
securities catalogue is loaded in loadForDate and exposed as
state.securities, so it refreshes after a save that creates a security.
- i18n: extended balance.snapshot.detailed.* (col.*, picker.*, book cost,
unrealized gain) in FR + EN — no hardcoded UI text.
- CHANGELOG (EN + FR) under [Unreleased]: first user-visible surface of
the per-title detail chain (#210-#213 were schema/service/reducer).
Build (tsc + vite) green; npm test green (613 tests, +10 SecurityPicker).
Generated autonomously by /autopilot run of 2026-06-06
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Structural rewrite of useSnapshotEditor for N holdings per detailed account,
and switch ALL simple/detailed dispatch from category_kind to the account's
own kind. This is the state/plumbing layer; the full multi-security entry UI
(SecurityPicker, rich sub-rows) lands in #214. Simple accounts behave
identically.
Reducer state shape:
- values: Record<accountId, string> (simple accounts, scalar)
- holdings: Record<accountId, HoldingDraft[]> (detailed accounts, one per title)
HoldingDraft is a string-typed, editable mirror of SnapshotHoldingInput with a
stable client-side rowId for React keys. Actions: ADD_HOLDING / REMOVE_HOLDING /
SET_HOLDING_FIELD (plus existing SET_VALUE/PREFILL/RESET). The legacy priced
scalar path (SET_PRICED_FIELD / pricedValues) is removed: after migration v16
(#211) every former-priced account is kind='detailed' with one holding, so those
accounts flow through the holdings path.
Dispatch:
- LOADED hydrates detailed baskets via listHoldingsBySnapshotLine (edit) keeping
the saved price, or getHoldingsForLatestSnapshot (new) dropping the price
(qty-0 excluded server-side). Simple accounts keep the scalar value path.
- SnapshotLineRow / SnapshotEditor / AccountForm now gate on account.kind, not
category_kind. category.kind survives ONLY as the suggested seed default for a
NEW account in AccountForm.
Save: detailed accounts pass their holdings array into SnapshotLineInput.holdings
(presence marks the line detailed; value = rounded-cent SUM); simple accounts
pass a scalar value with no holdings. Blank holding rows are skipped; a partial
row throws a typed error before any DB mutation.
AccountForm: adds an entry-mode selector (defaulting to the category-mapped
kind). New accounts persist as 'simple' (CreateBalanceAccountInput carries no
kind, and the service is out of this issue's scope); converting a fresh account
to detailed + pivot date is #215. Editing locks the selector for an already-
detailed account (the detailed->simple downgrade is service-guarded).
Tests: 19 new reducer/helper unit tests (pure exports; the project has no
renderHook harness) covering ADD/REMOVE/SET_HOLDING_FIELD, LOADED-vs-PREFILL
hydration (price drop, book_cost), qty-0 already excluded upstream, the
build*Lines save builders, and the dispatch-on-account.kind regression
(detailed account under a 'simple' category).
Resolves#213.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Service layer for detailed (per-security) balance accounts:
- findOrCreateSecurity (UPSERT on normalized UPPER(TRIM) symbol, callable
in-txn via an executor), listSecurities, getSecurity, updateSecurity.
- saveSnapshotAtomic / upsertSnapshotLines: a detailed account (line carrying
a holdings array) writes its aggregated line (value = rounded-cent SUM,
qty/price NULL) AND its holdings in the SAME BEGIN/COMMIT; the line id is
captured, existing holdings DELETEd, each security find-or-created and each
holding INSERTed. A holding-insert failure rolls the whole save back. Simple
/ legacy-priced scalar path is unchanged. upsertSnapshotLines is now wrapped
in an explicit transaction for the same atomicity.
- validateDetailedSnapshot: detailed+holdings => line qty/price NULL and
value === rounded-cent SUM(holdings) compared EXACTLY (no float tolerance);
detailed without holdings => pre-pivot aggregated tolerated.
validateLineKindInvariants stays byte-for-byte for the scalar path.
- roundToCent helper; detailed path uses per-holding cent rounding then exact
comparison to avoid N-holding rounding accumulation (decision 2026-06-03).
- Service backstop in updateBalanceAccount: detailed->simple rejected with a
typed error (account_kind_detailed_has_holdings) when holdings exist; adds
kind/detailed_since to the account input + SELECT.
- getHoldingsForLatestSnapshot (prefill; excludes quantity-0 positions),
listHoldingsBySnapshotLine (drill-down).
- computeUnrealizedGain: per-holding and aggregated value - book_cost and %;
book_cost = 0 OR NULL => gain % null (no divide-by-zero); NULL book_cost
excluded from the aggregate and flagged.
Existing aggregators (getSnapshotTotalsBy*) and computeAccountReturn untouched.
Unit tests for every new function incl. casing dedup, N>=20 holdings rounding,
book_cost=0/NULL, detailed->simple guard, atomic save + rollback. Existing
upsertSnapshotLines/updateBalanceAccount tests updated for the BEGIN/COMMIT
wrapping and the kind/detailed_since columns.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
v16 is a purely additive, guarded, atomic data migration (Bilan détail par
titre, Étape 2). It converts each existing single-security priced account into
a detailed account holding exactly one position, with zero data loss.
1. Mints one shared balance_securities row per priced account symbol
(normalized UPPER(TRIM), deduped via ON CONFLICT(symbol) DO NOTHING on the
COLLATE NOCASE UNIQUE), ONLY for accounts whose category carries a real
asset_type — balance_securities.asset_type is NOT NULL, and a priced
account whose category has asset_type IS NULL has no valid routing.
2. Mirrors each existing priced line into one holding (qty/unit_price/value/
price_source/price_fetched_at copied; book_cost stays NULL — no
retroactive acquisition cost). UNIQUE(line, security) + ON CONFLICT DO
NOTHING makes a re-run a strict no-op.
3. Collapses the now-redundant per-line qty/unit_price to NULL ONLY where a
holding now exists (the security fix — a line that got no holding, i.e.
priced-without-asset_type, is never NULLed, so no silent data loss).
NULLing both columns together preserves the lines' (both NULL | both NOT
NULL) CHECK.
A trailing TEMP-table CHECK(ok = 1) asserts the invariant 'qty NULLed ⇒ has a
holding' and ABORTS on breach, rolling back the whole v16 transaction (sqlx
wraps each migration in a transaction). Priced accounts without asset_type or
without a symbol are left fully intact.
Integration tests (in-memory SQLite, apply v10→v16 via execute_batch, mirroring
the #210 migration-test style): convertible account gains a security + holding
with values/history preserved and its line qty NULLed; non-convertible priced
account untouched (qty intact, no holding); re-run idempotent; injected-failure
mid-v16 aborts on the guard and a transaction rollback restores the pre-v16
state (zero securities/holdings, quantity intact).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>