Kaynağa Gözat

Show both sides of a transfer in the dashboard feed

The feed built its rows from the postings a transfer created and dropped
the consumed ones to a count no page printed, so a reader could not tell
a debit from a credit and the value that left an account was nowhere on
screen. A deposit creates one positive and one negative posting and
consumes nothing, which is most of what the acme ledger holds, and the
negative one was styled as change and dimmed. That dimmed line was the
only record of where the value came from.

Each transfer now renders as a journal entry: both sides, grouped by
asset, with a pair of totals per group. Lines are normalized by sign
rather than by which list they came from, so a created negative posting
reads as the debit it is. The two totals agree as a consequence of
per-asset conservation, which is what gives a deposit a debit side at
all. A change output and an offset position are now separate kinds, told
apart as the resolver tells them apart, and named in words instead of by
opacity.

Reading an entry and then looking at an account it names meant going
back to the account list and finding it by eye, because no account name
anywhere was a link. Every one is now, counterparties and payers
included, and the two table rows that navigated by onclick alone are
reachable by keyboard.

Recovering a consumed posting's owner and value needs a lookup, since an
envelope stores consumed ids alone, so Ledger::get_postings exposes the
store method the dashboard could otherwise only reach through
Ledger::store. One batched call covers a whole page of entries.
C 3 gün önce
ebeveyn
işleme
495fd59f9d

+ 14 - 0
CHANGELOG.md

@@ -23,6 +23,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 - `kuatia::prelude` exports `SqlStore` under the `sql` feature.
 - A `quickstart` example, which the top-level README's quick example is held to
   by a test.
+- `Ledger::get_postings(ids)` reads postings by id from the immutable record. A
+  committed envelope stores consumed ids alone, so without it a reader could
+  not recover the owner or the value of anything a transfer spent.
 
 ### Fixed
 
@@ -30,6 +33,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
   which the asset registry made unusable: an amount needs the handle the
   registry returns. `crates/kuatia/README.md` and `doc/crates.md` still showed
   the pre-registry builder verbs taking a separate asset and amount.
+- The dashboard's transfer feed showed only the postings a transfer created, so
+  a reader could not tell debits from credits and the value that left an
+  account was nowhere on screen. It now renders each transfer as a journal
+  entry with both sides and a pair of per-asset totals, normalizing by sign so
+  that a negative created posting reads as the debit it is. A deposit, which
+  consumes nothing, had no debit side at all before. The feed also told a
+  change output apart from an offset position by nothing, dimming both, though
+  the offset is where a deposit's value comes from. Every account named in the
+  dashboard is now a link to its own page; none of them were. The dashboard's
+  transfer JSON changed shape with the view: `legs` and `consumes` give way to
+  per-asset `debits`, `credits` and totals.
 
 ## [0.4.0] - 2026-12-02
 

+ 2 - 2
crates/kuatia-dashboard/README.md

@@ -51,8 +51,8 @@ format them using the decimals from `/api/assets`.
 | `GET /api/assets`       | Asset registry: id, code, symbol, decimals            |
 | `GET /api/overview`     | Account count, transfer count, total issued per asset |
 | `GET /api/accounts`     | All accounts with policy, flags, and balances         |
-| `GET /api/accounts/:id` | One account plus its postings and transfers           |
-| `GET /api/transfers`    | Recent transfers with their created postings (legs)   |
+| `GET /api/accounts/:id` | One account plus its postings and journal entries     |
+| `GET /api/transfers`    | Recent transfers as journal entries, both sides        |
 | `GET /api/events`       | The append-only ledger event log                      |
 
 ## Configuration

+ 2 - 2
crates/kuatia-dashboard/src/api.rs

@@ -15,7 +15,7 @@ use kuatia_core::{AccountId, Asset};
 use serde::Deserialize;
 
 use crate::data::{
-    AccountDetailDto, AccountDto, ApiError, AppState, EventDto, OverviewDto, TransferDto,
+    AccountDetailDto, AccountDto, ApiError, AppState, EntryDto, EventDto, OverviewDto,
 };
 
 /// Build the `/api` router.
@@ -58,7 +58,7 @@ struct TransfersParams {
 async fn transfers(
     State(state): State<AppState>,
     Query(params): Query<TransfersParams>,
-) -> Result<Json<Vec<TransferDto>>, ApiError> {
+) -> Result<Json<Vec<EntryDto>>, ApiError> {
     Ok(Json(crate::data::transfers(&state, params.limit).await?))
 }
 

+ 443 - 35
crates/kuatia-dashboard/src/data.rs

@@ -5,6 +5,7 @@
 //! asset's own scale rather than pairing it with a lookup of its own.
 
 use std::cmp::Reverse;
+use std::collections::HashMap;
 use std::fmt;
 use std::sync::Arc;
 
@@ -15,7 +16,9 @@ use axum::{
 };
 use kuatia::error::LedgerError;
 use kuatia::ledger::Ledger;
-use kuatia_core::{Account, AccountId, Amount, Asset, PostingId, PostingState};
+use kuatia_core::{
+    Account, AccountId, Amount, Asset, AssetId, NewPosting, Posting, PostingId, PostingState,
+};
 use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
 use kuatia_storage::store::{TransferQuery, TransferRecord};
 use serde::Serialize;
@@ -60,21 +63,77 @@ pub struct PostingDto {
     pub status: String,
 }
 
+/// Which column an entry line falls in once normalized by sign. A negative
+/// credit is a debit, which is what gives an entry that consumes nothing (a
+/// deposit) a debit side at all.
+#[derive(Debug, Serialize, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum EntrySide {
+    /// Value leaving an account.
+    Debit,
+    /// Value arriving at an account.
+    Credit,
+}
+
+/// Why a line exists, read off the envelope rather than guessed from the sign.
+#[derive(Debug, Serialize, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum EntryLineKind {
+    /// A consumed posting.
+    Spend,
+    /// A created posting with a payer: the destination side of a movement.
+    Receive,
+    /// A created posting with no payer and a positive value, returned to the
+    /// account that was debited. The record cannot tell this apart from the
+    /// output of a movement whose `from` and `to` are the same account.
+    Change,
+    /// A created posting with no payer and a negative value: the position an
+    /// overdraft-permitting account takes on to fund a shortfall, and the whole
+    /// debit side of a deposit.
+    Offset,
+}
+
+/// One posting's effect, as one line of a journal entry.
 #[derive(Serialize)]
