Compare commits
11
Commits
46e02d95cb
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71e95917da | ||
|
|
83bb86bc93 | ||
|
|
0fd3c5c0dc | ||
|
|
16daa01647 | ||
|
|
b7e5bf26cc | ||
|
|
676065292e | ||
|
|
c569ae7dbf | ||
|
|
46cf578779 | ||
|
|
671cbb8ef3 | ||
|
|
1b3d7b22bb | ||
|
|
f9e829e6ba |
+36
-6
@@ -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
|
||||||
@@ -167,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
|
||||||
@@ -637,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
|
||||||
@@ -696,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
|
||||||
@@ -739,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
|
||||||
@@ -746,8 +775,9 @@ 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
|
||||||
|
commits do not require another analysis.
|
||||||
Previews are kept in memory for up to 24 hours from the start of analysis and
|
Previews are kept in memory for up to 24 hours from the start of analysis and
|
||||||
disappear on restart. Cancel writes nothing. Transfers and broker facts are
|
disappear on restart. Cancel writes nothing. Transfers and broker facts are
|
||||||
skipped, and unselected fields are preserved.
|
skipped, and unselected fields are preserved.
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -423,7 +425,7 @@ 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.
|
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.
|
||||||
|
|
||||||
@@ -439,6 +441,8 @@ 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.
|
||||||
|
|
||||||
## 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.
|
||||||
|
|||||||
+112
-14
@@ -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)
|
||||||
}
|
}
|
||||||
@@ -361,6 +415,50 @@ func TestPreviewIsReadOnlySelectedApplyPreservesFactsAndOtherFields(t *testing.T
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
func TestPreviewExpiresAfterTwentyFourHours(t *testing.T) {
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
name string
|
name string
|
||||||
@@ -378,7 +476,7 @@ func TestPreviewExpiresAfterTwentyFourHours(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)
|
||||||
}
|
}
|
||||||
@@ -392,7 +490,7 @@ func TestPreviewExpiresAfterTwentyFourHours(t *testing.T) {
|
|||||||
if tc.newPreview {
|
if tc.newPreview {
|
||||||
// Completing another run performs expired-preview cleanup.
|
// Completing another run performs expired-preview cleanup.
|
||||||
// An empty range needs no additional provider request.
|
// An empty range needs no additional provider request.
|
||||||
if _, err := runPreview(t, a, PreviewRequest{Revision: s.Revision, From: "2025-01-01", To: "2025-01-31", Model: "test/model", Fields: Fields{Category: true}}); err != nil {
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -423,7 +521,7 @@ 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)
|
||||||
}
|
}
|
||||||
@@ -455,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)
|
||||||
}
|
}
|
||||||
@@ -508,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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,11 +21,10 @@ type Fields struct {
|
|||||||
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"`
|
||||||
@@ -119,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
|
||||||
@@ -138,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 {
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
+60
-8
@@ -49,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
|
||||||
@@ -192,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 {
|
||||||
@@ -200,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 {
|
||||||
@@ -317,13 +353,22 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
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{
|
||||||
@@ -333,7 +378,7 @@ func WealthOf(data domain.Dataset) Wealth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
seen(account.Currency)
|
seen(account.Currency)
|
||||||
totals[account.Currency] += st.cash
|
totals[account.Currency] += 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]
|
||||||
@@ -372,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
|
||||||
|
|
||||||
@@ -384,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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -416,3 +416,71 @@ func TestWealthCountsHandValuedAssets(t *testing.T) {
|
|||||||
t.Errorf("assets not echoed sorted by name with their dates: %+v", report.Assets)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -343,7 +343,7 @@ 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"
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+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>
|
||||||
|
|||||||
+22
-18
@@ -21,7 +21,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,
|
||||||
@@ -550,17 +550,15 @@ function RegistryEditor({
|
|||||||
</select>
|
</select>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Parent category">
|
<Field label="Parent category">
|
||||||
<select
|
<CategoryCombobox
|
||||||
|
data={data}
|
||||||
|
kind={kind}
|
||||||
|
exclude={[...descendants]}
|
||||||
|
emptyLabel="No parent (root)"
|
||||||
|
mutate={mutate}
|
||||||
value={parent}
|
value={parent}
|
||||||
onChange={(e) => setParent(e.target.value)}
|
onChange={setParent}
|
||||||
>
|
/>
|
||||||
<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 +588,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.
|
||||||
|
|||||||
+57
-11
@@ -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,6 +112,7 @@ 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 filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
@@ -122,6 +143,12 @@ export function Transactions({
|
|||||||
(e.kind === "income"
|
(e.kind === "income"
|
||||||
? "cat_income_unclassified"
|
? "cat_income_unclassified"
|
||||||
: "cat_expenses_unclassified")) &&
|
: "cat_expenses_unclassified")) &&
|
||||||
|
(!status ||
|
||||||
|
(status === "unclassified"
|
||||||
|
? ["fallback", "unclassified", ""].includes(
|
||||||
|
e.classification.source || "",
|
||||||
|
)
|
||||||
|
: e.classification.source === status)) &&
|
||||||
(!filter.tag_id || e.tag_ids.includes(filter.tag_id)) &&
|
(!filter.tag_id || e.tag_ids.includes(filter.tag_id)) &&
|
||||||
(!filter.merchant_id || e.merchant_id === filter.merchant_id) &&
|
(!filter.merchant_id || e.merchant_id === filter.merchant_id) &&
|
||||||
(!query ||
|
(!query ||
|
||||||
@@ -134,7 +161,7 @@ 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),
|
||||||
@@ -181,6 +208,22 @@ 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} /> Click a transaction to edit
|
||||||
</span>
|
</span>
|
||||||
@@ -284,7 +327,8 @@ export function Transactions({
|
|||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<span className="badge neutral">
|
<span className="badge neutral">
|
||||||
{e.classification.source}
|
{CLASSIFICATIONS[e.classification.source] ??
|
||||||
|
e.classification.source}
|
||||||
</span>
|
</span>
|
||||||
{e.classification.error && (
|
{e.classification.error && (
|
||||||
<small className="text-danger">
|
<small className="text-danger">
|
||||||
@@ -453,16 +497,17 @@ function TransactionEditor({
|
|||||||
</div>
|
</div>
|
||||||
{value.kind !== "transfer" && value.kind !== "investment" && (
|
{value.kind !== "transfer" && value.kind !== "investment" && (
|
||||||
<Field label="Category">
|
<Field label="Category">
|
||||||
<select
|
<CategoryCombobox
|
||||||
|
data={data}
|
||||||
|
kind={value.kind}
|
||||||
|
leavesOnly
|
||||||
required
|
required
|
||||||
|
mutate={mutate}
|
||||||
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 +519,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>
|
||||||
|
|||||||
+9
-3
@@ -309,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>
|
||||||
@@ -547,7 +550,10 @@ function AssetsPanel({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="row-actions">
|
<div className="row-actions">
|
||||||
<button className="button secondary" onClick={() => setEditing(blank)}>
|
<button
|
||||||
|
className="button secondary"
|
||||||
|
onClick={() => setEditing(blank)}
|
||||||
|
>
|
||||||
<Plus size={16} />
|
<Plus size={16} />
|
||||||
Add asset
|
Add asset
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
+12
-22
@@ -136,13 +136,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 +351,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 +359,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 +368,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}
|
||||||
@@ -409,7 +395,11 @@ function App() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{page === "classification" && (
|
{page === "classification" && (
|
||||||
<Classification state={state} acceptState={acceptState} />
|
<Classification
|
||||||
|
state={state}
|
||||||
|
acceptState={acceptState}
|
||||||
|
mutate={mutate}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{page === "settings" && (
|
{page === "settings" && (
|
||||||
<Settings
|
<Settings
|
||||||
|
|||||||
@@ -744,6 +744,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;
|
||||||
}
|
}
|
||||||
@@ -966,6 +976,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 +1667,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);
|
||||||
}
|
}
|
||||||
@@ -2059,6 +2095,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 +2112,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 {
|
||||||
@@ -2627,3 +2675,9 @@ footer span:first-child {
|
|||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.anchor-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|||||||
+332
-27
@@ -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,
|
||||||
@@ -103,6 +104,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 +125,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 +135,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 +154,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 +193,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 +246,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 +266,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 +566,144 @@ 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,
|
||||||
}: {
|
}: {
|
||||||
data: Dataset;
|
data: Dataset;
|
||||||
value: string[];
|
value: string[];
|
||||||
onChange: (ids: string[]) => void;
|
onChange: (ids: string[]) => void;
|
||||||
|
mutate?: Mutate;
|
||||||
}) {
|
}) {
|
||||||
|
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>Tags</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 +728,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
|
||||||
|
// lands under the kind's root; "Parent / Name" creates under that 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 "${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 matching category. Type a name to create it."
|
||||||
|
: "No matching category."
|
||||||
|
}
|
||||||
|
create={create}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
export function Filters({
|
export function Filters({
|
||||||
data,
|
data,
|
||||||
value,
|
value,
|
||||||
@@ -680,8 +983,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