1use std::{
2 collections::{HashMap, HashSet},
3 fmt::{Debug, Display},
4 hash::Hash,
5 ops::{Add, AddAssign, Div, Mul, Neg, Sub},
6};
7
8#[derive(Debug, PartialEq, Eq)]
9pub struct BeancountFile<D> {
10 pub directives: Vec<Directive<D>>,
11}
12
13#[derive(Debug, PartialEq, Eq)]
14pub struct Directive<D> {
15 pub date: chrono::NaiveDate,
16 pub content: DirectiveContent<D>,
17 pub metadata: HashMap<String, MetadataValue<D>>,
18}
19
20#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
22pub struct Currency(pub String);
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum MetadataValue<D> {
26 String(String),
27 Number(D),
28 Currency(Currency),
29}
30
31#[derive(Debug, PartialEq, Eq)]
32pub struct Pad {
33 pub account: Account,
34 pub source_account: Account,
35}
36
37#[derive(Debug, PartialEq, Eq)]
38pub struct Balance<D> {
39 pub account: Account,
40 pub amount: Amount<D>,
41}
42
43#[derive(Debug, PartialEq, Eq)]
44pub struct Event {
45 pub name: String,
46 pub value: String,
47}
48
49#[derive(Debug, PartialEq, Eq)]
50pub struct Transaction<D> {
51 pub flag: Option<char>,
52 pub payee: Option<String>,
53 pub narration: Option<String>,
54 pub tags: HashSet<String>,
55 pub links: HashSet<String>,
56 pub postings: Vec<Posting<D>>,
57 pub balanced: bool,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct Posting<D> {
62 pub flag: Option<char>,
63 pub account: Account,
64 pub amount: Option<Amount<D>>,
65 pub cost: Option<Cost<D>>,
66 pub price: Option<PostingPrice<D>>,
67 pub metadata: HashMap<String, MetadataValue<D>>,
68 pub autocomputed: bool,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct Cost<D> {
74 pub amount: Option<Amount<D>>,
75 pub date: Option<chrono::NaiveDate>,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum PostingPrice<D> {
80 Unit(Amount<D>),
81 Total(Amount<D>),
82}
83
84#[derive(Debug, PartialEq, Eq)]
85pub enum DirectiveContent<D> {
86 Balance(Balance<D>),
87 Close(Close),
88 Commodity(Currency),
89 Event(Event),
90 Open(Open),
91 Pad(Pad),
92 Price(Price<D>),
93 Transaction(Transaction<D>),
94}
95
96impl<D> DirectiveContent<D> {
97 pub fn transaction_opt(&self) -> Option<&Transaction<D>> {
98 match self {
99 DirectiveContent::Transaction(t) => Some(t),
100 _ => None,
101 }
102 }
103
104 pub fn open_opt(&self) -> Option<&Open> {
105 match self {
106 DirectiveContent::Open(o) => Some(o),
107 _ => None,
108 }
109 }
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Price<D> {
114 pub currency: Currency,
115 pub amount: Amount<D>,
116}
117
118#[derive(Clone, Debug, Hash, PartialEq, Eq)]
119pub struct Amount<D> {
120 pub value: D,
121 pub currency: Currency,
122}
123
124impl<D> Neg for Amount<D>
125where
126 D: Decimal,
127{
128 type Output = Amount<D>;
129
130 fn neg(self) -> Self::Output {
131 Amount {
132 value: -self.value,
133 currency: self.currency,
134 }
135 }
136}
137
138impl<'a, D> Neg for &'a Amount<D>
139where
140 D: Decimal,
141{
142 type Output = Amount<D>;
143
144 fn neg(self) -> Self::Output {
145 Amount {
146 value: -self.value.clone(),
147 currency: self.currency.clone(),
148 }
149 }
150}
151
152#[derive(Debug, PartialEq, Eq)]
153pub struct Open {
154 pub account: Account,
155 pub currencies: HashSet<Currency>,
156}
157
158#[derive(Debug, PartialEq, Eq)]
159pub struct Close {
160 pub account: Account,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct Account(pub String);
165
166pub trait Decimal:
167 Clone
168 + Debug
169 + Display
170 + Hash
171 + From<i32>
172 + Add<Output = Self>
173 + AddAssign
174 + Sub<Output = Self>
175 + Mul<Output = Self>
176 + Div<Output = Self>
177 + Neg<Output = Self>
178 + PartialEq
179 + Eq
180 + PartialOrd
181{
182}
183
184impl<D> Decimal for D where
185 D: Clone
186 + Debug
187 + Display
188 + Hash
189 + From<i32>
190 + Add<Output = Self>
191 + AddAssign
192 + Sub<Output = Self>
193 + Mul<Output = Self>
194 + Div<Output = Self>
195 + Neg<Output = Self>
196 + PartialEq
197 + Eq
198 + PartialOrd
199{
200}
201
202impl<D> Transaction<D>
203where
204 D: Decimal,
205{
206 pub fn book(&mut self) -> anyhow::Result<()> {
209 let mut amounts: HashMap<Currency, D> = HashMap::new();
210 let mut postings_no_amount: Vec<&mut Posting<D>> = Vec::new();
211 for posting in &mut self.postings {
212 match posting_amount_to_balance(posting) {
213 Some(amount) => {
214 *amounts.entry(amount.currency.clone()).or_insert(0.into()) += amount.value
215 }
216 None => postings_no_amount.push(posting),
217 };
218 }
219 anyhow::ensure!(
220 postings_no_amount.len() <= 1,
221 "more than one posting without amount"
222 );
223 let non_zero_amounts = amounts
224 .iter()
225 .filter(|x| *x.1 != 0.into())
226 .collect::<Vec<_>>();
227 anyhow::ensure!(
228 non_zero_amounts.len() <= 1,
229 "more than one currency does not balance to 0"
230 );
231
232 if postings_no_amount.len() == 1 {
233 if non_zero_amounts.is_empty() {
234 anyhow::bail!("posting with no amount in transaction that is balanced");
235 }
236 postings_no_amount[0].amount = Some(Amount {
237 value: -non_zero_amounts[0].1.clone(),
238 currency: non_zero_amounts[0].0.clone(),
239 });
240 postings_no_amount[0].autocomputed = true;
241 } else if !non_zero_amounts.is_empty() {
242 anyhow::bail!("transaction does not balance to 0");
243 }
244 Ok(())
245 }
246}
247
248pub(crate) fn posting_amount_to_balance<D: Decimal>(posting: &Posting<D>) -> Option<Amount<D>> {
249 let amount = match &posting.amount {
250 Some(amount) => amount,
251 None => return None,
252 };
253 let sign: D = if amount.value > 0.into() {
255 1.into()
256 } else {
257 (-1).into()
258 };
259 if let Some(cost) = &posting.cost {
260 if let Some(cost_amount) = &cost.amount {
261 return Some(Amount {
262 value: amount.value.clone() * cost_amount.value.clone(),
264 currency: cost_amount.currency.clone(),
265 });
266 }
267 }
268 match &posting.price {
269 Some(PostingPrice::Unit(price_amount)) => {
270 return Some(Amount {
271 value: amount.value.clone() * price_amount.value.clone(),
272 currency: price_amount.currency.clone(),
273 })
274 }
275 Some(PostingPrice::Total(price_amount)) => {
276 return Some(Amount {
277 value: price_amount.value.clone() * sign,
278 currency: price_amount.currency.clone(),
279 })
280 }
281 _ => (),
282 }
283 Some(amount.clone())
284}