-pub struct TransferLegDto {
+pub struct EntryLineDto {
+    pub side: EntrySide,
+    pub kind: EntryLineKind,
+    pub posting: String,
     pub owner: AccountId,
     pub label: Option<&'static str>,
+    /// Signed, exactly as the posting holds it. The HTML prints the magnitude
+    /// because `side` already carries the direction; a client reading this gets
+    /// the record's own value.
     pub amount: Amount,
     pub payer: Option<AccountId>,
     pub payer_label: Option<&'static str>,
 }
 
+/// One asset's half of an entry. Conservation is per asset, so a multi-asset
+/// transfer has no single pair of totals.
 #[derive(Serialize)]
-pub struct TransferDto {
+pub struct EntryAssetDto {
+    pub asset: AssetId,
+    pub code: String,
+    pub debits: Vec<EntryLineDto>,
+    pub credits: Vec<EntryLineDto>,
+    pub debit_total: Amount,
+    pub credit_total: Amount,
+    /// What the payer-funded credits moved, as against what change and offsets
+    /// shuffled. Derived from `payer`, which is descriptive provenance, so the
+    /// totals above stay the authoritative pair.
+    pub moved: Amount,
+    /// The two totals agree whenever the envelope conserved value, so a false
+    /// here is a ledger bug worth seeing rather than a state to design around.
+    pub balanced: bool,
+}
+
+/// One committed envelope as a journal entry.
+#[derive(Serialize)]
+pub struct EntryDto {
     pub id: String,
     pub created_at: i64,
-    pub consumes: usize,
-    pub legs: Vec<TransferLegDto>,
+    pub assets: Vec<EntryAssetDto>,
 }
 
 #[derive(Serialize)]
@@ -102,7 +161,7 @@ pub struct AccountDetailDto {
     /// together while never summed.
     pub subaccounts: Vec<AccountDto>,
     pub postings: Vec<PostingDto>,
-    pub transfers: Vec<TransferDto>,
+    pub entries: Vec<EntryDto>,
 }
 
 // ---------------------------------------------------------------------------
@@ -139,25 +198,162 @@ async fn account_dto(state: &AppState, account: &Account) -> Result<AccountDto,
     })
 }
 
