ledger-utils 0.6.0

Ledger-cli (https://www.ledger-cli.org/) file processing Rust library, useful for calculating balances, creating reports etc.
Documentation
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use crate::*;
use chrono::NaiveDate;
use ledger_parser::{LedgerItem, Serializer, SerializerSettings, Tag, TagValue};
use std::str::FromStr;
use std::{fmt, io};

///
/// Main document. Contains transactions and/or commodity prices.
///
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Ledger {
    pub commodity_prices: Vec<ledger_parser::CommodityPrice>,
    pub transactions: Vec<Transaction>,
}

impl fmt::Display for Ledger {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            self.to_string_pretty(&SerializerSettings::default())
        )?;
        Ok(())
    }
}

impl Serializer for Ledger {
    fn write<W>(&self, writer: &mut W, settings: &SerializerSettings) -> Result<(), io::Error>
    where
        W: io::Write,
    {
        let mut first = true;

        for commodity_price in &self.commodity_prices {
            first = false;
            commodity_price.write(writer, settings)?;
            writeln!(writer)?;
        }

        for transaction in &self.transactions {
            if !first {
                writeln!(writer)?;
            }

            first = false;
            transaction.write(writer, settings)?;
            writeln!(writer)?;
        }

        Ok(())
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    ParseError(ledger_parser::ParseError),
    IncompleteTransaction(Box<ledger_parser::Posting>),
    UnbalancedTransaction(Box<ledger_parser::Transaction>),
    BalanceAssertionFailed(Box<ledger_parser::Transaction>),
    ZeroBalanceAssertionFailed(Box<ledger_parser::Transaction>),
    UnbalancedVirtualWithNoAmount(Box<ledger_parser::Transaction>),
    ZeroBalanceMultipleCurrencies(Box<ledger_parser::Transaction>),
}

impl std::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::ParseError(p) => {
                write!(f, "Parse error:\n{}", p)
            }
            Error::IncompleteTransaction(p) => {
                write!(f, "Incomplete transaction:\n{}", p)
            }
            Error::UnbalancedTransaction(t) => {
                write!(f, "Unbalanced transaction:\n{}", t)
            }
            Error::BalanceAssertionFailed(t) => {
                write!(f, "Balance assertion failed:\n{}", t)
            }
            Error::ZeroBalanceAssertionFailed(t) => {
                write!(f, "Zero balance assertion failed:\n{}", t)
            }
            Error::UnbalancedVirtualWithNoAmount(t) => {
                write!(f, "Unbalanced virtual posting with no amount:\n{}", t)
            }
            Error::ZeroBalanceMultipleCurrencies(t) => {
                write!(f, "Zero balance with multiple currencies:\n{}", t)
            }
        }
    }
}

impl From<ledger_parser::ParseError> for Error {
    fn from(e: ledger_parser::ParseError) -> Self {
        Error::ParseError(e)
    }
}

impl FromStr for Ledger {
    type Err = Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        input.parse::<ledger_parser::Ledger>()?.try_into()
    }
}

impl TryFrom<ledger_parser::Ledger> for Ledger {
    type Error = Error;

