|
|
@@ -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()
|
|
|
+ );
|
|
|
+ }
|
|
|
+}
|