-fn transfer_dto(record: &TransferRecord) -> TransferDto {
-    let legs = record
-        .envelope
-        .creates
-        .iter()
-        .map(|p| TransferLegDto {
-            owner: p.owner,
-            label: account_label(p.owner),
-            amount: p.amount.clone(),
-            payer: p.payer,
-            payer_label: p.payer.and_then(account_label),
-        })
-        .collect();
-    TransferDto {
+/// Classify a created posting from the shape the resolver gave it: a payer is
+/// set only for a movement output between two accounts, and change and offset
+/// differ by sign alone.
+fn created_kind(posting: &NewPosting) -> EntryLineKind {
+    match posting.payer {
+        Some(_) => EntryLineKind::Receive,
+        None if posting.amount.is_negative() => EntryLineKind::Offset,
+        None => EntryLineKind::Change,
+    }
+}
+
+/// The column a line belongs in. Consuming a positive posting and creating a
+/// negative one are both value leaving an account, so both are debits.
+///
+/// The two column totals are equal only as a consequence of per-asset
+/// conservation: with `P` and `N` the positive and negative sums of each side,
+/// `debits - credits` is `(P_consumed - N_consumed) - (P_created - N_created)`,
+/// which `sum(consumed) == sum(created)` makes zero.
+fn entry_side(consumed: bool, amount: &Amount) -> EntrySide {
+    match (consumed, amount.is_negative()) {
+        (true, false) | (false, true) => EntrySide::Debit,
+        (true, true) | (false, false) => EntrySide::Credit,
+    }
+}
+
+/// Sum the magnitudes of one column. The column carries the direction, so a
+/// negative line contributes its absolute value.
+fn magnitude_sum<'a>(
+    asset: &Arc<Asset>,
+    lines: impl Iterator<Item = &'a EntryLineDto>,
+) -> Result<Amount, ApiError> {
+    let mut total = Amount::zero(Arc::clone(asset));
+    for line in lines {
+        let magnitude = if line.amount.is_negative() {
+            line.amount.checked_neg().map_err(ApiError::from_display)?
+        } else {
+            line.amount.clone()
+        };
+        total = total
+            .checked_add(&magnitude)
+            .map_err(ApiError::from_display)?;
+    }
+    Ok(total)
+}
+
+/// Build one journal entry from a committed record and the consumed postings
+/// read back for it.
+///
+/// A consumed id absent from `consumed` is a 500 rather than a partially drawn
+/// entry: a posting row is written once and never deleted, so an envelope
+/// naming one the table does not hold is a corrupt database.
+fn entry_dto(
+    record: &TransferRecord,
+    consumed: &HashMap<PostingId, Posting>,
+) -> Result<EntryDto, ApiError> {
+    let envelope = &record.envelope;
+    let mut lines: Vec<EntryLineDto> =
+        Vec::with_capacity(envelope.consumes.len() + envelope.creates.len());
+
+    for id in &envelope.consumes {
+        let posting = consumed.get(id).ok_or_else(|| {
+            ApiError::internal(format!(
+                "consumed posting {} is missing from the record",
+                posting_id(id)
+            ))
+        })?;
+        lines.push(EntryLineDto {
+            side: entry_side(true, &posting.amount),
+            kind: EntryLineKind::Spend,
+            posting: posting_id(id),
+            owner: posting.owner,
+            label: account_label(posting.owner),
+            amount: posting.amount.clone(),
+            payer: None,
+            payer_label: None,
+        });
+    }
+
+    for (index, posting) in envelope.creates.iter().enumerate() {
+        // A created posting's id is its position in `creates` under the
+        // transfer id, which is how the commit path mints it.
+        let id = PostingId {
+            transfer: record.receipt.transfer_id,
+            index: index as u16,
+        };
+        lines.push(EntryLineDto {
+            side: entry_side(false, &posting.amount),
+            kind: created_kind(posting),
+            posting: posting_id(&id),
+            owner: posting.owner,
+            label: account_label(posting.owner),
+            amount: posting.amount.clone(),
+            payer: posting.payer,
+            payer_label: posting.payer.and_then(account_label),
+        });
+    }
+
+    // Group by asset, keeping each group's own handle: every amount carries its
+    // `Arc<Asset>`, so the registry is not needed here. A transfer spans a
+    // handful of assets at most, so a linear scan beats a map.
+    let mut groups: Vec<(Arc<Asset>, Vec<EntryLineDto>)> = Vec::new();
+    for line in lines {
+        match groups
+            .iter_mut()
+            .find(|(asset, _)| asset.id == line.amount.asset_id())
+        {
+            Some((_, group)) => group.push(line),
+            None => groups.push((Arc::clone(line.amount.asset()), vec![line])),
+        }
+    }
+    // Stable across the dashboard's poll, which reorders nothing else.
+    groups.sort_by(|(a, _), (b, _)| a.code.cmp(&b.code));
+
+    let mut out = Vec::with_capacity(groups.len());
+    for (asset, group) in groups {
+        let (debits, credits): (Vec<EntryLineDto>, Vec<EntryLineDto>) =
+            group.into_iter().partition(|l| l.side == EntrySide::Debit);
+        let debit_total = magnitude_sum(&asset, debits.iter())?;
+        let credit_total = magnitude_sum(&asset, credits.iter())?;
+        let moved = magnitude_sum(
+            &asset,
+            credits.iter().filter(|l| l.kind == EntryLineKind::Receive),
+        )?;
+        out.push(EntryAssetDto {
+            asset: asset.id,
+            code: asset.code.clone(),
+            balanced: debit_total == credit_total,
+            debits,
+            credits,
+            debit_total,
+            credit_total,
+            moved,
+        });
+    }
+
+    Ok(EntryDto {
         id: hex32(&record.receipt.transfer_id.0),
         created_at: record.created_at,
-        consumes: record.envelope.consumes.len(),
-        legs,
-    }
+        assets: out,
+    })
+}
+
+/// One batched lookup of every consumed posting across a page of entries, so a
+/// feed of N entries costs one query rather than N.
+async fn consumed_index(
+    state: &AppState,
+    records: &[TransferRecord],
+) -> Result<HashMap<PostingId, Posting>, ApiError> {
+    let mut ids: Vec<PostingId> = records
+        .iter()
+        .flat_map(|r| r.envelope.consumes.iter().copied())
+        .collect();
+    ids.sort();
+    ids.dedup();
+    let postings = state.ledger.get_postings(&ids).await?;
+    Ok(postings.into_iter().map(|p| (p.id, p)).collect())
 }
 
 fn event_dto(event: &LedgerEvent) -> EventDto {
@@ -260,13 +456,12 @@ pub async fn account_detail(state: &AppState, id: AccountId) -> Result<AccountDe
         .collect();
     postings.sort_by_key(|p| Reverse(p.amount.minor_units()));
 
-    let transfers = state
-        .ledger
-        .history(&id)
-        .await?
-        .iter()
-        .map(transfer_dto)
-        .collect();
+    let records = state.ledger.history(&id).await?;
+    let consumed = consumed_index(state, &records).await?;
+    let mut entries = Vec::with_capacity(records.len());
+    for record in &records {
+        entries.push(entry_dto(record, &consumed)?);
+    }
 
     // The base account and its non-closed subaccounts, so the detail page can
     // list every partition with its own (segregated) balances.
@@ -280,19 +475,23 @@ pub async fn account_detail(state: &AppState, id: AccountId) -> Result<AccountDe
         account: account_dto(state, &account).await?,
         subaccounts,
         postings,
-        transfers,
+        entries,
     })
 }
 