    /// Fails if any transactions are unbalanced, any balance assertions fail, or if an unbalanced
    /// virtual posting (account name in `()`) has no amount.
    ///
    /// "Balance assertions" are postings with both amount and balance provided. The calculated
    /// amount using the balance must match the given amount.
    fn try_from(ledger: ledger_parser::Ledger) -> Result<Self, Self::Error> {
        let mut transactions = Vec::<ledger_parser::Transaction>::new();
        let mut commodity_prices = Vec::<ledger_parser::CommodityPrice>::new();

        let mut current_comment: Option<String> = None;

        for item in ledger.items {
            match item {
                LedgerItem::EmptyLine => {
                    current_comment = None;
                }
                LedgerItem::LineComment(comment) => {
                    if let Some(ref mut c) = current_comment {
                        c.push('\n');
                        c.push_str(&comment);
                    } else {
                        current_comment = Some(comment);
                    }
                }
                LedgerItem::Transaction(mut transaction) => {
                    if let Some(current_comment) = current_comment {
                        let mut full_comment = current_comment;
                        if let Some(ref transaction_comment) = transaction.comment {
                            full_comment.push('\n');
                            full_comment.push_str(transaction_comment);
                        }
                        transaction.comment = Some(full_comment);
                    }
                    current_comment = None;

                    transactions.push(transaction);
                }
                LedgerItem::CommodityPrice(commodity_price) => {
                    current_comment = None;
                    commodity_prices.push(commodity_price);
                }
                _ => {}
            }
        }

        calculate_amounts::calculate_amounts_from_balances(
            &mut transactions,
            &mut commodity_prices,
        )?;

        Ok(Ledger {
            transactions: transactions
                .into_iter()
                .map(Transaction::try_from)
                .collect::<Result<_, _>>()?,
            commodity_prices,
        })
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Transaction {
    pub comment: Option<String>,
    pub date: NaiveDate,
    pub effective_date: NaiveDate,
    pub status: Option<TransactionStatus>,
    pub code: Option<String>,
    pub description: String,
    pub postings: Vec<Posting>,
}

impl TryFrom<ledger_parser::Transaction> for Transaction {
    type Error = Error;

    /// Fails if any transactions are unbalanced, or if an unbalanced virtual posting
    /// (account name in `()`) has no amount.
    ///
    /// Ignores `balance`s. Fails if they are necessary to fill in any omitted `amount`s.
    fn try_from(mut transaction: ledger_parser::Transaction) -> Result<Self, Self::Error> {
        calculate_amounts::calculate_omitted_amounts(&mut transaction)?;

        Ok(Transaction {
            comment: transaction.comment,
            date: transaction.date,
            effective_date: transaction.effective_date.unwrap_or(transaction.date),
            status: transaction.status,
            code: transaction.code,
            description: transaction.description,
            postings: transaction
                .postings
                .into_iter()
                .map(OptionalDatePosting::try_from)
                .map(|res| {
                    res.map(|posting| {
                        posting.fill_dates(transaction.date, transaction.effective_date)
                    })
                })
                .collect::<Result<_, _>>()?,
        })
    }
}

impl Serializer for Transaction {
    fn write<W>(&self, writer: &mut W, settings: &SerializerSettings) -> Result<(), io::Error>
    where
        W: io::Write,
    {
        write!(writer, "{}", self.date.format("%Y-%m-%d"))?;

        if self.effective_date != self.date {
            write!(writer, "={}", self.effective_date.format("%Y-%m-%d"))?;
        }

        if let Some(ref status) = self.status {
            write!(writer, " ")?;
            status.write(writer, settings)?;
        }

        if let Some(ref code) = self.code {
            write!(writer, " ({})", code)?;
        }

        if !self.description.is_empty() {
            write!(writer, " {}", self.description)?;
        }

        if let Some(ref comment) = self.comment {
            for comment in comment.split('\n') {
                write!(writer, "{}{}; {}", settings.eol, settings.indent, comment)?;
            }
        }

        for posting in &self.postings {
            write!(writer, "{}{}", settings.eol, settings.indent)?;
            posting.elide_dates(self).write(writer, settings)?;
        }

        Ok(())
    }
}

impl fmt::Display for Transaction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            self.to_string_pretty(&SerializerSettings::default())
        )?;
        Ok(())
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct OptionalDatePosting {
    pub date: Option<NaiveDate>,
    pub effective_date: Option<NaiveDate>,
    pub account: String,
    pub reality: Reality,
    pub amount: Amount,
    pub status: Option<TransactionStatus>,
    pub comment: Option<String>,
    pub tags: Vec<Tag>,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Posting {
    pub date: NaiveDate,
    pub effective_date: NaiveDate,
    pub account: String,
    pub reality: Reality,
    pub amount: Amount,
    pub status: Option<TransactionStatus>,
    pub comment: Option<String>,
    pub tags: Vec<Tag>,
}

impl OptionalDatePosting {
    pub fn fill_dates(self, txn_date: NaiveDate, txn_effective_date: Option<NaiveDate>) -> Posting {
        Posting {
            date: self.date.unwrap_or(txn_date),
            effective_date: self
                .effective_date
                .or(self.date)
                .or(txn_effective_date)
                .unwrap_or(txn_date),
            account: self.account,
            reality: self.reality,
            amount: self.amount,
            status: self.status,
            comment: self.comment,
            tags: self.tags,
        }
    }
}

impl Posting {
    pub fn elide_dates(&self, txn: &Transaction) -> OptionalDatePosting {
        let date = if self.date != txn.date {
            Some(self.date)
        } else {
            None
        };

        let effective_date = if self.effective_date != date.unwrap_or(txn.effective_date) {
            Some(self.effective_date)
        } else {
            None
        };

        OptionalDatePosting {
            date,
            effective_date,
            account: self.account.clone(),
            reality: self.reality,
            amount: self.amount.clone(),
            status: self.status,
            comment: self.comment.clone(),
            tags: self.tags.clone(),
        }
    }
}

impl TryFrom<ledger_parser::Posting> for OptionalDatePosting {
    type Error = Error;

    /// Fails unless all `amount`s are `Some`. Ignores `balance`s.
    fn try_from(posting: ledger_parser::Posting) -> Result<Self, Self::Error> {
        if let Some(ledger_parser::PostingAmount { amount, .. }) = posting.amount {
            Ok(Self {
                date: posting.metadata.date,
                effective_date: posting.metadata.effective_date,
                account: posting.account,
                reality: posting.reality,
                status: posting.status,
                comment: posting.comment,
                amount,
                tags: posting.metadata.tags,
            })
        } else {
            Err(Error::IncompleteTransaction(posting.into()))
        }
    }
}

impl Serializer for OptionalDatePosting {
    fn write<W>(&self, writer: &mut W, settings: &SerializerSettings) -> Result<(), io::Error>
    where
        W: io::Write,
    {
        if let Some(ref status) = self.status {
            status.write(writer, settings)?;
            write!(writer, " ")?;
        }

        match self.reality {
            Reality::Real => write!(writer, "{}", self.account)?,
            Reality::BalancedVirtual => write!(writer, "[{}]", self.account)?,
            Reality::UnbalancedVirtual => write!(writer, "({})", self.account)?,
        }

        write!(writer, "  ")?;
        self.amount.write(writer, settings)?;

        let mut first = true;

        if let Some(ref comment) = self.comment {
            for comment in comment.split('\n') {
                if first {
                    first = false;
                    write!(writer, "  ")?;
                } else {
                    write!(writer, "{}{}", settings.eol, settings.indent)?;
                }
                write!(writer, "; {}", comment)?;
            }
        }

        if self.date.is_some() || self.effective_date.is_some() {
            if first {
                first = false;
                write!(writer, "  ")?;
            } else {
                write!(writer, "{}{}", settings.eol, settings.indent)?;
            }
            write!(writer, "; [")?;
            if let Some(d) = self.date {
                write!(writer, "{d}")?;
            }
            if let Some(d) = self.effective_date {
                write!(writer, "={d}")?;
            }
            write!(writer, "]")?;
        }

        let (tags, tags_with_values): (Vec<_>, Vec<_>) =
            self.tags.iter().partition(|t| t.value.is_none());

        if !tags.is_empty() {
            if first {
                first = false;
                write!(writer, "  ")?;
            } else {
                write!(writer, "{}{}", settings.eol, settings.indent)?;
            }
            write!(writer, "; :")?;
            for tag in tags {
                write!(writer, "{}:", tag.name)?;
            }
        }

        for tag in tags_with_values {
            if first {
                first = false;
                write!(writer, "  ")?;
            } else {
                write!(writer, "{}{}", settings.eol, settings.indent)?;
            }
            match &tag.value {
                Some(TagValue::String(s)) => write!(writer, "; {}: {s}", tag.name)?,
                Some(other_type) => write!(writer, "; {}:: {other_type}", tag.name)?,
                None => unreachable!(),
            }
        }

        Ok(())
    }
}

impl fmt::Display for OptionalDatePosting {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            self.to_string_pretty(&SerializerSettings::default())
        )?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::NaiveDate;
    use ledger_parser::{Amount, Commodity, CommodityPosition, CommodityPrice, Reality};
    use rust_decimal::Decimal;

    #[test]
    fn test_handle_commodity_exchange() {
        let ledger = ledger_parser::parse(
            r#"
2022-02-19 Exchange
  DollarAccount   $1.00
  PLNAccount  -4.00 PLN
"#,
        )
        .unwrap();
        let simplified_ledger: Result<Ledger, _> = ledger.try_into();
        assert!(simplified_ledger.is_ok());
        assert_eq!(simplified_ledger.unwrap().commodity_prices.len(), 1);
    }

    #[test]
    fn test_handle_commodity_exchange2() {
        let ledger = ledger_parser::parse(
            r#"
2020-02-01 Buy ADA
  assets:cc:ada          2000 ADA @ $0.02
  assets:bank:checking                   $-40
"#,
        )
        .unwrap();
        let simplified_ledger: Result<Ledger, _> = ledger.try_into();
        assert!(simplified_ledger.is_ok());
        assert_eq!(simplified_ledger.unwrap().commodity_prices.len(), 1);
    }

    #[test]
    fn display_ledger() {
        let actual = format!(
            "{}",
            Ledger {
                transactions: vec![
                    Transaction {
                        comment: Some("Comment Line 1\nComment Line 2".to_string()),
                        date: NaiveDate::from_ymd_opt(2018, 10, 1).unwrap(),
                        effective_date: NaiveDate::from_ymd_opt(2018, 10, 14).unwrap(),
                        status: Some(TransactionStatus::Pending),
                        code: Some("123".to_string()),
                        description: "Marek Ogarek".to_string(),
                        postings: vec![
                            Posting {
                                date: NaiveDate::from_ymd_opt(2018, 10, 1).unwrap(),
                                effective_date: NaiveDate::from_ymd_opt(2018, 10, 14).unwrap(),
                                account: "TEST:ABC 123".to_string(),
                                reality: Reality::Real,
                                amount: Amount {
                                    quantity: Decimal::new(120, 2),
                                    commodity: Commodity {
                                        name: "$".to_string(),
                                        position: CommodityPosition::Left
                                    }
                                },
                                status: None,
                                comment: Some("dd".to_string()),
                                tags: vec![],
                            },
                            Posting {
                                date: NaiveDate::from_ymd_opt(2018, 10, 1).unwrap(),
                                effective_date: NaiveDate::from_ymd_opt(2018, 10, 14).unwrap(),
                                account: "TEST:ABC 123".to_string(),
                                reality: Reality::Real,
                                amount: Amount {
                                    quantity: Decimal::new(120, 2),
                                    commodity: Commodity {
                                        name: "$".to_string(),
                                        position: CommodityPosition::Left
                                    }
                                },
                                status: None,
                                comment: None,
                                tags: vec![
                                    Tag {
                                        name: "Tag1".to_string(),
                                        value: None
                                    },
                                    Tag {
                                        name: "Tag2".to_string(),
                                        value: None
                                    }
                                ],
                            }
                        ]
                    },
                    Transaction {
                        comment: None,
                        date: NaiveDate::from_ymd_opt(2018, 10, 1).unwrap(),
                        effective_date: NaiveDate::from_ymd_opt(2018, 10, 1).unwrap(),
                        status: None,
                        code: None,
                        description: "Marek Ogarek".to_string(),
                        postings: vec![
                            Posting {
                                date: NaiveDate::from_ymd_opt(2018, 10, 1).unwrap(),
                                effective_date: NaiveDate::from_ymd_opt(2018, 10, 1).unwrap(),
                                account: "TEST:ABC 123".to_string(),
                                reality: Reality::Real,
                                amount: Amount {
                                    quantity: Decimal::new(120, 2),
                                    commodity: Commodity {
                                        name: "$".to_string(),
                                        position: CommodityPosition::Left
                                    }
                                },
                                status: None,
                                comment: None,
                                tags: vec![Tag {
                                    name: "DateTag".to_string(),
                                    value: Some(TagValue::Date(
                                        NaiveDate::from_ymd_opt(2017, 12, 31).unwrap()
                                    ))
                                }],
                            },
                            Posting {
                                date: NaiveDate::from_ymd_opt(2017, 12, 30).unwrap(),
                                effective_date: NaiveDate::from_ymd_opt(2017, 12, 30).unwrap(),
                                account: "TEST:ABC 123".to_string(),
                                reality: Reality::Real,
                                amount: Amount {
                                    quantity: Decimal::new(120, 2),
                                    commodity: Commodity {
                                        name: "$".to_string(),
                                        position: CommodityPosition::Left
                                    }
                                },
                                status: None,
                                comment: None,
                                tags: vec![],
                            }
                        ]
                    }
                ],
                commodity_prices: vec![CommodityPrice {
                    datetime: NaiveDate::from_ymd_opt(2017, 11, 12)
                        .unwrap()
                        .and_hms_opt(12, 00, 00)
                        .unwrap(),
                    commodity_name: "mBH".to_string(),
                    amount: Amount {
                        quantity: Decimal::new(500, 2),
                        commodity: Commodity {
                            name: "PLN".to_string(),
                            position: CommodityPosition::Right
                        }
                    }
                }]
            }
        );
        let expected = r#"P 2017-11-12 12:00:00 mBH 5.00 PLN

2018-10-01=2018-10-14 ! (123) Marek Ogarek
  ; Comment Line 1
  ; Comment Line 2
  TEST:ABC 123  $1.20  ; dd
  TEST:ABC 123  $1.20  ; :Tag1:Tag2:

2018-10-01 Marek Ogarek
  TEST:ABC 123  $1.20  ; DateTag:: [2017-12-31]
  TEST:ABC 123  $1.20  ; [2017-12-30]
"#;
        assert_eq!(actual, expected);
    }
}