Compare commits
16
Commits
a1480af74d
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d787150f2d | ||
|
|
9cc3130b4f | ||
|
|
8aab21fe9e | ||
|
|
71e95917da | ||
|
|
83bb86bc93 | ||
|
|
0fd3c5c0dc | ||
|
|
16daa01647 | ||
|
|
b7e5bf26cc | ||
|
|
676065292e | ||
|
|
c569ae7dbf | ||
|
|
46cf578779 | ||
|
|
671cbb8ef3 | ||
|
|
1b3d7b22bb | ||
|
|
f9e829e6ba | ||
|
|
46e02d95cb | ||
|
|
77f4ea5655 |
+55
-15
@@ -13,7 +13,12 @@ from Accounts and confirm the reviewed mapping. The application starts empty
|
|||||||
except for expense/income fallback categories. Create your category tree, tags,
|
except for expense/income fallback categories. Create your category tree, tags,
|
||||||
and merchants in the UI. Enable a merchant's default rule explicitly only when
|
and merchants in the UI. Enable a merchant's default rule explicitly only when
|
||||||
its category/tags are reliable; leave it disabled for ambiguous merchants such
|
its category/tags are reliable; leave it disabled for ambiguous merchants such
|
||||||
as Amazon.
|
as Amazon. Category and tag pickers create in place: type an unknown name in
|
||||||
|
a category picker and choose "Create … in …" (a bare name lands under the
|
||||||
|
kind's root; "Parent / Name" targets that parent), or type a new tag next to
|
||||||
|
the tag checkboxes. Assignment pickers offer leaf categories only, matching
|
||||||
|
what the server accepts; a name that already exists is selected, never
|
||||||
|
duplicated.
|
||||||
|
|
||||||
Tests: go test ./...
|
Tests: go test ./...
|
||||||
The Go build embeds web/dist, so build React first. CGO and a C++ linker are
|
The Go build embeds web/dist, so build React first. CGO and a C++ linker are
|
||||||
@@ -147,8 +152,14 @@ this is not local AI and cannot promise that a remote provider honors policy.
|
|||||||
|
|
||||||
Each classification sends the transaction date, signed amount, currency,
|
Each classification sends the transaction date, signed amount, currency,
|
||||||
merchant and counterparty text, account institution/currency, the complete
|
merchant and counterparty text, account institution/currency, the complete
|
||||||
leaf-category registry for the transaction kind, all tags and all merchants
|
leaf-category registry for the transaction kind, all tags and all merchants.
|
||||||
with their real local IDs. Identifier-only redaction removes IBANs (with a
|
Names, paths, hints and aliases remain available, but registry IDs use short
|
||||||
|
request-local references (c1, m1, t1), including merchant usual categories and
|
||||||
|
history. History includes only categories offered for that transaction kind.
|
||||||
|
Responses are mapped back to canonical IDs and validated locally; canonical
|
||||||
|
IDs are not accepted as alternative response references. This keeps the full
|
||||||
|
registry without the long-ID schema overhead that providers can reject.
|
||||||
|
Identifier-only redaction removes IBANs (with a
|
||||||
directly attached BIC), labeled BIC/SWIFT references, UUIDs, URLs/emails,
|
directly attached BIC), labeled BIC/SWIFT references, UUIDs, URLs/emails,
|
||||||
labeled payment or customer references, card fragments, long digit-bearing
|
labeled payment or customer references, card fragments, long digit-bearing
|
||||||
tokens, the row's own IDs, account labels and configured private names. A
|
tokens, the row's own IDs, account labels and configured private names. A
|
||||||
@@ -161,7 +172,14 @@ response records high, medium or low confidence. Imports never auto-apply a
|
|||||||
low-confidence category: the row keeps the kind-specific unclassified
|
low-confidence category: the row keeps the kind-specific unclassified
|
||||||
category with merchant and confidence recorded. Analyse previews show the
|
category with merchant and confidence recorded. Analyse previews show the
|
||||||
low-confidence suggestion unselected for review. Transactions exposes a
|
low-confidence suggestion unselected for review. Transactions exposes a
|
||||||
Needs review filter for low-confidence or fallback rows.
|
Needs review filter for low-confidence or fallback rows, and a
|
||||||
|
classification filter over how each row was classified: manually, by AI,
|
||||||
|
by a merchant rule, by transfer matching, or not at all. A model-proposed
|
||||||
|
merchant name is dropped (the row keeps its validated category and tags)
|
||||||
|
when it is identifier-shaped, longer than 100 characters, or contains
|
||||||
|
control or format code points such as bidirectional overrides and
|
||||||
|
zero-width characters, which could visually spoof the review UI; proposed
|
||||||
|
taxonomy names are rejected under the same hidden-rune rule.
|
||||||
|
|
||||||
Categories and tags have editable hints. Categories -> Propose taxonomy sends
|
Categories and tags have editable hints. Categories -> Propose taxonomy sends
|
||||||
up to 300 grouped, redacted transaction samples, then shows proposed
|
up to 300 grouped, redacted transaction samples, then shows proposed
|
||||||
@@ -536,10 +554,13 @@ repeats daily. Nothing is committed when no quote changed.
|
|||||||
|
|
||||||
A holding's value is its share count times its quote, rounded half away from
|
A holding's value is its share count times its quote, rounded half away from
|
||||||
zero to money's four places. Positions is that value summed per account, wealth
|
zero to money's four places. Positions is that value summed per account, wealth
|
||||||
is cash plus positions, and result is value plus everything the position
|
is cash plus positions plus hand-valued assets, and result is value plus
|
||||||
returned less everything put into it - the outcome to date, realised and not.
|
everything the position returned less everything put into it - the outcome to
|
||||||
None of these figures are read from the DuckDB index: the report is recomputed
|
date, realised and not. A hand-valued asset (a house, a car, a private loan) is
|
||||||
from the journal so it can be checked against a broker's own screen.
|
entered on the Wealth page with a stated value, a currency and the day the
|
||||||
|
estimate was made; a negative value records a liability. None of these figures
|
||||||
|
are read from the DuckDB index: the report is recomputed from the journal so it
|
||||||
|
can be checked against a broker's own screen.
|
||||||
|
|
||||||
A broker reuses one reference across every leg of an economic event: the cash
|
A broker reuses one reference across every leg of an economic event: the cash
|
||||||
and position sides of a corporate action arrive with the same reference byte for
|
and position sides of a corporate action arrive with the same reference byte for
|
||||||
@@ -628,7 +649,20 @@ exists to be compared with the figures a bank or broker shows on its own screen.
|
|||||||
|
|
||||||
A cash balance equals the real balance only when the journal holds that
|
A cash balance equals the real balance only when the journal holds that
|
||||||
account's complete history. A broker export does; a date-windowed bank statement
|
account's complete history. A broker export does; a date-windowed bank statement
|
||||||
does not.
|
does not. A connected cash account closes that gap with a balance anchor: after
|
||||||
|
its first successful sync, the bank's booked (CLBD) balance is captured once,
|
||||||
|
verbatim, with the day it was true, and stored on the account (anchor_balance,
|
||||||
|
anchor_date in accounts.finance). The start balance - the money from before the
|
||||||
|
recorded rows - is derived as the anchor less every movement booked through the
|
||||||
|
anchor day, and reads as the first line of the account's flow breakdown. Because
|
||||||
|
the bank's figure is stored rather than the derivation, importing older history
|
||||||
|
later corrects the start balance by itself. An available or expected balance is
|
||||||
|
never anchored: it includes pending amounts with no booked fact to subtract. The
|
||||||
|
anchor is set once and never moved by later syncs; clear it in the account's
|
||||||
|
edit form and the next successful sync captures a fresh one. Running-balance
|
||||||
|
checks are only judged after the anchor day, where the balance is observable.
|
||||||
|
Anchors are refused on investment accounts, whose broker exports carry their
|
||||||
|
complete history.
|
||||||
|
|
||||||
Checks that fail mean the journal disagrees with itself: row arithmetic, cash
|
Checks that fail mean the journal disagrees with itself: row arithmetic, cash
|
||||||
never negative, holdings never negative. A negative holding means a position was
|
never negative, holdings never negative. A negative holding means a position was
|
||||||
@@ -652,6 +686,7 @@ finance/
|
|||||||
tags.finance
|
tags.finance
|
||||||
merchants.finance
|
merchants.finance
|
||||||
instruments.finance
|
instruments.finance
|
||||||
|
assets.finance
|
||||||
journal/YYYY/YYYY-MM.finance
|
journal/YYYY/YYYY-MM.finance
|
||||||
state/sync-state.json sensitive local consent/session metadata
|
state/sync-state.json sensitive local consent/session metadata
|
||||||
state/openrouter.json sensitive UI-managed OpenRouter key or explicit disable
|
state/openrouter.json sensitive UI-managed OpenRouter key or explicit disable
|
||||||
@@ -686,7 +721,9 @@ The grammar is version-one strict: extension/split fields are not accepted yet.
|
|||||||
Future format extensions require an explicit parser migration.
|
Future format extensions require an explicit parser migration.
|
||||||
|
|
||||||
Stable category IDs survive renaming and moving; assigned categories must remain
|
Stable category IDs survive renaming and moving; assigned categories must remain
|
||||||
leaves. Built-in roots and fallback leaves are protected. Move assigned records
|
leaves. Registry display names (category, tag, merchant, instrument) are
|
||||||
|
capped at 200 characters server-side, matching every UI form. Built-in roots
|
||||||
|
and fallback leaves are protected. Move assigned records
|
||||||
to another leaf before adding children to their former category. Category
|
to another leaf before adding children to their former category. Category
|
||||||
merges migrate referenced transactions/defaults; tag merges deduplicate links;
|
merges migrate referenced transactions/defaults; tag merges deduplicate links;
|
||||||
tag deletion removes all affected links after UI confirmation. Merchant merging
|
tag deletion removes all affected links after UI confirmation. Merchant merging
|
||||||
@@ -729,6 +766,8 @@ and revisited, and Stop abandons the run without writing anything. A run that
|
|||||||
has produced no successful proposal and fails three times in a row with the
|
has produced no successful proposal and fails three times in a row with the
|
||||||
same error stops early and reports that error instead of repeating it across
|
same error stops early and reports that error instead of repeating it across
|
||||||
the whole range. Only one run exists at a time.
|
the whole range. Only one run exists at a time.
|
||||||
|
Starting analysis reads the latest journal, independent of the page's revision.
|
||||||
|
The page refreshes registry labels before starting; analysis itself writes nothing.
|
||||||
History precedent sent with each request marks the user's own decisions
|
History precedent sent with each request marks the user's own decisions
|
||||||
(manual edits and merchant rules) as source user, ranks them ahead of the
|
(manual edits and merchant rules) as source user, ranks them ahead of the
|
||||||
model's earlier answers, and reserves window slots for them, so one manual
|
model's earlier answers, and reserves window slots for them, so one manual
|
||||||
@@ -736,11 +775,12 @@ correction outweighs repeated uncorrected AI output for the same payee.
|
|||||||
Manually linking a merchant also records the counterparty as an alias, so
|
Manually linking a merchant also records the counterparty as an alias, so
|
||||||
recurring payees classify locally without any provider request.
|
recurring payees classify locally without any provider request.
|
||||||
The finished run is a read-only preview. Apply all/selected writes all
|
The finished run is a read-only preview. Apply all/selected writes all
|
||||||
selected changes in one canonical commit; financial facts never change. A
|
selected changes in one canonical commit; financial facts never change. Apply
|
||||||
manual edit, external journal change or taxonomy change invalidates old previews.
|
checks selected transactions against the preview snapshot; unrelated journal
|
||||||
Previews are kept in memory for up to one hour and disappear on restart. Cancel
|
commits do not require another analysis.
|
||||||
writes nothing. Transfers and broker facts are skipped, and unselected fields
|
Previews are kept in memory for up to 24 hours from the start of analysis and
|
||||||
are preserved.
|
disappear on restart. Cancel writes nothing. Transfers and broker facts are
|
||||||
|
skipped, and unselected fields are preserved.
|
||||||
When a selected transaction is linked to a merchant, applying the preview and
|
When a selected transaction is linked to a merchant, applying the preview and
|
||||||
manual transaction edits may add its normalized counterparty as an alias if
|
manual transaction edits may add its normalized counterparty as an alias if
|
||||||
that alias is unambiguous and the merchant has fewer than 32 aliases. A new
|
that alias is unambiguous and the merchant has fewer than 32 aliases. A new
|
||||||
|
|||||||
@@ -144,6 +144,8 @@ Finance Duck verifies the callback state, exchanges the returned code for a `ses
|
|||||||
|
|
||||||
Initial synchronization requests the selected number of **calendar months of booked transactions per account**, defaulting to **12 months**. The bank may provide less history. The choice is saved with the bank connection and reused on reconnection. Automatic synchronization then runs **twice a day**, every **12 hours** after the last successful run, overlapping each account's last successful sync by **14 days**. **Sync now** starts a manual synchronization at any time. Existing accounts keep their successful-sync cursors: changing the history choice or reconnecting does **not** backfill them. Older history can be imported with CSV.
|
Initial synchronization requests the selected number of **calendar months of booked transactions per account**, defaulting to **12 months**. The bank may provide less history. The choice is saved with the bank connection and reused on reconnection. Automatic synchronization then runs **twice a day**, every **12 hours** after the last successful run, overlapping each account's last successful sync by **14 days**. **Sync now** starts a manual synchronization at any time. Existing accounts keep their successful-sync cursors: changing the history choice or reconnecting does **not** backfill them. Older history can be imported with CSV.
|
||||||
|
|
||||||
|
**The start balance is anchored, not guessed.** Open banking shares a date-windowed history, so the sum of the recorded rows alone is not the account's real balance — the money from before the window is missing. After a connected cash account's first successful sync, Finance Duck captures the bank's **booked balance** once, with the day it was true, and stores it on the account (`anchor_balance`, `anchor_date`). **Wealth** then derives the start balance — the anchor less every movement booked through the anchor day — shows it as the first line of the account's flow breakdown, and reports the real balance. Only the booked (CLBD) figure is used, never an available balance that includes pending amounts. The anchor is set once and never moved by a later sync; importing older history corrects the derived start balance by itself, and clearing the anchor in the account's edit form makes the next sync capture a fresh one.
|
||||||
|
|
||||||
**HTTP 429 is a provider rate limit, not evidence that bank consent has expired.** Bank reads honor `Retry-After` and use bounded exponential retries. A longer or exhausted limit pauses further requests until the reported retry time; failed accounts keep their previous sync cursors and imported data. Session checks use the saved account metadata rather than fetching every account's details again. A failed session is reported once instead of also marking each of its accounts unavailable. After the cooldown, **Sync now** can retry; the warning clears after a successful sync. One-time authorization and code-exchange requests are never automatically replayed.
|
**HTTP 429 is a provider rate limit, not evidence that bank consent has expired.** Bank reads honor `Retry-After` and use bounded exponential retries. A longer or exhausted limit pauses further requests until the reported retry time; failed accounts keep their previous sync cursors and imported data. Session checks use the saved account metadata rather than fetching every account's details again. A failed session is reported once instead of also marking each of its accounts unavailable. After the cooldown, **Sync now** can retry; the warning clears after a successful sync. One-time authorization and code-exchange requests are never automatically replayed.
|
||||||
|
|
||||||
**A rate-limited sync is a wait, not a fault.** While every failing bank has supplied a retry time, the dashboard reports that synchronization retries by itself after that moment, the account card shows a rate-limit badge instead of a connection error, and the background scheduler sleeps until the deadline rather than retrying hourly into a refusal it already knows about. **Sync now** still tries immediately. Any failure without a supplied deadline keeps the hourly retry, and its cause is named where Finance Duck can determine it locally: an expired consent, an HTTP status, an unreachable provider, or a response it cannot use, such as a booked transaction without a booking date. Provider response text is never displayed.
|
**A rate-limited sync is a wait, not a fault.** While every failing bank has supplied a retry time, the dashboard reports that synchronization retries by itself after that moment, the account card shows a rate-limit badge instead of a connection error, and the background scheduler sleeps until the deadline rather than retrying hourly into a refusal it already knows about. **Sync now** still tries immediately. Any failure without a supplied deadline keeps the hourly retry, and its cause is named where Finance Duck can determine it locally: an expired consent, an HTTP status, an unreachable provider, or a response it cannot use, such as a booked transaction without a booking date. Provider response text is never displayed.
|
||||||
@@ -220,6 +222,8 @@ One ISIN lists on several exchanges in different currencies, and the wrong listi
|
|||||||
|
|
||||||
**Verify it yourself.** **Wealth** shows each account's cash, its positions as exact share counts, each holding's quote, value and result, and named checks — row arithmetic, cash never negative, holdings never negative, holdings priced. Compare the cash balance and the positions against your broker's own screen. The figures come from the journal, not from the DuckDB index, so they do not depend on the cache that the same journal derives. A negative holding means the imported history is partial: a position was closed that was never opened.
|
**Verify it yourself.** **Wealth** shows each account's cash, its positions as exact share counts, each holding's quote, value and result, and named checks — row arithmetic, cash never negative, holdings never negative, holdings priced. Compare the cash balance and the positions against your broker's own screen. The figures come from the journal, not from the DuckDB index, so they do not depend on the cache that the same journal derives. A negative holding means the imported history is partial: a position was closed that was never opened.
|
||||||
|
|
||||||
|
**Other assets.** Possessions with no market feed — a house, a car, a private loan — are added by hand on the **Wealth** page with a stated value, a currency and the day the estimate was made, and they join the total immediately. A negative value records a liability such as a mortgage. Each asset is a plaintext block in `assets.finance` like every other registry entity, so a backup carries it and a text editor can correct it. The value is never guessed or aged: it stays what you stated, dated, until you re-edit it.
|
||||||
|
|
||||||
Deliberately **not** included: intraday prices, net worth over time, FIFO lot accounting, realised gains, `Vorabpauschale`, and currency conversion. A position's *invested* figure is cash in less cash out, not a cost basis, and *result* is value plus everything returned less everything put in — the outcome to date, not a taxable gain.
|
Deliberately **not** included: intraday prices, net worth over time, FIFO lot accounting, realised gains, `Vorabpauschale`, and currency conversion. A position's *invested* figure is cash in less cash out, not a cost basis, and *result* is value plus everything returned less everything put in — the outcome to date, not a taxable gain.
|
||||||
|
|
||||||
## Deployment options
|
## Deployment options
|
||||||
@@ -421,7 +425,9 @@ Bank synchronization and recognized N26, ING, and Kontist CSV imports do **not**
|
|||||||
|
|
||||||
**Classify newly imported transactions with AI** under **Classification preferences** controls whether importing contacts the provider at all. It covers CSV imports and bank synchronization, is on by default, and is stored as `classify_on_import` in `config.toml`. With it off, no import makes a provider request: enabled merchant rules still classify, and everything else arrives unclassified and editable without a failure that would suggest the provider was unreachable. **AI classification → Analyse** still works on demand, so you can review a batch deliberately instead of on every import.
|
**Classify newly imported transactions with AI** under **Classification preferences** controls whether importing contacts the provider at all. It covers CSV imports and bank synchronization, is on by default, and is stored as `classify_on_import` in `config.toml`. With it off, no import makes a provider request: enabled merchant rules still classify, and everything else arrives unclassified and editable without a failure that would suggest the provider was unreachable. **AI classification → Analyse** still works on demand, so you can review a batch deliberately instead of on every import.
|
||||||
|
|
||||||
AI classification sends only identifier-redacted text: the transaction's own IDs, account identifiers and labels, payment references, labeled or IBAN-attached BICs, and configured private names are removed, while merchant and counterparty text remains available for recognition. Classification responses carry `high`, `medium`, or `low` confidence. Imports never auto-apply a low-confidence category — the row stays on the kind-appropriate unclassified category with the merchant link and confidence recorded — while **Analyse** previews show the low-confidence suggestion unselected for review, and **Transactions → Needs review** lists both.
|
AI classification sends only identifier-redacted text: the transaction's own IDs, account identifiers and labels, payment references, labeled or IBAN-attached BICs, and configured private names are removed, while merchant and counterparty text remains available for recognition. Classification responses carry `high`, `medium`, or `low` confidence. Imports never auto-apply a low-confidence category — the row stays on the kind-appropriate unclassified category with the merchant link and confidence recorded — while **Analyse** previews show the low-confidence suggestion unselected for review, and **Transactions → Needs review** lists both. Transactions also filters by classification status — manual, AI, merchant rule, transfer match, or unclassified — matching the labels its Source column shows.
|
||||||
|
|
||||||
|
Classification choices retain their names, paths, hints, and aliases, but use short request-local references such as `c1`, `m1`, and `t1` instead of long database IDs. Merchant defaults and applicable classification history use the same references. Every eligible category, merchant, and tag remains available; responses are mapped back to canonical IDs and validated locally.
|
||||||
|
|
||||||
From **Categories**, **Propose taxonomy** samples up to 300 redacted transactions, grouped so recurring counterparties are represented without sending raw identifiers. The proposal can suggest categories, tags, and merchants with hints and evidence. Approve each item individually; applying it also creates any approved category parents required by the hierarchy. Existing registry entries and transaction facts are never overwritten.
|
From **Categories**, **Propose taxonomy** samples up to 300 redacted transactions, grouped so recurring counterparties are represented without sending raw identifiers. The proposal can suggest categories, tags, and merchants with hints and evidence. Approve each item individually; applying it also creates any approved category parents required by the hierarchy. Existing registry entries and transaction facts are never overwritten.
|
||||||
|
|
||||||
@@ -435,6 +441,36 @@ The classifier learns from you in three ways. Manually linking a merchant record
|
|||||||
|
|
||||||
**AI classification → Analyse** runs in the background: the page shows how many transactions have been analysed, proposed changes, and every per-transaction failure as it happens, with a **Stop** button that abandons the run without writing anything. You can navigate away and return; the run keeps building and the page re-attaches to it. A run that has produced no successful result and fails **three times in a row with the same error** stops early and reports that error — a wrong key or an unsupported model surfaces within seconds instead of repeating across the whole range.
|
**AI classification → Analyse** runs in the background: the page shows how many transactions have been analysed, proposed changes, and every per-transaction failure as it happens, with a **Stop** button that abandons the run without writing anything. You can navigate away and return; the run keeps building and the page re-attaches to it. A run that has produced no successful result and fails **three times in a row with the same error** stops early and reports that error — a wrong key or an unsupported model surfaces within seconds instead of repeating across the whole range.
|
||||||
|
|
||||||
|
Wherever a category or tag is assigned — the transaction editor, an **Analyse** correction, or a merchant's defaults — the picker creates missing entries in place. Type a name and choose **Create "…" in …**: a bare name lands under the kind's root, and **Parent / Name** creates under that parent. New tags are typed next to the tag checkboxes. Assignment pickers offer leaf categories only, matching what the server accepts, and an existing name is selected rather than duplicated. Creating during an **Analyse** review keeps the preview applicable as long as the transactions themselves are unchanged.
|
||||||
|
|
||||||
|
## Filter by tags
|
||||||
|
|
||||||
|
**Overview** and **Transactions** share **Include tags** and **Exclude tags** pickers. Search for a tag and select it to add a removable pill; both pickers accept multiple tags.
|
||||||
|
|
||||||
|
- **Include tags** matches transactions carrying **any** selected tag. Leave it empty to include tagged and untagged transactions.
|
||||||
|
- **Exclude tags** hides transactions carrying **any** selected tag, including transactions that also carry an included tag.
|
||||||
|
- Both lists combine with the date, currency, account, category, and merchant filters. Adding a tag to one picker removes it from the other.
|
||||||
|
- Tag selections are remembered in this browser across visits. Remove an individual pill to clear it, or use **Reset** to clear all filters and restore the default six-month period.
|
||||||
|
|
||||||
|
For private spending, leave **Include tags** empty and add `business` to **Exclude tags**. Business-tagged expenses, including any taxes you tag that way, leave the overview's totals, charts, comparisons, and the transaction list. Untagged income remains included: net cash flow and income-based figures describe the filtered transactions, not your actual savings. Wealth and account balances remain unfiltered.
|
||||||
|
|
||||||
|
The dashboard API accepts repeated `tag_ids` and `exclude_tag_ids` query parameters, for example `?tag_ids=tag_holiday&tag_ids=tag_shared&exclude_tag_ids=tag_business`. Values are literal tag IDs, not comma-separated lists.
|
||||||
|
|
||||||
|
## Bulk edit transactions
|
||||||
|
|
||||||
|
In **Transactions**, choose **Bulk edit**, then select individual rows, the current page, or **Select all N matching** to include every currently filtered result across pages. Selection follows you across pages; changing a filter, search, review toggle, or classification status clears it. **Clear selection** unchecks the rows; **Cancel bulk edit** leaves selection mode.
|
||||||
|
|
||||||
|
**Edit selected** opens a change editor. Only explicitly chosen operations are applied:
|
||||||
|
|
||||||
|
- **Category** and **Merchant** start at **Leave unchanged**. A tag-only edit preserves each selected transaction's individual category and merchant, even when they differ.
|
||||||
|
- **Add tags** adds only the chosen tags, retaining existing ones. **Remove tags** removes only the chosen tags. Adding a tag already present or removing a known tag absent from a row does not disturb its other tags.
|
||||||
|
- Category changes require only expenses or only income and a compatible leaf category. Merchant changes allow expenses and income together, with a separate **Clear merchant** choice.
|
||||||
|
- Selections containing transfers or investments can change tags, but not category or merchant. Bank facts, transaction kinds, and transfer links are never edited.
|
||||||
|
|
||||||
|
Review the operation summary and selected count before applying. The entire batch is saved in one journal commit and marked manually classified. An invalid edit or revision conflict saves nothing and keeps the editor's choices; cancel and refresh the journal before retrying a revision conflict. Successful saves clear the selection, including when an edit makes rows disappear from the active filter.
|
||||||
|
|
||||||
|
The bulk API is `POST /api/transactions/bulk` with `revision`, `transaction_ids`, and only the requested fields: `category_id`, `merchant_id`, `add_tag_ids`, `remove_tag_ids`. Omitted category/merchant fields preserve per-transaction values; `merchant_id: ""` explicitly clears the merchant. Tags are additive/removal operations, not a replacement list.
|
||||||
|
|
||||||
## Data, backups, and recovery
|
## Data, backups, and recovery
|
||||||
|
|
||||||
Back up the **entire canonical finance directory**, including registry files, journals, `config.toml` when present, and operational/recovery state, plus any separately stored environment-managed secrets. `state/openrouter.json` and `state/enablebanking.json` contain UI-managed credentials: protect backups accordingly, including the matching banking session state. Stop the service for a consistent filesystem backup. DuckDB under `cache/` can be excluded and rebuilt.
|
Back up the **entire canonical finance directory**, including registry files, journals, `config.toml` when present, and operational/recovery state, plus any separately stored environment-managed secrets. `state/openrouter.json` and `state/enablebanking.json` contain UI-managed credentials: protect backups accordingly, including the matching banking session state. Stop the service for a consistent filesystem backup. DuckDB under `cache/` can be excluded and rebuilt.
|
||||||
|
|||||||
+18
-20
@@ -15,13 +15,14 @@ import (
|
|||||||
type Store struct{ db *sql.DB }
|
type Store struct{ db *sql.DB }
|
||||||
|
|
||||||
type Filter struct {
|
type Filter struct {
|
||||||
From string `json:"from"`
|
From string `json:"from"`
|
||||||
To string `json:"to"`
|
To string `json:"to"`
|
||||||
Currency string `json:"currency"`
|
Currency string `json:"currency"`
|
||||||
AccountID string `json:"account_id"`
|
AccountID string `json:"account_id"`
|
||||||
CategoryID string `json:"category_id"`
|
CategoryID string `json:"category_id"`
|
||||||
TagID string `json:"tag_id"`
|
TagIDs []string `json:"tag_ids"`
|
||||||
MerchantID string `json:"merchant_id"`
|
ExcludeTagIDs []string `json:"exclude_tag_ids"`
|
||||||
|
MerchantID string `json:"merchant_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Total struct {
|
type Total struct {
|
||||||
@@ -272,21 +273,18 @@ func (f Filter) where() (string, []any) {
|
|||||||
add("t.account_id = ?", f.AccountID)
|
add("t.account_id = ?", f.AccountID)
|
||||||
add("t.merchant_id = ?", f.MerchantID)
|
add("t.merchant_id = ?", f.MerchantID)
|
||||||
add("EXISTS (SELECT 1 FROM category_ancestors ca WHERE ca.category_id = t.category_id AND ca.ancestor_id = ?)", f.CategoryID)
|
add("EXISTS (SELECT 1 FROM category_ancestors ca WHERE ca.category_id = t.category_id AND ca.ancestor_id = ?)", f.CategoryID)
|
||||||
if f.TagID != "" {
|
addTags := func(predicate string, ids []string) {
|
||||||
ids := strings.Split(f.TagID, ",")
|
if len(ids) == 0 {
|
||||||
placeholders := make([]string, 0, len(ids))
|
return
|
||||||
for _, id := range ids {
|
|
||||||
id = strings.TrimSpace(id)
|
|
||||||
if id != "" {
|
|
||||||
placeholders = append(placeholders, "?")
|
|
||||||
args = append(args, id)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if len(placeholders) == 0 {
|
placeholders := make([]string, len(ids))
|
||||||
clauses = append(clauses, "FALSE")
|
for i, id := range ids {
|
||||||
} else {
|
placeholders[i] = "?"
|
||||||
clauses = append(clauses, "EXISTS (SELECT 1 FROM transaction_tags tt WHERE tt.transaction_id = t.id AND tt.tag_id IN ("+strings.Join(placeholders, ",")+"))")
|
args = append(args, id)
|
||||||
}
|
}
|
||||||
|
clauses = append(clauses, predicate+" (SELECT 1 FROM transaction_tags tt WHERE tt.transaction_id = t.id AND tt.tag_id IN ("+strings.Join(placeholders, ",")+"))")
|
||||||
}
|
}
|
||||||
|
addTags("EXISTS", f.TagIDs)
|
||||||
|
addTags("NOT EXISTS", f.ExcludeTagIDs)
|
||||||
return strings.Join(clauses, " AND "), args
|
return strings.Join(clauses, " AND "), args
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ func TestMonthlySplitsDirectionsAndRanksLargestPerCurrency(t *testing.T) {
|
|||||||
|
|
||||||
func TestTagUnionNeverDuplicatesTransactions(t *testing.T) {
|
func TestTagUnionNeverDuplicatesTransactions(t *testing.T) {
|
||||||
s := openFixture(t, fixture())
|
s := openFixture(t, fixture())
|
||||||
filter := Filter{From: "2026-02-01", To: "2026-02-28", Currency: "EUR", TagID: "tag_shared,tag_work,tag_shared"}
|
filter := Filter{From: "2026-02-01", To: "2026-02-28", Currency: "EUR", TagIDs: []string{"tag_shared", "tag_work", "tag_shared"}}
|
||||||
got := queryFixture(t, s, filter)
|
got := queryFixture(t, s, filter)
|
||||||
want := []Total{{Currency: "EUR", Expenses: "900719925474.1000", Income: "0.0000", Net: "-900719925474.1000"}}
|
want := []Total{{Currency: "EUR", Expenses: "900719925474.1000", Income: "0.0000", Net: "-900719925474.1000"}}
|
||||||
if !reflect.DeepEqual(got.Totals, want) {
|
if !reflect.DeepEqual(got.Totals, want) {
|
||||||
@@ -141,17 +141,132 @@ func TestTagUnionNeverDuplicatesTransactions(t *testing.T) {
|
|||||||
if len(got.Monthly) != 1 || got.Monthly[0].Count != 2 {
|
if len(got.Monthly) != 1 || got.Monthly[0].Count != 2 {
|
||||||
t.Fatalf("tag union count: %#v", got.Monthly)
|
t.Fatalf("tag union count: %#v", got.Monthly)
|
||||||
}
|
}
|
||||||
filter.TagID = "tag_shared"
|
filter.TagIDs = []string{"tag_shared"}
|
||||||
got = queryFixture(t, s, filter)
|
got = queryFixture(t, s, filter)
|
||||||
if len(got.Totals) != 1 || got.Totals[0].Expenses != "900719925474.0991" {
|
if len(got.Totals) != 1 || got.Totals[0].Expenses != "900719925474.0991" {
|
||||||
t.Fatalf("single tag filter: %#v", got.Totals)
|
t.Fatalf("single tag filter: %#v", got.Totals)
|
||||||
}
|
}
|
||||||
filter.TagID = "tag_shared') OR TRUE --"
|
filter.TagIDs = []string{"tag_shared') OR TRUE --"}
|
||||||
if totals := queryFixture(t, s, filter).Totals; len(totals) != 0 {
|
if totals := queryFixture(t, s, filter).Totals; len(totals) != 0 {
|
||||||
t.Fatalf("tag input altered SQL predicate: %#v", totals)
|
t.Fatalf("tag input altered SQL predicate: %#v", totals)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTagExclusionsAndComposition(t *testing.T) {
|
||||||
|
s := openFixture(t, fixture())
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
include []string
|
||||||
|
exclude []string
|
||||||
|
totals []Total
|
||||||
|
count int64
|
||||||
|
tagIDs []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "excluded tag removes whole multi-tag transaction",
|
||||||
|
exclude: []string{"tag_shared"},
|
||||||
|
totals: []Total{{Currency: "EUR", Expenses: "0.0009", Income: "100.1235", Net: "100.1226"}},
|
||||||
|
count: 3,
|
||||||
|
tagIDs: []string{"tag_work"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "any excluded tag removes transaction and untagged income survives",
|
||||||
|
exclude: []string{"tag_shared", "tag_work"},
|
||||||
|
totals: []Total{{Currency: "EUR", Expenses: "0.0000", Income: "100.1235", Net: "100.1235"}},
|
||||||
|
count: 2,
|
||||||
|
tagIDs: []string{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "include union and exclusion intersect with exclusion winning overlap",
|
||||||
|
include: []string{"tag_shared", "tag_work"},
|
||||||
|
exclude: []string{"tag_shared"},
|
||||||
|
totals: []Total{{Currency: "EUR", Expenses: "0.0009", Income: "0.0000", Net: "-0.0009"}},
|
||||||
|
count: 1,
|
||||||
|
tagIDs: []string{"tag_work"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "identical include and exclude match nothing",
|
||||||
|
include: []string{"tag_shared"},
|
||||||
|
exclude: []string{"tag_shared"},
|
||||||
|
totals: []Total{},
|
||||||
|
tagIDs: []string{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "exclusion values cannot alter SQL",
|
||||||
|
exclude: []string{"tag_shared') OR TRUE --"},
|
||||||
|
totals: []Total{{Currency: "EUR", Expenses: "900719925474.1000", Income: "100.1235", Net: "-900719925373.9765"}},
|
||||||
|
count: 4,
|
||||||
|
tagIDs: []string{"tag_shared", "tag_work"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty lists leave transactions unrestricted",
|
||||||
|
include: []string{},
|
||||||
|
exclude: []string{},
|
||||||
|
totals: []Total{{Currency: "EUR", Expenses: "900719925474.1000", Income: "100.1235", Net: "-900719925373.9765"}},
|
||||||
|
count: 4,
|
||||||
|
tagIDs: []string{"tag_shared", "tag_work"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range cases {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := queryFixture(t, s, Filter{From: "2026-02-01", To: "2026-02-28", Currency: "EUR", TagIDs: tt.include, ExcludeTagIDs: tt.exclude})
|
||||||
|
if !reflect.DeepEqual(got.Totals, tt.totals) {
|
||||||
|
t.Fatalf("totals: got %#v, want %#v", got.Totals, tt.totals)
|
||||||
|
}
|
||||||
|
var count int64
|
||||||
|
for _, month := range got.Monthly {
|
||||||
|
count += month.Count
|
||||||
|
}
|
||||||
|
if count != tt.count {
|
||||||
|
t.Fatalf("transaction count: got %d, want %d", count, tt.count)
|
||||||
|
}
|
||||||
|
tagIDs := make([]string, 0, len(got.Tags))
|
||||||
|
for _, tag := range got.Tags {
|
||||||
|
tagIDs = append(tagIDs, tag.ID)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(tagIDs, tt.tagIDs) {
|
||||||
|
t.Fatalf("tag groups: got %#v, want %#v", got.Tags, tt.tagIDs)
|
||||||
|
}
|
||||||
|
accounts := []Group{}
|
||||||
|
if len(tt.totals) != 0 {
|
||||||
|
accounts = append(accounts, Group{ID: "acc_eur", Name: "Current", Currency: "EUR", Amount: tt.totals[0].Net, Count: tt.count})
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got.Accounts, accounts) {
|
||||||
|
t.Fatalf("account groups: got %#v, want %#v", got.Accounts, accounts)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTagFiltersApplyToPreviousPeriodAndCategoryRollups(t *testing.T) {
|
||||||
|
data := fixture()
|
||||||
|
// Mirror current transactions into the preceding month, including the
|
||||||
|
// untagged income and the multi-tag expense that must be excluded.
|
||||||
|
for _, transaction := range data.Transactions[:4] {
|
||||||
|
transaction.Facts.ID += "_previous"
|
||||||
|
transaction.Facts.Fingerprint += "_previous"
|
||||||
|
transaction.Facts.BookingDate = "2026-01-15"
|
||||||
|
data.Transactions = append(data.Transactions, transaction)
|
||||||
|
}
|
||||||
|
s := openFixture(t, data)
|
||||||
|
got := queryFixture(t, s, Filter{
|
||||||
|
From: "2026-02-01", To: "2026-02-28", Currency: "EUR",
|
||||||
|
TagIDs: []string{"tag_shared", "tag_work"}, ExcludeTagIDs: []string{"tag_shared"},
|
||||||
|
})
|
||||||
|
want := []Total{{Currency: "EUR", Expenses: "0.0009", Income: "0.0000", Net: "-0.0009"}}
|
||||||
|
if !reflect.DeepEqual(got.Totals, want) || !reflect.DeepEqual(got.Previous, want) {
|
||||||
|
t.Fatalf("period totals: current %#v, previous %#v, want %#v", got.Totals, got.Previous, want)
|
||||||
|
}
|
||||||
|
groups := []Group{
|
||||||
|
{ID: "cat_expenses", Name: "Expenses", Currency: "EUR", Amount: "-0.0009", Count: 1},
|
||||||
|
{ID: "cat_food", Name: "Food", Currency: "EUR", Amount: "-0.0009", Count: 1},
|
||||||
|
{ID: "cat_living", Name: "Living", Currency: "EUR", Amount: "-0.0009", Count: 1},
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got.Categories, groups) || !reflect.DeepEqual(got.PreviousCategories, groups) {
|
||||||
|
t.Fatalf("category rollups: current %#v, previous %#v, want %#v", got.Categories, got.PreviousCategories, groups)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAncestorFilteringAndRollups(t *testing.T) {
|
func TestAncestorFilteringAndRollups(t *testing.T) {
|
||||||
s := openFixture(t, fixture())
|
s := openFixture(t, fixture())
|
||||||
filter := Filter{From: "2026-02-01", To: "2026-02-28", Currency: "EUR", CategoryID: "cat_living"}
|
filter := Filter{From: "2026-02-01", To: "2026-02-28", Currency: "EUR", CategoryID: "cat_living"}
|
||||||
|
|||||||
+170
-13
@@ -60,6 +60,64 @@ func seed(t *testing.T, a *App, s State) State {
|
|||||||
return result.State
|
return result.State
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSaveAccountClearsStaleBalanceAnchorOnIdentityChange(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
change func(*domain.Account)
|
||||||
|
clear bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "currency",
|
||||||
|
change: func(account *domain.Account) {
|
||||||
|
account.Currency = "USD"
|
||||||
|
},
|
||||||
|
clear: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "external account",
|
||||||
|
change: func(account *domain.Account) {
|
||||||
|
account.ExternalAccountID = "new_uid"
|
||||||
|
},
|
||||||
|
clear: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "display name",
|
||||||
|
change: func(account *domain.Account) {
|
||||||
|
account.DisplayName = "Renamed"
|
||||||
|
},
|
||||||
|
clear: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
a, s := testApp(t)
|
||||||
|
anchored := s.Data.Accounts[0]
|
||||||
|
anchored.ExternalAccountID = "old_uid"
|
||||||
|
anchored.AnchorBalance = "100.00"
|
||||||
|
anchored.AnchorDate = "2026-09-10"
|
||||||
|
var err error
|
||||||
|
s, err = a.Mutate(context.Background(), s.Revision, func(d *domain.Dataset) error {
|
||||||
|
return SaveAccount(d, anchored)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
changed := anchored
|
||||||
|
tc.change(&changed)
|
||||||
|
s, err = a.Mutate(context.Background(), s.Revision, func(d *domain.Dataset) error {
|
||||||
|
return SaveAccount(d, changed)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := s.Data.Accounts[0]
|
||||||
|
if tc.clear != (got.AnchorBalance == "" && got.AnchorDate == "") {
|
||||||
|
t.Fatalf("anchor after %s change: balance=%q date=%q", tc.name, got.AnchorBalance, got.AnchorDate)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// A released binary wrote include_amount into config.toml. Refusing it on
|
// A released binary wrote include_amount into config.toml. Refusing it on
|
||||||
// startup made every upgraded deployment crash-loop against its own settings
|
// startup made every upgraded deployment crash-loop against its own settings
|
||||||
// file, so a retired key must load and then disappear on the next save.
|
// file, so a retired key must load and then disappear on the next save.
|
||||||
@@ -171,10 +229,8 @@ func TestPreviewCooldownProtectsLaterPreviewsAndImports(t *testing.T) {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
for _, model := range []string{"test/model", "test/another-model"} {
|
for _, model := range []string{"test/model", "test/another-model"} {
|
||||||
preview, err := runPreview(t, a, PreviewRequest{
|
preview, err := runPreview(t, a, PreviewRequest{From: "2026-09-01", To: "2026-09-30",
|
||||||
Revision: s.Revision, From: "2026-09-01", To: "2026-09-30",
|
Model: model, Fields: Fields{Category: true}})
|
||||||
Model: model, Fields: Fields{Category: true},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -224,10 +280,8 @@ func TestCancelledPreviewRunProducesNoPreview(t *testing.T) {
|
|||||||
}))
|
}))
|
||||||
defer provider.Close()
|
defer provider.Close()
|
||||||
a.classifier = classification.Client{APIKey: "test", Model: "test/model", BaseURL: provider.URL}
|
a.classifier = classification.Client{APIKey: "test", Model: "test/model", BaseURL: provider.URL}
|
||||||
start, err := a.StartPreview(context.Background(), PreviewRequest{
|
start, err := a.StartPreview(context.Background(), PreviewRequest{From: "2026-09-09", To: "2026-09-09",
|
||||||
Revision: s.Revision, From: "2026-09-09", To: "2026-09-09",
|
Model: "test/model", Fields: Fields{Category: true}})
|
||||||
Model: "test/model", Fields: Fields{Category: true},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -319,7 +373,7 @@ func TestPreviewIsReadOnlySelectedApplyPreservesFactsAndOtherFields(t *testing.T
|
|||||||
}
|
}
|
||||||
mockClassifier(t, a)
|
mockClassifier(t, a)
|
||||||
before := domain.Clone(s.Data)
|
before := domain.Clone(s.Data)
|
||||||
preview, err := runPreview(t, a, PreviewRequest{Revision: s.Revision, From: "2026-09-01", To: "2026-09-30", Model: "improved/model", Fields: Fields{Category: true}})
|
preview, err := runPreview(t, a, PreviewRequest{From: "2026-09-01", To: "2026-09-30", Model: "improved/model", Fields: Fields{Category: true}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -360,11 +414,114 @@ func TestPreviewIsReadOnlySelectedApplyPreservesFactsAndOtherFields(t *testing.T
|
|||||||
t.Fatal("consumed preview applied twice")
|
t.Fatal("consumed preview applied twice")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPreviewUsesLatestSnapshotWithoutClientRevision(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
a, page := testApp(t)
|
||||||
|
page = seed(t, a, page)
|
||||||
|
mockClassifier(t, a)
|
||||||
|
request := PreviewRequest{From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true}}
|
||||||
|
id := page.Data.Transactions[0].Facts.ID
|
||||||
|
// Another writer changes the journal after the page loaded its state.
|
||||||
|
current, err := a.Mutate(ctx, page.Revision, func(d *domain.Dataset) error {
|
||||||
|
for i := range d.Transactions {
|
||||||
|
if d.Transactions[i].Facts.ID == id {
|
||||||
|
d.Transactions[i].Enrichment.TagIDs = []string{"home"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
preview, err := runPreview(t, a, request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if preview.Revision != current.Revision || len(preview.Changes) != 2 {
|
||||||
|
t.Fatalf("preview did not use the latest snapshot: %+v", preview)
|
||||||
|
}
|
||||||
|
unchanged, err := a.Snapshot(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(unchanged.Data, current.Data) {
|
||||||
|
t.Fatal("starting analysis changed the journal")
|
||||||
|
}
|
||||||
|
applied, err := a.ApplyPreview(ctx, preview.ID, preview.Revision, []string{id}, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, tx := range applied.Data.Transactions {
|
||||||
|
if tx.Facts.ID == id && (tx.Enrichment.CategoryID != "groceries" || !reflect.DeepEqual(tx.Enrichment.TagIDs, []string{"home"})) {
|
||||||
|
t.Fatalf("analysis overwrote an edit made after the page loaded: %+v", tx.Enrichment)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreviewExpiresAfterTwentyFourHours(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
age time.Duration
|
||||||
|
newPreview bool
|
||||||
|
expired bool
|
||||||
|
}{
|
||||||
|
{name: "apply before expiry", age: 24*time.Hour - time.Minute},
|
||||||
|
{name: "apply after expiry", age: 24*time.Hour + time.Minute, expired: true},
|
||||||
|
{name: "new preview retains unexpired review", age: 24*time.Hour - time.Minute, newPreview: true},
|
||||||
|
{name: "new preview discards expired review", age: 24*time.Hour + time.Minute, newPreview: true, expired: true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
a, s := testApp(t)
|
||||||
|
s = seed(t, a, s)
|
||||||
|
mockClassifier(t, a)
|
||||||
|
p, err := runPreview(t, a, PreviewRequest{From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(p.Changes) != 2 {
|
||||||
|
t.Fatalf("expected two proposed changes: %+v", p)
|
||||||
|
}
|
||||||
|
a.mu.Lock()
|
||||||
|
p.created = time.Now().Add(-tc.age)
|
||||||
|
a.previews[p.ID] = p
|
||||||
|
a.mu.Unlock()
|
||||||
|
if tc.newPreview {
|
||||||
|
// Completing another run performs expired-preview cleanup.
|
||||||
|
// An empty range needs no additional provider request.
|
||||||
|
if _, err := runPreview(t, a, PreviewRequest{From: "2025-01-01", To: "2025-01-31", Model: "test/model", Fields: Fields{Category: true}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
change := p.Changes[0]
|
||||||
|
_, err = a.ApplyPreview(ctx, p.ID, p.Revision, []string{change.ID}, nil)
|
||||||
|
if (err != nil) != tc.expired {
|
||||||
|
t.Fatalf("apply at age %s: error = %v, expired = %t", tc.age, err, tc.expired)
|
||||||
|
}
|
||||||
|
after, err := a.Snapshot(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
expected := domain.Clone(s.Data)
|
||||||
|
if !tc.expired {
|
||||||
|
for i := range expected.Transactions {
|
||||||
|
if expected.Transactions[i].Facts.ID == change.ID {
|
||||||
|
expected.Transactions[i].Enrichment = change.After
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(after.Data, expected) {
|
||||||
|
t.Fatal("expiry handling did not preserve the expected transaction state")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
func TestStalePreviewCannotOverwriteManualCorrection(t *testing.T) {
|
func TestStalePreviewCannotOverwriteManualCorrection(t *testing.T) {
|
||||||
a, s := testApp(t)
|
a, s := testApp(t)
|
||||||
s = seed(t, a, s)
|
s = seed(t, a, s)
|
||||||
mockClassifier(t, a)
|
mockClassifier(t, a)
|
||||||
p, err := runPreview(t, a, PreviewRequest{Revision: s.Revision, From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true}})
|
p, err := runPreview(t, a, PreviewRequest{From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -396,7 +553,7 @@ func TestApplyPreviewSurvivesUnrelatedCommitsAndPartialApplies(t *testing.T) {
|
|||||||
a, s := testApp(t)
|
a, s := testApp(t)
|
||||||
s = seed(t, a, s)
|
s = seed(t, a, s)
|
||||||
mockClassifier(t, a)
|
mockClassifier(t, a)
|
||||||
p, err := runPreview(t, a, PreviewRequest{Revision: s.Revision, From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true}})
|
p, err := runPreview(t, a, PreviewRequest{From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -449,7 +606,7 @@ func TestApplyPreviewHonoursReviewerEdits(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
mockClassifier(t, a)
|
mockClassifier(t, a)
|
||||||
p, err := runPreview(t, a, PreviewRequest{Revision: s.Revision, From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true, Tags: true}})
|
p, err := runPreview(t, a, PreviewRequest{From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true, Tags: true}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -491,7 +648,7 @@ func TestApplyPreviewHonoursReviewerEdits(t *testing.T) {
|
|||||||
func TestImportNeverAutoAppliesLowConfidenceCategory(t *testing.T) {
|
func TestImportNeverAutoAppliesLowConfidenceCategory(t *testing.T) {
|
||||||
a, s := testApp(t)
|
a, s := testApp(t)
|
||||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
content := `{"merchant_id":null,"new_merchant":"REWE","category_id":"groceries","tag_ids":[],"confidence":"low"}`
|
content := `{"merchant_id":null,"new_merchant":"REWE","category_id":"c1","tag_ids":[],"confidence":"low"}`
|
||||||
json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{
|
json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{
|
||||||
"finish_reason": "stop",
|
"finish_reason": "stop",
|
||||||
"message": map[string]any{"content": content},
|
"message": map[string]any{"content": content},
|
||||||
|
|||||||
@@ -882,6 +882,7 @@ func (a *App) Sync(ctx context.Context) (State, error) {
|
|||||||
}
|
}
|
||||||
s = result.State
|
s = result.State
|
||||||
a.ops.AccountSync[account.ID] = now.Format(time.RFC3339)
|
a.ops.AccountSync[account.ID] = now.Format(time.RFC3339)
|
||||||
|
s = a.anchorAccount(ctx, s, account, to)
|
||||||
}
|
}
|
||||||
a.ops.SyncError = strings.Join(failures, "; ")
|
a.ops.SyncError = strings.Join(failures, "; ")
|
||||||
a.ops.SyncRetryAt = ""
|
a.ops.SyncRetryAt = ""
|
||||||
@@ -897,6 +898,66 @@ func (a *App) Sync(ctx context.Context) (State, error) {
|
|||||||
return a.snapshot(ctx)
|
return a.snapshot(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// anchorAccount fixes a connected cash account's start balance after its first
|
||||||
|
// successful sync: the bank's booked (CLBD) balance is captured once, verbatim,
|
||||||
|
// with the day it was true, so a date-windowed history still yields the real
|
||||||
|
// balance — the money from before the window is derived as the anchor less
|
||||||
|
// every movement booked through the anchor date, and an older import later
|
||||||
|
// corrects that derivation by itself. The balance is fetched after the
|
||||||
|
// transactions to minimize the gap between the two reads. Banks supply booking
|
||||||
|
// dates rather than exact times, so the anchor day is deliberately treated as
|
||||||
|
// one completed booked state. Every failure leaves the anchor unset for the
|
||||||
|
// next sync to retry; a missing CLBD figure is such a failure, because an
|
||||||
|
// available or expected balance includes pending amounts that have no booked
|
||||||
|
// fact to subtract.
|
||||||
|
func (a *App) anchorAccount(ctx context.Context, s State, account domain.Account, today string) State {
|
||||||
|
if account.Investing() || account.AnchorDate != "" || account.ExternalAccountID == "" {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
balances, err := a.bank.Balances(ctx, account.ExternalAccountID)
|
||||||
|
if err != nil {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
var selected banking.Balance
|
||||||
|
anchorDate := ""
|
||||||
|
for _, balance := range balances {
|
||||||
|
if balance.Type != "CLBD" || balance.Currency != account.Currency {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
date := balance.ReferenceDate
|
||||||
|
if date == "" {
|
||||||
|
date = today
|
||||||
|
} else if _, e := time.Parse("2006-01-02", date); e != nil || date > today {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if date < anchorDate {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Two different booked figures for the same account, currency and
|
||||||
|
// reference day are ambiguous. Do not let response order decide money.
|
||||||
|
if date == anchorDate && anchorDate != "" && balance.Amount != selected.Amount {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
selected, anchorDate = balance, date
|
||||||
|
}
|
||||||
|
if anchorDate == "" {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
data := domain.Clone(s.Data)
|
||||||
|
for i := range data.Accounts {
|
||||||
|
if data.Accounts[i].ID != account.ID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data.Accounts[i].AnchorBalance = selected.Amount
|
||||||
|
data.Accounts[i].AnchorDate = anchorDate
|
||||||
|
if next, e := a.commit(ctx, s.Revision, data); e == nil {
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
// syncInterval is how often connected accounts synchronize on their own. Twice
|
// syncInterval is how often connected accounts synchronize on their own. Twice
|
||||||
// a day halves how long a booking can sit unseen while staying inside Enable
|
// a day halves how long a booking can sit unseen while staying inside Enable
|
||||||
// Banking's documented background allowance of roughly four fetches per day per
|
// Banking's documented background allowance of roughly four fetches per day per
|
||||||
|
|||||||
@@ -61,6 +61,12 @@ func SaveAccount(d *domain.Dataset, v domain.Account) error {
|
|||||||
}
|
}
|
||||||
for i, x := range d.Accounts {
|
for i, x := range d.Accounts {
|
||||||
if x.ID == v.ID {
|
if x.ID == v.ID {
|
||||||
|
// A balance belongs to the account identity and currency that the
|
||||||
|
// bank reported. Changing either makes the captured figure stale;
|
||||||
|
// clear it so the next connected sync can capture a matching one.
|
||||||
|
if x.Currency != v.Currency || x.ExternalAccountID != v.ExternalAccountID {
|
||||||
|
v.AnchorBalance, v.AnchorDate = "", ""
|
||||||
|
}
|
||||||
d.Accounts[i] = v
|
d.Accounts[i] = v
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -104,6 +110,25 @@ func SaveInstrument(d *domain.Dataset, v domain.Instrument) error {
|
|||||||
d.Instruments = append(d.Instruments, v)
|
d.Instruments = append(d.Instruments, v)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SaveAsset registers or revalues a hand-valued possession. The value and the
|
||||||
|
// day it was stated travel together; full validation happens at commit.
|
||||||
|
func SaveAsset(d *domain.Dataset, v domain.Asset) error {
|
||||||
|
v.Name = strings.TrimSpace(v.Name)
|
||||||
|
v.Kind = strings.TrimSpace(v.Kind)
|
||||||
|
v.Currency = strings.ToUpper(strings.TrimSpace(v.Currency))
|
||||||
|
if v.ID == "" {
|
||||||
|
v.ID = domain.NewID("asset")
|
||||||
|
}
|
||||||
|
for i, x := range d.Assets {
|
||||||
|
if x.ID == v.ID {
|
||||||
|
d.Assets[i] = v
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.Assets = append(d.Assets, v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
func SaveCategory(d *domain.Dataset, v domain.Category) error {
|
func SaveCategory(d *domain.Dataset, v domain.Category) error {
|
||||||
v.Name = strings.TrimSpace(v.Name)
|
v.Name = strings.TrimSpace(v.Name)
|
||||||
if v.ID == "" {
|
if v.ID == "" {
|
||||||
@@ -203,6 +228,15 @@ func Manage(d *domain.Dataset, entity, action, id, target string) error {
|
|||||||
if n == len(d.Instruments) {
|
if n == len(d.Instruments) {
|
||||||
return errors.New("unknown instrument")
|
return errors.New("unknown instrument")
|
||||||
}
|
}
|
||||||
|
case "asset":
|
||||||
|
if action != "delete" {
|
||||||
|
return errors.New("asset merging is not supported")
|
||||||
|
}
|
||||||
|
n := len(d.Assets)
|
||||||
|
d.Assets = slices.DeleteFunc(d.Assets, func(v domain.Asset) bool { return v.ID == id })
|
||||||
|
if n == len(d.Assets) {
|
||||||
|
return errors.New("unknown asset")
|
||||||
|
}
|
||||||
case "tag":
|
case "tag":
|
||||||
if !slices.ContainsFunc(d.Tags, func(v domain.Tag) bool { return v.ID == id }) {
|
if !slices.ContainsFunc(d.Tags, func(v domain.Tag) bool { return v.ID == id }) {
|
||||||
return errors.New("unknown tag")
|
return errors.New("unknown tag")
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func checkOpenRouterPreview(t *testing.T, a *App, s State, auth <-chan string, key string) {
|
func checkOpenRouterPreview(t *testing.T, a *App, auth <-chan string, key string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
p, err := runPreview(t, a, PreviewRequest{Revision: s.Revision, From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true}})
|
p, err := runPreview(t, a, PreviewRequest{From: "2026-09-01", To: "2026-09-30", Model: "test/model", Fields: Fields{Category: true}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -68,7 +68,7 @@ func TestOpenRouterKeyRotationChangesProviderAuthorization(t *testing.T) {
|
|||||||
if strings.Contains(string(encoded), "private-key") {
|
if strings.Contains(string(encoded), "private-key") {
|
||||||
t.Fatal("saved credential leaked into browser state")
|
t.Fatal("saved credential leaked into browser state")
|
||||||
}
|
}
|
||||||
checkOpenRouterPreview(t, a, s, auth, key)
|
checkOpenRouterPreview(t, a, auth, key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,7 +101,7 @@ func TestOpenRouterSavedKeyAndDisableSurviveRestartOverrideEnvironment(t *testin
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
reopen()
|
reopen()
|
||||||
checkOpenRouterPreview(t, a, s, auth, "environment-private-key")
|
checkOpenRouterPreview(t, a, auth, "environment-private-key")
|
||||||
for _, key := range []string{"saved-private-key", ""} {
|
for _, key := range []string{"saved-private-key", ""} {
|
||||||
var err error
|
var err error
|
||||||
s, err = a.SaveOpenRouterKey(context.Background(), key)
|
s, err = a.SaveOpenRouterKey(context.Background(), key)
|
||||||
@@ -119,7 +119,7 @@ func TestOpenRouterSavedKeyAndDisableSurviveRestartOverrideEnvironment(t *testin
|
|||||||
if s.Status.AIConfigured != (key != "") {
|
if s.Status.AIConfigured != (key != "") {
|
||||||
t.Fatal("restarted credential status ignored saved preference")
|
t.Fatal("restarted credential status ignored saved preference")
|
||||||
}
|
}
|
||||||
checkOpenRouterPreview(t, a, s, auth, key)
|
checkOpenRouterPreview(t, a, auth, key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,7 +187,7 @@ func TestOpenRouterRejectedKeysPreserveActiveCredential(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
checkOpenRouterPreview(t, a, s, auth, key)
|
checkOpenRouterPreview(t, a, auth, key)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestOpenRouterFailedWritePreservesActiveCredential(t *testing.T) {
|
func TestOpenRouterFailedWritePreservesActiveCredential(t *testing.T) {
|
||||||
@@ -216,5 +216,5 @@ func TestOpenRouterFailedWritePreservesActiveCredential(t *testing.T) {
|
|||||||
t.Fatal("persistence error leaked credential content")
|
t.Fatal("persistence error leaked credential content")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
checkOpenRouterPreview(t, a, s, auth, "active-private-key")
|
checkOpenRouterPreview(t, a, auth, "active-private-key")
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-16
@@ -13,17 +13,18 @@ import (
|
|||||||
"finance-duck/internal/domain"
|
"finance-duck/internal/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const previewLifetime = 24 * time.Hour
|
||||||
|
|
||||||
type Fields struct {
|
type Fields struct {
|
||||||
Merchant bool `json:"merchant"`
|
Merchant bool `json:"merchant"`
|
||||||
Category bool `json:"category"`
|
Category bool `json:"category"`
|
||||||
Tags bool `json:"tags"`
|
Tags bool `json:"tags"`
|
||||||
}
|
}
|
||||||
type PreviewRequest struct {
|
type PreviewRequest struct {
|
||||||
Revision string `json:"revision"`
|
From string `json:"from"`
|
||||||
From string `json:"from"`
|
To string `json:"to"`
|
||||||
To string `json:"to"`
|
Model string `json:"model"`
|
||||||
Model string `json:"model"`
|
Fields Fields `json:"fields"`
|
||||||
Fields Fields `json:"fields"`
|
|
||||||
}
|
}
|
||||||
type Change struct {
|
type Change struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
@@ -117,12 +118,11 @@ func previewEligible(t domain.Transaction, r PreviewRequest) bool {
|
|||||||
t.Enrichment.Kind != "transfer" && t.Enrichment.Kind != domain.KindInvestment
|
t.Enrichment.Kind != "transfer" && t.Enrichment.Kind != domain.KindInvestment
|
||||||
}
|
}
|
||||||
|
|
||||||
// StartPreview validates the request against the current journal and starts a
|
// StartPreview takes a fresh journal snapshot and starts a read-only
|
||||||
// background classification run. The provider is paced to one request every
|
// classification run. It does not require the page's revision: a sync or edit
|
||||||
// few seconds, so any real range takes minutes: the caller polls
|
// while the page is open must not block analysis. ApplyPreview checks for
|
||||||
// PreviewProgress instead of holding an HTTP request open for the duration.
|
// conflicting changes before writing. Only one run exists at a time; callers
|
||||||
// Only one run exists at a time; the run owns its own snapshot and never
|
// poll PreviewProgress instead of holding an HTTP request open.
|
||||||
// touches canonical data.
|
|
||||||
func (a *App) StartPreview(ctx context.Context, r PreviewRequest) (PreviewProgress, error) {
|
func (a *App) StartPreview(ctx context.Context, r PreviewRequest) (PreviewProgress, error) {
|
||||||
if err := validatePreviewRequest(r); err != nil {
|
if err := validatePreviewRequest(r); err != nil {
|
||||||
return PreviewProgress{}, err
|
return PreviewProgress{}, err
|
||||||
@@ -136,9 +136,6 @@ func (a *App) StartPreview(ctx context.Context, r PreviewRequest) (PreviewProgre
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return PreviewProgress{}, err
|
return PreviewProgress{}, err
|
||||||
}
|
}
|
||||||
if r.Revision != s.Revision {
|
|
||||||
return PreviewProgress{}, errors.New("revision conflict: reload before analysing")
|
|
||||||
}
|
|
||||||
client := a.classifier.WithModel(r.Model)
|
client := a.classifier.WithModel(r.Model)
|
||||||
total := 0
|
total := 0
|
||||||
for _, t := range s.Data.Transactions {
|
for _, t := range s.Data.Transactions {
|
||||||
@@ -173,7 +170,7 @@ func (a *App) runPreview(ctx context.Context, cancel context.CancelFunc, client
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
for id, old := range a.previews {
|
for id, old := range a.previews {
|
||||||
if time.Since(old.created) > time.Hour {
|
if time.Since(old.created) > previewLifetime {
|
||||||
delete(a.previews, id)
|
delete(a.previews, id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -343,7 +340,7 @@ func (a *App) ApplyPreview(ctx context.Context, id, rev string, ids []string, ed
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
p, ok := a.previews[id]
|
p, ok := a.previews[id]
|
||||||
if !ok || time.Since(p.created) > time.Hour {
|
if !ok || time.Since(p.created) > previewLifetime {
|
||||||
return State{}, errors.New("preview expired or unknown; analyse again")
|
return State{}, errors.New("preview expired or unknown; analyse again")
|
||||||
}
|
}
|
||||||
if rev != p.Revision {
|
if rev != p.Revision {
|
||||||
|
|||||||
@@ -17,8 +17,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type bankScenario struct {
|
type bankScenario struct {
|
||||||
session banking.Session
|
session banking.Session
|
||||||
fail bool
|
fail bool
|
||||||
|
balances []banking.Balance
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *bankScenario) Authorize(context.Context, string, string, string, string) (string, error) {
|
func (b *bankScenario) Authorize(context.Context, string, string, string, string) (string, error) {
|
||||||
@@ -41,6 +42,9 @@ func (b *bankScenario) Status(context.Context, string) (banking.SessionStatus, e
|
|||||||
return status, nil
|
return status, nil
|
||||||
}
|
}
|
||||||
func (b *bankScenario) Balances(context.Context, string) ([]banking.Balance, error) {
|
func (b *bankScenario) Balances(context.Context, string) ([]banking.Balance, error) {
|
||||||
|
if b.balances != nil {
|
||||||
|
return b.balances, nil
|
||||||
|
}
|
||||||
return []banking.Balance{{Amount: "100.00", Currency: "EUR", Type: "CLBD"}}, nil
|
return []banking.Balance{{Amount: "100.00", Currency: "EUR", Type: "CLBD"}}, nil
|
||||||
}
|
}
|
||||||
func (b *bankScenario) Transactions(_ context.Context, a domain.Account, from, to string, _ bool) ([]domain.Facts, error) {
|
func (b *bankScenario) Transactions(_ context.Context, a domain.Account, from, to string, _ bool) ([]domain.Facts, error) {
|
||||||
@@ -83,6 +87,53 @@ func TestSyncRestoresSavedConsentBindingsAndDoesNotDuplicateFacts(t *testing.T)
|
|||||||
t.Fatal("provider failure was not isolated from canonical data")
|
t.Fatal("provider failure was not isolated from canonical data")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The first successful sync fixes the start balance from the bank's booked
|
||||||
|
// figure only: an available balance includes pending amounts with no booked
|
||||||
|
// fact to subtract, and a later balance change must never move an anchor that
|
||||||
|
// has been set — the anchor is the day a figure was true, not a mirror.
|
||||||
|
func TestSyncAnchorsBalanceOnceFromBookedFigureOnly(t *testing.T) {
|
||||||
|
a, s := testApp(t)
|
||||||
|
account := s.Data.Accounts[0]
|
||||||
|
account.ExternalAccountID = "provider_uid"
|
||||||
|
provider := &bankScenario{
|
||||||
|
session: banking.Session{ID: "session", ValidUntil: time.Now().Add(24 * time.Hour).Format(time.RFC3339), Accounts: []domain.Account{account}},
|
||||||
|
balances: []banking.Balance{{Amount: "999.99", Currency: "EUR", Type: "ITAV"}},
|
||||||
|
}
|
||||||
|
a.bank = provider
|
||||||
|
a.ops.Sessions = []banking.Session{provider.session}
|
||||||
|
if err := a.saveOps(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
unbooked, err := a.Sync(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := unbooked.Data.Accounts[0]; got.AnchorBalance != "" || got.AnchorDate != "" {
|
||||||
|
t.Fatalf("available-only balance was anchored: %+v", got)
|
||||||
|
}
|
||||||
|
yesterday := time.Now().UTC().AddDate(0, 0, -1).Format("2006-01-02")
|
||||||
|
older := time.Now().UTC().AddDate(0, 0, -2).Format("2006-01-02")
|
||||||
|
provider.balances = append(provider.balances,
|
||||||
|
banking.Balance{Amount: "240.00", Currency: "EUR", Type: "CLBD", ReferenceDate: older},
|
||||||
|
banking.Balance{Amount: "250.00", Currency: "EUR", Type: "CLBD", ReferenceDate: yesterday},
|
||||||
|
)
|
||||||
|
anchored, err := a.Sync(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := anchored.Data.Accounts[0]; got.AnchorBalance != "250.00" || got.AnchorDate != yesterday {
|
||||||
|
t.Fatalf("booked balance was not anchored at its reference day: %+v", got)
|
||||||
|
}
|
||||||
|
provider.balances = []banking.Balance{{Amount: "300.00", Currency: "EUR", Type: "CLBD", ReferenceDate: yesterday}}
|
||||||
|
retained, err := a.Sync(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(anchored.Data, retained.Data) {
|
||||||
|
t.Fatal("a later balance moved an existing anchor")
|
||||||
|
}
|
||||||
|
}
|
||||||
func TestReconnectReplacesOldConsentWithoutDuplicatingLocalAccount(t *testing.T) {
|
func TestReconnectReplacesOldConsentWithoutDuplicatingLocalAccount(t *testing.T) {
|
||||||
a, s := testApp(t)
|
a, s := testApp(t)
|
||||||
account := s.Data.Accounts[0]
|
account := s.Data.Accounts[0]
|
||||||
@@ -196,9 +247,16 @@ func TestSyncSessionRateLimitPreservesBindingsAndRecovers(t *testing.T) {
|
|||||||
failures: map[string]error{},
|
failures: map[string]error{},
|
||||||
}
|
}
|
||||||
a.bank = b
|
a.bank = b
|
||||||
|
first, err := a.Sync(ctx)
|
||||||
|
if err != nil || len(first.Data.Transactions) != 4 {
|
||||||
|
t.Fatalf("initial sync: transactions=%d, error=%v, sync error=%s", len(first.Data.Transactions), err, first.Status.SyncError)
|
||||||
|
}
|
||||||
|
// The first successful sync also anchors each account's balance; a second
|
||||||
|
// sync reaches the steady state where the session bindings have absorbed
|
||||||
|
// the anchored accounts and nothing changes any more.
|
||||||
before, err := a.Sync(ctx)
|
before, err := a.Sync(ctx)
|
||||||
if err != nil || len(before.Data.Transactions) != 4 {
|
if err != nil || !reflect.DeepEqual(first.Data, before.Data) {
|
||||||
t.Fatalf("initial sync: transactions=%d, error=%v, sync error=%s", len(before.Data.Transactions), err, before.Status.SyncError)
|
t.Fatalf("steady-state sync changed canonical data: %v", err)
|
||||||
}
|
}
|
||||||
old := time.Now().Add(-48 * time.Hour).UTC().Format(time.RFC3339)
|
old := time.Now().Add(-48 * time.Hour).UTC().Format(time.RFC3339)
|
||||||
a.ops.LastSync = old
|
a.ops.LastSync = old
|
||||||
@@ -267,9 +325,19 @@ func TestSyncMissingMembershipStillRejectsAccount(t *testing.T) {
|
|||||||
if len(b.accounts) != 1 || b.accounts[0].ID != "other" || a.ops.AccountSync[s.Data.Accounts[0].ID] != last || a.ops.LastSync != last {
|
if len(b.accounts) != 1 || b.accounts[0].ID != "other" || a.ops.AccountSync[s.Data.Accounts[0].ID] != last || a.ops.LastSync != last {
|
||||||
t.Fatal("missing member was fetched or advanced its cursor, or valid member was skipped")
|
t.Fatal("missing member was fetched or advanced its cursor, or valid member was skipped")
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(before.Accounts, after.Data.Accounts) || len(after.Data.Transactions) != 1 || after.Data.Transactions[0].Facts.AccountID != "other" {
|
if !reflect.DeepEqual(before.Accounts[0], after.Data.Accounts[0]) || len(after.Data.Transactions) != 1 || after.Data.Transactions[0].Facts.AccountID != "other" {
|
||||||
t.Fatal("missing membership changed bindings or imported unauthorized facts")
|
t.Fatal("missing membership changed bindings or imported unauthorized facts")
|
||||||
}
|
}
|
||||||
|
// The authorized member's first successful sync anchors its balance from
|
||||||
|
// the bank's booked figure; the rejected member must not gain one.
|
||||||
|
anchored := after.Data.Accounts[1]
|
||||||
|
if anchored.AnchorBalance != "100.00" || anchored.AnchorDate == "" {
|
||||||
|
t.Fatalf("authorized member was not anchored: %+v", anchored)
|
||||||
|
}
|
||||||
|
anchored.AnchorBalance, anchored.AnchorDate = "", ""
|
||||||
|
if !reflect.DeepEqual(before.Accounts[1], anchored) {
|
||||||
|
t.Fatal("anchoring changed more than the anchor on the authorized member")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSyncTransactionFailuresPreserveProgressAndSafeErrors(t *testing.T) {
|
func TestSyncTransactionFailuresPreserveProgressAndSafeErrors(t *testing.T) {
|
||||||
|
|||||||
+107
-17
@@ -15,8 +15,11 @@ import (
|
|||||||
// same journal derives.
|
// same journal derives.
|
||||||
type Wealth struct {
|
type Wealth struct {
|
||||||
Accounts []WealthAccount `json:"accounts"`
|
Accounts []WealthAccount `json:"accounts"`
|
||||||
// Totals is cash, position value and their sum per currency, across every
|
// Assets are the hand-valued possessions outside any account, echoed here
|
||||||
// account.
|
// so the page that shows the total also shows what the total contains.
|
||||||
|
Assets []WealthAsset `json:"assets"`
|
||||||
|
// Totals is cash, position value, hand-valued assets and their sum per
|
||||||
|
// currency, across every account.
|
||||||
Totals []WealthTotal `json:"totals"`
|
Totals []WealthTotal `json:"totals"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,8 +31,11 @@ type WealthTotal struct {
|
|||||||
// in Unpriced, because valuing them at cost would report a number the
|
// in Unpriced, because valuing them at cost would report a number the
|
||||||
// journal cannot support.
|
// journal cannot support.
|
||||||
Positions domain.Money `json:"positions"`
|
Positions domain.Money `json:"positions"`
|
||||||
Wealth domain.Money `json:"wealth"`
|
// Assets is the stated value of every hand-valued asset in this currency,
|
||||||
Unpriced int `json:"unpriced"`
|
// and Wealth is cash, positions and assets together.
|
||||||
|
Assets domain.Money `json:"assets"`
|
||||||
|
Wealth domain.Money `json:"wealth"`
|
||||||
|
Unpriced int `json:"unpriced"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// WealthAccount is one account's position as the journal records it.
|
// WealthAccount is one account's position as the journal records it.
|
||||||
@@ -43,9 +49,11 @@ type WealthAccount struct {
|
|||||||
Records int `json:"records"`
|
Records int `json:"records"`
|
||||||
FirstBooking string `json:"first_booking,omitempty"`
|
FirstBooking string `json:"first_booking,omitempty"`
|
||||||
LastBooking string `json:"last_booking,omitempty"`
|
LastBooking string `json:"last_booking,omitempty"`
|
||||||
// Cash is every recorded movement summed. It equals the account's real
|
// Cash is every recorded movement summed — plus, when the account carries a
|
||||||
// balance only when the journal holds that account's complete history,
|
// balance anchor, the derived start balance. Without an anchor it equals
|
||||||
// which a broker export does and a date-windowed bank statement does not.
|
// the account's real balance only when the journal holds that account's
|
||||||
|
// complete history, which a broker export does and a date-windowed bank
|
||||||
|
// statement does not.
|
||||||
Cash domain.Money `json:"cash"`
|
Cash domain.Money `json:"cash"`
|
||||||
// Positions is the market value of every priced holding, and Wealth the two
|
// Positions is the market value of every priced holding, and Wealth the two
|
||||||
// together: the number this page exists to show. Unpriced counts the
|
// together: the number this page exists to show. Unpriced counts the
|
||||||
@@ -113,6 +121,17 @@ type WealthHolding struct {
|
|||||||
Records int `json:"records"`
|
Records int `json:"records"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WealthAsset is one hand-valued asset as the journal records it. The value is
|
||||||
|
// stated, never quoted, and carries the day it was stated.
|
||||||
|
type WealthAsset struct {
|
||||||
|
AssetID string `json:"asset_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Kind string `json:"kind,omitempty"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
Value domain.Money `json:"value"`
|
||||||
|
ValuedAt string `json:"valued_at"`
|
||||||
|
}
|
||||||
|
|
||||||
// WealthCheck is one named verification with its evidence. Failed marks a
|
// WealthCheck is one named verification with its evidence. Failed marks a
|
||||||
// disagreement inside the journal; the rest are notes that explain a figure
|
// disagreement inside the journal; the rest are notes that explain a figure
|
||||||
// before it is compared with a broker's screen.
|
// before it is compared with a broker's screen.
|
||||||
@@ -175,6 +194,13 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
unappliedFee, unappliedTax int64
|
unappliedFee, unappliedTax int64
|
||||||
unappliedRows int
|
unappliedRows int
|
||||||
unmatchedCash, unmatchedRows int64
|
unmatchedCash, unmatchedRows int64
|
||||||
|
// anchored accounts carry the bank's booked balance on anchorDate.
|
||||||
|
// residual is that figure less every movement booked through the
|
||||||
|
// anchor day: the money from before the recorded history, and the
|
||||||
|
// account's derived start balance.
|
||||||
|
anchored bool
|
||||||
|
anchorDate string
|
||||||
|
residual int64
|
||||||
}
|
}
|
||||||
states := map[string]*accountState{}
|
states := map[string]*accountState{}
|
||||||
state := func(id string) *accountState {
|
state := func(id string) *accountState {
|
||||||
@@ -183,15 +209,42 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
}
|
}
|
||||||
return states[id]
|
return states[id]
|
||||||
}
|
}
|
||||||
|
// An anchored account's balance is the bank's own figure plus what moved
|
||||||
|
// after the anchor day. The residue is order-independent, so it is settled
|
||||||
|
// before the chronological pass that judges running balances.
|
||||||
|
for _, account := range data.Accounts {
|
||||||
|
if account.AnchorDate == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
anchor, err := account.AnchorBalance.Minor()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
st := state(account.ID)
|
||||||
|
st.anchored, st.anchorDate, st.residual = true, account.AnchorDate, anchor
|
||||||
|
for _, t := range data.Transactions {
|
||||||
|
if t.Facts.AccountID != account.ID || t.Facts.BookingDate > account.AnchorDate {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if minor, e := t.Facts.Amount.Minor(); e == nil {
|
||||||
|
st.residual -= minor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
// A day's rows are applied together before any low-water mark is taken.
|
// A day's rows are applied together before any low-water mark is taken.
|
||||||
// Order within a day is not knowable: a broker export states a booking date
|
// Order within a day is not knowable: a broker export states a booking date
|
||||||
// and a clock time, the time is local and crosses midnight, so only the
|
// and a clock time, the time is local and crosses midnight, so only the
|
||||||
// date is imported. A purchase funded by a sale nine seconds earlier then
|
// date is imported. A purchase funded by a sale nine seconds earlier then
|
||||||
// arrives in an arbitrary order, and checking row by row reports a dip
|
// arrives in an arbitrary order, and checking row by row reports a dip
|
||||||
// that never happened.
|
// that never happened.
|
||||||
|
// Days on or before an anchor are not judged at all: the history before
|
||||||
|
// the anchor is incomplete by definition, so a running balance there is
|
||||||
|
// not observable.
|
||||||
closeDay := func(st *accountState) {
|
closeDay := func(st *accountState) {
|
||||||
if st.cash < st.lowestCash {
|
if !st.anchored || st.day > st.anchorDate {
|
||||||
st.lowestCash, st.lowestCashDate = st.cash, st.day
|
if effective := st.cash + st.residual; effective < st.lowestCash {
|
||||||
|
st.lowestCash, st.lowestCashDate = effective, st.day
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for _, held := range st.holdings {
|
for _, held := range st.holdings {
|
||||||
if held.units < held.lowest {
|
if held.units < held.lowest {
|
||||||
@@ -282,24 +335,40 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
report := Wealth{Accounts: []WealthAccount{}, Totals: []WealthTotal{}}
|
report := Wealth{Accounts: []WealthAccount{}, Assets: []WealthAsset{}, Totals: []WealthTotal{}}
|
||||||
totals := map[string]int64{}
|
totals := map[string]int64{}
|
||||||
positionTotals := map[string]int64{}
|
positionTotals := map[string]int64{}
|
||||||
|
assetTotals := map[string]int64{}
|
||||||
unpricedTotals := map[string]int{}
|
unpricedTotals := map[string]int{}
|
||||||
currencies := []string{}
|
currencies := []string{}
|
||||||
|
seen := func(currency string) {
|
||||||
|
if _, ok := totals[currency]; !ok {
|
||||||
|
currencies = append(currencies, currency)
|
||||||
|
totals[currency] = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, account := range data.Accounts {
|
for _, account := range data.Accounts {
|
||||||
st := state(account.ID)
|
st := state(account.ID)
|
||||||
kind := account.Kind
|
kind := account.Kind
|
||||||
if kind == "" {
|
if kind == "" {
|
||||||
kind = domain.AccountCash
|
kind = domain.AccountCash
|
||||||
}
|
}
|
||||||
|
cash := st.cash + st.residual
|
||||||
entry := WealthAccount{
|
entry := WealthAccount{
|
||||||
AccountID: account.ID, DisplayName: account.DisplayName, Institution: account.Institution,
|
AccountID: account.ID, DisplayName: account.DisplayName, Institution: account.Institution,
|
||||||
Currency: account.Currency, Kind: kind, Active: account.Active,
|
Currency: account.Currency, Kind: kind, Active: account.Active,
|
||||||
Records: st.records, FirstBooking: st.first, LastBooking: st.last,
|
Records: st.records, FirstBooking: st.first, LastBooking: st.last,
|
||||||
Cash: domain.FormatMoney(st.cash), Flows: []WealthFlow{},
|
Cash: domain.FormatMoney(cash), Flows: []WealthFlow{},
|
||||||
Holdings: []WealthHolding{}, Checks: []WealthCheck{},
|
Holdings: []WealthHolding{}, Checks: []WealthCheck{},
|
||||||
}
|
}
|
||||||
|
// The start balance reads first, like the carried-over line on a paper
|
||||||
|
// statement, and keeps the invariant that the flows sum to the balance.
|
||||||
|
if st.anchored {
|
||||||
|
entry.Flows = append(entry.Flows, WealthFlow{
|
||||||
|
Event: "anchor", Label: "Start balance (before the recorded rows)",
|
||||||
|
Cash: domain.FormatMoney(st.residual),
|
||||||
|
})
|
||||||
|
}
|
||||||
for _, flow := range flowLabels {
|
for _, flow := range flowLabels {
|
||||||
if moved := st.flows[flow.event]; moved != nil {
|
if moved := st.flows[flow.event]; moved != nil {
|
||||||
entry.Flows = append(entry.Flows, WealthFlow{
|
entry.Flows = append(entry.Flows, WealthFlow{
|
||||||
@@ -308,10 +377,8 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, seen := totals[account.Currency]; !seen {
|
seen(account.Currency)
|
||||||
currencies = append(currencies, account.Currency)
|
totals[account.Currency] += cash
|
||||||
}
|
|
||||||
totals[account.Currency] += st.cash
|
|
||||||
positions, unpriced, stale := int64(0), 0, []string{}
|
positions, unpriced, stale := int64(0), 0, []string{}
|
||||||
for _, id := range st.order {
|
for _, id := range st.order {
|
||||||
held := st.holdings[id]
|
held := st.holdings[id]
|
||||||
@@ -350,7 +417,7 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
}
|
}
|
||||||
slices.SortFunc(entry.Holdings, func(x, y WealthHolding) int { return strings.Compare(x.Name, y.Name) })
|
slices.SortFunc(entry.Holdings, func(x, y WealthHolding) int { return strings.Compare(x.Name, y.Name) })
|
||||||
entry.Positions, entry.Unpriced = domain.FormatMoney(positions), unpriced
|
entry.Positions, entry.Unpriced = domain.FormatMoney(positions), unpriced
|
||||||
entry.Wealth = domain.FormatMoney(st.cash + positions)
|
entry.Wealth = domain.FormatMoney(cash + positions)
|
||||||
positionTotals[account.Currency] += positions
|
positionTotals[account.Currency] += positions
|
||||||
unpricedTotals[account.Currency] += unpriced
|
unpricedTotals[account.Currency] += unpriced
|
||||||
|
|
||||||
@@ -362,8 +429,15 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
} else {
|
} else {
|
||||||
check("Row arithmetic", "every record agrees with its own gross, fee, tax, quantity and price", false)
|
check("Row arithmetic", "every record agrees with its own gross, fee, tax, quantity and price", false)
|
||||||
}
|
}
|
||||||
|
if st.anchored {
|
||||||
|
check("Balance anchored", fmt.Sprintf("cash is the bank's own booked balance %s on %s plus every movement after that day; the start balance line, %s, is that figure less the movements booked through it", account.AnchorBalance, st.anchorDate, domain.FormatMoney(st.residual)), false)
|
||||||
|
} else if !account.Investing() && account.ExternalAccountID != "" {
|
||||||
|
check("Balance not anchored", "cash is the recorded movements only; the next successful synchronization captures the bank's booked balance and fixes the start balance", false)
|
||||||
|
}
|
||||||
if st.lowestCash < 0 {
|
if st.lowestCash < 0 {
|
||||||
check("Cash never negative", fmt.Sprintf("balance reached %s on %s, so the history is incomplete or a movement is misread", domain.FormatMoney(st.lowestCash), st.lowestCashDate), true)
|
check("Cash never negative", fmt.Sprintf("balance reached %s on %s, so the history is incomplete or a movement is misread", domain.FormatMoney(st.lowestCash), st.lowestCashDate), true)
|
||||||
|
} else if st.anchored {
|
||||||
|
check("Cash never negative", "the running balance stays at or above zero from the anchor day onward; earlier days are not judged against an incomplete window", false)
|
||||||
} else {
|
} else {
|
||||||
check("Cash never negative", "the running balance stays at or above zero throughout", false)
|
check("Cash never negative", "the running balance stays at or above zero throughout", false)
|
||||||
}
|
}
|
||||||
@@ -391,11 +465,27 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
}
|
}
|
||||||
report.Accounts = append(report.Accounts, entry)
|
report.Accounts = append(report.Accounts, entry)
|
||||||
}
|
}
|
||||||
|
// Hand-valued assets join the totals after the accounts: they belong to no
|
||||||
|
// account, and a currency held only in an asset still earns its own line.
|
||||||
|
for _, asset := range data.Assets {
|
||||||
|
value, err := asset.Value.Minor()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen(asset.Currency)
|
||||||
|
assetTotals[asset.Currency] += value
|
||||||
|
report.Assets = append(report.Assets, WealthAsset{
|
||||||
|
AssetID: asset.ID, Name: asset.Name, Kind: asset.Kind,
|
||||||
|
Currency: asset.Currency, Value: domain.FormatMoney(value), ValuedAt: asset.ValuedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
slices.SortStableFunc(report.Assets, func(x, y WealthAsset) int { return strings.Compare(x.Name, y.Name) })
|
||||||
for _, currency := range currencies {
|
for _, currency := range currencies {
|
||||||
report.Totals = append(report.Totals, WealthTotal{
|
report.Totals = append(report.Totals, WealthTotal{
|
||||||
Currency: currency, Cash: domain.FormatMoney(totals[currency]),
|
Currency: currency, Cash: domain.FormatMoney(totals[currency]),
|
||||||
Positions: domain.FormatMoney(positionTotals[currency]),
|
Positions: domain.FormatMoney(positionTotals[currency]),
|
||||||
Wealth: domain.FormatMoney(totals[currency] + positionTotals[currency]),
|
Assets: domain.FormatMoney(assetTotals[currency]),
|
||||||
|
Wealth: domain.FormatMoney(totals[currency] + positionTotals[currency] + assetTotals[currency]),
|
||||||
Unpriced: unpricedTotals[currency],
|
Unpriced: unpricedTotals[currency],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -381,3 +381,106 @@ func TestWealthValuesHoldingsAtTheirQuote(t *testing.T) {
|
|||||||
t.Error("no note about the holdings left out of the wealth figure")
|
t.Error("no note about the holdings left out of the wealth figure")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A wealth figure that ignores the house is not a wealth figure. A hand-valued
|
||||||
|
// asset joins its currency's total, a currency held only in an asset earns its
|
||||||
|
// own line, and a negative value records a liability that subtracts.
|
||||||
|
func TestWealthCountsHandValuedAssets(t *testing.T) {
|
||||||
|
data := domain.NewDataset()
|
||||||
|
data.Accounts = []domain.Account{{ID: "acc_main", DisplayName: "Main", Currency: "EUR", Active: true}}
|
||||||
|
f := domain.Facts{
|
||||||
|
ID: "tx_1", Source: "csv", AccountID: "acc_main", BookingDate: "2026-01-02",
|
||||||
|
Amount: "1000.00", Currency: "EUR", RawDescription: "salary", Fingerprint: "tx_1",
|
||||||
|
}
|
||||||
|
data.Transactions = []domain.Transaction{{Facts: f, Enrichment: domain.Fallback(f)}}
|
||||||
|
data.Assets = []domain.Asset{
|
||||||
|
{ID: "asset_house", Name: "House", Kind: "Real estate", Currency: "EUR", Value: "250000.00", ValuedAt: "2026-09-01"},
|
||||||
|
{ID: "asset_loan", Name: "Mortgage", Currency: "EUR", Value: "-150000.00", ValuedAt: "2026-09-01"},
|
||||||
|
{ID: "asset_cabin", Name: "Cabin", Currency: "USD", Value: "40000.00", ValuedAt: "2026-08-15"},
|
||||||
|
}
|
||||||
|
if err := domain.Validate(data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
report := WealthOf(data)
|
||||||
|
byCurrency := map[string]WealthTotal{}
|
||||||
|
for _, total := range report.Totals {
|
||||||
|
byCurrency[total.Currency] = total
|
||||||
|
}
|
||||||
|
if eur := byCurrency["EUR"]; eur.Cash != "1000.00" || eur.Assets != "100000.00" || eur.Wealth != "101000.00" {
|
||||||
|
t.Errorf("EUR total %+v; want cash 1000.00, assets 100000.00, wealth 101000.00", eur)
|
||||||
|
}
|
||||||
|
if usd, ok := byCurrency["USD"]; !ok || usd.Cash != "0.00" || usd.Assets != "40000.00" || usd.Wealth != "40000.00" {
|
||||||
|
t.Errorf("a currency held only in an asset earned no line of its own: %+v", byCurrency["USD"])
|
||||||
|
}
|
||||||
|
if len(report.Assets) != 3 || report.Assets[0].Name != "Cabin" || report.Assets[1].ValuedAt != "2026-09-01" {
|
||||||
|
t.Errorf("assets not echoed sorted by name with their dates: %+v", report.Assets)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A bank's date-windowed history starts mid-life, so an anchored account
|
||||||
|
// derives its start balance: the bank's booked figure on the anchor day less
|
||||||
|
// everything booked through it. The derived line keeps the flows summing to
|
||||||
|
// the balance, and the pre-anchor window is never judged as an overdraft —
|
||||||
|
// the history there is incomplete by definition.
|
||||||
|
func TestAnchoredAccountDerivesStartBalance(t *testing.T) {
|
||||||
|
data := domain.NewDataset()
|
||||||
|
data.Accounts = []domain.Account{
|
||||||
|
{ID: "acc_anchored", DisplayName: "Checking", Currency: "EUR", Active: true, ExternalAccountID: "uid_one", AnchorBalance: "2450.00", AnchorDate: "2026-09-10"},
|
||||||
|
{ID: "acc_plain", DisplayName: "Connected", Currency: "EUR", Active: true, ExternalAccountID: "uid_two"},
|
||||||
|
}
|
||||||
|
row := func(id, account, date string, amount domain.Money) domain.Transaction {
|
||||||
|
f := domain.Facts{ID: id, Source: "enablebanking", AccountID: account, BookingDate: date, Amount: amount, Currency: "EUR", RawDescription: id, Fingerprint: "fp_" + id}
|
||||||
|
return domain.Transaction{Facts: f, Enrichment: domain.Fallback(f)}
|
||||||
|
}
|
||||||
|
data.Transactions = []domain.Transaction{
|
||||||
|
// The recorded window alone would dip to −900 before the anchor day.
|
||||||
|
row("tx_pre", "acc_anchored", "2026-09-01", "-900.00"),
|
||||||
|
row("tx_on", "acc_anchored", "2026-09-10", "50.00"),
|
||||||
|
row("tx_post", "acc_anchored", "2026-09-12", "-100.00"),
|
||||||
|
row("tx_other", "acc_plain", "2026-09-12", "10.00"),
|
||||||
|
}
|
||||||
|
if err := domain.Validate(data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
report := WealthOf(data)
|
||||||
|
anchored := report.Accounts[0]
|
||||||
|
// 2450.00 on 2026-09-10 less the −850.00 booked through that day puts
|
||||||
|
// 3300.00 before the window; the balance is 2450.00 − 100.00 booked after.
|
||||||
|
if anchored.Cash != "2350.00" || anchored.Wealth != "2350.00" {
|
||||||
|
t.Errorf("anchored cash %s wealth %s, want 2350.00", anchored.Cash, anchored.Wealth)
|
||||||
|
}
|
||||||
|
if len(anchored.Flows) == 0 || anchored.Flows[0].Event != "anchor" || anchored.Flows[0].Cash != "3300.00" {
|
||||||
|
t.Errorf("start balance line missing or wrong: %+v", anchored.Flows)
|
||||||
|
}
|
||||||
|
total := int64(0)
|
||||||
|
for _, flow := range anchored.Flows {
|
||||||
|
cash, err := flow.Cash.Minor()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
total += cash
|
||||||
|
}
|
||||||
|
if domain.FormatMoney(total) != anchored.Cash {
|
||||||
|
t.Errorf("flows sum to %s, balance is %s", domain.FormatMoney(total), anchored.Cash)
|
||||||
|
}
|
||||||
|
checks := map[string]WealthCheck{}
|
||||||
|
for _, check := range anchored.Checks {
|
||||||
|
checks[check.Name] = check
|
||||||
|
}
|
||||||
|
if _, ok := checks["Balance anchored"]; !ok {
|
||||||
|
t.Errorf("no anchor note: %+v", anchored.Checks)
|
||||||
|
}
|
||||||
|
if check := checks["Cash never negative"]; check.Failed {
|
||||||
|
t.Errorf("pre-anchor window judged as an overdraft: %s", check.Detail)
|
||||||
|
}
|
||||||
|
note := false
|
||||||
|
for _, check := range report.Accounts[1].Checks {
|
||||||
|
note = note || check.Name == "Balance not anchored"
|
||||||
|
}
|
||||||
|
if !note {
|
||||||
|
t.Errorf("connected account without an anchor carries no note: %+v", report.Accounts[1].Checks)
|
||||||
|
}
|
||||||
|
if report.Totals[0].Cash != "2360.00" {
|
||||||
|
t.Errorf("total cash %s, want 2360.00", report.Totals[0].Cash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ func (c *Client) ClassifyBatch(ctx context.Context, rows []domain.Facts, data do
|
|||||||
payload.Transactions = append(payload.Transactions, row)
|
payload.Transactions = append(payload.Transactions, row)
|
||||||
similar.WriteString(f.RawDescription + " " + f.Counterparty + " ")
|
similar.WriteString(f.RawDescription + " " + f.Counterparty + " ")
|
||||||
}
|
}
|
||||||
payload.History = history(domain.Facts{RawDescription: similar.String()}, data, clean, 40)
|
payload.History = candidates.history(domain.Facts{RawDescription: similar.String()}, data, clean, 40)
|
||||||
payload.Categories = candidates.categories
|
payload.Categories = candidates.categories
|
||||||
payload.Tags = candidates.tags
|
payload.Tags = candidates.tags
|
||||||
payload.Merchants = candidates.merchants
|
payload.Merchants = candidates.merchants
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package classification
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -32,28 +31,34 @@ func TestBatchClassifiesEveryRowInOneRequest(t *testing.T) {
|
|||||||
calls := 0
|
calls := 0
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
calls++
|
calls++
|
||||||
var req struct {
|
prompt := decodeClassificationPrompt(t, r)
|
||||||
Messages []struct {
|
if len(prompt.Transactions) != 2 {
|
||||||
Content string `json:"content"`
|
t.Errorf("batch prompt missing transactions: %+v", prompt.Transactions)
|
||||||
} `json:"messages"`
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
}
|
|
||||||
if json.NewDecoder(r.Body).Decode(&req) != nil || len(req.Messages) != 2 {
|
|
||||||
w.WriteHeader(400)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var prompt struct {
|
category := categoryRefForPath(t, prompt.Categories, normalize(domain.CategoryPath(d, "cat_food")))
|
||||||
Transactions []struct{ Ref, Counterparty, Amount, Currency string } `json:"transactions"`
|
merchant, tag := "", ""
|
||||||
|
for _, candidate := range prompt.Merchants {
|
||||||
|
if candidate.Name == "coffee house" {
|
||||||
|
merchant = candidate.ID
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if json.Unmarshal([]byte(req.Messages[1].Content), &prompt) != nil || len(prompt.Transactions) != 2 {
|
for _, candidate := range prompt.Tags {
|
||||||
t.Errorf("batch prompt missing transactions: %s", req.Messages[1].Content)
|
if candidate.Name == "daily" {
|
||||||
|
tag = candidate.ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if merchant == "" || tag == "" {
|
||||||
|
t.Error("batch prompt lost Coffee House or Daily")
|
||||||
}
|
}
|
||||||
for _, row := range prompt.Transactions {
|
for _, row := range prompt.Transactions {
|
||||||
if row.Amount == "" || row.Currency != "EUR" {
|
if row.Amount == "" || row.Currency != "EUR" {
|
||||||
t.Errorf("row %s lost amount or currency: %+v", row.Ref, row)
|
t.Errorf("row %s lost amount or currency: %+v", row.Ref, row)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
reply(w, `{"transactions":[{"ref":"r1","merchant_id":"mer_coffee","new_merchant":null,"category_id":"cat_food","tag_ids":["tag_daily"],"confidence":"high"},`+
|
reply(w, `{"transactions":[{"ref":"`+prompt.Transactions[1].Ref+`","merchant_id":null,"new_merchant":"Kleins Backstube","category_id":"`+category+`","tag_ids":[],"confidence":"medium"},`+
|
||||||
`{"ref":"r2","merchant_id":null,"new_merchant":"Kleins Backstube","category_id":"cat_food","tag_ids":[],"confidence":"medium"}]}`)
|
`{"ref":"`+prompt.Transactions[0].Ref+`","merchant_id":"`+merchant+`","new_merchant":null,"category_id":"`+category+`","tag_ids":["`+tag+`"],"confidence":"high"}]}`)
|
||||||
})
|
})
|
||||||
results := c.ClassifyBatch(context.Background(), []domain.Facts{f1, f2}, d)
|
results := c.ClassifyBatch(context.Background(), []domain.Facts{f1, f2}, d)
|
||||||
if calls != 1 {
|
if calls != 1 {
|
||||||
@@ -71,6 +76,8 @@ func TestBatchClassifiesEveryRowInOneRequest(t *testing.T) {
|
|||||||
if second.NewMerchant == nil || second.NewMerchant.Name != "Kleins Backstube" ||
|
if second.NewMerchant == nil || second.NewMerchant.Name != "Kleins Backstube" ||
|
||||||
!reflect.DeepEqual(second.NewMerchant.Aliases, []string{"Kleins Backstube"}) ||
|
!reflect.DeepEqual(second.NewMerchant.Aliases, []string{"Kleins Backstube"}) ||
|
||||||
second.Enrichment.MerchantID != second.NewMerchant.ID ||
|
second.Enrichment.MerchantID != second.NewMerchant.ID ||
|
||||||
|
second.Enrichment.CategoryID != "cat_food" ||
|
||||||
|
len(second.Enrichment.TagIDs) != 0 ||
|
||||||
second.Enrichment.Classification.Confidence != "medium" {
|
second.Enrichment.Classification.Confidence != "medium" {
|
||||||
t.Fatalf("second row lost: %+v", second)
|
t.Fatalf("second row lost: %+v", second)
|
||||||
}
|
}
|
||||||
@@ -80,8 +87,10 @@ func TestBatchClassifiesEveryRowInOneRequest(t *testing.T) {
|
|||||||
func TestBatchIsolatesInvalidRows(t *testing.T) {
|
func TestBatchIsolatesInvalidRows(t *testing.T) {
|
||||||
f1, f2, d := batchRows()
|
f1, f2, d := batchRows()
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
reply(w, `{"transactions":[{"ref":"r1","merchant_id":null,"new_merchant":null,"category_id":"cat_food","tag_ids":[],"confidence":"high"},`+
|
prompt := decodeClassificationPrompt(t, r)
|
||||||
`{"ref":"r2","merchant_id":null,"new_merchant":null,"category_id":"cat_forged","tag_ids":[],"confidence":"high"}]}`)
|
category := categoryRefForPath(t, prompt.Categories, normalize(domain.CategoryPath(d, "cat_food")))
|
||||||
|
reply(w, `{"transactions":[{"ref":"`+prompt.Transactions[0].Ref+`","merchant_id":null,"new_merchant":null,"category_id":"`+category+`","tag_ids":[],"confidence":"high"},`+
|
||||||
|
`{"ref":"`+prompt.Transactions[1].Ref+`","merchant_id":null,"new_merchant":null,"category_id":"c999999","tag_ids":[],"confidence":"high"}]}`)
|
||||||
})
|
})
|
||||||
results := c.ClassifyBatch(context.Background(), []domain.Facts{f1, f2}, d)
|
results := c.ClassifyBatch(context.Background(), []domain.Facts{f1, f2}, d)
|
||||||
if results[0].Err != nil || results[0].Proposal.Enrichment.CategoryID != "cat_food" {
|
if results[0].Err != nil || results[0].Proposal.Enrichment.CategoryID != "cat_food" {
|
||||||
@@ -96,8 +105,10 @@ func TestBatchIsolatesInvalidRows(t *testing.T) {
|
|||||||
func TestBatchSharesOneMintedMerchant(t *testing.T) {
|
func TestBatchSharesOneMintedMerchant(t *testing.T) {
|
||||||
f1, f2, d := batchRows()
|
f1, f2, d := batchRows()
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
reply(w, `{"transactions":[{"ref":"r1","merchant_id":null,"new_merchant":"REWE","category_id":"cat_food","tag_ids":[],"confidence":"high"},`+
|
prompt := decodeClassificationPrompt(t, r)
|
||||||
`{"ref":"r2","merchant_id":null,"new_merchant":"REWE","category_id":"cat_food","tag_ids":[],"confidence":"high"}]}`)
|
category := categoryRefForPath(t, prompt.Categories, normalize(domain.CategoryPath(d, "cat_food")))
|
||||||
|
reply(w, `{"transactions":[{"ref":"`+prompt.Transactions[0].Ref+`","merchant_id":null,"new_merchant":"REWE","category_id":"`+category+`","tag_ids":[],"confidence":"high"},`+
|
||||||
|
`{"ref":"`+prompt.Transactions[1].Ref+`","merchant_id":null,"new_merchant":"REWE","category_id":"`+category+`","tag_ids":[],"confidence":"high"}]}`)
|
||||||
})
|
})
|
||||||
results := c.ClassifyBatch(context.Background(), []domain.Facts{f1, f2}, d)
|
results := c.ClassifyBatch(context.Background(), []domain.Facts{f1, f2}, d)
|
||||||
if results[0].Err != nil || results[1].Err != nil {
|
if results[0].Err != nil || results[1].Err != nil {
|
||||||
@@ -144,19 +155,8 @@ func TestBatchSplitsOnProviderSchemaRejection(t *testing.T) {
|
|||||||
calls, oversized := 0, 0
|
calls, oversized := 0, 0
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
calls++
|
calls++
|
||||||
var req struct {
|
prompt := decodeClassificationPrompt(t, r)
|
||||||
Messages []struct {
|
category := categoryRefForPath(t, prompt.Categories, normalize(domain.CategoryPath(d, "cat_food")))
|
||||||
Content string `json:"content"`
|
|
||||||
} `json:"messages"`
|
|
||||||
}
|
|
||||||
if json.NewDecoder(r.Body).Decode(&req) != nil {
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var prompt struct {
|
|
||||||
Transactions []struct{ Ref string } `json:"transactions"`
|
|
||||||
}
|
|
||||||
_ = json.Unmarshal([]byte(req.Messages[1].Content), &prompt)
|
|
||||||
if len(prompt.Transactions) > 2 {
|
if len(prompt.Transactions) > 2 {
|
||||||
oversized++
|
oversized++
|
||||||
w.WriteHeader(400)
|
w.WriteHeader(400)
|
||||||
@@ -164,7 +164,7 @@ func TestBatchSplitsOnProviderSchemaRejection(t *testing.T) {
|
|||||||
}
|
}
|
||||||
answers := make([]string, 0, len(prompt.Transactions))
|
answers := make([]string, 0, len(prompt.Transactions))
|
||||||
for _, row := range prompt.Transactions {
|
for _, row := range prompt.Transactions {
|
||||||
answers = append(answers, `{"ref":"`+row.Ref+`","merchant_id":null,"new_merchant":null,"category_id":"cat_food","tag_ids":[],"confidence":"high"}`)
|
answers = append(answers, `{"ref":"`+row.Ref+`","merchant_id":null,"new_merchant":null,"category_id":"`+category+`","tag_ids":[],"confidence":"high"}`)
|
||||||
}
|
}
|
||||||
reply(w, `{"transactions":[`+strings.Join(answers, ",")+`]}`)
|
reply(w, `{"transactions":[`+strings.Join(answers, ",")+`]}`)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package classification
|
|||||||
import (
|
import (
|
||||||
"slices"
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
@@ -150,8 +151,6 @@ type merchantPrompt struct {
|
|||||||
UsualCategory string `json:"usual_category,omitempty"`
|
UsualCategory string `json:"usual_category,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// candidate is the historical merchant prompt shape used by older callers.
|
|
||||||
type candidate = merchantPrompt
|
|
||||||
type promptHistory struct {
|
type promptHistory struct {
|
||||||
Date string `json:"date"`
|
Date string `json:"date"`
|
||||||
Amount string `json:"amount"`
|
Amount string `json:"amount"`
|
||||||
@@ -166,12 +165,15 @@ type promptHistory struct {
|
|||||||
Source string `json:"source"`
|
Source string `json:"source"`
|
||||||
}
|
}
|
||||||
type candidateSet struct {
|
type candidateSet struct {
|
||||||
categories []categoryPrompt
|
categories []categoryPrompt
|
||||||
tags []tagPrompt
|
tags []tagPrompt
|
||||||
merchants []merchantPrompt
|
merchants []merchantPrompt
|
||||||
categoryIDs map[string]string
|
categoryIDs map[string]string
|
||||||
tagIDs map[string]string
|
tagIDs map[string]string
|
||||||
merchantIDs map[string]string
|
merchantIDs map[string]string
|
||||||
|
categoryRefs map[string]string
|
||||||
|
tagRefs map[string]string
|
||||||
|
merchantRefs map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func similarity(description, name string) int {
|
func similarity(description, name string) int {
|
||||||
@@ -194,18 +196,20 @@ func similarity(description, name string) int {
|
|||||||
return score
|
return score
|
||||||
}
|
}
|
||||||
|
|
||||||
// retrieve emits every registry entry with its real id. The legacy cleaner
|
// retrieve offers every eligible registry entry under a short request-local
|
||||||
// arguments remain in the signature because CSV/classification fixtures use
|
// reference. Names and paths retain their meaning; canonical IDs stay local.
|
||||||
// this helper directly; ranking and bounding are intentionally gone.
|
|
||||||
func retrieve(_ string, kind string, data domain.Dataset, clean, merchantClean func(string) string) candidateSet {
|
func retrieve(_ string, kind string, data domain.Dataset, clean, merchantClean func(string) string) candidateSet {
|
||||||
parents := map[string]bool{}
|
parents := map[string]bool{}
|
||||||
for _, cat := range data.Categories {
|
for _, cat := range data.Categories {
|
||||||
parents[cat.ParentID] = true
|
parents[cat.ParentID] = true
|
||||||
}
|
}
|
||||||
set := candidateSet{
|
set := candidateSet{
|
||||||
categoryIDs: map[string]string{},
|
categoryIDs: map[string]string{},
|
||||||
tagIDs: map[string]string{},
|
tagIDs: map[string]string{},
|
||||||
merchantIDs: map[string]string{},
|
merchantIDs: map[string]string{},
|
||||||
|
categoryRefs: map[string]string{},
|
||||||
|
tagRefs: map[string]string{},
|
||||||
|
merchantRefs: map[string]string{},
|
||||||
}
|
}
|
||||||
for _, cat := range data.Categories {
|
for _, cat := range data.Categories {
|
||||||
if cat.Kind != kind || parents[cat.ID] {
|
if cat.Kind != kind || parents[cat.ID] {
|
||||||
@@ -216,19 +220,31 @@ func retrieve(_ string, kind string, data domain.Dataset, clean, merchantClean f
|
|||||||
path = clean(path)
|
path = clean(path)
|
||||||
}
|
}
|
||||||
set.categories = append(set.categories, categoryPrompt{ID: cat.ID, Path: path, Kind: cat.Kind, Hint: cleanText(clean, cat.Hint)})
|
set.categories = append(set.categories, categoryPrompt{ID: cat.ID, Path: path, Kind: cat.Kind, Hint: cleanText(clean, cat.Hint)})
|
||||||
set.categoryIDs[cat.ID] = cat.ID
|
|
||||||
}
|
}
|
||||||
sort.Slice(set.categories, func(i, j int) bool {
|
sort.Slice(set.categories, func(i, j int) bool {
|
||||||
return set.categories[i].Path < set.categories[j].Path || set.categories[i].Path == set.categories[j].Path && set.categories[i].ID < set.categories[j].ID
|
return set.categories[i].Path < set.categories[j].Path || set.categories[i].Path == set.categories[j].Path && set.categories[i].ID < set.categories[j].ID
|
||||||
})
|
})
|
||||||
|
for i := range set.categories {
|
||||||
|
category := &set.categories[i]
|
||||||
|
ref := "c" + strconv.Itoa(i+1)
|
||||||
|
set.categoryIDs[ref] = category.ID
|
||||||
|
set.categoryRefs[category.ID] = ref
|
||||||
|
category.ID = ref
|
||||||
|
}
|
||||||
for _, tag := range data.Tags {
|
for _, tag := range data.Tags {
|
||||||
name := cleanText(clean, tag.Name)
|
name := cleanText(clean, tag.Name)
|
||||||
set.tags = append(set.tags, tagPrompt{ID: tag.ID, Name: name, Hint: cleanText(clean, tag.Hint)})
|
set.tags = append(set.tags, tagPrompt{ID: tag.ID, Name: name, Hint: cleanText(clean, tag.Hint)})
|
||||||
set.tagIDs[tag.ID] = tag.ID
|
|
||||||
}
|
}
|
||||||
sort.Slice(set.tags, func(i, j int) bool {
|
sort.Slice(set.tags, func(i, j int) bool {
|
||||||
return set.tags[i].Name < set.tags[j].Name || set.tags[i].Name == set.tags[j].Name && set.tags[i].ID < set.tags[j].ID
|
return set.tags[i].Name < set.tags[j].Name || set.tags[i].Name == set.tags[j].Name && set.tags[i].ID < set.tags[j].ID
|
||||||
})
|
})
|
||||||
|
for i := range set.tags {
|
||||||
|
tag := &set.tags[i]
|
||||||
|
ref := "t" + strconv.Itoa(i+1)
|
||||||
|
set.tagIDs[ref] = tag.ID
|
||||||
|
set.tagRefs[tag.ID] = ref
|
||||||
|
tag.ID = ref
|
||||||
|
}
|
||||||
usual := map[string]string{}
|
usual := map[string]string{}
|
||||||
counts := map[string]map[string]int{}
|
counts := map[string]map[string]int{}
|
||||||
for _, tx := range data.Transactions {
|
for _, tx := range data.Transactions {
|
||||||
@@ -263,13 +279,19 @@ func retrieve(_ string, kind string, data domain.Dataset, clean, merchantClean f
|
|||||||
}
|
}
|
||||||
set.merchants = append(set.merchants, merchantPrompt{
|
set.merchants = append(set.merchants, merchantPrompt{
|
||||||
ID: merchant.ID, Name: name, Aliases: aliases,
|
ID: merchant.ID, Name: name, Aliases: aliases,
|
||||||
UsualCategory: usualCategory,
|
UsualCategory: set.categoryRefs[usualCategory],
|
||||||
})
|
})
|
||||||
set.merchantIDs[merchant.ID] = merchant.ID
|
|
||||||
}
|
}
|
||||||
sort.Slice(set.merchants, func(i, j int) bool {
|
sort.Slice(set.merchants, func(i, j int) bool {
|
||||||
return set.merchants[i].Name < set.merchants[j].Name || set.merchants[i].Name == set.merchants[j].Name && set.merchants[i].ID < set.merchants[j].ID
|
return set.merchants[i].Name < set.merchants[j].Name || set.merchants[i].Name == set.merchants[j].Name && set.merchants[i].ID < set.merchants[j].ID
|
||||||
})
|
})
|
||||||
|
for i := range set.merchants {
|
||||||
|
merchant := &set.merchants[i]
|
||||||
|
ref := "m" + strconv.Itoa(i+1)
|
||||||
|
set.merchantIDs[ref] = merchant.ID
|
||||||
|
set.merchantRefs[merchant.ID] = ref
|
||||||
|
merchant.ID = ref
|
||||||
|
}
|
||||||
return set
|
return set
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -314,16 +336,12 @@ func candidateIDs(values []categoryPrompt) []string {
|
|||||||
return ids
|
return ids
|
||||||
}
|
}
|
||||||
|
|
||||||
func answerSchema(d domain.Dataset, kind string) map[string]any {
|
// history selects precedent whose category is offered in this request: the
|
||||||
return retrieve("", kind, d, nil, nil).schema()
|
// nearest rows by word overlap, filled out with the most recent. The user's
|
||||||
}
|
// own decisions — manual edits and locally applied merchant rules — outrank
|
||||||
|
// rows the model classified itself. References use the same mapping as the
|
||||||
// history selects precedent for the prompt: the nearest rows by word overlap,
|
// candidate lists and response schema.
|
||||||
// filled out with the most recent. The user's own decisions — manual edits
|
func (c candidateSet) history(f domain.Facts, d domain.Dataset, clean func(string) string, limit int) []promptHistory {
|
||||||
// and locally applied merchant rules — outrank rows the model classified
|
|
||||||
// itself, so one correction beats any number of uncorrected AI answers for
|
|
||||||
// the same payee.
|
|
||||||
func history(f domain.Facts, d domain.Dataset, clean func(string) string, limit int) []promptHistory {
|
|
||||||
type row struct {
|
type row struct {
|
||||||
tx domain.Transaction
|
tx domain.Transaction
|
||||||
score int
|
score int
|
||||||
@@ -332,7 +350,7 @@ func history(f domain.Facts, d domain.Dataset, clean func(string) string, limit
|
|||||||
rows := []row{}
|
rows := []row{}
|
||||||
for _, tx := range d.Transactions {
|
for _, tx := range d.Transactions {
|
||||||
e := tx.Enrichment
|
e := tx.Enrichment
|
||||||
if tx.Facts.ID == f.ID || e.Kind == "transfer" || e.CategoryID == "" || e.CategoryID == domain.ExpenseFallback || e.CategoryID == domain.IncomeFallback {
|
if tx.Facts.ID == f.ID || e.Kind == "transfer" || c.categoryRefs[e.CategoryID] == "" || e.CategoryID == domain.ExpenseFallback || e.CategoryID == domain.IncomeFallback {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
source := tx.Enrichment.Classification.Source
|
source := tx.Enrichment.Classification.Source
|
||||||
@@ -382,9 +400,11 @@ func history(f domain.Facts, d domain.Dataset, clean func(string) string, limit
|
|||||||
}
|
}
|
||||||
out := make([]promptHistory, 0, len(rows))
|
out := make([]promptHistory, 0, len(rows))
|
||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
tags := row.tx.Enrichment.TagIDs
|
tags := make([]string, 0, len(row.tx.Enrichment.TagIDs))
|
||||||
if tags == nil {
|
for _, id := range row.tx.Enrichment.TagIDs {
|
||||||
tags = []string{}
|
if ref := c.tagRefs[id]; ref != "" {
|
||||||
|
tags = append(tags, ref)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
source := "ai"
|
source := "ai"
|
||||||
if row.user {
|
if row.user {
|
||||||
@@ -393,8 +413,8 @@ func history(f domain.Facts, d domain.Dataset, clean func(string) string, limit
|
|||||||
out = append(out, promptHistory{
|
out = append(out, promptHistory{
|
||||||
Date: row.tx.Facts.BookingDate, Amount: string(row.tx.Facts.Amount),
|
Date: row.tx.Facts.BookingDate, Amount: string(row.tx.Facts.Amount),
|
||||||
Description: clean(row.tx.Facts.RawDescription), Counterparty: clean(row.tx.Facts.Counterparty),
|
Description: clean(row.tx.Facts.RawDescription), Counterparty: clean(row.tx.Facts.Counterparty),
|
||||||
CategoryID: row.tx.Enrichment.CategoryID, MerchantID: row.tx.Enrichment.MerchantID,
|
CategoryID: c.categoryRefs[row.tx.Enrichment.CategoryID], MerchantID: c.merchantRefs[row.tx.Enrichment.MerchantID],
|
||||||
TagIDs: append([]string{}, tags...),
|
TagIDs: tags,
|
||||||
Source: source,
|
Source: source,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"finance-duck/internal/domain"
|
"finance-duck/internal/domain"
|
||||||
@@ -220,7 +221,7 @@ func (c *Client) Classify(ctx context.Context, facts domain.Facts, data domain.D
|
|||||||
userPayload.Transaction.Counterparty = clean(facts.Counterparty)
|
userPayload.Transaction.Counterparty = clean(facts.Counterparty)
|
||||||
userPayload.Transaction.Account.Institution = clean(institution)
|
userPayload.Transaction.Account.Institution = clean(institution)
|
||||||
userPayload.Transaction.Account.Currency = facts.Currency
|
userPayload.Transaction.Account.Currency = facts.Currency
|
||||||
userPayload.History = history(facts, data, clean, 40)
|
userPayload.History = candidates.history(facts, data, clean, 40)
|
||||||
userPayload.Categories = candidates.categories
|
userPayload.Categories = candidates.categories
|
||||||
userPayload.Tags = candidates.tags
|
userPayload.Tags = candidates.tags
|
||||||
userPayload.Merchants = candidates.merchants
|
userPayload.Merchants = candidates.merchants
|
||||||
@@ -251,6 +252,13 @@ func (c *Client) Classify(ctx context.Context, facts domain.Facts, data domain.D
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hasHiddenRunes reports control or format code points — bidi overrides,
|
||||||
|
// zero-width characters — that would let model-supplied text spoof or
|
||||||
|
// reorder review UI. Legitimate payee names never need them.
|
||||||
|
func hasHiddenRunes(s string) bool {
|
||||||
|
return strings.ContainsFunc(s, func(r rune) bool { return unicode.IsControl(r) || unicode.Is(unicode.Cf, r) })
|
||||||
|
}
|
||||||
|
|
||||||
// resolveAnswer maps one schema-valid provider answer onto enrichment,
|
// resolveAnswer maps one schema-valid provider answer onto enrichment,
|
||||||
// revalidating every id against the local registry. proposed collects newly
|
// revalidating every id against the local registry. proposed collects newly
|
||||||
// minted merchants by normalized name so several rows resolved against the
|
// minted merchants by normalized name so several rows resolved against the
|
||||||
@@ -280,11 +288,12 @@ func resolveAnswer(answer answer, facts domain.Facts, data domain.Dataset, candi
|
|||||||
}
|
}
|
||||||
if answer.NewMerchant != nil {
|
if answer.NewMerchant != nil {
|
||||||
name := strings.Join(strings.Fields(*answer.NewMerchant), " ")
|
name := strings.Join(strings.Fields(*answer.NewMerchant), " ")
|
||||||
// An identifier-shaped or oversized name is dropped, never stored, but
|
// An identifier-shaped, oversized or hidden-rune name is dropped,
|
||||||
// the row keeps its independently enum-validated category and tags: a
|
// never stored, but the row keeps its independently enum-validated
|
||||||
// legitimate payee whose spelling trips the redactor (observed in the
|
// category and tags: a legitimate payee whose spelling trips the
|
||||||
// field) must not lose its whole classification.
|
// redactor (observed in the field) must not lose its whole
|
||||||
if !utf8.ValidString(name) || utf8.RuneCountInString(name) > 100 || normalize(name) == "" || normalize(clean(name)) != normalize(name) {
|
// classification.
|
||||||
|
if !utf8.ValidString(name) || utf8.RuneCountInString(name) > 100 || normalize(name) == "" || normalize(clean(name)) != normalize(name) || hasHiddenRunes(name) {
|
||||||
// no merchant
|
// no merchant
|
||||||
} else if existing := duplicateMerchant(name, data.Merchants); existing != nil {
|
} else if existing := duplicateMerchant(name, data.Merchants); existing != nil {
|
||||||
e.MerchantID = existing.ID
|
e.MerchantID = existing.ID
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ func fixture() (domain.Facts, domain.Dataset) {
|
|||||||
return f, d
|
return f, d
|
||||||
}
|
}
|
||||||
|
|
||||||
const validAnswer = `{"merchant_id":null,"new_merchant":null,"category_id":"cat_food","tag_ids":[],"confidence":"medium"}`
|
const validAnswer = `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":"medium"}`
|
||||||
|
|
||||||
func reply(w http.ResponseWriter, content string) {
|
func reply(w http.ResponseWriter, content string) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
@@ -44,6 +44,39 @@ func mockClient(t *testing.T, handler http.HandlerFunc) *Client {
|
|||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type classificationPrompt struct {
|
||||||
|
Categories []categoryPrompt `json:"categories"`
|
||||||
|
Tags []tagPrompt `json:"tags"`
|
||||||
|
Merchants []merchantPrompt `json:"merchants"`
|
||||||
|
History []promptHistory `json:"history"`
|
||||||
|
Transactions []struct {
|
||||||
|
Ref string `json:"ref"`
|
||||||
|
Counterparty string `json:"counterparty"`
|
||||||
|
Amount string `json:"amount"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
} `json:"transactions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeClassificationPrompt(t *testing.T, r *http.Request) classificationPrompt {
|
||||||
|
t.Helper()
|
||||||
|
var req struct {
|
||||||
|
Messages []struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
} `json:"messages"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(req.Messages) != 2 {
|
||||||
|
t.Fatalf("expected system and user messages, got %d", len(req.Messages))
|
||||||
|
}
|
||||||
|
var prompt classificationPrompt
|
||||||
|
if err := json.Unmarshal([]byte(req.Messages[1].Content), &prompt); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return prompt
|
||||||
|
}
|
||||||
|
|
||||||
func TestExplicitDefaultsAreOptInAndBypassAI(t *testing.T) {
|
func TestExplicitDefaultsAreOptInAndBypassAI(t *testing.T) {
|
||||||
f, d := fixture()
|
f, d := fixture()
|
||||||
d.Merchants[0].UseDefaults = true
|
d.Merchants[0].UseDefaults = true
|
||||||
@@ -72,7 +105,22 @@ func TestForceAIOverridesRuleWithoutChangingKind(t *testing.T) {
|
|||||||
f, d := fixture()
|
f, d := fixture()
|
||||||
d.Merchants[0].UseDefaults = true
|
d.Merchants[0].UseDefaults = true
|
||||||
calls := 0
|
calls := 0
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) { calls++; reply(w, validAnswer) })
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls++
|
||||||
|
prompt := decodeClassificationPrompt(t, r)
|
||||||
|
// Food is an expense-only choice; do not reuse c1 after the request
|
||||||
|
// switches to income, where that reference names a different category.
|
||||||
|
categoryID := "c999"
|
||||||
|
for _, category := range prompt.Categories {
|
||||||
|
if category.Path == normalize(domain.CategoryPath(d, "cat_food")) {
|
||||||
|
categoryID = category.ID
|
||||||
|
}
|
||||||
|
if calls == 2 && category.Kind != "income" {
|
||||||
|
t.Errorf("income request offered an expense category: %+v", category)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reply(w, fmt.Sprintf(`{"merchant_id":null,"new_merchant":null,"category_id":%q,"tag_ids":[],"confidence":"medium"}`, categoryID))
|
||||||
|
})
|
||||||
p, err := c.Classify(context.Background(), f, d, true)
|
p, err := c.Classify(context.Background(), f, d, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -82,7 +130,7 @@ func TestForceAIOverridesRuleWithoutChangingKind(t *testing.T) {
|
|||||||
}
|
}
|
||||||
f.Amount = "918.27"
|
f.Amount = "918.27"
|
||||||
p, err = c.Classify(context.Background(), f, d, true)
|
p, err = c.Classify(context.Background(), f, d, true)
|
||||||
if err == nil || p.Enrichment.Kind != "income" || p.Enrichment.CategoryID != domain.IncomeFallback {
|
if err == nil || calls != 2 || p.Enrichment.Kind != "income" || p.Enrichment.CategoryID != domain.IncomeFallback {
|
||||||
t.Fatalf("income sign: %+v %v", p, err)
|
t.Fatalf("income sign: %+v %v", p, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -117,21 +165,24 @@ func TestTransferNeverCallsAIOrAliases(t *testing.T) {
|
|||||||
|
|
||||||
func TestInvalidModelOutputsFailClosed(t *testing.T) {
|
func TestInvalidModelOutputsFailClosed(t *testing.T) {
|
||||||
cases := map[string]string{
|
cases := map[string]string{
|
||||||
"unknown key": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":0.9}`,
|
"unknown key": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":"high","unexpected":true}`,
|
||||||
"change kind": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":[],"kind":"transfer"}`,
|
"change kind": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":"high","kind":"transfer"}`,
|
||||||
"missing field": `{"merchant_id":null,"category_id":"c1","tag_ids":[]}`,
|
"missing field": `{"merchant_id":null,"category_id":"c1","tag_ids":[],"confidence":"high"}`,
|
||||||
"duplicate key": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","category_id":"c2","tag_ids":[]}`,
|
"duplicate key": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","category_id":"c2","tag_ids":[],"confidence":"high"}`,
|
||||||
"case folded key": `{"Merchant_ID":null,"new_merchant":null,"category_id":"c1","tag_ids":[]}`,
|
"case folded key": `{"Merchant_ID":null,"new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":"high"}`,
|
||||||
"unknown category": `{"merchant_id":null,"new_merchant":null,"category_id":"cat_invented","tag_ids":[]}`,
|
"unknown category": `{"merchant_id":null,"new_merchant":null,"category_id":"c999","tag_ids":[],"confidence":"high"}`,
|
||||||
"real ID not offered": `{"merchant_id":null,"new_merchant":null,"category_id":"cat_food","tag_ids":[]}`,
|
"canonical category": `{"merchant_id":null,"new_merchant":null,"category_id":"cat_food","tag_ids":[],"confidence":"high"}`,
|
||||||
"unknown tag": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":["t999"]}`,
|
"unknown tag": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":["t999"],"confidence":"high"}`,
|
||||||
"duplicate tags": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":["t1","t1"]}`,
|
"canonical tag": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":["tag_daily"],"confidence":"high"}`,
|
||||||
"null tags": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":null}`,
|
"duplicate tags": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":["t1","t1"],"confidence":"high"}`,
|
||||||
"null tag member": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":[null]}`,
|
"null tags": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":null,"confidence":"high"}`,
|
||||||
"unknown merchant": `{"merchant_id":"m999","new_merchant":null,"category_id":"c1","tag_ids":[]}`,
|
"null tag member": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":[null],"confidence":"high"}`,
|
||||||
"both merchant modes": `{"merchant_id":"m1","new_merchant":"Coffee","category_id":"c1","tag_ids":[]}`,
|
"unknown merchant": `{"merchant_id":"m999","new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":"high"}`,
|
||||||
"blank proposal": `{"merchant_id":null,"new_merchant":" ","category_id":"c1","tag_ids":[]}`,
|
"canonical merchant": `{"merchant_id":"mer_coffee","new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":"high"}`,
|
||||||
"wrong scalar": `{"merchant_id":23,"new_merchant":null,"category_id":"c1","tag_ids":[]}`,
|
"both merchant modes": `{"merchant_id":"m1","new_merchant":"Coffee","category_id":"c1","tag_ids":[],"confidence":"high"}`,
|
||||||
|
"blank proposal": `{"merchant_id":null,"new_merchant":" ","category_id":"c1","tag_ids":[],"confidence":"high"}`,
|
||||||
|
"wrong scalar": `{"merchant_id":23,"new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":"high"}`,
|
||||||
|
"numeric confidence": `{"merchant_id":null,"new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":0.9}`,
|
||||||
"trailing JSON": validAnswer + ` {}`,
|
"trailing JSON": validAnswer + ` {}`,
|
||||||
"markdown": "```json\n" + validAnswer + "\n```",
|
"markdown": "```json\n" + validAnswer + "\n```",
|
||||||
"array": "[" + validAnswer + "]",
|
"array": "[" + validAnswer + "]",
|
||||||
@@ -157,9 +208,9 @@ func TestMerchantSelectionAndLocalProposal(t *testing.T) {
|
|||||||
name, content, merchant string
|
name, content, merchant string
|
||||||
new bool
|
new bool
|
||||||
}{
|
}{
|
||||||
{"existing", `{"merchant_id":"mer_coffee","new_merchant":null,"category_id":"cat_food","tag_ids":["tag_daily"],"confidence":"high"}`, "mer_coffee", false},
|
{"existing", `{"merchant_id":"m1","new_merchant":null,"category_id":"c1","tag_ids":["t1"],"confidence":"high"}`, "mer_coffee", false},
|
||||||
{"duplicate alias", `{"merchant_id":null,"new_merchant":"COFFEE-house","category_id":"cat_food","tag_ids":["tag_daily"],"confidence":"high"}`, "mer_coffee", false},
|
{"duplicate alias", `{"merchant_id":null,"new_merchant":"COFFEE-house","category_id":"c1","tag_ids":["t1"],"confidence":"high"}`, "mer_coffee", false},
|
||||||
{"new", `{"merchant_id":null,"new_merchant":"Bakery Lane","category_id":"cat_food","tag_ids":["tag_daily"],"confidence":"high"}`, "", true},
|
{"new", `{"merchant_id":null,"new_merchant":"Bakery Lane","category_id":"c1","tag_ids":["t1"],"confidence":"high"}`, "", true},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
@@ -216,18 +267,14 @@ func TestIdentifierOnlyPromptRedactionAndRouting(t *testing.T) {
|
|||||||
if len(messages) != 2 {
|
if len(messages) != 2 {
|
||||||
t.Fatal("unexpected messages")
|
t.Fatal("unexpected messages")
|
||||||
}
|
}
|
||||||
var prompt struct {
|
wire, err := json.Marshal(captured)
|
||||||
Transaction map[string]any `json:"transaction"`
|
if err != nil {
|
||||||
History []any `json:"history"`
|
|
||||||
Categories []any `json:"categories"`
|
|
||||||
Tags []any `json:"tags"`
|
|
||||||
Merchants []any `json:"merchants"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal([]byte(messages[1].Content), &prompt); err != nil {
|
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(prompt.Transaction) == 0 || len(prompt.Categories) == 0 || len(prompt.Merchants) == 0 {
|
for _, canonicalID := range []string{"cat_food", "cat_expenses", "cat_income", "mer_coffee", "tag_daily"} {
|
||||||
t.Fatal("complete structured prompt missing")
|
if strings.Contains(string(wire), canonicalID) {
|
||||||
|
t.Errorf("request or response schema exposed canonical ID %q", canonicalID)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
lower := strings.ToLower(messages[1].Content)
|
lower := strings.ToLower(messages[1].Content)
|
||||||
for _, secret := range []string{"private_external", "private_fingerprint", "tx_private", "account_private", "ext_local_secret", "private_source", "personal checking", "550e8400", "cobadeff", "secretpayment", "example.com", "alice privateperson", "de89370400440532013000", "de44500105175407324931"} {
|
for _, secret := range []string{"private_external", "private_fingerprint", "tx_private", "account_private", "ext_local_secret", "private_source", "personal checking", "550e8400", "cobadeff", "secretpayment", "example.com", "alice privateperson", "de89370400440532013000", "de44500105175407324931"} {
|
||||||
@@ -296,11 +343,11 @@ func TestTransactionAmountAndCounterpartyAreSent(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestUnsafeMerchantProposalDroppedWithoutLosingClassification(t *testing.T) {
|
func TestUnsafeMerchantProposalDroppedWithoutLosingClassification(t *testing.T) {
|
||||||
for _, name := range []string{"Alice Privateperson", "DE89370400440532013000", "Bank 123456789", "reference secretpayment", strings.Repeat("x", 101)} {
|
for _, name := range []string{"Alice Privateperson", "DE89370400440532013000", "Bank 123456789", "reference secretpayment", strings.Repeat("x", 101), "Rent \u202Edeifirev \u2713", "zero\u200Bwidth"} {
|
||||||
t.Run(name, func(t *testing.T) {
|
t.Run(name, func(t *testing.T) {
|
||||||
f, d := fixture()
|
f, d := fixture()
|
||||||
f.Counterparty = "Alice Privateperson"
|
f.Counterparty = "Alice Privateperson"
|
||||||
answer, _ := json.Marshal(map[string]any{"merchant_id": nil, "new_merchant": name, "category_id": "cat_food", "tag_ids": []string{}, "confidence": "high"})
|
answer, _ := json.Marshal(map[string]any{"merchant_id": nil, "new_merchant": name, "category_id": "c1", "tag_ids": []string{}, "confidence": "high"})
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) { reply(w, string(answer)) })
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) { reply(w, string(answer)) })
|
||||||
c.PrivateNames = []string{"Alice Privateperson"}
|
c.PrivateNames = []string{"Alice Privateperson"}
|
||||||
p, err := c.Classify(context.Background(), f, d, true)
|
p, err := c.Classify(context.Background(), f, d, true)
|
||||||
@@ -410,33 +457,67 @@ func TestCompleteRegistryPayloadAndGlobalDuplicateDetection(t *testing.T) {
|
|||||||
d.Tags = append(d.Tags, domain.Tag{ID: fmt.Sprintf("tag_%02d", i), Name: fmt.Sprintf("Tag %02d", i)})
|
d.Tags = append(d.Tags, domain.Tag{ID: fmt.Sprintf("tag_%02d", i), Name: fmt.Sprintf("Tag %02d", i)})
|
||||||
d.Categories = append(d.Categories, domain.Category{ID: fmt.Sprintf("cat_%02d", i), Name: fmt.Sprintf("Category %02d", i), Kind: "expense", ParentID: "cat_expenses"})
|
d.Categories = append(d.Categories, domain.Category{ID: fmt.Sprintf("cat_%02d", i), Name: fmt.Sprintf("Category %02d", i), Kind: "expense", ParentID: "cat_expenses"})
|
||||||
}
|
}
|
||||||
d.Merchants[34].Name = "Distant Bakery"
|
d.Merchants[34].Name = "Z Distant Bakery"
|
||||||
set := retrieve(f.RawDescription, "expense", d, redactor(d, f, nil), redactor(d, f, nil))
|
|
||||||
if len(set.merchantIDs) != 35 || len(set.tags) != 36 {
|
|
||||||
t.Fatalf("complete registry omitted entries: merchants=%d tags=%d", len(set.merchantIDs), len(set.tags))
|
|
||||||
}
|
|
||||||
if set.merchantIDs["mer_34"] != "mer_34" ||
|
|
||||||
set.tagIDs["tag_34"] != "tag_34" ||
|
|
||||||
set.categoryIDs["cat_34"] != "cat_34" {
|
|
||||||
t.Fatal("registry omitted real ids")
|
|
||||||
}
|
|
||||||
before := domain.Clone(d)
|
before := domain.Clone(d)
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
for _, mode := range []string{"existing", "duplicate name"} {
|
||||||
content, _ := json.Marshal(map[string]any{
|
t.Run(mode, func(t *testing.T) {
|
||||||
"merchant_id": "mer_34",
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
"new_merchant": nil,
|
prompt := decodeClassificationPrompt(t, r)
|
||||||
"category_id": "cat_34",
|
if len(prompt.Merchants) != 35 || len(prompt.Tags) != 36 || len(prompt.Categories) != 37 {
|
||||||
"tag_ids": []string{"tag_34"},
|
t.Fatalf("complete candidates missing: merchants=%d tags=%d categories=%d", len(prompt.Merchants), len(prompt.Tags), len(prompt.Categories))
|
||||||
"confidence": "high",
|
}
|
||||||
|
merchants, categories, tags := map[string]string{}, map[string]string{}, map[string]string{}
|
||||||
|
for _, merchant := range prompt.Merchants {
|
||||||
|
merchants[merchant.Name] = merchant.ID
|
||||||
|
}
|
||||||
|
for _, category := range prompt.Categories {
|
||||||
|
if category.Kind != "expense" {
|
||||||
|
t.Errorf("ineligible category candidate: %+v", category)
|
||||||
|
}
|
||||||
|
categories[category.Path] = category.ID
|
||||||
|
}
|
||||||
|
for _, tag := range prompt.Tags {
|
||||||
|
tags[tag.Name] = tag.ID
|
||||||
|
}
|
||||||
|
for _, merchant := range d.Merchants {
|
||||||
|
if merchants[normalize(merchant.Name)] == "" {
|
||||||
|
t.Errorf("merchant omitted: %s", merchant.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, category := range d.Categories {
|
||||||
|
if category.Kind == "expense" && category.ID != "cat_expenses" && categories[normalize(domain.CategoryPath(d, category.ID))] == "" {
|
||||||
|
t.Errorf("eligible category omitted: %s", category.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, tag := range d.Tags {
|
||||||
|
if tags[normalize(tag.Name)] == "" {
|
||||||
|
t.Errorf("tag omitted: %s", tag.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var merchantID, newMerchant any = merchants["z distant bakery"], nil
|
||||||
|
if mode == "duplicate name" {
|
||||||
|
merchantID, newMerchant = nil, "Z Distant Bakery"
|
||||||
|
}
|
||||||
|
content, err := json.Marshal(map[string]any{
|
||||||
|
"merchant_id": merchantID,
|
||||||
|
"new_merchant": newMerchant,
|
||||||
|
"category_id": categories[normalize(domain.CategoryPath(d, "cat_34"))],
|
||||||
|
"tag_ids": []string{tags["tag 34"]},
|
||||||
|
"confidence": "high",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
reply(w, string(content))
|
||||||
|
})
|
||||||
|
p, err := c.Classify(context.Background(), f, d, true)
|
||||||
|
if err != nil || p.NewMerchant != nil || p.Enrichment.MerchantID != "mer_34" || p.Enrichment.CategoryID != "cat_34" || !reflect.DeepEqual(p.Enrichment.TagIDs, []string{"tag_34"}) {
|
||||||
|
t.Fatalf("complete registry selection failed: %+v %v", p, err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(before, d) {
|
||||||
|
t.Fatal("classification mutated the dataset")
|
||||||
|
}
|
||||||
})
|
})
|
||||||
reply(w, string(content))
|
|
||||||
})
|
|
||||||
p, err := c.Classify(context.Background(), f, d, true)
|
|
||||||
if err != nil || p.Enrichment.MerchantID != "mer_34" || p.Enrichment.CategoryID != "cat_34" || !reflect.DeepEqual(p.Enrichment.TagIDs, []string{"tag_34"}) {
|
|
||||||
t.Fatalf("complete registry selection failed: %+v %v", p, err)
|
|
||||||
}
|
|
||||||
if !reflect.DeepEqual(before, d) {
|
|
||||||
t.Fatal("retrieval mutated registry order")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -480,7 +561,7 @@ func TestConfiguredPrivateNamesAndIdentifiersRedactWithoutRemovingPayee(t *testi
|
|||||||
func TestLowConfidenceKeepsProposalAndRecordsConfidence(t *testing.T) {
|
func TestLowConfidenceKeepsProposalAndRecordsConfidence(t *testing.T) {
|
||||||
f, d := fixture()
|
f, d := fixture()
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
reply(w, `{"merchant_id":"mer_coffee","new_merchant":null,"category_id":"cat_food","tag_ids":["tag_daily"],"confidence":"low"}`)
|
reply(w, `{"merchant_id":"m1","new_merchant":null,"category_id":"c1","tag_ids":["t1"],"confidence":"low"}`)
|
||||||
})
|
})
|
||||||
p, err := c.Classify(context.Background(), f, d, true)
|
p, err := c.Classify(context.Background(), f, d, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -547,7 +628,7 @@ func TestPayeeAndPublicMerchantAreSentToAI(t *testing.T) {
|
|||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
Counterparty string `json:"counterparty"`
|
Counterparty string `json:"counterparty"`
|
||||||
} `json:"transaction"`
|
} `json:"transaction"`
|
||||||
Merchants []candidate `json:"merchants"`
|
Merchants []merchantPrompt `json:"merchants"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal([]byte(req.Messages[1].Content), &prompt); err != nil {
|
if err := json.Unmarshal([]byte(req.Messages[1].Content), &prompt); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -558,7 +639,7 @@ func TestPayeeAndPublicMerchantAreSentToAI(t *testing.T) {
|
|||||||
if len(prompt.Merchants) != 26 || prompt.Merchants[0].Name != "coffee house" {
|
if len(prompt.Merchants) != 26 || prompt.Merchants[0].Name != "coffee house" {
|
||||||
t.Fatalf("complete merchant registry missing: %d", len(prompt.Merchants))
|
t.Fatalf("complete merchant registry missing: %d", len(prompt.Merchants))
|
||||||
}
|
}
|
||||||
reply(w, `{"merchant_id":"mer_coffee","new_merchant":null,"category_id":"cat_food","tag_ids":[],"confidence":"high"}`)
|
reply(w, fmt.Sprintf(`{"merchant_id":%q,"new_merchant":null,"category_id":"c1","tag_ids":[],"confidence":"high"}`, prompt.Merchants[0].ID))
|
||||||
})
|
})
|
||||||
p, err := c.Classify(context.Background(), f, d, true)
|
p, err := c.Classify(context.Background(), f, d, true)
|
||||||
if err != nil || p.Enrichment.MerchantID != "mer_coffee" {
|
if err != nil || p.Enrichment.MerchantID != "mer_coffee" {
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ package classification
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -60,6 +62,17 @@ func ledgerFixture() (domain.Dataset, domain.Facts) {
|
|||||||
return d, facts
|
return d, facts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func categoryRefForPath(t *testing.T, categories []categoryPrompt, path string) string {
|
||||||
|
t.Helper()
|
||||||
|
for _, category := range categories {
|
||||||
|
if category.Path == path {
|
||||||
|
return category.ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Errorf("category path %q missing from prompt: %+v", path, categories)
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
// strictKeywords is what every targeted provider accepts in strict
|
// strictKeywords is what every targeted provider accepts in strict
|
||||||
// structured-output mode. uniqueItems is rejected outright by OpenAI-family
|
// structured-output mode. uniqueItems is rejected outright by OpenAI-family
|
||||||
// endpoints ("'uniqueItems' is not permitted"); minItems/maxItems make Gemini
|
// endpoints ("'uniqueItems' is not permitted"); minItems/maxItems make Gemini
|
||||||
@@ -115,7 +128,9 @@ func TestLedgerRowClassifiesThroughStrictSchema(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
reply(w, `{"merchant_id":null,"new_merchant":"Finanzamt Bruehl","category_id":"`+taxes+`","tag_ids":[],"confidence":"high"}`)
|
prompt := decodeClassificationPrompt(t, r)
|
||||||
|
category := categoryRefForPath(t, prompt.Categories, normalize(domain.CategoryPath(d, taxes)))
|
||||||
|
reply(w, `{"merchant_id":null,"new_merchant":"Finanzamt Bruehl","category_id":"`+category+`","tag_ids":[],"confidence":"high"}`)
|
||||||
})
|
})
|
||||||
p, err := c.Classify(context.Background(), facts, d, true)
|
p, err := c.Classify(context.Background(), facts, d, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -188,18 +203,123 @@ func TestManualCorrectionsOutrankAIPrecedent(t *testing.T) {
|
|||||||
add("tx_corrected", "2026-08-01", events, "manual")
|
add("tx_corrected", "2026-08-01", events, "manual")
|
||||||
target := domain.Facts{ID: "tx_new", AccountID: "acct_kontist", BookingDate: "2026-08-30",
|
target := domain.Facts{ID: "tx_new", AccountID: "acct_kontist", BookingDate: "2026-08-30",
|
||||||
Amount: "-13.00", Currency: "EUR", Counterparty: "LVR Landesmuseum Bonn"}
|
Amount: "-13.00", Currency: "EUR", Counterparty: "LVR Landesmuseum Bonn"}
|
||||||
rows := history(target, d, func(s string) string { return normalize(s) }, 20)
|
set := retrieve("", "expense", d, nil, nil)
|
||||||
if len(rows) == 0 || rows[0].Source != "user" || rows[0].CategoryID != events {
|
rows := set.history(target, d, normalize, 20)
|
||||||
|
eventsRef := categoryRefForPath(t, set.categories, domain.CategoryPath(d, events))
|
||||||
|
if len(rows) == 0 {
|
||||||
|
t.Fatal("manual correction missing from precedent")
|
||||||
|
}
|
||||||
|
if rows[0].Source != "user" || rows[0].CategoryID != eventsRef {
|
||||||
t.Fatalf("manual correction did not lead precedent: %+v", rows[0])
|
t.Fatalf("manual correction did not lead precedent: %+v", rows[0])
|
||||||
}
|
}
|
||||||
// The correction keeps its slot even in a window the AI rows could fill.
|
}
|
||||||
users := 0
|
|
||||||
for _, row := range rows {
|
func TestHistoryReferencesResolveThroughCurrentRequestCandidates(t *testing.T) {
|
||||||
if row.Source == "user" {
|
facts, d := fixture()
|
||||||
users++
|
d.Categories = append(d.Categories, domain.Category{ID: "cat_salary", Name: "Salary", ParentID: "cat_income", Kind: "income"})
|
||||||
|
d.Merchants = append(d.Merchants, domain.Merchant{ID: "mer_payroll", Name: "Payroll", DefaultCategoryID: "cat_salary"})
|
||||||
|
manual := facts
|
||||||
|
manual.ID, manual.Fingerprint, manual.BookingDate = "tx_manual", "fp_manual", "2026-08-01"
|
||||||
|
d.Transactions = append(d.Transactions, domain.Transaction{Facts: manual, Enrichment: domain.Enrichment{
|
||||||
|
Kind: "expense", CategoryID: "cat_food", MerchantID: "mer_coffee", TagIDs: []string{"tag_daily"},
|
||||||
|
Classification: domain.Provenance{Source: "manual"},
|
||||||
|
}})
|
||||||
|
income := manual
|
||||||
|
income.ID, income.Fingerprint, income.BookingDate, income.Amount = "tx_income", "fp_income", "2026-08-31", "100.00"
|
||||||
|
d.Transactions = append(d.Transactions, domain.Transaction{Facts: income, Enrichment: domain.Enrichment{
|
||||||
|
Kind: "income", CategoryID: "cat_salary", MerchantID: "mer_payroll", TagIDs: []string{"tag_daily"},
|
||||||
|
Classification: domain.Provenance{Source: "manual"},
|
||||||
|
}})
|
||||||
|
categoryPattern := regexp.MustCompile(`^c[1-9][0-9]*$`)
|
||||||
|
merchantPattern := regexp.MustCompile(`^m[1-9][0-9]*$`)
|
||||||
|
tagPattern := regexp.MustCompile(`^t[1-9][0-9]*$`)
|
||||||
|
expectedCategories := 2
|
||||||
|
c := mockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
prompt := decodeClassificationPrompt(t, r)
|
||||||
|
if len(prompt.Categories) != expectedCategories || len(prompt.Merchants) != len(d.Merchants) || len(prompt.Tags) != len(d.Tags) {
|
||||||
|
t.Errorf("request lost eligible registry candidates: categories=%d merchants=%d tags=%d",
|
||||||
|
len(prompt.Categories), len(prompt.Merchants), len(prompt.Tags))
|
||||||
}
|
}
|
||||||
}
|
categories := make(map[string]bool)
|
||||||
if users == 0 {
|
for _, candidate := range prompt.Categories {
|
||||||
t.Fatal("correction crowded out of the history window")
|
if !categoryPattern.MatchString(candidate.ID) || candidate.Kind != "expense" || categories[candidate.ID] {
|
||||||
|
t.Errorf("invalid expense category reference: %+v", candidate)
|
||||||
|
}
|
||||||
|
categories[candidate.ID] = true
|
||||||
|
}
|
||||||
|
food := categoryRefForPath(t, prompt.Categories, normalize(domain.CategoryPath(d, "cat_food")))
|
||||||
|
merchants := make(map[string]bool)
|
||||||
|
coffee := ""
|
||||||
|
for _, candidate := range prompt.Merchants {
|
||||||
|
if !merchantPattern.MatchString(candidate.ID) || merchants[candidate.ID] {
|
||||||
|
t.Errorf("invalid merchant reference: %+v", candidate)
|
||||||
|
}
|
||||||
|
merchants[candidate.ID] = true
|
||||||
|
if candidate.UsualCategory != "" && !categories[candidate.UsualCategory] {
|
||||||
|
t.Errorf("merchant has dangling usual category: %+v", candidate)
|
||||||
|
}
|
||||||
|
if candidate.Name == "coffee house" {
|
||||||
|
coffee = candidate.ID
|
||||||
|
if candidate.UsualCategory != food {
|
||||||
|
t.Errorf("merchant usual category does not identify Food: %+v", candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tags := make(map[string]bool)
|
||||||
|
daily := ""
|
||||||
|
for _, candidate := range prompt.Tags {
|
||||||
|
if !tagPattern.MatchString(candidate.ID) || tags[candidate.ID] {
|
||||||
|
t.Errorf("invalid tag reference: %+v", candidate)
|
||||||
|
}
|
||||||
|
tags[candidate.ID] = true
|
||||||
|
if candidate.Name == "daily" {
|
||||||
|
daily = candidate.ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if coffee == "" || daily == "" {
|
||||||
|
t.Error("request lost Coffee House or Daily")
|
||||||
|
}
|
||||||
|
if len(prompt.History) != 1 {
|
||||||
|
t.Errorf("expected only applicable manual expense history, got %+v", prompt.History)
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
history := prompt.History[0]
|
||||||
|
if history.Source != "user" || history.CategoryID != food || history.MerchantID != coffee ||
|
||||||
|
!reflect.DeepEqual(history.TagIDs, []string{daily}) {
|
||||||
|
t.Errorf("manual history references do not match offered records: %+v", history)
|
||||||
|
}
|
||||||
|
// Copying the correction must select the original registry records, not
|
||||||
|
// whatever records occupied these request-local references previously.
|
||||||
|
answer, err := json.Marshal(map[string]any{
|
||||||
|
"merchant_id": history.MerchantID, "new_merchant": nil,
|
||||||
|
"category_id": history.CategoryID, "tag_ids": history.TagIDs, "confidence": "high",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reply(w, string(answer))
|
||||||
|
})
|
||||||
|
for _, name := range []string{"original registry", "shifted registry"} {
|
||||||
|
if name == "shifted registry" {
|
||||||
|
// New names sort before every selected record and change all three
|
||||||
|
// references without changing the canonical correction.
|
||||||
|
d.Categories = append(d.Categories, domain.Category{ID: "cat_early", Name: "Aardvark", ParentID: "cat_expenses", Kind: "expense"})
|
||||||
|
d.Merchants = append(d.Merchants, domain.Merchant{ID: "mer_early", Name: "Aardvark"})
|
||||||
|
d.Tags = append(d.Tags, domain.Tag{ID: "tag_early", Name: "Aardvark"})
|
||||||
|
expectedCategories++
|
||||||
|
}
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
p, err := c.Classify(context.Background(), facts, d, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if p.NewMerchant != nil || p.Enrichment.CategoryID != "cat_food" || p.Enrichment.MerchantID != "mer_coffee" ||
|
||||||
|
!reflect.DeepEqual(p.Enrichment.TagIDs, []string{"tag_daily"}) {
|
||||||
|
t.Fatalf("manual precedent resolved to wrong canonical records: %+v", p)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ func normalizedProposalName(value string, max int) (string, error) {
|
|||||||
if !utf8.ValidString(value) || value == "" || utf8.RuneCountInString(value) > max {
|
if !utf8.ValidString(value) || value == "" || utf8.RuneCountInString(value) > max {
|
||||||
return "", errors.New("proposal name is blank, invalid UTF-8 or too long")
|
return "", errors.New("proposal name is blank, invalid UTF-8 or too long")
|
||||||
}
|
}
|
||||||
if strings.ContainsAny(value, "{}[]()<>/\\") || strings.Contains(value, "___") {
|
if strings.ContainsAny(value, "{}[]()<>/\\") || strings.Contains(value, "___") || hasHiddenRunes(value) {
|
||||||
return "", errors.New("proposal name is identifier-shaped")
|
return "", errors.New("proposal name is identifier-shaped")
|
||||||
}
|
}
|
||||||
return value, nil
|
return value, nil
|
||||||
|
|||||||
@@ -171,7 +171,7 @@ func NewDataset() Dataset {
|
|||||||
return Dataset{Accounts: []Account{}, Categories: []Category{
|
return Dataset{Accounts: []Account{}, Categories: []Category{
|
||||||
{ID: "cat_expenses", Name: "Expenses", Kind: "expense"}, {ID: ExpenseFallback, Name: "Unclassified", ParentID: "cat_expenses", Kind: "expense"},
|
{ID: "cat_expenses", Name: "Expenses", Kind: "expense"}, {ID: ExpenseFallback, Name: "Unclassified", ParentID: "cat_expenses", Kind: "expense"},
|
||||||
{ID: "cat_income", Name: "Income", Kind: "income"}, {ID: IncomeFallback, Name: "Unclassified", ParentID: "cat_income", Kind: "income"},
|
{ID: "cat_income", Name: "Income", Kind: "income"}, {ID: IncomeFallback, Name: "Unclassified", ParentID: "cat_income", Kind: "income"},
|
||||||
}, Tags: []Tag{}, Merchants: []Merchant{}, Instruments: []Instrument{}, Transactions: []Transaction{}}
|
}, Tags: []Tag{}, Merchants: []Merchant{}, Instruments: []Instrument{}, Assets: []Asset{}, Transactions: []Transaction{}}
|
||||||
}
|
}
|
||||||
|
|
||||||
// InstrumentID derives a stable registry ID from an ISIN so re-importing the
|
// InstrumentID derives a stable registry ID from an ISIN so re-importing the
|
||||||
@@ -181,7 +181,7 @@ func InstrumentID(isin string) string {
|
|||||||
return "ins_" + hex.EncodeToString(sum[:16])
|
return "ins_" + hex.EncodeToString(sum[:16])
|
||||||
}
|
}
|
||||||
func Clone(d Dataset) Dataset {
|
func Clone(d Dataset) Dataset {
|
||||||
c := Dataset{Accounts: append([]Account{}, d.Accounts...), Categories: append([]Category{}, d.Categories...), Tags: append([]Tag{}, d.Tags...), Merchants: append([]Merchant{}, d.Merchants...), Instruments: append([]Instrument{}, d.Instruments...), Transactions: append([]Transaction{}, d.Transactions...)}
|
c := Dataset{Accounts: append([]Account{}, d.Accounts...), Categories: append([]Category{}, d.Categories...), Tags: append([]Tag{}, d.Tags...), Merchants: append([]Merchant{}, d.Merchants...), Instruments: append([]Instrument{}, d.Instruments...), Assets: append([]Asset{}, d.Assets...), Transactions: append([]Transaction{}, d.Transactions...)}
|
||||||
for i := range c.Merchants {
|
for i := range c.Merchants {
|
||||||
c.Merchants[i].Aliases = append([]string{}, d.Merchants[i].Aliases...)
|
c.Merchants[i].Aliases = append([]string{}, d.Merchants[i].Aliases...)
|
||||||
c.Merchants[i].DefaultTagIDs = append([]string{}, d.Merchants[i].DefaultTagIDs...)
|
c.Merchants[i].DefaultTagIDs = append([]string{}, d.Merchants[i].DefaultTagIDs...)
|
||||||
@@ -250,6 +250,11 @@ func validHint(s string) bool {
|
|||||||
return utf8.ValidString(s) && utf8.RuneCountInString(s) <= 200
|
return utf8.ValidString(s) && utf8.RuneCountInString(s) <= 200
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// validName bounds registry display names at the 200 runes every UI form
|
||||||
|
// already enforces, so no client can persist an unbounded name that every
|
||||||
|
// later state response would carry.
|
||||||
|
func validName(s string) bool { return nonblank(s) && utf8.RuneCountInString(s) <= 200 }
|
||||||
|
|
||||||
// ValidISIN reports a syntactically valid ISIN: two country letters, nine
|
// ValidISIN reports a syntactically valid ISIN: two country letters, nine
|
||||||
// alphanumerics and a check digit.
|
// alphanumerics and a check digit.
|
||||||
func ValidISIN(s string) bool { return isinPattern.MatchString(s) }
|
func ValidISIN(s string) bool { return isinPattern.MatchString(s) }
|
||||||
@@ -286,13 +291,27 @@ func Validate(d Dataset) error {
|
|||||||
if a.Kind != "" && a.Kind != AccountCash && a.Kind != AccountInvestment {
|
if a.Kind != "" && a.Kind != AccountCash && a.Kind != AccountInvestment {
|
||||||
return fmt.Errorf("account %q: kind must be %q or %q", a.ID, AccountCash, AccountInvestment)
|
return fmt.Errorf("account %q: kind must be %q or %q", a.ID, AccountCash, AccountInvestment)
|
||||||
}
|
}
|
||||||
|
// An anchor is one figure and the day it was true: neither half means
|
||||||
|
// anything alone, and anchoring an investment account would mask an
|
||||||
|
// incomplete broker history instead of exposing it.
|
||||||
|
if (a.AnchorBalance == "") != (a.AnchorDate == "") {
|
||||||
|
return fmt.Errorf("account %q: an anchor needs both a balance and its date", a.ID)
|
||||||
|
}
|
||||||
|
if a.AnchorDate != "" {
|
||||||
|
if a.Investing() {
|
||||||
|
return fmt.Errorf("account %q: a balance anchor belongs to a cash account; a broker export carries its complete history", a.ID)
|
||||||
|
}
|
||||||
|
if _, err := a.AnchorBalance.Minor(); err != nil || !validDate(a.AnchorDate) {
|
||||||
|
return fmt.Errorf("account %q: invalid anchor balance or date", a.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
accounts[a.ID] = a
|
accounts[a.ID] = a
|
||||||
}
|
}
|
||||||
for _, c := range d.Categories {
|
for _, c := range d.Categories {
|
||||||
if err := register(c.ID, "category"); err != nil {
|
if err := register(c.ID, "category"); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !nonblank(c.Name) || !validHint(c.Hint) || (c.Kind != "expense" && c.Kind != "income") {
|
if !validName(c.Name) || !validHint(c.Hint) || (c.Kind != "expense" && c.Kind != "income") {
|
||||||
return fmt.Errorf("category %q: invalid name, hint or kind", c.ID)
|
return fmt.Errorf("category %q: invalid name, hint or kind", c.ID)
|
||||||
}
|
}
|
||||||
categories[c.ID] = c
|
categories[c.ID] = c
|
||||||
@@ -330,7 +349,7 @@ func Validate(d Dataset) error {
|
|||||||
if err := register(t.ID, "tag"); err != nil {
|
if err := register(t.ID, "tag"); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !nonblank(t.Name) || !validHint(t.Hint) {
|
if !validName(t.Name) || !validHint(t.Hint) {
|
||||||
return fmt.Errorf("tag %q: name or hint invalid", t.ID)
|
return fmt.Errorf("tag %q: name or hint invalid", t.ID)
|
||||||
}
|
}
|
||||||
tags[t.ID] = true
|
tags[t.ID] = true
|
||||||
@@ -339,8 +358,8 @@ func Validate(d Dataset) error {
|
|||||||
if err := register(m.ID, "merchant"); err != nil {
|
if err := register(m.ID, "merchant"); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !nonblank(m.Name) {
|
if !validName(m.Name) {
|
||||||
return fmt.Errorf("merchant %q: name required", m.ID)
|
return fmt.Errorf("merchant %q: valid name of at most 200 characters required", m.ID)
|
||||||
}
|
}
|
||||||
if m.DefaultCategoryID != "" {
|
if m.DefaultCategoryID != "" {
|
||||||
if _, ok := categories[m.DefaultCategoryID]; !ok || children[m.DefaultCategoryID] {
|
if _, ok := categories[m.DefaultCategoryID]; !ok || children[m.DefaultCategoryID] {
|
||||||
@@ -375,7 +394,7 @@ func Validate(d Dataset) error {
|
|||||||
if other, ok := isins[v.ISIN]; ok {
|
if other, ok := isins[v.ISIN]; ok {
|
||||||
return fmt.Errorf("instrument %q: ISIN %s already held by %q", v.ID, v.ISIN, other)
|
return fmt.Errorf("instrument %q: ISIN %s already held by %q", v.ID, v.ISIN, other)
|
||||||
}
|
}
|
||||||
if !nonblank(v.Name) || !currencyPattern.MatchString(v.Currency) || !validText(v.Symbol) {
|
if !validName(v.Name) || !currencyPattern.MatchString(v.Currency) || !validText(v.Symbol) {
|
||||||
return fmt.Errorf("instrument %q: valid UTF-8 name and symbol and three-letter uppercase currency required", v.ID)
|
return fmt.Errorf("instrument %q: valid UTF-8 name and symbol and three-letter uppercase currency required", v.ID)
|
||||||
}
|
}
|
||||||
// A quote without its day cannot be judged stale, and a day without a
|
// A quote without its day cannot be judged stale, and a day without a
|
||||||
@@ -398,6 +417,22 @@ func Validate(d Dataset) error {
|
|||||||
isins[v.ISIN] = v.ID
|
isins[v.ISIN] = v.ID
|
||||||
instruments[v.ID] = v
|
instruments[v.ID] = v
|
||||||
}
|
}
|
||||||
|
for _, v := range d.Assets {
|
||||||
|
if err := register(v.ID, "asset"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !nonblank(v.Name) || !currencyPattern.MatchString(v.Currency) || !validText(v.Kind) {
|
||||||
|
return fmt.Errorf("asset %q: valid UTF-8 name and three-letter uppercase currency required", v.ID)
|
||||||
|
}
|
||||||
|
// A hand-stated value without its day cannot be judged stale, so the
|
||||||
|
// two are recorded together, always.
|
||||||
|
if _, err := v.Value.Minor(); err != nil {
|
||||||
|
return fmt.Errorf("asset %q: %w", v.ID, err)
|
||||||
|
}
|
||||||
|
if !validDate(v.ValuedAt) {
|
||||||
|
return fmt.Errorf("asset %q: invalid valuation date %q", v.ID, v.ValuedAt)
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, t := range d.Transactions {
|
for _, t := range d.Transactions {
|
||||||
f := t.Facts
|
f := t.Facts
|
||||||
if err := register(f.ID, "transaction"); err != nil {
|
if err := register(f.ID, "transaction"); err != nil {
|
||||||
|
|||||||
@@ -75,6 +75,20 @@ func TestDomainRejectsBrokenReferencesAndTaxonomy(t *testing.T) {
|
|||||||
{"duplicate identity", func(d *Dataset) { d.Tags[0].ID = "acc_main" }},
|
{"duplicate identity", func(d *Dataset) { d.Tags[0].ID = "acc_main" }},
|
||||||
{"invalid provenance date", func(d *Dataset) { d.Transactions[0].Enrichment.Classification.Timestamp = "yesterday" }},
|
{"invalid provenance date", func(d *Dataset) { d.Transactions[0].Enrichment.Classification.Timestamp = "yesterday" }},
|
||||||
{"nonleaf merchant default", func(d *Dataset) { d.Merchants[0].DefaultCategoryID = "cat_food" }},
|
{"nonleaf merchant default", func(d *Dataset) { d.Merchants[0].DefaultCategoryID = "cat_food" }},
|
||||||
|
{"oversized tag name", func(d *Dataset) { d.Tags[0].Name = strings.Repeat("x", 201) }},
|
||||||
|
{"oversized category name", func(d *Dataset) { d.Categories[2].Name = strings.Repeat("x", 201) }},
|
||||||
|
{"anchor balance without its date", func(d *Dataset) { d.Accounts[1].AnchorBalance = "100.00" }},
|
||||||
|
{"anchor date without its balance", func(d *Dataset) { d.Accounts[1].AnchorDate = "2026-01-01" }},
|
||||||
|
{"anchored investment account", func(d *Dataset) {
|
||||||
|
d.Accounts[1].Kind = AccountInvestment
|
||||||
|
d.Accounts[1].AnchorBalance, d.Accounts[1].AnchorDate = "100.00", "2026-01-01"
|
||||||
|
}},
|
||||||
|
{"invalid anchor date", func(d *Dataset) {
|
||||||
|
d.Accounts[1].AnchorBalance, d.Accounts[1].AnchorDate = "100.00", "2026-02-30"
|
||||||
|
}},
|
||||||
|
{"invalid anchor balance", func(d *Dataset) {
|
||||||
|
d.Accounts[1].AnchorBalance, d.Accounts[1].AnchorDate = "1e2", "2026-01-01"
|
||||||
|
}},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
|||||||
@@ -31,6 +31,16 @@ type Account struct {
|
|||||||
// broker exports no counterparty column, so deposits and withdrawals carry
|
// broker exports no counterparty column, so deposits and withdrawals carry
|
||||||
// this IBAN instead and pair with the funding account like any transfer.
|
// this IBAN instead and pair with the funding account like any transfer.
|
||||||
ReferenceIBAN string `json:"reference_iban,omitempty"`
|
ReferenceIBAN string `json:"reference_iban,omitempty"`
|
||||||
|
// AnchorBalance is the bank's booked (CLBD) balance on AnchorDate, captured
|
||||||
|
// once from open banking after a sync. It fixes the start balance of a
|
||||||
|
// date-windowed history: the money that existed before the recorded rows is
|
||||||
|
// AnchorBalance less every movement booked through AnchorDate, so the
|
||||||
|
// account's real balance is computable without complete history. The bank's
|
||||||
|
// figure is stored verbatim — the start balance is derived, never stored —
|
||||||
|
// so importing older history later corrects the derivation by itself.
|
||||||
|
// Cash accounts only: a broker export carries its complete history.
|
||||||
|
AnchorBalance Money `json:"anchor_balance,omitempty"`
|
||||||
|
AnchorDate string `json:"anchor_date,omitempty"`
|
||||||
Active bool `json:"active"`
|
Active bool `json:"active"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,6 +126,20 @@ type Instrument struct {
|
|||||||
QuotedAt string `json:"quoted_at,omitempty"`
|
QuotedAt string `json:"quoted_at,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Asset is a possession valued by hand: a house, a car, anything without a
|
||||||
|
// market feed. Value is what the owner states it is worth and ValuedAt the day
|
||||||
|
// that estimate was made, so a stale figure is visible rather than silently
|
||||||
|
// trusted. A negative value records a liability such as a mortgage.
|
||||||
|
type Asset struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
// Kind is free display text grouping the asset: "Real estate", "Vehicle".
|
||||||
|
Kind string `json:"kind,omitempty"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
Value Money `json:"value"`
|
||||||
|
ValuedAt string `json:"valued_at"`
|
||||||
|
}
|
||||||
|
|
||||||
type Facts struct {
|
type Facts struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Source string `json:"source"`
|
Source string `json:"source"`
|
||||||
@@ -178,6 +202,7 @@ type Dataset struct {
|
|||||||
Tags []Tag `json:"tags"`
|
Tags []Tag `json:"tags"`
|
||||||
Merchants []Merchant `json:"merchants"`
|
Merchants []Merchant `json:"merchants"`
|
||||||
Instruments []Instrument `json:"instruments"`
|
Instruments []Instrument `json:"instruments"`
|
||||||
|
Assets []Asset `json:"assets"`
|
||||||
Transactions []Transaction `json:"transactions"`
|
Transactions []Transaction `json:"transactions"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import (
|
|||||||
// registryFiles are the non-monthly journal files, in the order they are read
|
// registryFiles are the non-monthly journal files, in the order they are read
|
||||||
// and written. A block's file is its kind pluralized, so this list and the
|
// and written. A block's file is its kind pluralized, so this list and the
|
||||||
// kinds accepted by parseDocument must stay in step.
|
// kinds accepted by parseDocument must stay in step.
|
||||||
var registryFiles = []string{"accounts.finance", "categories.finance", "tags.finance", "merchants.finance", "instruments.finance"}
|
var registryFiles = []string{"accounts.finance", "categories.finance", "tags.finance", "merchants.finance", "instruments.finance", "assets.finance"}
|
||||||
|
|
||||||
type fieldSpan struct{ start, end int }
|
type fieldSpan struct{ start, end int }
|
||||||
type block struct {
|
type block struct {
|
||||||
@@ -140,7 +140,7 @@ func parseDocument(path string, raw []byte) (*document, error) {
|
|||||||
}
|
}
|
||||||
header := strings.Fields(trimmed)
|
header := strings.Fields(trimmed)
|
||||||
if len(header) != 2 || header[1] != "{" {
|
if len(header) != 2 || header[1] != "{" {
|
||||||
return fail(i+1, "expected 'account|category|tag|merchant|instrument|transaction {'")
|
return fail(i+1, "expected 'account|category|tag|merchant|instrument|asset|transaction {'")
|
||||||
}
|
}
|
||||||
kind := header[0]
|
kind := header[0]
|
||||||
var value any
|
var value any
|
||||||
@@ -155,6 +155,8 @@ func parseDocument(path string, raw []byte) (*document, error) {
|
|||||||
value = &domain.Merchant{}
|
value = &domain.Merchant{}
|
||||||
case "instrument":
|
case "instrument":
|
||||||
value = &domain.Instrument{}
|
value = &domain.Instrument{}
|
||||||
|
case "asset":
|
||||||
|
value = &domain.Asset{}
|
||||||
case "transaction":
|
case "transaction":
|
||||||
value = &domain.Transaction{}
|
value = &domain.Transaction{}
|
||||||
default:
|
default:
|
||||||
@@ -237,6 +239,9 @@ func parseDocument(path string, raw []byte) (*document, error) {
|
|||||||
case *domain.Instrument:
|
case *domain.Instrument:
|
||||||
b.id = v.ID
|
b.id = v.ID
|
||||||
b.value = *v
|
b.value = *v
|
||||||
|
case *domain.Asset:
|
||||||
|
b.id = v.ID
|
||||||
|
b.value = *v
|
||||||
case *domain.Merchant:
|
case *domain.Merchant:
|
||||||
if v.Aliases == nil {
|
if v.Aliases == nil {
|
||||||
v.Aliases = []string{}
|
v.Aliases = []string{}
|
||||||
@@ -342,6 +347,9 @@ func datasetFiles(d domain.Dataset) map[string]map[string]piece {
|
|||||||
for _, v := range d.Instruments {
|
for _, v := range d.Instruments {
|
||||||
add("instruments.finance", "instrument", v.ID, v)
|
add("instruments.finance", "instrument", v.ID, v)
|
||||||
}
|
}
|
||||||
|
for _, v := range d.Assets {
|
||||||
|
add("assets.finance", "asset", v.ID, v)
|
||||||
|
}
|
||||||
for _, v := range d.Transactions {
|
for _, v := range d.Transactions {
|
||||||
month := v.Facts.BookingDate[:7]
|
month := v.Facts.BookingDate[:7]
|
||||||
add("journal/"+month[:4]+"/"+month+".finance", "transaction", v.Facts.ID, v)
|
add("journal/"+month[:4]+"/"+month+".finance", "transaction", v.Facts.ID, v)
|
||||||
|
|||||||
@@ -435,7 +435,7 @@ func (s *Store) snapshot() (*snapshot, error) {
|
|||||||
return snap, nil
|
return snap, nil
|
||||||
}
|
}
|
||||||
func decodeSnapshot(raw map[string][]byte) (*snapshot, error) {
|
func decodeSnapshot(raw map[string][]byte) (*snapshot, error) {
|
||||||
snap := &snapshot{raw: raw, docs: map[string]*document{}, revision: revision(raw), data: domain.Dataset{Accounts: []domain.Account{}, Categories: []domain.Category{}, Tags: []domain.Tag{}, Merchants: []domain.Merchant{}, Instruments: []domain.Instrument{}, Transactions: []domain.Transaction{}}}
|
snap := &snapshot{raw: raw, docs: map[string]*document{}, revision: revision(raw), data: domain.Dataset{Accounts: []domain.Account{}, Categories: []domain.Category{}, Tags: []domain.Tag{}, Merchants: []domain.Merchant{}, Instruments: []domain.Instrument{}, Assets: []domain.Asset{}, Transactions: []domain.Transaction{}}}
|
||||||
if len(raw) == 0 {
|
if len(raw) == 0 {
|
||||||
snap.data = domain.NewDataset()
|
snap.data = domain.NewDataset()
|
||||||
return snap, nil
|
return snap, nil
|
||||||
@@ -483,6 +483,8 @@ func decodeSnapshot(raw map[string][]byte) (*snapshot, error) {
|
|||||||
snap.data.Merchants = append(snap.data.Merchants, v)
|
snap.data.Merchants = append(snap.data.Merchants, v)
|
||||||
case domain.Instrument:
|
case domain.Instrument:
|
||||||
snap.data.Instruments = append(snap.data.Instruments, v)
|
snap.data.Instruments = append(snap.data.Instruments, v)
|
||||||
|
case domain.Asset:
|
||||||
|
snap.data.Assets = append(snap.data.Assets, v)
|
||||||
case domain.Transaction:
|
case domain.Transaction:
|
||||||
snap.data.Transactions = append(snap.data.Transactions, v)
|
snap.data.Transactions = append(snap.data.Transactions, v)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -514,6 +514,30 @@ func TestNullListsPreserveUntouchedExternalBlockBytes(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// An asset is a registry entity like any other: committed to its own file and
|
||||||
|
// identical after a fresh load, or the wealth it backs vanishes on restart.
|
||||||
|
func TestAssetsSurviveCommitAndReload(t *testing.T) {
|
||||||
|
s := openTestStore(t)
|
||||||
|
d, r := loadTestStore(t, s)
|
||||||
|
d.Assets = []domain.Asset{{ID: "asset_house", Name: "House", Kind: "Real estate", Currency: "EUR", Value: "250000.00", ValuedAt: "2026-09-01"}}
|
||||||
|
commitTestStore(t, s, r, d)
|
||||||
|
if err := s.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fresh, err := Open(s.dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer fresh.Close()
|
||||||
|
loaded, _ := loadTestStore(t, fresh)
|
||||||
|
if !reflect.DeepEqual(loaded.Assets, d.Assets) {
|
||||||
|
t.Errorf("assets after reload %+v, want %+v", loaded.Assets, d.Assets)
|
||||||
|
}
|
||||||
|
if raw := readTestFile(t, filepath.Join(s.dir, "assets.finance")); !bytes.Contains(raw, []byte(`asset {`)) {
|
||||||
|
t.Errorf("assets.finance holds no asset block: %s", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestOversizedCommitCannotPublishUnreadableRecoveryIntent(t *testing.T) {
|
func TestOversizedCommitCannotPublishUnreadableRecoveryIntent(t *testing.T) {
|
||||||
s := openTestStore(t)
|
s := openTestStore(t)
|
||||||
original, r := loadTestStore(t, s)
|
original, r := loadTestStore(t, s)
|
||||||
|
|||||||
+101
-1
@@ -11,6 +11,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -45,7 +46,9 @@ func New(a *app.App, assets fs.FS, publicURL string) (http.Handler, error) {
|
|||||||
s.mux.HandleFunc("POST /api/tags", s.tag)
|
s.mux.HandleFunc("POST /api/tags", s.tag)
|
||||||
s.mux.HandleFunc("POST /api/merchants", s.merchant)
|
s.mux.HandleFunc("POST /api/merchants", s.merchant)
|
||||||
s.mux.HandleFunc("POST /api/instruments", s.instrument)
|
s.mux.HandleFunc("POST /api/instruments", s.instrument)
|
||||||
|
s.mux.HandleFunc("POST /api/assets", s.asset)
|
||||||
s.mux.HandleFunc("POST /api/transactions/{id}/transfer", s.transfer)
|
s.mux.HandleFunc("POST /api/transactions/{id}/transfer", s.transfer)
|
||||||
|
s.mux.HandleFunc("POST /api/transactions/bulk", s.bulkTransactions)
|
||||||
s.mux.HandleFunc("POST /api/transactions/{id}", s.transaction)
|
s.mux.HandleFunc("POST /api/transactions/{id}", s.transaction)
|
||||||
s.mux.HandleFunc("POST /api/manage", s.manage)
|
s.mux.HandleFunc("POST /api/manage", s.manage)
|
||||||
s.mux.HandleFunc("POST /api/import/prepare", s.importPrepare)
|
s.mux.HandleFunc("POST /api/import/prepare", s.importPrepare)
|
||||||
@@ -236,7 +239,7 @@ func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
|
|||||||
respond(w, nil, errors.New("from must not exceed to"))
|
respond(w, nil, errors.New("from must not exceed to"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
v, e := s.app.Dashboard(r.Context(), analytics.Filter{From: from, To: to, Currency: q.Get("currency"), AccountID: q.Get("account_id"), CategoryID: q.Get("category_id"), TagID: q.Get("tag_id"), MerchantID: q.Get("merchant_id")})
|
v, e := s.app.Dashboard(r.Context(), analytics.Filter{From: from, To: to, Currency: q.Get("currency"), AccountID: q.Get("account_id"), CategoryID: q.Get("category_id"), TagIDs: q["tag_ids"], ExcludeTagIDs: q["exclude_tag_ids"], MerchantID: q.Get("merchant_id")})
|
||||||
respond(w, v, e)
|
respond(w, v, e)
|
||||||
}
|
}
|
||||||
func (s *Server) account(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) account(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -294,6 +297,17 @@ func (s *Server) instrument(w http.ResponseWriter, r *http.Request) {
|
|||||||
v, e := s.app.Mutate(r.Context(), b.Revision, func(d *domain.Dataset) error { return app.SaveInstrument(d, b.Instrument) })
|
v, e := s.app.Mutate(r.Context(), b.Revision, func(d *domain.Dataset) error { return app.SaveInstrument(d, b.Instrument) })
|
||||||
respond(w, v, e)
|
respond(w, v, e)
|
||||||
}
|
}
|
||||||
|
func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var b struct {
|
||||||
|
Revision string `json:"revision"`
|
||||||
|
Asset domain.Asset `json:"asset"`
|
||||||
|
}
|
||||||
|
if !decode(w, r, &b) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, e := s.app.Mutate(r.Context(), b.Revision, func(d *domain.Dataset) error { return app.SaveAsset(d, b.Asset) })
|
||||||
|
respond(w, v, e)
|
||||||
|
}
|
||||||
|
|
||||||
// transfer links or unlinks one transaction's own-account counterpart. It is a
|
// transfer links or unlinks one transaction's own-account counterpart. It is a
|
||||||
// separate endpoint because both sides change together: the transaction editor
|
// separate endpoint because both sides change together: the transaction editor
|
||||||
@@ -335,6 +349,92 @@ func (s *Server) transaction(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
respond(w, v, e)
|
respond(w, v, e)
|
||||||
}
|
}
|
||||||
|
func (s *Server) bulkTransactions(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var b struct {
|
||||||
|
Revision string `json:"revision"`
|
||||||
|
TransactionIDs []string `json:"transaction_ids"`
|
||||||
|
CategoryID *string `json:"category_id"`
|
||||||
|
MerchantID *string `json:"merchant_id"`
|
||||||
|
AddTagIDs []string `json:"add_tag_ids"`
|
||||||
|
RemoveTagIDs []string `json:"remove_tag_ids"`
|
||||||
|
}
|
||||||
|
if !decode(w, r, &b) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v, e := s.app.Mutate(r.Context(), b.Revision, func(d *domain.Dataset) error {
|
||||||
|
if len(b.TransactionIDs) == 0 {
|
||||||
|
return errors.New("select at least one transaction")
|
||||||
|
}
|
||||||
|
if b.CategoryID == nil && b.MerchantID == nil && len(b.AddTagIDs) == 0 && len(b.RemoveTagIDs) == 0 {
|
||||||
|
return errors.New("choose at least one bulk edit")
|
||||||
|
}
|
||||||
|
selected := make(map[string]bool, len(b.TransactionIDs))
|
||||||
|
for _, id := range b.TransactionIDs {
|
||||||
|
if id == "" || selected[id] {
|
||||||
|
return errors.New("transaction IDs must be nonempty and unique")
|
||||||
|
}
|
||||||
|
selected[id] = true
|
||||||
|
}
|
||||||
|
var knownTags map[string]bool
|
||||||
|
if len(b.AddTagIDs) > 0 || len(b.RemoveTagIDs) > 0 {
|
||||||
|
knownTags = make(map[string]bool, len(d.Tags))
|
||||||
|
for _, tag := range d.Tags {
|
||||||
|
knownTags[tag.ID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addTags := make(map[string]bool, len(b.AddTagIDs))
|
||||||
|
for _, id := range b.AddTagIDs {
|
||||||
|
if !knownTags[id] || addTags[id] {
|
||||||
|
return errors.New("added tag IDs must be known and unique")
|
||||||
|
}
|
||||||
|
addTags[id] = true
|
||||||
|
}
|
||||||
|
removeTags := make(map[string]bool, len(b.RemoveTagIDs))
|
||||||
|
for _, id := range b.RemoveTagIDs {
|
||||||
|
if !knownTags[id] || removeTags[id] || addTags[id] {
|
||||||
|
return errors.New("removed tag IDs must be known, unique and not also added")
|
||||||
|
}
|
||||||
|
removeTags[id] = true
|
||||||
|
}
|
||||||
|
matched := 0
|
||||||
|
provenance := domain.Provenance{Source: "manual", Timestamp: time.Now().UTC().Format(time.RFC3339)}
|
||||||
|
for i := range d.Transactions {
|
||||||
|
t := &d.Transactions[i]
|
||||||
|
if !selected[t.Facts.ID] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
matched++
|
||||||
|
if (b.CategoryID != nil || b.MerchantID != nil) && (t.Enrichment.Kind == "transfer" || t.Enrichment.Kind == domain.KindInvestment) {
|
||||||
|
return errors.New("category and merchant cannot be edited on transfers or investments")
|
||||||
|
}
|
||||||
|
if b.CategoryID != nil {
|
||||||
|
t.Enrichment.CategoryID = *b.CategoryID
|
||||||
|
}
|
||||||
|
if b.MerchantID != nil {
|
||||||
|
t.Enrichment.MerchantID = *b.MerchantID
|
||||||
|
if *b.MerchantID != "" {
|
||||||
|
app.LearnAlias(d, t.Facts, *b.MerchantID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(removeTags) > 0 {
|
||||||
|
t.Enrichment.TagIDs = slices.DeleteFunc(t.Enrichment.TagIDs, func(id string) bool { return removeTags[id] })
|
||||||
|
}
|
||||||
|
for _, id := range b.AddTagIDs {
|
||||||
|
if !slices.Contains(t.Enrichment.TagIDs, id) {
|
||||||
|
t.Enrichment.TagIDs = append(t.Enrichment.TagIDs, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Enrichment.Classification = provenance
|
||||||
|
}
|
||||||
|
if matched != len(selected) {
|
||||||
|
return errors.New("unknown transaction")
|
||||||
|
}
|
||||||
|
// Commit validates the complete dataset once, including category leaf/kind
|
||||||
|
// compatibility and merchant references, before writing any journal files.
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
respond(w, v, e)
|
||||||
|
}
|
||||||
func (s *Server) manage(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) manage(w http.ResponseWriter, r *http.Request) {
|
||||||
var b struct {
|
var b struct {
|
||||||
Revision string `json:"revision"`
|
Revision string `json:"revision"`
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"crypto/rsa"
|
"crypto/rsa"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
@@ -11,12 +12,17 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"reflect"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"testing/fstest"
|
"testing/fstest"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"finance-duck/internal/analytics"
|
||||||
"finance-duck/internal/app"
|
"finance-duck/internal/app"
|
||||||
"finance-duck/internal/banking"
|
"finance-duck/internal/banking"
|
||||||
|
"finance-duck/internal/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestOriginAndHostGuardProtectNoLoginService(t *testing.T) {
|
func TestOriginAndHostGuardProtectNoLoginService(t *testing.T) {
|
||||||
@@ -415,3 +421,336 @@ func TestCSVImportOverHTTPImportsOnlyAfterConfirmation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
send("/api/import/confirm", "application/json", confirm, origin, http.StatusBadRequest)
|
send("/api/import/confirm", "application/json", confirm, origin, http.StatusBadRequest)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDashboardRepeatedTagFiltersOverHTTP(t *testing.T) {
|
||||||
|
t.Setenv("OPENROUTER_API_KEY", "")
|
||||||
|
t.Setenv("ENABLEBANKING_APP_ID", "")
|
||||||
|
t.Setenv("ENABLEBANKING_KEY_FILE", "")
|
||||||
|
t.Setenv("ENABLEBANKING_REDIRECT_URL", "")
|
||||||
|
a, err := app.Open(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer a.Close()
|
||||||
|
state, err := a.Snapshot(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = a.Mutate(context.Background(), state.Revision, func(data *domain.Dataset) error {
|
||||||
|
data.Accounts = append(data.Accounts, domain.Account{ID: "acc_eur", DisplayName: "Current", Currency: "EUR", Active: true})
|
||||||
|
data.Tags = append(data.Tags, domain.Tag{ID: "tag_shared", Name: "Shared"}, domain.Tag{ID: "tag_work", Name: "Work"})
|
||||||
|
for _, item := range []struct {
|
||||||
|
id string
|
||||||
|
amount domain.Money
|
||||||
|
kind string
|
||||||
|
category string
|
||||||
|
tags []string
|
||||||
|
}{
|
||||||
|
{"tx_both", "-10.0000", "expense", domain.ExpenseFallback, []string{"tag_shared", "tag_work"}},
|
||||||
|
{"tx_work", "-20.0000", "expense", domain.ExpenseFallback, []string{"tag_work"}},
|
||||||
|
{"tx_income", "100.0000", "income", domain.IncomeFallback, []string{}},
|
||||||
|
} {
|
||||||
|
data.Transactions = append(data.Transactions, domain.Transaction{
|
||||||
|
Facts: domain.Facts{ID: item.id, Source: "test", AccountID: "acc_eur", BookingDate: "2026-02-10",
|
||||||
|
Amount: item.amount, Currency: "EUR", RawDescription: item.id, Fingerprint: item.id},
|
||||||
|
Enrichment: domain.Enrichment{Kind: item.kind, CategoryID: item.category, TagIDs: item.tags},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
h, err := New(a, fstest.MapFS{}, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
include []string
|
||||||
|
exclude []string
|
||||||
|
want []analytics.Total
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "repeated includes use union without duplication",
|
||||||
|
include: []string{"tag_shared", "tag_work"},
|
||||||
|
want: []analytics.Total{{Currency: "EUR", Expenses: "30.0000", Income: "0.0000", Net: "-30.0000"}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "repeated exclusions preserve untagged income",
|
||||||
|
exclude: []string{"tag_shared", "tag_work"},
|
||||||
|
want: []analytics.Total{{Currency: "EUR", Expenses: "0.0000", Income: "100.0000", Net: "100.0000"}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "include and exclude compose with exclusion winning",
|
||||||
|
include: []string{"tag_shared", "tag_work"},
|
||||||
|
exclude: []string{"tag_missing", "tag_shared"},
|
||||||
|
want: []analytics.Total{{Currency: "EUR", Expenses: "20.0000", Income: "0.0000", Net: "-20.0000"}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "comma separated values are not a list",
|
||||||
|
include: []string{"tag_shared,tag_work"},
|
||||||
|
want: []analytics.Total{},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range cases {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
query := url.Values{"from": {"2026-02-01"}, "to": {"2026-02-28"}, "currency": {"EUR"}}
|
||||||
|
for _, id := range tt.include {
|
||||||
|
query.Add("tag_ids", id)
|
||||||
|
}
|
||||||
|
for _, id := range tt.exclude {
|
||||||
|
query.Add("exclude_tag_ids", id)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://localhost:8080/api/dashboard?"+query.Encode(), nil))
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET dashboard: %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
var got analytics.Dashboard
|
||||||
|
if err := json.NewDecoder(w.Body).Decode(&got); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got.Totals, tt.want) {
|
||||||
|
t.Fatalf("totals: got %#v, want %#v", got.Totals, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTransactionsBulkOverHTTP(t *testing.T) {
|
||||||
|
t.Setenv("OPENROUTER_API_KEY", "")
|
||||||
|
t.Setenv("ENABLEBANKING_APP_ID", "")
|
||||||
|
t.Setenv("ENABLEBANKING_KEY_FILE", "")
|
||||||
|
t.Setenv("ENABLEBANKING_REDIRECT_URL", "")
|
||||||
|
a, err := app.Open(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer a.Close()
|
||||||
|
state, err := a.Snapshot(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = a.Mutate(context.Background(), state.Revision, func(d *domain.Dataset) error {
|
||||||
|
d.Accounts = []domain.Account{
|
||||||
|
{ID: "acc_current", DisplayName: "Current", Currency: "EUR", Active: true},
|
||||||
|
{ID: "acc_savings", DisplayName: "Savings", Currency: "EUR", Active: true},
|
||||||
|
{ID: "acc_broker", DisplayName: "Broker", Currency: "EUR", Kind: domain.AccountInvestment, Active: true},
|
||||||
|
}
|
||||||
|
d.Categories = append(d.Categories, domain.Category{ID: "cat_food", Name: "Food", ParentID: "cat_expenses", Kind: "expense"})
|
||||||
|
d.Tags = []domain.Tag{{ID: "tag_keep", Name: "Keep"}, {ID: "tag_remove", Name: "Remove"}, {ID: "tag_add", Name: "Add"}, {ID: "tag_absent", Name: "Absent"}}
|
||||||
|
d.Merchants = []domain.Merchant{{ID: "mer_old", Name: "Previous merchant"}, {ID: "mer_new", Name: "New merchant"}}
|
||||||
|
for _, item := range []struct {
|
||||||
|
id, account, kind, category, merchant, peer, counterparty string
|
||||||
|
amount domain.Money
|
||||||
|
tags []string
|
||||||
|
investment *domain.Investment
|
||||||
|
}{
|
||||||
|
{"tx_a", "acc_current", "expense", domain.ExpenseFallback, "mer_old", "", "Corner Bakery", "-10.0000", []string{"tag_keep", "tag_remove"}, nil},
|
||||||
|
{"tx_b", "acc_current", "expense", domain.ExpenseFallback, "mer_old", "", "Market Hall", "-20.0000", []string{"tag_add", "tag_keep"}, nil},
|
||||||
|
{"tx_untouched", "acc_current", "expense", domain.ExpenseFallback, "mer_old", "", "Station Kiosk", "-3.0000", []string{"tag_remove"}, nil},
|
||||||
|
{"tx_income", "acc_current", "income", domain.IncomeFallback, "", "", "Employer", "100.0000", []string{"tag_remove"}, nil},
|
||||||
|
{"tx_out", "acc_current", "transfer", "", "", "tx_in", "Savings", "-25.0000", []string{"tag_keep"}, nil},
|
||||||
|
{"tx_in", "acc_savings", "transfer", "", "", "tx_out", "Current", "25.0000", []string{}, nil},
|
||||||
|
{"tx_investment", "acc_broker", domain.KindInvestment, "", "", "", "Deposit", "30.0000", []string{"tag_keep"}, &domain.Investment{Event: domain.EventDeposit}},
|
||||||
|
} {
|
||||||
|
d.Transactions = append(d.Transactions, domain.Transaction{
|
||||||
|
Facts: domain.Facts{
|
||||||
|
ID: item.id, Source: "test", AccountID: item.account, BookingDate: "2026-02-10", ValueDate: "2026-02-11",
|
||||||
|
Amount: item.amount, Currency: "EUR", RawDescription: "Bank description " + item.id,
|
||||||
|
ExternalID: "external_" + item.id, Fingerprint: item.id, Counterparty: item.counterparty,
|
||||||
|
CounterpartyIBAN: "DE89370400440532013000", Investment: item.investment,
|
||||||
|
},
|
||||||
|
Enrichment: domain.Enrichment{
|
||||||
|
Kind: item.kind, CategoryID: item.category, MerchantID: item.merchant, TagIDs: item.tags,
|
||||||
|
TransferPeerID: item.peer, Classification: domain.Provenance{Source: "rules"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
h, err := New(a, fstest.MapFS{}, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
snapshot := func() app.State {
|
||||||
|
t.Helper()
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://localhost:8080/api/state", nil))
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET state: %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
var result app.State
|
||||||
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
post := func(body map[string]any, status int) app.State {
|
||||||
|
t.Helper()
|
||||||
|
if _, ok := body["revision"]; !ok {
|
||||||
|
body["revision"] = snapshot().Revision
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "http://localhost:8080/api/transactions/bulk", strings.NewReader(string(raw)))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
if w.Code != status {
|
||||||
|
t.Fatalf("POST bulk: got %d, want %d: %s", w.Code, status, w.Body.String())
|
||||||
|
}
|
||||||
|
var result app.State
|
||||||
|
if status == http.StatusOK {
|
||||||
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
persisted := snapshot()
|
||||||
|
if result.Revision != persisted.Revision || !reflect.DeepEqual(result.Data, persisted.Data) {
|
||||||
|
t.Fatal("bulk response differs from persisted state")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
transaction := func(s app.State, id string) domain.Transaction {
|
||||||
|
t.Helper()
|
||||||
|
for _, tx := range s.Data.Transactions {
|
||||||
|
if tx.Facts.ID == id {
|
||||||
|
return tx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("missing transaction %s", id)
|
||||||
|
return domain.Transaction{}
|
||||||
|
}
|
||||||
|
for _, tt := range []struct {
|
||||||
|
name string
|
||||||
|
body map[string]any
|
||||||
|
}{
|
||||||
|
{"empty selection", map[string]any{"transaction_ids": []string{}, "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"empty transaction ID", map[string]any{"transaction_ids": []string{"tx_a", ""}, "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"duplicate transaction ID", map[string]any{"transaction_ids": []string{"tx_a", "tx_a"}, "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"missing transaction rolls back category merchant tags and aliases", map[string]any{"transaction_ids": []string{"tx_a", "tx_missing"}, "category_id": "cat_food", "merchant_id": "mer_new", "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"no operations", map[string]any{"transaction_ids": []string{"tx_a"}, "add_tag_ids": []string{}, "remove_tag_ids": []string{}}},
|
||||||
|
{"unknown added tag", map[string]any{"transaction_ids": []string{"tx_a"}, "add_tag_ids": []string{"tag_missing"}}},
|
||||||
|
{"unknown removed tag", map[string]any{"transaction_ids": []string{"tx_a"}, "remove_tag_ids": []string{"tag_missing"}}},
|
||||||
|
{"duplicate added tag", map[string]any{"transaction_ids": []string{"tx_a"}, "add_tag_ids": []string{"tag_add", "tag_add"}}},
|
||||||
|
{"duplicate removed tag", map[string]any{"transaction_ids": []string{"tx_a"}, "remove_tag_ids": []string{"tag_remove", "tag_remove"}}},
|
||||||
|
{"overlapping tag operations", map[string]any{"transaction_ids": []string{"tx_a"}, "add_tag_ids": []string{"tag_add"}, "remove_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"nonleaf category", map[string]any{"transaction_ids": []string{"tx_a", "tx_b"}, "category_id": "cat_expenses", "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"unknown category", map[string]any{"transaction_ids": []string{"tx_a", "tx_b"}, "category_id": "cat_missing", "merchant_id": "mer_new"}},
|
||||||
|
{"category cannot be cleared", map[string]any{"transaction_ids": []string{"tx_a"}, "category_id": ""}},
|
||||||
|
{"incompatible category rolls back entire batch", map[string]any{"transaction_ids": []string{"tx_a", "tx_income"}, "category_id": "cat_food", "merchant_id": "mer_new", "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"unknown merchant", map[string]any{"transaction_ids": []string{"tx_a", "tx_b"}, "merchant_id": "mer_missing"}},
|
||||||
|
{"transfer category edit", map[string]any{"transaction_ids": []string{"tx_a", "tx_out"}, "category_id": "cat_food"}},
|
||||||
|
{"transfer merchant clear", map[string]any{"transaction_ids": []string{"tx_a", "tx_out"}, "merchant_id": ""}},
|
||||||
|
{"investment category edit", map[string]any{"transaction_ids": []string{"tx_a", "tx_investment"}, "category_id": "cat_food"}},
|
||||||
|
{"investment merchant clear", map[string]any{"transaction_ids": []string{"tx_a", "tx_investment"}, "merchant_id": ""}},
|
||||||
|
{"bank facts cannot be edited", map[string]any{"transaction_ids": []string{"tx_a"}, "amount": "1.0000", "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"kind cannot be edited", map[string]any{"transaction_ids": []string{"tx_a"}, "kind": "income", "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
{"transfer links cannot be edited", map[string]any{"transaction_ids": []string{"tx_out"}, "transfer_peer_id": "", "add_tag_ids": []string{"tag_add"}}},
|
||||||
|
} {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
before := snapshot()
|
||||||
|
post(tt.body, http.StatusBadRequest)
|
||||||
|
after := snapshot()
|
||||||
|
if before.Revision != after.Revision || !reflect.DeepEqual(before.Data, after.Data) {
|
||||||
|
t.Fatal("rejected batch changed persisted data or revision")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
t.Run("multi row edit preserves facts unrelated tags and unselected rows", func(t *testing.T) {
|
||||||
|
before := snapshot()
|
||||||
|
after := post(map[string]any{
|
||||||
|
"transaction_ids": []string{"tx_a", "tx_b"}, "category_id": "cat_food", "merchant_id": "mer_new",
|
||||||
|
"add_tag_ids": []string{"tag_add"}, "remove_tag_ids": []string{"tag_remove", "tag_absent"},
|
||||||
|
}, http.StatusOK)
|
||||||
|
for _, old := range before.Data.Transactions {
|
||||||
|
got := transaction(after, old.Facts.ID)
|
||||||
|
if old.Facts.ID != "tx_a" && old.Facts.ID != "tx_b" {
|
||||||
|
if !reflect.DeepEqual(old, got) {
|
||||||
|
t.Fatalf("unselected transaction changed: %s", old.Facts.ID)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tags := slices.Clone(got.Enrichment.TagIDs)
|
||||||
|
slices.Sort(tags)
|
||||||
|
if !reflect.DeepEqual(tags, []string{"tag_add", "tag_keep"}) || got.Enrichment.CategoryID != "cat_food" || got.Enrichment.MerchantID != "mer_new" {
|
||||||
|
t.Fatalf("bulk changes not applied: %+v", got.Enrichment)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(old.Facts, got.Facts) || got.Enrichment.Kind != old.Enrichment.Kind || got.Enrichment.TransferPeerID != old.Enrichment.TransferPeerID {
|
||||||
|
t.Fatalf("immutable transaction fields changed: %s", old.Facts.ID)
|
||||||
|
}
|
||||||
|
if got.Enrichment.Classification.Source != "manual" {
|
||||||
|
t.Fatalf("missing manual provenance: %+v", got.Enrichment.Classification)
|
||||||
|
}
|
||||||
|
if _, err := time.Parse(time.RFC3339, got.Enrichment.Classification.Timestamp); err != nil {
|
||||||
|
t.Fatalf("invalid manual timestamp: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, merchant := range after.Data.Merchants {
|
||||||
|
if merchant.ID == "mer_new" && (!slices.Contains(merchant.Aliases, "Corner Bakery") || !slices.Contains(merchant.Aliases, "Market Hall")) {
|
||||||
|
t.Fatalf("explicit merchant assignment did not learn aliases: %+v", merchant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
post(map[string]any{"revision": before.Revision, "transaction_ids": []string{"tx_a", "tx_b"}, "merchant_id": ""}, http.StatusConflict)
|
||||||
|
unchanged := snapshot()
|
||||||
|
if unchanged.Revision != after.Revision || !reflect.DeepEqual(unchanged.Data, after.Data) {
|
||||||
|
t.Fatal("stale batch overwrote the successful edit")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("tag-only edits preserve individual categories merchants and transfer links", func(t *testing.T) {
|
||||||
|
before := snapshot()
|
||||||
|
after := post(map[string]any{
|
||||||
|
"transaction_ids": []string{"tx_a", "tx_untouched", "tx_income", "tx_out", "tx_investment"},
|
||||||
|
"add_tag_ids": []string{"tag_add"}, "remove_tag_ids": []string{"tag_remove"},
|
||||||
|
}, http.StatusOK)
|
||||||
|
for _, id := range []string{"tx_a", "tx_untouched", "tx_income", "tx_out", "tx_investment"} {
|
||||||
|
old, got := transaction(before, id), transaction(after, id)
|
||||||
|
if !slices.Contains(got.Enrichment.TagIDs, "tag_add") || slices.Contains(got.Enrichment.TagIDs, "tag_remove") {
|
||||||
|
t.Fatalf("tags not updated on %s: %+v", id, got.Enrichment)
|
||||||
|
}
|
||||||
|
if id == "tx_out" || id == "tx_investment" {
|
||||||
|
if !slices.Contains(got.Enrichment.TagIDs, "tag_keep") {
|
||||||
|
t.Fatalf("unrelated tag removed from %s", id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(old.Facts, got.Facts) || got.Enrichment.Kind != old.Enrichment.Kind ||
|
||||||
|
got.Enrichment.CategoryID != old.Enrichment.CategoryID || got.Enrichment.MerchantID != old.Enrichment.MerchantID ||
|
||||||
|
got.Enrichment.TransferPeerID != old.Enrichment.TransferPeerID || got.Enrichment.Classification.Source != "manual" {
|
||||||
|
t.Fatalf("tag edit changed other fields or omitted manual provenance on %s: %+v", id, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(transaction(before, "tx_in"), transaction(after, "tx_in")) {
|
||||||
|
t.Fatal("tag edit changed unselected transfer counterpart")
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(before.Data.Merchants, after.Data.Merchants) {
|
||||||
|
t.Fatal("tag-only edits learned merchant aliases")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("merchant clearing preserves category and tags and fallback remains selectable", func(t *testing.T) {
|
||||||
|
before := snapshot()
|
||||||
|
cleared := post(map[string]any{"transaction_ids": []string{"tx_a", "tx_b"}, "merchant_id": ""}, http.StatusOK)
|
||||||
|
for _, id := range []string{"tx_a", "tx_b"} {
|
||||||
|
old, got := transaction(before, id), transaction(cleared, id)
|
||||||
|
if got.Enrichment.MerchantID != "" || old.Enrichment.CategoryID != got.Enrichment.CategoryID ||
|
||||||
|
!reflect.DeepEqual(old.Enrichment.TagIDs, got.Enrichment.TagIDs) || !reflect.DeepEqual(old.Facts, got.Facts) {
|
||||||
|
t.Fatalf("merchant clear changed unrelated fields: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(before.Data.Merchants, cleared.Data.Merchants) {
|
||||||
|
t.Fatal("merchant clearing changed aliases")
|
||||||
|
}
|
||||||
|
fallback := post(map[string]any{"transaction_ids": []string{"tx_a", "tx_b"}, "category_id": domain.ExpenseFallback}, http.StatusOK)
|
||||||
|
for _, id := range []string{"tx_a", "tx_b"} {
|
||||||
|
if transaction(fallback, id).Enrichment.CategoryID != domain.ExpenseFallback {
|
||||||
|
t.Fatalf("fallback category was not assigned to %s", id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
+42
-6
@@ -1244,9 +1244,16 @@ function AccountEditor({
|
|||||||
pattern="[A-Z]{3}"
|
pattern="[A-Z]{3}"
|
||||||
maxLength={3}
|
maxLength={3}
|
||||||
value={value.currency}
|
value={value.currency}
|
||||||
onChange={(e) =>
|
onChange={(e) => {
|
||||||
setValue({ ...value, currency: e.target.value.toUpperCase() })
|
const currency = e.target.value.toUpperCase();
|
||||||
}
|
setValue((current) => ({
|
||||||
|
...current,
|
||||||
|
currency,
|
||||||
|
...(currency !== current.currency
|
||||||
|
? { anchor_balance: "", anchor_date: "" }
|
||||||
|
: {}),
|
||||||
|
}));
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
</div>
|
</div>
|
||||||
@@ -1288,11 +1295,40 @@ function AccountEditor({
|
|||||||
>
|
>
|
||||||
<input
|
<input
|
||||||
value={value.external_account_id || ""}
|
value={value.external_account_id || ""}
|
||||||
onChange={(e) =>
|
onChange={(e) => {
|
||||||
setValue({ ...value, external_account_id: e.target.value })
|
const external = e.target.value;
|
||||||
}
|
setValue((current) => ({
|
||||||
|
...current,
|
||||||
|
external_account_id: external,
|
||||||
|
...(external !== (current.external_account_id || "")
|
||||||
|
? { anchor_balance: "", anchor_date: "" }
|
||||||
|
: {}),
|
||||||
|
}));
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
|
{value.anchor_date && (
|
||||||
|
<Field
|
||||||
|
label="Balance anchor"
|
||||||
|
hint="The bank's booked balance, captured once after a sync. It fixes this account's start balance on Wealth. Clear it and the next synchronization captures a fresh one."
|
||||||
|
>
|
||||||
|
<div className="anchor-row">
|
||||||
|
<span>
|
||||||
|
{money(value.anchor_balance ?? "0", value.currency)} on{" "}
|
||||||
|
{value.anchor_date}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button subtle"
|
||||||
|
onClick={() =>
|
||||||
|
setValue({ ...value, anchor_balance: "", anchor_date: "" })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Clear anchor
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
<label className="checkbox">
|
<label className="checkbox">
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
|
|||||||
+50
-21
@@ -16,7 +16,9 @@ import type {
|
|||||||
} from "./api";
|
} from "./api";
|
||||||
import { categoryPath, money, request } from "./api";
|
import { categoryPath, money, request } from "./api";
|
||||||
import {
|
import {
|
||||||
|
CategoryCombobox,
|
||||||
Combobox,
|
Combobox,
|
||||||
|
createTag,
|
||||||
DateField,
|
DateField,
|
||||||
Empty,
|
Empty,
|
||||||
ErrorMessage,
|
ErrorMessage,
|
||||||
@@ -24,12 +26,15 @@ import {
|
|||||||
Modal,
|
Modal,
|
||||||
ModelOptions,
|
ModelOptions,
|
||||||
} from "./ui";
|
} from "./ui";
|
||||||
|
import type { Mutate } from "./ui";
|
||||||
export function Classification({
|
export function Classification({
|
||||||
state,
|
state,
|
||||||
acceptState,
|
acceptState,
|
||||||
|
mutate,
|
||||||
}: {
|
}: {
|
||||||
state: State;
|
state: State;
|
||||||
acceptState: (state: State, message?: string) => void;
|
acceptState: (state: State, message?: string) => void;
|
||||||
|
mutate: Mutate;
|
||||||
}) {
|
}) {
|
||||||
const dates = state.data.transactions.map((t) => t.facts.booking_date).sort();
|
const dates = state.data.transactions.map((t) => t.facts.booking_date).sort();
|
||||||
const [from, setFrom] = useState(dates[0] || "");
|
const [from, setFrom] = useState(dates[0] || "");
|
||||||
@@ -292,10 +297,12 @@ export function Classification({
|
|||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError("");
|
setError("");
|
||||||
try {
|
try {
|
||||||
|
// Refresh registry labels for the review, but let the server
|
||||||
|
// take its own snapshot so another write cannot race analysis.
|
||||||
|
acceptState(await request<State>("/api/state"));
|
||||||
const start = await request<PreviewProgress>(
|
const start = await request<PreviewProgress>(
|
||||||
"/api/reclassify/preview",
|
"/api/reclassify/preview",
|
||||||
{
|
{
|
||||||
revision: state.revision,
|
|
||||||
from,
|
from,
|
||||||
to,
|
to,
|
||||||
model: model.trim(),
|
model: model.trim(),
|
||||||
@@ -480,6 +487,7 @@ export function Classification({
|
|||||||
value={effective(change)}
|
value={effective(change)}
|
||||||
edited={change.id in edits}
|
edited={change.id in edits}
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
|
mutate={mutate}
|
||||||
onChange={(value) => correct(change, value)}
|
onChange={(value) => correct(change, value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -665,14 +673,18 @@ interface CorrectionValue {
|
|||||||
}
|
}
|
||||||
// CorrectionEditor is the "Proposed" side of a review row, editable in place.
|
// CorrectionEditor is the "Proposed" side of a review row, editable in place.
|
||||||
// Category and tags are free-text inputs that autocomplete against the
|
// Category and tags are free-text inputs that autocomplete against the
|
||||||
// existing taxonomy; the category list is limited to leaves of the change's
|
// existing taxonomy and can create a missing entry in place; the category
|
||||||
// kind because that is what validation will accept.
|
// list is limited to leaves of the change's kind because that is what
|
||||||
|
// validation will accept. Creating mid-review bumps the journal revision,
|
||||||
|
// which the apply path tolerates as long as the transactions themselves are
|
||||||
|
// untouched.
|
||||||
function CorrectionEditor({
|
function CorrectionEditor({
|
||||||
data,
|
data,
|
||||||
change,
|
change,
|
||||||
value,
|
value,
|
||||||
edited,
|
edited,
|
||||||
disabled,
|
disabled,
|
||||||
|
mutate,
|
||||||
onChange,
|
onChange,
|
||||||
}: {
|
}: {
|
||||||
data: Dataset;
|
data: Dataset;
|
||||||
@@ -680,15 +692,14 @@ function CorrectionEditor({
|
|||||||
value: CorrectionValue;
|
value: CorrectionValue;
|
||||||
edited: boolean;
|
edited: boolean;
|
||||||
disabled: boolean;
|
disabled: boolean;
|
||||||
|
mutate: Mutate;
|
||||||
onChange: (value: CorrectionValue) => void;
|
onChange: (value: CorrectionValue) => void;
|
||||||
}) {
|
}) {
|
||||||
const categories = data.categories
|
// Async creates resolve against the freshest correction, not the snapshot
|
||||||
.filter(
|
// captured when the create row was clicked: a chip removed during the
|
||||||
(c) =>
|
// server round trip must survive the create landing.
|
||||||
c.kind === change.after.kind &&
|
const latest = useRef(value);
|
||||||
!data.categories.some((child) => child.parent_id === c.id),
|
latest.current = value;
|
||||||
)
|
|
||||||
.map((c) => ({ value: c.id, label: categoryPath(data, c.id) }));
|
|
||||||
const addable = data.tags
|
const addable = data.tags
|
||||||
.filter((t) => !value.tag_ids.includes(t.id))
|
.filter((t) => !value.tag_ids.includes(t.id))
|
||||||
.map((t) => ({ value: t.id, label: t.name }));
|
.map((t) => ({ value: t.id, label: t.name }));
|
||||||
@@ -726,13 +737,16 @@ function CorrectionEditor({
|
|||||||
<div>
|
<div>
|
||||||
<dt>Category</dt>
|
<dt>Category</dt>
|
||||||
<dd>
|
<dd>
|
||||||
<Combobox
|
<CategoryCombobox
|
||||||
options={categories}
|
data={data}
|
||||||
|
kind={change.after.kind}
|
||||||
|
leavesOnly
|
||||||
|
mutate={mutate}
|
||||||
value={value.category_id}
|
value={value.category_id}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onChange={(category_id) => onChange({ ...value, category_id })}
|
onChange={(category_id) =>
|
||||||
placeholder="Search categories"
|
onChange({ ...latest.current, category_id })
|
||||||
emptyText="No matching category. Create it in Categories first."
|
}
|
||||||
/>
|
/>
|
||||||
</dd>
|
</dd>
|
||||||
</div>
|
</div>
|
||||||
@@ -761,16 +775,31 @@ function CorrectionEditor({
|
|||||||
<Combobox
|
<Combobox
|
||||||
options={addable}
|
options={addable}
|
||||||
value=""
|
value=""
|
||||||
disabled={disabled || !addable.length}
|
disabled={disabled}
|
||||||
onChange={(id) =>
|
onChange={(id) =>
|
||||||
onChange({ ...value, tag_ids: [...value.tag_ids, id] })
|
onChange({ ...value, tag_ids: [...value.tag_ids, id] })
|
||||||
}
|
}
|
||||||
placeholder={
|
placeholder={data.tags.length ? "Add tag" : "Add or create tag"}
|
||||||
data.tags.length
|
emptyText="No matching tag. Type a name to create it."
|
||||||
? "Add tag"
|
create={(text) =>
|
||||||
: "No tags yet — create them in Tags"
|
data.tags.some(
|
||||||
|
(t) => t.name.toLowerCase() === text.toLowerCase(),
|
||||||
|
)
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
key: "tag",
|
||||||
|
label: `Create tag "${text}"`,
|
||||||
|
run: async () => {
|
||||||
|
const id = await createTag(mutate, data, text);
|
||||||
|
onChange({
|
||||||
|
...latest.current,
|
||||||
|
tag_ids: [...latest.current.tag_ids, id],
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
}
|
}
|
||||||
emptyText="No matching tag. Create it in Tags first."
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</dd>
|
</dd>
|
||||||
|
|||||||
@@ -261,8 +261,11 @@ export function Overview({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError("");
|
setError("");
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
for (const [key, value] of Object.entries(filter))
|
for (const [key, value] of Object.entries(filter)) {
|
||||||
if (value) params.set(key, value);
|
if (Array.isArray(value)) {
|
||||||
|
for (const id of value) params.append(key, id);
|
||||||
|
} else if (value) params.set(key, value);
|
||||||
|
}
|
||||||
request<Dashboard>(`/api/dashboard?${params}`, undefined, controller.signal)
|
request<Dashboard>(`/api/dashboard?${params}`, undefined, controller.signal)
|
||||||
.then((value) => {
|
.then((value) => {
|
||||||
for (const key of [
|
for (const key of [
|
||||||
@@ -498,7 +501,7 @@ export function Overview({
|
|||||||
groups={dashboard.tags.filter(
|
groups={dashboard.tags.filter(
|
||||||
(g) => g.currency === currency,
|
(g) => g.currency === currency,
|
||||||
)}
|
)}
|
||||||
onSelect={(id) => drill({ tag_id: id })}
|
onSelect={(id) => drill({ tag_ids: [id] })}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Recurring
|
<Recurring
|
||||||
@@ -617,6 +620,8 @@ function WealthStrip({
|
|||||||
{money(total.positions, total.currency)} in positions across{" "}
|
{money(total.positions, total.currency)} in positions across{" "}
|
||||||
{positions} investment account
|
{positions} investment account
|
||||||
{positions === 1 ? "" : "s"}
|
{positions === 1 ? "" : "s"}
|
||||||
|
{total.assets !== "0.00" &&
|
||||||
|
` · ${money(total.assets, total.currency)} in other assets`}
|
||||||
{total.unpriced > 0 &&
|
{total.unpriced > 0 &&
|
||||||
` · ${total.unpriced} holding${total.unpriced === 1 ? "" : "s"} without a quote, excluded`}
|
` · ${total.unpriced} holding${total.unpriced === 1 ? "" : "s"} without a quote, excluded`}
|
||||||
{failing > 0 &&
|
{failing > 0 &&
|
||||||
|
|||||||
+125
-91
@@ -5,6 +5,7 @@ import {
|
|||||||
GitMerge,
|
GitMerge,
|
||||||
Trash2,
|
Trash2,
|
||||||
FolderTree,
|
FolderTree,
|
||||||
|
FolderPlus,
|
||||||
Tag as TagIcon,
|
Tag as TagIcon,
|
||||||
Store,
|
Store,
|
||||||
CandlestickChart,
|
CandlestickChart,
|
||||||
@@ -21,7 +22,7 @@ import type {
|
|||||||
} from "./api";
|
} from "./api";
|
||||||
import { categoryPath, request } from "./api";
|
import { categoryPath, request } from "./api";
|
||||||
import {
|
import {
|
||||||
CategoryOptions,
|
CategoryCombobox,
|
||||||
Empty,
|
Empty,
|
||||||
ErrorMessage,
|
ErrorMessage,
|
||||||
Field,
|
Field,
|
||||||
@@ -32,6 +33,10 @@ import {
|
|||||||
import type { Mutate } from "./ui";
|
import type { Mutate } from "./ui";
|
||||||
type Entity = "category" | "tag" | "merchant" | "instrument";
|
type Entity = "category" | "tag" | "merchant" | "instrument";
|
||||||
type Item = Category | Tag | Merchant | Instrument;
|
type Item = Category | Tag | Merchant | Instrument;
|
||||||
|
const protectedCategoryIDs = new Set([
|
||||||
|
"cat_expenses_unclassified",
|
||||||
|
"cat_income_unclassified",
|
||||||
|
]);
|
||||||
const titles = {
|
const titles = {
|
||||||
category: "Categories",
|
category: "Categories",
|
||||||
tag: "Tags",
|
tag: "Tags",
|
||||||
@@ -82,83 +87,105 @@ export function Registry({
|
|||||||
? { id: "", isin: "", name: "", currency: "EUR", symbol: "" }
|
? { id: "", isin: "", name: "", currency: "EUR", symbol: "" }
|
||||||
: { id: "", name: "" },
|
: { id: "", name: "" },
|
||||||
);
|
);
|
||||||
const row = (item: Item, depth = 0) => (
|
const createChild = (parent: Category) =>
|
||||||
<div className="registry-row" key={item.id}>
|
setEditing({
|
||||||
<div
|
id: "",
|
||||||
className="registry-label"
|
name: "",
|
||||||
style={{ paddingLeft: `${depth * 23}px` }}
|
parent_id: parent.id,
|
||||||
>
|
kind: parent.kind,
|
||||||
{entity === "category" ? (
|
hint: "",
|
||||||
<FolderTree size={18} />
|
});
|
||||||
) : entity === "tag" ? (
|
const row = (item: Item, depth = 0) => {
|
||||||
<TagIcon size={18} />
|
const category = entity === "category" && "kind" in item ? item : null;
|
||||||
) : entity === "instrument" ? (
|
return (
|
||||||
<CandlestickChart size={18} />
|
<div className="registry-row" key={item.id}>
|
||||||
) : (
|
<div
|
||||||
<Store size={18} />
|
className="registry-label"
|
||||||
)}
|
style={{ paddingLeft: `${depth * 23}px` }}
|
||||||
<div>
|
|
||||||
<strong>{item.name}</strong>
|
|
||||||
{"kind" in item && (
|
|
||||||
<small>
|
|
||||||
{item.kind}
|
|
||||||
{!item.parent_id ? " root" : ""}
|
|
||||||
</small>
|
|
||||||
)}
|
|
||||||
{"aliases" in item && (
|
|
||||||
<small>
|
|
||||||
{item.aliases.length ? item.aliases.join(" · ") : "No aliases"}
|
|
||||||
{item.use_defaults ? " · Defaults enabled" : ""}
|
|
||||||
</small>
|
|
||||||
)}
|
|
||||||
{"hint" in item && item.hint && <small>{item.hint}</small>}
|
|
||||||
{"isin" in item && (
|
|
||||||
<small>
|
|
||||||
{item.isin} · {item.currency} ·{" "}
|
|
||||||
{item.symbol
|
|
||||||
? item.quote
|
|
||||||
? `${item.symbol} at ${item.quote} on ${item.quoted_at}`
|
|
||||||
: `${item.symbol}, not yet quoted`
|
|
||||||
: "No market symbol, so unpriced"}
|
|
||||||
</small>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{"default_category_id" in item && item.default_category_id && (
|
|
||||||
<span className="muted registry-detail">
|
|
||||||
{categoryPath(data, item.default_category_id)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<div className="row-actions">
|
|
||||||
<button
|
|
||||||
className="icon-button"
|
|
||||||
title={`Edit ${item.name}`}
|
|
||||||
aria-label={`Edit ${item.name}`}
|
|
||||||
onClick={() => setEditing(item)}
|
|
||||||
>
|
>
|
||||||
<Pencil size={16} />
|
{entity === "category" ? (
|
||||||
</button>
|
<FolderTree size={18} />
|
||||||
{entity !== "instrument" && (
|
) : entity === "tag" ? (
|
||||||
|
<TagIcon size={18} />
|
||||||
|
) : entity === "instrument" ? (
|
||||||
|
<CandlestickChart size={18} />
|
||||||
|
) : (
|
||||||
|
<Store size={18} />
|
||||||
|
)}
|
||||||
|
<div>
|
||||||
|
<strong>{item.name}</strong>
|
||||||
|
{"kind" in item && (
|
||||||
|
<small>
|
||||||
|
{item.kind}
|
||||||
|
{!item.parent_id ? " root" : ""}
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
|
{"aliases" in item && (
|
||||||
|
<small>
|
||||||
|
{item.aliases.length ? item.aliases.join(" · ") : "No aliases"}
|
||||||
|
{item.use_defaults ? " · Defaults enabled" : ""}
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
|
{"hint" in item && item.hint && <small>{item.hint}</small>}
|
||||||
|
{"isin" in item && (
|
||||||
|
<small>
|
||||||
|
{item.isin} · {item.currency} ·{" "}
|
||||||
|
{item.symbol
|
||||||
|
? item.quote
|
||||||
|
? `${item.symbol} at ${item.quote} on ${item.quoted_at}`
|
||||||
|
: `${item.symbol}, not yet quoted`
|
||||||
|
: "No market symbol, so unpriced"}
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{"default_category_id" in item && item.default_category_id && (
|
||||||
|
<span className="muted registry-detail">
|
||||||
|
{categoryPath(data, item.default_category_id)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<div className="row-actions">
|
||||||
|
{category && !protectedCategoryIDs.has(category.id) && (
|
||||||
|
<button
|
||||||
|
className="button subtle category-child-action"
|
||||||
|
title={`Add a child category under ${category.name}`}
|
||||||
|
aria-label={`Add a child category under ${category.name}`}
|
||||||
|
onClick={() => createChild(category)}
|
||||||
|
>
|
||||||
|
<FolderPlus size={15} />
|
||||||
|
Add child
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
className="icon-button"
|
className="icon-button"
|
||||||
title={`Merge ${item.name}`}
|
title={`Edit ${item.name}`}
|
||||||
aria-label={`Merge ${item.name}`}
|
aria-label={`Edit ${item.name}`}
|
||||||
onClick={() => setAction({ item, action: "merge" })}
|
onClick={() => setEditing(item)}
|
||||||
>
|
>
|
||||||
<GitMerge size={16} />
|
<Pencil size={16} />
|
||||||
</button>
|
</button>
|
||||||
)}
|
{entity !== "instrument" && (
|
||||||
<button
|
<button
|
||||||
className="icon-button danger"
|
className="icon-button"
|
||||||
title={`Delete ${item.name}`}
|
title={`Merge ${item.name}`}
|
||||||
aria-label={`Delete ${item.name}`}
|
aria-label={`Merge ${item.name}`}
|
||||||
onClick={() => setAction({ item, action: "delete" })}
|
onClick={() => setAction({ item, action: "merge" })}
|
||||||
>
|
>
|
||||||
<Trash2 size={16} />
|
<GitMerge size={16} />
|
||||||
</button>
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
className="icon-button danger"
|
||||||
|
title={`Delete ${item.name}`}
|
||||||
|
aria-label={`Delete ${item.name}`}
|
||||||
|
onClick={() => setAction({ item, action: "delete" })}
|
||||||
|
>
|
||||||
|
<Trash2 size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
);
|
||||||
);
|
};
|
||||||
const tree = (
|
const tree = (
|
||||||
parent: string | undefined,
|
parent: string | undefined,
|
||||||
depth = 0,
|
depth = 0,
|
||||||
@@ -181,7 +208,7 @@ export function Registry({
|
|||||||
<h2>{titles[entity]}</h2>
|
<h2>{titles[entity]}</h2>
|
||||||
<p>
|
<p>
|
||||||
{entity === "category"
|
{entity === "category"
|
||||||
? "A clear home for every transaction. Parent categories roll up their children."
|
? "Organize spending and income into a tree. Use Add child on any category to create a nested category."
|
||||||
: entity === "tag"
|
: entity === "tag"
|
||||||
? "Flexible labels that work across your accounts and categories."
|
? "Flexible labels that work across your accounts and categories."
|
||||||
: entity === "instrument"
|
: entity === "instrument"
|
||||||
@@ -549,18 +576,19 @@ function RegistryEditor({
|
|||||||
<option value="income">Income</option>
|
<option value="income">Income</option>
|
||||||
</select>
|
</select>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Parent category">
|
<Field
|
||||||
<select
|
label="Parent category"
|
||||||
|
hint="Choose an existing category to nest this one. Use Add child on the category list when you want to add a nested category."
|
||||||
|
>
|
||||||
|
<CategoryCombobox
|
||||||
|
data={data}
|
||||||
|
kind={kind}
|
||||||
|
exclude={[...descendants]}
|
||||||
|
emptyLabel="No parent (top level)"
|
||||||
value={parent}
|
value={parent}
|
||||||
onChange={(e) => setParent(e.target.value)}
|
onChange={setParent}
|
||||||
>
|
placeholder="Choose a parent category"
|
||||||
<option value="">No parent (root)</option>
|
/>
|
||||||
<CategoryOptions
|
|
||||||
data={data}
|
|
||||||
kind={kind}
|
|
||||||
exclude={[...descendants]}
|
|
||||||
/>
|
|
||||||
</select>
|
|
||||||
</Field>
|
</Field>
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
Changing the parent moves this category and its entire subtree.
|
Changing the parent moves this category and its entire subtree.
|
||||||
@@ -590,15 +618,21 @@ function RegistryEditor({
|
|||||||
Use these defaults when this merchant is recognized
|
Use these defaults when this merchant is recognized
|
||||||
</label>
|
</label>
|
||||||
<Field label="Default category">
|
<Field label="Default category">
|
||||||
<select
|
<CategoryCombobox
|
||||||
|
data={data}
|
||||||
|
leavesOnly
|
||||||
|
emptyLabel="No default category"
|
||||||
|
mutate={mutate}
|
||||||
value={category}
|
value={category}
|
||||||
onChange={(e) => setCategory(e.target.value)}
|
onChange={setCategory}
|
||||||
>
|
/>
|
||||||
<option value="">No default category</option>
|
|
||||||
<CategoryOptions data={data} />
|
|
||||||
</select>
|
|
||||||
</Field>
|
</Field>
|
||||||
<TagPicker data={data} value={tags} onChange={setTags} />
|
<TagPicker
|
||||||
|
data={data}
|
||||||
|
value={tags}
|
||||||
|
onChange={setTags}
|
||||||
|
mutate={mutate}
|
||||||
|
/>
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
Defaults are only used when explicitly enabled. Editing defaults
|
Defaults are only used when explicitly enabled. Editing defaults
|
||||||
does not rewrite existing transactions.
|
does not rewrite existing transactions.
|
||||||
|
|||||||
+579
-114
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo, useState } from "react";
|
import { useMemo, useRef, useState } from "react";
|
||||||
import {
|
import {
|
||||||
Search,
|
Search,
|
||||||
ArrowUpRight,
|
ArrowUpRight,
|
||||||
@@ -18,7 +18,7 @@ import type {
|
|||||||
} from "./api";
|
} from "./api";
|
||||||
import { categoryPath, money } from "./api";
|
import { categoryPath, money } from "./api";
|
||||||
import {
|
import {
|
||||||
CategoryOptions,
|
CategoryCombobox,
|
||||||
Empty,
|
Empty,
|
||||||
ErrorMessage,
|
ErrorMessage,
|
||||||
Field,
|
Field,
|
||||||
@@ -41,6 +41,26 @@ const EVENTS: Record<string, string> = {
|
|||||||
corporate_action: "Corporate action",
|
corporate_action: "Corporate action",
|
||||||
position_transfer: "Position transfer",
|
position_transfer: "Position transfer",
|
||||||
};
|
};
|
||||||
|
// Human labels for classification provenance sources; the filter options and
|
||||||
|
// the Source column speak the same language. Both fallback shapes — the
|
||||||
|
// import-time "unclassified" error record and the plain sign-based
|
||||||
|
// "fallback" — read as Unclassified.
|
||||||
|
const CLASSIFICATIONS: Record<string, string> = {
|
||||||
|
manual: "Manual",
|
||||||
|
openrouter: "AI",
|
||||||
|
rule: "Merchant rule",
|
||||||
|
transfer_match: "Transfer match",
|
||||||
|
fallback: "Unclassified",
|
||||||
|
unclassified: "Unclassified",
|
||||||
|
};
|
||||||
|
const CLASSIFICATION_FILTERS: [string, string][] = [
|
||||||
|
["manual", "Manual"],
|
||||||
|
["openrouter", "AI"],
|
||||||
|
["rule", "Merchant rule"],
|
||||||
|
["transfer_match", "Transfer match"],
|
||||||
|
["unclassified", "Unclassified"],
|
||||||
|
];
|
||||||
|
|
||||||
// A corporate action or a position transfer moves shares between holdings and
|
// A corporate action or a position transfer moves shares between holdings and
|
||||||
// settles no money at all, so its zero amount is a fact and not a gap.
|
// settles no money at all, so its zero amount is a fact and not a gap.
|
||||||
function positionOnly(investment?: Investment): boolean {
|
function positionOnly(investment?: Investment): boolean {
|
||||||
@@ -92,8 +112,16 @@ export function Transactions({
|
|||||||
}) {
|
}) {
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const [needsReview, setNeedsReview] = useState(false);
|
const [needsReview, setNeedsReview] = useState(false);
|
||||||
|
const [status, setStatus] = useState("");
|
||||||
const [editing, setEditing] = useState<Transaction | null>(null);
|
const [editing, setEditing] = useState<Transaction | null>(null);
|
||||||
const [page, setPage] = useState(0);
|
const [page, setPage] = useState(0);
|
||||||
|
const [bulk, setBulk] = useState(false);
|
||||||
|
const [bulkEditing, setBulkEditing] = useState(false);
|
||||||
|
const selectionScope = JSON.stringify([filter, query, needsReview, status]);
|
||||||
|
const [selection, setSelection] = useState(() => ({
|
||||||
|
scope: selectionScope,
|
||||||
|
ids: new Set<string>(),
|
||||||
|
}));
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
const categories = new Set(filter.category_id ? [filter.category_id] : []);
|
const categories = new Set(filter.category_id ? [filter.category_id] : []);
|
||||||
let changed = true;
|
let changed = true;
|
||||||
@@ -115,6 +143,7 @@ export function Transactions({
|
|||||||
(!filter.from || f.booking_date >= filter.from) &&
|
(!filter.from || f.booking_date >= filter.from) &&
|
||||||
(!filter.to || f.booking_date <= filter.to) &&
|
(!filter.to || f.booking_date <= filter.to) &&
|
||||||
(!filter.currency || f.currency === filter.currency) &&
|
(!filter.currency || f.currency === filter.currency) &&
|
||||||
|
(!filter.account_id || f.account_id === filter.account_id) &&
|
||||||
(!filter.category_id || categories.has(e.category_id || "")) &&
|
(!filter.category_id || categories.has(e.category_id || "")) &&
|
||||||
(!needsReview ||
|
(!needsReview ||
|
||||||
e.classification.confidence !== "high" ||
|
e.classification.confidence !== "high" ||
|
||||||
@@ -122,7 +151,15 @@ export function Transactions({
|
|||||||
(e.kind === "income"
|
(e.kind === "income"
|
||||||
? "cat_income_unclassified"
|
? "cat_income_unclassified"
|
||||||
: "cat_expenses_unclassified")) &&
|
: "cat_expenses_unclassified")) &&
|
||||||
(!filter.tag_id || e.tag_ids.includes(filter.tag_id)) &&
|
(!status ||
|
||||||
|
(status === "unclassified"
|
||||||
|
? ["fallback", "unclassified", ""].includes(
|
||||||
|
e.classification.source || "",
|
||||||
|
)
|
||||||
|
: e.classification.source === status)) &&
|
||||||
|
(!filter.tag_ids.length ||
|
||||||
|
filter.tag_ids.some((id) => e.tag_ids.includes(id))) &&
|
||||||
|
!filter.exclude_tag_ids.some((id) => e.tag_ids.includes(id)) &&
|
||||||
(!filter.merchant_id || e.merchant_id === filter.merchant_id) &&
|
(!filter.merchant_id || e.merchant_id === filter.merchant_id) &&
|
||||||
(!query ||
|
(!query ||
|
||||||
`${f.raw_description} ${f.counterparty || ""} ${data.merchants.find((m) => m.id === e.merchant_id)?.name || ""} ${f.amount}`
|
`${f.raw_description} ${f.counterparty || ""} ${data.merchants.find((m) => m.id === e.merchant_id)?.name || ""} ${f.amount}`
|
||||||
@@ -134,11 +171,44 @@ export function Transactions({
|
|||||||
b.facts.booking_date.localeCompare(a.facts.booking_date) ||
|
b.facts.booking_date.localeCompare(a.facts.booking_date) ||
|
||||||
a.facts.id.localeCompare(b.facts.id),
|
a.facts.id.localeCompare(b.facts.id),
|
||||||
);
|
);
|
||||||
}, [data, filter, query, needsReview]);
|
}, [data, filter, query, needsReview, status]);
|
||||||
const currentPage = Math.min(
|
const currentPage = Math.min(
|
||||||
page,
|
page,
|
||||||
Math.max(0, Math.ceil(filtered.length / 40) - 1),
|
Math.max(0, Math.ceil(filtered.length / 40) - 1),
|
||||||
);
|
);
|
||||||
|
const pageTransactions = filtered.slice(
|
||||||
|
currentPage * 40,
|
||||||
|
currentPage * 40 + 40,
|
||||||
|
);
|
||||||
|
const selectedTransactions = useMemo(
|
||||||
|
() => filtered.filter((tx) => selection.ids.has(tx.facts.id)),
|
||||||
|
[filtered, selection.ids],
|
||||||
|
);
|
||||||
|
// Reset before rendering children, including when shared filters change
|
||||||
|
// outside this view. A refresh may also remove rows from the matching set.
|
||||||
|
if (selection.scope !== selectionScope) {
|
||||||
|
setSelection({ scope: selectionScope, ids: new Set() });
|
||||||
|
setBulkEditing(false);
|
||||||
|
} else if (selectedTransactions.length !== selection.ids.size) {
|
||||||
|
setSelection({
|
||||||
|
scope: selectionScope,
|
||||||
|
ids: new Set(selectedTransactions.map((tx) => tx.facts.id)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const selectedPageCount = pageTransactions.reduce(
|
||||||
|
(count, tx) => count + Number(selection.ids.has(tx.facts.id)),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const clearSelection = () =>
|
||||||
|
setSelection({ scope: selectionScope, ids: new Set() });
|
||||||
|
const toggleSelected = (id: string) => {
|
||||||
|
setSelection((current) => {
|
||||||
|
const ids = new Set(current.ids);
|
||||||
|
if (ids.has(id)) ids.delete(id);
|
||||||
|
else ids.add(id);
|
||||||
|
return { scope: selectionScope, ids };
|
||||||
|
});
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="section-heading">
|
<div className="section-heading">
|
||||||
@@ -146,7 +216,21 @@ export function Transactions({
|
|||||||
<h2>Transactions</h2>
|
<h2>Transactions</h2>
|
||||||
<p>Your bank facts stay untouched. Make the meaning your own.</p>
|
<p>Your bank facts stay untouched. Make the meaning your own.</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="badge neutral">{filtered.length} transactions</span>
|
<div className="bulk-heading-actions">
|
||||||
|
<span className="badge neutral">{filtered.length} transactions</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button secondary"
|
||||||
|
aria-pressed={bulk}
|
||||||
|
onClick={() => {
|
||||||
|
setBulk(!bulk);
|
||||||
|
setBulkEditing(false);
|
||||||
|
clearSelection();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{bulk ? "Cancel bulk edit" : "Bulk edit"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Filters
|
<Filters
|
||||||
data={data}
|
data={data}
|
||||||
@@ -181,16 +265,108 @@ export function Transactions({
|
|||||||
/>
|
/>
|
||||||
Needs review
|
Needs review
|
||||||
</label>
|
</label>
|
||||||
|
<select
|
||||||
|
className="toolbar-select"
|
||||||
|
aria-label="Classification status"
|
||||||
|
value={status}
|
||||||
|
onChange={(e) => {
|
||||||
|
setStatus(e.target.value);
|
||||||
|
setPage(0);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">All classifications</option>
|
||||||
|
{CLASSIFICATION_FILTERS.map(([value, label]) => (
|
||||||
|
<option key={value} value={value}>
|
||||||
|
{label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
<span className="muted small">
|
<span className="muted small">
|
||||||
<SlidersHorizontal size={15} /> Click a transaction to edit
|
<SlidersHorizontal size={15} />{" "}
|
||||||
|
{bulk
|
||||||
|
? "Click a transaction to select"
|
||||||
|
: "Click a transaction to edit"}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
{bulk && (
|
||||||
|
<div className="bulk-toolbar">
|
||||||
|
<div className="bulk-selection-summary">
|
||||||
|
<strong role="status" aria-live="polite">
|
||||||
|
{selectedTransactions.length} selected
|
||||||
|
</strong>
|
||||||
|
<span className="muted small">
|
||||||
|
Selection follows you across pages. Changing a filter clears it.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="bulk-selection-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button secondary"
|
||||||
|
disabled={
|
||||||
|
!filtered.length ||
|
||||||
|
selectedTransactions.length === filtered.length
|
||||||
|
}
|
||||||
|
onClick={() =>
|
||||||
|
setSelection({
|
||||||
|
scope: selectionScope,
|
||||||
|
ids: new Set(filtered.map((tx) => tx.facts.id)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Select all {filtered.length} matching
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button subtle"
|
||||||
|
disabled={!selectedTransactions.length}
|
||||||
|
onClick={clearSelection}
|
||||||
|
>
|
||||||
|
Clear selection
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button primary"
|
||||||
|
disabled={!selectedTransactions.length}
|
||||||
|
onClick={() => setBulkEditing(true)}
|
||||||
|
>
|
||||||
|
Edit selected ({selectedTransactions.length})
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{filtered.length ? (
|
{filtered.length ? (
|
||||||
<>
|
<>
|
||||||
<div className="table-scroll">
|
<div className="table-scroll">
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
|
{bulk && (
|
||||||
|
<th className="transaction-selection">
|
||||||
|
<label className="transaction-select-control">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
aria-label={`Select all ${pageTransactions.length} transactions on this page`}
|
||||||
|
checked={
|
||||||
|
selectedPageCount === pageTransactions.length
|
||||||
|
}
|
||||||
|
ref={(input) => {
|
||||||
|
if (input)
|
||||||
|
input.indeterminate =
|
||||||
|
selectedPageCount > 0 &&
|
||||||
|
selectedPageCount < pageTransactions.length;
|
||||||
|
}}
|
||||||
|
onChange={(event) => {
|
||||||
|
const ids = new Set(selection.ids);
|
||||||
|
for (const tx of pageTransactions) {
|
||||||
|
if (event.target.checked) ids.add(tx.facts.id);
|
||||||
|
else ids.delete(tx.facts.id);
|
||||||
|
}
|
||||||
|
setSelection({ scope: selectionScope, ids });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</th>
|
||||||
|
)}
|
||||||
<th>Date / account</th>
|
<th>Date / account</th>
|
||||||
<th>Transaction</th>
|
<th>Transaction</th>
|
||||||
<th>Category / tags</th>
|
<th>Category / tags</th>
|
||||||
@@ -199,107 +375,128 @@ export function Transactions({
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{filtered
|
{pageTransactions.map((tx) => {
|
||||||
.slice(currentPage * 40, currentPage * 40 + 40)
|
const { facts: f, enrichment: e } = tx;
|
||||||
.map((tx) => {
|
const investment = f.investment;
|
||||||
const { facts: f, enrichment: e } = tx;
|
const moves = positionOnly(investment);
|
||||||
const investment = f.investment;
|
const security = data.instruments.find(
|
||||||
const moves = positionOnly(investment);
|
(i) => i.id === investment?.instrument_id,
|
||||||
const security = data.instruments.find(
|
);
|
||||||
(i) => i.id === investment?.instrument_id,
|
return (
|
||||||
);
|
<tr
|
||||||
return (
|
key={f.id}
|
||||||
<tr key={f.id}>
|
className={
|
||||||
<td>
|
bulk && selection.ids.has(f.id)
|
||||||
<span className="nowrap">{f.booking_date}</span>
|
? "transaction-selected"
|
||||||
<small>
|
: undefined
|
||||||
{data.accounts.find((a) => a.id === f.account_id)
|
}
|
||||||
?.display_name || f.account_id}
|
>
|
||||||
</small>
|
{bulk && (
|
||||||
|
<td className="transaction-selection">
|
||||||
|
<label className="transaction-select-control">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={selection.ids.has(f.id)}
|
||||||
|
aria-label={`Select ${f.booking_date}, ${f.raw_description}, ${money(f.amount, f.currency)}, ${data.accounts.find((a) => a.id === f.account_id)?.display_name || f.account_id}`}
|
||||||
|
onChange={() => toggleSelected(f.id)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
)}
|
||||||
<button
|
<td>
|
||||||
className="transaction-link"
|
<span className="nowrap">{f.booking_date}</span>
|
||||||
onClick={() => setEditing(tx)}
|
<small>
|
||||||
>
|
{data.accounts.find((a) => a.id === f.account_id)
|
||||||
<span className={`transaction-icon ${e.kind}`}>
|
?.display_name || f.account_id}
|
||||||
{moves ? (
|
</small>
|
||||||
<Layers size={17} />
|
</td>
|
||||||
) : e.kind === "transfer" ? (
|
<td>
|
||||||
<ArrowLeftRight size={17} />
|
<button
|
||||||
) : f.amount.startsWith("-") ? (
|
className="transaction-link"
|
||||||
<ArrowUpRight size={17} />
|
aria-pressed={
|
||||||
) : (
|
bulk ? selection.ids.has(f.id) : undefined
|
||||||
<ArrowDownLeft size={17} />
|
}
|
||||||
)}
|
onClick={() =>
|
||||||
</span>
|
bulk ? toggleSelected(f.id) : setEditing(tx)
|
||||||
<span>
|
}
|
||||||
<strong>
|
|
||||||
{data.merchants.find(
|
|
||||||
(m) => m.id === e.merchant_id,
|
|
||||||
)?.name ||
|
|
||||||
f.counterparty ||
|
|
||||||
(investment
|
|
||||||
? security?.name || f.raw_description
|
|
||||||
: "Bank transaction")}
|
|
||||||
</strong>
|
|
||||||
{(!investment ||
|
|
||||||
f.raw_description !== security?.name) && (
|
|
||||||
<small className="description">
|
|
||||||
{f.raw_description}
|
|
||||||
</small>
|
|
||||||
)}
|
|
||||||
{investment && (
|
|
||||||
<small className="description">
|
|
||||||
{EVENTS[investment.event] ||
|
|
||||||
investment.event}
|
|
||||||
{investment.quantity
|
|
||||||
? ` · ${signedQuantity(investment.quantity)} shares`
|
|
||||||
: ""}
|
|
||||||
{investment.price
|
|
||||||
? ` @ ${investment.price} ${f.currency}`
|
|
||||||
: ""}
|
|
||||||
{moves ? " · position only, no cash" : ""}
|
|
||||||
</small>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span>
|
|
||||||
{e.kind === "transfer"
|
|
||||||
? "Own-account transfer"
|
|
||||||
: e.kind === "investment"
|
|
||||||
? "Investment ledger"
|
|
||||||
: categoryPath(data, e.category_id)}
|
|
||||||
</span>
|
|
||||||
<div className="chips">
|
|
||||||
{e.tag_ids.map((id) => (
|
|
||||||
<span className="badge" key={id}>
|
|
||||||
{data.tags.find((t) => t.id === id)?.name ||
|
|
||||||
id}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span className="badge neutral">
|
|
||||||
{e.classification.source}
|
|
||||||
</span>
|
|
||||||
{e.classification.error && (
|
|
||||||
<small className="text-danger">
|
|
||||||
Classification error
|
|
||||||
</small>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td
|
|
||||||
className={`numeric money ${f.amount.startsWith("-") ? "" : "positive"}`}
|
|
||||||
>
|
>
|
||||||
{money(f.amount, f.currency)}
|
<span className={`transaction-icon ${e.kind}`}>
|
||||||
</td>
|
{moves ? (
|
||||||
</tr>
|
<Layers size={17} />
|
||||||
);
|
) : e.kind === "transfer" ? (
|
||||||
})}
|
<ArrowLeftRight size={17} />
|
||||||
|
) : f.amount.startsWith("-") ? (
|
||||||
|
<ArrowUpRight size={17} />
|
||||||
|
) : (
|
||||||
|
<ArrowDownLeft size={17} />
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<strong>
|
||||||
|
{data.merchants.find(
|
||||||
|
(m) => m.id === e.merchant_id,
|
||||||
|
)?.name ||
|
||||||
|
f.counterparty ||
|
||||||
|
(investment
|
||||||
|
? security?.name || f.raw_description
|
||||||
|
: "Bank transaction")}
|
||||||
|
</strong>
|
||||||
|
{(!investment ||
|
||||||
|
f.raw_description !== security?.name) && (
|
||||||
|
<small className="description">
|
||||||
|
{f.raw_description}
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
|
{investment && (
|
||||||
|
<small className="description">
|
||||||
|
{EVENTS[investment.event] || investment.event}
|
||||||
|
{investment.quantity
|
||||||
|
? ` · ${signedQuantity(investment.quantity)} shares`
|
||||||
|
: ""}
|
||||||
|
{investment.price
|
||||||
|
? ` @ ${investment.price} ${f.currency}`
|
||||||
|
: ""}
|
||||||
|
{moves ? " · position only, no cash" : ""}
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span>
|
||||||
|
{e.kind === "transfer"
|
||||||
|
? "Own-account transfer"
|
||||||
|
: e.kind === "investment"
|
||||||
|
? "Investment ledger"
|
||||||
|
: categoryPath(data, e.category_id)}
|
||||||
|
</span>
|
||||||
|
<div className="chips">
|
||||||
|
{e.tag_ids.map((id) => (
|
||||||
|
<span className="badge" key={id}>
|
||||||
|
{data.tags.find((t) => t.id === id)?.name || id}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className="badge neutral">
|
||||||
|
{CLASSIFICATIONS[e.classification.source] ??
|
||||||
|
e.classification.source}
|
||||||
|
</span>
|
||||||
|
{e.classification.error && (
|
||||||
|
<small className="text-danger">
|
||||||
|
Classification error
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
className={`numeric money ${f.amount.startsWith("-") ? "" : "positive"}`}
|
||||||
|
>
|
||||||
|
{money(f.amount, f.currency)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
@@ -352,9 +549,271 @@ export function Transactions({
|
|||||||
close={() => setEditing(null)}
|
close={() => setEditing(null)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{bulkEditing && selectedTransactions.length > 0 && (
|
||||||
|
<BulkTransactionEditor
|
||||||
|
data={data}
|
||||||
|
transactions={selectedTransactions}
|
||||||
|
mutate={mutate}
|
||||||
|
close={() => setBulkEditing(false)}
|
||||||
|
saved={() => {
|
||||||
|
setBulkEditing(false);
|
||||||
|
clearSelection();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
function BulkTransactionEditor({
|
||||||
|
data,
|
||||||
|
transactions,
|
||||||
|
mutate,
|
||||||
|
close,
|
||||||
|
saved,
|
||||||
|
}: {
|
||||||
|
data: Dataset;
|
||||||
|
transactions: Transaction[];
|
||||||
|
mutate: Mutate;
|
||||||
|
close: () => void;
|
||||||
|
saved: () => void;
|
||||||
|
}) {
|
||||||
|
const [categoryMode, setCategoryMode] = useState("keep");
|
||||||
|
const [categoryId, setCategoryId] = useState("");
|
||||||
|
const [merchantMode, setMerchantMode] = useState("keep");
|
||||||
|
const [merchantId, setMerchantId] = useState("");
|
||||||
|
const [addTagIds, setAddTagIds] = useState<string[]>([]);
|
||||||
|
const [removeTagIds, setRemoveTagIds] = useState<string[]>([]);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const submitting = useRef(false);
|
||||||
|
const canEditMerchant = transactions.every(
|
||||||
|
(tx) => tx.enrichment.kind === "expense" || tx.enrichment.kind === "income",
|
||||||
|
);
|
||||||
|
const categoryKind = transactions[0].enrichment.kind;
|
||||||
|
const canEditCategory =
|
||||||
|
canEditMerchant &&
|
||||||
|
transactions.every((tx) => tx.enrichment.kind === categoryKind);
|
||||||
|
const operations: string[] = [];
|
||||||
|
if (categoryMode === "set" && categoryId)
|
||||||
|
operations.push(`Set category to ${categoryPath(data, categoryId)}`);
|
||||||
|
if (merchantMode === "assign" && merchantId)
|
||||||
|
operations.push(
|
||||||
|
`Set merchant to ${data.merchants.find((m) => m.id === merchantId)?.name || merchantId}`,
|
||||||
|
);
|
||||||
|
if (merchantMode === "clear") operations.push("Clear merchant");
|
||||||
|
if (addTagIds.length)
|
||||||
|
operations.push(
|
||||||
|
`Add tags: ${addTagIds.map((id) => data.tags.find((tag) => tag.id === id)?.name || id).join(", ")}`,
|
||||||
|
);
|
||||||
|
if (removeTagIds.length)
|
||||||
|
operations.push(
|
||||||
|
`Remove tags: ${removeTagIds.map((id) => data.tags.find((tag) => tag.id === id)?.name || id).join(", ")}`,
|
||||||
|
);
|
||||||
|
const valid =
|
||||||
|
operations.length > 0 &&
|
||||||
|
(categoryMode === "keep" || (canEditCategory && !!categoryId)) &&
|
||||||
|
(merchantMode === "keep" ||
|
||||||
|
(canEditMerchant && (merchantMode === "clear" || !!merchantId)));
|
||||||
|
const closeWhenIdle = () => {
|
||||||
|
if (!submitting.current) close();
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
title={`Edit ${transactions.length} selected transactions`}
|
||||||
|
close={closeWhenIdle}
|
||||||
|
dismissible={!busy}
|
||||||
|
wide
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
aria-busy={busy}
|
||||||
|
onSubmit={async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (submitting.current || !valid) return;
|
||||||
|
submitting.current = true;
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
transaction_ids: transactions.map((tx) => tx.facts.id),
|
||||||
|
};
|
||||||
|
if (categoryMode === "set") body.category_id = categoryId;
|
||||||
|
if (merchantMode !== "keep")
|
||||||
|
body.merchant_id = merchantMode === "clear" ? "" : merchantId;
|
||||||
|
if (addTagIds.length) body.add_tag_ids = addTagIds;
|
||||||
|
if (removeTagIds.length) body.remove_tag_ids = removeTagIds;
|
||||||
|
try {
|
||||||
|
await mutate(
|
||||||
|
"/api/transactions/bulk",
|
||||||
|
body,
|
||||||
|
`${transactions.length} transactions updated`,
|
||||||
|
);
|
||||||
|
saved();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
|
} finally {
|
||||||
|
submitting.current = false;
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="form-body">
|
||||||
|
<ErrorMessage error={error} />
|
||||||
|
<p className="muted">
|
||||||
|
Choose only the fields to change. Every chosen operation applies to
|
||||||
|
all {transactions.length} selected transactions, or none are saved.
|
||||||
|
</p>
|
||||||
|
<fieldset
|
||||||
|
className="bulk-edit-fields"
|
||||||
|
disabled={busy}
|
||||||
|
aria-label="Bulk changes"
|
||||||
|
>
|
||||||
|
<div className="two-columns">
|
||||||
|
<div className="bulk-field-group">
|
||||||
|
<Field
|
||||||
|
label="Category change"
|
||||||
|
hint={
|
||||||
|
!canEditMerchant
|
||||||
|
? "Category changes are unavailable because the selection includes a transfer or investment. Tags can still be edited for every selected row."
|
||||||
|
: !canEditCategory
|
||||||
|
? "Category changes require only expenses or only income. This selection contains both; no rows will be skipped."
|
||||||
|
: "Choose a compatible leaf category, including Unclassified. Categories cannot be cleared."
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<select
|
||||||
|
value={categoryMode}
|
||||||
|
disabled={!canEditCategory}
|
||||||
|
onChange={(event) => setCategoryMode(event.target.value)}
|
||||||
|
>
|
||||||
|
<option value="keep">Leave category unchanged</option>
|
||||||
|
<option value="set">Set category</option>
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
{categoryMode === "set" && canEditCategory && (
|
||||||
|
<Field label="New category">
|
||||||
|
<CategoryCombobox
|
||||||
|
data={data}
|
||||||
|
kind={categoryKind}
|
||||||
|
leavesOnly
|
||||||
|
required
|
||||||
|
disabled={busy}
|
||||||
|
placeholder="Choose a category"
|
||||||
|
value={categoryId}
|
||||||
|
onChange={setCategoryId}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="bulk-field-group">
|
||||||
|
<Field
|
||||||
|
label="Merchant change"
|
||||||
|
hint={
|
||||||
|
canEditMerchant
|
||||||
|
? "Assign a merchant or explicitly clear it for every selected transaction."
|
||||||
|
: "Merchant changes are unavailable because the selection includes a transfer or investment. Tags can still be edited for every selected row."
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<select
|
||||||
|
value={merchantMode}
|
||||||
|
disabled={!canEditMerchant}
|
||||||
|
onChange={(event) => setMerchantMode(event.target.value)}
|
||||||
|
>
|
||||||
|
<option value="keep">Leave merchant unchanged</option>
|
||||||
|
<option value="assign">Assign merchant</option>
|
||||||
|
<option value="clear">Clear merchant</option>
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
{merchantMode === "assign" && canEditMerchant && (
|
||||||
|
<Field label="New merchant">
|
||||||
|
<select
|
||||||
|
value={merchantId}
|
||||||
|
required
|
||||||
|
onChange={(event) => setMerchantId(event.target.value)}
|
||||||
|
>
|
||||||
|
<option value="">Choose a merchant</option>
|
||||||
|
{data.merchants.map((merchant) => (
|
||||||
|
<option key={merchant.id} value={merchant.id}>
|
||||||
|
{merchant.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bulk-field-group">
|
||||||
|
<p className="muted small">
|
||||||
|
Other tags stay unchanged. Choosing a tag in one group removes
|
||||||
|
it from the other group.
|
||||||
|
</p>
|
||||||
|
<TagPicker
|
||||||
|
label="Add tags to every selected transaction"
|
||||||
|
data={data}
|
||||||
|
value={addTagIds}
|
||||||
|
onChange={(ids) => {
|
||||||
|
setAddTagIds(ids);
|
||||||
|
setRemoveTagIds((current) =>
|
||||||
|
current.filter((id) => !ids.includes(id)),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<TagPicker
|
||||||
|
label="Remove tags from every selected transaction"
|
||||||
|
data={data}
|
||||||
|
value={removeTagIds}
|
||||||
|
onChange={(ids) => {
|
||||||
|
setRemoveTagIds(ids);
|
||||||
|
setAddTagIds((current) =>
|
||||||
|
current.filter((id) => !ids.includes(id)),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
<section
|
||||||
|
className="bulk-operation-summary"
|
||||||
|
aria-label="Changes to apply"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
<h3>Apply to {transactions.length} transactions</h3>
|
||||||
|
{operations.length ? (
|
||||||
|
<ul>
|
||||||
|
{operations.map((operation, index) => (
|
||||||
|
<li key={index}>{operation}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<p className="muted">No changes chosen yet.</p>
|
||||||
|
)}
|
||||||
|
<p className="muted small">
|
||||||
|
Unselected fields stay unchanged. Saving marks each selected row
|
||||||
|
as manually classified. Bank facts, transaction kinds and transfer
|
||||||
|
links never change.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<div className="form-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button secondary"
|
||||||
|
onClick={closeWhenIdle}
|
||||||
|
disabled={busy}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="button primary"
|
||||||
|
disabled={busy || !valid}
|
||||||
|
>
|
||||||
|
{busy
|
||||||
|
? "Applying…"
|
||||||
|
: `Apply to ${transactions.length} transactions`}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function TransactionEditor({
|
function TransactionEditor({
|
||||||
data,
|
data,
|
||||||
transaction,
|
transaction,
|
||||||
@@ -452,17 +911,22 @@ function TransactionEditor({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{value.kind !== "transfer" && value.kind !== "investment" && (
|
{value.kind !== "transfer" && value.kind !== "investment" && (
|
||||||
<Field label="Category">
|
<Field
|
||||||
<select
|
label="Category"
|
||||||
|
hint="Choose a leaf category. To add one now, type a new name and choose “Create category”. Use “Parent / Child” to nest it under an existing category."
|
||||||
|
>
|
||||||
|
<CategoryCombobox
|
||||||
|
data={data}
|
||||||
|
kind={value.kind}
|
||||||
|
leavesOnly
|
||||||
required
|
required
|
||||||
|
mutate={mutate}
|
||||||
|
placeholder="Select or type to add a category"
|
||||||
value={value.category_id || ""}
|
value={value.category_id || ""}
|
||||||
onChange={(e) =>
|
onChange={(category_id) =>
|
||||||
setValue({ ...value, category_id: e.target.value })
|
setValue((v) => ({ ...v, category_id }))
|
||||||
}
|
}
|
||||||
>
|
/>
|
||||||
<option value="">Choose category</option>
|
|
||||||
<CategoryOptions data={data} kind={value.kind} />
|
|
||||||
</select>
|
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
<TransferLink
|
<TransferLink
|
||||||
@@ -474,7 +938,8 @@ function TransactionEditor({
|
|||||||
<TagPicker
|
<TagPicker
|
||||||
data={data}
|
data={data}
|
||||||
value={value.tag_ids}
|
value={value.tag_ids}
|
||||||
onChange={(tag_ids) => setValue({ ...value, tag_ids })}
|
onChange={(tag_ids) => setValue((v) => ({ ...v, tag_ids }))}
|
||||||
|
mutate={mutate}
|
||||||
/>
|
/>
|
||||||
<details open>
|
<details open>
|
||||||
<summary>
|
<summary>
|
||||||
|
|||||||
+323
-7
@@ -3,12 +3,30 @@ import {
|
|||||||
AlertTriangle,
|
AlertTriangle,
|
||||||
CandlestickChart,
|
CandlestickChart,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
|
Home,
|
||||||
Landmark,
|
Landmark,
|
||||||
|
Pencil,
|
||||||
PiggyBank,
|
PiggyBank,
|
||||||
|
Plus,
|
||||||
|
Trash2,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import type { QuoteResult, State, Wealth, WealthAccount } from "./api";
|
import type {
|
||||||
|
QuoteResult,
|
||||||
|
State,
|
||||||
|
Wealth,
|
||||||
|
WealthAccount,
|
||||||
|
WealthAsset,
|
||||||
|
} from "./api";
|
||||||
import { money, request } from "./api";
|
import { money, request } from "./api";
|
||||||
import { Empty, ErrorMessage } from "./ui";
|
import {
|
||||||
|
DateField,
|
||||||
|
Empty,
|
||||||
|
ErrorMessage,
|
||||||
|
Field,
|
||||||
|
FormActions,
|
||||||
|
Modal,
|
||||||
|
type Mutate,
|
||||||
|
} from "./ui";
|
||||||
|
|
||||||
// The report is recomputed from the journal, so it is keyed on the revision and
|
// The report is recomputed from the journal, so it is keyed on the revision and
|
||||||
// never cached: it exists to be compared with a bank or broker's own screen.
|
// never cached: it exists to be compared with a bank or broker's own screen.
|
||||||
@@ -17,9 +35,11 @@ import { Empty, ErrorMessage } from "./ui";
|
|||||||
export default function WealthPage({
|
export default function WealthPage({
|
||||||
revision,
|
revision,
|
||||||
acceptState,
|
acceptState,
|
||||||
|
mutate,
|
||||||
}: {
|
}: {
|
||||||
revision: string;
|
revision: string;
|
||||||
acceptState: (state: State, message?: string) => void;
|
acceptState: (state: State, message?: string) => void;
|
||||||
|
mutate: Mutate;
|
||||||
}) {
|
}) {
|
||||||
const [wealth, setWealth] = useState<Wealth | null>(null);
|
const [wealth, setWealth] = useState<Wealth | null>(null);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
@@ -33,7 +53,7 @@ export default function WealthPage({
|
|||||||
setError("");
|
setError("");
|
||||||
request<Wealth>("/api/wealth", undefined, controller.signal)
|
request<Wealth>("/api/wealth", undefined, controller.signal)
|
||||||
.then((value) => {
|
.then((value) => {
|
||||||
for (const key of ["accounts", "totals"] as const) {
|
for (const key of ["accounts", "assets", "totals"] as const) {
|
||||||
if (!(key in value))
|
if (!(key in value))
|
||||||
throw new Error(`Wealth response is missing ${key}.`);
|
throw new Error(`Wealth response is missing ${key}.`);
|
||||||
if (value[key] === null) Object.assign(value, { [key]: [] });
|
if (value[key] === null) Object.assign(value, { [key]: [] });
|
||||||
@@ -181,8 +201,9 @@ export default function WealthPage({
|
|||||||
Total wealth
|
Total wealth
|
||||||
</h3>
|
</h3>
|
||||||
<p>
|
<p>
|
||||||
Cash plus the market value of every priced holding, per
|
Cash, the market value of every priced holding, and your
|
||||||
currency, across all {wealth.accounts.length} account
|
other assets, per currency, across all{" "}
|
||||||
|
{wealth.accounts.length} account
|
||||||
{wealth.accounts.length === 1 ? "" : "s"}.
|
{wealth.accounts.length === 1 ? "" : "s"}.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -212,6 +233,14 @@ export default function WealthPage({
|
|||||||
</strong>{" "}
|
</strong>{" "}
|
||||||
in positions
|
in positions
|
||||||
</span>
|
</span>
|
||||||
|
{total.assets !== "0.00" && (
|
||||||
|
<span>
|
||||||
|
<strong className="money">
|
||||||
|
{money(total.assets, total.currency)}
|
||||||
|
</strong>{" "}
|
||||||
|
in other assets
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
{total.unpriced > 0 && (
|
{total.unpriced > 0 && (
|
||||||
<span>
|
<span>
|
||||||
<strong>{total.unpriced}</strong> holding
|
<strong>{total.unpriced}</strong> holding
|
||||||
@@ -224,6 +253,11 @@ export default function WealthPage({
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
<AssetsPanel
|
||||||
|
assets={wealth.assets}
|
||||||
|
currency={wealth.totals[0]?.currency ?? "EUR"}
|
||||||
|
mutate={mutate}
|
||||||
|
/>
|
||||||
{wealth.accounts.length === 0 ? (
|
{wealth.accounts.length === 0 ? (
|
||||||
<section className="panel">
|
<section className="panel">
|
||||||
<Empty title="No accounts to report on yet">
|
<Empty title="No accounts to report on yet">
|
||||||
@@ -275,8 +309,11 @@ export default function WealthPage({
|
|||||||
<dt>Completeness</dt>
|
<dt>Completeness</dt>
|
||||||
<dd>
|
<dd>
|
||||||
Cash equals the real balance only when the journal holds
|
Cash equals the real balance only when the journal holds
|
||||||
that account's full history: a broker export does, a
|
that account’s full history: a broker export does, a
|
||||||
date-windowed bank statement does not.
|
date-windowed bank statement does not. A connected bank
|
||||||
|
account closes that gap with an anchor — the bank’s
|
||||||
|
own booked balance, captured once — from which the start
|
||||||
|
balance before the recorded rows is derived.
|
||||||
</dd>
|
</dd>
|
||||||
</div>
|
</div>
|
||||||
</dl>
|
</dl>
|
||||||
@@ -476,3 +513,282 @@ function AccountReport({ account }: { account: WealthAccount }) {
|
|||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// AssetsPanel lists the hand-valued possessions counted into the total above
|
||||||
|
// and edits them in place: they live in the journal like any registry entity,
|
||||||
|
// but this page is where their figure matters, so this page manages them.
|
||||||
|
function AssetsPanel({
|
||||||
|
assets,
|
||||||
|
currency,
|
||||||
|
mutate,
|
||||||
|
}: {
|
||||||
|
assets: WealthAsset[];
|
||||||
|
currency: string;
|
||||||
|
mutate: Mutate;
|
||||||
|
}) {
|
||||||
|
const blank: WealthAsset = {
|
||||||
|
asset_id: "",
|
||||||
|
name: "",
|
||||||
|
kind: "",
|
||||||
|
currency,
|
||||||
|
value: "",
|
||||||
|
valued_at: new Date().toISOString().slice(0, 10),
|
||||||
|
};
|
||||||
|
const [editing, setEditing] = useState<WealthAsset | null>(null);
|
||||||
|
const [removing, setRemoving] = useState<WealthAsset | null>(null);
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<div className="panel-heading">
|
||||||
|
<div>
|
||||||
|
<h3>
|
||||||
|
<Home size={17} />
|
||||||
|
Other assets
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
Possessions you value by hand — a house, a car, a private loan —
|
||||||
|
counted into the total above. A negative value records a liability
|
||||||
|
such as a mortgage.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="row-actions">
|
||||||
|
<button
|
||||||
|
className="button secondary"
|
||||||
|
onClick={() => setEditing(blank)}
|
||||||
|
>
|
||||||
|
<Plus size={16} />
|
||||||
|
Add asset
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{assets.length === 0 ? (
|
||||||
|
<Empty title="No assets recorded yet">
|
||||||
|
Anything without a market feed goes here at the value you state, and
|
||||||
|
it joins the wealth figure immediately.
|
||||||
|
</Empty>
|
||||||
|
) : (
|
||||||
|
<div className="table-scroll">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Asset</th>
|
||||||
|
<th>Kind</th>
|
||||||
|
<th className="numeric">Value</th>
|
||||||
|
<th>Valued on</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{assets.map((asset) => (
|
||||||
|
<tr key={asset.asset_id}>
|
||||||
|
<td>{asset.name}</td>
|
||||||
|
<td className="muted">{asset.kind || "—"}</td>
|
||||||
|
<td
|
||||||
|
className={`numeric money ${asset.value.startsWith("-") ? "text-danger" : ""}`}
|
||||||
|
>
|
||||||
|
{money(asset.value, asset.currency)}
|
||||||
|
</td>
|
||||||
|
<td className="muted">{asset.valued_at}</td>
|
||||||
|
<td>
|
||||||
|
<div className="row-actions">
|
||||||
|
<button
|
||||||
|
className="icon-button"
|
||||||
|
aria-label={`Edit ${asset.name}`}
|
||||||
|
onClick={() => setEditing(asset)}
|
||||||
|
>
|
||||||
|
<Pencil size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="icon-button danger"
|
||||||
|
aria-label={`Delete ${asset.name}`}
|
||||||
|
onClick={() => setRemoving(asset)}
|
||||||
|
>
|
||||||
|
<Trash2 size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<p className="hint">
|
||||||
|
A value is what you state it is, dated so a stale estimate is
|
||||||
|
visible. Re-edit an asset when its worth changes.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{editing && (
|
||||||
|
<AssetEditor
|
||||||
|
asset={editing}
|
||||||
|
mutate={mutate}
|
||||||
|
close={() => setEditing(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{removing && (
|
||||||
|
<DeleteAsset
|
||||||
|
asset={removing}
|
||||||
|
mutate={mutate}
|
||||||
|
close={() => setRemoving(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function AssetEditor({
|
||||||
|
asset,
|
||||||
|
mutate,
|
||||||
|
close,
|
||||||
|
}: {
|
||||||
|
asset: WealthAsset;
|
||||||
|
mutate: Mutate;
|
||||||
|
close: () => void;
|
||||||
|
}) {
|
||||||
|
const [name, setName] = useState(asset.name);
|
||||||
|
const [kind, setKind] = useState(asset.kind || "");
|
||||||
|
const [currency, setCurrency] = useState(asset.currency);
|
||||||
|
const [value, setValue] = useState(asset.value);
|
||||||
|
const [valuedAt, setValuedAt] = useState(asset.valued_at);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
return (
|
||||||
|
<Modal title={asset.asset_id ? "Edit asset" : "New asset"} close={close}>
|
||||||
|
<form
|
||||||
|
onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await mutate(
|
||||||
|
"/api/assets",
|
||||||
|
{
|
||||||
|
asset: {
|
||||||
|
id: asset.asset_id,
|
||||||
|
name: name.trim(),
|
||||||
|
kind: kind.trim(),
|
||||||
|
currency: currency.toUpperCase(),
|
||||||
|
value: value.trim(),
|
||||||
|
valued_at: valuedAt,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
`${name.trim()} saved`,
|
||||||
|
);
|
||||||
|
close();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="form-body">
|
||||||
|
<ErrorMessage error={error} />
|
||||||
|
<Field label="Name">
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
maxLength={200}
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
placeholder="Family home"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="Kind" hint="Free text: Real estate, Vehicle, Loan…">
|
||||||
|
<input
|
||||||
|
maxLength={100}
|
||||||
|
value={kind}
|
||||||
|
onChange={(e) => setKind(e.target.value)}
|
||||||
|
placeholder="Real estate"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field
|
||||||
|
label="Value"
|
||||||
|
hint="Your own estimate. A negative value records a liability such as a mortgage."
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="-?\d+([.,]\d{1,4})?"
|
||||||
|
title="A decimal amount with up to four decimal places"
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => setValue(e.target.value.replace(",", "."))}
|
||||||
|
placeholder="250000"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="Currency">
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
maxLength={3}
|
||||||
|
pattern="[A-Za-z]{3}"
|
||||||
|
title="Three-letter currency code"
|
||||||
|
value={currency}
|
||||||
|
onChange={(e) => setCurrency(e.target.value.toUpperCase())}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<DateField
|
||||||
|
label="Valued on"
|
||||||
|
value={valuedAt}
|
||||||
|
onChange={setValuedAt}
|
||||||
|
hint="The day this estimate was made, so a stale figure is visible."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<FormActions
|
||||||
|
busy={busy}
|
||||||
|
close={close}
|
||||||
|
label={asset.asset_id ? "Save changes" : "Add asset"}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function DeleteAsset({
|
||||||
|
asset,
|
||||||
|
mutate,
|
||||||
|
close,
|
||||||
|
}: {
|
||||||
|
asset: WealthAsset;
|
||||||
|
mutate: Mutate;
|
||||||
|
close: () => void;
|
||||||
|
}) {
|
||||||
|
const [confirm, setConfirm] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
return (
|
||||||
|
<Modal title={`Delete ${asset.name}?`} close={close}>
|
||||||
|
<form
|
||||||
|
onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await mutate(
|
||||||
|
"/api/manage",
|
||||||
|
{ entity: "asset", action: "delete", id: asset.asset_id },
|
||||||
|
"Asset deleted",
|
||||||
|
);
|
||||||
|
close();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="form-body">
|
||||||
|
<ErrorMessage error={error} />
|
||||||
|
<p>
|
||||||
|
Its {money(asset.value, asset.currency)} leaves the wealth figure
|
||||||
|
immediately. Nothing else references an asset.
|
||||||
|
</p>
|
||||||
|
<label className="checkbox">
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
type="checkbox"
|
||||||
|
checked={confirm}
|
||||||
|
onChange={(e) => setConfirm(e.target.checked)}
|
||||||
|
/>
|
||||||
|
Permanently delete this asset.
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<FormActions busy={busy} close={close} label="Delete asset" />
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
+36
-2
@@ -11,6 +11,11 @@ export interface Account {
|
|||||||
// against: a broker export carries no counterparty, so its deposits and
|
// against: a broker export carries no counterparty, so its deposits and
|
||||||
// withdrawals pair with the funding account through this IBAN.
|
// withdrawals pair with the funding account through this IBAN.
|
||||||
reference_iban?: string;
|
reference_iban?: string;
|
||||||
|
// anchor_balance is the bank's booked balance on anchor_date, captured once
|
||||||
|
// from open banking after a sync. It fixes the start balance of a
|
||||||
|
// date-windowed history; clearing both lets the next sync re-anchor.
|
||||||
|
anchor_balance?: string;
|
||||||
|
anchor_date?: string;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
}
|
}
|
||||||
// Instrument is a security held in an investment account. The ISIN is the
|
// Instrument is a security held in an investment account. The ISIN is the
|
||||||
@@ -27,6 +32,17 @@ export interface Instrument {
|
|||||||
quote?: string;
|
quote?: string;
|
||||||
quoted_at?: string;
|
quoted_at?: string;
|
||||||
}
|
}
|
||||||
|
// Asset is a possession valued by hand: a house, a car, anything without a
|
||||||
|
// market feed. value is what the owner states it is worth and valued_at the
|
||||||
|
// day that estimate was made. A negative value records a liability.
|
||||||
|
export interface Asset {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
kind?: string;
|
||||||
|
currency: string;
|
||||||
|
value: string;
|
||||||
|
valued_at: string;
|
||||||
|
}
|
||||||
// Investment is the broker-native leg of a fact. Cash movement always stays in
|
// Investment is the broker-native leg of a fact. Cash movement always stays in
|
||||||
// Facts.amount, so a position-only event carries a zero amount. Quantity is an
|
// Facts.amount, so a position-only event carries a zero amount. Quantity is an
|
||||||
// exact signed decimal, not money: negative removes from the holding.
|
// exact signed decimal, not money: negative removes from the holding.
|
||||||
@@ -107,6 +123,7 @@ export interface Dataset {
|
|||||||
tags: Tag[];
|
tags: Tag[];
|
||||||
merchants: Merchant[];
|
merchants: Merchant[];
|
||||||
instruments: Instrument[];
|
instruments: Instrument[];
|
||||||
|
assets: Asset[];
|
||||||
transactions: Transaction[];
|
transactions: Transaction[];
|
||||||
}
|
}
|
||||||
export interface Connection {
|
export interface Connection {
|
||||||
@@ -197,7 +214,8 @@ export interface Filter {
|
|||||||
currency: string;
|
currency: string;
|
||||||
account_id: string;
|
account_id: string;
|
||||||
category_id: string;
|
category_id: string;
|
||||||
tag_id: string;
|
tag_ids: string[];
|
||||||
|
exclude_tag_ids: string[];
|
||||||
merchant_id: string;
|
merchant_id: string;
|
||||||
}
|
}
|
||||||
export interface Preview {
|
export interface Preview {
|
||||||
@@ -384,13 +402,27 @@ export interface WealthTotal {
|
|||||||
currency: string;
|
currency: string;
|
||||||
cash: string;
|
cash: string;
|
||||||
positions: string;
|
positions: string;
|
||||||
|
// assets is the stated value of every hand-valued asset in this currency,
|
||||||
|
// and wealth is cash, positions and assets together.
|
||||||
|
assets: string;
|
||||||
wealth: string;
|
wealth: string;
|
||||||
unpriced: number;
|
unpriced: number;
|
||||||
}
|
}
|
||||||
|
// WealthAsset is one hand-valued asset as the journal records it: the value is
|
||||||
|
// stated, never quoted, and carries the day it was stated.
|
||||||
|
export interface WealthAsset {
|
||||||
|
asset_id: string;
|
||||||
|
name: string;
|
||||||
|
kind?: string;
|
||||||
|
currency: string;
|
||||||
|
value: string;
|
||||||
|
valued_at: string;
|
||||||
|
}
|
||||||
// Wealth is a reconciliation report computed from the journal rather than the
|
// Wealth is a reconciliation report computed from the journal rather than the
|
||||||
// analytics index, so it can be checked against a bank or broker's own screen.
|
// analytics index, so it can be checked against a bank or broker's own screen.
|
||||||
export interface Wealth {
|
export interface Wealth {
|
||||||
accounts: WealthAccount[];
|
accounts: WealthAccount[];
|
||||||
|
assets: WealthAsset[];
|
||||||
totals: WealthTotal[];
|
totals: WealthTotal[];
|
||||||
}
|
}
|
||||||
export class APIError extends Error {
|
export class APIError extends Error {
|
||||||
@@ -461,6 +493,7 @@ export function normalizeState(state: State): State {
|
|||||||
"tags",
|
"tags",
|
||||||
"merchants",
|
"merchants",
|
||||||
"instruments",
|
"instruments",
|
||||||
|
"assets",
|
||||||
"transactions",
|
"transactions",
|
||||||
] as const) {
|
] as const) {
|
||||||
if (!(key in state.data))
|
if (!(key in state.data))
|
||||||
@@ -546,7 +579,8 @@ export const emptyFilter: Filter = {
|
|||||||
currency: "",
|
currency: "",
|
||||||
account_id: "",
|
account_id: "",
|
||||||
category_id: "",
|
category_id: "",
|
||||||
tag_id: "",
|
tag_ids: [],
|
||||||
|
exclude_tag_ids: [],
|
||||||
merchant_id: "",
|
merchant_id: "",
|
||||||
};
|
};
|
||||||
// A six-month window is the default view: long enough to show a trend and a
|
// A six-month window is the default view: long enough to show a trend and a
|
||||||
|
|||||||
+50
-24
@@ -64,7 +64,39 @@ function App() {
|
|||||||
const [refreshing, setRefreshing] = useState(false);
|
const [refreshing, setRefreshing] = useState(false);
|
||||||
const [notice, setNotice] = useState("");
|
const [notice, setNotice] = useState("");
|
||||||
const [mobileNav, setMobileNav] = useState(false);
|
const [mobileNav, setMobileNav] = useState(false);
|
||||||
const [filter, setFilter] = useState(defaultFilter);
|
const [filter, setFilter] = useState(() => {
|
||||||
|
const initial = defaultFilter();
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(
|
||||||
|
localStorage.getItem("finance-duck.tag-filters") || "null",
|
||||||
|
);
|
||||||
|
for (const key of ["tag_ids", "exclude_tag_ids"] as const) {
|
||||||
|
if (Array.isArray(saved?.[key])) {
|
||||||
|
initial[key] = [
|
||||||
|
...new Set<string>(
|
||||||
|
saved[key].filter((id: unknown) => typeof id === "string" && id),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Unavailable storage or an invalid saved value must not block the journal.
|
||||||
|
}
|
||||||
|
return initial;
|
||||||
|
});
|
||||||
|
useEffect(() => {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(
|
||||||
|
"finance-duck.tag-filters",
|
||||||
|
JSON.stringify({
|
||||||
|
tag_ids: filter.tag_ids,
|
||||||
|
exclude_tag_ids: filter.exclude_tag_ids,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// Filters still work for this visit when browser storage is unavailable.
|
||||||
|
}
|
||||||
|
}, [filter.tag_ids, filter.exclude_tag_ids]);
|
||||||
const acceptState = useCallback((value: State, message?: string) => {
|
const acceptState = useCallback((value: State, message?: string) => {
|
||||||
setState(normalizeState(value));
|
setState(normalizeState(value));
|
||||||
setConflict(false);
|
setConflict(false);
|
||||||
@@ -136,13 +168,12 @@ function App() {
|
|||||||
"/api/rebuild",
|
"/api/rebuild",
|
||||||
].includes(path);
|
].includes(path);
|
||||||
try {
|
try {
|
||||||
acceptState(
|
const next = await request<State>(
|
||||||
await request<State>(
|
path,
|
||||||
path,
|
revisionless ? body : { revision: state.revision, ...body },
|
||||||
revisionless ? body : { revision: state.revision, ...body },
|
|
||||||
),
|
|
||||||
message,
|
|
||||||
);
|
);
|
||||||
|
acceptState(next, message);
|
||||||
|
return next;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof APIError && err.status === 409) setConflict(true);
|
if (err instanceof APIError && err.status === 409) setConflict(true);
|
||||||
throw err;
|
throw err;
|
||||||
@@ -352,7 +383,6 @@ function App() {
|
|||||||
)}
|
)}
|
||||||
{page === "transactions" && (
|
{page === "transactions" && (
|
||||||
<Transactions
|
<Transactions
|
||||||
key={state.revision}
|
|
||||||
data={state.data}
|
data={state.data}
|
||||||
filter={filter}
|
filter={filter}
|
||||||
setFilter={setFilter}
|
setFilter={setFilter}
|
||||||
@@ -361,7 +391,6 @@ function App() {
|
|||||||
)}
|
)}
|
||||||
{page === "categories" && (
|
{page === "categories" && (
|
||||||
<Registry
|
<Registry
|
||||||
key={`categories-${state.revision}`}
|
|
||||||
entity="category"
|
entity="category"
|
||||||
data={state.data}
|
data={state.data}
|
||||||
mutate={mutate}
|
mutate={mutate}
|
||||||
@@ -371,24 +400,13 @@ function App() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{page === "tags" && (
|
{page === "tags" && (
|
||||||
<Registry
|
<Registry entity="tag" data={state.data} mutate={mutate} />
|
||||||
key={`tags-${state.revision}`}
|
|
||||||
entity="tag"
|
|
||||||
data={state.data}
|
|
||||||
mutate={mutate}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
{page === "merchants" && (
|
{page === "merchants" && (
|
||||||
<Registry
|
<Registry entity="merchant" data={state.data} mutate={mutate} />
|
||||||
key={`merchants-${state.revision}`}
|
|
||||||
entity="merchant"
|
|
||||||
data={state.data}
|
|
||||||
mutate={mutate}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
{page === "instruments" && (
|
{page === "instruments" && (
|
||||||
<Registry
|
<Registry
|
||||||
key={`instruments-${state.revision}`}
|
|
||||||
entity="instrument"
|
entity="instrument"
|
||||||
data={state.data}
|
data={state.data}
|
||||||
mutate={mutate}
|
mutate={mutate}
|
||||||
@@ -402,10 +420,18 @@ function App() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{page === "wealth" && (
|
{page === "wealth" && (
|
||||||
<Wealth revision={state.revision} acceptState={acceptState} />
|
<Wealth
|
||||||
|
revision={state.revision}
|
||||||
|
acceptState={acceptState}
|
||||||
|
mutate={mutate}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{page === "classification" && (
|
{page === "classification" && (
|
||||||
<Classification state={state} acceptState={acceptState} />
|
<Classification
|
||||||
|
state={state}
|
||||||
|
acceptState={acceptState}
|
||||||
|
mutate={mutate}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{page === "settings" && (
|
{page === "settings" && (
|
||||||
<Settings
|
<Settings
|
||||||
|
|||||||
@@ -718,6 +718,33 @@ main {
|
|||||||
padding: 17px 23px;
|
padding: 17px 23px;
|
||||||
border-bottom: 1px solid var(--line);
|
border-bottom: 1px solid var(--line);
|
||||||
}
|
}
|
||||||
|
.bulk-heading-actions,
|
||||||
|
.bulk-selection-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.bulk-toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 17px 23px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
background: #f5faf7;
|
||||||
|
}
|
||||||
|
.bulk-selection-summary {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
.bulk-selection-summary strong {
|
||||||
|
color: var(--emerald-dark);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
.search {
|
.search {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -744,6 +771,16 @@ main {
|
|||||||
.search input::placeholder {
|
.search input::placeholder {
|
||||||
color: #9aa6b3;
|
color: #9aa6b3;
|
||||||
}
|
}
|
||||||
|
.toolbar-select {
|
||||||
|
height: 35px;
|
||||||
|
font-size: 11px;
|
||||||
|
padding: 0 9px;
|
||||||
|
border: 1px solid #dbe2ea;
|
||||||
|
border-radius: 5px;
|
||||||
|
background: #fff;
|
||||||
|
color: #46596a;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
.table-scroll {
|
.table-scroll {
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
}
|
}
|
||||||
@@ -782,6 +819,29 @@ td small {
|
|||||||
tbody tr:hover {
|
tbody tr:hover {
|
||||||
background: #fcfefd;
|
background: #fcfefd;
|
||||||
}
|
}
|
||||||
|
.transaction-selection {
|
||||||
|
width: 54px;
|
||||||
|
padding: 8px 10px 8px 14px;
|
||||||
|
}
|
||||||
|
.transaction-select-control {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 30px;
|
||||||
|
min-height: 36px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.transaction-select-control input {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
margin: 0;
|
||||||
|
accent-color: var(--emerald);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.transaction-selected,
|
||||||
|
.transaction-selected:hover {
|
||||||
|
background: #eef8f3;
|
||||||
|
}
|
||||||
.numeric {
|
.numeric {
|
||||||
text-align: right;
|
text-align: right;
|
||||||
}
|
}
|
||||||
@@ -893,6 +953,11 @@ tbody tr:hover {
|
|||||||
gap: 5px;
|
gap: 5px;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
.category-child-action {
|
||||||
|
min-height: 32px;
|
||||||
|
padding: 6px 9px;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
.modal {
|
.modal {
|
||||||
border: 1px solid #dce5eb;
|
border: 1px solid #dce5eb;
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
@@ -952,6 +1017,38 @@ tbody tr:hover {
|
|||||||
grid-template-columns: 1fr 1fr;
|
grid-template-columns: 1fr 1fr;
|
||||||
gap: 18px;
|
gap: 18px;
|
||||||
}
|
}
|
||||||
|
.bulk-edit-fields,
|
||||||
|
.bulk-field-group {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.bulk-edit-fields {
|
||||||
|
border: 0;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
.bulk-operation-summary {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 16px;
|
||||||
|
background: #f5faf7;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.bulk-operation-summary h3 {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.bulk-operation-summary ul {
|
||||||
|
padding-left: 20px;
|
||||||
|
margin: 12px 0;
|
||||||
|
line-height: 1.8;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.bulk-operation-summary > p {
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
.tag-picker {
|
.tag-picker {
|
||||||
border: 1px solid var(--line);
|
border: 1px solid var(--line);
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
@@ -966,6 +1063,23 @@ tbody tr:hover {
|
|||||||
color: #546779;
|
color: #546779;
|
||||||
padding: 0 5px;
|
padding: 0 5px;
|
||||||
}
|
}
|
||||||
|
/* Inline tag creation inside the picker: a small input plus one button, so a
|
||||||
|
missing tag never forces a detour through the Tags page. */
|
||||||
|
.tag-add {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
.tag-add input {
|
||||||
|
width: 140px;
|
||||||
|
padding: 6px 9px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.tag-add-error {
|
||||||
|
flex-basis: 100%;
|
||||||
|
color: var(--danger);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
.check-chip {
|
.check-chip {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -1640,6 +1754,15 @@ footer span:first-child {
|
|||||||
width: 238px;
|
width: 238px;
|
||||||
transition: transform 0.2s;
|
transition: transform 0.2s;
|
||||||
}
|
}
|
||||||
|
/* With the classification select beside the review toggle, the search
|
||||||
|
would shrink to a sliver on phones; give it its own full-width row. */
|
||||||
|
.panel-toolbar {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.search {
|
||||||
|
flex-basis: 100%;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
.sidebar.open {
|
.sidebar.open {
|
||||||
transform: translateX(0);
|
transform: translateX(0);
|
||||||
}
|
}
|
||||||
@@ -1702,6 +1825,26 @@ footer span:first-child {
|
|||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
}
|
}
|
||||||
|
.bulk-heading-actions {
|
||||||
|
flex-shrink: 0;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-end;
|
||||||
|
}
|
||||||
|
.bulk-heading-actions .button {
|
||||||
|
font-size: 11px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.bulk-toolbar {
|
||||||
|
padding: 15px;
|
||||||
|
}
|
||||||
|
.bulk-selection-actions {
|
||||||
|
justify-content: flex-start;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.bulk-selection-actions .button {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
.filters {
|
.filters {
|
||||||
padding: 13px;
|
padding: 13px;
|
||||||
gap: 11px;
|
gap: 11px;
|
||||||
@@ -2059,6 +2202,7 @@ footer span:first-child {
|
|||||||
color: inherit;
|
color: inherit;
|
||||||
}
|
}
|
||||||
.combo-option:hover,
|
.combo-option:hover,
|
||||||
|
.combo-option.active,
|
||||||
.combo-option[aria-selected="true"] {
|
.combo-option[aria-selected="true"] {
|
||||||
background: #f0f7f4;
|
background: #f0f7f4;
|
||||||
}
|
}
|
||||||
@@ -2075,6 +2219,17 @@ footer span:first-child {
|
|||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
|
.combo-option.create {
|
||||||
|
color: var(--emerald);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.combo-option.create svg {
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
.combo-empty.error {
|
||||||
|
color: var(--danger);
|
||||||
|
}
|
||||||
/* The proposed side of a review row is editable in place: compact combobox
|
/* The proposed side of a review row is editable in place: compact combobox
|
||||||
inputs so a correction fits the diff card, removable chips for tags. */
|
inputs so a correction fits the diff card, removable chips for tags. */
|
||||||
.diff-value .combo > input {
|
.diff-value .combo > input {
|
||||||
@@ -2332,6 +2487,43 @@ footer span:first-child {
|
|||||||
padding-top: 13px;
|
padding-top: 13px;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
}
|
}
|
||||||
|
.tag-filters {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 14px 20px;
|
||||||
|
padding: 0 18px 17px;
|
||||||
|
}
|
||||||
|
.tag-filter {
|
||||||
|
flex: 1 1 250px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.tag-filter .field {
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.tag-filter .combo > input {
|
||||||
|
min-height: 35px;
|
||||||
|
padding: 7px 9px;
|
||||||
|
font-size: 12px;
|
||||||
|
background: #fcfdfe;
|
||||||
|
}
|
||||||
|
.tag-filter .tag-edit {
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
.tag-filter .tag-chip {
|
||||||
|
min-height: 32px;
|
||||||
|
max-width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.tag-filter .tag-chip span {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.tag-filter .tag-chip svg {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.tag-filter .tag-chip.excluded {
|
||||||
|
border-color: #e8cece;
|
||||||
|
color: var(--danger);
|
||||||
|
}
|
||||||
.chip {
|
.chip {
|
||||||
border: 1px solid #dde4ea;
|
border: 1px solid #dde4ea;
|
||||||
background: #fcfdfe;
|
background: #fcfdfe;
|
||||||
@@ -2611,6 +2803,9 @@ footer span:first-child {
|
|||||||
.range-row .filter-reset {
|
.range-row .filter-reset {
|
||||||
margin-left: 0;
|
margin-left: 0;
|
||||||
}
|
}
|
||||||
|
.tag-filters {
|
||||||
|
padding: 0 13px 13px;
|
||||||
|
}
|
||||||
.chart-body {
|
.chart-body {
|
||||||
padding: 4px 12px 18px;
|
padding: 4px 12px 18px;
|
||||||
}
|
}
|
||||||
@@ -2627,3 +2822,9 @@ footer span:first-child {
|
|||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.anchor-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|||||||
+411
-44
@@ -7,8 +7,9 @@ import {
|
|||||||
CalendarDays,
|
CalendarDays,
|
||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
|
Plus,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import type { Dataset, Filter, VerifiedModel } from "./api";
|
import type { Category, Dataset, Filter, State, VerifiedModel } from "./api";
|
||||||
import {
|
import {
|
||||||
categoryPath,
|
categoryPath,
|
||||||
DEFAULT_MONTHS,
|
DEFAULT_MONTHS,
|
||||||
@@ -22,11 +23,13 @@ export function Modal({
|
|||||||
children,
|
children,
|
||||||
close,
|
close,
|
||||||
wide = false,
|
wide = false,
|
||||||
|
dismissible = true,
|
||||||
}: {
|
}: {
|
||||||
title: string;
|
title: string;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
close: () => void;
|
close: () => void;
|
||||||
wide?: boolean;
|
wide?: boolean;
|
||||||
|
dismissible?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const ref = useRef<HTMLDialogElement>(null);
|
const ref = useRef<HTMLDialogElement>(null);
|
||||||
const titleID = useId();
|
const titleID = useId();
|
||||||
@@ -42,7 +45,7 @@ export function Modal({
|
|||||||
className={wide ? "modal wide" : "modal"}
|
className={wide ? "modal wide" : "modal"}
|
||||||
onCancel={(e) => {
|
onCancel={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
close();
|
if (dismissible) close();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="modal-header">
|
<div className="modal-header">
|
||||||
@@ -51,6 +54,7 @@ export function Modal({
|
|||||||
className="icon-button"
|
className="icon-button"
|
||||||
aria-label="Close dialog"
|
aria-label="Close dialog"
|
||||||
onClick={close}
|
onClick={close}
|
||||||
|
disabled={!dismissible}
|
||||||
>
|
>
|
||||||
<X size={20} />
|
<X size={20} />
|
||||||
</button>
|
</button>
|
||||||
@@ -103,6 +107,14 @@ export interface ComboOption {
|
|||||||
label: string;
|
label: string;
|
||||||
icon?: ReactNode;
|
icon?: ReactNode;
|
||||||
}
|
}
|
||||||
|
// ComboCreate is one "create it now" row a Combobox offers when the typed
|
||||||
|
// text matches nothing: running it is expected to persist the new entity and
|
||||||
|
// select it through the caller's own onChange.
|
||||||
|
export interface ComboCreate {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
run: () => Promise<void> | void;
|
||||||
|
}
|
||||||
// Combobox is a free-text input that autocompletes against a fixed option
|
// Combobox is a free-text input that autocompletes against a fixed option
|
||||||
// list: typing filters by label, Enter takes the exact or only match, and
|
// list: typing filters by label, Enter takes the exact or only match, and
|
||||||
// picking an option reports its value. The caller keeps working with stable
|
// picking an option reports its value. The caller keeps working with stable
|
||||||
@@ -116,6 +128,7 @@ export function Combobox({
|
|||||||
required = false,
|
required = false,
|
||||||
adornment,
|
adornment,
|
||||||
emptyText = "No matches.",
|
emptyText = "No matches.",
|
||||||
|
create,
|
||||||
}: {
|
}: {
|
||||||
options: ComboOption[];
|
options: ComboOption[];
|
||||||
value: string;
|
value: string;
|
||||||
@@ -125,9 +138,16 @@ export function Combobox({
|
|||||||
required?: boolean;
|
required?: boolean;
|
||||||
adornment?: ReactNode;
|
adornment?: ReactNode;
|
||||||
emptyText?: string;
|
emptyText?: string;
|
||||||
|
create?: (text: string) => ComboCreate[];
|
||||||
}) {
|
}) {
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
const [createError, setCreateError] = useState("");
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
|
// Index into the interactive rows (matches first, then create rows); -1
|
||||||
|
// means no row is armed and Enter falls back to exact/single-match logic.
|
||||||
|
const [active, setActive] = useState(-1);
|
||||||
|
const listID = useId();
|
||||||
const filter = query.trim().toLowerCase();
|
const filter = query.trim().toLowerCase();
|
||||||
const matches = options.filter((o) => o.label.toLowerCase().includes(filter));
|
const matches = options.filter((o) => o.label.toLowerCase().includes(filter));
|
||||||
const exact = filter
|
const exact = filter
|
||||||
@@ -137,10 +157,38 @@ export function Combobox({
|
|||||||
? [exact, ...matches.filter((o) => o !== exact).slice(0, 59)]
|
? [exact, ...matches.filter((o) => o !== exact).slice(0, 59)]
|
||||||
: matches.slice(0, 60);
|
: matches.slice(0, 60);
|
||||||
const selected = options.find((o) => o.value === value);
|
const selected = options.find((o) => o.value === value);
|
||||||
|
const creations =
|
||||||
|
create && filter && !exact && !disabled ? create(query.trim()) : [];
|
||||||
|
const total = shown.length + creations.length;
|
||||||
|
const cursor = active < total ? active : -1;
|
||||||
|
// The dropdown scrolls at 264px; keep the armed row visible while
|
||||||
|
// arrowing through a long category list.
|
||||||
|
useEffect(() => {
|
||||||
|
if (cursor < 0) return;
|
||||||
|
document
|
||||||
|
.getElementById(`${listID}-${cursor}`)
|
||||||
|
?.scrollIntoView({ block: "nearest" });
|
||||||
|
}, [cursor, listID]);
|
||||||
const pick = (v: string) => {
|
const pick = (v: string) => {
|
||||||
onChange(v);
|
onChange(v);
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
};
|
};
|
||||||
|
const runCreate = async (c: ComboCreate) => {
|
||||||
|
if (creating) return;
|
||||||
|
setCreating(true);
|
||||||
|
setCreateError("");
|
||||||
|
try {
|
||||||
|
await c.run();
|
||||||
|
setOpen(false);
|
||||||
|
} catch (err) {
|
||||||
|
setCreateError(err instanceof Error ? err.message : String(err));
|
||||||
|
// A blur may have closed the list mid-flight; a failure must never
|
||||||
|
// land invisibly.
|
||||||
|
setOpen(true);
|
||||||
|
} finally {
|
||||||
|
setCreating(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
<div className="combo">
|
<div className="combo">
|
||||||
<input
|
<input
|
||||||
@@ -148,24 +196,52 @@ export function Combobox({
|
|||||||
role="combobox"
|
role="combobox"
|
||||||
aria-expanded={open}
|
aria-expanded={open}
|
||||||
aria-autocomplete="list"
|
aria-autocomplete="list"
|
||||||
|
aria-controls={open ? listID : undefined}
|
||||||
|
aria-activedescendant={
|
||||||
|
open && cursor >= 0 ? `${listID}-${cursor}` : undefined
|
||||||
|
}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
value={open ? query : (selected?.label ?? value)}
|
value={open ? query : (selected?.label ?? value)}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
onFocus={() => {
|
onFocus={() => {
|
||||||
setQuery("");
|
setQuery("");
|
||||||
|
setActive(-1);
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
}}
|
}}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setQuery(e.target.value);
|
setQuery(e.target.value);
|
||||||
|
setCreateError("");
|
||||||
|
setActive(-1);
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
}}
|
}}
|
||||||
onBlur={() => setOpen(false)}
|
onBlur={() => {
|
||||||
|
// A blur during an in-flight create keeps the list mounted so the
|
||||||
|
// outcome (or the error row) stays visible.
|
||||||
|
if (!creating) setOpen(false);
|
||||||
|
}}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === "Escape") setOpen(false);
|
if (e.key === "Escape") setOpen(false);
|
||||||
|
if ((e.key === "ArrowDown" || e.key === "ArrowUp") && open && total) {
|
||||||
|
e.preventDefault();
|
||||||
|
setActive(
|
||||||
|
e.key === "ArrowDown"
|
||||||
|
? (cursor + 1) % total
|
||||||
|
: (cursor <= 0 ? total : cursor) - 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
if (e.key === "Enter" && open) {
|
if (e.key === "Enter" && open) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const hit = exact ?? (shown.length === 1 ? shown[0] : undefined);
|
if (cursor >= 0 && cursor < shown.length) pick(shown[cursor].value);
|
||||||
if (hit) pick(hit.value);
|
else if (cursor >= shown.length)
|
||||||
|
void runCreate(creations[cursor - shown.length]);
|
||||||
|
else {
|
||||||
|
const hit = exact ?? (shown.length === 1 ? shown[0] : undefined);
|
||||||
|
if (hit) pick(hit.value);
|
||||||
|
// Without an armed row, Enter creates only when nothing
|
||||||
|
// matches at all: minting from a half-typed name is too easy.
|
||||||
|
else if (!shown.length && creations.length === 1)
|
||||||
|
void runCreate(creations[0]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -173,14 +249,18 @@ export function Combobox({
|
|||||||
<span className="combo-adornment">{adornment}</span>
|
<span className="combo-adornment">{adornment}</span>
|
||||||
)}
|
)}
|
||||||
{open && (
|
{open && (
|
||||||
<ul className="combo-options" role="listbox">
|
<ul className="combo-options" role="listbox" id={listID}>
|
||||||
{shown.map((o) => (
|
{shown.map((o, i) => (
|
||||||
<li key={o.value}>
|
<li key={o.value}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="combo-option"
|
id={`${listID}-${i}`}
|
||||||
|
className={
|
||||||
|
i === cursor ? "combo-option active" : "combo-option"
|
||||||
|
}
|
||||||
role="option"
|
role="option"
|
||||||
aria-selected={o.value === value}
|
aria-selected={o.value === value}
|
||||||
|
disabled={creating}
|
||||||
onMouseDown={(e) => e.preventDefault()}
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
onClick={() => pick(o.value)}
|
onClick={() => pick(o.value)}
|
||||||
>
|
>
|
||||||
@@ -189,7 +269,35 @@ export function Combobox({
|
|||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
{shown.length === 0 && <li className="combo-empty">{emptyText}</li>}
|
{creations.map((c, i) => (
|
||||||
|
<li key={c.key}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
id={`${listID}-${shown.length + i}`}
|
||||||
|
className={
|
||||||
|
shown.length + i === cursor
|
||||||
|
? "combo-option create active"
|
||||||
|
: "combo-option create"
|
||||||
|
}
|
||||||
|
role="option"
|
||||||
|
aria-selected={false}
|
||||||
|
disabled={creating}
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={() => void runCreate(c)}
|
||||||
|
>
|
||||||
|
<Plus size={14} />
|
||||||
|
<span>{creating ? "Creating…" : c.label}</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{createError && (
|
||||||
|
<li className="combo-empty error" role="alert">
|
||||||
|
{createError}
|
||||||
|
</li>
|
||||||
|
)}
|
||||||
|
{shown.length === 0 && creations.length === 0 && !createError && (
|
||||||
|
<li className="combo-empty">{emptyText}</li>
|
||||||
|
)}
|
||||||
{matches.length > shown.length && (
|
{matches.length > shown.length && (
|
||||||
<li className="combo-empty">
|
<li className="combo-empty">
|
||||||
{matches.length - shown.length} more — keep typing to narrow down.
|
{matches.length - shown.length} more — keep typing to narrow down.
|
||||||
@@ -461,38 +569,146 @@ export function Empty({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// createTag persists a new tag and returns its server-minted id, found by
|
||||||
|
// diffing the returned state against the dataset the caller rendered with.
|
||||||
|
export async function createTag(
|
||||||
|
mutate: Mutate,
|
||||||
|
data: Dataset,
|
||||||
|
name: string,
|
||||||
|
): Promise<string> {
|
||||||
|
if (name.length > 200)
|
||||||
|
throw new Error("Tag names are limited to 200 characters.");
|
||||||
|
const next = await mutate(
|
||||||
|
"/api/tags",
|
||||||
|
{ tag: { id: "", name, hint: "" } },
|
||||||
|
`Tag "${name}" created`,
|
||||||
|
);
|
||||||
|
const created = next.data.tags.find(
|
||||||
|
(t) => !data.tags.some((o) => o.id === t.id),
|
||||||
|
);
|
||||||
|
if (!created)
|
||||||
|
throw new Error(`The server did not return the new tag "${name}".`);
|
||||||
|
return created.id;
|
||||||
|
}
|
||||||
|
export async function createCategory(
|
||||||
|
mutate: Mutate,
|
||||||
|
data: Dataset,
|
||||||
|
category: { name: string; parent_id: string; kind: string },
|
||||||
|
): Promise<string> {
|
||||||
|
if (category.name.length > 200)
|
||||||
|
throw new Error("Category names are limited to 200 characters.");
|
||||||
|
const next = await mutate(
|
||||||
|
"/api/categories",
|
||||||
|
{ category: { id: "", hint: "", ...category } },
|
||||||
|
`Category "${category.name}" created`,
|
||||||
|
);
|
||||||
|
const created = next.data.categories.find(
|
||||||
|
(c) => !data.categories.some((o) => o.id === c.id),
|
||||||
|
);
|
||||||
|
if (!created)
|
||||||
|
throw new Error(
|
||||||
|
`The server did not return the new category "${category.name}".`,
|
||||||
|
);
|
||||||
|
return created.id;
|
||||||
|
}
|
||||||
export function TagPicker({
|
export function TagPicker({
|
||||||
data,
|
data,
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
|
mutate,
|
||||||
|
label = "Tags",
|
||||||
}: {
|
}: {
|
||||||
data: Dataset;
|
data: Dataset;
|
||||||
value: string[];
|
value: string[];
|
||||||
onChange: (ids: string[]) => void;
|
onChange: (ids: string[]) => void;
|
||||||
|
mutate?: Mutate;
|
||||||
|
label?: string;
|
||||||
}) {
|
}) {
|
||||||
|
const [draft, setDraft] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
// The async add resolves against the freshest selection, not the one
|
||||||
|
// captured at click time: a checkbox toggled during the server round trip
|
||||||
|
// must survive the create landing.
|
||||||
|
const latest = useRef(value);
|
||||||
|
latest.current = value;
|
||||||
|
const add = async () => {
|
||||||
|
const name = draft.trim();
|
||||||
|
if (!name || busy || !mutate) return;
|
||||||
|
// An existing tag of the same name is checked instead of duplicated.
|
||||||
|
const existing = data.tags.find(
|
||||||
|
(t) => t.name.toLowerCase() === name.toLowerCase(),
|
||||||
|
);
|
||||||
|
if (existing) {
|
||||||
|
if (!value.includes(existing.id)) onChange([...value, existing.id]);
|
||||||
|
setDraft("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const id = await createTag(mutate, data, name);
|
||||||
|
onChange([...latest.current, id]);
|
||||||
|
setDraft("");
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
<fieldset className="tag-picker">
|
<fieldset className="tag-picker">
|
||||||
<legend>Tags</legend>
|
<legend>{label}</legend>
|
||||||
{data.tags.length ? (
|
{data.tags.map((tag) => (
|
||||||
data.tags.map((tag) => (
|
<label className="check-chip" key={tag.id}>
|
||||||
<label className="check-chip" key={tag.id}>
|
<input
|
||||||
<input
|
type="checkbox"
|
||||||
type="checkbox"
|
checked={value.includes(tag.id)}
|
||||||
checked={value.includes(tag.id)}
|
onChange={(e) =>
|
||||||
onChange={(e) =>
|
onChange(
|
||||||
onChange(
|
e.target.checked
|
||||||
e.target.checked
|
? [...value, tag.id]
|
||||||
? [...value, tag.id]
|
: value.filter((id) => id !== tag.id),
|
||||||
: value.filter((id) => id !== tag.id),
|
)
|
||||||
)
|
}
|
||||||
}
|
/>
|
||||||
/>
|
{tag.name}
|
||||||
{tag.name}
|
</label>
|
||||||
</label>
|
))}
|
||||||
))
|
{!data.tags.length && !mutate && (
|
||||||
) : (
|
|
||||||
<small>No tags yet. Create them in Tags.</small>
|
<small>No tags yet. Create them in Tags.</small>
|
||||||
)}
|
)}
|
||||||
|
{mutate && (
|
||||||
|
<span className="tag-add">
|
||||||
|
<input
|
||||||
|
value={draft}
|
||||||
|
maxLength={200}
|
||||||
|
placeholder="New tag"
|
||||||
|
aria-label="New tag name"
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) => {
|
||||||
|
setDraft(e.target.value);
|
||||||
|
setError("");
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
void add();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="icon-button"
|
||||||
|
aria-label="Create tag"
|
||||||
|
disabled={busy || !draft.trim()}
|
||||||
|
onClick={() => void add()}
|
||||||
|
>
|
||||||
|
<Plus size={15} />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{error && <small className="tag-add-error">{error}</small>}
|
||||||
</fieldset>
|
</fieldset>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -517,6 +733,98 @@ export function CategoryOptions({
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// CategoryCombobox is the one category picker: options are full paths, and
|
||||||
|
// with a mutate handle an unmatched name can be created in place. A bare name
|
||||||
|
// is offered under each matching root; "Parent / Name" creates under that
|
||||||
|
// existing parent. leavesOnly matches the server rule that assigned categories
|
||||||
|
// must be leaves; a freshly created category is always a leaf.
|
||||||
|
export function CategoryCombobox({
|
||||||
|
data,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
mutate,
|
||||||
|
kind,
|
||||||
|
leavesOnly = false,
|
||||||
|
exclude = [],
|
||||||
|
emptyLabel,
|
||||||
|
required = false,
|
||||||
|
disabled = false,
|
||||||
|
placeholder = "Search categories",
|
||||||
|
}: {
|
||||||
|
data: Dataset;
|
||||||
|
value: string;
|
||||||
|
onChange: (id: string) => void;
|
||||||
|
mutate?: Mutate;
|
||||||
|
kind?: string;
|
||||||
|
leavesOnly?: boolean;
|
||||||
|
exclude?: string[];
|
||||||
|
emptyLabel?: string;
|
||||||
|
required?: boolean;
|
||||||
|
disabled?: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
}) {
|
||||||
|
const parents = new Set(
|
||||||
|
data.categories.map((c) => c.parent_id).filter(Boolean),
|
||||||
|
);
|
||||||
|
const eligible = (c: Category) =>
|
||||||
|
(!kind || c.kind === kind) && !exclude.includes(c.id);
|
||||||
|
const options: ComboOption[] = data.categories
|
||||||
|
.filter((c) => eligible(c) && (!leavesOnly || !parents.has(c.id)))
|
||||||
|
.map((c) => ({ value: c.id, label: categoryPath(data, c.id) }));
|
||||||
|
if (emptyLabel) options.unshift({ value: "", label: emptyLabel });
|
||||||
|
const pathOf = (id: string) => categoryPath(data, id).toLowerCase();
|
||||||
|
const taken = (parentID: string, name: string) => {
|
||||||
|
const full = `${parentID ? pathOf(parentID) + " / " : ""}${name.toLowerCase()}`;
|
||||||
|
return data.categories.some((c) => pathOf(c.id) === full);
|
||||||
|
};
|
||||||
|
const create = (text: string): ComboCreate[] => {
|
||||||
|
if (!mutate) return [];
|
||||||
|
const segments = text
|
||||||
|
.split("/")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (!segments.length) return [];
|
||||||
|
const name = segments[segments.length - 1];
|
||||||
|
const row = (parent: Category): ComboCreate => ({
|
||||||
|
key: parent.id,
|
||||||
|
label: `Create category "${name}" in ${categoryPath(data, parent.id)}`,
|
||||||
|
run: async () =>
|
||||||
|
onChange(
|
||||||
|
await createCategory(mutate, data, {
|
||||||
|
name,
|
||||||
|
parent_id: parent.id,
|
||||||
|
kind: parent.kind,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
if (segments.length > 1) {
|
||||||
|
const prefix = segments.slice(0, -1).join(" / ").toLowerCase();
|
||||||
|
const parent = data.categories.find(
|
||||||
|
(c) => eligible(c) && pathOf(c.id) === prefix,
|
||||||
|
);
|
||||||
|
return parent && !taken(parent.id, name) ? [row(parent)] : [];
|
||||||
|
}
|
||||||
|
return data.categories
|
||||||
|
.filter((c) => !c.parent_id && eligible(c) && !taken(c.id, name))
|
||||||
|
.map(row);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Combobox
|
||||||
|
options={options}
|
||||||
|
value={value}
|
||||||
|
onChange={onChange}
|
||||||
|
required={required}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder={placeholder}
|
||||||
|
emptyText={
|
||||||
|
mutate
|
||||||
|
? "No match. Type a category name and choose Create category."
|
||||||
|
: "No matching category."
|
||||||
|
}
|
||||||
|
create={create}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
export function Filters({
|
export function Filters({
|
||||||
data,
|
data,
|
||||||
value,
|
value,
|
||||||
@@ -526,8 +834,10 @@ export function Filters({
|
|||||||
value: Filter;
|
value: Filter;
|
||||||
onChange: (filter: Filter) => void;
|
onChange: (filter: Filter) => void;
|
||||||
}) {
|
}) {
|
||||||
const update = (key: keyof Filter, text: string) =>
|
const update = (
|
||||||
onChange({ ...value, [key]: text });
|
key: Exclude<keyof Filter, "tag_ids" | "exclude_tag_ids">,
|
||||||
|
text: string,
|
||||||
|
) => onChange({ ...value, [key]: text });
|
||||||
const currencies = Array.from(
|
const currencies = Array.from(
|
||||||
new Set([
|
new Set([
|
||||||
...data.accounts.map((a) => a.currency),
|
...data.accounts.map((a) => a.currency),
|
||||||
@@ -546,6 +856,22 @@ export function Filters({
|
|||||||
{ label: "YTD", title: "Year to date", from: yearStart(), to: "" },
|
{ label: "YTD", title: "Year to date", from: yearStart(), to: "" },
|
||||||
{ label: "All", title: "All time", from: "", to: "" },
|
{ label: "All", title: "All time", from: "", to: "" },
|
||||||
];
|
];
|
||||||
|
const tagFilters = [
|
||||||
|
{
|
||||||
|
key: "tag_ids",
|
||||||
|
opposite: "exclude_tag_ids",
|
||||||
|
label: "Include tags",
|
||||||
|
polarity: "Include",
|
||||||
|
hint: "Match any selected tag; empty includes all.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "exclude_tag_ids",
|
||||||
|
opposite: "tag_ids",
|
||||||
|
label: "Exclude tags",
|
||||||
|
polarity: "Exclude",
|
||||||
|
hint: "Hide transactions with any selected tag.",
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
return (
|
return (
|
||||||
<div className="filter-bar">
|
<div className="filter-bar">
|
||||||
<div className="range-row">
|
<div className="range-row">
|
||||||
@@ -625,19 +951,6 @@ export function Filters({
|
|||||||
<CategoryOptions data={data} />
|
<CategoryOptions data={data} />
|
||||||
</select>
|
</select>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Tag">
|
|
||||||
<select
|
|
||||||
value={value.tag_id}
|
|
||||||
onChange={(e) => update("tag_id", e.target.value)}
|
|
||||||
>
|
|
||||||
<option value="">All tags</option>
|
|
||||||
{data.tags.map((t) => (
|
|
||||||
<option value={t.id} key={t.id}>
|
|
||||||
{t.name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</Field>
|
|
||||||
<Field label="Merchant">
|
<Field label="Merchant">
|
||||||
<select
|
<select
|
||||||
value={value.merchant_id}
|
value={value.merchant_id}
|
||||||
@@ -652,6 +965,58 @@ export function Filters({
|
|||||||
</select>
|
</select>
|
||||||
</Field>
|
</Field>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="tag-filters">
|
||||||
|
{tagFilters.map(({ key, opposite, label, polarity, hint }) => (
|
||||||
|
<div className="tag-filter" key={key}>
|
||||||
|
<Field label={label} hint={hint}>
|
||||||
|
<Combobox
|
||||||
|
options={data.tags
|
||||||
|
.filter((tag) => !value[key].includes(tag.id))
|
||||||
|
.map((tag) => ({ value: tag.id, label: tag.name }))}
|
||||||
|
value=""
|
||||||
|
placeholder={`Add tag to ${polarity.toLowerCase()}`}
|
||||||
|
emptyText="No more matching tags."
|
||||||
|
onChange={(id) =>
|
||||||
|
onChange({
|
||||||
|
...value,
|
||||||
|
[key]: value[key].includes(id)
|
||||||
|
? value[key]
|
||||||
|
: [...value[key], id],
|
||||||
|
[opposite]: value[opposite].filter((tag) => tag !== id),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
{value[key].length > 0 && (
|
||||||
|
<div className="tag-edit" role="group" aria-label={label}>
|
||||||
|
{value[key].map((id) => {
|
||||||
|
const name =
|
||||||
|
data.tags.find((tag) => tag.id === id)?.name || id;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`tag-chip ${key === "exclude_tag_ids" ? "excluded" : ""}`}
|
||||||
|
key={id}
|
||||||
|
aria-label={`Remove ${name} from ${polarity.toLowerCase()} tags`}
|
||||||
|
onClick={() =>
|
||||||
|
onChange({
|
||||||
|
...value,
|
||||||
|
[key]: value[key].filter((tag) => tag !== id),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
{polarity}: {name}
|
||||||
|
</span>
|
||||||
|
<X size={12} aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -680,8 +1045,10 @@ export function FormActions({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// Mutate posts a revisioned change and returns the accepted state, so a
|
||||||
|
// caller can find ids the server just minted.
|
||||||
export type Mutate = (
|
export type Mutate = (
|
||||||
path: string,
|
path: string,
|
||||||
body: Record<string, unknown>,
|
body: Record<string, unknown>,
|
||||||
message?: string,
|
message?: string,
|
||||||
) => Promise<void>;
|
) => Promise<State>;
|
||||||
|
|||||||
Reference in New Issue
Block a user