-/// Recent transfers, newest first.
-pub async fn transfers(state: &AppState, limit: Option<u32>) -> Result<Vec<TransferDto>, ApiError> {
+/// Recent transfers as journal entries, newest first.
+pub async fn transfers(state: &AppState, limit: Option<u32>) -> Result<Vec<EntryDto>, ApiError> {
     let query = TransferQuery {
         limit: limit.or(Some(100)),
         ..Default::default()
     };
     let page = state.ledger.query_transfers(&query).await?;
-    let mut out: Vec<TransferDto> = page.items.iter().map(transfer_dto).collect();
-    out.sort_by_key(|t| Reverse(t.created_at));
+    let consumed = consumed_index(state, &page.items).await?;
+    let mut out = Vec::with_capacity(page.items.len());
+    for record in &page.items {
+        out.push(entry_dto(record, &consumed)?);
+    }
+    out.sort_by_key(|e| Reverse(e.created_at));
     Ok(out)
 }
 
@@ -308,6 +507,7 @@ pub async fn events(state: &AppState, after: u64, limit: u32) -> Result<Vec<Even
 
 /// Any handler failure. Rendered as a JSON error body with a 500 (or 404 for a
 /// missing account). Shared by the JSON and HTML handlers.
+#[derive(Debug)]
 pub struct ApiError {
     status: StatusCode,
     message: String,
@@ -358,3 +558,211 @@ impl IntoResponse for ApiError {
             .into_response()
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use kuatia_core::{EnvelopeBuilder, Receipt, TransferId};
+
+    fn pyg() -> Arc<Asset> {
+        Arc::new(Asset::new(AssetId::new(1), "PYG", "\u{20b2}", 0))
+    }
+
+    fn usd() -> Arc<Asset> {
+        Arc::new(Asset::new(AssetId::new(2), "USD", "$", 2))
+    }
+
+    fn amount(value: i64, asset: &Arc<Asset>) -> Amount {
+        Amount::from((value, Arc::clone(asset)))
+    }
+
+    fn created(owner: i64, value: i64, asset: &Arc<Asset>, payer: Option<i64>) -> NewPosting {
+        NewPosting {
+            owner: AccountId::new(owner),
+            amount: amount(value, asset),
+            payer: payer.map(AccountId::new),
+        }
+    }
+
+    fn consumed(owner: i64, value: i64, asset: &Arc<Asset>, index: u16) -> Posting {
+        Posting::new(
+            PostingId {
+                transfer: TransferId([index as u8; 32]),
+                index,
+            },
+            AccountId::new(owner),
+            amount(value, asset),
+        )
+    }
+
+    fn record(consumes: Vec<PostingId>, creates: Vec<NewPosting>) -> TransferRecord {
+        TransferRecord {
+            envelope: EnvelopeBuilder::new()
+                .consumes(consumes)
+                .creates(creates)
+                .build(),
+            receipt: Receipt {
+                transfer_id: TransferId([9u8; 32]),
+            },
+            created_at: 0,
+        }
+    }
+
+    fn index(postings: Vec<Posting>) -> HashMap<PostingId, Posting> {
+        postings.into_iter().map(|p| (p.id, p)).collect()
+    }
+
+    #[test]
+    fn a_payer_funded_create_is_a_credit() {
+        let pyg = pyg();
+        let spent = consumed(1, 100, &pyg, 1);
+        let entry = entry_dto(
+            &record(vec![spent.id], vec![created(2, 100, &pyg, Some(1))]),
+            &index(vec![spent]),
+        )
+        .unwrap();
+
+        let asset = &entry.assets[0];
+        assert_eq!(asset.credits.len(), 1);
+        assert_eq!(asset.credits[0].kind, EntryLineKind::Receive);
+        assert_eq!(asset.credits[0].side, EntrySide::Credit);
+        assert_eq!(asset.debits[0].kind, EntryLineKind::Spend);
+    }
+
+    #[test]
+    fn a_positive_payerless_create_is_change() {
+        let pyg = pyg();
+        let spent = consumed(1, 100, &pyg, 1);
+        let entry = entry_dto(
+            &record(
+                vec![spent.id],
+                vec![created(2, 60, &pyg, Some(1)), created(1, 40, &pyg, None)],
+            ),
+            &index(vec![spent]),
+        )
+        .unwrap();
+
+        let change: Vec<_> = entry.assets[0]
+            .credits
+            .iter()
+            .filter(|l| l.kind == EntryLineKind::Change)
+            .collect();
+        assert_eq!(change.len(), 1);
+        assert_eq!(change[0].amount.minor_units(), 40);
+    }
+
+    #[test]
+    fn a_negative_payerless_create_is_an_offset_on_the_debit_side() {
+        // The old rendering called this change and dimmed it, which hid the
+        // only record of where a deposit's value came from.
+        let pyg = pyg();
+        let entry = entry_dto(
+            &record(
+                Vec::new(),
+                vec![created(2, 100, &pyg, Some(1)), created(1, -100, &pyg, None)],
+            ),
+            &HashMap::new(),
+        )
+        .unwrap();
+
+        let asset = &entry.assets[0];
+        assert_eq!(asset.debits.len(), 1);
+        assert_eq!(asset.debits[0].kind, EntryLineKind::Offset);
+        assert_eq!(asset.debits[0].side, EntrySide::Debit);
+        assert_eq!(asset.debits[0].owner, AccountId::new(1));
+        assert_eq!(asset.credits.len(), 1);
+        assert_eq!(asset.debit_total, asset.credit_total);
+        assert_eq!(asset.debit_total.minor_units(), 100);
+        assert!(asset.balanced);
+    }
+
+    #[test]
+    fn an_overdraft_splits_the_debit_side_between_a_spend_and_an_offset() {
+        let pyg = pyg();
+        let spent = consumed(1, 200, &pyg, 1);
+        let entry = entry_dto(
+            &record(
+                vec![spent.id],
+                vec![created(2, 250, &pyg, Some(1)), created(1, -50, &pyg, None)],
+            ),
+            &index(vec![spent]),
+        )
+        .unwrap();
+
+        let asset = &entry.assets[0];
+        let kinds: Vec<EntryLineKind> = asset.debits.iter().map(|l| l.kind).collect();
+        assert_eq!(kinds, vec![EntryLineKind::Spend, EntryLineKind::Offset]);
+        assert_eq!(asset.debit_total.minor_units(), 250);
+        assert_eq!(asset.credit_total.minor_units(), 250);
+        assert_eq!(asset.moved.minor_units(), 250);
+    }
+
+    #[test]
+    fn the_reported_entry_balances_above_what_it_moved() {
+        // The entry from the dashboard report: one consumed posting, three
+        // payments, change back to the payer, and two offsets.
+        let pyg = pyg();
+        let spent = consumed(4, 27_827_117, &pyg, 1);
+        let entry = entry_dto(
+            &record(
+                vec![spent.id],
+                vec![
+                    created(5, 225_455, &pyg, Some(1)),
+                    created(5, 22_545, &pyg, Some(6)),
+                    created(7, 181_153, &pyg, Some(4)),
+                    created(4, 27_645_964, &pyg, None),
+                    created(1, -225_455, &pyg, None),
+                    created(6, -22_545, &pyg, None),
+                ],
+            ),
+            &index(vec![spent]),
+        )
+        .unwrap();
+
+        let asset = &entry.assets[0];
+        assert_eq!(asset.debit_total.minor_units(), 28_075_117);
+        assert_eq!(asset.credit_total.minor_units(), 28_075_117);
+        assert_eq!(asset.moved.minor_units(), 429_153);
+        assert!(asset.balanced);
+    }
+
+    #[test]
+    fn each_asset_of_a_trade_balances_on_its_own() {
+        let pyg = pyg();
+        let usd = usd();
+        let pyg_spent = consumed(1, 100, &pyg, 1);
+        let usd_spent = consumed(2, 500, &usd, 2);
+        let entry = entry_dto(
+            &record(
+                vec![pyg_spent.id, usd_spent.id],
+                vec![
+                    created(2, 100, &pyg, Some(1)),
+                    created(1, 500, &usd, Some(2)),
+                ],
+            ),
+            &index(vec![pyg_spent, usd_spent]),
+        )
+        .unwrap();
+
+        assert_eq!(entry.assets.len(), 2);
+        // Ordered by code, so the rendering does not shuffle between polls.
+        assert_eq!(entry.assets[0].code, "PYG");
+        assert_eq!(entry.assets[1].code, "USD");
+        for asset in &entry.assets {
+            assert!(asset.balanced);
+        }
+    }
+
+    #[test]
+    fn a_consumed_posting_absent_from_the_record_is_an_error() {
+        let pyg = pyg();
+        let spent = consumed(1, 100, &pyg, 1);
+        assert!(
+            entry_dto(
+                &record(vec![spent.id], vec![created(2, 100, &pyg, Some(1))]),
+                &HashMap::new(),
+            )
+            .is_err()
+        );
+    }
+}

+ 127 - 42
crates/kuatia-dashboard/src/ui.rs

@@ -13,13 +13,15 @@ use axum::{
     response::{Html, IntoResponse, Response},
     routing::get,
 };
-use kuatia_core::{AccountId, Amount, Asset};
+use kuatia_core::{AccountId, Amount};
 use serde::Serialize;
 use tera::{Context, Tera};
 
 use crate::data::{
-    self, AccountDto, ApiError, AppState, EventDto, OverviewDto, PostingDto, TransferDto,
+    self, AccountDto, ApiError, AppState, EntryDto, EntryLineDto, EntryLineKind, EntrySide,
+    EventDto, OverviewDto, PostingDto,
 };
+use crate::seed::account_label;
 
 // ---------------------------------------------------------------------------
 // Tera setup — templates embedded via include_str!.
@@ -63,6 +65,10 @@ pub fn build_tera() -> Result<Tera, tera::Error> {
             include_str!("../templates/partials/account.html"),
         ),
         (
+            "partials/entry.html",
+            include_str!("../templates/partials/entry.html"),
+        ),
+        (
             "partials/transfers.html",
             include_str!("../templates/partials/transfers.html"),
         ),
@@ -134,29 +140,56 @@ struct PostingView {
     money: MoneyView,
 }
 
+/// An account as it appears in a row: a name to read, the full code to hover,
+/// and a link so a counterparty is navigable rather than dead text.
 #[derive(Serialize)]
-struct LegView {
-    to_name: String,
-    from_name: Option<String>,
-    is_change: bool,
+struct AcctRefView {
+    name: String,
+    title: String,
+    link: String,
+}
+
+#[derive(Serialize)]
+struct EntryLineView {
+    /// Also the CSS class on the note, so a kind is styled without the template
+    /// branching on it.
+    kind: &'static str,
+    note: &'static str,
+    posting_short: String,
+    account: AcctRefView,
+    /// The funding account of a payer-funded credit, so both accounts on a line
+    /// are navigable.
+    payer: Option<AcctRefView>,
     money: MoneyView,
+    /// Marks a line the viewed account owns. False on the ledger-wide feed.
+    mine: bool,
 }
 
 #[derive(Serialize)]
-struct TransferView {
+struct EntryAssetView {
+    code: String,
+    debits: Vec<EntryLineView>,
+    credits: Vec<EntryLineView>,
+    debit_total: MoneyView,
+    credit_total: MoneyView,
+    moved: MoneyView,
+    balanced: bool,
+}
+
+#[derive(Serialize)]
+struct EntryView {
     short_id: String,
     full_id: String,
     time: String,
-    consumes: usize,
-    legs: Vec<LegView>,
+    assets: Vec<EntryAssetView>,
 }
 
 #[derive(Serialize)]
 struct EventView {
     seq: u64,
     kind: &'static str,
-    /// Account's grouped IBAN-style code, if the event names an account.
-    account: Option<String>,
+    /// The account the event names, linked like any other account reference.
+    account: Option<AcctRefView>,
     transfer_short: Option<String>,
     time: String,
 }
@@ -199,6 +232,15 @@ fn fmt_amount(amount: &Amount) -> MoneyView {
     }
 }
 
+/// The magnitude alone. An entry cell's column already carries its direction,
+/// so a minus sign there would read as a second, contradicting one.
+fn fmt_magnitude(amount: &Amount) -> MoneyView {
+    MoneyView {
+        text: fmt_amount(amount).text.trim_start_matches('-').to_string(),
+        negative: false,
+    }
+}
+
 /// Insert commas every three digits from the right.
 fn group_thousands(digits: &str) -> String {
     let bytes = digits.as_bytes();
@@ -260,6 +302,27 @@ fn acct_link(id: AccountId) -> String {
     format!("/accounts/{id}")
 }
 
+/// First and last block of the grouped code, as `C2AU…S255`. Twenty opaque
+/// characters in a feed row read as noise.
+fn acct_short(id: AccountId) -> String {
+    let grouped = id.to_grouped();
+    let mut blocks = grouped.split(' ');
+    match (blocks.next(), grouped.rsplit(' ').next()) {
+        (Some(first), Some(last)) if first != last => format!("{first}…{last}"),
+        _ => grouped,
+    }
+}
+
+/// An account as a row reference: its label when it has one, else the short
+/// code, with the full code kept for the `title` attribute.
+fn acct_ref(id: AccountId, label: Option<&str>) -> AcctRefView {
+    AcctRefView {
+        name: label.map(String::from).unwrap_or_else(|| acct_short(id)),
+        title: acct_display(id),
+        link: acct_link(id),
+    }
+}
+
 fn account_view(dto: &AccountDto) -> AccountView {
     let display_id = acct_display(dto.id);
     let link = acct_link(dto.id);
@@ -292,33 +355,61 @@ fn account_view(dto: &AccountDto) -> AccountView {
     }
 }
 
-fn transfer_view(dto: &TransferDto, _assets: &[Asset]) -> TransferView {
-    TransferView {
+/// The word after the amount, naming why the line is on its side. A
+/// payer-funded credit says "from" and names the payer beside it.
+fn line_note(kind: EntryLineKind, side: EntrySide) -> &'static str {
+    match kind {
+        EntryLineKind::Receive => "from",
+        EntryLineKind::Change => "change",
+        EntryLineKind::Offset => "offset",
+        EntryLineKind::Spend if side == EntrySide::Credit => "offset retired",
+        EntryLineKind::Spend => "spent",
+    }
+}
+
+fn kind_class(kind: EntryLineKind) -> &'static str {
+    match kind {
+        EntryLineKind::Spend => "spend",
+        EntryLineKind::Receive => "receive",
+        EntryLineKind::Change => "change",
+        EntryLineKind::Offset => "offset",
+    }
+}
+
+fn line_view(dto: &EntryLineDto, viewpoint: Option<AccountId>) -> EntryLineView {
+    EntryLineView {
+        kind: kind_class(dto.kind),
+        note: line_note(dto.kind, dto.side),
+        posting_short: short_hex(&dto.posting),
+        account: acct_ref(dto.owner, dto.label),
+        payer: dto.payer.map(|p| acct_ref(p, dto.payer_label)),
+        money: fmt_magnitude(&dto.amount),
+        mine: viewpoint == Some(dto.owner),
+    }
+}
+
+fn entry_view(dto: &EntryDto, viewpoint: Option<AccountId>) -> EntryView {
+    EntryView {
         short_id: short_hex(&dto.id),
         full_id: dto.id.clone(),
         time: fmt_millis(dto.created_at),
-        consumes: dto.consumes,
-        legs: dto
-            .legs
+        assets: dto
+            .assets
             .iter()
-            .map(|leg| LegView {
-                to_name: leg
-                    .label
-                    .map(String::from)
-                    .unwrap_or_else(|| acct_display(leg.owner)),
-                from_name: leg.payer.map(|p| {
-                    leg.payer_label
-                        .map(String::from)
-                        .unwrap_or_else(|| acct_display(p))
-                }),
-                is_change: leg.payer.is_none(),
-                money: fmt_amount(&leg.amount),
+            .map(|a| EntryAssetView {
+                code: a.code.clone(),
+                debits: a.debits.iter().map(|l| line_view(l, viewpoint)).collect(),
+                credits: a.credits.iter().map(|l| line_view(l, viewpoint)).collect(),
+                debit_total: fmt_magnitude(&a.debit_total),
+                credit_total: fmt_magnitude(&a.credit_total),
+                moved: fmt_magnitude(&a.moved),
+                balanced: a.balanced,
             })
             .collect(),
     }
 }
 
-fn posting_view(dto: &PostingDto, _assets: &[Asset]) -> PostingView {
+fn posting_view(dto: &PostingDto) -> PostingView {
     PostingView {
         short_id: short_hex(&dto.id),
         status: dto.status.clone(),
@@ -330,7 +421,7 @@ fn event_view(dto: &EventDto) -> EventView {
     EventView {
         seq: dto.seq,
         kind: dto.kind,
-        account: dto.account.map(acct_display),
+        account: dto.account.map(|a| acct_ref(a, account_label(a))),
         transfer_short: dto.transfer.as_deref().map(short_hex),
         time: fmt_millis(dto.timestamp),
     }
@@ -381,16 +472,13 @@ async fn account_ctx(state: &AppState, id: AccountId) -> Result<Context, ApiErro
     );
     ctx.insert(
         "postings",
-        &dto.postings
-            .iter()
-            .map(|p| posting_view(p, &state.assets))
-            .collect::<Vec<_>>(),
+        &dto.postings.iter().map(posting_view).collect::<Vec<_>>(),
     );
     ctx.insert(
-        "transfers",
-        &dto.transfers
+        "entries",
+        &dto.entries
             .iter()
-            .map(|t| transfer_view(t, &state.assets))
+            .map(|e| entry_view(e, Some(id)))
             .collect::<Vec<_>>(),
     );
     Ok(ctx)
@@ -398,13 +486,10 @@ async fn account_ctx(state: &AppState, id: AccountId) -> Result<Context, ApiErro
 
 async fn transfers_ctx(state: &AppState) -> Result<Context, ApiError> {
     let dtos = data::transfers(state, None).await?;
-    let views: Vec<TransferView> = dtos
-        .iter()
-        .map(|t| transfer_view(t, &state.assets))
-        .collect();
+    let views: Vec<EntryView> = dtos.iter().map(|e| entry_view(e, None)).collect();
     let mut ctx = Context::new();
     ctx.insert("nav", "transfers");
-    ctx.insert("transfers", &views);
+    ctx.insert("entries", &views);
     Ok(ctx)
 }
 

+ 85 - 31
crates/kuatia-dashboard/static/dashboard.css

@@ -188,10 +188,6 @@ table.grid.small th {
   text-align: right;
 }
 
-table.grid tbody tr {
-  cursor: pointer;
-}
-
 table.grid tbody tr:hover {
   background: var(--panel-2);
 }
@@ -222,11 +218,8 @@ table.grid tbody tr:hover {
   white-space: nowrap;
 }
 
-.policy.NoOverdraft { color: #9fb4c6; }
-.policy.CappedOverdraft { color: #e0b25a; }
-.policy.UncappedOverdraft { color: #e8736b; }
-.policy.SystemAccount { color: #4c9be8; }
-.policy.ExternalAccount { color: #b98be0; }
+.policy.DebitMustNotExceedCredit { color: #9fb4c6; }
+.policy.Overdraft { color: #e0b25a; }
 
 .flag.frozen { background: #2b3f57; color: #7fb3ff; }
 .flag.closed { background: #4a2a2a; color: #e8736b; }
@@ -251,50 +244,111 @@ table.grid tbody tr:hover {
   gap: 0.6rem;
 }
 
-.feed-item {
+/* Journal entries */
+.entry {
   background: var(--panel-2);
   border: 1px solid var(--line);
   border-radius: 8px;
   padding: 0.6rem 0.7rem;
 }
 
-.feed-item.compact {
-  padding: 0.45rem 0.55rem;
-}
-
-.feed-head {
+.entry-head {
   display: flex;
   justify-content: space-between;
-  align-items: center;
-  margin-bottom: 0.4rem;
+  align-items: baseline;
+  gap: 0.6rem;
   font-size: 0.8rem;
 }
 
-.legs {
+.moved {
+  font-variant-numeric: tabular-nums;
+  color: var(--muted);
+}
+
+.entry-asset {
   display: flex;
-  flex-direction: column;
-  gap: 0.2rem;
+  align-items: baseline;
+  gap: 0.4rem;
+  margin: 0.5rem 0 0.25rem;
 }
 
-.leg {
+.entry-sides {
+  display: grid;
+  grid-template-columns: 1fr 1fr;
+  gap: 0.2rem 1.4rem;
+}
+
+.side-head {
+  font-size: 0.72rem;
+  text-transform: uppercase;
+  letter-spacing: 0.06em;
+  color: var(--muted);
+  border-bottom: 1px solid var(--line);
+  padding-bottom: 0.2rem;
+  margin-bottom: 0.25rem;
+}
+
+.line {
+  display: grid;
+  grid-template-columns: 1fr auto;
+  align-items: baseline;
+  gap: 0.2rem 0.6rem;
+  padding: 0.1rem 0;
+}
+
+.line .note {
+  grid-column: 1 / -1;
+  font-size: 0.75rem;
+  color: var(--muted);
+}
+
+.line.empty {
+  font-size: 0.78rem;
+}
+
+.line.mine {
+  border-left: 2px solid var(--accent);
+  margin-left: -0.5rem;
+  padding-left: 0.4rem;
+}
+
+.note.change { color: #9fb4c6; }
+.note.offset { color: #b98be0; }
+
+.side-total {
   display: flex;
   justify-content: space-between;
-  align-items: center;
-  gap: 1rem;
+  align-items: baseline;
+  gap: 0.6rem;
+  border-top: 1px solid var(--line);
+  margin-top: 0.3rem;
+  padding-top: 0.2rem;
 }
 
-.leg.change {
-  opacity: 0.6;
-  font-style: italic;
+.warn {
+  color: var(--neg);
+  font-size: 0.75rem;
 }
 
-.leg-dir b {
-  font-weight: 600;
+/* An account link stays quiet inside a dense row, but is a real link. */
+.acct-link {
+  color: inherit;
+  text-decoration: none;
 }
 
-.feed-foot {
-  margin-top: 0.4rem;
-  font-size: 0.75rem;
+.acct-link:hover,
+.acct-link:focus-visible {
+  text-decoration: underline;
+}
+
+@media (max-width: 720px) {
+  .entry-sides {
+    grid-template-columns: 1fr;
+  }
+
+  .side + .side {
+    margin-top: 0.6rem;
+  }
 }
 
 .hash {

+ 1 - 0
crates/kuatia-dashboard/templates/pages/account.html

@@ -1,4 +1,5 @@
 {% extends "base.html" %}
+{% import "partials/entry.html" as entry %}
 {% block content %}
 <p><a class="back" href="/accounts">&larr; Accounts</a></p>
 <div class="panel">

+ 1 - 0
crates/kuatia-dashboard/templates/pages/transfers.html

@@ -1,4 +1,5 @@
 {% extends "base.html" %}
+{% import "partials/entry.html" as entry %}
 {% block content %}
 <div class="panel">
   <h2>Transfers</h2>

+ 5 - 19
crates/kuatia-dashboard/templates/partials/account.html

@@ -1,3 +1,4 @@
+{% import "partials/entry.html" as entry %}
 <div class="detail-meta">
   <span class="policy {{ account.policy_kind }}">{{ account.policy_kind }}</span>
   <span class="muted">version {{ account.version }}</span>
@@ -31,9 +32,9 @@
   </thead>
   <tbody>
     {% for s in subaccounts %}
-    <tr onclick="window.location='{{ s.link }}'">
+    <tr>
       <td>
-        <div class="acct-id">{{ s.display_id }}{% if s.sub == 0 %} <span class="muted">(main)</span>{% endif %}</div>
+        <div class="acct-id"><a class="acct-link" href="{{ s.link }}">{{ s.display_id }}</a>{% if s.sub == 0 %} <span class="muted">(main)</span>{% endif %}</div>
       </td>
       <td><span class="policy {{ s.policy_kind }}">{{ s.policy_kind }}</span></td>
       <td class="right">
@@ -73,22 +74,7 @@
   </tbody>
 </table>
 
-<h3>Transfers ({{ transfers | length }})</h3>
+<h3>Journal entries ({{ entries | length }})</h3>
 <div class="feed">
-  {% for t in transfers %}
-  <div class="feed-item compact">
-    <div class="feed-head">
-      <code class="hash" title="{{ t.full_id }}">{{ t.short_id }}</code>
-      <span class="muted">{{ t.time }}</span>
-    </div>
-    <div class="legs">
-      {% for leg in t.legs %}
-      <div class="leg {% if leg.is_change %}change{% endif %}">
-        <span class="leg-dir">{{ leg.to_name }}</span>
-        <span class="money {% if leg.money.negative %}neg{% else %}pos{% endif %}">{{ leg.money.text }}</span>
-      </div>
-      {% endfor %}
-    </div>
-  </div>
-  {% endfor %}
+  {% for e in entries %}{{ entry::item(e=e) }}{% endfor %}
 </div>

+ 2 - 2
crates/kuatia-dashboard/templates/partials/accounts.html

@@ -8,9 +8,9 @@
   </thead>
   <tbody>
     {% for a in accounts %}
-    <tr onclick="window.location='{{ a.link }}'">
+    <tr>
       <td>
-        <div class="acct-name">{{ a.name }}</div>
+        <div class="acct-name"><a class="acct-link" href="{{ a.link }}">{{ a.name }}</a></div>
         <div class="acct-id">
           {{ a.display_id }}
           {% if a.sub %}<span class="flag sub">subaccount</span>{% endif %}

+ 43 - 0
crates/kuatia-dashboard/templates/partials/entry.html

@@ -0,0 +1,43 @@
+{% macro item(e) %}
+<div class="entry">
+  <div class="entry-head">
+    <code class="hash" title="{{ e.full_id }}">{{ e.short_id }}</code>
+    <span class="moved">{% for a in e.assets %}{{ a.moved.text }} {% endfor %}moved</span>
+    <span class="muted">{{ e.time }}</span>
+  </div>
+  {% for a in e.assets %}
+  <div class="entry-asset">
+    <span class="asset-code">{{ a.code }}</span>
+    {% if not a.balanced %}<span class="warn">unbalanced</span>{% endif %}
+  </div>
+  <div class="entry-sides">
+    <div class="side">
+      <div class="side-head">Debit</div>
+      {% for l in a.debits %}{{ self::line(l=l) }}{% endfor %}
+      {% if not a.debits %}<div class="line empty muted">nothing consumed</div>{% endif %}
+      <div class="side-total">
+        <span class="muted">&Sigma;</span>
+        <span class="money">{{ a.debit_total.text }}</span>
+      </div>
+    </div>
+    <div class="side">
+      <div class="side-head">Credit</div>
+      {% for l in a.credits %}{{ self::line(l=l) }}{% endfor %}
+      {% if not a.credits %}<div class="line empty muted">nothing created</div>{% endif %}
+      <div class="side-total">
+        <span class="muted">&Sigma;</span>
+        <span class="money">{{ a.credit_total.text }}</span>
+      </div>
+    </div>
+  </div>
+  {% endfor %}
+</div>
+{% endmacro item %}
+
+{% macro line(l) %}
+<div class="line{% if l.mine %} mine{% endif %}" title="posting {{ l.posting_short }}">
+  <a class="acct-link" href="{{ l.account.link }}" title="{{ l.account.title }}">{{ l.account.name }}</a>
+  <span class="money">{{ l.money.text }}</span>
+  <span class="note {{ l.kind }}">{{ l.note }}{% if l.payer %} <a class="acct-link" href="{{ l.payer.link }}" title="{{ l.payer.title }}">{{ l.payer.name }}</a>{% endif %}</span>
+</div>
+{% endmacro line %}

+ 1 - 1
crates/kuatia-dashboard/templates/partials/events.html

@@ -3,7 +3,7 @@
   <div class="event-row">
     <span class="event-kind {{ e.kind }}">{{ e.kind }}</span>
     <span class="event-target">
-      {% if e.account %}account {{ e.account }}{% endif %}
+      {% if e.account %}account <a class="acct-link" href="{{ e.account.link }}" title="{{ e.account.title }}">{{ e.account.name }}</a>{% endif %}
       {% if e.transfer_short %}<code class="hash">{{ e.transfer_short }}</code>{% endif %}
     </span>
     <span class="muted event-time">{{ e.time }}</span>

+ 2 - 23
crates/kuatia-dashboard/templates/partials/transfers.html

@@ -1,25 +1,4 @@
+{% import "partials/entry.html" as entry %}
 <div class="feed">
-  {% for t in transfers %}
-  <div class="feed-item">
-    <div class="feed-head">
-      <code class="hash" title="{{ t.full_id }}">{{ t.short_id }}</code>
-      <span class="muted">{{ t.time }}</span>
-    </div>
-    <div class="legs">
-      {% for leg in t.legs %}
-      <div class="leg {% if leg.is_change %}change{% endif %}">
-        <span class="leg-dir">
-          {% if leg.is_change %}
-            change &rarr; <b>{{ leg.to_name }}</b>
-          {% else %}
-            <b>{{ leg.from_name }}</b> &rarr; <b>{{ leg.to_name }}</b>
-          {% endif %}
-        </span>
-        <span class="money {% if leg.money.negative %}neg{% else %}pos{% endif %}">{{ leg.money.text }}</span>
-      </div>
-      {% endfor %}
-    </div>
-    <div class="feed-foot muted">consumes {{ t.consumes }} posting(s)</div>
-  </div>
-  {% endfor %}
+  {% for e in entries %}{{ entry::item(e=e) }}{% endfor %}
 </div>

+ 7 - 0
crates/kuatia/src/ledger/query.rs

@@ -52,6 +52,13 @@ impl Ledger {
             .await?)
     }
 
+    /// Postings by id from the immutable record. A consumed posting still
+    /// resolves here, which is what lets a reader show the debit side of a
+    /// committed envelope; the envelope stores consumed ids alone.
+    pub async fn get_postings(&self, ids: &[PostingId]) -> Result<Vec<Posting>, LedgerError> {
+        Ok(self.store.get_postings(ids).await?)
+    }
+
     /// Return all postings for the given account paired with their derived
     /// state, which distinguishes an unspent posting from a spent one.
     pub async fn postings_with_state(

+ 32 - 0
crates/kuatia/tests/integration.rs

@@ -962,6 +962,38 @@ async fn postings_returns_all_postings() {
 }
 
 #[tokio::test]
+async fn get_postings_resolves_a_consumed_posting() {
+    let ledger = setup_ledger().await;
+
+    deposit(&ledger, account(1), usd(), 100, external()).await;
+    pay(&ledger, account(1), account(2), usd(), 60).await;
+
+    let with_state = ledger.postings_with_state(&account(1)).await.unwrap();
+    let spent: Vec<PostingId> = with_state
+        .iter()
+        .filter(|(_, s)| *s == PostingState::Spent)
+        .map(|(p, _)| p.id)
+        .collect();
+    assert_eq!(spent.len(), 1);
+
+    let found = ledger.get_postings(&spent).await.unwrap();
+    assert_eq!(found.len(), 1);
+    assert_eq!(found[0].owner, account(1));
+    assert_eq!(found[0].amount.minor_units(), 100);
+}
+
+#[tokio::test]
+async fn get_postings_unknown_id_is_an_error() {
+    let ledger = setup_ledger().await;
+
+    let unknown = PostingId {
+        transfer: TransferId([7u8; 32]),
+        index: 0,
+    };
+    assert!(ledger.get_postings(&[unknown]).await.is_err());
+}
+
+#[tokio::test]
 async fn list_accounts_returns_all() {
     let ledger = setup_ledger().await;
 

+ 1 - 0
doc/crates.md

@@ -190,6 +190,7 @@ Transfers are built via `TransferBuilder` and committed with
 | `query_transfers(query)` | Paginated, filtered transfer history (by date range, book) |
 | `history(account)` | All transfers involving an account |
 | `postings(account)` | All postings (any state) |
+| `get_postings(ids)` | Postings by id from the immutable record; a consumed posting still resolves, which is how a reader recovers the debit side of a committed envelope |
 | `query_postings(query)` | Paginated, filtered postings (by asset, `PostingFilter`) |
 | `account_history(id)` | All version snapshots |
 | `get_events_since(seq, limit)` | Query ledger event log after a sequence number |