diff --git a/OPERATIONS.txt b/OPERATIONS.txt index 0b1b6e5..36fb02c 100644 --- a/OPERATIONS.txt +++ b/OPERATIONS.txt @@ -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, 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 -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 ./... The Go build embeds web/dist, so build React first. CGO and a C++ linker are diff --git a/README.md b/README.md index 245e418..2377b85 100644 --- a/README.md +++ b/README.md @@ -439,6 +439,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. +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 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. diff --git a/web/src/Classification.tsx b/web/src/Classification.tsx index f743bd4..d2f6e32 100644 --- a/web/src/Classification.tsx +++ b/web/src/Classification.tsx @@ -16,7 +16,9 @@ import type { } from "./api"; import { categoryPath, money, request } from "./api"; import { + CategoryCombobox, Combobox, + createTag, DateField, Empty, ErrorMessage, @@ -24,12 +26,15 @@ import { Modal, ModelOptions, } from "./ui"; +import type { Mutate } from "./ui"; export function Classification({ state, acceptState, + mutate, }: { state: State; acceptState: (state: State, message?: string) => void; + mutate: Mutate; }) { const dates = state.data.transactions.map((t) => t.facts.booking_date).sort(); const [from, setFrom] = useState(dates[0] || ""); @@ -482,6 +487,7 @@ export function Classification({ value={effective(change)} edited={change.id in edits} disabled={busy} + mutate={mutate} onChange={(value) => correct(change, value)} /> @@ -667,14 +673,18 @@ interface CorrectionValue { } // CorrectionEditor is the "Proposed" side of a review row, editable in place. // Category and tags are free-text inputs that autocomplete against the -// existing taxonomy; the category list is limited to leaves of the change's -// kind because that is what validation will accept. +// existing taxonomy and can create a missing entry in place; the category +// 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({ data, change, value, edited, disabled, + mutate, onChange, }: { data: Dataset; @@ -682,15 +692,9 @@ function CorrectionEditor({ value: CorrectionValue; edited: boolean; disabled: boolean; + mutate: Mutate; onChange: (value: CorrectionValue) => void; }) { - const categories = data.categories - .filter( - (c) => - c.kind === change.after.kind && - !data.categories.some((child) => child.parent_id === c.id), - ) - .map((c) => ({ value: c.id, label: categoryPath(data, c.id) })); const addable = data.tags .filter((t) => !value.tag_ids.includes(t.id)) .map((t) => ({ value: t.id, label: t.name })); @@ -728,13 +732,14 @@ function CorrectionEditor({
Category
- onChange({ ...value, category_id })} - placeholder="Search categories" - emptyText="No matching category. Create it in Categories first." />
@@ -763,16 +768,32 @@ function CorrectionEditor({ onChange({ ...value, tag_ids: [...value.tag_ids, id] }) } - placeholder={ - data.tags.length - ? "Add tag" - : "No tags yet — create them in Tags" + placeholder={data.tags.length ? "Add tag" : "Add or create tag"} + emptyText="No matching tag. Type a name to create it." + create={(text) => + data.tags.some( + (t) => t.name.toLowerCase() === text.toLowerCase(), + ) + ? [] + : [ + { + key: "tag", + label: `Create tag "${text}"`, + run: async () => + onChange({ + ...value, + tag_ids: [ + ...value.tag_ids, + await createTag(mutate, data, text), + ], + }), + }, + ] } - emptyText="No matching tag. Create it in Tags first." /> diff --git a/web/src/Registry.tsx b/web/src/Registry.tsx index 4c81203..0d288f9 100644 --- a/web/src/Registry.tsx +++ b/web/src/Registry.tsx @@ -21,7 +21,7 @@ import type { } from "./api"; import { categoryPath, request } from "./api"; import { - CategoryOptions, + CategoryCombobox, Empty, ErrorMessage, Field, @@ -550,17 +550,15 @@ function RegistryEditor({ - + onChange={setParent} + />

Changing the parent moves this category and its entire subtree. @@ -590,15 +588,21 @@ function RegistryEditor({ Use these defaults when this merchant is recognized - + onChange={setCategory} + /> - +

Defaults are only used when explicitly enabled. Editing defaults does not rewrite existing transactions. diff --git a/web/src/Transactions.tsx b/web/src/Transactions.tsx index 4ba9a13..f1218dc 100644 --- a/web/src/Transactions.tsx +++ b/web/src/Transactions.tsx @@ -18,7 +18,7 @@ import type { } from "./api"; import { categoryPath, money } from "./api"; import { - CategoryOptions, + CategoryCombobox, Empty, ErrorMessage, Field, @@ -453,16 +453,15 @@ function TransactionEditor({ {value.kind !== "transfer" && value.kind !== "investment" && ( - + onChange={(category_id) => setValue({ ...value, category_id })} + /> )} setValue({ ...value, tag_ids })} + mutate={mutate} />

diff --git a/web/src/main.tsx b/web/src/main.tsx index 71b8ac4..7d1abda 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -136,13 +136,12 @@ function App() { "/api/rebuild", ].includes(path); try { - acceptState( - await request( - path, - revisionless ? body : { revision: state.revision, ...body }, - ), - message, + const next = await request( + path, + revisionless ? body : { revision: state.revision, ...body }, ); + acceptState(next, message); + return next; } catch (err) { if (err instanceof APIError && err.status === 409) setConflict(true); throw err; @@ -352,7 +351,6 @@ function App() { )} {page === "transactions" && ( )} {page === "tags" && ( - + )} {page === "merchants" && ( - + )} {page === "instruments" && ( )} {page === "classification" && ( - + )} {page === "settings" && ( input { diff --git a/web/src/ui.tsx b/web/src/ui.tsx index 2dd7186..c7572c7 100644 --- a/web/src/ui.tsx +++ b/web/src/ui.tsx @@ -7,8 +7,9 @@ import { CalendarDays, ChevronLeft, ChevronRight, + Plus, } from "lucide-react"; -import type { Dataset, Filter, VerifiedModel } from "./api"; +import type { Category, Dataset, Filter, State, VerifiedModel } from "./api"; import { categoryPath, DEFAULT_MONTHS, @@ -103,6 +104,14 @@ export interface ComboOption { label: string; 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; +} // 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 // picking an option reports its value. The caller keeps working with stable @@ -116,6 +125,7 @@ export function Combobox({ required = false, adornment, emptyText = "No matches.", + create, }: { options: ComboOption[]; value: string; @@ -125,7 +135,10 @@ export function Combobox({ required?: boolean; adornment?: ReactNode; emptyText?: string; + create?: (text: string) => ComboCreate[]; }) { + const [creating, setCreating] = useState(false); + const [createError, setCreateError] = useState(""); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const filter = query.trim().toLowerCase(); @@ -137,10 +150,25 @@ export function Combobox({ ? [exact, ...matches.filter((o) => o !== exact).slice(0, 59)] : matches.slice(0, 60); const selected = options.find((o) => o.value === value); + const creations = + create && filter && !exact && !disabled ? create(query.trim()) : []; const pick = (v: string) => { onChange(v); 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)); + } finally { + setCreating(false); + } + }; return (
{ setQuery(e.target.value); + setCreateError(""); setOpen(true); }} onBlur={() => setOpen(false)} @@ -166,6 +195,10 @@ export function Combobox({ e.preventDefault(); const hit = exact ?? (shown.length === 1 ? shown[0] : undefined); if (hit) pick(hit.value); + // Enter creates only when nothing matches at all: with matches + // still listed, minting from a half-typed name is too easy. + else if (!shown.length && creations.length === 1) + void runCreate(creations[0]); } }} /> @@ -189,7 +222,24 @@ export function Combobox({ ))} - {shown.length === 0 &&
  • {emptyText}
  • } + {creations.map((c) => ( +
  • + +
  • + ))} + {createError &&
  • {createError}
  • } + {shown.length === 0 && creations.length === 0 && !createError && ( +
  • {emptyText}
  • + )} {matches.length > shown.length && (
  • {matches.length - shown.length} more — keep typing to narrow down. @@ -461,38 +511,135 @@ export function Empty({
  • ); } +// 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 { + 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 { + 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({ data, value, onChange, + mutate, }: { data: Dataset; value: string[]; onChange: (ids: string[]) => void; + mutate?: Mutate; }) { + const [draft, setDraft] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + 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([...value, id]); + setDraft(""); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setBusy(false); + } + }; return (
    Tags - {data.tags.length ? ( - data.tags.map((tag) => ( - - )) - ) : ( + {data.tags.map((tag) => ( + + ))} + {!data.tags.length && !mutate && ( No tags yet. Create them in Tags. )} + {mutate && ( + + { + setDraft(e.target.value); + setError(""); + }} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + void add(); + } + }} + /> + + + )} + {error && {error}}
    ); } @@ -517,6 +664,101 @@ 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[] => { + // Text aiming at the empty option ("No parent…") is a selection, not a + // new category name. + if (!mutate || emptyLabel?.toLowerCase().includes(text.toLowerCase())) + 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 ( + + ); +} export function Filters({ data, value, @@ -680,8 +922,10 @@ export function FormActions({ ); } +// Mutate posts a revisioned change and returns the accepted state, so a +// caller can find ids the server just minted. export type Mutate = ( path: string, body: Record, message?: string, -) => Promise; +) => Promise;