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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use num::rational::BigRational;
use std::{
collections::{HashMap, HashSet},
convert::TryFrom,
path::PathBuf,
};
pub use account::Account;
pub use balance::Balance;
pub use comment::Comment;
pub use currency::{Currency, CurrencyDisplayFormat, DigitGrouping};
pub use money::Money;
pub use payee::Payee;
pub use price::conversion;
pub use price::{Price, PriceType};
pub use transaction::{
Cleared, Posting, PostingOrigin, PostingType, Transaction, TransactionStatus, TransactionType,
};
use crate::parser::value_expr::build_root_node_from_expression;
use crate::parser::{tokenizers, value_expr};
use crate::List;
use crate::{error::EmptyLedgerFileError, parser::ParsedLedger};
use crate::{filter::filter_expression, CommonOpts};
use crate::{models::transaction::Cost, parser::Tokenizer};
use num::BigInt;
use std::cell::RefCell;
use std::rc::Rc;
mod account;
mod balance;
mod comment;
mod currency;
mod money;
mod payee;
mod price;
mod transaction;
#[derive(Debug, Clone)]
pub struct Ledger {
pub accounts: List<Account>,
pub(crate) commodities: List<Currency>,
pub(crate) transactions: Vec<Transaction<Posting>>,
pub(crate) prices: Vec<Price>,
pub(crate) payees: List<Payee>,
pub(crate) files: Vec<PathBuf>,
}
impl TryFrom<&CommonOpts> for Ledger {
type Error = Box<dyn std::error::Error>;
fn try_from(options: &CommonOpts) -> Result<Self, Self::Error> {
let path: PathBuf = options.input_file.clone();
let mut tokenizer: Tokenizer = Tokenizer::try_from(&path)?;
let items = tokenizer.tokenize(options);
if items.is_empty() {
Err(Box::new(EmptyLedgerFileError))
} else {
let ledger = items.to_ledger(options)?;
Ok(ledger)
}
}
}
impl Ledger {
pub fn get_commodities(&self) -> &List<Currency> {
&self.commodities
}
pub fn get_prices(&self) -> &Vec<Price> {
&self.prices
}
}
impl ParsedLedger {
pub fn to_ledger(mut self, options: &CommonOpts) -> Result<Ledger, Box<dyn std::error::Error>> {
let mut commodity_strs = HashSet::<String>::new();
let mut account_strs = HashSet::<String>::new();
let mut payee_strs = HashSet::<String>::new();
for transaction in self.transactions.iter() {
for p in transaction.postings.borrow().iter() {
account_strs.insert(p.account.clone());
if let Some(payee) = p.payee.clone() {
payee_strs.insert(payee);
}
}
}
for price in self.prices.iter() {
commodity_strs.insert(price.clone().commodity);
commodity_strs.insert(price.clone().other_commodity);
}
for alias in commodity_strs {
match self.commodities.get(&alias) {
Ok(_) => {}
Err(_) => {
if options.pedantic {
panic!("Error: commodity {} not declared.", &alias);
}
if options.strict {
eprintln!("Warning: commodity {} not declared.", &alias);
}
self.commodities.insert(Currency::from(alias.as_str()));
}
}
}
for alias in account_strs {
match self.accounts.get(&alias) {
Ok(_) => {}
Err(_) => {
if options.pedantic {
panic!("Error: account {} not declared.", &alias);
}
if options.strict {
eprintln!("Warning: account {} not declared.", &alias);
}
self.accounts.insert(Account::from(alias.as_str()))
}
}
}
let payees_copy = self.payees.clone();
for alias in payee_strs {
match self.payees.get(&alias) {
Ok(_) => {}
Err(_) => {
let mut matched = false;
let mut alias_to_add = "".to_string();
let mut payee_to_add = None;
'outer: for (_, p) in payees_copy.iter() {
for p_alias in p.get_aliases().iter() {
if p_alias.is_match(alias.as_str()) {
payee_to_add = Some(p);
alias_to_add = alias.to_string();
matched = true;
break 'outer;
}
}
}
if !matched {
self.payees.insert(Payee::from(alias.as_str()))
} else {
self.payees.add_alias(alias_to_add, payee_to_add.unwrap());
}
}
}
}
let mut prices: Vec<Price> = Vec::new();
for price in self.prices.iter() {
prices.push(Price::new(
price.date,
self.commodities
.get(price.commodity.as_str())
.unwrap()
.clone(),
Money::Money {
amount: price.other_quantity.clone(),
currency: self
.commodities
.get(price.other_commodity.as_str())
.unwrap()
.clone(),
},
));
}
let mut transactions = Vec::new();
let mut automated_transactions = Vec::new();
for parsed in self.transactions.iter() {
let mut transformer = self._transaction_to_ledger(parsed)?;
transactions.append(&mut transformer.ledger_transactions);
automated_transactions.append(&mut transformer.raw_transactions);
prices.append(&mut transformer.prices);
}
transactions.sort_by(|a, b| a.date.unwrap().cmp(&b.date.unwrap()));
let mut balances: HashMap<Rc<Account>, Balance> = HashMap::new();
for account in self.accounts.values() {
balances.insert(account.clone(), Balance::new());
}
for t in transactions.iter_mut() {
let date = t.date.unwrap();
let balance = t.balance(&mut balances, options.no_balance_check)?;
if balance.len() == 2 {
let vec = balance.iter().map(|(_, x)| x.abs()).collect::<Vec<Money>>();
let commodity = vec[0].get_commodity().unwrap().clone();
let price = Money::Money {
amount: vec[1].get_amount() / vec[0].get_amount(),
currency: vec[1].get_commodity().unwrap().clone(),
};
prices.push(Price::new(date, commodity, price));
}
}
if !automated_transactions.is_empty() {
let mut root_nodes = HashMap::new();
let mut regexes = HashMap::new();
for automated in automated_transactions.iter_mut() {
let query = automated.get_filter_query();
let node = build_root_node_from_expression(query.as_str(), &mut regexes);
root_nodes.insert(query, node);
}
for t in transactions.iter_mut() {
for automated in automated_transactions.iter_mut() {
let mut extra_postings = vec![];
for p in t.postings.borrow().iter() {
if p.origin != PostingOrigin::FromTransaction {
continue;
}
let node = root_nodes.get(automated.get_filter_query().as_str());
if filter_expression(
node.unwrap(),
p,
t,
&self.commodities,
&mut regexes,
)? {
for comment in automated.comments.iter() {
p.tags.borrow_mut().append(&mut comment.get_tags());
}
for auto_posting in automated.postings.borrow().iter() {
let account_alias = auto_posting.account.clone();
match self.accounts.get(&account_alias) {
Ok(_) => {}
Err(_) => {
self.accounts.insert(Account::from(account_alias.as_str()))
}
}
let payee = if let Some(payee_alias) = &auto_posting.payee {
match self.payees.get(payee_alias) {
Ok(_) => {}
Err(_) => {
self.payees.insert(Payee::from(payee_alias.as_str()))
}
}
Some(self.payees.get(payee_alias).unwrap().clone())
} else {
p.payee.clone()
};
let account = self.accounts.get(&account_alias).unwrap();
let money = match &auto_posting.money_currency {
None => Some(value_expr::eval_value_expression(
auto_posting.amount_expr.clone().unwrap().as_str(),
p,
t,
&mut self.commodities,
&mut regexes,
)),
Some(alias) => {
if alias.is_empty() {
Some(Money::from((
p.amount.clone().unwrap().get_commodity().unwrap(),
p.amount.clone().unwrap().get_amount()
* auto_posting.money_amount.clone().unwrap(),
)))
} else {
match self.commodities.get(alias) {
Ok(_) => {}
Err(_) => self
.commodities
.insert(Currency::from(alias.as_str())),
}
Some(Money::from((
self.commodities.get(alias).unwrap().clone(),
auto_posting.money_amount.clone().unwrap(),
)))
}
}
};
let posting = Posting {
account: account.clone(),
date: p.date,
amount: money,
balance: None,
cost: None,
kind: auto_posting.kind,
comments: vec![],
tags: RefCell::new(vec![]),
payee,
transaction: RefCell::new(Rc::downgrade(&Rc::new(t.clone()))),
origin: PostingOrigin::Automated,
};
extra_postings.push(posting);
}
}
}
t.postings.borrow_mut().append(&mut extra_postings);
}
}
let mut balances: HashMap<Rc<Account>, Balance> = HashMap::new();
for account in self.accounts.values() {
balances.insert(account.clone(), Balance::new());
}
for t in transactions.iter_mut() {
let date = t.date.unwrap();
let balance = match t.balance(&mut balances, options.no_balance_check) {
Ok(balance) => balance,
Err(e) => {
eprintln!("{}", t);
return Err(e);
}
};
if balance.len() == 2 {
let vec = balance.iter().map(|(_, x)| x.abs()).collect::<Vec<Money>>();
let commodity = vec[0].get_commodity().unwrap().clone();
let price = Money::Money {
amount: vec[1].get_amount() / vec[0].get_amount(),
currency: vec[1].get_commodity().unwrap().clone(),
};
prices.push(Price::new(date, commodity, price));
}
}
}
Ok(Ledger {
accounts: self.accounts,
commodities: self.commodities,
transactions,
prices,
payees: self.payees,
files: self.files,
})
}
fn _transaction_to_ledger(
&self,
parsed: &Transaction<tokenizers::transaction::RawPosting>,
) -> Result<TransactionTransformer, Box<dyn std::error::Error>> {
let mut automated_transactions = vec![];
let mut prices = vec![];
let mut transactions = vec![];
match parsed.transaction_type {
TransactionType::Real => {
let mut transaction = Transaction::<Posting>::new(TransactionType::Real);
transaction.description = parsed.description.clone();
transaction.code = parsed.code.clone();
transaction.comments = parsed.comments.clone();
transaction.date = parsed.date;
transaction.effective_date = parsed.effective_date;
transaction.payee = parsed.payee.clone();
transaction.cleared = parsed.cleared;
for comment in parsed.comments.iter() {
transaction.tags.append(&mut comment.get_tags());
}
for p in parsed.postings.borrow().iter() {
let payee = match &p.payee {
None => transaction.get_payee(&self.payees).unwrap(),
Some(x) => self.payees.get(x).unwrap().clone(),
};
let account = if p.account.to_lowercase().ends_with("unknown") {
let mut account = None;
for (_, acc) in self.accounts.iter() {
for alias in acc.payees().iter() {
if alias.is_match(payee.get_name()) {
account = Some(acc.clone());
break;
}
}
}
match account {
Some(x) => x,
None => self.accounts.get(&p.account)?.clone(),
}
} else {
self.accounts.get(&p.account)?.clone()
};
let mut posting: Posting = Posting::new(
&account,
p.kind,
&payee,
PostingOrigin::FromTransaction,
p.date.unwrap(),
);
posting.tags = RefCell::new(transaction.tags.clone());
for comment in p.comments.iter() {
posting.tags.borrow_mut().append(&mut comment.get_tags());
}
if let Some(c) = &p.money_currency {
posting.amount = Some(Money::from((
self.commodities.get(c.as_str()).unwrap().clone(),
p.money_amount.clone().unwrap(),
)));
}
if let Some(c) = &p.cost_currency {
let posting_currency = self
.commodities
.get(p.money_currency.as_ref().unwrap().as_str())
.unwrap();
let amount = Money::from((
self.commodities.get(c.as_str()).unwrap().clone(),
p.cost_amount.clone().unwrap(),
));
posting.cost = match p.cost_type.as_ref().unwrap() {
PriceType::Total => Some(Cost::Total {
amount: amount.clone(),
}),
PriceType::PerUnit => Some(Cost::PerUnit {
amount: amount.clone(),
}),
};
prices.push(Price::new(
transaction.date.unwrap(),
posting_currency.clone(),
Money::Money {
amount: p.cost_amount.clone().unwrap()
/ match p.cost_type.as_ref().unwrap() {
PriceType::Total => {
posting.amount.as_ref().unwrap().get_amount()
}
PriceType::PerUnit => BigRational::from(BigInt::from(1)),
},
currency: amount.get_commodity().unwrap().clone(),
},
))
}
if let Some(c) = &p.balance_currency {
posting.balance = Some(Money::from((
self.commodities.get(c.as_str()).unwrap().clone(),
p.balance_amount.clone().unwrap(),
)));
}
transaction.postings.borrow_mut().push(posting.to_owned());
}
if transaction.is_balanced() {
transaction.status = TransactionStatus::InternallyBalanced;
}
transactions.push(transaction);
}
TransactionType::Automated => {
automated_transactions.push(parsed.clone());
}
TransactionType::Periodic => {
eprintln!("Found periodic transaction. Skipping.");
}
}
Ok(TransactionTransformer {
ledger_transactions: transactions,
raw_transactions: automated_transactions,
prices,
})
}
}
#[derive(Copy, Clone, Debug)]
pub enum Origin {
FromDirective,
FromTransaction,
Other,
}
pub trait HasName {
fn get_name(&self) -> &str;
}
pub trait HasAliases {
fn get_aliases(&self) -> &HashSet<String>;
}
pub trait FromDirective {
fn is_from_directive(&self) -> bool;
}
#[cfg(test)]
mod tests {
use structopt::StructOpt;
use crate::{parser::Tokenizer, CommonOpts};
#[test]
fn payee_with_pipe_issue_121() {
let mut tokenizer = Tokenizer::from(
"2022-05-13 ! (8760) Intereses | EstateGuru
EstateGuru 1.06 EUR
Ingresos:Rendimientos
"
.to_string(),
);
let options = CommonOpts::from_iter(["", "-f", ""].iter());
let items = tokenizer.tokenize(&options);
let ledger = items.to_ledger(&options).unwrap();
let t = &ledger.transactions[0];
let payee = t.get_payee(&ledger.payees);
assert!(&ledger.payees.get("EstateGuru").is_ok());
assert!(payee.is_some());
}
}
use chrono::NaiveDate;
#[derive(Debug, Clone)]
pub struct ParsedPrice {
pub(crate) date: NaiveDate,
pub(crate) commodity: String,
pub(crate) other_commodity: String,
pub(crate) other_quantity: BigRational,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Tag {
pub name: String,
pub check: Vec<String>,
pub assert: Vec<String>,
pub value: Option<String>,
}
impl HasName for Tag {
fn get_name(&self) -> &str {
self.name.as_str()
}
}
struct TransactionTransformer {
ledger_transactions: Vec<Transaction<Posting>>,
raw_transactions: Vec<Transaction<tokenizers::transaction::RawPosting>>,
prices: Vec<Price>,
}