- The 13K-character instructions (clients cut them short) become a
connect text of at most 1,400 characters whose first 512 stand alone,
plus books.handbook and books://handbook/{section}: the old guidance by
section, with no helper commands, home paths, pull requests or
file-reading suggestions (tool_text_lint).
- Every tool has a title and read-only/destructive hints; no
requiresUserInteraction anywhere (owner decision 2026-10-16).
- books.import_local_file reads only regular files inside the import
roots (the downloads folder by default, or --import-root), never the
data dir, books dir, vault or the key's folder, no symlink escapes or
hard links, and the file opened must be the file checked.
- The store lock is a tokio mutex taken off the runtime threads.
- get_info refreshes settings first; a bare books://digest reads.
Review fixes (P0 review, 2026-10-16):
- Fail closed: a tokio mutex never poisons and spawn_blocking caught the
panic, so after a panic mid-mutation the server kept serving a Store
behind its journal. A panic (the task, or while holding the store)
now stops the shared store; every later request on every session is
refused with a plain message; a restart re-verifies the journal. The
join error goes through redact_refusal and never carries the panic's
text.
- books.set_w9 w9_file_path read any path (a link named w9.pdf to the
vault key was stored and get_w9 wrote it out): it now goes through the
import roots' lockdown, its type judged on the canonical path.
- Sealed even inside a root: the key file in force, where a linked one
leads, both folders, and the default key folder whatever the settings
say. Refusals check the roots first, so outside them every path gets
one message (no probing what exists); inside, other books-dir files say
to copy them out first.
- The open is O_NOFOLLOW | O_NONBLOCK (a pipe swapped in after the check
can't hang a thread) and must match the checked file's device and
inode. New dependency: libc (unix only), for those two open flags,
which std doesn't name.
- Default import roots are the downloads folder only (the plan); files
with full TINs (get_w9, vendor_1099 include_tins, the CPA package with
TINs) are never written into an import root, and the server refuses to
import any file it wrote with TINs (by SHA-256).
- set_tin and set_w9 overwrite vault records: destructive_hint = true;
annotations_complete pins the key tools' hints. The read-only hint is
checked in behaviour on every spec_mcp call (journal and data-dir files
unchanged).
- Text: the connect text names the settings file as the one local file
to edit, says every entry balances on real accounts and names its
party, says invoice/bill/payment/payroll tools post unchecked, rewords
the exemptions, and shows the company name as one plain line; the
handbook takes section "all", lists its ids in the schema and says to
read contract first; books.settings drops the config.json path and no
error names the data dir or the key file. tool_text_lint covers the
whole tool JSON and resources and bans git/commit/WL-0001; tool
descriptions over 700 characters are pinned to today's eight (P5).
- digest: an empty since= is bare; the default date is pinned on every
day of a month.
Round-2 review fixes (2026-10-16):
- TIN files (B-26): the in-memory, per-session set of TIN-file hashes
became one registry beside the vault (vault/tin-files.sha256, hashes
only), shared by every session and every later server. It holds the
W-9 set_w9 reads (recorded as read), get_w9 copies, 1099 worksheets
with TINs, CPA packages with TINs and each file in one that holds a
TIN; a file is recorded before it is written, and a failure refuses.
import_local_file, attach_receipt and file_document (base64 was never
checked) refuse a recorded file, and a text file (by type, name, or
UTF-8/UTF-16 decoding) holding a full TIN. Not caught: an altered
binary copy; the docs say so (P2/P7 remove the path tools).
- The text check is narrow (owner/engineer decision, 2026-10-16: bank
exports are filed for reconciliation, and has_full_tin's "nine digits
however separated" refused their routing numbers, long references and
dates run into amounts). Text is refused when it holds (a) a TIN the
vault holds for a party, anywhere, as nine digits, 3-2-4 joined by
hyphens, spaces or dots, or 2-7 joined by a hyphen or space, compared
on the server against the decrypted vault and never returned or
logged (a vault that can't be opened leaves (b)); or (b) a stand-alone
printed SSN (123-45-6789) or EIN (12-3456789) shape: no digit, and no
hyphen or dot followed by a digit, beside it. Full-width digits and
Unicode hyphens and spaces read as ASCII. has_full_tin still guards
refusals and results (redact_refusal). Known limit, for P7: a refusal
under (a) tells the agent a text it chose holds a vault TIN.
New dependency: zeroize in ledger-mcp (already in the workspace
through ledger-vault, same major version), so the vault's TINs decoded
for the scan are wiped from memory on drop as the vault's own are.
- Mutation testing of the final P0 diff (docs/testing.md): tests for
each law a survivor broke (handbook titles, a dropped default root, a
.jpg W-9, the waker, the walk's folder flags against a link and a
pipe, the 40-link limit, save paths refused as such, the package
marking only its TIN files, a registry that can't be read, text types,
the short receipt rule's counts and a 12-character code). Simpler
code where only a race could tell: inspect places an existing path by
canonicalize itself (no second comparison), read_checked's read limit
is its one size check, openat fails on -1 as specified. The 25 MiB
upload test removes its 50 MB of books however it ends.
- The GUI's stale-rule prompt no longer says to open a pull request: it
asks the agent to find the figure from the rule's official authority,
confirm it with the human, pass it explicitly, and tell the human so it
can be reported upstream (as the handbook says); a lib test pins it and
bans files, git, GitHub and pull requests from every attention prompt.
- Import roots (local_files.rs INVARIANT 0): XDG_DOWNLOAD_DIR="$HOME/"
made $HOME (or /) the root. No root may be /, the home folder or hold
it, or hold the books, data dir, vault or a key: a named one stops the
server at startup, a default one is dropped; the default falls back to
~/Downloads only if that is a real folder other than $HOME; with no
root, an import says so.
- The read is a component walk from / with openat(O_NOFOLLOW |
O_DIRECTORY) per folder and O_NOFOLLOW | O_NONBLOCK for the file, so a
folder swapped for a link after the check fails; no step may land on a
protected inode (one renamed into a root); dev/ino and nlink stay. No
/proc. Portable to macOS. (libc's openat, two small unsafe blocks.)
- One refusal for missing, dangling and outside paths: resolved()
follows every link, dangling ones too, so a link's target existing or
not no longer changes the answer.
- Sealing: the key files (in force, default) and their targets always;
their folders only when not $HOME, not a root, not holding a root; and
~/.config/wanderbooks whatever XDG_CONFIG_HOME says.
- Agent text (I-12): RuleNotKnown names the authority (IRS, with its
address) and says to tell the human, never a repo path, PR or GitHub;
the digest's stale_rules drop the repo catalog and path for it; vault,
outside-books, STOPPED and local-file refusals name no git, path or
flag. tool_text_lint bans docs/, .md, /home, data dir, --data-dir,
--import-root, vault.key, .jsonl, sqlite, .gitignore, github, pull
request, and also lints every error template (scanned from source),
built error texts, and the server's refusal constants.
- The receipt rule told (ReceiptPolicy::rule) is the one enforced: the
exact threshold in the base currency (no "$", no rounding), required
and exempt accounts, reversals exempt; the connect text fits 1,400
characters by dropping reasons, then codes, never the rule.
- The connect text follows the parties setting; "offer books.digest"
everywhere. shown_name drops Unicode format characters (bidi, zero
width).
- read_only_tools_change_nothing compares file contents, the database
by every row, the vault and the settings file (raw database bytes did
not change either; rows are the stable comparison).
- import_local_file takes the name and type from the canonical path;
the digest's journal repair says when the tail was set aside, not the
journal's file name; "version-history messages" back in the TIN rule;
openWorldHint false on every tool, pinned in annotations_complete.
- Outside the MCP crate, for the same texts: ledger-core's DatedRule
gains `authority` (the statute or publication with its address) and
RuleNotKnown carries it; ledger-store's "sqlite error" reads "database
error"; ledger-config's ReceiptPolicy::rule takes the base currency.
New dev-dependency: rusqlite in ledger-mcp (already in the workspace,
same version and features as ledger-store), to read the database's
rows in read_only_tools_change_nothing.
- The filing scan is no TIN oracle (tin_files.rs INVARIANT 4): text
holding more than two TIN-shaped numbers (any rendering rule (a)
reads) that end in a known TIN's last four (the books' TIN and W-9
facts, via known_tin_last4, before the vault is opened; then the
vault's own) is refused with TIN_PROBE, the same words whether or not
one is the vault's TIN; only one or two candidates are compared
against the vault. Tests: unit
text_probing_for_a_tin_is_refused_alike_whether_or_not_it_holds_it,
one_or_two_candidates_are_compared_against_the_vault; over HTTP
text_probing_for_a_tin_is_refused_alike_by_every_filing_tool.
Plan: plan/served.md P0, section 6 "Immediate hole (P0)", 4.1, 4.3, 4.9.
Review round 3. S1: a panic stops the server for every session, so no
input may reach one. Dates are four-digit years (new ledger_core::
calendar, 0001-01-01..9999-12-31): the MCP's parse_date is strict
YYYY-MM-DD, periods are bounded, last_day_of_month returns a refusal
(server and store); schedules, assets, recurring entries, periods,
documents, disposals and entries refuse dates outside the calendar, and
replay refuses such journal dates. Every amount a command takes is at
most a line's (draft lines by size, document lines, payouts, payroll,
statements, shares, tax basis, proceeds, recurring templates), on
replay too, so sums are exact; the 1099 vendor part and the K-1
property share use checked products (TooLargeToCompute); a recurring
run makes at most 1,000 drafts. tests/hostile_args.rs drives every tool
with schema-derived hostile arguments and every resource with generated
URIs, asserting the server never stops; the audit's panics are pinned.
S2: a `.` or `..` path name is refused as NO_SUCH_FILE up front. S3:
NUL-interleaved UTF-16 without a byte-order mark is scanned both ways.
S4: resource-read refusals are TIN-redacted. S5: set_w9 records its W-9
only once the call passes every check, just before the vault write.
S8: idempotentHint only on verify, run_depreciation, run_schedules,
run_recurring, set_party_roles (a repeat leaves journal and vault
alone; spec_vault checks every candidate twice); every tool's hints
pinned in one table. C1: books.settings lists receipt_required_accounts
and receipt_exempt_accounts uncut. C2: the default company name reads
"a new company". C3: the parties rule names no-party reasons. C4/C5:
the handbook names the settings file only as books.settings' books_toml,
and restores "check books.digest and offer it". C6: an import root
inside the books, data dir or vault is refused at startup. The lint
catches `just` however it ends and where the books are;
digest_resource_bare_reads reads the server's month.
Review round 4 (2026-10-17): round 3's bounds ran in replay too, so
journals main wrote and reopened (an entry dated 0000-06-01 or
+10000-01-01, a draft line of 2e15, an asset ending past 9999, a basis
or share past the line limit, sub-cent document and payroll lines) no
longer opened. Posted is forever: the bounds are the commands' only.
- Replay applies main's rule exactly: parse_date takes any date chrono
reads; replay_add_line(_fx) has no size bound (add_line/add_line_fx
do); replay_register_asset/correct_asset (chrono overflow only),
replay_set_asset_tax_basis (check_journaled), replay_set_entry_parties
(check_shares_journaled), replay_register_recurring
(validate_recurring_journaled), replay_register_schedule (months 1 to
600), replay_create_period (order only), replay_dispose_asset, and no
line, date, payment or payroll range checks in replay_invoice/bill,
their payments and replay_payroll_run.
- Derived figures over such books refuse (TooLargeToCompute,
DateOutOfRange), never panic: amortization plans, depreciation into
chrono's last month (and the true-up for lives past 9999), intervals,
document totals and aging, net pay and payroll plans, money flows and
share resolution, the asset register, receipt-policy debits; the MCP
tools and the viewer show what can't be computed.
- tests/fixtures/old-books: the review's 13 journals, its control and 15
more edges, written by main's Store API with main's figures
(expected.json); every one opens in the writer and the viewer to those
figures, every derived figure computes or refuses, every MCP tool and
GUI page answers; hostile_args restarts the server after each
property; each bound has a command/replay test pair.
Final review: a schedule's plan refuses a total of 10^26 or more
(TooLargeToCompute) instead of letting Decimal round its cents silently,
and a null `remaining` in the schedule output is always explained by
plan_error. Replay is unaffected: no journaled schedule month can belong
to a total that large (the line limit bounds every posted month).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
522 lines
19 KiB
Rust
522 lines
19 KiB
Rust
//! Ctrl+K: jump to anything. Pages, reports, accounts, entries (by text,
|
||
//! amount, or #id), fixed assets (by tag, serial, or description), parties
|
||
//! (vendors and customers among them, by name or display name),
|
||
//! documents, bank and card statements, and reconciliations (by account
|
||
//! and date), ranked by a simple fuzzy match.
|
||
|
||
use crate::books::Books;
|
||
use crate::fmt;
|
||
use crate::nav::{ReportKind, Route, Section};
|
||
use crate::theme::{self, pal};
|
||
use egui::{CornerRadius, Key, Margin, RichText, Sense, Stroke, vec2};
|
||
use egui_phosphor::regular as icon;
|
||
|
||
#[derive(Default)]
|
||
pub struct Palette {
|
||
open: bool,
|
||
query: String,
|
||
selected: usize,
|
||
focus: bool,
|
||
}
|
||
|
||
/// One search result.
|
||
pub struct Item {
|
||
pub icon: &'static str,
|
||
pub title: String,
|
||
pub detail: String,
|
||
pub route: Route,
|
||
pub score: i32,
|
||
}
|
||
|
||
impl Palette {
|
||
pub fn open(&mut self) {
|
||
self.open = true;
|
||
self.query.clear();
|
||
self.selected = 0;
|
||
self.focus = true;
|
||
}
|
||
|
||
/// Show the palette if open; returns where to go.
|
||
pub fn show(&mut self, ctx: &egui::Context, books: &Books) -> Option<Route> {
|
||
if !self.open {
|
||
return None;
|
||
}
|
||
let p = pal(ctx);
|
||
let items = search(books, &self.query);
|
||
let mut go = None;
|
||
let (up, down, enter, esc) = ctx.input(|i| {
|
||
(
|
||
i.key_pressed(Key::ArrowUp),
|
||
i.key_pressed(Key::ArrowDown),
|
||
i.key_pressed(Key::Enter),
|
||
i.key_pressed(Key::Escape),
|
||
)
|
||
});
|
||
if down {
|
||
self.selected = (self.selected + 1).min(items.len().saturating_sub(1));
|
||
}
|
||
if up {
|
||
self.selected = self.selected.saturating_sub(1);
|
||
}
|
||
if esc {
|
||
self.open = false;
|
||
return None;
|
||
}
|
||
if enter && let Some(it) = items.get(self.selected) {
|
||
self.open = false;
|
||
return Some(it.route.clone());
|
||
}
|
||
let modal = egui::Modal::new(egui::Id::new("palette"))
|
||
.frame(
|
||
egui::Frame::new()
|
||
.fill(p.surface)
|
||
.stroke(Stroke::new(1.0, p.border))
|
||
.corner_radius(CornerRadius::same(14))
|
||
.inner_margin(Margin::same(10)),
|
||
)
|
||
.show(ctx, |ui| {
|
||
// Never wider or taller than the window allows.
|
||
let screen = ctx.content_rect().size();
|
||
ui.set_width(620.0_f32.min(screen.x - 48.0).max(200.0));
|
||
let edit = egui::TextEdit::singleline(&mut self.query)
|
||
.hint_text("Search entries, accounts, assets, vendors, documents, reports…")
|
||
.font(theme::regular(16.0))
|
||
.frame(egui::Frame::NONE)
|
||
.desired_width(f32::INFINITY);
|
||
let r = ui.add(edit);
|
||
if self.focus {
|
||
r.request_focus();
|
||
self.focus = false;
|
||
}
|
||
if r.changed() {
|
||
self.selected = 0;
|
||
}
|
||
ui.add_space(6.0);
|
||
crate::widgets::rule(ui);
|
||
ui.add_space(4.0);
|
||
egui::ScrollArea::vertical()
|
||
.max_height(420.0_f32.min(screen.y - 160.0).max(120.0))
|
||
.show(ui, |ui| {
|
||
if items.is_empty() {
|
||
ui.label(RichText::new("Nothing matches.").color(p.muted));
|
||
}
|
||
for (i, it) in items.iter().enumerate() {
|
||
let (rect, resp) = ui.allocate_exact_size(
|
||
vec2(ui.available_width(), 40.0),
|
||
Sense::click(),
|
||
);
|
||
if i == self.selected || resp.hovered() {
|
||
ui.painter()
|
||
.rect_filled(rect, CornerRadius::same(8), p.hover);
|
||
}
|
||
if i == self.selected {
|
||
ui.scroll_to_rect(rect, None);
|
||
}
|
||
let painter = ui.painter_at(rect);
|
||
painter.text(
|
||
rect.left_center() + vec2(12.0, 0.0),
|
||
egui::Align2::LEFT_CENTER,
|
||
it.icon,
|
||
egui::FontId::proportional(16.0),
|
||
p.muted,
|
||
);
|
||
painter.text(
|
||
rect.left_center() + vec2(38.0, -7.0),
|
||
egui::Align2::LEFT_CENTER,
|
||
&it.title,
|
||
theme::regular(14.0),
|
||
p.text,
|
||
);
|
||
painter.text(
|
||
rect.left_center() + vec2(38.0, 9.0),
|
||
egui::Align2::LEFT_CENTER,
|
||
&it.detail,
|
||
theme::regular(11.5),
|
||
p.faint,
|
||
);
|
||
if resp.clicked() {
|
||
go = Some(it.route.clone());
|
||
}
|
||
}
|
||
});
|
||
});
|
||
if modal.should_close() {
|
||
self.open = false;
|
||
}
|
||
if go.is_some() {
|
||
self.open = false;
|
||
}
|
||
go
|
||
}
|
||
}
|
||
|
||
/// Subsequence match: every query character in order, rewarding
|
||
/// contiguous runs and word starts. None if no match.
|
||
/// Fuzzy match score, higher is better.
|
||
///
|
||
/// ```text
|
||
/// INVARIANTS:
|
||
/// 1. Matches (Some) exactly when the query's non-space characters,
|
||
/// lower-cased, appear in order in the lower-cased hay; the empty
|
||
/// query matches everything with score 0.
|
||
/// 2. A match's score is at least the number of non-space query
|
||
/// characters; consecutive matches and matches at a word start score
|
||
/// more. The score is the best over every way to match (not the
|
||
/// first match found), so a hay holding the query whole at a word
|
||
/// start scores at least as high as any hay's match of it.
|
||
/// ```
|
||
pub fn fuzzy(hay: &str, query: &str) -> Option<i32> {
|
||
let hay: Vec<char> = hay.to_lowercase().chars().collect();
|
||
// Query characters, each marked whether a space came just before it
|
||
// (a space ends a run: the next match earns no run bonus).
|
||
let mut q: Vec<(char, bool)> = Vec::new();
|
||
let mut after_space = false;
|
||
for c in query.to_lowercase().chars() {
|
||
if c == ' ' {
|
||
after_space = true;
|
||
} else {
|
||
q.push((c, after_space));
|
||
after_space = false;
|
||
}
|
||
}
|
||
if q.is_empty() {
|
||
return Some(0);
|
||
}
|
||
// The best score over every way to match (a greedy left-most match
|
||
// can miss a word start further on): best[j] is the top score for the
|
||
// query so far with its last character at hay[j].
|
||
let word_start = |j: usize| j == 0 || !hay[j - 1].is_alphanumeric();
|
||
let mut best: Vec<Option<i32>> = hay
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(j, &c)| (c == q[0].0).then(|| 1 + if word_start(j) { 4 } else { 0 }))
|
||
.collect();
|
||
for &(qc, gap) in &q[1..] {
|
||
let mut next = vec![None; hay.len()];
|
||
// The best score ending strictly before j.
|
||
let mut before: Option<i32> = None;
|
||
for j in 0..hay.len() {
|
||
if hay[j] == qc {
|
||
let bonus = if word_start(j) { 4 } else { 0 };
|
||
let run = if gap {
|
||
None
|
||
} else {
|
||
j.checked_sub(1)
|
||
.and_then(|p| best[p])
|
||
.map(|s| s + 6 + bonus)
|
||
};
|
||
let jump = before.map(|s| s + 1 + bonus);
|
||
next[j] = run.max(jump);
|
||
}
|
||
before = before.max(best[j]);
|
||
}
|
||
best = next;
|
||
}
|
||
best.into_iter().flatten().max()
|
||
}
|
||
|
||
/// What the palette lists for `query`, best first (at most 40).
|
||
///
|
||
/// ```text
|
||
/// INVARIANTS (fixed assets; everything else as it was):
|
||
/// 1. An asset whose tag equals the trimmed query, ignoring ASCII case,
|
||
/// scores 2000: above every other result (an entry's exact #id is
|
||
/// 1000).
|
||
/// 2. Otherwise an asset is listed when the query fuzzily matches its
|
||
/// tag, serial, and description; a query found whole in its tag or
|
||
/// serial (ignoring case) adds 500, in its description 50.
|
||
/// 3. Every asset result opens Route::Asset(its id).
|
||
/// INVARIANTS (parties):
|
||
/// 4. A party whose name or display name equals the trimmed query,
|
||
/// ignoring case, scores 1500: above an entry's exact #id, below an
|
||
/// exact asset tag.
|
||
/// 5. Otherwise a party is listed when the query fuzzily matches its
|
||
/// name and display name; a query found whole in either (ignoring
|
||
/// case) adds 500.
|
||
/// 6. Every party result opens Route::Party(its id); archived parties
|
||
/// are found too, and say so.
|
||
/// INVARIANTS (statements and reconciliations):
|
||
/// 7. A statement is listed when the query fuzzily matches "statement",
|
||
/// its account's code and name, its period's dates (as shown and as
|
||
/// YYYY-MM-DD), and its file name; it opens Route::Document(its
|
||
/// attachment).
|
||
/// 8. A reconciliation is listed when the query fuzzily matches
|
||
/// "reconciliation reconciled", its account's code and name, and its
|
||
/// statement date (as shown and as YYYY-MM-DD); it opens
|
||
/// Route::Reconciliation(its id), voided ones too, saying so.
|
||
/// ```
|
||
pub fn search(b: &Books, query: &str) -> Vec<Item> {
|
||
let q = query.trim();
|
||
let mut out: Vec<Item> = Vec::new();
|
||
let mut add = |icon: &'static str, title: String, detail: String, route: Route, hay: &str| {
|
||
if let Some(score) = fuzzy(hay, q) {
|
||
out.push(Item {
|
||
icon,
|
||
title,
|
||
detail,
|
||
route,
|
||
score,
|
||
});
|
||
}
|
||
};
|
||
for s in Section::ALL {
|
||
add(
|
||
s.icon(),
|
||
s.title().into(),
|
||
"Page".into(),
|
||
s.home(),
|
||
s.title(),
|
||
);
|
||
}
|
||
for r in ReportKind::ALL {
|
||
add(
|
||
icon::FILE_TEXT,
|
||
r.title().into(),
|
||
"Report".into(),
|
||
Route::Reports(r),
|
||
&format!("report {}", r.title()),
|
||
);
|
||
}
|
||
if !q.is_empty() {
|
||
for a in b.ledger.chart().all() {
|
||
add(
|
||
icon::TREE_STRUCTURE,
|
||
format!("{} {}", a.code, a.name),
|
||
format!("{:?} account", a.account_type),
|
||
Route::Account(a.id),
|
||
&format!("{} {}", a.code, a.name),
|
||
);
|
||
}
|
||
let id_query = q.strip_prefix('#').and_then(|s| s.parse::<u64>().ok());
|
||
for e in &b.entries {
|
||
let exact = id_query == Some(e.id);
|
||
let hay = &e.haystack;
|
||
let score = if exact {
|
||
Some(1000)
|
||
} else {
|
||
fuzzy(hay, q).filter(|_| q.len() >= 2)
|
||
};
|
||
if let Some(score) = score {
|
||
// Prefer substring hits for entries: fuzzy over long text is noisy.
|
||
let bonus = if hay.contains(&q.to_lowercase()) {
|
||
50
|
||
} else {
|
||
0
|
||
};
|
||
if bonus == 0 && !exact && q.len() < 4 {
|
||
continue;
|
||
}
|
||
out.push(Item {
|
||
icon: icon::RECEIPT,
|
||
title: format!("#{} {}", e.id, e.description),
|
||
detail: format!("{} · {}", fmt::date(e.date), fmt::dollars_or(e.amount)),
|
||
route: Route::Entry(e.id),
|
||
score: score + bonus,
|
||
});
|
||
}
|
||
}
|
||
let ql = q.to_lowercase();
|
||
for a in b.ledger.registered_assets() {
|
||
let tag = a.tag.as_deref().unwrap_or("");
|
||
let serial = a.serial.as_deref().unwrap_or("");
|
||
let hay = format!("{tag} {serial} {}", a.description);
|
||
let score = if !tag.is_empty() && tag.eq_ignore_ascii_case(q) {
|
||
Some(2000)
|
||
} else {
|
||
fuzzy(&hay, q).map(|s| {
|
||
let whole = |t: &str| !t.is_empty() && t.to_lowercase().contains(&ql);
|
||
s + if whole(tag) || whole(serial) {
|
||
500
|
||
} else if whole(&a.description) {
|
||
50
|
||
} else {
|
||
0
|
||
}
|
||
})
|
||
};
|
||
if let Some(score) = score {
|
||
let mut detail = vec!["Fixed asset".to_string()];
|
||
if !serial.is_empty() {
|
||
detail.push(format!("serial {serial}"));
|
||
}
|
||
detail.push(format!("in service {}", fmt::date(a.purchase_date)));
|
||
out.push(Item {
|
||
icon: icon::PACKAGE,
|
||
title: b.asset_label(a.id),
|
||
detail: detail.join(" · "),
|
||
route: Route::Asset(a.id),
|
||
score,
|
||
});
|
||
}
|
||
}
|
||
for p in b.ledger.parties() {
|
||
let display = p.display_name.as_deref().unwrap_or("");
|
||
let exact = |t: &str| !t.is_empty() && t.trim().to_lowercase() == ql;
|
||
let whole = |t: &str| !t.is_empty() && t.to_lowercase().contains(&ql);
|
||
let score = if exact(&p.name) || exact(display) {
|
||
Some(1500)
|
||
} else {
|
||
fuzzy(&format!("{} {display}", p.name), q).map(|s| {
|
||
s + if whole(&p.name) || whole(display) {
|
||
500
|
||
} else {
|
||
0
|
||
}
|
||
})
|
||
};
|
||
if let Some(score) = score {
|
||
let mut detail = vec![crate::pages::parties::roles_text(p)];
|
||
if p.display_name.is_some() {
|
||
detail.push(p.name.clone());
|
||
}
|
||
if p.archived {
|
||
detail.push("archived".into());
|
||
}
|
||
out.push(Item {
|
||
icon: crate::pages::parties::party_icon(p),
|
||
title: p.label().to_string(),
|
||
detail: detail.join(" · "),
|
||
route: Route::Party(p.id),
|
||
score,
|
||
});
|
||
}
|
||
}
|
||
for st in &b.statements {
|
||
let file = b
|
||
.attachment(st.attachment_id)
|
||
.map_or("", |a| a.file_name.as_str());
|
||
let hay = format!(
|
||
"statement {} {} {} {} {} {file}",
|
||
b.account_label(st.account_id),
|
||
fmt::date(st.period_start),
|
||
fmt::date(st.period_end),
|
||
st.period_start,
|
||
st.period_end
|
||
);
|
||
if let Some(score) = fuzzy(&hay, q) {
|
||
out.push(Item {
|
||
icon: icon::FILE_TEXT,
|
||
title: format!(
|
||
"Statement: {}, {} – {}",
|
||
b.account_name(st.account_id),
|
||
fmt::date_short(st.period_start),
|
||
fmt::date(st.period_end)
|
||
),
|
||
detail: format!("Closing {} · {file}", fmt::dollars(st.closing_balance)),
|
||
route: Route::Document(st.attachment_id),
|
||
score,
|
||
});
|
||
}
|
||
}
|
||
for r in &b.reconciliations {
|
||
let hay = format!(
|
||
"reconciliation reconciled {} {} {}",
|
||
b.account_label(r.account_id),
|
||
fmt::date(r.statement_date),
|
||
r.statement_date
|
||
);
|
||
if let Some(score) = fuzzy(&hay, q) {
|
||
let mut detail = vec![
|
||
fmt::dollars(r.statement_balance),
|
||
fmt::count(r.cleared.len(), "cleared line", "cleared lines"),
|
||
];
|
||
if r.voided.is_some() {
|
||
detail.push("voided".into());
|
||
}
|
||
out.push(Item {
|
||
icon: icon::CHECK_SQUARE,
|
||
title: format!(
|
||
"Reconciliation: {} through {}",
|
||
b.account_name(r.account_id),
|
||
fmt::date(r.statement_date)
|
||
),
|
||
detail: detail.join(" · "),
|
||
route: Route::Reconciliation(r.id),
|
||
score,
|
||
});
|
||
}
|
||
}
|
||
for a in &b.attachments {
|
||
let hay = format!("{} {}", a.file_name, a.description.as_deref().unwrap_or(""));
|
||
if let Some(score) = fuzzy(&hay, q) {
|
||
out.push(Item {
|
||
icon: icon::FILE,
|
||
title: a.file_name.clone(),
|
||
detail: format!(
|
||
"{} · {}",
|
||
fmt::label(&a.category),
|
||
a.description.as_deref().unwrap_or("")
|
||
),
|
||
route: Route::Document(a.id),
|
||
score,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
out.sort_by_key(|i| std::cmp::Reverse(i.score));
|
||
out.truncate(40);
|
||
out
|
||
}
|
||
|
||
/// The breadcrumb for a route, outermost first: its section, any page it
|
||
/// sits under (a reconciliation under its account), then the route
|
||
/// itself. Each crumb is its text and where clicking it goes; `None` for
|
||
/// the page you're on, which isn't a link.
|
||
///
|
||
/// ```text
|
||
/// INVARIANTS:
|
||
/// 1. The first crumb is the section's title, going to Section::home.
|
||
/// 2. The last crumb is the current page: describe(r) when it says
|
||
/// anything, else the section itself (a section's own page).
|
||
/// 3. Only the last crumb is None; a crumb whose route is the current
|
||
/// one is never a link.
|
||
/// ```
|
||
pub fn crumbs(b: Option<&Books>, r: &Route) -> Vec<(String, Option<Route>)> {
|
||
let section = r.section();
|
||
let here = b.map(|b| describe(b, r)).unwrap_or_default();
|
||
let mut out = vec![(section.title().to_string(), Some(section.home()))];
|
||
if let (Some(b), Route::Reconciliation(id)) = (b, r)
|
||
&& let Some(rec) = b.reconciliation(*id)
|
||
{
|
||
let account = Route::Account(rec.account_id);
|
||
out.push((describe(b, &account), Some(account)));
|
||
}
|
||
if here.is_empty() {
|
||
out.truncate(1);
|
||
} else {
|
||
out.push((here, None));
|
||
}
|
||
for c in &mut out {
|
||
if c.1.as_ref() == Some(r) {
|
||
c.1 = None;
|
||
}
|
||
}
|
||
if let Some(last) = out.last_mut() {
|
||
last.1 = None;
|
||
}
|
||
out
|
||
}
|
||
|
||
/// A short description of a route for the breadcrumb.
|
||
pub fn describe(b: &Books, r: &Route) -> String {
|
||
match r {
|
||
Route::Entry(id) => b
|
||
.entry(*id)
|
||
.map(|e| format!("#{} {}", e.id, e.description))
|
||
.unwrap_or_default(),
|
||
Route::Reports(k) => k.title().into(),
|
||
Route::Account(id) => b.account_label(*id),
|
||
Route::Document(id) => b
|
||
.attachments
|
||
.iter()
|
||
.find(|a| a.id == *id)
|
||
.map(|a| a.file_name.clone())
|
||
.unwrap_or_default(),
|
||
Route::Asset(id) => b.asset_label(*id),
|
||
Route::Party(id) => b.party_label(*id),
|
||
Route::Reconciliation(id) => b.subject_label(ledger_store::Subject::Reconciliation(*id)),
|
||
Route::JournalEvent(seq) => format!("Event {seq}"),
|
||
_ => String::new(),
|
||
}
|
||
}
|