1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#![cfg(feature = "unstable")]
use super::{Posting, Transaction};
use crate::Amount;
#[allow(clippy::module_name_repetitions)]
pub type BalancedTransaction<'a> = Transaction<'a, Amount<'a>>;
#[allow(clippy::module_name_repetitions)]
pub type BalancedPosting<'a> = Posting<'a, Amount<'a>>;
impl<'a> Transaction<'a> {
#[must_use]
pub fn balanced(self) -> Option<BalancedTransaction<'a>> {
let mut postings = Vec::with_capacity(self.postings.len());
for posting in self.postings {
let Some(amount) = posting.amount else { return None };
postings.push(BalancedPosting {
info: posting.info,
amount,
});
}
Some(BalancedTransaction {
info: self.info,
postings,
})
}
}
#[cfg(test)]
mod tests {
use crate::{
account, transaction::posting::Info as PostingInfo, transaction::Info as TrxInfo, Account,
Date,
};
use super::*;
#[test]
fn balance_an_emtpy_transaction() {
let balanced: BalancedTransaction<'_> = transaction([]).balanced().unwrap();
assert_eq!(balanced.postings.len(), 0);
}
#[test]
#[ignore = "not implemeted"]
fn simple_balance() {
let balanced = transaction([
posting(
Account::new(account::Type::Assets, []),
Some(Amount::new(1, "CHF")),
),
posting(Account::new(account::Type::Income, []), None),
])
.balanced()
.unwrap();
assert_eq!(balanced.postings.len(), 2);
assert_eq!(balanced.postings[0].amount, Amount::new(-1, "CHF"));
assert_eq!(balanced.postings[1].amount, Amount::new(-1, "CHF"));
}
fn transaction<'a>(postings: impl IntoIterator<Item = Posting<'a>>) -> Transaction<'a> {
Transaction {
info: TrxInfo {
date: Date::new(2022, 11, 20),
flag: None,
payee: None,
narration: None,
comment: None,
tags: Vec::new(),
},
postings: postings.into_iter().collect(),
}
}
fn posting<'a>(account: Account<'a>, amount: Option<Amount<'a>>) -> Posting<'a> {
Posting {
info: PostingInfo {
flag: None,
account,
price: None,
cost: None,
comment: None,
},
amount,
}
}
}