Fixed assets, fully featured: tags, serials, acquisition links, label sheets, the fixed asset register, and an Assets section in the viewer; fix a flaky verify
- core: asset tags (generated PREFIX-0001 or the human's own; unique ignoring case; never reused by another asset) and serial numbers (rules.md B-24); a journaled link from an asset to the entry that acquired it (posted, unreversed, debiting the cost account); fixed_asset_register(as_of), reconciled to the GL (unposted depreciation, unregistered cost) - store: asset.tagged, asset.serial_set, asset.acquisition_linked journaled, replayed, projected (schema v9); differs_from now also compares control roles and tag history - config: [books] asset_tag_prefix, default the company's initials without legal-form words - import: Avery 5160/8160 label sheets with QR codes (geometry vendored from Avery, docs/spec/sources/avery-5160.md); the register as XLSX and PDF - mcp: register_asset tags (and links) automatically; books.label_asset, books.asset_labels; asset tools take a tag; books.show asset / assets page / register report; export fixed_asset_register (json, csv, xlsx, pdf) and in the CPA package - viewer: Assets page (register, reconciliation), asset page (identity, schedule posted vs not, entries, documents), Fixed asset register report, global search by tag/serial/description, journal text, needs-attention items - fix: verify compared snapshot amounts as strings; a zero total summed in hash-map order could print "0" or "0.00", so agreeing books failed verify at random. Now by value (regression test) - tests: spec-blind suites for tags, register, prefix, store, MCP; label and register PDF/XLSX tests; viewer tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GWVo7x3UHw5kwCUaWxiejX
This commit is contained in:
1 parent
4e96b5f54d
commit
cd085108c1
53 files changed
+7872
-104
No files matched your search
@@ -21,6 +21,7 @@ pub struct PageState {
|
||||
pub transactions: pages::transactions::State,
|
||||
pub reports: pages::reports::State,
|
||||
pub accounts: pages::accounts::State,
|
||||
pub assets: pages::assets::State,
|
||||
pub documents: pages::documents::State,
|
||||
pub journal: pages::journal::State,
|
||||
}
|
||||
@@ -121,6 +122,7 @@ impl App {
|
||||
"transactions" => Route::Transactions,
|
||||
"reports" => Route::Reports(ReportKind::ProfitAndLoss),
|
||||
"accounts" => Route::Accounts,
|
||||
"assets" => Route::Assets,
|
||||
"documents" => Route::Documents,
|
||||
"company" => Route::Company,
|
||||
"journal" => Route::Journal,
|
||||
@@ -170,6 +172,7 @@ impl App {
|
||||
"vendor_1099" => ReportKind::Vendor1099,
|
||||
"ar_aging" => ReportKind::ArAging,
|
||||
"ap_aging" => ReportKind::ApAging,
|
||||
"fixed_asset_register" => ReportKind::FixedAssetRegister,
|
||||
_ => return,
|
||||
};
|
||||
if let (s, e) = (date(&start), date(&end))
|
||||
@@ -182,6 +185,12 @@ impl App {
|
||||
Route::Reports(kind)
|
||||
}
|
||||
T::Document { attachment_id } => Route::Document(attachment_id),
|
||||
T::Asset { asset_id } => {
|
||||
if b.ledger.get_asset(asset_id).is_none() {
|
||||
return;
|
||||
}
|
||||
Route::Asset(asset_id)
|
||||
}
|
||||
T::Search { query } => {
|
||||
let st = &mut self.state.transactions;
|
||||
st.query = query;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! What the books need: drafts left unposted, missing receipts, schedules
|
||||
//! and recurring entries due, open past periods, uncategorized tax lines,
|
||||
//! 1099 vendors without a W-9, overdue bills and invoices, money owed to
|
||||
//! owners, and legal rules (like the 1099 threshold) due for an update. Each item says what's wrong, where to look, and the prompt that
|
||||
//! owners, fixed asset depreciation not posted and assets without a tag,
|
||||
//! and legal rules (like the 1099 threshold) due for an update. Each item says what's wrong, where to look, and the prompt that
|
||||
//! asks the agent to fix it (the GUI never changes the books itself).
|
||||
|
||||
use crate::books::{Attention, Books, Severity};
|
||||
@@ -31,7 +32,11 @@ use rust_decimal::Decimal;
|
||||
/// invoices (Problem, one each, with the total); money owed to
|
||||
/// owners (Info, per account with a balance); the database differing
|
||||
/// from the journal or unreadable, and damaged or missing stored
|
||||
/// files (Problem).
|
||||
/// files (Problem); depreciation due through the last finished month
|
||||
/// and not posted (Books::depreciation_due amount > 0: Todo, one
|
||||
/// item); the asset register and the books' asset cost accounts
|
||||
/// disagreeing today (unregistered_cost != 0: Problem); an active
|
||||
/// asset in service with no tag (Todo, one per asset).
|
||||
/// 3. Nothing else: books with none of those yield no items.
|
||||
/// 4. Every item's prompt starts "In wanderbooks," or names
|
||||
/// wanderbooks, and its amounts are the books' exact amounts.
|
||||
@@ -306,6 +311,79 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
}
|
||||
}
|
||||
|
||||
let due = b.depreciation_due(today);
|
||||
if due.amount > Decimal::ZERO {
|
||||
let months = if due.periods.is_empty() {
|
||||
"every month not yet posted".to_string()
|
||||
} else {
|
||||
due.periods.join(", ")
|
||||
};
|
||||
out.push(Attention {
|
||||
severity: Severity::Todo,
|
||||
title: format!("Depreciation not posted through {}", fmt::date(due.through)),
|
||||
detail: format!(
|
||||
"{} scheduled and not yet in the books ({}).",
|
||||
fmt::dollars(due.amount),
|
||||
months
|
||||
),
|
||||
target: Some(Route::Assets),
|
||||
prompt: format!(
|
||||
"In wanderbooks, run books.run_depreciation for {months} (depreciation due through {} and not posted: {}), then show me the fixed asset register.",
|
||||
due.through,
|
||||
fmt::dollars(due.amount)
|
||||
),
|
||||
});
|
||||
}
|
||||
let register = b.asset_register(today);
|
||||
let unregistered = register.unregistered_cost();
|
||||
if !unregistered.is_zero() {
|
||||
let (title, why) = if unregistered > Decimal::ZERO {
|
||||
(
|
||||
format!(
|
||||
"{} of equipment not in the asset register",
|
||||
fmt::dollars(unregistered)
|
||||
),
|
||||
"The asset cost accounts hold more than the registered assets cost: something bought was never registered.",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
format!(
|
||||
"{} of registered assets not in the books",
|
||||
fmt::dollars(-unregistered)
|
||||
),
|
||||
"Registered assets cost more than their cost accounts hold: a purchase entry may be missing.",
|
||||
)
|
||||
};
|
||||
out.push(Attention {
|
||||
severity: Severity::Problem,
|
||||
title,
|
||||
detail: why.into(),
|
||||
target: Some(Route::Assets),
|
||||
prompt: format!(
|
||||
"In wanderbooks, the fixed asset register and the asset cost accounts differ by {} today. Find what's behind it (books.list_assets and the cost accounts' registers) and tell me how to fix it.",
|
||||
fmt::dollars(unregistered)
|
||||
),
|
||||
});
|
||||
}
|
||||
for a in b.ledger.registered_assets().filter(|a| {
|
||||
a.tag.is_none() && a.status == ledger_core::AssetStatus::Active && a.purchase_date <= today
|
||||
}) {
|
||||
out.push(Attention {
|
||||
severity: Severity::Todo,
|
||||
title: format!("No tag: {}", a.description),
|
||||
detail: format!(
|
||||
"Asset {}, in service {}. A tag is the label on the thing itself.",
|
||||
a.id,
|
||||
fmt::date(a.purchase_date)
|
||||
),
|
||||
target: Some(Route::Asset(a.id)),
|
||||
prompt: format!(
|
||||
"In wanderbooks, label asset {} (\"{}\") with books.label_asset: give it the next generated tag unless I have my own, and its serial number if I can find it. Then print its label with books.asset_labels.",
|
||||
a.id, a.description
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
use ledger_store::DiskCheck;
|
||||
let verify_prompt = "In wanderbooks, run books.verify and tell me what it found.".to_string();
|
||||
match &b.integrity.disk {
|
||||
|
||||
@@ -7,11 +7,14 @@ use chrono::{Datelike, NaiveDate};
|
||||
use ledger_config::BooksSettings;
|
||||
use ledger_core::analysis::{balance_history, balance_series};
|
||||
use ledger_core::reports::{balance_sheet_as_of, profit_and_loss_for_period};
|
||||
use ledger_core::{AccountId, AccountType, EntryId, EntryStatus, Ledger, Side};
|
||||
use ledger_core::{
|
||||
AccountId, AccountType, AssetId, AssetRegister, AssetStatus, EntryId, EntryStatus, Ledger,
|
||||
Side, fixed_asset_register,
|
||||
};
|
||||
use ledger_store::{Attachment, JournalLine, Snapshot};
|
||||
use rust_decimal::Decimal;
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// One entry, indexed for listing and detail.
|
||||
@@ -45,6 +48,63 @@ pub struct EntryInfo {
|
||||
pub haystack: String,
|
||||
}
|
||||
|
||||
/// One fixed asset's trail through the journal and the entries.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct AssetTrail {
|
||||
/// Depreciation the books carry, by month ("YYYY-MM"): the entry and
|
||||
/// its amount, from `asset.depreciation_posted`.
|
||||
pub depreciation: BTreeMap<String, (EntryId, Decimal)>,
|
||||
/// The disposal entry, from `asset.disposed`.
|
||||
pub disposal_entry: Option<EntryId>,
|
||||
/// The entry that put it on the books, when one can be told: posted,
|
||||
/// debiting its cost account exactly its cost, dated its in-service
|
||||
/// date (else the nearest such entry within 31 days), and not already
|
||||
/// claimed by an earlier asset.
|
||||
pub purchase_entry: Option<EntryId>,
|
||||
/// Indexes into [`Books::journal`] of every `asset.*` event about it.
|
||||
pub events: Vec<usize>,
|
||||
}
|
||||
|
||||
impl AssetTrail {
|
||||
/// Every entry that touches the asset: purchase, depreciation (by
|
||||
/// month), disposal.
|
||||
pub fn entries(&self) -> Vec<EntryId> {
|
||||
let mut out: Vec<EntryId> = self.purchase_entry.into_iter().collect();
|
||||
out.extend(self.depreciation.values().map(|(e, _)| *e));
|
||||
out.extend(self.disposal_entry);
|
||||
out
|
||||
}
|
||||
|
||||
/// Depreciation the books carry for it, summed exactly.
|
||||
pub fn posted(&self) -> Decimal {
|
||||
self.depreciation.values().map(|(_, a)| *a).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// Depreciation due and not yet in the books.
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: say when monthly depreciation hasn't been run, without crying
|
||||
/// wolf over the month still under way.
|
||||
/// SOURCE: docs/spec/rules.md B-15 (monthly straight-line depreciation);
|
||||
/// CONVENTION (a month's depreciation is posted when the month
|
||||
/// ends: ledger-store dates it the month's last day).
|
||||
/// INVARIANTS:
|
||||
/// 1. through is as_of when as_of is a month's last day, else the last
|
||||
/// day of the month before as_of's.
|
||||
/// 2. amount is fixed_asset_register(ledger, through)
|
||||
/// .unposted_depreciation(), exactly.
|
||||
/// 3. periods: the months ("YYYY-MM", ascending, distinct) that some
|
||||
/// asset held on `through` has in its schedule through `through`
|
||||
/// and no depreciation posted for.
|
||||
/// ```
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DepreciationDue {
|
||||
pub through: NaiveDate,
|
||||
pub amount: Decimal,
|
||||
pub periods: Vec<String>,
|
||||
}
|
||||
|
||||
/// Something the books need, with how to fix it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Attention {
|
||||
@@ -90,6 +150,10 @@ pub struct Books {
|
||||
pub attention: Vec<Attention>,
|
||||
pub kpis: Kpis,
|
||||
pub integrity: Integrity,
|
||||
/// Each registered asset's trail, by asset id.
|
||||
pub asset_trails: HashMap<AssetId, AssetTrail>,
|
||||
/// The asset each depreciation, disposal, or purchase entry is about.
|
||||
pub entry_assets: HashMap<EntryId, AssetId>,
|
||||
}
|
||||
|
||||
/// Whether what's on disk is what the journal says.
|
||||
@@ -319,6 +383,13 @@ impl Books {
|
||||
}
|
||||
entries.sort_by(|a, b| b.date.cmp(&a.date).then(b.id.cmp(&a.id)));
|
||||
let entry_index = entries.iter().enumerate().map(|(i, e)| (e.id, i)).collect();
|
||||
let asset_trails = asset_trails(&ledger, &journal);
|
||||
let mut entry_assets = HashMap::new();
|
||||
for (&a, t) in &asset_trails {
|
||||
for e in t.entries() {
|
||||
entry_assets.insert(e, a);
|
||||
}
|
||||
}
|
||||
let mut books = Books {
|
||||
ledger,
|
||||
settings,
|
||||
@@ -340,6 +411,8 @@ impl Books {
|
||||
attention: Vec::new(),
|
||||
kpis: Kpis::default(),
|
||||
integrity,
|
||||
asset_trails,
|
||||
entry_assets,
|
||||
};
|
||||
books.kpis = books.compute_kpis();
|
||||
books.attention = crate::attention::find(&books);
|
||||
@@ -483,6 +556,61 @@ impl Books {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixed asset register on `as_of`, exactly as ledger-core
|
||||
/// computes it.
|
||||
pub fn asset_register(&self, as_of: NaiveDate) -> AssetRegister {
|
||||
fixed_asset_register(&self.ledger, as_of)
|
||||
}
|
||||
|
||||
/// An asset's trail (empty for an unknown asset).
|
||||
pub fn asset_trail(&self, id: AssetId) -> AssetTrail {
|
||||
self.asset_trails.get(&id).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// "FL-0001 MacBook Pro" (or just the description, untagged).
|
||||
pub fn asset_label(&self, id: AssetId) -> String {
|
||||
match self.ledger.get_asset(id) {
|
||||
Some(a) => match &a.tag {
|
||||
Some(t) => format!("{t} {}", a.description),
|
||||
None => a.description.clone(),
|
||||
},
|
||||
None => format!("asset {id}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Depreciation due through the last finished month on or before
|
||||
/// `as_of` and not yet posted (see [`DepreciationDue`]).
|
||||
pub fn depreciation_due(&self, as_of: NaiveDate) -> DepreciationDue {
|
||||
let through = if as_of.succ_opt().is_some_and(|d| d.day() == 1) {
|
||||
as_of
|
||||
} else {
|
||||
NaiveDate::from_ymd_opt(as_of.year(), as_of.month(), 1).expect("valid")
|
||||
- chrono::Days::new(1)
|
||||
};
|
||||
let amount = self.asset_register(through).unposted_depreciation();
|
||||
let mut periods = std::collections::BTreeSet::new();
|
||||
for a in self
|
||||
.ledger
|
||||
.registered_assets()
|
||||
.filter(|a| a.purchase_date <= through)
|
||||
{
|
||||
if matches!(a.status, AssetStatus::Disposed { date, .. } if date <= through) {
|
||||
continue;
|
||||
}
|
||||
let posted = self.asset_trails.get(&a.id);
|
||||
for l in ledger_core::depreciation_schedule(a, through) {
|
||||
if !posted.is_some_and(|t| t.depreciation.contains_key(&l.period)) {
|
||||
periods.insert(l.period);
|
||||
}
|
||||
}
|
||||
}
|
||||
DepreciationDue {
|
||||
through,
|
||||
amount,
|
||||
periods: periods.into_iter().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Blob store path for an attachment.
|
||||
pub fn blob_root(&self) -> PathBuf {
|
||||
self.data_dir.join("blobs")
|
||||
@@ -520,6 +648,92 @@ fn parties(ledger: &Ledger, journal: &[JournalLine]) -> HashMap<EntryId, String>
|
||||
out
|
||||
}
|
||||
|
||||
/// Every registered asset's trail, from the journal (depreciation,
|
||||
/// disposal, its own events) and the entries (the purchase).
|
||||
fn asset_trails(ledger: &Ledger, journal: &[JournalLine]) -> HashMap<AssetId, AssetTrail> {
|
||||
let mut out: HashMap<AssetId, AssetTrail> = ledger
|
||||
.registered_assets()
|
||||
.map(|a| (a.id, AssetTrail::default()))
|
||||
.collect();
|
||||
let u = |p: &Value, k: &str| p.get(k).and_then(|v| v.as_u64());
|
||||
for (i, line) in journal.iter().enumerate() {
|
||||
let p = &line.payload;
|
||||
let asset = match line.line_type.as_str() {
|
||||
"asset.registered" => u(p, "id"),
|
||||
t if t.starts_with("asset.") => u(p, "asset_id"),
|
||||
_ => None,
|
||||
};
|
||||
let Some(t) = asset.and_then(|a| out.get_mut(&a)) else {
|
||||
continue;
|
||||
};
|
||||
t.events.push(i);
|
||||
match line.line_type.as_str() {
|
||||
"asset.depreciation_posted" => {
|
||||
if let (Some(period), Some(entry), Some(amount)) = (
|
||||
p.get("period").and_then(|v| v.as_str()),
|
||||
u(p, "entry_id"),
|
||||
p.get("amount")
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(|s| s.parse::<Decimal>().ok()),
|
||||
) {
|
||||
t.depreciation.insert(period.to_string(), (entry, amount));
|
||||
}
|
||||
}
|
||||
"asset.disposed" => t.disposal_entry = u(p, "entry_id"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// The purchase: an entry that debits the cost account exactly the cost,
|
||||
// on the in-service date or as near it as can be (within 31 days).
|
||||
// A linked acquisition is the purchase; otherwise match it.
|
||||
for a in ledger.registered_assets() {
|
||||
if let (Some(id), Some(t)) = (a.acquired_by, out.get_mut(&a.id)) {
|
||||
t.purchase_entry = Some(id);
|
||||
}
|
||||
}
|
||||
let reversed: HashSet<EntryId> = (1..ledger.next_entry_id())
|
||||
.filter_map(|id| ledger.get_entry(id).and_then(|e| e.reversal_of()))
|
||||
.collect();
|
||||
let mut claimed: HashSet<EntryId> = out.values().flat_map(|t| t.entries()).collect();
|
||||
for a in ledger
|
||||
.registered_assets()
|
||||
.filter(|a| a.acquired_by.is_none())
|
||||
{
|
||||
let mut best: Option<(i64, EntryId)> = None;
|
||||
for id in 1..ledger.next_entry_id() {
|
||||
let Some(e) = ledger.get_entry(id) else {
|
||||
continue;
|
||||
};
|
||||
if e.status() != EntryStatus::Posted
|
||||
|| e.reversal_of().is_some()
|
||||
|| reversed.contains(&id)
|
||||
|| claimed.contains(&id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let days = (e.date() - a.purchase_date).num_days().abs();
|
||||
if days > 31 {
|
||||
continue;
|
||||
}
|
||||
let buys = e.lines().iter().any(|l| {
|
||||
l.account == a.cost_account
|
||||
&& l.side == Side::Debit
|
||||
&& l.amount.amount == a.cost.amount
|
||||
});
|
||||
if buys && best.is_none_or(|(d, _)| days < d) {
|
||||
best = Some((days, id));
|
||||
}
|
||||
}
|
||||
if let Some((_, id)) = best {
|
||||
claimed.insert(id);
|
||||
if let Some(t) = out.get_mut(&a.id) {
|
||||
t.purchase_entry = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Entry ids a journal line refers to.
|
||||
pub fn entry_refs(line: &JournalLine) -> Vec<EntryId> {
|
||||
let p = &line.payload;
|
||||
|
||||
@@ -376,6 +376,9 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
accum_depr_account: accum,
|
||||
expense_account: depreciation,
|
||||
})?;
|
||||
// The label on the laptop, and its serial number.
|
||||
s.set_asset_tag(asset, "JS-0001")?;
|
||||
s.set_asset_serial(asset, Some("C02FK3XJQ6L4"))?;
|
||||
|
||||
// Prepaid insurance, spread over a year.
|
||||
let ins_date = day(start + Months::new(2), 15);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Where you are and how you got there: a browser-style history.
|
||||
|
||||
use ledger_core::{AccountId, EntryId};
|
||||
use ledger_core::{AccountId, AssetId, EntryId};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ReportKind {
|
||||
@@ -14,16 +14,18 @@ pub enum ReportKind {
|
||||
ArAging,
|
||||
ApAging,
|
||||
Vendor1099,
|
||||
FixedAssetRegister,
|
||||
}
|
||||
|
||||
impl ReportKind {
|
||||
pub const ALL: [ReportKind; 10] = [
|
||||
pub const ALL: [ReportKind; 11] = [
|
||||
ReportKind::ProfitAndLoss,
|
||||
ReportKind::BalanceSheet,
|
||||
ReportKind::CashFlow,
|
||||
ReportKind::MembersEquity,
|
||||
ReportKind::TrialBalance,
|
||||
ReportKind::GeneralLedger,
|
||||
ReportKind::FixedAssetRegister,
|
||||
ReportKind::TaxSummary,
|
||||
ReportKind::Vendor1099,
|
||||
ReportKind::ArAging,
|
||||
@@ -42,6 +44,7 @@ impl ReportKind {
|
||||
ReportKind::ArAging => "Receivables aging",
|
||||
ReportKind::ApAging => "Payables aging",
|
||||
ReportKind::Vendor1099 => "1099 worksheet",
|
||||
ReportKind::FixedAssetRegister => "Fixed asset register",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,6 +59,10 @@ pub enum Route {
|
||||
Reports(ReportKind),
|
||||
Accounts,
|
||||
Account(AccountId),
|
||||
/// The fixed asset register.
|
||||
Assets,
|
||||
/// One fixed asset.
|
||||
Asset(AssetId),
|
||||
Documents,
|
||||
Document(u64),
|
||||
Company,
|
||||
@@ -73,6 +80,7 @@ impl Route {
|
||||
Route::Transactions | Route::Entry(_) => Section::Transactions,
|
||||
Route::Reports(_) => Section::Reports,
|
||||
Route::Accounts | Route::Account(_) => Section::Accounts,
|
||||
Route::Assets | Route::Asset(_) => Section::Assets,
|
||||
Route::Documents | Route::Document(_) => Section::Documents,
|
||||
Route::Company => Section::Company,
|
||||
Route::Journal | Route::JournalEvent(_) => Section::Journal,
|
||||
@@ -88,19 +96,21 @@ pub enum Section {
|
||||
Transactions,
|
||||
Reports,
|
||||
Accounts,
|
||||
Assets,
|
||||
Documents,
|
||||
Company,
|
||||
Journal,
|
||||
}
|
||||
|
||||
impl Section {
|
||||
pub const ALL: [Section; 9] = [
|
||||
pub const ALL: [Section; 10] = [
|
||||
Section::Overview,
|
||||
Section::Cash,
|
||||
Section::Profit,
|
||||
Section::Transactions,
|
||||
Section::Reports,
|
||||
Section::Accounts,
|
||||
Section::Assets,
|
||||
Section::Documents,
|
||||
Section::Company,
|
||||
Section::Journal,
|
||||
@@ -114,6 +124,7 @@ impl Section {
|
||||
Section::Transactions => "Transactions",
|
||||
Section::Reports => "Reports",
|
||||
Section::Accounts => "Accounts",
|
||||
Section::Assets => "Assets",
|
||||
Section::Documents => "Documents",
|
||||
Section::Company => "Company",
|
||||
Section::Journal => "Journal",
|
||||
@@ -129,6 +140,7 @@ impl Section {
|
||||
Section::Transactions => i::LIST_BULLETS,
|
||||
Section::Reports => i::FILE_TEXT,
|
||||
Section::Accounts => i::TREE_STRUCTURE,
|
||||
Section::Assets => i::PACKAGE,
|
||||
Section::Documents => i::FILES,
|
||||
Section::Company => i::BUILDINGS,
|
||||
Section::Journal => i::SCROLL,
|
||||
@@ -143,6 +155,7 @@ impl Section {
|
||||
Section::Transactions => Route::Transactions,
|
||||
Section::Reports => Route::Reports(ReportKind::ProfitAndLoss),
|
||||
Section::Accounts => Route::Accounts,
|
||||
Section::Assets => Route::Assets,
|
||||
Section::Documents => Route::Documents,
|
||||
Section::Company => Route::Company,
|
||||
Section::Journal => Route::Journal,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -194,10 +194,18 @@ fn assets(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
return;
|
||||
}
|
||||
let mut go = None;
|
||||
widgets::titled_card(
|
||||
let (register, _) = widgets::titled_card(
|
||||
ui,
|
||||
"Fixed assets",
|
||||
|_| {},
|
||||
|ui| {
|
||||
widgets::link(
|
||||
ui,
|
||||
RichText::new(format!("Asset register {}", icon::ARROW_RIGHT))
|
||||
.font(theme::regular(12.5))
|
||||
.color(p.accent),
|
||||
)
|
||||
.clicked()
|
||||
},
|
||||
|ui| {
|
||||
for a in &assets {
|
||||
// What has actually been posted, so this ties to the balance
|
||||
@@ -228,11 +236,11 @@ fn assets(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if widgets::link(
|
||||
ui,
|
||||
RichText::new(&a.description).font(theme::semibold(13.5)),
|
||||
RichText::new(b.asset_label(a.id)).font(theme::semibold(13.5)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
go = Some(a.cost_account);
|
||||
go = Some(a.id);
|
||||
}
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
@@ -271,7 +279,10 @@ fn assets(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
},
|
||||
);
|
||||
if let Some(id) = go {
|
||||
shell.go(Route::Account(id));
|
||||
shell.go(Route::Asset(id));
|
||||
}
|
||||
if register {
|
||||
shell.go(Route::Assets);
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
}
|
||||
|
||||
@@ -85,6 +85,19 @@ pub fn detail(ui: &mut Ui, b: &Books, e: &EntryInfo, shell: &mut Shell<'_>) {
|
||||
shell.go(Route::Entry(r));
|
||||
}
|
||||
}
|
||||
if let Some(&asset) = b.entry_assets.get(&e.id) {
|
||||
ui.add_space(4.0);
|
||||
if widgets::link(
|
||||
ui,
|
||||
RichText::new(format!("{} {}", icon::PACKAGE, b.asset_label(asset)))
|
||||
.color(p.accent),
|
||||
)
|
||||
.on_hover_text("Open this fixed asset")
|
||||
.clicked()
|
||||
{
|
||||
shell.go(Route::Asset(asset));
|
||||
}
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
|
||||
// Facts.
|
||||
|
||||
@@ -23,6 +23,8 @@ pub struct Event {
|
||||
pub icon: &'static str,
|
||||
pub text: String,
|
||||
pub route: Option<Route>,
|
||||
/// A second place it's about (the asset of a depreciation entry).
|
||||
pub also: Option<Route>,
|
||||
}
|
||||
|
||||
fn s<'a>(p: &'a Value, k: &str) -> &'a str {
|
||||
@@ -58,7 +60,32 @@ pub fn describe(b: &Books, line: &JournalLine) -> Option<Event> {
|
||||
let id = p.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let entry_id = p.get("entry_id").and_then(|v| v.as_u64());
|
||||
let att = p.get("attachment_id").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let ev = |icon, text: String, route: Option<Route>| Some(Event { icon, text, route });
|
||||
let ev = |icon, text: String, route: Option<Route>| {
|
||||
Some(Event {
|
||||
icon,
|
||||
text,
|
||||
route,
|
||||
also: None,
|
||||
})
|
||||
};
|
||||
let asset_id = p.get("asset_id").and_then(|v| v.as_u64());
|
||||
let asset = |id: Option<u64>| {
|
||||
id.map(|a| {
|
||||
b.ledger
|
||||
.get_asset(a)
|
||||
.map(|x| x.description.clone())
|
||||
.unwrap_or_else(|| format!("asset {a}"))
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let with_asset = |icon, text: String| {
|
||||
Some(Event {
|
||||
icon,
|
||||
text,
|
||||
route: entry_id.map(Route::Entry),
|
||||
also: asset_id.map(Route::Asset),
|
||||
})
|
||||
};
|
||||
match line.line_type.as_str() {
|
||||
"entry.created" | "entry.line_added" | "entry.line_class_set" => None,
|
||||
"store.created" => ev(icon::BOOK_OPEN, "Books created".into(), None),
|
||||
@@ -223,17 +250,45 @@ pub fn describe(b: &Books, line: &JournalLine) -> Option<Event> {
|
||||
"asset.registered" => ev(
|
||||
icon::PACKAGE,
|
||||
format!("Registered asset {}", s(p, "description")),
|
||||
Some(Route::Company),
|
||||
Some(Route::Asset(id)),
|
||||
),
|
||||
"asset.depreciation_posted" => ev(
|
||||
"asset.tagged" => {
|
||||
let tag = s(p, "tag");
|
||||
let text = match p.get("previous_tag").and_then(|v| v.as_str()) {
|
||||
Some(old) => format!("Retagged {} from {old} to {tag}", asset(asset_id)),
|
||||
None => format!("Tagged {} {tag}", asset(asset_id)),
|
||||
};
|
||||
ev(icon::TAG, text, asset_id.map(Route::Asset))
|
||||
}
|
||||
"asset.serial_set" => {
|
||||
let text = match p.get("serial").and_then(|v| v.as_str()) {
|
||||
Some(serial) => format!("Serial number of {} set to {serial}", asset(asset_id)),
|
||||
None => format!("Serial number of {} cleared", asset(asset_id)),
|
||||
};
|
||||
ev(icon::BARCODE, text, asset_id.map(Route::Asset))
|
||||
}
|
||||
"asset.depreciation_posted" => with_asset(
|
||||
icon::TREND_DOWN,
|
||||
"Depreciation posted".into(),
|
||||
entry_id.map(Route::Entry),
|
||||
format!(
|
||||
"Depreciation posted: {} {} ({})",
|
||||
asset(asset_id),
|
||||
s(p, "period"),
|
||||
amount(p)
|
||||
),
|
||||
),
|
||||
"asset.disposed" => ev(
|
||||
"asset.disposed" => with_asset(
|
||||
icon::TRASH,
|
||||
"Asset disposed".into(),
|
||||
entry_id.map(Route::Entry),
|
||||
format!(
|
||||
"Disposed {} on {} for {}",
|
||||
asset(asset_id),
|
||||
s(p, "date"),
|
||||
p.get("proceeds")
|
||||
.and_then(|v| v.get("amount"))
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(|a| a.parse().ok())
|
||||
.map(fmt::dollars)
|
||||
.unwrap_or_default()
|
||||
),
|
||||
),
|
||||
"schedule.registered" => ev(
|
||||
icon::CALENDAR,
|
||||
@@ -310,6 +365,7 @@ pub fn describe_any(b: &Books, line: &JournalLine) -> Event {
|
||||
icon: icon::PENCIL_SIMPLE,
|
||||
text: format!("Drafted #{id} {}", s(p, "description")),
|
||||
route: Some(Route::Entry(id)),
|
||||
also: None,
|
||||
},
|
||||
"entry.line_added" => {
|
||||
let amount = p
|
||||
@@ -332,6 +388,7 @@ pub fn describe_any(b: &Books, line: &JournalLine) -> Event {
|
||||
),
|
||||
),
|
||||
route: Some(Route::Entry(id)),
|
||||
also: None,
|
||||
}
|
||||
}
|
||||
"entry.line_class_set" => {
|
||||
@@ -350,12 +407,14 @@ pub fn describe_any(b: &Books, line: &JournalLine) -> Event {
|
||||
.map_or(0, |i| i + 1)
|
||||
),
|
||||
route: Some(Route::Entry(id)),
|
||||
also: None,
|
||||
}
|
||||
}
|
||||
t => Event {
|
||||
icon: icon::DOT,
|
||||
text: t.to_string(),
|
||||
route: None,
|
||||
also: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -510,7 +569,7 @@ fn detail(ui: &mut Ui, b: &Books, line: &JournalLine, shell: &mut Shell<'_>) {
|
||||
fact(ui, "Previous", &line.prev);
|
||||
let own = ledger_store::journal::sha256_hex(line.to_canonical().as_bytes());
|
||||
fact(ui, "This hash", &own);
|
||||
if let Some(r) = &ev.route {
|
||||
for r in ev.route.iter().chain(&ev.also) {
|
||||
ui.add_space(6.0);
|
||||
if ui
|
||||
.button(format!(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! One module per screen.
|
||||
|
||||
pub mod accounts;
|
||||
pub mod assets;
|
||||
pub mod cash;
|
||||
pub mod company;
|
||||
pub mod documents;
|
||||
@@ -52,6 +53,8 @@ pub fn show(ui: &mut Ui, b: &Books, route: &Route, shell: &mut Shell<'_>) {
|
||||
Route::Reports(kind) => reports::show(ui, b, *kind, shell),
|
||||
Route::Accounts => accounts::show_chart(ui, b, shell),
|
||||
Route::Account(id) => accounts::show_account(ui, b, *id, shell),
|
||||
Route::Assets => assets::show_register(ui, b, shell),
|
||||
Route::Asset(id) => assets::show_asset(ui, b, *id, shell),
|
||||
Route::Documents => documents::show(ui, b, None, shell),
|
||||
Route::Document(id) => documents::show(ui, b, Some(*id), shell),
|
||||
Route::Company => company::show(ui, b, shell),
|
||||
|
||||
@@ -943,6 +943,119 @@ fn aging(rows: Vec<ledger_core::AgingRow>, as_of: NaiveDate) -> Table {
|
||||
t
|
||||
}
|
||||
|
||||
/// The fixed asset register on `as_of`: ledger-core's
|
||||
/// `fixed_asset_register`, laid out, with its reconciliation to the
|
||||
/// general ledger and what that says (the Assets page's notices).
|
||||
fn asset_register(b: &Books, as_of: NaiveDate) -> Table {
|
||||
let r = b.asset_register(as_of);
|
||||
let mut t = Table::new(vec![
|
||||
"Cost".into(),
|
||||
"Accumulated".into(),
|
||||
"Book value".into(),
|
||||
]);
|
||||
if r.rows.is_empty() {
|
||||
t.note(format!(
|
||||
"No fixed asset was in service by {}.",
|
||||
fmt::date(as_of)
|
||||
));
|
||||
return t;
|
||||
}
|
||||
t.section("Assets");
|
||||
for x in &r.rows {
|
||||
let label = match &x.tag {
|
||||
Some(tag) => format!("{tag} · {}", x.description),
|
||||
None => format!("{} (no tag)", x.description),
|
||||
};
|
||||
let mut detail = Vec::new();
|
||||
if let Some(s) = &x.serial {
|
||||
detail.push(format!("serial {s}"));
|
||||
}
|
||||
detail.push(format!("in service {}", fmt::date(x.in_service)));
|
||||
detail.push(fmt::count(x.useful_life_months as usize, "month", "months"));
|
||||
if !x.salvage.is_zero() {
|
||||
detail.push(format!("salvage {}", fmt::dollars(x.salvage)));
|
||||
}
|
||||
let cells = match x.disposed {
|
||||
Some(_) => {
|
||||
detail.push(format!(
|
||||
"{}; cost {}",
|
||||
super::assets::status_text(x.disposed),
|
||||
fmt::dollars(x.cost)
|
||||
));
|
||||
vec![Cell::none(), Cell::none(), Cell::none()]
|
||||
}
|
||||
None => vec![
|
||||
Cell::of(x.cost),
|
||||
Cell::of(x.accumulated),
|
||||
Cell::of(x.book_value),
|
||||
],
|
||||
};
|
||||
t.rows.push(Row {
|
||||
kind: Kind::Line,
|
||||
label,
|
||||
detail: detail.join(" · "),
|
||||
cells,
|
||||
});
|
||||
}
|
||||
t.row(
|
||||
Kind::Grand,
|
||||
"Total held",
|
||||
vec![
|
||||
Cell::of(r.total_cost),
|
||||
Cell::of(r.total_accumulated),
|
||||
Cell::of(r.total_book_value),
|
||||
],
|
||||
);
|
||||
t.section("Reconciliation to the books");
|
||||
let start = b.kpis.first_entry.unwrap_or(as_of).min(as_of);
|
||||
let held: Vec<_> = r
|
||||
.rows
|
||||
.iter()
|
||||
.filter_map(|x| b.ledger.get_asset(x.asset_id))
|
||||
.collect();
|
||||
// One account behind a figure drills down to it.
|
||||
let only = |ids: Vec<AccountId>| -> Option<Drill> {
|
||||
let mut ids = ids;
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
(ids.len() == 1).then(|| Drill {
|
||||
account: ids[0],
|
||||
start,
|
||||
end: as_of,
|
||||
})
|
||||
};
|
||||
let cost_drill = only(held.iter().map(|a| a.cost_account).collect());
|
||||
let accum_drill = only(held.iter().map(|a| a.accum_depr_account).collect());
|
||||
t.row(
|
||||
Kind::Line,
|
||||
"In the books",
|
||||
vec![
|
||||
Cell {
|
||||
value: Some(r.ledger_cost),
|
||||
drill: cost_drill,
|
||||
},
|
||||
Cell {
|
||||
value: Some(r.ledger_accumulated),
|
||||
drill: accum_drill,
|
||||
},
|
||||
Cell::of(r.ledger_cost - r.ledger_accumulated),
|
||||
],
|
||||
);
|
||||
t.row(
|
||||
Kind::Subtotal,
|
||||
"Register less books",
|
||||
vec![
|
||||
Cell::of(-r.unregistered_cost()),
|
||||
Cell::of(r.unposted_depreciation()),
|
||||
Cell::of(-r.unregistered_cost() - r.unposted_depreciation()),
|
||||
],
|
||||
);
|
||||
for n in super::assets::notices(b, &r) {
|
||||
t.note(n.text);
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The page.
|
||||
|
||||
@@ -959,7 +1072,11 @@ const GROUPS: [(&str, &[ReportKind]); 3] = [
|
||||
),
|
||||
(
|
||||
"Ledgers",
|
||||
&[ReportKind::TrialBalance, ReportKind::GeneralLedger],
|
||||
&[
|
||||
ReportKind::TrialBalance,
|
||||
ReportKind::GeneralLedger,
|
||||
ReportKind::FixedAssetRegister,
|
||||
],
|
||||
),
|
||||
(
|
||||
"Tax and aging",
|
||||
@@ -1042,7 +1159,10 @@ fn report(ui: &mut Ui, b: &Books, kind: ReportKind, shell: &mut Shell<'_>, picke
|
||||
let p = pal(ui.ctx());
|
||||
let point_in_time = matches!(
|
||||
kind,
|
||||
ReportKind::TrialBalance | ReportKind::ArAging | ReportKind::ApAging
|
||||
ReportKind::TrialBalance
|
||||
| ReportKind::ArAging
|
||||
| ReportKind::ApAging
|
||||
| ReportKind::FixedAssetRegister
|
||||
) || (kind == ReportKind::BalanceSheet
|
||||
&& shell.state.reports.columns == Columns::Total);
|
||||
let splittable = matches!(
|
||||
@@ -1231,6 +1351,7 @@ fn report(ui: &mut Ui, b: &Books, kind: ReportKind, shell: &mut Shell<'_>, picke
|
||||
Some(t)
|
||||
}
|
||||
ReportKind::TrialBalance => Some(trial_balance(b, e)),
|
||||
ReportKind::FixedAssetRegister => Some(asset_register(b, e)),
|
||||
ReportKind::MembersEquity => Some(owners_equity(b, s, e)),
|
||||
ReportKind::TaxSummary => {
|
||||
let mut t = tax(b, s, e);
|
||||
@@ -1922,6 +2043,7 @@ mod tests {
|
||||
tables.push(("equity", owners_equity(&b, s, e)));
|
||||
tables.push(("tax", tax(&b, s, e)));
|
||||
tables.push(("ar", aging(b.ledger.ar_aging(e), e)));
|
||||
tables.push(("assets", asset_register(&b, e)));
|
||||
tables.push(("gl", gl_table(&general_ledger(&b.ledger, s, e).unwrap())));
|
||||
let keep = std::env::var_os("PDF_DIR").map(std::path::PathBuf::from);
|
||||
for (name, t) in tables {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Ctrl+K: jump to anything. Pages, reports, accounts, entries (by text,
|
||||
//! amount, or #id), vendors, and documents, ranked by a simple fuzzy match.
|
||||
//! amount, or #id), fixed assets (by tag, serial, or description), vendors,
|
||||
//! and documents, ranked by a simple fuzzy match.
|
||||
|
||||
use crate::books::Books;
|
||||
use crate::fmt;
|
||||
@@ -16,12 +17,13 @@ pub struct Palette {
|
||||
focus: bool,
|
||||
}
|
||||
|
||||
struct Item {
|
||||
icon: &'static str,
|
||||
title: String,
|
||||
detail: String,
|
||||
route: Route,
|
||||
score: i32,
|
||||
/// One search result.
|
||||
pub struct Item {
|
||||
pub icon: &'static str,
|
||||
pub title: String,
|
||||
pub detail: String,
|
||||
pub route: Route,
|
||||
pub score: i32,
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
@@ -75,7 +77,7 @@ impl Palette {
|
||||
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, vendors, documents, reports…")
|
||||
.hint_text("Search entries, accounts, assets, vendors, documents, reports…")
|
||||
.font(theme::regular(16.0))
|
||||
.frame(egui::Frame::NONE)
|
||||
.desired_width(f32::INFINITY);
|
||||
@@ -211,7 +213,19 @@ pub fn fuzzy(hay: &str, query: &str) -> Option<i32> {
|
||||
best.into_iter().flatten().max()
|
||||
}
|
||||
|
||||
fn search(b: &Books, query: &str) -> Vec<Item> {
|
||||
/// 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).
|
||||
/// ```
|
||||
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| {
|
||||
@@ -281,6 +295,40 @@ fn search(b: &Books, query: &str) -> Vec<Item> {
|
||||
});
|
||||
}
|
||||
}
|
||||
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 v in b.ledger.list_vendors() {
|
||||
if let Some(score) = fuzzy(&v.name, q) {
|
||||
out.push(Item {
|
||||
@@ -329,6 +377,7 @@ pub fn describe(b: &Books, r: &Route) -> String {
|
||||
.find(|a| a.id == *id)
|
||||
.map(|a| a.file_name.clone())
|
||||
.unwrap_or_default(),
|
||||
Route::Asset(id) => b.asset_label(*id),
|
||||
Route::JournalEvent(seq) => format!("Event {seq}"),
|
||||
_ => String::new(),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,614 @@
|
||||
//! Fixed assets in the viewer: the register and each asset's schedule are
|
||||
//! ledger-core's numbers exactly; what's posted comes from the journal;
|
||||
//! search, books.show, the journal, and "Needs attention" know assets.
|
||||
|
||||
use chrono::{Datelike, Days, Months, NaiveDate};
|
||||
use egui_kittest::Harness;
|
||||
use ledger_core::{
|
||||
AccountType, AssetId, Currency, EntryId, Money, NewAsset, Side, depreciation_schedule,
|
||||
fixed_asset_register,
|
||||
};
|
||||
use ledger_gui::books::Books;
|
||||
use ledger_gui::nav::{ReportKind, Route};
|
||||
use ledger_gui::pages::assets::{MonthStatus, notices, schedule};
|
||||
use ledger_gui::pages::journal::describe;
|
||||
use ledger_gui::{App, Source, attention, data, fmt, palette};
|
||||
use ledger_store::Store;
|
||||
use ledger_store::viewer::ViewerTarget;
|
||||
use proptest::prelude::*;
|
||||
use rust_decimal::Decimal;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static DIRS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> TempDir {
|
||||
let n = DIRS.fetch_add(1, Ordering::Relaxed);
|
||||
let d = std::env::temp_dir().join(format!(
|
||||
"ledger-gui-assets-{tag}-{}-{n}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
TempDir(d)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn d(y: i32, m: u32, day: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(y, m, day).unwrap()
|
||||
}
|
||||
|
||||
fn usd(cents: i64) -> Money {
|
||||
Money::new(Decimal::new(cents, 2), Currency::USD)
|
||||
}
|
||||
|
||||
fn load(dir: &Path, today: NaiveDate) -> Books {
|
||||
data::load_once(&Source {
|
||||
data_dir: dir.join("books-data"),
|
||||
books_toml: None,
|
||||
today: Some(today),
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
_dir: TempDir,
|
||||
books: Books,
|
||||
/// The store's own ledger (the oracle's input), reopened from disk.
|
||||
oracle: ledger_core::Ledger,
|
||||
laptop: AssetId,
|
||||
monitor: AssetId,
|
||||
old: AssetId,
|
||||
laptop_purchase: EntryId,
|
||||
}
|
||||
|
||||
const TODAY: (i32, u32, u32) = (2026, 10, 15);
|
||||
|
||||
fn today() -> NaiveDate {
|
||||
d(TODAY.0, TODAY.1, TODAY.2)
|
||||
}
|
||||
|
||||
/// A laptop (tagged, serial, depreciation through July), a monitor (no
|
||||
/// tag, through August), and an old laptop retagged, its serial cleared,
|
||||
/// and sold in June.
|
||||
fn fixture(tag: &str) -> Fixture {
|
||||
let dir = TempDir::new(tag);
|
||||
let data = dir.0.join("books-data");
|
||||
let mut s = Store::create(&data, Currency::USD).unwrap();
|
||||
let cash = s
|
||||
.add_account("1000", "Checking", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let equip = s
|
||||
.add_account("1500", "Equipment", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let accum = s
|
||||
.add_account(
|
||||
"1510",
|
||||
"Accumulated Depreciation",
|
||||
AccountType::Asset,
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let capital = s
|
||||
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||
.unwrap();
|
||||
let dep = s
|
||||
.add_account("6500", "Depreciation", AccountType::Expense, None, false)
|
||||
.unwrap();
|
||||
let gain = s
|
||||
.add_account("7000", "Gain on sale", AccountType::Revenue, None, false)
|
||||
.unwrap();
|
||||
let buy = |s: &mut Store, date, what: &str, cents| {
|
||||
let e = s.create_entry(date, what).unwrap();
|
||||
s.add_line(e, equip, Side::Debit, usd(cents)).unwrap();
|
||||
s.add_line(e, cash, Side::Credit, usd(cents)).unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
e
|
||||
};
|
||||
let e = s.create_entry(d(2026, 1, 1), "Owner contribution").unwrap();
|
||||
s.add_line(e, cash, Side::Debit, usd(1_000_000)).unwrap();
|
||||
s.add_line(e, capital, Side::Credit, usd(1_000_000))
|
||||
.unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
let register = |s: &mut Store, what: &str, date, cents, salvage, months| {
|
||||
s.register_asset(NewAsset {
|
||||
description: what.into(),
|
||||
purchase_date: date,
|
||||
cost: usd(cents),
|
||||
salvage_value: usd(salvage),
|
||||
useful_life_months: months,
|
||||
cost_account: equip,
|
||||
accum_depr_account: accum,
|
||||
expense_account: dep,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let laptop_purchase = buy(&mut s, d(2026, 1, 10), "Laptop", 300_000);
|
||||
let laptop = register(&mut s, "Laptop", d(2026, 1, 10), 300_000, 0, 36);
|
||||
buy(&mut s, d(2026, 2, 1), "Monitor", 120_000);
|
||||
let monitor = register(&mut s, "Monitor", d(2026, 2, 1), 120_000, 0, 12);
|
||||
buy(&mut s, d(2026, 1, 1), "Old laptop", 60_000);
|
||||
let old = register(&mut s, "Old laptop", d(2026, 1, 1), 60_000, 10_000, 24);
|
||||
s.set_asset_tag(laptop, "FL-0001").unwrap();
|
||||
s.set_asset_serial(laptop, Some("SN-123")).unwrap();
|
||||
s.set_asset_tag(old, "OLD-1").unwrap();
|
||||
s.set_asset_tag(old, "FL-0009").unwrap();
|
||||
s.set_asset_serial(old, Some("X1")).unwrap();
|
||||
s.set_asset_serial(old, None).unwrap();
|
||||
for m in 1..=7 {
|
||||
s.run_depreciation(laptop, &format!("2026-{m:02}")).unwrap();
|
||||
}
|
||||
for m in 2..=8 {
|
||||
s.run_depreciation(monitor, &format!("2026-{m:02}"))
|
||||
.unwrap();
|
||||
}
|
||||
for m in 1..=3 {
|
||||
s.run_depreciation(old, &format!("2026-{m:02}")).unwrap();
|
||||
}
|
||||
s.dispose_asset(old, d(2026, 6, 30), usd(30_000), cash, gain)
|
||||
.unwrap();
|
||||
drop(s);
|
||||
let oracle = Store::open(&data).unwrap().ledger().clone();
|
||||
Fixture {
|
||||
books: load(&dir.0, today()),
|
||||
_dir: dir,
|
||||
oracle,
|
||||
laptop,
|
||||
monitor,
|
||||
old,
|
||||
laptop_purchase,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_register_is_ledger_cores_register() {
|
||||
let f = fixture("register");
|
||||
let b = &f.books;
|
||||
for as_of in [
|
||||
d(2025, 12, 31),
|
||||
d(2026, 1, 10),
|
||||
d(2026, 3, 31),
|
||||
d(2026, 6, 29),
|
||||
d(2026, 6, 30),
|
||||
d(2026, 7, 31),
|
||||
d(2026, 9, 30),
|
||||
today(),
|
||||
d(2030, 1, 1),
|
||||
] {
|
||||
let mine = b.asset_register(as_of);
|
||||
let oracle = fixed_asset_register(&f.oracle, as_of);
|
||||
assert_eq!(mine, oracle, "register on {as_of}");
|
||||
}
|
||||
let r = b.asset_register(today());
|
||||
assert_eq!(r.rows.len(), 3);
|
||||
let old = r.rows.iter().find(|x| x.asset_id == f.old).unwrap();
|
||||
assert_eq!(
|
||||
old.disposed,
|
||||
Some((d(2026, 6, 30), Decimal::new(30_000, 2)))
|
||||
);
|
||||
assert_eq!(
|
||||
ledger_gui::pages::assets::status_text(old.disposed),
|
||||
"Disposed Jun 30, 2026 for $300.00"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depreciation_due_is_the_register_through_the_last_finished_month() {
|
||||
let f = fixture("due");
|
||||
let b = &f.books;
|
||||
let due = b.depreciation_due(today());
|
||||
assert_eq!(due.through, d(2026, 9, 30));
|
||||
assert_eq!(
|
||||
due.amount,
|
||||
fixed_asset_register(&f.oracle, d(2026, 9, 30)).unposted_depreciation()
|
||||
);
|
||||
assert_eq!(due.periods, vec!["2026-08", "2026-09"]);
|
||||
// Independently: the laptop's August and September, the monitor's
|
||||
// September, straight from the schedules.
|
||||
let sched = |id| depreciation_schedule(f.oracle.get_asset(id).unwrap(), d(2026, 9, 30));
|
||||
let month = |id, p: &str| {
|
||||
sched(id)
|
||||
.into_iter()
|
||||
.find(|l| l.period == p)
|
||||
.unwrap()
|
||||
.amount
|
||||
};
|
||||
assert_eq!(
|
||||
due.amount,
|
||||
month(f.laptop, "2026-08") + month(f.laptop, "2026-09") + month(f.monitor, "2026-09")
|
||||
);
|
||||
// A month's last day counts that month as finished.
|
||||
assert_eq!(b.depreciation_due(d(2026, 7, 31)).through, d(2026, 7, 31));
|
||||
assert_eq!(
|
||||
b.depreciation_due(d(2026, 7, 31)).periods,
|
||||
Vec::<String>::new()
|
||||
);
|
||||
|
||||
// The notices name the due amount exactly, and the month under way.
|
||||
let r = b.asset_register(today());
|
||||
let n = notices(b, &r);
|
||||
assert!(n[0].problem);
|
||||
assert!(
|
||||
n[0].text.contains(&format!(
|
||||
"Depreciation not yet posted through Sep 30, 2026: {}",
|
||||
fmt::dollars(due.amount)
|
||||
)),
|
||||
"{:?}",
|
||||
n[0].text
|
||||
);
|
||||
assert!(n[0].text.contains("ask the bookkeeper to run depreciation"));
|
||||
let accruing = r.unposted_depreciation() - due.amount;
|
||||
assert!(accruing > Decimal::ZERO);
|
||||
assert!(n[1].text.contains(&fmt::dollars(accruing)));
|
||||
assert!(!n[1].problem);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_assets_schedule_and_trail() {
|
||||
let f = fixture("schedule");
|
||||
let b = &f.books;
|
||||
let lines = schedule(b, f.laptop);
|
||||
let asset = f.oracle.get_asset(f.laptop).unwrap();
|
||||
let oracle = depreciation_schedule(asset, NaiveDate::MAX);
|
||||
assert_eq!(
|
||||
oracle.len(),
|
||||
37,
|
||||
"36 months from Jan 10: 37 calendar months"
|
||||
);
|
||||
assert_eq!(
|
||||
lines.iter().map(|(l, _)| l.clone()).collect::<Vec<_>>(),
|
||||
oracle
|
||||
);
|
||||
let trail = b.asset_trail(f.laptop);
|
||||
for (l, st) in &lines {
|
||||
let want = match l.period.as_str() {
|
||||
p if p <= "2026-07" => MonthStatus::Posted(trail.depreciation[p].0),
|
||||
"2026-08" | "2026-09" => MonthStatus::Due,
|
||||
"2026-10" => MonthStatus::ThisMonth,
|
||||
_ => MonthStatus::Scheduled,
|
||||
};
|
||||
assert_eq!(*st, want, "{}", l.period);
|
||||
}
|
||||
// Posted amounts are the schedule's, and the purchase is found.
|
||||
for (period, (_, amount)) in &trail.depreciation {
|
||||
let l = oracle.iter().find(|l| &l.period == period).unwrap();
|
||||
assert_eq!(*amount, l.amount);
|
||||
}
|
||||
assert_eq!(trail.purchase_entry, Some(f.laptop_purchase));
|
||||
assert_eq!(b.entry_assets.get(&f.laptop_purchase), Some(&f.laptop));
|
||||
assert_eq!(trail.entries().len(), 1 + 7);
|
||||
// The sold laptop: its disposal entry, and a final depreciation.
|
||||
let old = b.asset_trail(f.old);
|
||||
let disposal = old.disposal_entry.expect("disposal entry");
|
||||
assert_eq!(b.entry(disposal).unwrap().origin, "Asset disposal");
|
||||
assert!(old.depreciation.contains_key("2026-06"));
|
||||
assert_eq!(b.entry_assets.get(&disposal), Some(&f.old));
|
||||
assert_eq!(b.asset_label(f.laptop), "FL-0001 Laptop");
|
||||
assert_eq!(b.asset_label(f.monitor), "Monitor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_finds_assets_by_tag_serial_and_description() {
|
||||
let f = fixture("search");
|
||||
let b = &f.books;
|
||||
for q in ["FL-0001", "fl-0001", " Fl-0001 "] {
|
||||
let items = palette::search(b, q);
|
||||
assert_eq!(items[0].route, Route::Asset(f.laptop), "{q}");
|
||||
assert_eq!(items[0].score, 2000);
|
||||
}
|
||||
let first_asset = |q: &str| {
|
||||
palette::search(b, q)
|
||||
.into_iter()
|
||||
.find(|i| matches!(i.route, Route::Asset(_)))
|
||||
.map(|i| i.route)
|
||||
};
|
||||
assert_eq!(first_asset("sn-123"), Some(Route::Asset(f.laptop)));
|
||||
assert_eq!(
|
||||
palette::search(b, "SN-123")[0].route,
|
||||
Route::Asset(f.laptop)
|
||||
);
|
||||
assert_eq!(first_asset("monitor"), Some(Route::Asset(f.monitor)));
|
||||
assert_eq!(first_asset("fl-0009"), Some(Route::Asset(f.old)));
|
||||
// Everything else still found as before.
|
||||
assert!(
|
||||
palette::search(b, "checking")
|
||||
.iter()
|
||||
.any(|i| matches!(i.route, Route::Account(_)))
|
||||
);
|
||||
assert!(
|
||||
palette::search(b, "")
|
||||
.iter()
|
||||
.any(|i| i.route == Route::Assets)
|
||||
);
|
||||
assert!(
|
||||
palette::search(b, "fixed asset register")
|
||||
.iter()
|
||||
.any(|i| i.route == Route::Reports(ReportKind::FixedAssetRegister))
|
||||
);
|
||||
assert_eq!(
|
||||
palette::describe(b, &Route::Asset(f.laptop)),
|
||||
"FL-0001 Laptop"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn journal_text_for_asset_events() {
|
||||
let f = fixture("journal");
|
||||
let b = &f.books;
|
||||
let texts: Vec<(String, Option<Route>, Option<Route>)> = b
|
||||
.journal
|
||||
.iter()
|
||||
.filter(|l| l.line_type.starts_with("asset."))
|
||||
.filter_map(|l| describe(b, l))
|
||||
.map(|e| (e.text, e.route, e.also))
|
||||
.collect();
|
||||
let has = |t: &str, route: Option<Route>| {
|
||||
assert!(
|
||||
texts.iter().any(|(x, r, _)| x == t && *r == route),
|
||||
"no {t:?} ({route:?}) in {texts:#?}"
|
||||
);
|
||||
};
|
||||
has("Registered asset Laptop", Some(Route::Asset(f.laptop)));
|
||||
has("Tagged Laptop FL-0001", Some(Route::Asset(f.laptop)));
|
||||
has(
|
||||
"Retagged Old laptop from OLD-1 to FL-0009",
|
||||
Some(Route::Asset(f.old)),
|
||||
);
|
||||
has(
|
||||
"Serial number of Laptop set to SN-123",
|
||||
Some(Route::Asset(f.laptop)),
|
||||
);
|
||||
has(
|
||||
"Serial number of Old laptop cleared",
|
||||
Some(Route::Asset(f.old)),
|
||||
);
|
||||
let disposal = b.asset_trail(f.old).disposal_entry;
|
||||
has(
|
||||
"Disposed Old laptop on 2026-06-30 for $300.00",
|
||||
disposal.map(Route::Entry),
|
||||
);
|
||||
let (jan, _) = b.asset_trail(f.laptop).depreciation["2026-01"];
|
||||
let dep = texts
|
||||
.iter()
|
||||
.find(|(x, _, _)| x.starts_with("Depreciation posted: Laptop 2026-01"))
|
||||
.expect("depreciation text");
|
||||
assert_eq!(dep.1, Some(Route::Entry(jan)));
|
||||
assert_eq!(dep.2, Some(Route::Asset(f.laptop)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attention_asks_for_depreciation_and_tags() {
|
||||
let f = fixture("attention");
|
||||
let b = &f.books;
|
||||
let items = attention::find(b);
|
||||
let due = b.depreciation_due(today());
|
||||
let dep = items
|
||||
.iter()
|
||||
.find(|a| a.title == "Depreciation not posted through Sep 30, 2026")
|
||||
.expect("depreciation item");
|
||||
assert_eq!(dep.target, Some(Route::Assets));
|
||||
assert!(dep.prompt.starts_with("In wanderbooks,"));
|
||||
assert!(
|
||||
dep.prompt
|
||||
.contains("books.run_depreciation for 2026-08, 2026-09")
|
||||
);
|
||||
assert!(dep.prompt.contains(&fmt::dollars(due.amount)));
|
||||
let tag = items
|
||||
.iter()
|
||||
.find(|a| a.title == "No tag: Monitor")
|
||||
.expect("tag item");
|
||||
assert_eq!(tag.target, Some(Route::Asset(f.monitor)));
|
||||
assert!(tag.prompt.contains("books.label_asset"));
|
||||
// Tagged, disposed, and agreeing assets ask for nothing.
|
||||
assert!(
|
||||
!items
|
||||
.iter()
|
||||
.any(|a| a.title.contains("Laptop") && a.title.starts_with("No tag"))
|
||||
);
|
||||
assert!(!items.iter().any(|a| a.title.contains("not in the")));
|
||||
for a in &items {
|
||||
assert!(a.prompt.contains("wanderbooks"), "{:?}", a.prompt);
|
||||
}
|
||||
|
||||
// Caught up and labeled: nothing about assets.
|
||||
let data = f._dir.0.join("books-data");
|
||||
let mut s = Store::open(&data).unwrap();
|
||||
s.run_depreciation(f.laptop, "2026-08").unwrap();
|
||||
s.run_depreciation(f.laptop, "2026-09").unwrap();
|
||||
s.run_depreciation(f.monitor, "2026-09").unwrap();
|
||||
s.set_asset_tag(f.monitor, "FL-0002").unwrap();
|
||||
drop(s);
|
||||
let b = load(&f._dir.0, today());
|
||||
let titles: Vec<String> = attention::find(&b).into_iter().map(|a| a.title).collect();
|
||||
assert!(
|
||||
!titles
|
||||
.iter()
|
||||
.any(|t| t.contains("Depreciation") || t.starts_with("No tag")),
|
||||
"{titles:?}"
|
||||
);
|
||||
assert_eq!(b.depreciation_due(today()).amount, Decimal::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregistered_equipment_is_flagged() {
|
||||
let f = fixture("unregistered");
|
||||
let data = f._dir.0.join("books-data");
|
||||
let mut s = Store::open(&data).unwrap();
|
||||
let equip = s.ledger().chart().find_by_code("1500").unwrap().id;
|
||||
let cash = s.ledger().chart().find_by_code("1000").unwrap().id;
|
||||
let e = s.create_entry(d(2026, 9, 2), "Printer").unwrap();
|
||||
s.add_line(e, equip, Side::Debit, usd(45_000)).unwrap();
|
||||
s.add_line(e, cash, Side::Credit, usd(45_000)).unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
drop(s);
|
||||
let b = load(&f._dir.0, today());
|
||||
let r = b.asset_register(today());
|
||||
assert_eq!(r.unregistered_cost(), Decimal::new(45_000, 2));
|
||||
assert!(
|
||||
notices(&b, &r)
|
||||
.iter()
|
||||
.any(|n| n.problem && n.text.starts_with("$450.00 in the asset cost accounts"))
|
||||
);
|
||||
assert!(
|
||||
attention::find(&b)
|
||||
.iter()
|
||||
.any(|a| a.title == "$450.00 of equipment not in the asset register")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn books_show_opens_assets() {
|
||||
let f = fixture("show");
|
||||
let laptop = f.laptop;
|
||||
let books = f.books;
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(1440.0, 920.0))
|
||||
.build_eframe(|cc| App::with_books(&cc.egui_ctx, books, false, Route::Overview));
|
||||
h.state_mut().show(ViewerTarget::Page {
|
||||
page: "assets".into(),
|
||||
});
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state_mut().route(), &Route::Assets);
|
||||
h.state_mut().show(ViewerTarget::Asset { asset_id: laptop });
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state_mut().route(), &Route::Asset(laptop));
|
||||
h.state_mut().show(ViewerTarget::Report {
|
||||
report: "fixed_asset_register".into(),
|
||||
start: None,
|
||||
end: Some("2026-06-30".into()),
|
||||
columns: None,
|
||||
compare: None,
|
||||
});
|
||||
h.run_steps(2);
|
||||
assert_eq!(
|
||||
h.state_mut().route(),
|
||||
&Route::Reports(ReportKind::FixedAssetRegister)
|
||||
);
|
||||
assert!(matches!(
|
||||
h.state_mut().state_mut().reports.range,
|
||||
ledger_gui::pages::reports::Range::Custom(_, e) if e == d(2026, 6, 30)
|
||||
));
|
||||
// An unknown asset is ignored, not a crash.
|
||||
h.state_mut().show(ViewerTarget::Asset { asset_id: 999 });
|
||||
h.run_steps(1);
|
||||
assert_eq!(
|
||||
h.state_mut().route(),
|
||||
&Route::Reports(ReportKind::FixedAssetRegister)
|
||||
);
|
||||
}
|
||||
|
||||
/// The asset pages render at every width without panicking, and with no
|
||||
/// assets at all.
|
||||
#[test]
|
||||
fn asset_pages_render() {
|
||||
let f = fixture("render");
|
||||
let routes = [
|
||||
Route::Assets,
|
||||
Route::Asset(f.laptop),
|
||||
Route::Asset(f.monitor),
|
||||
Route::Asset(f.old),
|
||||
Route::Asset(999),
|
||||
Route::Reports(ReportKind::FixedAssetRegister),
|
||||
];
|
||||
for width in [420.0, 900.0, 1440.0] {
|
||||
for route in &routes {
|
||||
let books = load(&f._dir.0, today());
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(width, 900.0))
|
||||
.build_eframe(|cc| App::with_books(&cc.egui_ctx, books, true, route.clone()));
|
||||
h.run_steps(3);
|
||||
}
|
||||
}
|
||||
let empty = TempDir::new("empty");
|
||||
drop(Store::create(&empty.0.join("books-data"), Currency::USD).unwrap());
|
||||
for route in [
|
||||
Route::Assets,
|
||||
Route::Reports(ReportKind::FixedAssetRegister),
|
||||
] {
|
||||
let books = load(&empty.0, today());
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(1280.0, 800.0))
|
||||
.build_eframe(|cc| App::with_books(&cc.egui_ctx, books, false, route.clone()));
|
||||
h.run_steps(3);
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(12))]
|
||||
|
||||
/// On random assets with depreciation run for random months, the
|
||||
/// register on any date is ledger-core's, and what's due is the
|
||||
/// register through the last finished month.
|
||||
#[test]
|
||||
fn register_and_due_match_the_oracle(
|
||||
assets in proptest::collection::vec(
|
||||
(0u64..400, 1i64..2_000_000, 0i64..50, 1u32..60, 0u32..30),
|
||||
1..5,
|
||||
),
|
||||
today_off in 0u64..900,
|
||||
probe in 0u64..1200,
|
||||
) {
|
||||
let dir = TempDir::new("prop");
|
||||
let data = dir.0.join("books-data");
|
||||
let mut s = Store::create(&data, Currency::USD).unwrap();
|
||||
let cash = s.add_account("1000", "Checking", AccountType::Asset, None, false).unwrap();
|
||||
let equip = s.add_account("1500", "Equipment", AccountType::Asset, None, false).unwrap();
|
||||
let accum = s.add_account("1510", "Accumulated", AccountType::Asset, None, false).unwrap();
|
||||
let dep = s.add_account("6500", "Depreciation", AccountType::Expense, None, false).unwrap();
|
||||
let base = d(2025, 1, 1);
|
||||
for (i, (off, cents, salvage_pct, months, run)) in assets.iter().enumerate() {
|
||||
let date = base + Days::new(*off);
|
||||
let e = s.create_entry(date, &format!("Buy {i}")).unwrap();
|
||||
s.add_line(e, equip, Side::Debit, usd(*cents)).unwrap();
|
||||
s.add_line(e, cash, Side::Credit, usd(*cents)).unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
let id = s.register_asset(NewAsset {
|
||||
description: format!("Asset {i}"),
|
||||
purchase_date: date,
|
||||
cost: usd(*cents),
|
||||
salvage_value: usd(cents * salvage_pct / 100),
|
||||
useful_life_months: *months,
|
||||
cost_account: equip,
|
||||
accum_depr_account: accum,
|
||||
expense_account: dep,
|
||||
}).unwrap();
|
||||
// Depreciation for the first `run` months of its life.
|
||||
for k in 0..*run {
|
||||
let m = date.with_day0(0).unwrap() + Months::new(k);
|
||||
let _ = s.run_depreciation(id, &m.format("%Y-%m").to_string());
|
||||
}
|
||||
}
|
||||
drop(s);
|
||||
let oracle = Store::open(&data).unwrap().ledger().clone();
|
||||
let today = base + Days::new(today_off);
|
||||
let b = load(&dir.0, today);
|
||||
let at = base + Days::new(probe);
|
||||
prop_assert_eq!(b.asset_register(at), fixed_asset_register(&oracle, at));
|
||||
let due = b.depreciation_due(today);
|
||||
prop_assert!(due.through <= today);
|
||||
prop_assert_eq!(due.through.succ_opt().unwrap().day0(), 0);
|
||||
prop_assert!(today - due.through < chrono::TimeDelta::days(32));
|
||||
prop_assert_eq!(
|
||||
due.amount,
|
||||
fixed_asset_register(&oracle, due.through).unposted_depreciation()
|
||||
);
|
||||
// Every period listed is unposted and in some schedule.
|
||||
for p in &due.periods {
|
||||
let found = b.ledger.registered_assets().any(|a| {
|
||||
depreciation_schedule(a, due.through).iter().any(|l| &l.period == p)
|
||||
&& !b.asset_trail(a.id).depreciation.contains_key(p)
|
||||
});
|
||||
prop_assert!(found, "{} listed but not due", p);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,12 @@ fn the_viewer_never_writes_into_the_books() {
|
||||
let cash = books.cash_accounts[0];
|
||||
let doc = books.attachments.last().map(|a| a.id).unwrap();
|
||||
let event = books.seq();
|
||||
let asset = books
|
||||
.ledger
|
||||
.registered_assets()
|
||||
.next()
|
||||
.map(|a| a.id)
|
||||
.unwrap();
|
||||
drop(books);
|
||||
|
||||
// Follow live for a moment.
|
||||
@@ -161,8 +167,13 @@ fn the_viewer_never_writes_into_the_books() {
|
||||
Route::Reports(ReportKind::TaxSummary),
|
||||
Route::Reports(ReportKind::Vendor1099),
|
||||
Route::Reports(ReportKind::ArAging),
|
||||
Route::Reports(ReportKind::ApAging),
|
||||
Route::Reports(ReportKind::MembersEquity),
|
||||
Route::Reports(ReportKind::FixedAssetRegister),
|
||||
Route::Accounts,
|
||||
Route::Account(cash),
|
||||
Route::Assets,
|
||||
Route::Asset(asset),
|
||||
Route::Document(doc),
|
||||
Route::JournalEvent(event),
|
||||
Route::Documents,
|
||||
|
||||
@@ -45,6 +45,12 @@ fn screenshots() {
|
||||
let first_cash = loaded.cash_accounts.first().copied().unwrap_or(1);
|
||||
let last_doc = loaded.attachments.last().map(|a| a.id).unwrap_or(1);
|
||||
let last_event = loaded.seq();
|
||||
let first_asset = loaded
|
||||
.ledger
|
||||
.registered_assets()
|
||||
.next()
|
||||
.map(|a| a.id)
|
||||
.unwrap_or(1);
|
||||
drop(loaded);
|
||||
let routes: Vec<(&str, Route)> = vec![
|
||||
("overview", Route::Overview),
|
||||
@@ -68,8 +74,14 @@ fn screenshots() {
|
||||
("tax", Route::Reports(ReportKind::TaxSummary)),
|
||||
("v1099", Route::Reports(ReportKind::Vendor1099)),
|
||||
("ar", Route::Reports(ReportKind::ArAging)),
|
||||
(
|
||||
"asset-register",
|
||||
Route::Reports(ReportKind::FixedAssetRegister),
|
||||
),
|
||||
("accounts", Route::Accounts),
|
||||
("account", Route::Account(first_cash)),
|
||||
("assets", Route::Assets),
|
||||
("asset", Route::Asset(first_asset)),
|
||||
("document", Route::Document(last_doc)),
|
||||
("event", Route::JournalEvent(last_event)),
|
||||
("documents", Route::Documents),
|
||||
|
||||
@@ -18,6 +18,7 @@ fn show_requests_navigate_the_viewer() {
|
||||
};
|
||||
let books = data::load_once(&source).unwrap();
|
||||
let rent = books.ledger.chart().find_by_code("6200").unwrap().id;
|
||||
let laptop = books.ledger.asset_by_tag("js-0001").unwrap().id;
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(1440.0, 920.0))
|
||||
.build_eframe(|cc| App::with_books(&cc.egui_ctx, books, true, Route::Overview));
|
||||
@@ -62,6 +63,44 @@ fn show_requests_navigate_the_viewer() {
|
||||
assert_eq!(h.state_mut().route(), &Route::Transactions);
|
||||
assert_eq!(h.state_mut().state_mut().transactions.query, "adobe");
|
||||
|
||||
// "Show me the asset register", "the laptop", "the register at June 30".
|
||||
h.state_mut().show(ViewerTarget::Page {
|
||||
page: "assets".into(),
|
||||
});
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state_mut().route(), &Route::Assets);
|
||||
h.state_mut().show(ViewerTarget::Asset { asset_id: laptop });
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state_mut().route(), &Route::Asset(laptop));
|
||||
h.state_mut().show(ViewerTarget::Report {
|
||||
report: "fixed_asset_register".into(),
|
||||
start: None,
|
||||
end: Some("2026-06-30".into()),
|
||||
columns: None,
|
||||
compare: None,
|
||||
});
|
||||
h.run_steps(2);
|
||||
assert_eq!(
|
||||
h.state_mut().route(),
|
||||
&Route::Reports(ReportKind::FixedAssetRegister)
|
||||
);
|
||||
assert!(matches!(
|
||||
h.state_mut().state_mut().reports.range,
|
||||
ledger_gui::pages::reports::Range::Custom(_, e)
|
||||
if e == chrono::NaiveDate::from_ymd_opt(2026, 6, 30).unwrap()
|
||||
));
|
||||
// An unknown asset is ignored.
|
||||
h.state_mut().show(ViewerTarget::Asset { asset_id: 999 });
|
||||
h.run_steps(1);
|
||||
assert_eq!(
|
||||
h.state_mut().route(),
|
||||
&Route::Reports(ReportKind::FixedAssetRegister)
|
||||
);
|
||||
h.state_mut().show(ViewerTarget::Search {
|
||||
query: "adobe".into(),
|
||||
});
|
||||
h.run_steps(2);
|
||||
|
||||
// Unknown accounts are ignored, not crashes.
|
||||
h.state_mut().show(ViewerTarget::Account {
|
||||
code: "9999".into(),
|
||||
|
||||
Reference in new issue
Block a user